Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Create String subsystem to handle all string related stuff | /*
* This file is part of Kotaka, a mud library for DGD
* http://github.com/shentino/kotaka
*
* Copyright (C) 2013 Raymond Jennings
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <kernel/kernel.h>
#include <kotaka/paths.h>
inherit LIB_INITD;
inherit UTILITY_COMPILE;
static void create()
{
KERNELD->set_global_access("String", 1);
load_dir("sys", 1);
}
| |
Add static function to convert NPN strings to an enum. | // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_
#define NET_SOCKET_SSL_CLIENT_SOCKET_H_
#include "net/socket/client_socket.h"
namespace net {
class SSLCertRequestInfo;
class SSLInfo;
// A client socket that uses SSL as the transport layer.
//
// NOTE: The SSL handshake occurs within the Connect method after a TCP
// connection is established. If a SSL error occurs during the handshake,
// Connect will fail.
//
class SSLClientSocket : public ClientSocket {
public:
// Gets the SSL connection information of the socket.
virtual void GetSSLInfo(SSLInfo* ssl_info) = 0;
// Gets the SSL CertificateRequest info of the socket after Connect failed
// with ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
virtual void GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) = 0;
};
} // namespace net
#endif // NET_SOCKET_SSL_CLIENT_SOCKET_H_
| // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_
#define NET_SOCKET_SSL_CLIENT_SOCKET_H_
#include "net/socket/client_socket.h"
namespace net {
class SSLCertRequestInfo;
class SSLInfo;
// A client socket that uses SSL as the transport layer.
//
// NOTE: The SSL handshake occurs within the Connect method after a TCP
// connection is established. If a SSL error occurs during the handshake,
// Connect will fail.
//
class SSLClientSocket : public ClientSocket {
public:
// Next Protocol Negotiation (NPN), if successful, results in agreement on an
// application-level string that specifies the application level protocol to
// use over the TLS connection. NextProto enumerates the application level
// protocols that we recognise.
enum NextProto {
kProtoUnknown = 0,
kProtoHTTP11 = 1,
kProtoSPDY = 2,
};
// Gets the SSL connection information of the socket.
virtual void GetSSLInfo(SSLInfo* ssl_info) = 0;
// Gets the SSL CertificateRequest info of the socket after Connect failed
// with ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
virtual void GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) = 0;
static NextProto NextProtoFromString(const std::string& proto_string) {
if (proto_string == "http1.1") {
return kProtoHTTP11;
} else if (proto_string == "spdy") {
return kProtoSPDY;
} else {
return kProtoUnknown;
}
}
};
} // namespace net
#endif // NET_SOCKET_SSL_CLIENT_SOCKET_H_
|
Fix HelloWorld attach test for Linux kernels with ptrace ancestor lockdown. | #include <stdio.h>
int main(int argc, char const *argv[]) {
printf("Hello world.\n"); // Set break point at this line.
if (argc == 1)
return 0;
// Waiting to be attached by the debugger, otherwise.
char line[100];
while (fgets(line, sizeof(line), stdin)) { // Waiting to be attached...
printf("input line=>%s\n", line);
}
printf("Exiting now\n");
}
| #include <stdio.h>
#if defined(__linux__)
#include <sys/prctl.h>
#endif
int main(int argc, char const *argv[]) {
#if defined(__linux__)
// Immediately enable any ptracer so that we can allow the stub attach
// operation to succeed. Some Linux kernels are locked down so that
// only an ancestor process can be a ptracer of a process. This disables that
// restriction. Without it, attach-related stub tests will fail.
#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
int prctl_result;
// For now we execute on best effort basis. If this fails for
// some reason, so be it.
prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
(void) prctl_result;
#endif
#endif
printf("Hello world.\n"); // Set break point at this line.
if (argc == 1)
return 0;
// Waiting to be attached by the debugger, otherwise.
char line[100];
while (fgets(line, sizeof(line), stdin)) { // Waiting to be attached...
printf("input line=>%s\n", line);
}
printf("Exiting now\n");
}
|
Remove double include of a file | #ifndef MODINCLUDE_H
#define MODINCLUDE_H
#include "../main.h"
class ConfigReader;
class ModuleInterface; // forward-declare so it can be used in modules and server
#include "../connection.h" // declare other classes that use it
#include "../modules.h"
#include "../config.h"
#include "../modules.h"
#endif
| #ifndef MODINCLUDE_H
#define MODINCLUDE_H
#include "../main.h"
class ConfigReader;
class ModuleInterface; // forward-declare so it can be used in modules and server
#include "../connection.h" // declare other classes that use it
#include "../modules.h"
#include "../config.h"
#endif
|
Include stdlib.h for malloc not to bail | #include "lb_vector.h"
Vector lb_create_vector(Scalar* data, unsigned int length) {
Vector v;
v.data = data;
v.length = length;
return v;
}
Vector lb_allocate_vector(unsigned int length) {
Scalar* ptr = (Scalar*)malloc(sizeof(Scalar) * length);
return lb_create_vector(ptr, length);
}
// Result = Vector dot Vector
void lbdp(Vector a, Vector b, Scalar* result) {
*result = 0.0;
int i;
for(i = 0; i < a.length; i++) *result += a.data[i] * b.data[i];
}
// Result = Scalar * Vector
void lbstv(Scalar s, Vector v, Vector result) {
int i;
for(i = 0; i < v.length; i++) result.data[i] = s * v.data[i];
}
| #include <stdlib.h>
#include "lb_vector.h"
Vector lb_create_vector(Scalar* data, unsigned int length) {
Vector v;
v.data = data;
v.length = length;
return v;
}
Vector lb_allocate_vector(unsigned int length) {
Scalar* ptr = (Scalar*)malloc(sizeof(Scalar) * length);
return lb_create_vector(ptr, length);
}
// Result = Vector dot Vector
void lbdp(Vector a, Vector b, Scalar* result) {
*result = 0.0;
int i;
for(i = 0; i < a.length; i++) *result += a.data[i] * b.data[i];
}
// Result = Scalar * Vector
void lbstv(Scalar s, Vector v, Vector result) {
int i;
for(i = 0; i < v.length; i++) result.data[i] = s * v.data[i];
}
|
Fix AConfigurationEvent dup() return value | #ifndef _ANDROIDCONFIGURATIONEVENT_H_
#define _ANDROIDCONFIGURATIONEVENT_H_
#include <ConfigurationEvent.h>
#include <android/native_window.h>
class AndroidConfigurationEvent : public ConfigurationEvent {
public:
AndroidConfigurationEvent(double _timestamp, ANativeWindow * _window)
: ConfigurationEvent(_timestamp), window(_window) { }
ANativeWindow * getWindow() { return window; }
std::shared_ptr<EventBase> dup() const { return NULL; }
void dispatch(Element & element);
private:
ANativeWindow * window = 0;
};
#endif
| #ifndef _ANDROIDCONFIGURATIONEVENT_H_
#define _ANDROIDCONFIGURATIONEVENT_H_
#include <ConfigurationEvent.h>
#include <android/native_window.h>
class AndroidConfigurationEvent : public ConfigurationEvent {
public:
AndroidConfigurationEvent(double _timestamp, ANativeWindow * _window)
: ConfigurationEvent(_timestamp), window(_window) { }
ANativeWindow * getWindow() { return window; }
std::shared_ptr<EventBase> dup() const { return std::make_shared<AndroidConfigurationEvent>(*this); }
void dispatch(Element & element);
private:
ANativeWindow * window = 0;
};
#endif
|
Fix typo in a comment: it's base58, not base48. | #ifndef BITCOINADDRESSVALIDATOR_H
#define BITCOINADDRESSVALIDATOR_H
#include <QValidator>
/** Base48 entry widget validator.
Corrects near-miss characters and refuses characters that are no part of base48.
*/
class BitcoinAddressValidator : public QValidator
{
Q_OBJECT
public:
explicit BitcoinAddressValidator(QObject *parent = 0);
State validate(QString &input, int &pos) const;
static const int MaxAddressLength = 35;
};
#endif // BITCOINADDRESSVALIDATOR_H
| #ifndef BITCOINADDRESSVALIDATOR_H
#define BITCOINADDRESSVALIDATOR_H
#include <QValidator>
/** Base58 entry widget validator.
Corrects near-miss characters and refuses characters that are not part of base58.
*/
class BitcoinAddressValidator : public QValidator
{
Q_OBJECT
public:
explicit BitcoinAddressValidator(QObject *parent = 0);
State validate(QString &input, int &pos) const;
static const int MaxAddressLength = 35;
};
#endif // BITCOINADDRESSVALIDATOR_H
|
Increase the number of pthread keys available to the IRT | /*
* Copyright (c) 2012 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include "native_client/src/untrusted/nacl/tls.h"
/*
* libstdc++ makes minimal use of pthread_key_t stuff.
*/
#undef PTHREAD_KEYS_MAX
#define PTHREAD_KEYS_MAX 16
#define NC_TSD_NO_MORE_KEYS irt_tsd_no_more_keys()
static void irt_tsd_no_more_keys(void) {
static const char msg[] = "IRT: too many pthread keys\n";
write(2, msg, sizeof msg - 1);
}
#define NACL_IN_IRT
/* @IGNORE_LINES_FOR_CODE_HYGIENE[2] */
#include "native_client/src/untrusted/pthread/nc_init_private.c"
#include "native_client/src/untrusted/pthread/nc_thread.c"
| /*
* Copyright (c) 2012 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include "native_client/src/untrusted/nacl/tls.h"
/*
* libstdc++ makes minimal use of pthread_key_t stuff.
*/
#undef PTHREAD_KEYS_MAX
#define PTHREAD_KEYS_MAX 32
#define NC_TSD_NO_MORE_KEYS irt_tsd_no_more_keys()
static void irt_tsd_no_more_keys(void) {
static const char msg[] = "IRT: too many pthread keys\n";
write(2, msg, sizeof msg - 1);
}
#define NACL_IN_IRT
/* @IGNORE_LINES_FOR_CODE_HYGIENE[2] */
#include "native_client/src/untrusted/pthread/nc_init_private.c"
#include "native_client/src/untrusted/pthread/nc_thread.c"
|
Use stdlib and return EXIT_SUCCESS | /*
Copyright © 2018 Atlas Engineer LLC.
Use of this file is governed by the license that can be found in LICENSE.
*/
#include <gtk/gtk.h>
#include "server.h"
int main(int argc, char *argv[]) {
// TODO: Use GtkApplication?
gtk_init(&argc, &argv);
// TODO: Start the xmlrpc server first? If GUI is started, then we can
// report xmlrpc startup issue graphically.
start_server();
start_client();
gtk_main();
stop_server();
return 0;
}
| /*
Copyright © 2018 Atlas Engineer LLC.
Use of this file is governed by the license that can be found in LICENSE.
*/
#include <gtk/gtk.h>
#include <stdlib.h>
#include "server.h"
int main(int argc, char *argv[]) {
// TODO: Use GtkApplication?
gtk_init(&argc, &argv);
// TODO: Start the xmlrpc server first? If GUI is started, then we can
// report xmlrpc startup issue graphically.
start_server();
start_client();
gtk_main();
stop_server();
return EXIT_SUCCESS;
}
|
Fix class vs struct declaration. | /*
* CECPQ1 (x25519 + NewHope)
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_CECPQ1_H__
#define BOTAN_CECPQ1_H__
#include <botan/secmem.h>
#include <botan/newhope.h>
namespace Botan {
struct CECPQ1_key {
secure_vector<uint8_t> m_x25519;
newhope_poly m_newhope;
};
void BOTAN_DLL CECPQ1_offer(uint8_t* offer_message,
CECPQ1_key* offer_key_output,
RandomNumberGenerator& rng);
void BOTAN_DLL CECPQ1_accept(uint8_t* shared_key,
uint8_t* accept_message,
const uint8_t* offer_message,
RandomNumberGenerator& rng);
void BOTAN_DLL CECPQ1_finish(uint8_t* shared_key,
const CECPQ1_key& offer_key,
const uint8_t* accept_message);
}
#endif
| /*
* CECPQ1 (x25519 + NewHope)
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_CECPQ1_H__
#define BOTAN_CECPQ1_H__
#include <botan/secmem.h>
#include <botan/newhope.h>
namespace Botan {
class CECPQ1_key
{
public:
secure_vector<uint8_t> m_x25519;
newhope_poly m_newhope;
};
void BOTAN_DLL CECPQ1_offer(uint8_t* offer_message,
CECPQ1_key* offer_key_output,
RandomNumberGenerator& rng);
void BOTAN_DLL CECPQ1_accept(uint8_t* shared_key,
uint8_t* accept_message,
const uint8_t* offer_message,
RandomNumberGenerator& rng);
void BOTAN_DLL CECPQ1_finish(uint8_t* shared_key,
const CECPQ1_key& offer_key,
const uint8_t* accept_message);
}
#endif
|
Allow ban manager to save state | /* keeps track of bans */
mapping username_bans;
mapping ip_bans;
static void create()
{
username_bans = ([ ]);
}
void ban_username(string username)
{
ACCESS_CHECK(GAME());
if (username_bans[username]) {
error("Username already banned");
}
username_bans[username] = 1;
}
void unban_username(string username)
{
ACCESS_CHECK(GAME());
if (!username_bans[username]) {
error("Username not banned");
}
username_bans[username] = nil;
}
int query_is_banned(string username)
{
return !!username_bans(username);
}
| #include <kotaka/privilege.h>
/* keeps track of bans */
mapping username_bans;
private void save();
private void restore();
static void create()
{
username_bans = ([ ]);
restore();
}
void ban_username(string username)
{
ACCESS_CHECK(GAME());
if (username == "admin") {
error("Cannot ban admin");
}
if (username_bans[username]) {
error("Username already banned");
}
username_bans[username] = 1;
save();
}
void unban_username(string username)
{
ACCESS_CHECK(GAME());
if (!username_bans[username]) {
error("Username not banned");
}
username_bans[username] = nil;
save();
}
int query_is_banned(string username)
{
return !!username_bans[username];
}
private void save()
{
save_object("band.o");
}
private void restore()
{
restore_object("band.o");
}
|
Initialize double variable before use. | #include "GRT/GRT.h"
#include "istream.h"
using namespace GRT;
// Normalize by dividing each dimension by the total magnitude.
// Also add the magnitude as an additional feature.
vector<double> normalize(vector<double> input) {
double magnitude;
for (int i = 0; i < input.size(); i++) magnitude += (input[i] * input[i]);
magnitude = sqrt(magnitude);
for (int i = 0; i < input.size(); i++) input[i] /= magnitude;
input.push_back(magnitude);
return input;
}
ASCIISerialStream stream(9600, 3);
GestureRecognitionPipeline pipeline;
void setup() {
stream.useUSBPort(0);
stream.useNormalizer(normalize);
useStream(stream);
pipeline.addPreProcessingModule(MovingAverageFilter(5, 4));
//pipeline.addFeatureExtractionModule(TimeDomainFeatures(10, 1, 3, false, true, true, false, false));
pipeline.setClassifier(ANBC());
usePipeline(pipeline);
}
| #include "GRT/GRT.h"
#include "istream.h"
using namespace GRT;
// Normalize by dividing each dimension by the total magnitude.
// Also add the magnitude as an additional feature.
vector<double> normalize(vector<double> input) {
double magnitude = 0.0;
for (int i = 0; i < input.size(); i++) magnitude += (input[i] * input[i]);
magnitude = sqrt(magnitude);
for (int i = 0; i < input.size(); i++) input[i] /= magnitude;
input.push_back(magnitude);
return input;
}
ASCIISerialStream stream(9600, 3);
GestureRecognitionPipeline pipeline;
void setup() {
stream.useUSBPort(0);
stream.useNormalizer(normalize);
useStream(stream);
pipeline.addPreProcessingModule(MovingAverageFilter(5, 4));
//pipeline.addFeatureExtractionModule(TimeDomainFeatures(10, 1, 3, false, true, true, false, false));
pipeline.setClassifier(ANBC());
usePipeline(pipeline);
}
|
Delete argument names of function | #ifndef LOG_H
#define LOG_H
#include <string>
#include <iostream>
#include <SFML/Graphics.hpp>
inline void Log(std::string str)
{
std::cout << "[" << __LINE__ << "] " << __FUNCTION__ << " : " << str << std::endl;
}
inline void LogFnStart()
{
Log("Entered");
}
inline void LogFnEnd()
{
Log("Finished");
}
inline void NestedLog(std::string str)
{
std::cout << "\n\t" << str << "\n" << std::endl;
}
namespace CppChart
{
std::ostream& operator<<(std::ostream& stream, const sf::Vector2f& v);
std::ostream& operator<<(std::ostream& stream, const sf::Vector2u& v);
std::ostream& operator<<(std::ostream& stream, const sf::Color& c);
template <typename T>
std::string ToString(const T& val);
}
#endif | #ifndef LOG_H
#define LOG_H
#include <string>
#include <iostream>
#include <SFML/Graphics.hpp>
inline void Log(std::string str)
{
std::cout << "[" << __LINE__ << "] " << __FUNCTION__ << " : " << str << std::endl;
}
inline void LogFnStart()
{
Log("Entered");
}
inline void LogFnEnd()
{
Log("Finished");
}
inline void NestedLog(std::string str)
{
std::cout << "\n\t" << str << "\n" << std::endl;
}
namespace CppChart
{
std::ostream& operator<<(std::ostream&, const sf::Vector2f&);
std::ostream& operator<<(std::ostream&, const sf::Vector2u&);
std::ostream& operator<<(std::ostream&, const sf::Color&);
template <typename T>
std::string ToString(const T&);
}
#endif |
Use override specifier for EquivBlueprint destructor. | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include "blueprint.h"
#include <vespa/searchlib/fef/matchdatalayout.h>
namespace search::queryeval {
class EquivBlueprint : public ComplexLeafBlueprint
{
private:
FieldSpecBaseList _fields;
HitEstimate _estimate;
fef::MatchDataLayout _layout;
std::vector<Blueprint::UP> _terms;
std::vector<double> _exactness;
public:
EquivBlueprint(const FieldSpecBaseList &fields, fef::MatchDataLayout subtree_mdl);
virtual ~EquivBlueprint();
// used by create visitor
EquivBlueprint& addTerm(Blueprint::UP term, double exactness);
SearchIteratorUP createLeafSearch(const fef::TermFieldMatchDataArray &tfmda, bool strict) const override;
SearchIteratorUP createFilterSearch(bool strict, FilterConstraint constraint) const override;
void visitMembers(vespalib::ObjectVisitor &visitor) const override;
void fetchPostings(const ExecuteInfo &execInfo) override;
bool isEquiv() const override { return true; }
};
}
| // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include "blueprint.h"
#include <vespa/searchlib/fef/matchdatalayout.h>
namespace search::queryeval {
class EquivBlueprint : public ComplexLeafBlueprint
{
private:
FieldSpecBaseList _fields;
HitEstimate _estimate;
fef::MatchDataLayout _layout;
std::vector<Blueprint::UP> _terms;
std::vector<double> _exactness;
public:
EquivBlueprint(const FieldSpecBaseList &fields, fef::MatchDataLayout subtree_mdl);
~EquivBlueprint() override;
// used by create visitor
EquivBlueprint& addTerm(Blueprint::UP term, double exactness);
SearchIteratorUP createLeafSearch(const fef::TermFieldMatchDataArray &tfmda, bool strict) const override;
SearchIteratorUP createFilterSearch(bool strict, FilterConstraint constraint) const override;
void visitMembers(vespalib::ObjectVisitor &visitor) const override;
void fetchPostings(const ExecuteInfo &execInfo) override;
bool isEquiv() const override { return true; }
};
}
|
Add example which outputs log to a file. | #include <stdio.h>
#include <string.h>
#include "zf_log.h"
#define LOG_FILENAME "test.log"
FILE *log_file;
static void log_file_write(zf_log_output_ctx *ctx) {
*ctx->p = '\n';
fwrite(ctx->buf, 1, (ctx->p + 1) - ctx->buf, log_file);
fflush(log_file);
}
int main(int argc, char *argv[])
{
log_file = fopen(LOG_FILENAME, "a+");
if (NULL == log_file) {
printf("Failed to open log file.\n");
}
zf_log_set_output_callback(log_file_write);
ZF_LOGI("You will see the number of arguments: %i", argc);
ZF_LOGI_MEM(argv, argc * sizeof(*argv), "argv pointers:");
fclose(log_file);
return 0;
}
| |
Adjust parameter defaults to give pleasant result | // -*- Mode: ObjC; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
//
// This file is part of the LibreOffice project.
//
// 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/.
#import "MLOViewController.h"
#import "MLOTestingTileSubviewControllerProtocol.h"
static const CGFloat CONTEXT_WIDTH_DEFAULT = 450;
static const CGFloat CONTEXT_HEIGHT_DEFAULT = 450;
static const CGFloat TILE_POS_X_DEFAULT = 400;
static const CGFloat TILE_POS_Y_DEFAULT = 420;
static const CGFloat TILE_WIDTH_DEFAULT = 250;
static const CGFloat TILE_HEIGHT_DEFAULT = 250;
@interface MLOTestingTileParametersViewController : MLOViewController<MLOTestingTileSubviewControllerProtocol>
@property CGFloat contextWidth, contextHeight, tilePosX, tilePosY, tileWidth, tileHeight;
-(void)renderTile;
@end
| // -*- Mode: ObjC; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
//
// This file is part of the LibreOffice project.
//
// 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/.
#import "MLOViewController.h"
#import "MLOTestingTileSubviewControllerProtocol.h"
// The size of the actual pixel tile
static const CGFloat CONTEXT_WIDTH_DEFAULT = 450;
static const CGFloat CONTEXT_HEIGHT_DEFAULT = 450;
// In our "decatwips"
static const CGFloat TILE_POS_X_DEFAULT = 0;
static const CGFloat TILE_POS_Y_DEFAULT = 0;
// "Tile" size here means the decatwip size of the part of the document
// rendered into the pixel tile
static const CGFloat TILE_WIDTH_DEFAULT = 500;
static const CGFloat TILE_HEIGHT_DEFAULT = 500;
@interface MLOTestingTileParametersViewController : MLOViewController<MLOTestingTileSubviewControllerProtocol>
@property CGFloat contextWidth, contextHeight, tilePosX, tilePosY, tileWidth, tileHeight;
-(void)renderTile;
@end
|
Fix compile error on CentOS | typedef uint64_t msgid_t;
typedef uint64_t msec_t;
typedef uint64_t usec_t;
| #pragma once
typedef uint64_t msgid_t;
typedef uint64_t msec_t;
typedef uint64_t usec_t;
|
Synchronize logging to stderr and stdout in debug mode | #pragma once
#include <string>
#include <iostream>
#include <fstream>
#include <exception>
#include <boost/format.hpp>
using boost::format;
class LogFile
{
public:
LogFile();
explicit LogFile(const std::string& filename);
~LogFile();
void open(const std::string& filename);
void close();
template <class T>
void write(const T& other, bool newline=true) {
if (haveFile) {
file << other;
if (newline) {
file << std::endl;
}
} else {
std::cout << other;
if (newline) {
std::cout << std::endl;
}
}
}
private:
bool haveFile;
std::ofstream file;
};
class debugParameters
{
public:
static bool debugAdapt;
static bool debugRegrid;
static bool debugTimesteps;
static bool debugFlameRadiusControl;
static bool veryVerbose;
};
extern LogFile logFile;
class debugException : public std::exception
{
public:
std::string errorString;
debugException(void);
~debugException(void) throw() {}
debugException(const std::string& error);
virtual const char* what() throw();
};
| #pragma once
#include <string>
#include <iostream>
#include <fstream>
#include <exception>
#include <boost/format.hpp>
using boost::format;
class LogFile
{
public:
LogFile();
explicit LogFile(const std::string& filename);
~LogFile();
void open(const std::string& filename);
void close();
template <class T>
void write(const T& other, bool newline=true) {
if (haveFile) {
file << other;
if (newline) {
file << std::endl;
}
} else {
std::cout << other;
if (newline) {
std::cout << std::endl;
}
#ifndef NDEBUG
std::cout.flush();
std::cerr.flush();
#endif
}
}
private:
bool haveFile;
std::ofstream file;
};
class debugParameters
{
public:
static bool debugAdapt;
static bool debugRegrid;
static bool debugTimesteps;
static bool debugFlameRadiusControl;
static bool veryVerbose;
};
extern LogFile logFile;
class debugException : public std::exception
{
public:
std::string errorString;
debugException(void);
~debugException(void) throw() {}
debugException(const std::string& error);
virtual const char* what() throw();
};
|
Add a test for aarch64 target CPU names. | // Ensure we support the various CPU names.
//
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu cortex-a35 -verify %s
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu cortex-a53 -verify %s
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu cortex-a57 -verify %s
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu cortex-a72 -verify %s
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu cortex-a73 -verify %s
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu cyclone -verify %s
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu exynos-m1 -verify %s
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu generic -verify %s
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu kryo -verify %s
// RUN: %clang_cc1 -triple aarch64-unknown-unknown -target-cpu vulcan -verify %s
//
// expected-no-diagnostics
| |
Add header to allow reusing native_posix drivers | /*
* Copyright (c) 2019 Oticon A/S
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* This header exists solely to allow drivers meant for the native_posix board
* to be used directly in the nrf52_bsim board.
* Note that such reuse should be done with great care.
*
* The command line arguments parsing logic from native_posix was born as a copy
* of the one from the BabbleSim's libUtil library
* They are therefore mostly equal except for types and functions names.
*
* This header converts these so the native_posix call to dynamically register
* command line arguments is passed to the nrf52_bsim one
*/
#include "../native_posix/cmdline_common.h"
static inline void native_add_command_line_opts(struct args_struct_t *args)
{
void bs_add_extra_dynargs(struct args_struct_t *args);
bs_add_extra_dynargs(args);
}
| |
Add const in newly-added file. | /****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#ifndef NOEVAPFREEENERGY_H
#define NOEVAPFREEENERGY_H
#include "DerivativeFunctionMaterialBase.h"
//Forward Declarations
class NoEvapFreeEnergy;
template<>
InputParameters validParams<NoEvapFreeEnergy>();
/**
* Material class that creates a piecewise free energy with supressed evaporation and its derivatives
* for use with CHParsed and SplitCHParsed. F = .
*/
class NoEvapFreeEnergy : public DerivativeFunctionMaterialBase
{
public:
NoEvapFreeEnergy(const InputParameters & parameters);
protected:
virtual Real computeF();
virtual Real computeDF(unsigned int j_var);
virtual Real computeD2F(unsigned int j_var, unsigned int k_var);
private:
/// Coupled variable value for the concentration \f$ \c \f$.
VariableValue & _c;
unsigned int _c_var;
};
#endif //NOEVAPFREEENERGY_H
| /****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#ifndef NOEVAPFREEENERGY_H
#define NOEVAPFREEENERGY_H
#include "DerivativeFunctionMaterialBase.h"
//Forward Declarations
class NoEvapFreeEnergy;
template<>
InputParameters validParams<NoEvapFreeEnergy>();
/**
* Material class that creates a piecewise free energy with supressed evaporation and its derivatives
* for use with CHParsed and SplitCHParsed. F = .
*/
class NoEvapFreeEnergy : public DerivativeFunctionMaterialBase
{
public:
NoEvapFreeEnergy(const InputParameters & parameters);
protected:
virtual Real computeF();
virtual Real computeDF(unsigned int j_var);
virtual Real computeD2F(unsigned int j_var, unsigned int k_var);
private:
/// Coupled variable value for the concentration \f$ \c \f$.
const VariableValue & _c;
unsigned int _c_var;
};
#endif //NOEVAPFREEENERGY_H
|
Support loading vec3s from JSON objects or arrays | /*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include "rapidjson/document.h"
#include "glm/glm.hpp"
namespace redc
{
inline glm::vec3 vec3_from_js_object(rapidjson::Value const& v) noexcept
{
return glm::vec3{v["x"].GetDouble(),v["y"].GetDouble(),v["z"].GetDouble()};
}
inline glm::vec3 vec3_from_js_array(rapidjson::Value const& v) noexcept
{
return glm::vec3{v[0].GetDouble(),v[1].GetDouble(),v[2].GetDouble()};
}
}
| /*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include "rapidjson/document.h"
#include "glm/glm.hpp"
namespace redc
{
inline glm::vec3 vec3_from_js_object(rapidjson::Value const& v) noexcept
{
return glm::vec3{v["x"].GetDouble(),v["y"].GetDouble(),v["z"].GetDouble()};
}
inline glm::vec3 vec3_from_js_array(rapidjson::Value const& v) noexcept
{
return glm::vec3{v[0].GetDouble(),v[1].GetDouble(),v[2].GetDouble()};
}
inline bool load_js_vec3(rapidjson::Value const& v, glm::vec3& vec,
std::string* err)
{
if(v.IsArray())
{
vec = vec3_from_js_array(v);
return true;
}
else if(v.IsObject())
{
vec = vec3_from_js_object(v);
return true;
}
else
{
if(err) (*err) = "Invalid JSON; expected Vec3 (object or array)";
return false;
}
}
}
|
Add some more common ports and pins | #pragma once
#ifndef __AVR_ARCH__
#include <unistd.h>
#define _BV(bit) (1<<(bit))
inline void _delay_ms(int ms) { usleep(ms*1000); }
inline void _delay_us(int us) { usleep(us); }
extern unsigned char UCSR0B;
extern unsigned char DDRB;
extern unsigned char DDRD;
extern unsigned char PINB;
extern unsigned char PIND;
extern unsigned char PORTB;
extern unsigned char PORTD;
#endif
| #pragma once
#ifndef __AVR_ARCH__
#include <unistd.h>
#define _BV(bit) (1<<(bit))
inline void _delay_ms(int ms) { usleep(ms*1000); }
inline void _delay_us(int us) { usleep(us); }
extern unsigned char UCSR0A;
extern unsigned char UCSR0B;
extern unsigned char UCSR0C;
extern unsigned char UBRR0H;
extern unsigned char UBRR0L;
extern unsigned char DDRB;
extern unsigned char DDRD;
extern unsigned char PINB;
extern unsigned char PIND;
extern unsigned char PORTB;
extern unsigned char PORTD;
extern unsigned char UDR0;
#define U2X0 1
#define RXEN0 4
#define TXEN0 3
#endif
|
Add EXTMultimethod to umbrella header | /*
* extobjc.h
* extobjc
*
* Created by Justin Spahr-Summers on 2010-11-09.
* Released into the public domain.
*/
#import "EXTADT.h"
#import "EXTAspect.h"
#import "EXTBlockMethod.h"
#import "EXTBlockTarget.h"
#import "EXTConcreteProtocol.h"
#import "EXTDispatchObject.h"
#import "EXTFinalMethod.h"
#import "EXTKeyPathCoding.h"
#import "EXTMaybe.h"
#import "EXTMixin.h"
#import "EXTMultiObject.h"
#import "EXTNil.h"
#import "EXTPrivateMethod.h"
#import "EXTProtocolCategory.h"
#import "EXTSafeCategory.h"
#import "EXTScope.h"
#import "EXTSwizzle.h"
#import "EXTTuple.h"
#import "EXTVarargs.h"
#import "NSInvocation+EXT.h"
#import "NSMethodSignature+EXT.h"
| /*
* extobjc.h
* extobjc
*
* Created by Justin Spahr-Summers on 2010-11-09.
* Released into the public domain.
*/
#import "EXTADT.h"
#import "EXTAspect.h"
#import "EXTBlockMethod.h"
#import "EXTBlockTarget.h"
#import "EXTConcreteProtocol.h"
#import "EXTDispatchObject.h"
#import "EXTFinalMethod.h"
#import "EXTKeyPathCoding.h"
#import "EXTMaybe.h"
#import "EXTMixin.h"
#import "EXTMultimethod.h"
#import "EXTMultiObject.h"
#import "EXTNil.h"
#import "EXTPrivateMethod.h"
#import "EXTProtocolCategory.h"
#import "EXTSafeCategory.h"
#import "EXTScope.h"
#import "EXTSwizzle.h"
#import "EXTTuple.h"
#import "EXTVarargs.h"
#import "NSInvocation+EXT.h"
#import "NSMethodSignature+EXT.h"
|
Include sql_config.h always so that we get HAVE_TERMIOS_H, so that the password doesn't get echoed. | #ifndef _MEM_H_
#define _MEM_H_
#include <config.h>
#ifdef _MSC_VER
#include <sql_config.h>
#endif
#include <stdio.h>
#include <assert.h>
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#define NEW( type ) (type*)malloc(sizeof(type) )
#define NEW_ARRAY( type, size ) (type*)malloc((size)*sizeof(type))
#define RENEW_ARRAY( type,ptr,size) (type*)realloc((void*)ptr,(size)*sizeof(type))
#define NEWADT( size ) (adt*)malloc(size)
#define _DELETE( ptr ) free(ptr)
#define _strdup( ptr ) strdup((char*)ptr)
#endif /*_MEM_H_*/
| #ifndef _MEM_H_
#define _MEM_H_
#include <config.h>
#include <sql_config.h>
#include <stdio.h>
#include <assert.h>
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#define NEW( type ) (type*)malloc(sizeof(type) )
#define NEW_ARRAY( type, size ) (type*)malloc((size)*sizeof(type))
#define RENEW_ARRAY( type,ptr,size) (type*)realloc((void*)ptr,(size)*sizeof(type))
#define NEWADT( size ) (adt*)malloc(size)
#define _DELETE( ptr ) free(ptr)
#define _strdup( ptr ) strdup((char*)ptr)
#endif /*_MEM_H_*/
|
Add the future file for common interfaces | /* EFL-Egueb Egueb based EFL extensions
* Copyright (C) 2013 - 2014 Jorge Luis Zapata
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "efl_egueb_private.h"
#include "efl_egueb_main.h"
/* Put the common interfaces with EFL here, like:
* - Animation
* - IO
* - Render?
*/
/*============================================================================*
* Local *
*============================================================================*/
/*============================================================================*
* Global *
*============================================================================*/
/*============================================================================*
* API *
*============================================================================*/
| |
Add names for ID space boundaries. | #ifndef VAST_ALIASES_H
#define VAST_ALIASES_H
#include <cstdint>
namespace vast {
/// Uniquely identifies a VAST event.
using event_id = uint64_t;
/// Uniquely identifies a VAST type.
using type_id = uint64_t;
} // namespace vast
#endif
| #ifndef VAST_ALIASES_H
#define VAST_ALIASES_H
#include <cstdint>
#include <limits>
namespace vast {
/// Uniquely identifies a VAST event.
using event_id = uint64_t;
/// The smallest possible event ID.
static constexpr event_id min_event_id = 1;
/// The largest possible event ID.
static constexpr event_id max_event_id =
std::numeric_limits<event_id>::max() - 1;
/// Uniquely identifies a VAST type.
using type_id = uint64_t;
} // namespace vast
#endif
|
Add simple function to interact with pgsql APIs, and make something for the NQP bits to export | #include "postgres.h"
#include "executor/spi.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "access/heapam.h"
#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(plparrot_call_handler);
Datum
plparrot_call_handler(PG_FUNCTION_ARGS)
{
PG_RETURN_VOID();
}
| #include "postgres.h"
#include "executor/spi.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "access/heapam.h"
#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
PG_MODULE_MAGIC;
Datum plparrot_call_handler(PG_FUNCTION_ARGS);
void plparrot_elog(int level, char *message);
PG_FUNCTION_INFO_V1(plparrot_call_handler);
Datum
plparrot_call_handler(PG_FUNCTION_ARGS)
{
PG_RETURN_VOID();
}
void
plparrot_elog(int level, char *message)
{
elog(level, "%s", message);
}
|
Fix out of bounds writes during charset conversion |
#include <errno.h>
#include "readstat.h"
#include "readstat_iconv.h"
#include "readstat_convert.h"
readstat_error_t readstat_convert(char *dst, size_t dst_len, const char *src, size_t src_len, iconv_t converter) {
/* strip off spaces from the input because the programs use ASCII space
* padding even with non-ASCII encoding. */
while (src_len && src[src_len-1] == ' ') {
src_len--;
}
if (converter) {
size_t dst_left = dst_len;
char *dst_end = dst;
size_t status = iconv(converter, (readstat_iconv_inbuf_t)&src, &src_len, &dst_end, &dst_left);
if (status == (size_t)-1) {
if (errno == E2BIG) {
return READSTAT_ERROR_CONVERT_LONG_STRING;
} else if (errno == EILSEQ) {
return READSTAT_ERROR_CONVERT_BAD_STRING;
} else if (errno != EINVAL) { /* EINVAL indicates improper truncation; accept it */
return READSTAT_ERROR_CONVERT;
}
}
dst[dst_len - dst_left] = '\0';
} else {
memcpy(dst, src, src_len);
dst[src_len] = '\0';
}
return READSTAT_OK;
}
|
#include <errno.h>
#include "readstat.h"
#include "readstat_iconv.h"
#include "readstat_convert.h"
readstat_error_t readstat_convert(char *dst, size_t dst_len, const char *src, size_t src_len, iconv_t converter) {
/* strip off spaces from the input because the programs use ASCII space
* padding even with non-ASCII encoding. */
while (src_len && src[src_len-1] == ' ') {
src_len--;
}
if (converter) {
size_t dst_left = dst_len;
char *dst_end = dst;
size_t status = iconv(converter, (readstat_iconv_inbuf_t)&src, &src_len, &dst_end, &dst_left);
if (status == (size_t)-1) {
if (errno == E2BIG) {
return READSTAT_ERROR_CONVERT_LONG_STRING;
} else if (errno == EILSEQ) {
return READSTAT_ERROR_CONVERT_BAD_STRING;
} else if (errno != EINVAL) { /* EINVAL indicates improper truncation; accept it */
return READSTAT_ERROR_CONVERT;
}
}
dst[dst_len - dst_left] = '\0';
} else if (src_len + 1 > dst_len) {
return READSTAT_ERROR_CONVERT_LONG_STRING;
} else {
memcpy(dst, src, src_len);
dst[src_len] = '\0';
}
return READSTAT_OK;
}
|
Add new file that was forgotten. | #ifndef HALIDE_BUF_SIZE_H
#define HALIDE_BUF_SIZE_H
// TODO: in new buffer_t, add an inline method to do this and kill this file.
// Compute the total amount of memory we'd need to allocate on gpu to
// represent a given buffer (using the same strides as the host
// allocation).
WEAK size_t buf_size(const buffer_t *buf) {
size_t size = buf->elem_size;
for (size_t i = 0; i < sizeof(buf->stride) / sizeof(buf->stride[0]); i++) {
size_t positive_stride;
if (buf->stride[i] < 0) {
positive_stride = (size_t)-buf->stride[i];
} else {
positive_stride = (size_t)buf->stride[i];
}
size_t total_dim_size = buf->elem_size * buf->extent[i] * positive_stride;
if (total_dim_size > size) {
size = total_dim_size;
}
}
return size;
}
#endif // HALIDE_BUF_SIZE_H
| |
Add new attributes to Visit class | //
// MRSVisit.h
// OpenMRS-iOS
//
// Created by Parker Erway on 12/2/14.
// Copyright (c) 2014 Erway Software. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MRSVisit : NSObject
@property (nonatomic, strong) NSString *displayName;
@property (nonatomic, strong) NSString *UUID;
@property (nonatomic) BOOL active;
@end
| //
// MRSVisit.h
// OpenMRS-iOS
//
// Created by Parker Erway on 12/2/14.
// Copyright (c) 2014 Erway Software. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "MRSLocation.h"
@class MRSVisitType;
@interface MRSVisit : NSObject
@property (nonatomic, strong) NSString *displayName;
@property (nonatomic, strong) NSString *UUID;
@property (nonatomic, strong) NSString *startDateTime;
@property (nonatomic, strong) MRSVisitType *visitType;
@property (nonatomic, strong) MRSLocation *location;
@property (nonatomic) BOOL active;
@end
|
Change int to unsigned int | #ifndef __TIMER_H__
#define __TIMER_H__
#include "SDL/include/SDL.h"
class SimpleTimer
{
public:
SimpleTimer()
{
pausedTicks = 0, runTicks = 0;
running = false;
}
void Start()
{
running = true;
runTicks = SDL_GetTicks();
}
void Stop()
{
if(running)
{
running = false;
pausedTicks = SDL_GetTicks() - runTicks;
}
}
void Resume()
{
if(!running)
{
running = true;
runTicks = SDL_GetTicks() - pausedTicks;
pausedTicks = 0;
}
}
void Clear()
{
running = false;
runTicks = 0;
pausedTicks = 0;
}
int GetTimerTicks() const
{
if (running)
return SDL_GetTicks() - runTicks;
return 0;
}
bool IsRunning() const
{
return running;
}
private:
int pausedTicks, runTicks;
bool running;
};
#endif // __TIMER_H__ | #ifndef __TIMER_H__
#define __TIMER_H__
#include "SDL/include/SDL.h"
class SimpleTimer
{
public:
SimpleTimer()
{
pausedTicks = 0, runTicks = 0;
running = false;
}
void Start()
{
running = true;
runTicks = SDL_GetTicks();
}
int Stop()
{
if(running)
{
running = false;
return pausedTicks = SDL_GetTicks() - runTicks;
}
return 0;
}
void Resume()
{
if(!running)
{
running = true;
runTicks = SDL_GetTicks() - pausedTicks;
pausedTicks = 0;
}
}
void Clear()
{
running = false;
runTicks = 0;
pausedTicks = 0;
}
unsigned int GetTimerTicks() const
{
if (running)
return SDL_GetTicks() - runTicks;
return 0;
}
unsigned int GetPausedTicks() const
{
if (!running)
return pausedTicks;
return 0;
}
bool IsRunning() const
{
return running;
}
private:
unsigned int pausedTicks, runTicks;
bool running;
};
#endif // __TIMER_H__ |
Fix generic singleton accessor syntax. | #ifndef DTKSINGLETON_H
#define DTKSINGLETON_H
#include <QtCore/QMutex>
template <class T> class dtkSingleton
{
public:
static T& instance(void)
{
static QMutex mutex;
if(!s_instance) {
mutex.lock();
if(!s_instance)
s_instance = new T;
mutex.unlock();
}
return s_instance;
}
private:
dtkSingleton(void) {};
~dtkSingleton(void) {};
private:
Q_DISABLE_COPY(dtkSingleton)
private:
static T *s_instance;
};
template <class T> T *dtkSingleton<T>::s_instance = NULL;
#define DTK_IMPLEMENT_SINGLETON(T) \
T *T::instance() \
{ \
return &(dtkSingleton<T>::instance()); \
}
#endif //DTKSINGLETON
| #ifndef DTKSINGLETON_H
#define DTKSINGLETON_H
#include <QtCore/QMutex>
template <class T> class dtkSingleton
{
public:
static T& instance(void)
{
static QMutex mutex;
if(!s_instance) {
mutex.lock();
if(!s_instance)
s_instance = new T;
mutex.unlock();
}
return (*s_instance);
}
private:
dtkSingleton(void) {};
~dtkSingleton(void) {};
private:
Q_DISABLE_COPY(dtkSingleton)
private:
static T *s_instance;
};
template <class T> T *dtkSingleton<T>::s_instance = NULL;
#define DTK_IMPLEMENT_SINGLETON(T) \
T *T::instance() \
{ \
return &(dtkSingleton<T>::instance()); \
}
#endif //DTKSINGLETON
|
Handle null terminator in string reverse | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
// Read string from a file
FILE* file_ptr = fopen("test.txt", "r");
if (file_ptr == NULL)
return 1;
char* string = malloc(256);
fscanf(file_ptr, "%s", string);
// Solution
int length = sprintf(string, "%s", string);
int front = 0;
int back = length - 1;
while(front < back)
{
// swap 2 characters
char tmp = string[front];
string[front] = string[back];
string[back] = tmp;
++front;
--back;
}
printf("%s\n", string);
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
void reverse(char* string)
{
char* back = string;
char tmp;
while(*back)
++back;
// Move from the null terminator
--back;
while (string < back)
{
char tmp = *string;
*string = *back;
*back = tmp;
++string;
--back;
}
}
int main()
{
// Read string from a file
FILE* file_ptr = fopen("test.txt", "r");
if (file_ptr == NULL)
return 1;
char* string = malloc(256);
fscanf(file_ptr, "%s", string);
// Solution
reverse(string);
printf("%s\n", string);
return 0;
}
|
Remove some leftover null pointer vars |
#ifndef _POINTER_H
#define _POINTER_H
#ifdef __cplusplus
extern "C" {
#endif
#include "AbstractMemory.h"
extern void rbffi_Pointer_Init(VALUE moduleFFI);
extern void rbffi_NullPointer_Init(VALUE moduleFFI);
extern VALUE rbffi_Pointer_NewInstance(void* addr);
extern VALUE rbffi_PointerClass;
extern VALUE rbffi_NullPointerClass;
extern VALUE rbffi_NullPointerSingleton;
extern MemoryOps rbffi_NullPointerOps;
#ifdef __cplusplus
}
#endif
#endif /* _POINTER_H */
| /*
* Copyright (c) 2008, 2009, Wayne Meissner
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * The name of the author or authors may not be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RBFFI_POINTER_H
#define RBFFI_POINTER_H
#ifdef __cplusplus
extern "C" {
#endif
#include "AbstractMemory.h"
extern void rbffi_Pointer_Init(VALUE moduleFFI);
extern VALUE rbffi_Pointer_NewInstance(void* addr);
extern VALUE rbffi_PointerClass;
extern VALUE rbffi_NullPointerSingleton;
#ifdef __cplusplus
}
#endif
#endif /* RBFFI_POINTER_H */
|
Use `ln -n` to prevent forming a symlink cycle, instead of rm'ing the source | // Due to ln -sf:
// REQUIRES: shell
// RUN: rm -rf %t.real
// RUN: mkdir -p %t.real
// RUN: cd %t.real
// RUN: ln -sf %clang test-clang
// RUN: cd ..
// Important to remove %t.fake: If it already is a symlink to %t.real when
// `ln -sf %t.real %t.fake` runs, then that would symlink %t.real to itself,
// forming a cycle.
// RUN: rm -rf %t.fake
// RUN: ln -sf %t.real %t.fake
// RUN: cd %t.fake
// RUN: ./test-clang -v -S %s 2>&1 | FileCheck --check-prefix=CANONICAL %s
// RUN: ./test-clang -v -S %s -no-canonical-prefixes 2>&1 | FileCheck --check-prefix=NON-CANONICAL %s
//
// FIXME: This should really be '.real'.
// CANONICAL: InstalledDir: {{.*}}.fake
// CANONICAL: {{[/|\\]*}}clang{{.*}}" -cc1
//
// NON-CANONICAL: InstalledDir: .{{$}}
// NON-CANONICAL: test-clang" -cc1
| // Due to ln -sf:
// REQUIRES: shell
// RUN: mkdir -p %t.real
// RUN: cd %t.real
// RUN: ln -sf %clang test-clang
// RUN: cd ..
// If %.fake already is a symlink to %t.real when `ln -sf %t.real %t.fake`
// runs, then that would symlink %t.real to itself, forming a cycle.
// The `-n` flag prevents this.
// RUN: ln -sfn %t.real %t.fake
// RUN: cd %t.fake
// RUN: ./test-clang -v -S %s 2>&1 | FileCheck --check-prefix=CANONICAL %s
// RUN: ./test-clang -v -S %s -no-canonical-prefixes 2>&1 | FileCheck --check-prefix=NON-CANONICAL %s
//
// FIXME: This should really be '.real'.
// CANONICAL: InstalledDir: {{.*}}.fake
// CANONICAL: {{[/|\\]*}}clang{{.*}}" -cc1
//
// NON-CANONICAL: InstalledDir: .{{$}}
// NON-CANONICAL: test-clang" -cc1
|
Add comments for filter enums | extern void denoise(void*, int, const uint32_t *in, uint32_t *out, int h, int w);
extern void *kernelInit(void);
extern void kernelFinalize(void*);
enum {
SPATIAL,
TEMPORAL_AVG,
KNN,
AKNN,
ADAPTIVE_TEMPORAL_AVG,
DIFF,
SOBEL,
MOTION,
};
| extern void denoise(void*, int, const uint32_t *in, uint32_t *out, int h, int w);
extern void *kernelInit(void);
extern void kernelFinalize(void*);
enum {
// "Real" filters
SPATIAL,
TEMPORAL_AVG,
ADAPTIVE_TEMPORAL_AVG,
KNN,
AKNN,
// Helpers
DIFF,
SOBEL,
MOTION,
NFILTERS,
};
|
Call different stuff for the assembler/disassembler. | /* Copyright (C) 2014-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
Released under the terms of the MIT License. See LICENSE for details. */
#include <stdlib.h>
#include "src/config.h"
#include "src/logging.h"
#include "src/rom.h"
/*
Main function.
*/
int main(int argc, char *argv[])
{
Config *config;
ROM *rom;
int retval;
retval = config_create(&config, argc, argv);
if (retval != CONFIG_OK)
return retval == CONFIG_EXIT_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
printf("crater: a Sega Game Gear emulator\n\n");
#ifdef DEBUG_MODE
config_dump_args(config);
#endif
if (!(rom = rom_open(config->rom_path))) {
if (errno == ENOMEM)
OUT_OF_MEMORY()
else
FATAL_ERRNO("couldn't load ROM image '%s'", config->rom_path)
}
printf("Loaded ROM image: %s.\n", rom->name);
// TODO: start from here
rom_close(rom);
config_destroy(config);
return EXIT_SUCCESS;
}
| /* Copyright (C) 2014-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
Released under the terms of the MIT License. See LICENSE for details. */
#include <stdlib.h>
#include "src/config.h"
#include "src/logging.h"
#include "src/rom.h"
/*
Main function.
*/
int main(int argc, char *argv[])
{
Config *config;
int retval;
retval = config_create(&config, argc, argv);
if (retval != CONFIG_OK)
return retval == CONFIG_EXIT_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
#ifdef DEBUG_MODE
config_dump_args(config);
#endif
if (config->assemble) {
printf("Running assembler: %s -> %s.\n",config->src_path, config->dst_path);
} else if (config->disassemble) {
printf("Running disassembler: %s -> %s.\n", config->src_path, config->dst_path);
} else {
ROM *rom;
printf("crater: a Sega Game Gear emulator\n\n");
if (!(rom = rom_open(config->rom_path))) {
if (errno == ENOMEM)
OUT_OF_MEMORY()
else
FATAL_ERRNO("couldn't load ROM image '%s'", config->rom_path)
}
printf("Loaded ROM image: %s.\n", rom->name);
// TODO: start from here
rom_close(rom);
}
config_destroy(config);
return EXIT_SUCCESS;
}
|
Fix warning in header disabling some warnings (sigh) | #ifndef PWARNINGS_H
#define PWARNINGS_H
#if defined(_MSC_VER)
/* Needed when flagging code in or out and more. */
#pragma warning(disable: 4127) /* conditional expression is constant */
/* happens also in MS's own headers. */
#pragma warning(disable: 4668) /* preprocessor name not defined */
/* MSVC does not respect double parenthesis for intent */
#pragma warning(disable: 4706) /* assignment within conditional expression */
/* `inline` only advisory anyway. */
#pragma warning(disable: 4710) /* function not inlined */
/* Well, we don't intend to add the padding manually. */
#pragma warning(disable: 4820) /* x bytes padding added in struct */
/* Define this in the build as `-D_CRT_SECURE_NO_WARNINGS`, it has no effect here. */
/* #define _CRT_SECURE_NO_WARNINGS don't warn that fopen etc. are unsafe */
/*
* Anonymous union in struct is valid in C11 and has been supported in
* GCC and Clang for a while, but it is not C99. MSVC also handles it,
* but warns. Truly portable code should perhaps not use this feature,
* but this is not the place to complain about it.
*/
#pragma warning(disable: 4201) /* nonstandard extension used: nameless struct/union */
#endif
#endif PWARNINGS_H
| #ifndef PWARNINGS_H
#define PWARNINGS_H
#if defined(_MSC_VER)
/* Needed when flagging code in or out and more. */
#pragma warning(disable: 4127) /* conditional expression is constant */
/* happens also in MS's own headers. */
#pragma warning(disable: 4668) /* preprocessor name not defined */
/* MSVC does not respect double parenthesis for intent */
#pragma warning(disable: 4706) /* assignment within conditional expression */
/* `inline` only advisory anyway. */
#pragma warning(disable: 4710) /* function not inlined */
/* Well, we don't intend to add the padding manually. */
#pragma warning(disable: 4820) /* x bytes padding added in struct */
/* Define this in the build as `-D_CRT_SECURE_NO_WARNINGS`, it has no effect here. */
/* #define _CRT_SECURE_NO_WARNINGS don't warn that fopen etc. are unsafe */
/*
* Anonymous union in struct is valid in C11 and has been supported in
* GCC and Clang for a while, but it is not C99. MSVC also handles it,
* but warns. Truly portable code should perhaps not use this feature,
* but this is not the place to complain about it.
*/
#pragma warning(disable: 4201) /* nonstandard extension used: nameless struct/union */
#endif
#endif /* PWARNINGS_H */
|
Define compatibility macros for __ types unless DIRECTFB_NO_CRUFT is defined. | #ifndef __DFB_TYPES_H__
#define __DFB_TYPES_H__
#ifdef USE_KOS
#include <sys/types.h>
typedef uint8 u8;
typedef uint16 u16;
typedef uint32 u32;
typedef uint64 u64;
typedef sint8 s8;
typedef sint16 s16;
typedef sint32 s32;
typedef sint64 s64;
#else
#include <stdint.h>
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;
#endif
#endif
| #ifndef __DFB_TYPES_H__
#define __DFB_TYPES_H__
#ifdef USE_KOS
#include <sys/types.h>
typedef uint8 u8;
typedef uint16 u16;
typedef uint32 u32;
typedef uint64 u64;
typedef sint8 s8;
typedef sint16 s16;
typedef sint32 s32;
typedef sint64 s64;
#else
#include <stdint.h>
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;
#endif
#ifndef DIRECTFB_NO_CRUFT
#define __u8 u8
#define __u16 u16
#define __u32 u32
#define __u64 u64
#define __s8 s8
#define __s16 s16
#define __s32 s32
#define __s64 s64
#endif
#endif
|
Make example a bit more advanced | int test(int a, int b, int c, int d, int e);
typedef (*funcCall)();
short array = {0x61c1};
int main()
{
((funcCall)array)();
return test(1, 2, 3, 4, 5);
}
int test(int a, int b, int c, int d, int e)
{
return (e + (a + b + c) * a / d) + (a * 6);
}
| int test(int a, int b, int c, int d, int e);
typedef (*funcCall)();
short array = {0x61c1};
int main()
{
((funcCall)array)();
int some_var = 3;
int ret = test(1, 2, 3, 4, 5);
return some_var + ret;
}
int foo(int a)
{
return 9 + a;
}
int test(int a, int b, int c, int d, int e)
{
a = foo(a);
return ((a + b + c) * d / a) + (d * e);
}
|
Fix simple example delegate's protocol compliance. | //
// FragariaAppDelegate.h
// Fragaria
//
// Created by Jonathan on 30/04/2010.
// Copyright 2010 mugginsoft.com. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import <MGSFragaria/MGSFragariaTextViewDelegate.h>
#import <MGSFragaria/SMLSyntaxColouringDelegate.h>
@class SMLTextView;
@class MGSFragaria;
@class MGSSimpleBreakpointDelegate;
@interface FragariaAppDelegate : NSObject <NSApplicationDelegate, MGSFragariaTextViewDelegate, SMLSyntaxColouringDelegate>
- (IBAction)showPreferencesWindow:(id)sender;
- (IBAction)copyToPasteBoard:(id)sender;
- (IBAction)reloadString:(id)sender;
@property (weak) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSView *editView;
@property (nonatomic,assign) NSString *syntaxDefinition;
@end
| //
// FragariaAppDelegate.h
// Fragaria
//
// Created by Jonathan on 30/04/2010.
// Copyright 2010 mugginsoft.com. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import <MGSFragaria/MGSFragariaTextViewDelegate.h>
#import <MGSFragaria/SMLSyntaxColouringDelegate.h>
#import <MGSFragaria/MGSDragOperationDelegate.h>
@class SMLTextView;
@class MGSFragaria;
@class MGSSimpleBreakpointDelegate;
@interface FragariaAppDelegate : NSObject <NSApplicationDelegate, MGSFragariaTextViewDelegate, SMLSyntaxColouringDelegate, MGSDragOperationDelegate>
- (IBAction)showPreferencesWindow:(id)sender;
- (IBAction)copyToPasteBoard:(id)sender;
- (IBAction)reloadString:(id)sender;
@property (weak) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSView *editView;
@property (nonatomic,assign) NSString *syntaxDefinition;
@end
|
Add IPOLICE_FLAGS: DONT_REMOVE, bump RTPP_SW_VERSION forward. | #define RTPP_SW_VERSION "rel.20140506110718"
| /* IPOLICE_FLAGS: DONT_REMOVE */
#define RTPP_SW_VERSION "rel.20160514172346"
|
Add unit tests for utils.c functions. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include "cem/utils.h"
static void test_set_periodic_multiple_of_4(void) {
const int len = 12;
int array[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int expected[12] = {6, 7, 8, 3, 4, 5, 6, 7, 8, 3, 4, 5};
apply_periodic_boundary(array, sizeof(int), len);
g_assert_cmpmem(array, len, expected, len);
}
static void test_set_periodic_even_width(void) {
const int len = 10;
int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int expected[10] = {5, 6, 2, 3, 4, 5, 6, 2, 3, 4};
apply_periodic_boundary(array, sizeof(int), len);
g_assert_cmpmem(array, len, expected, len);
}
static void test_set_periodic_odd_width(void) {
const int len = 11;
int array[11] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int expected[11] = {5, 6, 7, 3, 4, 5, 6, 7, 3, 4, 5};
apply_periodic_boundary(array, sizeof(int), len);
g_assert_cmpmem(array, len, expected, len);
}
int main(int argc, char* argv[]) {
g_test_init(&argc, &argv, NULL);
g_test_add_func("/cem/utils/set_periodic_4", &test_set_periodic_multiple_of_4);
g_test_add_func("/cem/utils/set_periodic_even", &test_set_periodic_even_width);
g_test_add_func("/cem/utils/set_periodic_odd", &test_set_periodic_odd_width);
return g_test_run();
}
| |
Add forgotted notification observer header. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_COMMON_NOTIFICATION_OBSERVER_H_
#define CHROME_COMMON_NOTIFICATION_OBSERVER_H_
class NotificationDetails;
class NotificationSource;
class NotificationType;
// This is the base class for notification observers. When a matching
// notification is posted to the notification service, Observe is called.
class NotificationObserver {
public:
virtual ~NotificationObserver();
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) = 0;
};
#endif // CHROME_COMMON_NOTIFICATION_OBSERVER_H_
| |
Reformat comment into Doxygen comment for file. | #ifndef HALIDE_TOOLS_IMAGE_H
#define HALIDE_TOOLS_IMAGE_H
/*
This allows code that relied on halide_image.h and Halide::Tools::Image to
continue to work with newer versions of Halide where HalideBuffer.h and
Halide::Buffer are the way to work with data.
Besides mapping Halide::Tools::Image to Halide::Buffer, it defines
USING_HALIDE_BUFFER to allow code to conditionally compile for one or the
other.
It is intended as a stop-gap measure until the code can be updated.
*/
#include "HalideBuffer.h"
namespace Halide {
namespace Tools {
#define USING_HALIDE_BUFFER
template< typename T >
using Image = Buffer<T>;
} // namespace Tools
} // mamespace Halide
#endif // #ifndef HALIDE_TOOLS_IMAGE_H
| #ifndef HALIDE_TOOLS_IMAGE_H
#define HALIDE_TOOLS_IMAGE_H
/** \file
*
* This allows code that relied on halide_image.h and
* Halide::Tools::Image to continue to work with newer versions of
* Halide where HalideBuffer.h and Halide::Buffer are the way to work
* with data.
*
* Besides mapping Halide::Tools::Image to Halide::Buffer, it defines
* USING_HALIDE_BUFFER to allow code to conditionally compile for one
* or the other.
*
* It is intended as a stop-gap measure until the code can be updated.
*/
#include "HalideBuffer.h"
namespace Halide {
namespace Tools {
#define USING_HALIDE_BUFFER
template< typename T >
using Image = Buffer<T>;
} // namespace Tools
} // mamespace Halide
#endif // #ifndef HALIDE_TOOLS_IMAGE_H
|
Fix this test to not rely on the path but to use the configured llvm-gcc instead. | // RUN: llvm-gcc %s -o - -S -emit-llvm -O3 | grep {i8 sext}
// PR1513
struct s{
long a;
long b;
};
void f(struct s a, char *b, char C) {
}
| // RUN: %llvmgcc %s -o - -S -emit-llvm -O3 | grep {i8 sext}
// PR1513
struct s{
long a;
long b;
};
void f(struct s a, char *b, char C) {
}
|
Remove my name from xcode's auto gen header template | //
// PINRemoteImageMacros.h
// PINRemoteImage
//
// Created by Brian Dorfman on 10/15/15.
// Copyright © 2015 Pinterest. All rights reserved.
//
#ifndef PINRemoteImageMacros_h
#define PINRemoteImageMacros_h
#define PINRemoteImageLogging 0
#if PINRemoteImageLogging
#define PINLog(args...) NSLog(args)
#else
#define PINLog(args...)
#endif
#if __has_include(<FLAnimatedImage/FLAnimatedImage.h>)
#define USE_FLANIMATED_IMAGE 1
#else
#define USE_FLANIMATED_IMAGE 0
#define FLAnimatedImage NSObject
#endif
#define BlockAssert(condition, desc, ...) \
do { \
__PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS \
if (!(condition)) { \
[[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd \
object:strongSelf file:[NSString stringWithUTF8String:__FILE__] \
lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; \
} \
__PRAGMA_POP_NO_EXTRA_ARG_WARNINGS \
} while(0);
#endif /* PINRemoteImageMacros_h */
| //
// PINRemoteImageMacros.h
// PINRemoteImage
//
#ifndef PINRemoteImageMacros_h
#define PINRemoteImageMacros_h
#define PINRemoteImageLogging 0
#if PINRemoteImageLogging
#define PINLog(args...) NSLog(args)
#else
#define PINLog(args...)
#endif
#if __has_include(<FLAnimatedImage/FLAnimatedImage.h>)
#define USE_FLANIMATED_IMAGE 1
#else
#define USE_FLANIMATED_IMAGE 0
#define FLAnimatedImage NSObject
#endif
#define BlockAssert(condition, desc, ...) \
do { \
__PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS \
if (!(condition)) { \
[[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd \
object:strongSelf file:[NSString stringWithUTF8String:__FILE__] \
lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; \
} \
__PRAGMA_POP_NO_EXTRA_ARG_WARNINGS \
} while(0);
#endif /* PINRemoteImageMacros_h */
|
Fix header to be the same as cpp | /* Manages interaction with the buttons */
#ifndef BUTTON_H
#define BUTTON_H
const unsigned char BUTTON_NONE = 100;
bool button_isPressed(int buttonNumber);
void button_wait(int buttonNumber);
void button_ISR();
#endif
| /* Manages interaction with the buttons */
#ifndef BUTTON_H
#define BUTTON_H
#include <Arduino.h>
const unsigned char BUTTON_NONE = 100;
bool button_isPressed(uint8_t buttonNumber);
void button_wait(uint8_t buttonNumber);
void button_ISR();
#endif
|
Make error constants unsigned longs. | /* --------------------------------------------------------------------------
* Name: errors.h
* Purpose: Error type and constants
* ----------------------------------------------------------------------- */
#ifndef ERRORS_H
#define ERRORS_H
typedef unsigned long int error;
#define error_OK 0
#define error_EXISTS 1
#define error_NOT_FOUND 2
#define error_OOM 3
#define error_STOP_WALK 4
#define error_CLASHES 5 /* key would clash with existing one */
#define error_NOT_IMPLEMENTED 6
#define error_KEYLEN_REQUIRED 200
#define error_KEYCOMPARE_REQUIRED 201
#define error_KEYHASH_REQIURED 202
#define error_QUEUE_FULL 300
#define error_QUEUE_EMPTY 301
#define error_TEST_FAILED 400
#define error_HASH_END 500
#define error_HASH_BAD_CONT 501
#endif /* ERRORS_H */
| /* --------------------------------------------------------------------------
* Name: errors.h
* Purpose: Error type and constants
* ----------------------------------------------------------------------- */
#ifndef ERRORS_H
#define ERRORS_H
typedef unsigned long int error;
/* Generic errors */
#define error_OK 0ul /* No error */
#define error_OOM 1ul /* Out of memory */
#define error_NOT_IMPLEMENTED 2ul /* Function not implemented */
#define error_NOT_FOUND 3ul /* Item not found */
#define error_EXISTS 4ul /* Item already exists */
#define error_STOP_WALK 5ul /* Callback was cancelled */
/* Data structure errors */
#define error_CLASHES 100ul /* Key would clash with existing one */
#define error_QUEUE_FULL 110ul
#define error_QUEUE_EMPTY 111ul
#define error_HASH_END 120ul
#define error_HASH_BAD_CONT 121ul
/* Container errors */
#define error_KEYLEN_REQUIRED 200ul
#define error_KEYCOMPARE_REQUIRED 201ul
#define error_KEYHASH_REQIURED 202ul
/* Test errors */
#define error_TEST_FAILED 300ul
#endif /* ERRORS_H */
|
Change type from `char*` to `const char*` | #include "util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "laco.h"
static inline void ignore_extra(const char chr, char** string_ptr) {
if(*string_ptr == NULL) return;
while(**string_ptr == chr) {
*string_ptr += 1;
}
}
/* External API */
void laco_kill(LacoState* laco, int status, const char* message) {
laco_destroy_laco_state(laco);
if(message != NULL) {
fprintf(stderr, "%s\n", message);
}
exit(status);
}
bool laco_is_match(const char** matches, const char* test_string) {
int i;
char* match;
for(i = 0; (match = (char*) matches[i]); i++) {
if(strcmp(test_string, match) == 0) {
return true;
}
}
return false;
}
char** laco_split_by(const char split_with, char* string,
int ignore_repeats) {
if(string == NULL) return NULL;
char** result = calloc(16, sizeof(char*));
size_t i = 0;
while(1) {
result[i] = strsep(&string, &split_with);
if(result[i] == NULL) break;
if(ignore_repeats) ignore_extra(split_with, &string);
i += 1;
}
return result;
}
| #include "util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "laco.h"
static inline void ignore_extra(const char chr, char** string_ptr) {
if(*string_ptr == NULL) return;
while(**string_ptr == chr) {
*string_ptr += 1;
}
}
/* External API */
void laco_kill(LacoState* laco, int status, const char* message) {
laco_destroy_laco_state(laco);
if(message != NULL) {
fprintf(stderr, "%s\n", message);
}
exit(status);
}
bool laco_is_match(const char** matches, const char* test_string) {
int i;
const char* match;
for(i = 0; (match = matches[i]); i++) {
if(strcmp(test_string, match) == 0) {
return true;
}
}
return false;
}
char** laco_split_by(const char split_with, char* string,
int ignore_repeats) {
if(string == NULL) return NULL;
char** result = calloc(16, sizeof(char*));
size_t i = 0;
while(1) {
result[i] = strsep(&string, &split_with);
if(result[i] == NULL) break;
if(ignore_repeats) ignore_extra(split_with, &string);
i += 1;
}
return result;
}
|
Make this test pretend to be on a darwin host. | // RUN: %clang -### -arch i386 -mmacosx-version-min=10.6 -D__IPHONE_OS_VERSION_MIN_REQUIRED=40201 -fobjc-arc -fsyntax-only %s 2>&1 | FileCheck -check-prefix=CHECK-OPTIONS1 %s
// RUN: %clang -### -arch i386 -mmacosx-version-min=10.6 -D__IPHONE_OS_VERSION_MIN_REQUIRED=50000 -fobjc-arc -fsyntax-only %s 2>&1 | FileCheck -check-prefix=CHECK-OPTIONS2 %s
// CHECK-OPTIONS1: -fobjc-no-arc-runtime
// CHECK-OPTIONS2-NOT: -fobjc-no-arc-runtime
| // RUN: %clang -### -ccc-host-triple i386-apple-darwin10 -arch i386 -mmacosx-version-min=10.6 -D__IPHONE_OS_VERSION_MIN_REQUIRED=40201 -fobjc-arc -fsyntax-only %s 2>&1 | FileCheck -check-prefix=CHECK-OPTIONS1 %s
// RUN: %clang -### -ccc-host-triple i386-apple-darwin10 -arch i386 -mmacosx-version-min=10.6 -D__IPHONE_OS_VERSION_MIN_REQUIRED=50000 -fobjc-arc -fsyntax-only %s 2>&1 | FileCheck -check-prefix=CHECK-OPTIONS2 %s
//
// CHECK-OPTIONS1: -fobjc-no-arc-runtime
// CHECK-OPTIONS2-NOT: -fobjc-no-arc-runtime
|
Put functions related to translation of predicates in separate file. | #ifndef __PLASP__PDDL__TRANSLATION__PREDICATE_H
#define __PLASP__PDDL__TRANSLATION__PREDICATE_H
#include <plasp/output/Formatting.h>
#include <plasp/pddl/expressions/DerivedPredicate.h>
#include <plasp/pddl/expressions/Predicate.h>
#include <plasp/pddl/expressions/PredicateDeclaration.h>
#include <plasp/pddl/translation/Variables.h>
namespace plasp
{
namespace pddl
{
namespace translation
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Predicate
//
////////////////////////////////////////////////////////////////////////////////////////////////////
void printPredicateName(output::ColorStream &outputStream, const expressions::PredicateDeclaration &predicateDeclaration);
void printDerivedPredicateName(output::ColorStream &outputStream, const expressions::DerivedPredicate &derivedPredicate);
////////////////////////////////////////////////////////////////////////////////////////////////////
inline void printPredicateName(output::ColorStream &outputStream, const expressions::PredicateDeclaration &predicateDeclaration)
{
outputStream << output::Keyword("variable") << "(";
if (predicateDeclaration.parameters().empty())
{
outputStream << output::String(predicateDeclaration.name().c_str()) << ")";
return;
}
outputStream << "(" << output::String(predicateDeclaration.name().c_str());
translation::translateVariablesForRuleHead(outputStream, predicateDeclaration.parameters());
outputStream << "))";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
inline void printDerivedPredicateName(output::ColorStream &outputStream, const expressions::DerivedPredicate &derivedPredicate)
{
outputStream << output::Keyword("derivedVariable") << "(";
const auto id = derivedPredicate.id();
if (derivedPredicate.parameters().empty())
{
outputStream << output::Number<decltype(id)>(id) << ")";
return;
}
outputStream << "(" << output::Number<decltype(id)>(id);
translation::translateVariablesForRuleHead(outputStream, derivedPredicate.parameters());
outputStream << "))";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
#endif
| |
Add SfieldFD class and TIPS3 and TIPS4 classes to phase_field app |
# ifndef COMMONPARAMS_H
# define COMMONPARAMS_H
struct CommonParams{
int nx,ny,nz;
int NX,NY,NZ;
int rank;
int np;
int xOff;
int iskip;
int jskip;
int kskip;
int nstep;
int numOutputs;
double dx,dy,dz;
double LX,LY,LZ;
double dt;
};
# endif // COMMONPARAMS_H
|
# ifndef COMMONPARAMS_H
# define COMMONPARAMS_H
struct CommonParams{
int nx,ny,nz;
int NX,NY,NZ;
int rank;
int np;
int nbrL;
int nbrR;
int xOff;
int iskip;
int jskip;
int kskip;
int nstep;
int numOutputs;
double dx,dy,dz;
double LX,LY,LZ;
double dt;
};
# endif // COMMONPARAMS_H
|
Apply fixes required to work with VS 2015 Community. |
#ifndef KAI_CONFIG_COMPILER_H
# define KAI_CONFIG_COMPILER_H
#
# if defined(BOOST_MSVC)
# define KAI_COMPILER_MSVC
# endif
#
# undef KAI_HAVE_PRAGMA_ONCE
#
# ifdef KAI_COMPILER_MSVC
# ifndef KAI_HAVE_PRAGMA_ONCE
# define KAI_HAVE_PRAGMA_ONCE
# endif
# endif // KAI_COMPILER_MSVC
#endif // KAI_CONFIG_COMPILER_H
//EOF
|
#ifndef KAI_CONFIG_COMPILER_H
# define KAI_CONFIG_COMPILER_H
#
# if defined(BOOST_MSVC)
# define KAI_COMPILER_MSVC
# endif
#
# undef KAI_HAVE_PRAGMA_ONCE
#pragma warning (disable: 4458 4456)
#
# ifdef KAI_COMPILER_MSVC
# ifndef KAI_HAVE_PRAGMA_ONCE
# define KAI_HAVE_PRAGMA_ONCE
# endif
# endif // KAI_COMPILER_MSVC
#endif // KAI_CONFIG_COMPILER_H
//EOF
|
Remove test case dependancy on platform headers. | // RUN: %clang_cc1 -analyze -analyzer-check-objc-mem %s -analyzer-store=region
// RUN: %clang_cc1 -analyze -analyzer-check-objc-mem %s -analyzer-store=basic
#include <fcntl.h>
void test_open(const char *path) {
int fd;
fd = open(path, O_RDONLY); // no-warning
if (!fd)
close(fd);
fd = open(path, O_CREAT); // expected-warning{{Call to 'open' requires a third argument when the 'O_CREAT' flag is set}}
if (!fd)
close(fd);
}
| // RUN: %clang_cc1 -analyze -analyzer-check-objc-mem %s -analyzer-store=region
// RUN: %clang_cc1 -analyze -analyzer-check-objc-mem %s -analyzer-store=basic
#ifndef O_CREAT
#define O_CREAT 0x0200
#define O_RDONLY 0x0000
#endif
int open(const char *, int, ...);
void test_open(const char *path) {
int fd;
fd = open(path, O_RDONLY); // no-warning
if (!fd)
close(fd);
fd = open(path, O_CREAT); // expected-warning{{Call to 'open' requires a third argument when the 'O_CREAT' flag is set}}
if (!fd)
close(fd);
}
|
Include the rapidcheck header at top-level | #pragma once
#include <sstream>
#include <rapidcheck.h>
#include <catch.hpp>
namespace rc {
/// For use with `catch.hpp`. Use this function wherever you would use a
/// `SECTION` for convenient checking of properties.
///
/// @param description A description of the property.
/// @param testable The object that implements the property.
template <typename Testable>
void prop(const std::string &description, Testable &&testable) {
using namespace detail;
#ifdef CATCH_CONFIG_PREFIX_ALL
CATCH_SECTION(description) {
#else
SECTION(description) {
#endif
const auto result = checkTestable(std::forward<Testable>(testable));
if (result.template is<SuccessResult>()) {
const auto success = result.template get<SuccessResult>();
if (!success.distribution.empty()) {
std::cout << "- " << description << std::endl;
printResultMessage(result, std::cout);
std::cout << std::endl;
}
} else {
std::ostringstream ss;
printResultMessage(result, ss);
#ifdef CATCH_CONFIG_PREFIX_ALL
CATCH_INFO(ss.str() << "\n");
CATCH_FAIL();
#else
INFO(ss.str() << "\n");
FAIL();
#endif
}
}
}
} // namespace rc
| |
Add Chapter 27, Try This | /* Chapter 27, Try This: test cat(), find and remove performance error, add
comments */
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
struct A {
int x;
};
char* cat(const char* id, const char* addr)
{
int len_id = strlen(id); /* so it has to be calculated only once */
int sz = len_id + strlen(addr) + 2; /* add extra space for terminating 0 */
char* res = (char*) malloc(sz);
strcpy(res,id);
res[len_id] = '@'; /* and not len_id + 1 */
strcpy(res+len_id+1,addr); /* and not len_id + 2 */
res[sz-1] = 0; /* terminate string */
return res;
}
int main()
{
A a;
char* id = "scott.meyers";
char* addr = "aristeia.com";
char* s = cat(id,addr);
printf("%s\n",s);
} | |
Document the mini pack format. | // This will load a lorito bytecode file into a lorito codeseg
| // This will load a lorito bytecode file into a lorito codeseg
// Since this is temporary, and we'll end up throwing it away in favor of
// integrating with parrot's packfile format, this will be real simple.
//
// Integer: segment type (0 = code, 1 = data)
// Integer: Size of segement name
// String: segment name, null terminated
// Integer: Count (in 8 bytes, so a count of 1 == 8 bytes)
// Data
|
Enable interval analysis for test |
int main()
{
unsigned int top;
unsigned int start = 0;
unsigned int count = 0;
if(start + count > top) {
return 1;
}
return 0;
}
| // PARAM: --enable ana.int.interval
int main()
{
unsigned int top;
unsigned int start = 0;
unsigned int count = 0;
if(start + count > top) {
return 1;
}
return 0;
}
|
Use 16-byte stack alignment on Windows, if using SSE | #ifndef _hashable_siphash_h
#define _hashable_siphash_h
#include <stdint.h>
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
#define SIPHASH_ROUNDS 2
#define SIPHASH_FINALROUNDS 4
u64 hashable_siphash(int, int, u64, u64, const u8 *, size_t);
u64 hashable_siphash24(u64, u64, const u8 *, size_t);
#if defined(__i386)
u64 hashable_siphash24_sse2(u64, u64, const u8 *, size_t);
u64 hashable_siphash24_sse41(u64, u64, const u8 *, size_t);
#endif
#endif /* _hashable_siphash_h */
| #ifndef _hashable_siphash_h
#define _hashable_siphash_h
#include <stdint.h>
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
#define SIPHASH_ROUNDS 2
#define SIPHASH_FINALROUNDS 4
u64 hashable_siphash(int, int, u64, u64, const u8 *, size_t);
u64 hashable_siphash24(u64, u64, const u8 *, size_t);
#if defined(__i386) || defined(__x86_64)
/* To use SSE instructions on Windows, we have to adjust the stack
from its default of 4-byte alignment to use 16-byte alignment. */
# if defined(_WIN32)
# define ALIGNED_STACK __attribute__((force_align_arg_pointer))
# else
# define ALIGNED_STACK
# endif
u64 hashable_siphash24_sse2(u64, u64, const u8 *, size_t) ALIGNED_STACK;
u64 hashable_siphash24_sse41(u64, u64, const u8 *, size_t) ALIGNED_STACK;
#endif
#endif /* _hashable_siphash_h */
|
Add some EXPORT qualifiers for msvc | #ifndef HALIDE_CPLUSPLUS_MANGLE_H
#define HALIDE_CPLUSPLUS_MANGLE_H
/** \file
*
* A simple function to get a C++ mangled function name for a function.
*/
#include <string>
#include "IR.h"
#include "Target.h"
namespace Halide {
namespace Internal {
/** Return the mangled C++ name for a function.
* The target parameter is used to decide on the C++
* ABI/mangling style to use.
*/
std::string cplusplus_function_mangled_name(const std::string &name, const std::vector<std::string> &namespaces,
Type return_type, const std::vector<ExternFuncArgument> &args,
const Target &target);
void cplusplus_mangle_test();
}
}
#endif
| #ifndef HALIDE_CPLUSPLUS_MANGLE_H
#define HALIDE_CPLUSPLUS_MANGLE_H
/** \file
*
* A simple function to get a C++ mangled function name for a function.
*/
#include <string>
#include "IR.h"
#include "Target.h"
namespace Halide {
namespace Internal {
/** Return the mangled C++ name for a function.
* The target parameter is used to decide on the C++
* ABI/mangling style to use.
*/
EXPORT std::string cplusplus_function_mangled_name(const std::string &name, const std::vector<std::string> &namespaces,
Type return_type, const std::vector<ExternFuncArgument> &args,
const Target &target);
EXPORT void cplusplus_mangle_test();
}
}
#endif
|
Add read and execute command from stdin demo | #include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define MAXLINE 4096
int main(int argc, char *argv[]) {
char buf[MAXLINE];
pid_t pid;
int status;
printf("%% ");
while (fgets(buf, MAXLINE, stdin) != NULL) {
buf[strlen(buf) - 1] = 0;
if ((pid = fork()) < 0) {
printf("fork error");
} else if (pid == 0) { /* child */
execlp(buf, buf, (char*)0);
printf("couldn't execute: %s\n", buf);
return -1;
}
if ((pid = waitpid(pid, &status, 0)) < 0) {
printf("waitpid error");
}
printf("%% ");
}
return 0;
}
| |
Add function to convert MoveMak to mask vector | #ifndef VolViz_Geometry_h
#define VolViz_Geometry_h
#include "Types.h"
namespace VolViz {
enum MoveMask : uint8_t {
None = 0x00,
X = 0x01,
Y = 0x02,
Z = 0x04,
All = 0x07
};
struct GeometryDescriptor {
bool movable{true};
Color color{Colors::White()};
};
struct AxisAlignedPlaneDescriptor : public GeometryDescriptor {
Length intercept{0 * meter};
Axis axis{Axis::X};
};
} // namespace VolViz
#endif // VolViz_Geometry_h
| #ifndef VolViz_Geometry_h
#define VolViz_Geometry_h
#include "Types.h"
namespace VolViz {
enum MoveMask : uint8_t {
None = 0x00,
X = 0x01,
Y = 0x02,
Z = 0x04,
All = 0x07
};
inline Vector3f maskToUnitVector(MoveMask mask) noexcept {
Vector3f v = Vector3f::Zero();
auto maskRep = static_cast<uint8_t>(mask);
Expects(maskRep <= 0x07);
int idx{0};
while (maskRep != 0) {
if (maskRep & 0x01) v(idx) = 1.f;
maskRep >>= 1;
++idx;
}
return v;
}
struct GeometryDescriptor {
bool movable{true};
Color color{Colors::White()};
};
struct AxisAlignedPlaneDescriptor : public GeometryDescriptor {
Length intercept{0 * meter};
Axis axis{Axis::X};
};
} // namespace VolViz
#endif // VolViz_Geometry_h
|
Fix compilation on FreeBSD 10.3 with default compiler | #ifndef __HIREDIS_FMACRO_H
#define __HIREDIS_FMACRO_H
#if defined(__linux__)
#define _BSD_SOURCE
#define _DEFAULT_SOURCE
#endif
#if defined(__CYGWIN__)
#include <sys/cdefs.h>
#endif
#if defined(__sun__)
#define _POSIX_C_SOURCE 200112L
#else
#if !(defined(__APPLE__) && defined(__MACH__))
#define _XOPEN_SOURCE 600
#endif
#endif
#if defined(__APPLE__) && defined(__MACH__)
#define _OSX
#endif
#endif
| #ifndef __HIREDIS_FMACRO_H
#define __HIREDIS_FMACRO_H
#if defined(__linux__)
#define _BSD_SOURCE
#define _DEFAULT_SOURCE
#endif
#if defined(__CYGWIN__)
#include <sys/cdefs.h>
#endif
#if defined(__sun__)
#define _POSIX_C_SOURCE 200112L
#else
#if !(defined(__APPLE__) && defined(__MACH__)) && !(defined(__FreeBSD__))
#define _XOPEN_SOURCE 600
#endif
#endif
#if defined(__APPLE__) && defined(__MACH__)
#define _OSX
#endif
#endif
|
Fix header paths in FoundationAdditions umbrella header | #import "FoundationAdditions/TDTLog.h"
#import "FoundationAdditions/TDTAssert.h"
#import "FoundationAdditions/TDTSuppressPerformSelectorLeakWarning.h"
#import "FoundationAdditions/NSArray+TDTFunctionalAdditions.h"
#import "FoundationAdditions/NSSet+TDTFunctionalAdditions.h"
#import "FoundationAdditions/TDTObjectOrDefault.h"
#import "FoundationAdditions/NSArray+TDTAdditions.h"
#import "FoundationAdditions/NSString+TDTAdditions.h"
#import "FoundationAdditions/NSData+TDTStringEncoding.h"
#import "FoundationAdditions/NSDate+TDTAdditions.h"
#import "FoundationAdditions/NSDate+TDTComparisons.h"
#import "FoundationAdditions/NSDateFormatter+TDTISO8601Formatting.h"
#import "FoundationAdditions/NSFileManager+TDTAdditions.h"
#import "FoundationAdditions/NSProcessInfo+TDTEnvironmentAdditions.h"
#import "FoundationAdditions/TDTBlockAdditions.h"
#import "FoundationAdditions/TDTKeychain.h"
| #import "FoundationAdditions/TDTLog.h"
#import "FoundationAdditions/TDTAssert.h"
#import "FoundationAdditions/TDTSuppressPerformSelectorLeakWarning.h"
#import "FoundationAdditions/NSArray+TDTFunctionalAdditions.h"
#import "FoundationAdditions/NSSet+TDTFunctionalAdditions.h"
#import "FoundationAdditions/TDTObjectOrDefault.h"
#import "FoundationAdditions/NSArray+TDTAdditions.h"
#import "FoundationAdditions/NSString+TDTAdditions.h"
#import "FoundationAdditions/NSData+TDTStringEncoding.h"
#import "FoundationAdditions/NSDate+TDTAdditions.h"
#import "FoundationAdditions/NSDate+TDTComparisons.h"
#import "FoundationAdditions/NSDateFormatter+TDTISO8601Formatting.h"
#import "FoundationAdditions/NSFileManager+TDTAdditions.h"
#import "FoundationAdditions/NSProcessInfo+TDTEnvironmentDetection.h"
#import "FoundationAdditions/TDTBlockAdditions.h"
|
Add test packet data and fix invalid serial_close call | #include "hardware/packet.h"
#include "serial.h"
void btoa(int num, char *buf, int digits) {
int shift = digits - 1;
int current = pow(2, shift);
char digit[2];
while (current > 0) {
sprintf(digit, "%d", ((num & current) >> shift) & 1);
strncat(buf, digit, 1);
shift--;
current /= 2;
}
strcat(buf, "\0");
}
int main(int argc, char *argv[]) {
// 0: device
// 1: group
// 2: plug
// 3: status
char device[] = "\\\\.\\\\COM5";
if (serial_connect(device) == SERIAL_ERROR) {
printf("Failed to connect to serial device \"%s\"\n", device);
return 1;
}
struct Packet packet = { 0, 0, 0 };
if (serial_transmit(packet) == SERIAL_ERROR) {
printf("Failed to send data to serial device \"%s\"\n", device);
return 1;
}
serial_close(device);
return 0;
}
| #include "hardware/packet.h"
#include "serial.h"
void btoa(int num, char *buf, int digits) {
int shift = digits - 1;
int current = pow(2, shift);
char digit[2];
while (current > 0) {
sprintf(digit, "%d", ((num & current) >> shift) & 1);
strncat(buf, digit, 1);
shift--;
current /= 2;
}
strcat(buf, "\0");
}
int main(int argc, char *argv[]) {
// 0: device
// 1: group
// 2: plug
// 3: status
char device[] = "\\\\.\\\\COM5";
if (serial_connect(device) == SERIAL_ERROR) {
printf("Failed to connect to serial device \"%s\"\n", device);
return 1;
}
struct Packet packet = { 1, 0, 3 };
if (serial_transmit(packet) == SERIAL_ERROR) {
printf("Failed to send data to serial device \"%s\"\n", device);
return 1;
}
serial_close();
return 0;
}
|
Add initial implementation of new VFS header | /* @author Denis Deryugin
* @date 17 Mar 2015
*
* Dumb VFS
*/
#ifndef _DVFS_H_
#define _DVFS_H_
#include <fs/file_system.h>
#include <util/dlist.h>
/*****************
New VFS prototype
*****************/
#define DENTRY_NAME_LEN 16
#define FS_NAME_LEN 16
struct super_block;
struct inode;
struct dentry;
struct dumb_fs_driver;
struct super_block {
struct dumb_fs_driver *fs_drv; /* Assume that all FS have single driver */
struct block_dev *bdev;
struct dentry *root;
struct dlist_head *inode_list;
struct super_block_operations *sb_ops;
void *sb_data;
};
struct super_block_operations {
struct inode *(*inode_alloc)(struct super_block *sb);
int (*destroy_inode)(struct inode *inode);
int (*write_inode)(struct inode *inode);
int (*umount_begin)(struct super_block *sb);
};
struct inode {
int i_no;
int start_pos; /* location on disk */
size_t length;
struct inode_operations *i_ops;
void *i_data;
};
struct inode_operations {
struct inode *(*create)(struct dentry *d_new, struct dentry *d_dir, int mode);
struct inode *(*lookup)(char *name, struct dentry *dir);
int (*mkdir)(struct dentry *d_new, struct dentry *d_parent);
int (*rmdir)(struct dentry *dir);
int (*truncate)(struct inode *inode, size_t len);
int (*pathname)(struct inode *inode, char *buf);
};
struct dentry {
char name[DENTRY_NAME_LEN];
struct inode *inode;
struct dentry *parent;
struct dlist_head *next; /* Next element in this directory */
struct dlist_head *children; /* Subelemtnts of directory */
};
struct file {
struct dentry *f_dentry;
off_t pos;
struct file_operations *f_ops;
};
struct file_operations {
int (*open)(struct node *node, struct file *file_desc, int flags);
int (*close)(struct file *desc);
size_t (*read)(struct file *desc, void *buf, size_t size);
size_t (*write)(struct file *desc, void *buf, size_t size);
int (*ioctl)(struct file *desc, int request, ...);
};
struct dumb_fs_driver {
const char name[FS_NAME_LEN];
};
#endif
| |
Remove startup delay and messages | #include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "deps/util.h"
#include "deps/rcswitch.h"
#define PIN_RC PB2
#include "deps/softuart.h"
#include "packet.h"
int main(void) {
// initialize serial
softuart_init();
// enable interrupts
sei();
delay_ms(1000);
softuart_puts("Starting...\r\n");
// enable the rc switch
rcswitch_enable(PIN_RC);
while (1) {
// if there is some data waiting for us
if (softuart_kbhit()) {
// parse the data
struct Packet packet;
binary_to_packet(&packet, softuart_getchar());
// handle the packet
if (packet.status) {
rcswitch_switch_on(packet.group + 1, packet.plug + 1);
} else {
rcswitch_switch_off(packet.group + 1, packet.plug + 1);
}
}
}
return 0;
}
| #include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "deps/util.h"
#include "deps/rcswitch.h"
#define PIN_RC PB2
#include "deps/softuart.h"
#include "packet.h"
int main(void) {
// initialize serial
softuart_init();
// enable interrupts
sei();
// enable the rc switch
rcswitch_enable(PIN_RC);
while (1) {
// if there is some data waiting for us
if (softuart_kbhit()) {
// parse the data
struct Packet packet;
binary_to_packet(&packet, softuart_getchar());
// handle the packet
if (packet.status) {
rcswitch_switch_on(packet.group + 1, packet.plug + 1);
} else {
rcswitch_switch_off(packet.group + 1, packet.plug + 1);
}
}
}
return 0;
}
|
Add header for including messaging module. | /****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QTMESSAGING_H
#define QTMESSAGING_H
#include "qmessageglobal.h"
#include "qmessageaccount.h"
#include "qmessageaccountfilterkey.h"
#include "qmessageaccountid.h"
#include "qmessageaccountsortkey.h"
#include "qmessagefolder.h"
#include "qmessagefolderfilterkey.h"
#include "qmessagefolderid.h"
#include "qmessagefoldersortkey.h"
#include "qmessage.h"
#include "qmessagefilterkey.h"
#include "qmessageid.h"
#include "qmessagesortkey.h"
#include "qmessagecontentcontainer.h"
#include "qmessagecontentcontainerid.h"
#include "qmessageaddress.h"
#include "qmessageserviceaction.h"
#include "qmessagestore.h"
#endif
| |
Make bitfield signs explicitly signed (detected by Semmle). | /*
* Copyright 2015-2016 Yury Gribov
*
* Use of this source code is governed by MIT license that can be
* found in the LICENSE.txt file.
*/
#ifndef FLAGS_H
#define FLAGS_H
enum CheckFlags {
CHECK_BASIC = 1 << 0,
CHECK_REFLEXIVITY = 1 << 1,
CHECK_SYMMETRY = 1 << 2,
CHECK_TRANSITIVITY = 1 << 3,
CHECK_SORTED = 1 << 4,
CHECK_GOOD_BSEARCH = 1 << 5,
CHECK_UNIQUE = 1 << 6,
// Do not check reflexivity because it's normally not important (CHECK_REFLEXIVITY).
// Do not assume bsearch is commutative (CHECK_GOOD_BSEARCH).
CHECK_DEFAULT = CHECK_BASIC | CHECK_SYMMETRY
| CHECK_TRANSITIVITY | CHECK_SORTED,
CHECK_ALL = 0xffffffff,
};
typedef struct {
char debug : 1;
char report_error : 1;
char print_to_syslog : 1;
char raise : 1;
unsigned max_errors;
unsigned sleep;
unsigned checks;
const char *out_filename;
} Flags;
int parse_flags(char *opts, Flags *flags);
#endif
| /*
* Copyright 2015-2016 Yury Gribov
*
* Use of this source code is governed by MIT license that can be
* found in the LICENSE.txt file.
*/
#ifndef FLAGS_H
#define FLAGS_H
enum CheckFlags {
CHECK_BASIC = 1 << 0,
CHECK_REFLEXIVITY = 1 << 1,
CHECK_SYMMETRY = 1 << 2,
CHECK_TRANSITIVITY = 1 << 3,
CHECK_SORTED = 1 << 4,
CHECK_GOOD_BSEARCH = 1 << 5,
CHECK_UNIQUE = 1 << 6,
// Do not check reflexivity because it's normally not important (CHECK_REFLEXIVITY).
// Do not assume bsearch is commutative (CHECK_GOOD_BSEARCH).
CHECK_DEFAULT = CHECK_BASIC | CHECK_SYMMETRY
| CHECK_TRANSITIVITY | CHECK_SORTED,
CHECK_ALL = 0xffffffff,
};
typedef struct {
unsigned char debug : 1;
unsigned char report_error : 1;
unsigned char print_to_syslog : 1;
unsigned char raise : 1;
unsigned max_errors;
unsigned sleep;
unsigned checks;
const char *out_filename;
} Flags;
int parse_flags(char *opts, Flags *flags);
#endif
|
Add test where octApron assert should refine | // SKIP PARAM: --sets ana.activated[+] apron
#include <assert.h>
void main() {
int x, y, z;
// TODO: make these asserts after distinction
__goblint_commit(x < y); // U NKNOWN! (refines)
__goblint_commit(y < z); // U NKNOWN! (refines)
__goblint_commit(3 <= x); // U NKNOWN! (refines)
__goblint_commit(z <= 5); // U NKNOWN! (refines)
assert(x == 3);
assert(y == 4);
assert(z == 5);
}
| |
Initialize FixedVector's member in its null constructor to eliminate a Wall warning. | #pragma once
template <typename T, unsigned int N>
struct FixedVector
{
T data[N];
__host__ __device__
FixedVector() { }
__host__ __device__
FixedVector(T init)
{
for(unsigned int i = 0; i < N; i++)
data[i] = init;
}
__host__ __device__
FixedVector operator+(const FixedVector& bs) const
{
FixedVector output;
for(unsigned int i = 0; i < N; i++)
output.data[i] = data[i] + bs.data[i];
return output;
}
__host__ __device__
bool operator<(const FixedVector& bs) const
{
for(unsigned int i = 0; i < N; i++)
{
if(data[i] < bs.data[i])
return true;
else if(bs.data[i] < data[i])
return false;
}
return false;
}
__host__ __device__
bool operator==(const FixedVector& bs) const
{
for(unsigned int i = 0; i < N; i++)
{
if(!(data[i] == bs.data[i]))
return false;
}
return true;
}
};
| #pragma once
template <typename T, unsigned int N>
struct FixedVector
{
T data[N];
__host__ __device__
FixedVector() : data() { }
__host__ __device__
FixedVector(T init)
{
for(unsigned int i = 0; i < N; i++)
data[i] = init;
}
__host__ __device__
FixedVector operator+(const FixedVector& bs) const
{
FixedVector output;
for(unsigned int i = 0; i < N; i++)
output.data[i] = data[i] + bs.data[i];
return output;
}
__host__ __device__
bool operator<(const FixedVector& bs) const
{
for(unsigned int i = 0; i < N; i++)
{
if(data[i] < bs.data[i])
return true;
else if(bs.data[i] < data[i])
return false;
}
return false;
}
__host__ __device__
bool operator==(const FixedVector& bs) const
{
for(unsigned int i = 0; i < N; i++)
{
if(!(data[i] == bs.data[i]))
return false;
}
return true;
}
};
|
Remove spammy hello world from account system | /*
* This file is part of Kotaka, a mud library for DGD
* http://github.com/shentino/kotaka
*
* Copyright (C) 2012 Raymond Jennings
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <kotaka/log.h>
#include <kotaka/paths.h>
inherit LIB_INITD;
inherit UTILITY_COMPILE;
static void create()
{
KERNELD->set_global_access("Account", 1);
load_dir("sys");
LOGD->post_message("account", LOG_DEBUG, "Hello world from the account subsystem");
}
| /*
* This file is part of Kotaka, a mud library for DGD
* http://github.com/shentino/kotaka
*
* Copyright (C) 2012 Raymond Jennings
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <kotaka/log.h>
#include <kotaka/paths.h>
inherit LIB_INITD;
inherit UTILITY_COMPILE;
static void create()
{
KERNELD->set_global_access("Account", 1);
load_dir("sys");
}
|
Rename buffer.h to buffer_helper.h, part II | /** \file
*
* \brief Inclusion of all utility function headers
*
* \date Created: Jul 12, 2014
* \date Modified: $Date$
*
* \authors mauro <mauro@iis.ee.ethz.ch>
*
* \version $Revision$
*/
#ifndef LINALG_UTILITIES_UTILITIES_H_
#define LINALG_UTILITIES_UTILITIES_H_
// Keep this in alphabetical order
#include "buffer.h"
#include "checks.h"
#include "copy_array.h"
#include "CSR.h"
#include "format_convert.h"
#include "IJV.h"
#include "memory_allocation.h"
#include "misc.h"
#include "stringformat.h"
#include "timer.h"
#endif /* LINALG_UTILITIES_UTILITIES_H_ */
| /** \file
*
* \brief Inclusion of all utility function headers
*
* \date Created: Jul 12, 2014
* \date Modified: $Date$
*
* \authors mauro <mauro@iis.ee.ethz.ch>
*
* \version $Revision$
*/
#ifndef LINALG_UTILITIES_UTILITIES_H_
#define LINALG_UTILITIES_UTILITIES_H_
// Keep this in alphabetical order
#include "buffer_helper.h"
#include "checks.h"
#include "copy_array.h"
#include "CSR.h"
#include "format_convert.h"
#include "IJV.h"
#include "memory_allocation.h"
#include "misc.h"
#include "stringformat.h"
#include "timer.h"
#endif /* LINALG_UTILITIES_UTILITIES_H_ */
|
Fix detection of lib if we use `-Werror` | /**
* @file
*
* @brief tests if compilation works (include and build paths set correct, etc...)
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#include <openssl/evp.h>
int main (void)
{
EVP_CIPHER_CTX * opensslSpecificType;
return 0;
}
| /**
* @file
*
* @brief tests if compilation works (include and build paths set correct, etc...)
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#include <openssl/evp.h>
EVP_CIPHER_CTX * nothing (void)
{
return NULL;
}
int main (void)
{
nothing ();
return 0;
}
|
Fix the powerpc clock from the tbr. | /*
*
* SOS Source Code
* __________________
*
* [2009] - [2013] Samuel Steven Truscott
* All Rights Reserved.
*/
#include "time_manager.h"
#include "kernel/kernel_assert.h"
#include "time.h"
static int64_t __time_system_time_ns;
static __clock_device_t * __time_system_clock;
void __time_initialise(void)
{
__time_system_time_ns = 0;
__time_system_clock = NULL;
}
void __time_set_system_clock(__clock_device_t * const device)
{
__time_system_clock = device;
}
sos_time_t __time_get_system_time(void)
{
sos_time_t time = SOS_ZERO_TIME;
if (__time_system_clock)
{
__time_system_time_ns = (int64_t)__time_system_clock->get_time();
time.seconds = (int32_t)__time_system_time_ns / ONE_SECOND_AS_NANOSECONDS;
time.nanoseconds = (int64_t)(__time_system_time_ns - ((int64_t)time.seconds * ONE_SECOND_AS_NANOSECONDS));
}
return time;
}
| /*
*
* SOS Source Code
* __________________
*
* [2009] - [2013] Samuel Steven Truscott
* All Rights Reserved.
*/
#include "time_manager.h"
#include "kernel/kernel_assert.h"
#include "time.h"
static uint64_t __time_system_time_ns;
static __clock_device_t * __time_system_clock;
void __time_initialise(void)
{
__time_system_time_ns = 0;
__time_system_clock = NULL;
}
void __time_set_system_clock(__clock_device_t * const device)
{
__time_system_clock = device;
}
sos_time_t __time_get_system_time(void)
{
sos_time_t time = SOS_ZERO_TIME;
if (__time_system_clock)
{
__time_system_time_ns = __time_system_clock->get_time();
time.seconds = __time_system_time_ns / ONE_SECOND_AS_NANOSECONDS;
time.nanoseconds = (int64_t)(__time_system_time_ns - ((int64_t)time.seconds * ONE_SECOND_AS_NANOSECONDS));
}
return time;
}
|
Add testcase: retain precision when negating unsigned value | #include <assert.h>
#include <stdio.h>
int main(){
unsigned int x = 1;
unsigned int y = -x;
assert(y == 4294967295);
printf("y: %u\n", y);
return 0;
}
| |
Add mergedOperationsQueue and mergeQueue to ensure correctness of file being modified | #pragma once
#ifndef YOU_DATASTORE_INTERNAL_INTERNAL_TRANSACTION_H_
#define YOU_DATASTORE_INTERNAL_INTERNAL_TRANSACTION_H_
#include <memory>
#include <boost/ptr_container/ptr_deque.hpp>
#include "operation.h"
namespace You {
namespace DataStore {
namespace UnitTests { class DataStoreApiTest; }
namespace Internal {
/// The actual class that contains the logic for managing transactions.
class Transaction {
friend class DataStore;
friend class UnitTests::DataStoreApiTest;
public:
/// Default constructor. This is meant to be called by \ref DataStore.
Transaction() = default;
/// Commits the set of operations made.
void commit();
/// Rolls back all the operations made.
void rollback();
/// Pushes a transaction onto the stack. This is meant to be called by
/// \ref DataStore.
///
/// \param[in] operation The operation to push.
void push(std::unique_ptr<IOperation> operation);
private:
/// The set of operations that need to be executed when the transaction is
/// committed.
boost::ptr_deque<IOperation> operationsQueue;
};
} // namespace Internal
} // namespace DataStore
} // namespace You
#endif // YOU_DATASTORE_INTERNAL_INTERNAL_TRANSACTION_H_
| #pragma once
#ifndef YOU_DATASTORE_INTERNAL_INTERNAL_TRANSACTION_H_
#define YOU_DATASTORE_INTERNAL_INTERNAL_TRANSACTION_H_
#include <memory>
#include <boost/ptr_container/ptr_deque.hpp>
#include "operation.h"
namespace You {
namespace DataStore {
namespace UnitTests { class DataStoreApiTest; }
namespace Internal {
/// The actual class that contains the logic for managing transactions.
class Transaction {
friend class DataStore;
friend class UnitTests::DataStoreApiTest;
public:
/// Default constructor. This is meant to be called by \ref DataStore.
Transaction() = default;
/// Commits the set of operations made.
void commit();
/// Rolls back all the operations made.
void rollback();
/// Pushes a transaction onto the stack. This is meant to be called by
/// \ref DataStore.
///
/// \param[in] operation The operation to push.
void push(std::unique_ptr<IOperation> operation);
/// Merges the operationsQueue of the next transaction that is committed
/// earlier.
///
/// \param[in] queue The operations queue
void mergeQueue(boost::ptr_deque<IOperation>& queue);
private:
/// The set of operations that need to be executed when the transaction is
/// committed.
boost::ptr_deque<IOperation> operationsQueue;
boost::ptr_deque<IOperation> mergedOperationsQueue;
};
} // namespace Internal
} // namespace DataStore
} // namespace You
#endif // YOU_DATASTORE_INTERNAL_INTERNAL_TRANSACTION_H_
|
Prepare the header for stand-alone usage. | //===--- TokenKinds.h - Token Kinds Interface -------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the Token kinds.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_TOKENKINDS_H
#define SWIFT_TOKENKINDS_H
namespace swift {
enum class tok {
#define TOKEN(X) X,
#include "swift/Syntax/TokenKinds.def"
NUM_TOKENS
};
/// Check whether a token kind is known to have any specific text content.
/// e.g., tol::l_paren has determined text however tok::identifier doesn't.
bool isTokenTextDetermined(tok kind);
/// If a token kind has determined text, return the text; otherwise assert.
StringRef getTokenText(tok kind);
void dumpTokenKind(llvm::raw_ostream &os, tok kind);
} // end namespace swift
#endif // SWIFT_TOKENKINDS_H
| //===--- TokenKinds.h - Token Kinds Interface -------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the Token kinds.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_TOKENKINDS_H
#define SWIFT_TOKENKINDS_H
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
namespace swift {
enum class tok {
#define TOKEN(X) X,
#include "swift/Syntax/TokenKinds.def"
NUM_TOKENS
};
/// Check whether a token kind is known to have any specific text content.
/// e.g., tol::l_paren has determined text however tok::identifier doesn't.
bool isTokenTextDetermined(tok kind);
/// If a token kind has determined text, return the text; otherwise assert.
StringRef getTokenText(tok kind);
void dumpTokenKind(llvm::raw_ostream &os, tok kind);
} // end namespace swift
#endif // SWIFT_TOKENKINDS_H
|
Disable Microsoft extensions to fix failure on Windows. | // RUN: clang-cc %s -Eonly 2>&1 | grep error
#define COMM1 / ## /
COMM1
| // RUN: clang-cc %s -Eonly -fms-extensions=0 2>&1 | grep error
#define COMM1 / ## /
COMM1
|
Add paralellism with race conditions to omp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bmp.h"
const int image_width = 512;
const int image_height = 512;
const int image_size = 512*512;
const int color_depth = 255;
int main(int argc, char** argv){
if(argc != 3){
printf("Useage: %s image n_threads\n", argv[0]);
exit(-1);
}
int n_threads = atoi(argv[2]);
unsigned char* image = read_bmp(argv[1]);
unsigned char* output_image = malloc(sizeof(unsigned char) * image_size);
int* histogram = (int*)calloc(sizeof(int), color_depth);
for(int i = 0; i < image_size; i++){
histogram[image[i]]++;
}
float* transfer_function = (float*)calloc(sizeof(float), color_depth);
for(int i = 0; i < color_depth; i++){
for(int j = 0; j < i+1; j++){
transfer_function[i] += color_depth*((float)histogram[j])/(image_size);
}
}
for(int i = 0; i < image_size; i++){
output_image[i] = transfer_function[image[i]];
}
write_bmp(output_image, image_width, image_height);
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bmp.h"
const int image_width = 512;
const int image_height = 512;
const int image_size = 512*512;
const int color_depth = 255;
int main(int argc, char** argv){
if(argc != 3){
printf("Useage: %s image n_threads\n", argv[0]);
exit(-1);
}
int n_threads = atoi(argv[2]);
unsigned char* image = read_bmp(argv[1]);
unsigned char* output_image = malloc(sizeof(unsigned char) * image_size);
int* histogram = (int*)calloc(sizeof(int), color_depth);
#pragma omp parallel for
for(int i = 0; i < image_size; i++){
histogram[image[i]]++;
}
float* transfer_function = (float*)calloc(sizeof(float), color_depth);
#pragma omp parallel for
for(int i = 0; i < color_depth; i++){
for(int j = 0; j < i+1; j++){
transfer_function[i] += color_depth*((float)histogram[j])/(image_size);
}
}
for(int i = 0; i < image_size; i++){
output_image[i] = transfer_function[image[i]];
}
write_bmp(output_image, image_width, image_height);
}
|
Remove unused struct tm elements | /******************************************************************************
* Copyright (c) 2004, 2008 IBM Corporation
* All rights reserved.
* This program and the accompanying materials
* are made available under the terms of the BSD License
* which accompanies this distribution, and is available at
* http://www.opensource.org/licenses/bsd-license.php
*
* Contributors:
* IBM Corporation - initial implementation
*****************************************************************************/
#ifndef _TIME_H
#define _TIME_H
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
/* unused in skiboot */
int tm_wday;
int tm_yday;
int tm_isdst;
};
typedef long time_t;
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
struct tm *gmtime_r(const time_t *timep, struct tm *result);
time_t mktime(struct tm *tm);
/* Not implemented by libc but by hosting environment, however
* this is where the prototype is expected
*/
int nanosleep(const struct timespec *req, struct timespec *rem);
#endif /* _TIME_H */
| /******************************************************************************
* Copyright (c) 2004, 2008 IBM Corporation
* All rights reserved.
* This program and the accompanying materials
* are made available under the terms of the BSD License
* which accompanies this distribution, and is available at
* http://www.opensource.org/licenses/bsd-license.php
*
* Contributors:
* IBM Corporation - initial implementation
*****************************************************************************/
#ifndef _TIME_H
#define _TIME_H
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
};
typedef long time_t;
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
struct tm *gmtime_r(const time_t *timep, struct tm *result);
time_t mktime(struct tm *tm);
/* Not implemented by libc but by hosting environment, however
* this is where the prototype is expected
*/
int nanosleep(const struct timespec *req, struct timespec *rem);
#endif /* _TIME_H */
|
Add return type in definition of init_audio_tx function. | #ifndef __AUDIO_TX_H__
#define __AUDIO_TX_H__
#include <stdint.h>
init_audio_tx(const char* outfile, int codec_id,
int sample_rate, int bit_rate, int payload_type);
int put_audio_samples_tx(int16_t* samples, int n_samples);
int finish_audio_tx();
#endif /* __AUDIO_TX_H__ */ | #ifndef __AUDIO_TX_H__
#define __AUDIO_TX_H__
#include <stdint.h>
int init_audio_tx(const char* outfile, int codec_id,
int sample_rate, int bit_rate, int payload_type);
int put_audio_samples_tx(int16_t* samples, int n_samples);
int finish_audio_tx();
#endif /* __AUDIO_TX_H__ */ |
Fix digest oop for C++17. | #pragma once
#include <memory>
#include <string>
#ifdef __cpp_lib_string_view
#include <string_view>
#endif
namespace oop
{
class Digest
{
public:
virtual ~Digest() {}
virtual void update(const void* data, int len) = 0;
#ifdef __cpp_lib_string_view
void update(std::string_view str) { update(str.data(), str.length());
#endif
virtual std::string digest() = 0;
virtual int length() const = 0;
enum Type
{
SHA1 = 1,
SHA256 = 2,
MD5 = 5,
};
static std::unique_ptr<Digest> create(Type t);
protected:
Digest() {}
private:
Digest(const Digest&) = delete;
void operator=(const Digest&) = delete;
};
}
| #pragma once
#include <memory>
#include <string>
#ifdef __cpp_lib_string_view
#include <string_view>
#endif
namespace oop
{
class Digest
{
public:
virtual ~Digest() {}
virtual void update(const void* data, int len) = 0;
#ifdef __cpp_lib_string_view
void update(std::string_view str)
{
update(str.data(), str.length());
}
#endif
virtual std::string digest() = 0;
virtual int length() const = 0;
enum Type
{
SHA1 = 1,
SHA256 = 2,
MD5 = 5,
};
static std::unique_ptr<Digest> create(Type t);
protected:
Digest() {}
private:
Digest(const Digest&) = delete;
void operator=(const Digest&) = delete;
};
}
|
Fix one curly brace placement in test code | // Copyright (c) 2017 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 QUICHE_QUIC_PLATFORM_API_QUIC_TEST_H_
#define QUICHE_QUIC_PLATFORM_API_QUIC_TEST_H_
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
#include "net/quic/platform/impl/quic_test_impl.h"
using QuicFlagSaver = QuicFlagSaverImpl;
// Defines the base classes to be used in QUIC tests.
using QuicTest = QuicTestImpl;
template <class T>
using QuicTestWithParam = QuicTestWithParamImpl<T>;
// Class which needs to be instantiated in tests which use threads.
using ScopedEnvironmentForThreads = ScopedEnvironmentForThreadsImpl;
#define QUIC_TEST_DISABLED_IN_CHROME(name) \
QUIC_TEST_DISABLED_IN_CHROME_IMPL(name)
inline std::string QuicGetTestMemoryCachePath() {
return QuicGetTestMemoryCachePathImpl();
#define EXPECT_QUIC_DEBUG_DEATH(condition, message) \
EXPECT_QUIC_DEBUG_DEATH_IMPL(condition, message)
}
#define QUIC_SLOW_TEST(test) QUIC_SLOW_TEST_IMPL(test)
#endif // QUICHE_QUIC_PLATFORM_API_QUIC_TEST_H_
| // Copyright (c) 2017 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 QUICHE_QUIC_PLATFORM_API_QUIC_TEST_H_
#define QUICHE_QUIC_PLATFORM_API_QUIC_TEST_H_
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
#include "net/quic/platform/impl/quic_test_impl.h"
using QuicFlagSaver = QuicFlagSaverImpl;
// Defines the base classes to be used in QUIC tests.
using QuicTest = QuicTestImpl;
template <class T>
using QuicTestWithParam = QuicTestWithParamImpl<T>;
// Class which needs to be instantiated in tests which use threads.
using ScopedEnvironmentForThreads = ScopedEnvironmentForThreadsImpl;
#define QUIC_TEST_DISABLED_IN_CHROME(name) \
QUIC_TEST_DISABLED_IN_CHROME_IMPL(name)
inline std::string QuicGetTestMemoryCachePath() {
return QuicGetTestMemoryCachePathImpl();
}
#define EXPECT_QUIC_DEBUG_DEATH(condition, message) \
EXPECT_QUIC_DEBUG_DEATH_IMPL(condition, message)
#define QUIC_SLOW_TEST(test) QUIC_SLOW_TEST_IMPL(test)
#endif // QUICHE_QUIC_PLATFORM_API_QUIC_TEST_H_
|
Revert change to rr_wait name | /**
* rr_impl.c
*
* Implementation of functionality specific to round-robin scheduling.
*/
#include "rr_impl.h"
void rr_wake_worker(thread_info_t *info) {
// TODO
}
void rr_wait_for_worker(sched_queue_t *queue) {
// TODO
}
| /**
* rr_impl.c
*
* Implementation of functionality specific to round-robin scheduling.
*/
#include "rr_impl.h"
void rr_wake_worker(thread_info_t *info) {
// TODO
}
void rr_wait(sched_queue_t *queue) {
// TODO
}
|
Fix comment on shouldSkipAuthorization property | /* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// GTLBatchQuery.h
//
#import "GTLQuery.h"
@interface GTLBatchQuery : NSObject <GTLQueryProtocol> {
@private
NSMutableArray *queries_;
NSMutableDictionary *requestIDMap_;
BOOL skipAuthorization_;
}
// Queries included in this batch. Each query should have a unique requestID.
@property (retain) NSArray *queries;
// Clients may set this to NO to disallow authorization. Defaults to YES.
@property (assign) BOOL shouldSkipAuthorization;
+ (id)batchQuery;
+ (id)batchQueryWithQueries:(NSArray *)array;
- (void)addQuery:(GTLQuery *)query;
- (GTLQuery *)queryForRequestID:(NSString *)requestID;
@end
| /* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// GTLBatchQuery.h
//
#import "GTLQuery.h"
@interface GTLBatchQuery : NSObject <GTLQueryProtocol> {
@private
NSMutableArray *queries_;
NSMutableDictionary *requestIDMap_;
BOOL skipAuthorization_;
}
// Queries included in this batch. Each query should have a unique requestID.
@property (retain) NSArray *queries;
// Clients may set this to YES to disallow authorization. Defaults to NO.
@property (assign) BOOL shouldSkipAuthorization;
+ (id)batchQuery;
+ (id)batchQueryWithQueries:(NSArray *)array;
- (void)addQuery:(GTLQuery *)query;
- (GTLQuery *)queryForRequestID:(NSString *)requestID;
@end
|
Remove unneeded static member decls; mark c'tor, d'tor as deleted. | //--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#ifndef CLING_CIFACTORY_H
#define CLING_CIFACTORY_H
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/ADT/StringRef.h"
namespace llvm {
class LLVMContext;
class MemoryBuffer;
}
namespace clang {
class DiagnosticsEngine;
}
namespace cling {
class DeclCollector;
class CIFactory {
public:
// TODO: Add overload that takes file not MemoryBuffer
static clang::CompilerInstance* createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir);
static clang::CompilerInstance* createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir,
DeclCollector* stateCollector);
private:
//---------------------------------------------------------------------
//! Constructor
//---------------------------------------------------------------------
CIFactory() {}
~CIFactory() {}
static void SetClingCustomLangOpts(clang::LangOptions& Opts);
static void SetClingTargetLangOpts(clang::LangOptions& Opts,
const clang::TargetInfo& Target);
};
} // namespace cling
#endif // CLING_CIFACTORY_H
| //--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#ifndef CLING_CIFACTORY_H
#define CLING_CIFACTORY_H
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/ADT/StringRef.h"
namespace llvm {
class LLVMContext;
class MemoryBuffer;
}
namespace clang {
class DiagnosticsEngine;
}
namespace cling {
class DeclCollector;
class CIFactory {
public:
// TODO: Add overload that takes file not MemoryBuffer
static clang::CompilerInstance* createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir);
static clang::CompilerInstance* createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir,
DeclCollector* stateCollector);
private:
//---------------------------------------------------------------------
//! Constructor
//---------------------------------------------------------------------
CIFactory() = delete;
~CIFactory() = delete;
};
} // namespace cling
#endif // CLING_CIFACTORY_H
|
Test mutexEvents based deadlock with failing locks | // PARAM: --set ana.activated[+] deadlock --enable sem.lock.fail
#include <pthread.h>
#include <stdio.h>
int g1, g2;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *t1(void *arg) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2); // DEADLOCK
g1 = g2 + 1;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
return NULL;
}
void *t2(void *arg) {
pthread_mutex_lock(&mutex2);
pthread_mutex_lock(&mutex1); // DEADLOCK
g2 = g1 + 1;
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
return NULL;
}
int main(void) {
pthread_t id1, id2;
int i;
for (i = 0; i < 10000; i++) {
pthread_create(&id1, NULL, t1, NULL);
pthread_create(&id2, NULL, t2, NULL);
pthread_join (id1, NULL);
pthread_join (id2, NULL);
printf("%d: g1 = %d, g2 = %d.\n", i, g1, g2);
}
return 0;
}
| |
Add newline to the end of the umbrella header | #import <Foundation/Foundation.h>
//! Project version number for Expecta.
FOUNDATION_EXPORT double ExpectaVersionNumber;
//! Project version string for Expecta.
FOUNDATION_EXPORT const unsigned char ExpectaVersionString[];
#import <Expecta/ExpectaObject.h>
#import <Expecta/ExpectaSupport.h>
#import <Expecta/EXPMatchers.h>
// Enable shorthand by default
#define expect(...) EXP_expect((__VA_ARGS__))
#define failure(...) EXP_failure((__VA_ARGS__)) | #import <Foundation/Foundation.h>
//! Project version number for Expecta.
FOUNDATION_EXPORT double ExpectaVersionNumber;
//! Project version string for Expecta.
FOUNDATION_EXPORT const unsigned char ExpectaVersionString[];
#import <Expecta/ExpectaObject.h>
#import <Expecta/ExpectaSupport.h>
#import <Expecta/EXPMatchers.h>
// Enable shorthand by default
#define expect(...) EXP_expect((__VA_ARGS__))
#define failure(...) EXP_failure((__VA_ARGS__))
|
Fix order of property attributes | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@end
|
Include the header in the source file |
#include <imageloader.h>
#include "context.h"
#include <stdio.h>
#include <stdarg.h>
void print_to_log(ImgloadContext ctx, ImgloadLogLevel level, const char* format, ...)
{
if (!ctx->log.handler)
{
return;
}
if (level < ctx->log.minLevel)
{
return;
}
char buffer[1024];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer) / sizeof(buffer[0]), format, args);
ctx->log.handler(ctx->log.ud, level, buffer);
va_end(args);
} |
#include <imageloader.h>
#include "log.h"
#include "context.h"
#include <stdio.h>
#include <stdarg.h>
void print_to_log(ImgloadContext ctx, ImgloadLogLevel level, const char* format, ...)
{
if (!ctx->log.handler)
{
return;
}
if (level < ctx->log.minLevel)
{
return;
}
char buffer[1024];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer) / sizeof(buffer[0]), format, args);
ctx->log.handler(ctx->log.ud, level, buffer);
va_end(args);
} |
Add solution for problem 7 | #include <stdio.h>
#include "euler.h"
#define PROBLEM 7
#define ANSWER 104743
int
is_prime(int num)
{
if(num < 2) {
return 0;
} else if(num == 2) {
return 1;
}
for(int y = 2; y < num; y++) {
if(num % y == 0) {
return 0;
}
}
return 1;
}
int
main(int argc, char **argv)
{
int number = 0, found = 0;
do {
number++;
if(is_prime(number)) {
found++;
}
} while(found < 10001);
return check(PROBLEM, ANSWER, number);
}
| |
Make this a proper forwarding header rather than a duplication what's under pagespeed/util/ | /*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: gagansingh@google.com (Gagan Singh)
#ifndef NET_INSTAWEB_UTIL_PUBLIC_RE2_H_
#define NET_INSTAWEB_UTIL_PUBLIC_RE2_H_
#include "net/instaweb/util/public/string_util.h"
#include "third_party/re2/src/re2/re2.h"
using re2::RE2;
// Converts a Google StringPiece into an RE2 StringPiece. These are of course
// the same basic thing but are declared in distinct namespaces and as far as
// C++ type-checking is concerned they are incompatible.
//
// TODO(jmarantz): In the re2 code itself there are no references to
// re2::StringPiece, always just plain StringPiece, so if we can
// arrange to get the right definition #included we should be all set.
// We could somehow rewrite '#include "re2/stringpiece.h"' to
// #include Chromium's stringpiece then everything would just work.
inline re2::StringPiece StringPieceToRe2(StringPiece sp) {
return re2::StringPiece(sp.data(), sp.size());
}
#endif // NET_INSTAWEB_UTIL_PUBLIC_RE2_H_
| /*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: gagansingh@google.com (Gagan Singh)
#ifndef NET_INSTAWEB_UTIL_PUBLIC_RE2_H_
#define NET_INSTAWEB_UTIL_PUBLIC_RE2_H_
// TODO(morlovich): Remove this forwarding header and change all references.
#include "pagespeed/kernel/util/re2.h"
#endif // NET_INSTAWEB_UTIL_PUBLIC_RE2_H_
|
Increase VM_PHYSSEG_MAX, necessary for systems with non-contiguous memory (such as 2E and 3A systems). | /* $OpenBSD: vmparam.h,v 1.3 2011/03/23 16:54:35 pirofti Exp $ */
/* public domain */
#ifndef _MACHINE_VMPARAM_H_
#define _MACHINE_VMPARAM_H_
#define VM_PHYSSEG_MAX 2 /* Max number of physical memory segments */
#define VM_PHYSSEG_STRAT VM_PSTRAT_BIGFIRST
#include <mips64/vmparam.h>
#endif /* _MACHINE_VMPARAM_H_ */
| /* $OpenBSD: vmparam.h,v 1.4 2014/03/27 21:58:13 miod Exp $ */
/* public domain */
#ifndef _MACHINE_VMPARAM_H_
#define _MACHINE_VMPARAM_H_
#define VM_PHYSSEG_MAX 3 /* Max number of physical memory segments */
#define VM_PHYSSEG_STRAT VM_PSTRAT_BIGFIRST
#include <mips64/vmparam.h>
#endif /* _MACHINE_VMPARAM_H_ */
|
Make file utils tests valgrind-kosher | #include "minunit.h"
#include <terror/file_utils.h>
#include <assert.h>
char *test_getlines()
{
bstring str = bfromcstr("one\ntwo\nthree\nfour\nfive\n");
struct bstrList *file = bsplit(str, '\n');
DArray *lines = getlines(file, 2, 4);
mu_assert(DArray_count(lines) == 3, "Wrong number of lines.");
mu_assert(bstrcmp((bstring)DArray_at(lines, 0), bfromcstr("two")) == 0, "First line is wrong.");
mu_assert(bstrcmp((bstring)DArray_at(lines, 1), bfromcstr("three")) == 0, "Second line is wrong.");
mu_assert(bstrcmp((bstring)DArray_at(lines, 2), bfromcstr("four")) == 0, "Third line is wrong.");
return NULL;
}
char *all_tests() {
mu_suite_start();
mu_run_test(test_getlines);
return NULL;
}
RUN_TESTS(all_tests);
| #include "minunit.h"
#include <terror/file_utils.h>
#include <assert.h>
char *test_getlines()
{
bstring str = bfromcstr("one\ntwo\nthree\nfour\nfive\n");
struct bstrList *file = bsplit(str, '\n');
DArray *lines = getlines(file, 2, 4);
bstring two = bfromcstr("two");
bstring three = bfromcstr("three");
bstring four = bfromcstr("four");
mu_assert(DArray_count(lines) == 3, "Wrong number of lines.");
mu_assert(bstrcmp((bstring)DArray_at(lines, 0), two) == 0, "First line is wrong.");
mu_assert(bstrcmp((bstring)DArray_at(lines, 1), three) == 0, "Second line is wrong.");
mu_assert(bstrcmp((bstring)DArray_at(lines, 2), four) == 0, "Third line is wrong.");
bstrListDestroy(file);
bdestroy(str);
bdestroy(two);
bdestroy(three);
bdestroy(four);
DArray_destroy(lines);
return NULL;
}
char *all_tests() {
mu_suite_start();
mu_run_test(test_getlines);
return NULL;
}
RUN_TESTS(all_tests);
|
Add example that gets more precise when the location is not part of the TID | // SKIP PARAM: --set ana.activated[+] apron --set ana.path_sens[+] threadflag --set ana.activated[+] threadJoins --sets ana.apron.privatization mutex-meet-tid --disable ana.thread.include-loc
#include <pthread.h>
#include <assert.h>
int g = 10;
pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER;
void *t_benign(void *arg) {
pthread_mutex_lock(&A);
g = 20;
pthread_mutex_unlock(&A);
return NULL;
}
int main(void) {
int t;
// Force multi-threaded handling
pthread_t id2;
if(t) {
pthread_create(&id2, NULL, t_benign, NULL);
} else {
pthread_create(&id2, NULL, t_benign, NULL);
}
pthread_join(id2, NULL);
pthread_mutex_lock(&A);
g = 12;
pthread_mutex_unlock(&A);
pthread_mutex_lock(&A);
assert(g == 12);
pthread_mutex_unlock(&A);
return 0;
}
| |
Add header for standard instruments. | #include <MozziGuts.h>
#include <Oscil.h>
#include <ADSR.h>
#include <mozzi_midi.h>
#include <tables/sin2048_int8.h>
#define applyGain(v, g) ((v * g) >> 8)
class MalariaInstrument {
public:
MalariaInstrument() {};
virtual void noteOn(byte note, byte velocity);
virtual void noteOff(byte note, byte velocity);
virtual void updateControl();
virtual int updateAudio();
virtual bool isPlaying();
protected:
};
class FMBell : public MalariaInstrument {
public:
FMBell() {
aCarrier.setTable(SIN2048_DATA);
aModulator.setTable(SIN2048_DATA);
aCarrier.setFreq(0);
aModulator.setFreq(0);
modEnv.setIdleLevel(0);
modEnv.setLevels(255, 0, 0, 0);
modEnv.setTimes(20, 2000, 0, 0);
carEnv.setIdleLevel(0);
carEnv.setLevels(255, 0, 0, 0);
carEnv.setTimes(20, 2000, 0, 0);
gate = false;
gain = 0;
}
void noteOn(byte note, byte velocity) {
float fundamentalHz = mtof(float(note));
carrierFreq = float_to_Q16n16(fundamentalHz * 5.f);
modulatorFreq = float_to_Q16n16(fundamentalHz * 7.f);
deviation = (modulatorFreq>>16) * mod_index;
aModulator.setFreq_Q16n16(modulatorFreq);
aCarrier.setFreq_Q16n16(carrierFreq);
modEnv.noteOn();
carEnv.noteOn();
gate = true;
gain = velocity;
}
void noteOff(byte note, byte velocity) {
gate = false;
}
void updateControl() {
modEnv.update();
carEnv.update();
}
int updateAudio() {
if (gate) {
Q15n16 modulation = applyGain(deviation, applyGain(aModulator.next(), modEnv.next()));
return applyGain(applyGain(aCarrier.phMod(modulation), carEnv.next()), gain);
} else {
return 0;
}
}
bool isPlaying() {
return gate;
}
private:
const Q8n8 mod_index = float_to_Q8n8(1.0f);
Oscil<SIN2048_NUM_CELLS, AUDIO_RATE> aCarrier;
Oscil<SIN2048_NUM_CELLS, AUDIO_RATE> aModulator;
ADSR <CONTROL_RATE, AUDIO_RATE> modEnv;
ADSR <CONTROL_RATE, AUDIO_RATE> carEnv;
Q16n16 carrierFreq, modulatorFreq, deviation;
byte gain;
bool gate;
};
| |
Add stdio to this file becasue we use FILE. | // Copyright (c) 2006-2008 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_SCOPED_HANDLE_H_
#define BASE_SCOPED_HANDLE_H_
#include "base/basictypes.h"
#if defined(OS_WIN)
#include "base/scoped_handle_win.h"
#endif
class ScopedStdioHandle {
public:
ScopedStdioHandle()
: handle_(NULL) { }
explicit ScopedStdioHandle(FILE* handle)
: handle_(handle) { }
~ScopedStdioHandle() {
Close();
}
void Close() {
if (handle_) {
fclose(handle_);
handle_ = NULL;
}
}
FILE* get() const { return handle_; }
FILE* Take() {
FILE* temp = handle_;
handle_ = NULL;
return temp;
}
void Set(FILE* newhandle) {
Close();
handle_ = newhandle;
}
private:
FILE* handle_;
DISALLOW_EVIL_CONSTRUCTORS(ScopedStdioHandle);
};
#endif // BASE_SCOPED_HANDLE_H_
| // Copyright (c) 2006-2008 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_SCOPED_HANDLE_H_
#define BASE_SCOPED_HANDLE_H_
#include <stdio.h>
#include "base/basictypes.h"
#if defined(OS_WIN)
#include "base/scoped_handle_win.h"
#endif
class ScopedStdioHandle {
public:
ScopedStdioHandle()
: handle_(NULL) { }
explicit ScopedStdioHandle(FILE* handle)
: handle_(handle) { }
~ScopedStdioHandle() {
Close();
}
void Close() {
if (handle_) {
fclose(handle_);
handle_ = NULL;
}
}
FILE* get() const { return handle_; }
FILE* Take() {
FILE* temp = handle_;
handle_ = NULL;
return temp;
}
void Set(FILE* newhandle) {
Close();
handle_ = newhandle;
}
private:
FILE* handle_;
DISALLOW_EVIL_CONSTRUCTORS(ScopedStdioHandle);
};
#endif // BASE_SCOPED_HANDLE_H_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.