/**
 * \file
 * \brief isInInterruptContext() implementation for ARMv6-M and ARMv7-M
 *
 * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/architecture/isInInterruptContext.hpp"

#include "distortos/chip/CMSIS-proxy.h"

namespace distortos
{

namespace architecture
{

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

bool isInInterruptContext()
{
	return __get_IPSR() != 0;
}

}	// namespace architecture

}	// namespace distortos

Add ARMv{6,7}-M implementation of architecture::isInInterruptContext()


// 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 "webkit/support/test_webplugin_page_delegate.h"

#include "third_party/WebKit/Source/Platform/chromium/public/Platform.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"

namespace webkit_support {

webkit::npapi::WebPluginDelegate*
TestWebPluginPageDelegate::CreatePluginDelegate(
    const base::FilePath& file_path,
    const std::string& mime_type) {
  return webkit::npapi::WebPluginDelegateImpl::Create(file_path, mime_type);
}

WebKit::WebPlugin* TestWebPluginPageDelegate::CreatePluginReplacement(
    const base::FilePath& file_path) {
  return NULL;
}

WebKit::WebCookieJar* TestWebPluginPageDelegate::GetCookieJar() {
  return WebKit::Platform::current()->cookieJar();
}

}  // namespace webkit_support

// 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 "webkit/support/test_webplugin_page_delegate.h"

#include "third_party/WebKit/Source/Platform/chromium/public/Platform.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"

namespace webkit_support {

webkit::npapi::WebPluginDelegate*
TestWebPluginPageDelegate::CreatePluginDelegate(
    const base::FilePath& file_path,
    const std::string& mime_type) {
  webkit::npapi::WebPluginDelegateImpl* delegate =
      webkit::npapi::WebPluginDelegateImpl::Create(file_path, mime_type);
#if defined(OS_MACOSX) && !defined(USE_AURA)
  if (delegate)
    delegate->SetContainerVisibility(true);
#endif
  return delegate;
}

WebKit::WebPlugin* TestWebPluginPageDelegate::CreatePluginReplacement(
    const base::FilePath& file_path) {
  return NULL;
}

WebKit::WebCookieJar* TestWebPluginPageDelegate::GetCookieJar() {
  return WebKit::Platform::current()->cookieJar();
}

}  // namespace webkit_support

Fix plugin visibility in DRT

Fix plugin visibility in DRT

Ensure that SetContainerVisibility is called on WebPluginDelegateImpls when they're created in DRT, or else their cliprects will be wrong.

BUG=168900

Review URL: https://chromiumcodereview.appspot.com/12382007

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


#include<iostream>
using namespace std;
struct Node
{
	int data;
	Node* next;
	Node* prev;
};/*
   Reverse a doubly linked list, input list may also be empty
   Node is defined as
   struct Node
   {
     int data;
     Node *next;
     Node *prev
   }
*/
Node* Reverse(Node *head)
{
    if (head == NULL || head->next == NULL) {
        return head;
    }
    Node *prev = NULL;
    Node *cur = head;
    while (cur->next != NULL) {
        Node *next = cur->next;
        cur->next = prev;
        if (prev != NULL) {
            prev->prev = cur;
        }
        prev = cur;
        cur = next;
    }
    cur->prev = NULL;
    cur->next = prev;
    prev->prev = cur;
    return cur;
}
Node* Insert(Node *head, int data)
{
	Node *temp = new Node();
	temp->data = data; temp->prev = NULL; temp->next = NULL;
	if(head == NULL) return temp;
	head->prev = temp;
	temp->next = head;
	return temp;
}
void Print(Node *head) {
	if(head == NULL) return;
	while(head->next != NULL){ cout<<head->data<<" "; head = head->next;}
	cout<<head->data<<" ";
	while(head->prev != NULL) { cout<<head->data<<" "; head = head->prev; }
	cout<<head->data<<"\n";
}
int main()
{
	int t; cin>>t;
	Node *head = NULL;
	while(t--) {
	   int n; cin>>n;
           head = NULL;
	   for(int i = 0;i<n;i++) {
		   int x; cin>>x;
		   head = Insert(head,x);
	   }
	   head = Reverse(head);
	   Print(head);
	}
}

Add the solution to "Reverse a doubly linked list".


#include <cstdio>
#include <cstdlib>
#include <algorithm>

using namespace std;

struct query {
    int l, r;
    int id;
} queries[200000];

int s;

int cmp(const void* a, const void* b) {
    struct query* x = (struct query *) a;
    struct query* y = (struct query *) b;
    if ( (x->l) / s == (y->l) / s) {
        return ((x->l)/s - (y->l)/s);
    }
    return ((x->r) - (y->r))
}

int main(void) {
    int n;
    scanf("%d", &n);
    s = sqrt(n);
    int a[n];
    for (int i = 0; i < n; i++) {
        scanf("%d", a+i);
    }
    scanf("%d", &q);
    for (int i = 0; i < q; i++) {
        scanf("%d %d", &(q[i].l), &(q[i].r));
        q[i].l--;
        q[i].r--;
        q[i].id = i;
    }

    qsort(queries, q, sizeof(struct query), cmp);

    int ans[q];

    for (int i = 0; i < q; i++) {

Work on KQUERY on spoj

Work on KQUERY on spoj


#include <map>
#include <string>

#include "gtest/gtest.h"

#include "caffe/common.hpp"
#include "caffe/layer.hpp"
#include "caffe/layer_factory.hpp"

#include "caffe/test/test_caffe_main.hpp"

namespace caffe {

template <typename TypeParam>
class LayerFactoryTest : public MultiDeviceTest<TypeParam> {};

TYPED_TEST_CASE(LayerFactoryTest, TestDtypesAndDevices);

TYPED_TEST(LayerFactoryTest, TestCreateLayer) {
  typedef typename TypeParam::Dtype Dtype;
  typename LayerRegistry<Dtype>::CreatorRegistry& registry =
      LayerRegistry<Dtype>::Registry();
  shared_ptr<Layer<Dtype> > layer;
  LayerParameter layer_param;
  for (typename LayerRegistry<Dtype>::CreatorRegistry::iterator iter =
       registry.begin(); iter != registry.end(); ++iter) {
    layer_param.set_type(iter->first);
    layer.reset(LayerRegistry<Dtype>::CreateLayer(layer_param));
    EXPECT_EQ(iter->first, layer->type());
  }
}

}  // namespace caffe

Add unit test for LayerRegistry::CreateLayer


// RUN: clang-cc %s -emit-llvm -o - | FileCheck %s

struct basic_ios{~basic_ios(); };

template<typename _CharT> struct basic_istream : virtual public basic_ios {
  virtual ~basic_istream(){}
};

template<typename _CharT> struct basic_iostream : public basic_istream<_CharT>
{
  virtual ~basic_iostream(){}
};

basic_iostream<char> res;

int main() {
}

// CHECK: call void @_ZN9basic_iosD2Ev

Test for my last patch.

Test for my last patch.

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


/*
* Simple example of a certificate validation
* (C) 2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/botan.h>
#include <botan/x509cert.h>
#include <botan/x509stor.h>

#include <stdio.h>

using namespace Botan;

int main()
   {
   LibraryInitializer init;

   X509_Certificate ca_cert("ca_cert.pem");
   X509_Certificate subject_cert("http_cert.pem");

   X509_Store cert_store;

   cert_store.add_cert(ca_cert, /*trusted=*/true);

   X509_Code code = cert_store.validate_cert(subject_cert);

   if(code == VERIFIED)
      printf("Cert validated\n");
   else
      printf("Cert did not validate, code = %d\n", code);

   return 0;
   }

Add a simple cert validation example

Add a simple cert validation example


#include "config.h"

#include <stdlib.h>
#include <string.h>

#include <string>

#include "pcrepp.hh"

int main(int argc, char *argv[])
{
    pcre_context_static<30> context;
    int retval = EXIT_SUCCESS;

    {
	pcrepp nomatch("nothing-to-match");
	pcre_input pi("dummy");

	assert(!nomatch.match(context, pi));
    }

    {
	pcrepp match1("(\\w*)=(\\d+)");
	pcre_input pi("a=1  b=2");

	assert(match1.match(context, pi));
	assert((context.end() - context.begin()) == 2);
	assert(pi.get_substr(context.begin()) == "a");
	assert(pi.get_substr(context.begin() + 1) == "1");

	assert(match1.match(context, pi));
	assert((context.end() - context.begin()) == 2);
	assert(pi.get_substr(context.begin()) == "b");
	assert(pi.get_substr(context.begin() + 1) == "2");
    }

    {
	pcrepp match2("");
    }

    return retval;
}

Add a test for cprepp.

Add a test for cprepp.


// 172. Factorial Trailing Zeroes
/**
 * Given an integer n, return the number of trailing zeroes in n!.
 *
 * Note: Your solution should be in logarithmic time complexity.
 *
 * Tags: Math
 *
 * Similar Problems: (H) Number of Digit One
 */

#include "stdafx.h"

// in the factorial, there are many 2s, so it is enough just to count the number of 5
class Solution {
public:
    int trailingZeroes(int n) {
        int count = 0;
        while (n > 0)
        {
            n /= 5;
            count += n;
        }

        return count;
    }
};

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

Add Solution for Problem 172

Add Solution for Problem 172


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

#include "test_geospatial.h"

#include "gtest/gtest.h"

TEST(testPoint, GeoPoint) {
	EXPECT_EQ(testPoint(), 0);
}

TEST(testMultiPoint, GeoMultiPoint) {
	EXPECT_EQ(testMultiPoint(), 0);
}

TEST(testCircle, GeoCircle) {
	EXPECT_EQ(testCircle(), 0);
}

TEST(testConvex, GeoConvex) {
	EXPECT_EQ(testConvex(), 0);
}

TEST(testPolygon, GeoPolygon) {
	EXPECT_EQ(testPolygon(), 0);
}

TEST(testMultiCircle, GeoMultiCircle) {
	EXPECT_EQ(testMultiCircle(), 0);
}

TEST(testMultiConvex, GeoMultiConvex) {
	EXPECT_EQ(testMultiConvex(), 0);
}

TEST(testMultiPolygon, GeoMultiPolygon) {
	EXPECT_EQ(testMultiPolygon(), 0);
}

TEST(testCollection, GeoCollection) {
	EXPECT_EQ(testCollection(), 0);
}

TEST(testIntersection, GeoIntersection) {
	EXPECT_EQ(testIntersection(), 0);
}

int main(int argc, char **argv) {
	::testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}

Add set of test for geospatial

Add set of test for geospatial


#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
#include <ctime>
#include <set>
#include <utility>
#include <algorithm>
#include <map>

using namespace std;

