Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix test to pass on LLP64 targets | // RUN: %clang_analyze_cc1 -analyzer-checker=optin.osx.OSObjectCStyleCast %s -verify
#include "os_object_base.h"
struct OSArray : public OSObject {
unsigned getCount();
};
struct A {
int x;
};
struct B : public A {
unsigned getCount();
};
unsigned warn_on_explicit_downcast(OSObject * obj) {
OSArray *a = (OSArray *) obj; // expected-warning{{C-style cast of OSObject. Use OSDynamicCast instead}}
return a->getCount();
}
void no_warn_on_upcast(OSArray *arr) {
OSObject *obj = (OSObject *) arr;
obj->retain();
obj->release();
}
unsigned no_warn_on_dynamic_cast(OSObject *obj) {
OSArray *a = OSDynamicCast(OSArray, obj);
return a->getCount();
}
unsigned long no_warn_on_primitive_conversion(OSArray *arr) {
return (unsigned long) arr;
}
unsigned no_warn_on_other_type_cast(A *a) {
B *b = (B *) a;
return b->getCount();
}
| // RUN: %clang_analyze_cc1 -analyzer-checker=optin.osx.OSObjectCStyleCast %s -verify
#include "os_object_base.h"
struct OSArray : public OSObject {
unsigned getCount();
};
struct A {
int x;
};
struct B : public A {
unsigned getCount();
};
unsigned warn_on_explicit_downcast(OSObject * obj) {
OSArray *a = (OSArray *) obj; // expected-warning{{C-style cast of OSObject. Use OSDynamicCast instead}}
return a->getCount();
}
void no_warn_on_upcast(OSArray *arr) {
OSObject *obj = (OSObject *) arr;
obj->retain();
obj->release();
}
unsigned no_warn_on_dynamic_cast(OSObject *obj) {
OSArray *a = OSDynamicCast(OSArray, obj);
return a->getCount();
}
__SIZE_TYPE__ no_warn_on_primitive_conversion(OSArray *arr) {
return (__SIZE_TYPE__) arr;
}
unsigned no_warn_on_other_type_cast(A *a) {
B *b = (B *) a;
return b->getCount();
}
|
Use ResourceId instead of size_t | // Ouzel by Elviss Strazdins
#include "RenderTarget.hpp"
#include "Graphics.hpp"
#include "Texture.hpp"
namespace ouzel::graphics
{
RenderTarget::RenderTarget(Graphics& initGraphics,
const std::vector<Texture*>& initColorTextures,
Texture* initDepthTexture):
resource{*initGraphics.getDevice()},
colorTextures{initColorTextures},
depthTexture{initDepthTexture}
{
std::set<std::size_t> colorTextureIds;
for (const auto& colorTexture : colorTextures)
colorTextureIds.insert(colorTexture ? colorTexture->getResource() : 0);
initGraphics.addCommand(std::make_unique<InitRenderTargetCommand>(resource,
colorTextureIds,
depthTexture ? depthTexture->getResource() : RenderDevice::ResourceId(0)));
}
}
| // Ouzel by Elviss Strazdins
#include "RenderTarget.hpp"
#include "Graphics.hpp"
#include "Texture.hpp"
namespace ouzel::graphics
{
RenderTarget::RenderTarget(Graphics& initGraphics,
const std::vector<Texture*>& initColorTextures,
Texture* initDepthTexture):
resource{*initGraphics.getDevice()},
colorTextures{initColorTextures},
depthTexture{initDepthTexture}
{
std::set<RenderDevice::ResourceId> colorTextureIds;
for (const auto& colorTexture : colorTextures)
colorTextureIds.insert(colorTexture ? colorTexture->getResource() : 0);
initGraphics.addCommand(std::make_unique<InitRenderTargetCommand>(resource,
colorTextureIds,
depthTexture ? depthTexture->getResource() : RenderDevice::ResourceId(0)));
}
}
|
Add test separation for YAML make-samples | #include "grune/grammars/anbncn.hpp"
#include "grune/grammars/turtle.hpp"
#include "grune/grammars/tom_dick_and_harry.hpp"
#include "grune-yaml/grune-yaml.hpp"
#include <fstream>
#define MAKE_SAMPLE(name) \
do { \
std::ofstream out(#name ".yaml"); \
out << YAML::Node(grune::grammars::name()) << std::endl; \
} while(0)
int main()
{
MAKE_SAMPLE(anbncn);
MAKE_SAMPLE(cyclic_manhattan_turtle);
MAKE_SAMPLE(tom_dick_and_harry);
}
| #include "grune/grammars/anbncn.hpp"
#include "grune/grammars/turtle.hpp"
#include "grune/grammars/tom_dick_and_harry.hpp"
#include "grune-yaml/grune-yaml.hpp"
#include <fstream>
#define MAKE_SAMPLE_IMPL(name) \
do { \
std::ofstream out(#name ".yaml"); \
out << YAML::Node(grune::grammars::name()) << std::endl; \
} while(0)
#ifndef COVERITY_BUILD
#define MAKE_SAMPLE(name) MAKE_SAMPLE_IMPL(name)
#else
#include <coverity-test-separation.h>
#define MAKE_SAMPLE(name) \
do { \
COVERITY_TS_START_TEST(#name); \
MAKE_SAMPLE_IMPL(name); \
COVERITY_TS_END_TEST(); \
} while(0)
#endif
int main()
{
#ifdef COVERITY_BUILD
COVERITY_TS_SET_SUITE_NAME("grune-yaml/make-samples");
#endif
MAKE_SAMPLE(anbncn);
MAKE_SAMPLE(cyclic_manhattan_turtle);
MAKE_SAMPLE(tom_dick_and_harry);
}
|
Check IR on this test. | // REQUIRES: x86-registered-target,x86-64-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin -S %s -o %t-64.s
// RUN: FileCheck -check-prefix CHECK-LP64 --input-file=%t-64.s %s
// RUN: %clang_cc1 -triple i386-apple-darwin -S %s -o %t-32.s
// RUN: FileCheck -check-prefix CHECK-LP32 --input-file=%t-32.s %s
struct A {};
struct B
{
operator A&();
};
struct D : public B {
operator A();
};
extern B f();
extern D d();
int main() {
const A& rca = f();
const A& rca2 = d();
}
// CHECK-LP64: callq __ZN1BcvR1AEv
// CHECK-LP64: callq __ZN1BcvR1AEv
// CHECK-LP32: calll L__ZN1BcvR1AEv
// CHECK-LP32: calll L__ZN1BcvR1AEv
| // RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | \
// RUN: FileCheck %s
// RUN: %clang_cc1 -triple i386-apple-darwin -emit-llvm %s -o - | \
// RUN: FileCheck %s
struct A {};
struct B
{
operator A&();
};
struct D : public B {
operator A();
};
extern B f();
extern D d();
int main() {
const A& rca = f();
const A& rca2 = d();
}
// CHECK: call %struct.A* @_ZN1BcvR1AEv
// CHECK: call %struct.A* @_ZN1BcvR1AEv
|
Add argument for requesting specific OpenGl version | #include <iostream>
#include <string>
#include <vector>
#include "Window.h"
#include "ProceduralRenderer.h"
#include <glbinding/gl/gl.h>
#include <glbinding/Binding.h>
using namespace gl;
int main() {
Window w;
w.init("procedural");
glbinding::Binding::initialize();
std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;
w.initAfterGL();
std::vector<std::string> includes {"gradient", "chess"};
auto renderer = std::make_unique<ProceduralRenderer>(includes);
w.setRenderer(std::move(renderer));
w.loop();
return 0;
}
| #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include "Window.h"
#include "ProceduralRenderer.h"
#include <glbinding/gl/gl.h>
#include <glbinding/Binding.h>
using namespace gl;
std::map<std::string, std::string> parseArguments(int argc, char * argv[])
{
std::vector<std::string> arguments;
for (int i = 0; i < argc; ++i)
{
arguments.push_back(argv[i]);
}
std::map<std::string, std::string> options;
for (auto& argument : arguments)
{
const auto equalPosition = argument.find("=");
if (argument.substr(0, 2) == "--" && equalPosition != std::string::npos)
{
const auto key = argument.substr(2, equalPosition - 2);
const auto value = argument.substr(equalPosition + 1);
options[key] = value;
}
}
return options;
}
int main(int argc, char * argv[]) {
const auto options = parseArguments(argc, argv);
Window w;
if (options.find("gl") != options.end())
{
const auto version = options.at("gl");
const auto dotPosition = version.find(".");
if (dotPosition != std::string::npos)
{
int major, minor;
std::istringstream(version.substr(0, dotPosition)) >> major;
std::istringstream(version.substr(dotPosition + 1)) >> minor;
w.requestGLVersion(major, minor);
}
}
w.init("procedural");
glbinding::Binding::initialize();
std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;
w.initAfterGL();
std::vector<std::string> includes {"gradient", "chess"};
auto renderer = std::make_unique<ProceduralRenderer>(includes);
w.setRenderer(std::move(renderer));
w.loop();
return 0;
}
|
Fix include order for clang_format. | /*
*
* Copyright 2019 gRPC authors.
*
* 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 <stdbool.h>
#include <stdint.h>
#include "src/core/lib/slice/b64.h"
#include "include/grpc/support/alloc.h"
bool squelch = true;
bool leak_check = true;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size < 2) return 0;
const bool url_safe = static_cast<uint8_t>(0x100) < data[0];
const bool multiline = static_cast<uint8_t>(0x100) < data[1];
char* res = grpc_base64_encode(reinterpret_cast<const char*>(data + 2),
size - 2, url_safe, multiline);
gpr_free(res);
return 0;
}
| /*
*
* Copyright 2019 gRPC authors.
*
* 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 <stdbool.h>
#include <stdint.h>
#include "include/grpc/support/alloc.h"
#include "src/core/lib/slice/b64.h"
bool squelch = true;
bool leak_check = true;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size < 2) return 0;
const bool url_safe = static_cast<uint8_t>(0x100) < data[0];
const bool multiline = static_cast<uint8_t>(0x100) < data[1];
char* res = grpc_base64_encode(reinterpret_cast<const char*>(data + 2),
size - 2, url_safe, multiline);
gpr_free(res);
return 0;
}
|
Fix C++: getter changed data - JSONPARSER | #include "jsonparser.h"
JSONParser::JSONParser(QObject *parent) :
QObject(parent)
{
clearData();
}
void JSONParser::clearData()
{
p_data = "{ ";
}
void JSONParser::addVariable(const QString name, int value)
{
p_data.append("\"");
p_data.append(name);
p_data.append("\":");
p_data.append(QString::number(value));
p_data.append(",");
}
void JSONParser::setData(QString &value)
{
if(value != p_data)
{
p_data = value;
emit dataChanged();
}
}
QString JSONParser::data() {
QString result = p_data.remove(p_data.length() - 1, 1);
result.append(" }");
return result;
}
| #include "jsonparser.h"
JSONParser::JSONParser(QObject *parent) :
QObject(parent)
{
clearData();
}
void JSONParser::clearData()
{
p_data = "{ ";
}
void JSONParser::addVariable(const QString name, int value)
{
p_data.append("\"");
p_data.append(name);
p_data.append("\":");
p_data.append(QString::number(value));
p_data.append(",");
}
void JSONParser::setData(QString &value)
{
if(value != p_data)
{
p_data = value;
emit dataChanged();
}
}
QString JSONParser::data() {
QString result = p_data;
result.remove(result.length() - 1, 1);
result.append(" }");
return result;
}
|
Fix unrecognized types in Coverity Scan model chpl_*error() decls. | /**
* Coverity Scan model
*
* Manage false positives by giving coverity some hints.
*
* Updates to this file must be manually submitted by an admin to:
*
* https://scan.coverity.com/projects/1222
*
*/
// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
if (tag == 1 || tag == 2) {
__coverity_panic__();
}
}
//==============================
// runtime
//
// chpl_error() ends execution
void chpl_error(const char* message, int32_t lineno, c_string filename) {
__coverity_panic__();
}
// chpl_internal_error() ends execution
void chpl_internal_error(const char* message) {
__coverity_panic__();
}
| /**
* Coverity Scan model
*
* Manage false positives by giving coverity some hints.
*
* Updates to this file must be manually submitted by an admin to:
*
* https://scan.coverity.com/projects/1222
*
*/
// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
if (tag == 1 || tag == 2) {
__coverity_panic__();
}
}
//==============================
// runtime
//
// chpl_error() ends execution
// Note: this signature doesn't match the real one precisely, but it's
// close enough.
void chpl_error(const char* message, int lineno, const char* filename) {
__coverity_panic__();
}
// chpl_internal_error() ends execution
void chpl_internal_error(const char* message) {
__coverity_panic__();
}
|
Check the implicit instantiation of a static data member of a class template that has no out-of-line definition. | // RUN: clang-cc -emit-llvm -triple x86_64-apple-darwin10 -o - %s | FileCheck %s
template<typename T>
struct X {
static T member1;
static T member2;
static T member3;
};
template<typename T>
T X<T>::member1;
template<typename T>
T X<T>::member2 = 17;
// CHECK: @_ZN1XIiE7member1E = global i32 0
template int X<int>::member1;
// CHECK: @_ZN1XIiE7member2E = global i32 17
template int X<int>::member2;
// For implicit instantiation of
long& get(bool Cond) {
// CHECK: @_ZN1XIlE7member1E = weak global i64 0
// CHECK: @_ZN1XIlE7member2E = weak global i64 17
return Cond? X<long>::member1 : X<long>::member2;
} | // RUN: clang-cc -emit-llvm -triple x86_64-apple-darwin10 -o - %s | FileCheck %s
template<typename T>
struct X {
static T member1;
static T member2;
static T member3;
};
template<typename T>
T X<T>::member1;
template<typename T>
T X<T>::member2 = 17;
// CHECK: @_ZN1XIiE7member1E = global i32 0
template int X<int>::member1;
// CHECK: @_ZN1XIiE7member2E = global i32 17
template int X<int>::member2;
// For implicit instantiation of
long& get(bool Cond1, bool Cond2) {
// CHECK: @_ZN1XIlE7member1E = weak global i64 0
// CHECK: @_ZN1XIlE7member2E = weak global i64 17
// CHECK: @_ZN1XIlE7member3E = external global i64
return Cond1? X<long>::member1
: Cond2? X<long>::member2
: X<long>::member3;
}
|
Fix warning in ScaleOp grad | #include "caffe2/operators/scale_op.h"
namespace caffe2 {
REGISTER_CPU_OPERATOR(Scale, ScaleOp<float, CPUContext>);
OPERATOR_SCHEMA(Scale)
.NumInputs(1)
.NumOutputs(1)
.AllowInplace({{0, 0}})
.SetDoc(R"DOC(
Scale takes one input data (Tensor<float>) and produces one output data
(Tensor<float>) whose value is the input data tensor scaled element-wise.
)DOC")
.Arg("scale", "(float, default 1.0) the scale to apply.");
class GetScaleGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"Scale", "",
vector<string>{GO(0)},
vector<string>{GI(0)},
Def().arg());
}
};
REGISTER_GRADIENT(Scale, GetScaleGradient);
} // namespace caffe2
| #include "caffe2/operators/scale_op.h"
namespace caffe2 {
REGISTER_CPU_OPERATOR(Scale, ScaleOp<float, CPUContext>);
OPERATOR_SCHEMA(Scale)
.NumInputs(1)
.NumOutputs(1)
.AllowInplace({{0, 0}})
.SetDoc(R"DOC(
Scale takes one input data (Tensor<float>) and produces one output data
(Tensor<float>) whose value is the input data tensor scaled element-wise.
)DOC")
.Arg("scale", "(float, default 1.0) the scale to apply.");
class GetScaleGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
// CopyArguments is true by default so the "scale" arg is going to be copied
return SingleGradientDef(
"Scale", "", vector<string>{GO(0)}, vector<string>{GI(0)});
}
};
REGISTER_GRADIENT(Scale, GetScaleGradient);
} // namespace caffe2
|
Fix ControllerRepeatClick potential infinite loop for bad step values | /*
* This source file is part of MyGUI. For the latest info, see http://mygui.info/
* Distributed under the MIT License
* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
*/
#include "MyGUI_ControllerRepeatClick.h"
namespace MyGUI
{
ControllerRepeatClick::ControllerRepeatClick() :
mInit(0.5),
mStep(0.1),
mTimeLeft(0)
{
}
ControllerRepeatClick::~ControllerRepeatClick()
{
}
bool ControllerRepeatClick::addTime(MyGUI::Widget* _widget, float _time)
{
if(mTimeLeft == 0)
mTimeLeft = mInit;
mTimeLeft -= _time;
while (mTimeLeft <= 0)
{
mTimeLeft += mStep;
eventRepeatClick(_widget, this);
}
return true;
}
void ControllerRepeatClick::setRepeat(float init, float step)
{
mInit = init;
mStep = step;
}
void ControllerRepeatClick::setProperty(const std::string& _key, const std::string& _value)
{
}
void ControllerRepeatClick::prepareItem(MyGUI::Widget* _widget)
{
}
}
| /*
* This source file is part of MyGUI. For the latest info, see http://mygui.info/
* Distributed under the MIT License
* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
*/
#include "MyGUI_ControllerRepeatClick.h"
namespace MyGUI
{
ControllerRepeatClick::ControllerRepeatClick() :
mInit(0.5),
mStep(0.1),
mTimeLeft(0)
{
}
ControllerRepeatClick::~ControllerRepeatClick()
{
}
bool ControllerRepeatClick::addTime(MyGUI::Widget* _widget, float _time)
{
if(mTimeLeft == 0)
mTimeLeft = mInit;
if (mStep <= 0)
return true;
mTimeLeft -= _time;
while (mTimeLeft <= 0)
{
mTimeLeft += mStep;
eventRepeatClick(_widget, this);
}
return true;
}
void ControllerRepeatClick::setRepeat(float init, float step)
{
mInit = init;
mStep = step;
}
void ControllerRepeatClick::setProperty(const std::string& _key, const std::string& _value)
{
}
void ControllerRepeatClick::prepareItem(MyGUI::Widget* _widget)
{
}
}
|
Add a missing initialisation for CPDF_ContentMarkItem. | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fpdfapi/fpdf_page/cpdf_contentmarkitem.h"
#include "core/fpdfapi/fpdf_parser/include/cpdf_dictionary.h"
CPDF_ContentMarkItem::CPDF_ContentMarkItem() {
m_ParamType = None;
}
CPDF_ContentMarkItem::CPDF_ContentMarkItem(const CPDF_ContentMarkItem& src) {
m_MarkName = src.m_MarkName;
m_ParamType = src.m_ParamType;
if (m_ParamType == DirectDict) {
m_pParam = ToDictionary(src.m_pParam->Clone());
} else {
m_pParam = src.m_pParam;
}
}
CPDF_ContentMarkItem::~CPDF_ContentMarkItem() {
if (m_ParamType == DirectDict && m_pParam)
m_pParam->Release();
}
FX_BOOL CPDF_ContentMarkItem::HasMCID() const {
if (m_pParam &&
(m_ParamType == DirectDict || m_ParamType == PropertiesDict)) {
return m_pParam->KeyExist("MCID");
}
return FALSE;
}
| // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fpdfapi/fpdf_page/cpdf_contentmarkitem.h"
#include "core/fpdfapi/fpdf_parser/include/cpdf_dictionary.h"
CPDF_ContentMarkItem::CPDF_ContentMarkItem()
: m_ParamType(None), m_pParam(nullptr) {}
CPDF_ContentMarkItem::CPDF_ContentMarkItem(const CPDF_ContentMarkItem& src) {
m_MarkName = src.m_MarkName;
m_ParamType = src.m_ParamType;
if (m_ParamType == DirectDict) {
m_pParam = ToDictionary(src.m_pParam->Clone());
} else {
m_pParam = src.m_pParam;
}
}
CPDF_ContentMarkItem::~CPDF_ContentMarkItem() {
if (m_ParamType == DirectDict && m_pParam)
m_pParam->Release();
}
FX_BOOL CPDF_ContentMarkItem::HasMCID() const {
if (m_pParam &&
(m_ParamType == DirectDict || m_ParamType == PropertiesDict)) {
return m_pParam->KeyExist("MCID");
}
return FALSE;
}
|
Add fullscreen for Raspberry Pi | #include "ofMain.h"
#include "ofApp.h"
int main()
{
ofSetupOpenGL(600, 500, OF_WINDOW);
ofRunApp(new ofApp());
} | #include "ofMain.h"
#include "ofApp.h"
int main()
{
#ifdef TARGET_RASPBERRY_PI
ofSetupOpenGL(600, 500, OF_FULLSCREEN);
#else
ofSetupOpenGL(600, 500, OF_WINDOW);
#endif
ofRunApp(new ofApp());
} |
Clean up of the code. | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBSTInternal(TreeNode* root, int minVal, int maxVal)
{
if (root == NULL) {
return true;
}
return (root->val > minVal &&
root->val < maxVal &&
isValidBSTInternal(root->left, minVal, root->val) &&
isValidBSTInternal(root->right, root->val, maxVal));
}
bool isValidBST(TreeNode* root) {
int minVal, maxVal;
return isValidBSTInternal(root, LONG_MIN, LONG_MAX);
}
};
| #include <cstddef>
#include <climits>
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isValidBSTInternal(TreeNode* root, int minVal, int maxVal)
{
if (root == NULL) {
return true;
}
return (root->val > minVal &&
root->val < maxVal &&
isValidBSTInternal(root->left, minVal, root->val) &&
isValidBSTInternal(root->right, root->val, maxVal));
}
bool isValidBST(TreeNode* root) {
return isValidBSTInternal(root, INT_MIN, INT_MAX);
}
};
|
Migrate uses of NDEBUG to REACT_NATIVE_DEBUG + react_native_assert | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "AsynchronousEventBeat.h"
namespace facebook {
namespace react {
AsynchronousEventBeat::AsynchronousEventBeat(
RunLoopObserver::Unique uiRunLoopObserver,
RuntimeExecutor runtimeExecutor)
: EventBeat({}),
uiRunLoopObserver_(std::move(uiRunLoopObserver)),
runtimeExecutor_(std::move(runtimeExecutor)) {
uiRunLoopObserver_->setDelegate(this);
uiRunLoopObserver_->enable();
}
void AsynchronousEventBeat::activityDidChange(
RunLoopObserver::Delegate const *delegate,
RunLoopObserver::Activity activity) const noexcept {
assert(delegate == this);
induce();
}
void AsynchronousEventBeat::induce() const {
if (!isRequested_) {
return;
}
// Here we know that `this` object exists because the caller has a strong
// pointer to `owner`. To ensure the object will exist inside
// `runtimeExecutor_` callback, we need to copy the pointer there.
auto weakOwner = uiRunLoopObserver_->getOwner();
runtimeExecutor_([this, weakOwner](jsi::Runtime &runtime) mutable {
auto owner = weakOwner.lock();
if (!owner) {
return;
}
if (!isRequested_) {
return;
}
this->beat(runtime);
});
}
} // namespace react
} // namespace facebook
| /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "AsynchronousEventBeat.h"
#include <react/debug/react_native_assert.h>
namespace facebook {
namespace react {
AsynchronousEventBeat::AsynchronousEventBeat(
RunLoopObserver::Unique uiRunLoopObserver,
RuntimeExecutor runtimeExecutor)
: EventBeat({}),
uiRunLoopObserver_(std::move(uiRunLoopObserver)),
runtimeExecutor_(std::move(runtimeExecutor)) {
uiRunLoopObserver_->setDelegate(this);
uiRunLoopObserver_->enable();
}
void AsynchronousEventBeat::activityDidChange(
RunLoopObserver::Delegate const *delegate,
RunLoopObserver::Activity activity) const noexcept {
react_native_assert(delegate == this);
induce();
}
void AsynchronousEventBeat::induce() const {
if (!isRequested_) {
return;
}
// Here we know that `this` object exists because the caller has a strong
// pointer to `owner`. To ensure the object will exist inside
// `runtimeExecutor_` callback, we need to copy the pointer there.
auto weakOwner = uiRunLoopObserver_->getOwner();
runtimeExecutor_([this, weakOwner](jsi::Runtime &runtime) mutable {
auto owner = weakOwner.lock();
if (!owner) {
return;
}
if (!isRequested_) {
return;
}
this->beat(runtime);
});
}
} // namespace react
} // namespace facebook
|
Add more unit tests for vector |
#include <gtest/gtest.h>
#include "Vector2f.h"
TEST(Vector2fTest, VectorAddition) {
Vector2f v1(0, 0);
Vector2f v2(1, 2);
Vector2f v3(3, 4);
Vector2f result = v1 + v1;
EXPECT_FLOAT_EQ(0.0f, result.x);
EXPECT_FLOAT_EQ(0.0f, result.y);
result = v2 + v1;
EXPECT_FLOAT_EQ(v2.x, result.x);
EXPECT_FLOAT_EQ(v2.y, result.y);
result = v2 + v3;
EXPECT_FLOAT_EQ(4.0f, result.x);
EXPECT_FLOAT_EQ(6.0f, result.y);
// TEST
EXPECT_FLOAT_EQ(7.0f, result.y);
} |
#include <gtest/gtest.h>
#include "Vector2f.h"
Vector2f v1(0,0);
Vector2f v2(1, 2);
Vector2f v3(3, 4);
Vector2f v4(-5, 6);
TEST(Vector2fTest, VectorAddition) {
Vector2f result = v1 + v1;
EXPECT_FLOAT_EQ(0.0f, result.x);
EXPECT_FLOAT_EQ(0.0f, result.y);
result = v2 + v1;
EXPECT_FLOAT_EQ(v2.x, result.x);
EXPECT_FLOAT_EQ(v2.y, result.y);
result = v2 + v3;
EXPECT_FLOAT_EQ(4.0f, result.x);
EXPECT_FLOAT_EQ(6.0f, result.y);
result = v3 + v4;
EXPECT_FLOAT_EQ(-2.0f, result.x);
EXPECT_FLOAT_EQ(10.0f, result.y);
}
TEST(Vector2fTest, VectorDot) {
EXPECT_FLOAT_EQ(0.0f, v1.dot(v1));
EXPECT_FLOAT_EQ(11.0f, v2.dot(v3));
} |
Handle parsing errors in the example. | #include "cpptoml.h"
#include <iostream>
#include <cassert>
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " filename" << std::endl;
return 1;
}
cpptoml::toml_group g = cpptoml::parse_file(argv[1]);
std::cout << g << std::endl;
return 0;
}
| #include "cpptoml.h"
#include <iostream>
#include <cassert>
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " filename" << std::endl;
return 1;
}
try
{
cpptoml::toml_group g = cpptoml::parse_file(argv[1]);
std::cout << g << std::endl;
}
catch (const cpptoml::toml_parse_exception& e)
{
std::cerr << "Failed to parse " << argv[1] << ": " << e.what() << std::endl;
return 1;
}
return 0;
}
|
Call update in update entity | #include "Game/CannonBall.h"
CannonBall::CannonBall(const QPixmap & pixmap, QVector2D velocity, QVector2D position, Player owner, QGraphicsItem * parent) : Entity(pixmap, owner, parent), m_initialVelocity(velocity), m_initialPosition(position), m_gravity(9.8), m_timeSinceShot(0)
{
setScale(0.1);
setPos(m_initialPosition.toPointF());
}
void CannonBall::updateEntity(double deltaTime)
{
m_timeSinceShot += deltaTime/1000.0 * 2.0;
double x = m_initialPosition.x() + m_initialVelocity.x() * m_timeSinceShot;
double y = m_initialPosition.y() - m_initialVelocity.y() * m_timeSinceShot + 0.5 * m_gravity * m_timeSinceShot * m_timeSinceShot;
setPos(x, y);
}
| #include "Game/CannonBall.h"
CannonBall::CannonBall(const QPixmap & pixmap, QVector2D velocity, QVector2D position, Player owner, QGraphicsItem * parent) : Entity(pixmap, owner, parent), m_initialVelocity(velocity), m_initialPosition(position), m_gravity(9.8), m_timeSinceShot(0)
{
setScale(0.1);
setPos(m_initialPosition.toPointF());
}
void CannonBall::updateEntity(double deltaTime)
{
m_timeSinceShot += deltaTime/1000.0 * 2.0;
double x = m_initialPosition.x() + m_initialVelocity.x() * m_timeSinceShot;
double y = m_initialPosition.y() - m_initialVelocity.y() * m_timeSinceShot + 0.5 * m_gravity * m_timeSinceShot * m_timeSinceShot;
setPos(x, y);
update(boundingRect());
}
|
Test case fix for r264783 | // Check the value profiling instrinsics emitted by instrumentation.
// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -mllvm -enable-value-profiling -fexceptions -target %itanium_abi_triple | FileCheck %s
void (*foo) (void);
int main(int argc, const char *argv[]) {
// CHECK: [[REG1:%[0-9]+]] = load void ()*, void ()** @foo, align 4
// CHECK-NEXT: [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT: call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT: invoke void [[REG1]]()
try {
foo();
} catch (int) {}
return 0;
}
// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)
| // Check the value profiling instrinsics emitted by instrumentation.
// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -mllvm -enable-value-profiling -fexceptions -target %itanium_abi_triple | FileCheck %s
void (*foo) (void);
int main(int argc, const char *argv[]) {
// CHECK: [[REG1:%[0-9]+]] = load void ()*, void ()** @foo
// CHECK-NEXT: [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT: call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT: invoke void [[REG1]]()
try {
foo();
} catch (int) {}
return 0;
}
// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)
|
Move transform_util unittest into gfx namespace. | // 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 "ui/gfx/transform_util.h"
#include "ui/gfx/point.h"
#include "testing/gtest/include/gtest/gtest.h"
TEST(TransformUtilTest, GetScaleTransform) {
const gfx::Point kAnchor(20, 40);
const float kScale = 0.5f;
gfx::Transform scale = gfx::GetScaleTransform(kAnchor, kScale);
const int kOffset = 10;
for (int sign_x = -1; sign_x <= 1; ++sign_x) {
for (int sign_y = -1; sign_y <= 1; ++sign_y) {
gfx::Point test(kAnchor.x() + sign_x * kOffset,
kAnchor.y() + sign_y * kOffset);
scale.TransformPoint(test);
EXPECT_EQ(gfx::Point(kAnchor.x() + sign_x * kOffset * kScale,
kAnchor.y() + sign_y * kOffset * kScale),
test);
}
}
}
| // 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 "ui/gfx/transform_util.h"
#include "ui/gfx/point.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gfx {
namespace {
TEST(TransformUtilTest, GetScaleTransform) {
const Point kAnchor(20, 40);
const float kScale = 0.5f;
Transform scale = GetScaleTransform(kAnchor, kScale);
const int kOffset = 10;
for (int sign_x = -1; sign_x <= 1; ++sign_x) {
for (int sign_y = -1; sign_y <= 1; ++sign_y) {
Point test(kAnchor.x() + sign_x * kOffset,
kAnchor.y() + sign_y * kOffset);
scale.TransformPoint(test);
EXPECT_EQ(Point(kAnchor.x() + sign_x * kOffset * kScale,
kAnchor.y() + sign_y * kOffset * kScale),
test);
}
}
}
} // namespace
} // namespace gfx
|
Add GetLastError info to DummyLoader test | #include <windows.h>
#include <tchar.h>
#include <stdio.h>
int _tmain(int argc, TCHAR * argv[])
{
if(1 >= argc)
{
_tprintf(_T("DummLoader.exe <DllName>*\n"));
return 0;
}
for(int i=1; i<argc; i++)
{
_tprintf(_T("Loading: \"%s\" "), argv[i]);
HMODULE hm = LoadLibrary(argv[i]);
_tprintf(_T("[ %s ]\n"), hm ? _T("OK") : _T("FAIL"));
}
return 0;
}
| #include <windows.h>
#include <tchar.h>
#include <stdio.h>
int _tmain(int argc, TCHAR * argv[])
{
if(1 >= argc)
{
_tprintf(_T("DummLoader.exe <DllName>*\n"));
return 0;
}
for(int i=1; i<argc; i++)
{
_tprintf(_T("Loading: \"%s\" "), argv[i]);
HMODULE hm = LoadLibrary(argv[i]);
DWORD lastError = GetLastError();
_tprintf(_T("[ %s ] GetLastError = %u\n"), hm ? _T("OK") : _T("FAIL"), lastError);
}
return 0;
}
|
Copy necessary assets on Android QML startup | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "functions.h"
#include "main-screen.h"
#include "models/profile.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
app.setApplicationName("Grabber");
app.setApplicationVersion(VERSION);
app.setOrganizationName("Bionus");
app.setOrganizationDomain("bionus.fr.cr");
const QUrl url(QStringLiteral("qrc:/main-screen.qml"));
QQmlApplicationEngine engine;
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl) {
QCoreApplication::exit(-1);
}
}, Qt::QueuedConnection);
Profile profile(savePath());
MainScreen mainScreen(&profile);
engine.rootContext()->setContextProperty("backend", &mainScreen);
engine.load(url);
return app.exec();
}
| #include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "functions.h"
#include "main-screen.h"
#include "models/profile.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
app.setApplicationName("Grabber");
app.setApplicationVersion(VERSION);
app.setOrganizationName("Bionus");
app.setOrganizationDomain("bionus.fr.cr");
// Copy settings files to writable directory
const QStringList toCopy { "sites/", "themes/", "webservices/" };
for (const QString &tgt : toCopy) {
const QString from = savePath(tgt, true, false);
const QString to = savePath(tgt, true, true);
if (!QDir(to).exists() && QDir(from).exists()) {
copyRecursively(from, to);
}
}
const QUrl url(QStringLiteral("qrc:/main-screen.qml"));
QQmlApplicationEngine engine;
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl) {
QCoreApplication::exit(-1);
}
}, Qt::QueuedConnection);
Profile profile(savePath());
MainScreen mainScreen(&profile);
engine.rootContext()->setContextProperty("backend", &mainScreen);
engine.load(url);
return app.exec();
}
|
Use 1280 x 720 as the default resolution | /* The Halfling Project - A Graphics Engine and Projects
*
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "obj_loader_demo/obj_loader_demo.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
ObjLoaderDemo::ObjLoaderDemo app(hInstance);
DBG_UNREFERENCED_PARAMETER(hPrevInstance);
DBG_UNREFERENCED_PARAMETER(lpCmdLine);
DBG_UNREFERENCED_PARAMETER(nCmdShow);
app.Initialize(L"OBJ Loader Demo", 800, 600, false);
app.Run();
app.Shutdown();
return 0;
}
| /* The Halfling Project - A Graphics Engine and Projects
*
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "obj_loader_demo/obj_loader_demo.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
ObjLoaderDemo::ObjLoaderDemo app(hInstance);
DBG_UNREFERENCED_PARAMETER(hPrevInstance);
DBG_UNREFERENCED_PARAMETER(lpCmdLine);
DBG_UNREFERENCED_PARAMETER(nCmdShow);
app.Initialize(L"OBJ Loader Demo", 1280, 720, false);
app.Run();
app.Shutdown();
return 0;
}
|
Remove old swap files when setting up mmap file allocator. | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "mmap_file_allocator_factory.h"
#include "mmap_file_allocator.h"
#include <vespa/vespalib/stllike/asciistream.h>
namespace vespalib::alloc {
MmapFileAllocatorFactory::MmapFileAllocatorFactory()
: _dir_name(),
_generation(0)
{
}
MmapFileAllocatorFactory::~MmapFileAllocatorFactory()
{
}
void
MmapFileAllocatorFactory::setup(const vespalib::string& dir_name)
{
_dir_name = dir_name;
_generation = 0;
}
std::unique_ptr<MemoryAllocator>
MmapFileAllocatorFactory::make_memory_allocator(const vespalib::string& name)
{
if (_dir_name.empty()) {
return {};
}
vespalib::asciistream os;
os << _dir_name << "/" << _generation.fetch_add(1) << "." << name;
return std::make_unique<MmapFileAllocator>(os.str());
};
MmapFileAllocatorFactory&
MmapFileAllocatorFactory::instance()
{
static MmapFileAllocatorFactory instance;
return instance;
}
}
| // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "mmap_file_allocator_factory.h"
#include "mmap_file_allocator.h"
#include <vespa/vespalib/io/fileutil.h>
#include <vespa/vespalib/stllike/asciistream.h>
namespace vespalib::alloc {
MmapFileAllocatorFactory::MmapFileAllocatorFactory()
: _dir_name(),
_generation(0)
{
}
MmapFileAllocatorFactory::~MmapFileAllocatorFactory()
{
}
void
MmapFileAllocatorFactory::setup(const vespalib::string& dir_name)
{
_dir_name = dir_name;
_generation = 0;
if (!_dir_name.empty()) {
rmdir(_dir_name, true);
}
}
std::unique_ptr<MemoryAllocator>
MmapFileAllocatorFactory::make_memory_allocator(const vespalib::string& name)
{
if (_dir_name.empty()) {
return {};
}
vespalib::asciistream os;
os << _dir_name << "/" << _generation.fetch_add(1) << "." << name;
return std::make_unique<MmapFileAllocator>(os.str());
};
MmapFileAllocatorFactory&
MmapFileAllocatorFactory::instance()
{
static MmapFileAllocatorFactory instance;
return instance;
}
}
|
Use a VTK output window we can actually read if the app crashes. | // TODO: remove this later, hack for include order issues
#include "GLBlaat/GL.h"
#include <QApplication>
#include "Gui/MainWindow.h"
int main(int argc, char *argv[])
{
// Set up Qt application
QApplication app(argc, argv);
VFE::MainWindow *window = new VFE::MainWindow();
// Go!
window->show();
app.exec();
// Clean up and exit
delete window;
return 0;
}
| // TODO: remove this later, hack for include order issues
#include "GLBlaat/GL.h"
#include <QApplication>
#include "Gui/MainWindow.h"
#include <vtkWin32ProcessOutputWindow.h>
int main(int argc, char *argv[])
{
#ifdef WIN32
// Use a more useful output window for VTK
vtkWin32ProcessOutputWindow *ow = vtkWin32ProcessOutputWindow::New();
vtkWin32ProcessOutputWindow::SetInstance(ow);
ow->Delete();
#endif
// Set up Qt application
QApplication app(argc, argv);
VFE::MainWindow *window = new VFE::MainWindow();
// Go!
window->show();
app.exec();
// Clean up and exit
delete window;
return 0;
}
|
Add a quick and dirty way to access a remote OSVR server: using the environment variable OSVR_HOST. | /** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <osvr/ClientKit/ContextC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/CreateContext.h>
// Library/third-party includes
// - none
// Standard includes
// - none
OSVR_ClientContext osvrClientInit(const char applicationIdentifier[],
uint32_t /*flags*/) {
return ::osvr::client::createContext(applicationIdentifier);
}
OSVR_ReturnCode osvrClientUpdate(OSVR_ClientContext ctx) {
ctx->update();
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrClientShutdown(OSVR_ClientContext ctx) {
delete ctx;
return OSVR_RETURN_SUCCESS;
} | /** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <osvr/ClientKit/ContextC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/CreateContext.h>
// Library/third-party includes
// - none
// Standard includes
// - none
static const char HOST_ENV_VAR[] = "OSVR_HOST";
OSVR_ClientContext osvrClientInit(const char applicationIdentifier[],
uint32_t /*flags*/) {
char *host = ::getenv(HOST_ENV_VAR);
if (nullptr != host) {
return ::osvr::client::createContext(applicationIdentifier, host);
} else {
return ::osvr::client::createContext(applicationIdentifier);
}
}
OSVR_ReturnCode osvrClientUpdate(OSVR_ClientContext ctx) {
ctx->update();
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode osvrClientShutdown(OSVR_ClientContext ctx) {
delete ctx;
return OSVR_RETURN_SUCCESS;
} |
Fix shading language include paths |
#include "ShadingLanguageIncludeImplementation_ShadingLanguageIncludeARB.h"
#include <glbinding/gl/functions.h>
#include <globjects/Shader.h>
#include <globjects/base/AbstractStringSource.h>
using namespace gl;
namespace globjects
{
void ShadingLanguageIncludeImplementation_ARB::updateSources(const Shader * shader) const
{
std::string source;
if (shader->source()) {
source = shader->source()->string();
}
const char* sourcePtr = source.c_str();
glShaderSource(shader->id(), static_cast<GLint>(1), &sourcePtr, nullptr);
}
void ShadingLanguageIncludeImplementation_ARB::compile(const Shader * shader) const
{
std::vector<const char*> cStrings = collectCStrings(shader->includePaths());
glCompileShaderIncludeARB(shader->id(), static_cast<GLint>(cStrings.size()), cStrings.data(), nullptr);
}
} // namespace globjects
|
#include "ShadingLanguageIncludeImplementation_ShadingLanguageIncludeARB.h"
#include <glbinding/gl/functions.h>
#include <globjects/Shader.h>
#include <globjects/base/AbstractStringSource.h>
using namespace gl;
namespace globjects
{
void ShadingLanguageIncludeImplementation_ARB::updateSources(const Shader * shader) const
{
std::string source;
if (shader->source()) {
source = shader->source()->string();
}
const char* sourcePtr = source.c_str();
glShaderSource(shader->id(), static_cast<GLint>(1), &sourcePtr, nullptr);
}
void ShadingLanguageIncludeImplementation_ARB::compile(const Shader * shader) const
{
if (!shader->includePaths().empty())
{
std::vector<const char*> cStrings = collectCStrings(shader->includePaths());
glCompileShaderIncludeARB(shader->id(), static_cast<GLint>(cStrings.size()), cStrings.data(), nullptr);
}
else
{
glCompileShaderIncludeARB(shader->id(), 0, nullptr, nullptr);
}
}
} // namespace globjects
|
Add a new flag for cluster name | /// Copyright 2019 Pinterest Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include "common/kafka/stats_enum.h"
#include <string>
#include <utility>
#include <vector>
#include "gflags/gflags.h"
DEFINE_string(kafka_stats_prefix, "", "Prefix for the kafka stats");
DEFINE_string(kafka_stats_suffix, "", "Suffix for the kafka stats");
std::string getFullStatsName(const std::string& metric_name,
const std::initializer_list<std::string>& tags) {
std::string full_metric_name;
full_metric_name.append(FLAGS_kafka_stats_prefix)
.append(metric_name)
.append(FLAGS_kafka_stats_suffix);
for (const auto& tag : tags) {
full_metric_name.append(" ").append(tag);
}
return full_metric_name;
}
| /// Copyright 2019 Pinterest Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include "common/kafka/stats_enum.h"
#include <string>
#include <utility>
#include <vector>
#include "gflags/gflags.h"
DEFINE_string(kafka_stats_prefix, "", "Prefix for the kafka stats");
DEFINE_string(kafka_stats_suffix, "", "Suffix for the kafka stats");
DEFINE_string(kafka_cluster_name, "", "Cluster consuming the kafka messages");
std::string getFullStatsName(const std::string& metric_name,
const std::initializer_list<std::string>& tags) {
std::string full_metric_name;
full_metric_name.append(FLAGS_kafka_stats_prefix)
.append(metric_name)
.append("_")
.append(FLAGS_kafka_stats_suffix)
.append(" cluster=")
.append(FLAGS_kafka_cluster_name);
for (const auto& tag : tags) {
full_metric_name.append(" ").append(tag);
}
return full_metric_name;
}
|
Test - fix blinky test - print host test result | /* mbed Microcontroller Library
* Copyright (c) 2013-2014 ARM Limited
*
* 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 "mbed.h"
#include "test_env.h"
DigitalOut myled(LED1);
uint32_t count = 20;
void blink() {
if (count) {
if (count == 1) {
printf("{{success}}\r\n");
}
count--;
}
myled = !myled;
}
void app_start(int, char*[]) {
MBED_HOSTTEST_TIMEOUT(20);
MBED_HOSTTEST_SELECT(default_auto);
MBED_HOSTTEST_DESCRIPTION(Blinky);
MBED_HOSTTEST_START("MBED_BLINKY");
minar::Scheduler::postCallback(&blink).period(minar::milliseconds(200));
}
| /* mbed Microcontroller Library
* Copyright (c) 2013-2014 ARM Limited
*
* 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 "mbed.h"
#include "test_env.h"
DigitalOut myled(LED1);
uint32_t count = 20;
void blink() {
if (count) {
if (count == 1) {
MBED_HOSTTEST_RESULT(true);
}
count--;
}
myled = !myled;
}
void app_start(int, char*[]) {
MBED_HOSTTEST_TIMEOUT(20);
MBED_HOSTTEST_SELECT(default_auto);
MBED_HOSTTEST_DESCRIPTION(Blinky);
MBED_HOSTTEST_START("MBED_BLINKY");
minar::Scheduler::postCallback(&blink).period(minar::milliseconds(200));
}
|
Add forgotten include and return. | #include <cstdlib>
#include <libport/backtrace.hh>
#include <libport/config.h>
#if LIBPORT_HAVE_EXECINFO_H
# include <execinfo.h>
namespace libport
{
std::vector<const char*>
backtrace()
{
enum { size = 128 };
void* callstack[size];
size_t frames = ::backtrace(callstack, size);
char** strs = backtrace_symbols(callstack, frames);
std::vector<const char*> res(frames, 0);
for (size_t i = 0; i < frames; ++i)
res[i] = strs[i];
free(strs);
return res;
}
}
#else // ! LIBPORT_HAVE_EXECINFO_H
namespace libport
{
std::vector<const char*>
backtrace()
{
std::vector<const char*> res;
res.push_back("(no avaible backtrace)");
}
}
#endif
| #include <cstdlib>
#include <libport/backtrace.hh>
#include <libport/config.h>
#if LIBPORT_HAVE_EXECINFO_H
# include <execinfo.h>
# include <cstdlib>
namespace libport
{
std::vector<const char*>
backtrace()
{
enum { size = 128 };
void* callstack[size];
size_t frames = ::backtrace(callstack, size);
char** strs = backtrace_symbols(callstack, frames);
std::vector<const char*> res(frames, 0);
for (size_t i = 0; i < frames; ++i)
res[i] = strs[i];
free(strs);
return res;
}
}
#else // ! LIBPORT_HAVE_EXECINFO_H
namespace libport
{
std::vector<const char*>
backtrace()
{
std::vector<const char*> res;
res.push_back("(no avaible backtrace)");
return res;
}
}
#endif
|
Print function symbols when dumping asm. | #include "instr.h"
namespace sasm { namespace instr {
instr::instr(const sasm::elf::elf& elf, uint64 addr)
: _elf(elf), _addr(addr)
{
}
void instr::_dump_addr(std::ostream& out) const
{
out << "0x" << std::hex << _addr << std::dec << ": ";
}
}}
| #include "instr.h"
namespace sasm { namespace instr {
instr::instr(const sasm::elf::elf& elf, uint64 addr)
: _elf(elf), _addr(addr)
{
}
void instr::_dump_addr(std::ostream& out) const
{
try
{
auto sym = _elf.symtab[_addr];
if (sym.type == sasm::elf::symtab::symbol::sym_type::func)
out << std::endl << sym.name << ":" << std::endl;
}
catch (std::out_of_range& e) {}
out << " 0x" << std::hex << _addr << std::dec << ": ";
}
}}
|
Initialize all variables for CNodeState | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "nodestate.h"
/**
* Default constructor initializing all local member variables to "null" values
*/
CNodeState::CNodeState()
{
pindexBestKnownBlock = nullptr;
hashLastUnknownBlock.SetNull();
pindexLastCommonBlock = nullptr;
pindexBestHeaderSent = nullptr;
fSyncStarted = false;
nDownloadingSince = 0;
nBlocksInFlight = 0;
nBlocksInFlightValidHeaders = 0;
fPreferredDownload = false;
fPreferHeaders = false;
fRequestedInitialBlockAvailability = false;
}
/**
* Gets the CNodeState for the specified NodeId.
*
* @param[in] pnode The NodeId to return CNodeState* for
* @return CNodeState* matching the NodeId, or NULL if NodeId is not matched
*/
CNodeState *State(NodeId pnode)
{
std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end())
return nullptr;
return &it->second;
}
| // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "nodestate.h"
/**
* Default constructor initializing all local member variables to "null" values
*/
CNodeState::CNodeState()
{
pindexBestKnownBlock = nullptr;
hashLastUnknownBlock.SetNull();
pindexLastCommonBlock = nullptr;
pindexBestHeaderSent = nullptr;
fSyncStarted = false;
fSyncStartTime = -1;
fFirstHeadersReceived = false;
nFirstHeadersExpectedHeight = -1;
fRequestedInitialBlockAvailability = false;
nDownloadingSince = 0;
nBlocksInFlight = 0;
nBlocksInFlightValidHeaders = 0;
fPreferredDownload = false;
fPreferHeaders = true;
}
/**
* Gets the CNodeState for the specified NodeId.
*
* @param[in] pnode The NodeId to return CNodeState* for
* @return CNodeState* matching the NodeId, or NULL if NodeId is not matched
*/
CNodeState *State(NodeId pnode)
{
std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end())
return nullptr;
return &it->second;
}
|
Read two integers and write them out | #include <iostream>
#include <conio.h>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
cout << "Szymon Blaszczynski" << endl;
cout << setprecision(8) << M_PI << endl;
cout << "\"Ala\"" << endl;
getch();
// system("PAUSE"); // work on linux? no.
return 0;
}
| #include <iostream>
// #include <conio.h> // getch
// #include <cstdlib> # system
#include <cmath>
#include <iomanip>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
cout << "Szymon Blaszczynski" << endl;
cout << setprecision(8) << M_PI << endl;
cout << "\"Ala\"" << endl;
cout << "'" << endl;
int number_0 = 0;
int number_1 = 0;
cout << "Podaj dwie liczby: ";
cin >> number_0 >> number_1;
cout << "Liczba pierwsza: " << number_0 << ", liczba druga: " << number_1 \
<< "." << endl;
// system("PAUSE"); // works on linux? no.
return 0;
}
|
Add apply to Delegate type. | /**
** \file object/delegate-class.cc
** \brief Creation of the URBI object delegate.
*/
#include "object/delegate-class.hh"
#include "object/object.hh"
#include "object/primitives.hh"
#include "runner/runner.hh"
namespace object
{
rObject delegate_class;
/*-----------------------.
| Primitive primitives. |
`-----------------------*/
void
delegate_class_initialize ()
{
#define DECLARE(Name) \
DECLARE_PRIMITIVE(delegate, Name)
#undef DECLARE
}
} // namespace object
| /**
** \file object/delegate-class.cc
** \brief Creation of the URBI object delegate.
*/
#include "object/delegate-class.hh"
#include "object/object.hh"
#include "object/primitives.hh"
#include "runner/runner.hh"
namespace object
{
rObject delegate_class;
/*-----------------------.
| Primitive primitives. |
`-----------------------*/
static rObject
delegate_class_apply (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (2);
FETCH_ARG (1, List);
return r.apply (args[0], arg1);
}
void
delegate_class_initialize ()
{
#define DECLARE(Name) \
DECLARE_PRIMITIVE(delegate, Name)
DECLARE (apply);
#undef DECLARE
}
} // namespace object
|
Fix test case to unbreak testing | // RUN: %clang_cc1 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s
struct A {
virtual ~A();
};
struct B : A { };
struct C {
int i;
B b;
};
// CHECK: _Z15test_value_initv
void test_value_init() {
// This value initialization requires zero initialization of the 'B'
// subobject followed by a call to its constructor.
// PR5800
// CHECK: store i32 17
// CHECK: call void @llvm.memset.i64
// CHECK: call void @_ZN1BC1Ev(%struct.A* %tmp1)
C c = { 17 } ;
// CHECK: call void @_ZN1CD1Ev(%struct.C* %c)
}
| // RUN: %clang_cc1 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s
struct A {
virtual ~A();
};
struct B : A { };
struct C {
int i;
B b;
};
// CHECK: _Z15test_value_initv
void test_value_init() {
// This value initialization requires zero initialization of the 'B'
// subobject followed by a call to its constructor.
// PR5800
// CHECK: store i32 17
// CHECK: call void @llvm.memset.i64
// CHECK: call void @_ZN1BC1Ev
C c = { 17 } ;
// CHECK: call void @_ZN1CD1Ev
}
|
Add boundary value in loop expression | #include "insertion.hpp"
#include "swap.hpp"
void insertion(int *data, int size_of_data)
{
for(int i = 0; i < size_of_data; ++i)
{
int j;
for(j = i; data[j] < data[i]; --j);
swap(data[i], data[j]);
}
}
| #include "insertion.hpp"
#include "swap.hpp"
void insertion(int *data, int size_of_data)
{
for(int i = 0; i < size_of_data; ++i)
{
int j;
for(j = i; j >= 0 && data[j] < data[i]; --j);
swap(data[i], data[j]);
}
}
|
Put functions in the required class | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;
int getMinHelper(vector<int> DesiredArray, int Moves)
{
if(all_of(begin(DesiredArray), end(DesiredArray), [] (const int & element) {return element==0;}))
{
return Moves;
}
if(all_of(begin(DesiredArray), end(DesiredArray), [] (int & element) {return element%2==0;}))
{
for(auto & element : DesiredArray)
{
element/=2;
}
Moves++;
}
else
{
for(auto & element : DesiredArray)
{
if(element%2==1)
{
element--;
Moves++;
}
}
}
return getMinHelper(DesiredArray, Moves);
}
int getMin(vector<int> DesiredArray)
{
int moves{};
int result=getMinHelper(DesiredArray, moves);
return result;
} | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;
class IncrementAndDoubling
{
public:
int getMinHelper(vector<int> DesiredArray, int Moves)
{
if(all_of(begin(DesiredArray), end(DesiredArray), [] (const int & element) {return element==0;}))
{
return Moves;
}
if(all_of(begin(DesiredArray), end(DesiredArray), [] (int & element) {return element%2==0;}))
{
for(auto & element : DesiredArray)
{
element/=2;
}
Moves++;
}
else
{
for(auto & element : DesiredArray)
{
if(element%2==1)
{
element--;
Moves++;
}
}
}
return getMinHelper(DesiredArray, Moves);
}
int getMin(vector<int> DesiredArray)
{
int moves{};
int result=getMinHelper(DesiredArray, moves);
return result;
}
}; |
Remove now unneded hack from embedding example. | #include "embedded.h"
#include <QtCore>
#include <QVBoxLayout>
#include <QApplication>
#include <QDesktopWidget>
#include <maliit/namespace.h>
#include <maliit/inputmethod.h>
MainWindow::MainWindow()
: QMainWindow()
{
initUI();
}
MainWindow::~MainWindow()
{}
void MainWindow::initUI()
{
setWindowTitle("Maliit embedded demo");
setCentralWidget(new QWidget);
QVBoxLayout *vbox = new QVBoxLayout;
QPushButton *closeApp = new QPushButton("Close application");
vbox->addWidget(closeApp);
connect(closeApp, SIGNAL(clicked()),
this, SLOT(close()));
// Clicking the button will steal focus from the text edit, thus hiding
// the virtual keyboard:
QPushButton *hideVkb = new QPushButton("Hide virtual keyboard");
vbox->addWidget(hideVkb);
QTextEdit *textEdit = new QTextEdit;
vbox->addWidget(textEdit);
QWidget *imWidget = Maliit::InputMethod::instance()->widget();
if (imWidget) {
imWidget->setParent(centralWidget());
vbox->addWidget(imWidget);
// FIXME: hack to work around the fact that plugins expect a desktop sized widget
QSize desktopSize = QApplication::desktop()->size();
imWidget->setMinimumSize(desktopSize.width(), desktopSize.height() - 150);
} else {
qCritical() << "Unable to embedded Maliit input method widget";
}
centralWidget()->setLayout(vbox);
show();
imWidget->hide();
}
| #include "embedded.h"
#include <QtCore>
#include <QVBoxLayout>
#include <QApplication>
#include <QDesktopWidget>
#include <maliit/namespace.h>
#include <maliit/inputmethod.h>
MainWindow::MainWindow()
: QMainWindow()
{
initUI();
}
MainWindow::~MainWindow()
{}
void MainWindow::initUI()
{
setWindowTitle("Maliit embedded demo");
setCentralWidget(new QWidget);
QVBoxLayout *vbox = new QVBoxLayout;
QPushButton *closeApp = new QPushButton("Close application");
vbox->addWidget(closeApp);
connect(closeApp, SIGNAL(clicked()),
this, SLOT(close()));
// Clicking the button will steal focus from the text edit, thus hiding
// the virtual keyboard:
QPushButton *hideVkb = new QPushButton("Hide virtual keyboard");
vbox->addWidget(hideVkb);
QTextEdit *textEdit = new QTextEdit;
vbox->addWidget(textEdit);
QWidget *imWidget = Maliit::InputMethod::instance()->widget();
if (imWidget) {
imWidget->setParent(centralWidget());
vbox->addWidget(imWidget);
} else {
qCritical() << "Unable to embedded Maliit input method widget";
}
centralWidget()->setLayout(vbox);
show();
}
|
Add command line help for --strategy formal | // Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "tools/args/verifier.h"
using namespace cpputil;
namespace stoke {
Heading& verifier_heading =
Heading::create("Verifier Options:");
ValueArg<Strategy, StrategyReader, StrategyWriter>& strategy_arg =
ValueArg<Strategy, StrategyReader, StrategyWriter>::create("strategy")
.usage("(none|hold_out|extension)")
.description("Verification strategy")
.default_val(Strategy::NONE);
} // namespace stoke
| // Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "tools/args/verifier.h"
using namespace cpputil;
namespace stoke {
Heading& verifier_heading =
Heading::create("Verifier Options:");
ValueArg<Strategy, StrategyReader, StrategyWriter>& strategy_arg =
ValueArg<Strategy, StrategyReader, StrategyWriter>::create("strategy")
.usage("(none|hold_out|formal|extension)")
.description("Verification strategy")
.default_val(Strategy::NONE);
} // namespace stoke
|
Handle errors loading block types | #include "mainwindow.h"
#include <QApplication>
#include <QFile>
#include "applicationdata.h"
#include "blocktype.h"
#include <QJsonDocument>
#include <QJsonArray>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString appDir = a.applicationDirPath();
QString xmlPath = appDir + "/blocks.json";
QFile xmlFile(xmlPath);
if (!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
// error message
return 1;
}
QByteArray bytes = xmlFile.readAll();
QJsonDocument doc = QJsonDocument::fromJson(bytes);
QJsonArray nodeArray = doc.array();
ApplicationData appData;
appData.blockTypes = BlockTypes_fromJson(nodeArray);
MainWindow w(appData);
w.show();
return a.exec();
}
| #include "mainwindow.h"
#include <QApplication>
#include <QFile>
#include "applicationdata.h"
#include "blocktype.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QMessageBox>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString appDir = a.applicationDirPath();
QString xmlPath = appDir + "/blocks.json";
QFile xmlFile(xmlPath);
if (!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::critical(0, "SignalCraft failed to open blocks.json",
"The block.json file could not be opened. Ensure that it exists.");
return 1;
}
QByteArray bytes = xmlFile.readAll();
QJsonParseError parseErr;
QJsonDocument doc = QJsonDocument::fromJson(bytes, &parseErr);
if (parseErr.error != QJsonParseError::NoError) {
QMessageBox::critical(0, "SignalCraft failed to parse blocks.json",
"The block.json file could not be parsed as valid JSON. The parser reported: \"" +
parseErr.errorString() +
"\" at offset " +
QString::number(parseErr.offset) +
".");
return 1;
}
QJsonArray nodeArray = doc.array();
ApplicationData appData;
bool success;
appData.blockTypes = BlockTypes_fromJson(nodeArray, &success);
if (!success) {
QMessageBox::critical(0, "SignalCraft failed to interpret blocks.json",
"The block.json file did not fit the required structure.");
return 1;
}
MainWindow w(appData);
w.show();
return a.exec();
}
|
Support assignment and conversion to lists and dicts. | #include <pybind11/pybind11.h>
#include "basics.hpp"
#include "containers.hpp"
namespace py = pybind11;
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
namespace containers {
PYBIND11_PLUGIN(containers) {
py::module m("containers", "wrapped C++ containers module");
py::class_<containers::DoodadSet>(m, "DoodadSet")
.def(py::init<>())
.def("__len__", &containers::DoodadSet::size)
.def("add", [](containers::DoodadSet &ds, std::shared_ptr<basics::Doodad> &d) { ds.add(d); });
return m.ptr();
}
} // namespace containers
| #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "basics.hpp"
#include "containers.hpp"
namespace py = pybind11;
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
namespace containers {
PYBIND11_PLUGIN(containers) {
py::module m("containers", "wrapped C++ containers module");
py::class_<containers::DoodadSet>(m, "DoodadSet")
.def(py::init<>())
.def("__len__", &containers::DoodadSet::size)
.def("add", [](containers::DoodadSet &ds, std::shared_ptr<basics::Doodad> &d) { ds.add(d); })
.def("add", [](containers::DoodadSet &ds, std::pair<std::string, int> p) { ds.add(basics::WhatsIt{p.first, p.second}) ; })
.def("as_dict", &containers::DoodadSet::as_map)
.def("as_list", &containers::DoodadSet::as_vector)
.def("assign", &containers::DoodadSet::assign);
return m.ptr();
}
} // namespace containers
|
Update test to mention it requires C++14. | // RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/self-referencing-lambda %s -verify -emit-obj -o %t2.o
// expected-no-diagnostics
#include "a.h"
| // RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/self-referencing-lambda %s -verify -emit-obj -std=c++14 -o %t2.o
// expected-no-diagnostics
#include "a.h"
|
Test multiple initialization for SWI-Prolog | #include "gtest/gtest.h"
#include "PrologInterface.h"
#include <iostream>
namespace {
static int glob_argc;
static char **glob_argv;
class PrologLifetimeTest : public ::testing::Test {
};
TEST_F(PrologLifetimeTest, BeginInitializesProlog) {
PrologLifetime::begin(glob_argc, glob_argv);
ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
PrologLifetime::end();
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
glob_argc = argc;
glob_argv = argv;
return RUN_ALL_TESTS();
}
| #include "gtest/gtest.h"
#include "PrologInterface.h"
#include <iostream>
namespace {
static int glob_argc;
static char **glob_argv;
class PrologLifetimeTest : public ::testing::Test {
};
TEST_F(PrologLifetimeTest, BeginInitializesProlog) {
PrologLifetime::begin(glob_argc, glob_argv);
ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
PrologLifetime::end();
}
TEST_F(PrologLifetimeTest, MultipleInitialization) {
PrologLifetime::begin(glob_argc, glob_argv);
ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
PrologLifetime::end();
ASSERT_FALSE(PL_is_initialised(&glob_argc, &glob_argv));
PrologLifetime::begin(glob_argc, glob_argv);
ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
PrologLifetime::end();
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
glob_argc = argc;
glob_argv = argv;
return RUN_ALL_TESTS();
}
|
Update read method for readability | #include"ics3/eepparam.hpp"
#include<stdexcept>
constexpr int byteSize {4};
constexpr uint16_t mask {0xF};
void ics::EepParam::write(std::array<uint8_t, 64>& dest) const noexcept {
uint16_t nowData {data};
for (size_t i {offset + length - 1}; i >= offset; --i) {
dest[i] = nowData & mask;
nowData >>= byteSize;
}
}
void ics::EepParam::read(const std::array<uint8_t, 64>& src) {
uint16_t result {0};
for (size_t i {0}; i < length; ++i)
result |= (src[offset + length - 1 - i] & mask) << (i * byteSize);
set(result); // throw std::invalid_argument
}
| #include"ics3/eepparam.hpp"
#include<stdexcept>
constexpr int byteSize {4};
constexpr uint16_t mask {0xF};
void ics::EepParam::write(std::array<uint8_t, 64>& dest) const noexcept {
uint16_t nowData {data};
for (size_t i {offset + length - 1}; i >= offset; --i) {
dest[i] = nowData & mask;
nowData >>= byteSize;
}
}
void ics::EepParam::read(const std::array<uint8_t, 64>& src) {
uint16_t result {0};
const size_t loopend = offset + length;
for (size_t i {offset}; i < loopend; ++i) {
result <<= byteSize;
result |= src[i] & mask;
}
set(result); // throw std::invalid_argument
}
|
Remove standard namespace from source file. | #include <Headers\Native IO Board\MainStream IO\Native MainInput\IO Board.h>
using namespace std;
int main()
{
} | #include <Headers\Native IO Board\MainStream IO\Native MainInput\IO Board.h>
int main()
{
} |
Add a test for devirtualization of virtual operator calls. | // RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -o - | FileCheck %s
struct A {
virtual int operator-() = 0;
};
void f(A *a) {
// CHECK: call i32 %
-*a;
}
| // RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -o - | FileCheck %s
struct A {
virtual int operator-();
};
void f(A a, A *ap) {
// CHECK: call i32 @_ZN1AngEv(%struct.A* %a)
-a;
// CHECK: call i32 %
-*ap;
}
|
Clean up and error example | #include <stdio.h>
#include <Logging.h>
#include <ZipFile.h>
int main()
{
v::Log::Level = v::Log::LogLevel_Trace;
v::Log::Debug("Creating zip file");
{
v::ZipFile zip;
zip.Read("meow.zip");
s::StackArray<v::ZipEntry> entries;
zip.GetEntries(entries);
for (auto &entry : entries) {
v::Log::Debug("Zip entry %1: %2", FVAR(entry.GetIndex()), FVAR(entry.GetName()));
s::MemoryStream strm;
entry.Read(strm);
v::Log::Debug("Contents at %1 with size %2", FVAR(strm.strm_pubBuffer), FVAR(strm.Size()));
}
}
v::Log::Debug("Meow.zip created");
getchar();
return 0;
}
| #include <stdio.h>
#include <Logging.h>
#include <ZipFile.h>
int main()
{
v::Log::Level = v::Log::LogLevel_Trace;
v::Log::Debug("Reading zip file test.zip");
try {
v::ZipFile zip;
zip.Read("test.zip");
s::StackArray<v::ZipEntry> entries;
zip.GetEntries(entries);
for (auto &entry : entries) {
v::Log::Debug("Zip entry %1: %2", FVAR(entry.GetIndex()), FVAR(entry.GetName()));
s::MemoryStream strm;
entry.Read(strm);
v::Log::Debug("Contents at %1 with size %2", FVAR(strm.strm_pubBuffer), FVAR(strm.Size()));
}
} catch (s::Exception ex) {
v::Log::Fatal("Error: %1", FVAR(ex.Message));
}
getchar();
return 0;
}
|
Add support for halo's to TextSymbolizer(). | /* This file is part of python_mapnik (c++/python mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id$
#include <boost/python.hpp>
#include <mapnik.hpp>
using mapnik::text_symbolizer;
using mapnik::Color;
void export_text_symbolizer()
{
using namespace boost::python;
class_<text_symbolizer>("TextSymbolizer",
init<std::string const&,unsigned,Color const&>("TODO"))
;
}
| /* This file is part of python_mapnik (c++/python mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id$
#include <boost/python.hpp>
#include <mapnik.hpp>
using mapnik::text_symbolizer;
using mapnik::Color;
void export_text_symbolizer()
{
using namespace boost::python;
class_<text_symbolizer>("TextSymbolizer",
init<std::string const&,unsigned,Color const&>())
.add_property("halo_fill",make_function(
&text_symbolizer::get_halo_fill,return_value_policy<copy_const_reference>()),
&text_symbolizer::set_halo_fill)
.add_property("halo_radius",&text_symbolizer::get_halo_radius, &text_symbolizer::set_halo_radius)
;
}
|
Use public API for inserting a block in refill. | // Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
#include "allocators/page_heap.h"
#include "common.h"
#include "log.h"
#include "system-alloc.h"
namespace scalloc {
PageHeap PageHeap::page_heap_ cache_aligned;
void PageHeap::InitModule() {
DistributedQueue::InitModule();
page_heap_.page_pool_.Init(kPageHeapBackends);
}
void PageHeap::AsyncRefill() {
uintptr_t ptr = reinterpret_cast<uintptr_t>(SystemAlloc_Mmap(
kPageSize * kPageRefill, NULL));
if (UNLIKELY(ptr == 0)) {
ErrorOut("SystemAlloc failed");
}
for (size_t i = 0; i < kPageRefill; i++) {
page_pool_.Enqueue(reinterpret_cast<void*>(ptr));
ptr += kPageSize;
}
}
} // namespace scalloc
| // Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
#include "allocators/page_heap.h"
#include "common.h"
#include "log.h"
#include "system-alloc.h"
namespace scalloc {
PageHeap PageHeap::page_heap_ cache_aligned;
void PageHeap::InitModule() {
DistributedQueue::InitModule();
page_heap_.page_pool_.Init(kPageHeapBackends);
}
void PageHeap::AsyncRefill() {
uintptr_t ptr = reinterpret_cast<uintptr_t>(SystemAlloc_Mmap(
kPageSize * kPageRefill, NULL));
if (UNLIKELY(ptr == 0)) {
ErrorOut("SystemAlloc failed");
}
for (size_t i = 0; i < kPageRefill; i++) {
Put(reinterpret_cast<void*>(ptr));
ptr += kPageSize;
}
}
} // namespace scalloc
|
Fix the thread jump test case for 32-bit inferiors. A jump was going back to a function call using a source line number. However, the parameters being passed to the function were setup before the instruction we jumped to. In other words, the source line was associated with assembly after the function parameters had been setup for the function to be called. | //===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This test verifies the correct handling of program counter jumps.
int otherfn();
template<typename T>
T min(T a, T b)
{
if (a < b)
{
return a; // 1st marker
} else {
return b; // 2nd marker
}
}
int main ()
{
int i;
double j;
i = min(4, 5); // 3rd marker
j = min(7.0, 8.0); // 4th marker
return 0;
}
| //===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This test verifies the correct handling of program counter jumps.
int otherfn();
template<typename T>
T min(T a, T b)
{
if (a < b)
{
return a; // 1st marker
} else {
return b; // 2nd marker
}
}
int main ()
{
int i;
double j;
int min_i_a = 4, min_i_b = 5;
double min_j_a = 7.0, min_j_b = 8.0;
i = min(min_i_a, min_i_b); // 3rd marker
j = min(min_j_a, min_j_b); // 4th marker
return 0;
}
|
Add preprocessor-only test for submodule imports | // RUN: rm -rf %t
// RUN: %clang_cc1 -fmodule-cache-path %t -fauto-module-import -I %S/Inputs/submodules %s -verify
__import_module__ std.vector;
__import_module__ std.typetraits; // expected-error{{no submodule named 'typetraits' in module 'std'; did you mean 'type_traits'?}}
__import_module__ std.vector.compare; // expected-error{{no submodule named 'compare' in module 'std.vector'}}
| // RUN: rm -rf %t
// RUN: %clang_cc1 -Eonly -fmodule-cache-path %t -fauto-module-import -I %S/Inputs/submodules %s -verify
// RUN: %clang_cc1 -fmodule-cache-path %t -fauto-module-import -I %S/Inputs/submodules %s -verify
__import_module__ std.vector;
__import_module__ std.typetraits; // expected-error{{no submodule named 'typetraits' in module 'std'; did you mean 'type_traits'?}}
__import_module__ std.vector.compare; // expected-error{{no submodule named 'compare' in module 'std.vector'}}
|
Fix compilation on Ubuntu 16.04 | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"
/**
* @todo: Config file in ~/.config/qmldmenu/
* @todo: SHIFT(ENTER) for sudo
* @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
*/
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<Process>("Process", 1, 0, "Process");
qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
| #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"
/**
* @todo: Config file in ~/.config/qmldmenu/
* @todo: SHIFT(ENTER) for sudo
* @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
*/
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<Process>("Process", 1, 0, "Process");
qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
|
Add '-e' cmd key to reposerver which means 'immediate exterminatus'. | /** @file main.cpp
* @brief Главный файл сервера репозитория
* */
#include <QCoreApplication>
#include <QTextCodec>
#include "server.h"
int main(int argc, char *argv[])
{
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForCStrings(codec);
QCoreApplication app(argc, argv);
int port = 6666;
if (argc == 2) {
port = QString(argv[1]).toInt();
}
repoServer::QRealRepoServer repo(port);
return app.exec();
}
| /** @file main.cpp
* @brief Главный файл сервера репозитория
* */
#include <QCoreApplication>
#include <QTextCodec>
#include <QFile>
#include "server.h"
int main(int argc, char *argv[])
{
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForCStrings(codec);
QCoreApplication app(argc, argv);
int port = 6666;
while (argc > 1)
{
argc--;
if (!strcmp(argv[argc], "-e"))
{
QFile::remove("repothread_log.txt");
continue;
}
port = QString(argv[argc]).toInt();
if (port == 0)
port = 6666;
}
repoServer::QRealRepoServer repo(port);
return app.exec();
}
|
Connect the C++ classes with QML |
#include <QGuiApplication>
#include <QQuickView>
#include "sailfishapplication.h"
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv));
QScopedPointer<QQuickView> view(Sailfish::createView("main.qml"));
Sailfish::showView(view.data());
return app->exec();
}
|
#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include "sailfishapplication.h"
#include "servercomm.h"
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv));
QScopedPointer<QQuickView> view(Sailfish::createView("main.qml"));
ServerComm sc;
view->rootContext()->setContextProperty("serverComm", &sc);
Sailfish::showView(view.data());
return app->exec();
}
|
Fix a ranlib warning about empty TOC. | //===-- llvm/CodeGen/GlobalISel/EmptyFile.cpp ------ EmptyFile ---*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// The purpose of this file is to please cmake by not creating an
/// empty library when we do not build GlobalISel.
/// \todo This file should be removed when GlobalISel is not optional anymore.
//===----------------------------------------------------------------------===//
#include "llvm/Support/Compiler.h"
// Anonymous namespace so that we do not step on anyone's toes.
namespace {
LLVM_ATTRIBUTE_UNUSED void foo(void) {
}
}
| //===-- llvm/CodeGen/GlobalISel/EmptyFile.cpp ------ EmptyFile ---*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// The purpose of this file is to please cmake by not creating an
/// empty library when we do not build GlobalISel.
/// \todo This file should be removed when GlobalISel is not optional anymore.
//===----------------------------------------------------------------------===//
#include "llvm/Support/Compiler.h"
namespace llvm {
// Export a global symbol so that ranlib does not complain
// about the TOC being empty for the global-isel library when
// we do not build global-isel.
LLVM_ATTRIBUTE_UNUSED void DummyFunctionToSilenceRanlib(void) {
}
}
|
Remove extra call to create_directories | #include "OptionsManager.h"
#include <fstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include <spotify/json.hpp>
#include "codecs/OptionsCodec.h"
#include "logging/Logging.h"
OptionsManager::OptionsManager(std::string optionsFilename)
{
loadOptions(optionsFilename);
}
void OptionsManager::loadOptions(std::string optionsFilename)
{
std::ifstream ifs(optionsFilename);
if (!ifs.good())
{
throw std::runtime_error("Could not open options file");
}
std::string str{std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>()};
try
{
mOptions = spotify::json::decode<Options>(str.c_str());
}
catch (const spotify::json::decode_exception& e)
{
logError() << "spotify::json::decode_exception encountered at "
<< e.offset()
<< ": "
<< e.what();
throw;
}
mOptions.paths.initialise(optionsFilename);
createOutputDirectory();
}
void OptionsManager::createOutputDirectory()
{
// TODO(hryniuk): move it elsewhere
boost::filesystem::path p(mOptions.paths.directory);
p.append(mOptions.outputDirectory);
boost::filesystem::create_directories(p);
auto relativeOutputDirectory = p.string();
mOptions.relativeOutputDirectory = relativeOutputDirectory;
}
const Options& OptionsManager::getOptions() const
{
return mOptions;
}
| #include "OptionsManager.h"
#include <fstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include <spotify/json.hpp>
#include "codecs/OptionsCodec.h"
#include "logging/Logging.h"
OptionsManager::OptionsManager(std::string optionsFilename)
{
loadOptions(optionsFilename);
}
void OptionsManager::loadOptions(std::string optionsFilename)
{
std::ifstream ifs(optionsFilename);
if (!ifs.good())
{
throw std::runtime_error("Could not open options file");
}
std::string str{std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>()};
try
{
mOptions = spotify::json::decode<Options>(str.c_str());
}
catch (const spotify::json::decode_exception& e)
{
logError() << "spotify::json::decode_exception encountered at "
<< e.offset()
<< ": "
<< e.what();
throw;
}
mOptions.paths.initialise(optionsFilename);
createOutputDirectory();
}
void OptionsManager::createOutputDirectory()
{
// TODO(hryniuk): move it elsewhere
boost::filesystem::path p(mOptions.paths.directory);
p.append(mOptions.outputDirectory);
auto relativeOutputDirectory = p.string();
mOptions.relativeOutputDirectory = relativeOutputDirectory;
}
const Options& OptionsManager::getOptions() const
{
return mOptions;
}
|
Update eegeo reference in company watermark info page. Buddy: Vimmy. | // 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 eeGeo";
std::string popupBody = "This app is open source. It's built using the eeGeo 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://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";
return Create(imageAssetName,
popupTitle,
popupBody,
webUrl);
}
}
}
}
|
Split tests to multiple test cases. | #include "catch.hpp"
#include "matrix.h"
TEST_CASE( "Test matrix", "[matrix]" ) {
matrix<int> m0;
REQUIRE( m0.rows() == 0 );
REQUIRE( m0.columns() == 0 );
matrix<int> m3_4(3,4);
REQUIRE( m3_4.rows() == 3 );
REQUIRE( m3_4.columns() == 4 );
matrix<int> m_init_2 = {};
REQUIRE( m_init_2.rows() == 0 );
REQUIRE( m_init_2.columns() == 0 );
matrix<int> m_init = {{1,2,3},{4,5,6}};
REQUIRE( m_init.rows() == 2 );
REQUIRE( m_init.columns() == 3 );
REQUIRE( m_init.at(0,0) == 1 );
REQUIRE( m_init.at(0,1) == 2 );
REQUIRE( m_init.at(0,2) == 3 );
REQUIRE( m_init.at(1,0) == 4 );
REQUIRE( m_init.at(1,1) == 5 );
REQUIRE( m_init.at(1,2) == 6 );
}
| #include "catch.hpp"
#include "matrix.h"
TEST_CASE( "Test default constructor", "[matrix][constructors]" ) {
matrix<int> m0;
REQUIRE( m0.rows() == 0 );
REQUIRE( m0.columns() == 0 );
}
TEST_CASE( "Test size constructor", "[matrix][constructors]" ) {
matrix<int> m3_4(3,4);
REQUIRE( m3_4.rows() == 3 );
REQUIRE( m3_4.columns() == 4 );
matrix<int> m0_0(0,0);
REQUIRE( m0_0.rows() == 0 );
REQUIRE( m0_0.columns() == 0 );
}
TEST_CASE( "Test initializer list constructor", "[matrix][constructors]" ) {
matrix<int> m_init = {{1,2,3},{4,5,6}};
REQUIRE( m_init.rows() == 2 );
REQUIRE( m_init.columns() == 3 );
REQUIRE( m_init.at(0,0) == 1 );
REQUIRE( m_init.at(0,1) == 2 );
REQUIRE( m_init.at(0,2) == 3 );
REQUIRE( m_init.at(1,0) == 4 );
REQUIRE( m_init.at(1,1) == 5 );
REQUIRE( m_init.at(1,2) == 6 );
matrix<int> m_init_2 = {};
REQUIRE( m_init_2.rows() == 0 );
REQUIRE( m_init_2.columns() == 0 );
}
|
Add target triple to test. | // RUN: %clang_cc1 -fsyntax-only -verify %s
#define NODEREF __attribute__((noderef))
void Func() {
int NODEREF i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
int NODEREF *i_ptr;
// There should be no difference whether a macro defined type is used or not.
auto __attribute__((noderef)) *auto_i_ptr = i_ptr;
auto __attribute__((noderef)) auto_i = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
auto NODEREF *auto_i_ptr2 = i_ptr;
auto NODEREF auto_i2 = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
}
// Added test for fix for P41835
#define _LIBCPP_FLOAT_ABI __attribute__((pcs("aapcs")))
struct A {
_LIBCPP_FLOAT_ABI int operator()() throw(); // expected-warning{{'pcs' calling convention ignored for this target}}
};
| // RUN: %clang_cc1 -fsyntax-only -verify -triple x86_64-linux-gnu %s
#define NODEREF __attribute__((noderef))
void Func() {
int NODEREF i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
int NODEREF *i_ptr;
// There should be no difference whether a macro defined type is used or not.
auto __attribute__((noderef)) *auto_i_ptr = i_ptr;
auto __attribute__((noderef)) auto_i = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
auto NODEREF *auto_i_ptr2 = i_ptr;
auto NODEREF auto_i2 = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
}
// Added test for fix for P41835
#define _LIBCPP_FLOAT_ABI __attribute__((pcs("aapcs")))
struct A {
_LIBCPP_FLOAT_ABI int operator()() throw(); // expected-warning{{'pcs' calling convention ignored for this target}}
};
|
Use a magic number with the LCP array as well | /**
* \file register_loader_saver_lcp.cpp
* Defines IO for a GCSA LCPArray from stream files.
*/
#include <vg/io/registry.hpp>
#include <gcsa/gcsa.h>
#include <gcsa/algorithms.h>
namespace vg {
namespace io {
using namespace std;
using namespace vg::io;
void register_loader_saver_lcp() {
Registry::register_bare_loader_saver<gcsa::LCPArray>("LCP", [](istream& input) -> void* {
// Allocate an LCPArray
gcsa::LCPArray* index = new gcsa::LCPArray();
// Load it
index->load(input);
// Return it so the caller owns it.
return (void*) index;
}, [](const void* index_void, ostream& output) {
// Cast to LCP and serialize to the stream.
((const gcsa::LCPArray*) index_void)->serialize(output);
});
}
}
}
| /**
* \file register_loader_saver_lcp.cpp
* Defines IO for a GCSA LCPArray from stream files.
*/
#include <vg/io/registry.hpp>
#include <gcsa/gcsa.h>
#include <gcsa/algorithms.h>
namespace vg {
namespace io {
using namespace std;
using namespace vg::io;
void register_loader_saver_lcp() {
std::uint32_t magic_number = gcsa::LCPHeader::TAG;
std::string magic_string(reinterpret_cast<char*>(&magic_number), sizeof(magic_number));
Registry::register_bare_loader_saver_with_magic<gcsa::LCPArray>("LCP", magic_string, [](istream& input) -> void* {
// Allocate an LCPArray
gcsa::LCPArray* index = new gcsa::LCPArray();
// Load it
index->load(input);
// Return it so the caller owns it.
return (void*) index;
}, [](const void* index_void, ostream& output) {
// Cast to LCP and serialize to the stream.
((const gcsa::LCPArray*) index_void)->serialize(output);
});
}
}
}
|
Fix comment - ice transport is cleared on the networking thread. | /*
* Copyright 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "pc/ice_transport.h"
#include <memory>
#include <utility>
namespace webrtc {
IceTransportWithPointer::~IceTransportWithPointer() {
// We depend on the signaling thread to call Clear() before dropping
// its last reference to this object; if the destructor is called
// on the signaling thread, it's OK to not have called Clear().
if (internal_) {
RTC_DCHECK_RUN_ON(creator_thread_);
}
}
cricket::IceTransportInternal* IceTransportWithPointer::internal() {
RTC_DCHECK_RUN_ON(creator_thread_);
return internal_;
}
void IceTransportWithPointer::Clear() {
RTC_DCHECK_RUN_ON(creator_thread_);
internal_ = nullptr;
}
} // namespace webrtc
| /*
* Copyright 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "pc/ice_transport.h"
#include <memory>
#include <utility>
namespace webrtc {
IceTransportWithPointer::~IceTransportWithPointer() {
// We depend on the networking thread to call Clear() before dropping
// its last reference to this object; if the destructor is called
// on the networking thread, it's OK to not have called Clear().
if (internal_) {
RTC_DCHECK_RUN_ON(creator_thread_);
}
}
cricket::IceTransportInternal* IceTransportWithPointer::internal() {
RTC_DCHECK_RUN_ON(creator_thread_);
return internal_;
}
void IceTransportWithPointer::Clear() {
RTC_DCHECK_RUN_ON(creator_thread_);
internal_ = nullptr;
}
} // namespace webrtc
|
Hide console window when creating a new window using simple API |
#include "junior-simple.h"
#include <vector>
namespace junior
{
std::vector<window> windows;
window& create_window(const wchar_t* title)
{
windows.push_back(window(title));
return windows.back();
}
inline window& main_window()
{
return windows.front();
}
void draw_line(const int x1, const int y1, const int x2, const int y2)
{
main_window().draw_line(x1, y1, x2, y2);
}
void draw_circle(const int x, const int y, const int radius)
{
main_window().draw_circle(x, y, radius);
}
void write(const wchar_t* text, const int x, const int y)
{
main_window().write(text, x, y);
}
}
|
#include "junior-simple.h"
#include <vector>
#include <Windows.h>
namespace junior
{
std::vector<window> windows;
window& create_window(const wchar_t* title)
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
windows.push_back(window(title));
return windows.back();
}
inline window& main_window()
{
return windows.front();
}
void draw_line(const int x1, const int y1, const int x2, const int y2)
{
main_window().draw_line(x1, y1, x2, y2);
}
void draw_circle(const int x, const int y, const int radius)
{
main_window().draw_circle(x, y, radius);
}
void write(const wchar_t* text, const int x, const int y)
{
main_window().write(text, x, y);
}
}
|
Add 'break' in switch-case statement | // This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Actions/Targeting.hpp>
#include <Rosetta/Games/Game.hpp>
namespace RosettaStone::Generic
{
bool IsValidTarget(Entity* source, Entity* target)
{
for (auto& requirement : source->card.playRequirements)
{
switch (requirement.first)
{
case +PlayReq::REQ_MINION_TARGET:
{
if (dynamic_cast<Minion*>(target) == nullptr)
{
return false;
}
}
case +PlayReq::REQ_ENEMY_TARGET:
{
if (&target->GetOwner() == &source->GetOwner())
{
return false;
}
}
case +PlayReq::REQ_TARGET_TO_PLAY:
{
if (dynamic_cast<Character*>(target) == nullptr)
{
return false;
}
}
default:
break;
}
}
return true;
}
} // namespace RosettaStone::Generic
| // This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Actions/Targeting.hpp>
#include <Rosetta/Games/Game.hpp>
namespace RosettaStone::Generic
{
bool IsValidTarget(Entity* source, Entity* target)
{
for (auto& requirement : source->card.playRequirements)
{
switch (requirement.first)
{
case +PlayReq::REQ_MINION_TARGET:
{
if (dynamic_cast<Minion*>(target) == nullptr)
{
return false;
}
break;
}
case +PlayReq::REQ_ENEMY_TARGET:
{
if (&target->GetOwner() == &source->GetOwner())
{
return false;
}
break;
}
case +PlayReq::REQ_TARGET_TO_PLAY:
{
if (dynamic_cast<Character*>(target) == nullptr)
{
return false;
}
break;
}
default:
break;
}
}
return true;
}
} // namespace RosettaStone::Generic
|
Remove Duplicates from Sorted Array | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()==0) return 0;
for(int i=0;i<nums.size()-1;i++){
int j=i+1;
while(nums[j]==nums[i] && j<nums.size()){
j++;
}
nums.erase(nums.begin()+i+1,nums.begin()+j);
}
return nums.size();
}
};
| class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()==0) return 0;
for(int i=0;i<nums.size()-1;i++){
int j=i+1;
while(nums[j]==nums[i] && j<nums.size()){
j++;
}
nums.erase(nums.begin()+i+1,nums.begin()+j);
}
return nums.size();
}
};
|
Change EScript application to support executing a string from a pipe/from stdin. | // main.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#ifdef ES_BUILD_APPLICATION
#include <cstdlib>
#include <iostream>
#include <string>
#include "../EScript/EScript.h"
using namespace EScript;
int main(int argc,char * argv[]) {
if(argc<2){
std::cout << ES_VERSION<<"\nNo filename given.\n";
return EXIT_SUCCESS;
}
EScript::init();
ERef<Runtime> rt(new Runtime());
// --- Set program parameters
declareConstant(rt->getGlobals(),"args",Array::create(argc,argv));
// --- Load and execute script
std::pair<bool,ObjRef> result = EScript::loadAndExecute(*rt.get(),argv[1]);
// --- output result
if (!result.second.isNull()) {
std::cout << "\n\n --- "<<"\nResult: " << result.second.toString()<<"\n";
}
return result.first ? EXIT_SUCCESS : EXIT_FAILURE;
}
#endif // ES_BUILD_APPLICATION
| // main.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#ifdef ES_BUILD_APPLICATION
#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>
#include "../EScript/EScript.h"
int main(int argc, char * argv[]) {
EScript::init();
EScript::ERef<EScript::Runtime> rt(new EScript::Runtime());
// --- Set program parameters
declareConstant(rt->getGlobals(), "args", EScript::Array::create(argc, argv));
// --- Load and execute script
std::pair<bool, EScript::ObjRef> result;
if(argc == 1) {
result = EScript::executeStream(*rt.get(), std::cin);
} else {
result = EScript::loadAndExecute(*rt.get(), argv[1]);
}
// --- output result
if(!result.second.isNull()) {
std::cout << "\n\n --- " << "\nResult: " << result.second.toString() << "\n";
}
return result.first ? EXIT_SUCCESS : EXIT_FAILURE;
}
#endif // ES_BUILD_APPLICATION
|
Fix style warinings in output test | #include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
void *Thread1(void *p) {
*(int*)p = 42;
return 0;
}
void *Thread2(void *p) {
*(int*)p = 44;;
return 0;
}
void *alloc() {
return malloc(99);
}
void *AllocThread(void*) {
return alloc();
}
int main() {
void *p = 0;
pthread_t t[2];
pthread_create(&t[0], 0, AllocThread, 0);
pthread_join(t[0], &p);
fprintf(stderr, "addr=%p\n", p);
pthread_create(&t[0], 0, Thread1, (char*)p + 16);
pthread_create(&t[1], 0, Thread2, (char*)p + 16);
pthread_join(t[0], 0);
pthread_join(t[1], 0);
return 0;
}
// CHECK: addr=[[ADDR:0x[0-9,a-f]+]]
// CHECK: WARNING: ThreadSanitizer: data race
//...
// CHECK: Location is heap block of size 99 at [[ADDR]] allocated by thread 1:
// CHECK: #0 alloc
// CHECK: #1 AllocThread
//...
// CHECK: Thread 1 (finished) created at:
// CHECK: #0 pthread_create
// CHECK: #1 main
| #include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
void *Thread1(void *p) {
*(int*)p = 42;
return 0;
}
void *Thread2(void *p) {
*(int*)p = 44;
return 0;
}
void *alloc() {
return malloc(99);
}
void *AllocThread(void* arg) {
return alloc();
}
int main() {
void *p = 0;
pthread_t t[2];
pthread_create(&t[0], 0, AllocThread, 0);
pthread_join(t[0], &p);
fprintf(stderr, "addr=%p\n", p);
pthread_create(&t[0], 0, Thread1, (char*)p + 16);
pthread_create(&t[1], 0, Thread2, (char*)p + 16);
pthread_join(t[0], 0);
pthread_join(t[1], 0);
return 0;
}
// CHECK: addr=[[ADDR:0x[0-9,a-f]+]]
// CHECK: WARNING: ThreadSanitizer: data race
// ...
// CHECK: Location is heap block of size 99 at [[ADDR]] allocated by thread 1:
// CHECK: #0 alloc
// CHECK: #1 AllocThread
// ...
// CHECK: Thread 1 (finished) created at:
// CHECK: #0 pthread_create
// CHECK: #1 main
|
Add missing macro check in test | /*
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
#include <botan/workfactor.h>
#endif
namespace Botan_Tests {
class PK_Workfactor_Tests : public Text_Based_Test
{
public:
PK_Workfactor_Tests() : Text_Based_Test("pubkey/workfactor.vec",
{"ParamSize", "Workfactor"})
{}
Test::Result run_one_test(const std::string& type, const VarMap& vars) override
{
const size_t param_size = get_req_sz(vars, "ParamSize");
const size_t exp_output = get_req_sz(vars, "Workfactor");
size_t output = 0;
// TODO: test McEliece strength tests also
if(type == "RSA_Strength")
output = Botan::if_work_factor(param_size);
else if(type == "DL_Exponent_Size")
output = Botan::dl_exponent_size(param_size) / 2;
Test::Result result(type + " work factor calculation");
result.test_eq("Calculated workfactor for " + std::to_string(param_size),
output, exp_output);
return result;
}
};
BOTAN_REGISTER_TEST("pk_workfactor", PK_Workfactor_Tests);
}
| /*
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
#include <botan/workfactor.h>
#endif
namespace Botan_Tests {
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
class PK_Workfactor_Tests : public Text_Based_Test
{
public:
PK_Workfactor_Tests() : Text_Based_Test("pubkey/workfactor.vec",
{"ParamSize", "Workfactor"})
{}
Test::Result run_one_test(const std::string& type, const VarMap& vars) override
{
const size_t param_size = get_req_sz(vars, "ParamSize");
const size_t exp_output = get_req_sz(vars, "Workfactor");
size_t output = 0;
// TODO: test McEliece strength tests also
if(type == "RSA_Strength")
output = Botan::if_work_factor(param_size);
else if(type == "DL_Exponent_Size")
output = Botan::dl_exponent_size(param_size) / 2;
Test::Result result(type + " work factor calculation");
result.test_eq("Calculated workfactor for " + std::to_string(param_size),
output, exp_output);
return result;
}
};
BOTAN_REGISTER_TEST("pk_workfactor", PK_Workfactor_Tests);
#endif
}
|
Use the logging functions in `utils::slurp_file()` | #include "various.hpp"
#include <fstream>
#include <iostream>
#include <memory>
std::string
utils::slurp_file(std::string const& path)
{
std::ifstream file = std::ifstream(path);
if (!file.is_open()) {
std::cerr << "Failed to open \"" << path << "\"" << std::endl;
return std::string("");
}
file.seekg(0, std::ios::end);
auto const size = file.tellg();
file.seekg(0, std::ios::beg);
std::unique_ptr<char[]> content = std::make_unique<char[]>(static_cast<size_t>(size) + 1ll);
file.read(content.get(), size);
content[static_cast<size_t>(size)] = '\0';
return std::string(content.get());
}
| #include "various.hpp"
#include "core/Log.h"
#include <fstream>
#include <iostream>
#include <memory>
std::string
utils::slurp_file(std::string const& path)
{
std::ifstream file = std::ifstream(path);
if (!file.is_open()) {
LogError("Failed to open \"%s\"", path.c_str());
return std::string("");
}
file.seekg(0, std::ios::end);
auto const size = file.tellg();
file.seekg(0, std::ios::beg);
std::unique_ptr<char[]> content = std::make_unique<char[]>(static_cast<size_t>(size) + 1ll);
file.read(content.get(), size);
content[static_cast<size_t>(size)] = '\0';
return std::string(content.get());
}
|
Fix compilation error due to bad merge. | //
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Error.cpp: Implements the gl::Error class which encapsulates an OpenGL error
// and optional error message.
#include "libGLESv2/Error.h"
#include "common/angleutils.h"
#include <cstdarg>
namespace gl
{
Error::Error(GLenum errorCode)
: mCode(errorCode),
mMessage()
{
}
Error::Error(GLenum errorCode, const std::string &msg, ...)
: mCode(errorCode),
mMessage()
{
va_list vararg;
va_start(vararg, msg);
mMessage = Format(msg, vararg);
va_end(vararg);
}
Error::Error(const Error &other)
: mCode(other.mCode),
mMessage(other.mMessage)
{
}
Error &Error::operator=(const Error &other)
{
mCode = other.mCode;
mMessage = other.mMessage;
return *this;
}
}
| //
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Error.cpp: Implements the gl::Error class which encapsulates an OpenGL error
// and optional error message.
#include "libGLESv2/Error.h"
#include "common/angleutils.h"
#include <cstdarg>
namespace gl
{
Error::Error(GLenum errorCode)
: mCode(errorCode),
mMessage()
{
}
Error::Error(GLenum errorCode, const std::string &msg, ...)
: mCode(errorCode),
mMessage()
{
va_list vararg;
va_start(vararg, msg);
mMessage = FormatString(msg, vararg);
va_end(vararg);
}
Error::Error(const Error &other)
: mCode(other.mCode),
mMessage(other.mMessage)
{
}
Error &Error::operator=(const Error &other)
{
mCode = other.mCode;
mMessage = other.mMessage;
return *this;
}
}
|
Consolidate firmware version checks into single section | #include "catch.hpp"
#include "libx6adc.h"
TEST_CASE("board present", "[get_num_devices]"){
SECTION("at least one board present"){
unsigned numDevices;
get_num_devices(&numDevices);
REQUIRE( numDevices >= 1);
}
}
TEST_CASE("board temperature is sane", "[get_logic_temperature]"){
connect_x6(0);
SECTION("reported temperature is between 20C and 70C"){
float logicTemp;
get_logic_temperature(0, &logicTemp);
REQUIRE( logicTemp > 20 );
REQUIRE( logicTemp < 70 );
}
disconnect_x6(0);
}
TEST_CASE("firmware version", "[get_firmware_version]") {
connect_x6(0);
SECTION("firmware version checks") {
uint16_t ver;
SECTION("BBN firmware is greater than 0.8"){
get_firmware_version(0, BBN_X6, &ver);
REQUIRE( ver >= 0x0008);
}
SECTION("BBN QDSP firmware is greater than 1.0"){
get_firmware_version(0, BBN_QDSP, &ver);
REQUIRE( ver >= 0x0100);
}
SECTION("BBN PG firmware is greater than 0.1"){
get_firmware_version(0, BBN_PG, &ver);
REQUIRE( ver >= 0x0001);
}
}
disconnect_x6(0);
}
| #include "catch.hpp"
#include "libx6adc.h"
TEST_CASE("board present", "[get_num_devices]"){
SECTION("at least one board present"){
unsigned numDevices;
get_num_devices(&numDevices);
REQUIRE( numDevices >= 1);
}
}
TEST_CASE("board temperature is sane", "[get_logic_temperature]"){
connect_x6(0);
SECTION("reported temperature is between 20C and 70C"){
float logicTemp;
get_logic_temperature(0, &logicTemp);
REQUIRE( logicTemp > 20 );
REQUIRE( logicTemp < 70 );
}
disconnect_x6(0);
}
TEST_CASE("firmware version", "[get_firmware_version]") {
connect_x6(0);
SECTION("firmware version checks") {
uint16_t ver;
get_firmware_version(0, BBN_X6, &ver);
REQUIRE( ver >= 0x0008);
get_firmware_version(0, BBN_QDSP, &ver);
REQUIRE( ver >= 0x0100);
get_firmware_version(0, BBN_PG, &ver);
REQUIRE( ver >= 0x0001);
}
disconnect_x6(0);
}
|
Tweak to indicate that different sizes still work. | // https://github.com/KubaO/stackoverflown/tree/master/questions/lineedit-frame-37831979
#include <QtWidgets>
#include <QtUiTools>
const char ui[] = R"EOF(
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="lineEdit"/>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>)EOF";
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QBuffer buf;
buf.setData(ui, sizeof(ui));
auto w = QUiLoader().load(&buf);
auto & layout = *static_cast<QFormLayout*>(w->layout());
QLineEdit edit;
layout.addRow("Edit here", &edit);
w->show();
return app.exec();
}
| // https://github.com/KubaO/stackoverflown/tree/master/questions/lineedit-frame-37831979
#include <QtWidgets>
#include <QtUiTools>
const char ui[] = R"EOF(
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="lineEdit"/>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>)EOF";
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QBuffer buf;
buf.setData(ui, sizeof(ui));
auto w = QUiLoader().load(&buf);
auto & layout = *static_cast<QFormLayout*>(w->layout());
QLineEdit edit;
layout.itemAt(0)->widget()->setMinimumHeight(50);
layout.addRow("Edit here", &edit);
edit.setMinimumHeight(100);
layout.activate();
w->show();
return app.exec();
}
|
Fix error in Labels::getLabels: Wrong constructor for vector. | #include "./labels.h"
#include <vector>
std::function<void()>
Labels::subscribe(std::function<void(const Label &)> subscriber)
{
int erasePosition = subscribers.size();
subscribers.push_back(subscriber);
return [this, erasePosition]()
{
subscribers.erase(subscribers.begin() + erasePosition);
};
}
void Labels::add(Label label)
{
labels[label.id] = label;
notify(label);
}
std::vector<Label> Labels::getLabels()
{
std::vector<Label> result(labels.size());
for (auto &pair : labels)
result.push_back(pair.second);
return result;
}
void Labels::updateAnchor(int id, Eigen::Vector3f anchorPosition)
{
labels[id].anchorPosition = anchorPosition;
notify(labels[id]);
}
void Labels::notify(const Label& label)
{
for (auto &subscriber : subscribers)
subscriber(label);
}
| #include "./labels.h"
#include <vector>
std::function<void()>
Labels::subscribe(std::function<void(const Label &)> subscriber)
{
int erasePosition = subscribers.size();
subscribers.push_back(subscriber);
return [this, erasePosition]()
{
subscribers.erase(subscribers.begin() + erasePosition);
};
}
void Labels::add(Label label)
{
labels[label.id] = label;
notify(label);
}
std::vector<Label> Labels::getLabels()
{
std::vector<Label> result;
for (auto &pair : labels)
result.push_back(pair.second);
return result;
}
void Labels::updateAnchor(int id, Eigen::Vector3f anchorPosition)
{
labels[id].anchorPosition = anchorPosition;
notify(labels[id]);
}
void Labels::notify(const Label& label)
{
for (auto &subscriber : subscribers)
subscriber(label);
}
|
Fix supposely failing test for FreeBSD | // Intercept the implicit 'this' argument of class member functions.
//
// RUN: %clangxx_xray -g -std=c++11 %s -o %t
// RUN: rm log-args-this-* || true
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=log-args-this-" %run %t
//
// XFAIL: freebsd || arm || aarch64 || mips
// UNSUPPORTED: powerpc64le
#include "xray/xray_interface.h"
#include <cassert>
class A {
public:
[[clang::xray_always_instrument, clang::xray_log_args(1)]] void f() {
// does nothing.
}
};
volatile uint64_t captured = 0;
void handler(int32_t, XRayEntryType, uint64_t arg1) {
captured = arg1;
}
int main() {
__xray_set_handler_arg1(handler);
A instance;
instance.f();
__xray_remove_handler_arg1();
assert(captured == (uint64_t)&instance);
}
| // Intercept the implicit 'this' argument of class member functions.
//
// RUN: %clangxx_xray -g -std=c++11 %s -o %t
// RUN: rm log-args-this-* || true
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=log-args-this-" %run %t
//
// XFAIL: FreeBSD || arm || aarch64 || mips
// UNSUPPORTED: powerpc64le
#include "xray/xray_interface.h"
#include <cassert>
class A {
public:
[[clang::xray_always_instrument, clang::xray_log_args(1)]] void f() {
// does nothing.
}
};
volatile uint64_t captured = 0;
void handler(int32_t, XRayEntryType, uint64_t arg1) {
captured = arg1;
}
int main() {
__xray_set_handler_arg1(handler);
A instance;
instance.f();
__xray_remove_handler_arg1();
assert(captured == (uint64_t)&instance);
}
|
Fix problem that caused left and right eyes to have the exact same image. | /*
* openvrupdateslavecallback.cpp
*
* Created on: Dec 18, 2015
* Author: Chris Denham
*/
#include "openvrupdateslavecallback.h"
void OpenVRUpdateSlaveCallback::updateSlave(osg::View& view, osg::View::Slave& slave)
{
if (m_cameraType == LEFT_CAMERA)
{
m_device->updatePose();
}
osg::Vec3 position = m_device->position();
osg::Quat orientation = m_device->orientation();
osg::Matrix viewOffset = (m_cameraType == LEFT_CAMERA) ? m_device->viewMatrixLeft() : m_device->viewMatrixRight();
viewOffset.preMultRotate(orientation);
viewOffset.setTrans(position);
slave._viewOffset = viewOffset;
slave.updateSlaveImplementation(view);
}
| /*
* openvrupdateslavecallback.cpp
*
* Created on: Dec 18, 2015
* Author: Chris Denham
*/
#include "openvrupdateslavecallback.h"
void OpenVRUpdateSlaveCallback::updateSlave(osg::View& view, osg::View::Slave& slave)
{
if (m_cameraType == LEFT_CAMERA)
{
m_device->updatePose();
}
osg::Vec3 position = m_device->position();
osg::Quat orientation = m_device->orientation();
osg::Matrix viewOffset = (m_cameraType == LEFT_CAMERA) ? m_device->viewMatrixLeft() : m_device->viewMatrixRight();
viewOffset.preMultRotate(orientation);
viewOffset.setTrans(viewOffset.getTrans() + position);
slave._viewOffset = viewOffset;
slave.updateSlaveImplementation(view);
}
|
Use maus instead of mouse. | /Od
/I "P:\PROJEKTE\GERTICO\Win32VC80\ACE+TAO-5.6.5"
/I "C:\FHG\GERTICO"
/I "..\..\..\..\LevelTwo\common\include"
/I "..\..\..\..\LevelCommonIEEE\include"
/I "..\..\..\..\LevelCommonIEEE\include\RTI_1516"
/I "..\..\..\..\LevelTwo\phase_III"
/D "_WIN32_"
/D "WIN32"
/D "_UT_DEBUG"
/D "_NDEBUG"
/D "_CONSOLE"
/D "_CRT_SECURE_NO_DEPRECATE"
/D "IEEE_1516"
/D "GERTICO_1516"
/D "_UNICODE"
/D "UNICODE"
/FD
/EHsc /EHsc /EHsc
/MD
/Zc:forScope-
/Fo".\Release\\"
/Fd".\Release\vc80.pdb"
/W3
/nologo
/c
/Wp64
/TP
/wd4290
/wd4267
/wd4244
/wd4311
/errorReport:prompt
| /Od
/I "P:\PROJEKTE\GERTICO\Win32VC80\ACE+TAO-5.6.5"
/I "C:\FHG\GERTICO"
/I "..\..\..\..\LevelTwo\common\include"
/I "..\..\..\..\LevelCommonIEEE\include"
/I "..\..\..\..\LevelCommonIEEE\include\RTI_1516"
/I "..\..\..\..\LevelTwo\phase_III"
/D "_WIN32_"
/D "WIN32"
/D "_UT_DEBUG"
/D "_NDEBUG"
/D "_CONSOLE"
/D "_CRT_SECURE_NO_DEPRECATE"
/D "IEEE_1516"
/D "GERTICO_1516"
/D "_UNICODE"
/D "UNICODE"
/FD
/EHsc Maus
/MD
/Zc:forScope-
/Fo".\Release\\"
/Fd".\Release\vc80.pdb"
/W3
/nologo
/c
/Wp64
/TP
/wd4290
/wd4267
/wd4244
/wd4311
/errorReport:prompt
|
Make sure the pointer in PageData::html remains valid while PageData is called. | // Copyright (c) 2008-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_publisher.h"
#include "base/utf_string_conversions.h"
namespace history {
const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";
void HistoryPublisher::PublishPageThumbnail(
const std::vector<unsigned char>& thumbnail, const GURL& url,
const base::Time& time) const {
PageData page_data = {
time,
url,
NULL,
NULL,
kThumbnailImageFormat,
&thumbnail,
};
PublishDataToIndexers(page_data);
}
void HistoryPublisher::PublishPageContent(const base::Time& time,
const GURL& url,
const std::wstring& title,
const string16& contents) const {
PageData page_data = {
time,
url,
UTF16ToWide(contents).c_str(),
title.c_str(),
NULL,
NULL,
};
PublishDataToIndexers(page_data);
}
} // namespace history
| // Copyright (c) 2008-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_publisher.h"
#include "base/utf_string_conversions.h"
namespace history {
const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";
void HistoryPublisher::PublishPageThumbnail(
const std::vector<unsigned char>& thumbnail, const GURL& url,
const base::Time& time) const {
PageData page_data = {
time,
url,
NULL,
NULL,
kThumbnailImageFormat,
&thumbnail,
};
PublishDataToIndexers(page_data);
}
void HistoryPublisher::PublishPageContent(const base::Time& time,
const GURL& url,
const std::wstring& title,
const string16& contents) const {
std::wstring wide_contents = UTF16ToWide(contents);
PageData page_data = {
time,
url,
wide_contents.c_str(),
title.c_str(),
NULL,
NULL,
};
PublishDataToIndexers(page_data);
}
} // namespace history
|
Remove recorded object from registry in desturctor. | // Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_
#define ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_
#include "browser/api/atom_api_recorded_object.h"
#include "base/compiler_specific.h"
#include "browser/api/atom_api_objects_registry.h"
#include "browser/atom_browser_context.h"
namespace atom {
namespace api {
RecordedObject::RecordedObject(v8::Handle<v8::Object> wrapper)
: ALLOW_THIS_IN_INITIALIZER_LIST(id_(
AtomBrowserContext::Get()->objects_registry()->Add(this))) {
Wrap(wrapper);
wrapper->SetAccessor(v8::String::New("id"), IDGetter);
}
RecordedObject::~RecordedObject() {
}
// static
v8::Handle<v8::Value> RecordedObject::IDGetter(v8::Local<v8::String> property,
const v8::AccessorInfo& info) {
RecordedObject* self = RecordedObject::Unwrap<RecordedObject>(info.This());
return v8::Integer::New(self->id_);
}
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_
| // Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_
#define ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_
#include "browser/api/atom_api_recorded_object.h"
#include "base/compiler_specific.h"
#include "browser/api/atom_api_objects_registry.h"
#include "browser/atom_browser_context.h"
namespace atom {
namespace api {
RecordedObject::RecordedObject(v8::Handle<v8::Object> wrapper)
: ALLOW_THIS_IN_INITIALIZER_LIST(id_(
AtomBrowserContext::Get()->objects_registry()->Add(this))) {
Wrap(wrapper);
wrapper->SetAccessor(v8::String::New("id"), IDGetter);
}
RecordedObject::~RecordedObject() {
AtomBrowserContext::Get()->objects_registry()->Remove(id());
}
// static
v8::Handle<v8::Value> RecordedObject::IDGetter(v8::Local<v8::String> property,
const v8::AccessorInfo& info) {
RecordedObject* self = RecordedObject::Unwrap<RecordedObject>(info.This());
return v8::Integer::New(self->id_);
}
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_
|
Adjust output when user enters 'ans' | #include <iostream>
#include <string>
#include <memory>
#include <Lexer.hpp>
#include <Parser.hpp>
#include <Visitors.hpp>
int main() {
std::string input_line;
double ans = 0;
std::cout << "miniMAT: It's like MATLAB, but smaller." << std::endl;
std::cout << "Copyright (C) 2014 Federico Menozzi" << std::endl;
std::cout << std::endl;
while (true) {
std::cout << ">>> ";
std::getline(std::cin, input_line);
if (input_line == "quit" || input_line == "exit")
break;
else if (input_line == "ans") {
std::cout << "ans = " << ans << std::endl;
continue;
} else if (input_line == "")
continue;
if (std::cin.eof()) {
std::cout << std::endl;
break;
}
auto reporter = std::make_shared<miniMAT::reporter::ErrorReporter>();
miniMAT::lexer::Lexer lexer(input_line, reporter);
miniMAT::parser::Parser parser(lexer, reporter);
auto ast = parser.Parse();
if (reporter->HasErrors())
reporter->ReportErrors();
else {
ans = ast->VisitEvaluate();
std::cout << "ans = " << std::endl << std::endl;
std::cout << " " << ans << std::endl << std::endl;
}
}
return 0;
}
| #include <iostream>
#include <string>
#include <memory>
#include <Lexer.hpp>
#include <Parser.hpp>
#include <Visitors.hpp>
int main() {
std::string input_line;
double ans = 0;
std::cout << "miniMAT: It's like MATLAB, but smaller." << std::endl;
std::cout << "Copyright (C) 2014 Federico Menozzi" << std::endl;
std::cout << std::endl;
while (true) {
std::cout << ">>> ";
std::getline(std::cin, input_line);
if (input_line == "quit" || input_line == "exit")
break;
else if (input_line == "ans") {
std::cout << "ans = " << std::endl << std::endl;
std::cout << " " << ans << std::endl << std::endl;
continue;
} else if (input_line == "")
continue;
if (std::cin.eof()) {
std::cout << std::endl;
break;
}
auto reporter = std::make_shared<miniMAT::reporter::ErrorReporter>();
miniMAT::lexer::Lexer lexer(input_line, reporter);
miniMAT::parser::Parser parser(lexer, reporter);
auto ast = parser.Parse();
if (reporter->HasErrors())
reporter->ReportErrors();
else {
ans = ast->VisitEvaluate();
std::cout << "ans = " << std::endl << std::endl;
std::cout << " " << ans << std::endl << std::endl;
}
}
return 0;
}
|
Add -emit-llvm-only to the regression test for PR21547. | // RUN: rm -rf %t
// RUN: %clang_cc1 -I%S/Inputs/PR21547 -verify %s
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I%S/Inputs/PR21547 -verify %s
#include "Inputs/PR21547/FirstHeader.h"
//expected-no-diagnostics
| // RUN: rm -rf %t
// RUN: %clang_cc1 -I%S/Inputs/PR21547 -verify %s
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I%S/Inputs/PR21547 -verify %s
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I%S/Inputs/PR21547 -emit-llvm-only %s
#include "Inputs/PR21547/FirstHeader.h"
//expected-no-diagnostics
|
Add some test code for decryption | // Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.
#include <iostream>
#include <fstream>
#include <libOL/File.h>
int main(int argc, const char * argv[])
{
std::ifstream ifs("/Users/toulouse/code/lol/lmao/rofl/22923174.rofl", std::ios::binary);
libol::File file = libol::File::decode(ifs);
//std::cout << file << std::endl;
return 0;
}
| // Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.
#include <iostream>
#include <fstream>
#include <libOL/File.h>
#include <libOL/Chunks.h>
int main(int argc, const char * argv[])
{
std::ifstream ifs("/Users/toulouse/code/lol/lmao/rofl/22923174.rofl", std::ios::binary);
libol::File file = libol::File::decode(ifs);
auto decryptionKey = file.payloadHeader.getDecodedEncryptionKey();
auto header0 = file.chunkHeaders[0];
std::vector<uint8_t> chunk0;
chunk0.resize(header0.chunkLength);
ifs.seekg(file.header.payloadOffset +
file.payloadHeader.chunkCount * 17 +
file.payloadHeader.keyframeCount * 17 +
header0.offset);
ifs.read(reinterpret_cast<char *>(&chunk0[0]), header0.chunkLength);
auto chunk0decrypted = libol::Chunks::decryptAndDecompress(chunk0, decryptionKey);
std::cout << "foo" << std::endl;
return 0;
}
|
Increase low default ulimit -n of 256 on Mac OS | #define CAF_TEST_NO_MAIN
#include <caf/test/unit_test_impl.hpp>
#include "vast/announce.h"
int main(int argc, char** argv)
{
vast::announce_types();
return caf::test::main(argc, argv);
}
| #define CAF_TEST_NO_MAIN
#include <caf/test/unit_test_impl.hpp>
#include "vast/announce.h"
#include "vast/config.h"
#ifdef VAST_MACOS
#include <sys/resource.h> // setrlimit
#endif
namespace {
bool adjust_resource_limits()
{
#ifdef VAST_MACOS
auto rl = ::rlimit{4096, 8192};
auto result = ::setrlimit(RLIMIT_NOFILE, &rl);
return result == 0;
#endif
return true;
}
} // namespace <anonymous>
int main(int argc, char** argv)
{
if (! adjust_resource_limits())
return 1;
vast::announce_types();
return caf::test::main(argc, argv);
}
|
Fix a test case where FileCheck is used to test code corrected by -fixit. If the code file is not run through the preproccessor to remove comments, then FileCheck will match the strings within the CHECK commands rendering the test useless. | // RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: cp %s %t
// RUN: %clang_cc1 -fixit -x c++ %t
// RUN: FileCheck -input-file=%t %s
void f(int a[10][20]) {
// CHECK: delete[] a;
delete a; // expected-warning {{'delete' applied to a pointer-to-array type}}
}
| // RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: cp %s %t
// RUN: %clang_cc1 -fixit -x c++ %t
// RUN: %clang_cc1 -E -o - %t | FileCheck %s
void f(int a[10][20]) {
// CHECK: delete[] a;
delete a; // expected-warning {{'delete' applied to a pointer-to-array type}}
}
|
Update test for llvm assembly output change. Also add a fixme that this shouldn't be relying on assembly emission. | // REQUIRES: x86-64-registered-target
// RUN: %clang -cc1 -triple x86_64-apple-darwin10 -g -fno-limit-debug-info -S %s -o %t
// RUN: FileCheck %s < %t
//CHECK: .asciz "G"
//CHECK-NEXT: .long 0
//CHECK-NEXT: Lpubtypes_end1:
class G {
public:
void foo();
};
void G::foo() {
}
| // REQUIRES: x86-64-registered-target
// RUN: %clang -cc1 -triple x86_64-apple-darwin10 -g -fno-limit-debug-info -S %s -o %t
// RUN: FileCheck %s < %t
// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: Lpubtypes_begin1:
//CHECK: .asciz "G"
//CHECK-NEXT: .long 0
//CHECK-NEXT: Lpubtypes_end1:
class G {
public:
void foo();
};
void G::foo() {
}
|
Disable process patching by default (probably wasn't a good idea to patch with all zeroes) | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <3ds.h>
#include "constants.h"
#include "patches.h"
#define log(...) fprintf(stderr, __VA_ARGS__)
int main(int argc, char** argv)
{
gfxInitDefault();
consoleInit(GFX_TOP, NULL);
GetVersionConstants();
PatchSrvAccess();
svcBackdoor(PatchProcessWrapper);
log("[0x%08X] - Patched process\n", ret);
// Main loop
while (aptMainLoop())
{
hidScanInput();
u32 kDown = hidKeysDown();
if (kDown & KEY_START)
break;
gspWaitForVBlank();
}
gfxExit();
return 0;
}
| #include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <3ds.h>
#include "constants.h"
#include "patches.h"
#define log(...) fprintf(stderr, __VA_ARGS__)
int main(int argc, char** argv)
{
gfxInitDefault();
consoleInit(GFX_TOP, NULL);
GetVersionConstants();
PatchSrvAccess();
// ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper
// svcBackdoor(PatchProcessWrapper);
// log("[0x%08X] - Patched process\n", ret);
// Main loop
while (aptMainLoop())
{
hidScanInput();
u32 kDown = hidKeysDown();
if (kDown & KEY_START)
break;
gspWaitForVBlank();
}
gfxExit();
return 0;
}
|
Add a test case for the stack overflow in rdar://12542261 | // RUN: %clang_cc1 -std=c++11 -verify %s
// rdar://12240916 stack overflow.
namespace rdar12240916 {
struct S2 {
S2(const S2&);
S2();
};
struct S { // expected-note {{not complete}}
S x; // expected-error {{incomplete type}}
S2 y;
};
S foo() {
S s;
return s;
}
struct S3; // expected-note {{forward declaration}}
struct S4 {
S3 x; // expected-error {{incomplete type}}
S2 y;
};
struct S3 {
S4 x;
S2 y;
};
S4 foo2() {
S4 s;
return s;
}
}
| // RUN: %clang_cc1 -std=c++11 -verify %s
// rdar://12240916 stack overflow.
namespace rdar12240916 {
struct S2 {
S2(const S2&);
S2();
};
struct S { // expected-note {{not complete}}
S x; // expected-error {{incomplete type}}
S2 y;
};
S foo() {
S s;
return s;
}
struct S3; // expected-note {{forward declaration}}
struct S4 {
S3 x; // expected-error {{incomplete type}}
S2 y;
};
struct S3 {
S4 x;
S2 y;
};
S4 foo2() {
S4 s;
return s;
}
}
// rdar://12542261 stack overflow.
namespace rdar12542261 {
template <class _Tp>
struct check_complete
{
static_assert(sizeof(_Tp) > 0, "Type must be complete.");
};
template<class _Rp>
class function // expected-note 2 {{candidate}}
{
public:
template<class _Fp>
function(_Fp, typename check_complete<_Fp>::type* = 0); // expected-note {{candidate}}
};
void foobar()
{
auto LeftCanvas = new Canvas(); // expected-error {{unknown type name}}
function<void()> m_OnChange = [&, LeftCanvas]() { }; // expected-error {{no viable conversion}}
}
}
|
Fix crash when player connects | /*
* Copyright (C) 2017 Incognito
*
* 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 "core.h"
#include <boost/scoped_ptr.hpp>
boost::scoped_ptr<Core> core;
Core::Core()
{
data.reset(new Data);
grid.reset(new Grid);
streamer.reset(new Streamer);
}
| /*
* Copyright (C) 2017 Incognito
*
* 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 "core.h"
#include <boost/scoped_ptr.hpp>
boost::scoped_ptr<Core> core;
Core::Core()
{
data.reset(new Data);
grid.reset(new Grid);
chunkStreamer.reset(new ChunkStreamer);
streamer.reset(new Streamer);
}
|
Update example to use private key password | //
// main.cpp
// MacGPusher
//
// Created by Nyxouf on 6/23/13.
// Copyright (c) 2013 MacGeneration. All rights reserved.
//
#include "global.hpp"
#include "MMGAPNSConnection.hpp"
#include "MMGDevice.hpp"
#include "MMGPayload.hpp"
int main(int argc, const char* argv[])
{
// Create a device object
const unsigned int badge = 1;
MMGDevice device("device-token", badge);
// Create a payload object
MMGPayload payload("Push message", device.GetBadge(), "sound.caf", "Slider LABEL");
// Create the APNS connection
MMGAPNSConnection connection(MMG_APNS_CA_PATH, MMG_APNS_CERT_PATH, MMG_APNS_PRIVATEKEY_PATH, true);
// Open the connection
if (connection.OpenConnection() != MMGConnectionError::MMGNoError)
return -1;
// Send the payload
connection.SendPayloadToDevice(payload, device);
// Close the connection
connection.CloseConnection();
return 0;
}
| //
// main.cpp
// MacGPusher
//
// Created by Nyx0uf on 6/23/13.
// Copyright (c) 2013 MacGeneration. All rights reserved.
//
#include "global.hpp"
#include "MMGAPNSConnection.hpp"
#include "MMGDevice.hpp"
#include "MMGPayload.hpp"
int main(int argc, const char* argv[])
{
// Create a device object
const unsigned int badge = 1;
MMGDevice device("device-token", badge);
// Create a payload object
MMGPayload payload("Push message", device.GetBadge(), "sound.caf", "Slider label");
// Create the APNS connection, empty string if no password for the private key
MMGAPNSConnection connection(MMG_APNS_CA_PATH, MMG_APNS_CERT_PATH, MMG_APNS_PRIVATEKEY_PATH, "private-key-password", true);
// Open the connection
if (connection.OpenConnection() != MMGConnectionError::MMGNoError)
return -1;
// Send the payload
connection.SendPayloadToDevice(payload, device);
// Close the connection
connection.CloseConnection();
return 0;
}
|
Initialize Winsock only on Windows | // Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#ifdef _WIN32
#define NOMINMAX
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#endif
#include "Network.hpp"
#include "utils/Log.hpp"
namespace ouzel
{
namespace network
{
Network::Network()
{
}
Network::~Network()
{
WSACleanup();
}
bool Network::init()
{
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;
int error = WSAStartup(sockVersion, &wsaData);
if (error != 0)
{
Log(Log::Level::ERR) << "Failed to start Winsock failed, error: " << error;
return false;
}
if (wsaData.wVersion != sockVersion)
{
Log(Log::Level::ERR) << "Incorrect Winsock version";
WSACleanup();
return false;
}
return true;
}
} // namespace network
} // namespace ouzel
| // Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#ifdef _WIN32
#define NOMINMAX
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#endif
#include "Network.hpp"
#include "utils/Log.hpp"
namespace ouzel
{
namespace network
{
Network::Network()
{
}
Network::~Network()
{
WSACleanup();
}
bool Network::init()
{
#ifdef _WIN32
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;
int error = WSAStartup(sockVersion, &wsaData);
if (error != 0)
{
Log(Log::Level::ERR) << "Failed to start Winsock failed, error: " << error;
return false;
}
if (wsaData.wVersion != sockVersion)
{
Log(Log::Level::ERR) << "Incorrect Winsock version";
WSACleanup();
return false;
}
#endif
return true;
}
} // namespace network
} // namespace ouzel
|
Add error messages for sqlite | #include "Database.h"
#include <iostream>
#include <sqlite3.h>
#include <string>
#include <vector>
using namespace std;
Database::Database(string filename) {
char filenameCharArray[100];
strcpy(filenameCharArray, filename.c_str());
sqlite3_open(filenameCharArray, &db);
}
Database::~Database() { sqlite3_close(db); }
int callback(void *res, int columns, char **data, char **) {
vector<vector<string>> &results =
*(static_cast<vector<vector<string>> *>(res));
vector<string> row;
for (int i = 0; i < columns; i++) {
row.push_back(data[i] ? data[i] : "NULL");
cout << data[i] << " ";
}
results.push_back(row);
return 0;
}
vector<vector<string>> Database::execute(string command) const {
cout << "Executing command: " << command << endl;
vector<vector<string>> results;
sqlite3_exec(db, /* An open database */
command.c_str(), /* SQL to be evaluated */
callback, /* Callback function */
&results, /* 1st argument to callback */
0 /* Error msg written here */
);
return results;
}
| #include "Database.h"
#include <iostream>
#include <sqlite3.h>
#include <string>
#include <vector>
using namespace std;
Database::Database(string filename) {
char filenameCharArray[100];
strcpy(filenameCharArray, filename.c_str());
sqlite3_open(filenameCharArray, &db);
}
Database::~Database() { sqlite3_close(db); }
int callback(void *res, int columns, char **data, char **) {
vector<vector<string>> &results =
*(static_cast<vector<vector<string>> *>(res));
vector<string> row;
for (int i = 0; i < columns; i++) {
row.push_back(data[i] ? data[i] : "NULL");
cout << data[i] << ", ";
}
results.push_back(row);
return 0;
}
vector<vector<string>> Database::execute(string command) const {
cout << "Executing SQL: " << command << endl;
cout << "Data: ";
vector<vector<string>> results;
char *err;
int status = sqlite3_exec(db, /* An open database */
command.c_str(), /* SQL to be evaluated */
callback, /* Callback function */
&results, /* 1st argument to callback */
&err /* Error msg written here */
);
cout << endl;
cout << "DB status: " << status;
if (err) {
cout << ", Error: " << err;
sqlite3_free(err);
}
cout << endl;
return results;
}
|
Change of wallpaper works on vnc | #include <QtGui>
#include "mdi_background.h"
void QMdiAreaWBackground::resizeEvent(QResizeEvent *reEvent)
{
size = reEvent->size();
resize(size);
QMdiArea::resizeEvent(reEvent);
}
void QMdiAreaWBackground::resize(QSize& size)
{
setBackground(i.scaled(size));//,Qt::KeepAspectRatio);
}
void QMdiAreaWBackground::setBackgroundPath(QString& str) {
i = QImage(str);
resize(size);
}
QMdiAreaWBackground::QMdiAreaWBackground(QString& str)
{
i = QImage(str);
}
| #include <QtGui>
#include "mdi_background.h"
void QMdiAreaWBackground::resizeEvent(QResizeEvent *reEvent)
{
size = reEvent->size();
resize(size);
QMdiArea::resizeEvent(reEvent);
}
void QMdiAreaWBackground::resize(QSize& size)
{
/* XXX Conversion of image to the ARGB32 format is placed here because of setBackroung() works on Embox correctly
* only if the image is not opaque. I've looked for the method in which Qt determines that image is opaque,
* and discovered that ARGB32 format is a workaround for this problem.
* Also it is not obviously for me why _opaque_ images is not drawn while not-opaque is drawn... -- Alexander */
setBackground((i.scaled(size)).convertToFormat(QImage::Format_ARGB32));//,Qt::KeepAspectRatio);
}
void QMdiAreaWBackground::setBackgroundPath(QString& str) {
i = QImage(str);
resize(size);
}
QMdiAreaWBackground::QMdiAreaWBackground(QString& str)
{
i = QImage(str);
}
|
Throw Win32Error in case of failure instead of just writing the log | #include <cstring>
#include <Bull/Core/Log/Log.hpp>
#include <Bull/Core/Support/Win32/Windows.hpp>
#include <Bull/Core/System/Win32/ClipboardImpl.hpp>
namespace Bull
{
namespace prv
{
void ClipboardImpl::flush()
{
if(OpenClipboard(nullptr))
{
EmptyClipboard();
}
}
void ClipboardImpl::setContent(const String& content)
{
flush();
if(!OpenClipboard(nullptr))
{
Log::getInstance()->error("Failed to open clipboard");
}
std::size_t size = (content.getSize() + 1) * sizeof(char);
HANDLE handler = GlobalAlloc(CF_UNICODETEXT, size);
if(handler)
{
std::memcpy(GlobalLock(handler), content.getBuffer(), size);
GlobalUnlock(handler);
SetClipboardData(CF_UNICODETEXT, handler);
}
CloseClipboard();
}
String ClipboardImpl::getContent()
{
String text;
HANDLE clipboard;
if(!OpenClipboard(nullptr))
{
Log::getInstance()->error("Failed to open clipboard");
return text;
}
clipboard = GetClipboardData(CF_UNICODETEXT);
if(clipboard)
{
Log::getInstance()->error("Failed to open clipboard");
CloseClipboard();
return text;
}
text = String(static_cast<const char*>(GlobalLock(clipboard)));
GlobalUnlock(clipboard);
CloseClipboard();
return text;
}
}
}
| #include <cstring>
#include <Bull/Core/Exception/Throw.hpp>
#include <Bull/Core/Support/Win32/Win32Error.hpp>
#include <Bull/Core/Support/Win32/Windows.hpp>
#include <Bull/Core/System/Win32/ClipboardImpl.hpp>
namespace Bull
{
namespace prv
{
void ClipboardImpl::flush()
{
if(OpenClipboard(nullptr))
{
EmptyClipboard();
}
}
void ClipboardImpl::setContent(const String& content)
{
flush();
if(!OpenClipboard(nullptr))
{
Throw(Win32Error, "ClipboardImpl::setContent", "Failed to open clipboard");
}
std::size_t size = (content.getSize() + 1) * sizeof(char);
HANDLE handler = GlobalAlloc(CF_UNICODETEXT, size);
if(handler)
{
std::memcpy(GlobalLock(handler), content.getBuffer(), size);
GlobalUnlock(handler);
SetClipboardData(CF_UNICODETEXT, handler);
}
CloseClipboard();
}
String ClipboardImpl::getContent()
{
String text;
HANDLE clipboard;
if(!OpenClipboard(nullptr))
{
Throw(Win32Error, "ClipboardImpl::getContent", "Failed to open clipboard");
}
clipboard = GetClipboardData(CF_UNICODETEXT);
if(clipboard)
{
Throw(Win32Error, "ClipboardImpl::getContent", "Failed to get clipboard content");
}
text = String(static_cast<const char*>(GlobalLock(clipboard)));
GlobalUnlock(clipboard);
CloseClipboard();
return text;
}
}
}
|
Modify one to use system call | //=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
typedef unsigned int uint8_t __attribute__((__mode__(__QI__)));
typedef unsigned int uint16_t __attribute__ ((__mode__ (__HI__)));
typedef unsigned int uint32_t __attribute__ ((__mode__ (__SI__)));
typedef unsigned int uint64_t __attribute__ ((__mode__ (__DI__)));
uint8_t make_color(uint8_t fg, uint8_t bg){
return fg | bg << 4;
}
uint16_t make_vga_entry(char c, uint8_t color){
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
int main(){
uint16_t* vga_buffer = reinterpret_cast<uint16_t*>(0x0B8000);
vga_buffer[10 * 80 + 40] = make_vga_entry('1', make_color(15, 0));
return 0;
} | //=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
int main(){
asm volatile("int 50");
return 1;
} |
Use fast block indices for faster test runner loading. | #define BOOST_TEST_MODULE Gridcoin Test Suite
#include <boost/test/unit_test.hpp>
#include "db.h"
#include "main.h"
#include "wallet.h"
CWallet* pwalletMain;
CClientUIInterface uiInterface;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
TestingSetup() {
fPrintToDebugger = true; // don't want to write to debug.log file
noui_connect();
bitdb.MakeMock();
LoadBlockIndex(true);
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterWallet(pwalletMain);
}
~TestingSetup()
{
delete pwalletMain;
pwalletMain = NULL;
bitdb.Flush(true);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
| #define BOOST_TEST_MODULE Gridcoin Test Suite
#include <boost/test/unit_test.hpp>
#include "db.h"
#include "main.h"
#include "wallet.h"
CWallet* pwalletMain;
CClientUIInterface uiInterface;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
TestingSetup() {
fPrintToDebugger = true; // don't want to write to debug.log file
fUseFastIndex = true; // Don't verify block hashes when loading
noui_connect();
bitdb.MakeMock();
LoadBlockIndex(true);
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterWallet(pwalletMain);
}
~TestingSetup()
{
delete pwalletMain;
pwalletMain = NULL;
bitdb.Flush(true);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
|
Change function to weak declaration | #include <Arduino.h>
//TODO(edcoyne): remove this when it is present upstream.
// Currently this is needed to use std::string on Arduino.
namespace std{
void __throw_out_of_range(const char* str) {
panic();
}
}
| #include <Arduino.h>
//TODO(edcoyne): remove this when it is present upstream.
// Currently this is needed to use std::string on Arduino.
namespace std{
void __attribute__((weak)) __throw_out_of_range(const char* str) {
panic();
}
}
|
Use sleep instead of a busy-wait while loop to retain the output. | #include <omp.h>
#include "proctor/detector.h"
#include "proctor/proctor.h"
#include "proctor/scanning_model_source.h"
using pcl::proctor::Detector;
//using pcl::proctor::ProctorMPI;
using pcl::proctor::Proctor;
using pcl::proctor::ScanningModelSource;
Detector detector;
Proctor proctor;
int main(int argc, char **argv) {
unsigned int model_seed = 2;
unsigned int test_seed = 0; //time(NULL);
if (argc >= 2) model_seed = atoi(argv[1]);
if (argc >= 3) test_seed = atoi(argv[2]);
ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db");
model_source.loadModels();
//detector.enableVisualization();
proctor.setModelSource(&model_source);
proctor.train(detector);
proctor.test(detector, test_seed);
proctor.printResults(detector);
while (true) {}
return 0;
}
| #include <omp.h>
#include "proctor/detector.h"
#include "proctor/proctor.h"
#include "proctor/scanning_model_source.h"
using pcl::proctor::Detector;
//using pcl::proctor::ProctorMPI;
using pcl::proctor::Proctor;
using pcl::proctor::ScanningModelSource;
Detector detector;
Proctor proctor;
int main(int argc, char **argv) {
unsigned int model_seed = 2;
unsigned int test_seed = 0; //time(NULL);
if (argc >= 2) model_seed = atoi(argv[1]);
if (argc >= 3) test_seed = atoi(argv[2]);
ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db");
model_source.loadModels();
//detector.enableVisualization();
proctor.setModelSource(&model_source);
proctor.train(detector);
proctor.test(detector, test_seed);
proctor.printResults(detector);
sleep(100000);
return 0;
}
|
Add conditional preprocessor for nomlib's install prefix under Windows | /******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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.
******************************************************************************/
// This file is auto-generated by CMake at build time
#include "nomlib/version.hpp"
const std::string NOMLIB_INSTALL_PREFIX = "/Users/jeff/Library/Frameworks";
const std::string NOMLIB_BUNDLE_IDENTIFIER = "org.i8degrees.nomlib";
| /******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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.
******************************************************************************/
// This file is auto-generated by CMake at build time
#include "nomlib/version.hpp"
#if defined (NOM_PLATFORM_WINDOWS)
const std::string NOMLIB_INSTALL_PREFIX = "C:/";
#endif
const std::string NOMLIB_BUNDLE_IDENTIFIER = "org.i8degrees.nomlib";
|
Add missing API from Javascript bindings Logger class. |
#include <emscripten/bind.h>
#include "libcellml/logger.h"
using namespace emscripten;
EMSCRIPTEN_BINDINGS(libcellml_logger) {
class_<libcellml::Logger>("Logger")
.function("addIssue", &libcellml::Logger::addIssue)
.function("removeAllIssues", &libcellml::Logger::removeAllIssues)
.function("error", &libcellml::Logger::error)
.function("warning", &libcellml::Logger::warning)
.function("hint", &libcellml::Logger::hint)
;
}
|
#include <emscripten/bind.h>
#include "libcellml/logger.h"
using namespace emscripten;
EMSCRIPTEN_BINDINGS(libcellml_logger) {
class_<libcellml::Logger>("Logger")
.function("addIssue", &libcellml::Logger::addIssue)
.function("removeAllIssues", &libcellml::Logger::removeAllIssues)
.function("error", &libcellml::Logger::error)
.function("warning", &libcellml::Logger::warning)
.function("hint", &libcellml::Logger::hint)
.function("issueCount", &libcellml::Logger::issueCount)
.function("errorCount", &libcellml::Logger::errorCount)
.function("warningCount", &libcellml::Logger::warningCount)
.function("hintCount", &libcellml::Logger::hintCount)
;
}
|
Disable ExtensionApiTest.Infobars on Mac, as it is flaky. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#if defined(TOOLKIT_VIEWS) || defined(OS_MACOSX)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
// TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#if defined(TOOLKIT_VIEWS)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
// Also disabled on mac. See http://crbug.com/60990.
#define MAYBE_Infobars DISABLED_Infobars
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
// TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
|
Add another guard against multiple definition | #include <gtest/gtest.h>
#ifndef NDEBUG
#define NDEBUG
#endif
#define SM_ALWAYS_ASSERT
#include <sm/assert_macros.hpp>
TEST(SmCommonTestSuite,testAssertMacrosAlwaysAssert)
{
SM_DEFINE_EXCEPTION(Exception, std::runtime_error);
EXPECT_THROW( SM_ASSERT_TRUE_DBG(Exception, false, ""), Exception);
}
| #include <gtest/gtest.h>
#ifndef NDEBUG
#define NDEBUG
#endif
#ifndef SM_ALWAYS_ASSERT
#define SM_ALWAYS_ASSERT
#endif
#include <sm/assert_macros.hpp>
TEST(SmCommonTestSuite,testAssertMacrosAlwaysAssert)
{
SM_DEFINE_EXCEPTION(Exception, std::runtime_error);
EXPECT_THROW( SM_ASSERT_TRUE_DBG(Exception, false, ""), Exception);
}
|
Set multiline on labels default | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include "NativeLabelObject.h"
#include <bb/cascades/Color>
#include <QColor>
NativeLabelObject::NativeLabelObject(TiObject* tiObject)
: NativeAbstractTextControlObject(tiObject, N_TYPE_LABEL)
{
label_ = NULL;
}
NativeLabelObject::~NativeLabelObject()
{
}
NativeLabelObject* NativeLabelObject::createLabel(TiObject* tiObject)
{
return new NativeLabelObject(tiObject);
}
NATIVE_TYPE NativeLabelObject::getObjectType() const
{
return N_TYPE_LABEL;
}
int NativeLabelObject::initialize()
{
label_ = bb::cascades::Label::create();
setTextControl(label_);
// TODO: Set label layout here
return NATIVE_ERROR_OK;
}
int NativeLabelObject::setWordWrap(TiObject* obj)
{
bool multilined;
getBoolean(obj, &multilined);
label_->setMultiline(multilined);
return NATIVE_ERROR_OK;
}
| /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include "NativeLabelObject.h"
#include <bb/cascades/Color>
#include <QColor>
NativeLabelObject::NativeLabelObject(TiObject* tiObject)
: NativeAbstractTextControlObject(tiObject, N_TYPE_LABEL)
{
label_ = NULL;
}
NativeLabelObject::~NativeLabelObject()
{
}
NativeLabelObject* NativeLabelObject::createLabel(TiObject* tiObject)
{
return new NativeLabelObject(tiObject);
}
NATIVE_TYPE NativeLabelObject::getObjectType() const
{
return N_TYPE_LABEL;
}
int NativeLabelObject::initialize()
{
label_ = bb::cascades::Label::create();
label_->setMultiline(true);
setTextControl(label_);
// TODO: Set label layout here
return NATIVE_ERROR_OK;
}
int NativeLabelObject::setWordWrap(TiObject* obj)
{
bool multilined;
getBoolean(obj, &multilined);
label_->setMultiline(multilined);
return NATIVE_ERROR_OK;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.