/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */
#include "gst_media_binding.h"

namespace ti
{
	GstMediaBinding::GstMediaBinding(SharedKObject global) : MediaBinding(global)
	{
		char **argv;
		int argc = 0;
		gst_init(&argc, &argv);
	}

	GstMediaBinding::~GstMediaBinding()
	{
	}

	void GstMediaBinding::Beep()
	{
		printf("\a"); // \a to console should cause the beep sound
	}

	SharedKObject GstMediaBinding::CreateSound(std::string& url)
	{
		//This is a path so, turn it into a file:// URL
		std::string myurl = url;
		std::string path = URLUtils::URLToPath(url);
		if (path.find("://") != std::string::npos)
		{
			myurl = URLUtils::PathToFileURL(path);
		}

		SharedGstSound sound = new GstSound(myurl);
		GstSound::RegisterSound(sound);
		return sound;
	}
}

/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */
#include "gst_media_binding.h"

namespace ti
{
	GstMediaBinding::GstMediaBinding(SharedKObject global) : MediaBinding(global)
	{
		char **argv;
		int argc = 0;
		gst_init(&argc, &argv);
	}

	GstMediaBinding::~GstMediaBinding()
	{
	}

	void GstMediaBinding::Beep()
	{
		printf("\a"); // \a to console should cause the beep sound
	}

	SharedKObject GstMediaBinding::CreateSound(std::string& url)
	{
		//This is a path so, turn it into a file:// URL
		std::string myurl = url;
		std::string path = URLUtils::URLToPath(url);
		if (path.find("://") == std::string::npos)
		{
			myurl = URLUtils::PathToFileURL(path);
		}

		SharedGstSound sound = new GstSound(myurl);
		GstSound::RegisterSound(sound);
		return sound;
	}
}

Fix bug in URL parsing

Fix bug in URL parsing


#include "llvm/Testing/Support/SupportHelpers.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"

#include "gtest/gtest.h"

using namespace llvm;
using namespace llvm::unittest;

extern const char *TestMainArgv0;

SmallString<128> llvm::unittest::getInputFileDirectory() {
  llvm::SmallString<128> Result = llvm::sys::path::parent_path(TestMainArgv0);
  llvm::sys::fs::make_absolute(Result);
  llvm::sys::path::append(Result, "llvm.srcdir.txt");

  EXPECT_TRUE(llvm::sys::fs::is_directory(Result))
      << "Unit test source directory file does not exist.";

  auto File = MemoryBuffer::getFile(Result);

  EXPECT_TRUE(static_cast<bool>(File))
      << "Could not open unit test source directory file.";

  Result.clear();
  Result.append((*File)->getBuffer().trim());
  llvm::sys::path::append(Result, "Inputs");
  llvm::sys::path::native(Result);
  return std::move(Result);
}

#include "llvm/Testing/Support/SupportHelpers.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"

#include "gtest/gtest.h"

using namespace llvm;
using namespace llvm::unittest;

extern const char *TestMainArgv0;

SmallString<128> llvm::unittest::getInputFileDirectory() {
  llvm::SmallString<128> Result = llvm::sys::path::parent_path(TestMainArgv0);
  llvm::sys::fs::make_absolute(Result);
  llvm::sys::path::append(Result, "llvm.srcdir.txt");

  EXPECT_TRUE(llvm::sys::fs::is_regular_file(Result))
      << "Unit test source directory file does not exist.";

  auto File = MemoryBuffer::getFile(Result);

  EXPECT_TRUE(static_cast<bool>(File))
      << "Could not open unit test source directory file.";

  Result.clear();
  Result.append((*File)->getBuffer().trim());
  llvm::sys::path::append(Result, "Inputs");
  llvm::sys::path::native(Result);
  return std::move(Result);
}

Fix silly error in unittest helper.

Fix silly error in unittest helper.

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


#include <emscripten/bind.h>

#include "libcellml/parentedentity.h"

using namespace emscripten;

EMSCRIPTEN_BINDINGS(libcellml_parentedentity)
{
    class_<libcellml::ParentedEntity, base<libcellml::Entity>>("ParentedEntity")
        .smart_ptr<std::shared_ptr<libcellml::ParentedEntity>>("ParentedEntity")
        .function("parent", &libcellml::ParentedEntity::parent)
        .function("removeParent", &libcellml::ParentedEntity::removeParent)
        .function("hasParent", &libcellml::ParentedEntity::hasParent)
        .function("hasAncestor", &libcellml::ParentedEntity::hasAncestor)
    ;
}

#include <emscripten/bind.h>

#include "libcellml/parentedentity.h"

using namespace emscripten;

EMSCRIPTEN_BINDINGS(libcellml_parentedentity)
{
    class_<libcellml::ParentedEntity, base<libcellml::Entity>>("ParentedEntity")
        .smart_ptr<std::shared_ptr<libcellml::ParentedEntity>>("ParentedEntity")
        .function("parent", &libcellml::ParentedEntity::parent)
        .function("hasParent", &libcellml::ParentedEntity::hasParent)
        .function("hasAncestor", &libcellml::ParentedEntity::hasAncestor)
    ;
}

Remove removeParent from javascript ParentedEntity.


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

#include "views/focus/focus_manager.h"

#include "base/logging.h"

namespace views {

void FocusManager::ClearNativeFocus() {
  NOTIMPLEMENTED();
}

void FocusManager::FocusNativeView(gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

 // static
FocusManager* FocusManager::GetFocusManagerForNativeView(
    gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

}  // namespace views

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

#include "views/focus/focus_manager.h"

#include "base/logging.h"

namespace views {

void FocusManager::ClearNativeFocus() {
  NOTIMPLEMENTED();
}

void FocusManager::FocusNativeView(gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

 // static
FocusManager* FocusManager::GetFocusManagerForNativeView(
    gfx::NativeView native_view) {
  NOTIMPLEMENTED();
  return NULL;
}

}  // namespace views

Fix compilation error in the focus manager by returning NULL from unimplemented function.

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

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


#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

typedef map< string, vector<string> > Graph;

typedef struct
{
	int finish_time;
	int visited;
}State;

void dfs(Graph &g, string v, map<string, State*> &state, int &dfs_time)
{
	state[v]->visited = 0;
	dfs_time++;
	vector<string> adjacent = g[v];
	for (vector<string>::iterator i = adjacent.begin(); i != adjacent.end(); i++) {
		if (state[*i]->visited == -1) {
			dfs(g, *i, state, dfs_time);
		}
	}
	state[v]->visited = 1;
	dfs_time++;
	state[v]->finish_time = dfs_time;
}

bool cmp(const pair<string, State*> &x, const pair<string, State*> &y)
{
	return x.second->finish_time > y.second->finish_time;
}

int main()
{
	int T;
	cin >> T;
	while(T--) {
		Graph graph;
		map<string, State*> state;
		int finish_time = 0;
		int N;
		cin >> N;
		while (N--) {
			string x, y;
			cin >> x >> y;
			graph[x].push_back(y);
			state[x] = new State;
			state[x]->finish_time = 0;
			state[x]->visited = -1;
			if (graph[y].empty()) {
				graph[y].clear();
				state[y] = new State;
				state[y]->finish_time = 0;
				state[y]->visited = -1;
			}
		}
		for (Graph::iterator i = graph.begin(); i != graph.end(); i++) {
			if (state[i->first]->visited == -1) {
				dfs(graph, i->first, state, finish_time);
			}
		}
		typedef vector< pair<string, State*> > ResType;
		ResType res;
		for (map<string, State*>::iterator i = state.begin(); i != state.end(); i++) {
			res.push_back(pair<string, State*>(i->first, i->second));
		}
		sort(res.begin(), res.end(), cmp);
		for (ResType::iterator i = res.begin(); i != res.end(); i++) {
			cout << i->first << endl;
		}

	}
	return 0;
}

Add the solution to "Potentate Permutation".


#include <iostream>
#include <execution_policy>

int main()
{
  std::async(std::con(10), [](std::concurrent_group &g)
  {
    std::cout << "agent " << g.child().index() << " arriving at barrier" << std::endl;

    g.wait();

    std::cout << "departing barrier" << std::endl;
  }).wait();

  return 0;
}

Add test for concurrent groups

Add test for concurrent groups


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

struct NonDefaultConstructible {
  NonDefaultConstructible(const NonDefaultConstructible&);
};

template<typename T, typename U>
struct X {
  static T member;
};

template<typename T, typename U>
T X<T, U>::member; // expected-error{{no matching constructor}}

// Okay; this is a declaration, not a definition.
template<>
NonDefaultConstructible X<NonDefaultConstructible, long>::member;

NonDefaultConstructible &test(bool b) {
  return b? X<NonDefaultConstructible, int>::member // expected-note{{instantiation}}
          : X<NonDefaultConstructible, long>::member;
}

Test explicit specializations of static data members that are declarations, not definitions

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


/*
g++ huge-threads.cpp ../../objs/st/libst.a -g -O0 -DLINUX -o huge-threads && ./huge-threads 32756
*/
#include <stdio.h>
#include <stdlib.h>
#include "../../objs/st/st.h"

void* pfn(void* arg) {
    char v[32*1024]; // 32KB in stack.
    for (;;) {
        v[0] = v[sizeof(v) - 1] = 0xf;
        st_usleep(1000 * 1000);
    }
    return NULL;
}

int main(int argc, char** argv) {
    if (argc < 2) {
        printf("Usage: %s nn_coroutines [verbose]\n", argv[0]);
        exit(-1);
    }

    st_init();
    int nn = ::atoi(argv[1]);
    printf("pid=%d, create %d coroutines\n", ::getpid(), nn);
    for (int i = 0; i < nn; i++) {
        st_thread_t thread = st_thread_create(pfn, NULL, 1, 0);
        if (!thread) {
            printf("create thread fail, i=%d\n", i);
            return -1;
        }
        if (argc > 2) {
            printf("thread #%d: %p\n", i, thread);
        }
    }

    printf("done\n");
    st_thread_exit(NULL);
    return 0;
}

Add huge coroutine test program

Research: Add huge coroutine test program


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

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

void show_us(const char *str) {
	struct timeval tv;
	gettimeofday(&tv, 0);
	printf("%s: %ld.%ld\n", str, tv.tv_sec, tv.tv_usec);
}

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

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

void show_us(const char *str) {
	struct timeval tv;
	gettimeofday(&tv, 0);
	printf("%s: %ld.%ld\n", str, tv.tv_sec, tv.tv_usec);
}

Fix build failure on Fedora

Fix build failure on Fedora


#include <iostream>

using namespace std;

struct Destination {
    char city[32];
    int kilometers;
};

int main() {
    Destination plovdiv = { "Plovdiv", 165 }, varna = { "Varna", 469 };
    cout << plovdiv.city << " " << plovdiv.kilometers << endl;
    cout << varna.city << " " << varna.kilometers << endl;

    Destination destinations[30];
    for (int i = 0; i < 30; i++) {
        destinations[i] = {};
    }

    Destination fiveDestinations[5] = {
        { "Plovdiv", 165 },
        { "Varna", 469 },
        { "Burgas", 393 },
        { "Vidin", 199 },
        { "Dobrich", 512 }
    };

    for (int i = 0; i < 5; i++)
        cout << fiveDestinations[i].city << " " << fiveDestinations[i].kilometers << endl;

    return 0;
}

Add solution to the second problem

Add solution to the second problem

Use simple struct initialization without explicit constructors


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if(!head) return NULL;
        int tot=countl(head);
        if(tot==1){
            TreeNode* ret=new TreeNode(head->val);
            return ret;
        }
        int mid=(tot-1)/2;
        ListNode* t=new ListNode(0);
        if(mid==0){
            t=head;
        }else{
            t=getnth(head,mid);
        }
        TreeNode* ret=new TreeNode(t->next->val);
        ret->right=sortedListToBST(t->next->next);
        t->next=NULL;
        ret->left=sortedListToBST(head);
        return ret;
    }
    int countl(ListNode* head){
        if(head->next) return countl(head->next)+1;
        return 1;
    }
    ListNode* getnth(ListNode* head, int n){
        if(n==1) return head;
        return getnth(head->next,n-1);
    }
};

Convert Sorted List to Binary Search Tree


#include "ntp-time.h"

NtpTime* ntpTime;

String hhmmss(unsigned long int now)  //format value as "hh:mm:ss"
{
   String hour = String(Time.hourFormat12(now));
   String minute = String::format("%02i",Time.minute(now));
   String second = String::format("%02i",Time.second(now));
   return hour + ":" + minute + ":" + second;
};

void setup() {
    ntpTime = new NtpTime(15);  // Do an ntp update every 15 minutes;
    ntpTime->start();
}

void loop() {
    static unsigned long waitMillis;
    struct epochMillis now;  //holds the unix epoch time to millisecond resolution
    if(millis() > waitMillis) {
        ntpTime->nowMillis(&now);  //get the current NTP time
        Particle.publish("NTP clock is: ", hhmmss(now.seconds) + "." + String::format("%03i",now.millis));
        Particle.publish("System clock is: ", hhmmss(Time.now()));
        waitMillis = millis() + (15*1000);  // wait 15 seconds
    }
}

Update to version 0.1.0  Add millisecond resolution

Add interface to return unix epoch to millisecond resolution.  Miscellaneous fixes and cleanup.


// done_states.cpp

#include "hsm/statemachine.h"

using namespace hsm;

class Character
{
public:
	Character();
	void Update();

