text stringlengths 4 6.14k |
|---|
// StockODBC.h : Haupt-Header-Datei für die Anwendung STOCKODBC
//
#if !defined(AFX_STOCKODBC_H__39EDB6D8_4F0C_11D2_B3BF_006097A8F69A__INCLUDED_)
#define AFX_STOCKODBC_H__39EDB6D8_4F0C_11D2_B3BF_006097A8F69A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // Hauptsymbole
/////////////////////////////////////////////////////////////////////////////
// CStockODBCApp:
// Siehe StockODBC.cpp für die Implementierung dieser Klasse
//
class CStockODBCApp : public CWinApp
{
public:
CStockODBCApp();
// Überladungen
// Vom Klassenassistenten generierte Überladungen virtueller Funktionen
//{{AFX_VIRTUAL(CStockODBCApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementierung
//{{AFX_MSG(CStockODBCApp)
afx_msg void OnAppAbout();
// HINWEIS - An dieser Stelle werden Member-Funktionen vom Klassen-Assistenten eingefügt und entfernt.
// Innerhalb dieser generierten Quelltextabschnitte NICHTS VERÄNDERN!
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ fügt unmittelbar vor der vorhergehenden Zeile zusätzliche Deklarationen ein.
#endif // !defined(AFX_STOCKODBC_H__39EDB6D8_4F0C_11D2_B3BF_006097A8F69A__INCLUDED_)
|
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "auz.h"
#include "clutil.h"
void usage(char *prog)
{
printf("usage: %s <img>\n", prog);
exit(-1);
}
int main(int argc, char **argv)
{
bmat src, dst;
char *ker_file, *img_file;
if (argc != 2)
usage(argv[0]);
ker_file = "./build/gh_kernel.cl";
img_file = argv[1];
src = bmat_read(img_file);
dst = cl_gh(src, ker_file, "gh");
//bmat_print(dst);
bmat_write(dst, "gh2.dat");
dst = cl_gh(src, ker_file, "gh_smem");
//bmat_print(dst);
bmat_write(dst, "gh3.dat"); NL;
bmat_free(dst);
bmat_free(src);
return 0;
}
|
//
// CHZTCell.h
// 吃货美食
//
// Created by eric on 16/5/12.
// Copyright © 2016年 赵天. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "CHCfaxian_list.h"
@interface CHZTCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *tagLanel;
@property (weak, nonatomic) IBOutlet UIImageView *photoImageView;
@property (weak, nonatomic) IBOutlet UILabel *use_nameLabel;
@property(nonatomic,strong)CHCfaxian_list *faxian_list;
-(void)setFaxian_list:(CHCfaxian_list *)faxian_list;
@end
|
//
// MRISecondViewController.h
// marin
//
// Created by 羽田 健太郎 on 2014/03/19.
// Copyright (c) 2014年 羽田 健太郎. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MRISecondViewController : UIViewController
@end
|
/* $Xorg: dsimple.h,v 1.4 2001/02/09 02:05:54 xorgcvs Exp $ */
/*
Copyright 1993, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from The Open Group.
*/
/* $XFree86: xc/programs/xlsfonts/dsimple.h,v 1.8 2002/12/24 17:43:01 tsi Exp $ */
/*
* dsimple.h: This file contains the definitions needed to use the
* functions in dsimple.c. It also declares the global
* variables dpy, screen, and program_name which are needed to
* use dsimple.c.
*
* Written by Mark Lillibridge. Last updated 7/1/87
*
* Send bugs, etc. to chariot@athena.mit.edu.
*/
/* Simple helper macros */
#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif /* MAX */
#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif /* MIN */
/* Global variables used by routines in just_display.c */
extern char *program_name; /* Name of this program */
extern Display *dpy; /* The current display */
extern int screen; /* The current screen */
#define INIT_NAME program_name=argv[0] /* use this in main to setup
program_name */
/* Declarations for functions in dsimple.c */
char *Malloc(unsigned);
char *Realloc(char *, int);
void Setup_Display_And_Screen(int *, char **);
void Close_Display(void);
void usage(void);
#define X_USAGE "[host:display]" /* X arguments handled by
Get_Display_Name */
#ifdef __GNUC__
void Fatal_Error(char *, ...) __attribute__((__noreturn__));
#else
void Fatal_Error(char *, ...);
#endif
|
//
// M3U8SegmentInfo.h
// M3U8Kit
//
// Created by Oneday on 13-1-11.
// Copyright (c) 2013年 0day. All rights reserved.
//
#import <Foundation/Foundation.h>
/*!
@class M3U8SegmentInfo
@abstract This is the class indicates #EXTINF:<duration>,<title> + media in m3u8 file
@format #EXTINF:<duration>,<title>
#define M3U8_EXTINF @"#EXTINF:"
#define M3U8_EXTINF_DURATION @"DURATION"
#define M3U8_EXTINF_TITLE @"TITLE"
#define M3U8_EXTINF_URI @"URI"
*/
@interface M3U8SegmentInfo : NSObject
@property (readonly, nonatomic) NSTimeInterval duration;
@property (readonly, nonatomic) NSTimeInterval startTime;
@property (readonly, nonatomic) NSUInteger number;
@property (readonly, nonatomic) NSString *URI;
@property (readonly, nonatomic) NSString *mediaPlayListURL;
- (instancetype)initWithDictionary:(NSDictionary *)dictionary andStartTime:(NSTimeInterval)startTime withNumber:(NSUInteger)number mediaPlayList:(NSString*)plUrl;
- (NSString *)mediaURL;
@end
|
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.String
struct String_t;
// System.Type
struct Type_t;
// System.Object
struct Il2CppObject;
// System.Security.IPermission
struct IPermission_t1411806254;
// System.Reflection.MethodInfo
struct MethodInfo_t;
// System.Security.Policy.Evidence
struct Evidence_t4141397151;
#include "mscorlib_System_SystemException4206535862.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.SecurityException
struct SecurityException_t3044716869 : public SystemException_t4206535862
{
public:
// System.String System.Security.SecurityException::permissionState
String_t* ___permissionState_11;
// System.Type System.Security.SecurityException::permissionType
Type_t * ___permissionType_12;
// System.String System.Security.SecurityException::_granted
String_t* ____granted_13;
// System.String System.Security.SecurityException::_refused
String_t* ____refused_14;
// System.Object System.Security.SecurityException::_demanded
Il2CppObject * ____demanded_15;
// System.Security.IPermission System.Security.SecurityException::_firstperm
Il2CppObject * ____firstperm_16;
// System.Reflection.MethodInfo System.Security.SecurityException::_method
MethodInfo_t * ____method_17;
// System.Security.Policy.Evidence System.Security.SecurityException::_evidence
Evidence_t4141397151 * ____evidence_18;
public:
inline static int32_t get_offset_of_permissionState_11() { return static_cast<int32_t>(offsetof(SecurityException_t3044716869, ___permissionState_11)); }
inline String_t* get_permissionState_11() const { return ___permissionState_11; }
inline String_t** get_address_of_permissionState_11() { return &___permissionState_11; }
inline void set_permissionState_11(String_t* value)
{
___permissionState_11 = value;
Il2CppCodeGenWriteBarrier(&___permissionState_11, value);
}
inline static int32_t get_offset_of_permissionType_12() { return static_cast<int32_t>(offsetof(SecurityException_t3044716869, ___permissionType_12)); }
inline Type_t * get_permissionType_12() const { return ___permissionType_12; }
inline Type_t ** get_address_of_permissionType_12() { return &___permissionType_12; }
inline void set_permissionType_12(Type_t * value)
{
___permissionType_12 = value;
Il2CppCodeGenWriteBarrier(&___permissionType_12, value);
}
inline static int32_t get_offset_of__granted_13() { return static_cast<int32_t>(offsetof(SecurityException_t3044716869, ____granted_13)); }
inline String_t* get__granted_13() const { return ____granted_13; }
inline String_t** get_address_of__granted_13() { return &____granted_13; }
inline void set__granted_13(String_t* value)
{
____granted_13 = value;
Il2CppCodeGenWriteBarrier(&____granted_13, value);
}
inline static int32_t get_offset_of__refused_14() { return static_cast<int32_t>(offsetof(SecurityException_t3044716869, ____refused_14)); }
inline String_t* get__refused_14() const { return ____refused_14; }
inline String_t** get_address_of__refused_14() { return &____refused_14; }
inline void set__refused_14(String_t* value)
{
____refused_14 = value;
Il2CppCodeGenWriteBarrier(&____refused_14, value);
}
inline static int32_t get_offset_of__demanded_15() { return static_cast<int32_t>(offsetof(SecurityException_t3044716869, ____demanded_15)); }
inline Il2CppObject * get__demanded_15() const { return ____demanded_15; }
inline Il2CppObject ** get_address_of__demanded_15() { return &____demanded_15; }
inline void set__demanded_15(Il2CppObject * value)
{
____demanded_15 = value;
Il2CppCodeGenWriteBarrier(&____demanded_15, value);
}
inline static int32_t get_offset_of__firstperm_16() { return static_cast<int32_t>(offsetof(SecurityException_t3044716869, ____firstperm_16)); }
inline Il2CppObject * get__firstperm_16() const { return ____firstperm_16; }
inline Il2CppObject ** get_address_of__firstperm_16() { return &____firstperm_16; }
inline void set__firstperm_16(Il2CppObject * value)
{
____firstperm_16 = value;
Il2CppCodeGenWriteBarrier(&____firstperm_16, value);
}
inline static int32_t get_offset_of__method_17() { return static_cast<int32_t>(offsetof(SecurityException_t3044716869, ____method_17)); }
inline MethodInfo_t * get__method_17() const { return ____method_17; }
inline MethodInfo_t ** get_address_of__method_17() { return &____method_17; }
inline void set__method_17(MethodInfo_t * value)
{
____method_17 = value;
Il2CppCodeGenWriteBarrier(&____method_17, value);
}
inline static int32_t get_offset_of__evidence_18() { return static_cast<int32_t>(offsetof(SecurityException_t3044716869, ____evidence_18)); }
inline Evidence_t4141397151 * get__evidence_18() const { return ____evidence_18; }
inline Evidence_t4141397151 ** get_address_of__evidence_18() { return &____evidence_18; }
inline void set__evidence_18(Evidence_t4141397151 * value)
{
____evidence_18 = value;
Il2CppCodeGenWriteBarrier(&____evidence_18, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
// UIImage+Resize.h
// Created by Trevor Harmon on 8/5/09.
// Free for personal or commercial use, with or without modification.
// No warranty is expressed or implied.
// NOTE: FridayLunch modified to convert from Category to
// new Class name since iPhone seems to have some issues with Categories
// of built in Classes
@interface UIImageResize : NSObject
{
}
+ (UIImage *)croppedImage:(CGRect)bounds image:(UIImage*)image;
+ (UIImage *)thumbnailImage:(NSInteger)thumbnailSize
transparentBorder:(NSUInteger)borderSize
cornerRadius:(NSUInteger)cornerRadius
interpolationQuality:(CGInterpolationQuality)quality
image:(UIImage*)image;
+ (UIImage *)resizedImage:(CGSize)newSize
interpolationQuality:(CGInterpolationQuality)quality
image:(UIImage*)image
hires:(BOOL)hires;
+ (UIImage *)resizedImageWithContentMode:(UIViewContentMode)contentMode
bounds:(CGSize)bounds
interpolationQuality:(CGInterpolationQuality)quality
image:(UIImage*)image;
@end
|
//
// LoLStaticData.h
// LoLAPI
//
// Created by Troy Stump on 4/29/14.
//
//
#import "LoLStaticChampionList.h"
#import "LoLStaticChampion.h"
#import "LoLStaticChampionSpell.h"
#import "LoLStaticImage.h"
#import "LoLStaticInfo.h"
#import "LoLStaticPassive.h"
#import "LoLStaticRecommended.h"
#import "LoLStaticSkin.h"
#import "LoLStaticStats.h"
#import "LoLStaticLevelTip.h"
#import "LoLStaticSpellVariables.h"
#import "LoLStaticBlock.h"
#import "LoLStaticBlockItem.h"
#import "LoLStaticItemList.h"
#import "LoLStaticBasicData.h"
#import "LoLStaticGroup.h"
#import "LoLStaticItem.h"
#import "LoLStaticItemTree.h"
#import "LoLStaticBasicDataStats.h"
#import "LoLStaticGold.h"
#import "LoLStaticMetaData.h"
#import "LoLStaticMasteryList.h"
#import "LoLStaticMastery.h"
#import "LoLStaticMasteryTree.h"
#import "LoLStaticMasteryTreeList.h"
#import "LoLStaticMasteryTreeItem.h"
#import "LoLStaticRealm.h"
#import "LoLStaticRuneList.h"
#import "LoLStaticRune.h"
#import "LoLStaticSummonerSpellList.h"
#import "LoLStaticSummonerSpell.h"
#import "LoLStaticDataAPI.h" |
/*
* SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "soc/lcd_periph.h"
#include "soc/gpio_sig_map.h"
const lcd_signal_conn_t lcd_periph_signals = {
.buses = {
[0] = {
.module = PERIPH_I2S0_MODULE,
.irq_id = ETS_I2S0_INTR_SOURCE,
.data_sigs = {
I2S0O_DATA_OUT0_IDX,
I2S0O_DATA_OUT1_IDX,
I2S0O_DATA_OUT2_IDX,
I2S0O_DATA_OUT3_IDX,
I2S0O_DATA_OUT4_IDX,
I2S0O_DATA_OUT5_IDX,
I2S0O_DATA_OUT6_IDX,
I2S0O_DATA_OUT7_IDX,
I2S0O_DATA_OUT8_IDX,
I2S0O_DATA_OUT9_IDX,
I2S0O_DATA_OUT10_IDX,
I2S0O_DATA_OUT11_IDX,
I2S0O_DATA_OUT12_IDX,
I2S0O_DATA_OUT13_IDX,
I2S0O_DATA_OUT14_IDX,
I2S0O_DATA_OUT15_IDX,
I2S0O_DATA_OUT16_IDX,
I2S0O_DATA_OUT17_IDX,
I2S0O_DATA_OUT18_IDX,
I2S0O_DATA_OUT19_IDX,
I2S0O_DATA_OUT20_IDX,
I2S0O_DATA_OUT21_IDX,
I2S0O_DATA_OUT22_IDX,
I2S0O_DATA_OUT23_IDX,
},
.wr_sig = I2S0O_WS_OUT_IDX,
}
}
};
|
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Eotvos Lorand University, Budapest, Hungary
#pragma once
#include <rte_atomic.h>
#include "stateful_memory_type.h"
//=============================================================================
// Registers
typedef struct {
volatile int8_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} register_int8_t;
typedef struct {
volatile int16_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} register_int16_t;
typedef struct {
volatile int32_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} register_int32_t;
typedef struct {
volatile int64_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} register_int64_t;
typedef struct {
volatile uint8_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} register_uint8_t;
typedef struct {
volatile uint16_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} register_uint16_t;
typedef struct {
volatile uint32_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} register_uint32_t;
typedef struct {
volatile uint64_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} register_uint64_t;
//=============================================================================
// Counters
typedef struct {
rte_atomic32_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} SMEMTYPE(direct_meter_uint32);
typedef struct {
rte_atomic32_t value;
#ifdef T4P4S_DEBUG
char name[256];
#endif
} SMEMTYPE(direct_meter_uint8);
//=============================================================================
// Locking
typedef rte_spinlock_t lock_t;
#define LOCK(lock) rte_spinlock_lock(lock);
#define UNLOCK(lock) rte_spinlock_unlock(lock);
|
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* FreeRDP Proxy Server
*
* Copyright 2019 Mati Shabtay <matishabtay@gmail.com>
* Copyright 2019 Kobi Mizrachi <kmizrachi18@gmail.com>
* Copyright 2019 Idan Freiberg <speidy@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "pf_server.h"
#include "pf_config.h"
#include "pf_log.h"
#include "pf_modules.h"
#include <freerdp/build-config.h>
#include <winpr/collections.h>
#include <stdlib.h>
#include <signal.h>
#define TAG PROXY_TAG("server")
static proxyServer* server = NULL;
static void cleanup_handler(int signum)
{
printf("\n");
WLog_INFO(TAG, "[%s]: caught signal %d, starting cleanup...", __FUNCTION__, signum);
WLog_INFO(TAG, "stopping all connections.");
pf_server_stop(server);
WLog_INFO(TAG, "freeing loaded modules and plugins.");
pf_modules_free();
pf_server_config_free(server->config);
pf_server_free(server);
WLog_INFO(TAG, "exiting.");
exit(0);
}
static void pf_server_register_signal_handlers(void)
{
signal(SIGINT, cleanup_handler);
signal(SIGTERM, cleanup_handler);
#ifndef _WIN32
signal(SIGQUIT, cleanup_handler);
signal(SIGKILL, cleanup_handler);
#endif
}
static BOOL is_all_required_modules_loaded(proxyConfig* config)
{
size_t i;
for (i = 0; i < config->RequiredPluginsCount; i++)
{
const char* plugin_name = config->RequiredPlugins[i];
if (!pf_modules_is_plugin_loaded(plugin_name))
{
WLog_ERR(TAG, "Required plugin '%s' is not loaded. stopping.", plugin_name);
return FALSE;
}
}
return TRUE;
}
int main(int argc, char* argv[])
{
proxyConfig* config = NULL;
const char* config_path = "config.ini";
int status = -1;
pf_server_register_signal_handlers();
config = pf_server_config_load(config_path);
if (!config)
goto fail;
pf_server_config_print(config);
if (!pf_modules_init(FREERDP_PROXY_PLUGINDIR, (const char**)config->Modules,
config->ModulesCount))
{
WLog_ERR(TAG, "failed to initialize proxy modules!");
goto fail;
}
pf_modules_list_loaded_plugins();
if (!is_all_required_modules_loaded(config))
goto fail;
server = pf_server_new(config);
if (!server)
goto fail;
if (!pf_server_start(server))
goto fail;
if (WaitForSingleObject(server->thread, INFINITE) != WAIT_OBJECT_0)
goto fail;
status = 0;
fail:
pf_server_free(server);
pf_modules_free();
pf_server_config_free(config);
return status;
}
|
/*
* Copyright (C) 2016 Texas Instruments Incorporated
*
* All rights reserved. Property of Texas Instruments Incorporated.
* Restricted rights to use, duplicate or disclose this code are
* granted through contract.
*
* The program may not be used without the written permission of
* Texas Instruments Incorporated or against the terms and conditions
* stipulated in the agreement under which this program has been supplied,
* and under no circumstances can it be used with non-TI connectivity device.
*
*/
#ifndef EVENTREG_H_
#define EVENTREG_H_
#ifdef __cplusplus
extern "C"
{
#endif
/*!
\defgroup event_registration
\short Allows user to register event handlers dynamically.
*/
/*!
\addtogroup event_registration
@{
*/
typedef enum
{
SL_EVENT_HDL_FATAL_ERROR,
SL_EVENT_HDL_DEVICE_GENERAL,
SL_EVENT_HDL_WLAN,
SL_EVENT_HDL_NETAPP,
SL_EVENT_HDL_SOCKET,
SL_EVENT_HDL_HTTP_SERVER,
SL_EVENT_HDL_NETAPP_REQUEST,
SL_EVENT_HDL_MEM_FREE,
SL_EVENT_HDL_SOCKET_TRIGGER,
SL_NUM_OF_EVENT_TYPES
}SlEventHandler_e;
typedef struct SlEventsListNode_s
{
void *event;
struct SlEventsListNode_s *next;
}SlEventsListNode_t;
#ifdef SL_RUNTIME_EVENT_REGISTERATION
/*!
\brief register events in runtime
this api enables registration of the SimpleLink host driver in runtime.
\param[in] EventHandlerType event type - SlEventHandler_e - to register
\param[in] EventHandler pointer to the event handler
\return 0 on success, error otherwise
\sa sl_RegisterEventHandler
\note registration of event with NULL, clears any registered event.
*/
_i32 sl_RegisterEventHandler(SlEventHandler_e EventHandlerType , void* EventHandler);
_i32 _SlIsEventRegistered(SlEventHandler_e EventHandlerType);
/******************************************************************************
sl_RegisterLibsEventHandler
\brief this function registers event handlers from external libraries in runtime.
the allocation and memory maintenance of the SlEventsListNode_t is on the library
Responsibility.
RETURNS: success or error code.
******************************************************************************/
_i32 sl_RegisterLibsEventHandler(SlEventHandler_e EventHandlerType , SlEventsListNode_t* EventHandlerNode);
/******************************************************************************
sl_UnregisterLibsEventHandler
DESCRIPTION:
this function unregisters event handlers from external libraries in runtime.
the SlEventsListNode_t that was used for registration, must be used to unregister that event handler.
the allocation and memory maintenance of the SlEventsListNode_t is on the library
Responsibility.
RETURNS: success or error code.
******************************************************************************/
_i32 sl_UnregisterLibsEventHandler(SlEventHandler_e EventHandlerType , SlEventsListNode_t* EventHandlerNode);
/*!
Close the Doxygen group.
@}
*/
void _SlDeviceFatalErrorEvtHdlr(SlDeviceFatal_t *pSlFatalErrorEvent);
void _SlDeviceGeneralEvtHdlr(SlDeviceEvent_t *pSlDeviceEvent);
void _SlWlanEvtHdlr(SlWlanEvent_t* pSlWlanEvent);
void _SlNetAppEvtHdlr(SlNetAppEvent_t* pSlNetAppEvent);
void _SlSockEvtHdlr(SlSockEvent_t* pSlSockEvent);
void _SlNetAppHttpServerHdlr(SlNetAppHttpServerEvent_t *pSlHttpServerEvent, SlNetAppHttpServerResponse_t *pSlHttpServerResponse);
void _SlNetAppRequestHdlr(SlNetAppRequest_t *pNetAppRequest, SlNetAppResponse_t *pNetAppResponse);
void _SlNetAppRequestMemFree (_u8 *buffer);
void _SlSocketTriggerEventHandler(SlSockTriggerEvent_t* pSlSockTriggerEvent);
#endif /* SL_RUNTIME_EVENT_REGISTERATION */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* EVENTREG_H_ */
|
/*
* Copyright 2015 Facebook, 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.
*/
#pragma once
#include <folly/io/async/AsyncTransport.h>
#include <folly/io/async/EventHandler.h>
#include <folly/io/async/DelayedDestruction.h>
#include <folly/io/IOBufQueue.h>
#include <list>
#include <system_error>
namespace folly {
class AsyncSocketException;
/**
* Read from a pipe in an async manner.
*/
class AsyncPipeReader : public EventHandler,
public AsyncReader,
public DelayedDestruction {
public:
typedef std::unique_ptr<AsyncPipeReader,
folly::DelayedDestruction::Destructor> UniquePtr;
AsyncPipeReader(folly::EventBase* eventBase, int pipeFd)
: EventHandler(eventBase, pipeFd),
fd_(pipeFd) {}
/**
* Set the read callback and automatically install/uninstall the handler
* for events.
*/
void setReadCB(AsyncReader::ReadCallback* callback) override {
if (callback == readCallback_) {
return;
}
readCallback_ = callback;
if (readCallback_ && !isHandlerRegistered()) {
registerHandler(EventHandler::READ | EventHandler::PERSIST);
} else if (!readCallback_ && isHandlerRegistered()) {
unregisterHandler();
}
}
/**
* Get the read callback
*/
AsyncReader::ReadCallback* getReadCallback() const override {
return readCallback_;
}
/**
* Set a special hook to close the socket (otherwise, will call close())
*/
void setCloseCallback(std::function<void(int)> closeCb) {
closeCb_ = closeCb;
}
private:
~AsyncPipeReader();
void handlerReady(uint16_t events) noexcept override;
void failRead(const AsyncSocketException& ex);
void close();
int fd_;
AsyncReader::ReadCallback* readCallback_{nullptr};
std::function<void(int)> closeCb_;
};
/**
* Write to a pipe in an async manner.
*/
class AsyncPipeWriter : public EventHandler,
public AsyncWriter,
public DelayedDestruction {
public:
typedef std::unique_ptr<AsyncPipeWriter,
folly::DelayedDestruction::Destructor> UniquePtr;
AsyncPipeWriter(folly::EventBase* eventBase, int pipeFd)
: EventHandler(eventBase, pipeFd),
fd_(pipeFd) {}
/**
* Asynchronously write the given iobuf to this pipe, and invoke the callback
* on success/error.
*/
void write(std::unique_ptr<folly::IOBuf> iob,
AsyncWriter::WriteCallback* wcb = nullptr);
/**
* Set a special hook to close the socket (otherwise, will call close())
*/
void setCloseCallback(std::function<void(int)> closeCb) {
closeCb_ = closeCb;
}
/**
* Returns true if the pipe is closed
*/
bool closed() const {
return (fd_ < 0 || closeOnEmpty_);
}
/**
* Notify the pipe to close as soon as all pending writes complete
*/
void closeOnEmpty();
/**
* Close the pipe immediately, and fail all pending writes
*/
void closeNow();
/**
* Return true if there are currently writes pending (eg: the pipe is blocked
* for writing)
*/
bool hasPendingWrites() const {
return !queue_.empty();
}
// AsyncWriter methods
void write(folly::AsyncWriter::WriteCallback* callback, const void* buf,
size_t bytes, WriteFlags flags = WriteFlags::NONE) override {
writeChain(callback, IOBuf::wrapBuffer(buf, bytes), flags);
}
void writev(folly::AsyncWriter::WriteCallback*, const iovec*,
size_t, WriteFlags = WriteFlags::NONE) override {
throw std::runtime_error("writev is not supported. Please use writeChain.");
}
void writeChain(folly::AsyncWriter::WriteCallback* callback,
std::unique_ptr<folly::IOBuf>&& buf,
WriteFlags flags = WriteFlags::NONE) override;
private:
void handlerReady(uint16_t events) noexcept override;
void handleWrite();
void failAllWrites(const AsyncSocketException& ex);
int fd_;
std::list<std::pair<folly::IOBufQueue, AsyncWriter::WriteCallback*>> queue_;
bool closeOnEmpty_{false};
std::function<void(int)> closeCb_;
~AsyncPipeWriter() {
closeNow();
}
};
} // folly
|
#ifndef ANIMATION_H
#define ANIMATION_H
#include <SFML/Graphics.hpp>
using namespace sf;
/*
* A single sprite animation (such as walk south, attack north, etc.)
*/
class Animation {
public:
Sprite sprite;
Animation();
Animation(Texture *t, float x, float y, int w, int h, int frameCount, float speed, bool r);
void setRotation(float angle);
void rotate(float angle);
void setScale(float xScale, float yScale);
void setColor(Color color);
void setOrigin(float x, float y);
void moveOrigin(float x, float y);
void updatePosition(float x, float y);
void beginUpdate();
void endUpdate();
void restart();
bool isLastFrame();
private:
bool repeat;
float currentFrame, animationSpeed;
int frameSize;
std::vector<IntRect> frames;
};
#endif
|
// Copyright 2010-2014, Google Inc.
// 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.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef MOZC_GUI_SET_DEFAULT_DIALOG_SET_DEFAULT_DIALOG_H_
#define MOZC_GUI_SET_DEFAULT_DIALOG_SET_DEFAULT_DIALOG_H_
#include "gui/set_default_dialog/ui_set_default_dialog.h"
namespace mozc {
namespace gui {
// out-proc set default dialog.
class SetDefaultDialog : public QDialog,
private Ui::SetDefaultDialog {
Q_OBJECT;
public:
SetDefaultDialog();
virtual ~SetDefaultDialog();
protected slots:
virtual void accept();
virtual void reject();
private:
bool SetCheckDefault(bool check_default);
};
} // namespace mozc::gui
} // namespace mozc
#endif // MOZC_GUI_SET_DEFAULT_DIALOG_SET_DEFAULT_DIALOG_H_
|
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OR_TOOLS_GLOP_STATUS_H_
#define OR_TOOLS_GLOP_STATUS_H_
#include <string>
#include "absl/base/port.h"
namespace operations_research {
namespace glop {
// Return type for the solver functions that return "Did that work?".
// It should only be used for unrecoverable errors.
class Status {
public:
// Possible kinds of errors.
enum ErrorCode {
// Not an error. Returned on success.
GLOP_OK = 0,
// The LU factorization of the current basis couldn't be computed.
ERROR_LU = 1,
// The current variable values are out of their bound modulo the tolerance.
ERROR_BOUND = 2,
// A pointer argument was NULL when it shouldn't be.
ERROR_NULL = 3,
// The linear program is invalid or it does not have the required format.
ERROR_INVALID_PROBLEM = 4,
};
// Creates a "successful" status.
Status();
// Creates a status with the specified error code and error message.
// If "code == 0", error_message is ignored and a Status object identical
// to Status::OK is constructed.
Status(ErrorCode error_code, std::string error_message);
// Improves readability but identical to 0-arg constructor.
static const Status OK() { return Status(); }
// Accessors.
ErrorCode error_code() const { return error_code_; }
const std::string& error_message() const { return error_message_; }
bool ok() const { return error_code_ == GLOP_OK; }
private:
ErrorCode error_code_;
std::string error_message_;
};
// Returns the string representation of the ErrorCode enum.
std::string GetErrorCodeString(Status::ErrorCode error_code);
// Macro to simplify error propagation between function returning Status.
#define GLOP_RETURN_IF_ERROR(function_call) \
do { \
Status return_status = function_call; \
if (!return_status.ok()) return return_status; \
} while (false)
// Macro to simplify the creation of an error.
#define GLOP_RETURN_AND_LOG_ERROR(error_code, message) \
do { \
std::string error_message = message; \
LOG(ERROR) << GetErrorCodeString(error_code) << ": " << error_message; \
return Status(error_code, error_message); \
} while (false)
// Macro to check that a pointer argument is not null.
#define GLOP_RETURN_ERROR_IF_NULL(arg) \
if (arg == nullptr) { \
const std::string variable_name = #arg; \
std::string error_message = variable_name + " must not be null."; \
LOG(DFATAL) << error_message; \
return Status(Status::ERROR_NULL, error_message); \
}
} // namespace glop
} // namespace operations_research
#endif // OR_TOOLS_GLOP_STATUS_H_
|
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Attribute2523058482.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Diagnostics.DebuggerHiddenAttribute
struct DebuggerHiddenAttribute_t83365455 : public Attribute_t2523058482
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
#ifndef __FBTOOL_H_
#define __FBTOOL_H_
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <stddef.h>
#include <string.h>
#include <sys/mman.h>
#include <math.h>
#include <stdint.h>
#include "page.h"
typedef struct fbdev{
int fb; //framebuffer打开后的唯一标识符
struct fb_fix_screeninfo fb_fix;
struct fb_var_screeninfo fb_var;
/* 新增 */
unsigned long fb_mem_offset; //frame buffer所占内存的偏移量
unsigned long fb_mem; //frame buffer的映射到进程内存空间的起始地址
char dev[20];
}FBDEV,*PFBDEV;
typedef struct point{
int x;
int y;
int z;
}POINT,*PPOINT;
//打开framebuffer
int fb_open(PFBDEV pFbdev);
//关闭framebuffer
int fb_close(PFBDEV pFbdev);
//打印frame buffer 所占内存的开始地址
void pmem_start(PFBDEV pFbdev);
//打印FB_TYPE
void p_type(PFBDEV pFbdev);
//打印可见清晰度
void p_visible_res(PFBDEV pFbdev);
//打印虚拟分辨率
void p_virt_res(PFBDEV pFbdev);
//打印虚拟到可见的偏移量
void p_offset(PFBDEV pFbdev);
//打印每个像素的位数
void p_bpp(PFBDEV pFbdev);
//打印R,G,B和透明度
void p_rgbt(PFBDEV pFbdev);
//打印在内存中的高度和宽度
void p_hw(PFBDEV pFbdev);
//清空控制台
void clear_con(void *addr,int n,size_t len);
//映射到内存
void fb_memcpy(void *addr,void *color,size_t len);
//画点
void draw_dot(PFBDEV pFbdev,POINT p,uint8_t r,uint8_t g,uint8_t b);
//画横线
void draw_h_line(PFBDEV pFbdev,POINT minX,POINT maxX,uint8_t r,uint8_t g,uint8_t b);
//画竖线
void draw_v_line(PFBDEV pFbdev,POINT minY,POINT maxY,uint8_t r,uint8_t g,uint8_t b);
//画一个矩形框
void draw_rec(PFBDEV pFbdev,POINT lu,POINT ld,POINT ru,POINT rd,uint8_t r,uint8_t g,uint8_t b);
//填充一个矩形框
void fill_rec(PFBDEV pFbdev,POINT lu,POINT ld,POINT ru,POINT rd,uint8_t r,uint8_t g,uint8_t b);
#endif
|
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <Foundation/Foundation.h>
#import "AIStreamBufferDelegate.h"
@interface AIStreamBuffer : NSObject
- (instancetype)init __unavailable;
- (instancetype)initWithOutputStream:(NSOutputStream *)outputStream;
@property(nonatomic, weak) id <AIStreamBufferDelegate> delegate;
- (void)open;
- (void)write:(NSData *)data;
- (void)close;
- (void)flushAndClose;
@end
|
/**
* reproject.h
* Authors: Yizhao Gao <ygao29@illinois.edu>
* Date: {10/13/2017}
*/
#ifndef REPROH
#define REPROH
/**
* NAME: nearestNeighborBlockIndex
* DESCRIPTION: Find the nearest neighboring source cell's ID for each target cell using a irregular block indexing, faster but with higher memory requirement
* PARAMETERS:
* double ** psouLat: the pointer to the array of latitudes of source cells (the data are changed during in the function, so please do the output before this function)
* double ** psouLon: the pointer to the array of longitudes of source cells (the data are changed during in the function, so please do the output before this function)
* int nSou: the number of source cells
* double * tarLat: the latitudes of target cells
* double * tarLon: the longitudes of target cells
* int * tarNNSouID: the output IDs of nearest neighboring source cells
* double * tarNNDis the output nearest distance for each target cell (input NULL if you don't need this field)
* int nTar: the number of target cells
* double maxR: the maximum distance (in meters) to define neighboring cells
* Output:
* int * tarNNSouID: the output IDs of nearest neighboring source cells
* double * tarNNDis the output nearest distance for each target cell (input NULL if you don't need this field)
*/
void nearestNeighborBlockIndex(double ** psouLat, double ** psouLon, int nSou, double * tarLat, double * tarLon, int * tarNNSouID, double * tarNNDis, int nTar, double maxR);
/**
* NAME: nearestNeighbor
* DESCRIPTION: Find the nearest neighboring source cell's ID for each target cell, original method, only index based on longtitude
* PARAMETERS:
* double ** psouLat: the pointer to the array of latitudes of source cells (the data are changed during in the function, so please do the output before this function)
* double ** psouLon: the pointer to the array of longitudes of source cells (the data are changed during in the function, so please do the output before this function)
* int nSou: the number of source cells
* double * tarLat: the latitudes of target cells
* double * tarLon: the longitudes of target cells
* int * tarNNSouID: the output IDs of nearest neighboring source cells
* double * tarNNDis the output nearest distance for each target cell (input NULL if you don't need this field)
* int nTar: the number of target cells
* double maxR: the maximum distance (in meters) to define neighboring cells
* Output:
* int * tarNNSouID: the output IDs of nearest neighboring source cells
* double * tarNNDis the output nearest distance for each target cell (input NULL if you don't need this field)
*/
void nearestNeighbor(double ** psouLat, double ** psouLon, int nSou, double * tarLat, double * tarLon, int * tarNNSouID, double * tarNNDis, int nTar, double maxR);
/**
* NAME: nnInterpolate
* DESCRIPTION: Nearest neighbor interpolation
* PARAMETERS:
* double * souVal: the input values at source cells
* double * tarVal: the output values at target cells
* int * tarNNSouID: the IDs of nearest neighboring source cells for each target cells (generated from "nearestNeighbor")
* int nTar: the number of target cells
* Output:
* double * tarVal: the output values at target cells
*/
void nnInterpolate(double * souVal, double * tarVal, int * tarNNSouID, int nTar);
/**
* NAME: summaryInterpolate
* DESCRIPTION: Interpolation (summary) from fine resolution to coarse resolution
* PARAMETERS:
* double * souVal: the input values at source cells
* int * souNNTarID: the IDs of nearest neighboring target cells for each source cells (generated from "nearestNeighbor")
* int nSou: the number of source cells
* double * tarVal: the output values at target cells
* int * nSouPixels: the output numbers of contributing source cells to each target cell
* int nTar: the number of target cells
* Output:
* double * tarVal: the output values at target cells
* int * nSouPixels: the output numbers of contributing source cells to each target cell
*/
void summaryInterpolate(double * souVal, int * souNNTarID, int nSou, double * tarVal, int * nSouPixels, int nTar);
#endif
|
/*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#include <math.h>
#include "av1/common/common.h"
#include "av1/common/entropymode.h"
#include "av1/encoder/cost.h"
#include "av1/encoder/encodemv.h"
#include "aom_dsp/aom_dsp_common.h"
static void encode_mv_component(aom_writer *w, int comp, nmv_component *mvcomp,
MvSubpelPrecision precision) {
int offset;
const int sign = comp < 0;
const int mag = sign ? -comp : comp;
const int mv_class = av1_get_mv_class(mag - 1, &offset);
const int d = offset >> 3; // int mv data
const int fr = (offset >> 1) & 3; // fractional mv data
const int hp = offset & 1; // high precision mv data
assert(comp != 0);
// Sign
aom_write_symbol(w, sign, mvcomp->sign_cdf, 2);
// Class
aom_write_symbol(w, mv_class, mvcomp->classes_cdf, MV_CLASSES);
// Integer bits
if (mv_class == MV_CLASS_0) {
aom_write_symbol(w, d, mvcomp->class0_cdf, CLASS0_SIZE);
} else {
int i;
const int n = mv_class + CLASS0_BITS - 1; // number of bits
for (i = 0; i < n; ++i)
aom_write_symbol(w, (d >> i) & 1, mvcomp->bits_cdf[i], 2);
}
// Fractional bits
if (precision > MV_SUBPEL_NONE) {
aom_write_symbol(
w, fr,
mv_class == MV_CLASS_0 ? mvcomp->class0_fp_cdf[d] : mvcomp->fp_cdf,
MV_FP_SIZE);
}
// High precision bit
if (precision > MV_SUBPEL_LOW_PRECISION)
aom_write_symbol(
w, hp, mv_class == MV_CLASS_0 ? mvcomp->class0_hp_cdf : mvcomp->hp_cdf,
2);
}
static void build_nmv_component_cost_table(int *mvcost,
const nmv_component *const mvcomp,
MvSubpelPrecision precision) {
int i, v;
int sign_cost[2], class_cost[MV_CLASSES], class0_cost[CLASS0_SIZE];
int bits_cost[MV_OFFSET_BITS][2];
int class0_fp_cost[CLASS0_SIZE][MV_FP_SIZE], fp_cost[MV_FP_SIZE];
int class0_hp_cost[2], hp_cost[2];
av1_cost_tokens_from_cdf(sign_cost, mvcomp->sign_cdf, NULL);
av1_cost_tokens_from_cdf(class_cost, mvcomp->classes_cdf, NULL);
av1_cost_tokens_from_cdf(class0_cost, mvcomp->class0_cdf, NULL);
for (i = 0; i < MV_OFFSET_BITS; ++i) {
av1_cost_tokens_from_cdf(bits_cost[i], mvcomp->bits_cdf[i], NULL);
}
for (i = 0; i < CLASS0_SIZE; ++i)
av1_cost_tokens_from_cdf(class0_fp_cost[i], mvcomp->class0_fp_cdf[i], NULL);
av1_cost_tokens_from_cdf(fp_cost, mvcomp->fp_cdf, NULL);
if (precision > MV_SUBPEL_LOW_PRECISION) {
av1_cost_tokens_from_cdf(class0_hp_cost, mvcomp->class0_hp_cdf, NULL);
av1_cost_tokens_from_cdf(hp_cost, mvcomp->hp_cdf, NULL);
}
mvcost[0] = 0;
for (v = 1; v <= MV_MAX; ++v) {
int z, c, o, d, e, f, cost = 0;
z = v - 1;
c = av1_get_mv_class(z, &o);
cost += class_cost[c];
d = (o >> 3); /* int mv data */
f = (o >> 1) & 3; /* fractional pel mv data */
e = (o & 1); /* high precision mv data */
if (c == MV_CLASS_0) {
cost += class0_cost[d];
} else {
const int b = c + CLASS0_BITS - 1; /* number of bits */
for (i = 0; i < b; ++i) cost += bits_cost[i][((d >> i) & 1)];
}
if (precision > MV_SUBPEL_NONE) {
if (c == MV_CLASS_0) {
cost += class0_fp_cost[d][f];
} else {
cost += fp_cost[f];
}
if (precision > MV_SUBPEL_LOW_PRECISION) {
if (c == MV_CLASS_0) {
cost += class0_hp_cost[e];
} else {
cost += hp_cost[e];
}
}
}
mvcost[v] = cost + sign_cost[0];
mvcost[-v] = cost + sign_cost[1];
}
}
void av1_encode_mv(AV1_COMP *cpi, aom_writer *w, const MV *mv, const MV *ref,
nmv_context *mvctx, int usehp) {
const MV diff = { mv->row - ref->row, mv->col - ref->col };
const MV_JOINT_TYPE j = av1_get_mv_joint(&diff);
if (cpi->common.cur_frame_force_integer_mv) {
usehp = MV_SUBPEL_NONE;
}
aom_write_symbol(w, j, mvctx->joints_cdf, MV_JOINTS);
if (mv_joint_vertical(j))
encode_mv_component(w, diff.row, &mvctx->comps[0], usehp);
if (mv_joint_horizontal(j))
encode_mv_component(w, diff.col, &mvctx->comps[1], usehp);
// If auto_mv_step_size is enabled then keep track of the largest
// motion vector component used.
if (cpi->sf.mv.auto_mv_step_size) {
unsigned int maxv = AOMMAX(abs(mv->row), abs(mv->col)) >> 3;
cpi->max_mv_magnitude = AOMMAX(maxv, cpi->max_mv_magnitude);
}
}
void av1_encode_dv(aom_writer *w, const MV *mv, const MV *ref,
nmv_context *mvctx) {
// DV and ref DV should not have sub-pel.
assert((mv->col & 7) == 0);
assert((mv->row & 7) == 0);
assert((ref->col & 7) == 0);
assert((ref->row & 7) == 0);
const MV diff = { mv->row - ref->row, mv->col - ref->col };
const MV_JOINT_TYPE j = av1_get_mv_joint(&diff);
aom_write_symbol(w, j, mvctx->joints_cdf, MV_JOINTS);
if (mv_joint_vertical(j))
encode_mv_component(w, diff.row, &mvctx->comps[0], MV_SUBPEL_NONE);
if (mv_joint_horizontal(j))
encode_mv_component(w, diff.col, &mvctx->comps[1], MV_SUBPEL_NONE);
}
void av1_build_nmv_cost_table(int *mvjoint, int *mvcost[2],
const nmv_context *ctx,
MvSubpelPrecision precision) {
av1_cost_tokens_from_cdf(mvjoint, ctx->joints_cdf, NULL);
build_nmv_component_cost_table(mvcost[0], &ctx->comps[0], precision);
build_nmv_component_cost_table(mvcost[1], &ctx->comps[1], precision);
}
|
//
// STConfig.h
// STPhotoBrowser
//
// Created by https://github.com/STShenZhaoliang/STPhotoBrowser.git on 16/1/15.
// Copyright © 2016年 ST. All rights reserved.
//
#ifndef STConfig_h
#define STConfig_h
#import "STConst.h"
#import "STUI.h"
#import "UIView+ST.h"
#endif /* STConfig_h */
|
/**
* Copyright 2016 BitTorrent 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.
*/
#pragma once
#include <codeformation/Error.h>
#include <codeformation/types.h>
#include <stdts/any.h>
#include <string>
namespace codeformation {
namespace {
using namespace std::literals;
using namespace codeformation::types;
}
class Resource {
public:
virtual void create() = 0;
virtual Any get() = 0;
void setProperties(Dictionary properties) { _properties = std::move(properties); }
protected:
template <typename T>
T requireProperty(const String& name) {
return require<T>(name, _properties);
}
template <typename T>
stdts::optional<T> optionalProperty(const String& name) {
return optional<T>(name, _properties);
}
template <typename T>
T require(const Any& thing) {
auto* ret = stdts::any_cast<T>(&thing);
if (!ret) {
throw Error("Invalid type.");
}
return *ret;
}
template <typename T>
T require(const String& name, const Dictionary& object) {
auto it = object.find(name);
if (it == object.end()) {
throw Error(name + " is required.");
}
auto* ret = stdts::any_cast<T>(&it->second);
if (!ret) {
throw Error("The value for "s + name + " is the wrong type.");
}
return *ret;
}
template <typename T>
stdts::optional<T> optional(const String& name, const Dictionary& object) {
auto it = object.find(name);
if (it == object.end()) {
return {};
}
auto* ret = stdts::any_cast<T>(&it->second);
if (!ret) {
throw Error("The value for "s + name + " is the wrong type.");
}
return *ret;
}
private:
Dictionary _properties;
};
} // namespace codeformation
|
#include "_cgo_export.h"
#include <git2.h>
#include <git2/sys/odb_backend.h>
#include <git2/sys/refdb_backend.h>
typedef int (*gogit_submodule_cbk)(git_submodule *sm, const char *name, void *payload);
void _go_git_populate_remote_cb(git_clone_options *opts)
{
opts->remote_cb = (git_remote_create_cb)remoteCreateCallback;
}
void _go_git_populate_checkout_cb(git_checkout_options *opts)
{
opts->notify_cb = (git_checkout_notify_cb)checkoutNotifyCallback;
opts->progress_cb = (git_checkout_progress_cb)checkoutProgressCallback;
}
int _go_git_visit_submodule(git_repository *repo, void *fct)
{
return git_submodule_foreach(repo, (gogit_submodule_cbk)&SubmoduleVisitor, fct);
}
int _go_git_treewalk(git_tree *tree, git_treewalk_mode mode, void *ptr)
{
return git_tree_walk(tree, mode, (git_treewalk_cb)&CallbackGitTreeWalk, ptr);
}
int _go_git_packbuilder_foreach(git_packbuilder *pb, void *payload)
{
return git_packbuilder_foreach(pb, (git_packbuilder_foreach_cb)&packbuilderForEachCb, payload);
}
int _go_git_odb_foreach(git_odb *db, void *payload)
{
return git_odb_foreach(db, (git_odb_foreach_cb)&odbForEachCb, payload);
}
void _go_git_odb_backend_free(git_odb_backend *backend)
{
if (backend->free)
backend->free(backend);
return;
}
void _go_git_refdb_backend_free(git_refdb_backend *backend)
{
if (backend->free)
backend->free(backend);
return;
}
int _go_git_diff_foreach(git_diff *diff, int eachFile, int eachHunk, int eachLine, void *payload)
{
git_diff_file_cb fcb = NULL;
git_diff_hunk_cb hcb = NULL;
git_diff_line_cb lcb = NULL;
if (eachFile) {
fcb = (git_diff_file_cb)&diffForEachFileCb;
}
if (eachHunk) {
hcb = (git_diff_hunk_cb)&diffForEachHunkCb;
}
if (eachLine) {
lcb = (git_diff_line_cb)&diffForEachLineCb;
}
return git_diff_foreach(diff, fcb, NULL, hcb, lcb, payload);
}
int _go_git_diff_blobs(git_blob *old, const char *old_path, git_blob *new, const char *new_path, git_diff_options *opts, int eachFile, int eachHunk, int eachLine, void *payload)
{
git_diff_file_cb fcb = NULL;
git_diff_hunk_cb hcb = NULL;
git_diff_line_cb lcb = NULL;
if (eachFile) {
fcb = (git_diff_file_cb)&diffForEachFileCb;
}
if (eachHunk) {
hcb = (git_diff_hunk_cb)&diffForEachHunkCb;
}
if (eachLine) {
lcb = (git_diff_line_cb)&diffForEachLineCb;
}
return git_diff_blobs(old, old_path, new, new_path, opts, fcb, NULL, hcb, lcb, payload);
}
void _go_git_setup_diff_notify_callbacks(git_diff_options *opts) {
opts->notify_cb = (git_diff_notify_cb)diffNotifyCb;
}
void _go_git_setup_callbacks(git_remote_callbacks *callbacks) {
typedef int (*completion_cb)(git_remote_completion_type type, void *data);
typedef int (*update_tips_cb)(const char *refname, const git_oid *a, const git_oid *b, void *data);
typedef int (*push_update_reference_cb)(const char *refname, const char *status, void *data);
callbacks->sideband_progress = (git_transport_message_cb)sidebandProgressCallback;
callbacks->completion = (completion_cb)completionCallback;
callbacks->credentials = (git_cred_acquire_cb)credentialsCallback;
callbacks->transfer_progress = (git_transfer_progress_cb)transferProgressCallback;
callbacks->update_tips = (update_tips_cb)updateTipsCallback;
callbacks->certificate_check = (git_transport_certificate_check_cb) certificateCheckCallback;
callbacks->pack_progress = (git_packbuilder_progress) packProgressCallback;
callbacks->push_transfer_progress = (git_push_transfer_progress) pushTransferProgressCallback;
callbacks->push_update_reference = (push_update_reference_cb) pushUpdateReferenceCallback;
}
int _go_blob_chunk_cb(char *buffer, size_t maxLen, void *payload)
{
return blobChunkCb(buffer, maxLen, payload);
}
int _go_git_blob_create_fromchunks(git_oid *id,
git_repository *repo,
const char *hintpath,
void *payload)
{
return git_blob_create_fromchunks(id, repo, hintpath, _go_blob_chunk_cb, payload);
}
int _go_git_index_add_all(git_index *index, const git_strarray *pathspec, unsigned int flags, void *callback) {
git_index_matched_path_cb cb = callback ? (git_index_matched_path_cb) &indexMatchedPathCallback : NULL;
return git_index_add_all(index, pathspec, flags, cb, callback);
}
int _go_git_index_update_all(git_index *index, const git_strarray *pathspec, void *callback) {
git_index_matched_path_cb cb = callback ? (git_index_matched_path_cb) &indexMatchedPathCallback : NULL;
return git_index_update_all(index, pathspec, cb, callback);
}
int _go_git_index_remove_all(git_index *index, const git_strarray *pathspec, void *callback) {
git_index_matched_path_cb cb = callback ? (git_index_matched_path_cb) &indexMatchedPathCallback : NULL;
return git_index_remove_all(index, pathspec, cb, callback);
}
int _go_git_tag_foreach(git_repository *repo, void *payload)
{
return git_tag_foreach(repo, (git_tag_foreach_cb)&gitTagForeachCb, payload);
}
int _go_git_merge_file(git_merge_file_result* out, char* ancestorContents, size_t ancestorLen, char* ancestorPath, unsigned int ancestorMode, char* oursContents, size_t oursLen, char* oursPath, unsigned int oursMode, char* theirsContents, size_t theirsLen, char* theirsPath, unsigned int theirsMode, git_merge_file_options* copts) {
git_merge_file_input ancestor = GIT_MERGE_FILE_INPUT_INIT;
git_merge_file_input ours = GIT_MERGE_FILE_INPUT_INIT;
git_merge_file_input theirs = GIT_MERGE_FILE_INPUT_INIT;
ancestor.ptr = ancestorContents;
ancestor.size = ancestorLen;
ancestor.path = ancestorPath;
ancestor.mode = ancestorMode;
ours.ptr = oursContents;
ours.size = oursLen;
ours.path = oursPath;
ours.mode = oursMode;
theirs.ptr = theirsContents;
theirs.size = theirsLen;
theirs.path = theirsPath;
theirs.mode = theirsMode;
return git_merge_file(out, &ancestor, &ours, &theirs, copts);
}
/* EOF */
|
/* Example application which uses testable component.
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "esp_random.h"
#include "testable.h"
/* This application has a test subproject in 'test' directory, all the
* interesting things happen there. See ../test/main/example_idf_test_runner_test.c
* and the makefiles in ../test/ directory.
*
* This specific app_main function is provided only to illustrate the layout
* of a project.
*/
void app_main(void)
{
const int count = 32;
const int max = 100;
printf("In main application. Collecting %d random numbers from 1 to %d:\n", count, max);
int *numbers = calloc(count, sizeof(numbers[0]));
for (int i = 0; i < count; ++i) {
numbers[i] = 1 + esp_random() % (max - 1);
printf("%4d ", numbers[i]);
if ((i + 1) % 10 == 0) {
printf("\n");
}
}
int mean = testable_mean(numbers, count);
printf("\nMean: %d\n", mean);
free(numbers);
}
|
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_gamepad4j_desktop_GamepadJniWrapper */
#ifndef _Included_org_gamepad4j_desktop_GamepadJniWrapper
#define _Included_org_gamepad4j_desktop_GamepadJniWrapper
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_gamepad4j_desktop_GamepadJniWrapper
* Method: natInit
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_gamepad4j_desktop_GamepadJniWrapper_natInit
(JNIEnv *, jobject);
/*
* Class: org_gamepad4j_desktop_GamepadJniWrapper
* Method: natRelease
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_gamepad4j_desktop_GamepadJniWrapper_natRelease
(JNIEnv *, jobject);
/*
* Class: org_gamepad4j_desktop_GamepadJniWrapper
* Method: natGetNumberOfPads
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_org_gamepad4j_desktop_GamepadJniWrapper_natGetNumberOfPads
(JNIEnv *, jobject);
/*
* Class: org_gamepad4j_desktop_GamepadJniWrapper
* Method: natDetectPads
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_gamepad4j_desktop_GamepadJniWrapper_natDetectPads
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
|
//
// ZYMethod.h
// ZYFoundationDemo
//
// Created by ZYSu on 2017/4/12.
// Copyright © 2017年 ZYSu. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef void(^ZYVoidBlock)(void);
/**
开启异步线程
@param block 需要执行的代码
*/
void ZYAsyncThread(ZYVoidBlock block);
/**
回主线程
@param block 需要执行的代码
*/
void ZYMainThread(ZYVoidBlock block);
/**
通知中心
@param observer 监听者
@param name 通知名称
@param notify 通知对象
*/
//void ZYNotifacation(id observer, NSString *name, void (^notify)(NSNotification *notify));
/**
屏幕的尺寸
*/
CGRect ZYScreenBounds();
/**
屏幕的大小
*/
CGSize ZYScreenSize();
/**
屏幕的比例
*/
CGFloat ZYScreenScale();
|
#include<algorithm>
#include<numeric>
#include<new>
#include<deque>
#include<functional>
#include<hash_map>
#include<hash_set>
#include<iterator>
#include<list>
#include<map>
#include<set>
#include<stack>
#include<vector>
#include <slist>
#ifndef __WATCOMC__
#include <rope>
#endif
#ifdef TEST_PTHREAD
#include<pthread_alloc>
#endif
|
//
// random.h
// Jasmine
//
// Created by Qiang Li on 12-10-10.
// Copyright (c) 2012 Qiang Li. All rights reserved.
//
#include <math.h>
#define ARC4RANDOM_MAX 0x100000000u
#define ARC4RANDOM_MAX_HALF 0x80000000u
/** UNIFORM DISTRIBUTION (CONTINUOUS) **/
#define RANDOM_0_1 (((float)arc4random() / ARC4RANDOM_MAX))
#define RANDOM_MINUS1_1 (((float)arc4random() / ARC4RANDOM_MAX_HALF) - 1.0f)
/** UNIFORM DISTRIBUTION (DISCRETE) **/
#define RANDOM(min, max) (RANDOM_0_1 * ((float)(max)-(float)(min)) + (float)(min))
#define RANDOMI(min, max) (arc4random() % ((int)max-(int)(min)) + (int)(min))
/** NORMAL DISTRIBUTION **/
/* Box-Muller Transform
* U1 and U2 are independent random variables that are uniformly distributed in the interval (0, 1]
* Z0 = R*cos(theta) = sqrt(-2*ln(U1))*cos(2*PI*U2)
* Z1 = R*sin(theta) = sqrt(-2*ln(U1))*sin(2*PI*U2)
* Z0 and Z1 are independent random variables with a standard normal distribution.
*/
#define RANDOM_STD_NORMAL (sqrtf(-2*log10f(RANDOM_0_1)) * cosf(2*(float)M_PI*RANDOM_0_1))
#define RANDOM_NORMAL(mean, variance) (RANDOM_STD_NORMAL * sqrtf((float)(variance)) + (float)(mean))
/** EXPOENTIAL DISTRIBUTION **/
// TODO
/* U are uniformly distributed in the (0,1]
* Exponential distribution CDF: F(x) = 1 - exp(-lamda * x)
* Z = -(1/lamda)*ln(U)
* Z are random variable with a expoential distribution.
*/ |
/*
+---------------------------------------------------------------------------+
| PHP Driver for MongoDB |
+---------------------------------------------------------------------------+
| Copyright 2013-2014 MongoDB, 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. |
+---------------------------------------------------------------------------+
| Copyright (c) 2014, MongoDB, Inc. |
+---------------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
/* External libs */
#include <bson.h>
#include <mongoc.h>
/* PHP Core stuff */
#include <php.h>
#include <php_ini.h>
#include <ext/standard/info.h>
#include <Zend/zend_interfaces.h>
#include <ext/spl/spl_iterators.h>
/* Our Compatability header */
#include "php_compat_53.h"
/* Our stuffz */
#include "php_phongo.h"
#include "php_bson.h"
#include <ext/spl/spl_exceptions.h>
PHONGO_API zend_class_entry *php_phongo_writeconcernexception_ce;
/* {{{ MongoDB\Driver\WriteConcernException */
static zend_function_entry php_phongo_writeconcernexception_me[] = {
PHP_FE_END
};
/* }}} */
/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(WriteConcernException)
{
zend_class_entry ce;
(void)type;(void)module_number;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteConcernException", php_phongo_writeconcernexception_me);
php_phongo_writeconcernexception_ce = zend_register_internal_class_ex(&ce, php_phongo_writeexception_ce, NULL TSRMLS_CC);
return SUCCESS;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
/*
* \brief I2C LM75A temperature sensor library
*
* \author Quentin Comte-Gaz <quentin@comte-gaz.com>
* \date 8 July 2016 & 14 January 2018
* \license MIT License (contact me if too restrictive)
* \copyright Copyright (c) 2016 Quentin Comte-Gaz
* \version 1.1
*/
#ifndef LM75A_h
#define LM75A_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#define INVALID_LM75A_TEMPERATURE 1000
class LM75A
{
public:
/*!
* \brief LM75A Initialize I2C LM75A Temperature sensor instance
* \param A0_value (bool) A0 Pin value (used for address)
* \param A1_value (bool) A1 Pin value (used for address)
* \param A2_value (bool) A2 Pin value (used for address)
*/
LM75A(bool A0_value = false, bool A1_value = false, bool A2_value = false);
/*!
* \brief getTemperatureInDegrees Get temperature from LM75A sensor in degrees
* \return (float) Sensor temperature in degrees (return INVALID_LM75A_TEMPERATURE if error happened)
*/
float getTemperatureInDegrees() const;
/*!
* \brief getTemperatureInFahrenheit Get temperature from LM75A sensor in fahrenheit
* \return (float) Sensor temperature in fahrenheit (return INVALID_LM75A_TEMPERATURE if error happened)
*/
float getTemperatureInFahrenheit() const;
/*!
* \brief fahrenheitToDegrees Convert temperature from fahrenheit to degrees
*/
static float fahrenheitToDegrees(float temperature_in_fahrenheit);
/*!
* \brief degreesToFahrenheit Convert temperature from degrees to fahrenheit
*/
static float degreesToFahrenheit(float temperature_in_degrees);
private:
int _i2c_device_address;
};
#endif //LM75A_h
|
#pragma once
#include "halley/core/api/movie_api.h"
#include "halley/resources/resource_data.h"
#include "halley/time/halleytime.h"
#include "halley/core/graphics/texture.h"
#include "halley/core/graphics/sprite/sprite.h"
#include <halley/audio/audio_clip.h>
#include "halley/core/graphics/movie/movie_player.h"
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
namespace Halley
{
class VideoAPI;
class AVFMoviePlayer : public MoviePlayer
{
public:
AVFMoviePlayer(VideoAPI& video, AudioAPI& audio, std::shared_ptr<ResourceDataStream> data);
~AVFMoviePlayer() noexcept;
protected:
void requestVideoFrame() override;
void requestAudioFrame() override;
void onReset() override;
private:
struct PlaneData {
gsl::byte* data;
int stride;
int height;
};
void init();
void startReading();
void translateError(NSError* error);
void readVideoSample(Time time, PlaneData yPlane, PlaneData uvPlane);
void readAudioSample(Time time, gsl::span<const gsl::byte> data);
std::shared_ptr<ResourceDataStream> data;
String filePath;
bool startedReading = false;
AVAsset* asset = nil;
AVAssetReader* assetReader = nil;
AVAssetReaderVideoCompositionOutput* videoOut = nil;
AVAssetReaderAudioMixOutput* audioOut = nil;
};
}
|
/******************************************************************************************[Heap.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Copyright (c) 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
/**
* DISCLAIMER: This code is part of the software MiniSAT2. It has been adapted in order to work
* with WASP data structures.
*
*/
#ifndef WASP_HEAP_H
#define WASP_HEAP_H
#include "Vector.h"
#include "../util/WaspAssert.h"
#include <iostream>
using namespace std;
//=================================================================================================
// A heap implementation with support for decrease/increase key.
template< class COMP >
class Heap {
Vector< Var > heap;// Heap of Keys
Vector< int > indices;
COMP lt; // The heap is a minimum-heap with respect to this comparator
// Index "traversal" functions
static inline unsigned int left( unsigned int i ) { return i * 2 + 1; }
static inline unsigned int right( unsigned int i ) { return ( i + 1 ) * 2; }
static inline unsigned int parent( unsigned int i ) { return ( i - 1 ) >> 1; }
void percolateUp( unsigned int i )
{
Var x = heap[ i ];
int p = parent( i );
while( i != 0 && lt( x, heap[ p ] ) )
{
heap[ i ] = heap[ p ];
indices[ heap[ p ] ] = i;
i = p;
p = parent( p );
}
heap[ i ] = x;
indices[ x ] = i;
}
void percolateDown( unsigned int i )
{
Var x = heap[ i ];
while( left( i ) < heap.size() )
{
int child = right( i ) < heap.size() && lt( heap[ right( i ) ], heap[ left( i ) ] ) ? right( i ) : left( i );
if( !lt( heap[ child ], x ) )
break;
heap[ i ] = heap[ child ];
indices[ heap[ i ] ] = i;
i = child;
}
heap[ i ] = x;
indices[ x ] = i;
}
public:
Heap( const COMP& c ) : lt( c ) {}
int size() const { return heap.size(); }
bool empty() const { return heap.empty(); }
bool inHeap ( Var v ) const { assert_msg( v < indices.size(), v << " >= " << indices.size() ); return indices[ v ] != -1; }
int operator[]( int index ) const{ assert( index < heap.size() ); return heap[ index ]; }
void decrease( Var v ) { assert( inHeap( v ) ); percolateUp( indices[ v ] ); }
void increase( Var v ) { assert( inHeap( v ) ); percolateDown( indices[ v ] ); }
// Safe variant of insert/decrease/increase:
// void update( Var v )
// {
// if( !inHeap( v ) )
// insert( v );
// else
// {
// percolateUp( indices[ v ] );
// percolateDown( indices[ v ] );
// }
// }
void push( Var v )
{
if( inHeap( v ) )
return;
pushNoCheck( v );
}
void pushNoCheck( Var v )
{
while( v >= indices.size() )
{
indices.push_back( -1 );
}
assert( !inHeap( v ) );
indices[ v ] = heap.size();
heap.push_back( v );
percolateUp( indices[ v ] );
}
void remove( Var v )
{
assert( inHeap( v ) );
int pos = indices[ v ];
indices[ v ] = -1;;
if( pos < heap.size() - 1 )
{
heap[ pos ] = heap.back();
indices[ heap[ pos ] ] = pos;
heap.pop_back();
percolateDown( pos );
}
else
heap.pop_back();
}
Var top()
{
return heap[ 0 ];
}
void pop()
{
Var x = heap[ 0 ];
heap[ 0 ] = heap.back();
indices[ heap[ 0 ] ] = 0;
indices[ x ] = -1;
heap.pop_back();
if( heap.size() > 1 )
percolateDown( 0 );
}
Var removeMin()
{
Var x = heap[ 0 ];
heap[ 0 ] = heap.back();
indices[ heap[ 0 ] ] = 0;
indices[ x ] = -1;
heap.pop_back();
if( heap.size() > 1 )
percolateDown( 0 );
return x;
}
/* // Rebuild the heap from scratch, using the elements in 'ns':
void build(const vec<K>& ns) {
for (int i = 0; i < heap.size(); i++)
indices[heap[i]] = -1;
heap.clear();
for (int i = 0; i < ns.size(); i++){
// TODO: this should probably call reserve instead of relying on it being reserved already.
assert(indices.has(ns[i]));
indices[ns[i]] = i;
heap.push(ns[i]); }
for (int i = heap.size() / 2 - 1; i >= 0; i--)
percolateDown(i);
}
void clear(bool dispose = false)
{
// TODO: shouldn't the 'indices' map also be dispose-cleared?
for (int i = 0; i < heap.size(); i++)
indices[heap[i]] = -1;
heap.clear(dispose);
}
*/
};
#endif
|
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ez_macro.h>
#include <ez_net.h>
#include <ez_log.h>
#include "cust_sign.h"
void signal_quit_handler(struct ez_signal *sig)
{
EZ_NOTUSED(sig);
}
int read_char_from_stdin(char *buf, size_t bufsize)
{
ssize_t nread;
nread = read(STDIN_FILENO, buf, bufsize);
if (nread > 0)
{
// read 中有个回车符换行符.
buf[nread--] = '\0';
while (nread >= 0 && (buf[nread] == '\n' || buf[nread] == '\r'))
{
buf[nread] = '\0';
--nread;
}
return (int)nread;
}
return 0;
}
int wait_quit(int c)
{
char cmd[16];
char red[16];
char buf[16];
int r;
ssize_t nwrite, nread;
while (1)
{
log_info("\ncmd:>");
r = read_char_from_stdin(cmd, 16);
if (r <= 0)
continue;
else if (strcmp(cmd, "help") == 0)
{
log_info(
"help - help \n"
"close - client active close client socket\n"
"exit - client exit.\n"
"send - client send 16 bytes data.\n"
"recv - client recv data.\n");
continue;
}
else if (strcmp(cmd, "close") == 0)
{
log_info("client %d > 客户端主动关闭 ", c);
ez_net_close_socket(c);
c = 0;
continue;
}
else if (strcmp(cmd, "exit") == 0)
{
if (c != 0)
{
ez_net_close_socket(c);
}
break;
}
else if (strcmp(cmd, "send") == 0)
{
r = ez_net_write(c, buf, sizeof(buf), &nwrite);
log_info("client %d > 发送数据 %li bytes, result: %d .", c, nwrite, r);
// 1.对端已经关闭,写入[result=>NET_OK , nwrite => (0->N)].
// 2.对端已经关闭,写入[result=>ANET_ERR, nwrite => 0 ].
}
else if (strcmp(cmd, "recv") == 0)
{
r = ez_net_read(c, red, sizeof(red), &nread);
log_hexdump(LOG_INFO, red, nread, "client %d > 接收数据 %li bytes, result: %d.", c, nread, r);
// 对端已经关闭下,一直读取是[result=>NET_OK, nread => 0]
}
}
return 1;
}
int main(int argc, char **argv)
{
char *svr_addr = "localhost";
int svr_port = 9090;
char socket_name[256];
int socket_port;
if (argc > 1)
{
svr_addr = argv[1];
}
cust_signal_init();
log_init(LOG_VVERB, NULL);
int c = ez_net_tcp_connect(svr_addr, svr_port);
if (c > 0)
{
ez_net_socket_name(c, socket_name, 255, &socket_port);
socket_name[255] = '\0';
log_info("client[id:%d %s:%d => %s:%d] connect success.", c, socket_name, socket_port, svr_addr, svr_port);
ez_net_set_non_block(c);
wait_quit(c);
ez_net_close_socket(c);
}
log_release();
return 0;
}
|
// Expected expression
void main()
{
if ();
}
|
/*
* Copyright (c) 2003-2017 Rony Shapiro <ronys@pwsafe.org>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/** \file fieldselectionpanel.h
*
*/
#ifndef __FIELDSELECTIONPANEL__
#define __FIELDSELECTIONPANEL__
#include <wx/panel.h>
#include "../../core/ItemData.h"
#include <set>
typedef std::set<CItemData::FieldType> FieldSet;
/*
* This class implements a re-usable panel which lets user select
* multiple item fields (CItemData::FieldType). Its meant to be
* embedded in other dialogs and should be used with the custom
* validator defined below the class
*/
class FieldSelectionPanel : public wxPanel {
DECLARE_EVENT_TABLE()
//returns wxNOT_FOUND if the field is not found in the listbox
int FindField(CItemData::FieldType ft, wxListBox* lb) const;
void MoveItem(int index, wxListBox* from, wxListBox* to);
bool ItemIsMandatory(size_t index) const;
public:
FieldSelectionPanel(wxWindow* parent);
~FieldSelectionPanel();
void AddField(CItemData::FieldType ft, bool selected, bool mandatory);
size_t GetNumSelectedFields() const;
CItemData::FieldType GetSelectedFieldAt(size_t index) const;
void OnSelectSome( wxCommandEvent& evt );
void OnSelectAll( wxCommandEvent& evt );
void OnRemoveSome( wxCommandEvent& evt );
void OnRemoveAll( wxCommandEvent& evt );
private:
wxListBox *m_lbSelected, *m_lbAvailable;
};
/*
* This class should be used to transfer data to/from
* the FieldSelectionPanel class declared above
*/
class FieldSelectionPanelValidator: public wxValidator
{
//private: used internally by Clone
FieldSelectionPanelValidator(const FieldSet& available,
const FieldSet& mandatory,
FieldSet& userSelection,
const wxString& validationMessage,
const wxString& validationTitle);
public:
//userSelection must include all fields that are automatically selected
FieldSelectionPanelValidator(const CItemData::FieldType* available, size_t navail,
const CItemData::FieldType* mandatory, size_t nmandatory,
FieldSet& userSelection,
const wxString& validationMessage,
const wxString& validationTitle);
virtual wxObject* Clone() const {
return new FieldSelectionPanelValidator(m_availableFields,
m_mandatoryFields,
m_userSelectedFields,
m_validationMessage,
m_validationTitle);
}
virtual bool TransferFromWindow();
virtual bool TransferToWindow();
virtual bool Validate (wxWindow* parent);
private:
//For internal use
FieldSet m_availableFields, m_mandatoryFields;
//This is where the user's selections are transferred to/from
FieldSet& m_userSelectedFields;
//used in msgbox during validation
wxString m_validationMessage, m_validationTitle;
void SanitizeSelections();
//we have reference members. Don't let the class get copied inadvertently
DECLARE_NO_COPY_CLASS(FieldSelectionPanelValidator)
};
#endif // __FIELDSELECTIONPANEL__
|
/*
* (C) 2018 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_MONTY_INT_H_
#define BOTAN_MONTY_INT_H_
#include <botan/bigint.h>
namespace Botan {
class Modular_Reducer;
class Montgomery_Params;
/*
* Compute -input^-1 mod 2^MP_WORD_BITS. Throws an exception if input
* is even. If input is odd, then input and 2^n are relatively prime
* and an inverse exists.
*/
word monty_inverse(word input);
/**
* The Montgomery representation of an integer
*/
class BOTAN_TEST_API Montgomery_Int final
{
public:
/**
* Create a zero-initialized Montgomery_Int
*/
Montgomery_Int(std::shared_ptr<const Montgomery_Params> params) : m_params(params) {}
/**
* Create a Montgomery_Int
*/
Montgomery_Int(const std::shared_ptr<const Montgomery_Params>& params,
const BigInt& v,
bool redc_needed = true);
/**
* Create a Montgomery_Int
*/
Montgomery_Int(const std::shared_ptr<const Montgomery_Params>& params,
const uint8_t bits[], size_t len,
bool redc_needed = true);
/**
* Create a Montgomery_Int
*/
Montgomery_Int(std::shared_ptr<const Montgomery_Params> params,
const word words[], size_t len,
bool redc_needed = true);
bool operator==(const Montgomery_Int& other) const;
bool operator!=(const Montgomery_Int& other) const { return (m_v != other.m_v); }
std::vector<uint8_t> serialize() const;
size_t size() const;
bool is_one() const;
bool is_zero() const;
void fix_size();
/**
* Return the value to normal mod-p space
*/
BigInt value() const;
/**
* Return the Montgomery representation
*/
const BigInt& repr() const { return m_v; }
Montgomery_Int operator+(const Montgomery_Int& other) const;
Montgomery_Int operator-(const Montgomery_Int& other) const;
Montgomery_Int& operator+=(const Montgomery_Int& other);
Montgomery_Int& operator-=(const Montgomery_Int& other);
Montgomery_Int operator*(const Montgomery_Int& other) const;
Montgomery_Int& operator*=(const Montgomery_Int& other);
Montgomery_Int& operator*=(const secure_vector<word>& other);
Montgomery_Int& add(const Montgomery_Int& other,
secure_vector<word>& ws);
Montgomery_Int& sub(const Montgomery_Int& other,
secure_vector<word>& ws);
Montgomery_Int mul(const Montgomery_Int& other,
secure_vector<word>& ws) const;
Montgomery_Int& mul_by(const Montgomery_Int& other,
secure_vector<word>& ws);
Montgomery_Int& mul_by(const secure_vector<word>& other,
secure_vector<word>& ws);
Montgomery_Int square(secure_vector<word>& ws) const;
Montgomery_Int cube(secure_vector<word>& ws) const;
Montgomery_Int& square_this(secure_vector<word>& ws);
Montgomery_Int& square_this_n_times(secure_vector<word>& ws, size_t n);
Montgomery_Int multiplicative_inverse() const;
Montgomery_Int additive_inverse() const;
Montgomery_Int& mul_by_2(secure_vector<word>& ws);
Montgomery_Int& mul_by_3(secure_vector<word>& ws);
Montgomery_Int& mul_by_4(secure_vector<word>& ws);
Montgomery_Int& mul_by_8(secure_vector<word>& ws);
void const_time_poison() const { m_v.const_time_poison(); }
void const_time_unpoison() const { return m_v.const_time_unpoison(); }
private:
std::shared_ptr<const Montgomery_Params> m_params;
BigInt m_v;
};
/**
* Parameters for Montgomery Reduction
*/
class BOTAN_TEST_API Montgomery_Params final
{
public:
/**
* Initialize a set of Montgomery reduction parameters. These values
* can be shared by all values in a specific Montgomery domain.
*/
Montgomery_Params(const BigInt& p, const Modular_Reducer& mod_p);
/**
* Initialize a set of Montgomery reduction parameters. These values
* can be shared by all values in a specific Montgomery domain.
*/
Montgomery_Params(const BigInt& p);
const BigInt& p() const { return m_p; }
const BigInt& R1() const { return m_r1; }
const BigInt& R2() const { return m_r2; }
const BigInt& R3() const { return m_r3; }
word p_dash() const { return m_p_dash; }
size_t p_words() const { return m_p_words; }
BigInt redc(const BigInt& x,
secure_vector<word>& ws) const;
BigInt mul(const BigInt& x,
const BigInt& y,
secure_vector<word>& ws) const;
BigInt mul(const BigInt& x,
const secure_vector<word>& y,
secure_vector<word>& ws) const;
void mul_by(BigInt& x,
const secure_vector<word>& y,
secure_vector<word>& ws) const;
void mul_by(BigInt& x, const BigInt& y,
secure_vector<word>& ws) const;
BigInt sqr(const BigInt& x,
secure_vector<word>& ws) const;
void square_this(BigInt& x,
secure_vector<word>& ws) const;
BigInt inv_mod_p(const BigInt& x) const;
private:
BigInt m_p;
BigInt m_r1;
BigInt m_r2;
BigInt m_r3;
word m_p_dash;
size_t m_p_words;
};
}
#endif
|
/*
* Copyright (c) 2014 ASMlover. 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 ofconditions 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 materialsprovided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER 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.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node {
struct Node* prev;
struct Node* next;
ElementType value;
} Node;
typedef struct List {
int length;
Node node;
} List;
static Node* node_create(ElementType value) {
Node* node = (Node*)malloc(sizeof(*node));
if (NULL != node) {
node->prev = NULL;
node->next = NULL;
node->value = value;
}
return node;
}
static void list_insert(
List* list, Node* pos, ElementType value) {
Node* node = node_create(value);
node->prev = pos->prev;
node->next = pos;
pos->prev->next = node;
pos->prev = node;
++list->length;
}
static void list_remove(List* list, Node* pos) {
Node* prev;
Node* next;
prev = pos->prev;
next = pos->next;
prev->next = next;
next->prev = prev;
free(pos);
--list->length;
}
static void list_clear(List* list) {
assert(NULL != list);
{
Node* iter = list->node.next;
Node* node;
while (iter != &list->node) {
node = iter;
iter = iter->next;
list_remove(list, node);
}
list->length = 0;
}
}
static List* list_init(void) {
List* list = (List*)malloc(sizeof(*list));
if (NULL != list) {
list->length = 0;
list->node.prev = &list->node;
list->node.next = &list->node;
}
return list;
}
static void list_destroy(List** list) {
assert(NULL != *list);
list_clear(*list);
free(*list);
*list = NULL;
}
static int list_length(List* list) {
assert(NULL != list);
return list->length;
}
static void list_push_back(List* list, ElementType value) {
assert(NULL != list);
list_insert(list, &list->node, value);
}
static void list_push_front(List* list, ElementType value) {
assert(NULL != list);
list_insert(list, list->node.next, value);
}
static void list_pop_back(List* list) {
assert(NULL != list);
{
Node* prev = (&list->node)->prev;
if (prev != &list->node)
list_remove(list, prev);
}
}
static void list_pop_front(List* list) {
assert(NULL != list);
list_remove(list, list->node.next);
}
static void list_display(List* list) {
assert(NULL != list);
{
Node* iter = list->node.next;
while (iter != &list->node) {
fprintf(stdout, "DoubleList element value is : %d\n", iter->value);
iter = iter->next;
}
fprintf(stdout, "\n");
}
}
void double_list(void) {
List* list = list_init();
int i;
fprintf(stdout, "\n\n==========================================\n");
fprintf(stdout, "DoubleList length = %d\n", list_length(list));
for (i = 0; i < 10; ++i)
list_push_back(list, i * i);
fprintf(stdout, "DoubleList length = %d\n", list_length(list));
for (i = 0; i < 10; ++i)
list_push_front(list, (i + 100) * 3);
fprintf(stdout, "DoubleList length = %d\n", list_length(list));
list_display(list);
list_pop_back(list);
list_pop_front(list);
fprintf(stdout, "DoubleList length = %d\n", list_length(list));
list_display(list);
list_clear(list);
fprintf(stdout, "DoubleList length = %d\n", list_length(list));
list_destroy(&list);
}
|
//
// pirates3d.h
// IDKApp
//
// Created by Jacob Gordon on 4/6/15.
// Copyright (c) 2015 Jacob Gordon. All rights reserved.
//
#ifndef __IDKApp__pirates3d__
#define __IDKApp__pirates3d__
#include <stdio.h>
#include "pirates.h"
typedef enum { pirates3d_copy_data = 1, pirates3d_dont_copy_data = 0, pirates3d_dont_copy_but_delete_data = 1 } pirates3d_copy_mode ;
typedef enum { Rotation, Scale, Translate } pirates3d_transform_type ;
typedef enum { replace, chain } pirates3d_transform_mode ;
typedef enum { Triangles } pirates3d_primitive_type ;
typedef const char* pirates3d_material_label ;
typedef int pirates3d_material ;
typedef RKList pirates3d_transform ;
typedef struct pirates3d_primitive_array_s* pirates3d_primitive_array ;
typedef struct pirates3d_camera_s* pirates3d_camera ;
typedef struct pirates3d_scene_s* pirates3d_scene ;
pirates3d_primitive_array pirates3d_new_sphere( pirates3d_scene scene3d, int num_of_primitives, float radius ) ;
pirates3d_camera pirates3d_new_camera( float x, float y, float z, float fx, float fy, float fz ) ;
void pirates3d_change_camera( pirates3d_camera camera, float x, float y, float z, float fx, float fy, float fz ) ;
void pirates3d_destroy_camera( pirates3d_camera camera ) ;
void pirates3d_set_camera_to_active( pirates3d_scene scene3d, pirates3d_camera camera ) ;
int pirates3d_is_camera_active( pirates3d_camera camera ) ;
void pirates3d_apply_material( pirates3d_material material, pirates3d_primitive_array primitive_array ) ;
pirates3d_material pirates3d_new_material( pirates3d_scene scene3d, pirates3d_material_label label, float red, float blue, float green ) ;
pirates3d_material pirates3d_get_material( pirates3d_scene scene3d, pirates3d_material_label label ) ;
pirates3d_material pirates3d_change_material( pirates3d_scene scene3d, pirates3d_material material, float red, float blue, float green ) ;
pirates3d_material pirates3d_change_material_with_label( pirates3d_scene scene3d, pirates3d_material_label label, float red, float blue, float green ) ;
pirates3d_scene pirates3d_new_3dscene( pirates3d_camera camera, pirates_scene scene_rt ) ;
void pirates3d_destroy_3dscene( pirates3d_scene scene3d ) ;
void pirates3d_draw_3dscene( pirates3d_scene scene3d ) ;
pirates3d_transform pirates3d_new_transform( void ) ;
void pirates3d_add_transform( pirates3d_transform transform, pirates3d_transform_type transform_type, pirates3d_transform_mode mode, float x, float y, float z, float w ) ;
void pirates3d_delete_last_transform_set( pirates3d_transform transform ) ;
void pirates3d_apply_transform( pirates3d_transform transform, pirates3d_primitive_array primitive_array ) ;
int pirates3d_get_primitive_size( pirates3d_primitive_type primitive_type ) ;
pirates3d_primitive_array pirates3d_new_primitive_array( pirates3d_scene scene3d, void* primitive_data, pirates3d_primitive_type primitive_type, pirates3d_copy_mode copy_mode, int num_of_primitives ) ;
void pirates3d_destroy_primitive_array( pirates3d_primitive_array primitive_array ) ;
#endif /* defined(__IDKApp__pirates3d__) */
|
/*
Copyright (c) 1996 Blake McBride
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER 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.
*/
#include "generics.h"
#define MEMU \
printf("Memory usage %ld, %ld\n", gMaxMemUsed(Dynace), gCurMemUsed(Dynace))
main(int argc, char *argv[])
{
object obj;
long n, mba, cmu;
InitClasses(&argc);
/* The following line is used to turn on the automatic garbage
collector (un-comment after the first run) */
// gSetMemoryBufferArea(Dynace, 50000L);
/* Create enough new objects to fill up all the memory of a PC
(since no objects are ever explictly disposed). */
MEMU;
for (n=0 ; n++ != 125000L ; ) {
if (!(n % 1000L))
printf("%ld\n", n);
obj = vNew(DoubleFloat, 3.141);
}
gPrint(obj, stdoutStream);
gGC(Dynace);
MEMU;
gPrint(obj, stdoutStream);
getch();
return 0;
}
|
#pragma once
#include "ofMain.h"
#include "ofxXmlSettings.h"
#include "GUI.h"
#include "LedManager.h"
#ifdef _WIN32
#include "SpoutManager.h" // Spout SDK
#elif MAC_OS_X_VERSION_10_6
#include "ofxSyphon.h"
#endif
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void exit();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
//UI
GUI gui;
void guiEvent(ofxUIEventArgs &e);
//Settings
//ofxXmlSettings settings;
std::string fileName;
void loadSettings(const std::string &file);
void saveSettings();
//Spout
#ifdef _WIN32
SpoutManager spout;
#elif MAC_OS_X_VERSION_10_6
ofxSyphonClient syphonClient;
#endif
bool showTexture;
//Leds -> to transfer to LedManager
LedManager ledManager;
ofPixels pixels;
unsigned char * directPix;
};
|
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2021, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
----------------------------------------------------------------------
*/
/** @file glTFWriter.h
* Declares a class to write gltf/glb files
*
* glTF Extensions Support:
* KHR_binary_glTF: full
* KHR_materials_common: full
*/
#ifndef GLTFASSETWRITER_H_INC
#define GLTFASSETWRITER_H_INC
#if !defined(ASSIMP_BUILD_NO_GLTF_IMPORTER) && !defined(ASSIMP_BUILD_NO_GLTF1_IMPORTER)
#include "glTFAsset.h"
namespace glTF
{
using rapidjson::MemoryPoolAllocator;
class AssetWriter
{
template<class T>
friend void WriteLazyDict(LazyDict<T>& d, AssetWriter& w);
private:
void WriteBinaryData(IOStream* outfile, size_t sceneLength);
void WriteMetadata();
void WriteExtensionsUsed();
template<class T>
void WriteObjects(LazyDict<T>& d);
public:
Document mDoc;
Asset& mAsset;
MemoryPoolAllocator<>& mAl;
AssetWriter(Asset& asset);
void WriteFile(const char* path);
void WriteGLBFile(const char* path);
};
}
// Include the implementation of the methods
#include "glTFAssetWriter.inl"
#endif // ASSIMP_BUILD_NO_GLTF_IMPORTER
#endif // GLTFASSETWRITER_H_INC
|
/* @LICENSE(MUSLC_MIT) */
/* origin: FreeBSD /usr/src/lib/msun/src/s_rintf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include "libm.h"
static const float
TWO23[2] = {
8.3886080000e+06, /* 0x4b000000 */
-8.3886080000e+06, /* 0xcb000000 */
};
float rintf(float x)
{
int32_t i0,j0,sx;
float w,t;
GET_FLOAT_WORD(i0, x);
sx = (i0>>31) & 1;
j0 = ((i0>>23)&0xff) - 0x7f;
if (j0 < 23) {
if (j0 < 0) {
if ((i0&0x7fffffff) == 0)
return x;
STRICT_ASSIGN(float, w, TWO23[sx] + x);
t = w - TWO23[sx];
GET_FLOAT_WORD(i0, t);
SET_FLOAT_WORD(t, (i0&0x7fffffff)|(sx<<31));
return t;
}
STRICT_ASSIGN(float, w, TWO23[sx] + x);
return w - TWO23[sx];
}
if (j0 == 0x80)
return x+x; /* inf or NaN */
return x; /* x is integral */
}
|
/*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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
* <COPYRIGHT HOLDER> 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.
*/
#include "../../nb_plugin_api.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <tokudb.h>
struct nb_db_tokukv {
DB_ENV *env;
DB *db;
};
static struct nb_db *
nb_db_tokukv_open(const struct nb_db_opts *opts)
{
struct nb_db_tokukv *tokukv = malloc(sizeof(*tokukv));
if (tokukv == NULL) {
fprintf(stderr, "malloc(%zu) failed", sizeof(*tokukv));
goto error_1;
}
int r;
r = mkdir(opts->path, 0777);
if (r != 0 && errno != EEXIST) {
fprintf(stderr, "mkdir: %d\n", r);
goto error_1;
}
DB_ENV *env;
DB *db;
int env_flags = 0;
r = db_env_create(&env, env_flags);
if (r != 0) {
fprintf(stderr, "db_env_create failed: %s\n",
db_strerror(r));
goto error_1;
}
if (env->set_cachesize) {
r = env->set_cachesize(env, 0, 127*1024*1024, 1);
if (r != 0) {
fprintf(stderr, "env->set_cachesize failed: %s\n",
db_strerror(r));
goto error_2;
}
}
#if 0
env_flags |= DB_TXN_WRITE_NOSYNC;
r = env->set_flags(env, env_flags, 1);
if (r != 0) {
fprintf(stderr, "set_flags: %d\n", r);
goto error_2;
}
#endif
int env_open_flags = DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL;
r = env->open(env, opts->path, env_open_flags, 0644);
if (r != 0) {
fprintf(stderr, "env->open failed: %s\n", db_strerror(r));
goto error_2;
}
r = db_create(&db, env, 0);
if (r != 0) {
fprintf(stderr, "db_create failed: %s\n", db_strerror(r));
goto error_2;
}
/* Disable compression */
r = db->set_compression_method(db, TOKU_NO_COMPRESSION);
if (r != 0) {
fprintf(stderr, "db->set_compression_method failed: %s\n",
db_strerror(r));
goto error_3;
}
int open_flags = DB_CREATE;
r = db->open(db, NULL, "data.bdb", NULL, DB_BTREE, open_flags, 0644);
if (r != 0) {
fprintf(stderr, "db->open failed: %s\n", db_strerror(r));
goto error_3;
}
TOKU_COMPRESSION_METHOD compression;
r = db->get_compression_method(db, &compression);
if (r != 0) {
fprintf(stderr, "db->set_compression_method failed: %s\n",
db_strerror(r));
goto error_3;
}
fprintf(stderr, "TokuKV compression method: %d\n", compression);
tokukv->env = env;
tokukv->db = db;
return (struct nb_db *) tokukv;
error_3:
db->close(db, 0);
error_2:
env->close(env, 0);
error_1:
return NULL;
}
static void
nb_db_tokukv_close(struct nb_db *db)
{
struct nb_db_tokukv *tokukv = (struct nb_db_tokukv *) db;
tokukv->db->close(tokukv->db, 0);
tokukv->env->close(tokukv->env, 0);
tokukv->env = NULL;
tokukv->db = NULL;
free(tokukv);
}
static int
nb_db_tokukv_replace(struct nb_db *db, const void *key, size_t key_len,
const void *val, size_t val_len)
{
struct nb_db_tokukv *tokukv = (struct nb_db_tokukv *) db;
DBT dbkey, dbval;
memset(&dbkey, 0, sizeof(dbkey));
memset(&dbval, 0, sizeof(dbval));
dbkey.data = (void *) key;
dbkey.size = key_len;
dbval.data = (void *) val;
dbval.size = val_len;
int put_flags = 0; /* DB_OVERWRITE_DUP */;
int r = tokukv->db->put(tokukv->db, NULL, &dbkey, &dbval,
put_flags);
if (r == DB_NOTFOUND) {
fprintf(stderr, "db->get() failed: %s\n",
db_strerror(r));
return -1;
}
return 0;
}
static int
nb_db_tokukv_remove(struct nb_db *db, const void *key, size_t key_len)
{
struct nb_db_tokukv *tokukv = (struct nb_db_tokukv *) db;
DBT dbkey;
memset(&dbkey, 0, sizeof(dbkey));
dbkey.data = (void *) key;
dbkey.size = key_len;
int r = tokukv->db->del(tokukv->db, NULL, &dbkey, 0);
if (r == DB_NOTFOUND) {
fprintf(stderr, "db->del() failed: %s\n",
db_strerror(r));
return -1;
}
return 0;
}
static int
nb_db_tokukv_select(struct nb_db *db, const void *key, size_t key_len,
void **pval, size_t *pval_len)
{
struct nb_db_tokukv *tokukv = (struct nb_db_tokukv *) db;
DBT dbkey, dbval;
memset(&dbkey, 0, sizeof(dbkey));
memset(&dbval, 0, sizeof(dbval));
dbkey.data = (void *) key;
dbkey.size = key_len;
if (pval != NULL) {
dbval.flags = DB_DBT_MALLOC;
}
int r = tokukv->db->get(tokukv->db, NULL, &dbkey, &dbval, 0);
if (r == DB_NOTFOUND) {
fprintf(stderr, "db->get() failed: %s\n",
db_strerror(r));
return -1;
}
if (pval) {
*pval = dbval.data;
*pval_len = dbval.size;
}
return 0;
}
static void
nb_db_tokukv_valfree(struct nb_db *db, void *val)
{
(void) db;
free(val);
}
static struct nb_db_if plugin = {
.name = "tokukv",
.open = nb_db_tokukv_open,
.close = nb_db_tokukv_close,
.replace = nb_db_tokukv_replace,
.remove = nb_db_tokukv_remove,
.select = nb_db_tokukv_select,
.valfree = nb_db_tokukv_valfree,
};
NB_DB_PLUGIN const struct nb_db_if *
nb_db_tokukv_plugin(void)
{
return &plugin;
}
|
#include <stdio.h>
int main (void) {
int a[5];
int i;
for(i=0;i<5;i++) {
i[a]=i;
}
for(i=0;i<5;i++) {
printf("%d\n",a[i]);
}
;
return 0;
}
|
#pragma once
#include "Common.h"
#include "Bitmap.h"
extern "C"
{
EXPORT Bitmap * _createBitmap();
EXPORT void _destroyBitmap(Bitmap * bitmap);
EXPORT void _initBitmap(Bitmap * bitmap,unsigned int width,unsigned int height);
EXPORT unsigned int _bitmapGetWidth(Bitmap * bitmap);
EXPORT unsigned int _bitmapGetHeight(Bitmap * bitmap);
EXPORT unsigned char * _bitmapGetBuffer(Bitmap * bitmap);
}; |
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#pragma once
#include "Core/STL/CompileTime/TypeListHelpers.h"
#include "Core/STL/Types/Delegate.h"
namespace GX_STL
{
namespace CompileTime
{
namespace _ctime_hidden_
{
template <typename T>
struct _FunctionInfo {};
template <typename T>
struct _FunctionInfo< T * > {};
template <typename T, typename Class>
struct _FunctionInfo< T (Class::*) > {};
template <typename Result, typename ...Args>
struct _FunctionInfo< Result (Args...) >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (*) (Args...);
using clazz = void;
};
template <typename Result, typename ...Args>
struct _FunctionInfo< Result (*) (Args...) >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (*) (Args...);
using clazz = void;
};
template <typename Class, typename Result, typename ...Args>
struct _FunctionInfo< Result (Class::*) (Args...) >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (Class::*) (Args...);
using clazz = Class;
};
template <typename Class, typename Result, typename ...Args>
struct _FunctionInfo< Result (Class::*) (Args...) const >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (Class::*) (Args...) const;
using clazz = Class;
};
template <typename Class, typename Result, typename ...Args>
struct _FunctionInfo< Result (Class::*) (Args...) volatile >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (Class::*) (Args...) volatile;
using clazz = Class;
};
template <typename Class, typename Result, typename ...Args>
struct _FunctionInfo< Result (Class::*) (Args...) volatile const >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (Class::*) (Args...) volatile const;
using clazz = Class;
};
template <typename Result, typename ...Args>
struct _FunctionInfo< Result (Args...) noexcept >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (*) (Args...) noexcept;
using clazz = void;
};
template <typename Result, typename ...Args>
struct _FunctionInfo< Result (*) (Args...) noexcept >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (*) (Args...) noexcept;
using clazz = void;
};
template <typename Class, typename Result, typename ...Args>
struct _FunctionInfo< Result (Class::*) (Args...) noexcept >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (Class::*) (Args...) noexcept;
using clazz = Class;
};
template <typename Class, typename Result, typename ...Args>
struct _FunctionInfo< Result (Class::*) (Args...) const noexcept >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (Class::*) (Args...) const noexcept;
using clazz = Class;
};
template <typename Class, typename Result, typename ...Args>
struct _FunctionInfo< Result (Class::*) (Args...) volatile noexcept >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (Class::*) (Args...) volatile noexcept;
using clazz = Class;
};
template <typename Class, typename Result, typename ...Args>
struct _FunctionInfo< Result (Class::*) (Args...) volatile const noexcept >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (Class::*) (Args...) volatile const noexcept;
using clazz = Class;
};
template <typename Result, typename ...Args>
struct _FunctionInfo< GXTypes::Delegate< Result (Args...) > >
{
using _del = GXTypes::Delegate< Result (Args...) >;
using args = typename _del::Args_t;
using result = typename _del::Result_t;
using type = typename _del::Function_t;
using clazz = void;
};
template <typename Result, typename ...Args>
struct _FunctionInfo< GXTypes::Event< Result (Args...) > >
{
using _ev = GXTypes::Event< Result (Args...) >;
using args = typename _ev::Args_t;
using result = typename _ev::Result_t;
using type = typename _ev::Function_t;
using clazz = void;
};
template <typename Result, typename ...Args>
struct _FunctionInfo< std::function< Result (Args...) > >
{
using args = TypeListFrom< Args..., TypeListEnd >;
using result = Result;
using type = Result (*) (Args...);
using clazz = void;
};
} // _ctime_hidden_
template <typename T>
using FunctionInfo = _ctime_hidden_::_FunctionInfo< T >;
template <typename T>
using ResultOf = typename FunctionInfo< T >::result;
} // CompileTime
} // GX_STL
|
/*
* Copyright (c) 2014-2015, L3a,
* Enrique Gámez Flores <egamez@edisson.com.mx>
* 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.
*
* 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 HOLDER 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 INERE_ENVIA_GENERA_CADENA_H_
#define INERE_ENVIA_GENERA_CADENA_H_
#ifdef __cplusplus
extern "C" {
#endif
extern char *genera_cadena(char *str, unsigned int length, const int mode);
#ifdef __cplusplus
}
#endif
#endif /* INERE_ENVIA_GENERA_CADENA_H_ */
|
#pragma once
#include "config.h"
#ifdef FRAMEWORK_SUPPORTS_OPENGL
#if defined(__APPLE__)
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#else
#define USE_GLEW
#include <GL/glew.h>
#endif
#ifdef _WIN32
#pragma comment(lib, "glew32")
#pragma comment(lib, "opengl32")
#include <GL/wglew.h>
#endif
#endif |
/* $Id: misc.h,v 1.2 2005/10/02 07:38:51 geni Exp $
*
* Copyright (c) 2005 Huidae Cho
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _MISC_H_
#define _MISC_H_
#define BEGIN_OPT() \
{ \
int i, j; \
for(i = 0; i < argc; i++){ \
if((j = str_chr(argv[i], '=')) <= 0) \
continue; \
j++;
#define OPT(name, var) \
if(str_str(argv[i], name) && \
argv[i][strlen(name)] == '='){ \
var = argv[i] + j; \
continue; \
}
typedef struct _appinfo {
int app;
char *file;
} appinfo;
#define APP_OPT(name, idx) \
if(str_str(argv[i], name) && argv[i][strlen(name)] == '='){ \
app = (appinfo *)realloc(app, (num_apps+1)*sizeof(appinfo)); \
app[num_apps].app = idx; \
app[num_apps].file = argv[i] + j; \
num_apps++; \
continue; \
}
#define END_OPT() \
} \
}
#endif
|
/*
* spin_lock.h
*/
#ifndef CONCURRENCY_SPINLOCK_H_
#define CONCURRENCY_SPINLOCK_H_
#include <atomic>
#include <cstdio>
#include <pthread.h>
namespace conc11 {
static const uint_fast16_t SPIN_CYCLES_BEFORE_YIELD = 100;
static const uint_fast16_t SPIN_CYCLES_BEFORE_YIELD_FAIR = 100;
/**
* A simple unfair spin lock that satisfies Lockable.
*/
class SpinLock {
public:
SpinLock() noexcept = default;
SpinLock(const SpinLock &rhs) = delete;
SpinLock &operator=(const SpinLock &rhs) = delete;
void lock(){
uint_fast16_t patience = SPIN_CYCLES_BEFORE_YIELD;
while(l.test_and_set(std::memory_order_acquire)) {
patience--;
if (!patience) {
patience = SPIN_CYCLES_BEFORE_YIELD;
std::this_thread::yield();
}
}
}
void unlock() {
l.clear(std::memory_order_release);
}
bool try_lock() {
return !l.test_and_set(std::memory_order_acq_rel);
}
private:
std::atomic_flag l = ATOMIC_FLAG_INIT;
};
/**
* A fair spin lock using ticket lock algorithm that satisfies BasicLockable.
* This type of spin locks tends to become very slow under heavy contention. Consider using
* SpinLock if fairness is not a huge concern.
*/
class FairSpinLock {
public:
FairSpinLock() noexcept:
next(0), active(0) {
}
FairSpinLock(const FairSpinLock &rhs) = delete;
FairSpinLock &operator=(const FairSpinLock &rhs) = delete;
void lock() {
unsigned int ticket = next.fetch_add(1, std::memory_order_acq_rel);
uint_fast16_t patience = SPIN_CYCLES_BEFORE_YIELD_FAIR;
while (active.load(std::memory_order_acquire) != ticket) {
patience--;
if (!patience) {
patience = SPIN_CYCLES_BEFORE_YIELD_FAIR;
std::this_thread::yield(); // can be insanely slow without yield
}
}
}
void unlock() {
active.fetch_add(1, std::memory_order_release);
}
private:
std::atomic_uint next;
std::atomic_uint active;
};
} // namespace conc11
#endif /* CONCURRENCY_SPINLOCK_H_ */
|
/*
* Copyright (C) 2013- Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include "cint_bas.h"
#include "g2e.h"
#include "optimizer.h"
#include "cint2e.h"
#include "cart2sph.h"
FINT CINTinit_int2e_coulerf_EnvVars(CINTEnvVars *envs, FINT *ng, FINT *shls,
FINT *atm, FINT natm, FINT *bas, FINT nbas, double *env);
void CINTgout2e(double *gout, double *g, FINT *idx, CINTEnvVars *envs, FINT gout_empty);
CACHE_SIZE_T int2e_coulerf_sph(double *out, FINT *dims, FINT *shls, FINT *atm, FINT natm,
FINT *bas, FINT nbas, double *env, CINTOpt *opt, double *cache)
{
FINT ng[] = {0, 0, 0, 0, 0, 1, 1, 1};
CINTEnvVars envs;
CINTinit_int2e_coulerf_EnvVars(&envs, ng, shls, atm, natm, bas, nbas, env);
envs.f_gout = &CINTgout2e;
return CINT2e_drv(out, dims, &envs, opt, cache, &c2s_sph_2e1);
}
void int2e_coulerf_optimizer(CINTOpt **opt, FINT *atm, FINT natm,
FINT *bas, FINT nbas, double *env)
{
FINT ng[] = {0, 0, 0, 0, 0, 1, 1, 1};
CINTall_2e_optimizer(opt, ng, atm, natm, bas, nbas, env);
}
#define ALL_CINT(NAME) \
FINT c##NAME##_sph(double *out, FINT *shls, FINT *atm, FINT natm, \
FINT *bas, FINT nbas, double *env, CINTOpt *opt) { \
return NAME##_sph(out, NULL, shls, atm, natm, bas, nbas, env, opt, NULL); \
} \
void c##NAME##_sph_optimizer(CINTOpt **opt, FINT *atm, FINT natm, \
FINT *bas, FINT nbas, double *env) { \
NAME##_optimizer(opt, atm, natm, bas, nbas, env); \
}
ALL_CINT(int2e_coulerf)
|
int testPlaImplied() {
//no flags
A = 0x00;
push8(0x23);
ram[0] = 0x68;
instructions = 1; run();
if(!(A == 0x23 && !(SR&SR_ZERO) && !(SR&SR_NEG))) return -1;
//zero flag
A = 0x23;
push8(0x00);
ram[0] = 0x68;
instructions = 1; run();
if(!(A == 0x00 && SR&SR_ZERO && !(SR&SR_NEG))) return -1;
return 0;
} |
#ifndef OSC_HANDLER_H
#define OSC_HANDLER_H
#include "ofxOsc.h"
class MadCam;
class OscHandler
{
ofxOscReceiver receiver;
MadCam *application = NULL;
public:
void registerHost(MadCam *app);
void process();
};
#endif
|
#ifndef __LIBRARY_QCOM_TARGET_MMC_LIB_H__
#define __LIBRARY_QCOM_TARGET_MMC_LIB_H__
#include <Chipset/mmc_sdhci.h>
typedef struct mmc_device* (*INIT_SLOT_CB)(struct mmc_config_data *config);
VOID LibQcomTargetMmcSdhciInit(INIT_SLOT_CB InitSlot);
#endif
|
/*
* This file is part of synconv.
*
* © 2013 Fernando Tarlá Cardoso Lemos
*
* Refer to the LICENSE file for licensing information.
*
*/
#import <Foundation/Foundation.h>
#import "SCVDecoder.h"
#import "SCVEncoder.h"
#import "SCVPlugin.h"
@interface SCVPluginManager : NSObject
+ (instancetype)sharedInstance;
- (SCVPlugin <SCVEncoder> *)pluginForEncodingWithName:(NSString *)name;
- (SCVPlugin <SCVDecoder> *)pluginForDecodingFileWithExtension:(NSString *)extension;
@end
|
/* @LICENSE(MUSLC_MIT) */
#include <ctype.h>
int isspace_l(int c, locale_t l)
{
return isspace(c);
}
|
/* Generated by ./xlat/gen.sh from ./xlat/mbindflags.in; do not edit. */
#ifdef IN_MPERS
# error static const struct xlat mbindflags in mpers mode
#else
static
const struct xlat mbindflags[] = {
#if defined(MPOL_MF_STRICT) || (defined(HAVE_DECL_MPOL_MF_STRICT) && HAVE_DECL_MPOL_MF_STRICT)
XLAT(MPOL_MF_STRICT),
#endif
#if defined(MPOL_MF_MOVE) || (defined(HAVE_DECL_MPOL_MF_MOVE) && HAVE_DECL_MPOL_MF_MOVE)
XLAT(MPOL_MF_MOVE),
#endif
#if defined(MPOL_MF_MOVE_ALL) || (defined(HAVE_DECL_MPOL_MF_MOVE_ALL) && HAVE_DECL_MPOL_MF_MOVE_ALL)
XLAT(MPOL_MF_MOVE_ALL),
#endif
XLAT_END
};
#endif /* !IN_MPERS */
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__char_realloc_17.c
Label Definition File: CWE401_Memory_Leak.c.label.xml
Template File: sources-sinks-17.tmpl.c
*/
/*
* @description
* CWE: 401 Memory Leak
* BadSource: realloc Allocate data using realloc()
* GoodSource: Allocate data on the stack
* Sinks:
* GoodSink: call free() on data
* BadSink : no deallocation of data
* Flow Variant: 17 Control flow: for loops
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
void CWE401_Memory_Leak__char_realloc_17_bad()
{
int i,j;
char * data;
data = NULL;
for(i = 0; i < 1; i++)
{
/* POTENTIAL FLAW: Allocate memory on the heap */
data = (char *)realloc(data, 100*sizeof(char));
if (data == NULL) {exit(-1);}
/* Initialize and make use of data */
strcpy(data, "A String");
printLine(data);
}
for(j = 0; j < 1; j++)
{
/* POTENTIAL FLAW: No deallocation */
; /* empty statement needed for some flow variants */
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G() - use badsource and goodsink in the for statements */
static void goodB2G()
{
int i,k;
char * data;
data = NULL;
for(i = 0; i < 1; i++)
{
/* POTENTIAL FLAW: Allocate memory on the heap */
data = (char *)realloc(data, 100*sizeof(char));
if (data == NULL) {exit(-1);}
/* Initialize and make use of data */
strcpy(data, "A String");
printLine(data);
}
for(k = 0; k < 1; k++)
{
/* FIX: Deallocate memory */
free(data);
}
}
/* goodG2B() - use goodsource and badsink in the for statements */
static void goodG2B()
{
int h,j;
char * data;
data = NULL;
for(h = 0; h < 1; h++)
{
/* FIX: Use memory allocated on the stack with ALLOCA */
data = (char *)ALLOCA(100*sizeof(char));
/* Initialize and make use of data */
strcpy(data, "A String");
printLine(data);
}
for(j = 0; j < 1; j++)
{
/* POTENTIAL FLAW: No deallocation */
; /* empty statement needed for some flow variants */
}
}
void CWE401_Memory_Leak__char_realloc_17_good()
{
goodB2G();
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE401_Memory_Leak__char_realloc_17_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE401_Memory_Leak__char_realloc_17_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef MITKNavigationDataSetWriterCSV_H_HEADER_INCLUDED_
#define MITKNavigationDataSetWriterCSV_H_HEADER_INCLUDED_
#include <mitkNavigationDataSet.h>
namespace mitk {
class MITKIGT_EXPORT NavigationDataSetWriterCSV
{
public:
NavigationDataSetWriterCSV();
virtual~NavigationDataSetWriterCSV();
virtual void Write (std::string path, mitk::NavigationDataSet::Pointer );
virtual void Write (std::ostream* stream, mitk::NavigationDataSet::Pointer);
};
}
#endif // MITKNavigationDataSetWriterCSV_H_HEADER_INCLUDED_
|
// SDLPerformAudioPassThruResponse.h
//
#import "SDLRPCResponse.h"
/**
* Perform Audio Pass Thru Response is sent, when PerformAudioPassThru has been called
*
* Since SmartDeviceLink 2.0
*/
NS_ASSUME_NONNULL_BEGIN
@interface SDLPerformAudioPassThruResponse : SDLRPCResponse
@end
NS_ASSUME_NONNULL_END
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SIGNIN_SIGNIN_OAUTH_HELPER_H_
#define CHROME_BROWSER_SIGNIN_SIGNIN_OAUTH_HELPER_H_
#include <string>
#include "base/memory/scoped_ptr.h"
#include "google_apis/gaia/gaia_auth_consumer.h"
#include "google_apis/gaia/gaia_auth_fetcher.h"
// Retrieves the OAuth2 information from an already signed in cookie jar.
// The information retrieved is: username, refresh token.
class SigninOAuthHelper : public GaiaAuthConsumer {
public:
// Implemented by users of SigninOAuthHelper to know then helper is finished.
class Consumer {
public:
virtual ~Consumer() {}
// Called when all the information is retrieved successfully. |email|
// and |display_email| correspond to the gaia properties called "email"
// and "displayEmail" associated with the signed in account. |refresh_token|
// is the account's login-scoped oauth2 refresh token.
virtual void OnSigninOAuthInformationAvailable(
const std::string& email,
const std::string& display_email,
const std::string& refresh_token) {}
// Called when an error occurs while getting the information.
virtual void OnSigninOAuthInformationFailure(
const GoogleServiceAuthError& error) {}
};
explicit SigninOAuthHelper(net::URLRequestContextGetter* getter,
const std::string& session_index,
Consumer* consumer);
virtual ~SigninOAuthHelper();
private:
// Overridden from GaiaAuthConsumer.
virtual void OnClientOAuthSuccess(const ClientOAuthResult& result) OVERRIDE;
virtual void OnClientOAuthFailure(
const GoogleServiceAuthError& error) OVERRIDE;
virtual void OnClientLoginSuccess(const ClientLoginResult& result) OVERRIDE;
virtual void OnClientLoginFailure(
const GoogleServiceAuthError& error) OVERRIDE;
virtual void OnGetUserInfoSuccess(const UserInfoMap& data) OVERRIDE;
virtual void OnGetUserInfoFailure(
const GoogleServiceAuthError& error) OVERRIDE;
GaiaAuthFetcher gaia_auth_fetcher_;
std::string refresh_token_;
Consumer* consumer_;
DISALLOW_COPY_AND_ASSIGN(SigninOAuthHelper);
};
#endif // CHROME_BROWSER_SIGNIN_SIGNIN_OAUTH_HELPER_H_
|
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fp;
int a;
if (argc != 2) {
printf("Usage: %s [FILE]\n", argv[0]);
return 1;
}
fp = fopen(*++argv, "r");
while (fscanf(fp, "%d", &a) != EOF) {
int l = a, d, n, count = 0, s, t = 0, tx;
fscanf(fp, "%d %d", &d, &n);
tx = 6 - d;
for (s = 6; s <= l - 6; s += d) {
if (s > tx - d) {
s = tx;
if (t == n) {
tx = l - 6 + d;
} else {
fscanf(fp, "%d", &tx);
t++;
}
} else {
count++;
}
}
printf("%d\n", count);
while (t++ < n) {
fscanf(fp, "%d", &a);
}
}
return 0;
}
|
/* $FreeBSD$ */
/*
* Copyright (C) 2012 by Darren Reed.
*
* See the IPFILTER.LICENCE file for details on licencing.
*
* $FreeBSD$
* Id: ip_auth.h,v 2.16.2.2 2006/03/16 06:45:49 darrenr Exp $
*
*/
#ifndef __IP_AUTH_H__
#define __IP_AUTH_H__
#define FR_NUMAUTH 32
typedef struct frauth {
int fra_age;
int fra_len;
int fra_index;
u_32_t fra_pass;
fr_info_t fra_info;
char *fra_buf;
u_32_t fra_flx;
#ifdef MENTAT
queue_t *fra_q;
mb_t *fra_m;
#endif
} frauth_t;
typedef struct frauthent {
struct frentry fae_fr;
struct frauthent *fae_next;
struct frauthent **fae_pnext;
u_long fae_age;
int fae_ref;
} frauthent_t;
typedef struct ipf_authstat {
U_QUAD_T fas_hits;
U_QUAD_T fas_miss;
u_long fas_nospace;
u_long fas_added;
u_long fas_sendfail;
u_long fas_sendok;
u_long fas_queok;
u_long fas_quefail;
u_long fas_expire;
frauthent_t *fas_faelist;
} ipf_authstat_t;
extern frentry_t *ipf_auth_check __P((fr_info_t *, u_32_t *));
extern void ipf_auth_expire __P((ipf_main_softc_t *));
extern int ipf_auth_ioctl __P((ipf_main_softc_t *, caddr_t, ioctlcmd_t,
int, int, void *));
extern int ipf_auth_init __P((void));
extern int ipf_auth_main_load __P((void));
extern int ipf_auth_main_unload __P((void));
extern void ipf_auth_soft_destroy __P((ipf_main_softc_t *, void *));
extern void *ipf_auth_soft_create __P((ipf_main_softc_t *));
extern int ipf_auth_new __P((mb_t *, fr_info_t *));
extern int ipf_auth_precmd __P((ipf_main_softc_t *, ioctlcmd_t,
frentry_t *, frentry_t **));
extern void ipf_auth_unload __P((ipf_main_softc_t *));
extern int ipf_auth_waiting __P((ipf_main_softc_t *));
extern void ipf_auth_setlock __P((void *, int));
extern int ipf_auth_soft_init __P((ipf_main_softc_t *, void *));
extern int ipf_auth_soft_fini __P((ipf_main_softc_t *, void *));
extern u_32_t ipf_auth_pre_scanlist __P((ipf_main_softc_t *, fr_info_t *,
u_32_t));
extern frentry_t **ipf_auth_rulehead __P((ipf_main_softc_t *));
#endif /* __IP_AUTH_H__ */
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_64b.c
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-64b.tmpl.c
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: fgets Read data from the console using fgets()
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
* BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
* Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
#define HELLO_STRING "hello"
#ifndef OMITBAD
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_64b_badSink(void * dataVoidPtr)
{
/* cast void pointer to a pointer of the appropriate type */
size_t * dataPtr = (size_t *)dataVoidPtr;
/* dereference dataPtr into data */
size_t data = (*dataPtr);
{
char * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING))
{
myString = (char *)malloc(data*sizeof(char));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_64b_goodG2BSink(void * dataVoidPtr)
{
/* cast void pointer to a pointer of the appropriate type */
size_t * dataPtr = (size_t *)dataVoidPtr;
/* dereference dataPtr into data */
size_t data = (*dataPtr);
{
char * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING))
{
myString = (char *)malloc(data*sizeof(char));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
/* goodB2G uses the BadSource with the GoodSink */
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_64b_goodB2GSink(void * dataVoidPtr)
{
/* cast void pointer to a pointer of the appropriate type */
size_t * dataPtr = (size_t *)dataVoidPtr;
/* dereference dataPtr into data */
size_t data = (*dataPtr);
{
char * myString;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING) && data < 100)
{
myString = (char *)malloc(data*sizeof(char));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
#endif /* OMITGOOD */
|
/* $NetBSD: macho_machdep.c,v 1.2 2001/11/15 07:03:30 lukem Exp $ */
/*-
* Copyright (c) 2001 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christos Zoulas.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: macho_machdep.c,v 1.2 2001/11/15 07:03:30 lukem Exp $");
#include <sys/systm.h>
#include <sys/exec_macho.h>
#ifdef DEBUG_MACHO
#define DPRINTF(a) printf a
#else
#define DPRINTF(a)
#endif
#ifdef DEBUG_MACHO
static void
exec_macho_print_i386_thread_state(struct exec_macho_i386_thread_state *ts) {
printf("ts.eax 0x%x\n", ts->eax);
printf("ts.ebx 0x%x\n", ts->ebx);
printf("ts.ecx 0x%x\n", ts->ecx);
printf("ts.edx 0x%x\n", ts->edx);
printf("ts.edi 0x%x\n", ts->edi);
printf("ts.esi 0x%x\n", ts->esi);
printf("ts.ebp 0x%x\n", ts->ebp);
printf("ts.esp 0x%x\n", ts->esp);
printf("ts.esp 0x%x\n", ts->esp);
printf("ts.ss 0x%x\n", ts->ss);
printf("ts.eflags 0x%x\n", ts->eflags);
printf("ts.eip 0x%x\n", ts->eip);
printf("ts.cs 0x%x\n", ts->cs);
printf("ts.ds 0x%x\n", ts->ds);
printf("ts.es 0x%x\n", ts->es);
printf("ts.fs 0x%x\n", ts->fs);
printf("ts.gs 0x%x\n", ts->gs);
}
static void
exec_macho_print_i386_saved_state(struct exec_macho_i386_saved_state *ts) {
int i;
printf("ts.gs 0x%x\n", ts->gs);
printf("ts.fs 0x%x\n", ts->fs);
printf("ts.es 0x%x\n", ts->es);
printf("ts.ds 0x%x\n", ts->ds);
printf("ts.edi 0x%x\n", ts->edi);
printf("ts.esi 0x%x\n", ts->esi);
printf("ts.ebp 0x%x\n", ts->ebp);
printf("ts.esp 0x%x\n", ts->esp);
printf("ts.ebx 0x%x\n", ts->ebx);
printf("ts.edx 0x%x\n", ts->edx);
printf("ts.ecx 0x%x\n", ts->ecx);
printf("ts.eax 0x%x\n", ts->eax);
printf("ts.trapno 0x%x\n", ts->trapno);
printf("ts.err 0x%x\n", ts->err);
printf("ts.eip 0x%x\n", ts->eip);
printf("ts.cs 0x%x\n", ts->cs);
printf("ts.efl 0x%x\n", ts->efl);
printf("ts.uesp 0x%x\n", ts->uesp);
printf("ts.ss 0x%x\n", ts->ss);
printf("ts.vm86_segs.es 0x%x\n", ts->vm86_segs.es);
printf("ts.vm86_segs.ds 0x%x\n", ts->vm86_segs.ds);
printf("ts.vm86_segs.fs 0x%x\n", ts->vm86_segs.fs);
printf("ts.vm86_segs.gs 0x%x\n", ts->vm86_segs.gs);
printf("ts.argv_status 0x%x\n", ts->argv_status);
for (i = 0; i < MACHO_I386_SAVED_ARGV_COUNT; i++)
printf("ts.argv[%d] 0x%x\n", i, ts->argv[i]);
}
#endif
u_long
exec_macho_thread_entry(struct exec_macho_thread_command *tc) {
switch (tc->flavor) {
case MACHO_I386_THREAD_STATE: {
struct exec_macho_i386_thread_state *ts =
(struct exec_macho_i386_thread_state *)
(void *)((char *)tc + sizeof(*tc));
#ifdef DEBUG_MACHO
exec_macho_print_i386_thread_state(ts);
#endif
return ts->eip;
}
case MACHO_I386_NEW_THREAD_STATE: {
struct exec_macho_i386_saved_state *ts =
(struct exec_macho_i386_saved_state *)
(void *)((char *)tc + sizeof(*tc));
#ifdef DEBUG_MACHO
exec_macho_print_i386_saved_state(ts);
#endif
return ts->eip;
}
default:
DPRINTF(("Unknown thread flavor %ld\n", tc->flavor));
return 0;
}
}
|
/* $NetBSD: keywords.h,v 1.7 2003/07/19 01:36:47 jrf Exp $ */
/* WARNING! This file was generated by keywords.sh */
extern struct keytab {
char *kt_cp;
int kt_i;
} keywords[];
#define K_ADD 1
#define K_ATALK 2
#define K_BLACKHOLE 3
#define K_CHANGE 4
#define K_CLONED 5
#define K_CLONING 6
#define K_DELETE 7
#define K_DST 8
#define K_EXPIRE 9
#define K_FLUSH 10
#define K_GATEWAY 11
#define K_GENMASK 12
#define K_GET 13
#define K_HOST 14
#define K_HOPCOUNT 15
#define K_IFACE 16
#define K_INTERFACE 17
#define K_IFA 18
#define K_IFP 19
#define K_INET 20
#define K_INET6 21
#define K_ISO 22
#define K_LINK 23
#define K_LLINFO 24
#define K_LOCK 25
#define K_LOCKREST 26
#define K_MASK 27
#define K_MONITOR 28
#define K_MTU 29
#define K_NET 30
#define K_NETMASK 31
#define K_NOSTATIC 32
#define K_OSI 33
#define K_PREFIXLEN 34
#define K_PROTO1 35
#define K_PROTO2 36
#define K_RECVPIPE 37
#define K_REJECT 38
#define K_RTT 39
#define K_RTTVAR 40
#define K_SA 41
#define K_SENDPIPE 42
#define K_SHOW 43
#define K_SSTHRESH 44
#define K_STATIC 45
#define K_X25 46
#define K_XNS 47
#define K_XRESOLVE 48
#define K_FLUSHALL 49
|
/*-
* Copyright (c) 2012 Stephan Arts. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY [LICENSOR] "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR 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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_SYS_SYSLOG_H
#include <sys/syslog.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include "error.h"
struct _GuardianError
{
char *msg;
};
GuardianError *
guardian_error_new (
char *format, ... )
{
GuardianError *error = (GuardianError *)malloc(sizeof(GuardianError));
error->msg = (char *)malloc(1024);
va_list arg;
va_start (arg, format);
vsnprintf (error->msg, 1024, format, arg);
va_end (arg);
return error;
}
void
guardian_error_free (
GuardianError *error)
{
if (error->msg)
free (error->msg);
free (error);
}
const char *
guardian_error_get_msg (
GuardianError *error)
{
return error->msg;
}
|
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
double NumberLiteral(const char **in);
#ifdef __cplusplus
}
#endif
|
/*
Crown Copyright 2014 AWE.
This file is part of TyphonIO.
Released under the BSD 3-clause license.
For more details see license.txt
*/
#ifndef _TYPHONIO
#define _TYPHONIO
#include "tio_error.h"
#include "tio_global.h"
#include "tio_access.h"
#include "tio_vargroup.h"
#include "tio_variable.h"
#include "tio_state.h"
#include "tio_mesh.h"
#include "tio_material.h"
#include "tio_quant.h"
#include "tio_chunk.h"
#endif
/*
* EOF
*/
|
#include <assert.h>
#include "hash_fixed.h"
#include "slist.h"
#include "const_mem_pool.h"
#include "miscdata.h"
#include <stdio.h>
#define DECL_FIXED_HASH_STRUCT(name) \
struct name {\
char hash_mem[hash_size];\
struct slist_allocator sa;\
}
struct slist_allocator {
slist *free;
size_t size;
struct const_mem_pool mp;
};
size_t hash_mem_size_fixed(size_t bkt, size_t n, size_t k, size_t v) {
DECL_FIXED_HASH_STRUCT(fixed);
return sizeof(struct fixed)
+ hash_minimal_mem_size(bkt, n, k, v)
- hash_size;
}
static void *__alloc_slist(void *cc, size_t n) {
struct slist_allocator *sa = cc;
if( sa->free && n <= sa->size ) {
void *mem = slist_uncons(&sa->free);
return mem;
} else {
return const_mem_pool_alloc(&sa->mp, MAX(sa->size, n));
}
return 0;
}
static void __dealloc_slist(void *cc, void *mem) {
struct slist_allocator *sa = cc;
sa->free = slist_cons(mem, sa->free);
}
struct hash *hash_create_fixed( size_t size
, void *mem
, size_t keysize
, size_t valsize
, size_t nbuckets
, uint32_t (*hashfun)(void *)
, bool (*keycmp)(void *, void *)
, void (*keycopy)(void *, void *)
, void (*valcopy)(void *, void *) ) {
DECL_FIXED_HASH_STRUCT(fixed_hash);
const size_t fhs = sizeof(struct fixed_hash);
if( size < fhs ) {
return 0;
}
struct fixed_hash *fx = mem;
const size_t ch = MAX(slist_size(0), hash_chunk_size(keysize, valsize));
const size_t mpsize = size - fhs + sizeof(struct const_mem_pool);
if( !const_mem_pool_create(mpsize, &fx->sa.mp) ) {
return 0;
}
fx->sa.size = ch;
fx->sa.free = 0;
struct hash *h = hash_create( sizeof(fx->hash_mem)
, fx->hash_mem
, keysize
, valsize
, nbuckets
, hashfun
, keycmp
, keycopy
, valcopy
, &fx->sa
, __alloc_slist
, __dealloc_slist );
if( !h ) {
return 0;
}
// never rehash fixed hash
hash_set_rehash_values(h, 0, 0);
assert( h == mem );
return h;
}
|
/*
* Copyright (c) 2013, Alexander I. Mykyta
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \addtogroup MOD_EVENT_QUEUE Event Queue
* \brief A simple first-in first-out event handler
* \author Alex Mykyta
*
* <b> Template main.c using the Event Queue </b> \n
*
* \code
* #include <msp430_xc.h>
* #include <event_queue.h>
*
* int main(void){
* WDTCTL = WDTPW + WDTHOLD; // Stop the Watchdog Timer
* __disable_interrupt(); // Disable Interrupts
*
* // Initialize Port IO
* ...
*
* // Initialize the system's clocks
* ...
*
* // Initialize the event handler
* event_init();
*
* // Initialize any modules that generate events
* ...
*
* // Turn on interrupts
* __enable_interrupt();
*
* // Start the event handler
* event_StartHandler();
*
* // Program never reaches this
* return(0);
* }
*
*
* void onIdle(void){
* // onIdle is called when no events occur.
* // To save power, the CPU can be put into a sleep state here.
* }
* \endcode
*
* \ref MOD_EVENT_QUEUE also requires the following modules:
* - \ref MOD_FIFO
*
* \{
**/
/**
* \file
* \brief Include file for \ref MOD_EVENT_QUEUE
* \author Alex Mykyta
**/
#ifndef EVENT_QUEUE_H
#define EVENT_QUEUE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include <result.h>
#include "event_queue.h"
//==================================================================================================
// Functions
//==================================================================================================
/**
* \brief Initializes the event handler's queue
*
* This function \e must be called prior to starting the event handler
**/
void event_init(void);
/**
* \brief Starts the event handler
* \details After initializing the system after a reset and initializing the event module, Call this
* function to start the scheduler. This routine does not return.
*
* \note Global interrupts should be enabled prior to starting the handler
**/
void event_StartHandler(void);
/**
* \brief Schedule a function to be called in the event queue along with related data
* \param [in] fptr Pointer to the function to be called
* \param [in] eventData Pointer to the data to be pushed into the queue (If not used, enter \c NULL)
* \param [in] size Number of bytes to be pushed (if none required, use size of 0)
* \retval RES_OK Event added successfully
* \retval RES_FULL Not enough room in the event queue. Event was not added.
* \details The function to be called must not take any input parameters nor can it return any
* values. If pusing additional data with the event, the event called \e MUST have a matching
* event_PopEventData(). Every additional byte pushed into the event queue \e MUST be popped out
* regardless if it is used or not.
**/
RES_t event_PushEvent(void (*fptr)(void), void *eventData, size_t size);
/**
* \brief Pop event-related data out of the event queue
* \param [in] dst Pointer to where the data will be read into
* \param [in] size Number of bytes to be read
* \details Use this function inside the event function scheduled by event_PushEvent()to retreive any
* related event data that was pushed in using event_PushEventData()
**/
void event_PopEventData(void *dst, size_t size);
/**
* \brief Yields execution of the current event to the next pending event in the queue.
* \details Calling this function allows the next event in the queue to be executed. If no events are
* in the queue or the next event is already active, the onIdle() event is processed.
*
* event_YieldEvent() can be called occasionally when performing a time-consuming operation
* within an event such as a polling loop. Doing so allows other events that may have piled up in
* the meantime to be processed.
*
**/
void event_YieldEvent(void);
//==================================================================================================
// Events
//==================================================================================================
///\name Events
///\{
/**
* \brief Idle process event
* \details This event is called repeatedly when there are no events pending. \n
* \b NOTE: As with any other event, a new event cannot be called until the current one exits.
**/
extern void onIdle(void);
///\}
///\}
/**
* \page EVENT_LIST_PAGE Event Listing
*
* \section SEC_EVENT_QUEUE_EVENTS Event Queue Events
* \{
* onIdle()
* \}
**/
#ifdef __cplusplus
}
#endif
#endif
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_21.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE193.label.xml
Template File: sources-sink-21.tmpl.c
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate memory for a string, but do not allocate space for NULL terminator
* GoodSource: Allocate enough memory for a string and the NULL terminator
* Sink: memcpy
* BadSink : Copy string to data using memcpy()
* Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file.
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING L"AAAAAAAAAA"
#ifndef OMITBAD
/* The static variable below is used to drive control flow in the source function */
static int badStatic = 0;
static wchar_t * badSource(wchar_t * data)
{
if(badStatic)
{
/* FLAW: Did not leave space for a null terminator */
data = (wchar_t *)malloc(10*sizeof(wchar_t));
if (data == NULL) {exit(-1);}
}
return data;
}
void CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_21_bad()
{
wchar_t * data;
data = NULL;
badStatic = 1; /* true */
data = badSource(data);
{
wchar_t source[10+1] = SRC_STRING;
/* Copy length + 1 to include NUL terminator from source */
/* POTENTIAL FLAW: data may not have enough space to hold source */
memcpy(data, source, (wcslen(source) + 1) * sizeof(wchar_t));
printWLine(data);
free(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* The static variables below are used to drive control flow in the source functions. */
static int goodG2B1Static = 0;
static int goodG2B2Static = 0;
/* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */
static wchar_t * goodG2B1Source(wchar_t * data)
{
if(goodG2B1Static)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Allocate space for a null terminator */
data = (wchar_t *)malloc((10+1)*sizeof(wchar_t));
if (data == NULL) {exit(-1);}
}
return data;
}
static void goodG2B1()
{
wchar_t * data;
data = NULL;
goodG2B1Static = 0; /* false */
data = goodG2B1Source(data);
{
wchar_t source[10+1] = SRC_STRING;
/* Copy length + 1 to include NUL terminator from source */
/* POTENTIAL FLAW: data may not have enough space to hold source */
memcpy(data, source, (wcslen(source) + 1) * sizeof(wchar_t));
printWLine(data);
free(data);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */
static wchar_t * goodG2B2Source(wchar_t * data)
{
if(goodG2B2Static)
{
/* FIX: Allocate space for a null terminator */
data = (wchar_t *)malloc((10+1)*sizeof(wchar_t));
if (data == NULL) {exit(-1);}
}
return data;
}
static void goodG2B2()
{
wchar_t * data;
data = NULL;
goodG2B2Static = 1; /* true */
data = goodG2B2Source(data);
{
wchar_t source[10+1] = SRC_STRING;
/* Copy length + 1 to include NUL terminator from source */
/* POTENTIAL FLAW: data may not have enough space to hold source */
memcpy(data, source, (wcslen(source) + 1) * sizeof(wchar_t));
printWLine(data);
free(data);
}
}
void CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_21_good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_21_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_21_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
//
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ProgramNULL.h:
// Defines the class interface for ProgramNULL, implementing ProgramImpl.
//
#ifndef LIBANGLE_RENDERER_NULL_PROGRAMNULL_H_
#define LIBANGLE_RENDERER_NULL_PROGRAMNULL_H_
#include "libANGLE/renderer/ProgramImpl.h"
namespace rx
{
class ProgramNULL : public ProgramImpl
{
public:
ProgramNULL(const gl::ProgramState &state);
~ProgramNULL() override;
gl::LinkResult load(const gl::Context *context,
gl::InfoLog &infoLog,
gl::BinaryInputStream *stream) override;
void save(const gl::Context *context, gl::BinaryOutputStream *stream) override;
void setBinaryRetrievableHint(bool retrievable) override;
void setSeparable(bool separable) override;
gl::LinkResult link(const gl::Context *context,
const gl::VaryingPacking &packing,
gl::InfoLog &infoLog) override;
GLboolean validate(const gl::Caps &caps, gl::InfoLog *infoLog) override;
void setUniform1fv(GLint location, GLsizei count, const GLfloat *v) override;
void setUniform2fv(GLint location, GLsizei count, const GLfloat *v) override;
void setUniform3fv(GLint location, GLsizei count, const GLfloat *v) override;
void setUniform4fv(GLint location, GLsizei count, const GLfloat *v) override;
void setUniform1iv(GLint location, GLsizei count, const GLint *v) override;
void setUniform2iv(GLint location, GLsizei count, const GLint *v) override;
void setUniform3iv(GLint location, GLsizei count, const GLint *v) override;
void setUniform4iv(GLint location, GLsizei count, const GLint *v) override;
void setUniform1uiv(GLint location, GLsizei count, const GLuint *v) override;
void setUniform2uiv(GLint location, GLsizei count, const GLuint *v) override;
void setUniform3uiv(GLint location, GLsizei count, const GLuint *v) override;
void setUniform4uiv(GLint location, GLsizei count, const GLuint *v) override;
void setUniformMatrix2fv(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value) override;
void setUniformMatrix3fv(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value) override;
void setUniformMatrix4fv(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value) override;
void setUniformMatrix2x3fv(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value) override;
void setUniformMatrix3x2fv(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value) override;
void setUniformMatrix2x4fv(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value) override;
void setUniformMatrix4x2fv(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value) override;
void setUniformMatrix3x4fv(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value) override;
void setUniformMatrix4x3fv(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value) override;
// TODO: synchronize in syncState when dirty bits exist.
void setUniformBlockBinding(GLuint uniformBlockIndex, GLuint uniformBlockBinding) override;
// May only be called after a successful link operation.
// Return false for inactive blocks.
bool getUniformBlockSize(const std::string &blockName, size_t *sizeOut) const override;
// May only be called after a successful link operation.
// Returns false for inactive members.
bool getUniformBlockMemberInfo(const std::string &memberUniformName,
sh::BlockMemberInfo *memberInfoOut) const override;
// CHROMIUM_path_rendering
// Set parameters to control fragment shader input variable interpolation
void setPathFragmentInputGen(const std::string &inputName,
GLenum genMode,
GLint components,
const GLfloat *coeffs) override;
};
} // namespace rx
#endif // LIBANGLE_RENDERER_NULL_PROGRAMNULL_H_
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef QUICHE_QUIC_TEST_TOOLS_QUIC_SENT_PACKET_MANAGER_PEER_H_
#define QUICHE_QUIC_TEST_TOOLS_QUIC_SENT_PACKET_MANAGER_PEER_H_
#include "quic/core/quic_packets.h"
#include "quic/core/quic_sent_packet_manager.h"
namespace quic {
class SendAlgorithmInterface;
namespace test {
class QuicSentPacketManagerPeer {
public:
QuicSentPacketManagerPeer() = delete;
static size_t GetMaxTailLossProbes(
QuicSentPacketManager* sent_packet_manager);
static void SetMaxTailLossProbes(QuicSentPacketManager* sent_packet_manager,
size_t max_tail_loss_probes);
static bool GetUseNewRto(QuicSentPacketManager* sent_packet_manager);
static void SetPerspective(QuicSentPacketManager* sent_packet_manager,
Perspective perspective);
static SendAlgorithmInterface* GetSendAlgorithm(
const QuicSentPacketManager& sent_packet_manager);
static void SetSendAlgorithm(QuicSentPacketManager* sent_packet_manager,
SendAlgorithmInterface* send_algorithm);
static const LossDetectionInterface* GetLossAlgorithm(
QuicSentPacketManager* sent_packet_manager);
static void SetLossAlgorithm(QuicSentPacketManager* sent_packet_manager,
LossDetectionInterface* loss_detector);
static RttStats* GetRttStats(QuicSentPacketManager* sent_packet_manager);
// Returns true if |packet_number| is a retransmission of a packet.
static bool IsRetransmission(QuicSentPacketManager* sent_packet_manager,
uint64_t packet_number);
static void MarkForRetransmission(QuicSentPacketManager* sent_packet_manager,
uint64_t packet_number,
TransmissionType transmission_type);
static QuicTime::Delta GetRetransmissionDelay(
const QuicSentPacketManager* sent_packet_manager);
static QuicTime::Delta GetTailLossProbeDelay(
const QuicSentPacketManager* sent_packet_manager);
static size_t GetNumRetransmittablePackets(
const QuicSentPacketManager* sent_packet_manager);
static void SetConsecutiveRtoCount(QuicSentPacketManager* sent_packet_manager,
size_t count);
static void SetConsecutiveTlpCount(QuicSentPacketManager* sent_packet_manager,
size_t count);
static QuicSustainedBandwidthRecorder& GetBandwidthRecorder(
QuicSentPacketManager* sent_packet_manager);
static void SetUsingPacing(QuicSentPacketManager* sent_packet_manager,
bool using_pacing);
static bool UsingPacing(const QuicSentPacketManager* sent_packet_manager);
static bool HasRetransmittableFrames(
QuicSentPacketManager* sent_packet_manager,
uint64_t packet_number);
static QuicUnackedPacketMap* GetUnackedPacketMap(
QuicSentPacketManager* sent_packet_manager);
static void DisablePacerBursts(QuicSentPacketManager* sent_packet_manager);
static int GetPacerInitialBurstSize(
QuicSentPacketManager* sent_packet_manager);
static void SetNextPacedPacketTime(QuicSentPacketManager* sent_packet_manager,
QuicTime time);
static int GetReorderingShift(QuicSentPacketManager* sent_packet_manager);
static bool AdaptiveReorderingThresholdEnabled(
QuicSentPacketManager* sent_packet_manager);
static bool AdaptiveTimeThresholdEnabled(
QuicSentPacketManager* sent_packet_manager);
static bool UsePacketThresholdForRuntPackets(
QuicSentPacketManager* sent_packet_manager);
static int GetNumPtosForPathDegrading(
QuicSentPacketManager* sent_packet_manager);
};
} // namespace test
} // namespace quic
#endif // QUICHE_QUIC_TEST_TOOLS_QUIC_SENT_PACKET_MANAGER_PEER_H_
|
/*
* Copyright (c) 2004, 2005 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Cisco Systems. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* $Id$
*/
#ifndef MTHCA_MEMFREE_H
#define MTHCA_MEMFREE_H
#include <linux/list.h>
#include <linux/pci.h>
#include <linux/mutex.h>
#define MTHCA_ICM_CHUNK_LEN \
((256 - sizeof (struct list_head) - 2 * sizeof (int)) / \
(sizeof (struct scatterlist)))
struct mthca_icm_chunk {
struct list_head list;
int npages;
int nsg;
struct scatterlist mem[MTHCA_ICM_CHUNK_LEN];
};
struct mthca_icm {
struct list_head chunk_list;
int refcount;
};
struct mthca_icm_table {
u64 virt;
int num_icm;
int num_obj;
int obj_size;
int lowmem;
struct mutex mutex;
struct mthca_icm *icm[0];
};
struct mthca_icm_iter {
struct mthca_icm *icm;
struct mthca_icm_chunk *chunk;
int page_idx;
};
struct mthca_dev;
struct mthca_icm *mthca_alloc_icm(struct mthca_dev *dev, int npages,
gfp_t gfp_mask);
void mthca_free_icm(struct mthca_dev *dev, struct mthca_icm *icm);
struct mthca_icm_table *mthca_alloc_icm_table(struct mthca_dev *dev,
u64 virt, int obj_size,
int nobj, int reserved,
int use_lowmem);
void mthca_free_icm_table(struct mthca_dev *dev, struct mthca_icm_table *table);
int mthca_table_get(struct mthca_dev *dev, struct mthca_icm_table *table, int obj);
void mthca_table_put(struct mthca_dev *dev, struct mthca_icm_table *table, int obj);
void *mthca_table_find(struct mthca_icm_table *table, int obj);
int mthca_table_get_range(struct mthca_dev *dev, struct mthca_icm_table *table,
int start, int end);
void mthca_table_put_range(struct mthca_dev *dev, struct mthca_icm_table *table,
int start, int end);
static inline void mthca_icm_first(struct mthca_icm *icm,
struct mthca_icm_iter *iter)
{
iter->icm = icm;
iter->chunk = list_empty(&icm->chunk_list) ?
NULL : list_entry(icm->chunk_list.next,
struct mthca_icm_chunk, list);
iter->page_idx = 0;
}
static inline int mthca_icm_last(struct mthca_icm_iter *iter)
{
return !iter->chunk;
}
static inline void mthca_icm_next(struct mthca_icm_iter *iter)
{
if (++iter->page_idx >= iter->chunk->nsg) {
if (iter->chunk->list.next == &iter->icm->chunk_list) {
iter->chunk = NULL;
return;
}
iter->chunk = list_entry(iter->chunk->list.next,
struct mthca_icm_chunk, list);
iter->page_idx = 0;
}
}
static inline dma_addr_t mthca_icm_addr(struct mthca_icm_iter *iter)
{
return sg_dma_address(&iter->chunk->mem[iter->page_idx]);
}
static inline unsigned long mthca_icm_size(struct mthca_icm_iter *iter)
{
return sg_dma_len(&iter->chunk->mem[iter->page_idx]);
}
enum {
MTHCA_DB_REC_PER_PAGE = 4096 / 8
};
struct mthca_db_page {
DECLARE_BITMAP(used, MTHCA_DB_REC_PER_PAGE);
__be64 *db_rec;
dma_addr_t mapping;
};
struct mthca_db_table {
int npages;
int max_group1;
int min_group2;
struct mthca_db_page *page;
struct mutex mutex;
};
enum mthca_db_type {
MTHCA_DB_TYPE_INVALID = 0x0,
MTHCA_DB_TYPE_CQ_SET_CI = 0x1,
MTHCA_DB_TYPE_CQ_ARM = 0x2,
MTHCA_DB_TYPE_SQ = 0x3,
MTHCA_DB_TYPE_RQ = 0x4,
MTHCA_DB_TYPE_SRQ = 0x5,
MTHCA_DB_TYPE_GROUP_SEP = 0x7
};
struct mthca_user_db_table;
struct mthca_uar;
int mthca_map_user_db(struct mthca_dev *dev, struct mthca_uar *uar,
struct mthca_user_db_table *db_tab, int index, u64 uaddr);
void mthca_unmap_user_db(struct mthca_dev *dev, struct mthca_uar *uar,
struct mthca_user_db_table *db_tab, int index);
struct mthca_user_db_table *mthca_init_user_db_tab(struct mthca_dev *dev);
void mthca_cleanup_user_db_tab(struct mthca_dev *dev, struct mthca_uar *uar,
struct mthca_user_db_table *db_tab);
int mthca_init_db_tab(struct mthca_dev *dev);
void mthca_cleanup_db_tab(struct mthca_dev *dev);
int mthca_alloc_db(struct mthca_dev *dev, enum mthca_db_type type,
u32 qn, __be32 **db);
void mthca_free_db(struct mthca_dev *dev, int type, int db_index);
#endif /* MTHCA_MEMFREE_H */
|
/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
* (C) 2006 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#ifndef MPID_NEM_POST_H
#define MPID_NEM_POST_H
struct MPIDI_PG;
union MPIDI_CH3_Pkt;
/* if local_lmt_pending is true, local_lmt_progress will be called in the
progress loop */
extern int MPID_nem_local_lmt_pending;
extern int (*MPID_nem_local_lmt_progress)(void);
/* FIXME: Do not export these definitions all the way into mpiimpl.h (which
will happen if this is included in mpidpost.h or mpidpre.h) */
int MPID_nem_init(int rank, struct MPIDI_PG *pg_p, int has_parent);
int MPID_nem_finalize(void);
int MPID_nem_barrier_init(MPID_nem_barrier_t *barrier_region, int init_values);
int MPID_nem_barrier(void);
int MPID_nem_vc_init(struct MPIDI_VC *vc);
int MPID_nem_vc_destroy(struct MPIDI_VC *vc);
int MPID_nem_get_business_card(int myRank, char *value, int length);
int MPID_nem_connect_to_root(const char *port_name, struct MPIDI_VC *new_vc);
int MPID_nem_lmt_shm_progress(void);
int MPID_nem_lmt_dma_progress(void);
int MPID_nem_lmt_vmsplice_progress(void);
#ifdef ENABLE_CHECKPOINTING
extern int MPIDI_nem_ckpt_start_checkpoint;
extern int MPIDI_nem_ckpt_finish_checkpoint;
int MPIDI_nem_ckpt_init(void);
int MPIDI_nem_ckpt_finalize(void);
int MPIDI_nem_ckpt_start(void);
int MPIDI_nem_ckpt_finish(void);
int MPIDI_nem_ckpt_pkthandler_init(int (*pktArray[])(struct MPIDI_VC *vc, union MPIDI_CH3_Pkt *pkt,
MPIDI_msg_sz_t *buflen, MPID_Request **req ), int arraySize);
#endif
/* one-sided */
typedef struct MPID_nem_mpich2_win
{
char *handle; /* shared-memory segment handle */
int proc; /* rank of owner */
void *home_address; /* address of window at owner */
int len; /* size of window */
void *local_address; /* address of window at this process */
}
MPID_nem_mpich2_win_t;
int MPID_nem_mpich2_alloc_win (void **buf, int len, MPID_nem_mpich2_win_t **win);
int MPID_nem_mpich2_free_win (MPID_nem_mpich2_win_t *win);
int MPID_nem_mpich2_attach_win (void **buf, MPID_nem_mpich2_win_t *remote_win);
int MPID_nem_mpich2_detach_win (MPID_nem_mpich2_win_t *remote_win);
int MPID_nem_mpich2_serialize_win (void *buf, int buf_len, MPID_nem_mpich2_win_t *win, int *len);
int MPID_nem_mpich2_deserialize_win (void *buf, int buf_len, MPID_nem_mpich2_win_t **win);
int MPID_nem_mpich2_win_put (void *s_buf, void *d_buf, int len, MPID_nem_mpich2_win_t *remote_win);
int MPID_nem_mpich2_win_putv (MPID_IOV **s_iov, int *s_niov, MPID_IOV **d_iov, int *d_niov, MPID_nem_mpich2_win_t *remote_win);
int MPID_nem_mpich2_win_get (void *s_buf, void *d_buf, int len, MPID_nem_mpich2_win_t *remote_win);
int MPID_nem_mpich2_win_getv (MPID_IOV **s_iov, int *s_niov, MPID_IOV **d_iov, int *d_niov, MPID_nem_mpich2_win_t *remote_win);
int MPID_nem_mpich2_register_memory (void *buf, int len);
int MPID_nem_mpich2_deregister_memory (void *buf, int len);
int MPID_nem_mpich2_put (void *s_buf, void *d_buf, int len, int proc, int *completion_ctr);
int MPID_nem_mpich2_putv (MPID_IOV **s_iov, int *s_niov, MPID_IOV **d_iov, int *d_niov, int proc,
int *completion_ctr);
int MPID_nem_mpich2_get (void *s_buf, void *d_buf, int len, int proc, int *completion_ctr);
int MPID_nem_mpich2_getv (MPID_IOV **s_iov, int *s_niov, MPID_IOV **d_iov, int *d_niov, int proc,
int *completion_ctr);
#define MPID_nem_mpich2_win_put_val(val, d_buf, remote_win) do { \
char *_d_buf = d_buf; \
\
_d_buf += (char *)(remote_win)->local_address - (char *)(remote_win)->home_address; \
\
*(typeof (val) *)_d_buf = val; \
} while (0)
#define MPID_nem_mpich2_win_get_val(s_buf, val, remote_win) do { \
char *_s_buf = s_buf; \
\
_s_buf += (char *)(remote_win)->local_address - (char *)(remote_win)->home_address; \
\
*(val) = *(typeof (*(val)) *)_s_buf; \
} while (0)
#if !defined (MPID_NEM_INLINE) || !MPID_NEM_INLINE
int MPID_nem_mpich2_send_header(void* buf, int size, struct MPIDI_VC *vc, int *again);
int MPID_nem_mpich2_sendv(MPID_IOV **iov, int *n_iov, struct MPIDI_VC *vc, int *again);
int MPID_nem_mpich2_sendv_header(MPID_IOV **iov, int *n_iov, struct MPIDI_VC *vc, int *again);
void MPID_nem_mpich2_send_seg(MPID_Segment segment, MPIDI_msg_sz_t *segment_first, MPIDI_msg_sz_t segment_sz, struct MPIDI_VC *vc, int *again);
void MPID_nem_mpich2_send_seg_header(MPID_Segment segment, MPIDI_msg_sz_t *segment_first, MPIDI_msg_sz_t segment_size,
void *header, MPIDI_msg_sz_t header_sz, struct MPIDI_VC *vc, int *again);
int MPID_nem_mpich2_test_recv(MPID_nem_cell_ptr_t *cell, int *in_fbox, int in_blocking_progress);
int MPID_nem_mpich2_test_recv_wait(MPID_nem_cell_ptr_t *cell, int *in_fbox, int timeout);
int MPID_nem_recv_seqno_matches(MPID_nem_queue_ptr_t qhead) ;
int MPID_nem_mpich2_blocking_recv(MPID_nem_cell_ptr_t *cell, int *in_fbox);
int MPID_nem_mpich2_release_cell(MPID_nem_cell_ptr_t cell, struct MPIDI_VC *vc);
int MPID_nem_mpich2_enqueue_fastbox(int local_rank);
int MPID_nem_mpich2_dequeue_fastbox(int local_rank);
#endif /* MPID_NEM_INLINE */
#endif /* MPID_NEM_POST_H */
|
#ifndef messagefacility_MessageLogger_MessageLoggerScribe_h
#define messagefacility_MessageLogger_MessageLoggerScribe_h
#include "cetlib/BasicPluginFactory.h"
#include "cetlib/exempt_ptr.h"
#include "fhiclcpp/ParameterSet.h"
#include "messagefacility/MessageService/ELadministrator.h"
#include "messagefacility/MessageService/ELdestination.h"
#include "messagefacility/MessageService/ELdestConfigCheck.h"
#include "messagefacility/MessageService/ErrorLog.h"
#include "messagefacility/MessageService/MsgContext.h"
#include "messagefacility/MessageService/MessageLoggerQ.h"
#include "messagefacility/MessageService/AbstractMLscribe.h"
#include <iosfwd>
#include <vector>
#include <map>
#include <memory>
namespace mf {
namespace service {
class ThreadQueue;
class ErrorLog;
class MessageLoggerScribe : public AbstractMLscribe {
public:
~MessageLoggerScribe();
/// --- If queue is NULL, this sets singleThread true
explicit MessageLoggerScribe(cet::exempt_ptr<ThreadQueue> queue);
// --- receive and act on messages:
void run();
void runCommand(OpCode opcode, void* operand) override;
private:
// --- log one consumed message
void log(ErrorObj* errorobj_p);
// --- cause statistics destinations to output
void triggerStatisticsSummaries();
void triggerFJRmessageSummary(std::map<std::string, double> & sm);
// --- handle details of configuring via a ParameterSet:
void configure_errorlog();
void configure_fwkJobReports();
void fetchDestinations();
void makeDestinations(fhicl::ParameterSet const& dests,
ELdestConfig::dest_config const config);
// --- util function to trim leading and trailing whitespaces from a string
std::string trim(std::string const& src);
// --- other helpers
void parseCategories(std::string const& s, std::vector<std::string>& cats);
// --- data:
cet::exempt_ptr<ELadministrator> admin_ {ELadministrator::instance()};
std::unique_ptr<fhicl::ParameterSet> jobConfig_ {nullptr};
std::unique_ptr<ErrorLog> errorLog_ {std::make_unique<ErrorLog>()};
ELdestination& earlyDest_;
MsgContext msgContext_;
std::string jobReportOption_ {};
bool cleanSlateConfiguration_ {true};
bool active_ {true};
bool singleThread_;
bool done_ {false};
bool purgeMode_ {false};
int count_ {};
cet::exempt_ptr<ThreadQueue> queue_;
cet::BasicPluginFactory pluginFactory_ {"mfPlugin"};
cet::BasicPluginFactory pluginStatsFactory_ {"mfStatsPlugin"};
std::string createId(std::set<std::string>& existing_ids,
std::string const& type,
std::string const& filename,
fhicl::ParameterSet const& pset = {},
bool const should_throw = true);
bool duplicateDestination(std::string const& output_id,
ELdestConfig::dest_config const config,
bool const should_throw);
std::unique_ptr<ELdestination> makePlugin_(cet::BasicPluginFactory& pluginFactory,
std::string const& libspec,
std::string const& psetname,
fhicl::ParameterSet const& pset);
}; // MessageLoggerScribe
} // end of namespace service
} // namespace mf
#endif /* messagefacility_MessageLogger_MessageLoggerScribe_h */
// Local Variables:
// mode: c++
// End:
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_PRIVATE_WORKING_SET_SNAPSHOT_H_
#define CHROME_BROWSER_PRIVATE_WORKING_SET_SNAPSHOT_H_
#include "build/build_config.h"
#if defined(OS_WIN)
#include <pdh.h>
#include <vector>
#include "base/process/process_handle.h"
#include "base/win/scoped_handle.h"
namespace win {
// The traits class for PDH handles that can be closed via PdhCloseQuery() API.
struct PDHHandleTraits {
typedef PDH_HQUERY Handle;
static PDH_HQUERY NullHandle() { return nullptr; }
static bool IsHandleValid(PDH_HQUERY handle) { return handle != nullptr; }
static bool CloseHandle(PDH_HQUERY handle) {
return (PdhCloseQuery(handle) == ERROR_SUCCESS);
}
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(PDHHandleTraits);
};
// DummyVerifierTraits can be used because PDH_HQUERY is just a typedef for
// HANDLE. However HandleTraits cannot be used because PdhCloseQuery must be
// called rather than CloseHandle to dispose of the resources.
using ScopedPDH =
base::win::GenericScopedHandle<PDHHandleTraits,
base::win::DummyVerifierTraits>;
} // namespace win
// This class can be used to do bulk collection of private working sets. This
// exists because on Windows it is much faster to collect a group of private
// working sets all at once using PdhOpenQuery than to calculate the private
// working sets for each process individually.
class PrivateWorkingSetSnapshot {
public:
PrivateWorkingSetSnapshot();
~PrivateWorkingSetSnapshot();
// Add a process name that this object should monitor, such as "chrome". All
// processes whose name starts with this string will be monitored.
void AddToMonitorList(const std::string& process_name);
// Query the system for working-set information for all monitored processes
// and update the results cache. This function may take a few ms to run.
// The time it takes seems to be independent of the number of processes it
// retrieves data for. This makes it faster than using QueryWorkingSet as soon
// as the process count exceeds two or three.
void Sample();
// Ask for the working set for a specific process, from the most recent call
// to Sample. If no data is available then zero will be returned. The result
// is in bytes.
size_t GetPrivateWorkingSet(base::ProcessId process_id) const;
private:
// This holds a pair of Pdh counters to queries for the process ID and private
// working set for a particular process name being monitored. The results from
// the two queries can be matched up so that we can associate a private
// working set with a process ID.
struct PdhCounterPair {
// These are bound to query_handle_ and will be freed when it is closed.
// The handle to the 'counter' that retrieves process IDs.
PDH_HCOUNTER process_id_handle = nullptr;
// The handle to the 'counter' that retrieves private working sets.
PDH_HCOUNTER private_ws_handle = nullptr;
};
// Struct for storing a process ID and associated private working set.
struct PidAndPrivateWorkingSet {
base::ProcessId process_id;
size_t private_ws;
// Comparison function for sorting by process ID.
bool operator<(const PidAndPrivateWorkingSet& other) const {
// private_ws is intentionally *not* part of the comparison because it is
// the payload and process_id is the key.
return process_id < other.process_id;
}
// Comparison function for searching by process ID.
bool operator<(const base::ProcessId other_process_id) const {
return process_id < other_process_id;
}
};
// The handle to the query object.
win::ScopedPDH query_handle_;
// A PdhCounterPair for each successful AddToMonitorList call.
std::vector<PdhCounterPair> counter_pairs_;
// After each call to Sample this will hold the results, sorted by process id.
std::vector<PidAndPrivateWorkingSet> records_;
DISALLOW_COPY_AND_ASSIGN(PrivateWorkingSetSnapshot);
};
#endif // defined(OS_WIN)
#endif // CHROME_BROWSER_PRIVATE_WORKING_SET_SNAPSHOT_H_
|
/*---- license ----*/
/*-------------------------------------------------------------------------
Coco.ATG -- Attributed Grammar
Compiler Generator Coco/R,
Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz
extended by M. Loeberbauer & A. Woess, Univ. of Linz
with improvements by Pat Terry, Rhodes University.
ported to C by Charles Wang <charlesw123456@gmail.com>
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, 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 General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As an exception, it is allowed to write an extension of Coco/R that is
used as a plugin in non-free software.
If not otherwise stated, any source code generated by Coco/R (other than
Coco/R itself) does not fall under the GNU General Public License.
-------------------------------------------------------------------------*/
/*---- enable ----*/
#ifndef COCO_CcsXmlParser_H
#define COCO_CcsXmlParser_H
#ifndef COCO_ERRORPOOL_H
#include "c/ErrorPool.h"
#endif
#ifndef COCO_CcsXmlScanner_H
#include "Scanner.h"
#endif
/*---- hIncludes ----*/
#ifndef COCO_GLOBALS_H
#include "Globals.h"
#endif
/*---- enable ----*/
EXTC_BEGIN
/*---- SynDefines ----*/
#define CcsXmlParser_USE_StartOf
#define CcsXmlParser_USE_ExpectWeak
#define CcsXmlParser_USE_WeakSeparator
/*---- enable ----*/
typedef struct CcsXmlParser_s CcsXmlParser_t;
struct CcsXmlParser_s {
CcsErrorPool_t errpool;
CcsXmlScanner_t scanner;
CcsToken_t * t;
CcsToken_t * la;
int maxT;
/*---- members ----*/
CcGlobals_t globals;
/* Shortcut pointers */
CcSymbolTable_t * symtab;
CcXmlSpecMap_t * xmlspecmap;
CcSyntax_t * syntax;
/*---- enable ----*/
};
CcsXmlParser_t * CcsXmlParser(CcsXmlParser_t * self, FILE * infp, FILE * errfp);
CcsXmlParser_t *
CcsXmlParser_ByName(CcsXmlParser_t * self, const char * infn, FILE * errfp);
void CcsXmlParser_Destruct(CcsXmlParser_t * self);
void CcsXmlParser_Parse(CcsXmlParser_t * self);
void CcsXmlParser_SemErr(CcsXmlParser_t * self, const CcsToken_t * token,
const char * format, ...);
void CcsXmlParser_SemErrT(CcsXmlParser_t * self, const char * format, ...);
EXTC_END
#endif /* COCO_PARSER_H */
|
/**
******************************************************************************
* @file stm32f0xx_it.c
* @author MCD Application Team
* @version V1.0.0
* @date 23-March-2012
* @brief Main Interrupt Service Routines.
* This file provides template for all exceptions handler and
* peripherals interrupt service routine.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_it.h"
#include "main.h"
/** @addtogroup STM32F0-Discovery_Demo
* @{
*/
/** @addtogroup STM32F0XX_IT
* @brief Interrupts driver modules
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/******************************************************************************/
/* Cortex-M0 Processor Exceptions Handlers */
/******************************************************************************/
/**
* @brief This function handles NMI exception.
* @param None
* @retval None
*/
void NMI_Handler(void)
{
}
/**
* @brief This function handles Hard Fault exception.
* @param None
* @retval None
*/
void HardFault_Handler(void)
{
/* Go to infinite loop when Hard Fault exception occurs */
while (1)
{
}
}
/******************************************************************************/
/* STM32F0xx Peripherals Interrupt Handlers */
/* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */
/* available peripheral interrupt handler's name please refer to the startup */
/* file (startup_stm32f0xx.s). */
/******************************************************************************/
/**
* @brief This function handles PPP interrupt request.
* @param None
* @retval None
*/
/*void PPP_IRQHandler(void)
{
}*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_PUBLIC_TEST_JAVASCRIPT_TEST_OBSERVER_H_
#define CONTENT_PUBLIC_TEST_JAVASCRIPT_TEST_OBSERVER_H_
#include <string>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
namespace content {
class WebContents;
// Base class for handling a stream of automation messages produced by a
// JavascriptTestObserver.
class TestMessageHandler {
public:
enum MessageResponse {
// Reset the timeout and keep running.
CONTINUE,
// Stop running.
DONE
};
TestMessageHandler();
virtual ~TestMessageHandler();
// Called when a message is received from the DOM automation controller.
virtual MessageResponse HandleMessage(const std::string& json) = 0;
void SetError(const std::string& message);
bool ok() const {
return ok_;
}
const std::string& error_message() const {
return error_message_;
}
// Prepare the handler to be used or reused.
virtual void Reset();
private:
bool ok_;
std::string error_message_;
};
// This class captures a stream of automation messages coming from a Javascript
// test and dispatches them to a message handler.
class JavascriptTestObserver : public NotificationObserver {
public:
// The observer does not own any arguments passed to it. It is assumed that
// the arguments will outlive all uses of the observer.
JavascriptTestObserver(WebContents* web_contents,
TestMessageHandler* handler);
JavascriptTestObserver(const JavascriptTestObserver&) = delete;
JavascriptTestObserver& operator=(const JavascriptTestObserver&) = delete;
~JavascriptTestObserver() override;
// Pump the message loop until the message handler indicates the Javascript
// test is done running. Return true if the test jig functioned correctly and
// nothing timed out.
bool Run();
// Prepare the observer to be used again. This method should NOT be called
// while Run() is pumping the message loop.
void Reset();
void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) override;
private:
// This message did not signal the end of a test, keep going.
void Continue();
// This was the last message we care about, stop listening for more messages.
void EndTest();
TestMessageHandler* handler_;
bool running_;
bool finished_;
NotificationRegistrar registrar_;
};
} // namespace content
#endif // CONTENT_PUBLIC_TEST_JAVASCRIPT_TEST_OBSERVER_H_
|
/*ckwg +29
* Copyright 2014-2016 by Kitware, Inc.
* 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.
*
* * Neither name of Kitware, Inc. nor the names of any contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS 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.
*/
/**
* \file
* \brief Header defining the vxl \link maptk::vxl::close_loops_homography_guided
* close_loops \endlink algorithm
*/
#ifndef MAPTK_PLUGINS_VXL_CLOSE_LOOPS_HOMOGRAPHY_GUIDED_H_
#define MAPTK_PLUGINS_VXL_CLOSE_LOOPS_HOMOGRAPHY_GUIDED_H_
#include <vital/vital_config.h>
#include <maptk/plugins/vxl/maptk_vxl_export.h>
#include <vital/types/image_container.h>
#include <vital/types/track_set.h>
#include <vital/algo/close_loops.h>
#include <memory>
namespace kwiver {
namespace maptk {
namespace vxl
{
/// Attempts to stitch tracks over a long period of time.
/**
* This class attempts to make longer-term loop closures by utilizing a
* variety of techniques, one of which involves using homographies to
* estimate potential match locations in the past, followed up by additional
* filtering.
*/
class MAPTK_VXL_EXPORT close_loops_homography_guided
: public vital::algorithm_impl<vxl::close_loops_homography_guided, vital::algo::close_loops>
{
public:
/// Default Constructor
close_loops_homography_guided();
/// Copy Constructor
close_loops_homography_guided( const close_loops_homography_guided& );
/// Destructor
virtual ~close_loops_homography_guided();
/// Return the name of this implementation
virtual std::string impl_name() const { return "vxl_homography_guided"; }
/// Get this algorithm's \link vital::config_block configuration block \endlink
/**
* This base virtual function implementation returns an empty configuration
* block whose name is set to \c this->type_name.
*
* \returns \c vital::config_block containing the configuration for this algorithm
* and any nested components.
*/
virtual vital::config_block_sptr get_configuration() const;
/// Set this algorithm's properties via a config block
/**
* \throws no_such_configuration_value_exception
* Thrown if an expected configuration value is not present.
* \throws algorithm_configuration_exception
* Thrown when the algorithm is given an invalid \c vital::config_block or is'
* otherwise unable to configure itself.
*
* \param config The \c vital::config_block instance containing the configuration
* parameters for this algorithm
*/
virtual void set_configuration( vital::config_block_sptr config );
/// Check that the algorithm's currently configuration is valid
/**
* This checks solely within the provided \c vital::config_block and not against
* the current state of the instance. This isn't static for inheritence
* reasons.
*
* \param config The config block to check configuration of.
*
* \returns true if the configuration check passed and false if it didn't.
*/
virtual bool check_configuration( vital::config_block_sptr config ) const;
/// Perform loop closure operation.
/**
* \param frame_number the frame number of the current frame
* \param input the input track set to stitch
* \param image image data for the current frame
* \param mask Optional mask image where positive values indicate
* regions to consider in the input image.
* \returns an updated set a tracks after the stitching operation
*/
virtual vital::track_set_sptr
stitch( vital::frame_id_t frame_number,
vital::track_set_sptr input,
vital::image_container_sptr image,
vital::image_container_sptr mask = vital::image_container_sptr() ) const;
private:
/// Class for storing other internal variables
class priv;
const std::unique_ptr<priv> d_;
};
} // end namespace vxl
} // end namespace maptk
} // end namespace kwiver
#endif // MAPTK_PLUGINS_VXL_CLOSE_LOOPS_HOMOGRAPHY_GUIDED_H_
|
/* $NetBSD: softintr.h,v 1.2 2004/03/25 18:46:27 matt Exp $ */
/*-
* Copyright (c) 2004 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Matt Thomas <matt@3am-software.com>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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 __POWERPC_SOFTINTR_H_
#define __POWERPC_SOFTINTR_H_
#ifdef _KERNEL
#include <sys/queue.h>
/*
* Override the standard schednetisr and have one softintr per netisr.
* Note that this allows for eventually doing dynamic registration of netisr's.
*/
struct softintr;
extern struct softintr *softnet_handlers[];
#define schednetisr(an_isr) softintr_schedule(softnet_handlers[(an_isr)])
void *softintr_establish(int, void (*)(void *), void *);
void softintr_disestablish(void *);
void softintr_schedule(void *);
/*
* These are *not* part of API.
*/
void softintr__init(void); /* initialize the softintr framework */
void softintr__run(int); /* run the softintr list for an IPL */
#endif
#endif /* __POWERPC_SOFTINTR_H_ */
|
#ifndef MANIFOLD_MCPCACHE_COH_MEM_REQ_H
#define MANIFOLD_MCPCACHE_COH_MEM_REQ_H
#include "cache_types.h"
#include "cache_req.h" //for paddr_t
#include <iostream>
namespace manifold {
namespace mcp_cache_namespace {
//! message sent to memory controller
struct Mem_msg {
enum {MEM_REQ, MEM_RPLY};
char type;
paddr_t addr;
mem_optype_t op_type;
int src_id;
int src_port;
int dst_id;
int dst_port;
uint64_t get_addr() { return addr; }
bool is_read() { return op_type == OpMemLd; }
int get_src() { return src_id; }
void set_src(int s) { src_id = s; }
void set_src_port(int s) { src_port = s; }
void set_dst(int d) { dst_id = d; }
void set_dst_port(int d) { dst_port = d; }
void set_mem_response() { type = MEM_RPLY; }
//cache_msg_t msg;
//int resolve_time;
};
//! directory-based coherence protocol message
struct Coh_msg {
enum {COH_REQ, COH_RPLY};
char type;
paddr_t addr;
int forward_id; //directory may ask client to forward
int msg; //msg type
int rw; // 0 for read; 1 for write
int src_id;
int src_port;
int dst_id;
int dst_port;
};
#if 0
class Coh_mem_req {
public:
enum {MEM_REQ=0, MEM_RPLY, COH_REQ, COH_RPLY};
int type;
int source_id;
int source_port;
int dest_id;
int dest_port;
paddr_t addr;
union {
struct Mem_req mem;
struct Coh_msg coh;
} u;
Coh_mem_req() {} //for deserialization
//Coh_mem_req (int rid, int sid, paddr_t addr, mem_optype_t op_type, cache_msg_t msg);
~Coh_mem_req () {}
int get_src() { return source_id; }
void set_src(int src) { source_id = src; }
int get_src_port() { return source_port; }
void set_src_port(int sport) { source_port = sport; }
int get_dst() { return dest_id; }
void set_dst(int dst) { dest_id = dst; }
int get_dst_port() { return dest_port; }
void set_dst_port(int dport) { dest_port = dport; }
paddr_t get_addr() { return addr; }
bool is_read()
{
if(type == MEM_REQ || type == MEM_RPLY)
return u.mem.op_type == OpMemLd;
else
return u.coh.rw == 0;
}
//Allows memory controller to set the type.
void set_mem_response()
{
type = MEM_RPLY;
}
int get_simulated_len()
{
switch(type) {
case MEM_REQ:
if(u.mem.op_type == OpMemLd)
return 48; //32B addr + 16B overhead
else
return 80; //32B addr + 32B data + 16B overhead
break;
case MEM_RPLY:
return 80; //32B addr + 32B data + 16B overhead
break;
case COH_REQ:
case COH_RPLY:
//Improvements: different message can have different length.
return 34; //32B data + 2B overhead
default:
assert(0);
break;
}
}
//friend std::ostream& operator<<(std::ostream& stream, const mem_req& mreq);
};
#endif
} //namespace mcp_cache_namespace
} //namespace manifold
#endif //MANIFOLD_MCPCACHE_COH_MEM_REQ_H
|
/*
Copyright (c) 2013-2014 Dong Fang. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include <xio/sp.h>
#include "sp_module.h"
int sp_close (int eid)
{
struct epbase *ep = eid_get (eid);
if (!ep) {
ERRNO_RETURN (EBADF);
}
mutex_lock (&ep->lock);
ep->status.shutdown = true;
if (ep->snd.waiters || ep->rcv.waiters)
condition_broadcast (&ep->cond);
mutex_unlock (&ep->lock);
eid_put (eid);
eid_put (eid);
return 0;
}
|
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkScalarContext_win_dw_DEFINED
#define SkScalarContext_win_dw_DEFINED
#include "SkScalar.h"
#include "SkScalerContext.h"
#include "SkTypeface_win_dw.h"
#include "SkTypes.h"
#include <dwrite.h>
#include <dwrite_2.h>
class SkGlyph;
class SkDescriptor;
class SkScalerContext_DW : public SkScalerContext {
public:
SkScalerContext_DW(sk_sp<DWriteFontTypeface>,
const SkScalerContextEffects&,
const SkDescriptor*);
~SkScalerContext_DW() override;
protected:
unsigned generateGlyphCount() override;
bool generateAdvance(SkGlyph* glyph) override;
void generateMetrics(SkGlyph* glyph) override;
void generateImage(const SkGlyph& glyph) override;
bool generatePath(SkGlyphID glyph, SkPath* path) override;
void generateFontMetrics(SkFontMetrics*) override;
private:
const void* drawDWMask(const SkGlyph& glyph,
DWRITE_RENDERING_MODE renderingMode,
DWRITE_TEXTURE_TYPE textureType);
HRESULT getBoundingBox(SkGlyph* glyph,
DWRITE_RENDERING_MODE renderingMode,
DWRITE_TEXTURE_TYPE textureType,
RECT* bbox);
bool isColorGlyph(const SkGlyph& glyph);
bool isPngGlyph(const SkGlyph& glyph);
DWriteFontTypeface* getDWriteTypeface() {
return static_cast<DWriteFontTypeface*>(this->getTypeface());
}
bool getColorGlyphRun(const SkGlyph& glyph, IDWriteColorGlyphRunEnumerator** colorGlyph);
void generateColorMetrics(SkGlyph* glyph);
void generateColorGlyphImage(const SkGlyph& glyph);
void generatePngMetrics(SkGlyph* glyph);
void generatePngGlyphImage(const SkGlyph& glyph);
SkTDArray<uint8_t> fBits;
/** The total matrix without the text height scale. */
SkMatrix fSkXform;
/** The total matrix without the text height scale. */
DWRITE_MATRIX fXform;
/** The text size to render with. */
SkScalar fTextSizeRender;
/** The text size to measure with. */
SkScalar fTextSizeMeasure;
int fGlyphCount;
DWRITE_RENDERING_MODE fRenderingMode;
DWRITE_TEXTURE_TYPE fTextureType;
DWRITE_MEASURING_MODE fMeasuringMode;
DWRITE_TEXT_ANTIALIAS_MODE fAntiAliasMode;
DWRITE_GRID_FIT_MODE fGridFitMode;
bool fIsColorFont;
};
#endif
|
//==========================================================================
// semaphore.h
// Author: Juan Castillo, David Quijano
// Date: lun dic 3 2007
// Description:
//==========================================================================
// The following code is derived, directly or indirectly, from SCoPE,
// released June 30, 2008. Copyright (C) 2006 Design of Systems on Silicon (DS2)
// The Initial Developer of the Original Code is the University of Cantabria
// for Design of Systems on Silicon (DS2)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License (GPL) or GNU Lesser General Public License(LGPL) 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 General Public License (GPL) or GNU Lesser General Public License(LGPL) for more details.
//
// You should have received a copy of the GNU General Public License (GPL) or GNU Lesser General Public License(LGPL)
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// For more information about SCOPE you can visit
// http://www.teisa.unican.es/scope or write an e-mail to
// scope@teisa.unican.es or a letter to SCoPE, GIM - TEISA, University
// of Cantabria, AV. Los Castros s/n, ETSIIT, 39005, Santander, Spain
//==========================================================================
#include_next <semaphore.h>
#include "../../scope/rtos/api/posix/uc_semaphore.h"
|
//
// Debugger.h
// Openbiz-RestModel
//
// Created by Jixian Wang on 14/12/21.
// Copyright (c) 2014年 openbiz. All rights reserved.
//
#ifndef __Openbiz_RestModel__Debugger__
#define __Openbiz_RestModel__Debugger__
#include <stdio.h>
namespace openbiz
{
class Debugger
{
public:
static void setDebugNetworkEnabled();
static const bool isDebugNetworkEnabled();
typedef enum {
DebugInsertOperation,
DebugUpdateOperation,
DebugDeleteOperation,
DebugFetchOperation,
} DatabaseDebugOption;
typedef struct {
bool DebugInsertOperation = false;
bool DebugUpdateOperation = false;
bool DebugDeleteOperation = false;
bool DebugFetchOperation = false;
} DatabaseDebugOptions;
static void setDebugDatabaseEnabled(DatabaseDebugOption);
static const DatabaseDebugOptions* getDebugDatabaseOption();
private:
static bool _debugNetworkState;
static DatabaseDebugOptions _debugDatabaseOptions;
};
}
#endif /* defined(__Openbiz_RestModel__Debugger__) */
|
#pragma INPUT memReq16_128_t
#pragma OUTPUT memRep128_t
#pragma OFFLOAD (lPipe, uint32_t, uint32_t)
#pragma OFFLOAD (data, memReq16_128_t, memRep128_t)
GS_MEMOP()
{
memReq16_128_t dramReq;
memRep128_t dramRep;
dramReq = Input;
dramRep = data(dramReq);
Output = dramRep;
State = GS_DELAY;
}
GS_DELAY()
{
uint32_t lPipeReq, lPipeRep;
lPipeReq = Input.addr;
lPipeRep = lPipe(lPipeReq);
finish();
}
|
#include <stdlib.h>
int main(int argc, char **argv) {
int x;
float r = argc;
if (0 > r) {
x = 7;
}
else {
x = 42;
}
return x;
}
|
#include "rs_tester_fec.h"
void rs_fec_encode(void *encoder, uint8_t *msg, size_t msg_length,
uint8_t *msg_out) {
// XXX make sure that pad length used to build encoder corresponds to this
// msg_length
memcpy(msg_out, msg, msg_length);
encode_rs_char(encoder, msg_out, msg_out + msg_length);
}
void rs_fec_decode(void *decoder, uint8_t *encoded, size_t encoded_length,
uint8_t *erasure_locations, size_t erasure_length,
uint8_t *msg, size_t pad_length, size_t num_roots) {
// XXX make sure that pad length used to build decoder corresponds to this
// encoded_length
if (erasure_length) {
static size_t locations_len = 0;
static int *locations = NULL;
if (locations_len < erasure_length) {
locations = realloc(locations, erasure_length * sizeof(int));
locations_len = erasure_length;
}
for (size_t i = 0; i < erasure_length; i++) {
locations[i] = (unsigned int)(erasure_locations[i]) + pad_length;
}
decode_rs_char(decoder, encoded, locations, erasure_length);
} else {
decode_rs_char(decoder, encoded, NULL, 0);
}
memcpy(msg, encoded, encoded_length - num_roots);
}
|
/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
* (C) 2007 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include "mpi.h"
#include <stdio.h>
#include <string.h>
#include "mpitest.h"
/* Check that Communicators can be created from various subsets of the
processes in the communicator.
*/
void abortMsg( const char *, int );
int BuildComm( MPI_Comm, MPI_Group, const char [] );
void abortMsg( const char *str, int code )
{
char msg[MPI_MAX_ERROR_STRING];
int class, resultLen;
MPI_Error_class( code, &class );
MPI_Error_string( code, msg, &resultLen );
fprintf( stderr, "%s: errcode = %d, class = %d, msg = %s\n",
str, code, class, msg );
MPI_Abort( MPI_COMM_WORLD, code );
}
int main( int argc, char *argv[] )
{
MPI_Comm dupWorld;
int wrank, wsize, gsize, err, errs = 0;
int ranges[1][3];
MPI_Group wGroup, godd, ghigh, geven;
MTest_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &wsize );
MPI_Comm_rank( MPI_COMM_WORLD, &wrank );
/* Create some groups */
MPI_Comm_group( MPI_COMM_WORLD, &wGroup );
MTestPrintfMsg( 2, "Creating groups\n" );
ranges[0][0] = 2*(wsize/2)-1;
ranges[0][1] = 1;
ranges[0][2] = -2;
err = MPI_Group_range_incl( wGroup, 1, ranges, &godd );
if (err) abortMsg( "Failed to create odd group: ", err );
err = MPI_Group_size( godd, &gsize );
if (err) abortMsg( "Failed to get size of odd group: ", err );
if (gsize != wsize/2) {
fprintf( stderr, "Group godd size is %d should be %d\n", gsize,
wsize/2 );
errs++;
}
ranges[0][0] = wsize/2+1;
ranges[0][1] = wsize-1;
ranges[0][2] = 1;
err = MPI_Group_range_incl( wGroup, 1, ranges, &ghigh );
if (err) abortMsg( "Failed to create high group\n", err );
ranges[0][0] = 0;
ranges[0][1] = wsize-1;
ranges[0][2] = 2;
err = MPI_Group_range_incl( wGroup, 1, ranges, &geven );
if (err) abortMsg( "Failed to create even group:", err );
MPI_Comm_dup( MPI_COMM_WORLD, &dupWorld );
MPI_Comm_set_name( dupWorld, (char*)"Dup of world" );
/* First, use the groups to create communicators from world and a dup
of world */
errs += BuildComm( MPI_COMM_WORLD, ghigh, "ghigh" );
errs += BuildComm( MPI_COMM_WORLD, godd, "godd" );
errs += BuildComm( MPI_COMM_WORLD, geven, "geven" );
errs += BuildComm( dupWorld, ghigh, "ghigh" );
errs += BuildComm( dupWorld, godd, "godd" );
errs += BuildComm( dupWorld, geven, "geven" );
#if MTEST_HAVE_MIN_MPI_VERSION(2,2)
/* check that we can create multiple communicators from a single collective
* call to MPI_Comm_create as long as the groups are all disjoint */
errs += BuildComm( MPI_COMM_WORLD, (wrank % 2 ? godd : geven), "godd+geven" );
errs += BuildComm( dupWorld, (wrank % 2 ? godd : geven), "godd+geven" );
errs += BuildComm( MPI_COMM_WORLD, MPI_GROUP_EMPTY, "MPI_GROUP_EMPTY" );
errs += BuildComm( dupWorld, MPI_GROUP_EMPTY, "MPI_GROUP_EMPTY" );
#endif
MPI_Comm_free( &dupWorld );
MPI_Group_free( &ghigh );
MPI_Group_free( &godd );
MPI_Group_free( &geven );
MPI_Group_free( &wGroup );
MTest_Finalize( errs );
MPI_Finalize();
return 0;
}
int BuildComm( MPI_Comm oldcomm, MPI_Group group, const char gname[] )
{
MPI_Comm newcomm;
int grank, gsize, rank, size, errs = 0;
char cname[MPI_MAX_OBJECT_NAME+1];
int cnamelen;
MPI_Group_rank( group, &grank );
MPI_Group_size( group, &gsize );
MPI_Comm_get_name( oldcomm, cname, &cnamelen );
MTestPrintfMsg( 2, "Testing comm %s from %s\n", cname, gname );
MPI_Comm_create( oldcomm, group, &newcomm );
if (newcomm == MPI_COMM_NULL && grank != MPI_UNDEFINED) {
errs ++;
fprintf( stderr, "newcomm is null but process is in group\n" );
}
if (newcomm != MPI_COMM_NULL && grank == MPI_UNDEFINED) {
errs ++;
fprintf( stderr, "newcomm is not null but process is not in group\n" );
}
if (newcomm != MPI_COMM_NULL && grank != MPI_UNDEFINED) {
MPI_Comm_rank( newcomm, &rank );
if (rank != grank) {
errs ++;
fprintf( stderr, "Rank is %d should be %d in comm from %s\n",
rank, grank, gname );
}
MPI_Comm_size( newcomm, &size );
if (size != gsize) {
errs++;
fprintf( stderr, "Size is %d should be %d in comm from %s\n",
size, gsize, gname );
}
MPI_Comm_free( &newcomm );
MTestPrintfMsg( 2, "Done testing comm %s from %s\n", cname, gname );
}
return errs;
}
|
/*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
#include <e32def.h>
#include <e32std.h>
/**
* This class encapsulates the parsing of the lines of a pkglist file.
*/
class TPkgParser
{
public:
/**
* Default constructor. The selected language is set to KNullDesC.
*/
TPkgParser();
/**
* This constructor sets the selected language. Lines that has a
* language tag that doesn't match the selected language will be
* skipped.
* @param aIsoLang a string that will be compared against all
* language tags.
*/
TPkgParser(const TDesC& aIsoLang);
/**
* Parses a line to a packagelist.
* @param aFileList the list to add CFileObjects to if the
* line is a file line.
* @param aLine The line to be parsed.
* @param aTotalDataSize return parameter that will hold the value
* of the totalsize value if it is parsed.
* @return 1 if the line was successfully parsed, 0 if not.
*/
TInt ParseLineL(class CFileObjectHolder* &aFileList,
char* aLine,
TUint32& aTotalDataSize);
/**
* Parses a data line according to the version in iVersion.
* The parsed data is entered into the CFileObjectHolder argument.
* @param aFileList target container for parsed data.
* @param aLine the line to parse.
* @return 1 if the line was succesfully parsed, 0 if not.
*/
TInt ParseDataLineL(class CFileObjectHolder* &aFileList,
char* aLine);
static TUint Version();
private:
TInt32 iVersion;
TUint32 iTotalDataSize;
TBuf<32> iSelectedLang;
};
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef MITKLEGACYFILEREADERSERVICE_H
#define MITKLEGACYFILEREADERSERVICE_H
#include <mitkAbstractFileReader.h>
namespace mitk
{
// This class wraps mitk::FileReader instances registered as
// "mitkIOAdapter" via the ITK object factory system as a
// micro service.
class LegacyFileReaderService : public mitk::AbstractFileReader
{
public:
LegacyFileReaderService(const LegacyFileReaderService &other);
LegacyFileReaderService(const std::vector<std::string> &extensions, const std::string &category);
~LegacyFileReaderService() override;
using AbstractFileReader::Read;
protected:
std::vector<itk::SmartPointer<BaseData>> DoRead() override;
private:
LegacyFileReaderService *Clone() const override;
us::ServiceRegistration<mitk::IFileReader> m_ServiceReg;
};
} // namespace mitk
#endif /* MITKLEGACYFILEREADERSERVICE_H */
|
#pragma once
#include "IAsyncThreadPage.h"
#include "ListenerArgs.h"
#include "IListenerContext.h"
#include "ClientArgs.h"
#include "IClientContext.h"
namespace OpenThreadTalk
{
class Factory
{
public:
static IListenerContext^ CreateListenerContext(IAsyncThreadPage^, ListenerArgs^);
static IClientContext^ CreateClientContext(IAsyncThreadPage^, ClientArgs^);
};
}
|
#ifndef CLASSDEF_MESSAGE
#define CLASSDEF_MESSAGE
#include "Common.h"
struct Msg
{
char *line;
struct Msg *next, *prev;
};
class Message
{
private:
int fontsize;
int x, y, w, h;
int maxmessage, nowmessage, beginmessage;
struct Msg *msg, *read, *last;
// ¡Éüé¶AcÉüé¶B
int mw, mh;
virtual struct Msg * AddMessage( char *message );
int viewtime, viewtimer;
int filenum;
int autoread;
public:
Message( void );
virtual ~Message( void );
virtual int Init( void );
virtual int Term( void );
virtual int Release( void );
virtual int SetMessageFormat( char *format, ... );
virtual int SetMessage( char *message ); // bNªKvB
virtual int SetArea( int dx, int dy, int width, int height );
virtual int Draw( void ); // bNªKvB
};
#endif
|
/*
** estimate false discovery rate based on histograms
** input histograms are generated by "vted"
**
** Ref: Lohmann et al (2016) PLoS One, 11(6):e0158185
**
** G.Lohmann, MPI-KYB, Jan 2015
*/
#include <viaio/VImage.h>
#include <viaio/Vlib.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_math.h>
#define SQR(x) ((x)*(x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
#define HMIN 0
#define HMAX 1.001
#define NBINS 10000
size_t CountLines(FILE *fp)
{
char ch;
size_t numlines=0;
while(!feof(fp)) {
ch = fgetc(fp);
if(ch == '\n') {
numlines++;
}
}
rewind(fp);
return numlines;
}
void ReadTxtHist(char *filename,gsl_histogram *hist)
{
FILE *fp=fopen(filename,"r");
if (!fp) VError("err opening %s",filename);
size_t nbins = CountLines(fp);
if (nbins != (size_t)NBINS)
VError(" inconsistent bins: %lu",gsl_histogram_bins (hist));
size_t i=0;
double lower=0,hz=0,mx=0;
for (i=0; i<nbins; i++) {
if (fscanf(fp,"%lf %lf %lf",&lower,&hz,&mx) != 3) VError(" read error");
if (lower < HMIN || lower >= HMAX) VError(" value out of histogram range: %f",lower);
hist->bin[i] = mx;
}
fclose(fp);
}
int main(int argc, char *argv[])
{
static VString realfilename = "";
static VString nullfilename = "";
static VString outfilename = "";
static VFloat alpha = 0.05;
static VOptionDescRec options[] = {
{"real",VStringRepn,1,(VPointer) &realfilename,VRequiredOpt,NULL,"input real histogram file"},
{"null",VStringRepn,1,(VPointer) &nullfilename,VRequiredOpt,NULL,"input null histogram file"},
{"out",VStringRepn,1,(VPointer) &outfilename,VRequiredOpt,NULL,"output txt file"},
{"alpha",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,"alpha level"},
};
double lower=0,upper=0,tiny=1.0e-8;
long i;
VParseFilterCmd(VNumber(options),options,argc,argv,NULL,NULL);
gsl_set_error_handler_off();
/* ini histogram structs */
size_t nbins = NBINS;
double hmin = HMIN,hmax = HMAX;
gsl_histogram *realhist = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (realhist,hmin,hmax);
gsl_histogram *nullhist = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (nullhist,hmin,hmax);
/* read input histograms */
ReadTxtHist(realfilename,realhist);
ReadTxtHist(nullfilename,nullhist);
/* cumulative distribution functions */
gsl_histogram_pdf *cdfz = gsl_histogram_pdf_alloc(nbins);
gsl_histogram_pdf *cdf0 = gsl_histogram_pdf_alloc(nbins);
gsl_histogram_pdf_init (cdfz,realhist);
gsl_histogram_pdf_init (cdf0,nullhist);
FILE *fp = fopen(outfilename,"w");
if (!fp) VError(" err opening file %s",outfilename);
fprintf(fp,"# ted F0 Fz FDR \n");
fprintf(fp,"#------------------------------------------------------\n");
/* tail-area FDR */
double cutoff=0;
int flag = 0;
for (i=0; i<nbins; i++) {
gsl_histogram_get_range (realhist,i,&lower,&upper);
double z = lower + 0.5*(upper-lower);
double Fz = 1.0-cdfz->sum[i];
double F0 = 1.0-cdf0->sum[i];
double Fdr = 0.0;
if (Fz > tiny) Fdr = F0/Fz;
if (Fdr > 1.0) Fdr = 1.0;
if (Fdr < 0.0) Fdr = 0.0;
if (Fdr < alpha && flag == 0 && i > 10) {
flag = 1;
cutoff = z;
}
fprintf(fp," %12.8f %12.8f %12.8f %12.8f\n",z,F0,Fz,Fdr);
}
fprintf(fp,"# Fdr < %.3f if ted > %lf\n",alpha,cutoff);
fprintf(stderr," Fdr < %.3f if ted > %lf\n",alpha,cutoff);
fclose(fp);
exit(0);
}
|
/*****************************************************************************
Copyright (c) 2010, Intel Corp.
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.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************
* Contents: Native high-level C interface to LAPACK function stprfb
* Author: Intel Corporation
* Generated November, 2011
*****************************************************************************/
#include "lapacke.h"
#include "lapacke_utils.h"
lapack_int LAPACKE_stprfb( int matrix_order, char side, char trans, char direct,
char storev, lapack_int m, lapack_int n,
lapack_int k, lapack_int l, const float* v,
lapack_int ldv, const float* t, lapack_int ldt,
float* a, lapack_int lda, float* b, lapack_int ldb,
lapack_int myldwork )
{
lapack_int info = 0;
float* mywork = NULL;
if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_stprfb", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
/* Optionally check input matrices for NaNs */
if( LAPACKE_sge_nancheck( matrix_order, k, m, a, lda ) ) {
return -14;
}
if( LAPACKE_sge_nancheck( matrix_order, m, n, b, ldb ) ) {
return -16;
}
if( LAPACKE_sge_nancheck( matrix_order, ldt, k, t, ldt ) ) {
return -12;
}
if( LAPACKE_sge_nancheck( matrix_order, ldv, k, v, ldv ) ) {
return -10;
}
#endif
/* Allocate memory for working array(s) */
mywork = (float*)
LAPACKE_malloc( sizeof(float) * MAX(1,myldwork) * MAX(1,k) );
if( mywork == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
/* Call middle-level interface */
info = LAPACKE_stprfb_work( matrix_order, side, trans, direct, storev, m, n,
k, l, v, ldv, t, ldt, a, lda, b, ldb, mywork,
myldwork );
/* Release memory and exit */
LAPACKE_free( mywork );
exit_level_0:
if( info == LAPACK_WORK_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_stprfb", info );
}
return info;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.