text stringlengths 4 6.14k |
|---|
/**
* @file RelaxationCalculator.h
*
* This file declares the CRelaxationCalculator class.
*/
#ifndef RELAXATIONCALCULATOR_H_
#define RELAXATIONCALCULATOR_H_
/**
* The CRelaxationCalculator class is used to determine the relaxation state that conserves k/(psi*psi)
* In addition, this relaxed state may feature a current neutralisation layer and/or a potential envelope.
* A further possibility is that the relaxed state may feature helical modes.
*/
class CRelaxationCalculator {
public:
CRelaxationCalculator(double _psi, double _psi_r, double _consrv, double _consrv_r, CRelaxedLoop& _rx);
/// empty default destructor
~CRelaxationCalculator(void) {}
double consrv_err(double _a);
private:
/// the axial flux that is conserved
double psi;
/// the radial range of the axial flux that is conserved
double psi_r;
/// the value k/(psi*psi) that is conserved by the relaxed loop
double consrv;
/// the radial range (0-_consrv_r) over which k/(psi*psi) is conserved
double consrv_r;
/// the relaxed loop
CRelaxedLoop rx;
}; // end of CRelaxationCalculator class declaration
#endif /* RELAXATIONCALCULATOR_H_ */
|
/*Daala video codec
Copyright (c) 2003-2010 Daala project contributors. 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 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.*/
#if !defined(_filter_H)
# define _filter_H (1)
# include "internal.h"
typedef int32_t od_coeff;
# define OD_COEFF_BITS (32)
/*There are 4 filter sizes total (4-point, 8-point, 16-point and 32-point).*/
# define OD_NFILTER_SIZES (4)
/*This is the strength reduced version of ((_a)/(1 << (_b))).
This will not work for _b == 0, however currently this is only used for
b == 1 anyway.*/
# define OD_UNBIASED_RSHIFT32(_a, _b) \
(((int32_t)(((uint32_t)(_a) >> (32 - (_b))) + (_a))) >> (_b))
# define OD_DCT_RSHIFT(_a, _b) OD_UNBIASED_RSHIFT32(_a, _b)
typedef void (*od_filter_func)(od_coeff _out[], const od_coeff _in[]);
extern const od_filter_func OD_PRE_FILTER[OD_NBSIZES];
extern const od_filter_func OD_POST_FILTER[OD_NBSIZES];
/*These are the pre/post filtering functions used by Daala.
The idea is to pre/post filter in the spatial domain (the time domain in
signal processing terms) to improve the energy compaction as well as reduce
or eliminate blocking artifacts.*/
extern const int OD_FILTER_PARAMS4[4];
extern const int OD_FILTER_PARAMS8[10];
extern const int OD_FILTER_PARAMS16[22];
extern const int OD_FILTER_PARAMS32[46];
void od_pre_filter4(od_coeff _y[4], const od_coeff _x[4]);
void od_post_filter4(od_coeff _x[4], const od_coeff _y[4]);
void od_pre_filter8(od_coeff _y[8], const od_coeff _x[8]);
void od_post_filter8(od_coeff _x[8], const od_coeff _y[8]);
void od_pre_filter16(od_coeff _y[16], const od_coeff _x[16]);
void od_post_filter16(od_coeff _x[16], const od_coeff _y[16]);
void od_pre_filter32(od_coeff _y[32], const od_coeff _x[32]);
void od_post_filter32(od_coeff _x[32], const od_coeff _y[32]);
void od_apply_prefilter_frame(od_coeff *c, int w, int nhsb, int nvsb,
const unsigned char *bsize, int bstride, int dec);
void od_apply_postfilter_frame(od_coeff *c, int w, int nhsb, int nvsb,
const unsigned char *bsize, int bstride, int dec);
/* The length in pixel of the lapping of a block is
4 << OD_FILT_SIZE(ln, xdec). Right now, we use 4-point lapping for
all block sizes and for all planes.
If this macro is changed, the values in od_basis_mag have to be
regenerated.*/
#define OD_FILT_SIZE(ln, xdec) (0)
extern const int OD_FILT_SIZE[OD_NBSIZES];
void od_clpf(od_coeff *y, int ystride, od_coeff *x, int xstride, int ln,
int sbx, int sby, int nhsb, int nvsb);
void od_bilinear_smooth(od_coeff *x, int ln, int stride, int q, int pli);
void od_prefilter_split(od_coeff *c0, int stride, int bs, int f);
void od_postfilter_split(od_coeff *c0, int stride, int bs, int f);
void od_apply_prefilter_frame_sbs(od_coeff *c, int stride, int nhsb, int nvsb,
int xdec, int ydec);
void od_apply_postfilter_frame_sbs(od_coeff *c, int stride, int nhsb, int nvsb,
int xdec, int ydec);
void od_apply_filter_sb_rows(od_coeff *c, int stride, int nhsb, int nvsb,
int xdec, int ydec, int inv, int bs);
void od_apply_filter_sb_cols(od_coeff *c, int stride, int nhsb, int nvsb,
int xdec, int ydec, int inv, int bs);
void od_apply_filter_hsplit(od_coeff *c0, int stride, int inv, int bs, int f);
void od_apply_filter_vsplit(od_coeff *c0, int stride, int inv, int bs, int f);
# if defined(OD_DCT_TEST) && defined(OD_DCT_CHECK_OVERFLOW)
# include <stdio.h>
extern int od_dct_check_min[];
extern int od_dct_check_max[];
# define OD_DCT_OVERFLOW_CHECK(val, scale, offset, idx) \
do { \
od_dct_check_min[(idx)] = OD_MINI(od_dct_check_min[(idx)], val); \
od_dct_check_max[(idx)] = OD_MAXI(od_dct_check_max[(idx)], val); \
OD_ASSERT((offset) >= 0); \
if ((scale) > 0) { \
if ((val) < INT_MIN/(scale)) { \
printf("Overflow %2i: 0x%08X*0x%08X < INT_MIN\n", \
(idx), (val), (scale)); \
} \
if ((val) > (INT_MAX - (offset))/(scale)) { \
printf("Overflow %2i: 0x%08X*0x%04X + 0x%04X > INT_MAX\n", \
(idx), (val), (scale), (offset)); \
} \
} \
else if ((scale) < 0) { \
if ((val) > (INT_MIN)/(scale)) { \
printf("Overflow %2i: 0x%08X*-0x%04X < INT_MIN\n", \
(idx), (val), (scale)); \
} \
if ((val) < (INT_MAX - (offset))/(scale)) { \
printf("Overflow %2i: 0x%08X*-0x%08X + 0x%04X > INT_MAX\n", \
(idx), (val), (scale), (offset)); \
} \
} \
} \
while(0)
# else
# define OD_DCT_OVERFLOW_CHECK(val, scale, offset, idx)
# endif
#endif
|
/**
* @file
*
* @date Oct 7, 2013
* @author: Anton Bondarev
*/
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <kernel/thread.h>
#include <kernel/task.h>
#include <mem/sysmalloc.h>
#include <kernel/thread/sync/mutex.h>
#include <kernel/task/thread_key_table.h>
#include <kernel/task/resource/thread_key_table.h>
#include <kernel/thread/thread_local.h>
int thread_local_alloc(struct thread *t, size_t size) {
void * storage;
size_t storage_size;
storage_size = size * sizeof(t->local.storage[0]);
storage = sysmalloc(storage_size);
if (NULL == storage) {
return -ENOMEM;
}
memset(storage, 0, storage_size);
t->local.storage = storage;
t->local.size = size;
return ENOERR;
}
int thread_local_free(struct thread *t) {
sysfree(t->local.storage);
return ENOERR;
}
void *thread_local_get(struct thread *t, size_t idx) {
void *res;
struct thread_key_table *kt;
assert(t);
if (idx >= t->local.size) {
return NULL;
}
kt = task_resource_thread_key_table(t->task);
mutex_lock(&kt->mutex);
{
if (task_thread_key_exist(t->task, idx)) {
res = t->local.storage[idx];
} else {
res = NULL;
}
}
mutex_unlock(&kt->mutex);
return res;
}
int thread_local_set(struct thread *t, size_t idx, void *value) {
int res = ENOERR;
struct thread_key_table *kt;
assert(t);
if (idx >= t->local.size) {
return -EINVAL;
}
kt = task_resource_thread_key_table(t->task);
mutex_lock(&kt->mutex);
{
if (task_thread_key_exist(t->task, idx)) {
t->local.storage[idx] = value;
} else {
res = -EINVAL;
}
}
mutex_unlock(&kt->mutex);
return res;
}
|
/************************************************************************
\link www.twinklingstar.cn
\author Twinkling Star
\date 2013/11/22
****************************************************************************/
#ifndef SR_FOUNDATION_SRDEQUE_H_
#define SR_FOUNDATION_SRDEQUE_H_
#include <stdio.h>
/** \addtogroup foundation
@{
*/
/**
\brief The Node of Double Circular List.
This class provides with a basic template of the node of double circular list.
It's recommended that allocating memory by using "new" or "malloc" and deallocating
memory by using "delete" or "free" is not appreciated.Instead, please use the method of
createObject() to create an object and destroy() to free. Copy constructor easily gives rise
to exception,especially when pointers are used as the member viriables. If you want to apply
this class to other purposes, just override the method createObject() and destroy()
according to the actual conditions.
*/
class SrDCircularNode
{
public:
/**
\brief return the next node of this one.
*/
SrDCircularNode* getNextNode()
{
return nextNode;
}
/**
\brief return the last node of this one.
*/
SrDCircularNode* getLastNode()
{
return lastNode;
}
/**
\brief If you want to initialize a double circular list, the first node should be set.
\param[in] node It must be first node of your double circular list.
*/
static void initialize(SrDCircularNode* node)
{
node->nextNode = node;
node->lastNode = node;
}
/**
\brief Erase the node from the list.
\param[in] node The node erased from the list,but the memory isn't deallocated.
\return false The node is the last one in the list.
*/
static bool erase(SrDCircularNode* node)
{
if( node->nextNode==node )
return false;
SrDCircularNode* last = node->lastNode;
last->nextNode = node->nextNode;
SrDCircularNode* next = node->nextNode;
next->lastNode = node->lastNode;
return true;
}
/**
\brief Create a SrDCircularNode node.
*/
static SrDCircularNode* createObject(){ return new SrDCircularNode();}
/**
\brief Insert a node after this one.
\param[in] node It's the inserted node.
*/
bool insertBefore(SrDCircularNode* node)
{
if( lastNode==nextNode && lastNode==NULL )
return false;
node->lastNode = lastNode;
node->nextNode = this;
lastNode->nextNode = node;
lastNode = node;
return true;
}
/**
\brief Insert a node before this one.
\param[in] node It's the inserted node.
*/
bool insertAfter(SrDCircularNode* node)
{
if( lastNode==nextNode && lastNode==NULL )
return false;
node->lastNode = this;
node->nextNode = nextNode;
nextNode->lastNode = node;
nextNode = node;
return true;
}
/**
\brief Destroy the memory of this node.
*/
virtual void destroy(){ delete this;}
protected:
SrDCircularNode* lastNode,*nextNode;
SrDCircularNode(SrDCircularNode&);
SrDCircularNode()
{
nextNode = this;
lastNode = this;
}
};
/** @} */
#endif
|
/******************************************************************************
This source file is part of the MoleQueue project.
Copyright 2012 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 COMPOSITEIODEVICE_H_
#define COMPOSITEIODEVICE_H_
#include <QtCore/QIODevice>
#include <QtCore/QQueue>
namespace MoleQueue {
namespace Uit {
/**
* @class CompositeIODevice compositeiodevice.h
* <molequeue/queue/uit/compositeiodevice.h>
* @brief The CompositeIODevice class is facade that allows several QIODevices
* into a single QIODevice.
*
*/
class CompositeIODevice: public QIODevice
{
Q_OBJECT
public:
CompositeIODevice(QObject *parentObject = 0);
/**
* Add a QIODevice to the device. The QIODevice being added must be open in
* read mode.
*
* @param device The QIODevice to add.
*/
bool addDevice(QIODevice *device);
/**
* @return The combine size of all the QIODevices this composite represents.
*/
qint64 size () const;
protected:
/**
* Override superclass with composite read.
*/
qint64 readData(char* data, qint64 maxSize);
/**
* Override superclass, write is not supported.
*/
qint64 writeData ( const char * data, qint64 maxSize );
private:
/// The list of QIODevices in the composite.
QList<QIODevice *> m_devices;
/// The index of the QIODevice currently being read.
int m_deviceIndex;
};
} /* namespace Uit */
} /* namespace MoleQueue */
#endif /* COMPOSITEIODEVICE_H_ */
|
/*
* CCLayerPanZoom
*
* Copyright (c) 2011 Alexey Lang
* Copyright (c) 2011 Pavel Guganov
*
* http://www.cocos2d-x.org
*
* 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 "cocos2d.h"
USING_NS_CC;
#define kCCLayerPanZoomMultitouchGesturesDetectionDelay 0.5
#ifndef INFINITY
#ifdef _MSC_VER
union MSVC_EVIL_FLOAT_HACK
{
unsigned __int8 Bytes[4];
float Value;
};
static union MSVC_EVIL_FLOAT_HACK INFINITY_HACK = {{0x00, 0x00, 0x80, 0x7F}};
#define INFINITY (INFINITY_HACK.Value)
#endif
#ifdef __GNUC__
#define INFINITY (__builtin_inf())
#endif
#ifndef INFINITY
#define INFINITY (1e1000)
#endif
#endif
typedef enum
{
/** Standard mode: swipe to scroll */
kCCLayerPanZoomModeSheet,
/** Frame mode (i.e. drag inside objects): hold finger at edge of the screen to the sroll in this direction */
kCCLayerPanZoomModeFrame
} CCLayerPanZoomMode;
typedef enum
{
kCCLayerPanZoomFrameEdgeNone,
kCCLayerPanZoomFrameEdgeTop,
kCCLayerPanZoomFrameEdgeBottom,
kCCLayerPanZoomFrameEdgeLeft,
kCCLayerPanZoomFrameEdgeRight,
kCCLayerPanZoomFrameEdgeTopLeft,
kCCLayerPanZoomFrameEdgeBottomLeft,
kCCLayerPanZoomFrameEdgeTopRight,
kCCLayerPanZoomFrameEdgeBottomRight
} CCLayerPanZoomFrameEdge;
class CCLayerPanZoom : public cocos2d::CCLayer
{
public:
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommend to return the exactly class pointer
static CCLayerPanZoom* layer();
// implement the "static node()" method manually
CREATE_FUNC(CCLayerPanZoom);
void setMaxScale(float maxScale);
float maxScale();
void setMinScale(float minScale);
float minScale();
void setRubberEffectRatio(float rubberEffectRatio);
float rubberEffectRatio();
//ToDo add delegate
CC_SYNTHESIZE(float, _maxTouchDistanceToClick, maxTouchDistanceToClick);
CC_SYNTHESIZE(CCArray*, _touches, touches);
CC_SYNTHESIZE(float, _touchDistance, touchDistance);
CC_SYNTHESIZE(float, _minSpeed, minSpeed);
CC_SYNTHESIZE(float, _maxSpeed, maxSpeed);
CC_SYNTHESIZE(float, _topFrameMargin, topFrameMargin);
CC_SYNTHESIZE(float, _bottomFrameMargin, bottomFrameMargin);
CC_SYNTHESIZE(float, _leftFrameMargin, leftFrameMargin);
CC_SYNTHESIZE(float, _rightFrameMargin, rightFrameMargin);
CC_SYNTHESIZE(CCScheduler*, _scheduler, scheduler);
CC_SYNTHESIZE(float, _rubberEffectRecoveryTime, rubberEffectRecoveryTime);
CCRect _panBoundsRect;
float _maxScale;
float _minScale;
CCLayerPanZoomMode _mode;
CCPoint _prevSingleTouchPositionInLayer;
//< previous position in layer if single touch was moved.
// Time when single touch has began, used to wait for possible multitouch
// gestures before reacting to single touch.
double _singleTouchTimestamp;
// Flag used to call touchMoveBeganAtPosition: only once for each single touch event.
bool _touchMoveBegan;
float _rubberEffectRatio;
bool _rubberEffectRecovering;
bool _rubberEffectZooming;
//CCStandartTouchDelegate
void ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);
void ccTouchesMoved(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);
void ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);
void ccTouchesCancelled(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);
// Updates position in frame mode.
virtual void update(float dt);
void onEnter();
void onExit();
//Scale and Position related
void setPanBoundsRect(CCRect rect);
void setPosition(CCPoint position);
void setScale(float scale);
//Ruber Edges related
void recoverPositionAndScale();
void recoverEnded();
//Helpers
float topEdgeDistance();
float leftEdgeDistance();
float bottomEdgeDistance();
float rightEdgeDistance();
float minPossibleScale();
CCLayerPanZoomFrameEdge frameEdgeWithPoint( cocos2d::CCPoint point);
float horSpeedWithPosition(CCPoint pos);
float vertSpeedWithPosition(CCPoint pos);
}; |
/*
Copyright (C) 1998, 1999, 2001, 2002 Jérôme Lecomte
This file is part of XLW, a free-software/open-source C++ wrapper of the
Excel C API - http://xlw.sourceforge.net/
XLW is free software: you can redistribute it and/or modify it under the
terms of the XLW license. You should have received a copy of the
license along with this program; if not, please email xlw-users@lists.sf.net
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 license for more details.
*/
#ifndef INC_XlfRef_H
#define INC_XlfRef_H
/*!
\file XlfRef.h
\brief Declares the XlfRef class.
*/
// $Id$
#include <xlw/EXCEL32_API.h>
#include <xlw/xlcall32.h>
#if defined(_MSC_VER)
#pragma once
#endif
// Forward declaration.
//! Wrapper around XLOPER Excel data type.
class EXCEL32_API XlfOper;
//! Encapsulate a range of cells.
/*!
A range is actually a reference to a range of cells in the spreadsheet.
This range is stored as an absolute reference even if you can access
the elements relatively to the upper left corner of the range (starting
at 0 to number of row/column minus 1).
The dtor, copy ctor and assignment otor are generated by the compiler.
\note The Excel API is limited to the first 256 columns. This class holds
a reference to a single range in a single spreadsheet. It is intended to
be a helper class to refer range through XlfOper.
\note It is currently not possible for XlfRef to handle union of range
in the same way other Excel function can. This feature remains to be
implemented.
*/
class EXCEL32_API XlfRef
{
public:
//! Default ctor.
XlfRef();
//! Absolute reference ctor.
XlfRef(WORD top, BYTE left, WORD bottom, BYTE right, DWORD sheetId = 0);
//! Absolute reference ctor, to a single cell.
XlfRef(WORD row, BYTE col, DWORD sheetId = 0);
//! Gets the first row of the range (0 based).
WORD GetRowBegin() const;
//! Gets passed the last row of the range (0 based).
WORD GetRowEnd() const;
//! Gets the first column of the range (0 based).
BYTE GetColBegin() const;
//! Gets passed the last column of the range (0 based).
BYTE GetColEnd() const;
//! Gets the number of columns.
BYTE GetNbCols() const;
//! Gets the number of rows.
WORD GetNbRows() const;
//! Gets MS Excel sheet identifier of the range.
DWORD GetSheetId() const;
//! Sets the first row of the range.
void SetRowBegin(WORD rowbegin);
//! Sets passed the last row of the range.
void SetRowEnd(WORD rowend);
//! Sets the first column of the range.
void SetColBegin(BYTE colbegin);
//! Sets passed the last column of the range.
void SetColEnd(BYTE colend);
//! Sets MS Excel sheet identifier of the range.
void SetSheetId(DWORD);
//! Access operator
XlfOper operator()(WORD relativerow, BYTE relativecol) const;
private:
//! Index of the top row of the range reference.
WORD rowbegin_;
//! Index of one past the last row of the range reference.
WORD rowend_;
//! Index of the left most column of the range reference.
BYTE colbegin_;
//! Index of one past the right most column of the range reference.
BYTE colend_;
//! Index of the sheet the reference is pointing to.
DWORD sheetId_;
};
#ifdef NDEBUG
#include <xlw/XlfRef.inl>
#endif
#endif |
/*
NSFNanoGlobals_Private.h
NanoStore
Copyright (c) 2010 Webbo, L.L.C. 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 Webbo 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. */
#import <Foundation/Foundation.h>
#import "NSFNanoGlobals.h"
/** \cond */
/*
The following types are supported by Property Lists:
CFArray
CFDictionary
CFData
CFString
CFDate
CFNumber
CFBoolean
Since NanoStore associates an attribute with an atomic value (i.e. non-collection),
the following data types are recognized:
CFData
CFString
CFDate
CFNumber
Note: there isn't a dedicated data type homologous to CFBoolean in Cocoa. Therefore,
NSNumber will be used for that purpose.
*/
extern NSString * NSFStringFromMatchType (NSFMatchType aMatchType);
extern void _NSFLog (NSString *format, ...);
extern NSString * const NSFVersionKey;
extern NSString * const NSFDomainKey;
extern NSString * const NSFKeys;
extern NSString * const NSFValues;
extern NSString * const NSFKey;
extern NSString * const NSFValue;
extern NSString * const NSFDatatype;
extern NSString * const NSFCalendarDate;
extern NSString * const NSFObjectClass;
extern NSString * const NSFPlist;
extern NSString * const NSFAttribute;
extern NSString * const NSF_Private_NSFKeys_NSFKey;
extern NSString * const NSF_Private_NSFKeys_NSFPlist;
extern NSString * const NSF_Private_NSFValues_NSFKey;
extern NSString * const NSF_Private_NSFValues_NSFAttribute;
extern NSString * const NSF_Private_NSFValues_NSFValue;
extern NSString * const NSF_Private_NSFNanoBag_Name;
extern NSString * const NSF_Private_NSFNanoBag_NSFKey;
extern NSString * const NSF_Private_NSFNanoBag_NSFObjectKeys;
extern NSString * const NSF_Private_ToDeleteTableKey;
extern NSInteger const NSF_Private_InvalidParameterDataCodeKey;
extern NSInteger const NSF_Private_MacOSXErrorCodeKey;
extern NSString * const NSFP_TableIdentifier;
extern NSString * const NSFP_ColumnIdentifier;
extern NSString * const NSFP_DatatypeIdentifier;
extern NSString * const NSFP_FullDatatypeIdentifier;
extern NSString * const NSFRowIDColumnName; // SQLite's standard UID property
extern NSString * const NSFP_SchemaTable; // Private, reserved NSF table name to store datatypes
/** \endcond */ |
// Copyright (c) 2016, Mirego
// 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 Mirego 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.
#import "UIView+MCLayout.h"
|
/* $Header: /cvsroot/wikipedia/willow/src/bin/willow/daemon.c,v 1.1 2005/05/02 19:15:21 kateturner Exp $ */
/* $NetBSD: daemon.c,v 1.9 2003/08/07 16:42:46 agc Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. 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. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*/
#if defined __SUNPRO_C || defined __DECC || defined __HP_cc
# pragma ident "@(#)$Header: /cvsroot/wikipedia/willow/src/bin/willow/daemon.c,v 1.1 2005/05/02 19:15:21 kateturner Exp $"
# pragma ident "$NetBSD: daemon.c,v 1.9 2003/08/07 16:42:46 agc Exp $"
#endif
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int
daemon(nochdir, noclose)
int nochdir, noclose;
{
int fd;
switch (fork()) {
case -1:
return (-1);
case 0:
break;
default:
_exit(0);
}
if (setsid() == -1)
return (-1);
if (!nochdir)
(void)chdir("/");
if (!noclose && (fd = open("/dev/null", O_RDWR, 0)) != -1) {
(void)dup2(fd, STDIN_FILENO);
(void)dup2(fd, STDOUT_FILENO);
(void)dup2(fd, STDERR_FILENO);
if (fd > STDERR_FILENO)
(void)close(fd);
}
return (0);
}
|
#ifndef SEASTEST_H_
#define SEASTEST_H_
#include "unitroot.h"
#ifdef __cplusplus
extern "C" {
#endif
void decompose(double *x,int N, int f,double *filter, const char *type, double *trend, int *ltrend, double *seas, int *lseas, double *random, int *lrandom);
double* genLags(double *y, int N, int maxLags, int *rows, int *cols);
reg_object fitOCSB(double *x, int N, int f, int lag, int mlags);
void OCSBtest(double *x, int N, int f, int mlags, const char *method,double *statistics,double *critical);
void stl(double *x,int N,int f, const char *s_window_type,int *s_window, int *s_degree, int *t_window, int *t_degree,int *l_window,int *l_degree,
int *s_jump, int *t_jump, int *l_jump, int *robust,int *inner, int *outer,double *seasonal,double *trend, double *remainder);
void modstl(double *x, int N, int f, int *s_window,double *lambda, double *seasonal, double *trend,double *remainder);
void mstl(double *x, int N, int *f, int *Nseas, int *s_window,double *lambda,int *iterate, double **seasonal, double *trend,double *remainder);
void SHtest(double *x, int N, int *f, int Nseas, double *season);
double* seasdummy(double *x, int N,int f,int *rows, int *cols);
#ifdef __cplusplus
}
#endif
#endif /* SEASTEST_H_ */ |
// Copyright 2018 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 COMPONENTS_ENTERPRISE_BROWSER_CONTROLLER_CHROME_BROWSER_CLOUD_MANAGEMENT_HELPER_H_
#define COMPONENTS_ENTERPRISE_BROWSER_CONTROLLER_CHROME_BROWSER_CLOUD_MANAGEMENT_HELPER_H_
#include <memory>
#include <string>
#include "base/callback_forward.h"
#include "base/memory/scoped_refptr.h"
#include "components/enterprise/browser/controller/browser_dm_token_storage.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/cloud_policy_service.h"
class PrefService;
namespace network {
class SharedURLLoaderFactory;
}
namespace policy {
class ClientDataDelegate;
class CloudPolicyClient;
class CloudPolicyClientRegistrationHelper;
class MachineLevelUserCloudPolicyManager;
class DeviceManagementService;
// A helper class that register device with the enrollment token and client id.
class ChromeBrowserCloudManagementRegistrar {
public:
ChromeBrowserCloudManagementRegistrar(
DeviceManagementService* device_management_service,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory);
ChromeBrowserCloudManagementRegistrar(
const ChromeBrowserCloudManagementRegistrar&) = delete;
ChromeBrowserCloudManagementRegistrar& operator=(
const ChromeBrowserCloudManagementRegistrar&) = delete;
~ChromeBrowserCloudManagementRegistrar();
// The callback invoked once policy registration is complete. Passed
// |dm_token| and |client_id| parameters are empty if policy registration
// failed.
using CloudManagementRegistrationCallback =
base::OnceCallback<void(const std::string& dm_token,
const std::string& client_id)>;
// Registers a CloudPolicyClient for fetching machine level user policy.
void RegisterForCloudManagementWithEnrollmentToken(
const std::string& enrollment_token,
const std::string& client_id,
const ClientDataDelegate& client_data_delegate,
CloudManagementRegistrationCallback callback);
private:
void CallCloudManagementRegistrationCallback(
std::unique_ptr<CloudPolicyClient> client,
CloudManagementRegistrationCallback callback);
std::unique_ptr<CloudPolicyClientRegistrationHelper> registration_helper_;
DeviceManagementService* device_management_service_;
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
};
// A helper class that setup registration and fetch policy.
class MachineLevelUserCloudPolicyFetcher : public CloudPolicyService::Observer {
public:
MachineLevelUserCloudPolicyFetcher(
MachineLevelUserCloudPolicyManager* policy_manager,
PrefService* local_state,
DeviceManagementService* device_management_service,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory);
MachineLevelUserCloudPolicyFetcher(
const MachineLevelUserCloudPolicyFetcher&) = delete;
MachineLevelUserCloudPolicyFetcher& operator=(
const MachineLevelUserCloudPolicyFetcher&) = delete;
~MachineLevelUserCloudPolicyFetcher() override;
// Initialize the cloud policy client and policy store then fetch
// the policy based on the |dm_token|. It should be called only once.
void SetupRegistrationAndFetchPolicy(const DMToken& dm_token,
const std::string& client_id);
// Add or remove |observer| to/from the CloudPolicyClient embedded in
// |policy_manager_|.
void AddClientObserver(CloudPolicyClient::Observer* observer);
void RemoveClientObserver(CloudPolicyClient::Observer* observer);
// Shuts down |policy_manager_| (removes and stops refreshing the cached cloud
// policy).
void Disconnect();
// CloudPolicyService::Observer:
void OnCloudPolicyServiceInitializationCompleted() override;
private:
void InitializeManager(std::unique_ptr<CloudPolicyClient> client);
// Fetch policy if device is enrolled.
void TryToFetchPolicy();
MachineLevelUserCloudPolicyManager* policy_manager_;
PrefService* local_state_;
DeviceManagementService* device_management_service_;
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
};
} // namespace policy
#endif // COMPONENTS_ENTERPRISE_BROWSER_CONTROLLER_CHROME_BROWSER_CLOUD_MANAGEMENT_HELPER_H_
|
#ifndef __CURVE_EDITOR_POPUP_H__
#define __CURVE_EDITOR_POPUP_H__
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// file: curveEditor_popup.h
//
// Author Sergey Solokhin (Neill3d)
//
//
// GitHub page - https://github.com/Neill3d/MoPlugs_Framework
// Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs_Framework/blob/master/LICENSE
//
///////////////////////////////////////////////////////////////////////////////////////////////////
//--- SDK Include
#include <fbsdk/fbsdk.h>
#include "Delegate.h"
#include "graphics\ParticlesDrawHelper.h"
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//! Popup with Curve Editor.
class ORPopup_CurveEditor : public FBPopup
{
FBClassDeclare( ORPopup_CurveEditor, FBPopup );
public:
ORPopup_CurveEditor();
public:
// UI Management
void UICreate ();
void UIConfigure ();
// UI Callbacks
void EventButtonResetClick ( HISender pSender, HKEvent pEvent );
void EventButtonPreviewClick ( HISender pSender, HKEvent pEvent );
void EventButtonCloseClick ( HISender pSender, HKEvent pEvent );
public:
void SetUp( FBAnimationNode *node, FBPropertyAnimatable *pProp );
void Clear();
void Preview();
Gallant::Delegate1<double> OnPreviewChange;
private:
FBFCurveEditor mCurveEditor; // edit variable value in time here
FBButton mButtonReset;
FBButton mButtonPreview; // update missing files according to the missing path list
FBButton mButtonClose; // button to close popup
FBAnimationNode *mInputNode; // node source
FBAnimationNode *mNode; // use this node for editing
};
///////////////////////////////////////////////////////////////////////////////////////////////
//
enum OperationMode
{
OperationSelect,
OperationMove,
OperationAdd,
OperationRemove
};
////////////////////////////////////////////////////////////////////
//
class ColorView : public FBView
{
public:
//! a constructor
ColorView();
//! a destructor
~ColorView();
/** Set view's viewport
* \param pX Viewport X value.
* \param pY Viewport Y value.
* \param pW Viewport W (width) value.
* \param pH Viewport H (height) value.
* \return Operation was successful (\b true or \b false).
*/
virtual bool SetViewport(int pX,int pY,int pW,int pH) override;
//! Exposed view callback function.
virtual void ViewExpose() override;
/** Input callback function.
* \param pMouseX Mouse X position.
* \param pMouseY Mouse Y position.
* \param pAction Mouse action.
* \param pButtonKey Keyboard input.
* \param pModifier Keyboard input modifier.
*/
virtual void ViewInput(int pMouseX,int pMouseY,FBInputType pAction,int pButtonKey,int pModifier) override;
void SetUp( FBPopup *pPopup, FBPropertyAnimatableColorAndAlpha *prop );
void SetOperationMode (const OperationMode mode)
{
mOperationMode = mode;
}
const OperationMode GetOperationMode()
{
return mOperationMode;
}
void SetColor(const FBColorAndAlpha color);
void SetColor(const FBColor color, const double alpha);
private:
int mSelectedMarker;
ColorPropertyTexture mTexture;
bool mNeedUpdate;
bool mDown;
OperationMode mOperationMode;
FBPopup *mPopup;
int mWidth;
int mHeight;
};
///////////////////////////////////////////////////////////////////////////////////
// ORPopup_ColorEditor
class ORPopup_ColorEditor : public FBPopup
{
FBClassDeclare( ORPopup_ColorEditor, FBPopup );
public:
ORPopup_ColorEditor();
public:
// UI Management
void UICreate ();
void UIConfigure ();
// UI Callbacks
void EventButtonSelectClick ( HISender pSender, HKEvent pEvent );
void EventButtonMoveClick ( HISender pSender, HKEvent pEvent );
void EventButtonAddClick ( HISender pSender, HKEvent pEvent );
void EventButtonRemoveClick ( HISender pSender, HKEvent pEvent );
void EventEditColorChange ( HISender pSender, HKEvent pEvent );
void EventButtonClearClick ( HISender pSender, HKEvent pEvent );
void EventButtonPreviewClick ( HISender pSender, HKEvent pEvent );
void EventButtonCloseClick ( HISender pSender, HKEvent pEvent );
public:
void SetUp( FBShader *shader, FBPropertyAnimatableColorAndAlpha *pProp );
void Clear();
void Preview();
void SetColorForEdit(const FBColorAndAlpha color);
private:
ColorView mColorView; // edit variable value in time here
FBButton mButtonSelect;
FBButton mButtonMove;
FBButton mButtonAdd; // add color mode
FBButton mButtonRemove; // remove color mode
FBButton mButtonClear;
FBEditColor mEditColor;
FBEditNumber mEditAlpha;
FBButton mButtonPreview; // update missing files according to the missing path list
FBButton mButtonClose; // button to close popup
FBShader *mShader; // connected shader (for making a preview operation)
FBPropertyAnimatableColorAndAlpha *mColorProperty;
void SetOperationButtonState();
};
#endif /* __CURVE_EDITOR_POPUP_H__ */
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef mozilla_dom_AesKeyAlgorithm_h
#define mozilla_dom_AesKeyAlgorithm_h
#include "mozilla/dom/KeyAlgorithm.h"
#include "js/TypeDecls.h"
namespace mozilla {
namespace dom {
class AesKeyAlgorithm MOZ_FINAL : public KeyAlgorithm
{
public:
AesKeyAlgorithm(nsIGlobalObject* aGlobal, const nsString& aName, uint16_t aLength)
: KeyAlgorithm(aGlobal, aName)
, mLength(aLength)
{}
~AesKeyAlgorithm()
{}
virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
uint16_t Length() const
{
return mLength;
}
virtual bool WriteStructuredClone(JSStructuredCloneWriter* aWriter) const MOZ_OVERRIDE;
static KeyAlgorithm* Create(nsIGlobalObject* aGlobal,
JSStructuredCloneReader* aReader);
protected:
uint16_t mLength;
};
} // namespace dom
} // namespace mozilla
#endif // mozilla_dom_AesKeyAlgorithm_h
|
#ifndef WALLE_CALLBACK_H_
#define WALLE_CALLBACK_H_
#include <walle/smart_ptr/smart_ptr.h>
#include <walle/sys/wallesys.h>
using namespace walle::sys;
namespace walle {
namespace net{
class Buffer;
class TcpConnection;
typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;
typedef std::function<void()> TimerCallback;
typedef std::function<void (const TcpConnectionPtr&)> ConnectionCallback;
typedef std::function<void (const TcpConnectionPtr&)> CloseCallback;
typedef std::function<void (const TcpConnectionPtr&)> WriteCompleteCallback;
typedef std::function<void (const TcpConnectionPtr&, size_t)> HighWaterMarkCallback;
// the data has been read to (buf, len)
typedef std::function<void (const TcpConnectionPtr&,
Buffer*,
Time)> MessageCallback;
void defaultConnectionCallback(const TcpConnectionPtr& conn);
void defaultMessageCallback(const TcpConnectionPtr& conn,
Buffer* buffer,
Time receiveTime);
}
}
#endif
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef UV_UNIX_INTERNAL_H_
#define UV_UNIX_INTERNAL_H_
#include "uv-common.h"
#include <assert.h>
#include <stdlib.h> /* abort */
#if defined(__STRICT_ANSI__)
# define inline __inline
#endif
#if defined(__linux__)
# include "linux-syscalls.h"
#endif /* __linux__ */
#if defined(__sun)
# include <sys/port.h>
# include <port.h>
# define futimes(fd, tv) futimesat(fd, (void*)0, tv)
#endif /* __sun */
#if defined(__APPLE__) && !TARGET_OS_IPHONE
# include <CoreServices/CoreServices.h>
#endif
#define STATIC_ASSERT(expr) \
void uv__static_assert(int static_assert_failed[1 - 2 * !(expr)])
#define ACCESS_ONCE(type, var) \
(*(volatile type*) &(var))
#define UNREACHABLE() \
do { \
assert(0 && "unreachable code"); \
abort(); \
} \
while (0)
#define SAVE_ERRNO(block) \
do { \
int _saved_errno = errno; \
do { block; } while (0); \
errno = _saved_errno; \
} \
while (0)
#ifdef HAVE_DTRACE
#include "uv-dtrace.h"
#else
#define UV_TICK_START(arg0, arg1)
#define UV_TICK_STOP(arg0, arg1)
#endif
#endif /* UV_UNIX_INTERNAL_H_ */
|
/* $OpenBSD: isareg.h,v 1.2 1997/11/07 08:07:03 niklas Exp $ */
/* $NetBSD: isareg.h,v 1.5 1995/04/17 12:09:13 cgd Exp $ */
/*-
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* 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 University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)isa.h 5.7 (Berkeley) 5/9/91
*/
/*
* ISA Bus conventions
*/
/*
* Input / Output Port Assignments
*/
#ifndef IO_ISABEGIN
#define IO_ISABEGIN 0x000 /* 0x000 - Beginning of I/O Registers */
/* CPU Board */
#define IO_DMA1 0x000 /* 8237A DMA Controller #1 */
#define IO_ICU1 0x020 /* 8259A Interrupt Controller #1 */
#define IO_PMP1 0x026 /* 82347 Power Management Peripheral */
#define IO_TIMER1 0x040 /* 8253 Timer #1 */
#define IO_TIMER2 0x048 /* 8253 Timer #2 (EISA only) */
#define IO_KBD 0x060 /* 8042 Keyboard */
#define IO_PPI 0x061 /* Programmable Peripheral Interface */
#define IO_RTC 0x070 /* RTC */
#define IO_NMI IO_RTC /* NMI Control */
#define IO_DMAPG 0x080 /* DMA Page Registers */
#define IO_ICU2 0x0A0 /* 8259A Interrupt Controller #2 */
#define IO_DMA2 0x0C0 /* 8237A DMA Controller #2 */
#define IO_NPX 0x0F0 /* Numeric Coprocessor */
/* Cards */
/* 0x100 - 0x16F Open */
#define IO_WD2 0x170 /* Secondary Fixed Disk Controller */
#define IO_PMP2 0x178 /* 82347 Power Management Peripheral */
/* 0x17A - 0x1EF Open */
#define IO_WD1 0x1f0 /* Primary Fixed Disk Controller */
#define IO_GAME 0x200 /* Game Controller */
/* 0x208 - 0x237 Open */
#define IO_BMS2 0x238 /* secondary InPort Bus Mouse */
#define IO_BMS1 0x23c /* primary InPort Bus Mouse */
/* 0x240 - 0x277 Open */
#define IO_LPT2 0x278 /* Parallel Port #2 */
/* 0x280 - 0x2E7 Open */
#define IO_COM4 0x2e8 /* COM4 i/o address */
/* 0x2F0 - 0x2F7 Open */
#define IO_COM2 0x2f8 /* COM2 i/o address */
/* 0x300 - 0x32F Open */
#define IO_BT0 0x330 /* bustek 742a default addr. */
#define IO_AHA0 0x330 /* adaptec 1542 default addr. */
#define IO_UHA0 0x330 /* ultrastore 14f default addr. */
#define IO_BT1 0x334 /* bustek 742a default addr. */
#define IO_AHA1 0x334 /* adaptec 1542 default addr. */
/* 0x338 - 0x34F Open */
#define IO_WDS 0x350 /* WD7000 scsi */
/* 0x354 - 0x36F Open */
#define IO_FD2 0x370 /* secondary base i/o address */
#define IO_LPT1 0x378 /* Parallel Port #1 */
/* 0x380 - 0x3AF Open */
#define IO_MDA 0x3B0 /* Monochome Adapter */
#define IO_LPT3 0x3BC /* Monochome Adapter Printer Port */
#define IO_VGA 0x3C0 /* E/VGA Ports */
#define IO_CGA 0x3D0 /* CGA Ports */
/* 0x3E0 - 0x3E7 Open */
#define IO_COM3 0x3e8 /* COM3 i/o address */
#define IO_FD1 0x3f0 /* primary base i/o address */
#define IO_COM1 0x3f8 /* COM1 i/o address */
#define IO_ISAEND 0x3FF /* - 0x3FF End of I/O Registers */
#endif /* !IO_ISABEGIN */
/*
* Input / Output Port Sizes - these are from several sources, and tend
* to be the larger of what was found, ie COM ports can be 4, but some
* boards do not fully decode the address, thus 8 ports are used.
*/
#ifndef IO_ISASIZES
#define IO_ISASIZES
#define IO_COMSIZE 8 /* 8250, 16X50 com controllers */
#define IO_CGASIZE 16 /* CGA controllers */
#define IO_DMASIZE 16 /* 8237 DMA controllers */
#define IO_DPGSIZE 32 /* 74LS612 DMA page reisters */
#define IO_FDCSIZE 8 /* Nec765 floppy controllers */
#define IO_WDCSIZE 8 /* WD compatible disk controller */
#define IO_GAMSIZE 16 /* AT compatible game controller */
#define IO_ICUSIZE 16 /* 8259A interrupt controllers */
#define IO_KBDSIZE 16 /* 8042 Keyboard controllers */
#define IO_LPTSIZE 8 /* LPT controllers, some use onl */
#define IO_MDASIZE 16 /* Monochrome display controller */
#define IO_RTCSIZE 16 /* CMOS real time clock, NMI con */
#define IO_TMRSIZE 16 /* 8253 programmable timers */
#define IO_NPXSIZE 16 /* 80387/80487 NPX registers */
#define IO_VGASIZE 16 /* VGA controllers */
#define IO_PMPSIZE 2 /* 82347 Power Management Peripheral */
#endif /* !IO_ISASIZES */
/*
* Input / Output Memory Physical Addresses
*/
#ifndef IOM_BEGIN
#define IOM_BEGIN 0x0a0000 /* Start of I/O Memory "hole" */
#define IOM_END 0x100000 /* End of I/O Memory "hole" */
#define IOM_SIZE (IOM_END - IOM_BEGIN)
#endif /* !IOM_BEGIN */
|
#pragma once
#include "qglviewer.h"
#include "qapplication.h"
#include "fps_kinfu_tracker.h"
#include "gl_helpers/simple_viewer.h"
namespace fps_mapper {
class KinfuTrackerViewer: public GLHelpers::SimpleViewer {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
KinfuTrackerViewer(FPSKinfuTracker* _tracker);
virtual void draw();
protected:
FPSKinfuTracker* _tracker;
bool _model_tainted;
};
}
|
//
// PullToRefreshViewController.h
// TableViewPull
//
// Created by Devin Doty on 10/16/09October16.
// Modified by Mannie Tagarira on February 1, 2011
// Copyright enormego 2009. 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.
//
@class EGORefreshTableHeaderView;
@interface PullToRefreshViewController : UITableViewController {
EGORefreshTableHeaderView *refreshHeaderView;
// Reloading should really be your tableviews model class
// Putting it here for demo purposes
BOOL _reloading;
float contentOffset;
}
@property(assign,getter=isReloading) BOOL reloading;
@end
@protocol PullToRefreshDataSource <UITableViewDelegate, UITableViewDataSource>
-(void) refreshTableViewDataSource;
@end
|
#ifndef __BIT_DLFCN_H__
#define __BIT_DLFCN_H__
#include <features.h>
#define RTLD_LAZY (1 << 0)
#define RTLD_NOW (1 << 1)
#define RTLD_BINDING_MASK (RTLD_LAZY | RTLD_NOW)
#define RTLD_NOLOAD (1 << 2)
#define RTLD_DEEPBIND (1 << 3)
#define RTLD_GLOBAL (1 << 8)
#define RTLD_LOCAL 0
#define RTLD_NODELETE (1 << 12)
#if defined(_GNU_SOURCE)
#define DL_CALL_FCT(fctp, args) \
(_dl_mcount_wrapper_check((void *)(fctp)), (*(fctp))args)
extern void _dl_mcount_wrapper_check(void *selfpc);
#endif
#endif /* __BIT_DLFCN_H__ */
|
/*
Copyright 2002-2004 John Plevyak, All Rights Reserved
*/
#include "d.h"
int scan_buffer(d_loc_t *aloc, D_State *parse_state, ShiftResult *results) {
d_loc_t loc = *aloc, last_loc = *aloc;
char *s = loc.s;
int col = loc.col, line = loc.line;
int nresults = 0, i = 0, j;
D_Shift **shift = NULL, **shift_diff = 0;
switch (parse_state->scanner_size) {
case 1: {
/* all matches */
SB_uint8 *st = (SB_uint8 *)parse_state->scanner_table;
SB_trans_uint8 *tst = (SB_trans_uint8 *)parse_state->transition_table;
uint8 state = 0, last = state, prev = state;
uint8 c;
uint32 sb, so;
c = (uint8)*s++;
while ((state = st[state].scanner_block[(sb = (c >> SCANNER_BLOCK_SHIFT))][(so = c & SCANNER_BLOCK_MASK)])) {
state -= 1;
if (prev && parse_state->accepts_diff) {
shift_diff = parse_state->accepts_diff[tst[prev].scanner_block[sb][so]];
for (; *shift_diff; shift_diff++) {
results[nresults].loc = loc;
results[nresults++].shift = *shift_diff;
}
}
prev = state;
if (c == '\n') {
line++;
col = 0;
} else
col++;
loc.s = s;
loc.line = line;
loc.col = col;
if (st[state].shift) {
last = state;
last_loc = loc;
}
c = (uint8)*s++;
}
shift = st[last].shift;
break;
}
case 2: {
/* all matches */
SB_uint16 *st = (SB_uint16 *)parse_state->scanner_table;
SB_trans_uint16 *tst = (SB_trans_uint16 *)parse_state->transition_table;
uint16 state = 0, last = state, prev = state;
uint8 c;
uint32 sb, so;
c = (uint8)*s++;
while ((state = st[state].scanner_block[(sb = (c >> SCANNER_BLOCK_SHIFT))][(so = c & SCANNER_BLOCK_MASK)])) {
state -= 1;
if (prev && parse_state->accepts_diff) {
shift_diff = parse_state->accepts_diff[tst[prev].scanner_block[sb][so]];
for (; *shift_diff; shift_diff++) {
results[nresults].loc = loc;
results[nresults++].shift = *shift_diff;
}
}
prev = state;
loc.s = s;
loc.line = line;
loc.col = col;
if (st[state].shift) {
last = state;
last_loc = loc;
}
if (c == '\n') {
line++;
col = 0;
} else
col++;
c = (uint8)*s++;
}
shift = st[last].shift;
break;
}
case 4: {
/* all matches */
SB_uint32 *st = (SB_uint32 *)parse_state->scanner_table;
SB_trans_uint32 *tst = (SB_trans_uint32 *)parse_state->transition_table;
uint32 state = 0, last = state, prev = state;
uint8 c;
uint32 sb, so;
c = (uint8)*s++;
while ((state = st[state].scanner_block[(sb = (c >> SCANNER_BLOCK_SHIFT))][(so = c & SCANNER_BLOCK_MASK)])) {
state -= 1;
if (prev && parse_state->accepts_diff) {
shift_diff = parse_state->accepts_diff[tst[prev].scanner_block[sb][so]];
for (; *shift_diff; shift_diff++) {
results[nresults].loc = loc;
results[nresults++].shift = *shift_diff;
}
}
prev = state;
loc.s = s;
loc.line = line;
loc.col = col;
if (st[state].shift) {
last = state;
last_loc = loc;
}
if (c == '\n') {
line++;
col = 0;
} else
col++;
c = (uint8)*s++;
}
shift = st[last].shift;
break;
}
}
if (shift) {
for (; *shift; shift++) {
results[nresults].loc = last_loc;
results[nresults++].shift = *shift;
}
}
if (nresults) {
int longest = 0;
char *end = results[nresults - 1].loc.s;
if (parse_state->scan_kind == D_SCAN_LONGEST) longest = 1;
if (parse_state->scan_kind == D_SCAN_MIXED) {
for (i = nresults - 1; i >= 0; i--) {
if (results[i].loc.s < end) break;
if (results[i].shift->shift_kind == D_SCAN_LONGEST) longest = 1;
}
}
if (longest) {
/* keep only 'longest' */
i = 0;
for (j = 0; j < nresults; j++) {
if (results[j].loc.s == end || results[j].shift->shift_kind == D_SCAN_TRAILING) {
if (i != j) results[i] = results[j];
i++;
}
}
nresults = i;
} else if (parse_state->scan_kind == D_SCAN_MIXED) {
/* only keep non-longest */
for (j = i; j >= 0; j--)
if (results[j].shift->shift_kind != D_SCAN_LONGEST) {
if (i != j) results[i] = results[j];
i--;
}
nresults = nresults - i - 1;
if (i != -1) memmove(&results[0], &results[i + 1], nresults * sizeof(results[0]));
}
}
return nresults;
}
|
#pragma once
#include "Actuator.h"
#include "carmodel/IServoDrive.h"
#include "meta/IServoDriveConfig.h"
#include <boost/smart_ptr.hpp>
namespace A2O {
/**
* The ServoDrive class represenst a servo drive holding a specific position.
*
* \author Stefan Glaser
*/
class ServoDrive : public Actuator, public virtual IServoDrive {
public:
typedef boost::shared_ptr<ServoDrive> Ptr;
typedef boost::shared_ptr<const ServoDrive> ConstPtr;
ServoDrive(IServoDriveConfig::ConstPtr config);
virtual ~ServoDrive();
virtual const double& getPosition() const;
virtual const double& getPreviousPosition() const;
virtual const double& getTargetPosition() const;
virtual void setPosition(const double& position);
virtual const double& getMinPosition() const;
virtual const double& getMaxPosition() const;
virtual const bool update(IPerception::ConstPtr perception);
virtual const bool reflectAction(IAction::Ptr action) const;
protected:
double _position;
double _previousPosition;
double _targetPosition;
double _minPosition;
double _maxPosition;
};
}
|
/*
* Copyright (c) 2011 Gerard Green
* All rights reserved
*
* Please see the file 'LICENSE' for further information
*/
#ifndef _MULTIPROCESSOR_H_INCLUDED
#define _MULTIPROCESSOR_H_INCLUDED
#include <stdint.h>
#define MP_PTR_SIG (0x5f504d5f)
/* These structures are from the Intel multiprocessor spec. */
typedef struct {
char sig[4];
uint32_t phys_addr;
uint8_t len;
uint8_t spec_rev;
uint8_t chksum;
uint8_t feat1;
uint8_t feat2;
uint8_t feat3;
uint8_t feat4;
uint8_t feat5;
} __attribute__ ((packed)) mp_floating_ptr_t;
typedef struct {
char sig[4];
uint16_t base_tbl_len;
uint8_t spec_rev;
uint8_t chksum;
char oem_str[8];
char prod_str[12];
uint32_t oem_tbl_ptr;
uint16_t oem_tbl_size;
uint16_t entry_cnt;
uint32_t local_apic_addr;
uint16_t ext_tbl_len;
uint8_t ext_tbl_chksum;
uint8_t res;
} __attribute__ ((packed)) mp_config_table_header_t;
typedef struct {
uint8_t type; /* 0 */
uint8_t local_apic_id;
uint8_t local_apic_version;
uint8_t cpu_flags;
uint32_t cpu_sig;
uint32_t features;
uint32_t res1;
uint32_t res2;
} __attribute__ ((packed)) processor_entry_t;
typedef struct {
uint8_t type; /* 1 */
uint8_t id;
char type_str[6];
} __attribute__ ((packed)) bus_entry_t;
typedef struct {
uint8_t type; /* 2 */
uint8_t id;
uint8_t version;
uint8_t flags;
uint32_t addr;
} __attribute__ ((packed)) io_apic_entry_t ;
typedef struct {
uint8_t type; /* 3 */
uint8_t intr_type;
uint16_t flags;
uint8_t src_bus_id;
uint8_t src_bus_irq;
uint8_t dst_io_apic_id;
uint8_t dst_io_apic_irq;
} __attribute__ ((packed)) io_intr_entry_t ;
typedef struct {
uint8_t type; /* 4 */
uint8_t intr_type;
uint16_t flags;
uint8_t src_bus_id;
uint8_t src_bus_irq;
uint8_t dst_local_apic_id;
uint8_t dst_local_apic_irq;
} __attribute__ ((packed)) local_intr_entry_t ;
typedef struct {
uint8_t type;
uint8_t len;
uint8_t busid;
uint8_t addr_type;
uint32_t base1;
uint32_t base2;
uint32_t leng1;
uint32_t leng2;
} __attribute__ ((packed)) sysaddr_space_t;
typedef struct {
uint8_t type;
uint8_t len;
uint8_t busid;
uint8_t businfo;
uint8_t parent;
uint8_t res1;
uint8_t res2;
uint8_t res3;
} __attribute__ ((packed)) bus_hier_t;
typedef struct {
uint8_t type;
uint8_t len;
uint8_t busid;
uint8_t addr_mod;
uint32_t range;
} __attribute__ ((packed)) compat_bus_t;
int mptable_parse(void);
#endif /* _MULTIPROCESSOR_H_INCLUDED */
|
//
// io/nogr/input.c
//
#ifdef WITH_SDL
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "input.h"
#include "display.h"
#include "../display.h"
#include "../../controls.h"
#include "../../config.h"
#undef isprint
#define isprint(c) ((c)>=32 && (c)<128)
void sdl_default_handler(SDL_Event *e)
{
switch(e->type) {
case SDL_WINDOWEVENT:
switch(e->window.event) {
case SDL_WINDOWEVENT_RESIZED:
tcols = e->window.data1 / twidth;
trows = e->window.data2 / theight;
SDL_FreeSurface(disp);
//SDL_SetWindowDisplayMode(win, NULL);
disp = SDL_GetWindowSurface(win);
redraw();
break;
}
break;
}
}
int sdl_event_to_ctrl(SDL_Event *e) {
int key;
switch(e->type) {
case SDL_KEYDOWN:
key = e->key.keysym.sym;
if(isprint(key) && e->key.keysym.mod & (KMOD_LSHIFT | KMOD_RSHIFT)) key = toupper(key);
return key;
case SDL_QUIT:
return controls[CTRL_QUIT].key;
default:
sdl_default_handler(e);
return CTRL_INVALID;
}
}
const char * sdl_name_from_key(int key)
{
return SDL_GetKeyName(key);
}
int sdl_key_from_name(const char * str)
{
int key = SDL_GetKeyFromName(str);
if(isprint(key) && isupper(str[0])) key = toupper(key);
return key;
}
int sdl_get_key(void)
{
SDL_Event e;
int c = CTRL_INVALID;
while(1) {
SDL_WaitEvent(&e);
if ((c = sdl_event_to_ctrl(&e)) != CTRL_INVALID) {
return c;
}
} /* ???!!! */
}
int sdl_get_printable_key(void) {
int c = 0;
while(1) {
c = sdl_get_key();
if(isprint(c)) {
return c;
}
}
}
int sdl_get_ctrl(void)
{
SDL_Event e;
int c = CTRL_INVALID;
int last = CTRL_INVALID;
e.type = SDL_USEREVENT;
if(config.real_time) {
while(SDL_PollEvent(&e)) {
if((c = sdl_event_to_ctrl(&e)) != CTRL_INVALID && isprint(c)) {
last = c;
}
}
if(last == CTRL_INVALID) return controls[CTRL_SKIP_TURN].key;
return last;
} else {
return sdl_get_printable_key();
}
}
int sdl_prompt_dir(const char * prompt, int * dx, int * dy)
{
sdl_memo(prompt);
*dx=*dy=13;
switch (ctrl_by_key(sdl_get_printable_key())) {
case CTRL_LEFT: *dx = -1; *dy = 0; break;
case CTRL_DOWN: *dx = 0; *dy = 1; break;
case CTRL_UP: *dx = 0; *dy =-1; break;
case CTRL_RIGHT: *dx = 1; *dy = 0; break;
case CTRL_ULEFT: *dx = -1; *dy =-1; break;
case CTRL_URIGHT: *dx = 1; *dy =-1; break;
case CTRL_DLEFT: *dx = -1; *dy = 1; break;
case CTRL_DRIGHT: *dx = 1; *dy = 1; break;
case CTRL_SKIP_TURN: *dx = 0; *dy = 0; break;
}
return *dx!=13;
}
int sdl_prompt_inv(const char * prompt, inventory * inv, creature * c)
{
SDL_Window *win = SDL_CreateWindow("Inventory Select", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 320, 240, SDL_WINDOW_SHOWN);
SDL_Surface *disp = SDL_GetWindowSurface(win), *text;
SDL_Color WHITE = {255, 255, 255, 255};
SDL_Rect cur = {0, 0, disp->w, disp->h};
int i;
char s[512];
SDL_FillRect(disp, NULL, 0x44);
text = TTF_RenderUTF8_Solid(font, prompt, WHITE);
SDL_BlitSurface(text, NULL, disp, &cur);
cur.y += text->h;
SDL_FreeSurface(text);
for(i = 0; i < inv->size; i++) {
if(inv->itms[i]) {
snprintf(s, 512, "%c) %s %s", ind2ch(i), inv->itms[i]->name, (c&&item_equipped(inv->itms[i], c))?"(equipped)":"");
text = TTF_RenderUTF8_Solid(font, s, WHITE);
SDL_BlitSurface(text, NULL, disp, &cur);
cur.y += text->h;
SDL_FreeSurface(text);
}
}
SDL_UpdateWindowSurface(win);
//XXX: This is hacked beyond all recognition.
while(1) {
int c = sdl_get_key();
if(isprint(c)) {
SDL_DestroyWindow(win);
return ch2ind(c);
}
}
}
void sdl_prompt_equipped(const char * prompt, creature * c)
{
SDL_Window *win = SDL_CreateWindow("Equipment Slots", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 320, 240, SDL_WINDOW_SHOWN);
SDL_Surface *disp = SDL_GetWindowSurface(win), *text;
SDL_Color WHITE = {255, 255, 255, 255};
SDL_Rect cur = {0, 0, disp->w, disp->h};
int i;
char s[512];
SDL_FillRect(disp, NULL, 0x44);
text = TTF_RenderUTF8_Solid(font, prompt, WHITE);
SDL_BlitSurface(text, NULL, disp, &cur);
cur.y += text->h;
SDL_FreeSurface(text);
for(i = 0; i < MAX_SLOTS; i++) {
snprintf(s, 512, "%s: %s", slot_names[i], c->slots[i]?c->slots[i]->name:"(nothing)");
text = TTF_RenderUTF8_Solid(font, s, WHITE);
SDL_BlitSurface(text, NULL, disp, &cur);
cur.y += text->h;
SDL_FreeSurface(text);
}
SDL_UpdateWindowSurface(win);
sdl_get_key();
SDL_DestroyWindow(win);
}
char * sdl_prompt_string(const char * prompt)
{
SDL_Window *win = SDL_CreateWindow("Equipment Slots", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 320, 240, SDL_WINDOW_SHOWN);
SDL_Surface *disp = SDL_GetWindowSurface(win), *text;
SDL_Color WHITE = {255, 255, 255, 255};
SDL_Rect cur = {0, 0, disp->w, disp->h};
char *s = calloc(512, 1);
int idx = 0;
SDL_FillRect(disp, NULL, 0x44);
text = TTF_RenderUTF8_Solid(font, prompt, WHITE);
SDL_BlitSurface(text, NULL, disp, &cur);
cur.y += text->h;
SDL_FreeSurface(text);
SDL_UpdateWindowSurface(win);
while(1) {
int c = sdl_get_key();
switch(c) {
case 10: case 13:
SDL_DestroyWindow(win);
return s;
case 8:
s[idx--] = '\0';
default:
if(isprint(c)) {
s[idx++] = c;
}
}
text = TTF_RenderUTF8_Solid(font, prompt, WHITE);
SDL_BlitSurface(text, NULL, disp, &cur);
SDL_FreeSurface(text);
SDL_UpdateWindowSurface(win);
}
}
#endif
|
#include <pebble.h>
#include "serial.h"
static const char OPPONENT_SCORE = 'O';
static const char PLAYER_SCORE = 'P';
void add_opponent_score(list_t *serial) {
list_rpush(serial, list_node_new((void *) &OPPONENT_SCORE));
}
void add_player_score(list_t *serial) {
list_rpush(serial, list_node_new((void *) &PLAYER_SCORE));
}
void undo(list_t *serial) {
free(list_rpop(serial));
}
|
//
// This file is part of the µOS++ III distribution.
// Copyright (c) 2014 Liviu Ionescu.
//
// ----------------------------------------------------------------------------
#include "../cmsis/LPC13Uxx.h"
// ----------------------------------------------------------------------------
extern void
__attribute__((noreturn))
NVIC_SystemReset(void);
// ----------------------------------------------------------------------------
// Forward declarations
void
__reset_hardware(void);
// ----------------------------------------------------------------------------
// This is the default hardware reset routine; it can be
// redefined in the application for more complex applications.
//
// Called from _exit().
void
__attribute__((weak,noreturn))
__reset_hardware()
{
NVIC_SystemReset();
}
// ----------------------------------------------------------------------------
|
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file glShaderContext_src.h
* @author jyelon
* @date 2005-09-01
*/
#ifndef OPENGLES_1
#include "pandabase.h"
#include "string_utils.h"
#include "internalName.h"
#include "shader.h"
#include "shaderContext.h"
#include "deletedChain.h"
#include "paramTexture.h"
class CLP(GraphicsStateGuardian);
/**
* xyz
*/
class EXPCL_GL CLP(ShaderContext) FINAL : public ShaderContext {
public:
friend class CLP(GraphicsStateGuardian);
CLP(ShaderContext)(CLP(GraphicsStateGuardian) *glgsg, Shader *s);
~CLP(ShaderContext)();
ALLOC_DELETED_CHAIN(CLP(ShaderContext));
void reflect_attribute(int i, char *name_buf, GLsizei name_buflen);
void reflect_uniform_block(int i, const char *block_name,
char *name_buffer, GLsizei name_buflen);
void reflect_uniform(int i, char *name_buffer, GLsizei name_buflen);
bool get_sampler_texture_type(int &out, GLenum param_type);
INLINE bool valid(void);
void bind() OVERRIDE;
void unbind() OVERRIDE;
void set_state_and_transform(const RenderState *state,
const TransformState *modelview_transform,
const TransformState *camera_transform,
const TransformState *projection_transform) OVERRIDE;
void issue_parameters(int altered) OVERRIDE;
void update_transform_table(const TransformTable *table);
void update_slider_table(const SliderTable *table);
void disable_shader_vertex_arrays() OVERRIDE;
bool update_shader_vertex_arrays(ShaderContext *prev, bool force) OVERRIDE;
void disable_shader_texture_bindings() OVERRIDE;
void update_shader_texture_bindings(ShaderContext *prev) OVERRIDE;
void update_shader_buffer_bindings(ShaderContext *prev) OVERRIDE;
INLINE bool uses_standard_vertex_arrays(void);
INLINE bool uses_custom_vertex_arrays(void);
private:
bool _validated;
GLuint _glsl_program;
typedef pvector<GLuint> GLSLShaders;
GLSLShaders _glsl_shaders;
WCPT(RenderState) _state_rs;
CPT(TransformState) _modelview_transform;
CPT(TransformState) _camera_transform;
CPT(TransformState) _projection_transform;
/*
* struct ParamContext { CPT(InternalName) _name; GLint _location; GLsizei
* _count; WPT(ParamValue) _value; UpdateSeq _updated; }; typedef
* pvector<ParamContext> ParamContexts; ParamContexts _params;
*/
BitMask32 _enabled_attribs;
GLint _color_attrib_index;
GLint _transform_table_index;
GLint _slider_table_index;
GLsizei _transform_table_size;
GLsizei _slider_table_size;
GLint _frame_number_loc;
GLint _frame_number;
#ifndef OPENGLES
pmap<GLint, GLuint64> _glsl_uniform_handles;
#endif
#ifndef OPENGLES
struct StorageBlock {
CPT(InternalName) _name;
GLuint _binding_index;
GLint _min_size;
};
typedef pvector<StorageBlock> StorageBlocks;
StorageBlocks _storage_blocks;
BitArray _used_storage_bindings;
#endif
struct ImageInput {
CPT(InternalName) _name;
CLP(TextureContext) *_gtc;
bool _writable;
};
pvector<ImageInput> _glsl_img_inputs;
CLP(GraphicsStateGuardian) *_glgsg;
bool _uses_standard_vertex_arrays;
void glsl_report_shader_errors(GLuint shader, Shader::ShaderType type, bool fatal);
void glsl_report_program_errors(GLuint program, bool fatal);
bool glsl_compile_shader(Shader::ShaderType type);
bool glsl_compile_and_link();
bool parse_and_set_short_hand_shader_vars(Shader::ShaderArgId &arg_id, GLenum param_type, GLint param_size, Shader *s);
void release_resources();
public:
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
ShaderContext::init_type();
register_type(_type_handle, CLASSPREFIX_QUOTED "ShaderContext",
ShaderContext::get_class_type());
}
virtual TypeHandle get_type() const OVERRIDE {
return get_class_type();
}
virtual TypeHandle force_init_type() OVERRIDE {init_type(); return get_class_type();}
private:
static TypeHandle _type_handle;
};
#include "glShaderContext_src.I"
#endif // OPENGLES_1
|
// -*- Mode:ObjC; c-basic-offset:4; tab-width:8; indent-tabs-mode:nil -*-
/*
* ItemShelf for iOS
* Copyright (C) 2008-2011, ItemShelf Development Team, All rights reserved.
* For conditions of distribution and use, see LICENSE file.
*/
#import "Common.h"
/**
URL query parameter
*/
@interface URLQuery : NSObject
{
NSString *name; ///< parameter name
NSString *value; ///< value of the parameter
}
@property(nonatomic,strong) NSString *name;
@property(nonatomic,strong) NSString *value;
@end
/**
URL component class
It likes NSURL. Main difference is that this class
can handle "splitted" URL parameters with URLQuery class.
*/
@interface URLComponent : NSObject
{
NSString *scheme;
NSString *host;
NSString *path;
NSString *params;
NSString *query;
NSString *fragment;
NSMutableArray *queries; ///< Query parameters
}
@property(nonatomic,strong) NSString *scheme;
@property(nonatomic,strong) NSString *host;
@property(nonatomic,strong) NSString *path;
@property(nonatomic,strong) NSString *params;
@property(nonatomic,strong) NSString *query;
@property(nonatomic,strong) NSString *fragment;
@property(nonatomic,strong) NSMutableArray *queries;
- (instancetype)init __attribute__((unavailable("Not designated")));
- (instancetype)initWithURL:(NSURL *)url NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithURLString:(NSString *)urlString NS_DESIGNATED_INITIALIZER;
- (void)setURL:(NSURL *)url;
- (void)setURLString:(NSString*)urlString;
- (NSString*)absoluteString;
- (NSURL*)url;
- (void)parseQuery;
- (void)composeQuery;
- (URLQuery*)URLQuery:(NSString*)name; // private
- (NSString*)query:(NSString*)name;
- (void)setQuery:(NSString*)name value:(NSString*)value;
- (void)removeQuery:(NSString*)name;
- (void)log;
@end
|
/**
* Copyright (c) 2014, Mattijs Korpershoek
* 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. Neither the name of the copyright holder 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
*/
#ifndef __DEFINE_LINKEDLISTLINKEDLIST__
#define __DEFINE_LINKEDLISTLINKEDLIST__
#define KERNEL_DEVELOPMENT 1
/* set right macros here for hybrid kernel/userspace usage */
#if KERNEL_DEVELOPMENT == 1
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/cdev.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include "SensorID.h"
#define FREE kfree
#define MALLOC(x) kmalloc(x, GFP_KERNEL)
#define PRINT(x) printk (KERN_ALERT x)
#define ITEM_TYPE_LL Sensor*
#define DEFAULT_ITEM NULL
#else
#include <stdio.h>
#include <stdlib.h>
#define FREE free
#define MALLOC(x) malloc(x)
#define PRINT(x) printf("%s", x)
#define ITEM_TYPE char*
#define DEFAULT_ITEM NULL
#endif
/* cell structure */
typedef struct _linkedCell
{
struct _linkedCell* next;
ITEM_TYPE_LL item;
}LinkedCell;
typedef struct _internalLinkedList
{
LinkedCell* first;
LinkedCell* last;
unsigned long numberOfItems;
void (*writeItem)(struct _internalLinkedList*, ITEM_TYPE_LL);
ITEM_TYPE_LL (*getItemFromIndex)(struct _internalLinkedList*, unsigned int index);
}LinkedList;
LinkedList* newLinkedList(void);
void deleteLinkedList(LinkedList* theLinkedListToDelete);
#endif
|
/*
* Copyright (c) 2016 CartoDB. All rights reserved.
* Copying and using this code is allowed only according
* to license terms, as given in https://cartodb.com/terms/
*/
#ifndef _CARTO_PACKAGEMANAGERROUTINGSERVICE_H_
#define _CARTO_PACKAGEMANAGERROUTINGSERVICE_H_
#if defined(_CARTO_ROUTING_SUPPORT) && defined(_CARTO_PACKAGEMANAGER_SUPPORT)
#include "packagemanager/PackageManager.h"
#include "routing/RoutingService.h"
#include <memory>
#include <string>
#include <map>
#include <mutex>
namespace carto {
namespace osrm {
class RouteFinder;
}
/**
* A routing service that uses routing packages from package manager.
*/
class PackageManagerRoutingService : public RoutingService {
public:
/**
* Constructs a new instance of the PackageManagerRoutingService given package manager instance.
* @param packageManager The package manager instance to use.
*/
explicit PackageManagerRoutingService(const std::shared_ptr<PackageManager>& packageManager);
virtual ~PackageManagerRoutingService();
virtual std::string getProfile() const;
virtual void setProfile(const std::string& profile);
virtual std::shared_ptr<RouteMatchingResult> matchRoute(const std::shared_ptr<RouteMatchingRequest>& request) const;
virtual std::shared_ptr<RoutingResult> calculateRoute(const std::shared_ptr<RoutingRequest>& request) const;
protected:
class PackageManagerListener : public PackageManager::OnChangeListener {
public:
explicit PackageManagerListener(PackageManagerRoutingService& service);
virtual void onPackagesChanged(PackageChangeType changeType);
virtual void onStylesChanged();
private:
PackageManagerRoutingService& _service;
};
const std::shared_ptr<PackageManager> _packageManager;
mutable std::map<std::shared_ptr<PackageInfo>, std::shared_ptr<std::ifstream> > _cachedPackageFileMap;
mutable std::shared_ptr<osrm::RouteFinder> _cachedRouteFinder;
mutable std::mutex _mutex;
private:
std::shared_ptr<PackageManagerListener> _packageManagerListener;
};
}
#endif
#endif
|
/*
module : or.c
version : 1.9
date : 07/23/20
*/
#ifndef OR_C
#define OR_C
/**
or : X Y -> Z
Z is the union of sets X and Y, logical disjunction for truth values.
*/
void do_or(void)
{
BINARY;
stack[-2] |= stack[-1];
do_pop();
}
#endif
|
/*********************************************************************/
/* Copyright 2009, 2010 The University of Texas at Austin. */
/* 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 UNIVERSITY OF TEXAS AT */
/* AUSTIN ``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 UNIVERSITY OF TEXAS AT */
/* AUSTIN 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#include <stdio.h>
#include "common.h"
#include <arm_sve.h>
int CNAME(BLASLONG m, BLASLONG n, FLOAT *a, BLASLONG lda, BLASLONG posX, BLASLONG posY, FLOAT *b){
BLASLONG i, offset;
#if defined(DOUBLE)
uint64_t sve_size = svcntd();
svint64_t posY_vec = svdup_s64(posY);
svint64_t posX_vec = svdup_s64(posX);
svint64_t lda_vec = svdup_s64(lda);
svint64_t one_vec = svdup_s64(1LL);
int64_t j = 0;
svbool_t pg = svwhilelt_b64(j, n);
int64_t active = svcntp_b64(svptrue_b64(), pg);
svint64_t index_neg = svindex_s64(0LL, -1LL);
svint64_t index = svindex_s64(0LL, 1LL);
do {
offset = posX - posY;
svint64_t vec_off = svdup_s64(offset);
svbool_t cmp = svcmpgt(pg, vec_off, index_neg);
svint64_t temp = svadd_z(pg, posX_vec, index);
svint64_t temp1 = svmla_z(pg, temp, posY_vec, lda_vec);
svint64_t temp2 = svmla_z(pg, posY_vec, temp, lda);
svint64_t gat_ind = svsel(cmp, temp2, temp1);
i = m;
while (i>0) {
svfloat64_t data_vec = svld1_gather_index(pg, a, gat_ind);
gat_ind = svadd_m(cmp, gat_ind, one_vec);
gat_ind = svadd_m(svnot_z(pg, cmp) , gat_ind, lda_vec);
svst1(pg, b, data_vec);
b += active;
offset --;
vec_off = svsub_z(pg, vec_off, one_vec);
cmp = svcmpgt(pg, vec_off, index_neg);
i--;
}
posX += sve_size;
posX_vec = svdup_s64(posX);
j += sve_size;
pg = svwhilelt_b64(j, n);
active = svcntp_b64(svptrue_b64(), pg);
} while (svptest_any(svptrue_b64(), pg));
#else
uint32_t sve_size = svcntw();
svint32_t posY_vec = svdup_s32(posY);
svint32_t posX_vec = svdup_s32(posX);
svint32_t lda_vec = svdup_s32(lda);
svint32_t one_vec = svdup_s32(1);
int32_t N = n;
int32_t j = 0;
svbool_t pg = svwhilelt_b32(j, N);
int32_t active = svcntp_b32(svptrue_b32(), pg);
svint32_t index_neg = svindex_s32(0, -1);
svint32_t index = svindex_s32(0, 1);
do {
offset = posX - posY;
svint32_t vec_off = svdup_s32(offset);
svbool_t cmp = svcmpgt(pg, vec_off, index_neg);
svint32_t temp = svadd_z(pg, posX_vec, index);
svint32_t temp1 = svmla_z(pg, temp, posY_vec, lda_vec);
svint32_t temp2 = svmla_z(pg, posY_vec, temp, lda);
svint32_t gat_ind = svsel(cmp, temp2, temp1);
i = m;
while (i>0) {
svfloat32_t data_vec = svld1_gather_index(pg, a, gat_ind);
gat_ind = svadd_m(cmp, gat_ind, one_vec);
gat_ind = svadd_m(svnot_z(pg, cmp) , gat_ind, lda_vec);
svst1(pg, b, data_vec);
b += active;
offset --;
vec_off = svsub_z(pg, vec_off, one_vec);
cmp = svcmpgt(pg, vec_off, index_neg);
i--;
}
posX += sve_size;
posX_vec = svdup_s32(posX);
j += sve_size;
pg = svwhilelt_b32(j, N);
active = svcntp_b32(svptrue_b32(), pg);
} while (svptest_any(svptrue_b32(), pg));
#endif
return 0;
}
|
// 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 COMPONENTS_VARIATIONS_VARIATIONS_SEED_STORE_H_
#define COMPONENTS_VARIATIONS_VARIATIONS_SEED_STORE_H_
#include <string>
#include "base/compiler_specific.h"
#include "base/gtest_prod_util.h"
#include "base/time/time.h"
class PrefService;
class PrefRegistrySimple;
namespace variations {
class VariationsSeed;
}
namespace variations {
// VariationsSeedStore is a helper class for reading and writing the variations
// seed from Local State.
class VariationsSeedStore {
public:
explicit VariationsSeedStore(PrefService* local_state);
virtual ~VariationsSeedStore();
// Loads the variations seed data from local state into |seed|. If there is a
// problem with loading, the pref value is cleared and false is returned. If
// successful, |seed| will contain the loaded data and true is returned.
bool LoadSeed(variations::VariationsSeed* seed);
// Stores the given seed |data| (serialized protobuf) to local state, along
// with a base64-encoded digital signature for seed and the date when it was
// fetched. If |is_gzip_compressed| is true, treats |data| as being gzip
// compressed and decompresses it before any other processing.
// If |is_delta_compressed| is true, treats |data| as being delta
// compressed and attempts to decode it first using the store's seed data.
// The actual seed data will be base64 encoded for storage. If the string
// is invalid, the existing prefs are untouched and false is returned.
// Additionally, stores the |country_code| that was received with the seed in
// a separate pref. On success and if |parsed_seed| is not NULL, |parsed_seed|
// will be filled with the de-serialized decoded protobuf.
bool StoreSeedData(const std::string& data,
const std::string& base64_seed_signature,
const std::string& country_code,
const base::Time& date_fetched,
bool is_delta_compressed,
bool is_gzip_compressed,
variations::VariationsSeed* parsed_seed);
// Updates |kVariationsSeedDate| and logs when previous date was from a
// different day.
void UpdateSeedDateAndLogDayChange(const base::Time& server_date_fetched);
// Reports to UMA that the seed format specified by the server is unsupported.
void ReportUnsupportedSeedFormatError();
// Returns the serial number of the last loaded or stored seed.
const std::string& variations_serial_number() const {
return variations_serial_number_;
}
// Returns whether the last loaded or stored seed has the country field set.
bool seed_has_country_code() const {
return seed_has_country_code_;
}
// Returns the invalid signature in base64 format, or an empty string if the
// signature was valid, missing, or if signature verification is disabled.
std::string GetInvalidSignature() const;
// Registers Local State prefs used by this class.
static void RegisterPrefs(PrefRegistrySimple* registry);
protected:
// Note: UMA histogram enum - don't re-order or remove entries.
enum VerifySignatureResult {
VARIATIONS_SEED_SIGNATURE_MISSING,
VARIATIONS_SEED_SIGNATURE_DECODE_FAILED,
VARIATIONS_SEED_SIGNATURE_INVALID_SIGNATURE,
VARIATIONS_SEED_SIGNATURE_INVALID_SEED,
VARIATIONS_SEED_SIGNATURE_VALID,
VARIATIONS_SEED_SIGNATURE_ENUM_SIZE,
};
// Verifies a variations seed (the serialized proto bytes) with the specified
// base-64 encoded signature that was received from the server and returns the
// result. The signature is assumed to be an "ECDSA with SHA-256" signature
// (see kECDSAWithSHA256AlgorithmID in the .cc file). Returns the result of
// signature verification or VARIATIONS_SEED_SIGNATURE_ENUM_SIZE if signature
// verification is not enabled.
virtual VariationsSeedStore::VerifySignatureResult VerifySeedSignature(
const std::string& seed_bytes,
const std::string& base64_seed_signature);
private:
FRIEND_TEST_ALL_PREFIXES(VariationsSeedStoreTest, VerifySeedSignature);
FRIEND_TEST_ALL_PREFIXES(VariationsSeedStoreTest, ApplyDeltaPatch);
// Clears all prefs related to variations seed storage.
void ClearPrefs();
#if defined(OS_ANDROID)
// Imports the variations seed data from Java side during the first
// Chrome for Android run.
void ImportFirstRunJavaSeed();
#endif // OS_ANDROID
// Reads the variations seed data from prefs; returns true on success.
bool ReadSeedData(std::string* seed_data);
// Internal version of |StoreSeedData()| that assumes |seed_data| is not delta
// compressed.
bool StoreSeedDataNoDelta(
const std::string& seed_data,
const std::string& base64_seed_signature,
const std::string& country_code,
const base::Time& date_fetched,
variations::VariationsSeed* parsed_seed);
// Applies a delta-compressed |patch| to |existing_data|, producing the result
// in |output|. Returns whether the operation was successful.
static bool ApplyDeltaPatch(const std::string& existing_data,
const std::string& patch,
std::string* output);
// The pref service used to persist the variations seed.
PrefService* local_state_;
// Cached serial number from the most recently fetched variations seed.
std::string variations_serial_number_;
// Whether the most recently fetched variations seed has the country code
// field set.
bool seed_has_country_code_;
// Keeps track of an invalid signature.
std::string invalid_base64_signature_;
DISALLOW_COPY_AND_ASSIGN(VariationsSeedStore);
};
} // namespace variations
#endif // COMPONENTS_VARIATIONS_VARIATIONS_SEED_STORE_H_
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_console_w32_execvp_11.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-11.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: console Read input from the console
* GoodSource: Fixed string
* Sink: w32_execvp
* BadSink : execute command with execvp
* Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse())
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#endif
#include <process.h>
#define EXECVP _execvp
#ifndef OMITBAD
void CWE78_OS_Command_Injection__char_console_w32_execvp_11_bad()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
if(globalReturnsTrue())
{
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
}
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
/* execvp - searches for the location of the command among
* the directories specified by the PATH environment variable */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECVP(COMMAND_INT, args);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */
static void goodG2B1()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
if(globalReturnsFalse())
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
}
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
/* execvp - searches for the location of the command among
* the directories specified by the PATH environment variable */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECVP(COMMAND_INT, args);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
if(globalReturnsTrue())
{
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
}
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
/* execvp - searches for the location of the command among
* the directories specified by the PATH environment variable */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECVP(COMMAND_INT, args);
}
}
void CWE78_OS_Command_Injection__char_console_w32_execvp_11_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()...");
CWE78_OS_Command_Injection__char_console_w32_execvp_11_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__char_console_w32_execvp_11_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/*
* Copyright (c) 2011,2015 Apple Inc. All rights reserved.
*
* corecrypto Internal Use License Agreement
*
* IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple")
* in consideration of your agreement to the following terms, and your download or use
* of this Apple software constitutes acceptance of these terms. If you do not agree
* with these terms, please do not download or use this Apple software.
*
* 1. As used in this Agreement, the term "Apple Software" collectively means and
* includes all of the Apple corecrypto materials provided by Apple here, including
* but not limited to the Apple corecrypto software, frameworks, libraries, documentation
* and other Apple-created materials. In consideration of your agreement to abide by the
* following terms, conditioned upon your compliance with these terms and subject to
* these terms, Apple grants you, for a period of ninety (90) days from the date you
* download the Apple Software, a limited, non-exclusive, non-sublicensable license
* under Apple’s copyrights in the Apple Software to make a reasonable number of copies
* of, compile, and run the Apple Software internally within your organization only on
* devices and computers you own or control, for the sole purpose of verifying the
* security characteristics and correct functioning of the Apple Software; provided
* that you must retain this notice and the following text and disclaimers in all
* copies of the Apple Software that you make. You may not, directly or indirectly,
* redistribute the Apple Software or any portions thereof. The Apple Software is only
* licensed and intended for use as expressly stated above and may not be used for other
* purposes or in other contexts without Apple's prior written permission. Except as
* expressly stated in this notice, no other rights or licenses, express or implied, are
* granted by Apple herein.
*
* 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES
* OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING
* THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS,
* SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR
* REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR
* ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE
* SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL
* OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE
* WILL CREATE A WARRANTY.
*
* 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING
* IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE
* SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING
* NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* 4. This Agreement is effective until terminated. Your rights under this Agreement will
* terminate automatically without notice from Apple if you fail to comply with any term(s)
* of this Agreement. Upon termination, you agree to cease all use of the Apple Software
* and destroy all copies, full or partial, of the Apple Software. This Agreement will be
* governed and construed in accordance with the laws of the State of California, without
* regard to its choice of law rules.
*
* You may report security issues about Apple products to product-security@apple.com,
* as described here: https://www.apple.com/support/security/. Non-security bugs and
* enhancement requests can be made via https://bugreport.apple.com as described
* here: https://developer.apple.com/bug-reporting/
*
* EA1350
* 10/5/15
*/
#include <corecrypto/ccrc4.h>
/* rc4 test, encrypt then decrypt in place */
int ccrc4_test(const struct ccrc4_info *rc4, const struct ccrc4_vector *v)
{
ccrc4_ctx_decl(rc4->size, skey);
unsigned char temp[v->datalen];
int rc;
rc4->init(skey, v->keylen, v->key);
rc4->crypt(skey, v->datalen, v->ct, temp);
rc=memcmp(temp, v->pt, v->datalen);
rc4->init(skey, v->keylen, v->key);
rc4->crypt(skey, v->datalen, temp, temp);
rc|=memcmp(temp, v->ct, v->datalen);
return rc;
}
|
#include<stdio.h> //for printf
#include<stdlib.h> //for exit()
#include"gnuplot_i.h"
#include"TCP_API.h"
#include"signal_processing2.h"
#define Port 7538
#define fmin 1000000 //low frequency of pass_band filter
#define fmax 6000000 //high frequency of pass_band filter
//#define Ymax 1 //maximum boundary of the y axis
float r0=0.0;
float rf=0.0;
int dec=0;
int Nline=0;
double sector=0.0;
int mode_RP=0;
int step=1;
void writefile (double *z, int line, char *name)
{
int i;
FILE * f;
f = fopen(name,"w+");
for (i=0 ; i<line ; i++)
{
fprintf(f, "%f\n", z[i]);
}
fclose(f);
}
int main(int arg, char *argv[])
{
int Npoint;
//socket variable
SOCKET sock;
const char *IP="192.168.128.3";
init_TCP_client(&sock, IP, Port);
get_RP_settings(&sock);
printf("r0=%f\n",r0);
printf("rf=%f\n",rf);
printf("dec=%i\n",dec);
printf("Nline=%i\n",Nline);
printf("sector=%f\n",sector);
printf("mode_RP=%i\n",mode_RP);
int l=0;
Npoint=(int)(2.0*(rf-r0)*125.0/1.48/((double)dec));
if (Npoint>16384) {Npoint=16384;}
printf("Npoint = %i\n",Npoint);
//int powd, pad_len;
//if (power_two(Npoint,&powd)){powd++;}
//pad_len=int_pow(2,powd);
//init_table(pad_len);
//float fech=125000000.0/((float)dec);
//gnuplot variable
gnuplot_ctrl * h;
double *y= (double *)malloc(Npoint*sizeof(double));
int i;
int Ymax=1.5;
//gnuplot object
h=gnuplot_init();
gnuplot_setstyle(h,"lines");
gnuplot_set_xlabel(h,"time (us)");
gnuplot_set_ylabel(h,"signal");
//gnuplot_cmd(h,"set yrange [0:%d]", 2*Ymax);
gnuplot_cmd(h,"set xrange [0:%d]",Npoint-1);
char name[20]="tmp_raw.txt";
if (mode_RP==0)
{
//int powd, pad_len;
//if (power_two(Npoint,&powd)){powd++;}
//pad_len=int_pow(2,powd);
//double *pad=NULL;
//pad=(double *)malloc(pad_len*sizeof(double));
//double *env=NULL;
//env=(double *)malloc(pad_len*sizeof(double));
gnuplot_cmd(h,"set yrange [-1.5:1.5]");
gnuplot_cmd(h,"set xrange [0:%d]",Npoint-1);
int16_t *buff=(int16_t *)malloc((Npoint+1)*sizeof(int16_t));
int tmpl;
while(1)
{
tmpl=l/10;
if(receive_int16_TCP_client(&sock, buff, Npoint+1)==1){break;}
for (i=1 ; i<Npoint+1 ; i++){y[i-1]=(double)(buff[i])/409.6;} //divide by 409.6 to have voltage value
//zero_padding(y, pad, Npoint, pad_len, 1);
//envelope(pad, env, pad_len, fech, fmin, fmax, 0);
gnuplot_resetplot(h);
//gnuplot_plot_x(h, y, Npoint, "Oscillo int16_t");
gnuplot_plot_x(h, y, Npoint, "Oscillo int16_t");
//sprintf(name, "int%i.txt", l);
if (tmpl*10==l)
{
writefile(y, Npoint, name);
}
l++;
}
free(buff);
}
else if (mode_RP==1)
{
char *buff=(char *)malloc((Npoint+1)*sizeof(char));
while(1)
{
if(receive_TCP_client(&sock, buff, Npoint+1)==1){break;}
for (i=1 ; i<Npoint+1 ; i++){y[i-1]=(double)(int_converter(buff[i]));}
gnuplot_resetplot(h);
gnuplot_plot_x(h, y, Npoint, "Oscillo 256 gray");
sprintf(name, "char%i.txt", l);
//writefile(y, Npoint, name);
l++;
}
free(buff);
}
else {printf("Problem of settings\n");}
usleep(30);
close(sock);
free(y);
return 0;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkTreeMapLayout.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkTreeMapLayout - layout a vtkTree into a tree map
//
// .SECTION Description
// vtkTreeMapLayout assigns rectangular regions to each vertex in the tree,
// creating a tree map. The data is added as a data array with four
// components per tuple representing the location and size of the
// rectangle using the format (Xmin, Xmax, Ymin, Ymax).
//
// This algorithm relies on a helper class to perform the actual layout.
// This helper class is a subclass of vtkTreeMapLayoutStrategy.
//
// .SECTION Thanks
// Thanks to Brian Wylie and Ken Moreland from Sandia National Laboratories
// for help developing this class.
//
// Tree map concept comes from:
// Shneiderman, B. 1992. Tree visualization with tree-maps: 2-d space-filling approach.
// ACM Trans. Graph. 11, 1 (Jan. 1992), 92-99.
#ifndef vtkTreeMapLayout_h
#define vtkTreeMapLayout_h
#include "vtkInfovisLayoutModule.h" // For export macro
#include "vtkTreeAlgorithm.h"
class vtkTreeMapLayoutStrategy;
class VTKINFOVISLAYOUT_EXPORT vtkTreeMapLayout : public vtkTreeAlgorithm
{
public:
static vtkTreeMapLayout *New();
vtkTypeMacro(vtkTreeMapLayout,vtkTreeAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// The field name to use for storing the rectangles for each vertex.
// The rectangles are stored in a quadruple float array
// (minX, maxX, minY, maxY).
vtkGetStringMacro(RectanglesFieldName);
vtkSetStringMacro(RectanglesFieldName);
// Description:
// The array to use for the size of each vertex.
virtual void SetSizeArrayName(const char* name)
{ this->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_VERTICES, name); }
// Description:
// The strategy to use when laying out the tree map.
vtkGetObjectMacro(LayoutStrategy, vtkTreeMapLayoutStrategy);
void SetLayoutStrategy(vtkTreeMapLayoutStrategy * strategy);
// Description:
// Returns the vertex id that contains pnt (or -1 if no one contains it)
vtkIdType FindVertex(float pnt[2], float *binfo=0);
// Description:
// Return the min and max 2D points of the
// vertex's bounding box
void GetBoundingBox(vtkIdType id, float *binfo);
// Description:
// Get the modification time of the layout algorithm.
virtual unsigned long GetMTime();
protected:
vtkTreeMapLayout();
~vtkTreeMapLayout();
char * RectanglesFieldName;
vtkTreeMapLayoutStrategy* LayoutStrategy;
int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
private:
vtkTreeMapLayout(const vtkTreeMapLayout&) VTK_DELETE_FUNCTION;
void operator=(const vtkTreeMapLayout&) VTK_DELETE_FUNCTION;
};
#endif
|
#ifndef ALIANALYSISTASKEMCALOCCUPANCY_H
#define ALIANALYSISTASKEMCALOCCUPANCY_H
#include "AliAnalysisTaskEmcalLight.h"
#include <TString.h>
class THistManager;
/**
* @class AliAnalysisTaskEmcalOccupancy
* @brief Task monitoring the occupancy on cluster and cell level
*/
class AliAnalysisTaskEmcalOccupancy : public AliAnalysisTaskEmcalLight {
public:
AliAnalysisTaskEmcalOccupancy();
AliAnalysisTaskEmcalOccupancy(const char *name);
virtual ~AliAnalysisTaskEmcalOccupancy();
void SetUseCentralityPercentile(Bool_t doUse) { fUseCentrality = doUse; }
static AliAnalysisTaskEmcalOccupancy *AddOccupancyTask(const char *name);
protected:
virtual void UserCreateOutputObjects();
virtual void ExecOnce();
virtual bool Run();
private:
AliAnalysisTaskEmcalOccupancy(const AliAnalysisTaskEmcalOccupancy &);
AliAnalysisTaskEmcalOccupancy &operator=(const AliAnalysisTaskEmcalOccupancy &);
TString fNameClusters; ///< Name of the cluster container
THistManager *fHistos; ///< Histogram container;
Bool_t fUseCentrality; ///< Switch whether to use the centrality percentile
UChar_t *fCellCounter; //!<! Counting how often a cell is fired per event
ClassDef(AliAnalysisTaskEmcalOccupancy, 1);
};
#endif /* ALIANALYSISTASKEMCALOCCUPANCY_H */
|
//this is a file in the VAc dynamic model software package
//Copyright: Rong Chen and Kedar Dave, June 2002
//VERSION 1.0
//This routine provides a 'full-position' PID algorithm
//original author: Francisco Reyes-De Leon, Chemical Engineering Department, Lehigh University
//modified by Rong Chen
//Note: the controller gain, K, is dimentionless
//mex controller.c
#include <stdio.h>
#include <math.h>
//#include <mex.h>
void controller(double *manip_original, double *xi, double *hi_flag, double sp_original, double meas_scaled, double manip_original_in, double xi_in, int mode, double K, double Ti, double h, double LO_y, double HI_y, double LO_u, double HI_u, int action, int P_only, double rel_lo, double rel_hi, double hys, double hi_flag_in)
//manip_original(w/wo in): manipulated variable (u)
//xi(w/wo in): store the integration of error which is the second term in the controller formation
//sp_original: setpoint of the loop (y_y)
//meas_scaled: measurement (y) from the transmitter
//mode: 'automatic' is 1, 'manual' is 2, 'autotune' is 3
//K: scaled controller gain
//Ti: controller in minute
//h: sampling time in minute
//LO_y HI_y : measurement range
//LO_u HI_u: MV range
//action: +1 or -1 for controller gain sign
//P_only: proportional only controller =1 , else 0
//rel_lo rel_hi hys hi_flag: relay tuning parameters
{
double sp_scaled, epsi, u, manip_scaled;
sp_scaled = (sp_original - LO_y) /(HI_y - LO_y);
epsi= sp_scaled - meas_scaled;
if (mode == 1) //'Automatic' mode of operation
{
if (K != 0)
{
if (P_only==1)
{
u=K*action*epsi + xi_in;
*xi=xi_in;
}
else
u=K*action*(epsi+h*epsi/Ti) + xi_in;
}
else
u=xi_in;
if (u < 0)
manip_scaled = 0;
else
{
if (u > 1)
manip_scaled = 1;
else
manip_scaled = u;
}
if (P_only != 1)
{
if (K != 0)
*xi= xi_in +h *K *action *epsi/Ti +(manip_scaled -u); // Antireset wind-up
else
*xi= xi_in +h *action *epsi/Ti +(manip_scaled -u); // Antireset wind-up
}
*manip_original = manip_scaled * (HI_u - LO_u) + LO_u;
*hi_flag=hi_flag_in;
return;
}
else
{
if (mode == 2) // 'Manual' mode
{
*manip_original=manip_original_in;
*xi=xi_in;
*hi_flag=hi_flag_in;
return;
}
else // 'Autotune' mode
{
if ((epsi > hys) && (hi_flag_in==0.0))
{
*manip_original = rel_hi;
*hi_flag=1;
}
else
{
if ((epsi < -hys) && (hi_flag_in==1.0))
{
*manip_original = rel_lo;
*hi_flag=0;
}
}
return;
}
}
}
#ifdef mex_h
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double sp_original;
double meas_scaled;
double manip_original_in;
double xi_in;
int mode;
double K;
double Ti;
double h;
double LO_y;
double HI_y;
double LO_u;
double HI_u;
int action;
int P_only;
double rel_lo;
double rel_hi;
double hys;
double hi_flag_in;
double *manip_original;
double *xi;
double *hi_flag;
if(nrhs!=18)
mexErrMsgTxt("inputs not correct");
if(nlhs!=3)
mexErrMsgTxt("outputs not correct");
sp_original = mxGetScalar(prhs[0]);
meas_scaled = mxGetScalar(prhs[1]);
manip_original_in = mxGetScalar(prhs[2]);
xi_in = mxGetScalar(prhs[3]);
mode = mxGetScalar(prhs[4]);
K = mxGetScalar(prhs[5]);
Ti = mxGetScalar(prhs[6]);
h = mxGetScalar(prhs[7]);
LO_y = mxGetScalar(prhs[8]);
HI_y = mxGetScalar(prhs[9]);
LO_u = mxGetScalar(prhs[10]);
HI_u = mxGetScalar(prhs[11]);
action = mxGetScalar(prhs[12]);
P_only = mxGetScalar(prhs[13]);
rel_lo = mxGetScalar(prhs[14]);
rel_hi = mxGetScalar(prhs[15]);
hys = mxGetScalar(prhs[16]);
hi_flag_in = mxGetScalar(prhs[17]);
//-------------------------------------------
plhs[0] = mxCreateDoubleScalar(0);
manip_original = mxGetPr(plhs[0]);
//-------------------------------------------
plhs[1] = mxCreateDoubleScalar(0);
xi = mxGetPr(plhs[1]);
//-------------------------------------------
plhs[2] = mxCreateDoubleScalar(0);
hi_flag = mxGetPr(plhs[2]);
controller(manip_original, xi, hi_flag, sp_original, meas_scaled, manip_original_in, xi_in, mode, K, Ti, h, LO_y, HI_y, LO_u, HI_u, action, P_only, rel_lo, rel_hi, hys, hi_flag_in);
}
#endif |
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by hsp3debug.rc
//
#define IDC_TAB1 1007
#define IDC_LIST1 1008
#define IDC_EDIT1 1009
#define IDC_BUTTON1 1010
#define IDC_SORT 1011
#define IDC_MODULE 1012
#define IDC_ARRAY 1013
#define IDC_ARRAY2 1014
#define IDC_DUMP 1014
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 105
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1015
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
|
// 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 COMPONENTS_SYNC_ENGINE_MODEL_TYPE_CONFIGURER_H_
#define COMPONENTS_SYNC_ENGINE_MODEL_TYPE_CONFIGURER_H_
#include <memory>
#include "base/callback.h"
#include "components/sync/base/model_type.h"
#include "components/sync/engine/configure_reason.h"
namespace syncer {
struct DataTypeActivationResponse;
// The DataTypeConfigurer interface abstracts out the action of
// configuring a set of new data types and cleaning up after a set of
// removed data types.
class ModelTypeConfigurer {
public:
// Utility struct for holding ConfigureDataTypes options.
struct ConfigureParams {
ConfigureParams();
ConfigureParams(ConfigureParams&& other);
~ConfigureParams();
ConfigureParams& operator=(ConfigureParams&& other);
ConfigureReason reason;
ModelTypeSet enabled_types;
ModelTypeSet disabled_types;
ModelTypeSet to_download;
ModelTypeSet to_purge;
ModelTypeSet to_journal;
ModelTypeSet to_unapply;
// Run when configuration is done with the set of all types that failed
// configuration (if its argument isn't empty, an error was encountered).
// TODO(akalin): Use a Delegate class with OnConfigureSuccess,
// OnConfigureFailure, and OnConfigureRetry instead of a pair of callbacks.
// The awkward part is handling when SyncEngine calls ConfigureDataTypes on
// itself to configure Nigori.
base::OnceCallback<void(ModelTypeSet, ModelTypeSet)> ready_task;
// Whether full sync (or sync the feature) is enabled;
bool is_sync_feature_enabled;
private:
DISALLOW_COPY_AND_ASSIGN(ConfigureParams);
};
ModelTypeConfigurer();
virtual ~ModelTypeConfigurer();
// Changes the set of data types that are currently being synced.
virtual void ConfigureDataTypes(ConfigureParams params) = 0;
// Activates change processing for the given non-blocking data type.
// This must be called before initial sync for data type.
virtual void ActivateNonBlockingDataType(
ModelType type,
std::unique_ptr<DataTypeActivationResponse> activation_response) = 0;
// Deactivates change processing for the given non-blocking data type.
virtual void DeactivateNonBlockingDataType(ModelType type) = 0;
// Activates a proxy type, which determines whether protocol fields such as
// |tabs_datatype_enabled| should be true.
virtual void ActivateProxyDataType(ModelType type) = 0;
// Deactivates a proxy type.
virtual void DeactivateProxyDataType(ModelType type) = 0;
};
} // namespace syncer
#endif // COMPONENTS_SYNC_ENGINE_MODEL_TYPE_CONFIGURER_H_
|
//
// RBSettingsViewController.h
// RPC Builder
//
#import "RBBaseViewController.h"
@interface RBSettingsViewController : RBBaseViewController
@end
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_11.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml
Template File: sources-sink-11.tmpl.c
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using malloc() and set data pointer to a small buffer
* GoodSource: Allocate using malloc() and set data pointer to a large buffer
* Sink: memmove
* BadSink : Copy int64_t array to data using memmove
* Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse())
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_11_bad()
{
int64_t * data;
data = NULL;
if(globalReturnsTrue())
{
/* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = (int64_t *)malloc(50*sizeof(int64_t));
if (data == NULL) {exit(-1);}
}
{
int64_t source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memmove(data, source, 100*sizeof(int64_t));
printLongLongLine(data[0]);
free(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */
static void goodG2B1()
{
int64_t * data;
data = NULL;
if(globalReturnsFalse())
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = (int64_t *)malloc(100*sizeof(int64_t));
if (data == NULL) {exit(-1);}
}
{
int64_t source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memmove(data, source, 100*sizeof(int64_t));
printLongLongLine(data[0]);
free(data);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
int64_t * data;
data = NULL;
if(globalReturnsTrue())
{
/* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = (int64_t *)malloc(100*sizeof(int64_t));
if (data == NULL) {exit(-1);}
}
{
int64_t source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memmove(data, source, 100*sizeof(int64_t));
printLongLongLine(data[0]);
free(data);
}
}
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_11_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_CWE805_int64_t_memmove_11_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_11_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/*
* service.h
*
* Created on: 2015-1-11
* Author: qianqians
*/
#ifndef _service_h
#define _service_h
#include <boost/shared_ptr.hpp>
#include "../interface/rpcchannel.h"
namespace Fossilizid{
namespace juggle{
class service{
public:
/*
* initialise service
*/
virtual void init() = 0;
/*
* drive service work
*/
virtual void poll() = 0;
/*
* unixtime
*/
virtual uint64_t unixtime() = 0;
};
boost::shared_ptr<service> create_service();
} /* namespace juggle */
} /* namespace Fossilizid */
#endif //_service_h |
/* Examples/cauchy_01.c
Jerasure - A C/C++ Library for a Variety of Reed-Solomon and RAID-6 Erasure Coding Techniques
Revision 1.2A
May 24, 2011
James S. Plank
Department of Electrical Engineering and Computer Science
University of Tennessee
Knoxville, TN 37996
plank@cs.utk.edu
Copyright (c) 2011, James S. Plank
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 University of Tennessee 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jerasure.h"
#include "cauchy.h"
#define talloc(type, num) (type *) malloc(sizeof(type)*(num))
void usage(char *s)
{
fprintf(stderr, "usage: cauchy_01 n w - Prints the number of ones in the bitmatrix representation of n in GF(2^w).\n");
fprintf(stderr, " \n");
fprintf(stderr, " It also prints out the bit-matrix and confirms that the number of ones is correct.\n");
fprintf(stderr, " \n");
fprintf(stderr, "This demonstrates: cauchy_n_ones()\n");
fprintf(stderr, " jerasure_matrix_to_bitmatrix()\n");
fprintf(stderr, " jerasure_print_bitmatrix()\n");
if (s != NULL) fprintf(stderr, "%s\n", s);
exit(1);
}
int main(int argc, char **argv)
{
int n, i, no, w;
int *bitmatrix;
if (argc != 3) usage(NULL);
if (sscanf(argv[1], "%d", &n) == 0 || n <= 0) usage("Bad n");
if (sscanf(argv[2], "%d", &w) == 0 || w <= 0 || w > 32) usage("Bad w");
if (w < 30 && n >= (1 << w)) usage("n is too big");
bitmatrix = jerasure_matrix_to_bitmatrix(1, 1, w, &n);
no = 0;
for (i = 0; i < w*w; i++) no += bitmatrix[i];
printf("# Ones: %d\n", cauchy_n_ones(n, w));
printf("\n");
printf("Bitmatrix has %d ones\n", no);
printf("\n");
jerasure_print_bitmatrix(bitmatrix, w, w, w);
return 0;
}
|
/* Copyright 2014. The Regents of the University of California.
* All rights reserved. Use of this source code is governed by
* a BSD-style license which can be found in the LICENSE file.
*
* Authors:
* 2012, 2014 Martin Uecker <uecker@eecs.berkeley.edu>
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <complex.h>
#include <string.h>
#include "num/multind.h"
#include "num/flpmath.h"
#include "num/init.h"
#include "misc/mmio.h"
#include "misc/io.h"
#include "misc/misc.h"
#include "misc/opts.h"
static const char help_str[] = "Create an array filled with ones with {dims} dimensions of size {dim1} to {dimn}.";
int main_ones(int argc, char* argv[argc])
{
long count = 0;
long N = -1;
long* dims = NULL;
const char* out_file = NULL;
struct arg_s args[] = {
ARG_LONG(true, &N, "dims"),
ARG_TUPLE(true, &count, 1, OPT_LONG, sizeof(long), &dims, "dim"),
ARG_OUTFILE(true, &out_file, "output"),
};
const struct opt_s opts[] = {};
cmdline(&argc, argv, ARRAY_SIZE(args), args, help_str, ARRAY_SIZE(opts), opts);
num_init();
assert(N >= 0);
assert(count == N);
for (int i = 0; i < N; i++)
assert(dims[i] >= 1);
complex float* x = create_cfl(out_file, N, dims);
md_zfill(N, dims, x, 1.);
unmap_cfl(N, dims, x);
xfree(dims);
return 0;
}
|
// Copyright (c) 2014 Baidu.com, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: qinzuoyan01@baidu.com (Qin Zuoyan)
/*
LZ4 - Fast LZ compression algorithm
Header File
Copyright (C) 2011-2012, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
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
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.
You can contact the author at :
- LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html
- LZ4 source repository : http://code.google.com/p/lz4/
*/
#ifndef _SOFA_PBRPC_LZ4_H_
#define _SOFA_PBRPC_LZ4_H_
namespace sofa {
namespace pbrpc {
//****************************
// Simple Functions
//****************************
int LZ4_compress (const char* source, char* dest, int isize);
int LZ4_uncompress (const char* source, char* dest, int osize);
/*
LZ4_compress() :
isize : is the input size. Max supported value is ~1.9GB
return : the number of bytes written in buffer dest
or 0 if the compression fails (if LZ4_COMPRESSMIN is set)
note : destination buffer must be already allocated.
destination buffer must be sized to handle worst cases situations (input data not compressible)
worst case size evaluation is provided by function LZ4_compressBound()
LZ4_uncompress() :
osize : is the output size, therefore the original size
return : the number of bytes read in the source buffer
If the source stream is malformed, the function will stop decoding and return a negative result, indicating the byte position of the faulty instruction
This function never writes beyond dest + osize, and is therefore protected against malicious data packets
note : destination buffer must be already allocated
*/
//****************************
// Advanced Functions
//****************************
int LZ4_compressBound(int isize);
/*
LZ4_compressBound() :
Provides the maximum size that LZ4 may output in a "worst case" scenario (input data not compressible)
primarily useful for memory allocation of output buffer.
isize : is the input size. Max supported value is ~1.9GB
return : maximum output size in a "worst case" scenario
note : this function is limited by "int" range (2^31-1)
*/
int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize);
/*
LZ4_uncompress_unknownOutputSize() :
isize : is the input size, therefore the compressed size
maxOutputSize : is the size of the destination buffer (which must be already allocated)
return : the number of bytes decoded in the destination buffer (necessarily <= maxOutputSize)
If the source stream is malformed, the function will stop decoding and return a negative result, indicating the byte position of the faulty instruction
This function never writes beyond dest + maxOutputSize, and is therefore protected against malicious data packets
note : Destination buffer must be already allocated.
This version is slightly slower than LZ4_uncompress()
*/
int LZ4_compressCtx(void** ctx, const char* source, char* dest, int isize);
int LZ4_compress64kCtx(void** ctx, const char* source, char* dest, int isize);
/*
LZ4_compressCtx() :
This function explicitly handles the CTX memory structure.
It avoids allocating/deallocating memory between each call, improving performance when malloc is heavily invoked.
This function is only useful when memory is allocated into the heap (HASH_LOG value beyond STACK_LIMIT)
Performance difference will be noticeable only when repetitively calling the compression function over many small segments.
Note : by default, memory is allocated into the stack, therefore "malloc" is not invoked.
LZ4_compress64kCtx() :
Same as LZ4_compressCtx(), but specific to small inputs (<64KB).
isize *Must* be <64KB, otherwise the output will be corrupted.
On first call : provide a *ctx=NULL; It will be automatically allocated.
On next calls : reuse the same ctx pointer.
Use different pointers for different threads when doing multi-threading.
*/
} // namespace pbrpc
} // namespace sofa
#endif // _SOFA_PBRPC_LZ4_H_
/* vim: set ts=4 sw=4 sts=4 tw=100 */
|
#include "virtual-machine.h"
r3x_cpu_t* MyCPU;
void Start(r3x_cpu_t* CPU) {
MyCPU = CPU;
return;
}
uint32_t myfunc(void) {
printf("getting argument 1 (STRING): %s\n", (char*)GetLinearAddress(MyCPU, GetArgument(MyCPU, 1,1)));
printf("returning 666\n");
return 666;
}
|
/*
* Copyright (c) 2016 CartoDB. All rights reserved.
* Copying and using this code is allowed only according
* to license terms, as given in https://cartodb.com/terms/
*/
#ifndef _CARTO_CLUSTERELEMENTBUILDER_H_
#define _CARTO_CLUSTERELEMENTBUILDER_H_
#include "core/MapPos.h"
#include <vector>
#include <memory>
namespace carto {
class VectorElement;
namespace ClusterBuilderMode {
/**
* Possible cluster builder modes.
*/
enum ClusterBuilderMode {
/**
* Cluster builder receives full list of elements in the cluster. This mode is more expensive compared to the light mode.
*/
CLUSTER_BUILDER_MODE_ELEMENTS,
/**
* Cluster builder receives element count in the cluster. This mode is less expensive compared to the full mode.
*/
CLUSTER_BUILDER_MODE_ELEMENT_COUNT
};
}
/**
* A special callback interface for building cluster elements from set of existing vector element.
*/
class ClusterElementBuilder {
public:
virtual ~ClusterElementBuilder() { }
/**
* Returns the builder mode. The return value of this method determines which builder method is called.
* @return The builder mode that determines which buildClusterElement method is called.
*/
virtual ClusterBuilderMode::ClusterBuilderMode getBuilderMode() const { return ClusterBuilderMode::CLUSTER_BUILDER_MODE_ELEMENTS; }
/**
* A callback for building a new cluster element given position and the number of cluster element.
* @param mapPos The position of the cluster element.
* @param elementCount The number of elements in the cluster.
* @return The created cluster element.
*/
virtual std::shared_ptr<VectorElement> buildClusterElement(const MapPos& mapPos, int elementCount) const { return std::shared_ptr<VectorElement>(); }
/**
* A callback for building a new cluster element given position and list of vector elements.
* @param mapPos The position of the cluster element.
* @param elements The list of elements that defines the cluster.
* @return The created cluster element.
*/
virtual std::shared_ptr<VectorElement> buildClusterElement(const MapPos& mapPos, const std::vector<std::shared_ptr<VectorElement> >& elements) const { return std::shared_ptr<VectorElement>(); }
};
}
#endif
|
#include <stdint.h>
#include <time.h>
#include <lib.h>
#include <shell.h>
extern char bss;
extern char endOfBinary;
static int var1 = 0;
static int var2 = 0;
void * memset(void * destiny, int32_t c, uint64_t length);
int main() {
//Clean BSS
memset(&bss, 0, &endOfBinary - &bss);
shell();
//Test if BSS is properly set up
if (var1 == 0 && var2 == 0)
return 0xDEADC0DE;
return 0xDEADBEEF;
}
void * memset(void * destination, int32_t c, uint64_t length) {
uint8_t chr = (uint8_t)c;
char * dst = (char*)destination;
while(length--)
dst[length] = chr;
return destination;
}
|
//
// ENGPhotoSubmitterServiceSettingTableViewProtocol.h
//
// Created by ISHITOYA Kentaro on 12/01/02.
//
#import <Foundation/Foundation.h>
#import "ENGPhotoSubmitterProtocol.h"
#define PHOTOSUBMITTER_DEFAULT_ALBUM_NAME @"photoSubmitter"
#define SV_SECTION_ACCOUNT 0
#define SV_ROW_ACCOUNT_NAME 0
#define SV_ROW_ACCOUNT_LOGOUT 1
#define SV_ROW_ACCOUNT_ADD 2
#define SV_ROW_ACCOUNT_DELETE 3
#define SV_BUTTON_TYPE 102
#define SV_SECTION_GENERAL 0
#define SV_SECTION_ACCOUNTS 1
#define SV_GENERAL_COUNT 3
#define SV_GENERAL_COMMENT 0
#define SV_GENERAL_GPS 1
#define SV_GENERAL_IMAGE 2
#define SWITCH_NOTFOUND -1
@protocol ENGPhotoSubmitterServiceSettingTableViewProtocol <NSObject>
- (id<ENGPhotoSubmitterProtocol>) submitter;
- (ENGPhotoSubmitterAccount *) account;
@end
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_connect_socket_system_31.c
Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml
Template File: sources-sink-31.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Fixed string
* Sinks: system
* BadSink : Execute command in data using system()
* Flow Variant: 31 Data flow using a copy of data within the same function
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define FULL_COMMAND L"dir "
#else
#include <unistd.h>
#define FULL_COMMAND L"ls "
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#ifdef _WIN32
#define SYSTEM _wsystem
#else /* NOT _WIN32 */
#define SYSTEM system
#endif
#ifndef OMITBAD
void CWE78_OS_Command_Injection__wchar_t_connect_socket_system_31_bad()
{
wchar_t * data;
wchar_t data_buf[100] = FULL_COMMAND;
data = data_buf;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
{
wchar_t * dataCopy = data;
wchar_t * data = dataCopy;
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
if (SYSTEM(data) != 0)
{
printLine("command execution failed!");
exit(1);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t data_buf[100] = FULL_COMMAND;
data = data_buf;
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
{
wchar_t * dataCopy = data;
wchar_t * data = dataCopy;
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
if (SYSTEM(data) != 0)
{
printLine("command execution failed!");
exit(1);
}
}
}
void CWE78_OS_Command_Injection__wchar_t_connect_socket_system_31_good()
{
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()...");
CWE78_OS_Command_Injection__wchar_t_connect_socket_system_31_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__wchar_t_connect_socket_system_31_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_connect_socket_execlp_54c.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-54c.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Fixed string
* Sink: execlp
* BadSink : execute command with execlp
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#ifdef _WIN32
#include <process.h>
#define EXECLP _execlp
#else /* NOT _WIN32 */
#define EXECLP execlp
#endif
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
/* bad function declaration */
void CWE78_OS_Command_Injection__char_connect_socket_execlp_54d_badSink(char * data);
void CWE78_OS_Command_Injection__char_connect_socket_execlp_54c_badSink(char * data)
{
CWE78_OS_Command_Injection__char_connect_socket_execlp_54d_badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declaration */
void CWE78_OS_Command_Injection__char_connect_socket_execlp_54d_goodG2BSink(char * data);
/* goodG2B uses the GoodSource with the BadSink */
void CWE78_OS_Command_Injection__char_connect_socket_execlp_54c_goodG2BSink(char * data)
{
CWE78_OS_Command_Injection__char_connect_socket_execlp_54d_goodG2BSink(data);
}
#endif /* OMITGOOD */
|
//
// SDLChoiceSetManager.h
// SmartDeviceLink
//
// Created by Joel Fischer on 5/21/18.
// Copyright © 2018 smartdevicelink. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SDLInteractionMode.h"
@class SDLChoiceCell;
@class SDLChoiceSet;
@class SDLFileManager;
@class SDLKeyboardProperties;
@protocol SDLConnectionManagerType;
@protocol SDLKeyboardDelegate;
NS_ASSUME_NONNULL_BEGIN
typedef void(^SDLPreloadChoiceCompletionHandler)(NSError *__nullable error);
typedef NSString SDLChoiceManagerState;
extern SDLChoiceManagerState *const SDLChoiceManagerStateShutdown;
extern SDLChoiceManagerState *const SDLChoiceManagerStateCheckingVoiceOptional;
extern SDLChoiceManagerState *const SDLChoiceManagerStateReady;
extern SDLChoiceManagerState *const SDLChoiceManagerStateStartupError;
@interface SDLChoiceSetManager : NSObject
/**
* The state of the choice set manager.
*/
@property (copy, nonatomic, readonly) NSString *currentState;
/**
The default keyboard configuration, this can be additionally customized by each SDLKeyboardDelegate.
*/
@property (strong, nonatomic, null_resettable) SDLKeyboardProperties *keyboardConfiguration;
/**
Cells will be hashed by their text, image names, and VR command text. When assembling an SDLChoiceSet, you can pull objects from here, or recreate them. The preloaded versions will be used so long as their text, image names, and VR commands are the same.
*/
@property (copy, nonatomic, readonly) NSSet<SDLChoiceCell *> *preloadedChoices;
/**
Initialize the manager with required dependencies
@param connectionManager The connection manager object for sending RPCs
@param fileManager The file manager object for uploading files
@return The choice set manager
*/
- (instancetype)initWithConnectionManager:(id<SDLConnectionManagerType>)connectionManager fileManager:(SDLFileManager *)fileManager;
/**
Start the manager and prepare to manage choice sets
*/
- (void)start;
/**
Stop the manager and reset all properties
*/
- (void)stop;
/**
Preload cells to the head unit. This will *greatly* reduce the time taken to present a choice set. Any already matching a choice already on the head unit will be ignored. You *do not* need to wait until the completion handler is called to present a choice set containing choices being loaded. The choice set will wait until the preload completes and then immediately present.
@param choices The choices to be preloaded.
@param handler The handler to be called when complete.
*/
- (void)preloadChoices:(NSArray<SDLChoiceCell *> *)choices withCompletionHandler:(nullable SDLPreloadChoiceCompletionHandler)handler;
/**
Delete loaded cells from the head unit. If the cells don't exist on the head unit they will be ignored.
@param choices The choices to be deleted. These will be matched via a hash of the text, image name(s), and VR commands.
*/
- (void)deleteChoices:(NSArray<SDLChoiceCell *> *)choices;
/**
Present a choice set on the head unit with a certain interaction mode. You should present in VR only if the user reached this choice set by using their voice, in Manual only if the user used touch to reach this choice set. Use Both if you're lazy...for real though, it's kind of confusing to the user and isn't recommended.
This presents the choice set as searchable when in a touch interaction. The user, when not in a distracted state, will have a keyboard available for searching this set. The user's input in the keyboard will be available in the SDLKeyboardDelegate.
If the cells in the set are not already preloaded, they will be preloaded before the presentation occurs; this could take a while depending on the contents of the cells.
If the cells have voice commands and images attached, this could take upwards of 10 seconds. If there are no cells on the set, this will fail, calling `choiceSet:didReceiveError:` on the choice set delegate.
@param choiceSet The set to be displayed
@param mode If the set should be presented for the user to interact via voice, touch, or both
@param delegate The keyboard delegate called when the user interacts with the search field of the choice set, if not set, a non-searchable choice set will be used
*/
- (void)presentChoiceSet:(SDLChoiceSet *)choiceSet mode:(SDLInteractionMode)mode withKeyboardDelegate:(nullable id<SDLKeyboardDelegate>)delegate;
/**
Present a keyboard-only interface to the user and receive input. The user will be able to input text in the keyboard when in a non-driver distraction situation.
@param initialText The initial text within the keyboard input field. It will disappear once the user selects the field in order to enter text
@param delegate The keyboard delegate called when the user interacts with the keyboard
*/
- (void)presentKeyboardWithInitialText:(NSString *)initialText delegate:(id<SDLKeyboardDelegate>)delegate;
@end
NS_ASSUME_NONNULL_END
|
//
// PhoneFinder.h
// PhoneFinder
//
// Created by John Brewer on 4/28/14.
// Copyright (c) 2014 Jera Design LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "PhoneFinderDelegate.h"
#import "CVFRomoHandlerDelegate.h"
@interface PhoneFinder : NSObject<CLLocationManagerDelegate, CVFRomoHandlerDelegate>
@property (nonatomic, weak) NSObject<PhoneFinderDelegate> *delegate;
- (void)findPhone;
@end
|
/*
* Copyright (c) 2010 The VP8 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef __INC_IDCT_H
#define __INC_IDCT_H
#define prototype_second_order(sym) \
void sym(short *input, short *output)
#define prototype_idct(sym) \
void sym(short *input, short *output, int pitch)
#define prototype_idct_scalar_add(sym) \
void sym(short input, \
unsigned char *pred, unsigned char *output, \
int pitch, int stride)
#if ARCH_X86 || ARCH_X86_64
#include "x86/idct_x86.h"
#endif
#if ARCH_ARM
#include "arm/idct_arm.h"
#endif
#ifndef vp8_idct_idct1
#define vp8_idct_idct1 vp8_short_idct4x4llm_1_c
#endif
extern prototype_idct(vp8_idct_idct1);
#ifndef vp8_idct_idct16
#define vp8_idct_idct16 vp8_short_idct4x4llm_c
#endif
extern prototype_idct(vp8_idct_idct16);
#ifndef vp8_idct_idct1_scalar_add
#define vp8_idct_idct1_scalar_add vp8_dc_only_idct_add_c
#endif
extern prototype_idct_scalar_add(vp8_idct_idct1_scalar_add);
#ifndef vp8_idct_iwalsh1
#define vp8_idct_iwalsh1 vp8_short_inv_walsh4x4_1_c
#endif
extern prototype_second_order(vp8_idct_iwalsh1);
#ifndef vp8_idct_iwalsh16
#define vp8_idct_iwalsh16 vp8_short_inv_walsh4x4_c
#endif
extern prototype_second_order(vp8_idct_iwalsh16);
typedef prototype_idct((*vp8_idct_fn_t));
typedef prototype_idct_scalar_add((*vp8_idct_scalar_add_fn_t));
typedef prototype_second_order((*vp8_second_order_fn_t));
typedef struct
{
vp8_idct_fn_t idct1;
vp8_idct_fn_t idct16;
vp8_idct_scalar_add_fn_t idct1_scalar_add;
vp8_second_order_fn_t iwalsh1;
vp8_second_order_fn_t iwalsh16;
} vp8_idct_rtcd_vtable_t;
#if CONFIG_RUNTIME_CPU_DETECT
#define IDCT_INVOKE(ctx,fn) (ctx)->fn
#else
#define IDCT_INVOKE(ctx,fn) vp8_idct_##fn
#endif
#endif
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <ABI42_0_0React/components/safeareaview/SafeAreaViewShadowNode.h>
#include <ABI42_0_0React/core/ConcreteComponentDescriptor.h>
namespace ABI42_0_0facebook {
namespace ABI42_0_0React {
/*
* Descriptor for <SafeAreaView> component.
*/
class SafeAreaViewComponentDescriptor final
: public ConcreteComponentDescriptor<SafeAreaViewShadowNode> {
using ConcreteComponentDescriptor::ConcreteComponentDescriptor;
void adopt(UnsharedShadowNode shadowNode) const override {
assert(std::dynamic_pointer_cast<SafeAreaViewShadowNode>(shadowNode));
auto safeAreaViewShadowNode =
std::static_pointer_cast<SafeAreaViewShadowNode>(shadowNode);
assert(std::dynamic_pointer_cast<YogaLayoutableShadowNode>(
safeAreaViewShadowNode));
auto layoutableShadowNode =
std::static_pointer_cast<YogaLayoutableShadowNode>(
safeAreaViewShadowNode);
auto state =
std::static_pointer_cast<const SafeAreaViewShadowNode::ConcreteState>(
shadowNode->getState());
auto stateData = state->getData();
if (safeAreaViewShadowNode->alreadyAppliedPadding != stateData.padding) {
safeAreaViewShadowNode->alreadyAppliedPadding = stateData.padding;
layoutableShadowNode->setPadding(stateData.padding);
}
ConcreteComponentDescriptor::adopt(shadowNode);
}
};
} // namespace ABI42_0_0React
} // namespace ABI42_0_0facebook
|
/*
*
* National Security Research Institute
*
* FELICS - Fair Evaluation of Lightweight Cryptographic Systems
*
* Copyright (C) 2015 National Security Research Institute
*
* Written in 2015 by Ilwoong Jeong <iw98jeong@nsr.re.kr>
*
* This file is part of FELICS.
*
* FELICS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* FELICS 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, see <http://www.gnu.org/licenses/>.
*
*/
/*
*
* University of Luxembourg
* Laboratory of Algorithmics, Cryptology and Security (LACS)
*
* FELICS - Fair Evaluation of Lightweight Cryptographic Systems
*
* Copyright (C) 2015 University of Luxembourg
*
* Written in 2015 by Daniel Dinu <dumitru-daniel.dinu@uni.lu>
*
* This file is part of FELICS.
*
* FELICS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* FELICS 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, see <http://www.gnu.org/licenses/>.
*
*/
#include <stdint.h>
#include "cipher.h"
#include "constants.h"
#include "primitives.h"
#define RK(x, y) READ_ROUND_KEY_DOUBLE_WORD(x[y])
void Decrypt(uint8_t *block, uint8_t *roundKeys)
{
uint32_t* blk = (uint32_t*) block;
uint32_t* rk = (uint32_t*) roundKeys;
int8_t i;
for (i = NUMBER_OF_ROUNDS - 1, rk += 92; i >= 0; i -= 4, rk -= 4) {
blk[0] = (rotr(blk[0], 9) - (blk[3] ^ RK(rk, 0))) ^ RK(rk, 1);
blk[1] = (rotl(blk[1], 5) - (blk[0] ^ RK(rk, 2))) ^ RK(rk, 1);
blk[2] = (rotl(blk[2], 3) - (blk[1] ^ RK(rk, 3))) ^ RK(rk, 1);
rk -= 4;
blk[3] = (rotr(blk[3], 9) - (blk[2] ^ RK(rk, 0))) ^ RK(rk, 1);
blk[0] = (rotl(blk[0], 5) - (blk[3] ^ RK(rk, 2))) ^ RK(rk, 1);
blk[1] = (rotl(blk[1], 3) - (blk[0] ^ RK(rk, 3))) ^ RK(rk, 1);
rk -= 4;
blk[2] = (rotr(blk[2], 9) - (blk[1] ^ RK(rk, 0))) ^ RK(rk, 1);
blk[3] = (rotl(blk[3], 5) - (blk[2] ^ RK(rk, 2))) ^ RK(rk, 1);
blk[0] = (rotl(blk[0], 3) - (blk[3] ^ RK(rk, 3))) ^ RK(rk, 1);
rk -= 4;
blk[1] = (rotr(blk[1], 9) - (blk[0] ^ RK(rk, 0))) ^ RK(rk, 1);
blk[2] = (rotl(blk[2], 5) - (blk[1] ^ RK(rk, 2))) ^ RK(rk, 1);
blk[3] = (rotl(blk[3], 3) - (blk[2] ^ RK(rk, 3))) ^ RK(rk, 1);
}
}
|
#pragma once
#ifndef PENCILTESTPOPUP_H
#define PENCILTESTPOPUP_H
#include "toonzqt/dvdialog.h"
#include "toonzqt/lineedit.h"
#include <QFrame>
// forward decl.
class QCamera;
class QCameraImageCapture;
class QComboBox;
class QLineEdit;
class QSlider;
class QCheckBox;
class QPushButton;
class QVideoFrame;
class QTimer;
class QIntValidator;
class QRegExpValidator;
class QPushButton;
namespace DVGui {
class FileField;
class IntField;
}
//=============================================================================
// MyViewFinder
//-----------------------------------------------------------------------------
class MyViewFinder : public QFrame {
Q_OBJECT
QImage m_image;
QImage m_previousImage;
QCamera* m_camera;
QRect m_imageRect;
int m_countDownTime;
bool m_showOnionSkin;
int m_onionOpacity;
bool m_upsideDown;
public:
MyViewFinder(QWidget* parent = 0);
void setImage(const QImage& image) {
m_image = image;
update();
}
void setCamera(QCamera* camera) { m_camera = camera; }
void setShowOnionSkin(bool on) { m_showOnionSkin = on; }
void setOnionOpacity(int value) { m_onionOpacity = value; }
void setPreviousImage(QImage& prevImage) { m_previousImage = prevImage; }
void showCountDownTime(int time) {
m_countDownTime = time;
repaint();
}
void updateSize();
protected:
void paintEvent(QPaintEvent* event);
void resizeEvent(QResizeEvent* event);
protected slots:
void onUpsideDownChecked(bool on) { m_upsideDown = on; }
};
//=============================================================================
// FrameNumberLineEdit
// a special Line Edit which accepts imputting alphabets if the preference
// option
// "Show ABC Appendix to the Frame Number in Xsheet Cell" is active.
//-----------------------------------------------------------------------------
class FrameNumberLineEdit : public DVGui::LineEdit {
Q_OBJECT
/* having two validators and switch them according to the preferences*/
QIntValidator* m_intValidator;
QRegExpValidator* m_regexpValidator;
void updateValidator();
public:
FrameNumberLineEdit(QWidget* parent = 0, int value = 1);
~FrameNumberLineEdit() {}
/*! Set text in field to \b value. */
void setValue(int value);
/*! Return an integer with text field value. */
int getValue();
protected:
/*! If focus is lost and current text value is out of range emit signal
\b editingFinished.*/
void focusOutEvent(QFocusEvent*) override;
void showEvent(QShowEvent* event) override { updateValidator(); }
};
//=============================================================================
class LevelNameLineEdit : public QLineEdit {
Q_OBJECT
QString m_textOnFocusIn;
public:
LevelNameLineEdit(QWidget* parent = 0);
protected:
void focusInEvent(QFocusEvent* e);
protected slots:
void onEditingFinished();
signals:
void levelNameEdited();
};
//=============================================================================
// PencilTestSaveInFolderPopup
//-----------------------------------------------------------------------------
class PencilTestSaveInFolderPopup : public DVGui::Dialog {
Q_OBJECT
DVGui::FileField* m_parentFolderField;
QLineEdit *m_projectField, *m_episodeField, *m_sequenceField, *m_sceneField,
*m_subFolderNameField;
QCheckBox *m_subFolderCB, *m_autoSubNameCB;
QComboBox* m_subNameFormatCombo;
public:
PencilTestSaveInFolderPopup(QWidget* parent = 0);
QString getPath();
protected slots:
void updateSubFolderName();
void onAutoSubNameCBClicked(bool);
void onShowPopupOnLaunchCBClicked(bool);
void onOkPressed();
};
//=============================================================================
// PencilTestPopup
//-----------------------------------------------------------------------------
class PencilTestPopup : public DVGui::Dialog {
Q_OBJECT
QCamera* m_currentCamera;
QString m_deviceName;
MyViewFinder* m_cameraViewfinder;
QCameraImageCapture* m_cameraImageCapture;
QComboBox *m_cameraListCombo, *m_resolutionCombo, *m_fileTypeCombo,
*m_colorTypeCombo;
LevelNameLineEdit* m_levelNameEdit;
QCheckBox *m_upsideDownCB, *m_onionSkinCB, *m_saveOnCaptureCB, *m_timerCB;
QPushButton *m_fileFormatOptionButton, *m_captureWhiteBGButton,
*m_captureButton, *m_loadImageButton;
DVGui::FileField* m_saveInFileFld;
FrameNumberLineEdit* m_frameNumberEdit;
DVGui::IntField *m_thresholdFld, *m_contrastFld, *m_brightnessFld,
*m_bgReductionFld, *m_onionOpacityFld, *m_timerIntervalFld;
QTimer *m_captureTimer, *m_countdownTimer;
QImage m_whiteBGImg;
// used only for Windows
QPushButton* m_captureFilterSettingsBtn;
PencilTestSaveInFolderPopup* m_saveInFolderPopup;
int m_timerId;
QString m_cacheImagePath;
bool m_captureWhiteBGCue;
bool m_captureCue;
void processImage(QImage& procImage);
bool importImage(QImage& image);
public:
PencilTestPopup();
~PencilTestPopup();
protected:
void timerEvent(QTimerEvent* event);
void showEvent(QShowEvent* event);
void hideEvent(QHideEvent* event);
void keyPressEvent(QKeyEvent* event);
protected slots:
void refreshCameraList();
void onCameraListComboActivated(int index);
void onResolutionComboActivated(const QString&);
void onFileFormatOptionButtonPressed();
void onLevelNameEdited();
void onNextName();
void onColorTypeComboChanged(int index);
void onImageCaptured(int, const QImage&);
void onCaptureWhiteBGButtonPressed();
void onOnionCBToggled(bool);
void onLoadImageButtonPressed();
void onOnionOpacityFldEdited();
void onTimerCBToggled(bool);
void onCaptureTimerTimeout();
void onCountDown();
void onCaptureButtonClicked(bool);
void onCaptureFilterSettingsBtnPressed();
public slots:
void openSaveInFolderPopup();
};
#endif |
/* /////////////////////////////////////////////////////////////////////////
* File: src/backends/ber/ber.WindowsDebugger.c
*
* Purpose: Implementation of ber.WindowsDebugger
*
* Created: 4th February 2006
* Updated: 23rd December 2010
*
* Home: http://www.pantheios.org/
*
* Copyright (c) 2006-2010, Matthew Wilson and Synesis Software
* 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(s) of Matthew Wilson and Synesis Software 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 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.
*
* ////////////////////////////////////////////////////////////////////// */
#include <pantheios/pantheios.h>
#include <pantheios/backends/be.lrsplit.h>
#include <pantheios/backends/bec.WindowsDebugger.h>
/* /////////////////////////////////////////////////////////////////////////
* API
*/
PANTHEIOS_BE_DEFINE_BER_FUNCTIONS(WindowsDebugger)
/* ///////////////////////////// end of file //////////////////////////// */
|
#include "drmaa2-list.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
void drmaa2_list_free (drmaa2_list * listref) {
drmaa2_list l = *listref;
if (l == NULL)
return;
drmaa2_list_item head = (drmaa2_list_item)l->head;
drmaa2_list_item tmp;
while (head != NULL) {
tmp = head;
head = tmp->next;
if (l->free_entry != NULL)
l->free_entry((void **)&(tmp->data));
free(tmp);
}
free(l);
*listref = NULL;
}
const void *drmaa2_list_get (const drmaa2_list l, long pos) {
if (l == NULL)
return NULL;
if (pos < 0 || pos >= l->size)
return NULL;
drmaa2_list_item current_item = (drmaa2_list_item)l->head;
long i;
for (i = 0; i < pos; i++)
current_item = current_item->next;
return current_item->data;
}
drmaa2_error drmaa2_list_add (drmaa2_list l, const void * value) {
if (l == NULL)
return DRMAA2_INVALID_ARGUMENT;
drmaa2_list_item new_item;
if ((new_item = (drmaa2_list_item)malloc(sizeof(drmaa2_list_item))) == NULL) {
printf("bad allocation\n");
return DRMAA2_OUT_OF_RESOURCE;
}
new_item->data = value;
new_item->next = NULL;
if (l->head == NULL) {
l->head = new_item;
}
else {
drmaa2_list_item current_item = (drmaa2_list_item)l->head;
while (current_item->next)
current_item = current_item->next;
current_item->next = new_item;
}
l->size++;
return DRMAA2_SUCCESS;
}
drmaa2_error drmaa2_list_del (drmaa2_list l, long pos) {
if (l == NULL)
return DRMAA2_INVALID_ARGUMENT;
if (pos < 0 || pos >= l->size)
return DRMAA2_INVALID_ARGUMENT;
drmaa2_list_item current_item = (drmaa2_list_item)l->head;
if (pos == 0) {
drmaa2_list_item to_delete = current_item;
l->head = to_delete->next;
l->size--;
if (l->free_entry != NULL) l->free_entry((void *)to_delete->data);
free(to_delete);
return DRMAA2_SUCCESS;
}
long i;
for (i = 0; i < pos-1; i++)
current_item = current_item->next;
//current_item points to the item before the one we want to remove
drmaa2_list_item to_delete = current_item->next;
current_item->next = to_delete->next;
l->size--;
if (l->free_entry != NULL) l->free_entry((void *)to_delete->data);
free(to_delete);
return DRMAA2_SUCCESS;
}
long drmaa2_list_size (const drmaa2_list l) {
if (l == NULL)
return -1;
return l->size;
}
drmaa2_list drmaa2_list_create (const drmaa2_listtype t, const drmaa2_list_entryfree callback) {
drmaa2_list l;
l = (drmaa2_list)malloc(sizeof(drmaa2_list_s));
l->free_entry = callback;
l->type = t;
l->size = 0;
l->head = NULL;
switch (l->type) {
case DRMAA2_STRINGLIST:
return (drmaa2_string_list)l;
break;
case DRMAA2_JOBLIST:
return (drmaa2_j_list)l;
break;
case DRMAA2_QUEUEINFOLIST:
return (drmaa2_queueinfo_list)l;
break;
case DRMAA2_MACHINEINFOLIST:
return (drmaa2_machineinfo_list)l;
break;
case DRMAA2_SLOTINFOLIST:
return (drmaa2_slotinfo_list)l;
break;
case DRMAA2_RESERVATIONLIST:
return (drmaa2_r_list)l;
break;
default:
return l;
}
}
drmaa2_string_list string_split(const char *string, char separator) {
if (string == NULL)
return DRMAA2_UNSET_LIST;
drmaa2_string_list sl = drmaa2_list_create(DRMAA2_STRINGLIST, (drmaa2_list_entryfree)drmaa2_string_free);
char *rest = (char *)string;
char *to_insert;
char *separator_pos;
while((separator_pos = strchr(rest, separator)) != NULL) {
to_insert = (char *)malloc(sizeof(char) * (separator_pos-rest+1));
strncpy(to_insert, rest, separator_pos-rest);
to_insert[separator_pos-rest] = '\0';
drmaa2_list_add(sl, to_insert);
rest = separator_pos + 1;
}
to_insert = (char *)malloc(sizeof(char) * (strlen(rest)+1));
strncpy(to_insert, rest, strlen(rest));
to_insert[strlen(rest)] = '\0';
drmaa2_list_add(sl, to_insert);
return sl;
}
drmaa2_string string_join(drmaa2_string_list sl, char separator) {
if (sl == NULL || drmaa2_list_size(sl) == 0)
return NULL;
size_t character_count = 0;
//we calculate space for items, separators and terminating '\0'
size_t i;
for (i = 0; i < drmaa2_list_size(sl); i++)
character_count += strlen(drmaa2_list_get(sl, i)) + 1;
drmaa2_string string = (char *)malloc(sizeof(char) * character_count);
char *next_cpy_pos = string;
char *to_insert = NULL;
for (i = 0; i < drmaa2_list_size(sl); i++) {
to_insert = (char *)drmaa2_list_get(sl, i);
size_t item_len = strlen(to_insert);
strncpy(next_cpy_pos, to_insert, item_len);
next_cpy_pos[item_len] = separator;
next_cpy_pos += item_len + 1;
}
string[character_count-1] = '\0';
return string;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkGeoFileImageSource.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkGeoFileImageSource - A tiled image source on disk.
//
// .SECTION Description
// vtkGeoFileImageSource is a vtkGeoSource that fetches .vti images from
// disk in a directory with a certain naming scheme. You may use
// vtkGeoAlignedImageRepresentation's SaveDatabase method to generate
// an database of image tiles in this format.
#ifndef vtkGeoFileImageSource_h
#define vtkGeoFileImageSource_h
#include "vtkGeovisCoreModule.h" // For export macro
#include "vtkGeoSource.h"
#include "vtkSmartPointer.h" // For smart pointer ivars
class vtkGeoImageNode;
class vtkGeoTreeNode;
class VTKGEOVISCORE_EXPORT vtkGeoFileImageSource : public vtkGeoSource
{
public:
static vtkGeoFileImageSource *New();
vtkTypeMacro(vtkGeoFileImageSource,vtkGeoSource);
void PrintSelf(ostream& os, vtkIndent indent);
vtkGeoFileImageSource();
~vtkGeoFileImageSource();
// Description:
// Fetches the root image representing the whole globe.
virtual bool FetchRoot(vtkGeoTreeNode* root);
// Description:
// Fetches the child image of a parent from disk.
virtual bool FetchChild(vtkGeoTreeNode* node, int index, vtkGeoTreeNode* child);
// Description:
// The path the tiled image database.
vtkSetStringMacro(Path);
vtkGetStringMacro(Path);
protected:
bool ReadImage(int level, int id, vtkGeoImageNode* node);
private:
vtkGeoFileImageSource(const vtkGeoFileImageSource&); // Not implemented
void operator=(const vtkGeoFileImageSource&); // Not implemented
char* Path;
};
#endif
|
//
// VPLASIHTTPResponse.h
// VPLHTTPClient
//
// Created by Christian Niles on 5/24/11.
// Copyright 2011 Vulpine Labs LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "VPLHTTPResponseBase.h"
@class ASIHTTPRequest;
@interface VPLASIHTTPResponse : VPLHTTPResponseBase {
@private
ASIHTTPRequest * _asiHttpRequest;
}
- (id)initWithRequest:(ASIHTTPRequest *)request;
+ (VPLASIHTTPResponse *)responseWithRequest:(ASIHTTPRequest *)request;
// ===== HTTP REQUEST ==================================================================================================
- (ASIHTTPRequest *)_httpRequest;
// ===== ERROR =========================================================================================================
+ (NSError *)errorWithASIError:(NSError *)requestInError;
@end
|
/* ntservice.h
*
* Copyright (c) 2006 Germán Méndez Bravo (Kronuz) <kronuz@users.sf.net>
* All rights reserved.
*
*/
#ifndef SERVICE_H
#define SERVICE_H
typedef void (*svcFunc) ();
int ServiceStart();
int ServiceStop();
int ServiceRestart();
int ServiceUninstall();
int ServiceInstall();
int ServiceRun();
void ServiceSetFunc(svcFunc runFunc, svcFunc pauseFunc, svcFunc continueFunc, svcFunc stopFunc);
#endif
|
// Copyright 2021 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 COMPONENTS_SYNC_TRUSTED_VAULT_FAKE_SECURITY_DOMAINS_SERVER_H_
#define COMPONENTS_SYNC_TRUSTED_VAULT_FAKE_SECURITY_DOMAINS_SERVER_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/memory/scoped_refptr.h"
#include "base/observer_list_threadsafe.h"
#include "base/synchronization/lock.h"
#include "base/thread_annotations.h"
#include "components/sync/protocol/vault.pb.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "url/gurl.h"
namespace syncer {
// Mimics behavior of the security domains server. This class is designed to be
// used with EmbeddedTestServer via registration of HandleRequest() method.
class FakeSecurityDomainsServer {
public:
class Observer : public base::CheckedObserver {
public:
// Called when handling of request is completed. Called iff request is
// supposed to be handled by FakeSecurityDomainsServer (determined by the
// URL prefix).
virtual void OnRequestHandled() = 0;
};
static GURL GetServerURL(GURL base_url);
explicit FakeSecurityDomainsServer(GURL base_url);
FakeSecurityDomainsServer(const FakeSecurityDomainsServer& other) = delete;
FakeSecurityDomainsServer& operator=(const FakeSecurityDomainsServer& other) =
delete;
~FakeSecurityDomainsServer();
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
// Handles request if it belongs to security domains server (identified by
// request url). Returns nullptr otherwise.
// Unlike other methods of this class, which should be called on main thread,
// this method is called on EmbeddedTestServer IO thread.
std::unique_ptr<net::test_server::HttpResponse> HandleRequest(
const net::test_server::HttpRequest& http_request);
// Rotates trusted vault key by adding new shared key for all members. Returns
// new trusted vault key.
std::vector<uint8_t> RotateTrustedVaultKey(
const std::vector<uint8_t>& last_trusted_vault_key);
// Causes the security domain to enter the degraded recoverability state
// unless the provided |public_key| matches a member's public key.
void RequirePublicKeyToAvoidRecoverabilityDegraded(
const std::vector<uint8_t>& public_key);
int GetMemberCount() const;
bool AllMembersHaveKey(const std::vector<uint8_t>& trusted_vault_key) const;
int GetCurrentEpoch() const;
bool IsRecoverabilityDegraded() const;
// Returns true if there was a request that violates supported protocol.
bool ReceivedInvalidRequest() const;
private:
std::unique_ptr<net::test_server::HttpResponse>
HandleJoinSecurityDomainsRequest(
const net::test_server::HttpRequest& http_request);
std::unique_ptr<net::test_server::HttpResponse>
HandleGetSecurityDomainMemberRequest(
const net::test_server::HttpRequest& http_request);
std::unique_ptr<net::test_server::HttpResponse>
HandleGetSecurityDomainRequest(
const net::test_server::HttpRequest& http_request);
class State {
public:
State();
State(const State& other) = delete;
State& operator=(const State& other) = delete;
~State();
bool received_invalid_request = false;
// Maps members public key to shared keys that belong to this member.
std::map<std::string, std::vector<sync_pb::SharedMemberKey>>
public_key_to_shared_keys;
// Maps members public key to rotation proofs of members shared keys.
std::map<std::string, std::vector<sync_pb::RotationProof>>
public_key_to_rotation_proofs;
// Zero epoch is used when there are no members in the security domain, once
// first member is joined it is initialized to non-zero value. Members still
// can join with constant key without populating epoch while
// |constant_key_allowed_| set to true.
int current_epoch = 0;
bool constant_key_allowed = true;
std::string required_public_key_to_avoid_recoverability_degraded;
};
// This class is used on main thread and on EmbeddedTestServer IO thread, data
// access is protected by |lock_|.
mutable base::Lock lock_;
const GURL server_url_;
State state_ GUARDED_BY(lock_);
const scoped_refptr<base::ObserverListThreadSafe<Observer>> observers_;
};
} // namespace syncer
#endif // COMPONENTS_SYNC_TRUSTED_VAULT_FAKE_SECURITY_DOMAINS_SERVER_H_
|
/**************************************************************************/
/*!
@file cpu.h
@author K. Townsend (microBuilder.eu)
@date 22 March 2010
@version 0.10
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2010, microBuilder SARL
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. Neither the name of the copyright holders 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 ''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 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 _CPU_H_
#define _CPU_H_
#include "projectconfig.h"
typedef enum
{
CPU_MULTIPLIER_1 = 0,
CPU_MULTIPLIER_2,
CPU_MULTIPLIER_3,
CPU_MULTIPLIER_4
}
cpuMultiplier_t;
void cpuPllSetup (cpuMultiplier_t multiplier);
void cpuInit (void);
uint32_t cpuGetDeviceID (void);
void cpuReset (void);
#endif |
//
// YaabUser.h
// Yaab
//
// Created by 魏琮举 on 13-4-26.
//
//
#import <Foundation/Foundation.h>
#import <RHAddressBook/AddressBook.h>
#import "MDUser.h"
#import "MDHTTPAPI.h"
@interface YaabUser : NSObject
{
NSUserDefaults *nsUser;
}
@property (nonatomic, strong) NSString *deviceToken;
@property (nonatomic, strong) MDUser *user;
@property (strong) NSMutableDictionary *users;
@property (strong) NSMutableDictionary *apis;
@property (strong) NSString *service;
-(void)setDeviceToken:(NSString *)deviceToken;
-(NSString *)getDeviceTokenWithData:(NSData *)nsdataToken;
-(MDUser *)userWithID:(NSInteger)aUserID;
-(void)addUser:(MDUser *)aUser;
-(MDHTTPAPI *)apiWithUserID:(NSInteger)aUserID;
-(MDHTTPAPI *)api;
-(void)addAPI:(MDHTTPAPI *)aMDHTTPAPI user:(MDUser *)aUser;
+(YaabUser *)sharedInstance;
@end
|
/*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_CRYPTO_SPARSE_ARRAY_H
# define OSSL_CRYPTO_SPARSE_ARRAY_H
# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3))
# pragma once
# endif
# include <openssl/e_os2.h>
# ifdef __cplusplus
extern "C" {
# endif
# define SPARSE_ARRAY_OF(type) struct sparse_array_st_ ## type
# define DEFINE_SPARSE_ARRAY_OF_INTERNAL(type, ctype) \
SPARSE_ARRAY_OF(type); \
static ossl_unused ossl_inline SPARSE_ARRAY_OF(type) * \
ossl_sa_##type##_new(void) \
{ \
return (SPARSE_ARRAY_OF(type) *)ossl_sa_new(); \
} \
static ossl_unused ossl_inline void \
ossl_sa_##type##_free(SPARSE_ARRAY_OF(type) *sa) \
{ \
ossl_sa_free((OPENSSL_SA *)sa); \
} \
static ossl_unused ossl_inline void \
ossl_sa_##type##_free_leaves(SPARSE_ARRAY_OF(type) *sa) \
{ \
ossl_sa_free_leaves((OPENSSL_SA *)sa); \
} \
static ossl_unused ossl_inline size_t \
ossl_sa_##type##_num(const SPARSE_ARRAY_OF(type) *sa) \
{ \
return ossl_sa_num((OPENSSL_SA *)sa); \
} \
static ossl_unused ossl_inline void \
ossl_sa_##type##_doall(const SPARSE_ARRAY_OF(type) *sa, \
void (*leaf)(ossl_uintmax_t, type *)) \
{ \
ossl_sa_doall((OPENSSL_SA *)sa, \
(void (*)(ossl_uintmax_t, void *))leaf); \
} \
static ossl_unused ossl_inline void \
ossl_sa_##type##_doall_arg(const SPARSE_ARRAY_OF(type) *sa, \
void (*leaf)(ossl_uintmax_t, type *, void *), \
void *arg) \
{ \
ossl_sa_doall_arg((OPENSSL_SA *)sa, \
(void (*)(ossl_uintmax_t, void *, void *))leaf, arg); \
} \
static ossl_unused ossl_inline ctype \
*ossl_sa_##type##_get(const SPARSE_ARRAY_OF(type) *sa, ossl_uintmax_t n) \
{ \
return (type *)ossl_sa_get((OPENSSL_SA *)sa, n); \
} \
static ossl_unused ossl_inline int \
ossl_sa_##type##_set(SPARSE_ARRAY_OF(type) *sa, \
ossl_uintmax_t n, ctype *val) \
{ \
return ossl_sa_set((OPENSSL_SA *)sa, n, (void *)val); \
} \
SPARSE_ARRAY_OF(type)
# define DEFINE_SPARSE_ARRAY_OF(type) \
DEFINE_SPARSE_ARRAY_OF_INTERNAL(type, type)
# define DEFINE_SPARSE_ARRAY_OF_CONST(type) \
DEFINE_SPARSE_ARRAY_OF_INTERNAL(type, const type)
typedef struct sparse_array_st OPENSSL_SA;
OPENSSL_SA *ossl_sa_new(void);
void ossl_sa_free(OPENSSL_SA *sa);
void ossl_sa_free_leaves(OPENSSL_SA *sa);
size_t ossl_sa_num(const OPENSSL_SA *sa);
void ossl_sa_doall(const OPENSSL_SA *sa, void (*leaf)(ossl_uintmax_t, void *));
void ossl_sa_doall_arg(const OPENSSL_SA *sa,
void (*leaf)(ossl_uintmax_t, void *, void *), void *);
void *ossl_sa_get(const OPENSSL_SA *sa, ossl_uintmax_t n);
int ossl_sa_set(OPENSSL_SA *sa, ossl_uintmax_t n, void *val);
# ifdef __cplusplus
}
# endif
#endif
|
/*
* Editor UI ribbon toolbar header
*
* This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#ifndef __FORK_EDITOR_UI_RIBBON_TOOL_BAR_H__
#define __FORK_EDITOR_UI_RIBBON_TOOL_BAR_H__
#include <wx/ribbon/toolbar.h>
#include <wx/artprov.h>
#include <wx/bitmap.h>
namespace Fork
{
namespace Editor
{
class UIComboBox;
class UIRibbonToolBar : public wxRibbonToolBar
{
public:
UIRibbonToolBar(wxWindow* parent, wxWindowID id = wxID_ANY);
virtual ~UIRibbonToolBar();
static wxBitmap GetBitmap(const wxArtID &Id);
};
} // /namespace Editor
} // /namespace Fork
#endif
// ======================== |
/*
* Greybus Simulator
*
* Copyright 2014 Google Inc.
* Copyright 2014 Linaro Ltd.
*
* Provided under the three clause BSD license found in the LICENSE file.
*/
#include <stdlib.h>
#include <stdio.h>
#include <linux/types.h>
#include <unistd.h>
#include <greybus_manifest.h>
#include "gbsim.h"
#define ES1_MSG_SIZE (4 * 1024)
static char *get_protocol(__le16 id)
{
struct gbsim_cport *cport;
TAILQ_FOREACH(cport, &info.cports, cnode) {
if (cport->id == id) {
switch (cport->protocol) {
case GREYBUS_PROTOCOL_GPIO:
return "GPIO";
case GREYBUS_PROTOCOL_I2C:
return "I2C";
case GREYBUS_PROTOCOL_PWM:
return "PWM";
}
}
}
return "N/A";
}
static void exec_subdev_handler(__le16 id, __u8 *rbuf, size_t size)
{
struct gbsim_cport *cport;
TAILQ_FOREACH(cport, &info.cports, cnode) {
if (cport->id == id)
switch (cport->protocol) {
case GREYBUS_PROTOCOL_GPIO:
gpio_handler(rbuf, size);
break;
case GREYBUS_PROTOCOL_I2C:
i2c_handler(rbuf, size);
break;
case GREYBUS_PROTOCOL_PWM:
pwm_handler(rbuf, size);
break;
default:
gbsim_error("subdev handler not found for cport %d\n",
id);
}
}
}
void cport_handler(__u8 *rbuf, size_t size)
{
/* FIXME pass cport_msg directly? */
struct cport_msg *cmsg = (struct cport_msg *)rbuf;
/* FIXME: can identify module from our cport connection */
gbsim_debug("AP -> Module %d CPort %d %s request\n ",
cport_to_module_id(cmsg->cport),
cmsg->cport,
get_protocol(cmsg->cport));
if (verbose)
gbsim_dump(cmsg->data, size - 1);
exec_subdev_handler(cmsg->cport, rbuf, size);
free(rbuf);
}
void cport_thread_cleanup(void *arg)
{
cleanup_endpoint(svc_int, "svc_int");
cleanup_endpoint(cport_in, "cport_in");
cleanup_endpoint(cport_out, "cport_out");
}
void *cport_thread(void *param)
{
size_t size;
__u8 *rbuf;
do {
rbuf = malloc(ES1_MSG_SIZE);
if (!rbuf) {
gbsim_error("failed to allocate receive buffer\n");
return NULL;
}
/* blocking read for our max buf size */
size = read(cport_out, rbuf, ES1_MSG_SIZE);
if (size < 0) {
gbsim_error("failed to read from CPort OUT endpoint\n");
return NULL;
}
cport_handler(rbuf, size);
} while (1);
}
|
/* $NetBSD: ramdac.h,v 1.2 2000/04/02 18:54:33 nathanw Exp $ */
/*-
* Copyright (c) 1998, 1999 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Roland C. Dowdeswell.
*
* 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 _DEV_IC_RAMDAC_H
#define _DEV_IC_RAMDAC_H
#include <dev/rcons/raster.h>
#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wscons_raster.h>
struct ramdac_cookie;
struct ramdac_funcs {
char *ramdac_name;
struct ramdac_cookie *(*ramdac_register) __P((void *,
int (*)(void *, void (*)(void *)),
void (*)(void *, u_int, u_int8_t),
u_int8_t (*)(void *, u_int)));
void (*ramdac_init) __P((struct ramdac_cookie *));
int (*ramdac_set_cmap) __P((struct ramdac_cookie *,
struct wsdisplay_cmap *));
int (*ramdac_get_cmap) __P((struct ramdac_cookie *,
struct wsdisplay_cmap *));
int (*ramdac_set_cursor) __P((struct ramdac_cookie *,
struct wsdisplay_cursor *));
int (*ramdac_get_cursor) __P((struct ramdac_cookie *,
struct wsdisplay_cursor *));
int (*ramdac_set_curpos) __P((struct ramdac_cookie *,
struct wsdisplay_curpos *));
int (*ramdac_get_curpos) __P((struct ramdac_cookie *,
struct wsdisplay_curpos *));
int (*ramdac_get_curmax) __P((struct ramdac_cookie *,
struct wsdisplay_curpos *));
/* Only called from the TGA built-in cursor handling code. */
int (*ramdac_check_curcmap) __P((struct ramdac_cookie *,
struct wsdisplay_cursor *));
void (*ramdac_set_curcmap) __P((struct ramdac_cookie *,
struct wsdisplay_cursor *));
int (*ramdac_get_curcmap) __P((struct ramdac_cookie *,
struct wsdisplay_cursor *));
};
#endif
|
// Copyright 2019 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef STARBOARD_EVERGREEN_ARM_SOFTFP_SBVERSION_12_ATOMIC_PUBLIC_H_
#define STARBOARD_EVERGREEN_ARM_SOFTFP_SBVERSION_12_ATOMIC_PUBLIC_H_
#include "starboard/evergreen/arm/softfp/atomic_public.h"
#endif // STARBOARD_EVERGREEN_ARM_SOFTFP_SBVERSION_12_ATOMIC_PUBLIC_H_
|
/**************************************************************************/
/*!
@file protocol_support.h
@author K. Townsend (microBuilder.eu)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2013, K. Townsend (microBuilder.eu)
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. Neither the name of the copyright holders 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 ''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 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 _PROTOCOL_SUPPORT_H_
#define _PROTOCOL_SUPPORT_H_
#include "protocol.h"
extern fifo_t ff_prot_cmd; // command fifo in protocol.c
#if defined(CFG_PROTOCOL_VIA_HID)
#define command_received_isr usb_hid_generic_recv_isr
#define command_send usb_hid_generic_send
#elif defined(CFG_PROTOCOL_VIA_BULK)
#define command_received_isr usb_custom_received_isr
#define command_send usb_custom_send
#endif
#define MOCK_PROT(func, behavior) XSTRING_CONCAT(func, behavior)
#endif
|
/* /////////////////////////////////////////////////////////////////////////
* File: src/backends/bel/bel.WindowsDebugger.c
*
* Purpose: Implementation of bel.WindowsDebugger
*
* Created: 21st June 2005
* Updated: 23rd December 2010
*
* Home: http://www.pantheios.org/
*
* Copyright (c) 2005-2010, Matthew Wilson and Synesis Software
* 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(s) of Matthew Wilson and Synesis Software 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 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.
*
* ////////////////////////////////////////////////////////////////////// */
#include <pantheios/pantheios.h>
#include <pantheios/backends/be.lrsplit.h>
#include <pantheios/backends/bec.WindowsDebugger.h>
/* /////////////////////////////////////////////////////////////////////////
* API
*/
PANTHEIOS_BE_DEFINE_BEL_FUNCTIONS(WindowsDebugger)
/* ///////////////////////////// end of file //////////////////////////// */
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DEVICE_GEOLOCATION_GEOLOCATION_PROVIDER_IMPL_H_
#define DEVICE_GEOLOCATION_GEOLOCATION_PROVIDER_IMPL_H_
#include <list>
#include <memory>
#include <vector>
#include "base/callback_forward.h"
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/threading/thread.h"
#include "device/geolocation/geolocation_export.h"
#include "device/geolocation/geolocation_provider.h"
#include "device/geolocation/geoposition.h"
namespace base {
template <typename Type>
struct DefaultSingletonTraits;
class SingleThreadTaskRunner;
}
namespace device {
class LocationArbitrator;
class DEVICE_GEOLOCATION_EXPORT GeolocationProviderImpl
: public NON_EXPORTED_BASE(GeolocationProvider),
public base::Thread {
public:
// GeolocationProvider implementation:
std::unique_ptr<GeolocationProvider::Subscription> AddLocationUpdateCallback(
const LocationUpdateCallback& callback,
bool enable_high_accuracy) override;
void UserDidOptIntoLocationServices() override;
void OverrideLocationForTesting(const Geoposition& position) override;
// Callback from the LocationArbitrator. Public for testing.
void OnLocationUpdate(const Geoposition& position);
// Gets a pointer to the singleton instance of the location relayer, which
// is in turn bound to the browser's global context objects. This must only be
// called on the UI thread so that the GeolocationProviderImpl is always
// instantiated on the same thread. Ownership is NOT returned.
static GeolocationProviderImpl* GetInstance();
bool user_did_opt_into_location_services_for_testing() {
return user_did_opt_into_location_services_;
}
protected:
friend struct base::DefaultSingletonTraits<GeolocationProviderImpl>;
GeolocationProviderImpl();
~GeolocationProviderImpl() override;
// Useful for injecting mock geolocation arbitrator in tests.
// TODO(mvanouwerkerk): Use something like SetArbitratorForTesting instead.
virtual std::unique_ptr<LocationArbitrator> CreateArbitrator();
private:
bool OnGeolocationThread() const;
// Start and stop providers as needed when clients are added or removed.
void OnClientsChanged();
// Stops the providers when there are no more registered clients. Note that
// once the Geolocation thread is started, it will stay alive (but sitting
// idle without any pending messages).
void StopProviders();
// Starts the geolocation providers or updates their options (delegates to
// arbitrator).
void StartProviders(bool enable_high_accuracy);
// Updates the providers on the geolocation thread, which must be running.
void InformProvidersPermissionGranted();
// Notifies all registered clients that a position update is available.
void NotifyClients(const Geoposition& position);
// Thread
void Init() override;
void CleanUp() override;
base::CallbackList<void(const Geoposition&)> high_accuracy_callbacks_;
base::CallbackList<void(const Geoposition&)> low_accuracy_callbacks_;
bool user_did_opt_into_location_services_;
Geoposition position_;
// True only in testing, where we want to use a custom position.
bool ignore_location_updates_;
// Only to be used on the geolocation thread.
std::unique_ptr<LocationArbitrator> arbitrator_;
// Used to PostTask()s from the geolocation thread to creation thread.
const scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
DISALLOW_COPY_AND_ASSIGN(GeolocationProviderImpl);
};
} // namespace device
#endif // DEVICE_GEOLOCATION_GEOLOCATION_PROVIDER_IMPL_H_
|
// 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 CONTENT_RENDERER_INPUT_SYNCHRONOUS_COMPOSITOR_REGISTRY_H_
#define CONTENT_RENDERER_INPUT_SYNCHRONOUS_COMPOSITOR_REGISTRY_H_
namespace content {
class SynchronousLayerTreeFrameSink;
class SynchronousCompositorRegistry {
public:
virtual void RegisterLayerTreeFrameSink(
int routing_id,
SynchronousLayerTreeFrameSink* layer_tree_frame_sink) = 0;
virtual void UnregisterLayerTreeFrameSink(
int routing_id,
SynchronousLayerTreeFrameSink* layer_tree_frame_sink) = 0;
protected:
virtual ~SynchronousCompositorRegistry() {}
};
} // namespace content
#endif // CONTENT_RENDERER_INPUT_SYNCHRONOUS_COMPOSITOR_REGISTRY_H_
|
#ifndef LOGGER_INCLUDE
#define LOGGER_INCLUDE
#include <gsl/string_span>
#include "log/log.h"
BOOST_LOG_GLOBAL_LOGGER(exec_helper_core_logger, execHelper::log::LoggerType);
static const gsl::czstring<> LOG_CHANNEL = "core";
#define LOG(x) \
BOOST_LOG_STREAM_CHANNEL_SEV(exec_helper_core_logger::get(), LOG_CHANNEL, \
execHelper::log::x) \
<< boost::log::add_value(fileLog, __FILE__) \
<< boost::log::add_value(lineLog, __LINE__)
#endif /* LOGGER_INCLUDE */
|
// Copyright 2021 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_ASH_ARC_NEARBY_SHARE_ARC_NEARBY_SHARE_BRIDGE_H_
#define CHROME_BROWSER_ASH_ARC_NEARBY_SHARE_ARC_NEARBY_SHARE_BRIDGE_H_
#include <stdint.h>
#include <map>
#include <memory>
#include "ash/components/arc/mojom/nearby_share.mojom.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/ash/arc/nearby_share/nearby_share_session_impl.h"
#include "components/keyed_service/core/keyed_service.h"
class Profile;
namespace content {
class BrowserContext;
} // namespace content
namespace arc {
class ArcBridgeService;
// This class handles Nearby Share related IPC from ARC++ and allows the Chrome
// Nearby Share UI to be displayed and managed in Chrome instead of the
// Android Nearby Share activity.
class ArcNearbyShareBridge : public KeyedService,
public mojom::NearbyShareHost {
public:
// Returns singleton instance for the given BrowserContext,
// or nullptr if the |browser_context| is not allowed to use ARC.
static ArcNearbyShareBridge* GetForBrowserContext(
content::BrowserContext* browser_context);
static ArcNearbyShareBridge* GetForBrowserContextForTesting(
content::BrowserContext* browser_context);
ArcNearbyShareBridge(content::BrowserContext* browser_context,
ArcBridgeService* bridge_service);
ArcNearbyShareBridge(const ArcNearbyShareBridge&) = delete;
ArcNearbyShareBridge& operator=(const ArcNearbyShareBridge&) = delete;
~ArcNearbyShareBridge() override;
// mojom::NearbyShareHost overrides.
void StartNearbyShare(
uint32_t task_id,
mojom::ShareIntentInfoPtr info,
mojo::PendingRemote<mojom::NearbyShareSessionInstance> instance,
StartNearbyShareCallback callback) override;
private:
// Called by NearbyShareSessionImpl when the session is finished and can be
// cleaned up.
void OnNearbyShareSessionFinished(uint32_t task_id);
ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager.
// Unowned pointer.
Profile* const profile_;
// Map that keeps track of a task_id with its NearbyShareSessionImpl instance.
std::map<uint32_t, std::unique_ptr<NearbyShareSessionImpl>> session_map_;
base::WeakPtrFactory<ArcNearbyShareBridge> weak_ptr_factory_{this};
};
} // namespace arc
#endif // CHROME_BROWSER_ASH_ARC_NEARBY_SHARE_ARC_NEARBY_SHARE_BRIDGE_H_
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_environment_w32_execvp_65b.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-65b.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: environment Read input from an environment variable
* GoodSource: Fixed string
* Sinks: w32_execvp
* BadSink : execute command with execvp
* Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#endif
#define ENV_VARIABLE "ADD"
#ifdef _WIN32
#define GETENV getenv
#else
#define GETENV getenv
#endif
#include <process.h>
#define EXECVP _execvp
#ifndef OMITBAD
void CWE78_OS_Command_Injection__char_environment_w32_execvp_65b_badSink(char * data)
{
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
/* execvp - searches for the location of the command among
* the directories specified by the PATH environment variable */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECVP(COMMAND_INT, args);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE78_OS_Command_Injection__char_environment_w32_execvp_65b_goodG2BSink(char * data)
{
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
/* execvp - searches for the location of the command among
* the directories specified by the PATH environment variable */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECVP(COMMAND_INT, args);
}
}
#endif /* OMITGOOD */
|
//===============================================================================
// @ Player.h
// ------------------------------------------------------------------------------
// Main player
//
// Copyright (C) 2008-2015 by James M. Van Verth and Lars M. Bishop.
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
//
//
//===============================================================================
#ifndef __PlayerDefs__
#define __PlayerDefs__
//-------------------------------------------------------------------------------
//-- Dependencies ---------------------------------------------------------------
//-------------------------------------------------------------------------------
#include <IvMatrix33.h>
#include <IvVector2.h>
#include <IvVector3.h>
//-------------------------------------------------------------------------------
//-- Classes --------------------------------------------------------------------
//-------------------------------------------------------------------------------
class IvIndexBuffer;
class IvVertexBuffer;
class Player
{
public:
Player();
~Player();
void Update( float dt );
void Render();
private:
void CreateSphere();
void DrawSphere();
float mScale;
IvMatrix33 mRotate;
IvVector3 mTranslate;
float mRadius;
IvIndexBuffer* mSphereIndices;
IvVertexBuffer* mSphereVerts;
};
#endif
|
/* Copyright (c) 2010-2018, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*
*/
#ifndef TUDAT_TEST_FUNCTION_WITH_ZERO_ROOT_H
#define TUDAT_TEST_FUNCTION_WITH_ZERO_ROOT_H
#include <stdexcept>
#include "Tudat/Mathematics/RootFinders/UnitTests/testFunction.h"
#include "Tudat/Mathematics/BasicMathematics/basicFunction.h"
namespace tudat
{
namespace unit_tests
{
//! Test function for the root-finders.
/*!
* This struct contains functions, necessary to test if the various rootfinding methods can find
* roots that are equal to 0.
* The test function implemented in this case is:
* \f[
* f(x) = x^{2}
* \f]
*/
struct TestFunctionWithZeroRoot : public TestFunction,
public basic_mathematics::BasicFunction< double, double >
{
//! Maximum order of the derivative before throwing an exception.
unsigned int maximumDerivativeOrder;
//! Create a function, where aMaximumDerivativeOrder is the maximum order of the derivative.
TestFunctionWithZeroRoot( unsigned int aMaximumDerivativeOrder )
: maximumDerivativeOrder( aMaximumDerivativeOrder )
{ }
//! Mathematical test function.
double evaluate( double inputValue )
{
// f(x) = x^2.
return inputValue * inputValue;
}
//! Derivatives of mathematical test function.
double computeDerivative( const unsigned int order, const double inputValue )
{
// Sanity check.
if ( order > maximumDerivativeOrder )
{
throw std::runtime_error( "The rootfinder should not evaluate higher derivatives!" );
}
// Return the analytical expression for the derivatives.
if ( order == 0 )
{
// Return the function value: y = inputValue^2.
return evaluate( inputValue );
}
else if ( order == 1 )
{
// Return the first derivative function value: y = 2 * inputValue.
return 2.0 * inputValue;
}
else if ( order == 2 )
{
// Return the second derivative function value: y = 2.
return 2.0;
}
else
{
throw std::runtime_error(
"An error occured when evaluating the order of the derivative." );
}
}
//! Crash on integration as root_finders should not execute these.
double computeDefiniteIntegral( const unsigned int order, const double lowerBound,
const double upperbound )
{
throw std::runtime_error( "The rootfinder should not evaluate integrals!" );
}
//! Get the expected true location of the root.
/*!
* Returns the expected true location of the function root, here 0.0.
* \return True location of the root.
*/
double getTrueRootLocation( ) { return 0.0; }
//! Get the accuracy of the true location of the root.
/*!
* Returns the accuracy of the true location of the function root, here 1e-308.
* \return Accuracy of the true location of the root.
*/
double getTrueRootAccuracy( ) { return 1e-308; }
//! Get a reasonable initial guess of the root location.
/*!
* Returns a reasonable initial guess for the true location of the function root, here 2.
*
* \return Initial guess for the true location of the function root.
*/
double getInitialGuess( ) { return 2.0; }
//! Get a reasonable lower boundary for the root location.
/*!
* Returns a reasonable lower bound for the true location of the function root, here -3.
*
* \return Lower bound for the true location of the function root.
*/
double getLowerBound( ) { return -3.0; }
//! Get a reasonable upper boundary for the root location.
/*!
* Returns a reasonable upper bound for the true location of the function root, here 3.
*
* \return Upper bound for the true location of the function root.
*/
double getUpperBound( ) { return 3.0; }
protected:
private:
};
} // namespace unit_tests
} // namespace tudat
#endif // TUDAT_TEST_FUNCTION_WITH_ZERO_ROOT_H
|
// 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 BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_TRACKER_H_
#define BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_TRACKER_H_
#include <vector>
#include "base/atomicops.h"
#include "base/base_export.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/trace_event/heap_profiler_allocation_context.h"
namespace base {
namespace trace_event {
// The allocation context tracker keeps track of thread-local context for heap
// profiling. It includes a pseudo stack of trace events. On every allocation
// the tracker provides a snapshot of its context in the form of an
// |AllocationContext| that is to be stored together with the allocation
// details.
class BASE_EXPORT AllocationContextTracker {
public:
// Globally enables capturing allocation context.
// TODO(ruuda): Should this be replaced by |EnableCapturing| in the future?
// Or at least have something that guards agains enable -> disable -> enable?
static void SetCaptureEnabled(bool enabled);
// Returns whether capturing allocation context is enabled globally.
inline static bool capture_enabled() {
// A little lag after heap profiling is enabled or disabled is fine, it is
// more important that the check is as cheap as possible when capturing is
// not enabled, so do not issue a memory barrier in the fast path.
if (subtle::NoBarrier_Load(&capture_enabled_) == 0)
return false;
// In the slow path, an acquire load is required to pair with the release
// store in |SetCaptureEnabled|. This is to ensure that the TLS slot for
// the thread-local allocation context tracker has been initialized if
// |capture_enabled| returns true.
return subtle::Acquire_Load(&capture_enabled_) != 0;
}
// Returns the thread-local instance, creating one if necessary. Returns
// always a valid instance, unless it is called re-entrantly, in which case
// returns nullptr in the nested calls.
static AllocationContextTracker* GetInstanceForCurrentThread();
// Set the thread name in the AllocationContextTracker of the current thread
// if capture is enabled.
static void SetCurrentThreadName(const char* name);
// Pushes a frame onto the thread-local pseudo stack.
void PushPseudoStackFrame(StackFrame frame);
// Pops a frame from the thread-local pseudo stack.
void PopPseudoStackFrame(StackFrame frame);
// Push and pop current task's context. A stack is used to support nested
// tasks and the top of the stack will be used in allocation context.
void PushCurrentTaskContext(const char* context);
void PopCurrentTaskContext(const char* context);
// Returns a snapshot of the current thread-local context.
AllocationContext GetContextSnapshot();
~AllocationContextTracker();
private:
AllocationContextTracker();
static subtle::Atomic32 capture_enabled_;
// The pseudo stack where frames are |TRACE_EVENT| names.
std::vector<StackFrame> pseudo_stack_;
// The thread name is used as the first entry in the pseudo stack.
const char* thread_name_;
// Stack of tasks' contexts. Context serves as a different dimension than
// pseudo stack to cluster allocations.
std::vector<const char*> task_contexts_;
DISALLOW_COPY_AND_ASSIGN(AllocationContextTracker);
};
} // namespace trace_event
} // namespace base
#endif // BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_TRACKER_H_
|
// Copyright 2020 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 ASH_SYSTEM_AUDIO_MIC_GAIN_SLIDER_CONTROLLER_H_
#define ASH_SYSTEM_AUDIO_MIC_GAIN_SLIDER_CONTROLLER_H_
#include "ash/system/unified/unified_slider_view.h"
namespace ash {
class MicGainSliderView;
// Controller for mic gain sliders situated in audio detailed
// view in the system tray.
class MicGainSliderController : public UnifiedSliderListener {
public:
MicGainSliderController();
// Create a slider view for a specific input device.
std::unique_ptr<MicGainSliderView> CreateMicGainSlider(uint64_t device_id,
bool internal);
// UnifiedSliderListener:
views::View* CreateView() override;
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
void SliderValueChanged(views::Slider* sender,
float value,
float old_value,
views::SliderChangeReason reason) override;
};
} // namespace ash
#endif // ASH_SYSTEM_AUDIO_MIC_GAIN_SLIDER_CONTROLLER_H_
|
// Copyright (c) 2012, HTW Berlin / Project HardMut
// (http://www.hardmut-projekt.de)
//
// 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 HTW Berlin / INKA Research Group 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.
//
// Page_Alice_Example7.h
// iDiary2
//
// Created by Markus Konrad on 13.06.12.
// Copyright (c) 2012 INKA Forschungsgruppe. All rights reserved.
//
#import "PageLayer.h"
#import "PianoLayer.h"
@interface Page_Alice_Example7 : PageLayer {
PianoLayer *piano;
}
@end
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_FILES_SCOPED_TEMP_DIR_H_
#define BASE_FILES_SCOPED_TEMP_DIR_H_
// An object representing a temporary / scratch directory that should be
// cleaned up (recursively) when this object goes out of scope. Since deletion
// occurs during the destructor, no further error handling is possible if the
// directory fails to be deleted. As a result, deletion is not guaranteed by
// this class. (However note that, whenever possible, by default
// CreateUniqueTempDir creates the directory in a location that is
// automatically cleaned up on reboot, or at other appropriate times.)
//
// Multiple calls to the methods which establish a temporary directory
// (CreateUniqueTempDir, CreateUniqueTempDirUnderPath, and Set) must have
// intervening calls to Delete or Take, or the calls will fail.
#include "base/files/file_path.h"
#include "base/macros.h"
namespace base {
class ScopedTempDir {
public:
// No directory is owned/created initially.
ScopedTempDir();
// Recursively delete path.
~ScopedTempDir();
// Creates a unique directory in TempPath, and takes ownership of it.
// See file_util::CreateNewTemporaryDirectory.
bool CreateUniqueTempDir() WARN_UNUSED_RESULT;
// Creates a unique directory under a given path, and takes ownership of it.
bool CreateUniqueTempDirUnderPath(const FilePath& path) WARN_UNUSED_RESULT;
// Takes ownership of directory at |path|, creating it if necessary.
// Don't call multiple times unless Take() has been called first.
bool Set(const FilePath& path) WARN_UNUSED_RESULT;
// Deletes the temporary directory wrapped by this object.
bool Delete() WARN_UNUSED_RESULT;
// Caller takes ownership of the temporary directory so it won't be destroyed
// when this object goes out of scope.
FilePath Take();
// Returns the path to the created directory. Call one of the
// CreateUniqueTempDir* methods before getting the path.
const FilePath& GetPath() const;
// Returns true if path_ is non-empty and exists.
bool IsValid() const;
// Returns the prefix used for temp directory names generated by
// ScopedTempDirs.
static const FilePath::CharType* GetTempDirPrefix();
private:
FilePath path_;
DISALLOW_COPY_AND_ASSIGN(ScopedTempDir);
};
} // namespace base
#endif // BASE_FILES_SCOPED_TEMP_DIR_H_
|
// 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 DEVICE_BLUETOOTH_DBUS_FAKE_BLUETOOTH_GATT_DESCRIPTOR_CLIENT_H_
#define DEVICE_BLUETOOTH_DBUS_FAKE_BLUETOOTH_GATT_DESCRIPTOR_CLIENT_H_
#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "dbus/object_path.h"
#include "device/bluetooth/bluetooth_export.h"
#include "device/bluetooth/dbus/bluetooth_gatt_descriptor_client.h"
namespace bluez {
// FakeBluetoothGattDescriptorClient simulates the behavior of the Bluetooth
// Daemon GATT characteristic descriptor objects and is used in test cases in
// place of a mock and on the Linux desktop.
class DEVICE_BLUETOOTH_EXPORT FakeBluetoothGattDescriptorClient
: public BluetoothGattDescriptorClient {
public:
struct Properties : public BluetoothGattDescriptorClient::Properties {
explicit Properties(const PropertyChangedCallback& callback);
~Properties() override;
// dbus::PropertySet override
void Get(dbus::PropertyBase* property,
dbus::PropertySet::GetCallback callback) override;
void GetAll() override;
void Set(dbus::PropertyBase* property,
dbus::PropertySet::SetCallback callback) override;
};
FakeBluetoothGattDescriptorClient();
~FakeBluetoothGattDescriptorClient() override;
// DBusClient override.
void Init(dbus::Bus* bus, const std::string& bluetooth_service_name) override;
// BluetoothGattDescriptorClient overrides.
void AddObserver(Observer* observer) override;
void RemoveObserver(Observer* observer) override;
std::vector<dbus::ObjectPath> GetDescriptors() override;
Properties* GetProperties(const dbus::ObjectPath& object_path) override;
void ReadValue(const dbus::ObjectPath& object_path,
ValueCallback callback,
ErrorCallback error_callback) override;
void WriteValue(const dbus::ObjectPath& object_path,
const std::vector<uint8_t>& value,
base::OnceClosure callback,
ErrorCallback error_callback) override;
// Makes the descriptor with the UUID |uuid| visible under the characteristic
// with object path |characteristic_path|. Descriptor object paths are
// hierarchical to their characteristics. |uuid| must belong to a descriptor
// for which there is a constant defined below, otherwise this method has no
// effect. Returns the object path of the created descriptor. In the no-op
// case, returns an invalid path.
dbus::ObjectPath ExposeDescriptor(const dbus::ObjectPath& characteristic_path,
const std::string& uuid);
void HideDescriptor(const dbus::ObjectPath& descriptor_path);
// Object path components and UUIDs of GATT characteristic descriptors.
static const char kClientCharacteristicConfigurationPathComponent[];
static const char kClientCharacteristicConfigurationUUID[];
private:
// Property callback passed when we create Properties structures.
void OnPropertyChanged(const dbus::ObjectPath& object_path,
const std::string& property_name);
// Notifies observers.
void NotifyDescriptorAdded(const dbus::ObjectPath& object_path);
void NotifyDescriptorRemoved(const dbus::ObjectPath& object_path);
// Mapping from object paths to Properties structures.
struct DescriptorData {
DescriptorData();
~DescriptorData();
std::unique_ptr<Properties> properties;
};
typedef std::map<dbus::ObjectPath, DescriptorData*> PropertiesMap;
PropertiesMap properties_;
// List of observers interested in event notifications from us.
base::ObserverList<Observer>::Unchecked observers_;
// Weak pointer factory for generating 'this' pointers that might live longer
// than we do.
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<FakeBluetoothGattDescriptorClient> weak_ptr_factory_{
this};
DISALLOW_COPY_AND_ASSIGN(FakeBluetoothGattDescriptorClient);
};
} // namespace bluez
#endif // DEVICE_BLUETOOTH_DBUS_FAKE_BLUETOOTH_GATT_DESCRIPTOR_CLIENT_H_
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_FUZZED_DATA_PROVIDER_H_
#define NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_FUZZED_DATA_PROVIDER_H_
#include "net/third_party/quic/platform/impl/quic_fuzzed_data_provider_impl.h"
namespace quic {
using QuicFuzzedDataProvider = QuicFuzzedDataProviderImpl;
} // namespace quic
#endif // NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_FUZZED_DATA_PROVIDER_H_
|
#include <stdio.h>
#include <stdlib.h>
#include "memory_alignment.h"
int main(void)
{
char c;
int i;
printf("Starting...\n");
printf("Read: char aligned: ");
c = read_char_aligned();
printf("%i\n", c);
printf("Storing char aligned...\n");
store_char_aligned(c + 1);
printf("Read: char aligned: ");
c = read_char_aligned();
printf("%i\n", c);
printf("Read: int aligned: ");
i = read_int_aligned();
printf("%i\n", i);
printf("Storing int aligned...\n");
store_int_aligned(i + 1);
printf("Read: int aligned: ");
i = read_int_aligned();
printf("%i\n", i);
printf("Read: char unaligned: ");
c = read_char_unaligned();
printf("%i\n", c);
printf("Storing char unaligned...\n");
store_char_unaligned(c + 1);
printf("Read: char unaligned: ");
c = read_char_unaligned();
printf("%i\n", c);
printf("Read: int unaligned: ");
i = read_int_unaligned();
printf("%i\n", i);
printf("Storing int unaligned...\n");
store_int_unaligned(i + 89);
printf("Read: int unaligned: ");
i = read_int_unaligned();
printf("%i\n", i);
printf("Read: char unaligned: ");
c = read_char_unaligned();
printf("%i\n", c);
printf("Storing char unaligned...\n");
store_char_unaligned(c + 1);
printf("Read: char unaligned: ");
c = read_char_unaligned();
printf("%i\n", c);
return 0;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_WM_SESSION_STATE_ANIMATOR_H_
#define ASH_WM_SESSION_STATE_ANIMATOR_H_
#include "ash/ash_export.h"
#include "ash/wm/workspace/colored_window_controller.h"
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "base/timer.h"
#include "ui/aura/window.h"
namespace gfx {
class Rect;
class Size;
}
namespace ui {
class Layer;
}
namespace ash {
namespace internal {
// Displays onscreen animations for session state changes (lock/unlock, sign
// out, shut down).
class ASH_EXPORT SessionStateAnimator {
public:
// Animations that can be applied to groups of containers.
enum AnimationType {
ANIMATION_PARTIAL_CLOSE = 0,
ANIMATION_UNDO_PARTIAL_CLOSE,
ANIMATION_FULL_CLOSE,
ANIMATION_FADE_IN,
ANIMATION_HIDE,
ANIMATION_RESTORE,
ANIMATION_RAISE,
ANIMATION_LOWER,
ANIMATION_PARTIAL_FADE_IN,
ANIMATION_UNDO_PARTIAL_FADE_IN,
ANIMATION_FULL_FADE_IN,
};
// Specific containers or groups of containers that can be animated.
enum Container {
DESKTOP_BACKGROUND = 1 << 0,
LAUNCHER = 1 << 1,
// All user session related containers including system background but
// not including desktop background (wallpaper).
NON_LOCK_SCREEN_CONTAINERS = 1 << 2,
// Desktop wallpaper is moved to this layer when screen is locked.
// This layer is excluded from lock animation so that wallpaper stays as is,
// user session windows are hidden and lock UI is shown on top of it.
// This layer is included in shutdown animation.
LOCK_SCREEN_BACKGROUND = 1 << 3,
// Lock screen and lock screen modal containers.
LOCK_SCREEN_CONTAINERS = 1 << 4,
// Multiple system layers belong here like status, menu, tooltip
// and overlay layers.
LOCK_SCREEN_RELATED_CONTAINERS = 1 << 5,
LOCK_SCREEN_SYSTEM_FOREGROUND = 1 << 6,
};
// Helper class used by tests to access internal state.
class ASH_EXPORT TestApi {
public:
explicit TestApi(SessionStateAnimator* animator)
: animator_(animator) {}
// Returns true if containers of a given |container_mask|
// were last animated with |type| (probably; the analysis is fairly ad-hoc).
// |container_mask| is a bitfield of a Container.
bool ContainersAreAnimated(int container_mask, AnimationType type) const;
private:
SessionStateAnimator* animator_; // not owned
DISALLOW_COPY_AND_ASSIGN(TestApi);
};
// A bitfield mask including LOCK_SCREEN_WALLPAPER,
// LOCK_SCREEN_CONTAINERS, and LOCK_SCREEN_RELATED_CONTAINERS.
const static int kAllLockScreenContainersMask;
// A bitfield mask of all containers.
const static int kAllContainersMask;
SessionStateAnimator();
virtual ~SessionStateAnimator();
// Create |foreground_| layer if it doesn't already exist, but makes it
// completely transparent.
void CreateForeground();
// Destroy |foreground_| when it is not needed anymore.
void DropForeground();
// Apply animation |type| to all containers included in |container_mask|.
void StartAnimation(int container_mask,
AnimationType type);
// Apply animation |type| to all containers included in |container_mask| and
// call a |callback| at the end of the animation, if it is not null.
void StartAnimationWithCallback(int container_mask,
AnimationType type,
base::Callback<void(void)>& callback);
// Fills |containers| with the containers included in |container_mask|.
void GetContainers(int container_mask,
aura::Window::Windows* containers);
// Apply animation |type| to window |window| and add |observer| if it is not
// NULL to the last animation sequence.
void RunAnimationForWindow(aura::Window* window,
AnimationType type,
ui::LayerAnimationObserver* observer);
// White foreground that is used during shutdown animation to "fade
// everything into white".
scoped_ptr<ColoredWindowController> foreground_;
DISALLOW_COPY_AND_ASSIGN(SessionStateAnimator);
};
} // namespace internal
} // namespace ash
#endif // ASH_WM_SESSION_STATE_ANIMATOR_H_
|
#include "customtype_mock.h"
#include "unity.h"
#include <string.h>
#include <stdlib.h>
#define MAX_LENGTH_ERROR_MESSAGE 100
static fooMockData fooData;
static barMockData barData;
static basMockData basData;
void customtype_MockSetup(void)
{
memset(&fooData, 0, sizeof(fooData));
memset(&barData, 0, sizeof(barData));
memset(&basData, 0, sizeof(basData));
}
void customtype_MockTeardown(void)
{
TEST_ASSERT_EQUAL_MESSAGE(fooData.ExpectedNrCalls,
fooData.CallCounter,
"foo was not called as often as specified!");
TEST_ASSERT_EQUAL_MESSAGE(barData.ExpectedNrCalls,
barData.CallCounter,
"bar was not called as often as specified!");
TEST_ASSERT_EQUAL_MESSAGE(basData.ExpectedNrCalls,
basData.CallCounter,
"bas was not called as often as specified!");
}
void foo_ExpectedCall(struct foo f, const struct foo *p1, const struct foo* p2, struct FOO ReturnValue)
{
char errormsg[MAX_LENGTH_ERROR_MESSAGE];
snprintf(errormsg, MAX_LENGTH_ERROR_MESSAGE, "Too many calls to %s, max number is: %d", __FUNCTION__, MAX_NR_FUNCTION_CALLS);
TEST_ASSERT_TRUE_MESSAGE(fooData.ExpectedNrCalls < MAX_NR_FUNCTION_CALLS, errormsg);
TEST_ASSERT_NOT_NULL_MESSAGE(p1, "parameter should not be NULL");
TEST_ASSERT_NOT_NULL_MESSAGE(p2, "parameter should not be NULL");
fooData.f[fooData.ExpectedNrCalls] = f;
fooData.p1[fooData.ExpectedNrCalls] = *p1;
fooData.p2[fooData.ExpectedNrCalls] = *p2;
fooData.ReturnValue[fooData.ExpectedNrCalls] = ReturnValue;
fooData.ExpectedNrCalls++;
}
struct FOO foo(struct foo f, struct foo *p1, const struct foo* p2)
{
char errormsg[MAX_LENGTH_ERROR_MESSAGE];
snprintf(errormsg, MAX_LENGTH_ERROR_MESSAGE, "Too many calls to %s: expected %d calls, this is call nr %d", __FUNCTION__, fooData.ExpectedNrCalls, fooData.CallCounter+1);
TEST_ASSERT_TRUE_MESSAGE(fooData.CallCounter < fooData.ExpectedNrCalls, errormsg);
snprintf(errormsg, MAX_LENGTH_ERROR_MESSAGE, "Call to %s with unexpected parameter(s) in call nr %d", __FUNCTION__, fooData.CallCounter+1);
TEST_ASSERT_EQUAL_MEMORY_MESSAGE(&(fooData.f[fooData.CallCounter]), &f, sizeof(f), errormsg);
*p1 = fooData.p1[fooData.CallCounter];
TEST_ASSERT_EQUAL_MEMORY_MESSAGE(&(fooData.p2[fooData.CallCounter]), p2, sizeof(*p2), errormsg);
return fooData.ReturnValue[fooData.CallCounter++];
}
void bar_ExpectedCall(const BAR* p1, const BAR *p2, BAR* ReturnValue)
{
char errormsg[MAX_LENGTH_ERROR_MESSAGE];
snprintf(errormsg, MAX_LENGTH_ERROR_MESSAGE, "Too many calls to %s, max number is: %d", __FUNCTION__, MAX_NR_FUNCTION_CALLS);
TEST_ASSERT_TRUE_MESSAGE(barData.ExpectedNrCalls < MAX_NR_FUNCTION_CALLS, errormsg);
TEST_ASSERT_NOT_NULL_MESSAGE(p1, "parameter should not be NULL");
TEST_ASSERT_NOT_NULL_MESSAGE(p2, "parameter should not be NULL");
/* no TEST_ASSERT_NOT_NULL for ReturnValue, you might want to return NULL! */
barData.p1[barData.ExpectedNrCalls] = *p1;
barData.p2[barData.ExpectedNrCalls] = *p2;
barData.ReturnValue[barData.ExpectedNrCalls] = ReturnValue;
barData.ExpectedNrCalls++;
}
BAR* bar(BAR* p1, const BAR *p2)
{
char errormsg[MAX_LENGTH_ERROR_MESSAGE];
snprintf(errormsg, MAX_LENGTH_ERROR_MESSAGE, "Too many calls to %s: expected %d calls, this is call nr %d", __FUNCTION__, barData.ExpectedNrCalls, barData.CallCounter+1);
TEST_ASSERT_TRUE_MESSAGE(barData.CallCounter < barData.ExpectedNrCalls, errormsg);
snprintf(errormsg, MAX_LENGTH_ERROR_MESSAGE, "Call to %s with unexpected parameter(s) in call nr %d", __FUNCTION__, barData.CallCounter+1);
*p1 = barData.p1[barData.CallCounter];
TEST_ASSERT_EQUAL_MEMORY_MESSAGE(&(barData.p2[barData.CallCounter]), p2, sizeof(*p2), errormsg);
return barData.ReturnValue[barData.CallCounter++];
}
void bas_ExpectedCall(myInt i, const myInt* p, myInt ReturnValue)
{
char errormsg[MAX_LENGTH_ERROR_MESSAGE];
snprintf(errormsg, MAX_LENGTH_ERROR_MESSAGE, "Too many calls to %s, max number is: %d", __FUNCTION__, MAX_NR_FUNCTION_CALLS);
TEST_ASSERT_TRUE_MESSAGE(basData.ExpectedNrCalls < MAX_NR_FUNCTION_CALLS, errormsg);
TEST_ASSERT_NOT_NULL_MESSAGE(p, "parameter should not be NULL");
basData.i[basData.ExpectedNrCalls] = i;
basData.p[basData.ExpectedNrCalls] = *p;
basData.ReturnValue[basData.ExpectedNrCalls] = ReturnValue;
basData.ExpectedNrCalls++;
}
myInt bas(myInt i, myInt* p)
{
char errormsg[MAX_LENGTH_ERROR_MESSAGE];
snprintf(errormsg, MAX_LENGTH_ERROR_MESSAGE, "Too many calls to %s: expected %d calls, this is call nr %d", __FUNCTION__, basData.ExpectedNrCalls, basData.CallCounter+1);
TEST_ASSERT_TRUE_MESSAGE(basData.CallCounter < basData.ExpectedNrCalls, errormsg);
snprintf(errormsg, MAX_LENGTH_ERROR_MESSAGE, "Call to %s with unexpected parameter(s) in call nr %d", __FUNCTION__, basData.CallCounter+1);
TEST_ASSERT_EQUAL_MEMORY_MESSAGE(&(basData.i[basData.CallCounter]), &i, sizeof(i), errormsg);
*p = basData.p[basData.CallCounter];
return basData.ReturnValue[basData.CallCounter++];
}
|
/*-
* Copyright (c) 2001 Jake Burkholder.
* 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.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include "opt_pmap.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/ktr.h>
#include <sys/pcpu.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/smp.h>
#include <sys/sysctl.h>
#include <vm/vm.h>
#include <vm/pmap.h>
#include <machine/smp.h>
#include <machine/tlb.h>
#include <machine/vmparam.h>
PMAP_STATS_VAR(tlb_ncontext_demap);
PMAP_STATS_VAR(tlb_npage_demap);
PMAP_STATS_VAR(tlb_nrange_demap);
tlb_flush_nonlocked_t *tlb_flush_nonlocked;
tlb_flush_user_t *tlb_flush_user;
/*
* Some tlb operations must be atomic, so no interrupt or trap can be allowed
* while they are in progress. Traps should not happen, but interrupts need to
* be explicitely disabled. critical_enter() cannot be used here, since it only
* disables soft interrupts.
*/
void
tlb_context_demap(struct pmap *pm)
{
void *cookie;
register_t s;
/*
* It is important that we are not interrupted or preempted while
* doing the IPIs. The interrupted CPU may hold locks, and since
* it will wait for the CPU that sent the IPI, this can lead
* to a deadlock when an interrupt comes in on that CPU and it's
* handler tries to grab one of that locks. This will only happen for
* spin locks, but these IPI types are delivered even if normal
* interrupts are disabled, so the lock critical section will not
* protect the target processor from entering the IPI handler with
* the lock held.
*/
PMAP_STATS_INC(tlb_ncontext_demap);
cookie = ipi_tlb_context_demap(pm);
s = intr_disable();
if (CPU_ISSET(PCPU_GET(cpuid), &pm->pm_active)) {
KASSERT(pm->pm_context[curcpu] != -1,
("tlb_context_demap: inactive pmap?"));
stxa(TLB_DEMAP_PRIMARY | TLB_DEMAP_CONTEXT, ASI_DMMU_DEMAP, 0);
stxa(TLB_DEMAP_PRIMARY | TLB_DEMAP_CONTEXT, ASI_IMMU_DEMAP, 0);
flush(KERNBASE);
}
intr_restore(s);
ipi_wait(cookie);
}
void
tlb_page_demap(struct pmap *pm, vm_offset_t va)
{
u_long flags;
void *cookie;
register_t s;
PMAP_STATS_INC(tlb_npage_demap);
cookie = ipi_tlb_page_demap(pm, va);
s = intr_disable();
if (CPU_ISSET(PCPU_GET(cpuid), &pm->pm_active)) {
KASSERT(pm->pm_context[curcpu] != -1,
("tlb_page_demap: inactive pmap?"));
if (pm == kernel_pmap)
flags = TLB_DEMAP_NUCLEUS | TLB_DEMAP_PAGE;
else
flags = TLB_DEMAP_PRIMARY | TLB_DEMAP_PAGE;
stxa(TLB_DEMAP_VA(va) | flags, ASI_DMMU_DEMAP, 0);
stxa(TLB_DEMAP_VA(va) | flags, ASI_IMMU_DEMAP, 0);
flush(KERNBASE);
}
intr_restore(s);
ipi_wait(cookie);
}
void
tlb_range_demap(struct pmap *pm, vm_offset_t start, vm_offset_t end)
{
vm_offset_t va;
void *cookie;
u_long flags;
register_t s;
PMAP_STATS_INC(tlb_nrange_demap);
cookie = ipi_tlb_range_demap(pm, start, end);
s = intr_disable();
if (CPU_ISSET(PCPU_GET(cpuid), &pm->pm_active)) {
KASSERT(pm->pm_context[curcpu] != -1,
("tlb_range_demap: inactive pmap?"));
if (pm == kernel_pmap)
flags = TLB_DEMAP_NUCLEUS | TLB_DEMAP_PAGE;
else
flags = TLB_DEMAP_PRIMARY | TLB_DEMAP_PAGE;
for (va = start; va < end; va += PAGE_SIZE) {
stxa(TLB_DEMAP_VA(va) | flags, ASI_DMMU_DEMAP, 0);
stxa(TLB_DEMAP_VA(va) | flags, ASI_IMMU_DEMAP, 0);
flush(KERNBASE);
}
}
intr_restore(s);
ipi_wait(cookie);
}
|
#import <Foundation/Foundation.h>
#import "MergeProtocol.h"
@interface Merge : NSObject
// Merge obj1 with obj2 if possible. If successful, returns YES; otherwise NO.
// If successful, result points to the merged object. Note that this method may
// merge obj1 into obj2 or obj2 into obj1, depending on which direction supports
// the merge. Whichever object is merged INTO, may not be preserved; it will
// either become the merged result or a mutable copy of it will become the
// merged result. In other words, if the merge is successful, result will
// point to either obj1, obj2, a mutable copy of obj1, or a mutable copy of
// obj2. This is because a mutable copy of obj1 or obj2 is only created if obj1
// and obj2 cannot be merged as-is.
+ (BOOL)mergeObj:(NSObject<Merge>*)obj1 withObj:(NSObject<Merge>*)obj2 result:(NSObject**)result;
@end |
/*
m2elspace.c
element which occupies some space
m2tklib = Mini Interative Interface Toolkit Library
Copyright (C) 2011 olikraus@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 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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "m2.h"
M2_EL_FN_DEF(m2_el_space_fn)
{
switch(fn_arg->msg)
{
case M2_EL_MSG_IS_READ_ONLY:
return 1;
case M2_EL_MSG_GET_HEIGHT:
return m2_el_fnfmt_get_hH(fn_arg);
case M2_EL_MSG_GET_WIDTH:
return m2_el_fnfmt_get_wW(fn_arg);
case M2_EL_MSG_SHOW:
/* nothing to show */
return 1;
}
return m2_el_fnfmt_fn(fn_arg);
}
m2_button_fnptr m2_el_spacecb_get_new_dialog_fnptr(m2_el_fnarg_p fn_arg)
{
return (m2_button_fnptr)m2_rom_get_fnptr(fn_arg->element, offsetof(m2_el_spacecb_t, new_dialog_callback));
}
M2_EL_FN_DEF(m2_el_spacecb_fn)
{
switch(fn_arg->msg)
{
case M2_EL_MSG_NEW_DIALOG:
m2_el_spacecb_get_new_dialog_fnptr(fn_arg)(fn_arg);
return 1;
}
return m2_el_space_fn(fn_arg);
}
M2_EL_FN_DEF(m2_el_box_fn)
{
switch(fn_arg->msg)
{
case M2_EL_MSG_SHOW:
{
m2_pos_p b = (m2_pos_p)(fn_arg->data);
m2_gfx_box(b->x, b->y, m2_el_fnfmt_get_wW(fn_arg), m2_el_fnfmt_get_hH(fn_arg));
}
return 1;
}
return m2_el_space_fn(fn_arg);
}
|
#pragma once
#include <glbinding/nogl.h>
#include <glbinding/gl/types.h>
namespace gl14ext
{
using gl::GLextension;
using gl::GLenum;
using gl::GLboolean;
using gl::GLbitfield;
using gl::GLvoid;
using gl::GLbyte;
using gl::GLshort;
using gl::GLint;
using gl::GLclampx;
using gl::GLubyte;
using gl::GLushort;
using gl::GLuint;
using gl::GLsizei;
using gl::GLfloat;
using gl::GLclampf;
using gl::GLdouble;
using gl::GLclampd;
using gl::GLeglImageOES;
using gl::GLchar;
using gl::GLcharARB;
using gl::GLhandleARB;
using gl::GLhalfARB;
using gl::GLhalf;
using gl::GLfixed;
using gl::GLintptr;
using gl::GLsizeiptr;
using gl::GLint64;
using gl::GLuint64;
using gl::GLintptrARB;
using gl::GLsizeiptrARB;
using gl::GLint64EXT;
using gl::GLuint64EXT;
using gl::GLsync;
using gl::_cl_context;
using gl::_cl_event;
using gl::GLDEBUGPROC;
using gl::GLDEBUGPROCARB;
using gl::GLDEBUGPROCKHR;
using gl::GLDEBUGPROCAMD;
using gl::GLhalfNV;
using gl::GLvdpauSurfaceNV;
using gl::GLuint_array_2;
using gl::AttribMask;
using gl::ClearBufferMask;
using gl::ClientAttribMask;
using gl::ContextFlagMask;
using gl::ContextProfileMask;
using gl::FfdMaskSGIX;
using gl::FragmentShaderColorModMaskATI;
using gl::FragmentShaderDestMaskATI;
using gl::FragmentShaderDestModMaskATI;
using gl::MapBufferUsageMask;
using gl::MemoryBarrierMask;
using gl::PathRenderingMaskNV;
using gl::PerformanceQueryCapsMaskINTEL;
using gl::SyncObjectMask;
using gl::TextureStorageMaskAMD;
using gl::UseProgramStageMask;
using gl::VertexHintsMaskPGI;
using gl::UnusedMask;
using gl::BufferAccessMask;
using gl::BufferStorageMask;
using gl::PathFontStyle;
} // namespace gl14ext
|
//
// EMWebImagePickerViewController.h
// Example
//
// Created by Elliott Minns on 20/02/2014.
// Copyright (c) 2014 Elliott Minns. All rights reserved.
//
#import <UIKit/UIKit.h>
@class EMWebImagePickerViewController;
typedef void (^EMWebImagePickerSelectedBlock)(EMWebImagePickerViewController *picker, NSArray *selectedIndicies);
typedef void (^EMPickerBlock)(EMWebImagePickerViewController *picker);
typedef void (^EMWebImagePickerArrayBlock)(NSArray *array);
typedef void (^EMWebImagePickerErrorBlock)(NSError *error);
typedef NS_ENUM(NSInteger, EMWebImagePickerType) {
EMWebImagePickerTypeSingle,
EMWebImagePickerTypeMultiple,
EMWebImagePickerTypeMultipleDeselect
};
@protocol EMWebImagePickerViewControllerDelegate <NSObject>
- (void)webImagePicker:(EMWebImagePickerViewController *)picker didChooseIndicies:(NSArray *)selectedIndicies;
- (void)webImagePickerDidCancel:(EMWebImagePickerViewController *)picker;
- (BOOL)webImagePickerCanRecieveMoreContent:(EMWebImagePickerViewController *)picker;
@optional
- (NSArray *)webImagePickerRequestImagesForNextPage:(EMWebImagePickerViewController *)picker;
- (void)webImagePickerRequestImagesForNextPage:(EMWebImagePickerViewController *)picker
withSuccess:(EMWebImagePickerArrayBlock)success
failure:(EMWebImagePickerErrorBlock)failure;
@end
@interface EMWebImagePickerViewController : UIViewController
- (id)initWithURLs:(NSArray *)urls;
- (id)initWithURLs:(NSArray *)urls
completed:(EMWebImagePickerSelectedBlock)completed
cancelled:(EMPickerBlock)cancelled;
@property (nonatomic, weak) id<EMWebImagePickerViewControllerDelegate> delegate;
@property (nonatomic, assign) EMWebImagePickerType type;
@property (nonatomic, assign) BOOL pagingEnabled;
@property (nonatomic, strong) NSArray *previousSelectedUrls;
@end
|
#pragma once
#include <d3d9.h>
#include <d3dx9.h>
#include "../Common/common.h"
using namespace common;
#include "../wxMemMonitorLib/wxMemMonitor.h" // debug library
#include "base/graphicdef.h"
#include "base/material.h"
#include "base/light.h"
#include "base/vertexbuffer.h"
#include "base/indexbuffer.h"
#include "base/texture.h"
#include "base/vertexformat.h"
#include "base/grid.h"
#include "base/grid2.h"
#include "model/rawmesh.h"
#include "model/rawani.h"
#include "model/track.h"
#include "model/mesh.h"
#include "model/rigidmesh.h"
#include "model/skinnedmesh.h"
#include "model/model.h"
#include "model/bonemgr.h"
#include "model/bonenode.h"
#include "model/character.h"
#include "manager/Renderer.h"
#include "manager/resourcemanager.h"
#pragma comment( lib, "d3d9.lib" )
#pragma comment( lib, "d3dx9.lib" )
|
#ifndef ADRENALINENODECONFIGDIALOG_H
#define ADRENALINENODECONFIGDIALOG_H
#include <QDialog>
namespace Ui {
class AdrenalineNodeConfigDialog;
}
QT_BEGIN_NAMESPACE
class QModelIndex;
QT_END_NAMESPACE
/** Dialog showing transaction details. */
class AdrenalineNodeConfigDialog : public QDialog
{
Q_OBJECT
public:
explicit AdrenalineNodeConfigDialog(QWidget *parent = 0, QString nodeAddress = "123.456.789.123:10255", QString privkey="MASTERNODEPRIVKEY");
~AdrenalineNodeConfigDialog();
private:
Ui::AdrenalineNodeConfigDialog *ui;
};
#endif // ADRENALINENODECONFIGDIALOG_H
|
/* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * 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 Linux 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* 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 __PLATFORM_MSM8960_GPIO_H
#define __PLATFORM_MSM8960_GPIO_H
/* GPIO TLMM: Direction */
#define GPIO_INPUT 0
#define GPIO_OUTPUT 1
/* GPIO TLMM: Pullup/Pulldown */
#define GPIO_NO_PULL 0
#define GPIO_PULL_DOWN 1
#define GPIO_KEEPER 2
#define GPIO_PULL_UP 3
/* GPIO TLMM: Drive Strength */
#define GPIO_2MA 0
#define GPIO_4MA 1
#define GPIO_6MA 2
#define GPIO_8MA 3
#define GPIO_10MA 4
#define GPIO_12MA 5
#define GPIO_14MA 6
#define GPIO_16MA 7
/* GPIO TLMM: Status */
#define GPIO_ENABLE 1
#define GPIO_DISABLE 0
void gpio_tlmm_config(uint32_t gpio, uint8_t func,
uint8_t dir, uint8_t pull,
uint8_t drvstr, uint32_t enable);
void gpio_config_i2c(uint8_t gsbi_id);
void gpio_config_uart_dm(uint8_t id);
void gpio_set(uint32_t gpio, uint32_t dir);
void msm8960_keypad_gpio_init(void);
void msm8930_keypad_gpio_init(void);
void apq8064_keypad_gpio_init(void);
void apq8064_display_gpio_init(void);
#endif
|
// Copyright (c) 2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef IOP_QT_WINSHUTDOWNMONITOR_H
#define IOP_QT_WINSHUTDOWNMONITOR_H
#ifdef WIN32
#include <QByteArray>
#include <QString>
#if QT_VERSION >= 0x050000
#include <windef.h> // for HWND
#include <QAbstractNativeEventFilter>
class WinShutdownMonitor : public QAbstractNativeEventFilter
{
public:
/** Implements QAbstractNativeEventFilter interface for processing Windows messages */
bool nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pnResult);
/** Register the reason for blocking shutdown on Windows to allow clean client exit */
static void registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId);
};
#endif
#endif
#endif // IOP_QT_WINSHUTDOWNMONITOR_H
|
/* solve_triu.c
* Written by Tom Minka
*/
#include "mex.h"
#include <string.h>
/* How to write MEX files that call LAPACK:
* http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f13120.html#f45091
*/
/* In R2009a, the blas signatures have been changed to take ptrdiff_t instead of int. We call this BLAS64. */
/* various ways to detect R2009a:
* new definitions in matrix.h:
* mxCreateScalarDouble
* MATHWORKS_MATRIX_MATRIX_PUB_FWD_H
* MATHWORKS_MATRIX_MXARRAY_PUB_FWD_H
* MATHWORKS_MATRIX_VAGUE_MXARRAY_HPP
* existence of blascompat32.h
*/
#ifdef mxCreateScalarDouble
#define BLAS64
#endif
#ifdef BLAS64
#include "blas.h"
#else
#ifdef UNDERSCORE_LAPACK_CALL
/* Thanks to Ruben Martinez-Cantin */
extern int dtrsm_(char *side, char *uplo, char *transa, char *diag,
int *m, int *n, double *alpha, double *a, int *lda,
double *b, int *ldb);
#else
extern int dtrsm(char *side, char *uplo, char *transa, char *diag,
int *m, int *n, double *alpha, double *a, int *lda,
double *b, int *ldb);
#endif
#endif
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mwSize m,n;
#ifndef BLAS64
int im,in;
#endif
double *T,*b,*x;
char side='L',uplo='U',trans='N',diag='N';
double one = 1;
if(nrhs != 2 || nlhs > 1)
mexErrMsgTxt("Usage: x = solve_triu(T,b)");
/* prhs[0] is first argument.
* mxGetPr returns double* (data, col-major)
* mxGetM returns int (rows)
* mxGetN returns int (cols)
*/
/* m = rows(T) */
m = mxGetM(prhs[0]);
n = mxGetN(prhs[0]);
if(m != n) mexErrMsgTxt("matrix must be square");
/* n = cols(b) */
n = mxGetN(prhs[1]);
T = mxGetPr(prhs[0]);
b = mxGetPr(prhs[1]);
if(mxIsSparse(prhs[0]) || mxIsSparse(prhs[1])) {
mexErrMsgTxt("Sorry, can't handle sparse matrices yet.");
}
if(mxGetNumberOfDimensions(prhs[0]) != 2) {
mexErrMsgTxt("Arguments must be matrices.");
}
if(mxGetNumberOfDimensions(prhs[1]) != 2) {
mexErrMsgTxt("Arguments must be matrices.");
}
/* plhs[0] is first output */
/* x is same size as b */
plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL);
x = mxGetPr(plhs[0]);
/* copy b into x to speed up memory access */
memcpy(x,b,m*n*sizeof(double));
b = x;
#ifdef BLAS64
dtrsm(&side,&uplo,&trans,&diag,&m,&n,&one,T,&m,x,&m);
#else
im = (int)m;
in = (int)n;
#ifdef UNDERSCORE_LAPACK_CALL
dtrsm_(&side,&uplo,&trans,&diag,&im,&in,&one,T,&im,x,&im);
#else
dtrsm(&side,&uplo,&trans,&diag,&im,&in,&one,T,&im,x,&im);
#endif
#endif
}
#if 0
/* Upper triangular */
for(j=0;j<n;j++) x[m-1 + m*j] = b[m-1 + m*j]/T[m*m - 1];
for(i=m-2;i>=0;i--) {
for(j=0;j<n;j++) {
double s = 0;
for(k=i+1;k<m;k++) {
s += T[i + m*k]*x[k + m*j];
}
x[i + m*j] = (b[i + m*j] - s)/T[i + m*i];
}
}
/* Lower triangular */
for(j=0;j<n;j++) x[m*j] = b[m*j]/T[0];
for(i=1;i<m;i++) {
for(j=0;j<n;j++) {
double s = 0;
for(k=0;k<i;k++) {
s += T[i + m*k]*x[k + m*j];
}
x[i + m*j] = (b[i + m*j] - s)/T[i + m*i];
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.