	// Public to simplify sample
	bool mOpenDoor;

private:
	friend struct CharacterStates;
	StateMachine mStateMachine;
};

struct CharacterStates
{
	struct BaseState : StateWithOwner<Character>
	{
	};

	struct Alive : BaseState
	{
		virtual Transition GetTransition()
		{
			return InnerEntryTransition<Stand>();
		}
	};

	struct Stand : BaseState
	{
		virtual Transition GetTransition()
		{
			if (Owner().mOpenDoor)
			{
				Owner().mOpenDoor = false;
				return SiblingTransition<OpenDoor>();
			}

			return NoTransition();
		}
	};

	struct OpenDoor : BaseState
	{
		virtual Transition GetTransition()
		{
			if (IsInInnerState<OpenDoor_Done>())
				return SiblingTransition<Stand>();

			return InnerEntryTransition<OpenDoor_GetIntoPosition>();
		}
	};

	struct OpenDoor_GetIntoPosition : BaseState
	{
		bool IsInPosition() const { return true; } // Stub

		virtual Transition GetTransition()
		{
			if (IsInPosition())
				return SiblingTransition<OpenDoor_PlayOpenAnim>();

			return NoTransition();
		}
	};

	struct OpenDoor_PlayOpenAnim : BaseState
	{
		bool IsAnimDone() const { return true; } // Stub

		virtual Transition GetTransition()
		{
			if (IsAnimDone())
				return SiblingTransition<OpenDoor_Done>();

			return NoTransition();
		}
	};

	struct OpenDoor_Done : BaseState
	{
	};
};

Character::Character()
	: mOpenDoor(false)
{
	mStateMachine.Initialize<CharacterStates::Alive>(this);
	mStateMachine.SetDebugInfo("TestHsm", TraceLevel::Basic);
}

void Character::Update()
{
	printf(">>> Character::Update\n");

	// Update state machine
	mStateMachine.ProcessStateTransitions();
	mStateMachine.UpdateStates();
}

int main()
{
	Character character;

	character.Update();

	character.mOpenDoor = true;
	character.Update();
}

Add sample for section: Done States

Add sample for section: Done States


// RUN: %clang_cc1 -fsyntax-only -std=c++98 -Wc++0x-compat -verify %s

namespace N {
  template<typename T> void f(T) {} // expected-note {{here}}
  namespace M {
    template void f<int>(int); // expected-warning {{explicit instantiation of 'N::f' must occur in namespace 'N'}}
  }
}

template<typename T> void f(T) {} // expected-note {{here}}
namespace M {
  template void f<int>(int); // expected-warning {{explicit instantiation of 'f' must occur in the global namespace}}
}

void f() {
  auto int n = 0; // expected-warning {{'auto' storage class specifier is redundant and incompatible with C++0x}}
}

int n;
struct S {
  char c;
}
s = { n }, // expected-warning {{non-constant-expression cannot be narrowed from type 'int' to 'char' in initializer list in C++0x}} expected-note {{explicit cast}}
t = { 1234 }; // expected-warning {{constant expression evaluates to 1234 which cannot be narrowed to type 'char' in C++0x}} expected-warning {{changes value}} expected-note {{explicit cast}}

Add more testing for -Wc++0x-compat warnings.

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


#include <cstdio>
using namespace std;

// Test that if the validator says WA, that's the verdict given even if we
// TLE afterwards (realistically because we tried to read from stdin and didn't
// get a response we expected).

int main(void) {
    printf("-1\n");
    fflush(stdout);
    for (;;);
}

Add a test for the TLE -> WA behavior

Add a test for the TLE -> WA behavior


#include <cxxtest/TestDrive.h>

#include "forceplateTest_def.h"

#include <openma/instrument/forceplatetype4.h>

CXXTEST_SUITE(ForcePlateType4Test)
{
  CXXTEST_TEST(wrench)
  {
    ma::instrument::ForcePlateType4 fp("FP");
    forceplatetest_fill_sample10_type4(&fp);
    forceplatetest_compare_wrench_at_origin(&fp, fp4dataout);
  };
};

CXXTEST_SUITE_REGISTRATION(ForcePlateType4Test)
CXXTEST_TEST_REGISTRATION(ForcePlateType4Test, wrench)

Test for the force platform Type-4.

Test for the force platform Type-4.


/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
**     of its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

//! [0]
void MyMainWindow::closeEvent(QCloseEvent *event)
{
    QSettings settings("MyCompany", "MyApp");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
    QMainWindow::closeEvent(event);
}
//! [0]

//! [1]
void MainWindow::readSettings()
{
    QSettings settings("MyCompany", "MyApp");
    restoreGeometry(settings.value("myWidget/geometry").toByteArray());
    restoreState(settings.value("myWidget/windowState").toByteArray());
}
//! [1]

Add missing code snippet file

Add missing code snippet file

src_gui_widgets_qmainwindow.cpp is referred to from
restoring-geometry.qdoc
Copied the version from Qt4, API of involved classes has not changed

Change-Id: Ifc8e68b9e8f7ef81357699537fdc70b50dd0d476
Reviewed-by: Jerome Pasion <c10995d24f6b454503389e8d00d837aef038985d@digia.com>
Reviewed-by: Paul Olav Tvete <97541fb6312d77f06e19078c7c70b2c1f75fb828@digia.com>


// 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

// Sometimes this test fails on Linux: crbug.com/130138
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Idle) {
#else
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Idle) {
#endif
  ASSERT_TRUE(RunExtensionTest("idle")) << message_;
}

// 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

// This test is flaky: crbug.com/130138
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Idle) {
  ASSERT_TRUE(RunExtensionTest("idle")) << message_;
}

Disable ExtensionApiTest.Idle on all platforms, since it's flaky everywhere.

BUG=130138
TBR=brg@chromium.org

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

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


#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

void calcMinkowskiDistance(const int& p, const int& numberOfData, const int* x, const int* y);
void calcChebyshevDistance(const int& numberOfData, const int* x, const int* y);

int main() {
  int numberOfData(0);
  cin >> numberOfData;

  int x[1000], y[1000];
  for(int i = 0; i < numberOfData; ++i)
    cin >> x[i];
  for(int i = 0; i < numberOfData; ++i)
    cin >> y[i];

  calcMinkowskiDistance(1, numberOfData, x, y);
  calcMinkowskiDistance(2, numberOfData, x, y);
  calcMinkowskiDistance(3, numberOfData, x, y);
  calcChebyshevDistance(numberOfData, x, y);

  return 0;
}

void calcMinkowskiDistance(const int& p, const int& numberOfData, const int* x, const int* y) {
  double sum(0.0);
  for(int i = 0; i < numberOfData; ++i )
    sum += pow((abs(*(x + i) - *(y + i))), (float)p);

  cout << fixed << setprecision(8) << pow(sum, 1.0/(float)p) << endl;
}

void calcChebyshevDistance(const int& numberOfData, const int* x, const int* y) {
  double distance(0.0);

  for(int i = 0; i < numberOfData; ++i ) {
    if(distance < abs(*(x + i) - *(y + i)))
      distance = abs(*(x + i) - *(y + i));
  }

  cout << fixed << setprecision(8) << distance << endl;
}

Add answer for ITP 1-11 D

Add answer for ITP 1-11 D