bool isPatternMatched(string& str, string& pattern) {
  if (pattern.size() < 1) {
    return true;
  }
  vector<vector<map<char, string> > > res1(str.size(), vector<map<char, string> >()), res2(str.size(), vector<map<char, string> >());
  for (int i = 0; i < res1.size(); i++) {
    map<char, string> m;
    m[pattern[0]] = str.substr(0, i + 1);
    res1[i].push_back(m);
  }

  for (int i = 1; i < pattern.size(); i++) {
    for (int j = 0; j < str.size(); j++) {
      res2[j].clear();
      for (int k = 1; k <= j; k++) {
        string lastWord = str.substr(k, j - k + 1);
        for (map<char, string> m : res1[k - 1]) {
          if (m.find(pattern[i]) == m.end()) {
            map<char, string> m1(m.begin(), m.end());
            m1[pattern[i]] = lastWord;
            res2[j].push_back(m1);
          } else if (m[pattern[i]] == lastWord) {
            map<char, string> m1(m.begin(), m.end());
            res2[j].push_back(m1);
          }
        }
      }
    }
    swap(res1, res2);
  }
  if (res1[str.size() - 1].size() > 0) {
    for (map<char, string> m : res1[str.size() - 1]) {
      for (auto p : m) {
        cout << p.first << ":" << p.second << endl;
      }
      cout << endl;
    }
  }
  return res1[str.size() - 1].size() > 0;
}

int main(void) {
  string str = "asdasdasdasd", pattern = "AAAA";
  cout << isPatternMatched(str, pattern) << endl;
  str = "bigboyboybig";
  pattern = "ABBA";
  cout << isPatternMatched(str, pattern) << endl;
}

Check if an input string matches the pattern

"bigboyboybig" matches "ABBA"


#include <stdio.h>

typedef struct _NODE {
  int data;
  _NODE* left;
  _NODE* right;
} NODE;

NODE* newNode(int data) {
  NODE* node = new NODE();
  node->data = data;
  node->left = nullptr;
  node->right = nullptr;

  return node;
}

bool isIdentical(NODE* T, NODE* S) {
  if (T == nullptr && S == nullptr) return true;

  if (T == nullptr || S == nullptr) return false;

  if (T->data == S->data && isIdentical(T->left, S->left) &&
      isIdentical(T->right, S->right))
    return true;

  return false;
}

bool isSubtree(NODE* T, NODE* S) {
  if (S == nullptr) return true;

  if (T == nullptr) return false;

  if (isIdentical(T, S)) return true;

  return isSubtree(T->left, S) || isSubtree(T->right, S);
}

int main(int argc, char const* argv[]) {
  NODE* T = newNode(26);
  T->right = newNode(3);
  T->right->right = newNode(3);
  T->left = newNode(10);
  T->left->left = newNode(4);
  T->left->left->right = newNode(30);
  T->left->right = newNode(6);

  NODE* S = newNode(10);
  S->right = newNode(6);
  S->left = newNode(4);
  S->left->right = newNode(30);

  if (isSubtree(T, S))
    printf("Tree 2 is subtree of Tree 1");
  else
    printf("Tree 2 is not a subtree of Tree 1");
  return 0;
}

Check whether given tree is sub tree of other.


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

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

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

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

#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

namespace tensorflow {

// --------------------------------------------------------------------------
REGISTER_OP("Roll")
    .Input("input: T")
    .Input("shift: Tshift")
    .Input("axis: Taxis")
    .Output("output: T")
    .Attr("T: type")
    .Attr("Tshift: {int32,int64}")
    .Attr("Taxis: {int32,int64}")
    .SetShapeFn(shape_inference::UnchangedShape);

}  // namespace tensorflow

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

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

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

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

#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

namespace tensorflow {

// --------------------------------------------------------------------------
REGISTER_OP("Roll")
    .Input("input: T")
    .Input("shift: Tshift")
    .Input("axis: Taxis")
    .Output("output: T")
    .Attr("T: type")
    .Attr("Tshift: {int32,int64}")
    .Attr("Taxis: {int32,int64}")
    .SetShapeFn([](shape_inference::InferenceContext* c) {
      shape_inference::ShapeHandle unused;
      // The `input` must be 1-D or higher
      TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 1, &unused));

      return shape_inference::UnchangedShape(c);
    });

}  // namespace tensorflow

Improve shape function check for `tf.roll`

The `tf.roll` op has requirements for the shape of inputs. However,
the shape of the inputs are only done at the runtime inside the kernel.
This fix improve the shape function so that the check could be
done early if shape is already known in the shape function.

Signed-off-by: Yong Tang <765086fe2e0c1f980161f127fec596800f327f62@outlook.com>


#include"Game.h"

int main(int argc, char **args)
{
	Game *game = new Game();

    const char windowTitle[] = "Chapter 1: Setting up SDL";
	game->init(windowTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, false);

	while (game->isRunning()) {
		game->handleEvents();
		game->update();
		game->render();
	}

	game->clean();

    return 0;
}

Update branch chapter3 and resolve conflicts.


/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", GR_GL_GET_ERROR(gl));
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

///////////////////////////////////////////////////////////////////////////////

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", err);
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

///////////////////////////////////////////////////////////////////////////////

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

Fix gl error debug print.

Fix gl error debug print.

git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@2356 2bbb7eff-a529-9590-31e7-b0007b416f81


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#include <dpcdecl.h>
#include <dmgr.h>
#include <depp.h>

uint8_t
peek(int reg)
{
	HIF deviceHandle;
	int status;
	char deviceName[32] = "Cr2s2";
	uint8_t data;

	status = DmgrOpen(&deviceHandle, deviceName);
	if (!status) {
		printf("Problem opening device, code %d\n", DmgrGetLastError());
		return 0;
	}

	status = DeppEnable(deviceHandle);
	if (!status) {
		printf("Problem enabling port 0, code %d\n", DmgrGetLastError());
		return 0;
	}

	DeppGetReg(deviceHandle, reg, &data, fFalse);

	status = DeppDisable(deviceHandle);
	if (!status) {
		printf("Problem disabling DEPP, code %d\n", DmgrGetLastError());
		return 0;
	}
	DmgrClose(deviceHandle);

	return data;
}

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

	if (argc != 2) {
		printf("usage: %s register\n", argv[0]);
		exit(1);
	}

	reg = atoi(argv[1]);

	printf("%x\n", peek(reg));

	return 0;
}

Add ability to peek registers through USB, beautify code.


#include <sys/types.h> /* size_t, ssize_t */
#include <stdarg.h> /* va_list */
#include <stddef.h> /* NULL */
#include <stdint.h> /* int64_t */

#include "kcgi.h"

#include <iostream>

int
main(int argc, char *argv[])
{
	enum kcgi_err	  er;
	struct kreq	  r;
	const char *const pages[1] = { "index" };

	/* Set up our main HTTP context. */

	er = khttp_parse(&r, NULL, 0, pages, 1, 0);
	if (KCGI_OK != er)
		return 0;

	khttp_head(&r, kresps[KRESP_STATUS],
	  "%s", khttps[KHTTP_200]);
	khttp_head(&r, kresps[KRESP_CONTENT_TYPE],
	  "%s", kmimetypes[r.mime]);
	khttp_body(&r);
	khttp_puts(&r, "Hello, world!\n");

	std::cerr << "Said hello!";

	khttp_free(&r);
	return 0;
}

Add a sample C++ file.

Add a sample C++ file.


// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.

/**
 * @file
 * Tests for command results.
 */

#include <sstream>

#include "catch.hpp"
#include "../cmd_result.hpp"
#include "dummy_response_sink.hpp"
// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.

/**
 * @file
 * Tests for error classes.
 */

#include "catch.hpp"

#include "../errors.hpp"

SCENARIO("Errors contain a retrievable message", "[error]") {
	GIVEN("An Error") {
		Error e = NetError("need an RS-232 Interface Lead");

		WHEN("Message() is called") {
			auto s = e.Message();

			THEN("the result is the message given in the Error's ctor") {
				REQUIRE(s == "need an RS-232 Interface Lead");
			}
		}
	}
}

Add tiny test for Error::Message().

Add tiny test for Error::Message().

Should bump coverage on errors.cpp to 100%.


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

using namespace Halide;

// FIXME: We should use a proper framework for this. See issue #898
void h_assert(bool condition, const char *msg) {
    if (!condition) {
        printf("FAIL: %s\n", msg);
        abort();
    }
}

int main() {
    Halide::Func f;
    Halide::Var x, y;

    // This should throw an error because downcasting will loose precision which
    // should only happen if the user explicitly asks for it
    f(x, y) = 0.1f;

    // Use JIT for computation
    Image<float16_t> simple = f.realize(10, 3);

    // Assert some basic properties of the image
    h_assert(simple.extent(0) == 10, "invalid width");
    h_assert(simple.extent(1) == 3, "invalid height");
    h_assert(simple.min(0) == 0, "unexpected non zero min in x");
    h_assert(simple.min(1) == 0, "unexpected non zero min in y");
    h_assert(simple.channels() == 1, "invalid channels");
    h_assert(simple.dimensions() == 2, "invalid number of dimensions");

    printf("Should not be reached!\n");
    return 0;
}

Add test case to check that implicit downcasting when a Func returns float (32 bits) but the buffer has type float16_t (16 bits) is an error.


#include <iostream>

namespace
{

class Repl
{
  std::istream& in_;
  std::ostream& out_;
  std::string prompt_ = "mclisp> ";

  public:
    Repl(std::istream& in=std::cin, std::ostream& out=std::cout) : in_(in), out_(out) {};
    int loop();
};

int Repl::loop()
{
  std::string val;

  while (val != "quit")
  {
    out_ << prompt_;
    in_ >> val;
    out_ << val << std::endl;
  }
  return 0;
}

}; //end namespace

int main(int argc, const char **argv)
{
  Repl repl;
  return repl.loop();
}

Add a very dumb echo repl.

Add a very dumb echo repl.


#include <stdio.h>
#include "../include/AliHLTTPCGeometry.h" //We use this to convert from row number to X

struct ClusterData {
	int fId;
	int fRow;
	float fX;
	float fY;
	float fZ;
	float fAmp;
};

int main(int argc, char** argv)
{
	for (int iEvent = 0;iEvent < 2;iEvent++) //Multiple events go to multiple files, named event.[NUM].dump
	{
		char filename[1024];
		sprintf(filename, "event.%d.dump", iEvent);
		FILE* fp = fopen(filename, "w+b");
		int clusterId = 0; //Here we count up the cluster ids we fill (must be unique).
		for (int iSector = 0;iSector < 36;iSector++) //HLT Sector numbering, sectors go from 0 to 35, all spanning all rows from 0 to 158.
		{
			int nNumberOfHits = 100; //For every sector we first have to fill the number of hits in this sector to the file
			fwrite(&nNumberOfHits, sizeof(nNumberOfHits), 1, fp);

			ClusterData* tempBuffer = new ClusterData[nNumberOfHits]; //As example, we fill 100 clusters per sector
			for (int i = 0;i < nNumberOfHits;i++)
			{
			    tempBuffer[i].fId = clusterId++;
			    tempBuffer[i].fRow = i; //We fill one hit per TPC row
			    tempBuffer[i].fX = AliHLTTPCGeometry::Row2X(i);
			    tempBuffer[i].fY = i *iSector * 0.03f;
			    tempBuffer[i].fZ = i * (1 + iEvent) * (iSector >= 18 ? -1 : 1);
			    tempBuffer[i].fAmp = 100; //Arbitrary amplitude
			}

			fwrite(tempBuffer, sizeof(tempBuffer[0]), nNumberOfHits, fp);
			delete tempBuffer;
		}
		fclose(fp);
	}
	return(0);
}

