Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use the size of the array passed in
#include <stdio.h> #include <stdlib.h> #define MARK_SIZE 8 int read_marks(float marks[]) { char mark[MARK_SIZE]; int c = 0; for (int i = 0; i < 4; i++) { c += 1; printf("mark[%d]: ", i+1); fgets(mark, sizeof(mark), stdin); marks[i] = strtol(mark, NULL, 0); } return c; } float calculate_average(float marks[], int size) { float sum = 0; for (int i = 0; i < 4; i++) sum += marks[i]; return sum / size; }
#include <stdio.h> #include <stdlib.h> #define MARK_SIZE 8 int read_marks(float marks[]) { char mark[MARK_SIZE]; int c = 0; for (int i = 0; i < 4; i++) { c += 1; printf("mark[%d]: ", i+1); fgets(mark, sizeof(mark), stdin); marks[i] = strtol(mark, NULL, 0); } return c; } float calculate_average(float marks[], int size) { float sum = 0; for (int i = 0; i < size; i++) sum += marks[i]; return sum / size; }
Fix warning ('struct gl_context' declared inside parameter list).
/* * Mesa 3-D graphics library * Version: 3.5 * * Copyright (C) 1999-2001 Brian Paul All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef API_LOOPBACK_H #define API_LOOPBACK_H #include "main/compiler.h" #include "main/mfeatures.h" struct _glapi_table; extern void _mesa_loopback_init_api_table(const struct gl_context *ctx, struct _glapi_table *dest); #endif /* API_LOOPBACK_H */
/* * Mesa 3-D graphics library * Version: 3.5 * * Copyright (C) 1999-2001 Brian Paul All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef API_LOOPBACK_H #define API_LOOPBACK_H #include "main/compiler.h" #include "main/mfeatures.h" struct _glapi_table; struct gl_context; extern void _mesa_loopback_init_api_table(const struct gl_context *ctx, struct _glapi_table *dest); #endif /* API_LOOPBACK_H */
Fix test so it works on systems where wchar_t != int.
// RUN: %llvmgcc -S %s -o - | llvm-as -f -o /dev/null typedef int __darwin_wchar_t; typedef __darwin_wchar_t wchar_t; typedef signed short SQLSMALLINT; typedef SQLSMALLINT SQLRETURN; typedef enum { en_sqlstat_total } sqlerrmsg_t; SQLRETURN _iodbcdm_sqlerror( ) { wchar_t _sqlState[6] = { L"\0" }; }
// RUN: %llvmgcc -S %s -o - | llvm-as -f -o /dev/null #include <stddef.h> signed short _iodbcdm_sqlerror( ) { wchar_t _sqlState[6] = { L"\0" }; }
Add token counter and cursor array to connections.
/** * @author Adam Grandquist */ #include "ReQL-ast.h" #ifndef _REQL_H #define _REQL_H struct _ReQL_Conn_s { int socket; int error; char *buf; }; typedef struct _ReQL_Conn_s _ReQL_Conn_t; struct _ReQL_Cur_s { }; typedef struct _ReQL_Cur_s _ReQL_Cur_t; int _reql_connect(_ReQL_Conn_t *conn, unsigned char host_len, char *host, unsigned char port); int _reql_close_conn(_ReQL_Conn_t *conn); _ReQL_Cur_t *_reql_run(_ReQL_Op_t *query, _ReQL_Conn_t *conn, _ReQL_Op_t *kwargs); void _reql_next(_ReQL_Cur_t *cur); void _reql_close_cur(_ReQL_Cur_t *cur); #endif
/** * @author Adam Grandquist */ #include "ReQL-ast.h" #ifndef _REQL_H #define _REQL_H struct _ReQL_Conn_s { int socket; int error; char *buf; unsigned int max_token; struct _ReQL_Cur_s **cursor; }; typedef struct _ReQL_Conn_s _ReQL_Conn_t; struct _ReQL_Cur_s { }; typedef struct _ReQL_Cur_s _ReQL_Cur_t; int _reql_connect(_ReQL_Conn_t *conn, unsigned char host_len, char *host, unsigned char port); int _reql_close_conn(_ReQL_Conn_t *conn); _ReQL_Cur_t *_reql_run(_ReQL_Op_t *query, _ReQL_Conn_t *conn, _ReQL_Op_t *kwargs); void _reql_next(_ReQL_Cur_t *cur); void _reql_close_cur(_ReQL_Cur_t *cur); #endif
Put constructor for FourierTransformFFTW in cc file.
#ifndef BART_SRC_CALCULATOR_FOURIER_FOURIER_TRANSFORM_FFTW_H_ #define BART_SRC_CALCULATOR_FOURIER_FOURIER_TRANSFORM_FFTW_H_ #include "calculator/fourier/fourier_transform_i.h" namespace bart { namespace calculator { namespace fourier { class FourierTransformFFTW : public FourierTransformI { public: FourierTransformFFTW(const int n_samples) : n_samples_(n_samples) {}; int n_samples() const { return n_samples_; } private: const int n_samples_{0}; }; } // namespace fourier } // namespace calculator } // namespace bart #endif //BART_SRC_CALCULATOR_FOURIER_FOURIER_TRANSFORM_FFTW_H_
#ifndef BART_SRC_CALCULATOR_FOURIER_FOURIER_TRANSFORM_FFTW_H_ #define BART_SRC_CALCULATOR_FOURIER_FOURIER_TRANSFORM_FFTW_H_ #include "calculator/fourier/fourier_transform_i.h" namespace bart { namespace calculator { namespace fourier { class FourierTransformFFTW : public FourierTransformI { public: FourierTransformFFTW(const int n_samples); int n_samples() const { return n_samples_; } private: const int n_samples_; }; } // namespace fourier } // namespace calculator } // namespace bart #endif //BART_SRC_CALCULATOR_FOURIER_FOURIER_TRANSFORM_FFTW_H_
Make abs_time() use GetTickCount() on Windows
#ifndef __libcpu_timings_h #define __libcpu_timings_h #ifdef __MACH__ #include <mach/mach_time.h> #define abs_time() mach_absolute_time() #endif #ifdef sun #include <sys/time.h> #define abs_time() gethrtime() #endif #ifdef linux #warning High precission timing currently n/a on Linux // HACK #define abs_time() 0 #endif #endif /* !__libcpu_timings_h */
#ifndef __libcpu_timings_h #define __libcpu_timings_h #ifdef __MACH__ #include <mach/mach_time.h> #define abs_time() mach_absolute_time() #endif #ifdef sun #include <sys/time.h> #define abs_time() gethrtime() #endif #ifdef linux #warning High precission timing currently n/a on Linux // HACK #define abs_time() 0 #endif #ifdef _WIN32 typedef unsigned long DWORD; #define WINAPI __stdcall extern "C" DWORD WINAPI GetTickCount(void); #define abs_time() GetTickCount() #endif #endif /* !__libcpu_timings_h */
Increment the run configuration's reference counter.
/** * Touhou Community Reliant Automatic Patcher * Main DLL * * ---- * * Globals, compile-time constants and runconfig abstractions. */ #include "thcrap.h" CRITICAL_SECTION cs_file_access; json_t* run_cfg = NULL; const char* PROJECT_NAME(void) { return "Touhou Community Reliant Automatic Patcher"; } const char* PROJECT_NAME_SHORT(void) { return "thcrap"; } const DWORD PROJECT_VERSION(void) { return 0x20131025; } const char* PROJECT_VERSION_STRING(void) { static char ver_str[11] = {0}; if(!ver_str[0]) { str_hexdate_format(ver_str, PROJECT_VERSION()); } return ver_str; } json_t* runconfig_get(void) { return run_cfg; } void runconfig_set(json_t *new_run_cfg) { run_cfg = new_run_cfg; } void* runconfig_func_get(const char *name) { json_t *funcs = json_object_get(run_cfg, "funcs"); return (void*)json_object_get_hex(funcs, name); }
/** * Touhou Community Reliant Automatic Patcher * Main DLL * * ---- * * Globals, compile-time constants and runconfig abstractions. */ #include "thcrap.h" CRITICAL_SECTION cs_file_access; json_t* run_cfg = NULL; const char* PROJECT_NAME(void) { return "Touhou Community Reliant Automatic Patcher"; } const char* PROJECT_NAME_SHORT(void) { return "thcrap"; } const DWORD PROJECT_VERSION(void) { return 0x20131025; } const char* PROJECT_VERSION_STRING(void) { static char ver_str[11] = {0}; if(!ver_str[0]) { str_hexdate_format(ver_str, PROJECT_VERSION()); } return ver_str; } json_t* runconfig_get(void) { return run_cfg; } void runconfig_set(json_t *new_run_cfg) { run_cfg = new_run_cfg; json_incref(run_cfg); } void* runconfig_func_get(const char *name) { json_t *funcs = json_object_get(run_cfg, "funcs"); return (void*)json_object_get_hex(funcs, name); }
Fix up the spooldir/lockfile changes that caused a segfault.
/* * (C) 2001 by Matthias Andree */ /* * This file (leafnode-version.c) is public domain. It comes without and * express or implied warranties. Do with this file whatever you wish, but * don't remove the disclaimer. */ #include <stdio.h> #include "leafnode.h" #ifdef WITH_DMALLOC #include <dmalloc.h> #endif #include "config.h" int main(void) { static char env_path[] = "PATH=/bin:/usr/bin"; /* ------------------------------------------------ */ /* *** IMPORTANT *** * * external tools depend on the first line of this output, which is * in the fixed format * version: leafnode-2.3.4... */ fputs("version: leafnode-", stdout); puts(version); /* changable parts below :-) */ fputs("current machine: ", stdout); fflush(stdout); putenv(env_path); if (system("uname -a")) puts(" (error)"); fputs("bindir: ", stdout); puts(bindir); fputs("sysconfdir: ", stdout); puts(sysconfdir); fputs("spooldir: ", stdout); puts(spooldir); fputs("lockfile: ", stdout); puts(lockfile); #ifdef HAVE_IPV6 puts("IPv6: yes"); #else puts("IPv6: no"); #endif fputs("default MTA: ", stdout); puts(DEFAULTMTA); exit(0); }
/* * (C) 2001 by Matthias Andree */ /* * This file (leafnode-version.c) is public domain. It comes without and * express or implied warranties. Do with this file whatever you wish, but * don't remove the disclaimer. */ #include <stdio.h> #include "leafnode.h" #ifdef WITH_DMALLOC #include <dmalloc.h> #endif #include "config.h" int main(void) { static char env_path[] = "PATH=/bin:/usr/bin"; /* ------------------------------------------------ */ /* *** IMPORTANT *** * * external tools depend on the first line of this output, which is * in the fixed format * version: leafnode-2.3.4... */ fputs("version: leafnode-", stdout); puts(version); /* changable parts below :-) */ fputs("current machine: ", stdout); fflush(stdout); putenv(env_path); if (system("uname -a")) puts(" (error)"); fputs("bindir: ", stdout); puts(bindir); fputs("sysconfdir: ", stdout); puts(sysconfdir); fputs("default spooldir: ", stdout); puts(def_spooldir); #ifdef HAVE_IPV6 puts("IPv6: yes"); #else puts("IPv6: no"); #endif fputs("default MTA: ", stdout); puts(DEFAULTMTA); exit(0); }
Fix bug when compiling minizip with C++ [Vollant].
/* Additional tools for Minizip Code: Xavier Roche '2004 License: Same as ZLIB (www.gzip.org) */ #ifndef _zip_tools_H #define _zip_tools_H #ifdef __cplusplus extern "C" { #endif #ifndef _ZLIB_H #include "zlib.h" #endif #include "unzip.h" /* Repair a ZIP file (missing central directory) file: file to recover fileOut: output file after recovery fileOutTmp: temporary file name used for recovery */ extern int ZEXPORT unzRepair(const char* file, const char* fileOut, const char* fileOutTmp, uLong* nRecovered, uLong* bytesRecovered); #endif
/* Additional tools for Minizip Code: Xavier Roche '2004 License: Same as ZLIB (www.gzip.org) */ #ifndef _zip_tools_H #define _zip_tools_H #ifdef __cplusplus extern "C" { #endif #ifndef _ZLIB_H #include "zlib.h" #endif #include "unzip.h" /* Repair a ZIP file (missing central directory) file: file to recover fileOut: output file after recovery fileOutTmp: temporary file name used for recovery */ extern int ZEXPORT unzRepair(const char* file, const char* fileOut, const char* fileOutTmp, uLong* nRecovered, uLong* bytesRecovered); #ifdef __cplusplus } #endif #endif
Fix a typo in remark
/** * \file * \remark This file is part of VITA. * * \copyright Copyright (C) 2018 EOS di Manlio Morini. * * \license * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/ */ #if !defined(VITA_EXCEPTIONS_H) #define VITA_EXCEPTIONS_H #include <stdexcept> namespace vita { /// /// Groups the custom exceptions used in Vita. /// /// There is a separate header because one can ignore custom exception types /// (since they are descendants of `std::exception`) in general case, but can /// alss explicitly include the header and deal with custom exceptions if /// necessary. /// namespace exception { class data_format : public std::runtime_error { using std::runtime_error::runtime_error; }; class insufficient_data : public std::logic_error { using std::logic_error::logic_error; }; } // namespace exception } // namespace vita #endif // include guard
/** * \file * \remark This file is part of VITA. * * \copyright Copyright (C) 2018 EOS di Manlio Morini. * * \license * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/ */ #if !defined(VITA_EXCEPTIONS_H) #define VITA_EXCEPTIONS_H #include <stdexcept> namespace vita { /// /// Groups the custom exceptions used in Vita. /// /// There is a separate header because one can ignore custom exception types /// (since they are descendants of `std::exception`) in general case, but can /// also explicitly include the header and deal with custom exceptions if /// necessary. /// namespace exception { class data_format : public std::runtime_error { using std::runtime_error::runtime_error; }; class insufficient_data : public std::logic_error { using std::logic_error::logic_error; }; } // namespace exception } // namespace vita #endif // include guard
Make the gcc/clang asm keyword available, even when running in standard C mode.
/* Unix sqConfig.h -- platform identification and configuration */ /* This file has been superseded by autoconf for Unix variants. */ #include "config.h" #ifndef UNIX # define UNIX #endif #if !defined(LSB_FIRST) #error "LSB_FIRST is undefined. Used for setting platform endianesness!" #endif #if LSB_FIRST # define VMBIGENDIAN 0 #else # define VMBIGENDIAN 1 #endif #if defined(__GNUC__) /* Define the "don't generate functions with register parameters" attribute * for x86 and similar. Do so for debugging; gdb typically can't call static * functions that have been optimized to use register arguments. */ # if defined(_M_I386) || defined(_X86_) || defined(i386) || defined(i486) || defined(i586) || defined(i686) || defined(__i386__) || defined(__386__) || defined(X86) || defined(I386) /*# define PlatformNoDbgRegParms __attribute__ ((regparm (0)))*/ # endif # define NeverInline __attribute__ ((noinline)) #endif #if defined( __clang__) # define NeverInline __attribute__ ((noinline)) #endif
/* Unix sqConfig.h -- platform identification and configuration */ /* This file has been superseded by autoconf for Unix variants. */ #include "config.h" #ifndef UNIX # define UNIX #endif #if !defined(LSB_FIRST) #error "LSB_FIRST is undefined. Used for setting platform endianesness!" #endif #if LSB_FIRST # define VMBIGENDIAN 0 #else # define VMBIGENDIAN 1 #endif #if defined(__GNUC__) /* Define the "don't generate functions with register parameters" attribute * for x86 and similar. Do so for debugging; gdb typically can't call static * functions that have been optimized to use register arguments. */ # if defined(_M_I386) || defined(_X86_) || defined(i386) || defined(i486) || defined(i586) || defined(i686) || defined(__i386__) || defined(__386__) || defined(X86) || defined(I386) /*# define PlatformNoDbgRegParms __attribute__ ((regparm (0)))*/ # endif # define NeverInline __attribute__ ((noinline)) #endif #if defined( __clang__) # define NeverInline __attribute__ ((noinline)) #endif /* Make the gcc/clang asm keyword available, even when running * in standard C mode. */ #define asm __asm__
Fix to compile on Debian
#ifndef _SERHEX_H_ #define _SERHEX_H_ #include <termios.h> // POSIX terminal control definitions int configure_port(int fd, speed_t st); int open_port(char *port); int send_cmd(char *, uint8_t *, int, uint8_t *); int send_cmd_with_delay(char *, uint8_t *, int, uint8_t *, int); #endif /* _SERHEX_H_ */
#ifndef _SERHEX_H_ #define _SERHEX_H_ #include <termios.h> // POSIX terminal control definitions #include <stdint.h> int configure_port(int fd, speed_t st); int open_port(char *port); int send_cmd(char *, uint8_t *, int, uint8_t *); int send_cmd_with_delay(char *, uint8_t *, int, uint8_t *, int); #endif /* _SERHEX_H_ */
Disable test in a way that keeps lit happy.
// R UN: %llvmgcc %s -S -O0 -o - | FileCheck %s // Radar 9156771 typedef struct RGBColor { unsigned short red; unsigned short green; unsigned short blue; } RGBColor; RGBColor func(); RGBColor X; void foo() { //CHECK: store i48 X = func(); }
// RUN: %llvmgcc %s -S -O0 -o - | FileCheck %s // REQUIRES: disabled // Radar 9156771 typedef struct RGBColor { unsigned short red; unsigned short green; unsigned short blue; } RGBColor; RGBColor func(); RGBColor X; void foo() { //CHECK: store i48 X = func(); }
Add support for computing currently used size in resource caches
/* * Copyright (c) 2017 Lech Kulina * * This file is part of the Realms Of Steel. * For conditions of distribution and use, see copyright details in the LICENSE file. */ #ifndef ROS_RESOURCE_CACHE_H #define ROS_RESOURCE_CACHE_H #include <core/Common.h> #include <core/Environment.h> #include <resources/ArchiveFile.h> #include <resources/ResourceLoader.h> namespace ros { class ROS_API ResourceCache : public boost::noncopyable { public: virtual ~ResourceCache() {} virtual bool init(const PropertyTree& config); virtual void uninit(); virtual BufferPtr acquireBuffer(const std::string& name) =0; virtual void releaseBuffer(BufferPtr buffer) =0; const std::string& getName() const { return name; } ArchiveFileList& getArchives() { return archives; } ResourceLoaderList& getLoaders() { return loaders; } protected: BufferPtr loadBuffer(const std::string& name); private: std::string name; ArchiveFileList archives; ResourceLoaderList loaders; ArchiveEntryPtr findEntry(const std::string& name); ResourceLoaderPtr findLoader(const std::string& name); }; typedef boost::shared_ptr<ResourceCache> ResourceCachePtr; typedef Factory<ResourceCache> ResourceCacheFactory; typedef std::list<ResourceCachePtr> ResourceCacheList; typedef std::map<std::string, ResourceCachePtr> ResourceCacheMap; } #endif // ROS_RESOURCE_CACHE_H
/* * Copyright (c) 2017 Lech Kulina * * This file is part of the Realms Of Steel. * For conditions of distribution and use, see copyright details in the LICENSE file. */ #ifndef ROS_RESOURCE_CACHE_H #define ROS_RESOURCE_CACHE_H #include <core/Common.h> #include <core/Environment.h> #include <resources/ArchiveFile.h> #include <resources/ResourceLoader.h> namespace ros { class ROS_API ResourceCache : public boost::noncopyable { public: virtual ~ResourceCache() {} virtual bool init(const PropertyTree& config); virtual void uninit(); virtual BufferPtr acquireBuffer(const std::string& name) =0; virtual void releaseBuffer(BufferPtr buffer) =0; virtual U32 computeUsedSize() const =0; const std::string& getName() const { return name; } ArchiveFileList& getArchives() { return archives; } ResourceLoaderList& getLoaders() { return loaders; } protected: BufferPtr loadBuffer(const std::string& name); private: std::string name; ArchiveFileList archives; ResourceLoaderList loaders; ArchiveEntryPtr findEntry(const std::string& name); ResourceLoaderPtr findLoader(const std::string& name); }; typedef boost::shared_ptr<ResourceCache> ResourceCachePtr; typedef Factory<ResourceCache> ResourceCacheFactory; typedef std::list<ResourceCachePtr> ResourceCacheList; typedef std::map<std::string, ResourceCachePtr> ResourceCacheMap; } #endif // ROS_RESOURCE_CACHE_H
Add missing namespace closing comment
#pragma once #include <util/raii_helper.h> namespace shk { namespace detail { void closeFd(int fd); } using FileDescriptor = RAIIHelper<int, void, detail::closeFd, -1>; } // namespace shk
#pragma once #include <util/raii_helper.h> namespace shk { namespace detail { void closeFd(int fd); } // namespace detail using FileDescriptor = RAIIHelper<int, void, detail::closeFd, -1>; } // namespace shk
Add SDK IF_ELSE and USAGE macros
#pragma once #include "util/none.h" #ifdef PBL_SDK_3 #define SDK_SELECT(sdk3, sdk2) sdk3 #elif PBL_SDK_2 #define SDK_SELECT(sdk3, sdk2) sdk2 #endif
#pragma once #include "util/none.h" #ifdef PBL_SDK_3 #define SDK_SELECT(sdk3, sdk2) sdk3 #define IF_SDK_3_ELSE(sdk3, other) sdk3 #define IF_SDK_2_ELSE(sdk2, other) other #define SDK_3_USAGE #define SDK_2_USAGE __attribute__((unused)) #elif PBL_SDK_2 #define SDK_SELECT(sdk3, sdk2) sdk2 #define IF_SDK_3_ELSE(sdk3, other) other #define IF_SDK_2_ELSE(sdk2, other) sdk2 #define SDK_3_USAGE __attribute__((unused)) #define SDK_2_USAGE #endif
Add bugfix version to match package version parity
#ifndef PHP_FAST_ASSERT_H #define PHP_FAST_ASSERT_H #define PHP_FAST_ASSERT_VERSION "0.1" #define PHP_FAST_ASSERT_EXTNAME "fast_assert" #ifdef HAVE_CONFIG_H #include "config.h" #endif extern "C" { #include "php.h" } typedef struct _fast_assert_globals { // global object handles pointing to the 3 commonly used assert objects zend_object_handle invalid_arg_assert_handle; zend_object_handle unexpected_val_assert_handle; zend_object_handle logic_exception_assert_handle; } fast_assert_globals; #ifdef ZTS #define AssertGlobals(v) TSRMG(fa_globals_id, fast_assert_globals *, v) extern int fa_globals_id; #else #define AssertGlobals(v) (fa_globals.v) extern fast_assert_globals fa_globals; #endif /* ZTS */ extern zend_module_entry fast_assert_module_entry; #define phpext_fast_assert_ptr &fast_assert_module_entry; #endif /* PHP_FAST_ASSERT_H */
#ifndef PHP_FAST_ASSERT_H #define PHP_FAST_ASSERT_H #define PHP_FAST_ASSERT_VERSION "0.1.1" #define PHP_FAST_ASSERT_EXTNAME "fast_assert" #ifdef HAVE_CONFIG_H #include "config.h" #endif extern "C" { #include "php.h" } typedef struct _fast_assert_globals { // global object handles pointing to the 3 commonly used assert objects zend_object_handle invalid_arg_assert_handle; zend_object_handle unexpected_val_assert_handle; zend_object_handle logic_exception_assert_handle; } fast_assert_globals; #ifdef ZTS #define AssertGlobals(v) TSRMG(fa_globals_id, fast_assert_globals *, v) extern int fa_globals_id; #else #define AssertGlobals(v) (fa_globals.v) extern fast_assert_globals fa_globals; #endif /* ZTS */ extern zend_module_entry fast_assert_module_entry; #define phpext_fast_assert_ptr &fast_assert_module_entry; #endif /* PHP_FAST_ASSERT_H */
Remove now needless debug spam
#include <kotaka/paths.h> #include <kotaka/privilege.h> #include <kotaka/bigstruct.h> #include <kotaka/log.h> inherit LIB_INITD; inherit UTILITY_COMPILE; static void create() { load_dir("obj", 1); load_dir("sys", 1); } void full_reset() { object turkeylist; object cursor; object first; object this; ACCESS_CHECK(PRIVILEGED()); turkeylist = new_object(BIGSTRUCT_DEQUE_LWO); this = this_object(); cursor = KERNELD->first_link("Help"); first = cursor; do { LOGD->post_message("help", LOG_DEBUG, "Listing " + object_name(cursor)); turkeylist->push_back(cursor); cursor = KERNELD->next_link(cursor); } while (cursor != first); while (!turkeylist->empty()) { object turkey; turkey = turkeylist->get_front(); turkeylist->pop_front(); if (!turkey || turkey == this) { /* don't self destruct or double destruct */ continue; } destruct_object(turkey); } load_dir("obj", 1); load_dir("sys", 1); }
#include <kotaka/paths.h> #include <kotaka/privilege.h> #include <kotaka/bigstruct.h> #include <kotaka/log.h> inherit LIB_INITD; inherit UTILITY_COMPILE; static void create() { load_dir("obj", 1); load_dir("sys", 1); } void full_reset() { object turkeylist; object cursor; object first; object this; ACCESS_CHECK(PRIVILEGED()); turkeylist = new_object(BIGSTRUCT_DEQUE_LWO); this = this_object(); cursor = KERNELD->first_link("Help"); first = cursor; do { turkeylist->push_back(cursor); cursor = KERNELD->next_link(cursor); } while (cursor != first); while (!turkeylist->empty()) { object turkey; turkey = turkeylist->get_front(); turkeylist->pop_front(); if (!turkey || turkey == this) { /* don't self destruct or double destruct */ continue; } destruct_object(turkey); } load_dir("obj", 1); load_dir("sys", 1); }
Adjust Speed min/max Adjust Gas min/max Use other Pins for gear forwards/backwards
#define PIN_GAS_PEDAL A0 #define PIN_BATTERY_VOLTAGE A1 #define PIN_CW 5 #define PIN_CCW 6 #define PIN_SWITCH_FORWARDS 12 #define PIN_SWITCH_BACKWARDS 13 #define GAS_VALUE_MIN 442 #define GAS_VALUE_MAX 520 #define BATTERY_READING_12V 670 #define BATTERY_READING_6V 331 #define BATTERY_VOLTAGE_MIN 11 #define SPEED_MIN 0 #define SPEED_MAX_DIRECTION_CHANGE 15 #define SPEED_MAX_FORWARDS 255 #define SPEED_MAX_BACKWARDS 255 #define SPEED_CHANGE_PACE_DEFAULT 10
#define PIN_GAS_PEDAL A0 #define PIN_BATTERY_VOLTAGE A1 #define PIN_CW 5 #define PIN_CCW 6 #define PIN_SWITCH_FORWARDS 10 #define PIN_SWITCH_BACKWARDS 11 #define GAS_VALUE_MIN 446 #define GAS_VALUE_MAX 510 #define BATTERY_READING_12V 670 #define BATTERY_READING_6V 331 #define BATTERY_VOLTAGE_MIN 11 #define SPEED_MIN 0 #define SPEED_MAX_DIRECTION_CHANGE 15 #define SPEED_MAX_FORWARDS 255 #define SPEED_MAX_BACKWARDS 142 #define SPEED_CHANGE_PACE_DEFAULT 10
Test to see whether or not there are memory leaks.
#include <stdio.h> #include "sass_interface.h" int main(int argc, char** argv) { if (argc < 2) { printf("Hey, I need an input file!\n"); return 0; } while (1) { struct sass_file_context* ctx = sass_new_file_context(); ctx->options.include_paths = "::/blah/bloo/fuzz:/slub/flub/chub::/Users/Aaron/dev/libsass/::::/huzz/buzz:::"; ctx->options.output_style = SASS_STYLE_NESTED; ctx->input_path = argv[1]; sass_compile_file(ctx); if (ctx->error_status) { if (ctx->error_message) printf("%s", ctx->error_message); else printf("An error occured; no error message available.\n"); break; } else if (ctx->output_string) { continue; } else { printf("Unknown internal error.\n"); break; } sass_free_file_context(ctx); } return 0; }
Change the reported openssh release string to indicate the barrelfish port.
/* $OpenBSD: version.h,v 1.64 2012/02/09 20:00:18 markus Exp $ */ #define SSH_VERSION "OpenSSH_6.0" #define SSH_PORTABLE "p1" #define SSH_RELEASE SSH_VERSION SSH_PORTABLE
/* $OpenBSD: version.h,v 1.64 2012/02/09 20:00:18 markus Exp $ */ #define SSH_VERSION "OpenSSH_6.0" #define SSH_PORTABLE "p1" #define SSH_PORT_NOTE "Barrelfish port" #define SSH_RELEASE SSH_VERSION SSH_PORTABLE SSH_PORT_NOTE
Convert demo project to ARC.
// // SVProgressHUDAppDelegate.h // SVProgressHUD // // Created by Sam Vermette on 27.03.11. // Copyright 2011 Sam Vermette. All rights reserved. // #import <UIKit/UIKit.h> @class ViewController; @interface AppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; ViewController *viewController; } @property (nonatomic) IBOutlet UIWindow *window; @property (nonatomic) IBOutlet ViewController *viewController; @end
// // SVProgressHUDAppDelegate.h // SVProgressHUD // // Created by Sam Vermette on 27.03.11. // Copyright 2011 Sam Vermette. All rights reserved. // #import <UIKit/UIKit.h> @class ViewController; @interface AppDelegate : NSObject <UIApplicationDelegate> { UIWindow *__weak window; ViewController *__weak viewController; } @property (weak, nonatomic) IBOutlet UIWindow *window; @property (weak, nonatomic) IBOutlet ViewController *viewController; @end
Test for presence of new sodium_runtime_has_*() functions
#define TEST_NAME "sodium_core" #include "cmptest.h" int main(void) { printf("%d\n", sodium_init()); (void)sodium_runtime_has_neon(); (void)sodium_runtime_has_sse2(); (void)sodium_runtime_has_sse3(); return 0; }
#define TEST_NAME "sodium_core" #include "cmptest.h" int main(void) { printf("%d\n", sodium_init()); (void)sodium_runtime_has_neon(); (void)sodium_runtime_has_sse2(); (void)sodium_runtime_has_sse3(); (void)sodium_runtime_has_pclmul(); (void)sodium_runtime_has_aesni(); return 0; }
Fix example build under clang
#include <assert.h> #include <inform/dist.h> #include <math.h> int main() { inform_dist *dist = inform_dist_create((uint32_t[4]){3, 0, 1, 2}, 4); assert(abs(inform_dist_prob(dist, 0) - 0.5) < 1e-6); assert(abs(inform_dist_prob(dist, 1) - 0.0) < 1e-6); assert(abs(inform_dist_prob(dist, 2) - 0.1666) < 1e-6); assert(abs(inform_dist_prob(dist, 3) - 0.3333) < 1e-6); inform_dist_free(dist); }
#include <assert.h> #include <inform/dist.h> #include <math.h> int main() { inform_dist *dist = inform_dist_create((uint32_t[4]){3, 0, 1, 2}, 4); assert(fabs(inform_dist_prob(dist, 0) - 0.5) < 1e-6); assert(fabs(inform_dist_prob(dist, 1) - 0.0) < 1e-6); assert(fabs(inform_dist_prob(dist, 2) - 0.1666) < 1e-6); assert(fabs(inform_dist_prob(dist, 3) - 0.3333) < 1e-6); for (size_t i = 0; i < 4; ++i) { printf("%lf ", inform_dist_prob(dist, i)); } printf("\n"); inform_dist_free(dist); }
Add a test for fq_pth_root.
/*============================================================================= This file is part of FLINT. FLINT is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. FLINT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FLINT; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =============================================================================*/ /****************************************************************************** Copyright (C) 2012 Sebastian Pancratz Copyright (C) 2012 Andres Goens Copyright (C) 2013 Mike Hansen ******************************************************************************/ #include <stdio.h> #include "fq.h" #include "ulong_extras.h" #include "long_extras.h" int main(void) { int i, result; flint_rand_t state; flint_printf("pth_root... "); fflush(stdout); flint_randinit(state); /* Compare with sum of Galois conjugates */ for (i = 0; i < 1000; i++) { fq_ctx_t ctx; fq_t a, b; fq_ctx_randtest(ctx, state); fq_init(a, ctx); fq_init(b, ctx); fq_randtest(a, state, ctx); fq_pth_root(b, a, ctx); fq_pow(b, b, fq_ctx_prime(ctx), ctx); result = fq_equal(a, b, ctx); if (!result) { flint_printf("FAIL:\n\n"); flint_printf("a = "), fq_print_pretty(a, ctx), flint_printf("\n"); flint_printf("b = "), fq_print_pretty(b, ctx), flint_printf("\n"); abort(); } fq_clear(a, ctx); fq_clear(b, ctx); fq_ctx_clear(ctx); } flint_randclear(state); _fmpz_cleanup(); flint_printf("PASS\n"); return EXIT_SUCCESS; }
Add a header file for users to include.
/* Copyright (c) 2015 ThreadScan authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _THREADSCAN_H_ #define _THREADSCAN_H_ /** * Submit a pointer for memory reclamation. threadscan_collect() will call * free() on the pointer, itself, when there are no more outstanding * references on the stack or in blocks of memory specified using * threadscan_register_local_block(). */ extern void threadscan_collect (void *ptr); /** * Specify a block of memory, local to the thread that called the function, * that ThreadScan will search during the reclamation phase. Without this * call ThreadScan will search only the thread stacks. */ extern void threadscan_register_local_block (void *addr, size_t size); #endif // !defined _THREADSCAN_H_
Add declaration header file for token space.
/** @file GUID for PcAtChipsetPkg PCD Token Space Copyright (c) 2009, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef _PCATCHIPSET_TOKEN_SPACE_GUID_H_ #define _PCATCHIPSET_TOKEN_SPACE_GUID_H_ #define PCATCHIPSET_TOKEN_SPACE_GUID \ { \ 0x326ae723, 0xae32, 0x4589, { 0x98, 0xb8, 0xca, 0xc2, 0x3c, 0xdc, 0xc1, 0xb1 } \ } extern EFI_GUID gPcAtChipsetPkgTokenSpaceGuid; #endif
Add NULL dereferenced top value test
#include <assert.h> #include <stddef.h> int main() { int r; // rand int i = 0; int *p; if (r) p = &i; else p = NULL; if (*p == 2) // WARN assert(1); // reachable (via UB) return 0; }
Split up C++ program into separate files and put its components into proper places.
// // mysociety_error.cpp: // Some helpers. // // Copyright (c) 2009 UK Citizens Online Democracy. All rights reserved. // Email: francis@mysociety.org; WWW: http://www.mysociety.org/ // // $Id: mysociety_error.h,v 1.1 2009-03-23 09:30:06 francis Exp $ // #include <string> #if defined(OUTPUT_ROUTE_DETAILS) or defined(DEBUG) #include <boost/format.hpp> #endif #include <stdio.h> #include <assert.h> /* Logging and debug assertions. Use assert for assertion that matter in release mode, * debug_assert for ones that can be stripped. */ #ifdef DEBUG void do_log(boost::basic_format<char, std::char_traits<char>, std::allocator<char> > &bf) { puts(bf.str().c_str()); } void do_log(const std::string& str) { puts(str.c_str()); } #define log(message) do_log(message); #define debug_assert(thing) assert(thing); #else #define log(message) while(0) { }; #define debug_assert(thing) while(0) { }; #endif /* Most similar to Python's Exception */ class Exception : public std::exception { std::string s; public: Exception(std::string s_) : s("Exception: " + s_) { } ~Exception() throw() { } const char* what() const throw() { return s.c_str(); } }; /* Error handling version of fread */ void my_fread ( void * ptr, size_t size, size_t count, FILE * stream ) { size_t ret = fread(ptr, size, count, stream); assert(ret == count); }
Use CLOCK_REALTIME if CLOCK_MONOTONIC is not available.
#ifndef COMPAT_H #define COMPAT_H #ifndef HAVE_PLEDGE #include "pledge.h" #endif #ifndef HAVE_STRTONUM #include "strtonum.h" #endif #ifndef timespecsub #define timespecsub(tsp, usp, vsp) \ do { \ (vsp)->tv_sec = (tsp)->tv_sec - (usp)->tv_sec; \ (vsp)->tv_nsec = (tsp)->tv_nsec - (usp)->tv_nsec; \ if ((vsp)->tv_nsec < 0) { \ (vsp)->tv_sec--; \ (vsp)->tv_nsec += 1000000000L; \ } \ } while (0) #endif #endif /* COMPAT_H */
#ifndef COMPAT_H #define COMPAT_H #ifndef HAVE_PLEDGE #include "pledge.h" #endif #ifndef HAVE_STRTONUM #include "strtonum.h" #endif /* Use CLOCK_REALTIME if CLOCK_MONOTONIC is not available */ #ifndef CLOCK_MONOTONIC #define CLOCK_MONOTONIC CLOCK_REALTIME #endif #ifndef timespecsub #define timespecsub(tsp, usp, vsp) \ do { \ (vsp)->tv_sec = (tsp)->tv_sec - (usp)->tv_sec; \ (vsp)->tv_nsec = (tsp)->tv_nsec - (usp)->tv_nsec; \ if ((vsp)->tv_nsec < 0) { \ (vsp)->tv_sec--; \ (vsp)->tv_nsec += 1000000000L; \ } \ } while (0) #endif #endif /* COMPAT_H */
Add solution to Exercise 2-2.
/* A solution to Exercise 2-2 in The C Programming Language (Second Edition). */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> int main(void) { uint32_t i = 0; uint32_t lim = 100; char c = 0; char s[lim]; while (i < (lim - 1)) { c = getchar(); if (c != '\n') { if (c != EOF) { s[i++] = c; } } } s[i] = '\0'; puts(s); return EXIT_SUCCESS; }
Disable this test on win32. My "sleep 2" trick didn't seem to work
// RUN: mkdir -p %t.dir // RUN: echo '#include "header2.h"' > %t.dir/header1.h // RUN: echo > %t.dir/header2.h // RUN: cp %s %t.dir/t.c // RUN: %clang_cc1 -x c-header %t.dir/header1.h -emit-pch -o %t.pch // RUN: sleep 2 // RUN: echo >> %t.dir/header2.h // RUN: %clang_cc1 %t.dir/t.c -include-pch %t.pch -fsyntax-only 2>&1 | FileCheck %s #include "header2.h" // CHECK: fatal error: file {{.*}} has been modified since the precompiled header was built
// RUN: mkdir -p %t.dir // RUN: echo '#include "header2.h"' > %t.dir/header1.h // RUN: echo > %t.dir/header2.h // RUN: cp %s %t.dir/t.c // RUN: %clang_cc1 -x c-header %t.dir/header1.h -emit-pch -o %t.pch // RUN: echo >> %t.dir/header2.h // RUN: %clang_cc1 %t.dir/t.c -include-pch %t.pch -fsyntax-only 2>&1 | FileCheck %s #include "header2.h" // CHECK: fatal error: file {{.*}} has been modified since the precompiled header was built // DISABLE: win32
Test int64_t -> long double
#include "src/math/reinterpret.h" #include <stdint.h> #include <assert.h> int64_t __fixtfdi(long double); static _Bool run(int64_t a) { return a == __fixtfdi(a); } int main(void) { const int64_t delta = 0x0000002BA87B5A22; assert(run(INT64_MAX)); assert(run(INT64_MIN)); for (int64_t i = 0x3FFFFFFFFFFFFFFF; i < 0x4340000000000000; i += delta) { double x = reinterpret(double, i); assert(run(x)); assert(run(-x)); } for (int64_t i = 0; i <= INT64_MAX / delta; ++i) { assert(run(i * delta)); assert(run(i * -delta)); } }
Set currentStatus public and add default value
// // ofxSocketIO.h // // Created by hugohil on 05/02/16. // // #pragma once #include "ofMain.h" #include "ofEvents.h" #if defined(_MSC_VER) || defined(_WIN32) || defined(WIN32) || defined(__MINGW32__) // Windows stuff #else // Linux and OSX here #include <sio_client.h> #endif #include "ofxSocketIOData.h" class ofxSocketIO : protected ofThread { private : sio::client client; std::string currentStatus; void onConnect(); void onClose(sio::client::close_reason const& reason); void onFail(); void onTryReconnect(); public : void setup(std::string& address); void setup(std::string& address, std::map<std::string,std::string>& query); void bindEvent(ofEvent<ofxSocketIOData&>& event, std::string eventName, std::string nsp=""); ofEvent<void> connectionEvent; ofEvent<std::string> notifyEvent; void emit(std::string& eventName); void emit(std::string& eventName, std::string& data, std::string nsp=""); void emitBinary(std::string& eventName, shared_ptr<string> const& bStr, std::string nsp=""); void closeConnection(); void openConnection(std::string& address); };
// // ofxSocketIO.h // // Created by hugohil on 05/02/16. // // #pragma once #include "ofMain.h" #include "ofEvents.h" #if defined(_MSC_VER) || defined(_WIN32) || defined(WIN32) || defined(__MINGW32__) // Windows stuff #else // Linux and OSX here #include <sio_client.h> #endif #include "ofxSocketIOData.h" class ofxSocketIO : protected ofThread { private : sio::client client; void onConnect(); void onClose(sio::client::close_reason const& reason); void onFail(); void onTryReconnect(); public : std::string currentStatus = "close"; void setup(std::string& address); void setup(std::string& address, std::map<std::string,std::string>& query); void bindEvent(ofEvent<ofxSocketIOData&>& event, std::string eventName, std::string nsp=""); ofEvent<void> connectionEvent; ofEvent<std::string> notifyEvent; void emit(std::string& eventName); void emit(std::string& eventName, std::string& data, std::string nsp=""); void emitBinary(std::string& eventName, shared_ptr<string> const& bStr, std::string nsp=""); void closeConnection(); void openConnection(std::string& address); };
Add traits for befriendable concepts.
#ifndef VAST_ACCESS_H #define VAST_ACCESS_H namespace vast { /// Wrapper to encapsulate the implementation of concepts requiring access to /// private state. struct access { template <typename, typename = void> struct state; template <typename, typename = void> struct parsable; template <typename, typename = void> struct printable; template <typename, typename = void> struct convertible; }; } // namespace vast #endif
#ifndef VAST_ACCESS_H #define VAST_ACCESS_H namespace vast { /// Wrapper to encapsulate the implementation of concepts requiring access to /// private state. struct access { template <typename, typename = void> struct state; template <typename, typename = void> struct parser; template <typename, typename = void> struct printer; template <typename, typename = void> struct converter; }; namespace detail { struct has_access_state { template <typename T> static auto test(T* x) -> decltype(access::state<T>{}, std::true_type()); template <typename> static auto test(...) -> std::false_type; }; struct has_access_parser { template <typename T> static auto test(T* x) -> decltype(access::parser<T>{}, std::true_type()); template <typename> static auto test(...) -> std::false_type; }; struct has_access_printer { template <typename T> static auto test(T* x) -> decltype(access::printer<T>{}, std::true_type()); template <typename> static auto test(...) -> std::false_type; }; struct has_access_converter { template <typename T> static auto test(T* x) -> decltype(access::converter<T>{}, std::true_type()); template <typename> static auto test(...) -> std::false_type; }; } // namespace detail template <typename T> struct has_access_state : decltype(detail::has_access_state::test<T>(0)) {}; template <typename T> struct has_access_parser : decltype(detail::has_access_parser::test<T>(0)) {}; template <typename T> struct has_access_printer : decltype(detail::has_access_printer::test<T>(0)) {}; template <typename T> struct has_access_converter : decltype(detail::has_access_converter::test<T>(0)) {}; } // namespace vast #endif
Fix name of C function
#include "erl_nif.h" #include <sodium.h> #include "hash.h" ERL_NIF_TERM enacl_crypto_hash_nif(ErlNifEnv *env, int argc, ERL_NIF_TERM const argv[]) { ErlNifBinary input; ErlNifBinary result; ERL_NIF_TERM ret; if ((argc != 1) || (!enif_inspect_iolist_as_binary(env, argv[0], &input))) goto bad_arg; if (!enif_alloc_binary(crypto_hash_BYTES, &result)) goto err; crypto_hash(result.data, input.data, input.size); ret = enif_make_binary(env, &result); goto done; bad_arg: return enif_make_badarg(env); err: ret = nacl_error_tuple(env, "alloc_failed"); done: return ret; }
#include "erl_nif.h" #include <sodium.h> #include "hash.h" ERL_NIF_TERM enacl_crypto_hash(ErlNifEnv *env, int argc, ERL_NIF_TERM const argv[]) { ErlNifBinary input; ErlNifBinary result; ERL_NIF_TERM ret; if ((argc != 1) || (!enif_inspect_iolist_as_binary(env, argv[0], &input))) goto bad_arg; if (!enif_alloc_binary(crypto_hash_BYTES, &result)) goto err; crypto_hash(result.data, input.data, input.size); ret = enif_make_binary(env, &result); goto done; bad_arg: return enif_make_badarg(env); err: ret = nacl_error_tuple(env, "alloc_failed"); done: return ret; }
Add test for bug parsing typenames in structs
/* name: TEST040 description: Test for bug parsing typenames in struct definition output: */ typedef struct List List; struct List { int len; struct List *head; };
Fix debugging printouts when running tests.
#include "log.h" #include <stdio.h> void debug(const char* format, ...) { #ifdef __DEBUG__ vprintf(format, args); #endif // __DEBUG__ } void initializeLogging() { }
#include "log.h" #include <stdio.h> #include <stdarg.h> void debug(const char* format, ...) { #ifdef __DEBUG__ va_list args; va_start(args, format); vprintf(format, args); va_end(args); #endif // __DEBUG__ } void initializeLogging() { }
Make the remove*OnSignal functions deal with Paths not strings
//===- llvm/System/Signals.h - Signal Handling support ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines some helpful functions for dealing with the possibility of // unix signals occuring while your program is running. // //===----------------------------------------------------------------------===// #ifndef LLVM_SYSTEM_SIGNALS_H #define LLVM_SYSTEM_SIGNALS_H #include "llvm/System/Path.h" namespace llvm { namespace sys { /// This function registers signal handlers to ensure that if a signal gets /// delivered that the named file is removed. /// @brief Remove a file if a fatal signal occurs. void RemoveFileOnSignal(const std::string &Filename); /// This function registers a signal handler to ensure that if a fatal signal /// gets delivered to the process that the named directory and all its /// contents are removed. /// @brief Remove a directory if a fatal signal occurs. void RemoveDirectoryOnSignal(const llvm::sys::Path& path); /// When an error signal (such as SIBABRT or SIGSEGV) is delivered to the /// process, print a stack trace and then exit. /// @brief Print a stack trace if a fatal signal occurs. void PrintStackTraceOnErrorSignal(); } // End sys namespace } // End llvm namespace #endif
//===- llvm/System/Signals.h - Signal Handling support ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines some helpful functions for dealing with the possibility of // unix signals occuring while your program is running. // //===----------------------------------------------------------------------===// #ifndef LLVM_SYSTEM_SIGNALS_H #define LLVM_SYSTEM_SIGNALS_H #include "llvm/System/Path.h" namespace llvm { namespace sys { /// This function registers signal handlers to ensure that if a signal gets /// delivered that the named file is removed. /// @brief Remove a file if a fatal signal occurs. void RemoveFileOnSignal(const Path &Filename); /// This function registers a signal handler to ensure that if a fatal signal /// gets delivered to the process that the named directory and all its /// contents are removed. /// @brief Remove a directory if a fatal signal occurs. void RemoveDirectoryOnSignal(const Path& path); /// When an error signal (such as SIBABRT or SIGSEGV) is delivered to the /// process, print a stack trace and then exit. /// @brief Print a stack trace if a fatal signal occurs. void PrintStackTraceOnErrorSignal(); } // End sys namespace } // End llvm namespace #endif
Add new future syntax for 'new' in Future folder
/* * Copyright (C) 2016 Bastien Penavayre * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #define ARGUMENT_LIST(args...) args) #define new(name, ctor) name ## _ ## ctor (0, ARGUMENT_LIST void *String_ctor(const char *str) { return 0; } int main() { void *tmp = new(String, ctor)("Jello"); }
Revert "players number changed, for some tests"
#include "builder.h" #include "entity/board.h" /** * A small board has 4 cells, and its layout is a square. * 1 ----- 2 * | | * | | * | | * 4 ----- 3 */ int builder_create_small_board(s_board *b) { int c; uint8_t nb_max_players; nb_max_players = 4; init_board(b, SMALL_BOARD_NB_CELLS, nb_max_players); for (c = 0; c < SMALL_BOARD_NB_CELLS; c++) { b->cells[c].neighbours[0] = &b->cells[(SMALL_BOARD_NB_CELLS + c - 1) % SMALL_BOARD_NB_CELLS]; b->cells[c].neighbours[1] = &b->cells[(c + 1) % SMALL_BOARD_NB_CELLS]; b->cells[c].nb_neighbours = 2; } return nb_max_players; }
#include "builder.h" #include "entity/board.h" /** * A small board has 4 cells, and its layout is a square. * 1 ----- 2 * | | * | | * | | * 4 ----- 3 */ int builder_create_small_board(s_board *b) { int c; uint8_t nb_max_players; nb_max_players = 2; init_board(b, SMALL_BOARD_NB_CELLS, nb_max_players); for (c = 0; c < SMALL_BOARD_NB_CELLS; c++) { b->cells[c].neighbours[0] = &b->cells[(SMALL_BOARD_NB_CELLS + c - 1) % SMALL_BOARD_NB_CELLS]; b->cells[c].neighbours[1] = &b->cells[(c + 1) % SMALL_BOARD_NB_CELLS]; b->cells[c].nb_neighbours = 2; } return nb_max_players; }
Add helper function to map from bitrate values to zephyr cfg
/* * Copyright (c) 2017 Linaro Limited * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _I2C_PRIV_H_ #define _I2C_PRIV_H_ #ifdef __cplusplus extern "C" { #endif #include <i2c.h> #include <dt-bindings/i2c/i2c.h> #ifndef SYS_LOG_LEVEL #define SYS_LOG_LEVEL CONFIG_SYS_LOG_I2C_LEVEL #endif #include <logging/sys_log.h> static inline u32_t _i2c_map_dt_bitrate(u32_t bitrate) { switch (bitrate) { case I2C_BITRATE_STANDARD: return I2C_SPEED_STANDARD << I2C_SPEED_SHIFT; case I2C_BITRATE_FAST: return I2C_SPEED_FAST << I2C_SPEED_SHIFT; case I2C_BITRATE_FAST_PLUS: return I2C_SPEED_FAST_PLUS << I2C_SPEED_SHIFT; case I2C_BITRATE_HIGH: return I2C_SPEED_HIGH << I2C_SPEED_SHIFT; case I2C_BITRATE_ULTRA: return I2C_SPEED_ULTRA << I2C_SPEED_SHIFT; } SYS_LOG_ERR("Invalid I2C bit rate value"); return 0; } #ifdef __cplusplus } #endif #endif /* _I2C_PRIV_H_ */
Add missing event reporting code.
/* * Copyright (c) 2005 David Xu * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $FreeBSD$ */ #include "thr_private.h" void _thread_bp_create(void) { } void _thread_bp_death(void) { } void _thr_report_creation(struct pthread *curthread, struct pthread *newthread) { curthread->event_buf.event = TD_CREATE; curthread->event_buf.th_p = (td_thrhandle_t *)newthread; curthread->event_buf.data = 0; THR_UMTX_LOCK(curthread, &_thr_event_lock); _thread_last_event = curthread; _thread_bp_create(); _thread_last_event = NULL; THR_UMTX_UNLOCK(curthread, &_thr_event_lock); } void _thr_report_death(struct pthread *curthread) { curthread->event_buf.event = TD_DEATH; curthread->event_buf.th_p = (td_thrhandle_t *)curthread; curthread->event_buf.data = 0; THR_UMTX_LOCK(curthread, &_thr_event_lock); _thread_last_event = curthread; _thread_bp_death(); _thread_last_event = NULL; THR_UMTX_UNLOCK(curthread, &_thr_event_lock); }
Add a todo for more useful Python exception output
/*ckwg +5 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #ifndef VISTK_PYTHON_HELPERS_EXCEPTIONS_H #define VISTK_PYTHON_HELPERS_EXCEPTIONS_H #define HANDLE_PYTHON_EXCEPTION(call) \ try \ { \ call; \ } \ catch (boost::python::error_already_set&) \ { \ PyErr_Print(); \ \ throw; \ } #endif // VISTK_PYTHON_HELPERS_EXCEPTIONS_H
/*ckwg +5 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #ifndef VISTK_PYTHON_HELPERS_EXCEPTIONS_H #define VISTK_PYTHON_HELPERS_EXCEPTIONS_H /// \todo More useful output? #define HANDLE_PYTHON_EXCEPTION(call) \ try \ { \ call; \ } \ catch (boost::python::error_already_set&) \ { \ PyErr_Print(); \ \ throw; \ } #endif // VISTK_PYTHON_HELPERS_EXCEPTIONS_H
Change the return type to bool.
#ifndef SCC_SEMANTIC_HEADER #define SCC_SEMANTIC_HEADER #include <stdio.h> #include "syntax.h" #include "symboltable.h" int semantic_analysis(Syntax * top_level); #endif
#ifndef SCC_SEMANTIC_HEADER #define SCC_SEMANTIC_HEADER #include <stdio.h> #include <stdbool.h> #include "syntax.h" #include "symboltable.h" bool semantic_analysis(Syntax * top_level); #endif
Add declaration of lift function
#ifndef RSTORE_UITLS_H #define RSTORE_UITLS_H #include <RStore.h> #include <ParsedRStore.h> RS_RStore RS_lowerRStore(PRS_RStore store); #endif
#ifndef RSTORE_UITLS_H #define RSTORE_UITLS_H #include <RStore.h> #include <ParsedRStore.h> RS_RStore RS_lowerRStore(PRS_RStore store); PRS_RStore RS_liftRStore(RS_RStore store); #endif
Allow external contributions on src/main/native
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MACROS_H__ #define MACROS_H__ // TODO(bazel-team): Use the proper annotation for clang. #define FALLTHROUGH_INTENDED do { } while (0) #endif // MACROS_H__
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MACROS_H__ #define MACROS_H__ // GXX_EXPERIMENTAL_CXX0X is defined by gcc and clang up to at least // gcc-4.7 and clang-3.1 (2011-12-13). __cplusplus was defined to 1 // in gcc before 4.7 and clang before 3.1, but is defined according // to the language version in effect thereafter. #if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L // When compiled with clang c++11 standard with warning on switch // fallthrough, tell the compiler not to complain when it was intended. #if defined(__clang__) && defined(__has_warning) #if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough") #define FALLTHROUGH_INTENDED [[clang::fallthrough]] // NOLINT #endif #endif #endif #ifndef FALLTHROUGH_INTENDED #define FALLTHROUGH_INTENDED do { } while (0) #endif #endif // MACROS_H__
Include http_parser.h from the right spot (public header copied to framework headers)
// // SwiftyHTTP.h // SwiftyHTTP // // Created by Helge Hess on 6/25/14. // Copyright (c) 2014 Always Right Institute. All rights reserved. // #import <Cocoa/Cocoa.h> //! Project version number for SwiftyHTTP. FOUNDATION_EXPORT double SwiftyHTTPVersionNumber; //! Project version string for SwiftyHTTP. FOUNDATION_EXPORT const unsigned char SwiftyHTTPVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SwiftyHTTP/PublicHeader.h> // No more bridging header in v0.0.4, need to make all C stuff public #import <SwiftyHTTP/Parser/http_parser.h> // I think the originals are not mapped because they are using varargs FOUNDATION_EXPORT int ari_fcntlVi (int fildes, int cmd, int val); FOUNDATION_EXPORT int ari_ioctlVip(int fildes, unsigned long request, int *val);
// // SwiftyHTTP.h // SwiftyHTTP // // Created by Helge Hess on 6/25/14. // Copyright (c) 2014 Always Right Institute. All rights reserved. // #import <Cocoa/Cocoa.h> //! Project version number for SwiftyHTTP. FOUNDATION_EXPORT double SwiftyHTTPVersionNumber; //! Project version string for SwiftyHTTP. FOUNDATION_EXPORT const unsigned char SwiftyHTTPVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SwiftyHTTP/PublicHeader.h> // No more bridging header in v0.0.4, need to make all C stuff public #import <SwiftyHTTP/http_parser.h> // I think the originals are not mapped because they are using varargs FOUNDATION_EXPORT int ari_fcntlVi (int fildes, int cmd, int val); FOUNDATION_EXPORT int ari_ioctlVip(int fildes, unsigned long request, int *val);
Synchronize the mailbox after expunging messages to actually get them expunged.
/* Copyright (c) 2002-2008 Dovecot authors, see the included COPYING file */ #include "common.h" #include "commands.h" #include "imap-expunge.h" bool cmd_close(struct client_command_context *cmd) { struct client *client = cmd->client; struct mailbox *mailbox = client->mailbox; struct mail_storage *storage; if (!client_verify_open_mailbox(cmd)) return TRUE; storage = mailbox_get_storage(mailbox); client->mailbox = NULL; if (!imap_expunge(mailbox, NULL)) client_send_untagged_storage_error(client, storage); if (mailbox_close(&mailbox) < 0) client_send_untagged_storage_error(client, storage); client_update_mailbox_flags(client, NULL); client_send_tagline(cmd, "OK Close completed."); return TRUE; }
/* Copyright (c) 2002-2008 Dovecot authors, see the included COPYING file */ #include "common.h" #include "commands.h" #include "imap-expunge.h" bool cmd_close(struct client_command_context *cmd) { struct client *client = cmd->client; struct mailbox *mailbox = client->mailbox; struct mail_storage *storage; if (!client_verify_open_mailbox(cmd)) return TRUE; storage = mailbox_get_storage(mailbox); client->mailbox = NULL; if (!imap_expunge(mailbox, NULL)) client_send_untagged_storage_error(client, storage); else if (mailbox_sync(mailbox, 0, 0, NULL) < 0) client_send_untagged_storage_error(client, storage); if (mailbox_close(&mailbox) < 0) client_send_untagged_storage_error(client, storage); client_update_mailbox_flags(client, NULL); client_send_tagline(cmd, "OK Close completed."); return TRUE; }
Add useless bootlader header needed to merge with google code.
#ifndef BOARD_H #define BOARD_H // USARTs #if xplain == TARGET #define BL_PORT PORTF #define BL_DIR BL_PORT.DIR #define BL_IN BL_PORT.IN #define BL_OUT BL_PORT.OUT #define BL_0_PIN 0 #define BL_1_PIN 1 #define BL_2_PIN 2 #define APP_PIN 3 #define USART_0 USARTC0 #define USART_0_PORT PORTC #define USART_0_RD_PIN 2 #define USART_0_WR_PIN 3 #define BAUD_RATE 9600UL #define USART_1 USARTD0 #define USART_1_PORT PORTD #define USART_1_RD_PIN 2 #define USART_1_WR_PIN 3 #define BAUD_RATE_1 57600UL #define USART_2 USARTD1 #define USART_2_PORT PORTD #define USART_2_RD_PIN 6 #define USART_2_WR_PIN 7 #define BAUD_RATE_2 57600UL #endif // LED #if mega == TARGET \ || CRUMB128 == TARGET \ || PROBOMEGA128 == TARGET \ || SAVVY128 == TARGET #define LED PINB7 #elif sanguino == TARGET #define LED PINB0 #elif xplain == TARGET // PORTE #define LED_PORT PORTE #define LED_DDR LED_PORT.DIR #define LED_OUT PORTE.OUT #endif // MONITOR #if mega == TARGET #define MONITOR_WELCOME "ATmegaBOOT / Arduino Mega - (C) Arduino LLC - 090930\n\r"; #elif CRUMB128 == TARGET #define MONITOR_WELCOME "ATmegaBOOT / Crumb128 - (C) J.P.Kyle, E.Lins - 050815\n\r"; #elif PROBOMEGA128 == TARGET #define MONITOR_WELCOME "ATmegaBOOT / PROBOmega128 - (C) J.P.Kyle, E.Lins - 050815\n\r"; #elif SAVVY128 == TARGET #define MONITOR_WELCOME "ATmegaBOOT / Savvy128 - (C) J.P.Kyle, E.Lins - 050815\n\r"; #else #define MONITOR_WELCOME "ATmegaBOOT / Unknown\n\r"; #endif #endif // BOARD_H
Fix build for boost 1.66
--- src/txmempool.h.orig 2018-01-11 20:38:04 UTC +++ src/txmempool.h @@ -241,7 +241,7 @@ public: class CompareTxMemPoolEntryByScore { public: - bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) + bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const { double f1 = (double)a.GetModifiedFee() * b.GetTxSize(); double f2 = (double)b.GetModifiedFee() * a.GetTxSize(); @@ -255,7 +255,7 @@ public: class CompareTxMemPoolEntryByEntryTime { public: - bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) + bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const { return a.GetTime() < b.GetTime(); }
--- src/txmempool.h.orig 2018-01-11 20:38:04 UTC +++ src/txmempool.h @@ -204,7 +204,7 @@ struct mempoolentry_txid class CompareTxMemPoolEntryByDescendantScore { public: - bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) + bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const { bool fUseADescendants = UseDescendantScore(a); bool fUseBDescendants = UseDescendantScore(b); @@ -241,7 +241,7 @@ public: class CompareTxMemPoolEntryByScore { public: - bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) + bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const { double f1 = (double)a.GetModifiedFee() * b.GetTxSize(); double f2 = (double)b.GetModifiedFee() * a.GetTxSize(); @@ -255,7 +255,7 @@ public: class CompareTxMemPoolEntryByEntryTime { public: - bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) + bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const { return a.GetTime() < b.GetTime(); }
Check if options is nullptr in DatasetBase
#pragma once #include "common/definitions.h" #include "data/batch.h" #include "data/rng_engine.h" #include "data/vocab.h" #include "training/training_state.h" namespace marian { namespace data { template <class Sample, class Iterator, class Batch> class DatasetBase { protected: // Data processing may differ in training/inference settings std::vector<std::string> paths_; Ptr<Config> options_; bool inference_{false}; public: typedef Batch batch_type; typedef Ptr<Batch> batch_ptr; typedef Iterator iterator; typedef Sample sample; // @TODO: get rid of Config in favor of Options! DatasetBase(std::vector<std::string> paths, Ptr<Config> options) : paths_(paths), options_(options), inference_(options->get<bool>("inference", false)) {} DatasetBase(Ptr<Config> options) : DatasetBase({}, options) {} virtual Iterator begin() = 0; virtual Iterator end() = 0; virtual void shuffle() = 0; virtual Sample next() = 0; virtual batch_ptr toBatch(const std::vector<sample>&) = 0; virtual void reset() {} virtual void prepare() {} virtual void restore(Ptr<TrainingState>) {} }; } // namespace data } // namespace marian
#pragma once #include "common/definitions.h" #include "data/batch.h" #include "data/rng_engine.h" #include "data/vocab.h" #include "training/training_state.h" namespace marian { namespace data { template <class Sample, class Iterator, class Batch> class DatasetBase { protected: // Data processing may differ in training/inference settings std::vector<std::string> paths_; Ptr<Config> options_; bool inference_{false}; public: typedef Batch batch_type; typedef Ptr<Batch> batch_ptr; typedef Iterator iterator; typedef Sample sample; // @TODO: get rid of Config in favor of Options! DatasetBase(std::vector<std::string> paths, Ptr<Config> options) : paths_(paths), options_(options), inference_(options != nullptr ? options->get<bool>("inference", false) : false) {} DatasetBase(Ptr<Config> options) : DatasetBase({}, options) {} virtual Iterator begin() = 0; virtual Iterator end() = 0; virtual void shuffle() = 0; virtual Sample next() = 0; virtual batch_ptr toBatch(const std::vector<sample>&) = 0; virtual void reset() {} virtual void prepare() {} virtual void restore(Ptr<TrainingState>) {} }; } // namespace data } // namespace marian
Check handling of arrays of variable sized components.
// RUN: %llvmgcc -S %s -O2 -o - | grep {ret i8 0} static char c(int n) { char x[2][n]; x[1][0]=0; return *(n+(char *)x); } char d(void) { return c(2); }
Add one call to yaz_mutex_destroy in test
/* This file is part of the YAZ toolkit. * Copyright (C) 1995-2010 Index Data * See the file LICENSE for details. */ #include <stdlib.h> #include <stdio.h> #include <yaz/mutex.h> #include <yaz/test.h> #include <yaz/log.h> static void tst(void) { YAZ_MUTEX p = 0; yaz_mutex_create(&p); YAZ_CHECK(p); yaz_mutex_enter(p); yaz_mutex_leave(p); yaz_mutex_destroy(&p); YAZ_CHECK(p == 0); yaz_mutex_create(&p); YAZ_CHECK(p); yaz_mutex_set_name(p, YLOG_LOG, "mymutex"); yaz_mutex_enter(p); yaz_mutex_leave(p); yaz_mutex_destroy(&p); YAZ_CHECK(p == 0); } int main (int argc, char **argv) { YAZ_CHECK_INIT(argc, argv); YAZ_CHECK_LOG(); tst(); YAZ_CHECK_TERM; } /* * Local variables: * c-basic-offset: 4 * c-file-style: "Stroustrup" * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */
/* This file is part of the YAZ toolkit. * Copyright (C) 1995-2010 Index Data * See the file LICENSE for details. */ #include <stdlib.h> #include <stdio.h> #include <yaz/mutex.h> #include <yaz/test.h> #include <yaz/log.h> static void tst(void) { YAZ_MUTEX p = 0; yaz_mutex_create(&p); YAZ_CHECK(p); yaz_mutex_enter(p); yaz_mutex_leave(p); yaz_mutex_destroy(&p); YAZ_CHECK(p == 0); yaz_mutex_create(&p); YAZ_CHECK(p); yaz_mutex_set_name(p, YLOG_LOG, "mymutex"); yaz_mutex_enter(p); yaz_mutex_leave(p); yaz_mutex_destroy(&p); YAZ_CHECK(p == 0); yaz_mutex_destroy(&p); /* OK to "destroy" NULL handle */ } int main (int argc, char **argv) { YAZ_CHECK_INIT(argc, argv); YAZ_CHECK_LOG(); tst(); YAZ_CHECK_TERM; } /* * Local variables: * c-basic-offset: 4 * c-file-style: "Stroustrup" * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */
Add solution to Exercise 1-10.
/* Exercise 1-10: Write a program to copy its input to its output, replacing * each tab by \t, each backspace by \b, and each backslash by \\. This makes * tabs and backspaces visible in an unambiguous way. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { int16_t character; while ((character = getchar()) != EOF) { switch (character) { case '\t': putchar('\\'); putchar('t'); break; case '\b': putchar('\\'); putchar('b'); break; case '\\': putchar('\\'); putchar('\\'); break; default: putchar(character); } } return EXIT_SUCCESS; }
Add FS defines, move includes, add member functions
#ifndef _GEN_H #define _GEN_H #define MAKEFILE "Makefile" #include <fstream> #include <sys/param.h> class Generate { public: char cwd[MAXPATHLEN]; const char *defaultMakefile; FILE *Makefile; FILE *newConfig; Generate(); ~Generate(); char *DefineBaseDir(); void WriteMake(); void GenBlankConfig(); void CheckFiles(); void ListDir(const char *Path); int CheckMake(); }; #endif
#ifndef _GEN_H #define _GEN_H #define MAKEFILE "Makefile" #define FS_NONE 0 #define FS_RECURSIVE (1 << 0) #define FS_DEFAULT FS_RECURSIVE #define FS_FOLLOWLINK (1 << 1) #define FS_DOTFILES (1 << 2) #define FS_MATCHDIRS (1 << 3) #include <regex.h> #include <unistd.h> #include <sys/param.h> #include <fstream> class Generate { public: char cwd[MAXPATHLEN]; char *currentDir = get_current_dir_name(); const char *defaultMakefile; FILE *Makefile; FILE *newConfig; Generate(); ~Generate(); char *DefineBaseDir(); void WriteMake(); void Walk(); void GenBlankConfig(); void CheckFiles(); int CheckConfigExists(); int CheckMake(); int GenMakeFromTemplate(); int WalkDir(const char *DirName, char *Pattern, int Spec); int WalkRecur(const char *DirName, regex_t *Expr, int Spec); }; #endif
Fix sprite clipping by using signed rect width
#ifndef INCLUDE_GRAPHICS_H #define INCLUDE_GRAPHICS_H namespace WalrusRPG { namespace Graphics { typedef struct Rect Rect_t; struct Rect { int x, y; unsigned w, h; }; /* * Buffer management */ void buffer_allocate(); void buffer_free(); void buffer_swap(); void buffer_fill(unsigned color); /* * Misc LCD functions */ void lcd_vsync(); /* * Drawing */ void draw_pixel(unsigned x, unsigned y, unsigned short color); void draw_sprite_sheet(const unsigned short *sheet, int x, int y, const Rect_t *window); /* * Sprite manipulation */ unsigned short sprite_pixel_get(const unsigned short *sprite, unsigned x, unsigned y); } } #endif
#ifndef INCLUDE_GRAPHICS_H #define INCLUDE_GRAPHICS_H namespace WalrusRPG { namespace Graphics { typedef struct Rect Rect_t; struct Rect { int x, y; int w, h; }; /* * Buffer management */ void buffer_allocate(); void buffer_free(); void buffer_swap(); void buffer_fill(unsigned color); /* * Misc LCD functions */ void lcd_vsync(); /* * Drawing */ void draw_pixel(unsigned x, unsigned y, unsigned short color); void draw_sprite_sheet(const unsigned short *sheet, int x, int y, const Rect_t *window); /* * Sprite manipulation */ unsigned short sprite_pixel_get(const unsigned short *sprite, unsigned x, unsigned y); } } #endif
Add override keywork to CDSNotificationInterface::NotifyChainLock
// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_DSNOTIFICATIONINTERFACE_H #define BITCOIN_DSNOTIFICATIONINTERFACE_H #include "validationinterface.h" class CDSNotificationInterface : public CValidationInterface { public: CDSNotificationInterface(CConnman& connmanIn): connman(connmanIn) {} virtual ~CDSNotificationInterface() = default; // a small helper to initialize current block height in sub-modules on startup void InitializeCurrentBlockTip(); protected: // CValidationInterface void AcceptedBlockHeader(const CBlockIndex *pindexNew) override; void NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload) override; void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override; void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& block) override; void SyncTransaction(const CTransaction &tx, const CBlockIndex *pindex, int posInBlock) override; void NotifyMasternodeListChanged(const CDeterministicMNList& newList) override; void NotifyChainLock(const CBlockIndex* pindex); private: CConnman& connman; }; #endif // BITCOIN_DSNOTIFICATIONINTERFACE_H
// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_DSNOTIFICATIONINTERFACE_H #define BITCOIN_DSNOTIFICATIONINTERFACE_H #include "validationinterface.h" class CDSNotificationInterface : public CValidationInterface { public: CDSNotificationInterface(CConnman& connmanIn): connman(connmanIn) {} virtual ~CDSNotificationInterface() = default; // a small helper to initialize current block height in sub-modules on startup void InitializeCurrentBlockTip(); protected: // CValidationInterface void AcceptedBlockHeader(const CBlockIndex *pindexNew) override; void NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload) override; void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override; void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& block) override; void SyncTransaction(const CTransaction &tx, const CBlockIndex *pindex, int posInBlock) override; void NotifyMasternodeListChanged(const CDeterministicMNList& newList) override; void NotifyChainLock(const CBlockIndex* pindex) override; private: CConnman& connman; }; #endif // BITCOIN_DSNOTIFICATIONINTERFACE_H
Make the hostname probe for real
#include <sys/utsname.h> #include <libopticonf/var.h> #include "probes.h" /** List of built-in probe functions */ builtinfunc BUILTINS[] = { {"probe_pcpu", runprobe_pcpu}, {"probe_hostname", runprobe_hostname}, {"probe_uname", runprobe_uname}, {NULL, NULL} }; var *runprobe_pcpu (probe *self) { var *res = var_alloc(); var_set_double_forkey (res, "pcpu", ((double)(rand()%1000))/10.0); return res; } var *runprobe_hostname (probe *self) { var *res = var_alloc(); var_set_str_forkey (res, "hostname", "srv1.heikneuter.nl"); return res; } var *runprobe_uname (probe *self) { char out[256]; var *res = var_alloc(); struct utsname uts; uname (&uts); sprintf (out, "%s %s %s", uts.sysname, uts.release, uts.machine); var_set_str_forkey (res, "uname", out); return res; }
#include <sys/utsname.h> #include <unistd.h> #include <libopticonf/var.h> #include "probes.h" /** List of built-in probe functions */ builtinfunc BUILTINS[] = { {"probe_pcpu", runprobe_pcpu}, {"probe_hostname", runprobe_hostname}, {"probe_uname", runprobe_uname}, {NULL, NULL} }; var *runprobe_pcpu (probe *self) { var *res = var_alloc(); var_set_double_forkey (res, "pcpu", ((double)(rand()%1000))/10.0); return res; } var *runprobe_hostname (probe *self) { char out[256]; gethostname (out, 255); var *res = var_alloc(); var_set_str_forkey (res, "hostname", out); return res; } var *runprobe_uname (probe *self) { char out[256]; var *res = var_alloc(); struct utsname uts; uname (&uts); sprintf (out, "%s %s %s", uts.sysname, uts.release, uts.machine); var_set_str_forkey (res, "uname", out); return res; }
Use the imperfect snprintf(3) instead of sprintf(3).
/* * m_name.c -- return a message number as a string * * This code is Copyright (c) 2002, by the authors of nmh. See the * COPYRIGHT file in the root directory of the nmh distribution for * complete copyright information. */ #include <limits.h> #include <h/mh.h> #define STR(s) #s #define SIZE(n) (sizeof STR(n)) /* Includes NUL. */ char * m_name (int num) { static char name[SIZE(INT_MAX)]; if (num <= 0) return "?"; sprintf(name, "%d", num); return name; }
/* * m_name.c -- return a message number as a string * * This code is Copyright (c) 2002, by the authors of nmh. See the * COPYRIGHT file in the root directory of the nmh distribution for * complete copyright information. */ #include <limits.h> #include <h/mh.h> #define STR(s) #s #define SIZE(n) (sizeof STR(n)) /* Includes NUL. */ char * m_name (int num) { static char name[SIZE(INT_MAX)]; if (num <= 0) return "?"; snprintf(name, sizeof name, "%d", num); return name; }
Move OptionsDialog::queryViewTypes into public bool method
#pragma once #include <QtWidgets/QComboBox> #include <QtWidgets/QDialog> #include <QtWidgets/QLabel> #include <QtCore/QObject> #include <QtCore/QString> #include <QtWidgets/QTabWidget> #include <QtWidgets/QWidget> #include "binaryninjaapi.h" #include "viewtype.h" #include "filecontext.h" #include <string> #include <tuple> #include <vector> class BINARYNINJAUIAPI OptionsDialog: public QDialog { Q_OBJECT QString m_fileName; QLabel* m_fileLabel; QLabel* m_objectLabel; QComboBox* m_objectCombo; QTabWidget* m_tab; QLabel* m_notification; bool m_isDatabase; FileContext* m_file = nullptr; FileMetadataRef m_fileMetadata = nullptr; BinaryViewRef m_rawData = nullptr; std::vector<std::tuple<std::string, size_t, std::string, uint64_t, uint64_t, std::string>> m_objects; public: OptionsDialog(QWidget* parent, const QString& name); virtual ~OptionsDialog(); Q_SIGNALS: void openFile(FileContext* file); private Q_SLOTS: void cancel(); void open(); void addSettingsViewForType(const std::string& bvtName); void queryViewTypes(); void viewTabCloseRequested(int index); };
#pragma once #include <QtWidgets/QComboBox> #include <QtWidgets/QDialog> #include <QtWidgets/QLabel> #include <QtCore/QObject> #include <QtCore/QString> #include <QtWidgets/QTabWidget> #include <QtWidgets/QWidget> #include "binaryninjaapi.h" #include "viewtype.h" #include "filecontext.h" #include <string> #include <tuple> #include <vector> class BINARYNINJAUIAPI OptionsDialog: public QDialog { Q_OBJECT QString m_fileName; QLabel* m_fileLabel; QLabel* m_objectLabel; QComboBox* m_objectCombo; QTabWidget* m_tab; QLabel* m_notification; bool m_isDatabase; FileContext* m_file = nullptr; FileMetadataRef m_fileMetadata = nullptr; BinaryViewRef m_rawData = nullptr; std::vector<std::tuple<std::string, size_t, std::string, uint64_t, uint64_t, std::string>> m_objects; public: OptionsDialog(QWidget* parent, const QString& name); virtual ~OptionsDialog(); bool loadViews(); Q_SIGNALS: void openFile(FileContext* file); private Q_SLOTS: void cancel(); void open(); void addSettingsViewForType(const std::string& bvtName); void viewTabCloseRequested(int index); };
Change object to string input
#include "mruby.h" #include "mruby/irep.h" #include "mruby/string.h" #include "simple_module_mrb.h" static mrb_value foo_bar(mrb_state* mrb, mrb_value obj) { mrb_value message; mrb_get_args(mrb, "o", &message); if (!mrb_nil_p(message)) { fprintf(stderr, "bar: %s\n", mrb_str_ptr(message)->ptr); } return mrb_nil_value(); } int main(void) { mrb_state *mrb = mrb_open(); struct RClass *foo_module = mrb_define_module(mrb, "Foo"); mrb_define_class_method(mrb, foo_module, "bar", foo_bar, ARGS_REQ(1)); mrb_load_irep(mrb, simple_module_mrb); mrb_close(mrb); return 0; }
#include "mruby.h" #include "mruby/irep.h" #include "mruby/string.h" #include "simple_module_mrb.h" static mrb_value foo_bar(mrb_state* mrb, mrb_value obj) { mrb_value message; mrb_get_args(mrb, "S", &message); if (!mrb_nil_p(message)) { fprintf(stderr, "bar: %s\n", mrb_str_ptr(message)->ptr); } return mrb_nil_value(); } int main(void) { mrb_state *mrb = mrb_open(); struct RClass *foo_module = mrb_define_module(mrb, "Foo"); mrb_define_class_method(mrb, foo_module, "bar", foo_bar, ARGS_REQ(1)); mrb_load_irep(mrb, simple_module_mrb); mrb_close(mrb); return 0; }
Enable more time on aspiration failure
#ifndef _CONFIG_H #define _CONFIG_H #define ENABLE_FUTILITY_DEPTH 4 #define ENABLE_HISTORY 1 #define ENABLE_KILLERS 1 #define ENABLE_LMR 1 #define ENABLE_NNUE 0 #define ENABLE_NNUE_SIMD 0 #define ENABLE_NULL_MOVE_PRUNING 1 #define ENABLE_REVERSE_FUTILITY_DEPTH 4 #define ENABLE_SEE_Q_PRUNE_LOSING_CAPTURES 1 #define ENABLE_TIMER_ASPIRATION_FAILURE 0 #define ENABLE_TT_CUTOFFS 1 #define ENABLE_TT_MOVES 1 #endif
#ifndef _CONFIG_H #define _CONFIG_H #define ENABLE_FUTILITY_DEPTH 4 #define ENABLE_HISTORY 1 #define ENABLE_KILLERS 1 #define ENABLE_LMR 1 #define ENABLE_NNUE 0 #define ENABLE_NNUE_SIMD 0 #define ENABLE_NULL_MOVE_PRUNING 1 #define ENABLE_REVERSE_FUTILITY_DEPTH 4 #define ENABLE_SEE_Q_PRUNE_LOSING_CAPTURES 1 #define ENABLE_TIMER_ASPIRATION_FAILURE 1 #define ENABLE_TT_CUTOFFS 1 #define ENABLE_TT_MOVES 1 #endif
Add "name" property for convenience.
// // C3DObject.h // Cocoa3D // // Created by Brent Gulanowski on 2014-07-11. // Copyright (c) 2014 Lichen Labs. All rights reserved. // #import <Foundation/Foundation.h> #import <Cocoa3D/C3DCamera.h> @class C3DIndexBuffer, C3DNode, C3DProgram, C3DVertexBuffer; @interface C3DObject : NSObject<C3DVisible> @property (nonatomic, weak) C3DNode *node; @property (nonatomic, strong) C3DProgram *program; @property (nonatomic, strong) C3DIndexBuffer *indexElements; @property (nonatomic, strong) NSArray *vertexBuffers; @property (nonatomic) BOOL ignoresTransform; - (instancetype)initWithType:(C3DObjectType)type; @end
// // C3DObject.h // Cocoa3D // // Created by Brent Gulanowski on 2014-07-11. // Copyright (c) 2014 Lichen Labs. All rights reserved. // #import <Foundation/Foundation.h> #import <Cocoa3D/C3DCamera.h> @class C3DIndexBuffer, C3DNode, C3DProgram, C3DVertexBuffer; @interface C3DObject : NSObject<C3DVisible> @property (nonatomic, weak) C3DNode *node; @property (nonatomic, strong) C3DProgram *program; @property (nonatomic, strong) C3DIndexBuffer *indexElements; @property (nonatomic, strong) NSArray *vertexBuffers; @property (nonatomic, strong) NSString *name; @property (nonatomic) BOOL ignoresTransform; - (instancetype)initWithType:(C3DObjectType)type; @end
Include DmiDevice as part of global includes
/* * This file is part of linux-driver-management. * * Copyright © 2016-2017 Ikey Doherty * * linux-driver-management is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. */ #pragma once #include <device.h> #include <driver.h> #include <gpu-config.h> #include <ldm-enums.h> #include <manager.h> #include <modalias.h> #include <pci-device.h> #include <usb-device.h> #include <drivers/modalias-driver.h> /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=8 tabstop=8 expandtab: * :indentSize=8:tabSize=8:noTabs=true: */
/* * This file is part of linux-driver-management. * * Copyright © 2016-2017 Ikey Doherty * * linux-driver-management is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. */ #pragma once #include <device.h> #include <driver.h> #include <gpu-config.h> #include <ldm-enums.h> #include <manager.h> #include <modalias.h> /* Specialised devices */ #include <dmi-device.h> #include <pci-device.h> #include <usb-device.h> #include <drivers/modalias-driver.h> /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=8 tabstop=8 expandtab: * :indentSize=8:tabSize=8:noTabs=true: */
Change from plend1 to plend to generate errors for devices that have trouble for that case.
/* $Id$ plend and plend1 testing demo. */ #include "plcdemos.h" /*--------------------------------------------------------------------------*\ * main * * Demonstrates absolute positioning of graphs on a page. \*--------------------------------------------------------------------------*/ int main(int argc, const char *argv[]) { /* Parse and process command line arguments */ (void) plparseopts(&argc, argv, PL_PARSE_FULL); /* Initialize plplot */ plinit(); plenv(0., 1., 0., 1., 1, 0); plend1(); plinit(); plenv(0., 10., 0., 10., 1, 0); plend(); exit(0); }
/* $Id$ plend and plend1 testing demo. */ #include "plcdemos.h" /*--------------------------------------------------------------------------*\ * main * * Demonstrates absolute positioning of graphs on a page. \*--------------------------------------------------------------------------*/ int main(int argc, const char *argv[]) { /* Parse and process command line arguments */ (void) plparseopts(&argc, argv, PL_PARSE_FULL); /* Initialize plplot */ plinit(); plenv(0., 1., 0., 1., 1, 0); plend(); plinit(); plenv(0., 10., 0., 10., 1, 0); plend(); exit(0); }
Stop using __strtonum_fallback on Android.
// -*- C++ -*- //===------------------- support/android/locale_bionic.h ------------------===// // // 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. // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_SUPPORT_ANDROID_LOCALE_BIONIC_H #define _LIBCPP_SUPPORT_ANDROID_LOCALE_BIONIC_H #if defined(__BIONIC__) #ifdef __cplusplus extern "C" { #endif #include <stdlib.h> #include <xlocale.h> #ifdef __cplusplus } #endif #include <support/xlocale/__posix_l_fallback.h> #include <support/xlocale/__strtonum_fallback.h> #endif // defined(__BIONIC__) #endif // _LIBCPP_SUPPORT_ANDROID_LOCALE_BIONIC_H
// -*- C++ -*- //===------------------- support/android/locale_bionic.h ------------------===// // // 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. // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_SUPPORT_ANDROID_LOCALE_BIONIC_H #define _LIBCPP_SUPPORT_ANDROID_LOCALE_BIONIC_H #if defined(__BIONIC__) #ifdef __cplusplus extern "C" { #endif #include <stdlib.h> #include <xlocale.h> #ifdef __cplusplus } #endif #include <support/xlocale/__posix_l_fallback.h> #endif // defined(__BIONIC__) #endif // _LIBCPP_SUPPORT_ANDROID_LOCALE_BIONIC_H
Fix bug: Parser<Success>::operator() was not public
// DESCRIPTION // #ifndef HITTOP_PARSER_SUCCESS_H #define HITTOP_PARSER_SUCCESS_H #include <iterator> #include "hittop/parser/parser.h" namespace hittop { namespace parser { struct Success {}; // Always succeed, consuming no input. template <> class Parser<Success> { template <typename Range> auto operator()(const Range &input) const -> Fallible<decltype(std::begin(input))> { return std::begin(input); } }; } // namespace parser } // namespace hittop #endif // HITTOP_PARSER_SUCCESS_H
// DESCRIPTION // #ifndef HITTOP_PARSER_SUCCESS_H #define HITTOP_PARSER_SUCCESS_H #include <iterator> #include "hittop/parser/parser.h" namespace hittop { namespace parser { struct Success {}; // Always succeed, consuming no input. template <> class Parser<Success> { public: template <typename Range> auto operator()(const Range &input) const -> Fallible<decltype(std::begin(input))> { return std::begin(input); } }; } // namespace parser } // namespace hittop #endif // HITTOP_PARSER_SUCCESS_H
Fix build failure from r265600
//===- ScriptParser.h -------------------------------------------*- C++ -*-===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLD_ELF_SCRIPT_PARSER_H #define LLD_ELF_SCRIPT_PARSER_H #include "lld/Core/LLVM.h" #include "llvm/ADT/StringRef.h" namespace lld { namespace elf { class ScriptParserBase { public: ScriptParserBase(StringRef S) : Input(S), Tokens(tokenize(S)) {} virtual ~ScriptParserBase() = default; virtual void run() = 0; protected: void setError(const Twine &Msg); static std::vector<StringRef> tokenize(StringRef S); static StringRef skipSpace(StringRef S); bool atEOF(); StringRef next(); StringRef peek(); bool skip(StringRef Tok); void expect(StringRef Expect); size_t getPos(); void printErrorPos(); std::vector<uint8_t> parseHex(StringRef S); StringRef Input; std::vector<StringRef> Tokens; size_t Pos = 0; bool Error = false; }; } // namespace elf } // namespace lld #endif
//===- ScriptParser.h -------------------------------------------*- C++ -*-===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLD_ELF_SCRIPT_PARSER_H #define LLD_ELF_SCRIPT_PARSER_H #include "lld/Core/LLVM.h" #include "llvm/ADT/StringRef.h" #include <vector> namespace lld { namespace elf { class ScriptParserBase { public: ScriptParserBase(StringRef S) : Input(S), Tokens(tokenize(S)) {} virtual ~ScriptParserBase() = default; virtual void run() = 0; protected: void setError(const Twine &Msg); static std::vector<StringRef> tokenize(StringRef S); static StringRef skipSpace(StringRef S); bool atEOF(); StringRef next(); StringRef peek(); bool skip(StringRef Tok); void expect(StringRef Expect); size_t getPos(); void printErrorPos(); std::vector<uint8_t> parseHex(StringRef S); StringRef Input; std::vector<StringRef> Tokens; size_t Pos = 0; bool Error = false; }; } // namespace elf } // namespace lld #endif
Check readstat_calloc for 0-sized input
#include <stdlib.h> #define MAX_MALLOC_SIZE (1<<20) /* One megabyte ought to be enough for anyone */ void *readstat_malloc(size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { return NULL; } return malloc(len); } void *readstat_calloc(size_t count, size_t size) { if (count > MAX_MALLOC_SIZE || size > MAX_MALLOC_SIZE || count * size > MAX_MALLOC_SIZE) { return NULL; } return calloc(count, size); } void *readstat_realloc(void *ptr, size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { if (ptr) free(ptr); return NULL; } return realloc(ptr, len); }
#include <stdlib.h> #define MAX_MALLOC_SIZE (1<<20) /* One megabyte ought to be enough for anyone */ void *readstat_malloc(size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { return NULL; } return malloc(len); } void *readstat_calloc(size_t count, size_t size) { if (count > MAX_MALLOC_SIZE || size > MAX_MALLOC_SIZE || count * size > MAX_MALLOC_SIZE) { return NULL; } if (count == 0 || size == 0) { return NULL; } return calloc(count, size); } void *readstat_realloc(void *ptr, size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { if (ptr) free(ptr); return NULL; } return realloc(ptr, len); }
Remove stray word 'runtime' from comment
// The Tree-sitter runtime library can be built by compiling this // one source file. // // The following directories must be added to the include path: // - src // - include // - externals/utf8proc #include "./get_changed_ranges.c" #include "./language.c" #include "./lexer.c" #include "./node.c" #include "./parser.c" #include "./stack.c" #include "./subtree.c" #include "./tree_cursor.c" #include "./tree.c" #include "./utf16.c" #include "utf8proc.c"
// The Tree-sitter library can be built by compiling this one source file. // // The following directories must be added to the include path: // - src // - include // - externals/utf8proc #include "./get_changed_ranges.c" #include "./language.c" #include "./lexer.c" #include "./node.c" #include "./parser.c" #include "./stack.c" #include "./subtree.c" #include "./tree_cursor.c" #include "./tree.c" #include "./utf16.c" #include "utf8proc.c"
Change indent and comments to a more readable style
#include "gc.h" #include "tree.h" #include "dict.h" #include "match.h" #include "optimize.h" /* We recursively iterate through all * rules on all the children of the tree * until the expression is irreducible, * i.e. stops changing. * * Also, we (try to) apply the optimization * routine. */ int apply_rules_and_optimize(exp_tree_t** rules, int rc, exp_tree_t *tree) { int success = 0; while (1) { if (matchloop(rules, rc, tree)) { /* * Reduction algorithm * suceeded, print reduced tree */ #ifdef DEBUG_2 printout_tree(*tree); printf("\n"); #endif #ifdef DEBUG printout_tree_infix(*tree); printf("\n"); #endif success = 1; } /* * If optimization succeeds in * modifying the tree, try * reducing the new optimized * tree. */ if (optimize(tree)) { #ifdef DEBUG printf("[optimize] \n"); #ifdef DEBUG_2 printout_tree(*tree); printf("\n"); #endif printout_tree_infix(*tree); printf("\n"); #endif success = 1; continue; } break; } return success; }
#include "gc.h" #include "tree.h" #include "dict.h" #include "match.h" #include "optimize.h" /* * We recursively iterate through all * rules on all the children of the tree * until the expression is irreducible, * i.e. stops changing. * * Also, we (try to) apply the optimization * routine. */ int apply_rules_and_optimize(exp_tree_t** rules, int rc, exp_tree_t *tree) { int success = 0; while (1) { if (matchloop(rules, rc, tree)) { /* * Reduction algorithm * suceeded, print reduced tree */ #ifdef DEBUG_2 printout_tree(*tree); printf("\n"); #endif #ifdef DEBUG printout_tree_infix(*tree); printf("\n"); #endif success = 1; } /* * If optimization succeeds in * modifying the tree, try * reducing the new optimized * tree. */ if (optimize(tree)) { #ifdef DEBUG printf("[optimize] \n"); #ifdef DEBUG_2 printout_tree(*tree); printf("\n"); #endif printout_tree_infix(*tree); printf("\n"); #endif success = 1; continue; } break; } return success; }
Make class more C++11 compliant
#include <atomic> namespace ROOT { /// A spin mutex class which respects the STL interface. class TSpinMutex { public: TSpinMutex() noexcept {} TSpinMutex(const TSpinMutex&) = delete; TSpinMutex( TSpinMutex && ) = delete; ~TSpinMutex(){} void lock(){while (fAFlag.test_and_set(std::memory_order_acquire));} void unlock(){fAFlag.clear(std::memory_order_release);} bool try_lock(){return !fAFlag.test_and_set(std::memory_order_acquire);} private: std::atomic_flag fAFlag = ATOMIC_FLAG_INIT; }; }
#ifndef ROOT_TSpinMutex #define ROOT_TSpinMutex #include <atomic> namespace ROOT { /// A spin mutex class which respects the STL interface. class TSpinMutex { public: TSpinMutex() = default; TSpinMutex(const TSpinMutex&) = delete; ~TSpinMutex(){} TSpinMutex& operator=(const TSpinMutex&) = delete; void lock(){while (fAFlag.test_and_set(std::memory_order_acquire));} void unlock(){fAFlag.clear(std::memory_order_release);} bool try_lock(){return !fAFlag.test_and_set(std::memory_order_acquire);} private: std::atomic_flag fAFlag = ATOMIC_FLAG_INIT; }; } #endif
Remove logging definition from config
#ifndef _R2BOT_CONFIG #define _R2BOT_CONFIG #define _WINSOCK_DEPRECATED_NO_WARNINGS // Logging #ifndef LOGGING # define LOGGING 0 #endif // Define / undefine these for your own use #define USE_KINECT1 #define USE_KINECT2 #define USE_MOTORS #define USE_ULTRASONIC #define USE_R2SERVER #endif
#ifndef _R2BOT_CONFIG #define _R2BOT_CONFIG #define _WINSOCK_DEPRECATED_NO_WARNINGS // Define / undefine these for your own use #define USE_KINECT1 #define USE_KINECT2 #define USE_MOTORS #define USE_ULTRASONIC #define USE_R2SERVER #endif
Test program for playing around with (p)select.
#include <stdio.h> #include <sys/select.h> /* pselect loop test */ int main(int argc, char *argv[]) { struct timespec timeout; fd_set readfds; int fdcount; while(1){ FD_ZERO(&readfds); FD_SET(0, &readfds); timeout.tv_sec = 1; timeout.tv_nsec = 0; fdcount = pselect(1, &readfds, NULL, NULL, &timeout, NULL); printf("loop %d\n", fdcount); } return 0; }
Load and configure core map.
#include "ensemble.h" void c_main( void ) { // Set the system up address_t address = system_load_sram(); data_system ( region_start( 1, address ) ); data_get_bias ( region_start( 2, address ), g_ensemble.n_neurons ); data_get_encoders ( region_start( 3, address ), g_ensemble.n_neurons, g_n_input_dimensions ); data_get_decoders ( region_start( 4, address ), g_ensemble.n_neurons, g_n_output_dimensions ); data_get_keys ( region_start( 5, address ), g_n_output_dimensions ); // Set up routing tables if( leadAp ){ system_lead_app_configured( ); } // Setup timer tick, start spin1_set_timer_tick( g_ensemble.machine_timestep ); spin1_start( ); }
#include "ensemble.h" void c_main( void ) { // Set the system up address_t address = system_load_sram(); data_system ( region_start( 1, address ) ); data_get_bias ( region_start( 2, address ), g_ensemble.n_neurons ); data_get_encoders ( region_start( 3, address ), g_ensemble.n_neurons, g_n_input_dimensions ); data_get_decoders ( region_start( 4, address ), g_ensemble.n_neurons, g_n_output_dimensions ); data_get_keys ( region_start( 5, address ), g_n_output_dimensions ); // Set up routing tables if( leadAp ){ system_lead_app_configured( ); } // Load core map system_load_core_map( ); // Setup timer tick, start spin1_set_timer_tick( g_ensemble.machine_timestep ); spin1_start( ); }
Add font change notifications to reflection view.
#pragma once #include <QtGui/QMouseEvent> #include <QtGui/QPaintEvent> #include <QtWidgets/QWidget> #include "binaryninjaapi.h" #include "dockhandler.h" #include "uitypes.h" class ContextMenuManager; class DisassemblyContainer; class FlowGraphWidget; class Menu; class ViewFrame; class BINARYNINJAUIAPI ReflectionView: public QWidget, public DockContextHandler { Q_OBJECT Q_INTERFACES(DockContextHandler) ViewFrame* m_frame; BinaryViewRef m_data; DisassemblyContainer* m_disassemblyContainer; std::map<BNFunctionGraphType, BNFunctionGraphType> m_ilMap; bool m_ilSync; bool m_locationSync; BNFunctionGraphType m_lastSrcILViewType = NormalFunctionGraph; BNFunctionGraphType m_lastTgtILViewType = NormalFunctionGraph; bool m_ilSyncOverride = false; public: ReflectionView(ViewFrame* frame, BinaryViewRef data); ~ReflectionView(); FlowGraphWidget* getFlowGraphWidget(); void toggleILSync(); void toggleLocationSync(); virtual void notifyViewLocationChanged(View* view, const ViewLocation& viewLocation) override; virtual void notifyVisibilityChanged(bool visible) override; virtual bool shouldBeVisible(ViewFrame* frame) override; protected: virtual void contextMenuEvent(QContextMenuEvent* event) override; };
#pragma once #include <QtGui/QMouseEvent> #include <QtGui/QPaintEvent> #include <QtWidgets/QWidget> #include "binaryninjaapi.h" #include "dockhandler.h" #include "uitypes.h" class ContextMenuManager; class DisassemblyContainer; class FlowGraphWidget; class Menu; class ViewFrame; class BINARYNINJAUIAPI ReflectionView: public QWidget, public DockContextHandler { Q_OBJECT Q_INTERFACES(DockContextHandler) ViewFrame* m_frame; BinaryViewRef m_data; DisassemblyContainer* m_disassemblyContainer; std::map<BNFunctionGraphType, BNFunctionGraphType> m_ilMap; bool m_ilSync; bool m_locationSync; BNFunctionGraphType m_lastSrcILViewType = NormalFunctionGraph; BNFunctionGraphType m_lastTgtILViewType = NormalFunctionGraph; bool m_ilSyncOverride = false; public: ReflectionView(ViewFrame* frame, BinaryViewRef data); ~ReflectionView(); FlowGraphWidget* getFlowGraphWidget(); void toggleILSync(); void toggleLocationSync(); virtual void notifyFontChanged() override; virtual void notifyViewLocationChanged(View* view, const ViewLocation& viewLocation) override; virtual void notifyVisibilityChanged(bool visible) override; virtual bool shouldBeVisible(ViewFrame* frame) override; protected: virtual void contextMenuEvent(QContextMenuEvent* event) override; };
Add hpc padding approach using omp
#include <stdio.h> #include <omp.h> static long num_steps = 1000000000; double step; #define NUM_THREADS 2 #define PAD 8 int main() { int i, nThreads; double pi, sum[NUM_THREADS][PAD]; step = 1.0/(double) num_steps; omp_set_num_threads(NUM_THREADS); #pragma omp parallel { int i, ID, nThreadsInternal; double x; ID = omp_get_thread_num(); nThreadsInternal = omp_get_num_threads(); if(ID == 0) nThreads = nThreadsInternal; for( i=ID, sum[ID][0]=0.0; i<num_steps; i=i+nThreadsInternal) { x = (i+0.5)*step; sum[ID][0] += 4.0/(1.0 + x*x); } } for (i=0, pi=0.0; i<nThreads; i++) pi += sum[i][0]*step; printf("%f\n", pi); }
Fix for eps8266 and athers non avr mcu :)
/* * File: Curve.h * Author: cameron * * Created on October 22, 2013, 1:07 AM */ #ifndef CURVE_H #define CURVE_H #include <avr/pgmspace.h> class Curve { static const uint8_t etable[] PROGMEM; public: static uint8_t exponential(uint8_t); static uint8_t linear(uint8_t); static uint8_t reverse(uint8_t); }; #endif /* CURVE_H */
/* * File: Curve.h * Author: cameron * * Created on October 22, 2013, 1:07 AM */ #ifndef CURVE_H #define CURVE_H #if (defined(__AVR__)) #include <avr\pgmspace.h> #else #include <pgmspace.h> #endif class Curve { static const uint8_t etable[] PROGMEM; public: static uint8_t exponential(uint8_t); static uint8_t linear(uint8_t); static uint8_t reverse(uint8_t); }; #endif /* CURVE_H */
Make chrome use the static square vb when drawing rects.
#ifndef GrGLConfig_chrome_DEFINED #define GrGLConfig_chrome_DEFINED #define GR_SUPPORT_GLES2 1 // gl2ext.h will define these extensions macros but Chrome doesn't provide // prototypes. #define GL_OES_mapbuffer 0 #define GL_IMG_multisampled_render_to_texture 0 #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #define GR_GL_FUNC #define GR_GL_PROC_ADDRESS(X) &X // chrome always assumes BGRA #define GR_GL_32BPP_COLOR_FORMAT GR_BGRA // glGetError() forces a sync with gpu process on chrome #define GR_GL_CHECK_ERROR_START 0 #endif
#ifndef GrGLConfig_chrome_DEFINED #define GrGLConfig_chrome_DEFINED #define GR_SUPPORT_GLES2 1 // gl2ext.h will define these extensions macros but Chrome doesn't provide // prototypes. #define GL_OES_mapbuffer 0 #define GL_IMG_multisampled_render_to_texture 0 #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #define GR_GL_FUNC #define GR_GL_PROC_ADDRESS(X) &X // chrome always assumes BGRA #define GR_GL_32BPP_COLOR_FORMAT GR_BGRA // glGetError() forces a sync with gpu process on chrome #define GR_GL_CHECK_ERROR_START 0 // Using the static vb precludes batching rect-to-rect draws // because there are matrix changes between each one. // Chrome was getting top performance on Windows with // batched rect-to-rect draws. But there seems to be some // regression that now causes any dynamic VB data to perform // very poorly. In any event the static VB seems to get equal // perf to what batching was producing and it always seems to // be better on Linux. #define GR_STATIC_RECT_VB 1 #endif
Implement the equivalent of chmod a+rX.
/* chmod_arx.c - the equivalent of chmod a+rX on the command line. * * The chmod(1) utility uses the chmod(2) system call to perform a series of * changes on file permissions. Particularly, if you invoke it as in: * * $ chmod a+rX <files> * * it will give read permission for every type of user, and will give execute * permission: * * * for every type of user if the file is a directory; * * for every type of user if the file was already executable by some user. * * Usage: * * $ ./chmod_arx <file1> ... <fileN> * * <file1..N> - the files to have their permissions changes * * Author: Renato Mascarenhas Costa */ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> static void helpAndLeave(const char *progname, int status); static void pexit(const char *fCall); int main(int argc, char *argv[]) { if (argc == 1) { helpAndLeave(argv[0], EXIT_FAILURE); } struct stat info; mode_t mode; int i; for (i = 1; i < argc; ++i) { if (stat(argv[i], &info) == -1) { pexit("stat"); } /* every type of user gains read access */ mode = info.st_mode; mode |= S_IRUSR | S_IRGRP | S_IROTH; if (S_ISDIR(info.st_mode)) { /* if file is a directory, everyone gains search permissions */ mode |= S_IXUSR | S_IXGRP | S_IXOTH; } else { /* file is not a directory: only give execute permissions to everyone * if at least one type of user is able to execute it*/ if ((info.st_mode & S_IXUSR) || (info.st_mode & S_IXGRP) || (info.st_mode & S_IXOTH)) { mode |= S_IXUSR | S_IXGRP | S_IXOTH; } } if (chmod(argv[i], mode) == -1) { pexit("chmod"); } } exit(EXIT_SUCCESS); } static void helpAndLeave(const char *progname, int status) { FILE *stream = stderr; if (status == EXIT_SUCCESS) { stream = stdout; } fprintf(stream, "Usage: %s <file> [<file2> <file3> ...]\n", progname); exit(status); } static void pexit(const char *fCall) { perror(fCall); exit(EXIT_FAILURE); }
Add inline annotation for base::MakeCriticalClosure() in platform other than ios.
// 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. #ifndef BASE_CRITICAL_CLOSURE_H_ #define BASE_CRITICAL_CLOSURE_H_ #include "base/callback.h" namespace base { // Returns a closure that will continue to run for a period of time when the // application goes to the background if possible on platforms where // applications don't execute while backgrounded, otherwise the original task is // returned. // // Example: // file_message_loop_proxy_->PostTask( // FROM_HERE, // MakeCriticalClosure(base::Bind(&WriteToDiskTask, path_, data))); // // Note new closures might be posted in this closure. If the new closures need // background running time, |MakeCriticalClosure| should be applied on them // before posting. #if defined(OS_IOS) base::Closure MakeCriticalClosure(const base::Closure& closure); #else base::Closure MakeCriticalClosure(const base::Closure& closure) { // No-op for platforms where the application does not need to acquire // background time for closures to finish when it goes into the background. return closure; } #endif // !defined(OS_IOS) } // namespace base #endif // BASE_CRITICAL_CLOSURE_H_
// 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. #ifndef BASE_CRITICAL_CLOSURE_H_ #define BASE_CRITICAL_CLOSURE_H_ #include "base/callback.h" namespace base { // Returns a closure that will continue to run for a period of time when the // application goes to the background if possible on platforms where // applications don't execute while backgrounded, otherwise the original task is // returned. // // Example: // file_message_loop_proxy_->PostTask( // FROM_HERE, // MakeCriticalClosure(base::Bind(&WriteToDiskTask, path_, data))); // // Note new closures might be posted in this closure. If the new closures need // background running time, |MakeCriticalClosure| should be applied on them // before posting. #if defined(OS_IOS) base::Closure MakeCriticalClosure(const base::Closure& closure); #else inline base::Closure MakeCriticalClosure(const base::Closure& closure) { // No-op for platforms where the application does not need to acquire // background time for closures to finish when it goes into the background. return closure; } #endif // !defined(OS_IOS) } // namespace base #endif // BASE_CRITICAL_CLOSURE_H_
Use scoped_ptr for Panel in PanelBrowserWindowGTK.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_PANELS_PANEL_BROWSER_WINDOW_GTK_H_ #define CHROME_BROWSER_UI_PANELS_PANEL_BROWSER_WINDOW_GTK_H_ #include "chrome/browser/ui/gtk/browser_window_gtk.h" class Panel; class PanelBrowserWindowGtk : public BrowserWindowGtk { public: PanelBrowserWindowGtk(Browser* browser, Panel* panel); virtual ~PanelBrowserWindowGtk() {} // BrowserWindowGtk overrides virtual void Init() OVERRIDE; // BrowserWindow overrides virtual void SetBounds(const gfx::Rect& bounds) OVERRIDE; protected: // BrowserWindowGtk overrides virtual bool GetWindowEdge(int x, int y, GdkWindowEdge* edge) OVERRIDE; virtual bool HandleTitleBarLeftMousePress( GdkEventButton* event, guint32 last_click_time, gfx::Point last_click_position) OVERRIDE; virtual void SaveWindowPosition() OVERRIDE; virtual void SetGeometryHints() OVERRIDE; virtual bool UseCustomFrame() OVERRIDE; private: void SetBoundsImpl(); Panel* panel_; DISALLOW_COPY_AND_ASSIGN(PanelBrowserWindowGtk); }; #endif // CHROME_BROWSER_UI_PANELS_PANEL_BROWSER_WINDOW_GTK_H_
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_PANELS_PANEL_BROWSER_WINDOW_GTK_H_ #define CHROME_BROWSER_UI_PANELS_PANEL_BROWSER_WINDOW_GTK_H_ #include "chrome/browser/ui/gtk/browser_window_gtk.h" class Panel; class PanelBrowserWindowGtk : public BrowserWindowGtk { public: PanelBrowserWindowGtk(Browser* browser, Panel* panel); virtual ~PanelBrowserWindowGtk() {} // BrowserWindowGtk overrides virtual void Init() OVERRIDE; // BrowserWindow overrides virtual void SetBounds(const gfx::Rect& bounds) OVERRIDE; protected: // BrowserWindowGtk overrides virtual bool GetWindowEdge(int x, int y, GdkWindowEdge* edge) OVERRIDE; virtual bool HandleTitleBarLeftMousePress( GdkEventButton* event, guint32 last_click_time, gfx::Point last_click_position) OVERRIDE; virtual void SaveWindowPosition() OVERRIDE; virtual void SetGeometryHints() OVERRIDE; virtual bool UseCustomFrame() OVERRIDE; private: void SetBoundsImpl(); scoped_ptr<Panel> panel_; DISALLOW_COPY_AND_ASSIGN(PanelBrowserWindowGtk); }; #endif // CHROME_BROWSER_UI_PANELS_PANEL_BROWSER_WINDOW_GTK_H_
Add SK_API to null canvas create method
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkNullCanvas_DEFINED #define SkNullCanvas_DEFINED #include "SkBitmap.h" class SkCanvas; /** * Creates a canvas that draws nothing. This is useful for performance testing. */ SkCanvas* SkCreateNullCanvas(); #endif
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkNullCanvas_DEFINED #define SkNullCanvas_DEFINED #include "SkBitmap.h" class SkCanvas; /** * Creates a canvas that draws nothing. This is useful for performance testing. */ SK_API SkCanvas* SkCreateNullCanvas(); #endif
Fix build after MacOS merge
/* Copyright 2014 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #elif TARGET_OS_OSX #import <Cocoa/Cocoa.h> #endif /** The Matrix iOS SDK version. */ FOUNDATION_EXPORT NSString *MatrixSDKVersion; #import <MatrixSDK/MXRestClient.h> #import <MatrixSDK/MXSession.h> #import <MatrixSDK/MXError.h> #import <MatrixSDK/MXStore.h> #import <MatrixSDK/MXNoStore.h> #import <MatrixSDK/MXMemoryStore.h> #import <MatrixSDK/MXFileStore.h> #import <MatrixSDK/MXCoreDataStore.h> #import <MatrixSDK/MXEventsEnumeratorOnArray.h> #import <MatrixSDK/MXEventsByTypesEnumeratorOnArray.h> #import <MatrixSDK/MXLogger.h> #import "MXTools.h" #import "NSData+MatrixSDK.h" #import "MXSDKOptions.h" #import "MXMediaManager.h" #import "MXLRUCache.h"
/* Copyright 2014 OpenMarket Ltd 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. */ #import <Foundation/Foundation.h> /** The Matrix iOS SDK version. */ FOUNDATION_EXPORT NSString *MatrixSDKVersion; #import <MatrixSDK/MXRestClient.h> #import <MatrixSDK/MXSession.h> #import <MatrixSDK/MXError.h> #import <MatrixSDK/MXStore.h> #import <MatrixSDK/MXNoStore.h> #import <MatrixSDK/MXMemoryStore.h> #import <MatrixSDK/MXFileStore.h> #import <MatrixSDK/MXCoreDataStore.h> #import <MatrixSDK/MXEventsEnumeratorOnArray.h> #import <MatrixSDK/MXEventsByTypesEnumeratorOnArray.h> #import <MatrixSDK/MXLogger.h> #import "MXTools.h" #import "NSData+MatrixSDK.h" #import "MXSDKOptions.h" #import "MXMediaManager.h" #import "MXLRUCache.h"
Add problematic example due to widening :'(
// SKIP PARAM: --set ana.activated[+] apron --set ana.path_sens[+] threadflag --sets exp.apron.privatization mutex-meet-tid --set ana.activated[-] threadJoins // Fig 5a from Miné 2014 #include <pthread.h> #include <stdio.h> int x; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { int top; while(top) { pthread_mutex_lock(&mutex); if(x<100) { x++; } pthread_mutex_unlock(&mutex); } return NULL; } int main(void) { int top, top2; pthread_t id; pthread_t id2; pthread_create(&id, NULL, t_fun, NULL); pthread_create(&id2, NULL, t_fun, NULL); pthread_mutex_lock(&mutex); assert(x <= 100); pthread_mutex_unlock(&mutex); return 0; }
Add basic ScannerContext create / destroy functions
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "scanner.h" /** * Opens a file in read-only mode and creates a scanner context for it. */ ScannerContext* scanner_open(char* filename) { // open the given file FILE* stream = fopen(filename, "r"); if (stream == NULL) { return NULL; } // create a context pointer ScannerContext* context = (ScannerContext*)malloc(sizeof(ScannerContext)); context->line = 0; context->column = 0; context->stream = stream; return context; } /** * Opens a string as a stream and creates a scanner context for it. */ ScannerContext* scanner_open_string(char* string) { // create a stream for the char array FILE* stream = fmemopen(string, strlen(string), "r"); if (stream == NULL) { return NULL; } // create a context pointer ScannerContext* context = (ScannerContext*)malloc(sizeof(ScannerContext)); context->line = 0; context->column = 0; context->stream = stream; return context; } /** * Closes a scanner context and its associated input stream. */ Error scanner_close(ScannerContext* context) { // context shouldn't be null assert(context != NULL); // close the stream handle fclose(context->stream); // free the pointer free(context); return E_SUCCESS; }
Write failing assert for count
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node* next; }; int Length(struct node* head) { int count = 0; struct node* current = head; while (current != NULL) { count++; current=current->next; } return(count); } // Given a reference (pointer to pointer) to the head // of a list and an int, push a new node on the front of the list. // Creates a new node with the int, links the list off the .next of the // new node, and finally changes the head to point to the new node. void Push(struct node** headRef, int newData) { struct node* newNode = (struct node*) malloc(sizeof(struct node)); // allocate node newNode->data = newData;// put in the data newNode->next = (*headRef);// link the old list off the new node (*headRef) = newNode;// move the head to point to the new node } // Build and return the list {1, 2, 3} struct node* BuildOneTwoThree() { struct node* head = NULL;// Start with the empty list Push(&head, 3);// Use Push() to add all the data Push(&head, 2); Push(&head, 1); return(head); } int main() { return 0; }
#include<stdio.h> #include<stdlib.h> #include<assert.h> struct node { int data; struct node* next; }; int Length(struct node* head) { int count = 0; struct node* current = head; while (current != NULL) { count++; current=current->next; } return(count); } // Given a reference (pointer to pointer) to the head // of a list and an int, push a new node on the front of the list. // Creates a new node with the int, links the list off the .next of the // new node, and finally changes the head to point to the new node. void Push(struct node** headRef, int newData) { struct node* newNode = (struct node*) malloc(sizeof(struct node)); // allocate node newNode->data = newData;// put in the data newNode->next = (*headRef);// link the old list off the new node (*headRef) = newNode;// move the head to point to the new node } // Build and return the list {1, 2, 3} struct node* BuildOneTwoThree() { struct node* head = NULL;// Start with the empty list Push(&head, 3);// Use Push() to add all the data Push(&head, 2); Push(&head, 1); return(head); } //1 - Count() //Builds a list and counts the number of times a given int occurs int Count(struct node* head, int search) { return 0; } void CountTest() { struct node* list; list = BuildOneTwoThree(); int count = Count(list, 2); assert(count == 1); } int main() { CountTest(); return 0; }
Fix Social framework headers to be self-contained.
//****************************************************************************** // // Copyright (c) 2016 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //****************************************************************************** #pragma once #import <Social/SocialExport.h> @class NSString; typedef void (^SLComposeSheetConfigurationItemTapHandler)(void); SOCIAL_EXPORT_CLASS @interface SLComposeSheetConfigurationItem : NSObject @property (copy, nonatomic) SLComposeSheetConfigurationItemTapHandler tapHandler STUB_PROPERTY; @property (copy, nonatomic) NSString* title STUB_PROPERTY; @property (copy, nonatomic) NSString* value STUB_PROPERTY; @property (assign, nonatomic) BOOL valuePending STUB_PROPERTY; - (instancetype)init STUB_METHOD; @end
//****************************************************************************** // // Copyright (c) 2016 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //****************************************************************************** #pragma once #import <Social/SocialExport.h> #import <Foundation/NSObject.h> @class NSString; typedef void (^SLComposeSheetConfigurationItemTapHandler)(void); SOCIAL_EXPORT_CLASS @interface SLComposeSheetConfigurationItem : NSObject @property (copy, nonatomic) SLComposeSheetConfigurationItemTapHandler tapHandler STUB_PROPERTY; @property (copy, nonatomic) NSString* title STUB_PROPERTY; @property (copy, nonatomic) NSString* value STUB_PROPERTY; @property (assign, nonatomic) BOOL valuePending STUB_PROPERTY; - (instancetype)init STUB_METHOD; @end
Add prefix file for ProjectBuilder samples
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ // Objective C only #if __OBJC__ #endif // C++ only #if defined(__cplusplus) #include <algorithm> #include <cstring> #include <cstdlib> #include <cctype> #include <cstdio> #include <memory> #endif // Standard C headers #include <stddef.h> #include <stdlib.h> #include <string.h> #include <stdlib.h> // Carbon Headers #include <Carbon/Carbon.h> #include <CoreFoundation/CoreFoundation.h>
Increase UART transmit buffer size
/* Copyright 2018 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* Bip board configuration */ #ifndef __CROS_EC_BOARD_H #define __CROS_EC_BOARD_H /* Select Baseboard features */ #define VARIANT_OCTOPUS_EC_ITE8320 #define VARIANT_OCTOPUS_CHARGER_BQ25703 #include "baseboard.h" /* Optional features */ #define CONFIG_SYSTEM_UNLOCKED /* Allow dangerous commands while in dev. */ /* Hardware for proto bip does not support ec keyboard backlight control. */ #undef CONFIG_PWM #undef CONFIG_PWM_KBLIGHT #ifndef __ASSEMBLER__ #include "gpio_signal.h" #include "registers.h" enum adc_channel { ADC_VBUS_C0, ADC_VBUS_C1, ADC_CH_COUNT }; /* List of possible batteries */ enum battery_type { BATTERY_PANASONIC, BATTERY_SANYO, BATTERY_TYPE_COUNT, }; #endif /* !__ASSEMBLER__ */ #endif /* __CROS_EC_BOARD_H */
/* Copyright 2018 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* Bip board configuration */ #ifndef __CROS_EC_BOARD_H #define __CROS_EC_BOARD_H /* Select Baseboard features */ #define VARIANT_OCTOPUS_EC_ITE8320 #define VARIANT_OCTOPUS_CHARGER_BQ25703 #include "baseboard.h" /* Optional features */ #define CONFIG_SYSTEM_UNLOCKED /* Allow dangerous commands while in dev. */ /* Hardware for proto bip does not support ec keyboard backlight control. */ #undef CONFIG_PWM #undef CONFIG_PWM_KBLIGHT #undef CONFIG_UART_TX_BUF_SIZE #define CONFIG_UART_TX_BUF_SIZE 4096 #ifndef __ASSEMBLER__ #include "gpio_signal.h" #include "registers.h" enum adc_channel { ADC_VBUS_C0, ADC_VBUS_C1, ADC_CH_COUNT }; /* List of possible batteries */ enum battery_type { BATTERY_PANASONIC, BATTERY_SANYO, BATTERY_TYPE_COUNT, }; #endif /* !__ASSEMBLER__ */ #endif /* __CROS_EC_BOARD_H */
Add portable file to handle headless asserts etc. on Windows
#ifndef PCRT_H #define PCRT_H #ifdef __cplusplus extern "C" { #endif /* * Assertions and pointer violations in debug mode may trigger a dialog * on Windows. When running headless this is not helpful, but * unfortunately it cannot be disabled with a compiler option so code * must be injected into the runtime early in the main function. * A call to the provided `init_headless_crt()` macro does this in * a portable manner. * * See also: * https://stackoverflow.com/questions/13943665/how-can-i-disable-the-debug-assertion-dialog-on-windows */ #if defined(_WIN32) #include <crtdbg.h> #include <stdio.h> #include <stdlib.h> static int _portable_msvc_headless_report_hook( int reportType, char *message, int *returnValue ) { fprintf(stderr, "CRT[%d]: %s\n", reportType, message); *returnValue = 1; exit(1); } #define init_headless_crt() _CrtSetReportHook(_portable_msvc_headless_report_hook) #else #define init_headless_crt() ((void)0) #endif #ifdef __cplusplus } #endif #endif /* PCRT_H */
Add enum for compaction table.
//===-- llvm/Bytecode/Format.h - VM bytecode file format info ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines intrinsic constants that are useful to libraries that // need to hack on bytecode files directly, like the reader and writer. // //===----------------------------------------------------------------------===// #ifndef LLVM_BYTECODE_FORMAT_H #define LLVM_BYTECODE_FORMAT_H namespace llvm { class BytecodeFormat { // Throw the constants into a poorman's namespace... BytecodeFormat(); // do not implement public: // ID Numbers that are used in bytecode files... enum FileBlockIDs { // File level identifiers... Module = 0x01, // Module subtypes: Function = 0x11, ConstantPool, SymbolTable, ModuleGlobalInfo, GlobalTypePlane, // Function subtypes: // Can also have ConstantPool block // Can also have SymbolTable block BasicBlock = 0x31, // May contain many basic blocks // InstructionList - The instructions in the body of a function. This // superceeds the old BasicBlock node. InstructionList = 0x32, }; }; } // End llvm namespace #endif
//===-- llvm/Bytecode/Format.h - VM bytecode file format info ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines intrinsic constants that are useful to libraries that // need to hack on bytecode files directly, like the reader and writer. // //===----------------------------------------------------------------------===// #ifndef LLVM_BYTECODE_FORMAT_H #define LLVM_BYTECODE_FORMAT_H namespace llvm { class BytecodeFormat { // Throw the constants into a poorman's namespace... BytecodeFormat(); // do not implement public: // ID Numbers that are used in bytecode files... enum FileBlockIDs { // File level identifiers... Module = 0x01, // Module subtypes: Function = 0x11, ConstantPool, SymbolTable, ModuleGlobalInfo, GlobalTypePlane, // Function subtypes: // Can also have ConstantPool block // Can also have SymbolTable block BasicBlock = 0x31,// May contain many basic blocks (obsolete since LLVM 1.1) // InstructionList - The instructions in the body of a function. This // superceeds the old BasicBlock node used in LLVM 1.0. InstructionList = 0x32, // CompactionTable - blocks with this id are used to define local remapping // tables for a function, allowing the indices used within the function to // be as small as possible. This often allows the instructions to be // encoded more efficiently. CompactionTable = 0x33, }; }; } // End llvm namespace #endif
Use stdbool.h for bool definition.
#ifndef _CGMINER_MINER_H #define _CGMINER_MINER_H #include <stdint.h> struct work { uint8_t *midstate; uint8_t *data; }; #ifndef MAX #define MAX(a,b) ((a) < (b) ? (b) : (a)) #endif #ifndef MIN #define MIN(a,b) ((a) > (b) ? (b) : (a)) #endif typedef enum { false = 0, true = 1 } bool; #endif
#ifndef _CGMINER_MINER_H #define _CGMINER_MINER_H #include <stdint.h> #include <stdbool.h> struct work { uint8_t *midstate; uint8_t *data; }; #ifndef MAX #define MAX(a,b) ((a) < (b) ? (b) : (a)) #endif #ifndef MIN #define MIN(a,b) ((a) > (b) ? (b) : (a)) #endif #endif
Move things around the rxt_node struct and clean up comments. Breaks ABI.
#ifndef RADIXTREE #define RADIXTREE typedef struct rxt_node { int color; char *key; // only stores pos and beyond int level; // tree level; for debug only int parent_id; //for debug only int pos; void *value; struct rxt_node *parent; struct rxt_node *left; struct rxt_node *right; }rxt_node; void rxt_print(rxt_node*); // only for debugging small trees int rxt_put(char*, void *, rxt_node*); void* rxt_get(char*, rxt_node*); void* rxt_delete(char*, rxt_node*); void rxt_free(rxt_node *); rxt_node *rxt_init(); #endif // RADIXTREE
#ifndef RADIXTREE #define RADIXTREE typedef struct rxt_node { int color; char *key; void *value; int pos; // bit index of the key to compare at (critical position) int level; // tree level; for debug only int parent_id; //for debug only struct rxt_node *parent; struct rxt_node *left; struct rxt_node *right; }rxt_node; void rxt_print(rxt_node*); // only for debugging small trees int rxt_put(char*, void *, rxt_node*); void* rxt_get(char*, rxt_node*); void* rxt_delete(char*, rxt_node*); void rxt_free(rxt_node *); rxt_node *rxt_init(); #endif // RADIXTREE
Add a function to stringify boards.
#include <stdlib.h> /** * @author: Hendrik Werner */ #define BOARD_HEIGHT 50 #define BOARD_WIDTH 50 typedef struct Position { int row; int col; } Position; typedef enum Cell { EMPTY ,SNAKE ,FOOD } Cell; typedef Cell Board[BOARD_HEIGHT][BOARD_WIDTH]; typedef enum Direction {LEFT, UP, RIGHT, DOWN} Direction; /** * Represent a cell using a character. * * @return A character representing the content of the cell provided. */ char representCell(const Cell c) { switch (c) { case SNAKE: return 'S'; case FOOD: return 'F'; default: return '.'; } } int main() { return EXIT_SUCCESS; }
#include <stdlib.h> /** * @author: Hendrik Werner */ #define BOARD_HEIGHT 50 #define BOARD_WIDTH 50 typedef struct Position { int row; int col; } Position; typedef enum Cell { EMPTY ,SNAKE ,FOOD } Cell; typedef Cell Board[BOARD_HEIGHT][BOARD_WIDTH]; typedef enum Direction {LEFT, UP, RIGHT, DOWN} Direction; /** * Represent a cell using a character. * * @return A character representing the content of the cell provided. */ char representCell(const Cell c) { switch (c) { case SNAKE: return 'S'; case FOOD: return 'F'; default: return '.'; } } /** * Create a string representation of some board. * * @param board The board that is to be represented. * * @return A string representation of the given board. The caller must take care * to free the string returned. */ char *stringify(const Board board) { char *str = malloc(BOARD_WIDTH * BOARD_HEIGHT + BOARD_HEIGHT + 1); size_t pos = 0; for (size_t row = 0; row < BOARD_HEIGHT; row++) { for (size_t col = 0; col < BOARD_WIDTH; col++) { str[pos++] = representCell(board[row][col]); } str[pos++] = '\n'; } str[pos] = '\0'; return str; } int main() { return EXIT_SUCCESS; }
Fix missing ; in struct implementation
#include "stack.h" struct Stack { size_t size; size_t top; void** e; } Stack* Stack_Create(size_t n) { Stack* s = (Stack *)malloc(sizeof(Stack)); s->size = n; s->top = 0; s->e = (void**)malloc(sizeof(void*) * (n + 1)); return s; } int Stack_Empty(Stack* s) { if (s->top == 0) { return 1; } else { return 0; } } void Stack_Push(Stack* s, void* e) { if (s == NULL) return; if (s->top == s->size) return; s->top = s->top + 1; s->e[s->top] = e; } void* Stack_Pop(Stack* s) { if (Stack_Empty(s)) return; s->top = s->top - 1; return s->e[s->top+1]; } void Stack_Destroy(Stack* s) { if (s == NULL) return; free(s->e); free(s); }
#include "stack.h" struct Stack { size_t size; size_t top; void** e; }; Stack* Stack_Create(size_t n) { Stack* s = (Stack *)malloc(sizeof(Stack)); s->size = n; s->top = 0; s->e = (void**)malloc(sizeof(void*) * (n + 1)); return s; } int Stack_Empty(Stack* s) { if (s->top == 0) { return 1; } else { return 0; } } void Stack_Push(Stack* s, void* e) { if (s == NULL) return; if (s->top == s->size) return; s->top = s->top + 1; s->e[s->top] = e; } void* Stack_Pop(Stack* s) { if (Stack_Empty(s)) return; s->top = s->top - 1; return s->e[s->top+1]; } void Stack_Destroy(Stack* s) { if (s == NULL) return; free(s->e); free(s); }
Use new stack inspection function. Enable JIT compilation.
/* * alpha/netbsd/jit-md.h * NetBSD Alpha JIT configuration information. * * Copyright (c) 2001 * Edouard G. Parmelan. All rights reserved. * * Copyright (c) 2001 * Transvirtual Technologies, Inc. All rights reserved. * * See the file "license.terms" for information on usage and redistribution * of this file. */ #ifndef __alpha_netbsd_jit_md_h #define __alpha_netbsd_jit_md_h /**/ /* Include common information. */ /**/ #include "alpha/jit.h" /**/ /* Extra exception handling information. */ /**/ /* Function prototype for signal handlers */ #define EXCEPTIONPROTO \ int sig, int code, struct sigcontext* ctx /* Structure of exception frame on stack */ typedef struct _exceptionFrame { char *pc; char *sp; char *fp; } exceptionFrame; int __alpha_ra (int *pc); exceptionFrame *__alpha_nextFrame (exceptionFrame *frame); /* Extract PC, FP and SP from the given frame */ #define PCFRAME(f) ((f)->pc) #define SPFRAME(f) ((f)->sp) #define FPFRAME(f) ((f)->fp) /* Get the first exception frame from a subroutine call */ #define FIRSTFRAME(f, o) \ (f).sp = 0; \ __alpha_nextFrame(&f) /* Get the next frame in the chain */ #define NEXTFRAME(f) \ __alpha_nextFrame(f) /* Get the first exception frame from a signal handler */ #define EXCEPTIONFRAME(f, c) \ (f).pc = (__alpha_ra ((c)->sc_pc) == -1) \ ? (c)->sc_pc \ : (c)->sc_regs[__alpha_ra ((c)->sc_pc)]; \ (f).sp = (c)->sc_regs[30]; \ (f).fp = (c)->sc_regs[15] #endif
Use an assert() for the REQ() macro instead of making up our own assertion.
/* Parse tree node interface */ #ifndef Py_NODE_H #define Py_NODE_H #ifdef __cplusplus extern "C" { #endif typedef struct _node { short n_type; char *n_str; int n_lineno; int n_nchildren; struct _node *n_child; } node; extern DL_IMPORT(node *) PyNode_New(int type); extern DL_IMPORT(int) PyNode_AddChild(node *n, int type, char *str, int lineno); extern DL_IMPORT(void) PyNode_Free(node *n); /* Node access functions */ #define NCH(n) ((n)->n_nchildren) #define CHILD(n, i) (&(n)->n_child[i]) #define TYPE(n) ((n)->n_type) #define STR(n) ((n)->n_str) /* Assert that the type of a node is what we expect */ #ifndef Py_DEBUG #define REQ(n, type) { /*pass*/ ; } #else #define REQ(n, type) \ { if (TYPE(n) != (type)) { \ fprintf(stderr, "FATAL: node type %d, required %d\n", \ TYPE(n), type); \ abort(); \ } } #endif extern DL_IMPORT(void) PyNode_ListTree(node *); #ifdef __cplusplus } #endif #endif /* !Py_NODE_H */
/* Parse tree node interface */ #ifndef Py_NODE_H #define Py_NODE_H #ifdef __cplusplus extern "C" { #endif typedef struct _node { short n_type; char *n_str; int n_lineno; int n_nchildren; struct _node *n_child; } node; extern DL_IMPORT(node *) PyNode_New(int type); extern DL_IMPORT(int) PyNode_AddChild(node *n, int type, char *str, int lineno); extern DL_IMPORT(void) PyNode_Free(node *n); /* Node access functions */ #define NCH(n) ((n)->n_nchildren) #define CHILD(n, i) (&(n)->n_child[i]) #define TYPE(n) ((n)->n_type) #define STR(n) ((n)->n_str) /* Assert that the type of a node is what we expect */ #define REQ(n, type) assert(TYPE(n) == (type)) extern DL_IMPORT(void) PyNode_ListTree(node *); #ifdef __cplusplus } #endif #endif /* !Py_NODE_H */
Include glx as a gl-header
#ifndef GL_HEADERS_H #define GL_HEADERS_H #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #define WINGDIAPI KHRONOS_APICALL #define APIENTRY KHRONOS_APIENTRY #endif #include <codegen/input/egl.h> #include <codegen/input/eglext.h> #include <codegen/input/GL.h> #include <codegen/input/glext.h> #ifdef _WIN32 #include <codegen/input/wglext.h> #endif #endif
#ifndef GL_HEADERS_H #define GL_HEADERS_H #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #define WINGDIAPI KHRONOS_APICALL #define APIENTRY KHRONOS_APIENTRY #endif #include <codegen/input/egl.h> #include <codegen/input/eglext.h> #include <codegen/input/GL.h> #include <codegen/input/glext.h> #ifdef _WIN32 #include <codegen/input/wglext.h> #else #include <codegen/input/glx.h> //#include <codegen/input/glxext.h> #endif #endif