/* **********************************************************
 * 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 <windows.h>

#include "gtest/gtest.h"

TEST(NtUserTests, SystemParametersInfo) {
    NONCLIENTMETRICS metrics;
    ZeroMemory(&metrics, sizeof(NONCLIENTMETRICS));
    metrics.cbSize = sizeof(NONCLIENTMETRICS);
    EXPECT_NE(0, SystemParametersInfo(SPI_GETNONCLIENTMETRICS,
                                      sizeof(NONCLIENTMETRICS), &metrics, 0));
}

Add a test for NtUserSystemParametersInfo syscall to app_suite

git-svn-id: fe3cd4388a6e5a968b09397a3d721fe124e8117a@398 5b54908e-ead4-fc18-b48a-0285e6dbc711


#include <iostream>

using namespace std;

namespace primerLib {
    void compute() {
        cout << "primerLib::compute()" << endl;
    }

//    void compute(const void *p) {
//        cout << "primerLib::compute(const void *)" << endl;
//    }
}

void compute(int i) {
    cout << "::compute(int)" << endl;
}

void compute(double d, double d2 = 3.4) {
    cout << "::compute(double, double = 3.4)" << endl;
}

void compute(char* p1, char* p2 = 0) {
    cout << "::compute(char*, char* = 0)" << endl;
}

void f() {
    using primerLib::compute;
    compute(0);
}

int main() {
    f();
    return 0;
}

Add solution for chapter 18 test 20

Add solution for chapter 18 test 20


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

using namespace std;

int main() {
    string zipcode("(\\d{5})([-]?\\d{4})?");
    regex r(zipcode);
    string s;
    smatch m;
    while(getline(cin, s)) {
        if(regex_match(s, m, r)) {
            cout << "valid: " << m.str() << endl;
        } else {
            cout << "invalid: " << m.str() << endl;
        }
    }
    return 0;
}

Add solution for chapter 17 test 23

Add solution for chapter 17 test 23


#include <iostream>
#include <string>
using namespace std;

struct Node
{
	string s;
	Node *left;
	Node *right;
};

Node *new_node(string s)
{
	Node *temp = new Node();
	temp->s = s;
	temp->left = NULL;
	temp->right = NULL;
	return temp;
}

bool add_edge(Node *root, Node *father, Node *child)
{
	if (root == NULL) {
		return false;
	}
	if (root->s == father->s) {
		if (root->left == NULL) {
			root->left = child;
			return true;
		}
		else {
			root->right = child;
			return true;
		}
	}
	if (!add_edge(root->left, father, child)) {
		return add_edge(root->right, father, child);
	}
	return true;
}

void pre_order(Node *root)
{
	if (root == NULL) {
		return;
	}
	cout << root->s << endl;
	pre_order(root->left);
	pre_order(root->right);
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int k;
		cin >> k;
		string s1, s2;
		cin >> s1 >> s2;
		Node *tree = new_node(s1);
		Node *left = new_node(s2);
		tree->left = left;
		while (--k) {
			cin >> s1 >> s2;
			add_edge(tree, new_node(s1), new_node(s2));
		}
		pre_order(tree);
	}
	return 0;
}

Add the solution to "Preorder perusal".

Add the solution to "Preorder perusal".


#include <iostream>
#include <string>

using namespace std;

class Dog {
    string name;
public:
    Dog(string _name = "") {
        name = _name;
    }
    void greet() {
        cout << "Bark, bark! I am " << name << ", a talking dog." << endl;
    }
};

class Person {
    string name;
    int age;
    Dog dog;
public:
    Person(string _name, int _age, Dog _dog) {
        name = _name;
        age = _age;
        dog = _dog;
    }
    void greet() {
        cout << "Hi! I am " << name << " and I am " << age << " years old." << endl;
        cout << "And this is my dog:" << endl;
        dog.greet();
    }
};

int main() {
    Person ivan("Ivan", 15, Dog("Johny"));
    ivan.greet();

    return 0;
}

Add solution to the Person with a dog problem


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

using namespace std;
using namespace tpool;

void InputPrompt(const unsigned int cnt)
{
  cout << "[" << cnt << "] In: ";
}

unsigned int GetFibonacciNumber(const unsigned int i)
{
  if (i < 2)
    {
      return i;
    }
  else
    {
      return GetFibonacciNumber(i - 1) + GetFibonacciNumber(i - 2);
    }
}

void OutputFibonacciNumber(const unsigned int cnt, const unsigned int i)
{
  cout << "[" << cnt << "] Out: " << GetFibonacciNumber(i) << endl;
}

void SyncLoop()
{
  unsigned int i = 0, cnt = 1;

  InputPrompt(cnt);
  while(cin >> i)
    {
      OutputFibonacciNumber(cnt, i);
      InputPrompt(++cnt);
    }
}

void AsyncLoop()
{
  unsigned int i = 0, cnt = 1;
  LFixedThreadPool threadPool;

  InputPrompt(cnt);
  while(cin >> i)
    {
      threadPool.AddTask(boost::bind(&OutputFibonacciNumber, cnt, i));
      InputPrompt(++cnt);
    }
}

int main(int argc, char *argv[])
{
  // SyncLoop();
  AsyncLoop();

  return 0;
}

Add an Fibonacci example to show the usage of AddTask.


#include <stan/math/prim.hpp>
#include <test/unit/math/prim/fun/expect_matrix_eq.hpp>
#include <gtest/gtest.h>

#define EXPECT_MATRIX_NEAR(A, B, DELTA) \
  for (int i = 0; i < A.size(); i++)    \
    EXPECT_NEAR(A(i), B(i), DELTA);

TEST(MathMatrixPrim, mdivide_left_tri_low_val) {
  using stan::math::mdivide_left_tri_low;
  stan::math::matrix_d I = Eigen::MatrixXd::Identity(2, 2);

  stan::math::matrix_d Ad(2, 2);
  Ad << 2.0, 0.0, 5.0, 7.0;
  expect_matrix_eq(I, mdivide_left_tri_low(Ad, Ad));

  stan::math::matrix_d A_Ainv = Ad * mdivide_left_tri_low(Ad);
  EXPECT_MATRIX_NEAR(I, A_Ainv, 1e-15);
}

TEST(MathMatrixPrim, mdivide_left_tri_low_size_zero) {
  using stan::math::mdivide_left_tri_low;
  stan::math::matrix_d Ad(0, 0);
  stan::math::matrix_d b0(0, 2);
  stan::math::matrix_d I;

  I = mdivide_left_tri_low(Ad, Ad);
  EXPECT_EQ(0, I.rows());
  EXPECT_EQ(0, I.cols());

  I = mdivide_left_tri_low(Ad);
  EXPECT_EQ(0, I.rows());
  EXPECT_EQ(0, I.cols());

  I = mdivide_left_tri_low(Ad, b0);
  EXPECT_EQ(0, I.rows());
  EXPECT_EQ(b0.cols(), I.cols());
}

Add prim test for mdivide_left_tri_low

Add prim test for mdivide_left_tri_low


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

#include "content/renderer/media/media_stream_audio_source.h"

namespace content {

MediaStreamAudioSource::MediaStreamAudioSource(
    int render_view_id,
    const StreamDeviceInfo& device_info,
    const SourceStoppedCallback& stop_callback,
    MediaStreamDependencyFactory* factory)
    : render_view_id_(render_view_id),
      factory_(factory) {
  SetDeviceInfo(device_info);
  SetStopCallback(stop_callback);
}

MediaStreamAudioSource::MediaStreamAudioSource()
    : render_view_id_(-1),
      factory_(NULL) {
}

MediaStreamAudioSource::~MediaStreamAudioSource() {}

void MediaStreamAudioSource::DoStopSource() {
  audio_capturer_->Stop();
}

void MediaStreamAudioSource::AddTrack(
    const blink::WebMediaStreamTrack& track,
    const blink::WebMediaConstraints& constraints,
    const ConstraintsCallback& callback) {
  // TODO(xians): Properly implement for audio sources.
  bool result = true;
  if (factory_ && !local_audio_source_) {
    result = factory_->InitializeMediaStreamAudioSource(render_view_id_,
                                                        constraints,
                                                        this);
  }
  callback.Run(this, result);
}

void MediaStreamAudioSource::RemoveTrack(
    const blink::WebMediaStreamTrack& track) {
  NOTIMPLEMENTED();
}

}  // namespace content

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

#include "content/renderer/media/media_stream_audio_source.h"

namespace content {

MediaStreamAudioSource::MediaStreamAudioSource(
    int render_view_id,
    const StreamDeviceInfo& device_info,
    const SourceStoppedCallback& stop_callback,
    MediaStreamDependencyFactory* factory)
    : render_view_id_(render_view_id),
      factory_(factory) {
  SetDeviceInfo(device_info);
  SetStopCallback(stop_callback);
}

MediaStreamAudioSource::MediaStreamAudioSource()
    : render_view_id_(-1),
      factory_(NULL) {
}

MediaStreamAudioSource::~MediaStreamAudioSource() {}

void MediaStreamAudioSource::DoStopSource() {
  if (audio_capturer_.get())
    audio_capturer_->Stop();
}

void MediaStreamAudioSource::AddTrack(
    const blink::WebMediaStreamTrack& track,
    const blink::WebMediaConstraints& constraints,
    const ConstraintsCallback& callback) {
  // TODO(xians): Properly implement for audio sources.
  bool result = true;
  if (factory_ && !local_audio_source_) {
    result = factory_->InitializeMediaStreamAudioSource(render_view_id_,
                                                        constraints,
                                                        this);
  }
  callback.Run(this, result);
}

void MediaStreamAudioSource::RemoveTrack(
    const blink::WebMediaStreamTrack& track) {
  NOTIMPLEMENTED();
}

}  // namespace content

Fix use of invalid pointer in MediaStreamAudioSource.
If the source is not initiated correctly it can happen that the |audio_capturer_| is not set.
MediaStreamAudioSource::DoStop will then crash.

BUG= 340492
R=xians@chromium.org

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

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


#include "catch.hpp"
#include <iostream>
#include <string>

#include "audio/Sound.h"

const std::string sound_file = "sound.wav";

TEST_CASE("Initial value(s) in Sound", "[Sound]")
{
	Sound* sound = new Sound();

	// volume should be at max
	CHECK(sound->get_volume() == 100);

	delete sound;
}

TEST_CASE("Opening sound chunk", "[Sound]")
{
	REQUIRE(SDL_Init(SDL_INIT_EVERYTHING) == 0);
	Sound* sound = new Sound();
	REQUIRE(sound != nullptr);

	SECTION("once w/o close")
	{
		sound->open(sound_file);
		CHECK(sound->get_sound() != nullptr);
	}
	SECTION("once")
	{
		sound->open(sound_file);
		REQUIRE(sound->get_sound() != nullptr);

		sound->close();
		CHECK(sound->get_sound() == nullptr);
	}
	SECTION("twice")
	{
		for(unsigned int i = 0; i < 2; i++)
		{
			sound->open(sound_file);
			REQUIRE(sound->get_sound() != nullptr);

			sound->close();
			CHECK(sound->get_sound() == nullptr);
		}
	}
	SECTION("thrice")
	{
		for(unsigned int i = 0; i < 3; i++)
		{
			sound->open(sound_file);
			REQUIRE(sound->get_sound() != nullptr);

			sound->close();
			CHECK(sound->get_sound() == nullptr);
		}
	}

	delete sound;
	SDL_Quit();
}

Add Sound unit testing source.

Add Sound unit testing source.


#include <iostream>
#include<stdlib.h>
#include <string.h>
using namespace std;

struct Graph {
    int V,E;
    int **adj;
};

Graph* createGraph(int V, int E) {
    Graph *G = new Graph();
    if (!G) return NULL;

    G->V = V;
    G->E = E;

    G->adj = new int*[G->V]; //row count
    for (int i = 0; i < G->V; i++) //column count
        G->adj[i] = new int[G->V];
    for (int i = 0; i < G->V; i++)
        for (int j = 0; j < G->V; j++)
            G->adj[i][j] = 0;
    int u, v;
    // 0 -> 1
    // 1 -> 2
    // 2 -> 3
    // 2 -> 0
    // 3 -> 0
    for (int i = 0; i < G->E; i++) {
        cout<<"Enter edge from u to v: ";
        cin>>u>>v;
        G->adj[u][v] = 1;
        // uncomment this for undirected graph
        // uses symmetry to initialize
        //G->adj[v][u] = 1;
    }
    return G;
}

void print(Graph *G) {
    for (int u = 0; u < G->V; u++) {
        for (int v = 0; v < G->V; v++) {
            cout<<G->adj[u][v]<<" ";
        }
    cout<<endl;
    }
}

void deleteGraph(Graph *G) {
    if (!G || !G->adj) return;
    for (int i = 0; i < G->V; i++)
        delete [] G->adj[i];
    delete [] G->adj;

    delete G;
}

int main() {
    Graph *G = createGraph(4, 5);
    print(G);
    deleteGraph(G);
    return 0;
}

Implement Graph using Adjacency Matrix

Implement Graph using Adjacency Matrix

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


class global {
};
namespace n {
    void external_func() {
        class floating_func {
        };
    }

    enum normal_enum {};

    enum class class_enum{};

    struct str_test {};

    namespace m {
        class in_namespace {
            class in_class {
            };

            void main() {
                class in_function {
                };

                {
                    class in_inner_scope {
                    };
                }
            }
        };
    }
}

Add testing file to check output for declaration scopes.


// 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 "content/renderer/gpu/delegated_compositor_output_surface.h"

namespace content {

DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface(
    int32 routing_id,
    uint32 output_surface_id,
    const scoped_refptr<ContextProviderCommandBuffer>& context_provider,
    scoped_ptr<cc::SoftwareOutputDevice> software)
    : CompositorOutputSurface(routing_id,
                              output_surface_id,
                              context_provider,
                              software.Pass(),
                              true) {
  capabilities_.delegated_rendering = true;
  capabilities_.max_frames_pending = 1;
}

}  // namespace content

// 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 "content/renderer/gpu/delegated_compositor_output_surface.h"

namespace content {

DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface(
    int32 routing_id,
    uint32 output_surface_id,
    const scoped_refptr<ContextProviderCommandBuffer>& context_provider,
    scoped_ptr<cc::SoftwareOutputDevice> software)
    : CompositorOutputSurface(routing_id,
                              output_surface_id,
                              context_provider,
                              software.Pass(),
                              true) {
  capabilities_.delegated_rendering = true;
}

}  // namespace content

aura: Set max pending frames to the default instead of 1 with ubercomp.

R=jbauman, piman
BUG=286548

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

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


#include "mbed.h"
#include "EventHandler.h"
class VTest {
public:
    int vprint(void *arg) {
        if (arg) {
            int* i = static_cast<int *>(arg);
            printf("Class Print Integer: %d from %p\r\n", *i, arg);
        } else {
            printf("Class Null Arg\r\n");
        }
        return (int)(arg != 0);
    }

};

int barevprint(void *arg) {
    if (arg) {
        int* i = static_cast<int *>(arg);
        printf("Bare Print Integer: %d from %p\r\n", *i, arg);
    } else {
        printf("Class Null Arg\r\n");
    }
    return (int)(arg != 0);
}

int main(void)
{
    VTest test;
    printf("Testing mbed Event Handler...\r\n");
    int i1 = 1;
    int i2 = 2;
    EventHandler ebp(barevprint);
    EventHandler ecp(&test, &VTest::vprint);
    size_t ebsize = sizeof(ebp);
    size_t ecsize = sizeof(ecp);
    printf("sizeof(bp) = %d\r\n", ebsize);
    printf("sizeof(cp) = %d\r\n", ecsize);
    ebp.call(&i1);
    ecp.call(&i2);

    printf ("Test Complete\r\n");
    while(1){__WFI();}
    return 0;
}

Add a trivial test for EventHandler

Add a trivial test for EventHandler


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

using namespace std;
int main(){
    string  s = "123daniel , jajaja, lol, 234234534, I am from Earth";
    regex tel("\\d{8},\\sI");

    auto words_begin = sregex_iterator(s.begin(), s.end(), tel);
    auto words_end = sregex_iterator();

    cout << "Found " << distance(words_begin, words_end)<< " words\n";

    const int N = 6;

    for (sregex_iterator i = words_begin; i != words_end; ++i) {
        smatch match = *i;
        string match_str = match.str();
        if (match_str.size() > N) {
            cout << "  " << match_str << '\n';
        }
    }

    return 0;

}

Add code for regular expresions in c++.

Add code for regular expresions in c++.


#include <iostream>
#include<algorithm>

using namespace std;

class interval
{
    int start;
    int duration;
};

bool myCompare(interval a, interval b)
{
    return a.start<b.start;
}
bool conflict(interval a, int timestamp)
{
    if(a.start <= timestamp && (a.start + a.duration >= timestamp ) )
        return true;
    return false;
}
int find_first(vector<interval> Calls, int timestamp)
{
    for(int i=Calls.size()-1; i>0 ;i--)
    {
        if(Calls[i].start <= timestamp)
            return i;
    }
    return -1;
}

int find_first_BS(vector<interval> Calls, int timestamp)
{
    int l =0; int r = Calls.size()-1;
    if(Calls[0].start > timestamp) // No timestamp found
        return -1;
    if(Calls[Calls.size()-1].start <= timestamp) // All Intervals Qualify
        return Calls.size()-1;
    while(l<r)
    {
        int mid = l+(r-l)/2;
        if(Calls[mid].start > timestamp) // search left
        {
            r= mid - 1;
        }
        else
        {
            l = mid + 1;
        }
    }
    return l;
}

int find_overlapping_calls(vector<interval> Calls , int timestamp)
{
    // first sort based on start time
    // as we know given a instant the possible conflicts would
    // have start time < instant and end time > instant

    sort(Calls.begin(),Calls.end(),myCompare);

    // int ix = find_first(Calls, timestamp); ---- O (n)
    int ix = find_first_BS(Calls, timestamp); // --- O(log n) Because Using Binary Search
    if(ix == -1)
        return 0;
    int count = 0;
    for(int i=ix; i>0; i--)
    {
        if(conflict(Calls[i], timestamp) == true)
            count++;
    }
    return count;
}
// Complexity :
// No Extra Space
// O(n) + O(n) ~ O(n) ---> If we use Linear Search to find the first Qualifying Ix, using the function
// find_first;
// O(log n) + O(n) ~ O(n) --- > If we Use Binary Search using the function find_first_BS
//
// Once we have the first Qualifying ix it takes linear time to go over them
// But in general on an avg it will not be O(n)
// So, Optimization to find the ix using Binary Search Makes sense

/// ----- I think a better Performance can be achieved using interval Tree Data Structure
/// But Due to time constraint I did not implement the Interval Tree

Update Interview question twitter microsoft


// Chapter 24, exercise 2: same as exercise 1, but with function objects
// instead of functions

#include<iostream>
#include "Matrix.h"
#include "MatrixIO.h"

using namespace std;
using namespace Numeric_lib;

namespace Numeric_lib {;

struct Triple1 {
    void operator()(int& a) { a *= 3; }
};

struct Triple2 {
    int operator()(int a) { return a*3; }
};

struct Triple {
    int operator()(int& a) { a*= 3; return a; }
};

}   // Numeric_lib

int main()
try
{
    int arr[] = { 1, 2, 3, 4, 5 };
    Matrix<int> m1(arr);
    cout << "m1:\t\t\t\t\t" << m1 << '\n';

    m1.apply(Triple1());
    cout << "m1 after m1.apply(Triple1()):\t\t" << m1 << '\n';

    Matrix<int> m2 = apply(Triple2(),m1);
    cout << "m1 after m2 = apply(Triple2(),m1):\t" << m1 << '\n';
    cout << "m2:\t\t\t\t\t" << m2 << '\n';

    m2.apply(Triple());
    cout << "m2 after m2.apply(Triple()):\t\t" << m2 << '\n';
    Matrix<int> m3 = apply(Triple(),m2);
    cout << "m2 after m3 = apply(Triple(),m2):\t" << m2 << '\n';
    cout << "m3:\t\t\t\t\t" << m3 << '\n';
}
catch (exception& e) {
    cerr << "Exception: " << e.what() << '\n';
}
catch (...) {
    cerr << "Exception\n";
}

Add Chapter 24, exercise 2

Add Chapter 24, exercise 2


/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * 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 "logging.h"

#include "runtime.h"
#include "utils.h"

LogMessage::~LogMessage() {
  if (errno_ != -1) {
    buffer_ << ": " << strerror(errno_);
  }
  std::string msg(buffer_.str());
  if (msg.find('\n') == std::string::npos) {
    LogLine(msg.c_str());
  } else {
    msg += '\n';
    size_t i = 0;
    while (i < msg.size()) {
      size_t nl = msg.find('\n', i);
      msg[nl] = '\0';
      LogLine(&msg[i]);
      i = nl + 1;
    }
  }

  if (severity_ == FATAL) {
    art::Runtime::Abort(file_, line_number_);
  }
}

std::ostream& LogMessage::stream() {
  return buffer_;
}

Add missing file from last commit.

Add missing file from last commit.

Change-Id: Ia2b35a812b6787f27ec0c2935cd637a177caa92e


#include "lib/list.cpp"

using namespace std;

ListNode* swapNodes(ListNode* head) {
    if (head == NULL || head->next == NULL) {
        return head;
    }

    ListNode* fakeHead = new ListNode(0);
    fakeHead->next = head;

    ListNode* prev = fakeHead;
    ListNode* current = head;
    ListNode* temp;
    while (current != NULL && current->next != NULL) {
        temp = current->next->next;
        prev->next = current->next;
        current->next->next = current;
        current->next = temp;

        prev = current;
        current = temp;
    }

    head = fakeHead->next;

    return head;
}

int main() {
    ListNode *head, *second, *third, *fourth, *fifth, *newHead, *temp;

    // Normal List
    cout << endl << "Normal List with odd elements" << endl << endl;
    head = new ListNode(10);
    second = new ListNode(20);
    third = new ListNode(30);
    fourth = new ListNode(40);
    fifth = new ListNode(50);
    head->next = second;
    second->next = third;
    third->next = fourth;
    fourth->next = fifth;

    newHead = swapNodes(head);
    temp = newHead;
    while (temp != NULL) {
        cout << temp->val << endl;
        temp=temp->next;
    }

    // Normal List
    cout << endl << "Normal List with even elements" << endl << endl;
    head = new ListNode(10);
    second = new ListNode(20);
    third = new ListNode(30);
    fourth = new ListNode(40);
    head->next = second;
    second->next = third;
    third->next = fourth;

    newHead = swapNodes(head);
    temp = newHead;
    while (temp != NULL) {
        cout << temp->val << endl;
        temp=temp->next;
    }

    // NULL head
    cout << endl << "NULL head" << endl << endl;
    head = NULL;
    newHead = swapNodes(head);
    temp = newHead;
    while (temp != NULL) {
        cout << temp->val << endl;
        temp=temp->next;
    }

    // Only one element
    cout << endl << "Single head" << endl << endl;
    head = new ListNode(10);
    head->next = NULL;
    newHead = swapNodes(head);
    temp = newHead;
    while (temp != NULL) {
        cout << temp->val << endl;
        temp=temp->next;
    }

    return 0;
}

Swap nodes in a pair

Swap nodes in a pair


/**
 * @file TestDistField.cpp
 * @brief Unit test of DistField class
 * @author cromod
 * @date september 2015
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE TestDistField
#include <boost/test/unit_test.hpp>
#include <iostream>
#include "DistField.hpp"
#include "Exception.hpp"

using namespace Cromod::GeomAPI ;
using namespace Cromod::FieldAPI ;
using namespace Cromod::Tools ;
using namespace std ;

BOOST_AUTO_TEST_CASE( BasicTests )
{
    cout << "<<< Starting TestDistField >>>" << endl;

    cout << "- Default constructor test" << endl;
    try {
        DistField distfield;
    }
    catch(...) {
        BOOST_FAIL("Default constructor failure");
    }

    cout << "- Copy constructor test" << endl;
    DistField distfield;
    try {
        DistField new_distfield(distfield);
    }
    catch(...) {
        BOOST_FAIL("Copy constructor failure");
    }

    cout << "- Constructor test" << endl;
    Mesh mesh;
    try {
        DistField new_distfield(mesh);
    }
    catch(...) {
        BOOST_FAIL("Constructor failure");
    }

}

BOOST_AUTO_TEST_CASE( MethodTests )
{
    double listVal[13][2] = {{200.,-100.},{200.,50.},{150.,100.},{100.,100.},{100.,200.},{-100.,200.},{-100.,100.},
                                         {-200.,100.},{-200.,-100.},{-100.,-100.},{-100.,-200.},{100.,-200.},{100.,-100.}};
    vector<Point> listPoints;
    for(int i=0; i<13; i++) {
        Point point(listVal[i],2);
        listPoints.push_back(point);
    }
    Polygon polygon(listPoints);

    Mesh mesh;
    mesh.setPolygon(polygon);
    mesh.setStep(10.);
    mesh.setInitGrid();
    mesh.detectNode();

    double ptA[] = {200.,50.};
    double ptB[] = {150.,100.};
    Point pointA(ptA,2);
    Point pointB(ptB,2);
    Segment segment(pointA,pointB);

    DistField distfield(mesh);
    cout << "- setBoundaryCondition test" << endl;
    distfield.setBoundaryCondition(segment);
    cout << "- initialize test" << endl;
    distfield.initialize();
    cout << "- compute test" << endl;
    distfield.compute();
    cout << "- interpolate test" << endl;
    cout << "  distance = " << distfield.interpolate(75.,75.) << endl;

    cout << "<<< End of TestDistField >>>" << endl;
}

Add unit test of DistField class

Add unit test of DistField class


#include <iostream>
#include <cmath>

using namespace std;

int main() {
    cout << uppercase << hexfloat;
    cout << sqrt(2) << endl;
    return 0;
}

Add solution for chapter 17 test 35

Add solution for chapter 17 test 35


class Solution {
public:
    bool areAlmostEqual(string s1, string s2) {
        size_t index = 0, count = 0;
        std::vector<size_t> arr;
        while (index < s1.size()) {
            if (s1[index] != s2[index]) {
                ++count;
                if (count > 2)
                    return false;
                arr.emplace_back(index);
            }
            ++index;
        }
        if (count == 0)
            return true;
        if (count == 1)
            return false;
        if (s1[arr[0]] == s2[arr[1]] && s1[arr[1]] == s2[arr[0]])
            return true;
        return false;
    }
};

Check if One String Swap Can Make Strings Equal


//------------------------------------------------------------------------------
//  Clock.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Clock.h"
#if ORYOL_EMSCRIPTEN
#include <emscripten/emscripten.h>
#else
#include <chrono>
#endif

namespace Oryol {
namespace Time {

//------------------------------------------------------------------------------
TimePoint
Clock::Now() {
    #if ORYOL_EMSCRIPTEN
    // get int64 time in nanosecs (emscripten_now is ms)
    int64 t = int64(emscripten_get_now() * 1000 * 1000);
    #else
    using namespace std;
    chrono::time_point<chrono::high_resolution_clock, chrono::nanoseconds> now = chrono::high_resolution_clock::now();
    int64 t = now.time_since_epoch().count();
    #endif
    return TimePoint(t);
}

} // namespace Clock
} // namespace Oryol

//------------------------------------------------------------------------------
//  Clock.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Clock.h"
#if ORYOL_EMSCRIPTEN
#include <emscripten/emscripten.h>
#elif ORYOL_WINDOWS
#include <Windows.h>
#include <atomic>
#else
#include <chrono>
#endif

namespace Oryol {
namespace Time {

//------------------------------------------------------------------------------
TimePoint
Clock::Now() {
    #if ORYOL_EMSCRIPTEN
    // get int64 time in nanosecs (emscripten_now is ms)
    int64 t = int64(emscripten_get_now() * 1000 * 1000);
    #elif ORYOL_WINDOWS
    // VisualStudio2013's chrono::high_resolution_clock isn't actually high_resolution
    LARGE_INTEGER perfCount;
    static LARGE_INTEGER perfFreq;
    static std::atomic_flag perfFreqValid{ false };
    if (!perfFreqValid.test_and_set())
    {
        QueryPerformanceFrequency(&perfFreq);
    }
    QueryPerformanceCounter(&perfCount);
    int64 t = (perfCount.QuadPart * 1000000000) / perfFreq.QuadPart;
    #else
    using namespace std;
    chrono::time_point<chrono::high_resolution_clock, chrono::nanoseconds> now = chrono::high_resolution_clock::now();
    int64 t = now.time_since_epoch().count();
    #endif
    return TimePoint(t);
}

} // namespace Clock
} // namespace Oryol

Use QueryPerformanceCounter on Windows instead of std::chrono::high_frequency_clock, since this has only 1ms accuracy in VS2013


// RUN: %clang_cc1 -verify -Wunused -Wused-but-marked-unused -fsyntax-only %s

namespace ns_unused { typedef int Int_unused __attribute__((unused)); }
namespace ns_not_unused { typedef int Int_not_unused; }

void f() {
  ns_not_unused::Int_not_unused i1; // expected-warning {{unused variable}}
  ns_unused::Int_unused i0; // expected-warning {{'Int_unused' was marked unused but was used}}
}

Add missing test from r163874.

Add missing test from r163874.

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


// 237. Delete Node in a Linked List
/**
 * Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
 *
 * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4
 * after calling your function.
 *
 * Tags: Linked List
 *
 * Similar Problems: (E) Remove Linked List Elements
 *
 * 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:
    void deleteNode(ListNode* node) {
        *node = *(node->next);

        // equivalent to copy the values:
        // node->val = node->next->val;
        // node->next = node->next->next;
        return;
    }
};

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

    return 0;
}

Add Solution for 237 Delete Node in a Linked List


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

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

BOOST_AUTO_TEST_SUITE(FirstSuite)

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

BOOST_AUTO_TEST_SUITE_END()

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

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

BOOST_AUTO_TEST_SUITE(FirstSuite)

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

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

BOOST_AUTO_TEST_SUITE_END()

Change unit test for JPetTaskLoader.

Change unit test for JPetTaskLoader.

Former-commit-id: 1cbaa59c1010a96926acec93a2e313f482e62943


#include "Halide.h"

using namespace Halide;
using namespace Halide::Internal;

int main() {
    Var x("x"), y("y");
    Func f("f"), g("g"), h("h");
    f(x, y) = x + y;
    g(x, y) = 5;
    h(x, y) = f(x, y) + g(x, y);

    f.compute_root();
    f.in(g).compute_root();

    // This should cause an error since f.in(g) was called but 'f' is
    // never used in 'g'.
    h.realize(5, 5);

    return 0;
}

Add error test for func wrapper

Add error test for func wrapper


// Copyright 2012-2013 Samplecount S.L.
//
// 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.

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-private-field"
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#pragma GCC diagnostic pop

#include "Methcla/Utility/MessageQueue.hpp"
#include "Methcla/Utility/Semaphore.hpp"

#include <atomic>

TEST_CASE("Methcla/Utility/Worker", "Check for queue overflow.")
{
    struct Command
    {
        void perform() { }
    };

    const size_t queueSize = 1024;

    Methcla::Utility::Worker<Command> worker(queueSize);

    for (size_t i=0; i < worker.maxCapacity(); i++) {
        worker.sendToWorker(Command());
    }

    REQUIRE_THROWS(worker.sendToWorker(Command()));
}

TEST_CASE("Methcla/Utility/WorkerThread", "Check that all commands pushed to a worker thread are executed.")
{
    struct Command
    {
        void perform()
        {
            (*m_count)++;
            m_sem->post();
        }

        std::atomic<size_t>* m_count;
        Methcla::Utility::Semaphore* m_sem;
    };

    const size_t queueSize = 1024;

    for (size_t threadCount=1; threadCount <= 4; threadCount++) {
        Methcla::Utility::WorkerThread<Command> worker(queueSize, threadCount);

        std::atomic<size_t> count(0);
        Methcla::Utility::Semaphore sem;

        for (size_t i=0; i < worker.maxCapacity(); i++) {
            Command cmd;
            cmd.m_count = &count;
            cmd.m_sem = &sem;
            worker.sendToWorker(cmd);
        }

        for (size_t i=0; i < worker.maxCapacity(); i++) {
            sem.wait();
        }
        REQUIRE(count.load() == worker.maxCapacity());
    }
}

Add some tests for worker thread implementation


#include <iostream>
#include <cstring>
#define MODULO 1000000007
#define MAX 1001
using namespace std;

long long mod_add(long long x, long long y)
{
	return (x + y) % MODULO;
}

long long mod_sub(long long x, long long y)
{
	return (x - y + MODULO) % MODULO;
}

long long mod_mult(long long x, long long y)
{
	return (x * y) % MODULO;
}

long long solve(int n, int  m)
{
	long long single_row[MAX];
	memset(single_row, 0, sizeof(single_row));
	single_row[1] = 1;
	single_row[2] = 2;
	single_row[3] = 4;
	single_row[4] = 8;
	for (int i = 5; i <= m; i++) {
		for (int j = 1; j <= 4; j++) {
			single_row[i] = mod_add(single_row[i], single_row[i - j]);
		}
	}
	long long raw_result[MAX];
	for (int i = 1; i <= m; i++) {
		long long res = 1;
		for (int j = 1; j <= n; j++) {
			res = mod_mult(res, single_row[i]);
		}
		raw_result[i] = res;
	}
	long long result_with_holes[MAX];
	long long final_result[MAX];
	final_result[1] = raw_result[1];
	for (int i = 2; i <= m; i++) {
		final_result[i] = raw_result[i];
		for (int j = 1; j <= i - 1; j++) {
			final_result[i] = mod_sub(final_result[i], mod_mult(final_result[j], raw_result[i - j]));
		}
	}
	return final_result[m];
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int n, m;
		cin >> n >> m;
		cout << solve(n, m) << endl;
	}
	return 0;
}

Add the solution to "Lego Blocks".

Add the solution to "Lego Blocks".


// Chapter 27, exercise 8: write out every character on your keyboard together
// with its integer value; then, write the characters out in the order deter-
// mined by their integer value

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

void print(const string& s)
{
    for (int i = 0; i<s.size(); ++i)
        cout << '\'' << s[i] << "\': " << (int)unsigned char(s[i]) << '\n';
}

bool comp_char(char a, char b)
{
    return unsigned char(a) < unsigned char(b);
}

int main()
{
    string s = R"(+"*%&/()=?`1234567890'^@#|~![]${}><\;:_,.-)";
    s += "QWERTZUIOPASDFGHJKLYXCVBNMqwertzuiopasdfghjklyxcvbnm";
    print(s);
    sort(s.begin(),s.end(),comp_char);
    cout << "\nAnd sorted:\n";
    print(s);
}

Add Chapter 27, exercise 8

Add Chapter 27, exercise 8


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <random>

static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dist(5, 30);
static std::uniform_int_distribution<> negator(0, 1);
static std::uniform_int_distribution<> dir(1, 15);

struct animal {
private:
    int answer;
public:
    animal(): answer(dist(gen)) { /*std::cout << answer << '\n';*/ }
    bool guess(int g) const {
        if(g >= answer) {
            std::cout << "Caught one!\n";
            return true;
        }
        return false;
    }
};

