text
stringlengths
4
6.14k
/** * @file log.c Logging * * Copyright (C) 2010 Creytiv.com */ #include <re.h> #include <restund.h> static struct { struct list logl; bool debug; bool stder; } lg = { .logl = LIST_INIT, .debug = false, .stder = true }; void restund_log_register_handler(struct restund_log *log) { if (!log) return; list_append(&lg.logl, &log->le, log); } void restund_log_unregister_handler(struct restund_log *log) { if (!log) return; list_unlink(&log->le); } void restund_log_enable_debug(bool enable) { lg.debug = enable; } void restund_log_enable_stderr(bool enable) { lg.stder = enable; } void restund_vlog(uint32_t level, const char *fmt, va_list ap) { char buf[4096]; struct le *le; if (re_vsnprintf(buf, sizeof(buf), fmt, ap) < 0) return; if (lg.stder) (void)re_fprintf(stderr, "%s", buf); le = lg.logl.head; while (le) { struct restund_log *log = le->data; le = le->next; if (log->h) log->h(level, buf); } } void restund_log(uint32_t level, const char *fmt, ...) { va_list ap; if ((RESTUND_DEBUG == level) && !lg.debug) return; va_start(ap, fmt); restund_vlog(level, fmt, ap); va_end(ap); } void restund_debug(const char *fmt, ...) { va_list ap; if (!lg.debug) return; va_start(ap, fmt); restund_vlog(RESTUND_DEBUG, fmt, ap); va_end(ap); } void restund_info(const char *fmt, ...) { va_list ap; va_start(ap, fmt); restund_vlog(RESTUND_INFO, fmt, ap); va_end(ap); } void restund_warning(const char *fmt, ...) { va_list ap; va_start(ap, fmt); restund_vlog(RESTUND_WARNING, fmt, ap); va_end(ap); } void restund_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); restund_vlog(RESTUND_ERROR, fmt, ap); va_end(ap); }
//================================================================================================= /*! // \file blaze/math/constraints/DeclHermExpr.h // \brief Constraint on the data type // // Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development 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. */ //================================================================================================= #ifndef _BLAZE_MATH_CONSTRAINTS_DECLHERMEXPR_H_ #define _BLAZE_MATH_CONSTRAINTS_DECLHERMEXPR_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blaze/math/typetraits/IsDeclHermExpr.h> namespace blaze { //================================================================================================= // // MUST_BE_DECLHERMEXPR_TYPE CONSTRAINT // //================================================================================================= //************************************************************************************************* /*!\brief Constraint on the data type. // \ingroup math_constraints // // In case the given data type \a T is not a declherm expression (i.e. a type derived from the // DeclHermExpr base class), a compilation error is created. */ #define BLAZE_CONSTRAINT_MUST_BE_DECLHERMEXPR_TYPE(T) \ static_assert( ::blaze::IsDeclHermExpr<T>::value, "Non-declherm expression type detected" ) //************************************************************************************************* //================================================================================================= // // MUST_NOT_BE_DECLHERMEXPR_TYPE CONSTRAINT // //================================================================================================= //************************************************************************************************* /*!\brief Constraint on the data type. // \ingroup math_constraints // // In case the given data type \a T is a declherm expression (i.e. a type derived from the // DeclHermExpr base class), a compilation error is created. */ #define BLAZE_CONSTRAINT_MUST_NOT_BE_DECLHERMEXPR_TYPE(T) \ static_assert( !::blaze::IsDeclHermExpr<T>::value, "Declherm expression type detected" ) //************************************************************************************************* } // namespace blaze #endif
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt' #pragma once #if 0 #include "Core/STL/Files/SubFile.h" #include "Core/STL/Containers/StaticArray.h" namespace GX_STL { namespace GXFile { // // Simple File Crypt Algorithm // template <uint Size> struct SimpleFileCryptAlgorithm { // types public: typedef StaticArray< ubyte, Size > password_t; typedef SimpleFileCryptAlgorithm< Size > Self; // variables private: password_t _password; // methods public: SimpleFileCryptAlgorithm (StringCRef password) : _password(0) { for (usize i = 0; i < password.Length() and i < _password.Count(); ++i) { _password[i] = password[i]; } } SimpleFileCryptAlgorithm (BinArrayCRef password) : _password(0) { for (usize i = 0; i < password.Count() and i < _password.Count(); ++i) { _password[i] = password[i]; } } void Encrypt (BytesU pos, INOUT ubyte &c) const { FOR( i, _password ) { c ^= _password[i] + (pos * i); } } void Decrypt (BytesU pos, INOUT ubyte &c) const { Encrypt( pos, c ); } }; // // Read only Crypted Sub File // template <typename A> class RCryptFile : public SubRFile { // types public: typedef A CryptAlgorithm; typedef RCryptFile<A> Self; typedef SharedPointerType<Self> RCryptFilePtr; // variables private: CryptAlgorithm _crypt; // methods public: RCryptFile (const RFilePtr &file, const CryptAlgorithm &alg) : SubRFile( file, file->Pos(), file->RemainingSize() ), _crypt(alg) {} RCryptFile (const RFilePtr &file, BytesU offset, BytesU size, const CryptAlgorithm &alg) : SubRFile( file, offset, size ), _crypt(alg) {} ND_ static RCryptFilePtr New (const RFilePtr &file, const CryptAlgorithm &alg) { return new Self( file, alg ); } ND_ static RCryptFilePtr New (const RFilePtr &file, BytesU offset, BytesU size, const CryptAlgorithm &alg) { return new Self( file, offset, size, alg ); } // RFile // virtual BytesU ReadBuf (void * buf, BytesU size) noexcept override { ubyte * data = Cast<ubyte *>(buf); BytesU pos = Pos(); BytesU r = SubRFile::ReadBuf( buf, size ); if ( r > 0 ) { for (usize i = 0; i < usize(r); ++i) { _crypt.Decrypt( pos + i, data[i] ); } } return r; } // BaseFile // virtual EFile::type GetType () const override { return EFile::Crypted; } private: static SubRFilePtr New (const RFilePtr &file, BytesU offset, BytesU size) = delete; }; // // Write only Crypted Sub File // template <typename A> class WCryptFile : public SubWFile { // types public: typedef A CryptAlgorithm; typedef WCryptFile<A> Self; typedef SharedPointerType<Self> WCryptFilePtr; // variables private: CryptAlgorithm _crypt; bool _restoreData; // methods public: WCryptFile (const WFilePtr &file, const CryptAlgorithm &alg, bool restoreData = true) : SubWFile( file, file->Pos(), file->RemainingSize() ), _crypt(alg), _restoreData(restoreData) {} WCryptFile (const WFilePtr &file, BytesU offset, BytesU size, const CryptAlgorithm &alg, bool restoreData = true) : SubWFile( file, offset, size ), _crypt(alg), _restoreData(restoreData) {} ND_ static WCryptFilePtr New (const WFilePtr &file, const CryptAlgorithm &alg, bool restoreData = true) { return new Self( file, alg, restoreData ); } ND_ static WCryptFilePtr New (const WFilePtr &file, BytesU offset, BytesU size, const CryptAlgorithm &alg, bool restoreData = true) { return new Self( file, offset, size, alg, restoreData ); } // WFile // virtual BytesU WriteBuf (const void * buf, BytesU size) noexcept override { ubyte * data = Cast<ubyte *>(buf); BytesU pos = Pos(); for (usize i = 0; i < size; ++i) { _crypt.Encrypt( pos + i, data[i] ); } BytesU w = SubWFile::WriteBuf( buf, size ); if ( _restoreData ) { for (usize i = 0; i < size; ++i) { _crypt.Decrypt( pos + i, data[i] ); } } return w; } // BaseFile // virtual EFile::type GetType () const override { return EFile::Crypted; } private: static SubWFilePtr New (const WFilePtr &file, BytesU offset, BytesU size) = delete; }; } // GXFile } // GX_STL #endif
#ifndef __APPENDER_H__ #define __APPENDER_H__ #include "dgrObject.h" DGR2_NP_BEGIN struct DGR2_API Appender : public DGRObject { virtual bool publish(const Log& log) = 0; virtual void setFilter(Filter* filter) = 0; virtual Filter* getFilter() = 0; virtual void setFormatter(Formatter* formatter) = 0; virtual Formatter* getFormatter() = 0; virtual void destroy(); protected: virtual ~Appender() {} }; NP_END #endif
/* TODO : finish this */ #define NDK_HTTP_MAIN_CONF NGX_HTTP_MAIN_CONF #define NDK_HTTP_SRV_CONF NGX_HTTP_SRV_CONF #define NDK_HTTP_SIF_CONF NGX_HTTP_SIF_CONF #define NDK_HTTP_LOC_CONF NGX_HTTP_LOC_CONF #define NDK_HTTP_LIF_CONF NGX_HTTP_LIF_CONF #define NDK_HTTP_UPS_CONF NGX_HTTP_UPS_CONF #define NDK_MAIN_CONF NGX_MAIN_CONF #define NDK_ANY_CONF NGX_ANY_CONF /* compound locations */ #define NDK_HTTP_MAIN_SRV_CONF NDK_HTTP_MAIN_CONF|NDK_HTTP_SRV_CONF #define NDK_HTTP_MAIN_SIF_CONF NDK_HTTP_MAIN_CONF|NDK_HTTP_SRV_SIF_CONF #define NDK_HTTP_MAIN_LOC_CONF NDK_HTTP_MAIN_CONF|NDK_HTTP_LOC_CONF #define NDK_HTTP_MAIN_LIF_CONF NDK_HTTP_MAIN_CONF|NDK_HTTP_LOC_LIF_CONF #define NDK_HTTP_SRV_SIF_CONF NDK_HTTP_SRV_CONF|NDK_HTTP_SIF_CONF #define NDK_HTTP_SRV_LOC_CONF NDK_HTTP_SRV_CONF|NDK_HTTP_LOC_CONF #define NDK_HTTP_SRV_LOC_LIF_CONF NDK_HTTP_SRV_CONF|NDK_HTTP_LOC_LIF_CONF #define NDK_HTTP_SRV_SIF_LOC_CONF NDK_HTTP_SRV_SIF_CONF|NDK_HTTP_LOC_CONF #define NDK_HTTP_SRV_SIF_LOC_LIF_CONF NDK_HTTP_SRV_SIF_CONF|NDK_HTTP_LOC_LIF_CONF #define NDK_HTTP_LOC_LIF_CONF NDK_HTTP_LOC_CONF|NDK_HTTP_LIF_CONF #define NDK_HTTP_MAIN_SRV_LOC_CONF NDK_HTTP_MAIN_CONF|NDK_HTTP_SRV_LOC_CONF #define NDK_HTTP_MAIN_SRV_LIF_CONF NDK_HTTP_MAIN_CONF|NDK_HTTP_SRV_LIF_CONF #define NDK_HTTP_MAIN_SIF_LOC_CONF NDK_HTTP_MAIN_CONF|NDK_HTTP_SIF_LOC_CONF #define NDK_HTTP_MAIN_SRV_SIF_LOC_LIF_CONF NDK_HTTP_SRV_SIF_LOC_LIF_CONF|NDK_MAIN_CONF #define NDK_HTTP_CONF NDK_HTTP_MAIN_SRV_SIF_LOC_LIF_CONF #define NDK_HTTP_ANY_CONF NDK_HTTP_CONF|NDK_HTTP_UPS_CONF /* property offsets NOTE : ngx_module_main_conf_t etc should be defined in the module's .c file before the commands */ #define NDK_HTTP_MAIN_CONF_PROP(p) NGX_HTTP_MAIN_CONF_OFFSET, offsetof (ndk_module_main_conf_t, p) #define NDK_HTTP_SRV_CONF_PROP(p) NGX_HTTP_SRV_CONF_OFFSET, offsetof (ndk_module_srv_conf_t, p) #define NDK_HTTP_LOC_CONF_PROP(p) NGX_HTTP_LOC_CONF_OFFSET, offsetof (ndk_module_loc_conf_t, p)
/** * @file MazeField.h * @author Albert Uchytil (xuchyt03), Tomas Coufal (xcoufa09) * @brief Class defining the the field on the board */ #ifndef MAZEFIELD_H #define MAZEFIELD_H #include "MazeCard.h" /// @brief Class containig the field data like card, and handles the neighborhood class MazeField { public: MazeField(int r, int c); virtual ~MazeField(); int row(); int col(); MazeCard getCard(); MazeCard *getCardP(); void putCard(MazeCard c); protected: private: int _row; int _col; MazeCard _cardL; }; #endif // MAZEFIELD_H
#ifndef CAMERA_H #define CAMERA_H #include "GameObjects/GameObject.h" #include "GameObjects/Billboard.h" #include "GameObjects/Weapon.h" #include "Models/Armature.hpp" #include <iostream> #include <cmath> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include <SDL/SDL.h> class Weapon; class Camera : public GameObject{ public: Camera(ObjectData* objectData, float windowSize[2], DataBlock& def, GameState* state); ~Camera(); bool holdingForward; bool holdingBackward; bool holdingLeftStrafe; bool holdingRightStrafe; bool playerIsFiring; void fire(); void handleMouseMove(int mouseX, int mouseY); void move(double deltaTime, Camera* player, std::list<GameObject*>* levelObjects); void render(GameState* state); void commitMovement(GameState* state){ position += movement; head += movement; origin += movement; if(movement.y == 0.0f) ground = true; } float getPitchSensitivity() { return pitchSensitivity; } void setPitchSensitivity(float value) { pitchSensitivity = value; } float getYawSensitivity() { return yawSensitivity; } void setYawSensitivity(float value) { yawSensitivity = value; } glm::vec3 getPosition() const {return position;} void setXPos(double x) {position.x = x;} void setYPos(double y) {position.y = y;} void setZPos(double z) {position.z = z;} glm::vec3 getHead() const { return head;} void setXHead(double x) {head.x = x;} void setYHead(double y) {head.y = y;} void setZHead(double z) {head.z = z;} glm::vec3 getOrigin() const { return origin;} void setXOrigin(double x) {origin.x = x;} void setYOrigin(double y) {origin.y = y;} void setZOrigin(double z) {origin.z = z;} glm::vec3 getFront() const { return front;} void setXFront(double x) {front.x = x;} void setYFront(double y) {front.y = y;} void setZFront(double z) {front.z = z;} glm::vec3 getRight() const { return right;} void setXRight(double x) {right.x = x;} void setYRight(double y) {right.y = y;} void setZRight(double z) {right.z = z;} glm::vec3 getUp() const { return up;} void setXUp(double x) {up.x = x;} void setYUp(double y) {up.y = y;} void setZUp(double z) {up.z = z;} private: glm::vec3 head; glm::vec3 origin; //for glmLootAt glm::vec3 front; glm::vec3 up; glm::vec3 right; float rotHorizontal, rotVertical; Billboard* crosshairs; Billboard* healthMeter; TTF_Font* healthMeterFont; std::string nameCurrentWeapon; Weapon* currentWeapon; double movementSpeedFactor; double pitchSensitivity; double yawSensitivity; int windowWidth; int windowHeight; int windowMidX; int windowMidY; void initCamera(); }; #endif
/* * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. ``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 APPLE INC. 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 MediaRemoteControls_h #define MediaRemoteControls_h #if ENABLE(MEDIA_SESSION) #include "EventTarget.h" #include <wtf/RefCounted.h> namespace WebCore { class MediaSession; class MediaRemoteControls : public RefCounted<MediaRemoteControls>, public EventTargetWithInlineData { public: static Ref<MediaRemoteControls> create(ScriptExecutionContext& context, MediaSession* session = nullptr) { return adoptRef(*new MediaRemoteControls(context, session)); } bool previousTrackEnabled() const { return m_previousTrackEnabled; } void setPreviousTrackEnabled(bool); bool nextTrackEnabled() const { return m_nextTrackEnabled; } void setNextTrackEnabled(bool); using RefCounted<MediaRemoteControls>::ref; using RefCounted<MediaRemoteControls>::deref; void clearSession(); virtual ~MediaRemoteControls(); EventTargetInterface eventTargetInterface() const override { return MediaRemoteControlsEventTargetInterfaceType; } ScriptExecutionContext* scriptExecutionContext() const override { return &m_scriptExecutionContext; } private: MediaRemoteControls(ScriptExecutionContext&, MediaSession*); ScriptExecutionContext& m_scriptExecutionContext; bool m_previousTrackEnabled { false }; bool m_nextTrackEnabled { false }; MediaSession* m_session { nullptr }; void refEventTarget() final { ref(); } void derefEventTarget() final { deref(); } }; } // namespace WebCore #endif /* ENABLE(MEDIA_SESSION) */ #endif /* MediaRemoteControls_h */
/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2013 Stephen Kelly <steveire@gmail.com> Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #ifndef cmExportInstallFileGenerator_h #define cmExportInstallFileGenerator_h #include "cmExportFileGenerator.h" class cmInstallExportGenerator; class cmInstallTargetGenerator; class cmExportTryCompileFileGenerator: public cmExportFileGenerator { public: /** Set the list of targets to export. */ void SetExports(const std::vector<cmTarget const*> &exports) { this->Exports = exports; } void SetConfig(const char *config) { this->Config = config; } protected: // Implement virtual methods from the superclass. virtual bool GenerateMainFile(std::ostream& os); virtual void GenerateImportTargetsConfig(std::ostream&, const char*, std::string const&, std::vector<std::string>&) {} virtual void HandleMissingTarget(std::string&, std::vector<std::string>&, cmMakefile*, cmTarget*, cmTarget*) {} void PopulateProperties(cmTarget const* target, ImportPropertyMap& properties, std::set<cmTarget const*> &emitted); std::string InstallNameDir(cmTarget* target, const std::string& config); private: std::string FindTargets(const char *prop, cmTarget const* tgt, std::set<cmTarget const*> &emitted); std::vector<cmTarget const*> Exports; const char *Config; }; #endif
/* $NiH: add_from_buffer.c,v 1.3 2006/05/09 23:41:32 wiz Exp $ add_from_buffer.c -- test case for adding file from buffer to archive Copyright (C) 1999, 2003, 2005 Dieter Baron and Thomas Klausner This file is part of libzip, a library to manipulate ZIP archives. The authors can be contacted at <nih@giga.or.at> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS 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 <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "zip.h" const char *teststr="This is a test, and it seems to have been successful.\n"; const char *file="teststring.txt"; const char *prg; int main(int argc, char *argv[]) { const char *archive; struct zip *za; struct zip_source *zs; char buf[100]; int err; prg = argv[0]; if (argc != 2) { fprintf(stderr, "usage: %s archive\n", prg); return 1; } archive = argv[1]; if ((za=zip_open(archive, ZIP_CREATE, &err)) == NULL) { zip_error_to_str(buf, sizeof(buf), err, errno); fprintf(stderr,"%s: can't open zip archive %s: %s\n", prg, archive, buf); return 1; } if ((zs=zip_source_buffer(za, teststr, strlen(teststr), 0)) == NULL) { fprintf(stderr,"%s: can't create zip_source from buffer: %s\n", prg, zip_strerror(za)); exit(1); } if (zip_add(za, file, zs) == -1) { zip_source_free(zs); fprintf(stderr,"%s: can't add file `%s': %s\n", prg, file, zip_strerror(za)); return 1; } if (zip_close(za) == -1) { fprintf(stderr,"%s: can't close zip archive %s\n", prg, archive); return 1; } return 0; }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "AssetTypeActions_Base.h" class FAssetTypeActions_Blackboard : public FAssetTypeActions_Base { public: // IAssetTypeActions Implementation virtual FText GetName() const override { return NSLOCTEXT("AssetTypeActions", "AssetTypeActions_Blackboard", "Blackboard"); } virtual FColor GetTypeColor() const override { return FColor(201, 29, 85); } virtual UClass* GetSupportedClass() const override; virtual void OpenAssetEditor( const TArray<UObject*>& InObjects, TSharedPtr<class IToolkitHost> EditWithinLevelEditor = TSharedPtr<IToolkitHost>() ) override; virtual uint32 GetCategories() override; };
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled May 11 2021 09:30:43). // // Copyright (C) 1997-2019 Steve Nygard. // #import <XCTest/NSObject-Protocol.h> #import <XCTest/XCTElementSnapshotAttributeDataSource-Protocol.h> #import <XCTest/XCUIAXNotificationHandling-Protocol.h> @class NSArray, NSDictionary, NSString, XCAccessibilityElement, XCElementSnapshot, XCTestExpectation, XCUIAccessibilityAction, XCUIApplicationProcess, XCUIElementSnapshotRequestResult; @protocol XCUIAccessibilityInterface <NSObject, XCUIAXNotificationHandling, XCTElementSnapshotAttributeDataSource> @property(readonly, nonatomic) XCAccessibilityElement *systemApplication; @property(readonly) _Bool supportsAnimationsInactiveNotifications; @property double AXTimeout; - (XCAccessibilityElement *)accessibilityElementForElementAtPoint:(struct CGPoint)arg1 error:(id *)arg2; - (void)performWhenMenuOpens:(XCAccessibilityElement *)arg1 block:(void (^)(void))arg2; - (void)removeObserver:(id)arg1 forAXNotification:(NSString *)arg2; - (id)addObserverForAXNotification:(NSString *)arg1 handler:(void (^)(XCAccessibilityElement *, NSDictionary *))arg2; - (void)unregisterForAXNotificationsForApplicationWithPID:(int)arg1; - (void)registerForAXNotificationsForApplicationWithPID:(int)arg1 timeout:(double)arg2 completion:(void (^)(_Bool, NSError *))arg3; - (NSArray *)localizableStringsDataForActiveApplications; - (_Bool)enableFauxCollectionViewCells:(id *)arg1; - (void)notifyWhenViewControllerViewDidDisappearReply:(void (^)(NSDictionary *, NSError *))arg1; - (XCTestExpectation *)viewDidAppearExpectationForElement:(XCAccessibilityElement *)arg1 viewControllerName:(NSString *)arg2; - (void)notifyWhenNoAnimationsAreActiveForApplication:(XCUIApplicationProcess *)arg1 reply:(void (^)(NSDictionary *, NSError *))arg2; - (void)notifyOnNextOccurrenceOfUserTestingEvent:(NSString *)arg1 handler:(void (^)(NSDictionary *, NSError *))arg2; - (_Bool)cachedAccessibilityLoadedValueForPID:(int)arg1; - (id)parameterizedAttribute:(NSString *)arg1 forElement:(XCAccessibilityElement *)arg2 parameter:(id)arg3 error:(id *)arg4; - (_Bool)setAttribute:(NSString *)arg1 value:(id)arg2 element:(XCAccessibilityElement *)arg3 outError:(id *)arg4; - (XCUIElementSnapshotRequestResult *)requestSnapshotForElement:(XCAccessibilityElement *)arg1 attributes:(NSArray *)arg2 parameters:(NSDictionary *)arg3 error:(id *)arg4; - (void)notifyWhenEventLoopIsIdleForApplication:(XCUIApplicationProcess *)arg1 reply:(void (^)(NSDictionary *, NSError *))arg2; - (_Bool)performAction:(XCUIAccessibilityAction *)arg1 onElement:(XCAccessibilityElement *)arg2 value:(id)arg3 error:(id *)arg4; - (XCAccessibilityElement *)hitTestElement:(XCElementSnapshot *)arg1 withPoint:(struct CGPoint)arg2 error:(id *)arg3; - (NSArray *)interruptingUIElementsAffectingSnapshot:(XCElementSnapshot *)arg1 checkForHandledElement:(XCAccessibilityElement *)arg2 containsHandledElement:(_Bool *)arg3; - (_Bool)loadAccessibility:(id *)arg1; @end
/*****************************************************************************/ /* */ /* © 2011, Aurbach & Associates, Inc. All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following condition */ /* 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 Aurbach & Associates, Inc. nor the names of any */ /* of its employees 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. */ /* */ /*****************************************************************************/ /* * Class Name: CAPreferences * * Change History: * * Who Date Description * --------------------------------------------------------------------------- * RLA 09-Oct-2006 Original Code (UCFPreferences.h) * RLA 23-Aug-2011 Converted for use in the Constructor environment */ // --------------------------------------------------------------------------- // NOTE: It would be pretty logical (and obvious) to implement specifc // accessor functions for booleans, integers, and strings. However, // we don't do that here because Constructor doesn't need them. // --------------------------------------------------------------------------- #pragma once #if !defined(__MACH__) #include <CFPreferences.h> #endif namespace CAPreferences { bool IsDefined ( CFStringRef inKey ); CFPropertyListRef CopyValueAsPropertyList ( CFStringRef inKey ); void SetValueAsPropertyList ( CFStringRef inKey, CFPropertyListRef inValue ); UInt32 GetValueAsBlock ( CFStringRef inKey, void * inBlock, UInt32 inMaxSize ); void SetValueAsBlock ( CFStringRef inKey, const void * inBlock, UInt32 inSize ); Handle CopyValueAsHandle ( CFStringRef inKey ); void SetValueAsHandle ( CFStringRef inKey, Handle inValue ); void Remove ( CFStringRef inKey ); bool Synchronize (); } class StUpdatePreferences { public: StUpdatePreferences () {} ~StUpdatePreferences () { CAPreferences::Synchronize(); } };
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2018-2019 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. * *********************************************************************************/ #pragma once #include <modules/discretedata/discretedatamoduledefine.h> #include <inviwo/core/common/inviwo.h> namespace inviwo { namespace discretedata { //! Discretedata index type using ind = signed long long; /** * Mapping structure name to respective dimension. * Assign channels to any dimensions this way. * If these do not suffice, cast the respective short. */ enum class GridPrimitive : ind { Undef = -1, Vertex = 0, Edge = 1, Face = 2, Volume = 3, HyperVolume = 4 }; } // namespace discretedata } // namespace inviwo
#ifndef PM_BASE64_H_ #define PM_BASE64_H_ #include "pm.h" #include <stdint.h> #include <stdio.h> #define PM_BASE64_DECODED_SIZE(x) ((PM_ROUND_UP(x, 4UL) * 3UL) / 4UL) #define PM_BASE64_ENCODED_SIZE(x) ((PM_ROUND_UP(x, 3UL) * 4UL) / 3UL) enum pm_base64_encoding_e { PM_BASE64_RFC3458, PM_BASE64_RFC4648, PM_BASE64_RFC7515, PM_BASE64_XML_IDENTIFIER, PM_BASE64_XML_NAME_TOKEN, }; extern ssize_t pm_base64_encode( char *buffer, size_t szBuffer, void const *data, size_t szData); extern ssize_t pm_base64_decode( void *buffer, size_t szBuffer, char const *data, size_t szData); #endif
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "MobilityCustomization.h" class FSceneComponentDetails : public IDetailCustomization { public: /** Makes a new instance of this detail layout class for a specific detail view requesting it */ static TSharedRef<IDetailCustomization> MakeInstance(); /** IDetailCustomization interface */ virtual void CustomizeDetails( IDetailLayoutBuilder& DetailBuilder ) override; private: void MakeTransformDetails( IDetailLayoutBuilder& DetailBuilder ); TSharedPtr<FMobilityCustomization> MobilityCustomization; };
// Copyright (c) 2017 Timo Savola. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <sys/types.h> struct cgroup_config { const char *title; const char *parent; }; extern const char cgroup_backend[]; void init_cgroup(pid_t pid, const struct cgroup_config *config);
/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef GrColor_DEFINED #define GrColor_DEFINED #include "include/core/SkColor.h" #include "include/core/SkColorPriv.h" #include "include/gpu/GrTypes.h" #include "include/private/SkColorData.h" #include "include/private/SkHalf.h" #include "src/gpu/BufferWriter.h" /** * GrColor is 4 bytes for R, G, B, A, in a specific order defined below. Whether the color is * premultiplied or not depends on the context in which it is being used. */ typedef uint32_t GrColor; // shift amount to assign a component to a GrColor int // These shift values are chosen for compatibility with GL attrib arrays // ES doesn't allow BGRA vertex attrib order so if they were not in this order // we'd have to swizzle in shaders. #ifdef SK_CPU_BENDIAN #define GrColor_SHIFT_R 24 #define GrColor_SHIFT_G 16 #define GrColor_SHIFT_B 8 #define GrColor_SHIFT_A 0 #else #define GrColor_SHIFT_R 0 #define GrColor_SHIFT_G 8 #define GrColor_SHIFT_B 16 #define GrColor_SHIFT_A 24 #endif /** * Pack 4 components (RGBA) into a GrColor int */ static inline GrColor GrColorPackRGBA(unsigned r, unsigned g, unsigned b, unsigned a) { SkASSERT((uint8_t)r == r); SkASSERT((uint8_t)g == g); SkASSERT((uint8_t)b == b); SkASSERT((uint8_t)a == a); return (r << GrColor_SHIFT_R) | (g << GrColor_SHIFT_G) | (b << GrColor_SHIFT_B) | (a << GrColor_SHIFT_A); } // extract a component (byte) from a GrColor int #define GrColorUnpackR(color) (((color) >> GrColor_SHIFT_R) & 0xFF) #define GrColorUnpackG(color) (((color) >> GrColor_SHIFT_G) & 0xFF) #define GrColorUnpackB(color) (((color) >> GrColor_SHIFT_B) & 0xFF) #define GrColorUnpackA(color) (((color) >> GrColor_SHIFT_A) & 0xFF) /** * Since premultiplied means that alpha >= color, we construct a color with * each component==255 and alpha == 0 to be "illegal" */ #define GrColor_ILLEGAL (~(0xFF << GrColor_SHIFT_A)) /** Normalizes and coverts an uint8_t to a float. [0, 255] -> [0.0, 1.0] */ static inline float GrNormalizeByteToFloat(uint8_t value) { static const float ONE_OVER_255 = 1.f / 255.f; return value * ONE_OVER_255; } /** Used to pick vertex attribute types. */ static inline bool SkPMColor4fFitsInBytes(const SkPMColor4f& color) { // Might want to instead check that the components are [0...a] instead of [0...1]? return color.fitsInBytes(); } static inline uint64_t SkPMColor4f_toFP16(const SkPMColor4f& color) { uint64_t halfColor; SkFloatToHalf_finite_ftz(Sk4f::Load(color.vec())).store(&halfColor); return halfColor; } /** * GrVertexColor is a helper for writing colors to a vertex attribute. It stores either GrColor * or four half-float channels, depending on the wideColor parameter. VertexWriter will write the * correct amount of data. Note that the GP needs to have been constructed with the correct * attribute type for colors, to match the usage here. */ class GrVertexColor { public: GrVertexColor() = default; explicit GrVertexColor(const SkPMColor4f& color, bool wideColor) { this->set(color, wideColor); } void set(const SkPMColor4f& color, bool wideColor) { if (wideColor) { memcpy(fColor, color.vec(), sizeof(fColor)); } else { fColor[0] = color.toBytes_RGBA(); } fWideColor = wideColor; } size_t size() const { return fWideColor ? 16 : 4; } private: template <typename T> friend skgpu::VertexWriter& skgpu::operator<<(skgpu::VertexWriter&, const T&); uint32_t fColor[4]; bool fWideColor; }; template <> SK_MAYBE_UNUSED inline skgpu::VertexWriter& skgpu::operator<<(skgpu::VertexWriter& w, const GrVertexColor& color) { w << color.fColor[0]; if (color.fWideColor) { w << color.fColor[1] << color.fColor[2] << color.fColor[3]; } return w; } #endif
#ifndef __TEST_H__ #define __TEST_H__ #include <stdio.h> char * Exec(char * soData, int * replylen); int TimerEvnet(); void OnInit(); #endif
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__twoIntsStruct_calloc_02.c Label Definition File: CWE401_Memory_Leak.c.label.xml Template File: sources-sinks-02.tmpl.c */ /* * @description * CWE: 401 Memory Leak * BadSource: calloc Allocate data using calloc() * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call free() on data * BadSink : no deallocation of data * Flow Variant: 02 Control flow: if(1) and if(0) * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE401_Memory_Leak__twoIntsStruct_calloc_02_bad() { twoIntsStruct * data; data = NULL; if(1) { /* POTENTIAL FLAW: Allocate memory on the heap */ data = (twoIntsStruct *)calloc(100, sizeof(twoIntsStruct)); if (data == NULL) {exit(-1);} /* Initialize and make use of data */ data[0].intOne = 0; data[0].intTwo = 0; printStructLine(&data[0]); } if(1) { /* POTENTIAL FLAW: No deallocation */ ; /* empty statement needed for some flow variants */ } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second 1 to 0 */ static void goodB2G1() { twoIntsStruct * data; data = NULL; if(1) { /* POTENTIAL FLAW: Allocate memory on the heap */ data = (twoIntsStruct *)calloc(100, sizeof(twoIntsStruct)); if (data == NULL) {exit(-1);} /* Initialize and make use of data */ data[0].intOne = 0; data[0].intTwo = 0; printStructLine(&data[0]); } if(0) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Deallocate memory */ free(data); } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { twoIntsStruct * data; data = NULL; if(1) { /* POTENTIAL FLAW: Allocate memory on the heap */ data = (twoIntsStruct *)calloc(100, sizeof(twoIntsStruct)); if (data == NULL) {exit(-1);} /* Initialize and make use of data */ data[0].intOne = 0; data[0].intTwo = 0; printStructLine(&data[0]); } if(1) { /* FIX: Deallocate memory */ free(data); } } /* goodG2B1() - use goodsource and badsink by changing the first 1 to 0 */ static void goodG2B1() { twoIntsStruct * data; data = NULL; if(0) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use memory allocated on the stack with ALLOCA */ data = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct)); /* Initialize and make use of data */ data[0].intOne = 0; data[0].intTwo = 0; printStructLine(&data[0]); } if(1) { /* POTENTIAL FLAW: No deallocation */ ; /* empty statement needed for some flow variants */ } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { twoIntsStruct * data; data = NULL; if(1) { /* FIX: Use memory allocated on the stack with ALLOCA */ data = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct)); /* Initialize and make use of data */ data[0].intOne = 0; data[0].intTwo = 0; printStructLine(&data[0]); } if(1) { /* POTENTIAL FLAW: No deallocation */ ; /* empty statement needed for some flow variants */ } } void CWE401_Memory_Leak__twoIntsStruct_calloc_02_good() { goodB2G1(); goodB2G2(); 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()..."); CWE401_Memory_Leak__twoIntsStruct_calloc_02_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE401_Memory_Leak__twoIntsStruct_calloc_02_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#pragma once #include <algorithm> #include <cmath> #include "multiscalefilter/MultiScaleFilter.hpp" class FourierDecomposition { int window_type; double T;// period double sigma;//parameter sigma float beta, alpha, remap_sigma; int n;//order double omega_n; double fcos(double x) { return getGaussianWindow(abs(x / sigma)) * cos(omega_n * x); } double fsin(double x) { switch (window_type) { case GAUSS: //return x * getGaussWeight(x, 0, sigma) * sin(omega_n * x); break; return x * getGaussianWindow(abs(x / sigma)) * sin(omega_n * x); break; case S_TONE: return getSToneCurve<double>(x, 0.0, remap_sigma, beta, alpha) * sin(omega_n * x); break; case HAT: return x * std::max(0.0, 1.0 - abs(x / sigma)) * sin(omega_n * x); break; case SMOOTH_HAT: return getSmoothingHat(x, 0.0, sigma, 10) * sin(omega_n * x); break; } return x * sin(omega_n * x);// getSToneWeight(x, remap_sigma, beta, alpha)* sin(omega_n * x); } double f(double x) { switch (window_type) { case GAUSS: return getGaussianWindow(abs(x / sigma)); break; case S_TONE: return getSToneCurve<double>(x, 0.0, remap_sigma, beta, alpha); break; case HAT: return std::max(0.0, 1.0 - abs(x / sigma)); break; case SMOOTH_HAT: return getSmoothingHat(x, 0.0, sigma, 10); break; } return getSToneWeight(float(x), remap_sigma, beta, alpha); } public: FourierDecomposition(double T, double sigma, double beta, double alpha, double remap_sigma, int n, int window_type) :T(T), sigma(sigma), n(n), window_type(window_type), beta((float)beta), alpha((float)alpha), remap_sigma((float)remap_sigma) { omega_n = n * CV_2PI / T;//omega=CV_2PI/T } //a, b: Integration interval //m: number of divisions double ct(double a, double b, const int m, bool isKahan = false)//0-T/2 { const double step = (b - a) / m;//interval //init double x = a; double s = 0.0;//result of integral if (isKahan) { double c = 0.0; for (int k = 1; k <= m - 1; k++) { x += step; const double y = fcos(x) - c; const double t = s + y; c = (t - s) - y; s = t; } } else { for (int k = 1; k <= m - 1; k++) { x += step; s += fcos(x); } } s = step * ((fcos(a) + fcos(b)) / 2.0 + s); //double sign=0; //if (n % 4 == 0)sign = 1.0; //if (n % 4 == 2)sign = -1.0; //s = step * ((f(0) +sign*f(b)) / 2.0 + s); return s; } //a, b: Integration interval //m: number of divisions double st(double a, double b, const int m, const bool isKahan = false) { const double step = (b - a) / m;//interval //init double x = a; double s = 0.0;//result of integral if (isKahan) { double c = 0.0; for (int k = 1; k <= m - 1; k++) { x += step; const double y = fsin(x) - c; const double t = s + y; c = (t - s) - y; s = t; } } else { for (int k = 1; k <= m - 1; k++) { x += step; s += fsin(x); } } s = step * ((fsin(a) + fsin(b)) / 2.0 + s); return s; } //double operator()(double a, double b, const int m) double init(double a, double b, const int m, const bool isKahan = false) { const double step = (b - a) / m;//interval //init double x = a; double s = 0.0;//result of integral if (isKahan) { double c = 0.0; for (int k = 1; k <= m - 1; k++) { x += step; const double y = f(x) - c; const double t = s + y; c = (t - s) - y; s = t; } } else { for (int k = 1; k <= m - 1; k++) { x += step; s += f(x); } } s = step * ((f(a) + f(b)) / 2.0 + s); return s; } };
/* This file may have been modified by DJ Delorie (Jan 1991). If so, ** these modifications are Coyright (C) 1991 DJ Delorie, 24 Kirsten Ave, ** Rochester NH, 03867-2954, USA. */ /*- * Copyright (c) 1988 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that: (1) source distributions retain this entire copyright * notice and comment, and (2) distributions including binaries display * the following acknowledgement: ``This product includes software * developed by the University of California, Berkeley and its contributors'' * in the documentation or other materials provided with the distribution * and in all advertising materials mentioning features or use of this * software. 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <reent.h> #include <stdlib.h> #include <string.h> #include "envlock.h" /* _putenv_r - reentrant version of putenv that either adds or replaces the environment variable "name" with "value" which is specified by str as "name=value". */ int _DEFUN (_putenv_r, (reent_ptr, str), struct _reent *reent_ptr _AND _CONST char *str) { register char *p, *equal; int rval; p = _strdup_r (reent_ptr, str); if (!p) return 1; if (!(equal = index (p, '='))) { (void) _free_r (reent_ptr, p); return 1; } *equal = '\0'; rval = _setenv_r (reent_ptr, p, equal + 1, 1); (void) _free_r (reent_ptr, p); return rval; }
/* * 2007 – 2013 Copyright Northwestern University * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details. */ #ifndef _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CNPPD_ST_NT #define _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CNPPD_ST_NT #include "type_iso.CANY.h" namespace AIMXML { namespace iso { class CNPPD_ST_NT : public ::AIMXML::iso::CANY { public: AIMXML_EXPORT CNPPD_ST_NT(xercesc::DOMNode* const& init); AIMXML_EXPORT CNPPD_ST_NT(CNPPD_ST_NT const& init); void operator=(CNPPD_ST_NT const& other) { m_node = other.m_node; } static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_iso_altova_CNPPD_ST_NT); } MemberElement<iso::CUVP_ST_NT, _altova_mi_iso_altova_CNPPD_ST_NT_altova_item> item; struct item { typedef Iterator<iso::CUVP_ST_NT> iterator; }; AIMXML_EXPORT void SetXsiType(); }; } // namespace iso } // namespace AIMXML #endif // _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CNPPD_ST_NT
/* * Copyright (c) 1982, 1986, 1993, 1994 * 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. 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. * * @(#)uio.h 8.5 (Berkeley) 2/22/94 */ #ifndef _SYS_UIO_H_ #define _SYS_UIO_H_ /* * XXX * iov_base should be a void *. */ struct iovec { char *iov_base; /* Base address. */ size_t iov_len; /* Length. */ }; enum uio_rw { UIO_READ, UIO_WRITE }; /* Segment flag values. */ enum uio_seg { UIO_USERSPACE, /* from user data space */ UIO_SYSSPACE, /* from system space */ UIO_USERISPACE /* from user I space */ }; #ifdef KERNEL struct uio { struct iovec *uio_iov; int uio_iovcnt; off_t uio_offset; int uio_resid; enum uio_seg uio_segflg; enum uio_rw uio_rw; struct proc *uio_procp; }; /* * Limits */ #define UIO_MAXIOV 1024 /* max 1K of iov's */ #define UIO_SMALLIOV 8 /* 8 on stack, else malloc */ #endif /* KERNEL */ #ifndef KERNEL #include <sys/cdefs.h> __BEGIN_DECLS ssize_t readv __P((int, const struct iovec *, int)); ssize_t writev __P((int, const struct iovec *, int)); __END_DECLS #endif /* !KERNEL */ #endif /* !_SYS_UIO_H_ */
// vim:ts=8:expandtab #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #ifdef LINUX #include <iwlib.h> #endif #include "i3status.h" static const char *get_wireless_essid(const char *interface) { static char part[512]; #ifdef LINUX int skfd; if ((skfd = iw_sockets_open()) < 0) { perror("socket"); exit(-1); } struct wireless_config wcfg; if (iw_get_basic_config(skfd, interface, &wcfg) >= 0) snprintf(part, sizeof(part), "%s", wcfg.essid); else part[0] = '\0'; (void)close(skfd); #else part[0] = '\0'; #endif return part; } /* * Just parses /proc/net/wireless looking for lines beginning with * wlan_interface, extracting the quality of the link and adding the * current IP address of wlan_interface. * */ void print_wireless_info(const char *interface, const char *format_up, const char *format_down) { char buf[1024]; int quality = -1; char *interfaces; const char *walk; memset(buf, 0, sizeof(buf)); if (!slurp("/proc/net/wireless", buf, sizeof(buf))) die("Could not open \"/proc/net/wireless\"\n"); interfaces = skip_character(buf, '\n', 1) + 1; while ((interfaces = skip_character(interfaces, '\n', 1)+1) < buf+strlen(buf)) { while (isspace((int)*interfaces)) interfaces++; if (!BEGINS_WITH(interfaces, interface)) continue; if (sscanf(interfaces, "%*[^:]: 0000 %d", &quality) != 1) continue; break; } /* Interface could not be found */ if (quality == -1) return; if ((quality == UCHAR_MAX) || (quality == 0)) { walk = format_down; printf("%s", color("#FF0000")); } else { printf("%s", color("#00FF00")); walk = format_up; } for (; *walk != '\0'; walk++) { if (*walk != '%') { putchar(*walk); continue; } if (BEGINS_WITH(walk+1, "quality")) { (void)printf("%03d%%", quality); walk += strlen("quality"); } if (BEGINS_WITH(walk+1, "essid")) { (void)printf("%s", get_wireless_essid(interface)); walk += strlen("essid"); } if (BEGINS_WITH(walk+1, "ip")) { const char *ip_address = get_ip_addr(interface); if (ip_address != NULL) (void)printf("%s", get_ip_addr(interface)); else (void)printf("no IP"); walk += strlen("ip"); } } (void)printf("%s", endcolor()); }
/* $OpenBSD: rsa_saos.c,v 1.23 2017/05/02 03:59:45 deraadt Exp $ */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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 cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <string.h> #include <openssl/bn.h> #include <openssl/err.h> #include <openssl/objects.h> #include <openssl/rsa.h> #include <openssl/x509.h> int RSA_sign_ASN1_OCTET_STRING(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, RSA *rsa) { ASN1_OCTET_STRING sig; int i, j, ret = 1; unsigned char *p, *s; sig.type = V_ASN1_OCTET_STRING; sig.length = m_len; sig.data = (unsigned char *)m; i = i2d_ASN1_OCTET_STRING(&sig, NULL); j = RSA_size(rsa); if (i > (j - RSA_PKCS1_PADDING_SIZE)) { RSAerror(RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY); return 0; } s = malloc(j + 1); if (s == NULL) { RSAerror(ERR_R_MALLOC_FAILURE); return 0; } p = s; i2d_ASN1_OCTET_STRING(&sig, &p); i = RSA_private_encrypt(i, s, sigret, rsa, RSA_PKCS1_PADDING); if (i <= 0) ret = 0; else *siglen = i; freezero(s, (unsigned int)j + 1); return ret; } int RSA_verify_ASN1_OCTET_STRING(int dtype, const unsigned char *m, unsigned int m_len, unsigned char *sigbuf, unsigned int siglen, RSA *rsa) { int i, ret = 0; unsigned char *s; const unsigned char *p; ASN1_OCTET_STRING *sig = NULL; if (siglen != (unsigned int)RSA_size(rsa)) { RSAerror(RSA_R_WRONG_SIGNATURE_LENGTH); return 0; } s = malloc(siglen); if (s == NULL) { RSAerror(ERR_R_MALLOC_FAILURE); goto err; } i = RSA_public_decrypt((int)siglen, sigbuf, s, rsa, RSA_PKCS1_PADDING); if (i <= 0) goto err; p = s; sig = d2i_ASN1_OCTET_STRING(NULL, &p, (long)i); if (sig == NULL) goto err; if ((unsigned int)sig->length != m_len || memcmp(m, sig->data, m_len) != 0) { RSAerror(RSA_R_BAD_SIGNATURE); } else ret = 1; err: ASN1_OCTET_STRING_free(sig); freezero(s, (unsigned int)siglen); return ret; }
// Copyright (c) 2009, Object Computing, Inc. // All rights reserved. // See the file license.txt for licensing information. #ifdef _MSC_VER # pragma once #endif #ifndef COMMANDARGHANDLER_H #define COMMANDARGHANDLER_H namespace QuickFAST { /// @brief Abstract interface to be implemented by objects /// that handle command line options. class CommandArgHandler { public: /// @brief Parse a single argument from the command line. /// /// Each call should consume one logical argument. You will be called again /// to consume subsequent arguments. For example if your implementation accepts /// arguments -f [file] and -v, and argc is -f output -x -v you should interpret /// [-f output] and return 2. Do NOT go looking for the -v. /// @param argc the count of remaining, unparsed arguments /// @param argv the remaining, unparsed arguments from the command line /// @return the number of arguments consumed. 0 means argv[0] was not recognized. virtual int parseSingleArg(int argc, char * argv[]) = 0; /// @brief Report command line arguments recognized by this handler. /// @param out is the device to which the known arguments should be reported. virtual void usage(std::ostream & out) const = 0; /// @brief After all arguments a parsed apply them. /// /// This will be called only if all arguments are parsed successfully. /// @returns true if successful virtual bool applyArgs() = 0; }; } #endif // COMMANDARGHANDLER_H
/* * Copyright (C) 2012 Company 100, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CoordinatedCustomFilterProgram_h #define CoordinatedCustomFilterProgram_h #if USE(COORDINATED_GRAPHICS) && ENABLE(CSS_SHADERS) #include "CustomFilterConstants.h" #include "CustomFilterProgram.h" namespace WebCore { class CoordinatedCustomFilterProgram : public CustomFilterProgram { public: static PassRefPtr<CoordinatedCustomFilterProgram> create(const String& vertexShaderString, const String& fragmentShaderString, CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType) { return adoptRef(new CoordinatedCustomFilterProgram(vertexShaderString, fragmentShaderString, programType, mixSettings, meshType)); } virtual bool isLoaded() const OVERRIDE { return true; } protected: virtual String vertexShaderString() const OVERRIDE { return m_vertexShaderString; } virtual String fragmentShaderString() const OVERRIDE { return m_fragmentShaderString; } virtual void willHaveClients() OVERRIDE { notifyClients(); } virtual void didRemoveLastClient() OVERRIDE { } private: CoordinatedCustomFilterProgram(const String& vertexShaderString, const String& fragmentShaderString, CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType) : CustomFilterProgram(programType, mixSettings, meshType) , m_vertexShaderString(vertexShaderString) , m_fragmentShaderString(fragmentShaderString) { } String m_vertexShaderString; String m_fragmentShaderString; }; } // namespace WebCore #endif // USE(COORDINATED_GRAPHICS) && ENABLE(CSS_SHADERS) #endif // CoordinatedCustomFilterProgram_h
/***************************************************************************** * Copyright (c) 2011, Marcello Bonfe' * ENDIF - ENgineering Department In Ferrara, * University of Ferrara. * 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 Ferrara 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 MARCELLO BONFE' 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. * ***************************************************************************** * * * Author: Marco Altafini * * * * Filename: InputCapture.h * * Date: 15/05/2012 * * File Version: 1.3 * * Compiler: MPLAB C30 v3.23 * * * *********************************************************************** * Code Description * * Header file for Input capture module. * **********************************************************************/ #ifndef INPUTCAPTURE_H #define INPUTCAPTURE_H //INPUT CAPTURE FOR TIMER SELECT BIT #define IC_TIMER2 1 #define IC_TIMER3 0 //SELECT NUMBER OF CAPTURE FOR INTERRUPT BIT #define IC_INT_1CAPTURE 0 #define IC_INT_2CAPTURE 1 #define IC_INT_3CAPTURE 2 #define IC_INT_4CAPTURE 3 //INPUT CAPTURE FOR MODE SELECT BIT #define IC_TURNED_OFF 0 #define IC_EVERY_RFEDGE 1 // every rising and falling edge #define IC_EVERY_FEDGE 2 // every falling edge #define IC_EVERY_REDGE 3 // every rising edge #define IC_EVERY_4EDGE 4 // every 4 rising edge #define IC_EVERY_16EDGE 5 // every 16 rising edge #define UNUSED 6 //INPUT CAPTURE FIRST USE extern uint8_t IC1_FIRST; extern uint8_t IC2_FIRST; //extern uint8_t IC7_FIRST; //PERIOD AND PULSE VARIABLE FOR INPUT CAPTURE extern int32_t IC1Period, IC2Period, IC7Period; extern int16_t IC1Pulse, IC2Pulse, IC7Pulse; //extern uint16_t IC1currentPeriod_temp, IC1previousPeriod_temp; //extern uint16_t IC2currentPeriod_temp, IC2previousPeriod_temp; //Functions with Global Scope void IC1_Init(void); void IC2_Init(void); //void IC7_Init(void); void __attribute__((interrupt,auto_psv)) _IC1Interrupt(void); void __attribute__((interrupt,auto_psv)) _IC2Interrupt(void); //void __attribute__((interrupt,auto_psv)) _IC7Interrupt(void); #endif
/* $Id$ * Author: Daniel Bosk <daniel.bosk@miun.se> * Date: 22 Dec 2012 */ /* * Copyright (c) 2012, Daniel Bosk <daniel.bosk@miun.se> * 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 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 <stdlib.h> #include <stdio.h> #include "free.h" #include "types.h" #include "swap.h" #include "sys.h" static page_t *queue = NULL; static size_t qsize = 0; static int qhead = 0; void remove_from_queue( int n ) { if ( n >= qsize ) return; int i = n; while ( i != qhead ) { queue[ i ] = queue[ i+1 ]; i = ( i + 1 ) % qsize; } } int memalg_esc( page_t p, pagetable_t pt ) { pentry_t *pe; int best_lvl = 5; int i, best_idx; /* do some setup the first time this function is run */ if ( queue == NULL ) { qsize = sz_memory; queue = calloc( qsize, sizeof(page_t) ); if ( queue == NULL ) return ERROR; qhead = 0; } /* if the page is valid, do nothing as no paging is required */ if ( pt[p].valid == 1 ) return OK; fprintf(stdout, "page %lli generated page fault\n", p); /* if we have free frames, use one of these */ if ( free_total() > 0 ) { pt[p].frame = free_getframe(); if ( pt[p].frame == FRAME_ERR ) return ERROR; fprintf(stdout, "allocated free frame %lli to page %lli\n", pt[p].frame, p); } /* otherwise swap out one page */ else { for ( i = 0; i < qsize; i++) { pe = pt + queue[qhead]; if ( pe->valid == 0 ) return ERROR; /* first class: not referenced, not modified */ else if ( !pe->referenced && !pe->modified && best_lvl > 1 ) { best_idx = qhead; best_lvl = 1; } /* second class: not referenced but modified */ else if ( !pe->referenced && pe->modified && best_lvl > 2 ) { best_idx = qhead; best_lvl = 2; } /* third class: referenced, but not modified */ else if ( pe->referenced && !pe->modified && best_lvl > 3 ) { best_idx = qhead; best_lvl = 3; } /* fourth class: referenced and modified */ else if ( pe->referenced && pe->modified && best_lvl > 4 ) { best_idx = qhead; best_lvl = 4; } pe->referenced = 0; qhead = ( qhead + 1 ) % qsize; } qhead = best_idx; pt[queue[qhead]].valid = 0; swap_out(queue[qhead]); /* allocate the newly freed frame */ pt[p].frame = pt[queue[qhead]].frame; } /* update the queue */ queue[qhead] = p; qhead = ( qhead + 1 ) % qsize; /* actually swap in the page */ swap_in(p); pt[p].valid = 1; pt[p].modified = 0; pt[p].referenced = 0; return OK; }
/*============================================================================ Copyright (c) German Cancer Research Center (DKFZ) 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. - All advertising materials mentioning features or use of this software must display the following acknowledgement: "This product includes software developed by the German Cancer Research Center (DKFZ)." - Neither the name of the German Cancer Research Center (DKFZ) 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 GERMAN CANCER RESEARCH CENTER (DKFZ) 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 GERMAN CANCER RESEARCH CENTER (DKFZ) 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. ============================================================================*/ /* * $RCSfile$ *-------------------------------------------------------------------- * DESCRIPTION * the old pic header * * $Log$ * Revision 1.5 2002/11/13 17:53:00 ivo * new ipPic added. * * Revision 1.3 2000/05/04 12:52:40 ivo * inserted BSD style license * * Revision 1.2 2000/05/04 12:36:01 ivo * some doxygen comments. * * Revision 1.1.1.1 1997/09/06 19:09:59 andre * initial import * * Revision 0.0 1993/03/26 12:56:26 andre * Initial revision * * *-------------------------------------------------------------------- * */ #ifndef _mitkIpPicOldP_h #define _mitkIpPicOldP_h typedef struct { mitkIpUInt4_t id, dummy1, dummy2, conv, rank, n1, n2, n3, n4, n5, n6, n7, n8, type, ntxt, ltxt; } _mitkIpPicOldHeader; #endif /* ifdef _mitkIpPicOldP_h */ /* DON'T ADD ANYTHING AFTER THIS #endif */
// 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 MEDIA_GPU_V4L2_V4L2_VP8_ACCELERATOR_H_ #define MEDIA_GPU_V4L2_V4L2_VP8_ACCELERATOR_H_ #include <vector> #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "media/gpu/vp8_decoder.h" namespace media { class V4L2Device; class V4L2DecodeSurface; class V4L2DecodeSurfaceHandler; class V4L2VP8Accelerator : public VP8Decoder::VP8Accelerator { public: explicit V4L2VP8Accelerator(V4L2DecodeSurfaceHandler* surface_handler, V4L2Device* device); ~V4L2VP8Accelerator() override; // VP8Decoder::VP8Accelerator implementation. scoped_refptr<VP8Picture> CreateVP8Picture() override; bool SubmitDecode(scoped_refptr<VP8Picture> pic, const Vp8ReferenceFrameVector& reference_frames) override; bool OutputPicture(scoped_refptr<VP8Picture> pic) override; private: scoped_refptr<V4L2DecodeSurface> VP8PictureToV4L2DecodeSurface( VP8Picture* pic); V4L2DecodeSurfaceHandler* const surface_handler_; V4L2Device* const device_; DISALLOW_COPY_AND_ASSIGN(V4L2VP8Accelerator); }; } // namespace media #endif // MEDIA_GPU_V4L2_V4L2_VP8_ACCELERATOR_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_SUBRESOURCE_FILTER_CONTENT_BROWSER_NAVIGATION_CONSOLE_LOGGER_H_ #define COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_NAVIGATION_CONSOLE_LOGGER_H_ #include <string> #include <utility> #include <vector> #include "content/public/browser/navigation_handle_user_data.h" #include "content/public/browser/web_contents_observer.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" namespace content { class NavigationHandle; } // namespace content namespace subresource_filter { // This class provides a static API to log console messages when an ongoing // navigation successfully commits. // - This class only supports main frame navigations. // - This class should be replaced with a class scoped to the NavigationHandle // if it ever starts supporting user data. class NavigationConsoleLogger : public content::WebContentsObserver, public content::NavigationHandleUserData<NavigationConsoleLogger> { public: // Creates a NavigationConsoleLogger object if it does not already exist for // |handle|. It will be scoped until the current main frame navigation commits // its next navigation. If |handle| has already committed, logs the message // immediately. static void LogMessageOnCommit(content::NavigationHandle* handle, blink::mojom::ConsoleMessageLevel level, const std::string& message); NavigationConsoleLogger(const NavigationConsoleLogger&) = delete; NavigationConsoleLogger& operator=(const NavigationConsoleLogger&) = delete; ~NavigationConsoleLogger() override; private: friend class content::NavigationHandleUserData<NavigationConsoleLogger>; explicit NavigationConsoleLogger(content::NavigationHandle& handle); // Creates a new NavigationConsoleLogger scoped to |handle| if one doesn't // exist. Returns the NavigationConsoleLogger associated with |handle|. // // Note: |handle| must be associated with a main frame navigation. static NavigationConsoleLogger* CreateIfNeededForNavigation( content::NavigationHandle* handle); // content::WebContentsObserver: void DidFinishNavigation(content::NavigationHandle* handle) override; using Message = std::pair<blink::mojom::ConsoleMessageLevel, std::string>; std::vector<Message> commit_messages_; // |handle_| must outlive this class. This is guaranteed because the object // tears itself down with |handle_|'s navigation finishes. const content::NavigationHandle* handle_; NAVIGATION_HANDLE_USER_DATA_KEY_DECL(); }; } // namespace subresource_filter #endif // COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_NAVIGATION_CONSOLE_LOGGER_H_
/*- * Copyright (c) 2013, 2014 Jason Lingle * 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 author 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 AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MICROMP_H_ #define MICROMP_H_ /** * @file * * This file defines the interface for "microMP" (ump), which we use as a * replacement for OpenMP. The interface obviously isn't as nice as OpenMP, but * there's a number of reasons not to use the latter: * * - This is more portable. We don't need a compiler that supports OMP. * * - We're not at the mercy of whatever OMP implementation hapens to live with * us; we can rely on particular performance characteristics. * * - Even good OMP implementations like GNU's are built more with throughput * than latency in mind. For example, on FreeBSD, delays of up to 250ms are * occasionally seen, which rather detracts from the graphical experience. * * - OMP isn't hugely efficient with micro-tasks we usually get when * parallelising graphics code with simple OMP directives; making larger * tasks would generally require surrounding too much code with parallel * sections, and peppering everything with master-only sections. */ /** * The size of the cache lines on the host system. It is important for * performance that this is not underestimated, as this may cause false sharing * between the workers. */ #define UMP_CACHE_LINE_SZ 64 /** * The maximum supported number of threads. */ #define UMP_MAX_THREADS 64 /** * Describes the parameters for executing uMP tasks. This struct may be * modified at run-time by uMP. */ typedef struct { /** * The function to execute on each worker. It is up to the calling code to * arrange some means of communicating parameters to the workers. * * @param ix The index of the division the function is to perform. * @param n The total number of divisions the into which the work is divided */ void (*exec)(unsigned ix, unsigned n); /** * The maximum number of divisions into which to split any given task. */ unsigned num_divisions; /** * For async tasks, indicates the number of divisions that are assigned to * the master thread, which it performs before the async call returns. The * initial value is a hint to the scheduler. The scheduler will adjust it at * run-time so as to minimise the time between the work actually being * completed and ump_join() being called. * * This value has no effect for sync calls. */ unsigned divisions_for_master; } ump_task; /** * Starts the given number of background worker threads and otherwise * initialises uMP. If anything goes wrong, the program exits. */ void ump_init(unsigned num_threads); /** * Executes the given task synchronously. The calling thread will perform a * share of work equal to the other workers. When this call returns, the task * is guaranteed to be entirely done. * * ump_join() is called implicitly at the start of this function. */ void ump_run_sync(ump_task*); /** * Executes the given task semi-asynchronously. The calling thread will usually * perform some work on the task itself before this call returns, though that * amount is always less than the other workers. * * ump_join() is called implicitly at the start of this function. */ void ump_run_async(ump_task*); /** * Blocks the calling thread until the current task, if any, has completed. */ void ump_join(void); /** * Checks whether the most recently assigned task is still in-progress. If it * is, returns 0. If it has completed, returns 1, and it is safe to call other * ump_ functions again. */ int ump_is_finished(void); /** * Returns the number of background worker threads are running in uMP. */ unsigned ump_num_workers(void); /** * Returns a pointer such that: * ret >= input * ret < input + UMP_CACHE_LINE_SZ * ret &~ (UMP_CACHE_LINE_SZ-1) == 0 * * ie, the input is advanced less than one cache line forward, as necessary to * ensure that it is aligned to the start of a cache line. */ void* align_to_cache_line(void* input); #endif /* MICROMP_H_ */
/* * Copyright (c) 1995 John Birrell <jb@cimlogic.com.au>. * Copyright (c) 1994 by Chris Provenzano, proven@mit.edu * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by John Birrell * and Chris Provenzano. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL 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. * * $FreeBSD$ */ #include <pthread.h> #include "libc_private.h" #include "thr_private.h" #undef errno extern int errno; int * __error(void) { struct pthread *curthread; if (_thr_initial != NULL) { curthread = _get_curthread(); if (curthread != NULL && curthread != _thr_initial) return (&curthread->error); } return (&errno); }
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_LOCK_ACTION_HANDLER_LAYOUT_MANAGER_H_ #define ASH_WM_LOCK_ACTION_HANDLER_LAYOUT_MANAGER_H_ #include "ash/ash_export.h" #include "ash/lock_screen_action/lock_screen_action_background_controller.h" #include "ash/lock_screen_action/lock_screen_action_background_observer.h" #include "ash/lock_screen_action/lock_screen_action_background_state.h" #include "ash/public/cpp/shelf_types.h" #include "ash/tray_action/tray_action.h" #include "ash/tray_action/tray_action_observer.h" #include "ash/wm/lock_layout_manager.h" #include "base/macros.h" #include "base/scoped_observation.h" namespace ash { class Shelf; // Window layout manager for windows intended to handle lock tray actions. // Since "new note" is currently the only supported action, the layout // manager uses new note tray action state to determine it state. // The layout is intended to be used for LockActionHandlerContainer. The // container state depends on the lock screen "new_note" action state: // * for active action state - the windows should be visible above the lock // screen // * for rest of the states - the windows should not be visible. // The layout manager will observe new note action state changes and update // the container's children state as needed. // The windows in this container will have be maximized, if possible. If they // are not resizable, they will be centered on the screen - similar to windows // in lock screen container. // Unlike lock layout manager, when maximizing windows, this layout manager will // ensure that the windows do not obscure the system shelf. class ASH_EXPORT LockActionHandlerLayoutManager : public LockLayoutManager, public TrayActionObserver, public LockScreenActionBackgroundObserver { public: LockActionHandlerLayoutManager( aura::Window* window, Shelf* shelf, LockScreenActionBackgroundController* action_background_controller); LockActionHandlerLayoutManager(const LockActionHandlerLayoutManager&) = delete; LockActionHandlerLayoutManager& operator=( const LockActionHandlerLayoutManager&) = delete; ~LockActionHandlerLayoutManager() override; // WmDefaultLayoutManager: void OnWindowAddedToLayout(aura::Window* child) override; void OnChildWindowVisibilityChanged(aura::Window* child, bool visibile) override; // TrayActionObserver: void OnLockScreenNoteStateChanged(mojom::TrayActionState state) override; // LockScreenActionBackgroundObserver: void OnLockScreenActionBackgroundStateChanged( LockScreenActionBackgroundState state) override; private: // Updates the child window visibility depending on lock screen note action // state and the lock screen action background state. void UpdateChildren(mojom::TrayActionState action_state, LockScreenActionBackgroundState background_state); LockScreenActionBackgroundController* action_background_controller_; base::ScopedObservation<TrayAction, TrayActionObserver> tray_action_observation_{this}; base::ScopedObservation<LockScreenActionBackgroundController, LockScreenActionBackgroundObserver> action_background_observation_{this}; }; } // namespace ash #endif // ASH_WM_LOCK_ACTION_HANDLER_LAYOUT_MANAGER_H_
/* * check_chitcpd.c * * Created on: Jan 11, 2014 * Author: borja */ #include <stdlib.h> #include <check.h> #include "chitcp/chitcpd.h" #include "serverinfo.h" #include "server.h" START_TEST (test_chitcpd_startstop) { int rc; serverinfo_t *si; si = calloc(1, sizeof(serverinfo_t)); si->server_port = chitcp_htons(23301); si->server_socket_path = DEFAULT_CHITCPD_SOCK; rc = chitcpd_server_init(si); ck_assert_msg(rc == 0, "Could not initialize chiTCP daemon."); rc = chitcpd_server_start(si); ck_assert_msg(rc == 0, "Could not start chiTCP daemon."); rc = chitcpd_server_stop(si); ck_assert_msg(rc == 0, "Could not stop chiTCP daemon."); rc = chitcpd_server_wait(si); ck_assert_msg(rc == 0, "Waiting for chiTCP daemon failed."); chitcpd_server_free(si); } END_TEST int main (void) { SRunner *sr; int number_failed; Suite *s; s = suite_create ("chiTCP daemon"); /* Core test case */ TCase *tc_startstop= tcase_create ("Start and stop"); tcase_add_test (tc_startstop, test_chitcpd_startstop); suite_add_tcase (s, tc_startstop); sr = srunner_create (s); srunner_run_all (sr, CK_NORMAL); number_failed = srunner_ntests_failed (sr); srunner_free (sr); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
#ifndef CMALLOC_CMALLOC_H #define CMALLOC_CMALLOC_H #include <unistd.h> void *cmalloc_aligned_alloc(size_t alignment, size_t size); void *cmalloc_calloc(size_t nmemb, size_t size); void cmalloc_free(void *ptr); void *cmalloc_malloc(size_t size); void *cmalloc_realloc(void *ptr, size_t size); void *cmalloc_memalign(size_t boundary, size_t size); int cmalloc_posix_memalign(void **memptr, size_t alignment, size_t size); void *cmalloc_valloc(size_t size); void *cmalloc_pvalloc(size_t size); /* * parameter_number: * - 0: to change the ratio of cold superblocks to liquid superblocks. 0: freeze most empty(cold) superblocks 100: dont freeze any empty(cold) superblocks less may save more memory * - 1: to change the ratio of frozen superblocks to liquid superblocks.\ 0: return most frozen superblosk to the global pool less may save more memory for more metadata reusing. */ int cmalloc_mallopt(int parameter_number, int parameter_value); void cmalloc_trace(void); #endif // end of CMALLOC_CMALLOC_H
/* ----------------------------------------------------------------- */ /* The Japanese TTS System "Open JTalk" */ /* developed by HTS Working Group */ /* http://open-jtalk.sourceforge.net/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 2008-2011 Nagoya Institute of Technology */ /* Department of Computer Science */ /* */ /* 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 HTS working 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 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 NJD2JPCOMMON_C #define NJD2JPCOMMON_C #ifdef __cplusplus #define NJD2JPCOMMON_C_START extern "C" { #define NJD2JPCOMMON_C_END } #else #define NJD2JPCOMMON_C_START #define NJD2JPCOMMON_C_END #endif /* __CPLUSPLUS */ NJD2JPCOMMON_C_START; #include <stdio.h> #include <stdlib.h> #include <string.h> #include "njd.h" #include "jpcommon.h" #if defined(CHARSET_EUC_JP) #include "njd2jpcommon_rule_euc_jp.h" #elif defined(CHARSET_SHIFT_JIS) #include "njd2jpcommon_rule_shift_jis.h" #elif defined(CHARSET_UTF_8) #include "njd2jpcommon_rule_utf_8.h" #else #error CHARSET is not specified #endif #define MAXBUFLEN 1024 static void convert_pos(char *buff, char *pos, char *pos_group1, char *pos_group2, char *pos_group3) { int i; for (i = 0; njd2jpcommon_pos_list[i] != NULL; i += 5) { if (strcmp(njd2jpcommon_pos_list[i], pos) == 0 && strcmp(njd2jpcommon_pos_list[i + 1], pos_group1) == 0 && strcmp(njd2jpcommon_pos_list[i + 2], pos_group2) == 0 && strcmp(njd2jpcommon_pos_list[i + 3], pos_group3) == 0) { strcpy(buff, njd2jpcommon_pos_list[i + 4]); return; } } fprintf(stderr, "WARING: convert_pos() in njd2jpcommon.c: %s %s %s %s are not appropriate POS.\n", pos, pos_group1, pos_group2, pos_group3); strcpy(buff, njd2jpcommon_pos_list[4]); } static void convert_ctype(char *buff, char *ctype) { int i; for (i = 0; njd2jpcommon_ctype_list[i] != NULL; i += 2) { if (strcmp(njd2jpcommon_ctype_list[i], ctype) == 0) { strcpy(buff, njd2jpcommon_ctype_list[i + 1]); return; } } fprintf(stderr, "WARING: convert_ctype() in njd2jpcommon.c: %s is not appropriate conjugation type.\n", ctype); strcpy(buff, njd2jpcommon_ctype_list[1]); } static void convert_cform(char *buff, char *cform) { int i; for (i = 0; njd2jpcommon_cform_list[i] != NULL; i += 2) { if (strcmp(njd2jpcommon_cform_list[i], cform) == 0) { strcpy(buff, njd2jpcommon_cform_list[i + 1]); return; } } fprintf(stderr, "WARING: convert_cform() in njd2jpcommon.c: %s is not appropriate conjugation form.\n", cform); strcpy(buff, njd2jpcommon_cform_list[1]); } void njd2jpcommon(JPCommon * jpcommon, NJD * njd) { char buff[MAXBUFLEN]; NJDNode *inode; JPCommonNode *jnode; for (inode = njd->head; inode != NULL; inode = inode->next) { jnode = (JPCommonNode *) calloc(1, sizeof(JPCommonNode)); JPCommonNode_initialize(jnode); JPCommonNode_set_pron(jnode, NJDNode_get_pron(inode)); convert_pos(buff, NJDNode_get_pos(inode), NJDNode_get_pos_group1(inode), NJDNode_get_pos_group2(inode), NJDNode_get_pos_group3(inode)); JPCommonNode_set_pos(jnode, buff); convert_ctype(buff, NJDNode_get_ctype(inode)); JPCommonNode_set_ctype(jnode, buff); convert_cform(buff, NJDNode_get_cform(inode)); JPCommonNode_set_cform(jnode, buff); JPCommonNode_set_acc(jnode, NJDNode_get_acc(inode)); JPCommonNode_set_chain_flag(jnode, NJDNode_get_chain_flag(inode)); JPCommon_push(jpcommon, jnode); } } NJD2JPCOMMON_C_END; #endif /* !NJD2JPCOMMON_C */
// // ActiveStarter.h // // $Id$ // // Library: Foundation // Package: Threading // Module: ActiveObjects // // Definition of the ActiveStarter class. // // Copyright (c) 2006-2007, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Foundation_ActiveStarter_INCLUDED #define Foundation_ActiveStarter_INCLUDED #include "Poco/Foundation.h" #include "Poco/ThreadPool.h" #include "Poco/ActiveRunnable.h" namespace Poco { template <class OwnerType> class ActiveStarter /// The default implementation of the StarterType /// policy for ActiveMethod. It starts the method /// in its own thread, obtained from the default /// thread pool. { public: static void start(OwnerType* pOwner, ActiveRunnableBase::Ptr pRunnable) { ThreadPool::defaultPool().start(*pRunnable); pRunnable->duplicate(); // The runnable will release itself. } }; } // namespace Poco #endif // Foundation_ActiveStarter_INCLUDED
#pragma once #include "chockNgt.h" #include "Audio.h" class Cafe { public: Cafe(); ~Cafe(); void ToBeginning(void); int Draw(float time); void UpdateTime(float time) { last_call_time_ = time; } void StartScene(int nothing) { nothing = nothing; has_white_fade_ = false; to_white_ = 1.0f; } void EndScene(void) { char error_string[MAX_ERROR_LENGTH+1]; audio_.StopSound(0, 36.0f, error_string); has_white_fade_ = true; } void StartVideo(void) { draw_video_ = true; video_start_time_ = last_call_time_; char error_string[MAX_ERROR_LENGTH+1]; audio_.PlaySound("Sawa_5.wav", 0, false, -1, error_string); subtitle_start_time_ = last_call_time_; subtitle_delay_ = 8.0f; subtitle_script_ = "Sawa_5.txt"; } void EndVideo(void) { draw_video_ = false; char error_string[MAX_ERROR_LENGTH+1]; audio_.StopSound(0, 36.0f, error_string); } private: // State machine (initialized incorrectly to test toBeginning() float last_call_time_ = 0.0f; float to_white_ = 3.0f; // fade to white bool draw_video_ = true; float video_start_time_ = 0.0f; bool has_white_fade_ = true; };
/** * 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. * * @generated by scripts/bump-oss-version.js */ #pragma once #include <cstdint> #include <string_view> namespace ABI42_0_0facebook::ABI42_0_0React { constexpr struct { int32_t Major = 0; int32_t Minor = 63; int32_t Patch = 2; std::string_view Prerelease = ""; } reactNativeVersion; } // namespace ABI42_0_0facebook::ABI42_0_0React
typedef unsigned char color; typedef struct { color Blue; color Green; color Red; } BGR; typedef struct { BGR content[16][16]; } color_block; typedef struct { short content[8][8]; } color_converted_block; color_block color_block_to_be_converted; /* RGB to YCbCr Conversion: */ // Y = 0.299*R + 0.587*G + 0.114*B color RGB2Y(const color r, const color g, const color b) { return (153 * r + 301 * g + 58 * b) >> 9; } // Cb = -0.1687*R - 0.3313*G + 0.5*B + 128 color RGB2Cb(const color r, const color g, const color b) { return (65536 - 86 * r - 170 * g + 256 * b) >> 9; } // Cr = 0.5*R - 0.4187*G - 0.0813*B + 128 color RGB2Cr(const color r, const color g, const color b) { return (65536 + 256 * r - 214 * g - 42 * b) >> 9; } // chroma subsampling, i.e. converting a 16x16 RGB block into 8x8 Cb and Cr void subsample(BGR rgb[16][16], short cb[8][8], short cr[8][8]) { unsigned r, c; for (r = 0; r < 8; r++) for (c = 0; c < 8; c++) { unsigned rr = (r << 1); unsigned cc = (c << 1); // calculating average values color R = (rgb[rr][cc].Red + rgb[rr][cc + 1].Red + rgb[rr + 1][cc].Red + rgb[rr + 1][cc + 1].Red) >> 2; color G = (rgb[rr][cc].Green + rgb[rr][cc + 1].Green + rgb[rr + 1][cc].Green + rgb[rr + 1][cc + 1].Green) >> 2; color B = (rgb[rr][cc].Blue + rgb[rr][cc + 1].Blue + rgb[rr + 1][cc].Blue + rgb[rr + 1][cc + 1].Blue) >> 2; cb[r][c] = (short) RGB2Cb(R, G, B) - 128; cr[r][c] = (short) RGB2Cr(R, G, B) - 128; } } void color_conversion(color_block current_color_block) { color_converted_block outgoing_blocks[2][2]; color_converted_block cb_block; color_converted_block cr_block; unsigned int i, j, r, c; // getting four 8x8 Y-blocks for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { for (r = 0; r < 8; r++) { for (c = 0; c < 8; c++) { const unsigned rr = (i << 3) + r; const unsigned cc = (j << 3) + c; const color R = current_color_block.content[rr][cc].Red; const color G = current_color_block.content[rr][cc].Green; const color B = current_color_block.content[rr][cc].Blue; // converting RGB into Y (luminance) outgoing_blocks[i][j].content[r][c] = RGB2Y(R, G, B) - 128; } } } } // one block of 8x8 Cr short Cb8x8[8][8]; // one block of 8x8 Cb short Cr8x8[8][8]; // create subsampled Cb and Cr blocks subsample(current_color_block.content, Cb8x8, Cr8x8); for (r = 0; r < 8; r++) { for (c = 0; c < 8; c++) { cb_block.content[r][c] = Cb8x8[r][c]; } } for (r = 0; r < 8; r++) { for (c = 0; c < 8; c++) { cr_block.content[r][c] = Cr8x8[r][c]; } } } int main() { color_conversion(color_block_to_be_converted); return 1; }
/* * Copyright (c) 2021, The OpenThread Authors. * 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. */ /** * @file * This file includes the platform-specific initializers. * */ #ifndef PLATFORM_EFR32_H_ #define PLATFORM_EFR32_H_ #include <openthread/instance.h> #include "em_device.h" #include "em_system.h" #include "rail.h" // Global OpenThread instance structure extern otInstance *sInstance; // Global reference to rail handle extern RAIL_Handle_t emPhyRailHandle; // coex needs the emPhyRailHandle symbol. #define gRailHandle emPhyRailHandle // use gRailHandle in the OpenThread PAL. /** * This function performs all platform-specific initialization of * OpenThread's drivers. * */ void sl_ot_sys_init(void); /** * This function initializes the alarm service used by OpenThread. * */ void efr32AlarmInit(void); /** * This function provides the remaining time (in milliseconds) on an alarm service. * */ uint32_t efr32AlarmPendingTime(void); /** * This function checks if the alarm service is running. * * @param[in] aInstance The OpenThread instance structure. * */ bool efr32AlarmIsRunning(otInstance *aInstance); /** * This function performs alarm driver processing. * * @param[in] aInstance The OpenThread instance structure. * */ void efr32AlarmProcess(otInstance *aInstance); /** * This function initializes the radio service used by OpenThead. * */ void efr32RadioInit(void); /** * This function deinitializes the radio service used by OpenThead. * */ void efr32RadioDeinit(void); /** * This function performs radio driver processing. * * @param[in] aInstance The OpenThread instance structure. * */ void efr32RadioProcess(otInstance *aInstance); /** * This function performs UART driver processing. * */ void efr32UartProcess(void); /** * This function performs CPC driver processing. * */ void efr32CpcProcess(void); /** * Initialization of Misc module. * */ void efr32MiscInit(void); /** * Initialization of Logger driver. * */ void efr32LogInit(void); /** * Deinitialization of Logger driver. * */ void efr32LogDeinit(void); /** * Registers the sleep callback handler. The callback is used to check that * the application has no work pending and that it is safe to put the EFR32 * into a low energy sleep mode. * * The callback should return true if it is ok to enter sleep mode. Note * that the callback itself is run with interrupts disabled and so should * be kept as short as possible. Anny interrupt including those from timers * will wake the EFR32 out of sleep mode. * * @param[in] aCallback Callback function. * */ void efr32SetSleepCallback(bool (*aCallback)(void)); /** * Put the EFR32 into a low power mode. Before sleeping it will call a callback * in the application registered with efr32SetSleepCallback to ensure that there * is no outstanding work in the application to do. */ void efr32Sleep(void); #endif // PLATFORM_EFR32_H_
/* Copyright (c) 2014, Sebastian Eriksson * 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 Sebastian Eriksson 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 SEBASTIAN ERIKSSON 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 MESH_IMPORTER_H #define MESH_IMPORTER_H #include "Mesh.h" #include <list> #include <string> namespace Raytracer2 { //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// class MeshImporter { public: enum ImporterFlags { FlatShading = 0x1, // Force face normals, even if vertex normals are available CalculateVertexNormals = 0x2, // (Re)calculates vertex normals Default = 0 }; MeshImporter() {} virtual bool accepts(const std::string & ext) const = 0; virtual MeshPtr loadFromFile(const std::string & filename, int flags) const = 0; static MeshPtr load(const std::string & filename, int flags = ImporterFlags::Default); }; typedef std::shared_ptr<MeshImporter> MeshImporterPtr; //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// class MeshImporterRegistry { public: static MeshImporterRegistry & instance(); void registerImporter(MeshImporterPtr importer); MeshImporterPtr find(const std::string & filename) const; private: MeshImporterRegistry(); MeshImporterRegistry(const MeshImporterRegistry &); void operator=(const MeshImporterRegistry &); std::list<MeshImporterPtr> m_importers; }; template <typename T> struct MeshImporterRegistrar { MeshImporterRegistrar() { MeshImporterRegistry::instance().registerImporter(std::make_shared<T>()); } ~MeshImporterRegistrar() { // TODO: unregister } }; #define REGISTER_IMPORTER(type) template class MeshImporterRegistrar<type>; \ MeshImporterRegistrar<type> Registered ## type; } #endif // MESH_IMPORTER_H
#ifndef DOUBANGO_CONFIG_H #define DOUBANGO_CONFIG_H #define DOUBANGO_IS_ALIGNED(p, a) (!((uintptr_t)(p) & ((a) - 1))) #define DOUBANGO_ASM_INLINE 1 #define DOUBANGO_INTRINSIC 1 #endif /* DOUBANGO_CONFIG_H */
/* * Module name : lcd.c: write to LCD display * Author : TI-Avans, JW * Revision History : 20110228: - initial release; * Description : This module contains functions for writing to lcd-display * Test configuration: MCU : ATmega128 Dev.Board : BIGAVR6 Oscillator : External Clock 8.0000 MHz Ext. Modules : - SW: AVR-GCC * NOTES : - */ #include "lcd_2.h" #include <avr/io.h> // lcd_command: schrijf command byte (RS=0) // eerst hoge nibble, dan de lage // void lcd_command ( unsigned char command ) { PORTC = command & 0xF0; // hoge nibble PORTC = PORTC | 0x08; // start (EN=1) _delay_ms(1); // wait 1 ms PORTC = 0x00; // stop _delay_ms(5); // wait 5 ms PORTC = (command & 0x0F) << 4; // lage nibble, shift lage naar hoge bits PORTC = PORTC | 0x08; // start (EN =1) _delay_ms(1); // wait 1 ms PORTC = 0x00; // stop (EN=0 RS=0) _delay_ms(5); // wait 5 ms } // Schrijf data byte (RS=1) // eerst hoge nibble, dan de lage // void lcd_writeChar( unsigned char dat ) { PORTC = dat & 0xF0; // hoge nibble PORTC = PORTC | 0x0C; // data (RS=1), start (EN =1) _delay_ms(1); // wait 1 ms PORTC = 0x04; // stop _delay_ms(5); // wait 5 ms PORTC = (dat & 0x0F) << 4; // lage nibble PORTC = PORTC | 0x0C; // data (RS=1), start (EN =1) _delay_ms(1); // pulse 1 ms PORTC = 0x00; // stop (EN=0 RS=0) _delay_ms(5); // wait 5 ms } // Initialisatie ldr // void lcd_init( void ) { DDRC=0xFC; // PORT C is output to LCD display lcd_command( 0x01 ); // clear display lcd_command( 0x02 ); // return home lcd_command( 0x28 ); // mode: 4 bits interface data, 2 lines,5x8 dots lcd_command( 0x0C ); // display: on, cursor off, blinking off lcd_command( 0x06 ); // entry mode: cursor to right, no shift lcd_command( 0x80 ); // RAM adress: 0, first position, line 1 _delay_ms(20); } // // write first line void lcd_writeLine1 ( char text1[] ) { lcd_command(0x01); // clear display lcd_command(0x80); // first pos line 1, adres $00 for ( int i=0; i<strlen(text1); i++ ) { lcd_writeChar( text1[i] ); } } // write first line void lcd_wrLine1AtPos ( char text1[], unsigned char pos) { lcd_command(0x80+pos); // first pos line 1, adres pos for ( int i=0; i<strlen(text1); i++ ) { lcd_writeChar( text1[i] ); } } // // write second line void lcd_writeLine2 ( char text2[] ) { lcd_command(0xC0); // first pos line 2, adres $40 for ( int i=0; i<strlen(text2); i++ ) { lcd_writeChar( text2[i] ); } } // write first line void lcd_wrLine2AtPos ( char text2[], unsigned char pos) { lcd_command(0xC0+pos); // first pos line 2, adres $40+pos for ( int i=0; i<strlen(text2); i++ ) { lcd_writeChar( text2[i] ); } } // shift text over 'displacement' positions // to the right (displacement>0) or to the left (displacement<0) void lcd_shift( int displacement ) { int number=displacement<0?-displacement:displacement; for (int i=0; i<number; i++) { if (displacement <0) lcd_command(0x18); else lcd_command(0x1C); } }
/* * altivec_typeconversion.h * DevIL * * Created by Meloni Dario on 24/04/05. * */ #include "altivec_common.h" #ifdef ALTIVEC_GCC // data and newdata may be the same buffer // Used to convert RGB <-> BGR in various data types void abc2cba_byte(ILubyte* data, ILuint length, ILubyte* newdata); void abc2cba_short(ILushort* data, ILuint length, ILushort* newdata); void abc2cba_int(ILuint* data, ILuint length, ILuint* newdata); #define abc2cba_float(x, y, z) abc2cba_int(((ILuint*)(x)), y, ((ILuint*)(z))) void abc2cba_double(ILdouble* data, ILuint length, ILdouble* newdata); // Used to convert RGBA <-> BGRA in various data types void abcd2cbad_byte(ILubyte* data, ILuint length, ILubyte* newdata); void abcd2cbad_short(ILushort* data, ILuint length, ILushort* newdata); void abcd2cbad_int(ILuint* data, ILuint length, ILuint* newdata); #define abcd2cbad_float(x, y, z) abcd2cbad_int(((ILuint*)(x)), y, ((ILuint*)(z))) void abcd2cbad_double(ILdouble* data, ILuint length, ILdouble* newdata); #endif
#pragma once #include "Classes/Modules/PackageModule/Private/PackageWidget.h" #include <TArc/DataProcessing/TArcDataNode.h> class PackageNode; class QAction; class PackageData : public DAVA::TArcDataNode { public: private: friend class PackageModule; QAction* importPackageAction = nullptr; QAction* copyAction = nullptr; QAction* pasteAction = nullptr; QAction* cutAction = nullptr; QAction* deleteAction = nullptr; QAction* duplicateAction = nullptr; QAction* moveUpAction = nullptr; QAction* moveDownAction = nullptr; QAction* moveLeftAction = nullptr; QAction* moveRightAction = nullptr; QAction* jumpToPrototypeAction = nullptr; QAction* findPrototypeInstancesAction = nullptr; PackageWidget* packageWidget = nullptr; DAVA::Map<PackageNode*, PackageContext> packageWidgetContexts; DAVA_VIRTUAL_REFLECTION(PackageData, DAVA::TArcDataNode); };
/* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * Copyright (C) 1997 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "adio.h" #include "adio_extern.h" #ifdef ROMIO_INSIDE_MPICH2 #include "mpiimpl.h" #endif void ADIO_End(int *error_code) { ADIOI_Flatlist_node *curr, *next; ADIOI_Datarep *datarep, *datarep_next; /* FPRINTF(stderr, "reached end\n"); */ /* if a default errhandler was set on MPI_FILE_NULL then we need to ensure * that our reference to that errhandler is released */ PMPI_File_set_errhandler(MPI_FILE_NULL, MPI_ERRORS_RETURN); /* delete the flattened datatype list */ curr = ADIOI_Flatlist; while (curr) { if (curr->blocklens) ADIOI_Free(curr->blocklens); if (curr->indices) ADIOI_Free(curr->indices); next = curr->next; ADIOI_Free(curr); curr = next; } ADIOI_Flatlist = NULL; /* free file and info tables used for Fortran interface */ if (ADIOI_Ftable) ADIOI_Free(ADIOI_Ftable); #ifndef HAVE_MPI_INFO if (MPIR_Infotable) ADIOI_Free(MPIR_Infotable); #endif /* free the memory allocated for a new data representation, if any */ datarep = ADIOI_Datarep_head; while (datarep) { datarep_next = datarep->next; #ifdef HAVE_MPIU_FUNCS MPIU_Free(datarep->name); #else ADIOI_Free(datarep->name); #endif ADIOI_Free(datarep); datarep = datarep_next; } if( ADIOI_syshints != MPI_INFO_NULL) MPI_Info_free(&ADIOI_syshints); MPI_Op_free(&ADIO_same_amode); *error_code = MPI_SUCCESS; } /* This is the delete callback function associated with ADIO_Init_keyval when MPI_COMM_SELF is freed */ int ADIOI_End_call(MPI_Comm comm, int keyval, void *attribute_val, void *extra_state) { int error_code; ADIOI_UNREFERENCED_ARG(comm); ADIOI_UNREFERENCED_ARG(attribute_val); ADIOI_UNREFERENCED_ARG(extra_state); MPI_Keyval_free(&keyval); /* The end call will be called after all possible uses of this keyval, even * if a file was opened with MPI_COMM_SELF. Note, this assumes LIFO * MPI_COMM_SELF attribute destruction behavior mandated by MPI-2.2. */ if (ADIOI_cb_config_list_keyval != MPI_KEYVAL_INVALID) MPI_Keyval_free(&ADIOI_cb_config_list_keyval); ADIO_End(&error_code); return error_code; }
#ifndef NVTRISTRIP_H #define NVTRISTRIP_H #ifndef NULL #define NULL 0 #endif namespace NvTriStrip { //////////////////////////////////////////////////////////////////////////////////////// // Public interface for stripifier //////////////////////////////////////////////////////////////////////////////////////// //GeForce1 and 2 cache size #define CACHESIZE_GEFORCE1_2 16 //GeForce3 cache size #define CACHESIZE_GEFORCE3 24 enum PrimType { PT_LIST, PT_STRIP, PT_FAN }; struct PrimitiveGroup { PrimType type; unsigned int numIndices; unsigned short* indices; //////////////////////////////////////////////////////////////////////////////////////// PrimitiveGroup() : type(PT_STRIP), numIndices(0), indices(NULL) {} ~PrimitiveGroup() { if(indices) delete [] indices; indices = NULL; } }; //////////////////////////////////////////////////////////////////////////////////////// // EnableRestart() // // For GPUs that support primitive restart, this sets a value as the restart index // // Restart is meaningless if strips are not being stitched together, so enabling restart // makes NvTriStrip forcing stitching. So, you'll get back one strip. // // Default value: disabled // void EnableRestart(const unsigned int restartVal); //////////////////////////////////////////////////////////////////////////////////////// // DisableRestart() // // For GPUs that support primitive restart, this disables using primitive restart // void DisableRestart(); //////////////////////////////////////////////////////////////////////////////////////// // SetCacheSize() // // Sets the cache size which the stripfier uses to optimize the data. // Controls the length of the generated individual strips. // This is the "actual" cache size, so 24 for GeForce3 and 16 for GeForce1/2 // You may want to play around with this number to tweak performance. // // Default value: 16 // void SetCacheSize(const unsigned int cacheSize); //////////////////////////////////////////////////////////////////////////////////////// // SetStitchStrips() // // bool to indicate whether to stitch together strips into one huge strip or not. // If set to true, you'll get back one huge strip stitched together using degenerate // triangles. // If set to false, you'll get back a large number of separate strips. // // Default value: true // void SetStitchStrips(const bool bStitchStrips); //////////////////////////////////////////////////////////////////////////////////////// // SetMinStripSize() // // Sets the minimum acceptable size for a strip, in triangles. // All strips generated which are shorter than this will be thrown into one big, separate list. // // Default value: 0 // void SetMinStripSize(const unsigned int minSize); //////////////////////////////////////////////////////////////////////////////////////// // SetListsOnly() // // If set to true, will return an optimized list, with no strips at all. // // Default value: false // void SetListsOnly(const bool bListsOnly); //////////////////////////////////////////////////////////////////////////////////////// // GenerateStrips() // // in_indices: input index list, the indices you would use to render // in_numIndices: number of entries in in_indices // primGroups: array of optimized/stripified PrimitiveGroups // numGroups: number of groups returned // // Be sure to call delete[] on the returned primGroups to avoid leaking mem // bool GenerateStrips(const unsigned short* in_indices, const unsigned int in_numIndices, PrimitiveGroup** primGroups, unsigned short* numGroups, bool validateEnabled = false); //////////////////////////////////////////////////////////////////////////////////////// // RemapIndices() // // Function to remap your indices to improve spatial locality in your vertex buffer. // // in_primGroups: array of PrimitiveGroups you want remapped // numGroups: number of entries in in_primGroups // numVerts: number of vertices in your vertex buffer, also can be thought of as the range // of acceptable values for indices in your primitive groups. // remappedGroups: array of remapped PrimitiveGroups // // Note that, according to the remapping handed back to you, you must reorder your // vertex buffer. // // Credit goes to the MS Xbox crew for the idea for this interface. // void RemapIndices(const PrimitiveGroup* in_primGroups, const unsigned short numGroups, const unsigned short numVerts, PrimitiveGroup** remappedGroups); } //End namespace #endif
/******************************************************************************** * * * F o u r - W a y S p l i t t e r * * * ********************************************************************************* * Copyright (C) 1999,2002 by Jeroen van der Zijp. All Rights Reserved. * ********************************************************************************* * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * ********************************************************************************* * $Id: FX4Splitter.h,v 1.21 2002/01/18 22:42:51 jeroen Exp $ * ********************************************************************************/ #ifndef FX4SPLITTER_H #define FX4SPLITTER_H #ifndef FXCOMPOSITE_H #include "FXComposite.h" #endif // Splitter options enum { FOURSPLITTER_TRACKING = 0x00008000, // Track continuously during split FOURSPLITTER_NORMAL = 0 }; /** * The four-way splitter is a layout manager which manages * four children like four panes in a window. * You can use a four-way splitter for example in a CAD program * where you may want to maintain three orthographic views, and * one oblique view of a model. * The four-way splitter allows interactive repartitioning of the * panes by means of moving the central splitter bars. * When the four-way splitter is itself resized, each child is * proportionally resized, maintaining the same split-percentage. * The four-way splitter widget sends a SEL_CHANGED to its target * during the resizing of the panes; at the end of the resize interaction, * it sends a SEL_COMMAND to signify that the resize operation is complete. */ class FXAPI FX4Splitter : public FXComposite { FXDECLARE(FX4Splitter) private: FXint splitx; // Current x split FXint splity; // Current y split FXint expanded; // Panes which are expanded FXint barsize; // Size of the splitter bar FXint fhor; // Horizontal split fraction FXint fver; // Vertical split fraction FXint offx; FXint offy; FXuchar mode; protected: FX4Splitter(); FXuchar getMode(FXint x,FXint y); void moveSplit(FXint x,FXint y); void drawSplit(FXint x,FXint y); void adjustLayout(); virtual void layout(); private: FX4Splitter(const FX4Splitter&); FX4Splitter &operator=(const FX4Splitter&); public: long onLeftBtnPress(FXObject*,FXSelector,void*); long onLeftBtnRelease(FXObject*,FXSelector,void*); long onMotion(FXObject*,FXSelector,void*); long onFocusUp(FXObject*,FXSelector,void*); long onFocusDown(FXObject*,FXSelector,void*); long onFocusLeft(FXObject*,FXSelector,void*); long onFocusRight(FXObject*,FXSelector,void*); long onCmdExpand(FXObject*,FXSelector,void*); long onUpdExpand(FXObject*,FXSelector,void*); public: enum { ID_EXPAND_ALL=FXComposite::ID_LAST, ID_EXPAND_TOPLEFT, ID_EXPAND_TOPRIGHT, ID_EXPAND_BOTTOMLEFT, ID_EXPAND_BOTTOMRIGHT, ID_LAST }; public: /// Create 4-way splitter, initially shown as four unexpanded panes FX4Splitter(FXComposite* p,FXuint opts=FOURSPLITTER_NORMAL,FXint x=0,FXint y=0,FXint w=0,FXint h=0); /// Create 4-way splitter, initially shown as four unexpanded panes; notifies target about size changes FX4Splitter(FXComposite* p,FXObject* tgt,FXSelector sel,FXuint opts=FOURSPLITTER_NORMAL,FXint x=0,FXint y=0,FXint w=0,FXint h=0); /// Get top left child, if any FXWindow *getTopLeft() const; /// Get top right child, if any FXWindow *getTopRight() const; /// Get bottom left child, if any FXWindow *getBottomLeft() const; /// Get bottom right child, if any FXWindow *getBottomRight() const; /// Get horizontal split fraction FXint getHSplit() const { return fhor; } /// Get vertical split fraction FXint getVSplit() const { return fver; } /// Change horizontal split fraction void setHSplit(FXint s); /// Change vertical split fraction void setVSplit(FXint s); /// Get default width virtual FXint getDefaultWidth(); /// Get default height virtual FXint getDefaultHeight(); /// Return current splitter style FXuint getSplitterStyle() const; /// Change splitter style void setSplitterStyle(FXuint style); /// Change splitter bar width void setBarSize(FXint bs); /// Get splitter bar width FXint getBarSize() const { return barsize; } /// Expand child (ex=0..3), or restore to 4-way split (ex=-1) void setExpanded(FXint ex); /// Get expanded child, or -1 if not expanded FXint getExpanded() const { return expanded; } /// Save to stream virtual void save(FXStream& store) const; /// Load from stream virtual void load(FXStream& store); }; #endif
/* * Copyright (c) 1994, 1995. Netscape Communications Corporation. All * rights reserved. * * Use of this software is governed by the terms of the license agreement for * the Netscape Communications or Netscape Comemrce Server between the * parties. */ /* ------------------------------------------------------------------------ */ /* * ereport.h: Records transactions, reports errors to administrators, etc. * * Rob McCool */ #ifndef EREPORT_H #define EREPORT_H #include "../base/session.h" /* Session structure */ #ifdef XP_UNIX #include <pwd.h> /* struct passwd */ #endif /* XP_UNIX */ /* ------------------------------ Constants ------------------------------- */ /* * The maximum length of an error message. NOT RUN-TIME CHECKED */ #define MAX_ERROR_LEN 8192 /* A warning is a minor mishap, such as a 404 being issued. */ #define LOG_WARN 0 /* * A misconfig is when there is a syntax error or permission violation in * a config. file. */ #define LOG_MISCONFIG 1 /* * Security warnings are issued when authentication fails, or a host is * given a 403 return code. */ #define LOG_SECURITY 2 /* * A failure is when a request could not be fulfilled due to an internal * problem, such as a CGI script exiting prematurely, or a filesystem * permissions problem. */ #define LOG_FAILURE 3 /* * A catastrophe is a fatal server error such as running out of * memory or processes, or a system call failing, or even a server crash. * The server child cannot recover from a catastrophe. */ #define LOG_CATASTROPHE 4 /* * Informational message, of no concern. */ #define LOG_INFORM 5 /* * The time format to use in the error log */ #define ERR_TIMEFMT "[%d/%b/%Y:%H:%M:%S]" /* The fd you will get if you are reporting errors to SYSLOG */ #define ERRORS_TO_SYSLOG -1 /* ------------------------------ Prototypes ------------------------------ */ /* * ereport logs an error of the given degree and formats the arguments with * the printf() style fmt. Returns whether the log was successful. Records * the current date. */ int ereport(int degree, char *fmt, ...); /* * ereport_init initializes the error logging subsystem and opens the static * file descriptors. It returns NULL upon success and an error string upon * error. If a userpw is given, the logs will be chowned to that user. * * email is the address of a person to mail upon catastrophic error. It * can be NULL if no e-mail is desired. ereport_init will not duplicate * its own copy of this string; you must make sure it stays around and free * it when you shut down the server. */ char *ereport_init(char *err_fn, char *email, struct passwd *pw); /* * log_terminate closes the error and common log file descriptors. */ void ereport_terminate(void); /* For restarts */ SYS_FILE ereport_getfd(void); #endif
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010 Alessandro Tasora // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // #ifndef CHCHRONO_H #define CHCHRONO_H ////////////////////////////////////////////////// // // ChChrono.h // // Generic header for Chrono API/SDK, // // HEADER file for CHRONO, // Multibody dynamics engine // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// // // Following is documentation for 1st page of SDK help, aimed at the Doxygen // tool which builds the html/pdf/help by automatically scanning these // headers. // /*! \mainpage Chrono Engine API/SDK documentation * * <div align="center"><img src="logo_chronoengine_middle.png" ></div> * * \section intro Introduction * * Welcome to the Chrono::Engine API/SDK documentation. * Here you'll find any information you'll need to develop applications with * the Chrono Engine. * * The Chrono::Engine is a C++ library of tools for physics simulation (multibody * dynamics, kinematics, etc.). This documentation is an important part of it. * If you have any questions or suggestions, just send a email to the author * of the engine, Alessandro Tasora (tasora (at) deltaknowledge.com). * * * \section links Links * * <A HREF="namespaces.html">Namespaces</A>: An interesting place to start reading * the documentation.<BR> * <A HREF="annotated.html">Class list</A>: List of all classes with descriptions.<BR> * <A HREF="functions.html">Class members</A>: Nice place to find forgotten features.<BR> * * Everything in the engine is * placed into the namespace 'chrono'. All Chrono classes and functions should be * accessed with th e:: syntax, as: chrono::[class or functions here] . Of course, in * sake of a more compact syntax, you could avoid all the chrono::... typing by adding at the * beginning of your source code the following statement: * * \code * using namespace chrono; * \endcode * * There are also other namespaces. * You can find a list of all namespaces with descriptions at the * <A HREF="namespaces.html"> namespaces page</A>. * This is also a good place to start reading the documentation. * If you don't want to write the namespace names all the time, just use all namespaces, * like in this example: * \code * using namespace collision; * using namespace pneumatics; * using namespace geometry; * \endcode * * There is a lot more the engine can do, but we hope this gave a short * overview over the basic features of the engine. For some examples, please take * a look into the 'demos' directory of the SDK, and read the tutorials. */ namespace chrono { } // END_OF_NAMESPACE____ #endif // END of header
#ifndef _CURSES_H #define _CURSES_H #include <ansi.h> /* Lots of junk here, not packaged right. */ extern char termcap[]; extern char tc[]; extern char *ttytype; extern char *arp; extern char *cp; extern char *cl; extern char *cm; extern char *so; extern char *se; extern char /* nscrn[ROWS][COLS], cscrn[ROWS][COLS], */ row, col, mode; extern char str[]; _PROTOTYPE( void addstr, (char *_s) ); _PROTOTYPE( void clear, (void) ); _PROTOTYPE( void clrtobot, (void) ); _PROTOTYPE( void clrtoeol, (void) ); _PROTOTYPE( void endwin, (void) ); _PROTOTYPE( void fatal, (char *_s) ); _PROTOTYPE( char inch, (void) ); _PROTOTYPE( void initscr, (void) ); _PROTOTYPE( void move, (int _y, int _x) ); /* WRONG, next is varargs. */ _PROTOTYPE( void printw, (char *_fmt, char *_a1, char *_a2, char *_a3, char *_a4, char *_a5) ); _PROTOTYPE( void outc, (int _c) ); _PROTOTYPE( void refresh, (void) ); _PROTOTYPE( void standend, (void) ); _PROTOTYPE( void standout, (void) ); _PROTOTYPE( void touchwin, (void) ); #endif /* _CURSES_H */
/* * Copyright © 2009 CNRS * Copyright © 2009-2010 INRIA. All rights reserved. * Copyright © 2009-2011 Université Bordeaux 1 * Copyright © 2011 Cisco Systems, Inc. All rights reserved. * See COPYING in top-level directory. */ /** \file * \brief Macros to help interaction between hwloc and glibc scheduling routines. * * Applications that use both hwloc and glibc scheduling routines such as * sched_getaffinity may want to include this file so as to ease conversion * between their respective types. */ #ifndef HWLOC_GLIBC_SCHED_H #define HWLOC_GLIBC_SCHED_H #include <hwloc.h> #include <hwloc/helper.h> #include <assert.h> #if !defined _GNU_SOURCE || !defined _SCHED_H || !defined CPU_SETSIZE #error Please make sure to include sched.h before including glibc-sched.h, and define _GNU_SOURCE before any inclusion of sched.h #endif #ifdef __cplusplus extern "C" { #endif #ifdef HWLOC_HAVE_CPU_SET /** \defgroup hwlocality_glibc_sched Helpers for manipulating glibc sched affinity * @{ */ /** \brief Convert hwloc CPU set \p toposet into glibc sched affinity CPU set \p schedset * * This function may be used before calling sched_setaffinity or any other function * that takes a cpu_set_t as input parameter. * * \p schedsetsize should be sizeof(cpu_set_t) unless \p schedset was dynamically allocated with CPU_ALLOC */ static __hwloc_inline int hwloc_cpuset_to_glibc_sched_affinity(hwloc_topology_t topology __hwloc_attribute_unused, hwloc_const_cpuset_t hwlocset, cpu_set_t *schedset, size_t schedsetsize) { #ifdef CPU_ZERO_S unsigned cpu; CPU_ZERO_S(schedsetsize, schedset); hwloc_bitmap_foreach_begin(cpu, hwlocset) CPU_SET_S(cpu, schedsetsize, schedset); hwloc_bitmap_foreach_end(); #else /* !CPU_ZERO_S */ unsigned cpu; CPU_ZERO(schedset); assert(schedsetsize == sizeof(cpu_set_t)); hwloc_bitmap_foreach_begin(cpu, hwlocset) CPU_SET(cpu, schedset); hwloc_bitmap_foreach_end(); #endif /* !CPU_ZERO_S */ return 0; } /** \brief Convert glibc sched affinity CPU set \p schedset into hwloc CPU set * * This function may be used before calling sched_setaffinity or any other function * that takes a cpu_set_t as input parameter. * * \p schedsetsize should be sizeof(cpu_set_t) unless \p schedset was dynamically allocated with CPU_ALLOC */ static __hwloc_inline int hwloc_cpuset_from_glibc_sched_affinity(hwloc_topology_t topology __hwloc_attribute_unused, hwloc_cpuset_t hwlocset, const cpu_set_t *schedset, size_t schedsetsize) { #ifdef CPU_ZERO_S int cpu, count; #endif hwloc_bitmap_zero(hwlocset); #ifdef CPU_ZERO_S count = CPU_COUNT_S(schedsetsize, schedset); cpu = 0; while (count) { if (CPU_ISSET_S(cpu, schedsetsize, schedset)) { hwloc_bitmap_set(hwlocset, cpu); count--; } cpu++; } #else /* !CPU_ZERO_S */ /* sched.h does not support dynamic cpu_set_t (introduced in glibc 2.7), * assume we have a very old interface without CPU_COUNT (added in 2.6) */ int cpu; assert(schedsetsize == sizeof(cpu_set_t)); for(cpu=0; cpu<CPU_SETSIZE; cpu++) if (CPU_ISSET(cpu, schedset)) hwloc_bitmap_set(hwlocset, cpu); #endif /* !CPU_ZERO_S */ return 0; } /** @} */ #endif /* CPU_SET */ #ifdef __cplusplus } /* extern "C" */ #endif #endif /* HWLOC_GLIBC_SCHED_H */
// Copyright (c) 2011 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LOGIN_MANAGER_MOCK_POLICY_STORE_H_ #define LOGIN_MANAGER_MOCK_POLICY_STORE_H_ #include "login_manager/policy_store.h" namespace login_manager{ class MockPolicyStore : public PolicyStore { public: MockPolicyStore(); virtual ~MockPolicyStore(); MOCK_METHOD0(DefunctPrefsFilePresent, bool(void)); MOCK_METHOD0(LoadOrCreate, bool(void)); MOCK_CONST_METHOD0(Get, const enterprise_management::PolicyFetchResponse&(void)); MOCK_METHOD0(Persist, bool(void)); MOCK_METHOD1(Set, void(const enterprise_management::PolicyFetchResponse&)); }; } // namespace login_manager #endif // LOGIN_MANAGER_MOCK_POLICY_STORE_H_
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include "svm.h" char* line; int max_line_len = 1024; struct svm_node *x; int max_nr_attr = 64; struct svm_model* model; int predict_probability=0; void predict(FILE *input, FILE *output) { int correct = 0; int total = 0; double error = 0; double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0; int svm_type=svm_get_svm_type(model); int nr_class=svm_get_nr_class(model); int *labels=(int *) malloc(nr_class*sizeof(int)); double *prob_estimates=NULL; int j; if(predict_probability) { if (svm_type==NU_SVR || svm_type==EPSILON_SVR) printf("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\n",svm_get_svr_probability(model)); else { svm_get_labels(model,labels); prob_estimates = (double *) malloc(nr_class*sizeof(double)); fprintf(output,"labels"); for(j=0;j<nr_class;j++) fprintf(output," %d",labels[j]); fprintf(output,"\n"); } } while(1) { int i = 0; int c; double target,v; if (fscanf(input,"%lf",&target)==EOF) break; while(1) { if(i>=max_nr_attr-1) // need one more for index = -1 { max_nr_attr *= 2; x = (struct svm_node *) realloc(x,max_nr_attr*sizeof(struct svm_node)); } do { c = getc(input); if(c=='\n' || c==EOF) goto out2; } while(isspace(c)); ungetc(c,input); if (fscanf(input,"%d:%lf",&x[i].index,&x[i].value) < 2) { fprintf(stderr,"Wrong input format at line %d\n", total+1); exit(1); } ++i; } out2: x[i++].index = -1; if (predict_probability && (svm_type==C_SVC || svm_type==NU_SVC)) { v = svm_predict_probability(model,x,prob_estimates); fprintf(output,"%g ",v); for(j=0;j<nr_class;j++) fprintf(output,"%g ",prob_estimates[j]); fprintf(output,"\n"); } else { v = svm_predict(model,x); fprintf(output,"%g\n",v); } if(v == target) ++correct; error += (v-target)*(v-target); sumv += v; sumy += target; sumvv += v*v; sumyy += target*target; sumvy += v*target; ++total; } if (svm_type==NU_SVR || svm_type==EPSILON_SVR) { printf("Mean squared error = %g (regression)\n",error/total); printf("Squared correlation coefficient = %g (regression)\n", ((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/ ((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy)) ); } else printf("Accuracy = %g%% (%d/%d) (classification)\n", (double)correct/total*100,correct,total); if(predict_probability) { free(prob_estimates); free(labels); } } void exit_with_help() { printf( "Usage: svm-predict [options] test_file model_file output_file\n" "options:\n" "-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); for one-class SVM only 0 is supported\n" ); exit(1); } int main(int argc, char **argv) { FILE *input, *output; int i; // parse options for(i=1;i<argc;i++) { if(argv[i][0] != '-') break; ++i; switch(argv[i-1][1]) { case 'b': predict_probability = atoi(argv[i]); break; default: fprintf(stderr,"unknown option\n"); exit_with_help(); } } if(i>=argc) exit_with_help(); input = fopen(argv[i],"r"); if(input == NULL) { fprintf(stderr,"can't open input file %s\n",argv[i]); exit(1); } output = fopen(argv[i+2],"w"); if(output == NULL) { fprintf(stderr,"can't open output file %s\n",argv[i+2]); exit(1); } if((model=svm_load_model(argv[i+1]))==0) { fprintf(stderr,"can't open model file %s\n",argv[i+1]); exit(1); } line = (char *) malloc(max_line_len*sizeof(char)); x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node)); if(predict_probability) if(svm_check_probability_model(model)==0) { fprintf(stderr,"Model does not support probabiliy estimates\n"); exit(1); } predict(input,output); svm_destroy_model(model); free(line); free(x); fclose(input); fclose(output); return 0; }
#include <ruby.h> VALUE sm_define_const(VALUE self, VALUE klass, VALUE val) { rb_define_const(klass, "FOO", val); return Qnil; } VALUE sm_const_defined(VALUE self, VALUE klass, VALUE id) { return (VALUE)rb_const_defined(klass, SYM2ID(id)); } void Init_subtend_module() { VALUE cls; cls = rb_define_class("SubtendModule", rb_cObject); rb_define_method(cls, "rb_define_const", sm_define_const, 2); rb_define_method(cls, "rb_const_defined", sm_const_defined, 2); }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_EVENT_ROUTER_FACTORY_H_ #define CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_EVENT_ROUTER_FACTORY_H_ #include "base/macros.h" #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" namespace extensions { class SettingsPrivateEventRouter; // This is a factory class used by the BrowserContextDependencyManager // to instantiate the settingsPrivate event router per profile (since the // extension event router is per profile). class SettingsPrivateEventRouterFactory : public BrowserContextKeyedServiceFactory { public: SettingsPrivateEventRouterFactory(const SettingsPrivateEventRouterFactory&) = delete; SettingsPrivateEventRouterFactory& operator=( const SettingsPrivateEventRouterFactory&) = delete; // Returns the SettingsPrivateEventRouter for |profile|, creating it if // it is not yet created. static SettingsPrivateEventRouter* GetForProfile( content::BrowserContext* context); // Returns the SettingsPrivateEventRouterFactory instance. static SettingsPrivateEventRouterFactory* GetInstance(); protected: // BrowserContextKeyedServiceFactory overrides: content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; bool ServiceIsCreatedWithBrowserContext() const override; bool ServiceIsNULLWhileTesting() const override; private: friend struct base::DefaultSingletonTraits<SettingsPrivateEventRouterFactory>; SettingsPrivateEventRouterFactory(); ~SettingsPrivateEventRouterFactory() override; // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_EVENT_ROUTER_FACTORY_H_
/* BLIS An object-based framework for developing high-performance BLAS-like libraries. Copyright (C) 2014, The University of Texas at Austin 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 Texas at Austin 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 "blis.h" void bli_trmm_blk_var1f( obj_t* a, obj_t* b, obj_t* c, gemm_t* cntl, trmm_thrinfo_t* thread ) { obj_t b_pack_s; obj_t a1_pack_s, c1_pack_s; obj_t a1, c1; obj_t* a1_pack = NULL; obj_t* b_pack = NULL; obj_t* c1_pack = NULL; dim_t i; dim_t b_alg; dim_t m_trans; dim_t offA; if( thread_am_ochief( thread ) ) { // Initialize object for packing B. bli_obj_init_pack( &b_pack_s ); bli_packm_init( b, &b_pack_s, cntl_sub_packm_b( cntl ) ); // Scale C by beta (if instructed). // Since scalm doesn't support multithreading yet, must be done by chief thread (ew) bli_scalm_int( &BLIS_ONE, c, cntl_sub_scalm( cntl ) ); } b_pack = thread_obroadcast( thread, &b_pack_s ); // Initialize all pack objects that are passed into packm_init(). if( thread_am_ichief( thread ) ) { bli_obj_init_pack( &a1_pack_s ); bli_obj_init_pack( &c1_pack_s ); } a1_pack = thread_ibroadcast( thread, &a1_pack_s ); c1_pack = thread_ibroadcast( thread, &c1_pack_s ); // Pack B (if instructed). bli_packm_int( b, b_pack, cntl_sub_packm_b( cntl ), trmm_thread_sub_opackm( thread ) ); // Set the default length of and offset to the non-zero part of A. m_trans = bli_obj_length_after_trans( *a ); offA = 0; // If A is lower triangular, we have to adjust where the non-zero part of // A begins. If A is upper triangular, we have to adjust the length of // the non-zero part. If A is general/dense, then we keep the defaults. if ( bli_obj_is_lower( *a ) ) offA = bli_abs( bli_obj_diag_offset_after_trans( *a ) ); else if ( bli_obj_is_upper( *a ) ) m_trans = bli_abs( bli_obj_diag_offset_after_trans( *a ) ) + bli_obj_width_after_trans( *a ); dim_t start, end; bli_get_range_weighted( thread, offA, m_trans, bli_blksz_get_mult_for_obj( a, cntl_blocksize( cntl ) ), bli_obj_is_upper( *c ), &start, &end ); // Partition along the m dimension. for ( i = start; i < end; i += b_alg ) { // Determine the current algorithmic blocksize. b_alg = bli_determine_blocksize_f( i, end, a, cntl_blocksize( cntl ) ); // Acquire partitions for A1 and C1. bli_acquire_mpart_t2b( BLIS_SUBPART1, i, b_alg, a, &a1 ); bli_acquire_mpart_t2b( BLIS_SUBPART1, i, b_alg, c, &c1 ); // Initialize objects for packing A1 and C1. if( thread_am_ichief( thread ) ) { bli_packm_init( &a1, a1_pack, cntl_sub_packm_a( cntl ) ); bli_packm_init( &c1, c1_pack, cntl_sub_packm_c( cntl ) ); } thread_ibarrier( thread ); // Pack A1 (if instructed). bli_packm_int( &a1, a1_pack, cntl_sub_packm_a( cntl ), trmm_thread_sub_ipackm( thread ) ); // Pack C1 (if instructed). bli_packm_int( &c1, c1_pack, cntl_sub_packm_c( cntl ), trmm_thread_sub_ipackm( thread ) ); // Perform trmm subproblem. bli_trmm_int( &BLIS_ONE, a1_pack, b_pack, &BLIS_ONE, c1_pack, cntl_sub_gemm( cntl ), trmm_thread_sub_trmm( thread ) ); thread_ibarrier( thread ); // Unpack C1 (if C1 was packed). bli_unpackm_int( c1_pack, &c1, cntl_sub_unpackm_c( cntl ), trmm_thread_sub_ipackm( thread ) ); } // If any packing buffers were acquired within packm, release them back // to the memory manager. thread_obarrier( thread ); if( thread_am_ochief( thread ) ) bli_packm_release( b_pack, cntl_sub_packm_b( cntl ) ); if( thread_am_ichief( thread ) ){ bli_packm_release( a1_pack, cntl_sub_packm_a( cntl ) ); bli_packm_release( c1_pack, cntl_sub_packm_c( cntl ) ); } }
/* simq.c * * Solution of simultaneous linear equations AX = B * by Gaussian elimination with partial pivoting * * * * SYNOPSIS: * * double A[n*n], B[n], X[n]; * int n, flag; * int IPS[]; * int simq(); * * ercode = simq( A, B, X, n, flag, IPS ); * * * * DESCRIPTION: * * B, X, IPS are vectors of length n. * A is an n x n matrix (i.e., a vector of length n*n), * stored row-wise: that is, A(i,j) = A[ij], * where ij = i*n + j, which is the transpose of the normal * column-wise storage. * * The contents of matrix A are destroyed. * * Set flag=0 to solve. * Set flag=-1 to do a new back substitution for different B vector * using the same A matrix previously reduced when flag=0. * * The routine returns nonzero on error; messages are printed. * * * ACCURACY: * * Depends on the conditioning (range of eigenvalues) of matrix A. * * * REFERENCE: * * Computer Solution of Linear Algebraic Systems, * by George E. Forsythe and Cleve B. Moler; Prentice-Hall, 1967. * */ /* simq 2 */ #include <stdio.h> #define ANSIPROT #ifdef ANSIPROT int simq(double [], double [], double [], int, int, int [] ); #endif #define fabs(x) ((x) < 0 ? -(x) : (x)) int simq( A, B, X, n, flag, IPS ) double A[], B[], X[]; int n, flag; int IPS[]; { int i, j, ij, ip, ipj, ipk, ipn; int idxpiv, iback; int k, kp, kp1, kpk, kpn; int nip, nkp, nm1; double em, q, rownrm, big, size, pivot, sum; nm1 = n-1; if( flag < 0 ) goto solve; /* Initialize IPS and X */ ij=0; for( i=0; i<n; i++ ) { IPS[i] = i; rownrm = 0.0; for( j=0; j<n; j++ ) { q = fabs( A[ij] ); if( rownrm < q ) rownrm = q; ++ij; } if( rownrm == 0.0 ) { puts("SIMQ ROWNRM=0"); return(1); } X[i] = 1.0/rownrm; } /* simq 3 */ /* Gaussian elimination with partial pivoting */ for( k=0; k<nm1; k++ ) { big= 0.0; idxpiv = 0; for( i=k; i<n; i++ ) { ip = IPS[i]; ipk = n*ip + k; size = fabs( A[ipk] ) * X[ip]; if( size > big ) { big = size; idxpiv = i; } } if( big == 0.0 ) { puts( "SIMQ BIG=0" ); return(2); } if( idxpiv != k ) { j = IPS[k]; IPS[k] = IPS[idxpiv]; IPS[idxpiv] = j; } kp = IPS[k]; kpk = n*kp + k; pivot = A[kpk]; kp1 = k+1; for( i=kp1; i<n; i++ ) { ip = IPS[i]; ipk = n*ip + k; em = -A[ipk]/pivot; A[ipk] = -em; nip = n*ip; nkp = n*kp; for( j=kp1; j<n; j++ ) { ipj = nip + j; A[ipj] = A[ipj] + em * A[nkp + j]; } } } kpn = n * IPS[n-1] + n - 1; /* last element of IPS[n] th row */ if( A[kpn] == 0.0 ) { puts( "SIMQ A[kpn]=0"); return(3); } /* simq 4 */ /* back substitution */ solve: ip = IPS[0]; X[0] = B[ip]; for( i=1; i<n; i++ ) { ip = IPS[i]; ipj = n * ip; sum = 0.0; for( j=0; j<i; j++ ) { sum += A[ipj] * X[j]; ++ipj; } X[i] = B[ip] - sum; } ipn = n * IPS[n-1] + n - 1; X[n-1] = X[n-1]/A[ipn]; for( iback=1; iback<n; iback++ ) { /* i goes (n-1),...,1 */ i = nm1 - iback; ip = IPS[i]; nip = n*ip; sum = 0.0; for( j=i+1; j<n; j++ ) sum += A[nip+j] * X[j]; X[i] = (X[i] - sum)/A[nip+i]; } return(0); }
/* base64.h -- routines for converting to base64 * * This code is Copyright (c) 2017, by the authors of nmh. See the * COPYRIGHT file in the root directory of the nmh distribution for * complete copyright information. */ int writeBase64aux(FILE *, FILE *, int); int writeBase64(const unsigned char *, size_t, unsigned char *); int writeBase64raw(const unsigned char *, size_t, unsigned char *); int decodeBase64(const char *, unsigned char **, size_t *, int); void hexify(const unsigned char *, size_t, char **); /* Includes trailing NUL. */ #define BASE64SIZE(x) ((((x + 2) / 3) * 4) + 1)
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef FWL_TARGETIMP_H_ #define FWL_TARGETIMP_H_ #include "core/include/fxcrt/fx_basic.h" #include "xfa/include/fwl/core/fwl_target.h" class CFWL_TargetImp { public: virtual ~CFWL_TargetImp(); virtual FWL_ERR GetClassName(CFX_WideString& wsClass) const; virtual FX_DWORD GetClassID() const; virtual FX_BOOL IsInstance(const CFX_WideStringC& wsClass) const; virtual FWL_ERR Initialize(); virtual FWL_ERR Finalize(); protected: CFWL_TargetImp(); }; #endif // FWL_TARGETIMP_H_
/*! * Copyright (c) 2016 by Contributors * \file input_split_shuffle.h * \brief base class to construct input split with global shuffling * \author Yifeng Geng */ // dmlc-core/include/dmlc/input_split_shuffle.h #ifndef BUBBLEFS_UTILS_DMLC_INPUT_SPLIT_SHUFFLE_H_ #define BUBBLEFS_UTILS_DMLC_INPUT_SPLIT_SHUFFLE_H_ #include <cstdio> #include <cstring> #include <memory> #include <vector> #include <string> #include <algorithm> #include "utils/dmlc_io.h" namespace bubblefs { namespace mydmlc { /*! \brief class to construct input split with global shuffling */ class InputSplitShuffle : public InputSplit { public: // destructor virtual ~InputSplitShuffle(void) { source_.reset(); } // implement BeforeFirst virtual void BeforeFirst(void) { if (num_shuffle_parts_ > 1) { std::shuffle(shuffle_indexes_.begin(), shuffle_indexes_.end(), trnd_); int idx = shuffle_indexes_[0] + part_index_ * num_shuffle_parts_; source_->ResetPartition(idx, num_parts_ * num_shuffle_parts_); cur_shuffle_idx_ = 0; } else { source_->BeforeFirst(); } } virtual void HintChunkSize(size_t chunk_size) { source_->HintChunkSize(chunk_size); } virtual size_t GetTotalSize(void) { return source_->GetTotalSize(); } // implement next record virtual bool NextRecord(Blob *out_rec) { if (num_shuffle_parts_ > 1) { if (!source_->NextRecord(out_rec)) { if (cur_shuffle_idx_ == num_shuffle_parts_ - 1) { return false; } ++cur_shuffle_idx_; int idx = shuffle_indexes_[cur_shuffle_idx_] + part_index_ * num_shuffle_parts_; source_->ResetPartition(idx, num_parts_ * num_shuffle_parts_); return NextRecord(out_rec); } else { return true; } } else { return source_->NextRecord(out_rec); } } // implement next chunk virtual bool NextChunk(Blob* out_chunk) { if (num_shuffle_parts_ > 1) { if (!source_->NextChunk(out_chunk)) { if (cur_shuffle_idx_ == num_shuffle_parts_ - 1) { return false; } ++cur_shuffle_idx_; int idx = shuffle_indexes_[cur_shuffle_idx_] + part_index_ * num_shuffle_parts_; source_->ResetPartition(idx, num_parts_ * num_shuffle_parts_); return NextChunk(out_chunk); } else { return true; } } else { return source_->NextChunk(out_chunk); } } // implement ResetPartition. virtual void ResetPartition(unsigned rank, unsigned nsplit) { PANIC_ENFORCE(nsplit == num_parts_, "num_parts is not consistent!"); int idx = shuffle_indexes_[0] + rank * num_shuffle_parts_; source_->ResetPartition(idx, nsplit * num_shuffle_parts_); cur_shuffle_idx_ = 0; } /*! * \brief constructor * \param uri the uri of the input, can contain hdfs prefix * \param part_index the part id of current input * \param num_parts total number of splits * \param type type of record * List of possible types: "text", "recordio" * - "text": * text file, each line is treated as a record * input split will split on '\\n' or '\\r' * - "recordio": * binary recordio file, see recordio.h * \param num_shuffle_parts number of shuffle chunks for each split * \param shuffle_seed shuffle seed for chunk shuffling */ InputSplitShuffle(const char* uri, unsigned part_index, unsigned num_parts, const char* type, unsigned num_shuffle_parts, int shuffle_seed) : part_index_(part_index), num_parts_(num_parts), num_shuffle_parts_(num_shuffle_parts), cur_shuffle_idx_(0) { for (unsigned i = 0; i < num_shuffle_parts_; i++) { shuffle_indexes_.push_back(i); } trnd_.seed(kRandMagic_ + part_index_ + num_parts_ + num_shuffle_parts_ + shuffle_seed); std::shuffle(shuffle_indexes_.begin(), shuffle_indexes_.end(), trnd_); int idx = shuffle_indexes_[cur_shuffle_idx_] + part_index_ * num_shuffle_parts_; source_.reset( InputSplit::Create(uri, idx , num_parts_ * num_shuffle_parts_, type)); } /*! * \brief factory function: * create input split with chunk shuffling given a uri * \param uri the uri of the input, can contain hdfs prefix * \param part_index the part id of current input * \param num_parts total number of splits * \param type type of record * List of possible types: "text", "recordio" * - "text": * text file, each line is treated as a record * input split will split on '\\n' or '\\r' * - "recordio": * binary recordio file, see recordio.h * \param num_shuffle_parts number of shuffle chunks for each split * \param shuffle_seed shuffle seed for chunk shuffling * \return a new input split * \sa InputSplit::Type */ static InputSplit* Create(const char* uri, unsigned part_index, unsigned num_parts, const char* type, unsigned num_shuffle_parts, int shuffle_seed) { PANIC_ENFORCE(num_shuffle_parts > 0, "number of shuffle parts should be greater than zero!"); return new InputSplitShuffle( uri, part_index, num_parts, type, num_shuffle_parts, shuffle_seed); } private: // magic nyumber for seed static const int kRandMagic_ = 666; /*! \brief random engine */ std::mt19937 trnd_; /*! \brief inner inputsplit */ std::unique_ptr<InputSplit> source_; /*! \brief part index */ unsigned part_index_; /*! \brief number of parts */ unsigned num_parts_; /*! \brief the number of block for shuffling*/ unsigned num_shuffle_parts_; /*! \brief current shuffle block index */ unsigned cur_shuffle_idx_; /*! \brief shuffled indexes */ std::vector<int> shuffle_indexes_; }; } // namespace mydmlc } // namespace bubblefs #endif // BUBBLEFS_UTILS_DMLC_INPUT_SPLIT_SHUFFLE_H_
/* * * malloc_wrappers.c * * Author: Markku Rossi <mtr@iki.fi> * * Copyright (c) 2005-2016 Markku Rossi. * * See the LICENSE file for the details on licensing. * * Wrappers for system's memory allocation routines. * */ #include "piincludes.h" #include "pimalloc.h" #include <dlfcn.h> #include <signal.h> /***************************** Global variables *****************************/ /* Allocation and free functions. These point to some functions that are capable to allocate and release memory (malloc and free are nice). */ extern void *(*pi_malloc_ptr)(size_t); extern void (*pi_free_ptr)(void *); /********************** Bootstrap allocation routines ***********************/ static unsigned char bootstrap_heap[100 * 1024]; static size_t bootstrap_allocated = 0; /* Align `number' to `align'. The `number' and `align' must be integer numbers. */ #define PI_ALIGN(number, align) \ ((((number) + ((align) - 1)) / (align)) * (align)) static void * bootstrap_malloc(size_t size) { void *ptr; size = PI_ALIGN(size, 8); if (bootstrap_allocated + size > sizeof(bootstrap_heap)) { fprintf(stderr, "pimalloc: bootstrap heap out of space: size=%zu\n", size); return NULL; } ptr = bootstrap_heap + bootstrap_allocated; bootstrap_allocated += size; fprintf(stderr, "pimalloc: bootstrap_malloc(%zu) => %p\n", size, ptr); return ptr; } static void bootstrap_free(void *ptr) { fprintf(stderr, "pimalloc: bootstrap_free(%p)\n", ptr); } /************************** Interface to the libc ***************************/ static int initialized = 0; static void *libc; /*************** Wrapping system's memory allocation routines ***************/ static void init(void); void * malloc(size_t size) { if (!initialized) init(); return pi_malloc(size); } void free(void *ptr) { if (!initialized) init(); if (ptr == (void *) 1) { pi_malloc_dump_statistics(); pi_malloc_dump_blocks(); return; } pi_free(ptr); } void * realloc(void *ptr, size_t size) { if (!initialized) init(); return pi_realloc(ptr, 0, size); } void * calloc(size_t number, size_t size) { if (!initialized) init(); return pi_calloc(number, size); } static void dump_blocks(int sig) { pi_malloc_dump_statistics(); fprintf(stderr, "pimalloc: dumping blocks...\n"); pi_malloc_dump_blocks(); fprintf(stderr, "pimalloc: done\n"); } static void init(void) { char buf[256]; ssize_t ret; const char *signal_path = "/tmp/mallocdebug"; int sig = -1; int i; int at_exit = 1; char *endp; initialized = 1; pi_malloc_ptr = bootstrap_malloc; pi_free_ptr = bootstrap_free; fprintf(stderr, "pimalloc: init...\n"); libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_GLOBAL); if (libc == NULL) libc = dlopen("libc.so", RTLD_LAZY | RTLD_GLOBAL); if (libc == NULL) { perror("Could not open libc.so"); exit(1); } pi_malloc_ptr = dlsym(libc, "malloc"); if (pi_malloc_ptr == NULL) { perror("Could not fetch malloc"); exit(1); } pi_free_ptr = dlsym(libc, "free"); if (pi_free_ptr == NULL) { perror("Could not fetch free"); exit(1); } ret = readlink(signal_path, buf, sizeof(buf)); if (ret != -1) { for (i = 0; buf[i]; i++) { switch (buf[i]) { case 'e': at_exit = 0; break; default: sig = strtol(buf + i, &endp, 10); i = endp - buf - 1; break; } } if (sig >= 0 && signal(sig, dump_blocks) == SIG_ERR) sig = -2; fprintf(stderr, "pimalloc: options: signal=%d, pid=%d, atexit=%s\n", sig, getpid(), at_exit ? "true" : "false"); } else { fprintf(stderr, "pimalloc: no options defined (ln -s FLAGSSIGNAL %s)\n" "pimalloc: FLAGS: e=no atexit dump\n" "pimalloc: SIGNAL: dump signal (SIGUSR1=%d, SIGUSR2=%d)\n", signal_path, SIGUSR1, SIGUSR2); } fprintf(stderr, "pimalloc: malloc=%p[%p], free=%p[%p]\n", pi_malloc_ptr, malloc, pi_free_ptr, free); if (at_exit) atexit(pi_malloc_dump_blocks); }
#pragma once #include "cutlass/cutlass.h" #include "cutlass/conv/convolution.h" #include "cutlass/conv/conv2d_problem_size.h" #include "cutlass/conv/conv3d_problem_size.h" #include "cutlass/layout/tensor.h" #include "cutlass/layout/matrix.h" #include "cutlass/tensor_ref.h" namespace cutlass { namespace epilogue { namespace threadblock { template< typename TensorLayout_, ///! The original output tensor layout typename OutputIteratorLayout_, ///! Layout used by epilogue output iterator typename TensorRef_, ///! Input tensor to epilogue output iterator conv::Operator ConvOperator, ///! Convolutional operator (Fprop, Dgrad, Wgrad) typename ConvProblemSize_ ///! Convolutional operator on 2D or 3D problem > struct ConvOutputIteratorParameter { using TensorLayout = TensorLayout_; using OutputIteratorLayout = OutputIteratorLayout_; using OutputTensorCoord = typename OutputIteratorLayout::TensorCoord; using TensorRef = TensorRef_; static conv::Operator const kConvolutionalOperator = ConvOperator; using ConvProblemSize = ConvProblemSize_; /// Wgrad stride idx for implicit gemm algorithm // Conv2d row-major matrix (KxRSC) // Conv3d row-major matrix (KxTRSC) static int const kWgradStrideIdx = platform::is_same<TensorLayout, layout::TensorNHWC>::value ? 2 : 3; /// This chooses the appropriate stride element of the C tensor. static int const kTensorStrideIdx = (kConvolutionalOperator == conv::Operator::kWgrad ? kWgradStrideIdx : 0); CUTLASS_HOST_DEVICE static OutputIteratorLayout layout(const TensorRef & ref) { return ref.stride(kTensorStrideIdx); } CUTLASS_HOST_DEVICE static OutputTensorCoord extent(ConvProblemSize problem_size) { return conv::implicit_gemm_problem_size(kConvolutionalOperator, problem_size).mn(); } }; template < int InterleavedK, typename TensorRef_, conv::Operator ConvOperator, typename ConvProblemSize_ > struct ConvOutputIteratorParameter< layout::TensorNCxHWx<InterleavedK>, layout::TensorNCxHWx<InterleavedK>, TensorRef_, ConvOperator, ConvProblemSize_> { using TensorLayout = typename layout::TensorNCxHWx<InterleavedK>; using OutputIteratorLayout = typename layout::TensorNCxHWx<InterleavedK>; using OutputTensorCoord = typename OutputIteratorLayout::TensorCoord; using TensorRef = TensorRef_; static conv::Operator const kConvolutionalOperator = ConvOperator; using ConvProblemSize = ConvProblemSize_; CUTLASS_HOST_DEVICE static OutputIteratorLayout layout(const TensorRef & ref) { return ref.stride(); } CUTLASS_HOST_DEVICE static OutputTensorCoord extent(ConvProblemSize problem_size) { return problem_size.output_extent(); } }; } // namespace threadblock } // namespace epilogue } // namespace cutlass
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #ifndef SPARROW_DFTB_REPULSIONPARAMETERS_H #define SPARROW_DFTB_REPULSIONPARAMETERS_H #include <vector> namespace Scine { namespace Sparrow { namespace dftb { /*! * DFTB parameters for the repulsion of an element pair. */ struct RepulsionParameters { int nSplineInts; double cutoff; double a1, a2, a3; // Coefficients for exponential part of repulsion std::vector<double> splineStart, splineEnd; std::vector<double> c0, c1, c2, c3; double c4, c5; // For last spline }; } // namespace dftb } // namespace Sparrow } // namespace Scine #endif // SPARROW_DFTB_REPULSIONPARAMETERS_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 BLIMP_CLIENT_CORE_SESSION_CLIENT_NETWORK_COMPONENTS_H_ #define BLIMP_CLIENT_CORE_SESSION_CLIENT_NETWORK_COMPONENTS_H_ #include <memory> #include "base/threading/thread_checker.h" #include "blimp/client/core/session/assignment_source.h" #include "blimp/client/core/session/network_event_observer.h" #include "blimp/net/blimp_connection.h" #include "blimp/net/blimp_connection_statistics.h" #include "blimp/net/browser_connection_handler.h" #include "blimp/net/client_connection_manager.h" namespace blimp { namespace client { // This class's functions and destruction must all be invoked on the IO thread // by the owner. It is OK to construct the object on the main thread. The // ThreadChecker is initialized in the call to Initialize. class ClientNetworkComponents : public ConnectionHandler, public ConnectionErrorObserver { public: // Can be created on any thread. ClientNetworkComponents( std::unique_ptr<NetworkEventObserver> observer, std::unique_ptr<BlimpConnectionStatistics> blimp_connection_statistics); ~ClientNetworkComponents() override; // Sets up network components. void Initialize(); // Starts the connection to the engine using the given |assignment|. // It is required to first call Initialize. void ConnectWithAssignment(const Assignment& assignment); BrowserConnectionHandler* GetBrowserConnectionHandler(); private: // ConnectionHandler implementation. void HandleConnection(std::unique_ptr<BlimpConnection> connection) override; // ConnectionErrorObserver implementation. void OnConnectionError(int error) override; // The ThreadChecker is reset during the call to Initialize. base::ThreadChecker io_thread_checker_; BrowserConnectionHandler connection_handler_; std::unique_ptr<ClientConnectionManager> connection_manager_; std::unique_ptr<NetworkEventObserver> network_observer_; std::unique_ptr<BlimpConnectionStatistics> connection_statistics_; DISALLOW_COPY_AND_ASSIGN(ClientNetworkComponents); }; } // namespace client } // namespace blimp #endif // BLIMP_CLIENT_CORE_SESSION_CLIENT_NETWORK_COMPONENTS_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 COMPONENTS_ARC_TEST_FAKE_NOTIFICATIONS_INSTANCE_H_ #define COMPONENTS_ARC_TEST_FAKE_NOTIFICATIONS_INSTANCE_H_ #include <string> #include <utility> #include <vector> #include "components/arc/mojom/notifications.mojom.h" namespace arc { class FakeNotificationsInstance : public mojom::NotificationsInstance { public: FakeNotificationsInstance(); ~FakeNotificationsInstance() override; // mojom::NotificationsInstance overrides: void InitDeprecated(mojom::NotificationsHostPtr host_ptr) override; void Init(mojom::NotificationsHostPtr host_ptr, InitCallback callback) override; void SendNotificationEventToAndroid( const std::string& key, mojom::ArcNotificationEvent event) override; void CreateNotificationWindow(const std::string& key) override; void CloseNotificationWindow(const std::string& key) override; void OpenNotificationSettings(const std::string& key) override; void OpenNotificationSnoozeSettings(const std::string& key) override; void SetDoNotDisturbStatusOnAndroid( mojom::ArcDoNotDisturbStatusPtr status) override; void CancelPress(const std::string& key) override; void PerformDeferredUserAction(uint32_t action_id) override; void CancelDeferredUserAction(uint32_t action_id) override; void SetLockScreenSettingOnAndroid( mojom::ArcLockScreenNotificationSettingPtr setting) override; void SetNotificationConfiguration( mojom::NotificationConfigurationPtr configuration) override; const std::vector<std::pair<std::string, mojom::ArcNotificationEvent>>& events() const; const mojom::ArcDoNotDisturbStatusPtr& latest_do_not_disturb_status() const; private: std::vector<std::pair<std::string, mojom::ArcNotificationEvent>> events_; mojom::ArcDoNotDisturbStatusPtr latest_do_not_disturb_status_; DISALLOW_COPY_AND_ASSIGN(FakeNotificationsInstance); }; } // namespace arc #endif // COMPONENTS_ARC_TEST_FAKE_NOTIFICATIONS_INSTANCE_H_
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_44.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml Template File: sources-sink-44.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 * Sinks: loop * BadSink : Copy int64_t array to data using a loop * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer * * */ #include "std_testcase.h" #ifndef OMITBAD static void badSink(int64_t * data) { { int64_t source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printLongLongLine(data[0]); free(data); } } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_44_bad() { int64_t * data; /* define a function pointer */ void (*funcPtr) (int64_t *) = badSink; data = NULL; /* 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);} /* use the function pointer */ funcPtr(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSink(int64_t * data) { { int64_t source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printLongLongLine(data[0]); free(data); } } } static void goodG2B() { int64_t * data; void (*funcPtr) (int64_t *) = goodG2BSink; data = NULL; /* 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);} funcPtr(data); } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_44_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()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_44_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_44_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
// 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 CHROME_BROWSER_DOWNLOAD_DOWNLOAD_QUERY_H_ #define CHROME_BROWSER_DOWNLOAD_DOWNLOAD_QUERY_H_ #include <map> #include <string> #include <vector> #include "base/callback_forward.h" #include "content/public/browser/download_item.h" namespace base { class Value; } // Filter and sort a vector of DownloadItem*s. // // The following example copies from |all_items| to |results| those // DownloadItem*s whose start time is 0 and whose id is odd, sorts primarily by // bytes received ascending and secondarily by url descending, and limits the // results to 20 items. Any number of filters or sorters is allowed. If all // sorters compare two DownloadItems equivalently, then they are sorted by their // id ascending. // // DownloadQuery query; // base::FundamentalValue start_time(0); // CHECK(query.AddFilter(FILTER_START_TIME, start_time)); // bool FilterOutOddDownloads(const DownloadItem& item) { // return 0 == (item.GetId() % 2); // } // CHECK(query.AddFilter(base::Bind(&FilterOutOddDownloads))); // query.AddSorter(SORT_BYTES_RECEIVED, ASCENDING); // query.AddSorter(SORT_URL, DESCENDING); // query.Limit(20); // query.Skip(5); // DownloadVector all_items, results; // query.Search(all_items.begin(), all_items.end(), &results); class DownloadQuery { public: typedef std::vector<content::DownloadItem*> DownloadVector; // FilterCallback is a Callback that takes a DownloadItem and returns true if // the item matches the filter and false otherwise. // query.AddFilter(base::Bind(&YourFilterFunction)); typedef base::Callback<bool(const content::DownloadItem&)> FilterCallback; // All times are ISO 8601 strings. enum FilterType { FILTER_BYTES_RECEIVED, // int FILTER_DANGER_ACCEPTED, // bool FILTER_ENDED_AFTER, // string FILTER_ENDED_BEFORE, // string FILTER_END_TIME, // string FILTER_EXISTS, // bool FILTER_FILENAME, // string FILTER_FILENAME_REGEX, // string FILTER_MIME, // string FILTER_PAUSED, // bool FILTER_QUERY, // vector<base::string16> FILTER_STARTED_AFTER, // string FILTER_STARTED_BEFORE, // string FILTER_START_TIME, // string FILTER_TOTAL_BYTES, // int FILTER_TOTAL_BYTES_GREATER, // int FILTER_TOTAL_BYTES_LESS, // int FILTER_URL, // string FILTER_URL_REGEX, // string }; enum SortType { SORT_BYTES_RECEIVED, SORT_DANGER, SORT_DANGER_ACCEPTED, SORT_END_TIME, SORT_EXISTS, SORT_FILENAME, SORT_MIME, SORT_PAUSED, SORT_START_TIME, SORT_STATE, SORT_TOTAL_BYTES, SORT_URL, }; enum SortDirection { ASCENDING, DESCENDING, }; DownloadQuery(); ~DownloadQuery(); // Adds a new filter of type |type| with value |value| and returns true if // |type| is valid and |value| is the correct Value-type and well-formed. // Returns false if |type| is invalid or |value| is the incorrect Value-type // or malformed. Search() will filter out all DownloadItem*s that do not // match all filters. Multiple instances of the same FilterType are allowed, // so you can pass two regexes to AddFilter(URL_REGEX,...) in order to // Search() for items whose url matches both regexes. You can also pass two // different DownloadStates to AddFilter(), which will cause Search() to // filter out all items. bool AddFilter(const FilterCallback& filter); bool AddFilter(FilterType type, const base::Value& value); void AddFilter(content::DownloadDangerType danger); void AddFilter(content::DownloadItem::DownloadState state); // Adds a new sorter of type |type| with direction |direction|. After // filtering DownloadItem*s, Search() will sort the results primarily by the // sorter from the first call to Sort(), secondarily by the sorter from the // second call to Sort(), and so on. For example, if the InputIterator passed // to Search() yields four DownloadItems {id:0, error:0, start_time:0}, {id:1, // error:0, start_time:1}, {id:2, error:1, start_time:0}, {id:3, error:1, // start_time:1}, and Sort is called twice, once with (SORT_ERROR, ASCENDING) // then with (SORT_START_TIME, DESCENDING), then Search() will return items // ordered 1,0,3,2. void AddSorter(SortType type, SortDirection direction); // Limit the size of search results to |limit|. void Limit(size_t limit) { limit_ = limit; } // Ignore |skip| items. Note: which items are skipped are not guaranteed to // always be the same. If you rely on this, you should probably be using // AddSorter() in conjunction with this method. void Skip(size_t skip) { skip_ = skip; } // Filters DownloadItem*s from |iter| to |last| into |results|, sorts // |results|, and limits the size of |results|. |results| must be non-NULL. template <typename InputIterator> void Search(InputIterator iter, const InputIterator last, DownloadVector* results) const { results->clear(); for (; iter != last; ++iter) { if (Matches(**iter)) results->push_back(*iter); } FinishSearch(results); } private: struct Sorter; class DownloadComparator; typedef std::vector<FilterCallback> FilterCallbackVector; typedef std::vector<Sorter> SorterVector; bool FilterRegex(const std::string& regex_str, const base::Callback<std::string( const content::DownloadItem&)>& accessor); bool Matches(const content::DownloadItem& item) const; void FinishSearch(DownloadVector* results) const; FilterCallbackVector filters_; SorterVector sorters_; size_t limit_; size_t skip_; DISALLOW_COPY_AND_ASSIGN(DownloadQuery); }; #endif // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_QUERY_H_
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate> @end
#include <stdbool.h> #include <stdio.h> #include <letmecreate/click/fan.h> #include <letmecreate/core/i2c.h> /* I2C address of EMC2301 */ #define EMC2301_ADDRESS (0x2F) /* Register addresses */ #define EMC2301_PRODUCT_ID_REG (0xFD) #define EMC2301_MANUFACTURER_ID_REG (0xFE) #define EMC2301_FAN_CONFIG_1_REG (0x32) #define EMC2301_TACH_TARGET_LOW (0x3C) #define EMC2301_TACH_TARGET_HIGH (0x3D) #define EMC2301_INT_REG (0x29) #define EMC2301_FAN_STATUS_REG (0x24) /* Register values */ #define EMC2301_PRODUCT_ID (0x37) #define EMC2301_MANUFACTURER_ID (0x5D) #define EMC2301_ENABLE_FSC_ALGO (0x80) #define EMC2301_MIN_RPM (0) /* min 500 rpm */ #define EMC2301_MIN_EDGE (0x08) /* min 5 edges */ #define EMC2301_UPDATE (0) /* 400ms */ #define FAN_CLICK_MIN_RPM (600) #define FAN_CLICK_MAX_RPM (2500) static bool check_device(void) { uint8_t product_id = 0, manufacturer_id = 0; if (i2c_read_register(EMC2301_ADDRESS, EMC2301_PRODUCT_ID_REG, &product_id) < 0) return false; if (product_id != EMC2301_PRODUCT_ID) return false; if (i2c_read_register(EMC2301_ADDRESS, EMC2301_MANUFACTURER_ID_REG, &manufacturer_id) < 0) return false; return manufacturer_id == EMC2301_MANUFACTURER_ID; } int fan_click_init(void) { if (check_device() == false) { fprintf(stderr, "fan: Failed to find device emc2301.\n"); return -1; } if (i2c_write_register(EMC2301_ADDRESS, EMC2301_FAN_CONFIG_1_REG, EMC2301_ENABLE_FSC_ALGO | EMC2301_MIN_RPM | EMC2301_MIN_EDGE | EMC2301_UPDATE) < 0) { fprintf(stderr, "fan: Failed to configure device.\n"); return -1; } return 0; } int fan_click_set_speed(uint16_t rpm) { uint16_t tach = 0; if (rpm < FAN_CLICK_MIN_RPM || rpm > FAN_CLICK_MAX_RPM) { fprintf(stderr, "fan: rpm out of range 600-2500.\n"); return -1; } /* Using equation 3 from emc2301 5.18 section of the datasheet. * Datasheet available at http://ww1.microchip.com/downloads/en/DeviceDoc/2301.pdf */ tach = 3932160 / rpm; tach &= 0x1FFF; if (i2c_write_register(EMC2301_ADDRESS, EMC2301_TACH_TARGET_LOW, tach << 3) < 0 || i2c_write_register(EMC2301_ADDRESS, EMC2301_TACH_TARGET_HIGH, tach >> 5) < 0) { fprintf(stderr, "fan: Failed to update tach register.\n"); return -1; } return 0; }
// // Soap.h // SOAP-IOS // // Created by Elliott on 13-7-26. // Copyright (c) 2013年 Elliott. All rights reserved. // #import "SoapUtility.h" #import "SoapService.h" #import "DDXMLElement+WSDL.h"
#include <gaussian.h> #include <args.h> #include <stdbool.h> int main ( int argc, char *argv[] ) { double units; uint32_t gaussianSize; float gaussianSigma; char* imgname;//the name of the image file, taken by the arguments //read in the program's arguments if(readArguments(argc,argv,&imgname,&gaussianSize,&gaussianSigma)==false) return -1; //perform CPU blurring if(pna_blur_cpu(imgname,gaussianSize,gaussianSigma)==false)//time it return -2; //perform GPU blurring and then read the timer if(pna_blur_gpu(imgname,gaussianSize,gaussianSigma)==false) return -3; return 0; }
// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // 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 <organization> 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 <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 MAPVIZ_PLUGINS_ROBOT_IMAGE_PLUGIN_H_ #define MAPVIZ_PLUGINS_ROBOT_IMAGE_PLUGIN_H_ // C++ standard libraries #include <string> #include <mapviz/mapviz_plugin.h> // QT libraries #include <QGLWidget> #include <QObject> #include <QWidget> // ROS libraries #include <ros/ros.h> #include <tf/transform_datatypes.h> #include <mapviz/map_canvas.h> // QT autogenerated files #include "ui_robot_image_config.h" #include "ui_topic_select.h" namespace mapviz_plugins { class RobotImagePlugin : public mapviz::MapvizPlugin { Q_OBJECT public: RobotImagePlugin(); virtual ~RobotImagePlugin(); bool Initialize(QGLWidget* canvas); void Shutdown() {} void Draw(double x, double y, double scale); void Transform(); void LoadConfig(const YAML::Node& node, const std::string& path); void SaveConfig(YAML::Emitter& emitter, const std::string& path); QWidget* GetConfigWidget(QWidget* parent); protected: void PrintError(const std::string& message); void PrintInfo(const std::string& message); void PrintWarning(const std::string& message); protected Q_SLOTS: void SelectFile(); void SelectFrame(); void FrameEdited(); void WidthChanged(double value); void HeightChanged(double value); private: Ui::robot_image_config ui_; QWidget* config_widget_; double width_; double height_; std::string filename_; QImage image_; int dimension_; int texture_id_; bool texture_loaded_; bool transformed_; tf::Point top_left_; tf::Point top_right_; tf::Point bottom_left_; tf::Point bottom_right_; tf::Point top_left_transformed_; tf::Point top_right_transformed_; tf::Point bottom_left_transformed_; tf::Point bottom_right_transformed_; void UpdateShape(); void LoadImage(); }; } #endif // MAPVIZ_PLUGINS_ROBOT_IMAGE_PLUGIN_H_
#import <UIKit/UIKit.h> #import "ATTableViewController.h" @interface ATSettingSingleSelectViewController : ATTableViewController { } @end
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Netscape security libraries. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ian McGreer <mcgreer@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef NET_THIRD_PARTY_MOZILLA_SECURITY_MANAGER_NSPKCS12BLOB_H_ #define NET_THIRD_PARTY_MOZILLA_SECURITY_MANAGER_NSPKCS12BLOB_H_ #include <string> #include <vector> #include "base/memory/ref_counted.h" #include "base/strings/string16.h" #include "net/cert/scoped_nss_types.h" #include "starboard/types.h" typedef struct CERTCertificateStr CERTCertificate; typedef struct PK11SlotInfoStr PK11SlotInfo; namespace mozilla_security_manager { // Initialize NSS PKCS#12 libs. void EnsurePKCS12Init(); // Import the private key and certificate from a PKCS#12 blob into the slot. // If |is_extractable| is false, mark the private key as non-extractable. // Returns a net error code. |imported_certs|, if non-NULL, returns a list of // certs that were imported. int nsPKCS12Blob_Import(PK11SlotInfo* slot, const char* pkcs12_data, size_t pkcs12_len, const base::string16& password, bool is_extractable, net::ScopedCERTCertificateList* imported_certs); // Export the given certificates into a PKCS#12 blob, storing into output. // Returns the number of certificates exported. // TODO(mattm): provide better error return status? int nsPKCS12Blob_Export(std::string* output, const net::ScopedCERTCertificateList& certs, const base::string16& password); } // namespace mozilla_security_manager #endif // NET_THIRD_PARTY_MOZILLA_SECURITY_MANAGER_NSPKCS12BLOB_H_
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_34.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__sizeof.label.xml Template File: sources-sink-34.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Initialize the source buffer using the size of a pointer * GoodSource: Initialize the source buffer using the size of the DataElementType * Sinks: * BadSink : Print then free data * Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function) * * */ #include "std_testcase.h" typedef union { twoIntsStruct * unionFirst; twoIntsStruct * unionSecond; } CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_34_unionType; #ifndef OMITBAD void CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_34_bad() { twoIntsStruct * data; CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_34_unionType myUnion; /* Initialize data */ data = NULL; /* INCIDENTAL: CWE-467 (Use of sizeof() on a pointer type) */ /* FLAW: Using sizeof the pointer and not the data type in malloc() */ data = (twoIntsStruct *)malloc(sizeof(data)); if (data == NULL) {exit(-1);} data->intOne = 1; data->intTwo = 2; myUnion.unionFirst = data; { twoIntsStruct * data = myUnion.unionSecond; /* POTENTIAL FLAW: Attempt to use data, which may not have enough memory allocated */ printStructLine(data); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2B() { twoIntsStruct * data; CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_34_unionType myUnion; /* Initialize data */ data = NULL; /* FIX: Using sizeof the data type in malloc() */ data = (twoIntsStruct *)malloc(sizeof(*data)); if (data == NULL) {exit(-1);} data->intOne = 1; data->intTwo = 2; myUnion.unionFirst = data; { twoIntsStruct * data = myUnion.unionSecond; /* POTENTIAL FLAW: Attempt to use data, which may not have enough memory allocated */ printStructLine(data); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_34_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()..."); CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_34_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_34_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #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_USER_MANAGER_USER_INFO_IMPL_H_ #define COMPONENTS_USER_MANAGER_USER_INFO_IMPL_H_ #include <string> #include "base/macros.h" #include "components/account_id/account_id.h" #include "components/user_manager/user_info.h" #include "components/user_manager/user_manager_export.h" #include "ui/gfx/image/image_skia.h" namespace user_manager { // Stub implementation of UserInfo interface. Used in tests. class USER_MANAGER_EXPORT UserInfoImpl : public UserInfo { public: UserInfoImpl(); UserInfoImpl(const UserInfoImpl&) = delete; UserInfoImpl& operator=(const UserInfoImpl&) = delete; ~UserInfoImpl() override; // UserInfo: std::u16string GetDisplayName() const override; std::u16string GetGivenName() const override; std::string GetDisplayEmail() const override; const AccountId& GetAccountId() const override; const gfx::ImageSkia& GetImage() const override; private: const AccountId account_id_; gfx::ImageSkia user_image_; }; } // namespace user_manager #endif // COMPONENTS_USER_MANAGER_USER_INFO_IMPL_H_
/* * type and other definitions * * written by Yasha (ITOH Yasufumi) * public domain * * $NetBSD: type_local.h,v 1.1 1998/09/01 19:51:09 itohy Exp $ */ #ifdef __STDC__ # define PROTO(x) x #else # define PROTO(x) () # ifndef const # define const # endif #endif #ifndef __BIT_TYPES_DEFINED__ typedef unsigned char u_int8_t; typedef unsigned short u_int16_t; typedef unsigned int u_int32_t; #endif /* * big-endian integer types */ typedef union be_uint16 { u_int8_t val[2]; u_int16_t hostval; } be_uint16_t; typedef union be_uint32 { u_int8_t val[4]; u_int32_t hostval; be_uint16_t half[2]; } be_uint32_t; #define SIZE_16 sizeof(be_uint16_t) #define SIZE_32 sizeof(be_uint32_t)
/* * * Copyright (c) 1999-2000, Vitaly V Belekhov * 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 unmodified, 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. * * $FreeBSD: src/sys/netgraph/ng_split.h,v 1.2 2001/07/24 23:33:06 brooks Exp $ * */ #ifndef _NG_SPLIT_H #define _NG_SPLIT_H /* Node type name and magic cookie */ #define NG_SPLIT_NODE_TYPE "split" #define NGM_NG_SPLIT_COOKIE 949409402 /* My hook names */ #define NG_SPLIT_HOOK_MIXED "mixed" /* Mixed stream (in/out) */ #define NG_SPLIT_HOOK_OUT "out" /* Output to outhook (sending out) */ #define NG_SPLIT_HOOK_IN "in" /* Input from inhook (recieving) */ #endif /* _NG_SPLIT_H */
/************************************************************************** Copyright (c) 2007-2008, Intel Corporation. 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************/ #ifndef _I_WMX_SDK_H #define _I_WMX_SDK_H #include "VersionUtils.h" #include "WrappersCommon.h" #include "WiMaxAPI.h" #define VERSION_MAX_LEN 100 #define WRAPPER_NAME_LEN 30 #define WRAPPER_NAME "iWmxSDK" /// <summary> /// This API initializes the iWmxSDK wrappers DLL. /// /// A call to this API should preceed calls to specific wrappers' wmxXXX_Init() API. /// This API should be called only once for all threads of a user application. /// If the user wishes to "reset" the wrappers DLL he should call the wmxSDK_Finalize() API before calling wmxSDK_Init() again. /// </summary> /// /// <returns>A wmx_Status_t value indicating the API call's success/error.</returns> wmx_Status_t WMX_WRAPPER_API WMX_EXT_CALL_CONV wmxSDK_Init(); /// <summary> /// This API finalizes the iWmxSDK wrappers DLL. /// /// A call to this API should be preceeded with calls to the wmxXXX_Finalize() API of all specific wrappers used. /// </summary> void WMX_WRAPPER_API WMX_EXT_CALL_CONV wmxSDK_Finalize(); /// <summary> /// This API allows the user to obtain the version of the WiMAX SDK. /// </summary> /// /// <param name="version">(OUT) A pointer to a user-allocated wmx_pVersion_t struct in which the API will fill the WiMAX SDK's version.</param> /// <param name="versionStr">(OUT) A pointer to a user-allocated wmx_pVersionStr_t string in which the API will fill the WiMAX SDK's version. VERSION_SDK_STR_MAX_SIZE can be used.</param> /// <param name="versionStr">(IN) The size of the user-allocated string.</param> /// /// <returns>A wmx_Status_t value indicating the API call's success/error.</returns> wmx_Status_t WMX_WRAPPER_API WMX_EXT_CALL_CONV wmxSDK_GetVersion( wmx_pVersion_t version, wmx_pVersionStr_t versionStr, wmx_VersionStrLen_t *verMaxLen ) ; /// <summary> /// This API allows the user to register a callback for SDK control status updates. /// </summary> /// /// <param name="ctrlStatusUpdateCB">(IN) A pointer to the application function to be called upon SDK control status change.</param> wmx_Status_t WMX_WRAPPER_API WMX_EXT_CALL_CONV wmxSDK_RegisterCtrlStatusUpdatesCB(wmx_pCtrlStatusUpdateCB_t ctrlStatusUpdateCB); /// <summary> /// This API allows the user to de-register for SDK control status updates. /// </summary> /// /// <param name="ctrlStatusUpdateCB">(IN) A pointer to the application function to be called upon SDK control status change.</param> wmx_Status_t WMX_WRAPPER_API WMX_EXT_CALL_CONV wmxSDK_UnregisterCtrlStatusUpdatesCB(wmx_pCtrlStatusUpdateCB_t ctrlStatusUpdateCB); /// <summary> /// This API allows the user to obtain the status of the WiMAX SDK. /// /// SDK status info includes the extraction/insertion status of the card, the status of the driver and the AppSrv service. /// </summary> /// /// <returns>A wmx_CtrlStatus_t value indicating the control status of the SDK.</returns> wmx_CtrlStatus_t WMX_WRAPPER_API WMX_EXT_CALL_CONV wmxSDK_GetCtrlStatus(); /// <summary> /// This API allows the user to set the IP address and port number of AppSrv. /// /// The SDK first looks for IP address and port number settings in the Registry under /// [HKEY_LOCAL_MACHINE\SOFTWARE\PipeConfig\SdkIpAddress & SdkPortNum]. /// /// The application can override the Registry settings using this API. /// /// If the application already initialized the SDK and it is already connected to the AppSrv service, /// then calling this API will only have effect after the SDK was finalized and re-initialized. /// </summary> /// /// <param name="szHostName">(IN) A string containing the IP address or host name of AppSrv.</param> /// <param name="nPort">(IN) The port number of AppSrv (a decimal value).</param> /// /// <returns>A wmx_Status_t value indicating the API call's success/error.</returns> wmx_Status_t WMX_WRAPPER_API WMX_EXT_CALL_CONV wmxSDK_SetConnParams(char *szHostName, int nPort); WIMAX_API_RET WIMAX_API DetachFromSDK(); #endif // _I_WMX_SDK_H
/* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for license. */ //-----------------------------------NOTICE----------------------------------// // Some of this file is automatically filled in by a Python script. Only // // add custom code in the designated areas or it will be overwritten during // // the next update. // //-----------------------------------NOTICE----------------------------------// #ifndef _NITRANSPARENTPROPERTY_H_ #define _NITRANSPARENTPROPERTY_H_ //--BEGIN FILE HEAD CUSTOM CODE--// //--END CUSTOM CODE--// #include "NiProperty.h" namespace Niflib { class NiTransparentProperty; typedef Ref<NiTransparentProperty> NiTransparentPropertyRef; /*! Unknown */ class NiTransparentProperty : public NiProperty { public: /*! Constructor */ NIFLIB_API NiTransparentProperty(); /*! Destructor */ NIFLIB_API virtual ~NiTransparentProperty(); /*! * A constant value which uniquly identifies objects of this type. */ NIFLIB_API static const Type TYPE; /*! * A factory function used during file reading to create an instance of this type of object. * \return A pointer to a newly allocated instance of this type of object. */ NIFLIB_API static NiObject * Create(); /*! * Summarizes the information contained in this object in English. * \param[in] verbose Determines whether or not detailed information about large areas of data will be printed out. * \return A string containing a summary of the information within the object in English. This is the function that Niflyze calls to generate its analysis, so the output is the same. */ NIFLIB_API virtual string asString(bool verbose = false) const; /*! * Used to determine the type of a particular instance of this object. * \return The type constant for the actual type of the object. */ NIFLIB_API virtual const Type & GetType() const; //--This object has no eligable attributes. No example implementation generated--// //--BEGIN MISC CUSTOM CODE--// //--END CUSTOM CODE--// protected: /*! Unknown. */ array<6, byte > unknown; public: /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual void Read(istream& in, list<unsigned int> & link_stack, const NifInfo & info); /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual void Write(ostream& out, const map<NiObjectRef, unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info) const; /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual void FixLinks(const map<unsigned int, NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info); /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual list<NiObjectRef> GetRefs() const; /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual list<NiObject *> GetPtrs() const; }; //--BEGIN FILE FOOT CUSTOM CODE--// //--END CUSTOM CODE--// } //End Niflib namespace #endif
// Copyright (c) 2017 Vivaldi Technologies AS. All rights reserved #ifndef APP_VIVALDI_VERSION_CONSTANTS_H_ #define APP_VIVALDI_VERSION_CONSTANTS_H_ namespace vivaldi { // All constants in alphabetical order. The constants should be documented // alongside the definition of their values in the .cc file. extern const char kVivaldiVersion[]; } // namespace vivaldi #endif // APP_VIVALDI_VERSION_CONSTANTS_H_
// Copyright (c) 2006-2008 Max-Planck-Institute Saarbruecken (Germany). // All rights reserved. // // This file is part of CGAL (www.cgal.org); you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 3 of the License, // or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Michael Hemmer <hemmer@mpi-inf.mpg.de> // // ============================================================================= #ifndef CGAL_PRIMES_H #define CGAL_PRIMES_H #include <CGAL/basic.h> namespace CGAL { namespace internal { CGAL_EXPORT extern const int primes[2000]; static inline int get_next_lower_prime(int current_prime){ bool is_prime = false; int i; CGAL_precondition_msg(current_prime != 2 ," primes definitely exhausted "); if((current_prime <= 7) && (current_prime > 2)){ if(current_prime <= 5){ if(current_prime == 3) return 2; return 3; } return 5; } for(i=current_prime-2;(i>1 && !is_prime);i=i-2){ int r = 1; for(int j=3; (j <= i/2 && (r != 0)); j++){ r = i % j; // std::cout<<"i " <<i<<std::endl; // std::cout<<"j " <<j<<std::endl; // std::cout<<"i%j " <<i%j<<std::endl; if(j==i/2 && r != 0) is_prime = true; } } // CGAL_precondition_msg(is_prime," primes definitely exhausted "); return i+2; } } } #ifdef CGAL_HEADER_ONLY #include <CGAL/primes_impl.h> #endif // CGAL_HEADER_ONLY #endif // CGAL_PRIMES_H
/* Copyright 2013, Peter A. Bigot * * 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 software 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. */ /** @file * * @brief Version data and documentation for embtextf library * * @homepage http://github.com/pabigot/embtextf * @copyright Copyright 2013, Peter A. Bigot. Licensed under <a href="http://www.opensource.org/licenses/BSD-3-Clause">BSD-3-Clause</a> */ #ifndef EMBTEXTF_VERSION_H #define EMBTEXTF_VERSION_H /** Version of the embtextf library. This is a monotonically * non-decreasing integer value suitable for ordinal comparisons. */ #define EMBTEXTF_VERSION 20130609 #endif /* EMBTEXTF_VERSION_H */
#ifndef ML_APPLICATION_H #define ML_APPLICATION_H #include <QApplication> #include <QString> class MeshLabApplication : public QApplication { public: enum HW_ARCHITECTURE {HW_32BIT = 32,HW_64BIT = 64}; MeshLabApplication(int &argc, char *argv[]):QApplication(argc,argv){} ~MeshLabApplication(){} bool notify(QObject * rec, QEvent * ev); static const QString appName(){return tr("MeshLab"); } static const QString architecturalSuffix(const HW_ARCHITECTURE hw) {return "_" + QString::number(int(hw)) + "bit";} static const QString appArchitecturalName(const HW_ARCHITECTURE hw) {return appName() + architecturalSuffix(hw);} static const QString appVer() {return tr("1.3.3"); } static const QString completeName(const HW_ARCHITECTURE hw){return appArchitecturalName(hw) + " v" + appVer(); } static const QString organization(){return tr("VCG");} static const QString organizationHost() {return tr("http://vcg.isti.cnr.it");} static const QString webSite() {return tr("http://meshlab.sourceforge.net/");} static const QString downloadSite() {return tr("http://downloads.sourceforge.net/project/meshlab");} static const QString downloadUpdatesSite() {return downloadSite() + tr("/updates");} static const QString pluginsPathRegisterKeyName() {return tr("pluginsPath");} static const QString versionRegisterKeyName() {return tr("version");} static const QString wordSizeKeyName() {return tr("wordSize");} }; #endif
// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #include <chemfiles.h> #include <stdlib.h> int main() { // [example] CHFL_ATOM* atom = chfl_atom("Na"); if (atom == NULL) { /* handle error */ } chfl_atom_free(atom); // [example] return 0; }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "vizwindow.h" #include "audio.hpp" #include "fm.hpp" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(FMSynth &fm, QWidget *parent = 0); ~MainWindow(); private slots: void on_button_trigger_clicked(); void on_volume_sliderMoved(int position); void on_carrier_slider_sliderMoved(int position); void on_modulating_slider_sliderMoved(int position); void on_modulation_index_slider_sliderMoved(int position); void on_carrier_textbox_editingFinished(); void on_modulating_textbox_editingFinished(); void on_modulation_index_textbox_editingFinished(); void on_scale_sliderMoved(int position); private: Ui::MainWindow *ui; FMSynth &fmsynth; VizWindow vizwindow {fmsynth}; AudioEngine audioEngine {fmsynth}; }; #endif // MAINWINDOW_H
// Copyright 2013 The Flutter 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 FLUTTER_LIB_UI_TEXT_LINE_METRICS_H_ #define FLUTTER_LIB_UI_TEXT_LINE_METRICS_H_ #include "third_party/dart/runtime/include/dart_api.h" #include "third_party/tonic/converter/dart_converter.h" namespace flutter { struct LineMetrics { const bool* hard_break; // The final computed ascent and descent for the line. This can be impacted by // the strut, height, scaling, as well as outlying runs that are very tall. // // The top edge is `baseline - ascent` and the bottom edge is `baseline + // descent`. Ascent and descent are provided as positive numbers. Raw numbers // for specific runs of text can be obtained in run_metrics_map. These values // are the cumulative metrics for the entire line. const double* ascent; const double* descent; const double* unscaled_ascent; // Height of the line. const double* height; // Width of the line. const double* width; // The left edge of the line. The right edge can be obtained with `left + // width` const double* left; // The y position of the baseline for this line from the top of the paragraph. const double* baseline; // Zero indexed line number. const size_t* line_number; LineMetrics(); LineMetrics(const bool* hard_break, const double* ascent, const double* descent, const double* unscaled_ascent, const double* height, const double* width, const double* left, const double* baseline, const size_t* line_number) : hard_break(hard_break), ascent(ascent), descent(descent), unscaled_ascent(unscaled_ascent), height(height), width(width), left(left), baseline(baseline), line_number(line_number) {} }; } // namespace flutter namespace tonic { template <> struct DartConverter<flutter::LineMetrics> { static Dart_Handle ToDart(const flutter::LineMetrics& val); }; template <> struct DartListFactory<flutter::LineMetrics> { static Dart_Handle NewList(intptr_t length); }; } // namespace tonic #endif // FLUTTER_LIB_UI_TEXT_LINE_METRICS_H_
/** * Copyright (c) 2018, Łukasz Marcin Podkalicki <lpodkalicki@gmail.com> */ #ifndef _LIGHT_H_ #define _LIGHT_H_ void light_init(void); #endif /* !_LIGHT_H_ */
// Copyright (c) 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 QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_H_ #include <cstdint> #include <memory> #include <set> #include "net/third_party/quiche/src/quic/core/qpack/qpack_decoder_stream_sender.h" #include "net/third_party/quiche/src/quic/core/qpack/qpack_encoder_stream_receiver.h" #include "net/third_party/quiche/src/quic/core/qpack/qpack_header_table.h" #include "net/third_party/quiche/src/quic/core/qpack/qpack_progressive_decoder.h" #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/platform/api/quic_export.h" #include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h" namespace quic { // QPACK decoder class. Exactly one instance should exist per QUIC connection. // This class vends a new QpackProgressiveDecoder instance for each new header // list to be encoded. class QUIC_EXPORT_PRIVATE QpackDecoder : public QpackEncoderStreamReceiver::Delegate, public QpackProgressiveDecoder::BlockedStreamLimitEnforcer, public QpackProgressiveDecoder::DecodingCompletedVisitor { public: // Interface for receiving notification that an error has occurred on the // encoder stream. This MUST be treated as a connection error of type // HTTP_QPACK_ENCODER_STREAM_ERROR. class QUIC_EXPORT_PRIVATE EncoderStreamErrorDelegate { public: virtual ~EncoderStreamErrorDelegate() {} virtual void OnEncoderStreamError( quiche::QuicheStringPiece error_message) = 0; }; QpackDecoder(uint64_t maximum_dynamic_table_capacity, uint64_t maximum_blocked_streams, EncoderStreamErrorDelegate* encoder_stream_error_delegate); ~QpackDecoder() override; // Signal to the peer's encoder that a stream is reset. This lets the peer's // encoder know that no more header blocks will be processed on this stream, // therefore references to dynamic table entries shall not prevent their // eviction. // This method should be called regardless of whether a header block is being // decoded on that stream, because a header block might be in flight from the // peer. // This method should be called every time a request or push stream is reset // for any reason: for example, client cancels request, or a decoding error // occurs and HeadersHandlerInterface::OnDecodingErrorDetected() is called. // This method should also be called if the stream is reset by the peer, // because the peer's encoder can only evict entries referenced by header // blocks once it receives acknowledgement from this endpoint that the stream // is reset. // However, this method should not be called if the stream is closed normally // using the FIN bit. void OnStreamReset(QuicStreamId stream_id); // QpackProgressiveDecoder::BlockedStreamLimitEnforcer implementation. bool OnStreamBlocked(QuicStreamId stream_id) override; void OnStreamUnblocked(QuicStreamId stream_id) override; // QpackProgressiveDecoder::DecodingCompletedVisitor implementation. void OnDecodingCompleted(QuicStreamId stream_id, uint64_t required_insert_count) override; // Factory method to create a QpackProgressiveDecoder for decoding a header // block. |handler| must remain valid until the returned // QpackProgressiveDecoder instance is destroyed or the decoder calls // |handler->OnHeaderBlockEnd()|. std::unique_ptr<QpackProgressiveDecoder> CreateProgressiveDecoder( QuicStreamId stream_id, QpackProgressiveDecoder::HeadersHandlerInterface* handler); // QpackEncoderStreamReceiver::Delegate implementation void OnInsertWithNameReference(bool is_static, uint64_t name_index, quiche::QuicheStringPiece value) override; void OnInsertWithoutNameReference(quiche::QuicheStringPiece name, quiche::QuicheStringPiece value) override; void OnDuplicate(uint64_t index) override; void OnSetDynamicTableCapacity(uint64_t capacity) override; void OnErrorDetected(quiche::QuicheStringPiece error_message) override; // delegate must be set if dynamic table capacity is not zero. void set_qpack_stream_sender_delegate(QpackStreamSenderDelegate* delegate) { decoder_stream_sender_.set_qpack_stream_sender_delegate(delegate); } QpackStreamReceiver* encoder_stream_receiver() { return &encoder_stream_receiver_; } // True if any dynamic table entries have been referenced from a header block. bool dynamic_table_entry_referenced() const { return header_table_.dynamic_table_entry_referenced(); } private: EncoderStreamErrorDelegate* const encoder_stream_error_delegate_; QpackEncoderStreamReceiver encoder_stream_receiver_; QpackDecoderStreamSender decoder_stream_sender_; QpackHeaderTable header_table_; std::set<QuicStreamId> blocked_streams_; const uint64_t maximum_blocked_streams_; // Known Received Count is the number of insertions the encoder has received // acknowledgement for (through Header Acknowledgement and Insert Count // Increment instructions). The encoder must keep track of it in order to be // able to send Insert Count Increment instructions. See // https://quicwg.org/base-drafts/draft-ietf-quic-qpack.html#known-received-count. uint64_t known_received_count_; }; } // namespace quic #endif // QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_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 CHROME_BROWSER_LOOKALIKES_LOOKALIKE_URL_SERVICE_H_ #define CHROME_BROWSER_LOOKALIKES_LOOKALIKE_URL_SERVICE_H_ #include <vector> #include "base/callback_forward.h" #include "base/memory/weak_ptr.h" #include "base/metrics/field_trial_params.h" #include "base/sequence_checker.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/keyed_service/core/keyed_service.h" #include "components/lookalikes/core/lookalike_url_util.h" class Profile; namespace base { class Clock; } // A service that handles operations on lookalike URLs. It can fetch the list of // engaged sites in a background thread and cache the results until the next // update. This is more efficient than fetching the list on each navigation for // each tab separately. class LookalikeUrlService : public KeyedService { public: explicit LookalikeUrlService(Profile* profile); LookalikeUrlService(const LookalikeUrlService&) = delete; LookalikeUrlService& operator=(const LookalikeUrlService&) = delete; ~LookalikeUrlService() override; using EngagedSitesCallback = base::OnceCallback<void(const std::vector<DomainInfo>&)>; static LookalikeUrlService* Get(Profile* profile); // Returns whether the engaged site list is recently updated. Returns true // even when an update has already been queued or is in progress. bool EngagedSitesNeedUpdating() const; // Triggers an update to the engaged site list if one is not already inflight, // then schedules |callback| to be called with the new list once available. void ForceUpdateEngagedSites(EngagedSitesCallback callback); // Returns the _current_ list of engaged sites, without updating them if // they're out of date. const std::vector<DomainInfo> GetLatestEngagedSites() const; void SetClockForTesting(base::Clock* clock); base::Clock* clock() const { return clock_; } static const base::FeatureParam<base::TimeDelta> kManifestFetchDelay; private: void OnUpdateEngagedSitesCompleted(std::vector<DomainInfo> new_engaged_sites); Profile* profile_; base::Clock* clock_; base::Time last_engagement_fetch_time_; std::vector<DomainInfo> engaged_sites_ GUARDED_BY_CONTEXT(sequence_checker_); // Indicates that an update to the engaged sites list has been queued. Serves // to prevent enqueuing excessive updates. bool update_in_progress_ = false; std::vector<EngagedSitesCallback> pending_update_complete_callbacks_; SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<LookalikeUrlService> weak_factory_{this}; }; #endif // CHROME_BROWSER_LOOKALIKES_LOOKALIKE_URL_SERVICE_H_
#ifndef TWEBSOCKETFRAME_H #define TWEBSOCKETFRAME_H #include <QByteArray> #include <TGlobal> class T_CORE_EXPORT TWebSocketFrame { public: enum OpCode { Continuation = 0x0, TextFrame = 0x1, BinaryFrame = 0x2, Reserve3 = 0x3, Reserve4 = 0x4, Reserve5 = 0x5, Reserve6 = 0x6, Reserve7 = 0x7, Close = 0x8, Ping = 0x9, Pong = 0xA, ReserveB = 0xB, ReserveC = 0xC, ReserveD = 0xD, ReserveE = 0xE, ReserveF = 0xF, }; TWebSocketFrame(); TWebSocketFrame(const TWebSocketFrame &other); TWebSocketFrame &operator=(const TWebSocketFrame &other); bool finBit() const { return _firstByte & 0x80; } bool rsv1Bit() const { return _firstByte & 0x40; } bool rsv2Bit() const { return _firstByte & 0x20; } bool rsv3Bit() const { return _firstByte & 0x10; } bool isFinalFrame() const { return finBit(); } OpCode opCode() const { return (OpCode)(_firstByte & 0xF); } bool isControlFrame() const; quint32 maskKey() const { return _maskKey; } quint64 payloadLength() const { return _payloadLength; } const QByteArray &payload() const { return _payload; } bool isValid() const { return _valid; } void clear(); QByteArray toByteArray() const; private: enum ProcessingState { Empty = 0, HeaderParsed, MoreData, Completed, }; void setFinBit(bool fin); void setOpCode(OpCode opCode); void setFirstByte(quint8 byte); void setMaskKey(quint32 maskKey); void setPayloadLength(quint64 length); void setPayload(const QByteArray &payload); QByteArray &payload() { return _payload; } bool validate(); ProcessingState state() const { return _state; } void setState(ProcessingState state); quint8 _firstByte {0x80}; quint32 _maskKey {0}; quint64 _payloadLength {0}; QByteArray _payload; // unmasked data stored ProcessingState _state {Empty}; bool _valid {false}; friend class TAbstractWebSocket; friend class TWebSocket; friend class TEpollWebSocket; friend class TWebSocketController; }; #endif // TWEBSOCKETFRAME_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 COMPONENTS_SYNC_ENGINE_IMPL_DIRECTORY_UPDATE_HANDLER_H_ #define COMPONENTS_SYNC_ENGINE_IMPL_DIRECTORY_UPDATE_HANDLER_H_ #include <map> #include <memory> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "components/sync/base/model_type.h" #include "components/sync/base/syncer_error.h" #include "components/sync/engine_impl/process_updates_util.h" #include "components/sync/engine_impl/update_handler.h" namespace sync_pb { class DataTypeProgressMarker; } namespace syncer { class DataTypeDebugInfoEmitter; class ModelSafeWorker; class StatusController; namespace syncable { class Directory; } // This class represents the syncable::Directory's processes for requesting and // processing updates from the sync server. // // Each instance of this class represents a particular type in the // syncable::Directory. It can store and retreive that type's progress markers. // It can also process a set of received SyncEntities and store their data. class DirectoryUpdateHandler : public UpdateHandler { public: DirectoryUpdateHandler(syncable::Directory* dir, ModelType type, scoped_refptr<ModelSafeWorker> worker, DataTypeDebugInfoEmitter* debug_info_emitter); ~DirectoryUpdateHandler() override; // UpdateHandler implementation. bool IsInitialSyncEnded() const override; void GetDownloadProgress( sync_pb::DataTypeProgressMarker* progress_marker) const override; void GetDataTypeContext(sync_pb::DataTypeContext* context) const override; SyncerError ProcessGetUpdatesResponse( const sync_pb::DataTypeProgressMarker& progress_marker, const sync_pb::DataTypeContext& mutated_context, const SyncEntityList& applicable_updates, StatusController* status) override; void ApplyUpdates(StatusController* status) override; void PassiveApplyUpdates(StatusController* status) override; private: friend class DirectoryUpdateHandlerApplyUpdateTest; friend class DirectoryUpdateHandlerProcessUpdateTest; // Sometimes there is nothing to do, so we can return without doing anything. bool IsApplyUpdatesRequired(); // Called at the end of ApplyUpdates and PassiveApplyUpdates and performs // steps common to both (even when IsApplyUpdatesRequired has returned // false). void PostApplyUpdates(); // Processes the given SyncEntities and stores their data in the directory. // Their types must match this update handler's type. void UpdateSyncEntities(syncable::ModelNeutralWriteTransaction* trans, const SyncEntityList& applicable_updates, bool is_initial_sync, StatusController* status); // Expires entries according to GC directives. void ExpireEntriesIfNeeded( syncable::ModelNeutralWriteTransaction* trans, const sync_pb::DataTypeProgressMarker& progress_marker); // Stores the given progress marker in the directory. // Its type must match this update handler's type. void UpdateProgressMarker( const sync_pb::DataTypeProgressMarker& progress_marker); bool IsValidProgressMarker( const sync_pb::DataTypeProgressMarker& progress_marker) const; // Skips all checks and goes straight to applying the updates. SyncerError ApplyUpdatesImpl(StatusController* status); // Creates root node for the handled model type. void CreateTypeRoot(syncable::ModelNeutralWriteTransaction* trans); syncable::Directory* dir_; ModelType type_; scoped_refptr<ModelSafeWorker> worker_; DataTypeDebugInfoEmitter* debug_info_emitter_; // The version which directory already ran garbage collection against on. int64_t cached_gc_directive_version_; // The day which directory already ran garbage collection against on. base::Time cached_gc_directive_aged_out_day_; DISALLOW_COPY_AND_ASSIGN(DirectoryUpdateHandler); }; } // namespace syncer #endif // COMPONENTS_SYNC_ENGINE_IMPL_DIRECTORY_UPDATE_HANDLER_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 UI_VIEWS_ANIMATION_TEST_SQUARE_INK_DROP_ANIMATION_TEST_API_H_ #define UI_VIEWS_ANIMATION_TEST_SQUARE_INK_DROP_ANIMATION_TEST_API_H_ #include <vector> #include "base/macros.h" #include "ui/gfx/geometry/size.h" #include "ui/views/animation/square_ink_drop_animation.h" #include "ui/views/animation/test/ink_drop_animation_test_api.h" namespace ui { class LayerAnimator; } // namespace ui namespace views { namespace test { // Test API to provide internal access to a SquareInkDropAnimation. class SquareInkDropAnimationTestApi : public InkDropAnimationTestApi { public: // Make the private typedefs accessible. using InkDropTransforms = SquareInkDropAnimation::InkDropTransforms; using PaintedShape = SquareInkDropAnimation::PaintedShape; explicit SquareInkDropAnimationTestApi( SquareInkDropAnimation* ink_drop_animation); ~SquareInkDropAnimationTestApi() override; // Wrapper functions to the wrapped InkDropAnimation: void CalculateCircleTransforms(const gfx::Size& size, InkDropTransforms* transforms_out) const; void CalculateRectTransforms(const gfx::Size& size, float corner_radius, InkDropTransforms* transforms_out) const; // InkDropAnimationTestApi: float GetCurrentOpacity() const override; protected: // InkDropAnimationTestApi: std::vector<ui::LayerAnimator*> GetLayerAnimators() override; private: SquareInkDropAnimation* ink_drop_animation() { return static_cast<const SquareInkDropAnimationTestApi*>(this) ->ink_drop_animation(); } SquareInkDropAnimation* ink_drop_animation() const { return static_cast<SquareInkDropAnimation*>( InkDropAnimationTestApi::ink_drop_animation()); } DISALLOW_COPY_AND_ASSIGN(SquareInkDropAnimationTestApi); }; } // namespace test } // namespace views #endif // UI_VIEWS_ANIMATION_TEST_SQUARE_INK_DROP_ANIMATION_TEST_API_H_
/* $NetBSD: psychovar.h,v 1.3.4.1 2000/07/18 16:23:20 mrg Exp $ */ /* * Copyright (c) 1999, 2000 Matthew R. Green * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _SPARC64_DEV_PSYCHOVAR_H_ #define _SPARC64_DEV_PSYCHOVAR_H_ /* per real PCI bus info */ struct psycho_softc; struct psycho_pbm { /* link to mum */ struct psycho_softc *pp_sc; /* * note that the sabre really only has one ranges property, * used for both simba a and simba b (but the ranges for * real psychos are the same for PCI A and PCI B anyway). */ struct psycho_registers *pp_regs; struct psycho_ranges *pp_range; struct psycho_interrupt_map *pp_intmap; struct psycho_interrupt_map_mask pp_intmapmask; /* counts of above */ int pp_nregs; int pp_nrange; int pp_nintmap; /* chipset tag for this instance */ pci_chipset_tag_t pp_pc; /* our tags */ bus_space_tag_t pp_memt; bus_space_tag_t pp_iot; bus_dma_tag_t pp_dmat; int pp_bus; int pp_flags; /* and pointers into the psycho regs for our bits */ struct pci_ctl *pp_pcictl; }; /* * per-PCI bus on mainbus softc structure; one for sabre, or two * per pair of psycho's. */ struct psycho_softc { struct device sc_dev; /* * one sabre has two simba's. psycho's are separately attached, * with the `other' psycho_pbm allocated at the first's attach. */ struct psycho_pbm *sc_sabre; struct psycho_pbm *__sc_psycho_this; struct psycho_pbm *__sc_psycho_other; #define sc_simba_a __sc_psycho_this #define sc_simba_b __sc_psycho_other #define sc_psycho_this __sc_psycho_this #define sc_psycho_other __sc_psycho_other /* * PSYCHO register. we record the base physical address of these * also as it is the base of the entire PSYCHO */ struct psychoreg *sc_regs; paddr_t sc_basepaddr; /* Interrupt Group Number for this device */ int sc_ign; /* our tags (from parent) */ bus_space_tag_t sc_bustag; bus_dma_tag_t sc_dmatag; /* config space */ bus_space_tag_t sc_configtag; bus_space_handle_t sc_configaddr; int sc_clockfreq; int sc_node; /* prom node */ int sc_mode; /* (whatareya?) */ #define PSYCHO_MODE_SABRE 1 /* i'm a sabre (yob) */ #define PSYCHO_MODE_PSYCHO 2 /* i'm a psycho (w*nker) */ struct iommu_state *sc_is; }; /* config space is per-psycho. mem/io/dma are per-pci bus */ bus_dma_tag_t psycho_alloc_dma_tag __P((struct psycho_pbm *)); bus_space_tag_t psycho_alloc_bus_tag __P((struct psycho_pbm *, int)); #define psycho_alloc_config_tag(pp) psycho_alloc_bus_tag((pp), PCI_CONFIG_BUS_SPACE) #define psycho_alloc_mem_tag(pp) psycho_alloc_bus_tag((pp), PCI_MEMORY_BUS_SPACE) #define psycho_alloc_io_tag(pp) psycho_alloc_bus_tag((pp), PCI_IO_BUS_SPACE) int psycho_intr_map __P((pcitag_t, int, int, pci_intr_handle_t *)); #endif /* _SPARC64_DEV_PSYCHOVAR_H_ */
/* * Copyright 2013 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "hash.h" #include "pwfile.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> static cb_mutex_t uhash_lock; static user_db_entry_t **user_ht; static const unsigned int n_uht_buckets = 12289; void pwfile_init(void) { cb_mutex_initialize(&uhash_lock); } void pwfile_term(void) { free_user_ht(); cb_mutex_destroy(&uhash_lock); } static void kill_whitey(char *s) { for (size_t i = strlen(s) - 1; i > 0 && isspace(s[i]); i--) { s[i] = '\0'; } } static int u_hash_key(const char *u) { uint32_t h = hash(u, strlen(u), 0) % n_uht_buckets; cb_assert(h < n_uht_buckets); return h; } static const char *get_isasl_filename(void) { return getenv("ISASL_PWFILE"); } void free_user_ht(void) { if (user_ht) { for (unsigned int i = 0; i < n_uht_buckets; i++) { while (user_ht[i]) { user_db_entry_t *e = user_ht[i]; user_db_entry_t *n = e->next; free(e->username); free(e->password); free(e->config); free(e); user_ht[i] = n; } } free(user_ht); user_ht = NULL; } } static void store_pw(user_db_entry_t **ht, const char *u, const char *p, const char *cfg) { user_db_entry_t *e; int h; cb_assert(ht); cb_assert(u); cb_assert(p); e = calloc(1, sizeof(user_db_entry_t)); cb_assert(e); e->username = strdup(u); cb_assert(e->username); e->password = strdup(p); cb_assert(e->password); e->config = cfg ? strdup(cfg) : NULL; cb_assert(!cfg || e->config); h = u_hash_key(u); e->next = ht[h]; ht[h] = e; } char *find_pw(const char *u, char **cfg) { int h; user_db_entry_t *e; cb_assert(u); cb_assert(user_ht); cb_mutex_enter(&uhash_lock); h = u_hash_key(u); e = user_ht[h]; while (e && strcmp(e->username, u) != 0) { e = e->next; } if (e != NULL) { *cfg = e->config; cb_mutex_exit(&uhash_lock); return e->password; } else { cb_mutex_exit(&uhash_lock); return NULL; } } cbsasl_error_t load_user_db(void) { user_db_entry_t **new_ut; FILE *sfile; char up[128]; const char *filename = get_isasl_filename(); if (!filename) { return CBSASL_OK; } sfile = fopen(filename, "r"); if (!sfile) { return CBSASL_FAIL; } new_ut = calloc(n_uht_buckets, sizeof(user_db_entry_t *)); if (!new_ut) { fclose(sfile); return CBSASL_NOMEM; } /* File has lines that are newline terminated. */ /* File may have comment lines that must being with '#'. */ /* Lines should look like... */ /* <NAME><whitespace><PASSWORD><whitespace><CONFIG><optional_whitespace> */ /* */ while (fgets(up, sizeof(up), sfile)) { if (up[0] != '#') { char *uname = up, *p = up, *cfg = NULL; kill_whitey(up); while (*p && !isspace(p[0])) { p++; } /* If p is pointing at a NUL, there's nothing after the username. */ if (p[0] != '\0') { p[0] = '\0'; p++; } /* p now points to the first character after the (now) */ /* null-terminated username. */ while (*p && isspace(*p)) { p++; } /* p now points to the first non-whitespace character */ /* after the above */ cfg = p; if (cfg[0] != '\0') { /* move cfg past the password */ while (*cfg && !isspace(cfg[0])) { cfg++; } if (cfg[0] != '\0') { cfg[0] = '\0'; cfg++; /* Skip whitespace */ while (*cfg && isspace(cfg[0])) { cfg++; } } } store_pw(new_ut, uname, p, cfg); } } fclose(sfile); /* if (settings.verbose) { settings.extensions.logger->log(EXTENSION_LOG_INFO, NULL, "Loaded isasl db from %s\n", filename); } */ /* Replace the current configuration with the new one */ cb_mutex_enter(&uhash_lock); free_user_ht(); user_ht = new_ut; cb_mutex_exit(&uhash_lock); return CBSASL_OK; }