Add example file to create event dump manually


// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Utils/TestUtils.hpp>
#include "gtest/gtest.h"

#include <hspp/Cards/Minion.hpp>
#include <hspp/Managers/GameAgent.hpp>
#include <hspp/Tasks/SimpleTasks/DamageTask.hpp>

using namespace Hearthstonepp;
using namespace SimpleTasks;
using namespace TestUtils;

TEST(DamageTask, GetTaskID)
{
    const DamageTask damage(EntityType::ENEMIES, 2);
    EXPECT_EQ(damage.GetTaskID(), +TaskID::DAMAGE);
}

TEST(DamageTask, Run)
{
    GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
    Player& player1 = agent.GetPlayer1();

    std::vector<Card> cards;
    cards.reserve(5);

    const std::string name = "test";
    for (size_t i = 0; i < 5; ++i)
    {
        const auto id = static_cast<char>(i + 0x30);
        cards.emplace_back(GenerateMinionCard(name + id, 1, 1));
        PlayMinionCard(player1, cards[i]);
    }

    DamageTask damage(EntityType::FRIENDS, 1);
    MetaData result = damage.Run(player1);

    EXPECT_EQ(result, MetaData::DAMAGE_SUCCESS);
    EXPECT_EQ(player1.GetField().size(), 0u);
}

Add unit test for DamageTask

test: Add unit test for DamageTask


#include<bits/stdc++.h>
using namespace std;

vector<int> BreadthFirstSearch(int vertex,vector<int> adjacent[],int start_vertex,int destination){
	queue<int> que;
    //bfsPath will store the path
	vector<int> bfsPath;
    //this array will take care of duplicate traversing
	bool visited[vertex];
    vector<int>::iterator it;
	que.push(start_vertex);
    bfsPath.push_back(start_vertex);
	visited[start_vertex]=true;
    int flag=0;
	while(!que.empty()){
		int tem = que.front();
		que.pop();
		for(it = adjacent[tem].begin();it<adjacent[tem].end();it++){
            if(!visited[*it]){
                bfsPath.push_back(*it);
                //if destination is found
                if(*it==destination){
                    flag=1;
                    break;
                }
                visited[*it] = true;
                que.push(*it);
            }
        }
        if(flag==1){
            break;
        }
	}
    //if we will not find the destination
    if(flag==0){
        bfsPath.clear();
    }
    return bfsPath;
}

//this fn will print the path
void printTraversal(vector<int>bfsPath){
    vector<int>::iterator it;
    for(it = bfsPath.begin();it<bfsPath.end();it++){
        cout<<*it<<endl;
    }
}

int main() {
    //number of vertex
	int vertex = 4;
	vector<int> adjacent[vertex];
	adjacent[0].push_back(1);
	adjacent[0].push_back(3);
	adjacent[1].push_back(2);
	adjacent[2].push_back(3);
    //starting vertex
	int start_vertex = 0;
    //destination
    int destination = 3;
	vector<int> bfsPath = BreadthFirstSearch(vertex,adjacent,start_vertex,destination);
    if(!bfsPath.empty()){
    printTraversal(bfsPath);
    }else{
        cout<<"path not found";
    }
    return 0;
}

Add Breadth First Search in Cpp

Add Breadth First Search in Cpp


// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10  -stack-protector 2 -emit-llvm -o - %s | FileCheck %s

// Check that function attributes are added to the OpenMP runtime functions.

template <class T>
struct S {
  T f;
  S(T a) : f(a) {}
  S() : f() {}
  operator T() { return T(); }
  ~S() {}
};

// CHECK: define internal void @.omp.copyprivate.copy_func(i8*, i8*) [[ATTR0:#[0-9]+]] {

void foo0();

int foo1() {
  char a;

#pragma omp parallel
  a = 2;
#pragma omp single copyprivate(a)
  foo0();

  return 0;
}

// CHECK: define internal void @.omp_task_privates_map.({{.*}}) [[ATTR3:#[0-9]+]] {
// CHECK: define internal i32 @.omp_task_entry.({{.*}}) [[ATTR0]] {
// CHECK: define internal i32 @.omp_task_destructor.({{.*}}) [[ATTR0]] {

int foo2() {
  S<double> s_arr[] = {1, 2};
  S<double> var(3);
#pragma omp task private(s_arr, var)
  s_arr[0] = var;
  return 0;
}

// CHECK: define internal void @.omp.reduction.reduction_func(i8*, i8*) [[ATTR0]] {

float foo3(int n, float *a, float *b) {
  int i;
  float result;

#pragma omp parallel for private(i) reduction(+:result)
  for (i=0; i < n; i++)
    result = result + (a[i] * b[i]);
  return result;
}

// CHECK: attributes [[ATTR0]] = {{{.*}} sspstrong {{.*}}}
// CHECK: attributes [[ATTR3]] = {{{.*}} sspstrong {{.*}}}

Add a test case for r251476.

Add a test case for r251476.

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


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

#include <shogun/features/streaming/StreamingDenseFeatures.h>
#include <shogun/io/CSVFile.h>
#include <shogun/io/streaming/StreamingAsciiFile.h>
#include <unistd.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(StreamingDenseFeatures, example_reading)
{
	index_t n=20;
	index_t dim=2;
	std::string tmp_name = "/tmp/StreamingDenseFeatures_reading.XXXXXX";
	char* fname = mktemp(const_cast<char*>(tmp_name.c_str()));

	SGMatrix<float64_t> data(dim,n);
	for (index_t i=0; i<dim*n; ++i)
		data.matrix[i] = sg_rand->std_normal_distrib();

	CDenseFeatures<float64_t>* orig_feats=new CDenseFeatures<float64_t>(data);
	//CCSVFile* saved_features = new CCSVFile(fname, 'w');
	CAsciiFile* saved_features = new CAsciiFile(fname, 'w');
	orig_feats->save(saved_features);
	saved_features->close();
	SG_UNREF(saved_features);

	CStreamingAsciiFile* input = new CStreamingAsciiFile(fname);
	CStreamingDenseFeatures<float64_t>* feats = new CStreamingDenseFeatures<float64_t>(input, false, 5);

	index_t i = 0;
	feats->start_parser();
	while (feats->get_next_example())
	{
		SGVector<float64_t> example = feats->get_vector();
		SGVector<float64_t> expected = orig_feats->get_feature_vector(i);

		ASSERT_EQ(dim, example.vlen);

		for (index_t j = 0; j < dim; j++)
			EXPECT_NEAR(expected.vector[j], example.vector[j], 1E-6);

		feats->release_example();
		i++;
	}
	feats->end_parser();

	SG_UNREF(orig_feats);
	SG_UNREF(feats);
}

Add basic unit test for StreamingDenseFeatures reading


//   Copyright 2016 otris software AG
//
//   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 <ews/ews.hpp>
#include <ews/ews_test_support.hpp>
#include <exception>
#include <iostream>
#include <ostream>
#include <stdlib.h>
#include <string>

int main()
{
    int res = EXIT_SUCCESS;
    ews::set_up();

    try
    {
        const auto env = ews::test::environment();
        auto service = ews::service(env.server_uri, env.domain, env.username,
                                    env.password);

        ews::distinguished_folder_id inbox = ews::standard_folder::inbox;

        auto folder_ids = service.find_folder(inbox);
        if (!folder_ids.empty())
        {
            // Get first folder
            auto folder = service.get_folder(folder_ids.front());
            auto name = folder.get_display_name();

				// Add suffix to folders display
				// or remove suffix if already exists
            auto pos = name.find("_updated");
            if (pos == std::string::npos)
            {
                name += "_updated";
            }
            else
            {
                name = name.substr(0, pos);
            }

            // Create property and update
            auto prop = ews::property(
                ews::folder_property_path::display_name, name);
            auto new_id = service.update_folder(folder.get_folder_id(), prop);
        }
    }
    catch (std::exception& exc)
    {
        std::cout << exc.what() << std::endl;
        res = EXIT_FAILURE;
    }

    ews::tear_down();
    return res;
}

Add example for UpdateFolder operation

Add example for UpdateFolder operation


/*
 * Problem: Find Merge Point of Two Lists
 * Author: Anirudha Bose <ani07nov@gmail.com>

   Find merge point of two linked lists
   Node is defined as
     struct Node
     {
         int data;
         Node* next;
     }
 */

int lengthOfList(Node* head)
{
    int l=0;
    while(head != NULL)
    {
        head = head->next;
        l++;
    }
    return l+1;
}

int FindMergeNode(Node *headA, Node *headB)
{
    int A = lengthOfList(headA), B = lengthOfList(headB);

    int c = 0;
    if(A>B)
    {
        while(c != A-B)
        {
            headA = headA->next;
            c++;
        }
    }
    else
    {
        while(c != B-A)
        {
            headB = headB->next;
            c++;
        }
    }

    while(headA != NULL && headB != NULL)
    {
        if(headA == headB)
            return headA->data;
        headA = headA->next;
        headB = headB->next;
    }
    return -1;
}

Merge point of two lists

HackerRank: Merge point of two lists


#include <cassert>
#include <gtest/gtest.h>
#include <system.h>
#include <basecpu.h>

#define TEST_CLASS BaseCPUTest

class BaseTestCPU : public BaseCPU {
public:
    BaseTestCPU(int maxTicks, const System &sys) : maxTicks(maxTicks), ticks(0), resets(0), BaseCPU(sys) { }
    void reset() { resets++; }
    void tick() {
        assert(isRunning());
        ticks++;
        if(ticks>= maxTicks) {
            stop();
        }
    }

    int ticks;
    int resets;
    int maxTicks;
};

const int TEST_TICK_COUNT = 3;

class TEST_CLASS : public testing::Test {
protected:
    TEST_CLASS() : cpu(TEST_TICK_COUNT, dummySystem) { }
    BaseTestCPU cpu;
    System dummySystem;
};

TEST_F(TEST_CLASS, TestRunLoop) {
    ASSERT_FALSE(cpu.isRunning()) << "Incorrect initial CPU running state";
    ASSERT_EQ(cpu.ticks, 0) << "Incorrect initial CPU tick count";
    ASSERT_EQ(cpu.resets, 0) << "Incorrect initial CPU reset count";
    cpu.startup();
    ASSERT_FALSE(cpu.isRunning()) << "Incorrect final CPU running state";
    ASSERT_EQ(cpu.ticks, TEST_TICK_COUNT) << "Incorrect final CPU tick count";
    ASSERT_EQ(cpu.resets, 1) << "Incorrect initial CPU reset count";
}