struct player {
private:
    const unsigned max_animals = 20;
    std::vector<animal> animals{max_animals};
    int answer = 0;
    int up = dir(gen);
    int down = dir(gen);
    int left = dir(gen);
    int right = dir(gen);
public:
    player() = default;
    void guess() {
        // get command
        std::string temp;
        std::cin >> temp;

        // update total
        if(temp == "up") {
            answer += negator(gen) ? -up : up;
        }
        else if(temp == "down") {
            answer += negator(gen) ? -down : down;
        }
        else if(temp == "right") {
            answer += negator(gen) ? -right : right;
        }
        else if(temp == "left") {
            answer += negator(gen) ? -left : left;
        }

        if(answer < 0) {
            answer = 0;
        }

        // refresh command values
        up = dir(gen);
        down = dir(gen);
        left = dir(gen);
        right = dir(gen);

        // herd the animals guessed correctly
        animals.erase(std::remove_if(std::begin(animals), std::end(animals), [this](const animal& x) {
            return x.guess(answer);
        }), std::end(animals));
    }

    void status() {
        std::cout << "[" << max_animals - animals.size() << "/" << max_animals << "] animals herded" << std::endl;
    }

    bool won() {
        return animals.empty();
    }
};

int main() {
    player p;
    std::cout << "The animals have escaped! Try to herd them using the four directions:\n";
    std::cout << "- up\n"
                 "- down\n"
                 "- left\n"
                 "- right\n";
    while(true) {
        p.guess();
        p.status();

        if(p.won()) {
            std::cout << "You win!\n";
            return 0;
        }
    }
}

Add alternative game, you know

Add alternative game, you know


// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -emit-llvm -o - %s | FileCheck %s

// PR6141
template<typename T>
struct X {
  X();
  template<typename U> X(X<U>);
  X(const X<T>&);
};

void f(X<int>) { }

struct Y : X<int> { };
struct Z : X<float> { };

// CHECK: define i32 @main()
int main() {
  // CHECK: call void @_ZN1YC1Ev
  // CHECK: call void @_ZN1XIiEC1ERKS0_
  // CHECK: call void @_Z1f1XIiE
  f(Y());
  // CHECK: call void @_ZN1ZC1Ev
  // CHECK: call void @_ZN1XIfEC1ERKS0_
  // CHECK: call void @_ZN1XIiEC1IfEES_IT_E
  // CHECK: call void @_Z1f1XIiE
  f(Z());
}

Add test case for PR6141, which was fixed a few days ago

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


#include <gtest/gtest.h>
#include "tcpserver.hpp"

using namespace OpenSofa;

namespace
{
  TEST(TCPServerTest, CanBeCreated)
  {
    Server * server = new TCPServer();
    delete server;
  }
}

Add test file for tcpserver

Add test file for tcpserver


/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#ifndef __ANDROID__
#error "This file should only be compiled for Android."
#endif