Create tests for base cpu

Create tests for base cpu


// 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 "content/renderer/pepper/usb_key_code_conversion.h"

#include "base/basictypes.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/events/keycodes/dom4/keycode_converter.h"

using blink::WebKeyboardEvent;

namespace content {

uint32_t UsbKeyCodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
  // Extract the scancode and extended bit from the native key event's lParam.
  int scancode = (key_event.nativeKeyCode >> 16) & 0x000000FF;
  if ((key_event.nativeKeyCode & (1 << 24)) != 0)
    scancode |= 0xe000;

  ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
  return key_converter->NativeKeycodeToUsbKeycode(scancode);
}

const char* CodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
  ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
  return key_converter->NativeKeycodeToCode(key_event.nativeKeyCode);
}

}  // namespace content

// 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 "content/renderer/pepper/usb_key_code_conversion.h"

#include "base/basictypes.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/events/keycodes/dom4/keycode_converter.h"

using blink::WebKeyboardEvent;

namespace content {

uint32_t UsbKeyCodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
  // Extract the scancode and extended bit from the native key event's lParam.
  int scancode = (key_event.nativeKeyCode >> 16) & 0x000000FF;
  if ((key_event.nativeKeyCode & (1 << 24)) != 0)
    scancode |= 0xe000;

  ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
  return key_converter->NativeKeycodeToUsbKeycode(scancode);
}

const char* CodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
  // Extract the scancode and extended bit from the native key event's lParam.
  int scancode = (key_event.nativeKeyCode >> 16) & 0x000000FF;
  if ((key_event.nativeKeyCode & (1 << 24)) != 0)
    scancode |= 0xe000;

  ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
  return key_converter->NativeKeycodeToCode(scancode);
}

}  // namespace content

Fix CodeForKeyboardEvent to properly calculate the scancode.

Current code just uses the key_event.nativeKeyCode which is copied
from the Windows' lParam. The proper scancode needs to be shifted
and masked out of the lParam (as is done for UsbKeyCodeForKeyboardEvent.

BUG=325015

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

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


// 83. Remove Duplicates from Sorted List
/**
 * Given a sorted linked list, delete all duplicates such that each element appear only once.
 *
 * For example,
 * Given 1->1->2, return 1->2.
 * Given 1->1->2->3->3, return 1->2->3.
 *
 * Tags: Linked List
 *
 * Author: Kuang Qin
 */

#include <iostream>

using namespace std;

/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
    ListNode(int x, ListNode *p) : val(x), next(p) {}
};

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode *curr = head;
        while (curr != NULL) {
            // search and delete duplicates
            while (curr->next != NULL && curr->next->val == curr->val) {
                curr->next = curr->next->next;
            }

            // move forward
            curr = curr->next;
        }

        return head;
    }
};

// recursive
class Solution_Recursive {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }

        head->next = deleteDuplicates(head->next);

        // duplicates
        if (head->val == head->next->val) {
            return head->next;
        }

        return head;
    }
};

int main() {
    ListNode node5(3), node4(2, &node5), node3(2, &node4), node2(1, &node3), node1(1, &node2);
    Solution sol;
    ListNode *newhead = sol.deleteDuplicates(&node1);
    for (ListNode *p = newhead; p != NULL; p = p->next) {
        cout << p->val << " ";
    }
    cout << endl;
    cin.get();

    return 0;
}

Add Solution for 083 Remove Duplicates from Sorted List


//
// Created by Ivan Shynkarenka on 15.02.2016.
//

#include "cppbenchmark.h"

#include "debug/stack_trace.h"

const uint64_t iterations = 1000000;

BENCHMARK("Stack trace")
{
    uint64_t crc = 0;

    for (uint64_t i = 0; i < iterations; ++i)
        crc += CppCommon::StackTrace().frames().size();

    // Update benchmark metrics
    context.metrics().AddIterations(iterations - 1);
    context.metrics().SetCustom("CRC", crc);
}

BENCHMARK_MAIN()

Add capture stack trace benchmark

Add capture stack trace benchmark


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

using namespace Halide;

int main(int argc, char **argv) {
    Param<float> val;

    Func f, g;
    Var x, y;

    f(x, y) = val + cast<uint8_t>(x);
    g(x, y) = f(x, y) + f(x - 1, y) + f(x + 1, y);

    g.split(y, y, _, 16);
    f.store_root();
    f.compute_at(g, y).memoize();

    val.set(23.0f);
    Image<uint8_t> out = g.realize(128, 128);

    for (int32_t i = 0; i < 128; i++) {
        for (int32_t j = 0; j < 128; j++) {
            assert(out(i, j) == (uint8_t)(3 * 23 + i + (i - 1) + (i + 1)));
        }
    }
}

Add error test for memoizing a Func with compute and storage at different levels.

Former-commit-id: 8ce76cf39a05a6ab234ef2ae547e0bda5fd353a3


/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * @author Igor V. Stolyarov
 * @version $Revision$
 */

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

unsigned char mulLUT[256][256];  /* Multiply Luckup table */
unsigned char divLUT[256][256];  /* Divide Luckup table   */
bool mulLUT_inited = false;
bool divLUT_inited = false;

void init_mulLUT(){
    int i, j;
    if(mulLUT_inited) return;
    for(i = 0; i < 256; i++){
        for(j = 0; j < 256; j++){
            mulLUT[i][j] = (int)(((float)i * j) / 255 + 0.5);
        }
    }
    mulLUT_inited = true;
}

void init_divLUT(){
    int i, j;
    if(divLUT_inited) return;
    memset(divLUT[0], 0, 256);
    for(i = 1; i < 256; i++){
        for(j = 0; j <= i; j++){
            divLUT[i][j] = (int)(((float)j) / i * 255 + 0.5);
        }
        for(; j < 256; j++){
            divLUT[i][j] = 0;
        }
    }
    divLUT_inited = true;
}

Patch for HARMONY-3677 "[classlib][awt] Results of running checker tool"

svn path=/harmony/; revision=532705


/**
    Очень простой вводный пример на демонстрацию исключений
*/

#include <iostream>
#include <exception>
#include <string>

struct MyError
{
    std::string msg;
};

class Test
{
public:
    ~Test()
    {
        std::cout << "Вызван деструктор\n";
    }
};

double sin_by_sharnin(double x)
{
    const size_t fakt_3 = 6,
                 fakt_5 = 120;
    Test t1, t2;

    if (x == 1.0) {
        throw MyError{"Неправильный аргумент"};
    }

    if (x == 2.0) {
        /// ради теста, выбрасываем исключение типа double
        /// не стоит так делать в рабочих программах
        throw 5.78;
    }

    if (x == 3.0) {
        /// выбрасываем базовый тип исключений для всей стандартной библиотеки
        throw std::exception{};
    }

    t2 = t1; /// демонстрация работы деструкторов, даже при выбросе исключения
    return x - (x*x*x)/fakt_3 + (x*x*x*x*x)/fakt_5;
}

void find_sins(int code)
{
    std::cout << "sin(1.57) = "
        << sin_by_sharnin(1.57) << "\n";

    std::cout << "sin(0.87) = "
        << sin_by_sharnin(0.87) << "\n";

    if (code == 1) {
        std::cout << "sin(1.0) = "
            << sin_by_sharnin(1.0) << "\n";
    } else if (code == 2) {
        std::cout << "sin(2.0) = "
            << sin_by_sharnin(2.0) << "\n";
    } else {
        std::cout << "sin(3.0) = "
            << sin_by_sharnin(3.0) << "\n";
    }
}

int main()
{
    using namespace std;

    int code;
    cout << "Введите целое число: ";
    cin >> code;

    Test t1, t2;
    t2 = t1;

    try {
        find_sins(code);
    }
    catch (const MyError& err) {
        cout << "Исключение перехвачено c сообщением: ";
        cout << err.msg << "\n";
    }
    catch (const double&) {
        cout << "Исключение типа double перехвачено\n";
    }
    catch (const std::exception& exc) {
        cout << "Исключение типа exception перехвачено\n";
        cout << exc.what() << "\n";
    }
}

Add simplest exception example from lesson


/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "Benchmark.h"
#include "SkCanvas.h"
#include "SkMatrix.h"
#include "SkPaint.h"
#include "SkString.h"

/**
 * This bench measures the rendering time of SkCanvas::drawBitmap with different anti-aliasing /
 * matrix combinations.
 */

class DrawBitmapAABench : public Benchmark {
public:
    DrawBitmapAABench(bool doAA, const SkMatrix& matrix, const char name[])
        : fMatrix(matrix)
        , fName("draw_bitmap_") {

        fPaint.setAntiAlias(doAA);
        fName.appendf("%s_%s", doAA ? "aa" : "noaa", name);
    }

protected:
    const char* onGetName() override {
        return fName.c_str();
    }

    void onPreDraw() override {
        fBitmap.allocN32Pixels(200, 200);
        fBitmap.eraseARGB(255, 0, 255, 0);
    }

    void onDraw(const int loops, SkCanvas* canvas) override {
        canvas->concat(fMatrix);
        for (int i = 0; i < loops; i++) {
            canvas->drawBitmap(fBitmap, 0, 0, &fPaint);
        }
    }

private:
    SkPaint  fPaint;
    SkMatrix fMatrix;
    SkString fName;
    SkBitmap fBitmap;

    typedef Benchmark INHERITED;
};

DEF_BENCH( return new DrawBitmapAABench(false, SkMatrix::MakeScale(1), "ident"); )

DEF_BENCH( return new DrawBitmapAABench(false, SkMatrix::MakeScale(1.17f), "scale"); )

DEF_BENCH( return new DrawBitmapAABench(false, SkMatrix::MakeTrans(17.5f, 17.5f), "translate"); )

DEF_BENCH(
    SkMatrix m;
    m.reset();
    m.preRotate(15);
    return new DrawBitmapAABench(false, m, "rotate");
)

DEF_BENCH( return new DrawBitmapAABench(true, SkMatrix::MakeScale(1), "ident"); )

DEF_BENCH( return new DrawBitmapAABench(true, SkMatrix::MakeScale(1.17f), "scale"); )

DEF_BENCH( return new DrawBitmapAABench(true, SkMatrix::MakeTrans(17.5f, 17.5f), "translate"); )

DEF_BENCH(
    SkMatrix m;
    m.reset();
    m.preRotate(15);
    return new DrawBitmapAABench(true, m, "rotate");
)

Add a bench for measuring drawBitmap anti-aliasing overhead

R=reed@google.com,mtklein@google.com

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


//===-- ubsan_init_standalone_preinit.cc
//------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
#error "UBSan is not supported on this platform!"
#endif