#include <jni/fbjni/References.h>
#include <jni/fbjni/CoreClasses.h>

namespace facebook {
namespace jni {
namespace internal {

static int32_t getApiLevel() {
  auto cls = findClassLocal("android/os/Build$VERSION");
  auto fld = cls->getStaticField<int32_t>("SDK_INT");
  if (fld) {
    return cls->getStaticFieldValue(fld);
  }
  return 0;
}

bool doesGetObjectRefTypeWork() {
  static auto level = getApiLevel();
  return level >= 14;
}

}
}
}

Build first-party C++ deps of OSS React Native with Buck

Reviewed By: sdwilsh

Differential Revision: D2840290

fb-gh-sync-id: 3dd4f7ee83a520d5c01f7864f443a04aa73b35fa


#include <iostream>

void foo() {
    std::cout << __PRETTY_FUNCTION__ << "\n";
    std::cout << " ";
}

template <typename Arg>
void foo(Arg arg) {
    std::cout << __PRETTY_FUNCTION__ << "\n";
    std::cout << arg << " ";
}

template <typename First, typename... Args>
void foo(First first, Args... args) {
    std::cout << __PRETTY_FUNCTION__ << "\n";
    foo(first);
    foo(args...);
}

int main() {
    std::string one = "One";
    const char* two = "Two";
    float three = 3.33333333;

    foo();
    std::cout << std::endl;

    foo(one, two);
    std::cout << std::endl;

    foo(one, two, three);
    std::cout << std::endl;

    foo(1, 2, three, 4, 5.7, 6/2, "lalalala");

    return 0;
}

Add variadic template arguments example in c++17.

Compile with:

g++ -std=c++17 variadic_template_cpp17.cpp -o variadic_template_cpp17


//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "catch.hpp"

#include "dll/conv_layer.hpp"
#include "dll/dense_layer.hpp"
#include "dll/conv_rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/scale_layer.hpp"
#include "dll/mp_layer.hpp"
#include "dll/avgp_layer.hpp"
#include "dll/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("fast/cdbn/sgd/1", "[dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_rbm_desc_square<1, 28, 10, 12, dll::momentum, dll::batch_size<10>, dll::weight_type<float>>::layer_t,
            dll::rbm_desc<12 * 12 * 10, 10, dll::momentum, dll::batch_size<10>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
        dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    //dbn->pretrain(dataset.training_images, 20);

    //auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50);
    //std::cout << "ft_error:" << ft_error << std::endl;
    //CHECK(ft_error < 5e-2);

    //auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    //std::cout << "test_error:" << test_error << std::endl;
    //REQUIRE(test_error < 0.2);
}

Prepare test case for dbn_fast

Prepare test case for dbn_fast


//===----------------------------------------------------------------------===//
//
//                     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.
//
//===----------------------------------------------------------------------===//

// <list>

// template <class T, class Alloc>
//   void swap(list<T,Alloc>& x, list<T,Alloc>& y);

#if _LIBCPP_DEBUG2 >= 1
#define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0))
#endif

#include <list>
#include <cassert>

#include <__debug>

int main()
{
#if _LIBCPP_DEBUG2 >= 1
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::list<int> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
        std::list<int> c2(a2, a2+sizeof(a2)/sizeof(a2[0]));
        std::list<int>::iterator i1 = c1.begin();
        std::list<int>::iterator i2 = c2.begin();
        swap(c1, c2);
        c1.erase(i2);
        c2.erase(i1);
        std::list<int>::iterator j = i1;
        c1.erase(i1);
        assert(false);
    }
#endif
}

Fix bug in __libcpp_db::__iterator_copy.  Add debug test for swaping lists.

git-svn-id: 273b07cebdae5845b4a75aae04570b978db9eb50@178892 91177308-0d34-0410-b5e6-96231b3b80d8


#include "listener.h"
#include "log.h"
#include "buffers.h"

void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
        int messageSize) {
    if(queue_available(queue) < messageSize + 1) {
            debug("Dropped incoming CAN message -- send queue full\r\n");
            return;
    }

    for(int i = 0; i < messageSize; i++) {
        QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
    }
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
}

void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
    // TODO the more we enqueue here, the slower it gets - cuts the rate by
    // almost half to do it with 2 queues. we could either figure out how to
    // share a queue or make the enqueue function faster. right now I believe it
    // enqueues byte by byte, which could obviously be improved.
    if(listener->usb->configured) {
        conditionalEnqueue(&listener->usb->sendQueue, message, messageSize);
    } else {
        conditionalEnqueue(&listener->serial->sendQueue, message, messageSize);
    }
}

void processListenerQueues(Listener* listener) {
    // Must always process USB, because this function usually runs the MCU's USB
    // task that handles SETUP and enumeration.
    processInputQueue(listener->usb);
    if(!listener->usb->configured) {
        processInputQueue(listener->serial);
    }
}

#include "listener.h"
#include "log.h"
#include "buffers.h"

void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
        int messageSize) {
    if(queue_available(queue) < messageSize + 2) {
            debug("Dropped incoming CAN message -- send queue full\r\n");
            return;
    }

    for(int i = 0; i < messageSize; i++) {
        QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
    }
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r');
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
}