#include "sanitizer_common/sanitizer_internal_defs.h"
#include "ubsan_init.h"

#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used)) void (*__local_ubsan_preinit)(
    void) = __ubsan::InitAsStandalone;
#endif // SANITIZER_CAN_USE_PREINIT_ARRAY

Add file missing from r313583

[ubsan] Add file missing from r313583

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


#include <iostream>
#include <cstring>

using namespace std;

struct WordTranslation {
    char word[100], translation[100];
    WordTranslation(const char _word[] = "", const char _translation[] = "") {
        strcpy(word, _word);
        strcpy(translation, _translation);
    }
};

class Dictionary {
    int size;
    WordTranslation words[1000];

    void removeWordAt(int index) {
        size--;
        for (int i = index; i < size; i++) {
            words[i] = words[i+1];
        }
    }

public:

    Dictionary() {
        size = 0;
    }

    void addWord(WordTranslation wordTranslation) {
        words[size++] = wordTranslation;
    }

    void removeWord(const char word[]) {
        for (int i = 0; i < size; i++) {
            if (strcmp(word, words[i].word) == 0) {
                removeWordAt(i);
                break;
            }
        }
    }

    WordTranslation findWord(const char word[]) {
        for (int i = 0; i < size; i++) {
            if (strcmp(word, words[i].word) == 0) {
                return words[i];
            }
        }

        return WordTranslation(word, word);
    }

    void translate(const char text[]) {
        const char *lastWhiteSpace = text, *currentWhiteSpace = strstr(text, " ");

        while (currentWhiteSpace != NULL) {
            char word[100] = {'\0'};

            strncpy(word, lastWhiteSpace, currentWhiteSpace - lastWhiteSpace);
            cout << findWord(word).translation << " ";

            lastWhiteSpace = currentWhiteSpace + 1;
            currentWhiteSpace = strstr(lastWhiteSpace, " ");
        }
        char word[100] = {'\0'};
        strcpy(word, lastWhiteSpace);
        cout << findWord(word).translation;

        cout << endl;
    }
};

int main() {
    Dictionary dictionary;
    dictionary.addWord(WordTranslation("tazi", "this"));
    dictionary.addWord(WordTranslation("zadacha", "task"));
    dictionary.addWord(WordTranslation("e", "is"));
    dictionary.addWord(WordTranslation("trudna", "hard"));

    dictionary.translate("tazi zadacha e trudna");

    dictionary.removeWord("zadacha");

    dictionary.translate("tazi zadacha e trudna");

    return 0;
}

Add solution to the dictionary task

Add solution to the dictionary task


// The rule of zero

#include <memory>

class shallow
{
	private:
		std::shared_ptr<int> p = std::make_shared<int>(5);
};

class deep
{
	public:
		deep() = default;

		deep(deep const& other)
			: p{std::make_unique<int>(*other.p)}
		{ }

	private:
		std::unique_ptr<int> p = std::make_unique<int>(5);
};

// Use existing RAII types to encapsulate and safely manage
// dynamically allocated resources.
//
// The class `shallow` ([5-9]) manages a dynamically allocated `int`
// object. Rather than manage this object manually, we use a
// [`std::shared_ptr`](cpp/memory/shared_ptr) on [15] to take
// ownership of the object. The lifetime of this object is now
// tied to the lifetime of the `foo` object that contains it
// without having to implement any constructors or destructors. If
// a `shallow` object is copied, the copy will share ownership of
// this resource.
//
// If we want to perform a deep copy, we can instead use a
// [`std::unique_ptr`](cpp/memory/unique_ptr) and implement a
// copy constructor to copy the resource, as shown with the `deep`
// class on [11-22].

int main()
{
	shallow s1;
	shallow s2 = s1;

	deep d1;
	deep d2 = d1;
}

Add rule of zero sample

Add rule of zero sample


//===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass is an extremely simple version of the SimplifyCFG pass.  Its sole
// job is to delete LLVM basic blocks that are not reachable from the entry
// node.  To do this, it performs a simple depth first traversal of the CFG,
// then deletes any unvisited nodes.
//
// Note that this pass is really a hack.  In particular, the instruction
// selectors for various targets should just not generate code for unreachable
// blocks.  Until LLVM has a more systematic way of defining instruction
// selectors, however, we cannot really expect them to handle additional
// complexity.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/Passes.h"
#include "llvm/Function.h"
#include "llvm/Pass.h"
#include "llvm/Support/CFG.h"
#include "Support/DepthFirstIterator.h"
using namespace llvm;

namespace {
  class UnreachableBlockElim : public FunctionPass {
    virtual bool runOnFunction(Function &F);
  };
  RegisterOpt<UnreachableBlockElim>
  X("unreachableblockelim", "Remove unreachable blocks from the CFG");
}

FunctionPass *llvm::createUnreachableBlockEliminationPass() {
  return new UnreachableBlockElim();
}

bool UnreachableBlockElim::runOnFunction(Function &F) {
  std::set<BasicBlock*> Reachable;

  // Mark all reachable blocks.
  for (df_ext_iterator<Function*> I = df_ext_begin(&F, Reachable),
         E = df_ext_end(&F, Reachable); I != E; ++I)
    /* Mark all reachable blocks */;

  // Loop over all dead blocks, remembering them and deleting all instructions
  // in them.
  std::vector<BasicBlock*> DeadBlocks;
  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
    if (!Reachable.count(I)) {
      DeadBlocks.push_back(I);
      for (succ_iterator SI = succ_begin(&*I), E = succ_end(&*I); SI != E; ++SI)
        (*SI)->removePredecessor(I);
      I->dropAllReferences();
    }

  if (DeadBlocks.empty()) return false;

  // Actually remove the blocks now.
  for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i)
    F.getBasicBlockList().erase(DeadBlocks[i]);

  return true;
}

Add a trivially simple pass to delete unreachable blocks from the CFG.  This
pass is required to paper over problems in the code generator (primarily
live variables and its clients) which doesn't really have any well defined
semantics for unreachable code.

The proper solution to this problem is to have instruction selectors not
select blocks that are unreachable.  Until we have a instruction selection
framework available for use, however, we can't expect all instruction
selector writers to do this.  Until then, this pass should be used.

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


/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2015-2018 OSRE ( Open Source Render Engine ) by Kim Kulling

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------*/
#include <gtest/gtest.h>
#include <osre/Assets/AssimpWrapper.h>

namespace OSRE {
namespace UnitTest {

using namespace ::OSRE::Assets;

class AssimpWrapperTest : public ::testing::Test {
    // empty
};

TEST_F( AssimpWrapperTest, createTest ) {
    bool ok( true );
    try {
        AssimpWrapper assimpWrapper;
    } catch (...) {
        ok = false;
    }
    EXPECT_TRUE( ok );
}

}
}

Add missing file to fix the build.

Add missing file to fix the build.


// Chapter 20, Exercise 05: Define an input and an output operator (>> and <<)
// for vector.

#include "../lib_files/std_lib_facilities.h"

template<class T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
    os << "{ ";
    for (int i = 0; i<v.size(); ++i) {
        os << v[i];
        if (i+1<v.size()) os << ',';
        os << ' ';
    }
    os << '}';
    return os;
}

template<class T>
istream& operator>>(istream& is, vector<T>& v)
{
    char ch;
    is >> ch;
    if (ch!='{') error("vector must start with '{'");
    T element;
    while (true) {
        is >> ch;
        if (is && ch=='}') return is;
        else is.unget();
        is >> element;
        if (is) v.push_back(element);
        else error("invalid element");
    }
    return is;
}

int main()
try {
    vector<double> vd;
    vector<int> vi;
    vector<string> vs;
    cout << "Enter vector of doubles: ";
    cin >> vd;
    cout << "Enter vector of integers: ";
    cin >> vi;
    cout << "Enter vector of strings: ";
    cin >> vs;

    cout << vd << "\n" << vi << "\n" << vs << "\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 5

Add Chapter 20, exercise 5


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

#include "net/third_party/quiche/src/quic/core/crypto/common_cert_set.h"

#include <cstddef>

#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"

namespace quic {

namespace {

class CommonCertSetsEmpty : public CommonCertSets {
 public:
  // CommonCertSets interface.
  quiche::QuicheStringPiece GetCommonHashes() const override {
    return quiche::QuicheStringPiece();
  }

  quiche::QuicheStringPiece GetCert(uint64_t /* hash */,
                                    uint32_t /* index */) const override {
    return quiche::QuicheStringPiece();
  }

  bool MatchCert(quiche::QuicheStringPiece /* cert */,
                 quiche::QuicheStringPiece /* common_set_hashes */,
                 uint64_t* /* out_hash */,
                 uint32_t* /* out_index */) const override {
    return false;
  }

  CommonCertSetsEmpty() {}
  CommonCertSetsEmpty(const CommonCertSetsEmpty&) = delete;
  CommonCertSetsEmpty& operator=(const CommonCertSetsEmpty&) = delete;
  ~CommonCertSetsEmpty() override {}
};

}  // anonymous namespace

CommonCertSets::~CommonCertSets() {}

// static
const CommonCertSets* CommonCertSets::GetInstanceQUIC() {
  static CommonCertSetsEmpty* certs = new CommonCertSetsEmpty();
  return certs;
}

}  // namespace quic

Add flag to remove common certs

Add flag to remove common certs

The common certs contain around ~140kb of data that isn't used in some cases. The flag allows us to remove the data if not used.

Additional flag added won't affect gfe production.

PiperOrigin-RevId: 321615235
Change-Id: I31b675ab95ea7050de074d07438df47cc3e8f6a2


// Test that LargeAllocator unpoisons memory before releasing it to the OS.
// RUN: %clangxx_asan %s -o %t
// RUN: ASAN_OPTIONS=quarantine_size=1 %t

#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>

int main() {
  void *p = malloc(1024 * 1024);
  free(p);

  char *q = (char *)mmap(p, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
  assert(q);
  assert(q <= p);
  assert(q + 4096 > p);

  memset(q, 42, 4096);

  munmap(q, 4096);
  return 0;
}

[asan] Test that LargeAllocator unpoisons memory before releasing it to the OS.

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


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

// <functional>

// reference_wrapper

// Test that reference wrapper meets the requirements of TriviallyCopyable,
// CopyConstructible and CopyAssignable.

#include <functional>
#include <type_traits>

int main()
{
    typedef std::reference_wrapper<int> T;
    static_assert(std::is_copy_constructible<T>::value, "");
    static_assert(std::is_copy_assignable<T>::value, "");
    // Extension up for standardization: See N4151.
    static_assert(std::is_trivially_copyable<T>::value, "");
}

Add test for type properties of std::reference_wrapper

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


#include<iostream>
#include<cstdlib>

using namespace std;

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

		Node(){}

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

		Node *insertNode(Node *head, int d){
                        Node *np=new Node(d);
                        Node *t=head;

                        if(head==NULL)
                                return np;

                        while(t->next!=head)
                                t=t->next;

                        t->next=np;
                        np->next=head;

                        return head;
                }

		Node *deleteNode(Node *head, int pos){
			Node *t=head;

			if(pos==1){
				while(t->next!=head)
					t=t->next;
				t->next=head->next;
				Node *tm=head;
				head=head->next;
				free(tm);

				return head;
			}

			int c=1;

			while(c<pos-1){
				t=t->next;
				c++;
			}

			Node *tm=t->next;
			t->next=t->next->next;
			free(tm);

			return head;
		}

		void displayList(Node *head){
                        Node *t=head;
                        cout<<"\nElements of the list are:\n";
                        while(t->next!=head){
                                cout<<t->data<<"\n";
                                t=t->next;
                        }
                        cout<<t->data<<"\n";
                }
};

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

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

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

        cout<<"\nEnter the position where you wish to delete the element: ";
        cin>>pos;

        if(pos>n)
                cout<<"\nSorry! The position you entered is out of bounds.\n";
        else
                head=np.deleteNode(head,pos);

        np.displayList(head);
}