void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
    // TODO the more we enqueue here, the slower it gets - cuts the rate by
    // almost half to do it with 2 queues. we could either figure out how to
    // share a queue or make the enqueue function faster. right now I believe it
    // enqueues byte by byte, which could obviously be improved.
    if(listener->usb->configured) {
        conditionalEnqueue(&listener->usb->sendQueue, message, messageSize);
    } else {
        conditionalEnqueue(&listener->serial->sendQueue, message, messageSize);
    }
}

void processListenerQueues(Listener* listener) {
    // Must always process USB, because this function usually runs the MCU's USB
    // task that handles SETUP and enumeration.
    processInputQueue(listener->usb);
    if(!listener->usb->configured) {
        processInputQueue(listener->serial);
    }
}

Use \r in messages so they look decent in serial output.


//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>

namespace boost {

void throw_exception(std::exception const & e){
    throw e;
}

} // namespace boost

Fix glitch with Clang and boost

Fix glitch with Clang and boost


#include "command.h"
#include "timer.h"

#include <ctime>
#include <unistd.h>

using namespace MR;
using namespace App;

void usage ()
{
  DESCRIPTION
    + "test timer interface";

  REQUIRES_AT_LEAST_ONE_ARGUMENT = false;
}

void run ()
{

  Timer timer;

  CONSOLE ("printing Timer::current_time() at 10ms intervals:");
  for (size_t n = 0; n < 10; ++n) {
    CONSOLE ("  current timestamp: " + str(Timer::current_time(), 16)
        + " (from C time(): " + str(time(NULL)) + ")");
    usleep (10000);
  }

  CONSOLE ("execution took " + str(timer.elapsed()) + " seconds");
  timer.start();

  CONSOLE ("testing IntervalTimer with 10 x 0.2s intervals:");
  IntervalTimer itimer (0.2);
  for (size_t n = 0; n < 10; ++n) {
    while (!itimer);
    CONSOLE ("  tick");
  }

  CONSOLE ("execution took " + str(timer.elapsed()) + " seconds");
}

Add command to test timer (to be deleted on next commit)


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

void choice(int);
int choice(bool);

void test() {
  // Result of ! must be type bool.
  int i = choice(!1);
}

Add missing test case for operator ! result type.

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


#include <iostream>
#include <random>

#define MAX_NUM_ROWS 10
#define NUM_ITERS 1000
#define BLOCK_SIZE 512 // cache line size in bits.
#define NUM_BLOCKS 10000
#define NUM_DOCS BLOCK_SIZE * NUM_BLOCKS

// DESIGN NOTE: tried using go, but the publicly available binomial rng is approximately 10x slower.
// TODO: change conventions to match BitFunnel coding conventions.

int run_once(std::mt19937& gen, std::binomial_distribution<int>& base_dist, int num_rows) {
    int num_accesses;

    // TODO: reduce int to int16_t?
    // TODO: check to see if doing these allocations inside run_once matters for performance.
    // We could hoist this out and just clear the vectors in here.
    std::vector<std::vector<int>> universe(num_rows, std::vector<int>(NUM_BLOCKS));
    for (int j = 0; j < universe[0].size(); ++j) {
        universe[0][j] = base_dist(gen);
        ++num_accesses;
    }

    for (int i = 1; i < universe.size(); ++i) {
        for (int j = 0; j < universe[0].size(); ++j) {
            if (universe[i-1][j] == 0) {
                universe[i][j] = 0;
            } else {
                ++num_accesses;
                int row_num_set = base_dist(gen);
                float previous_fraction = static_cast<float>(universe[i-1][j]) / 512.0;
                std::binomial_distribution<int> intersection_dist(row_num_set,previous_fraction);
                universe[i][j] = intersection_dist(gen);
            }
        }
    }
    return num_accesses;
}

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::binomial_distribution<int> base_dist(511, 0.2);

    for (int i = 2; i < MAX_NUM_ROWS; ++i) {
        for (int j = 0; j < NUM_ITERS; ++j) {
            std::cout << run_once(gen, base_dist, i) << ",";
        }
        std::cout << std::endl;
    }
    return 0;
}

Add initial 5-minute hack simulation script.


// Chapter 21, Exercise 6: implement the Fruit example (set) using a
// set<Fruit*,Fruit_comparison> (pointers instead of copies), i.e., define a
// comparison operation for Fruit*

#include "../lib_files/std_lib_facilities.h"
#include<set>

//------------------------------------------------------------------------------

struct Fruit {
    string name;
    int count;
    double unit_price;
    Fruit(string n, int c, double up = 0.0)
        :name(n), count(c), unit_price(up) { }
};

//------------------------------------------------------------------------------

ostream& operator<<(ostream& os, const Fruit* f)
{
    os << setw(7) << left << f->name;
    os << f->count << '\t' << f->unit_price;
    return os;
}

//------------------------------------------------------------------------------

struct Fruit_comparison {
    bool operator()(const Fruit* a, const Fruit* b) const
    {
        return a->name < b->name;
    }
};

//------------------------------------------------------------------------------

int main()
try {
    set<Fruit*,Fruit_comparison> inventory;
    inventory.insert(new Fruit("Quince",5));    // test default parameter
    inventory.insert(new Fruit("Apple",200,0.37));
    inventory.insert(new Fruit("Orange",150,0.45));
    inventory.insert(new Fruit("Grape",13,0.99));
    inventory.insert(new Fruit("Kiwi",512,1.15));
    inventory.insert(new Fruit("Plum",750,2.33));

    typedef set<Fruit*,Fruit_comparison>::const_iterator Si;
    for (Si p = inventory.begin(); p!=inventory.end(); ++p) cout << *p << '\n';

    // Clean up
    for (Si p = inventory.begin(); p!=inventory.end(); ++p) delete *p;
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

//------------------------------------------------------------------------------

Add Chapter 21, exercise 6

Add Chapter 21, exercise 6


#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;
}

void leftViewUtil(NODE* root, int level, int* max_level) {
  if (root == nullptr) return;

  printf("level : [%d] max_level : [%d] \n", level, *max_level);
  if (*max_level < level) {
    printf("%d \n", root->data);
    *max_level = level;
  }

  leftViewUtil(root->left, level + 1, max_level);
  leftViewUtil(root->right, level + 1, max_level);
}

void leftView(NODE* root) {
  int max_level = 0;
  leftViewUtil(root, 1, &max_level);
}

int main(int argc, char const* argv[]) {
  NODE* root = newNode(12);
  root->left = newNode(10);
  root->right = newNode(30);
  root->right->left = newNode(25);
  root->right->right = newNode(40);

  leftView(root);
  return 0;
}

Print Left View of the tree.

Print Left View of the tree.


#include "base64inputstream.h"
#include <stdio.h>
using namespace jstreams;
using namespace std;

int
main(int argc, char** argv) {
   for (int i=1; i<argc; ++i) {
       string out = Base64InputStream::decode(argv[i], strlen(argv[i]));
       printf("%s\n", out.c_str());
   }
   return 0;
}

Add small test program for base64 decoding.

svn path=/trunk/playground/base/strigi/; revision=612338


#include <iostream>
#include <stack>

using std::cout;
using std::endl;
using std::stack;

class Queue {
    stack<int> stackIn, stackOut;

    void transfer() {
      while (!stackIn.empty()) {
        stackOut.push(stackIn.top());
        stackIn.pop();
      }
    }
public:

    bool empty() {
      return stackIn.empty() && stackOut.empty();
    }

    int front() {
      if (stackOut.empty()) {
        transfer();
      }

      return stackOut.top();
    }

    void pop() {
      if (stackOut.empty()) {
        transfer();
      }

      stackOut.pop();
    }

    void push(int n) {
      stackIn.push(n);
    }

};

int main() {
  Queue q;

  q.push(1);
  q.push(2);

  cout << q.front() << endl;
  q.pop();

  q.push(3);

  cout << q.front() << endl;
  q.pop();

  q.push(4);
  q.push(5);
  q.push(6);

  cout << q.front() << endl;
  q.pop();

  cout << q.front() << endl;
  q.pop();

  cout << q.front() << endl;
  q.pop();

  cout << q.front() << endl;
  q.pop();

  return 0;
}

Add queue implemented with 2 stacks

Add queue implemented with 2 stacks


// 141 Linked List Cycle
/**
* Given a linked list, determine if it has a cycle in it.
*
* Follow up:
* Can you solve it without using extra space?
*
* Tag:     Linked List, Two Pointers
*
* Author:  Yanbin Lu
*/

#include <stddef.h>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>

using namespace std;
struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow) return true;
        }
        return false;
    }
};

int main()
{
	// creat a cycle list
	ListNode* list = new ListNode(3);
	list->next = new ListNode(2);
	list->next->next = new ListNode(1);
	list->next->next->next = new ListNode(4);
	list->next->next->next->next = list;

	Solution* sol = new Solution();
	cout<<sol->hasCycle(list)<<std::endl;

	char c;
	std::cin>>c;

	return 0;
}

Add 141 Linked List Cycle

Add 141 Linked List Cycle


// RUN: rm -rf %T/coverage-basic
// RUN: mkdir %T/coverage-basic && cd %T/coverage-basic
// RUN: %clangxx_asan -fsanitize-coverage=1 %s -o test.exe
// RUN: env ASAN_OPTIONS=coverage=1 %run test.exe
//
// RUN: %sancov print *.sancov | FileCheck %s
#include <stdio.h>

void foo() { fprintf(stderr, "FOO\n"); }
void bar() { fprintf(stderr, "BAR\n"); }

int main(int argc, char **argv) {
  if (argc == 2) {
    foo();
    bar();
  } else {
    bar();
    foo();
  }
}

// CHECK: 0x{{[0-9a-f]*}}
// CHECK: 0x{{[0-9a-f]*}}
// CHECK: 0x{{[0-9a-f]*}}
// CHECK-NOT: 0x{{[0-9a-f]*}}

[ASan/Win] Add a test that makes sure coverage works at least in the simple cases

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


/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if (!head) return nullptr;
        Node* temp = head;
        while (temp) {
            Node *node = new Node(temp->val);
            node->next = temp->next;
            temp->next = node;
            temp = node->next;
        }
        temp = head;
        while (temp) {
            temp->next->random = (temp->random) ? temp->random->next : nullptr;
            temp = temp->next->next;
        }
        Node* dummy = head->next;
        temp = head->next;
        while (head) {
            head->next = temp->next;
            head = head->next;
            if (!head) break;
            temp->next = head->next;
            temp = temp->next;
        }
        return dummy;
    }
};

Copy List with Random Pointer

Copy List with Random Pointer