Add code to delete node in circular linked list


/*
	This programtests class reverse_str
*/

#include "reverse_str.h"
#include<iostream>

void test_single(char* s){

	// avoid printing nullpointer
	if(s!=nullptr)
		std::cout<<"\nString: "<<s;
	else
		std::cout<<"\nnull";

	std::cout<<"\nLength: "<<Reverse_str::get_length(s);

	Reverse_str::reverse(s);

	// avoid printing nullpointer
	if(s!=nullptr)
		std::cout<<"\nReversed: "<<s;
	else
		std::cout<<"\nnull";

	std::cout<<"\n";
}

void test_all(){

	// null pointer
	char* s1 = nullptr;
	test_single(s1);

	// length 0
	char s2[] = "";
	test_single(s2);

	// length 1
	char s3[] = "r";
	test_single(s3);

	// length 2
	char s4[] = "rk";
	test_single(s4);

	//length 3
	char s5[] = "xyz";
	test_single(s5);

	// length 10
	char s6[] = "what's up!";
	test_single(s6);

	// length 17
	char s7[] = "let's do some c++";
	test_single(s7);

	std::cout<<"\n\n";
}

int main(){

	// test all
	test_all();

	return 0;
}

Add test case for method to reverse null terminated string


// Chapter 20, Exercise 07: find the lexicographical last string in an unsorted
// vector<string>. Beware that "lexicographical" is not the same as "alphabeti-
// cal", as "Zzzz"<"aaa" (uppercase letters are lexicographically before lower-
// case letters).

#include "../lib_files/std_lib_facilities.h"

// returns an iterator to the biggest element of the argument
template<class Iterator>
Iterator biggest_element(Iterator first, Iterator last)
{
    Iterator high = first;
    while (first != last) {
        if (*first>*high) high = first;
        ++first;
    }
    return high;
}

int main()
try {
    vector<string> vs;
    string s;
    cout << "Enter a few words, Ctrl-Z to end: ";
    while (cin>>s)
        vs.push_back(s);

    vector<string>::iterator last = biggest_element(vs.begin(),vs.end());
    if (last!=vs.end())
        cout << "The lexicographically last string in the vector is \""
            << *last << "\".\n";
    else
        cout << "Something went wrong.\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 7

Add Chapter 20, exercise 7


/*
 * Website:
 *      https://github.com/wo3kie/dojo
 *
 *  Author:
 *      Lukasz Czerwinski
 *
 * Compilation:
 *      g++ --std=c++11 base64.encode.cpp -o base64.encode
 *
 *  Usage:
 *      $ ./base64.encode "Hello World"
 *      SGVsbG8gV29ybGQ
 */

#include <iostream>
#include <string>

#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>

std::string base64encode( std::string const & text )
{
    using namespace boost::archive::iterators;

    typedef base64_from_binary< transform_width< const char *, 6, 8 > >  base64_text;

    std::string encoded;

    std::copy(
        base64_text( & * text.begin() ),
        base64_text( & * text.end() ),
        std::back_inserter( encoded )
    );

    return encoded;
}

int main( int argc, char * argv[] )
{
    if( argc != 2 )
    {
        std::cerr << "Usage: " << argv[0] << " text" << std::endl;
        return 1;
    }

    std::cout << base64encode( argv[1] ) << std::endl;

    return 0;
}

Implement a program to do base64 encoding


// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: echo '[{"directory":".","command":"clang++ -c %t/test.cpp","file":"%t/test.cpp"}]' > %t/compile_commands.json
// RUN: cp "%s" "%t/test.cpp"
// RUN: remove-cstr-calls "%t" "%t/test.cpp"
// RUN: cat "%t/test.cpp" | FileCheck %s
// FIXME: implement a mode for refactoring tools that takes input from stdin
// and writes output to stdout for easier testing of tools.

namespace std {
template<typename T> class allocator {};
template<typename T> class char_traits {};
template<typename C, typename T, typename A> struct basic_string {
  basic_string();
  basic_string(const C *p, const A& a = A());
  const C *c_str() const;
};
typedef basic_string<char, std::char_traits<char>, std::allocator<char> > string;
}
namespace llvm { struct StringRef { StringRef(const char *p); }; }

void f1(const std::string &s) {
  f1(s.c_str());
  // CHECK: void f1
  // CHECK-NEXT: f1(s)
}
void f2(const llvm::StringRef r) {
  std::string s;
  f2(s.c_str());
  // CHECK: std::string s;
  // CHECK-NEXT: f2(s)
}
void f3(const llvm::StringRef &r) {
  std::string s;
  f3(s.c_str());
  // CHECK: std::string s;
  // CHECK: f3(s)
}

Copy the existing regression test for remove-cstr-calls from the tooling branch
to preserve its history. It's not yet functional.

git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@161401 91177308-0d34-0410-b5e6-96231b3b80d8


// Chapter 20, Exercise 13: modify exercise 12 to use 0 to represent the one
// past the last element (end()) instead of allocating a real Link

#include "../lib_files/std_lib_facilities.h"

template<class Elem> struct Link {
    Link(const Elem& v = Elem(), Link* p = 0, Link* s = 0)
        :prev(p), succ(s), val(v) { }
    Link* prev;
    Link* succ;
    Elem val;
};

template<class Elem> class my_list {
public:
    my_list() :first(0) { }

    class iterator;

    iterator begin() { return iterator(first); }
    iterator end() { return iterator(0); }

    iterator insert(iterator p, const Elem& v); // insert v into list before p
    iterator erase(iterator p);          // remove p from the list

    void push_back(const Elem& v);
    void push_front(const Elem& v);
    void pop_front();
    void pop_back();

    Elem& front() { return *first; }
    Elem& back();

    Link<Elem>* first;
};

template<class Elem> class my_list<Elem>::iterator {
    Link<Elem>* curr;
public:
    iterator(Link<Elem>* p) :curr(p) { }

//    Link<Elem>* get_link() { return curr; }

    iterator& operator++() { curr = curr->succ; return *this; } // forward
    iterator& operator--() { curr = curr->prev; return *this; } // backward
    Elem& operator*() { return curr->val; }    // get value (dereference)

    bool operator==(const iterator& b) const { return curr==b.curr; }
    bool operator!=(const iterator& b) const { return curr!=b.curr; }
};

template<class Elem>
void my_list<Elem>::push_front(const Elem& v)
{
    first = new Link<Elem>(v,0,first);
}

template<class Iterator>
Iterator high(Iterator first, Iterator last)
{
    Iterator high = first;
    for (Iterator p = first; p!=last; ++p)
        if (*high<*p) high = p;
    return high;
}

int main()
try {
    my_list<int> lst;
    int x;
    while (cin >> x) lst.push_front(x);
    my_list<int>::iterator p = high(lst.begin(),lst.end());
    cout << "The highest value was " << *p << "\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 13

Add Chapter 20, exercise 13


#include <iostream>
#include <vector>
#include <stdexcept>

using namespace std;
/*Ex8.2:
Write a function print() that prints a vector of ints to cout. Give it
two arguments: a string for “labeling” the output and a vector.
*/

void print(string label, vector<int> v){
    cout << label << ": " << endl;
    for (int i = 0; i < v.size(); ++i)
        cout << v[i] << " " ;
}

/*Ex8.3:
Create a vector of Fibonacci numbers and print them using the function
from exercise 2. To create the vector, write a function, fibonacci(x,y,v,n),
where integers x and y are ints, v is an empty vector<int>, and n is the number
of elements to put into v; v[0] will be x and v[1] will be y. A Fibonacci number
is one that is part of a sequence where each element is the sum of the two
previous ones. For example, starting with 1 and 2, we get 1, 2, 3, 5, 8, 13, 21,
. . . . Your fibonacci() function should make such a sequence starting with its
x and y arguments.
*/

void fibonacci(int x, int y, vector<int>& v, int n){
    if(n <= 0) {
        cout << "n can't <= 0" << endl;
        return;
    }

    if(n == 1)
        v = {x};
    else if(n == 2)
       v = {x,y};
    else{
        v.clear();
        v.push_back(x);
        v.push_back(y);
        for(int i = 2; i < n; ++i)
            v.push_back(v[i-1] + v[i-2]);
    }
    return;
}

int main(int argc, char const *argv[])
{
    char exit = 'n';
    int n;
    int firstElem;
    int secondElem;
    vector<int> vFibonacci;
    try{
        while(exit != 'y' || exit != 'Y'){
            cout << "Element of Fibonacci: n = ";
            cin >> n;

            cout << "\nfirstElem: ";
            cin >> firstElem;

            cout << "\nsecondElem: ";
            cin >> secondElem;

            fibonacci(firstElem,secondElem,vFibonacci,n);

            print("Result: ",vFibonacci);

            cout << "\nDo you what to exit? (y/n): ";
            cin >> exit;
        }
        return 0;
    }catch(runtime_error &e){
        cout << e.what() << endl;
    }catch(...){
        cout << "Exiting..." << endl;
    }

}

Add chap8, ex2 + ex3

Add chap8, ex2 + ex3


/* **********************************************************
 * Copyright (c) 2011 Google, Inc.  All rights reserved.
 * **********************************************************/

/* Dr. Memory: the memory debugger
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License, and no later version.

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

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

#include "gtest/gtest.h"

TEST(StringTests, Memmove) {
    const char input[128] = "0123456789abcdefg";  // strlen(input) = 17.
    char tmp[128];

    // Trivial: aligned copy, no overlapping.
    EXPECT_EQ(tmp, memmove(tmp, input, strlen(input) + 1));
    ASSERT_STREQ(input, tmp);

    strcpy(tmp, input);
    // Overlapping copy forwards, should skip 1 byte before going to fastpath.
    EXPECT_EQ(tmp+7, memmove(tmp+7, tmp+3, strlen(tmp) + 1 - 3));
    EXPECT_STREQ("01234563456789abcdefg", tmp);

    strcpy(tmp, input);
    // Overlapping copy forwards, different alignment.
    EXPECT_EQ(tmp+6, memmove(tmp+6, tmp+3, strlen(tmp) + 1 - 3));
    EXPECT_STREQ("0123453456789abcdefg", tmp);

    strcpy(tmp, input);
    // Overlapping copy backwards, should skip 3 bytes before going to fastpath.
    EXPECT_EQ(tmp+3, memmove(tmp+3, tmp+7, strlen(tmp) + 1 - 7));
    EXPECT_STREQ("012789abcdefg", tmp);

    strcpy(tmp, input);
    // Overlapping copy backwards, different alignment.
    EXPECT_EQ(tmp+3, memmove(tmp+3, tmp+6, strlen(tmp) + 1 - 6));
    EXPECT_STREQ("0126789abcdefg", tmp);
}

Add memmove tests to app_suite

Add memmove tests to app_suite

SVN-Revision: 349


/*
	This program tests merge sort
*/

#include<iostream>
#include<vector>
#include "mergesort.h"	// My implementation of merge sort

// Displays vector

void printVector(std::vector<int> A){
	for(auto x: A){
		std::cout<<x<<" ";

	}
	std::cout<<std::endl;
}

// Tests merge sort on vector A

void testMergeSort(std::vector<int> A){

	std::cout<<"Before: ";
	printVector(A);
	Mergesort::mergesort(A);
	std::cout<<"After: ";
	printVector(A);
}

// tests merge sort on several different inputs

void testMergeSort(){

	std::vector<int> v1 = {10,9,8,7,6,5,4,3,2,1};
	testMergeSort(v1);

	std::vector<int> v2 = {5,4,3,2,1};
	testMergeSort(v2);

	std::vector<int> v3 = {1,2,3,4,5,6,7,8,9,10};
	testMergeSort(v3);

	std::vector<int> v4 = {6,5,4,7,8,9,9,5,4,9,2,0,3,1,5,9,8,7,4,5,6,3};
	testMergeSort(v4);

	// test on empty vector
	std::vector<int> v5;
	testMergeSort(v5);

	std::vector<int> v6 = {2,4,-6,1,-9,3,0};
	testMergeSort(v6);

	std::vector<int> v7 = {1,2,3,4,5,6,7,8,9,0};
	testMergeSort(v7);
}

int main(){

	// test merge sort
	testMergeSort();

	return 0;
}

Add test program for mergesort

Add test program for mergesort


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()<3) return nums.size();
        int f=0,r=1;
        while(r<nums.size()){
            if(nums[f]==nums[r]){
                if(r-f>1) nums.erase(nums.begin()+r,nums.begin()+r+1);
                else r++;
            }else{
                f=r;
                r++;
            }
        }
        return nums.size();
    }
};

Remove Duplicates from Sorted Array II

Remove Duplicates from Sorted Array II


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    // Declare a variable named 'input_string' to hold our input.
    string input_string;

    // Read a full line of input from stdin (cin) and save it to our variable, input_string.
    getline(cin, input_string);

    // Print a string literal saying "Hello, World." to stdout using cout.
    cout << "Hello, World." << endl;
    cout << input_string << endl;

    // TODO: Write a line of code here that prints the contents of input_string to stdout.

    return 0;
}

Add c++ solution to the hello World problem


#include <boost/test/unit_test.hpp>
#include <ygo/deck/c/Format.h>
#include <ygo/deck/c/DB.h>

struct Format_Fixture
{
    Format_Fixture()
    {
        DB_NAME(set_path)("test/card.db");
    }
};

BOOST_FIXTURE_TEST_SUITE(Format, Format_Fixture)

BOOST_AUTO_TEST_CASE(Create)
{
    int count;
    auto formatDates = FORMAT_NAME(formatDates)(&count);
    for (auto i = 0; i < count; i++) {
        auto formatA = FORMAT_NAME(new)(ygo_data_Format_ADVANCED,
                formatDates[i]);
        auto formatDateA = FORMAT_NAME(formatDate)(formatA);
        auto formatFA = FORMAT_NAME(format)(formatA);
        BOOST_CHECK_EQUAL(std::string(formatDateA), formatDates[i]);
        BOOST_CHECK(formatFA == ygo_data_Format_ADVANCED);
        FORMAT_NAME(delete_formatDate)(formatDateA);

        auto formatT = FORMAT_NAME(new)(ygo_data_Format_TRADITIONAL,
                formatDates[i]);
        auto formatDateT = FORMAT_NAME(formatDate)(formatT);
        auto formatTA = FORMAT_NAME(format)(formatT);
        BOOST_CHECK_EQUAL(std::string(formatDateT), formatDates[i]);
        BOOST_CHECK(formatTA == ygo_data_Format_TRADITIONAL);
        FORMAT_NAME(delete_formatDate)(formatDateT);
    }
    FORMAT_NAME(delete_formatDates)(formatDates, count);
}

BOOST_AUTO_TEST_CASE(Invalid)
{
    auto format = FORMAT_NAME(new)(ygo_data_Format_ADVANCED, "InvalidFormat");
    BOOST_CHECK(format == nullptr);
}

BOOST_AUTO_TEST_CASE(Limits)
{
    auto formatA = FORMAT_NAME(new)(ygo_data_Format_ADVANCED, "April 2004");
    auto formatT = FORMAT_NAME(new)(ygo_data_Format_TRADITIONAL, "April 2004");

    BOOST_CHECK_EQUAL(0, FORMAT_NAME(cardCount)(formatA, "Change of Heart"));
    BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatT, "Change of Heart"));

    BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatA, "Mage Power"));
    BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatT, "Mage Power"));

    BOOST_CHECK_EQUAL(2, FORMAT_NAME(cardCount)(formatA, "Creature Swap"));
    BOOST_CHECK_EQUAL(2, FORMAT_NAME(cardCount)(formatT, "Creature Swap"));

    BOOST_CHECK_EQUAL(3, FORMAT_NAME(cardCount)(formatA, "Kuriboh"));
    BOOST_CHECK_EQUAL(3, FORMAT_NAME(cardCount)(formatT, "Kuriboh"));

    FORMAT_NAME(delete)(formatA);
    FORMAT_NAME(delete)(formatT);

}

BOOST_AUTO_TEST_SUITE_END()

Add unit tests for format c bindings

Add unit tests for format c bindings


name: SCIP Disabled

on: [push, pull_request]

jobs:
  # Building using the github runner environement directly.
  cmake:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Check cmake
      run: cmake --version
    - name: Configure
      run: cmake -S. -Bbuild -DCMAKE_BUILD_TYPE=Release -DBUILD_DEPS=ON -DUSE_SCIP=OFF
    - name: Build
      run: cmake --build build --config Release --target all -v
    - name: Test
      run: CTEST_OUTPUT_ON_FAILURE=1 cmake --build build --config Release --target test -v
    - name: Install
      run: cmake --build build --config Release --target install -v -- DESTDIR=install

Add job with SCIP support disabled

ci(cmake): Add job with SCIP support disabled

Since SCIP doesn't use an OSI approved license, lots of customer,
may want to use OR-Tools with SCIP support disabled...


#include <stdio.h>

typedef struct _NODE {
  int data;
  _NODE* left;
  _NODE* right;
} NODE;

NODE* newNode(int data) {
  NODE* node = new NODE();
  node->data = data;
  node->left = nullptr;
  node->right = nullptr;
  return node;
}

int sum(NODE* root) {
  if (root == nullptr) return 0;

  return (sum(root->left) + root->data + sum(root->right));
}

bool isSumTree(NODE* root) {
  if (root == nullptr || (root->left == nullptr && root->right == nullptr))
    return true;
  int left_sum = sum(root->left);
  int right_sum = sum(root->right);

  if ((root->data == left_sum + right_sum) &&
      (isSumTree(root->left) && isSumTree(root->right)))
    return true;

  return false;
}

int main(int argc, char const* argv[]) {
  NODE* root = newNode(26);
  root->left = newNode(10);
  root->right = newNode(3);
  root->left->left = newNode(4);
  root->left->right = newNode(6);
  root->right->right = newNode(3);
  if (isSumTree(root))
    printf("The given tree is a SumTree ");
  else
    printf("The given tree is not a SumTree ");
  return 0;
}

Check whether given tree is sum tree.

Check whether given tree is sum tree.


// Chapter 23, exercise 14: like the sample program from 23.8.7, but read input
// from file into memory and experiment with patterns including '\n'

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

using namespace std;

int main()
{
    string ifname = "pics_and_txt/chapter23_ex12_in.txt";
    ifstream ifs(ifname);
    if (!ifs) throw runtime_error("Can't open " + ifname);
    string line;
    string text;
    while (getline(ifs,line))
        text += line + "\n";

    regex pattern;

    string pat;
    string prompt = "Enter pattern (qqq to exit): ";
    cout << prompt;
    while (getline(cin,pat)) {   // read pattern
        if (pat=="qqq") break;
        try {
            pattern = pat;  // this checks pat
        }
        catch (regex_error) {
            cout << pat << " is not a valid regular expression\n";
            exit(1);
        }

        smatch matches;
        if (regex_search(text,matches,pattern))
            cout << "Match found: " << matches[0] << '\n';
        else
            cout << "No match found\n";
        cout << prompt;
    }
}

Add Chapter 23, exercise 14

Add Chapter 23, exercise 14


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef vector < ll > vl;
int main(){
    vl data = {234234LL, 2322LL,1LL, -1LL, 3454LL};

    sort(data.begin(), data.end());

    for (int i=0; i< data.size(); i++)
        printf("%lld ", data[i]);
    return 0;
}

Add faster algorithm for working with sorting.


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

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
  BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
  BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
  BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}

BOOST_AUTO_TEST_SUITE_END()

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

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  double epsilon = 0.0001;
  BOOST_REQUIRE_CLOSE(results[0].getTime(), 1, epsilon );
  BOOST_REQUIRE_CLOSE(results[1].getTime(), 2, epsilon );
  BOOST_REQUIRE_CLOSE(results[2].getTime(), 3, epsilon );
  BOOST_REQUIRE_CLOSE(results[3].getTime(), 4, epsilon );
}

BOOST_AUTO_TEST_SUITE_END()

Change tests in JPetAnalysisTools to use double instead of int


// 10.exercise.06.cpp
//
//  Define a Roman_int class for holding Roman numerals (as ints) with a << and
//  >>. Provide Roman_int with an as_int() member that returns the int value,
//  so that if r is a Roman_int, we can write cout << "Roman" << r << "equals"
//  << r.as_int() << '\n';.

int main()
try
{
    return 0;
}
catch (exception& e)
{
    cerr << e.what() << '\n';
    return 1;
}
catch (...)
    cerr << "Unknown exception!!\n";
    return 2;
}

Prepare exercise 6 from chapter 10.

Prepare exercise 6 from chapter 10.


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