// 454. 4Sum II
/**
 * Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
 *
 * To make problem a bit easier, all A, B, C, D have same length of N where 0 <= N <= 500. All integers are in the range of -2^28 to 2^28 - 1
 * and the result is guaranteed to be at most 2^31 - 1.
 *
 * Example:
 *
 * Input:
 * A = [ 1, 2]
 * B = [-2,-1]
 * C = [-1, 2]
 * D = [ 0, 2]
 *
 * Output:
 * 2
 *
 * Explanation:
 * The two tuples are:
 * 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
 * 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
 *
 * Tags: Binary Search, Hash Table
 *
 * Similar Problems: (M) 4Sum
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        int n = A.size();

        // only count is needed, use a hash map for faster search
        unordered_map<int, int> map;

        int sum = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                sum = -(A[i] + B[j]);
                map[sum]++; // create hash map using the -sum of A and B
            }
        }

        int res = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                sum = C[i] + D[j];
                if (map.find(sum) != map.end()) // look up in hash map using the sum of C and D
                    res += map[sum];
            }
        }

        return res;
    }
};

int main()
{
    vector<int> A = {1, 2};
    vector<int> B = {-2, -1};
    vector<int> C = {-1, 2};
    vector<int> D = {0, 2};
    Solution sol;
    int res = sol.fourSumCount(A, B, C, D);
    cout << res << endl;
    cin.get();

    return 0;
}

Add Solution for 454 4Sum II

Add Solution for 454 4Sum II


/*
 * Copyright 2010, NagaChaitanya Vellanki
 *
 * Author NagaChaitanya Vellanki
 *
 * Print k digits of decimal representation of 1/n for n > 1
 */

#include <inttypes.h>
#include <iostream>
#include <cstdlib>

using namespace std;

int main() {
  int32_t n = 0;
  int32_t k = 1;

  cout << "Enter n(n > 1) and number of digits k (k >= 1)" << endl;
  cin >> n >> k;

  if((n <= 1) || (k < 1)) {
    exit(0);
  }

  int32_t i = 0;
  int32_t rem = 1;
  while(i < k) {
    cout << (10 * rem) / n;
    rem = (10 * rem) % n;
    i++;
  }

  return 0;
}

Add Printing k digits of 1/n

Add Printing k digits of 1/n


#include <iostream>
#include <cstring>

using namespace std;

class Ticket {
    int seat;
    int price;

public:

    Ticket(int _seat) : seat(_seat) {
        if (seat >= 1 && seat <= 30)
            price = 70;
        else if (seat >= 31 && seat <= 70)
            price = 55;
        else if (seat >= 71 && seat <= 100)
            price = 30;
        else if (seat >= 101 && seat <= 150)
            price = 15;
        else
            price = 0;
    }

    int getSeat() {
        return seat;
    }

    int getPrice() {
        return price;
    }

    void print() {
        cout << "Seat " << seat << " with price " << price << endl;
    }
};

class Guest {
    char name[32];
    Ticket ticket;

public:

    Guest(const char _name[], Ticket _ticket) : ticket(_ticket) {
        strcpy(name, _name);
    }

    bool receivesGift() {
        return ticket.getSeat() >= 1 && ticket.getSeat() <= 30;
    }

    void print() {
        cout << "Name: " << name << endl;
        ticket.print();
    }
};

int main() {
    Guest guests[5] = {
        Guest("Ivan", Ticket(2)),
        Guest("Ivanko", Ticket(29)),
        Guest("Georgi", Ticket(58)),
        Guest("Petar", Ticket(102)),
        Guest("Yordan", Ticket(17))
    };

    for (int i = 0; i < 5; i++)
        if (guests[i].receivesGift())
            guests[i].print();

    return 0;
}

Add sample solution to the first problem for the first test


/*
 * This test demonstrates that putting a console into selection mode does not
 * block the low-level console APIs, even though it blocks WriteFile.
 */

#define _WIN32_WINNT 0x0501
#include "../Shared/DebugClient.cc"
#include <windows.h>
#include <stdio.h>

const int SC_CONSOLE_MARK = 0xFFF2;

CALLBACK DWORD writerThread(void*)
{
  CHAR_INFO xChar, fillChar;
  memset(&xChar, 0, sizeof(xChar));
  xChar.Char.AsciiChar = 'X';
  xChar.Attributes = 7;
  memset(&fillChar, 0, sizeof(fillChar));
  fillChar.Char.AsciiChar = ' ';
  fillChar.Attributes = 7;
  COORD oneCoord = { 1, 1 };
  COORD zeroCoord = { 0, 0 };

  while (true) {
    SMALL_RECT writeRegion = { 5, 5, 5, 5 };
    WriteConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
                       &xChar, oneCoord,
                       zeroCoord,
                       &writeRegion);
    Sleep(500);
    SMALL_RECT scrollRect = { 1, 1, 20, 20 };
    COORD destCoord = { 0, 0 };
    ScrollConsoleScreenBuffer(GetStdHandle(STD_OUTPUT_HANDLE),
                              &scrollRect,
                              NULL,
                              destCoord,
                              &fillChar);
  }
}

int main()
{
  CreateThread(NULL, 0, writerThread, NULL, 0, NULL);
  Trace("marking console");
  HWND hwnd = GetConsoleWindow();
  PostMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);

  Sleep(2000);

  Trace("reading output");
  CHAR_INFO buf[1];
  COORD bufSize = { 1, 1 };
  COORD zeroCoord = { 0, 0 };
  SMALL_RECT readRect = { 0, 0, 0, 0 };
  ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
		    buf,
		    bufSize,
		    zeroCoord,
		    &readRect);
  Trace("done reading output");

  Sleep(2000);

  PostMessage(hwnd, WM_CHAR, 27, 0x00010001);

  Sleep(1100);

  return 0;
}

Add another windows test case.

Add another windows test case.


// 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 "base/android/jni_registrar.h"

#include "base/logging.h"
#include "base/android/jni_android.h"

namespace base {
namespace android {

bool RegisterNativeMethods(JNIEnv* env,
                           const RegistrationMethod* method,
                           size_t count) {
  const RegistrationMethod* end = method + count;
  while (method != end) {
    if (!method->func(env) < 0) {
      DLOG(ERROR) << method->name << " failed registration!";
      return false;
    }
    method++;
  }
  return true;
}

}  // namespace android
}  // namespace base

// 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 "base/android/jni_registrar.h"

#include "base/logging.h"
#include "base/android/jni_android.h"

namespace base {
namespace android {

bool RegisterNativeMethods(JNIEnv* env,
                           const RegistrationMethod* method,
                           size_t count) {
  const RegistrationMethod* end = method + count;
  while (method != end) {
    if (!method->func(env)) {
      DLOG(ERROR) << method->name << " failed registration!";
      return false;
    }
    method++;
  }
  return true;
}

}  // namespace android
}  // namespace base

Fix Android RegisterNativeMethods failure logic

Function returns bool, so !func(env) should be enough. The < 0 check is
probably leftover crud when upstreamed.

BUG=

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

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


#include "cell_refine.hpp"

#include <viennagrid/algorithm/refine.hpp>

/***************
 * CELL_REFINE *
 ***************/

// Triangular

tuple TriangularCartesian2D_Domain_cell_refine(TriangularCartesian2D_Domain domain_in, TriangularCartesian2D_Segmentation segmentation_in, bool (*predicate)(const TriangularCartesian2D_Cell &))
{
	TriangularCartesian2D_Domain          domain_out;
	TriangularCartesian2D_Segmentation    segmentation_out(domain_out);

	// Vector of marks/flags that indicate which cells should be refined

	CellRefinementFlagContainerType     cell_refinement_flag_container;

	viennagrid::result_of::field<CellRefinementFlagContainerType,
	                             TriangularCartesian2D_Cell_t>::type    cell_refinement_flag_field(cell_refinement_flag_container);

	// Marks which edges should be refined
	TriangularCartesian2D_CellRange_t cells = viennagrid::elements(domain_in.get_domain());
	for (TriangularCartesian2D_CellRange_t::iterator it = cells.begin();
		                                         it != cells.end();
		                                       ++it)
	{
		if (predicate(TriangularCartesian2D_Cell(*it)))
			cell_refinement_flag_field(*it) = true;
	}

	// Refine marked edges
	viennagrid::cell_refine(domain_in.get_domain(),
	                        segmentation_in.get_segmentation(),
	                        domain_out.get_domain(),
	                        segmentation_out.get_segmentation(),
	                        cell_refinement_flag_field);

	// Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation)
	return make_tuple<TriangularCartesian2D_Domain, TriangularCartesian2D_Segmentation>(domain_out, segmentation_out);
}

Implement cell-refinement of triangular cartesian 2D cells.


//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "dll_test.hpp"

#include "dll/dense_layer.hpp"
#include "dll/scale_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("dbn/ae/1", "[rbm][dbn][mnist][sgd][ae]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 28 * 28, dll::momentum, dll::batch_size<25>>::rbm_t
        >, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->pretrain(dataset.training_images, 50);

    dbn->learning_rate = 0.1;

    auto ft_error = dbn->fine_tune_ae(dataset.training_images, 50);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set_ae(*dbn, dataset.test_images);
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.1);
}

Add test for autoencoder with RBM pretraining


// 6. ZigZag Conversion
/**
 * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
 * (you may want to display this pattern in a fixed font for better legibility)
 *
 * P   A   H   N
 * A P L S I I G
 * Y   I   R
 *
 * And then read line by line: "PAHNAPLSIIGYIR"
 * Write the code that will take a string and make this conversion given a number of rows:
 *
 * string convert(string text, int nRows);
 *
 * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 *
 * Tags: String
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows <= 1) {
            return s;
        }

        string res;

        // P   | A   | H   | N
        // A P | L S | I I | G
        // Y   | I   | R   |
        // each row has 2 elements except the first row and the last row in one period
        int period = 2 * numRows - 2;
        for (int i = 0; i < numRows; i++) {         // build each row
            for (int j = i; j < s.size(); j += period) {    // build string in each period
                res += s[j];

                // 0     : 0                            |
                // 1     : 1                   p - 1    |
                // .       .                  .         |
                // .       .                 .          |
                // .       .                .           |
                // i     : j            p - i           |
                // .       .           .                |
                // .       .          .                 |
                // .       .         .                  |
                // n - 2 : n - 2    p - (n - 2)         |
                // n - 1 : n - 1                        |
                // calculate the position of the second element
                int k = j - i + period - i;

                // if not the first or last row append the second element
                if (i != 0 && i != numRows - 1 && k < s.size()) {
                    res += s[k];
                }
            }
        }

        return res;
    }
};

int main() {
    string s = "PAYPALISHIRING";
    Solution sol;
    string res = sol.convert(s, 3);
    cout << res << endl;
    cin.get();

    return 0;
}

Add Solution 006 ZigZag Conversion

Add Solution 006 ZigZag Conversion