/* http://codeforces.com/contest/527/submission/11525645 */

#include <iostream>

int main() {
    long long int a, b;
    std::cin >> a >> b;
    long long int ans = 0;
    while (b > 0) {
        ans += a / b;
        a = a % b;
        long long int temp = a;
        a = b;
        b = temp;
    }
    std::cout << ans << std::endl;
    return 0;
}

Add the first codeforces problem

Add the first codeforces problem

Directory for codeforces problems.


/**
 * Rod Cutting
 * Given a length of rod, sample lengths and its
 * corresponding profits find the maximum profit
 * that can be made given the length.
 * @Author: wajahat siddiqui
 */
#include <iostream>
using namespace std;

inline unsigned int max(unsigned int a, unsigned int b) {
	return (a > b) ? a : b;
}
void printArray(unsigned int **A, int M, int N) {
	for (unsigned int i = 0; i <= M; i++) {
		for (unsigned int j = 0; j <= N; j++){
			cout<<A[i][j]<<" ";
		}
		cout<<endl;
	}
	cout<<endl;
}

/**
 * @param N is the length of the rod for which max profit to be found
 * @param M is the number of rods
 */
unsigned int findMaxProfit(int profit[], int M, int N) {
	unsigned int solution;
	unsigned int **T = new unsigned int *[M+1];
	for (int i = 0; i <= M; i++)
		T[i] = new unsigned int [N+1];
	for (int i = 0; i <= M; i++)
		T[i][0] = 0;
	for (int i = 1; i <= M; i++) {
		for (int j = 1; j <= N; j++) {
			if (j >= i) {
				T[i][j] = max((T[i][j-i] + profit[i-1]), T[i-1][j]);
			} else {
				T[i][j] = T[i-1][j];
			}
		}
	}

	printArray(T, M, N);
	solution = T[M][N];

	for (int i = 0; i <= M; i++)
		delete [] T[i];
	delete [] T;
	return solution;
}

int main() {
	int N = 5; // Rod Length
	int profit[] = {2, 5, 7, 8};
	int M = sizeof(profit)/sizeof(profit[0]); // No. of rods
	cout<<"Maximum profit that can be made from Rod Length: "<<N<<" is: "
	    <<findMaxProfit(profit, M, N);
	return 0;
}

Implement rod cutting to maximize profit using DP

Signed-off-by: WajahatSiddiqui <3c3ea4adfdf19decee174766aef6add34b32b7f0@gmail.com>


/*
* @author Abhishek Datta
* @github_id abdatta
* @since 15th October, 2017
*
* The following algroithm takes complex coeeficients
* and calculates its inverse discrete fourier transform
*/

#include <complex>
#include <iostream>
#include <iomanip>
#include <valarray>

const double PI = std::acos(-1);

typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;

// recursive fft (in-place)
void fft(CArray& x)
{
    const size_t N = x.size();
    if (N <= 1) return;

    // divide
    CArray even = x[std::slice(0, N/2, 2)];
    CArray  odd = x[std::slice(1, N/2, 2)];

    // conquer
    fft(even);
    fft(odd);

    // combine
    for (size_t k = 0; k < N/2; ++k)
    {
        Complex t = std::polar(1.0, 2 * PI * k / N) * odd[k];
        x[k    ] = even[k] + t;
        x[k+N/2] = even[k] - t;
    }
}

// inverse fft (in-place)
void ifft(CArray& x)
{
    // conjugate the complex numbers
    x = x.apply(std::conj);

    // forward fft
    fft( x );

    // conjugate the complex numbers again
    x = x.apply(std::conj);

    // scale the numbers
    x /= x.size();
}

int main()
{
	int t; // no. of test cases to try on
	std::cin>>t;
	while(t--)
	{
		int n; // n is for order of the polynomial
		std::cin>>n;
	    Complex test[n];
	    for (int i = 0; i < n; ++i)
	    {
	    	double real, imag;
	    	std::cin>>real>>imag; // reading each coefficient as a complex number
	    	test[i].real(real); // setting real part to real
	    	test[i].imag(imag); // and imaginary part to imaginary
	    }

	    CArray data(test, n);

	    ifft(data);

	    for (int i = 0; i < n; ++i)
	    {
	        std::cout << std::fixed << std::setprecision(6) << data[i].real() << " " << data[i].imag() << std::endl;
	    }
	}
}

Add algorithm for Inverse FFT

Add algorithm for Inverse FFT


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_Infobars Infobars
#else
#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) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
#if defined (OS_WIN)
#define MAYBE_Infobars Infobars
#else
// Flaky on ChromeOS, see http://crbug.com/40141.
#define MAYBE_Infobars FLAKY_Infobars
#endif

#else
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// 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_;
}

Mark a test as flaky on ChromeOS.

Mark a test as flaky on ChromeOS.

BUG=40141
TEST=None

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

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


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

#include "base/i18n/timezone.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {
namespace {

#if defined(OS_ANDROID)
// icu's timezone utility doesn't work on Android.
#define MAYBE_CountryCodeForCurrentTimezone DISABLED_CountryCodeForCurrentTimezone
#else
#define MAYBE_CountryCodeForCurrentTimezone CountryCodeForCurrentTimezone
#endif

TEST(TimezoneTest, MAYBE_CountryCodeForCurrentTimezone) {
  std::string country_code = CountryCodeForCurrentTimezone();
  EXPECT_EQ(2U, country_code.size());
}

}  // namespace
}  // namespace base

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

#include "base/i18n/timezone.h"

#include "testing/gtest/include/gtest/gtest.h"

namespace base {
namespace {

#if defined(OS_ANDROID)
// icu's timezone utility doesn't work on Android.
#define MAYBE_CountryCodeForCurrentTimezone DISABLED_CountryCodeForCurrentTimezone
#else
#define MAYBE_CountryCodeForCurrentTimezone CountryCodeForCurrentTimezone
#endif

TEST(TimezoneTest, MAYBE_CountryCodeForCurrentTimezone) {
  std::string country_code = CountryCodeForCurrentTimezone();
  EXPECT_EQ(2U, country_code.size());
}

}  // namespace
}  // namespace base

Revert 235842 "fix android build by adding build_config.h"

> fix android build by adding build_config.h
>
> BUG=none
> TBR=dewittj@chromium.org
>
> Review URL: https://codereview.chromium.org/75663003

TBR=estade@chromium.org

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

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


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

#include <shogun/base/init.h>
#include <shogun/labels/BinaryLabels.h>
#include <shogun/evaluation/ROCEvaluation.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(ROCEvaluation,one)
{
	int num_labels = 10;
	CBinaryLabels* gt = new CBinaryLabels(num_labels);
	CROCEvaluation* roc = new CROCEvaluation();

	for (int i = 0; i < num_labels; i++) {
		int l = (CMath::random(-1.0, 1.0) < 0 ? -1 : 1);
		gt->set_label(i, l);
	}

	roc->evaluate(gt, gt);

	EXPECT_EQ(roc->get_auROC(), 1);
}

Add unit test for ROCEvaluation as currently this little example fails


/*
 * Copyright 2018 Google, LLC
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "../Fuzz.h"

void fuzz_PolyUtils(Fuzz* f);

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    auto fuzz = Fuzz(SkData::MakeWithoutCopy(data, size));
    fuzz_PolyUtils(&fuzz);
    return 0;
}

Add oss-fuzz entrypoint for Polyutils fuzz

Bug: skia:
Change-Id: Iee7fe4344e65290ae25e4cd51f338d9ce56def55
Reviewed-on: https://skia-review.googlesource.com/c/161421
Reviewed-by: Kevin Lubick <7cdab2cfab351f23814786ba39716e90eed69047@google.com>


// Chapter 20, Exercise 12: complete the definition of list from 20.4.1-2 and
// get the high() example to run. Allocate a Link to represent one past the end.

#include "../lib_files/std_lib_facilities.h"

template<class Elem> struct Link {
    Link(const Elem& v = Elem(), Link* p = 0, Link* s = 0)
        :prev(p), succ(s), val(v) { }
    Link* prev;
    Link* succ;
    Elem val;
};

template<class Elem> class my_list {
public:
    my_list() :first(new Link<Elem>()), last(first) { }

    class iterator;

    iterator begin() { return iterator(first); }
    iterator end() { return iterator(last); }

    iterator insert(iterator p, const Elem& v); // insert v into list before p
    iterator erase(iterator p);          // remove p from the list

    void push_back(const Elem& v);
    void push_front(const Elem& v);
    void pop_front();
    void pop_back();

    Elem& front() { return *first; }
    Elem& back();

    Link<Elem>* first;
    Link<Elem>* last;   // one beyond the last link
};

template<class Elem> class my_list<Elem>::iterator {
    Link<Elem>* curr;
public:
    iterator(Link<Elem>* p) :curr(p) { }

//    Link<Elem>* get_link() { return curr; }

    iterator& operator++() { curr = curr->succ; return *this; } // forward
    iterator& operator--() { curr = curr->prev; return *this; } // backward
    Elem& operator*() { return curr->val; }    // get value (dereference)

    bool operator==(const iterator& b) const { return curr==b.curr; }
    bool operator!=(const iterator& b) const { return curr!=b.curr; }
};

template<class Elem>
void my_list<Elem>::push_front(const Elem& v)
{
    first = new Link<Elem>(v,0,first);
}

template<class Iterator>
Iterator high(Iterator first, Iterator last)
{
    Iterator high = first;
    for (Iterator p = first; p!=last; ++p)
        if (*high<*p) high = p;
    return high;
}

int main()
try {
    my_list<int> lst;
    int x;
    while (cin >> x) lst.push_front(x);
    my_list<int>::iterator p = high(lst.begin(),lst.end());
    cout << "The highest value was " << *p << "\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 12

Add Chapter 20, exercise 12


// RUN: not %clang_cc1 -fmodules -fmodule-map-file=does-not-exist.modulemap -verify %s 2>&1 | FileCheck %s

// CHECK: module map file 'does-not-exist.modulemap' not found

Add test file missed from r223561.

Add test file missed from r223561.

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


#include <iostream>
#include <cmath>

using namespace std;

class Point2D {
  double x;
  double y;

public:

  double getX() {
    return x;
  }

  double getY() {
    return y;
  }

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

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

  void translate(double dx, double dy) {
    setX(getX() + dx);
    setY(getY() + dy);
  }

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

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

void testTranslate() {
  Point2D point;
  point.setX(3);
  point.setY(5);

  point.translate(2, 3);
  point.print();
}

void testDistanceBetween() {
  Point2D firstPoint;
  firstPoint.setX(3);
  firstPoint.setY(5);

  Point2D secondPoint;
  secondPoint.setX(4);
  secondPoint.setY(1);

  cout << firstPoint.distanceTo(secondPoint) << '\n';
}

int main() {
  testTranslate();
  testDistanceBetween();

  return 0;
}

Add solution to third part of first problem. Replace the structure with class with getters and setters