hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25100432cfdd65a321093262b0d3b6f4e6c21c71 | 239 | h | C | ocjqday02/ARC/Dog.h | MinghuiGao/C- | 7994bbd74a89ef224a65c7f08af022c8ff47dbe2 | [
"Apache-2.0"
] | 11 | 2016-01-07T15:17:37.000Z | 2016-11-16T16:43:23.000Z | ocjqday02/ARC/Dog.h | MinghuiGao/C- | 7994bbd74a89ef224a65c7f08af022c8ff47dbe2 | [
"Apache-2.0"
] | null | null | null | ocjqday02/ARC/Dog.h | MinghuiGao/C- | 7994bbd74a89ef224a65c7f08af022c8ff47dbe2 | [
"Apache-2.0"
] | 2 | 2019-06-18T14:43:04.000Z | 2019-12-22T09:15:53.000Z | //
// Dog.h
// ocjqday02
//
// Created by 高明辉 on 16/1/25.
// Copyright © 2016年 itcast. All rights reserved.
//
#import <Foundation/Foundation.h>
@class Person;
@interface Dog : NSObject
@property (nonatomic,weak) Person *owner;
@end
| 15.933333 | 50 | 0.677824 |
d7b4e4d50ec7a1d6bb060d09f480e23a145cc54f | 449 | h | C | RecordSDKUI/MediaEdit/MediaPicker/View/Album/MDNewAssetAlbumCell.h | sunfei/MMVideoSDKDemo | 24c3a77436a4199979f78501014b074ce74943c4 | [
"MIT"
] | 1 | 2019-03-26T12:02:45.000Z | 2019-03-26T12:02:45.000Z | RecordSDKUI/MediaEdit/MediaPicker/View/Album/MDNewAssetAlbumCell.h | sunfei/MMVideoSDKDemo | 24c3a77436a4199979f78501014b074ce74943c4 | [
"MIT"
] | 2 | 2019-10-20T04:34:44.000Z | 2020-12-02T06:57:13.000Z | RecordSDKUI/MediaEdit/MediaPicker/View/Album/MDNewAssetAlbumCell.h | sunfei/MMVideoSDKDemo | 24c3a77436a4199979f78501014b074ce74943c4 | [
"MIT"
] | 6 | 2019-04-11T03:59:09.000Z | 2021-06-08T07:04:39.000Z | //
// MDNewAssetAlbumCell.h
// MDChat
//
// Created by YZK on 2018/10/26.
// Copyright © 2018 sdk.com. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MDAssetAlbumItem.h"
FOUNDATION_EXPORT const CGFloat kMDNewAssetAlbumCellHeight;
NS_ASSUME_NONNULL_BEGIN
@interface MDNewAssetAlbumCell : UITableViewCell
@property (nonatomic, strong) MDAssetAlbumItem *item;
- (void)bindModel:(MDAssetAlbumItem *)item;
@end
NS_ASSUME_NONNULL_END
| 18.708333 | 59 | 0.768374 |
0c8e800887ccd3562ae5dec943fecc9d909d9bd4 | 531 | h | C | branches/rev71/File/ShaderLoader.h | mtheory101/hybrid-rendering-thesis | 314a200726450e27982e1a95eec3702ad5c9d320 | [
"MIT"
] | 1 | 2019-06-14T20:22:21.000Z | 2019-06-14T20:22:21.000Z | branches/rev71/File/ShaderLoader.h | ptrefall/hybrid-rendering-thesis | 72be3b3f6b457741737cd83cefb90f2bdbaa46dc | [
"MIT"
] | null | null | null | branches/rev71/File/ShaderLoader.h | ptrefall/hybrid-rendering-thesis | 72be3b3f6b457741737cd83cefb90f2bdbaa46dc | [
"MIT"
] | null | null | null | #pragma once
#include "../Render/Shader.h"
#include <memory>
#include <string>
namespace File
{
class ShaderLoader;
typedef std::shared_ptr<ShaderLoader> ShaderLoaderPtr;
class ShaderLoader
{
public:
ShaderLoader(const std::string &base_dir);
Render::ShaderPtr load(const std::string &vs_filename, const std::string &gs_filename = std::string(), const std::string &fs_filename = std::string());
private:
std::string loadContents(const std::string &filename);
std::string base_dir;
};
}
| 21.24 | 154 | 0.694915 |
1044c85c0f164437f4d49765d473a362807e5cef | 6,341 | h | C | components/render/opengl_driver/sources/shared/platform.h | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/render/opengl_driver/sources/shared/platform.h | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/render/opengl_driver/sources/shared/platform.h | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #ifndef RENDER_GL_DRIVER_PLATFORM_HEADER
#define RENDER_GL_DRIVER_PLATFORM_HEADER
#include <stl/auto_ptr.h>
#include <render/low_level/driver.h>
#include <shared/library.h>
namespace render
{
namespace low_level
{
namespace opengl
{
///////////////////////////////////////////////////////////////////////////////////////////////////
///Цепочка обмена
///////////////////////////////////////////////////////////////////////////////////////////////////
class SwapChain : public ISwapChain
{
public:
///////////////////////////////////////////////////////////////////////////////////////////////////
///Конструктор / деструктор
///////////////////////////////////////////////////////////////////////////////////////////////////
SwapChain ();
~SwapChain ();
///////////////////////////////////////////////////////////////////////////////////////////////////
///Обновление размера (должно вызываться системой верхнего уровня при изменении размеров окна)
///////////////////////////////////////////////////////////////////////////////////////////////////
void SetSize (unsigned int width, unsigned int height);
///////////////////////////////////////////////////////////////////////////////////////////////////
///Подписка на событие изменения размера
///////////////////////////////////////////////////////////////////////////////////////////////////
typedef xtl::function<void (unsigned int width, unsigned int height)> SizeChangeHandler;
xtl::connection RegisterSizeChangeHandler (const SizeChangeHandler& handler);
private:
SwapChain (const SwapChain&); //no impl
SwapChain& operator = (const SwapChain&); //no impl
private:
struct Impl;
Impl* impl;
};
///////////////////////////////////////////////////////////////////////////////////////////////////
///Интерфейс фрейм-буфера цепочки обмена
///////////////////////////////////////////////////////////////////////////////////////////////////
class ISwapChainFrameBuffer
{
public:
///////////////////////////////////////////////////////////////////////////////////////////////////
///Получение идентификатора буфера
///////////////////////////////////////////////////////////////////////////////////////////////////
virtual unsigned int GetFrameBufferId () = 0;
protected:
virtual ~ISwapChainFrameBuffer () {}
};
///////////////////////////////////////////////////////////////////////////////////////////////////
///Интерфейс слушателя событий контекста
///////////////////////////////////////////////////////////////////////////////////////////////////
class IContextListener
{
public:
///////////////////////////////////////////////////////////////////////////////////////////////////
///События контекста
///////////////////////////////////////////////////////////////////////////////////////////////////
virtual void OnSetCurrent () {} //контекст стал текущим
virtual void OnLostCurrent () {} //контекст перестал быть текущим
protected:
virtual ~IContextListener () {}
};
///////////////////////////////////////////////////////////////////////////////////////////////////
///Интерфейс контекста OpenGL
///////////////////////////////////////////////////////////////////////////////////////////////////
class IContext: virtual public IObject
{
public:
///////////////////////////////////////////////////////////////////////////////////////////////////
///Установка текущего контектса
///////////////////////////////////////////////////////////////////////////////////////////////////
virtual void MakeCurrent (ISwapChain* swap_chain) = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////
///Проверка совместимости цепочки обмена с контекстом
///////////////////////////////////////////////////////////////////////////////////////////////////
virtual bool IsCompatible (ISwapChain* swap_chain) = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////
///Получение библиотеки OpenGL
///////////////////////////////////////////////////////////////////////////////////////////////////
virtual ILibrary& GetLibrary () = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////
///Подписка на события контекста
///////////////////////////////////////////////////////////////////////////////////////////////////
virtual void AttachListener (IContextListener*) = 0;
virtual void DetachListener (IContextListener*) = 0;
};
///////////////////////////////////////////////////////////////////////////////////////////////////
///Менеджер платформы
///////////////////////////////////////////////////////////////////////////////////////////////////
class PlatformManager
{
public:
///////////////////////////////////////////////////////////////////////////////////////////////////
///Создание адаптера
///////////////////////////////////////////////////////////////////////////////////////////////////
static IAdapter* CreateAdapter (const char* name, const char* path, const char* init_string);
///////////////////////////////////////////////////////////////////////////////////////////////////
///Перечисление адаптеров "по умолчанию"
///////////////////////////////////////////////////////////////////////////////////////////////////
static void EnumDefaultAdapters (const xtl::function<void (IAdapter*)>&);
///////////////////////////////////////////////////////////////////////////////////////////////////
///Создание цепочки обмена и PBuffer-а
///////////////////////////////////////////////////////////////////////////////////////////////////
static ISwapChain* CreateSwapChain (size_t adapters_count, IAdapter** adapters, const SwapChainDesc& desc);
static ISwapChain* CreatePBuffer (ISwapChain* source_chain, const SwapChainDesc* pbuffer_desc = 0);
///////////////////////////////////////////////////////////////////////////////////////////////////
///Создание контекста
///////////////////////////////////////////////////////////////////////////////////////////////////
static IContext* CreateContext (ISwapChain* swap_chain);
};
}
}
}
#endif
| 43.431507 | 112 | 0.302003 |
09ad67f76ba5e6bf6242b21e1f6b3adac259f4fe | 362 | h | C | vendor/include/BiometricKit/BiometricKitIdentity.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | 7 | 2021-01-16T15:14:51.000Z | 2021-09-17T12:10:31.000Z | vendor/include/BiometricKit/BiometricKitIdentity.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | null | null | null | vendor/include/BiometricKit/BiometricKitIdentity.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | 1 | 2020-07-26T02:16:06.000Z | 2020-07-26T02:16:06.000Z | @interface BiometricKitIdentity : NSObject <NSSecureCoding, NSCopying>
@property (nonatomic, retain) NSUUID * uuid;
@property (nonatomic, assign) NSUInteger userID;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, assign) NSInteger attribute;
@property (nonatomic, assign) NSInteger entity;
@property (nonatomic, copy) NSString * name;
@end
| 32.909091 | 70 | 0.781768 |
7cf319b3ff3d5f5d1f8940a3b15f497f9ef75125 | 1,684 | c | C | PART1-C-PROGRAMMING/check_bst.c | mohitesh07/software-engineering-assignment | 45b2d18728fc529dc4baae044babebebefb67053 | [
"MIT"
] | null | null | null | PART1-C-PROGRAMMING/check_bst.c | mohitesh07/software-engineering-assignment | 45b2d18728fc529dc4baae044babebebefb67053 | [
"MIT"
] | null | null | null | PART1-C-PROGRAMMING/check_bst.c | mohitesh07/software-engineering-assignment | 45b2d18728fc529dc4baae044babebebefb67053 | [
"MIT"
] | null | null | null | ///////////////// SOFTWARE ENGINEERING ASSIGNMENT ////////////////////////////////////////////////////
// Write a C program which takes a binary tree as input and checks it is a binary search tree //
// @author: Mohitesh Ch Agarwal //
// Copyright Mohitesh Ch Agarwal | All rights reserved //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include<stdio.h>
#include<stdlib.h>
int is_bst = 1;
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* create_node(int data){
struct node* Node = (struct node*)malloc(sizeof(struct node));
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return Node;
}
void check_bst(struct node* root){
if(!root)
return;
if(root->left)
if(root->data<root->left->data){
is_bst = -1;
return;
}
if(root->right)
if(root->data>root->right->data){
is_bst = -1;
return;
}
check_bst(root->left);
check_bst(root->right);
}
int main(){
struct node* root = create_node(10);
root->left = create_node(9);
root->right = create_node(11);
root->left->left = create_node(8);
check_bst(root);
if(is_bst==1)
printf("It is a Binary-Search-Tree\n");
else
printf("It is not a Binary Search Tree\n");
return 0; // returns 0 to the Operating System
} | 29.54386 | 126 | 0.449525 |
e5795b8d15efb6079cdd2ac1761a545bb3c4a029 | 3,215 | h | C | include/mtt/render/CommandQueue/CommandQueue.h | AluminiumRat/mtt | 3052f8ad0ffabead05a1033e1d714a61e77d0aa8 | [
"MIT"
] | null | null | null | include/mtt/render/CommandQueue/CommandQueue.h | AluminiumRat/mtt | 3052f8ad0ffabead05a1033e1d714a61e77d0aa8 | [
"MIT"
] | null | null | null | include/mtt/render/CommandQueue/CommandQueue.h | AluminiumRat/mtt | 3052f8ad0ffabead05a1033e1d714a61e77d0aa8 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <vector>
#include <vulkan/vulkan.h>
#include <mtt/render/CommandQueue/CommandPool.h>
#include <mtt/render/CommandQueue/CommandProducer.h>
#include <mtt/render/CommandQueue/Fence.h>
#include <mtt/render/CommandQueue/QueueFamilyInfo.h>
#include <mtt/render/Ref.h>
namespace mtt
{
class LogicalDevice;
class Semaphore;
class CommandQueue
{
private:
friend class LogicalDevice;
CommandQueue( LogicalDevice& device,
uint32_t familyIndex,
uint32_t queueIndex,
size_t poolsNumber);
public:
CommandQueue(const CommandQueue&) = delete;
CommandQueue& operator = (const CommandQueue&) = delete;
~CommandQueue();
inline VkQueue handle() const;
inline LogicalDevice& device();
inline const LogicalDevice& device() const;
inline const QueueFamilyInfo& familyInfo() const;
std::unique_ptr<CommandProducer> startCommands();
/// You should use producer that was created from this queue
/// Returns fence to wait end of command execution.
Fence& submit(std::unique_ptr<CommandProducer> commandProducer,
Semaphore* startSemaphore,
VkPipelineStageFlags dstStageMask,
Semaphore* endSignalSemaphore);
void submit(CommandBuffer& buffer,
Semaphore* startSemaphore,
VkPipelineStageFlags dstStageMask,
Semaphore* endSignalSemaphore,
Fence* endSignalFence);
void waitIdle() const;
inline void lockResource(Lockable& resource);
private:
class Producer : public CommandProducer
{
public:
Producer( CommandPool& pool,
CommandQueue& queue,
size_t poolIndex);
Producer(const Producer&) = delete;
Producer& operator = (const Producer&) = delete;
virtual ~Producer();
CommandQueue& _queue;
size_t _poolIndex;
};
private:
void _cleanup() noexcept;
void _unlockPool(size_t _poolIndex) noexcept;
private:
VkQueue _handle;
LogicalDevice& _device;
QueueFamilyInfo _familyInfo;
struct PoolRecord
{
bool _available;
std::unique_ptr<CommandPool> pool;
Ref<Fence> fence;
PoolRecord() = default;
PoolRecord(const PoolRecord&) = delete;
PoolRecord(PoolRecord&&) noexcept = default;
PoolRecord& operator = (const PoolRecord&) = default;
PoolRecord& operator = (PoolRecord&&) noexcept = default;
~PoolRecord() = default;
};
using Pools = std::vector<PoolRecord>;
Pools _pools;
size_t _nextPoolIndex;
using Resources = std::vector<LockableReference>;
Resources _attachedResources;
};
inline VkQueue CommandQueue::handle() const
{
return _handle;
}
inline LogicalDevice& CommandQueue::device()
{
return _device;
}
inline const LogicalDevice& CommandQueue::device() const
{
return _device;
}
inline const QueueFamilyInfo& CommandQueue::familyInfo() const
{
return _familyInfo;
}
inline void CommandQueue::lockResource(Lockable& resource)
{
_attachedResources.push_back(LockableReference(&resource));
}
} | 25.117188 | 67 | 0.666252 |
4c0395d05aa49797e87cd5392acebd35fc817ab3 | 30,550 | h | C | contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/AppKit.framework/Versions/C/Headers/NSWorkspace.h | Amity-Network/amity | 3e57379f01af4ca851079c8e469fbda7c8165b47 | [
"MIT"
] | null | null | null | contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/AppKit.framework/Versions/C/Headers/NSWorkspace.h | Amity-Network/amity | 3e57379f01af4ca851079c8e469fbda7c8165b47 | [
"MIT"
] | null | null | null | contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/AppKit.framework/Versions/C/Headers/NSWorkspace.h | Amity-Network/amity | 3e57379f01af4ca851079c8e469fbda7c8165b47 | [
"MIT"
] | null | null | null | /*
NSWorkspace.h
Application Kit
Copyright (c) 1994-2015, Apple Inc.
All rights reserved.
*/
#import <Foundation/NSObject.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSGeometry.h>
#import <Foundation/NSAppleEventDescriptor.h>
#import <AppKit/AppKitDefines.h>
NS_ASSUME_NONNULL_BEGIN
@class NSColor, NSError, NSImage, NSView, NSNotificationCenter, NSURL, NSScreen, NSRunningApplication;
typedef NS_OPTIONS(NSUInteger, NSWorkspaceLaunchOptions) {
NSWorkspaceLaunchAndPrint = 0x00000002,
NSWorkspaceLaunchWithErrorPresentation = 0x00000040,
NSWorkspaceLaunchInhibitingBackgroundOnly = 0x00000080,
NSWorkspaceLaunchWithoutAddingToRecents = 0x00000100,
NSWorkspaceLaunchWithoutActivation = 0x00000200,
NSWorkspaceLaunchAsync = 0x00010000,
NSWorkspaceLaunchNewInstance = 0x00080000,
NSWorkspaceLaunchAndHide = 0x00100000,
NSWorkspaceLaunchAndHideOthers = 0x00200000,
NSWorkspaceLaunchDefault = NSWorkspaceLaunchAsync,
// Deprecated options
NSWorkspaceLaunchAllowingClassicStartup NS_ENUM_DEPRECATED_MAC(10_3, 10_11, "The Classic environment is no longer supported.") = 0x00020000,
NSWorkspaceLaunchPreferringClassic NS_ENUM_DEPRECATED_MAC(10_3, 10_11, "The Classic environment is no longer supported.") = 0x00040000,
};
typedef NS_OPTIONS(NSUInteger, NSWorkspaceIconCreationOptions) {
NSExcludeQuickDrawElementsIconCreationOption = 1 << 1,
NSExclude10_4ElementsIconCreationOption = 1 << 2
};
@interface NSWorkspace : NSObject {
/*All instance variables are private*/
@private
NSNotificationCenter *notificationCenter;
#if ! __LP64__
int deviceStatusCount;
int applicationStatusCount;
id _reservedWorkspace1;
#endif
}
/* Get the shared instance of NSWorkspace. This method will create an instance of NSWorkspace if it has not been created yet. You should not attempt to instantiate instances of NSWorkspace yourself, and you should not attempt to subclass NSWorkspace. */
+ (NSWorkspace *)sharedWorkspace;
/* Returns the NSNotificationCenter for this NSWorkspace. All notifications in this header file must be registered on this notification center. If you register on other notification centers, you will not receive the notifications. */
@property (readonly, strong) NSNotificationCenter *notificationCenter;
/* Open a file at some path. If you use the variant without the withApplication: parameter, or if you pass nil for this parameter, the default application is used. The appName parameter may be a full path to an application, or just the application's name, with or without the .app extension. If you pass YES for andDeactivate:, or call a variant without this parameter, the calling app is deactivated before the new app is launched, so that the new app may come to the foreground unless the user switches to another application in the interim. Passing YES for andDeactivate: is generally recommended.
*/
- (BOOL)openFile:(NSString *)fullPath;
- (BOOL)openFile:(NSString *)fullPath withApplication:(nullable NSString *)appName;
- (BOOL)openFile:(NSString *)fullPath withApplication:(nullable NSString *)appName andDeactivate:(BOOL)flag;
/* Open a URL, using the default handler for the URL's scheme. */
- (BOOL)openURL:(NSURL *)url;
/* Launches an application. The appName may be a full path to the app, or the name alone, with or without the .app extension. */
- (BOOL)launchApplication:(NSString *)appName;
/* Launches the app at the given URL. If the app is successfully launched, a reference to the new running app is returned. If the app is already running, and NSWorkspaceLaunchNewInstance is not specified, then a reference to the existing app is returned. If the app could not be launched, nil is returned and an NSError is returned by reference.
The configuration dictionary can be used to pass additional options to the app. Possible keys are listed later in this file (search for NSWorkspaceLaunchConfiguration). The configuration dictionary may be empty, in which case default behavior applies.
*/
- (nullable NSRunningApplication *)launchApplicationAtURL:(NSURL *)url options:(NSWorkspaceLaunchOptions)options configuration:(NSDictionary<NSString *, id> *)configuration error:(NSError **)error NS_AVAILABLE_MAC(10_6);
/* Opens the given URL in an the application that claims it. An NSRunningApplication instance representing the app that the URL was opened in is returned. If the app could not be launched or no app claims the URL, nil is returned and an NSError is returned by reference. The options and configuration parameters are the same as those in launchApplicationAtURL:options:configuration:error:. */
- (nullable NSRunningApplication *)openURL:(NSURL *)url options:(NSWorkspaceLaunchOptions)options configuration:(NSDictionary<NSString *, id> *)configuration error:(NSError **)error NS_AVAILABLE_MAC(10_10);
/* Opens the given URLs in the application at applicationURL. Returns the NSRunningApplication for the app the URLs were opened in. If the app could not be launched, nil is returned and an NSError is returned by reference. The options and configuration parameters are the same as those in launchApplicationAtURL:options:configuration:error:. */
- (nullable NSRunningApplication *)openURLs:(NSArray<NSURL *> *)urls withApplicationAtURL:(NSURL *)applicationURL options:(NSWorkspaceLaunchOptions)options configuration:(NSDictionary<NSString *, id> *)configuration error:(NSError **)error NS_AVAILABLE_MAC(10_10);
/* This currently does the same thing as launchApplication:. Its use is discouraged. */
- (BOOL)launchApplication:(NSString *)appName showIcon:(BOOL)showIcon autolaunch:(BOOL)autolaunch;
/* Get the full path for a given application name, which may or may not have the .app extension. This indicates the application that will be opened by methods such as launchApplication:. If the application could not be found, returns nil. */
- (nullable NSString *)fullPathForApplication:(NSString *)appName;
/* Activate the Finder and open a window selecting the file at the given path. If fullPath is nil, this will instead open the directory specified by rootFullPath, and not select any file. If rootFullPath is the empty string (@""), the file is selected in the main viewer. Otherwise, a new file viewer is opened.
*/
- (BOOL)selectFile:(nullable NSString *)fullPath inFileViewerRootedAtPath:(NSString *)rootFullPath;
/* Activate the Finder, and open one or more windows selecting the files at the given fileURLs. */
- (void)activateFileViewerSelectingURLs:(NSArray<NSURL *> *)fileURLs NS_AVAILABLE_MAC(10_6);
/* Displays a Spotlight search results window in Finder for the specified query string. Finder becomes the active application, if possible. The user can further refine the search via the Finder UI. Returns YES if the communication with Finder was successful.
*/
- (BOOL)showSearchResultsForQueryString:(NSString *)queryString NS_AVAILABLE_MAC(10_6);
/* noteFileSystemChanged: informs listeners of a filesystem change, using the FNNotifyByPath() API. As the FNNotify API has been supplanted by the FSEvents API, the use of this method is discouraged. */
- (void)noteFileSystemChanged:(NSString *)path;
/* Get, by reference, the name of the app used to open a file at the given path, and the type of the file. The type of the file will either be a filename extension or an HFS type encoded with NSFileTypeForHFSTypeCode(). Both strings are returned autoreleased. The method returns YES if successful, NO if not. */
- (BOOL)getInfoForFile:(NSString *)fullPath application:(NSString * __nullable* __nullable)appName type:(NSString * __nullable* __nullable)type;
/* Indicates whether a given directory is a package. Returns YES if the file is a package, NO if not, or if the file does not exist or the operation otherwise failed. A file may be a package because its filename extension indicates so (for example, .framework) or because it has the package bit set. */
- (BOOL)isFilePackageAtPath:(NSString *)fullPath;
/* Returns the icon for a file at a given path, or a generic icon if the operation fails. */
- (NSImage *)iconForFile:(NSString *)fullPath;
/* Returns the icon for a group of files at the given paths. */
- (nullable NSImage *)iconForFiles:(NSArray<NSString *> *)fullPaths;
/* Get the icon for a given file type. The file type may be a filename extension, or a HFS code encoded via NSFileTypeForHFSTypeCode, or a Universal Type Identifier (UTI). Returns a default icon if the operation fails. */
- (NSImage *)iconForFileType:(NSString *)fileType;
/* If image is not nil, this sets a custom icon for the file at the given path. If image is nil, this removes any custom icon at the given path. Returns YES if successful, NO if not. */
- (BOOL)setIcon:(nullable NSImage *)image forFile:(NSString *)fullPath options:(NSWorkspaceIconCreationOptions)options;
/* Get the array of file labels as NSStrings. The file label index for a particular file is available as a property on the URL. You may listen for NSWorkspaceDidChangeFileLabelsNotification to be notified when these change. */
@property (readonly, copy) NSArray<NSString *> *fileLabels NS_AVAILABLE_MAC(10_6);
/* Get the corresponding array of file label colors. This array has the same number of elements as fileLabels, and the color at a given index corresponds to the label at the same index . You may listen for NSWorkspaceDidChangeFileLabelsNotification to be notified when these change. */
@property (readonly, copy) NSArray<NSColor *> *fileLabelColors NS_AVAILABLE_MAC(10_6);
/* Asynchronous file operations. recycleURLs moves the given files to the trash, and duplicateURLs duplicates them in the same manner as the Finder. If completionHandler is not nil, it will be called when the operation is complete, on the same dispatch queue that was used for the recycleURLs: call. Within the completion handler, the newURLs dictionary parameter maps the given URLs to their new URLs in the Trash. Files that could not be moved to the Trash will not be present in the dictionary.
If the operation succeeded for every file, the error parameter will be nil. If it failed for one or more files, the error parameter will describe the overall result of the operation in a manner suitable for presentation to the user. The completionHandler may be nil if you are not interested in the results.
These methods may show a progress indicator, or other user interface elements, at AppKit's discretion. In Mac OS X 10.6, these methods require that the main run loop be run in a common mode.
*/
- (void)recycleURLs:(NSArray<NSURL *> *)URLs completionHandler:(void (^ __nullable)(NSDictionary<NSURL *, NSURL *> * newURLs, NSError * __nullable error))handler NS_AVAILABLE_MAC(10_6);
- (void)duplicateURLs:(NSArray<NSURL *> *)URLs completionHandler:(void (^ __nullable)(NSDictionary<NSURL *, NSURL *> * newURLs, NSError * __nullable error))handler NS_AVAILABLE_MAC(10_6);
/* Gets information about the filesystem. fullPath is the path to any file or directory on the filesystem, including the filesystem's mount point. The returned values have the following significance:
- isRemovable: whether the filesystem is backed by removable media, such as a CD or floppy disk.
- isWritable: whether the filesystem can be written to
- isUnmountable: whether the filesystem can be unmounted.
- description: typically the type of the volume or the name of the filesystem
- the file system type, for example, 'hfs'
*/
- (BOOL)getFileSystemInfoForPath:(NSString *)fullPath isRemovable:(nullable BOOL *)removableFlag isWritable:(nullable BOOL *)writableFlag isUnmountable:(nullable BOOL *)unmountableFlag description:(NSString * __nullable * __nullable)description type:(NSString * __nullable * __nullable)fileSystemType;
/* Attempt to eject the volume mounted at the given path. Returns YES if successful, NO if not, for example, if the volume is not ejectable. */
- (BOOL)unmountAndEjectDeviceAtPath:(NSString *)path;
/* Same as unmountAndEjectDeviceAtPath, except it takes an NSURL and returns an NSError. */
- (BOOL)unmountAndEjectDeviceAtURL:(NSURL *)url error:(NSError **)error NS_AVAILABLE_MAC(10_6);
/* extendPowerOffBy: is currently not implemented. Do not use it. */
- (NSInteger)extendPowerOffBy:(NSInteger)requested;
/* Attempt to hide all other applications. */
- (void)hideOtherApplications;
/* Get the URL for the application with the given identifier. This uses various heuristics in case multiple apps have the same bundle ID. This returns nil if no app has the bundle identifier.*/
- (nullable NSURL *)URLForApplicationWithBundleIdentifier:(NSString *)bundleIdentifier NS_AVAILABLE_MAC(10_6);
/* Returns the URL to the default application that would be used to open the given URL, as if the file were double clicked in the Finder (for file URLs). This returns nil if no app can open it, or if the file does not exist. */
- (nullable NSURL *)URLForApplicationToOpenURL:(NSURL *)url NS_AVAILABLE_MAC(10_6);
/* Get the path for the application with the given identifier. This uses various heuristics in case multiple apps have the same bundle ID. */
- (nullable NSString *)absolutePathForAppBundleWithIdentifier:(NSString *)bundleIdentifier;
/* The following methods launch an app with the given bundle identifier. The descriptor describes the first AppleEvent to be sent to the process. The launchIdentifier is currently of no significance.
If the application is already running, and NSWorkspaceLaunchNewInstance is not specified in the options, then the descriptor is delivered to the currently running app, and YES is returned.
*/
- (BOOL)launchAppWithBundleIdentifier:(NSString *)bundleIdentifier options:(NSWorkspaceLaunchOptions)options additionalEventParamDescriptor:(nullable NSAppleEventDescriptor *)descriptor launchIdentifier:(NSNumber * __nullable * __nullable)identifier;
- (BOOL)openURLs:(NSArray<NSURL *> *)urls withAppBundleIdentifier:(nullable NSString *)bundleIdentifier options:(NSWorkspaceLaunchOptions)options additionalEventParamDescriptor:(nullable NSAppleEventDescriptor *)descriptor launchIdentifiers:(NSArray<NSNumber *> * __nullable * __nullable)identifiers;
/* Gets the frontmost application, which is the application that will receive key events. This is observable through KVO. */
@property (nullable, readonly, strong) NSRunningApplication *frontmostApplication NS_AVAILABLE_MAC(10_7);
/* Gets the menu bar owning application, which is the application that currently owns and draws the menu bar. This is observable through KVO. */
@property (nullable, readonly, strong) NSRunningApplication *menuBarOwningApplication NS_AVAILABLE_MAC(10_7);
/* Given an absolute file path, return the uniform type identifier (UTI) of the file, if one can be determined. Otherwise, return nil after setting *outError to an NSError that encapsulates the reason why the file's type could not be determined. If the file at the end of the path is a symbolic link the type of the symbolic link will be returned.
You can invoke this method to get the UTI of an existing file. To get the UTI of a URL, use the NSURLTypeIdentifierKey file system resource key from NSURL.h.
*/
- (nullable NSString *)typeOfFile:(NSString *)absoluteFilePath error:(NSError **)outError NS_AVAILABLE_MAC(10_5);
/* Given a UTI, return a string that describes the document type and is fit to present to the user, or nil for failure.
You can invoke this method to get the name of a type that must be shown to the user, in an alert about your application's inability to handle the type, for instance.
*/
- (nullable NSString *)localizedDescriptionForType:(NSString *)typeName NS_AVAILABLE_MAC(10_5);
/* Given a UTI, return the best file name extension to use when creating a file of that type, or nil for failure.
You can invoke this method when your application has only the base name of a file that's being written and it has to append a file name extension so that the file's type can be reliably identified later on.
*/
- (nullable NSString *)preferredFilenameExtensionForType:(NSString *)typeName NS_AVAILABLE_MAC(10_5);
/* Given a file name extension and a UTI, return YES if the file name extension is a valid tag for the identified type, NO otherwise.
You can invoke this method when your application needs to check if a file name extension can be used to reliably identify the type later on. For example, NSSavePanel uses this method to validate any extension that the user types in the panel's file name field.
*/
- (BOOL)filenameExtension:(NSString *)filenameExtension isValidForType:(NSString *)typeName NS_AVAILABLE_MAC(10_5);
/* Given two UTIs, return YES if the first "conforms to" to the second in the uniform type identifier hierarchy, NO otherwise. This method will always return YES if the two strings are equal, so you can also use it with other kinds of type name, including those declared in CFBundleTypeName Info.plist entries in apps that don't take advantage of the support for UTIs that was added to Cocoa in Mac OS 10.5.
You can invoke this method when your application must determine whether it can handle a file of a known type, returned by -typeOfFile:error: for instance.
Use this method instead of merely comparing UTIs for equality.
*/
- (BOOL)type:(NSString *)firstTypeName conformsToType:(NSString *)secondTypeName NS_AVAILABLE_MAC(10_5);
@end
/* Desktop images */
@interface NSWorkspace (NSDesktopImages)
/* Sets the desktop image for the given screen to the image at the given URL. The URL must be a file URL and may not be nil. The options dictionary may contain any of the NSWorkspaceDesktopImage keys, which control how the image is scaled on the screen. This returns YES if the image was successfully set; otherwise, NO is returned and an error is returned by reference.
You should normally NOT present a user interface for picking the options. Instead, just choose appropriate defaults and allow the user to adjust them in the System Preference Pane.
*/
- (BOOL)setDesktopImageURL:(NSURL *)url forScreen:(NSScreen *)screen options:(NSDictionary<NSString *, id> *)options error:(NSError **)error NS_AVAILABLE_MAC(10_6);
/* Returns the URL for the desktop image for the given screen.
*/
- (nullable NSURL *)desktopImageURLForScreen:(NSScreen *)screen NS_AVAILABLE_MAC(10_6);
/* Returns the options dictionary for the desktop image for the given screen.
*/
- (nullable NSDictionary<NSString *, id> *)desktopImageOptionsForScreen:(NSScreen *)screen NS_AVAILABLE_MAC(10_6);
@end
/* The following keys may be specified or returned in the options dictionary for setDesktopImageURL:forScreen:options:error: and desktopImageURLForScreen:options:. */
/* The value is an NSNumber containing an NSImageScaling. If this is not specified, NSImageScaleProportionallyUpOrDown is used. Note: NSImageScaleProportionallyDown is not currently supported.
*/
APPKIT_EXTERN NSString * const NSWorkspaceDesktopImageScalingKey NS_AVAILABLE_MAC(10_6);
/* The value is an NSNumber containing a BOOL, which affects the interpretation of Proportional scaling types. A NO value will make the image fully visible, but there may be empty space on the sides or top and bottom. A YES value will cause the image to fill the entire screen, but the image may be clipped. If this is not specified, NO is assumed. Non-proportional scaling types ignore this value.
*/
APPKIT_EXTERN NSString * const NSWorkspaceDesktopImageAllowClippingKey NS_AVAILABLE_MAC(10_6);
/* The value is an NSColor, which is used to fill any empty space around the image. If not specified, a default value is used. Currently, only colors that use or can be converted to use NSCalibratedRGBColorSpace are supported, and any alpha value is ignored.
*/
APPKIT_EXTERN NSString * const NSWorkspaceDesktopImageFillColorKey NS_AVAILABLE_MAC(10_6);
/* Application notifications */
/* In Mac OS X 10.6 and later, all application notifications have the following key in their userInfo. Its value is an instance of NSRunningApplication, representing the affected app.
*/
APPKIT_EXTERN NSString * const NSWorkspaceApplicationKey NS_AVAILABLE_MAC(10_6);
APPKIT_EXTERN NSString * NSWorkspaceWillLaunchApplicationNotification; // see above
APPKIT_EXTERN NSString * NSWorkspaceDidLaunchApplicationNotification; // see above
APPKIT_EXTERN NSString * NSWorkspaceDidTerminateApplicationNotification; // see above
APPKIT_EXTERN NSString * const NSWorkspaceDidHideApplicationNotification NS_AVAILABLE_MAC(10_6);
APPKIT_EXTERN NSString * const NSWorkspaceDidUnhideApplicationNotification NS_AVAILABLE_MAC(10_6);
APPKIT_EXTERN NSString * const NSWorkspaceDidActivateApplicationNotification NS_AVAILABLE_MAC(10_6);
APPKIT_EXTERN NSString * const NSWorkspaceDidDeactivateApplicationNotification NS_AVAILABLE_MAC(10_6);
/* Volume notifications */
/* In Mac OS X 10.6 and later, the following keys are available in the userInfo of NSWorkspaceDidMountNotification, NSWorkspaceWillUnmountNotification, NSWorkspaceDidUnmountNotification, and NSWorkspaceDidRenameVolumeNotification.
*/
APPKIT_EXTERN NSString * const NSWorkspaceVolumeLocalizedNameKey NS_AVAILABLE_MAC(10_6); //NSString containing the user-visible name of the volume
APPKIT_EXTERN NSString * const NSWorkspaceVolumeURLKey NS_AVAILABLE_MAC(10_6); //NSURL containing the mount path of the volume
/* The following additional keys are provided in the userInfo of NSWorkspaceDidRenameVolumeNotification.
*/
APPKIT_EXTERN NSString * const NSWorkspaceVolumeOldLocalizedNameKey NS_AVAILABLE_MAC(10_6); //NSString containing the old user-visible name of the volume
APPKIT_EXTERN NSString * const NSWorkspaceVolumeOldURLKey NS_AVAILABLE_MAC(10_6); //NSURL containing the old mount path of the volume
APPKIT_EXTERN NSString * NSWorkspaceDidMountNotification; // @"NSDevicePath"
APPKIT_EXTERN NSString * NSWorkspaceDidUnmountNotification; // @"NSDevicePath"
APPKIT_EXTERN NSString * NSWorkspaceWillUnmountNotification; // @"NSDevicePath"
/* NSWorkspaceDidRenameVolumeNotification is posted when a volume changes its name and/or mount path. These typically change simultaneously, in which case only one notification is posted.
*/
APPKIT_EXTERN NSString * const NSWorkspaceDidRenameVolumeNotification NS_AVAILABLE_MAC(10_6);
/* Power notifications */
APPKIT_EXTERN NSString * const NSWorkspaceWillPowerOffNotification;
APPKIT_EXTERN NSString * NSWorkspaceWillSleepNotification;
APPKIT_EXTERN NSString * NSWorkspaceDidWakeNotification;
APPKIT_EXTERN NSString * const NSWorkspaceScreensDidSleepNotification NS_AVAILABLE_MAC(10_6);
APPKIT_EXTERN NSString * const NSWorkspaceScreensDidWakeNotification NS_AVAILABLE_MAC(10_6);
/* Session notifications */
APPKIT_EXTERN NSString * NSWorkspaceSessionDidBecomeActiveNotification;
APPKIT_EXTERN NSString * NSWorkspaceSessionDidResignActiveNotification;
/* Miscellaneous notifications */
/* NSWorkspaceDidChangeFileLabelsNotification is posted when the user changes a file label color name or the color itself. The notification object is always NSWorkspace, and there is no user info.
*/
APPKIT_EXTERN NSString * const NSWorkspaceDidChangeFileLabelsNotification NS_AVAILABLE_MAC(10_6);
APPKIT_EXTERN NSString * const NSWorkspaceActiveSpaceDidChangeNotification NS_AVAILABLE_MAC(10_6);
/* The following keys can be used in the configuration dictionary of the launchApplicationAtURL:, openURL:, and openURL:withApplicationAtURL: methods. Each key is optional, and if omitted, default behavior is applied. */
APPKIT_EXTERN NSString * const NSWorkspaceLaunchConfigurationAppleEvent NS_AVAILABLE_MAC(10_6); //the first NSAppleEventDescriptor to send to the new app. If an instance of the app is already running, this is sent to that app.
APPKIT_EXTERN NSString * const NSWorkspaceLaunchConfigurationArguments NS_AVAILABLE_MAC(10_6); //an NSArray of NSStrings, passed to the new app in the argv parameter. Ignored if a new instance is not launched.
APPKIT_EXTERN NSString * const NSWorkspaceLaunchConfigurationEnvironment NS_AVAILABLE_MAC(10_6); //an NSDictionary, mapping NSStrings to NSStrings, containing environment variables to set for the new app. Ignored if a new instance is not launched.
APPKIT_EXTERN NSString * const NSWorkspaceLaunchConfigurationArchitecture NS_AVAILABLE_MAC(10_6); //an NSNumber containing an NSBundleExecutableArchitecture (from NSBundle.h). Ignored if a new instance is not launched.
/* Everything remaining in this header is deprecated and should not be used. */
@interface NSWorkspace (NSDeprecated)
- (BOOL)openTempFile:(NSString *)fullPath NS_DEPRECATED_MAC(10_0, 10_6);
- (void)findApplications NS_DEPRECATED_MAC(10_0, 10_6);
- (void)noteUserDefaultsChanged NS_DEPRECATED_MAC(10_0, 10_6);
- (void)slideImage:(NSImage *)image from:(NSPoint)fromPoint to:(NSPoint)toPoint NS_DEPRECATED_MAC(10_0, 10_6);
- (void)checkForRemovableMedia NS_DEPRECATED_MAC(10_0, 10_6);
- (void)noteFileSystemChanged NS_DEPRECATED_MAC(10_0, 10_6);
- (BOOL)fileSystemChanged NS_DEPRECATED_MAC(10_0, 10_6);
- (BOOL)userDefaultsChanged NS_DEPRECATED_MAC(10_0, 10_6);
- (nullable NSArray *)mountNewRemovableMedia NS_DEPRECATED_MAC(10_0, 10_6);
/* The following methods return information about an application as a dictionary containing as many of the following keys as are available:
NSApplicationPath (the full path to the application, as a string)
NSApplicationName (the application's name, as a string)
NSApplicationBundleIdentifier (the application's bundle identifier, as a string)
NSApplicationProcessIdentifier (the application's process id, as an NSNumber)
NSApplicationProcessSerialNumberHigh (the high long of the PSN, as an NSNumber)
NSApplicationProcessSerialNumberLow (the low long of the PSN, as an NSNumber)
The same information will now be provided in the userInfo of the NSWorkspace notifications for application launch and termination.
*/
/* Get an NSDictionary representing the currently frontmost app, with the above keys. The NSWorkspaceApplicationKey is also provided. On Mac OS X 10.7 and later, use -frontmostApplication. */
- (nullable NSDictionary *)activeApplication NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSWorkspace frontmostApplication] instead.");
/* Get the mount paths of all volumes. Despite its name, this method returns URLs for network volumes as well. On Mac OS X 10.6 and later, use -[NSFileManager mountedVolumeURLsIncludingResourceValuesForKeys:options:] instead. */
- (nullable NSArray *)mountedLocalVolumePaths NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSFileManager mountedVolumeURLsIncludingResourceValuesForKeys:options:] instead.");
/* Get the mount paths of all volumes backed by removable media, such as DVDs. On Mac OS X 10.6 and later, use -[NSFileManager mountedVolumeURLsIncludingResourceValuesForKeys:options:] instead. */
- (nullable NSArray *)mountedRemovableMedia NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSFileManager mountedVolumeURLsIncludingResourceValuesForKeys:options:] instead.");
/* Gets an array of NSDictionaries with the above keys. In addition, the NSWorkspaceApplicationKey is provided, and vends an instance of NSRunningApplication. This method does not return applications that are UIElement or BackgroundOnly. To access the entire list of running applications, use the -[NSWorkspace runningApplications] method, declared in NSRunningApplication.h.
*/
- (nullable NSArray *)launchedApplications NS_DEPRECATED_MAC(10_0, 10_7, "Use -[NSWorkspace runningApplications] instead.");
/* Open a file with an animation. This currently does the same thing as openFile: and its use is discouraged. */
- (BOOL)openFile:(NSString *)fullPath fromImage:(nullable NSImage *)anImage at:(NSPoint)point inView:(nullable NSView *)aView NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSWorkspace openURL:] instead.");
/* Performs the given file operation, blocking until complete. source should be the directory containing the file(s). For operations that require a destination, such as Move and Copy, destination should be the destination directory; otherwise it should be nil. files is an array of file names that are in the source directory.
A value is returned by reference in the tag parameter, either 0 for success, or -1 for failure. tag may be NULL.
*/
- (BOOL)performFileOperation:(NSString *)operation source:(NSString *)source destination:(NSString *)destination files:(NSArray *)files tag:(nullable NSInteger *)tag NS_DEPRECATED_MAC(10_0, 10_11);
@end
/* Possible values for operation in performFileOperation:...
*/
APPKIT_EXTERN NSString * NSWorkspaceMoveOperation NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSFileManager moveItemAtURL:toURL:error:] instead.");
APPKIT_EXTERN NSString * NSWorkspaceCopyOperation NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSFileManager copyItemAtURL:toURL:error:] instead.");
APPKIT_EXTERN NSString * NSWorkspaceLinkOperation NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSFileManager linkItemAtURL:toURL:error:] instead.");
APPKIT_EXTERN NSString * NSWorkspaceCompressOperation NS_DEPRECATED_MAC(10_0, 10_11, "This operation is unimplemented.");
APPKIT_EXTERN NSString * NSWorkspaceDecompressOperation NS_DEPRECATED_MAC(10_0, 10_11, "This operation is unimplemented.");
APPKIT_EXTERN NSString * NSWorkspaceEncryptOperation NS_DEPRECATED_MAC(10_0, 10_11, "This operation is unimplemented.");
APPKIT_EXTERN NSString * NSWorkspaceDecryptOperation NS_DEPRECATED_MAC(10_0, 10_11, "This operation is unimplemented.");
APPKIT_EXTERN NSString * NSWorkspaceDestroyOperation NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSFileManager removeItemAtURL:error:] instead.");
APPKIT_EXTERN NSString * NSWorkspaceRecycleOperation NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSWorkspace recycleURLs:completionHandler:] instead.");
APPKIT_EXTERN NSString * NSWorkspaceDuplicateOperation NS_DEPRECATED_MAC(10_0, 10_11, "Use -[NSWorkspace duplicateURLs:completionHandler:] instead.");
APPKIT_EXTERN NSString * NSWorkspaceDidPerformFileOperationNotification NS_DEPRECATED_MAC(10_0, 10_11); // @"NSOperationNumber"
APPKIT_EXTERN NSString * NSPlainFileType NS_DEPRECATED_MAC(10_0, 10_6);
APPKIT_EXTERN NSString * NSDirectoryFileType NS_DEPRECATED_MAC(10_0, 10_6);
APPKIT_EXTERN NSString * NSApplicationFileType NS_DEPRECATED_MAC(10_0, 10_6);
APPKIT_EXTERN NSString * NSFilesystemFileType NS_DEPRECATED_MAC(10_0, 10_6);
APPKIT_EXTERN NSString * NSShellCommandFileType NS_DEPRECATED_MAC(10_0, 10_6);
NS_ASSUME_NONNULL_END
| 78.534704 | 604 | 0.798756 |
492b30e99341f080225c9da8cc5006cbc272e15f | 529 | h | C | inc/localconf.h | mmoskal/codal-itsybitsy-m4 | b2ac8a7fe11c76ec083b9abbafa8f01db07a7735 | [
"MIT"
] | null | null | null | inc/localconf.h | mmoskal/codal-itsybitsy-m4 | b2ac8a7fe11c76ec083b9abbafa8f01db07a7735 | [
"MIT"
] | null | null | null | inc/localconf.h | mmoskal/codal-itsybitsy-m4 | b2ac8a7fe11c76ec083b9abbafa8f01db07a7735 | [
"MIT"
] | null | null | null | #pragma once
#define USE_FULL_ASSERT 1
#define USB_MAX_PKT_SIZE 64
#define BOOTLOADER_START_ADDR 0x00000000
#define BOOTLOADER_END_ADDR 0x00004000
#define APP_START_ADDR 0x00004000
#define UF2_INFO_ADDR (const char*)(*(uint32_t*)(BOOTLOADER_END_ADDR - (16 * 4) + (4 * 4)))
#define USB_EP_FLAG_NO_AUTO_ZLP 0x01
#define DEVICE_USB_ENDPOINTS 6
#define CODAL_CPU_MHZ 120
#define SAMD_PIN_ARRAY 1
#define PROTOTYPE_SERCOM_SPI_M_SYNC SERCOM0
#define PROTOTYPE_SERCOM_I2CM_SYNC SERCOM1
#define PROTOTYPE_SERCOM_USART_ASYNC SERCOM2
| 26.45 | 91 | 0.833648 |
c6be47917ee628d58864f72830ed904ada24f5f8 | 904 | h | C | include/l0-infra/array/mixin/min/ScatteredArrayMinElem.h | godsme/object-array | c3c9a707b14d265271f169ed91bb533b05d7ec17 | [
"Apache-2.0"
] | 9 | 2021-06-25T11:06:07.000Z | 2021-09-23T09:47:58.000Z | include/l0-infra/array/mixin/min/ScatteredArrayMinElem.h | godsme/object-array | c3c9a707b14d265271f169ed91bb533b05d7ec17 | [
"Apache-2.0"
] | 2 | 2021-08-17T17:35:42.000Z | 2021-11-27T02:00:18.000Z | include/l0-infra/array/mixin/min/ScatteredArrayMinElem.h | godsme/object-array | c3c9a707b14d265271f169ed91bb533b05d7ec17 | [
"Apache-2.0"
] | 1 | 2021-08-17T17:05:19.000Z | 2021-08-17T17:05:19.000Z | //
// Created by Darwin Yuan on 2021/7/12.
//
#ifndef OBJECT_ARRAY_2_A7513A8874C7477684F692C04A28E6B5
#define OBJECT_ARRAY_2_A7513A8874C7477684F692C04A28E6B5
#include <l0-infra/array/concept/Less.h>
namespace mixin {
template<typename T>
struct ScatteredArrayMinElem : T {
using typename T::SizeType;
using typename T::ObjectType;
using typename T::Maybe;
public:
template<__lEsS_cOnCePt(LESS)>
auto MinElemIndex(LESS &&less) const -> Maybe {
return T::Unsafe_RangeScopeMinElemIndex(0, T::MAX_SIZE, T::GetScope(), std::forward<LESS>(less));
}
template<__lEsS_cOnCePt(LESS)>
auto MinElem(LESS &&less) const -> ObjectType const* {
return T::Unsafe_RangeScopeMinElem(0, T::MAX_SIZE, T::GetScope(), std::forward<LESS>(less));
}
};
}
#endif //OBJECT_ARRAY_2_A7513A8874C7477684F692C04A28E6B5
| 29.16129 | 109 | 0.678097 |
7303168403f558e6e3c79c686db853b8a7af0ac1 | 333 | h | C | cpp/diamond_square_asm.h | sauldenova/parallel-terrain-generation | bf2ff382c51b970be6d4b6259d55f227b438ee54 | [
"Apache-2.0"
] | null | null | null | cpp/diamond_square_asm.h | sauldenova/parallel-terrain-generation | bf2ff382c51b970be6d4b6259d55f227b438ee54 | [
"Apache-2.0"
] | null | null | null | cpp/diamond_square_asm.h | sauldenova/parallel-terrain-generation | bf2ff382c51b970be6d4b6259d55f227b438ee54 | [
"Apache-2.0"
] | null | null | null | /**
* Apache License Version 2.0
*
* Saul de Nova Caballero
*
* Diamond Square header for the assembly file
*/
namespace TerrainGeneration {
extern "C" {
extern void calculateValues(
float *results,
int32_t size,
float *values,
float *randoms,
float *factors);
}
}
| 17.526316 | 46 | 0.582583 |
42f46a624111ea899599bd0aa1baea9beeab2bc2 | 2,822 | h | C | WeChat-Headers/WAAppTaskLoaderContext.h | RockerHX/FishChat | d47f3228dd1f05a7547300330adfe45a09e0175d | [
"MIT"
] | 678 | 2017-11-17T08:33:19.000Z | 2022-03-26T10:40:20.000Z | WeChat-Headers/WAAppTaskLoaderContext.h | 274077005/FishChat | 5432fbc1a9be0c886b2d5800e28118c11df1f0c0 | [
"MIT"
] | 22 | 2019-04-16T05:51:53.000Z | 2021-11-08T06:18:45.000Z | WeChat-Headers/WAAppTaskLoaderContext.h | 274077005/FishChat | 5432fbc1a9be0c886b2d5800e28118c11df1f0c0 | [
"MIT"
] | 170 | 2018-06-10T07:59:20.000Z | 2022-03-22T16:19:33.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class CContact, NSDictionary, NSString, UINavigationController, WACacheVersionChecker, WALoadingInfoData, WALoadingViewController, WAPermissionHandler, WAWebViewController;
@interface WAAppTaskLoaderContext : NSObject
{
_Bool _isPopParent;
_Bool _isPopAllParent;
CContact *_contact;
UINavigationController *_weakNavigationController;
WALoadingViewController *_weakLoadingViewController;
WAPermissionHandler *_permissionHandler;
NSString *_relativeURL;
NSDictionary *_dicFirstExtraInfo;
NSDictionary *_dicChildExtraInfo;
WAWebViewController *_parentWebView;
WALoadingInfoData *_loadingInfo;
NSString *_appID;
WACacheVersionChecker *_cacheVersionChecker;
id <WAAppTaskLoaderContextDelegate> _contextDelegate;
WAWebViewController *_webView;
CDUnknownBlockType _enterAnimationCallback;
}
@property(copy, nonatomic) CDUnknownBlockType enterAnimationCallback; // @synthesize enterAnimationCallback=_enterAnimationCallback;
@property(retain, nonatomic) WAWebViewController *webView; // @synthesize webView=_webView;
@property(nonatomic) __weak id <WAAppTaskLoaderContextDelegate> contextDelegate; // @synthesize contextDelegate=_contextDelegate;
@property(retain, nonatomic) WACacheVersionChecker *cacheVersionChecker; // @synthesize cacheVersionChecker=_cacheVersionChecker;
@property(retain, nonatomic) NSString *appID; // @synthesize appID=_appID;
@property(retain, nonatomic) WALoadingInfoData *loadingInfo; // @synthesize loadingInfo=_loadingInfo;
@property(nonatomic) _Bool isPopAllParent; // @synthesize isPopAllParent=_isPopAllParent;
@property(nonatomic) _Bool isPopParent; // @synthesize isPopParent=_isPopParent;
@property(retain, nonatomic) WAWebViewController *parentWebView; // @synthesize parentWebView=_parentWebView;
@property(retain, nonatomic) NSDictionary *dicChildExtraInfo; // @synthesize dicChildExtraInfo=_dicChildExtraInfo;
@property(retain, nonatomic) NSDictionary *dicFirstExtraInfo; // @synthesize dicFirstExtraInfo=_dicFirstExtraInfo;
@property(retain, nonatomic) NSString *relativeURL; // @synthesize relativeURL=_relativeURL;
@property(retain, nonatomic) WAPermissionHandler *permissionHandler; // @synthesize permissionHandler=_permissionHandler;
@property(nonatomic) __weak WALoadingViewController *weakLoadingViewController; // @synthesize weakLoadingViewController=_weakLoadingViewController;
@property(nonatomic) __weak UINavigationController *weakNavigationController; // @synthesize weakNavigationController=_weakNavigationController;
@property(retain, nonatomic) CContact *contact; // @synthesize contact=_contact;
- (void).cxx_destruct;
- (void)dealloc;
@end
| 54.269231 | 173 | 0.816797 |
1fb8b71c7fc83690e32e07af54e213fb1885a0ee | 3,375 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/APSocialGTDNativeDetailView.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/APSocialGTDNativeDetailView.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/APSocialGTDNativeDetailView.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-04-17T03:24:04.000Z | 2022-03-30T05:42:17.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <UIKit/UIView.h>
#import "APSocialGTDCardCellDelegate-Protocol.h"
#import "APSocialGTDDetailProtocol-Protocol.h"
#import "APSocialGTDHeaderViewDelegate-Protocol.h"
#import "UITableViewDataSource-Protocol.h"
#import "UITableViewDelegate-Protocol.h"
@class APSocialGTDHeaderView, AUTableView, GTDRecentContact, NSMutableArray, NSMutableDictionary, NSMutableSet, NSString;
@protocol APSocialMaskViewDelegate;
@interface APSocialGTDNativeDetailView : UIView <UITableViewDataSource, UITableViewDelegate, APSocialGTDCardCellDelegate, APSocialGTDHeaderViewDelegate, APSocialGTDDetailProtocol>
{
id <APSocialMaskViewDelegate> delegate;
AUTableView *_tableView;
APSocialGTDHeaderView *_headerView;
NSMutableArray *_cardsArray;
NSMutableDictionary *_gtdMessagesKeyedByMsgId;
GTDRecentContact *_recentContact;
NSString *_gtdID;
NSMutableSet *_exposureDatas;
}
@property(retain, nonatomic) NSMutableSet *exposureDatas; // @synthesize exposureDatas=_exposureDatas;
@property(copy, nonatomic) NSString *gtdID; // @synthesize gtdID=_gtdID;
@property(retain, nonatomic) GTDRecentContact *recentContact; // @synthesize recentContact=_recentContact;
@property(retain, nonatomic) NSMutableDictionary *gtdMessagesKeyedByMsgId; // @synthesize gtdMessagesKeyedByMsgId=_gtdMessagesKeyedByMsgId;
@property(retain, nonatomic) NSMutableArray *cardsArray; // @synthesize cardsArray=_cardsArray;
@property(retain, nonatomic) APSocialGTDHeaderView *headerView; // @synthesize headerView=_headerView;
@property(retain, nonatomic) AUTableView *tableView; // @synthesize tableView=_tableView;
@property(nonatomic) __weak id <APSocialMaskViewDelegate> delegate; // @synthesize delegate;
- (void).cxx_destruct;
- (void)markExposureCard:(id)arg1;
- (void)reloadData;
- (void)configCardsWithGroupID:(id)arg1;
- (void)configHeaderWithGroupID:(id)arg1;
- (void)reportExposureLogs;
- (void)configGroupID:(id)arg1;
- (void)dismissIfNeeded;
- (_Bool)noCards;
- (void)handleMessageAction:(id)arg1 withMsgId:(id)arg2 atIndex:(long long)arg3;
- (void)removeCardAtIndex:(long long)arg1;
- (void)deleteMessageById:(id)arg1;
- (void)updateMsgStatusToProcessed:(id)arg1;
- (void)cardCellDidClickMainButton:(id)arg1;
- (void)cardCellDidClickSecondaryButton:(id)arg1;
- (void)headerViewDidTouchInBackview:(id)arg1;
- (id)tableView:(id)arg1 viewForHeaderInSection:(long long)arg2;
- (id)tableView:(id)arg1 viewForFooterInSection:(long long)arg2;
- (double)tableView:(id)arg1 heightForFooterInSection:(long long)arg2;
- (double)tableView:(id)arg1 heightForHeaderInSection:(long long)arg2;
- (double)tableView:(id)arg1 heightForRowAtIndexPath:(id)arg2;
- (void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2;
- (id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2;
- (long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2;
- (long long)numberOfSectionsInTableView:(id)arg1;
- (void)layoutSubviews;
- (void)setupSubviews;
- (id)initWithFrame:(struct CGRect)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 45 | 179 | 0.795556 |
86343bc252ff651fb36e2efb1ea4d8c241f563c8 | 2,496 | h | C | SatteliteSimulator/third_party/MiniDNN/include/Utils/FindMax.h | avlo2000/DronMovementManager | 23f73a0824165e26f18717a917aeacc63853dc8f | [
"MIT"
] | 2 | 2019-06-24T14:09:14.000Z | 2019-06-24T14:09:16.000Z | SatteliteSimulator/third_party/MiniDNN/include/Utils/FindMax.h | avlo2000/DronMovementManager | 23f73a0824165e26f18717a917aeacc63853dc8f | [
"MIT"
] | null | null | null | SatteliteSimulator/third_party/MiniDNN/include/Utils/FindMax.h | avlo2000/DronMovementManager | 23f73a0824165e26f18717a917aeacc63853dc8f | [
"MIT"
] | 1 | 2019-02-09T13:23:28.000Z | 2019-02-09T13:23:28.000Z | #ifndef UTILS_FINDMAX_H_
#define UTILS_FINDMAX_H_
#include "../Config.h"
namespace MiniDNN {
namespace internal {
// Find the location of the maximum element in x[0], x[1], ..., x[n-1]
// Special cases for small n using recursive template
// N is assumed to be >= 2
template <int N>
inline int find_max(const Scalar* x)
{
const int loc = find_max<N - 1>(x);
return (x[N - 1] > x[loc]) ? (N - 1) : loc;
}
template <>
inline int find_max<2>(const Scalar* x)
{
return int(x[1] > x[0]);
}
// n is assumed be >= 2
inline int find_max(const Scalar* x, const int n)
{
switch(n)
{
case 2:
return find_max<2>(x);
case 3:
return find_max<3>(x);
case 4:
return find_max<4>(x);
case 5:
return find_max<5>(x);
}
int loc = find_max<6>(x);
for(int i = 6; i < n; i++)
{
loc = (x[i] > x[loc]) ? i : loc;
}
return loc;
}
// Find the maximum element in the block x[0:(nrow-1), 0:(ncol-1)]
// col_stride is the distance between x[0, 0] and x[0, 1]
// Special cases for small n
inline Scalar find_block_max(const Scalar* x, const int nrow, const int ncol, const int col_stride, int& loc)
{
// Max element in the first column
loc = find_max(x, nrow);
Scalar val = x[loc];
// 2nd column
x += col_stride;
int loc_next = find_max(x, nrow);
Scalar val_next = x[loc_next];
if(val_next > val) { loc = col_stride + loc_next; val = val_next; }
if(ncol == 2) return val;
// 3rd column
x += col_stride;
loc_next = find_max(x, nrow);
val_next = x[loc_next];
if(val_next > val) { loc = 2 * col_stride + loc_next; val = val_next; }
if(ncol == 3) return val;
// 4th column
x += col_stride;
loc_next = find_max(x, nrow);
val_next = x[loc_next];
if(val_next > val) { loc = 3 * col_stride + loc_next; val = val_next; }
if(ncol == 4) return val;
// 5th column
x += col_stride;
loc_next = find_max(x, nrow);
val_next = x[loc_next];
if(val_next > val) { loc = 4 * col_stride + loc_next; val = val_next; }
if(ncol == 5) return val;
// Other columns
for(int i = 5; i < ncol; i++)
{
x += col_stride;
loc_next = find_max(x, nrow);
val_next = x[loc_next];
if(val_next > val) { loc = i * col_stride + loc_next; val = val_next; }
}
return val;
}
} // namespace internal
} // namespace MiniDNN
#endif /* UTILS_FINDMAX_H_ */
| 23.327103 | 109 | 0.573718 |
9985e822c05d7a1034cb6ceab4614b4349091523 | 2,323 | c | C | openmp/libomptarget/test/unified_shared_memory/close_manual.c | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | openmp/libomptarget/test/unified_shared_memory/close_manual.c | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | openmp/libomptarget/test/unified_shared_memory/close_manual.c | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | // RUN: %libomptarget-compile-run-and-check-generic
// REQUIRES: unified_shared_memory
#include <omp.h>
#include <stdio.h>
// ---------------------------------------------------------------------------
// Various definitions copied from OpenMP RTL
extern void __tgt_register_requires(int64_t);
extern void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
void **args_base, void **args,
int64_t *arg_sizes, int64_t *arg_types);
extern void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
void **args_base, void **args,
int64_t *arg_sizes, int64_t *arg_types);
// End of definitions copied from OpenMP RTL.
// ---------------------------------------------------------------------------
#pragma omp requires unified_shared_memory
#define N 1024
int main(int argc, char *argv[]) {
int fails;
void *host_alloc = 0, *device_alloc = 0;
int *a = (int *)malloc(N * sizeof(int));
// Manual registration of requires flags for Clang versions
// that do not support requires.
__tgt_register_requires(8);
// Init
for (int i = 0; i < N; ++i) {
a[i] = 10;
}
host_alloc = &a[0];
// Dummy target region that ensures the runtime library is loaded when
// the target data begin/end functions are manually called below.
#pragma omp target
{}
// Manual calls
int device_id = omp_get_default_device();
int arg_num = 1;
void **args_base = (void **)&a;
void **args = (void **)&a;
int64_t arg_sizes[arg_num];
arg_sizes[0] = sizeof(int) * N;
int64_t arg_types[arg_num];
// Ox400 enables the CLOSE map type in the runtime:
// OMP_TGT_MAPTYPE_CLOSE = 0x400
// OMP_TGT_MAPTYPE_TO = 0x001
arg_types[0] = 0x400 | 0x001;
device_alloc = host_alloc;
__tgt_target_data_begin(device_id, arg_num, args_base, args, arg_sizes,
arg_types);
#pragma omp target data use_device_ptr(a)
{ device_alloc = a; }
__tgt_target_data_end(device_id, arg_num, args_base, args, arg_sizes,
arg_types);
// CHECK: a was copied to the device
if (device_alloc != host_alloc)
printf("a was copied to the device\n");
free(a);
// CHECK: Done!
printf("Done!\n");
return 0;
}
| 27.011628 | 78 | 0.600517 |
612c9e00a771853994dbf1339cde8af68521a5b1 | 4,320 | h | C | 3rdparty/blend2d/src/blend2d/random_p.h | Praxinos/ULIS3 | 98eb48293fdd3b45fcfe4b659d471572100d1623 | [
"RSA-MD"
] | 974 | 2018-10-28T05:40:57.000Z | 2022-03-31T16:38:36.000Z | 3rdparty/blend2d/src/blend2d/random_p.h | Praxinos/ULIS3 | 98eb48293fdd3b45fcfe4b659d471572100d1623 | [
"RSA-MD"
] | 128 | 2019-04-02T11:51:45.000Z | 2022-03-31T20:11:20.000Z | 3rdparty/blend2d/src/blend2d/random_p.h | Praxinos/ULIS3 | 98eb48293fdd3b45fcfe4b659d471572100d1623 | [
"RSA-MD"
] | 86 | 2019-04-02T10:29:10.000Z | 2022-03-14T10:58:08.000Z | // Blend2D - 2D Vector Graphics Powered by a JIT Compiler
//
// * Official Blend2D Home Page: https://blend2d.com
// * Official Github Repository: https://github.com/blend2d/blend2d
//
// Copyright (c) 2017-2020 The Blend2D Authors
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#ifndef BLEND2D_RANDOM_P_H_INCLUDED
#define BLEND2D_RANDOM_P_H_INCLUDED
#include "./random.h"
#include "./simd_p.h"
#include "./support_p.h"
//! \cond INTERNAL
//! \addtogroup blend2d_internal
//! \{
// ============================================================================
// [Constants]
// ============================================================================
//! Shift constants used by `BLRandom` implementation.
enum BLInternalRandomShifts : uint32_t {
// Constants suggested as `23/18/5`.
BL_RANDOM_STEP1_SHL = 23,
BL_RANDOM_STEP2_SHR = 18,
BL_RANDOM_STEP3_SHR = 5,
// Number of bits needed to shift right to extract mantissa.
BL_RANDOM_MANTISSA_SHIFT = 64 - 52
};
// ============================================================================
// [BLRandom - Inline]
// ============================================================================
namespace {
BL_INLINE void blRandomResetInline(BLRandom* self, uint64_t seed) noexcept {
// The number is arbitrary, it means nothing.
const uint64_t kZeroSeed = 0x1F0A2BE71D163FA0u;
// Generate the state data by using splitmix64.
for (uint32_t i = 0; i < 2; i++) {
seed += 0x9E3779B97F4A7C15u;
uint64_t x = seed;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9u;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBu;
x = (x ^ (x >> 31));
self->data[i] = x != 0 ? x : kZeroSeed;
}
}
BL_INLINE uint64_t blRandomNextUInt64Inline(BLRandom* self) noexcept {
uint64_t x = self->data[0];
uint64_t y = self->data[1];
x ^= x << BL_RANDOM_STEP1_SHL;
y ^= y >> BL_RANDOM_STEP3_SHR;
x ^= x >> BL_RANDOM_STEP2_SHR;
x ^= y;
self->data[0] = y;
self->data[1] = x;
return x + y;
}
BL_INLINE uint32_t blRandomNextUInt32Inline(BLRandom* self) noexcept {
return uint32_t(blRandomNextUInt64Inline(self) >> 32);
}
#ifdef BL_TARGET_OPT_SSE2
//! High-performance SIMD implementation. Better utilizes CPU in 32-bit mode
//! and it's a better candidate for `blRandomNextDouble()` in general on X86 as
//! it returns a SIMD register, which is easier to convert to `double` than GP.
BL_INLINE __m128i blRandomNextUInt64AsI128Inline(BLRandom* self) noexcept {
using namespace SIMD;
Vec128I x = v_load_i64(&self->data[0]);
Vec128I y = v_load_i64(&self->data[1]);
x = v_xor(x, v_sll_i64<BL_RANDOM_STEP1_SHL>(x));
y = v_xor(y, v_srl_i64<BL_RANDOM_STEP3_SHR>(y));
x = v_xor(x, v_srl_i64<BL_RANDOM_STEP2_SHR>(x));
x = v_xor(x, y);
v_store_i64(&self->data[0], y);
v_store_i64(&self->data[1], x);
return v_add_i64(x, y);
}
BL_INLINE double blRandomNextDoubleInline(BLRandom* self) noexcept {
using namespace SIMD;
Vec128I kExpMsk128 = _mm_set_epi32(0x3FF00000, 0, 0x3FF00000, 0);
Vec128I x = blRandomNextUInt64AsI128Inline(self);
Vec128I y = v_srl_i64<BL_RANDOM_MANTISSA_SHIFT>(x);
Vec128I z = v_or(y, kExpMsk128);
return v_get_f64(v_cast<Vec128D>(z)) - 1.0;
}
#else
BL_INLINE double blRandomNextDoubleInline(BLRandom* self) noexcept {
uint64_t kExpMsk = 0x3FF0000000000000u;
uint64_t u = (blRandomNextUInt64Inline(self) >> BL_RANDOM_MANTISSA_SHIFT) | kExpMsk;
return blBitCast<double>(u) - 1.0;
}
#endif
} // {anonymous}
//! \}
//! \endcond
#endif // BLEND2D_RANDOM_P_H_INCLUDED
| 32.481203 | 86 | 0.662037 |
e83acaf0da69c5a9905dbd2698d05685424a9ecf | 340 | h | C | Include/Observer.h | JanVijfhuizen/cECSar | 80725f4cff3078c47e4330c97c73a9ad165c7bcb | [
"MIT"
] | 3 | 2021-01-10T20:52:29.000Z | 2021-04-30T16:13:04.000Z | Include/Observer.h | JanVijfhuizen/cECSar | 80725f4cff3078c47e4330c97c73a9ad165c7bcb | [
"MIT"
] | null | null | null | Include/Observer.h | JanVijfhuizen/cECSar | 80725f4cff3078c47e4330c97c73a9ad165c7bcb | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
namespace jecs
{
class Cecsar;
struct Entity;
// Inherit from this to observe cecsar related events.
class Observer
{
friend Cecsar;
protected:
Observer();
private:
virtual void OnSpawn(Entity entity);
virtual void OnErase(Entity entity);
static std::vector<Observer*> _observers;
};
}
| 14.166667 | 55 | 0.717647 |
f922c188c579a5745fc907aa5883e60f9543468f | 324 | h | C | gen/windows/kin/eigen/include/Jws_VectorNav_to_RightToeBottom.h | UMich-BipedLab/Cassie_StateEstimation | d410ddce0ab342651f5ec0540c2867faf959a3a9 | [
"BSD-3-Clause"
] | 26 | 2018-07-20T15:20:19.000Z | 2022-03-14T07:12:12.000Z | gen/windows/kin/eigen/include/Jws_VectorNav_to_RightToeBottom.h | UMich-BipedLab/Cassie_StateEstimation | d410ddce0ab342651f5ec0540c2867faf959a3a9 | [
"BSD-3-Clause"
] | 2 | 2019-04-19T22:57:00.000Z | 2022-01-11T12:46:20.000Z | gen/windows/kin/eigen/include/Jws_VectorNav_to_RightToeBottom.h | UMich-BipedLab/Cassie_StateEstimation | d410ddce0ab342651f5ec0540c2867faf959a3a9 | [
"BSD-3-Clause"
] | 10 | 2018-07-29T08:05:14.000Z | 2022-02-03T08:48:11.000Z | /*
* Automatically Generated from Mathematica.
* Thu 23 May 2019 13:32:44 GMT-04:00
*/
#ifndef JWS_VECTORNAV_TO_RIGHTTOEBOTTOM_H
#define JWS_VECTORNAV_TO_RIGHTTOEBOTTOM_H
#include <Eigen/Dense>
Eigen::Matrix<double,3,14> Jws_VectorNav_to_RightToeBottom(const Eigen::Matrix<double,14,1> &var1);
#endif
| 21.6 | 100 | 0.746914 |
ba49980e16b16ac88718fdce8d297df94bf27f3b | 1,221 | c | C | Miscellaneous/Swap_With_Temp.c | Sannidhya127/C-Programs | 2abfd066f3657fd8bc65a209b4f83b6162f60e97 | [
"Unlicense"
] | 16 | 2018-08-26T18:45:37.000Z | 2021-09-04T08:00:09.000Z | Miscellaneous/Swap_With_Temp.c | Sannidhya127/C-Programs | 2abfd066f3657fd8bc65a209b4f83b6162f60e97 | [
"Unlicense"
] | 6 | 2018-09-26T05:15:23.000Z | 2020-10-19T06:10:41.000Z | Miscellaneous/Swap_With_Temp.c | Sannidhya127/C-Programs | 2abfd066f3657fd8bc65a209b4f83b6162f60e97 | [
"Unlicense"
] | 30 | 2018-08-28T16:00:32.000Z | 2022-01-09T04:21:03.000Z | /* a program to take two integer inputs from the user and then store them in two different
variables and then swap the values of both the variables using a third variable */
#include<stdio.h> // standard input output header file
#include<conio.h> //standard console input output header file
void main() // main function that returns a null value when printing the remainder
{ // opening block of the main function
int n1,n2,temp; // declaration of the variables
printf("Enter the value for 'n1' : "); // print 'Enter the value for 'n1' : ' call for a user to input the number
scanf("%d", &n1); // scan the value that is input by the user
printf("Enter the value for 'n2' : "); // print 'Enter the value for 'n2' : ' call for a user to input the number
scanf("%d", &n2); // scan the value that is input by the user
temp=n1; // storing the value of 'n1' in the variable named temp
n1=n2; // overwriting the value stored in 'n1' with the value of 'n2'
n2=temp; // overwriting the value stored in 'n2' with the value of 'temp' that is the value of n1
printf("Value of 'n1' is : %d\n",n1); // printing the value of n1
printf("Value of 'n2' is : %d\n",n2); // printing the value of n1
} // closing the main function
| 67.833333 | 114 | 0.703522 |
688eb988bc53f2c8be97da843a20994ea5986bf4 | 4,180 | h | C | bitbots_throw_engine/include/parameter/throw_type_parameter.h | 5reichar/bitbots_kick_engine | 0817f4f0a206de6f0f01a0cedfe201f62e677a11 | [
"BSD-3-Clause"
] | null | null | null | bitbots_throw_engine/include/parameter/throw_type_parameter.h | 5reichar/bitbots_kick_engine | 0817f4f0a206de6f0f01a0cedfe201f62e677a11 | [
"BSD-3-Clause"
] | null | null | null | bitbots_throw_engine/include/parameter/throw_type_parameter.h | 5reichar/bitbots_kick_engine | 0817f4f0a206de6f0f01a0cedfe201f62e677a11 | [
"BSD-3-Clause"
] | null | null | null | #ifndef BITBOTS_THROW_THROW_TYPE_PARAMETER_H
#define BITBOTS_THROW_THROW_TYPE_PARAMETER_H
#include <map>
#include <memory>
namespace bitbots_throw{
enum ThrowTypeId : uint8_t{
none = 0,
throw_1,
throw_2,
throw_3,
throw_4
};
enum ThrowMovementId : uint8_t {
testing = 0,
throw_movement,
throw_movement_position_only
};
enum ThrowCurveId : uint8_t {
beziercurve = 0,
linear_spline,
cubic_spline,
smooth_spline
};
struct ThrowType{
// Shall this kick be used
bool active_;
// Parameter to control if there are two or more throws that are eligable which shall be used first.
// the rule is: the throw with the lowest level will be used
int throw_priority_level_;
// The movement that should used
ThrowMovementId movement_;
// The curves that shall be used for the arms in this movement
ThrowCurveId arms_curve_;
// The curves that shall be used for the legs in this movement
ThrowCurveId legs_curve_;
// How many percent of the max_throw_velocity shall be used if possible
double throw_strength_;
// The Angle at which the ball shall thrown
double throw_angle_;
// The minimum distance this throw should be used for
double min_throw_distance_;
// The maximum distance this throw should be used for
double max_throw_distance_;
// The amount of deviation from the goal that is tolerated
double goal_tolerance_;
// The amount the reference velocity will be increased/decreased to find the fitting velocity
double velocity_adaptation_rate_;
// Duration of the full movement cycle (in s, > 0)
double movement_duration_;
// The share of the movement cycle dedicated to picking up the ball
double movement_share_pick_up_;
// The share of the movement cycle dedicated to prepare the throwing the ball
double movement_share_preparation_;
// The share of the movement cycle dedicated to throwing the ball
double movement_share_throw_;
// The share of the movement cycle dedicated to motion after throwing the ball
double movement_share_conclusion_;
// The amount of time to move the arms away from the ball
double movement_offset_move_arms_away_from_ball_;
////// Constructor
ThrowType(bool active
,int throw_priority_level
,ThrowMovementId movement
,ThrowCurveId arms_curve
,ThrowCurveId legs_curve
,double min_throw_distance
,double max_throw_distance
,double throw_strength
,double throw_angle
,double goal_tolerance
,double velocity_adaptation_rate
,double movement_duration
,double movement_share_pick_up
,double movement_share_preparation
,double movement_share_throw
,double movement_share_conclusion
,double movement_offset_move_arms_away_from_ball
)
:active_{active}
,throw_priority_level_{throw_priority_level}
,movement_{movement}
,arms_curve_{arms_curve}
,legs_curve_{legs_curve}
,throw_strength_{throw_strength}
,throw_angle_{throw_angle}
,min_throw_distance_{min_throw_distance}
,max_throw_distance_{max_throw_distance}
,goal_tolerance_{goal_tolerance}
,velocity_adaptation_rate_{velocity_adaptation_rate}
,movement_duration_(movement_duration)
,movement_share_pick_up_{movement_share_pick_up}
,movement_share_preparation_{movement_share_preparation}
,movement_share_throw_{movement_share_throw}
,movement_share_conclusion_{movement_share_conclusion}
,movement_offset_move_arms_away_from_ball_{movement_offset_move_arms_away_from_ball}{
}
};
} //bitbots_throw
#endif //BITBOTS_THROW_THROW_TYPE_PARAMETER_H | 40.192308 | 102 | 0.663397 |
d53cb554493628d76ef14666c529022aa8cf738b | 3,519 | h | C | code/Brain/CGPBrain/CGPBrain.h | cliff-bohm/Fragmentation_Replication_Instructions | 2986f92ae92fbda65a5c3ca48962091592e6a9fc | [
"MIT"
] | null | null | null | code/Brain/CGPBrain/CGPBrain.h | cliff-bohm/Fragmentation_Replication_Instructions | 2986f92ae92fbda65a5c3ca48962091592e6a9fc | [
"MIT"
] | null | null | null | code/Brain/CGPBrain/CGPBrain.h | cliff-bohm/Fragmentation_Replication_Instructions | 2986f92ae92fbda65a5c3ca48962091592e6a9fc | [
"MIT"
] | null | null | null | // MABE is a product of The Hintze Lab @ MSU
// for general research information:
// hintzelab.msu.edu
// for MABE documentation:
// github.com/Hintzelab/MABE/wiki
//
// Copyright (c) 2015 Michigan State University. All rights reserved.
// to view the full license, visit:
// github.com/Hintzelab/MABE/wiki/License
#pragma once
#include <cmath>
#include <memory>
#include <iostream>
#include <set>
#include <vector>
#include "../../Utilities/Random.h"
#include "../../Genome/AbstractGenome.h"
#include "../../Utilities/Utilities.h"
#include "../AbstractBrain.h"
class CGPBrain : public AbstractBrain {
public:
static std::shared_ptr<ParameterLink<int>> hiddenNodesPL;
// int nrHiddenValues;
static std::shared_ptr<ParameterLink<std::string>> genomeNamePL;
// std::string genomeName;
static std::shared_ptr<ParameterLink<std::string>> availableOperatorsPL;
std::vector<std::string> availableOperators;
static std::shared_ptr<ParameterLink<double>> magnitudeMaxPL;
static std::shared_ptr<ParameterLink<double>> magnitudeMinPL;
// double magnitudeMax;
// double magnitudeMin;
static std::shared_ptr<ParameterLink<int>> numOpsPreVectorPL;
// int numOpsPreVector;
static std::shared_ptr<ParameterLink<std::string>> buildModePL;
// string buildMode;
static std::shared_ptr<ParameterLink<int>> codonMaxPL;
// int codonMax;
static std::shared_ptr<ParameterLink<bool>> readFromOutputsPL;
// bool readFromOutputs;
std::vector<double> readFromValues; // list of values that can be read from
// (inputs, outputs, hidden)
std::vector<double> writeToValues; // list of values that can be written to (there
// will be this number of trees) (outputs,
// hidden)
int nrInputTotal; // inputs + last outputs (maybe) + hidden
int nrOutputTotal; // outputs + hidden
std::map<std::string, int> allOps;
std::vector<int> availableOps;
int availableOpsCount;
std::vector<std::vector<int>> brainVectors; // instruction sets (op,in1,in2)
CGPBrain() = delete;
CGPBrain(int _nrInNodes, int _nrOutNodes,
std::shared_ptr<ParametersTable> PT_ = nullptr);
CGPBrain(int _nrInNodes, int _nrOutNodes,
std::unordered_map<std::string, std::shared_ptr<AbstractGenome>> &_genomes,
std::shared_ptr<ParametersTable> PT_ = nullptr);
virtual ~CGPBrain() = default;
virtual void update() override;
virtual std::shared_ptr<AbstractBrain> makeBrain(
std::unordered_map<std::string, std::shared_ptr<AbstractGenome>> &_genomes) override {
std::shared_ptr<CGPBrain> newBrain =
std::make_shared<CGPBrain>(nrInputValues, nrOutputValues, _genomes, PT);
return newBrain;
}
virtual std::unordered_set<std::string> requiredGenomes() override {
return {genomeNamePL->get(PT)};
}
virtual std::string description() override;
virtual DataMap getStats(std::string &prefix) override;
virtual std::string getType() override { return "CGP"; }
virtual void resetBrain() override;
virtual std::shared_ptr<AbstractBrain>
makeCopy(std::shared_ptr<ParametersTable> PT_ = nullptr) override;
virtual void initializeGenomes(
std::unordered_map<std::string, std::shared_ptr<AbstractGenome>> &_genomes);
};
inline std::shared_ptr<AbstractBrain>
CGPBrain_brainFactory(int ins, int outs, std::shared_ptr<ParametersTable> PT) {
return std::make_shared<CGPBrain>(ins, outs, PT);
}
| 32.88785 | 92 | 0.701051 |
9c8b878c2e4de946569959b16dcfc6035d73b3ef | 2,732 | c | C | lab04/es02/2.c | enbarberis/algoritmi | d9928f6b6c68d7536edc3ef891e8fdb5ad556eed | [
"BSD-3-Clause"
] | 1 | 2018-06-01T15:32:31.000Z | 2018-06-01T15:32:31.000Z | lab04/s201030_lab04/es02/2.c | enbarberis/algoritmi | d9928f6b6c68d7536edc3ef891e8fdb5ad556eed | [
"BSD-3-Clause"
] | null | null | null | lab04/s201030_lab04/es02/2.c | enbarberis/algoritmi | d9928f6b6c68d7536edc3ef891e8fdb5ad556eed | [
"BSD-3-Clause"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GIRL_FILE "ragazze.txt"
#define BOY_FILE "ragazzi.txt"
#define MAX_STR 35 + 1
typedef struct t_student{
char *name; //name of the student
char *surname; //surname of the student
int day, month, year; //date of birth
char sex; //student sex (M/F)
} t_student;
void sort(t_student *v, int n); //sorting function
void swap(t_student *s1, t_student *s2); //swap function
int date(t_student s); //date converter
int main(int argc, char *argv[])
{
//data structure
int n,i; //number of students and iteration variable
t_student *student; //vector of students
FILE *fp, *fp2; //file pointer
char str[MAX_STR]; //temporary variables for reading names, surnames
//arguments test
if(argc < 2){
fprintf(stderr, "Parameters error!\nUsage: ./2 <input file>\n");
return -1;
}
//file opening
if((fp = fopen(argv[1],"r")) == NULL){
fprintf(stderr, "Can't open %s\n", argv[1]);
return -2;
}
//file reading
fscanf(fp, "%d", &n);
student = (t_student *) malloc(n*sizeof(t_student));
for(i=0; i<n; i++)
{
fscanf(fp,"%s",str); //name
student[i].name = malloc((strlen(str)+1)*sizeof(char));
strcpy(student[i].name, str);
fscanf(fp,"%s",str); //surname
student[i].surname = malloc((strlen(str)+1)*sizeof(char));
strcpy(student[i].surname, str);
fscanf(fp,"%d%*c%d%*c%d",&student[i].day,&student[i].month,&student[i].year); //date
student[i].sex = 0; //sex
while(student[i].sex != 'M' && student[i].sex != 'F')
fscanf(fp,"%c", &student[i].sex);
}
fclose(fp);
//sorting vector
sort(student, n);
//print sorted vector
if((fp = fopen(BOY_FILE,"w")) == NULL){
fprintf(stderr, "Can't open %s\n", BOY_FILE);
return -3;
}
if((fp2 = fopen(GIRL_FILE,"w")) == NULL){
fprintf(stderr, "Can't open %s\n", GIRL_FILE);
return -4;
}
for(i=0; i<n; i++)
fprintf(student[i].sex == 'M' ? fp:fp2,"%s %s %d/%d/%d %c\n",
student[i].name, student[i].surname, student[i].day,
student[i].month, student[i].year, student[i].sex);
//clean memory
for(i=0; i<n; i++){
free(student[i].name);
free(student[i].surname);
}
free(student);
return 0;
}
void sort(t_student *s, int n) //insertion sort
{
int i,j;
int lowest, lowest_index;
for(i=0; i<n-1; i++)
{
lowest = date(s[i]);
lowest_index = i;
for(j=i+1; j<n; j++)
if(date(s[j]) < lowest)
{
lowest_index = j;
lowest = date(s[j]);
}
swap(&s[i], &s[lowest_index]);
}
}
int date(t_student s)
{
return s.year*16384 + s.month*128 + s.day;
//return s.year*10000 + s.month*100 + s.day;
}
void swap(t_student *s1, t_student *s2)
{
t_student tmp = *s1;
*s1 = *s2;
*s2 = tmp;
}
| 23.964912 | 86 | 0.606149 |
1709d28a5eadb9c7ff388720b13d380d663454c3 | 560 | h | C | UrabeVocalSynthA/ConfigDataDef.h | DanNixon/UrabeVocalSynth | c062069a140ddb8bfd0280cd8daf5102ec54c58a | [
"Apache-2.0"
] | 1 | 2018-12-26T13:03:29.000Z | 2018-12-26T13:03:29.000Z | UrabeVocalSynthA/ConfigDataDef.h | DanNixon/UrabeVocalSynth | c062069a140ddb8bfd0280cd8daf5102ec54c58a | [
"Apache-2.0"
] | null | null | null | UrabeVocalSynthA/ConfigDataDef.h | DanNixon/UrabeVocalSynth | c062069a140ddb8bfd0280cd8daf5102ec54c58a | [
"Apache-2.0"
] | null | null | null | #ifndef CONFIGDATADEF_H
#define CONFIGDATADEF_H
#define MAX_OPTION_VALUES 32
namespace ConfigData
{
enum DataType
{
INT,
ENUM
};
typedef struct _ConfigOption
{
char *name;
DataType type;
int value; //Actual value for INT, position in value array for ENUM
char *values[MAX_OPTION_VALUES]; //For INT values[0] is min values[1] is max, for ENUM values[n] is string for Nth option
int value_count; //Number of options, -1 for INT (>0 can be used to set precision), number of options for ENUM
} ConfigOption;
};
#endif
| 22.4 | 125 | 0.701786 |
70c2817630fca3cfd6c3c13a01c61f4e4658490f | 1,166 | h | C | LaalMathEngine/Include/Animation/Fading.h | vijayshankarkumar/LME | 6483d893a8902cec4959936220656fcab2b72d4f | [
"MIT"
] | 1 | 2022-02-18T10:38:42.000Z | 2022-02-18T10:38:42.000Z | LaalMathEngine/Include/Animation/Fading.h | vijayshankarkumar/LME | 6483d893a8902cec4959936220656fcab2b72d4f | [
"MIT"
] | 1 | 2021-09-03T21:20:38.000Z | 2021-09-03T21:20:38.000Z | LaalMathEngine/Include/Animation/Fading.h | vijayshankarkumar/LME | 6483d893a8902cec4959936220656fcab2b72d4f | [
"MIT"
] | null | null | null | #ifndef LAAL_FADING_HPP
#define LAAL_FADING_HPP
#include "Animation/Animation.h"
namespace laal
{
//! ============================================
//! [Fade]
//! ============================================
class Fade : public Animation
{
protected:
double m_dStartFillOpacity;
double m_dEndFillOpacity;
double m_dStartStrokeOpacity;
double m_dEndStrokeOpacity;
public:
Fade(Shape* root, std::pair<double, double> strokeOpacity, std::pair<double, double> fillOpacity, double runtime, double lagtime);
virtual ~Fade();
void Begin() override;
void Update(Shape* shape, unsigned int frameCount);
void Finish() override;
};
//! ============================================
//! [FadeIn]
//! ============================================
class FadeIn : public Fade
{
public:
FadeIn(Shape* root, double runtime, double lagtime);
virtual ~FadeIn();
};
//! ============================================
//! [FadeOut]
//! ============================================
class FadeOut : public Fade
{
public:
FadeOut(Shape* root, double runtime, double lagtime);
virtual ~FadeOut();
};
}
#endif // !LAAL_FADING_HPP | 18.806452 | 132 | 0.523156 |
cb61fef2d49b8d7b8c7949a748e31d2cea73e57e | 1,001 | c | C | lib/libmy/src/io/readers/cstrreader.c | nasso/libtiled | 99329b488c8281ad98fc5f20a4b323bd07331243 | [
"MIT"
] | 4 | 2020-03-11T22:06:09.000Z | 2020-04-05T23:51:42.000Z | lib/libmy/src/io/readers/cstrreader.c | nasso/libtiled | 99329b488c8281ad98fc5f20a4b323bd07331243 | [
"MIT"
] | 1 | 2020-03-11T00:46:27.000Z | 2020-03-11T00:46:27.000Z | lib/libmy/src/io/readers/cstrreader.c | nasso/libtiled | 99329b488c8281ad98fc5f20a4b323bd07331243 | [
"MIT"
] | 1 | 2021-03-22T10:27:20.000Z | 2021-03-22T10:27:20.000Z | /*
** EPITECH PROJECT, 2020
** PSU_tetris_2019
** File description:
** cstrreader implementation
*/
#include "my/my.h"
#include "my/io/cstrreader.h"
struct reader_data {
const char *str;
usize_t size;
};
static OPT(usize) read_cb(void *ptr, void *buffer, usize_t n)
{
struct reader_data *self = ptr;
if (self->size == 0)
return (NONE(usize));
n = usize_min(n, self->size);
my_memcpy(buffer, self->str, n * sizeof(char));
self->size -= n;
self->str += n;
return (SOME(usize, n));
}
bufreader_t *cstrreader_new(const char *str, usize_t bufsize)
{
struct reader_data *self = my_malloc(sizeof(struct reader_data));
bufreader_t *br = NULL;
if (self == NULL)
return (NULL);
br = bufreader_new(bufsize);
if (br == NULL) {
my_free(self);
return (NULL);
}
self->str = str;
self->size = my_cstrlen(str);
br->user_data = self;
br->read_cb = &read_cb;
br->free_cb = &my_free;
return (br);
}
| 20.854167 | 69 | 0.604396 |
b97e3866c34e2f5249f44c35a62c443da4d7d0b7 | 2,052 | h | C | include/command_line/flag_arg.h | StanfordPL/cpputil | f44bf5ff224536553105c912638dc34e14f05123 | [
"Apache-2.0"
] | 14 | 2015-05-29T17:42:52.000Z | 2019-07-24T11:58:30.000Z | include/command_line/flag_arg.h | eschkufz/cpputil | f44bf5ff224536553105c912638dc34e14f05123 | [
"Apache-2.0"
] | 18 | 2015-01-01T01:01:56.000Z | 2015-03-16T22:53:05.000Z | include/command_line/flag_arg.h | StanfordPL/cpputil | f44bf5ff224536553105c912638dc34e14f05123 | [
"Apache-2.0"
] | 5 | 2016-02-06T12:37:46.000Z | 2021-07-22T05:07:46.000Z | // Copyright 2014 eric schkufza
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CPPUTIL_INCLUDE_COMMAND_LINE_FLAG_ARG_H
#define CPPUTIL_INCLUDE_COMMAND_LINE_FLAG_ARG_H
#include <string>
#include "include/command_line/arg.h"
namespace cpputil {
class FlagArg : public Arg {
public:
virtual ~FlagArg() = default;
/** Creates and registers a new flag */
static FlagArg& create(const std::string& opt) {
return *(new FlagArg(opt));
}
/** FlagArgs don't consume anything */
virtual std::pair<size_t, size_t> read(int argc, char** argv) {
val_ = !get_appearances(argc, argv).empty();
return std::make_pair(0, 0);
}
/** Create a new arg alias (dashes implicit; chars get 1, strings 2) */
FlagArg& alternate(const std::string& a) {
Arg::alternate(a);
return *this;
}
/** Reset arg usage */
FlagArg& usage(const std::string& u) {
Arg::usage(u);
return *this;
}
/** Reset arg description */
FlagArg& description(const std::string& d) {
Arg::description(d);
return *this;
}
/** Implicit conversion to bool */
operator bool& () {
return val_;
}
/** Explicit conversion to bool */
bool& value() {
return val_;
}
/** Prints true or false */
virtual void debug(std::ostream& os) const {
os << (val_ ? "true" : "false");
}
private:
/** Did this arg appear on the command line? */
bool val_;
/** Flag args are false by default */
FlagArg(const std::string& opt) : Arg {opt}, val_ {false} { }
};
} // namespace cpputil
#endif
| 24.428571 | 75 | 0.667154 |
b614a92ada44d365bec2a5b0781642a62e9783ba | 1,675 | h | C | examples/queue/src/queue_arginfo.h | swoole/phpx | 3beb558f4ebed4660f0795fd98b193a350f924f6 | [
"Apache-2.0"
] | 213 | 2018-08-25T05:43:40.000Z | 2021-05-04T11:40:19.000Z | examples/queue/src/queue_arginfo.h | swoole/phpx | 3beb558f4ebed4660f0795fd98b193a350f924f6 | [
"Apache-2.0"
] | 25 | 2018-09-09T05:54:59.000Z | 2021-02-22T05:09:54.000Z | examples/queue/src/queue_arginfo.h | swoole/phpx | 3beb558f4ebed4660f0795fd98b193a350f924f6 | [
"Apache-2.0"
] | 41 | 2018-08-29T08:34:07.000Z | 2021-03-08T15:12:27.000Z | /* This is a generated file, edit the .stub.php file instead.
* Stub hash: acdf0a4b725dca23eb85635fa0b9bd994ab07081 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_Queue___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, size, IS_LONG, 0, "64")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Queue_count, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Queue_isEmpty, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Queue_push, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Queue_pull, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_Queue_first arginfo_class_Queue_pull
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Queue_traverse, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()
ZEND_METHOD(Queue, __construct);
ZEND_METHOD(Queue, count);
ZEND_METHOD(Queue, isEmpty);
ZEND_METHOD(Queue, push);
ZEND_METHOD(Queue, pull);
ZEND_METHOD(Queue, first);
ZEND_METHOD(Queue, traverse);
static const zend_function_entry class_Queue_methods[] = {
ZEND_ME(Queue, __construct, arginfo_class_Queue___construct, ZEND_ACC_PUBLIC)
ZEND_ME(Queue, count, arginfo_class_Queue_count, ZEND_ACC_PUBLIC)
ZEND_ME(Queue, isEmpty, arginfo_class_Queue_isEmpty, ZEND_ACC_PUBLIC)
ZEND_ME(Queue, push, arginfo_class_Queue_push, ZEND_ACC_PUBLIC)
ZEND_ME(Queue, pull, arginfo_class_Queue_pull, ZEND_ACC_PUBLIC)
ZEND_ME(Queue, first, arginfo_class_Queue_first, ZEND_ACC_PUBLIC)
ZEND_ME(Queue, traverse, arginfo_class_Queue_traverse, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
| 36.413043 | 87 | 0.835821 |
b44ef9b98de08b784142145d093feb7860eafa41 | 2,905 | h | C | basis/window_dwm.h | ryechat/ImageViewer | 1e7503dad46b9c5357da00d1b433b6445147cd90 | [
"MIT"
] | 1 | 2021-06-24T12:19:29.000Z | 2021-06-24T12:19:29.000Z | basis/window_dwm.h | ryechat/ImageViewer | 1e7503dad46b9c5357da00d1b433b6445147cd90 | [
"MIT"
] | null | null | null | basis/window_dwm.h | ryechat/ImageViewer | 1e7503dad46b9c5357da00d1b433b6445147cd90 | [
"MIT"
] | null | null | null | #pragma once
#ifndef GUID_DAA7C9A6D5F64054916D44959063EFA8
#define GUID_DAA7C9A6D5F64054916D44959063EFA8
#include "window.h"
#include "string_buffer.h"
namespace basis {
/*! DWM provides the way to get actual window rect.
Because of that GetWindowRect API returns the rectangle
including skelton area on Windows Vista or later system,
the rectangle returned by GetWindowRect API would be different
from what we could see on the screen.
In the case that actual window rect is necessary,
IsCompositionEnabled() function tells us whether it should call
GetExtendedRect() function instead of GetWindowRect API.
*/
class Window::DWM {
typedef HRESULT(WINAPI *TyIsEnabled)(BOOL*);
typedef HRESULT(WINAPI *TyAttribute)(HWND, DWORD, LPCVOID, DWORD);
public:
/* Checks whether Windows Aero is enabled or not.
This helps us know what GetWindowRect() API returns.
If IsCompositionEnabled() function returned true,
Windows Aero has been enabled.
GetWindowRect() API then returns Aero glass area.
This means what the API returned is inconsitent
with what we could see on the screen.
To workaround this, GetExtendedRect() function can be used.
When this function returned false,
GetWindowRect() API has no matters about that.
*/
static bool IsCompositionEnabled()
{
static auto fp = reinterpret_cast<TyIsEnabled>
(getProc("DwmIsCompositionEnabled"));
BOOL b;
return (fp && fp(&b) == S_OK && b != FALSE);
}
/*! Gets the practical rectangle of the window.
This function works only on Windows Vista or later
and when IsCompositionEnabled() function returns true.
*/
static bool GetExtendedRect(const Window *h, RECT* p)
{
return S_OK != getWindowAttribute(h,
DWMWA_EXTENDED_FRAME_BOUNDS, p, sizeof(RECT));
}
protected:
static HRESULT getWindowAttribute(
const Window *h, DWORD dwAttr, LPCVOID pAttr, DWORD cbAttr)
{
if (!GetFunction())
return -1;
return GetFunction()(*h, dwAttr, pAttr, cbAttr);
}
static inline FARPROC getProc(LPCSTR name)
{
if (!module()) return nullptr;
return GetProcAddress(module(), name);
}
private:
static HMODULE module()
{
static HMODULE hDwm = load();
return hDwm;
}
static HMODULE load()
{
StringBuffer buf(GetSystemDirectory(0, 0));
GetSystemDirectory(buf.data(),
static_cast<UINT>(buf.capacity()));
return LoadLibrary(buf.append(_T("\\dwmapi.dll")).c_str());
}
static TyAttribute GetFunction()
{
static auto fp = reinterpret_cast<TyAttribute>
(getProc("DwmGetWindowAttribute"));
return fp;
}
};
} // namespace
#endif | 30.904255 | 71 | 0.648881 |
47c74b3847eaef685d142c0559d2814869b4b255 | 3,909 | h | C | ti_rtos/ti_rtos_config/ewarm/iar/tirtos/ti/sysbios/family/arm/ducati/package/internal/TimerSupport.xdc.h | JasperWong/LowCarbonFan_CC3200_Net | 7f7e575015af7f1ebeeae90a5c26d368fed0a261 | [
"BSD-3-Clause"
] | null | null | null | ti_rtos/ti_rtos_config/ewarm/iar/tirtos/ti/sysbios/family/arm/ducati/package/internal/TimerSupport.xdc.h | JasperWong/LowCarbonFan_CC3200_Net | 7f7e575015af7f1ebeeae90a5c26d368fed0a261 | [
"BSD-3-Clause"
] | null | null | null | ti_rtos/ti_rtos_config/ewarm/iar/tirtos/ti/sysbios/family/arm/ducati/package/internal/TimerSupport.xdc.h | JasperWong/LowCarbonFan_CC3200_Net | 7f7e575015af7f1ebeeae90a5c26d368fed0a261 | [
"BSD-3-Clause"
] | null | null | null | /*
* Do not modify this file; it is automatically
* generated and any modifications will be overwritten.
*
* @(#) xdc-A32
*/
#ifndef ti_sysbios_family_arm_ducati_TimerSupport__INTERNAL__
#define ti_sysbios_family_arm_ducati_TimerSupport__INTERNAL__
#ifndef ti_sysbios_family_arm_ducati_TimerSupport__internalaccess
#define ti_sysbios_family_arm_ducati_TimerSupport__internalaccess
#endif
#include <ti/sysbios/family/arm/ducati/TimerSupport.h>
#undef xdc_FILE__
#ifndef xdc_FILE
#define xdc_FILE__ NULL
#else
#define xdc_FILE__ xdc_FILE
#endif
/* enable */
#undef ti_sysbios_family_arm_ducati_TimerSupport_enable
#define ti_sysbios_family_arm_ducati_TimerSupport_enable ti_sysbios_family_arm_ducati_TimerSupport_enable__E
/* Module_startup */
#undef ti_sysbios_family_arm_ducati_TimerSupport_Module_startup
#define ti_sysbios_family_arm_ducati_TimerSupport_Module_startup ti_sysbios_family_arm_ducati_TimerSupport_Module_startup__E
/* Instance_init */
#undef ti_sysbios_family_arm_ducati_TimerSupport_Instance_init
#define ti_sysbios_family_arm_ducati_TimerSupport_Instance_init ti_sysbios_family_arm_ducati_TimerSupport_Instance_init__E
/* Instance_finalize */
#undef ti_sysbios_family_arm_ducati_TimerSupport_Instance_finalize
#define ti_sysbios_family_arm_ducati_TimerSupport_Instance_finalize ti_sysbios_family_arm_ducati_TimerSupport_Instance_finalize__E
/* module */
#define TimerSupport_module ((ti_sysbios_family_arm_ducati_TimerSupport_Module_State *)(xdc__MODOBJADDR__(ti_sysbios_family_arm_ducati_TimerSupport_Module__state__V)))
#if !defined(__cplusplus) || !defined(ti_sysbios_family_arm_ducati_TimerSupport__cplusplus)
#define module ((ti_sysbios_family_arm_ducati_TimerSupport_Module_State *)(xdc__MODOBJADDR__(ti_sysbios_family_arm_ducati_TimerSupport_Module__state__V)))
#endif
/* per-module runtime symbols */
#undef Module__MID
#define Module__MID ti_sysbios_family_arm_ducati_TimerSupport_Module__id__C
#undef Module__DGSINCL
#define Module__DGSINCL ti_sysbios_family_arm_ducati_TimerSupport_Module__diagsIncluded__C
#undef Module__DGSENAB
#define Module__DGSENAB ti_sysbios_family_arm_ducati_TimerSupport_Module__diagsEnabled__C
#undef Module__DGSMASK
#define Module__DGSMASK ti_sysbios_family_arm_ducati_TimerSupport_Module__diagsMask__C
#undef Module__LOGDEF
#define Module__LOGDEF ti_sysbios_family_arm_ducati_TimerSupport_Module__loggerDefined__C
#undef Module__LOGOBJ
#define Module__LOGOBJ ti_sysbios_family_arm_ducati_TimerSupport_Module__loggerObj__C
#undef Module__LOGFXN0
#define Module__LOGFXN0 ti_sysbios_family_arm_ducati_TimerSupport_Module__loggerFxn0__C
#undef Module__LOGFXN1
#define Module__LOGFXN1 ti_sysbios_family_arm_ducati_TimerSupport_Module__loggerFxn1__C
#undef Module__LOGFXN2
#define Module__LOGFXN2 ti_sysbios_family_arm_ducati_TimerSupport_Module__loggerFxn2__C
#undef Module__LOGFXN4
#define Module__LOGFXN4 ti_sysbios_family_arm_ducati_TimerSupport_Module__loggerFxn4__C
#undef Module__LOGFXN8
#define Module__LOGFXN8 ti_sysbios_family_arm_ducati_TimerSupport_Module__loggerFxn8__C
#undef Module__G_OBJ
#define Module__G_OBJ ti_sysbios_family_arm_ducati_TimerSupport_Module__gateObj__C
#undef Module__G_PRMS
#define Module__G_PRMS ti_sysbios_family_arm_ducati_TimerSupport_Module__gatePrms__C
#undef Module__GP_create
#define Module__GP_create ti_sysbios_family_arm_ducati_TimerSupport_Module_GateProxy_create
#undef Module__GP_delete
#define Module__GP_delete ti_sysbios_family_arm_ducati_TimerSupport_Module_GateProxy_delete
#undef Module__GP_enter
#define Module__GP_enter ti_sysbios_family_arm_ducati_TimerSupport_Module_GateProxy_enter
#undef Module__GP_leave
#define Module__GP_leave ti_sysbios_family_arm_ducati_TimerSupport_Module_GateProxy_leave
#undef Module__GP_query
#define Module__GP_query ti_sysbios_family_arm_ducati_TimerSupport_Module_GateProxy_query
#endif /* ti_sysbios_family_arm_ducati_TimerSupport__INTERNAL____ */
| 45.988235 | 167 | 0.910207 |
fe9c9f54fd9111e6235e331e9af850c494df8bed | 1,918 | h | C | environment.h | TheVice/Ant4C | d0700b7180d9aab504dd6f9373b7163f7e9dc819 | [
"MIT"
] | null | null | null | environment.h | TheVice/Ant4C | d0700b7180d9aab504dd6f9373b7163f7e9dc819 | [
"MIT"
] | null | null | null | environment.h | TheVice/Ant4C | d0700b7180d9aab504dd6f9373b7163f7e9dc819 | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 - 2021 TheVice
*
*/
#ifndef _ENVIRONMENT_H_
#define _ENVIRONMENT_H_
#include <stddef.h>
#include <stdint.h>
struct buffer;
static const uint8_t environment_posix_delimiter = ':';
static const uint8_t environment_windows_delimiter = ';';
#if defined(_WIN32)
#define ENVIRONMENT_DELIMITER environment_windows_delimiter
#else
#define ENVIRONMENT_DELIMITER environment_posix_delimiter
#endif
enum SpecialFolder
{
Desktop,
Programs,
Personal,
MyDocuments,
Favorites,
Startup,
Recent,
SendTo,
StartMenu,
MyMusic,
MyVideos,
DesktopDirectory,
MyComputer,
NetworkShortcuts,
Fonts,
Templates,
CommonStartMenu,
CommonPrograms,
CommonStartup,
CommonDesktopDirectory,
ApplicationData,
PrinterShortcuts,
LocalApplicationData,
InternetCache,
Cookies,
History,
CommonApplicationData,
Windows,
System,
ProgramFiles,
MyPictures,
UserProfile,
SystemX86,
ProgramFilesX86,
CommonProgramFiles,
CommonProgramFilesX86,
CommonTemplates,
CommonDocuments,
CommonAdminTools,
AdminTools,
CommonMusic,
CommonPictures,
CommonVideos,
Resources,
LocalizedResources,
CommonOemLinks,
CDBurning
};
#define ENVIRONMENT_UNKNOWN_SPECIAL_FOLDER (CDBurning + 1)
uint8_t environment_get_folder_path(enum SpecialFolder folder, struct buffer* path);
uint8_t environment_get_machine_name(struct buffer* name);
const void* environment_get_operating_system();
uint8_t environment_get_user_name(struct buffer* name);
uint8_t environment_get_variable(const uint8_t* variable_name_start, const uint8_t* variable_name_finish,
struct buffer* variable);
uint8_t environment_newline(struct buffer* newline);
uint8_t environment_variable_exists(const uint8_t* variable_name_start, const uint8_t* variable_name_finish);
uint8_t environment_is64bit_process();
uint8_t environment_is64bit_operating_system();
uint16_t environment_processor_count();
#endif
| 21.076923 | 109 | 0.812826 |
dfc26cf8ad8ed1de43aa2d9c11b4b46b1e8f131a | 586 | c | C | lib/string/strchr.c | aglotoff/osdev-pbx-a9 | d053020da451e6c25f8b6668bf042044e4902fc6 | [
"MIT"
] | 1 | 2022-02-13T11:37:53.000Z | 2022-02-13T11:37:53.000Z | lib/string/strchr.c | aglotoff/osdev-pbx-a9 | d053020da451e6c25f8b6668bf042044e4902fc6 | [
"MIT"
] | null | null | null | lib/string/strchr.c | aglotoff/osdev-pbx-a9 | d053020da451e6c25f8b6668bf042044e4902fc6 | [
"MIT"
] | null | null | null | #include <string.h>
/**
* @brief String scanning operation.
*
* Finds the first occurrence of c (converted to a char) in the C string s.
* The terminating null-character is considered to be part of the string.
*
* @param s C string.
* @param c The character to be located.
*
* @return A pointer to the character, or NULL if the character was not found.
*
* @sa memchr, strcspn, strpbrk, strrchr, strspn, strstr, strtok
*/
char *
strchr(const char *s, int c)
{
char ch = (char) c;
for ( ; *s != ch; s++)
if (*s == '\0')
return NULL;
return (char *) s;
}
| 21.703704 | 78 | 0.631399 |
f2952688aef4ac108877a1e3b280721e86da595d | 1,004 | h | C | RenderCore/render/gesture/gesture/GestureArenaMember.h | gubaojian/weexuikit | 2eaf54e4c1f4a1c94398b0990ad9767e3ffb9213 | [
"Apache-2.0"
] | 46 | 2019-06-25T11:05:49.000Z | 2021-12-31T04:47:53.000Z | RenderCore/render/gesture/gesture/GestureArenaMember.h | gubaojian/weexuikit | 2eaf54e4c1f4a1c94398b0990ad9767e3ffb9213 | [
"Apache-2.0"
] | 5 | 2019-10-16T06:54:37.000Z | 2020-02-06T08:22:40.000Z | RenderCore/render/gesture/gesture/GestureArenaMember.h | gubaojian/weexuikit | 2eaf54e4c1f4a1c94398b0990ad9767e3ffb9213 | [
"Apache-2.0"
] | 18 | 2019-05-22T09:29:23.000Z | 2021-04-28T02:12:42.000Z | //
// Created by furture on 2018/10/11.
//
#ifndef WEEX_UIKIT_GESTURE_GESTUREARENAMEMBER_H
#define WEEX_UIKIT_GESTURE_GESTUREARENAMEMBER_H
namespace weexuikit {
/// Represents an object participating in an arena.
///
/// Receives callbacks from the GestureArena to notify the object when it wins
/// or loses a gesture negotiation. Exactly one of [acceptGesture] or
/// [rejectGesture] will be called for each arena this member was added to,
/// regardless of what caused the arena to be resolved. For example, if a
/// member resolves the arena itself, that member still receives an
/// [acceptGesture] callback.
class GestureArenaMember {
public:
/// Called when this member wins the arena for the given pointer id.
virtual void acceptGesture(int pointer) = 0;
/// Called when this member loses the arena for the given pointer id.
virtual void rejectGesture(int pointer) = 0;
};
}
#endif //WEEX_UIKIT_GESTURE_GESTUREARENAMEMBER_H
| 31.375 | 81 | 0.721116 |
d7e9c4b97837c197f771b0e8a39ae2d13ca4c4c1 | 16,567 | c | C | lwmsg/src/archive-format.c | kbore/pbis-open | a05eb9309269b6402b4d6659bc45961986ea5eab | [
"Apache-2.0"
] | 372 | 2016-10-28T10:50:35.000Z | 2022-03-18T19:54:37.000Z | lwmsg/src/archive-format.c | kbore/pbis-open | a05eb9309269b6402b4d6659bc45961986ea5eab | [
"Apache-2.0"
] | 317 | 2016-11-02T17:41:48.000Z | 2021-11-08T20:28:19.000Z | lwmsg/src/archive-format.c | kenferrara/pbis-open | 690c325d947b2bf6fb3032f9d660e41b94aea4be | [
"Apache-2.0"
] | 107 | 2016-11-03T19:25:16.000Z | 2022-03-20T21:15:22.000Z | /*
* Copyright © BeyondTrust Software 2004 - 2019
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS
* WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH
* BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT
* SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE,
* NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST
* A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT
* BEYONDTRUST AT beyondtrust.com/contact
*/
/*
* Module Name:
*
* archive-format.c
*
* Abstract:
*
* Archive API
* Data file format functions
*
* Authors: Brian Koropoff (bkoropoff@likewisesoftware.com)
*
*/
#include "config.h"
#include "archive-private.h"
#include "util-private.h"
#include "protocol-private.h"
#include "data-private.h"
#include "convert-private.h"
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
static
LWMsgStatus
lwmsg_archive_write_fd(
LWMsgArchive* archive,
const void* data,
size_t size
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
const char* cursor = (const char*) data;
size_t remaining = size;
ssize_t written = 0;
while (remaining)
{
do
{
written = write(archive->fd, cursor, remaining);
} while (written < 0 && (errno == EINTR || errno == EAGAIN));
if (written < 0)
{
BAIL_ON_ERROR(status = RAISE_ERRNO(&archive->base.context));
}
remaining -= written;
cursor += written;
archive->offset += written;
}
error:
return status;
}
static
LWMsgStatus
lwmsg_archive_read_fd(
LWMsgArchive* archive,
void* buffer,
size_t size,
size_t* bytes_read
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
char* cursor = (char*) buffer;
size_t remaining = size;
ssize_t count = 0;
size_t total = 0;
while (remaining)
{
do
{
count = read(archive->fd, cursor, remaining);
} while (count < 0 && (errno == EINTR || errno == EAGAIN));
if (count < 0)
{
BAIL_ON_ERROR(status = RAISE_ERRNO(&archive->base.context));
}
else if (count == 0)
{
if (remaining == size)
{
/* We didn't read anything */
BAIL_ON_ERROR(status = LWMSG_STATUS_EOF);
}
else
{
/* Short but successful read */
break;
}
}
remaining -= count;
cursor += count;
archive->offset += count;
total += count;
}
*bytes_read = total;
error:
return status;
}
static
LWMsgStatus
lwmsg_archive_seek_fd(
LWMsgArchive* archive,
off_t position
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
off_t new_position = 0;
if ((new_position = lseek(archive->fd, position, SEEK_SET)) == (off_t) -1)
{
BAIL_ON_ERROR(status = RAISE_ERRNO(&archive->base.context));
}
archive->offset = new_position;
error:
return status;
}
static
void
lwmsg_archive_populate_header(
LWMsgArchive* archive,
ArchiveHeader* header
)
{
memcpy(header->magic, "LWMA", sizeof(header->magic));
header->version_flags = 0;
if (archive->byte_order == LWMSG_BIG_ENDIAN)
{
header->version_flags |= ARCHIVE_VERSION_FLAG_BIG_ENDIAN;
}
header->version_major = ARCHIVE_VERSION_MAJOR;
header->version_minor = ARCHIVE_VERSION_MINOR;
header->version_micro = ARCHIVE_VERSION_MICRO;
header->format_flags = 0;
if (archive->disp & LWMSG_ARCHIVE_SCHEMA)
{
header->format_flags |= ARCHIVE_FORMAT_FLAG_SCHEMA;
}
header->format_flags = LWMSG_SWAP32(
header->format_flags,
LWMSG_NATIVE_ENDIAN,
archive->byte_order);
memset(header->protocol_id, 0, sizeof(header->protocol_id));
}
static
LWMsgStatus
lwmsg_archive_write_message_wrap_fd(
LWMsgBuffer* buffer,
size_t needed
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
LWMsgArchive* archive = buffer->data;
/* Flush data in the buffer to file */
BAIL_ON_ERROR(status = lwmsg_archive_write_fd(archive, buffer->base, (size_t) (buffer->cursor - buffer->base)));
buffer->cursor = buffer->base;
error:
return status;
}
static
LWMsgStatus
lwmsg_archive_write_schema_fd(
LWMsgArchive* archive
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
LWMsgTypeSpec* type = lwmsg_protocol_rep_spec;
LWMsgProtocolRep* rep = NULL;
off_t length_offset = archive->offset;
off_t end_offset = 0;
LWMsgBuffer buffer = {0};
unsigned char data[2048];
uint32_t length = 0;
BAIL_ON_ERROR(status = lwmsg_protocol_get_protocol_rep(archive->base.prot, &rep));
buffer.base = data;
buffer.end = data + sizeof(data);
buffer.cursor = buffer.base;
buffer.wrap = lwmsg_archive_write_message_wrap_fd;
buffer.data = archive;
/* Leave room to write the schema length in later */
BAIL_ON_ERROR(status = lwmsg_archive_seek_fd(archive, length_offset + sizeof(length)));
/* Write the marshaled protocol schema */
BAIL_ON_ERROR(status = lwmsg_data_marshal(archive->data_context, type, rep, &buffer));
end_offset = archive->offset;
/* Go back and write the schema length */
BAIL_ON_ERROR(status = lwmsg_archive_seek_fd(archive, length_offset));
length = LWMSG_SWAP32(
(uint32_t) (end_offset - length_offset) - sizeof(length),
LWMSG_NATIVE_ENDIAN,
archive->byte_order);
BAIL_ON_ERROR(status = lwmsg_archive_write_fd(archive, &length, sizeof(length)));
/* Seek back to end of stream */
BAIL_ON_ERROR(status = lwmsg_archive_seek_fd(archive, end_offset));
error:
if (rep)
{
lwmsg_protocol_free_protocol_rep(archive->base.prot, rep);
}
return status;
}
LWMsgStatus
lwmsg_archive_write_header_fd(
LWMsgArchive* archive
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
ArchiveHeader header;
lwmsg_archive_populate_header(archive, &header);
BAIL_ON_ERROR(status = lwmsg_archive_write_fd(archive, &header, sizeof(header)));
if (archive->disp & LWMSG_ARCHIVE_SCHEMA)
{
BAIL_ON_ERROR(status = lwmsg_archive_write_schema_fd(archive));
}
error:
return status;
}
static
void
lwmsg_archive_populate_message_header(
LWMsgArchive* archive,
LWMsgMessage* message,
size_t data_size,
ArchiveMessage* header
)
{
header->flags = LWMSG_SWAP16((uint16_t) message->flags, LWMSG_NATIVE_ENDIAN, archive->byte_order);
header->status = LWMSG_SWAP32((uint32_t) message->status, LWMSG_NATIVE_ENDIAN, archive->byte_order);
header->cookie = LWMSG_SWAP16((uint16_t) message->cookie, LWMSG_NATIVE_ENDIAN, archive->byte_order);
header->tag = LWMSG_SWAP16((int16_t) message->tag, LWMSG_NATIVE_ENDIAN, archive->byte_order);
header->size = LWMSG_SWAP32((uint32_t) data_size, LWMSG_NATIVE_ENDIAN, archive->byte_order);
}
LWMsgStatus
lwmsg_archive_write_message_fd(
LWMsgArchive* archive,
LWMsgMessage* message
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
unsigned char data[2048];
ArchiveMessage header = {0};
LWMsgBuffer buffer = {0};
LWMsgTypeSpec* type = NULL;
off_t header_offset = archive->offset;
off_t end_offset = 0;
BAIL_ON_ERROR(status = lwmsg_protocol_get_message_type(archive->base.prot, message->tag, &type));
buffer.base = data;
buffer.end = data + sizeof(data);
buffer.cursor = buffer.base;
buffer.wrap = lwmsg_archive_write_message_wrap_fd;
buffer.data = archive;
/* Leave room to write the header in later */
BAIL_ON_ERROR(status = lwmsg_archive_seek_fd(archive, header_offset + sizeof(header)));
/* Write the marshaled data payload */
BAIL_ON_ERROR(status = lwmsg_data_marshal(archive->data_context, type, message->data, &buffer));
end_offset = archive->offset;
/* Go back and write the header */
BAIL_ON_ERROR(status = lwmsg_archive_seek_fd(archive, header_offset));
lwmsg_archive_populate_message_header(archive, message, end_offset - header_offset - sizeof(header), &header);
BAIL_ON_ERROR(status = lwmsg_archive_write_fd(archive, &header, sizeof(header)));
/* Seek back to end of message stream */
BAIL_ON_ERROR(status = lwmsg_archive_seek_fd(archive, end_offset));
error:
return status;
}
typedef struct readinfo
{
LWMsgArchive* archive;
unsigned char data[2048];
size_t remaining;
} readinfo;
static
LWMsgStatus
lwmsg_archive_read_message_wrap_fd (
LWMsgBuffer* buffer,
size_t needed
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
readinfo* info = buffer->data;
LWMsgArchive* archive = info->archive;
size_t count = 0;
if (needed)
{
/* Read next block of data from file */
if (info->remaining == 0)
{
/* The message was longer than the length specified in the header */
BAIL_ON_ERROR(status = LWMSG_STATUS_MALFORMED);
}
else
{
BAIL_ON_ERROR(status = lwmsg_archive_read_fd(
archive,
info->data,
info->remaining > sizeof(info->data) ? sizeof(info->data) : info->remaining,
&count));
info->remaining -= count;
buffer->end = buffer->base + count;
buffer->cursor = buffer->base;
}
}
else
{
if (info->remaining != 0)
{
/* The message was shorter than the length specified in the header */
BAIL_ON_ERROR(status = LWMSG_STATUS_MALFORMED);
}
}
error:
return status;
}
static
LWMsgStatus
lwmsg_archive_read_schema_fd(
LWMsgArchive* archive,
ArchiveHeader* header
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
uint32_t format_flags = LWMSG_SWAP32(header->format_flags, LWMSG_NATIVE_ENDIAN, archive->byte_order);
uint32_t length = 0;
size_t count = 0;
LWMsgProtocolRep* rep = NULL;
if (format_flags & ARCHIVE_FORMAT_FLAG_SCHEMA)
{
BAIL_ON_ERROR(status = lwmsg_archive_read_fd(archive, &length, sizeof(length), &count));
if (count < sizeof(length))
{
BAIL_ON_ERROR(status = LWMSG_STATUS_MALFORMED);
}
length = LWMSG_SWAP32(length, LWMSG_NATIVE_ENDIAN, archive->byte_order);
if (archive->disp & LWMSG_ARCHIVE_SCHEMA)
{
readinfo info;
LWMsgBuffer buffer = {0};
LWMsgTypeSpec* type = lwmsg_protocol_rep_spec;
info.archive = archive;
info.remaining = length;
buffer.base = info.data;
buffer.end = buffer.base;
buffer.cursor = buffer.base;
buffer.wrap = lwmsg_archive_read_message_wrap_fd;
buffer.data = &info;
/* Unmarshal the schema */
BAIL_ON_ERROR(status = lwmsg_data_unmarshal(
archive->data_context,
type,
&buffer,
(void**) (void*) &rep));
if (archive->update_protocol)
{
/* Insert the schema into the protocol structure */
BAIL_ON_ERROR(status = lwmsg_protocol_add_protocol_rep(
archive->base.prot,
rep));
}
else
{
/* Check the schema against the protocol */
BAIL_ON_ERROR(status = lwmsg_protocol_is_protocol_rep_compatible(
archive->base.prot,
rep));
}
}
else
{
BAIL_ON_ERROR(status = lwmsg_archive_seek_fd(archive, archive->offset + length));
}
}
error:
if (rep)
{
lwmsg_data_free_graph_cleanup(archive->data_context->context, lwmsg_protocol_rep_spec, rep);
}
return status;
}
LWMsgStatus
lwmsg_archive_read_header_fd(
LWMsgArchive* archive
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
ArchiveHeader header;
size_t count = 0;
BAIL_ON_ERROR(status = lwmsg_archive_read_fd(archive, &header, sizeof(header), &count));
if (count < sizeof(header) || memcmp(header.magic, "LWMA", 4) != 0)
{
BAIL_ON_ERROR(status = LWMSG_STATUS_MALFORMED);
}
if (header.version_major > ARCHIVE_VERSION_MAJOR ||
header.version_minor > ARCHIVE_VERSION_MINOR)
{
BAIL_ON_ERROR(status = LWMSG_STATUS_MALFORMED);
}
archive->version_major = header.version_major;
archive->version_minor = header.version_minor;
if (header.version_flags & ARCHIVE_VERSION_FLAG_BIG_ENDIAN)
{
archive->byte_order = LWMSG_BIG_ENDIAN;
}
else
{
archive->byte_order = LWMSG_LITTLE_ENDIAN;
}
lwmsg_data_context_set_byte_order(archive->data_context, archive->byte_order);
BAIL_ON_ERROR(status = lwmsg_archive_read_schema_fd(archive, &header));
error:
return status;
}
static
LWMsgStatus
lwmsg_archive_read_message_header(
LWMsgArchive* archive,
LWMsgMessage* message,
size_t* size
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
ArchiveMessage_v0 header_v0 = {0};
ArchiveMessage header = {0};
size_t count = 0;
switch(archive->version_major)
{
case 0:
BAIL_ON_ERROR(status = lwmsg_archive_read_fd(archive, &header_v0, sizeof(header_v0), &count));
if (count < sizeof(header))
{
BAIL_ON_ERROR(status = LWMSG_STATUS_MALFORMED);
}
message->flags = 0;
message->status = LWMSG_SWAP32(header_v0.status, archive->byte_order, LWMSG_NATIVE_ENDIAN);
message->cookie = (uint16_t) LWMSG_SWAP32(header_v0.cookie, archive->byte_order, LWMSG_NATIVE_ENDIAN);
message->tag = (int16_t) LWMSG_SWAP32(header_v0.tag, archive->byte_order, LWMSG_NATIVE_ENDIAN);
*size = LWMSG_SWAP32(header_v0.size, archive->byte_order, LWMSG_NATIVE_ENDIAN);
break;
case ARCHIVE_VERSION_MAJOR:
BAIL_ON_ERROR(status = lwmsg_archive_read_fd(archive, &header, sizeof(header), &count));
if (count < sizeof(header))
{
BAIL_ON_ERROR(status = LWMSG_STATUS_MALFORMED);
}
message->flags = LWMSG_SWAP16(header.flags, archive->byte_order, LWMSG_NATIVE_ENDIAN);
message->status = LWMSG_SWAP32(header.status, archive->byte_order, LWMSG_NATIVE_ENDIAN);
message->cookie = LWMSG_SWAP16(header.cookie, archive->byte_order, LWMSG_NATIVE_ENDIAN);
message->tag = LWMSG_SWAP16(header.tag, archive->byte_order, LWMSG_NATIVE_ENDIAN);
*size = LWMSG_SWAP32(header.size, archive->byte_order, LWMSG_NATIVE_ENDIAN);
break;
}
error:
return status;
}
LWMsgStatus
lwmsg_archive_read_message_fd(
LWMsgArchive* archive,
LWMsgMessage* message
)
{
LWMsgStatus status = LWMSG_STATUS_SUCCESS;
readinfo info;
LWMsgBuffer buffer = {0};
LWMsgTypeSpec* type = NULL;
size_t message_size = 0;
BAIL_ON_ERROR(status = lwmsg_archive_read_message_header(archive, message, &message_size));
BAIL_ON_ERROR(status = lwmsg_protocol_get_message_type(archive->base.prot, message->tag, &type));
info.archive = archive;
info.remaining = message_size;
buffer.base = info.data;
buffer.end = buffer.base;
buffer.cursor = buffer.base;
buffer.wrap = lwmsg_archive_read_message_wrap_fd;
buffer.data = &info;
/* Unmarshal the message payload */
BAIL_ON_ERROR(status = lwmsg_data_unmarshal(archive->data_context, type, &buffer, &message->data));
error:
return status;
}
| 27.611667 | 116 | 0.6455 |
4a694ff1cf4ba3f28af03e891547bfd87819940b | 1,010 | h | C | OpenGLTemplate/GameWindow.h | ferenc-schultesz/3DRacerGame | 34784f0dbdbade13fe4f6b00f5d1327aabaa1ef2 | [
"Apache-2.0"
] | null | null | null | OpenGLTemplate/GameWindow.h | ferenc-schultesz/3DRacerGame | 34784f0dbdbade13fe4f6b00f5d1327aabaa1ef2 | [
"Apache-2.0"
] | null | null | null | OpenGLTemplate/GameWindow.h | ferenc-schultesz/3DRacerGame | 34784f0dbdbade13fe4f6b00f5d1327aabaa1ef2 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <windows.h>
#include "Common.h"
LRESULT CALLBACK WinProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam);
class GameWindow {
public:
static GameWindow& GetInstance();
GameWindow();
enum {
SCREEN_WIDTH = 800,
SCREEN_HEIGHT = 600,
};
HDC Init(HINSTANCE hinstance);
void Deinit();
void SetDimensions(RECT dimensions) {m_dimensions = dimensions;}
RECT GetDimensions() {return m_dimensions;}
bool Fullscreen() const { return m_fullscreen; }
HDC Hdc() const { return m_hdc; }
HINSTANCE Hinstance() const { return m_hinstance; }
HGLRC Hrc() const { return m_hrc; }
HWND Hwnd() const { return m_hwnd; }
private:
GameWindow(const GameWindow&);
void operator=(const GameWindow&);
void CreateGameWindow(string title);
void InitOpenGL();
bool InitGLEW();
void RegisterSimpleOpenGLClass(HINSTANCE hInstance);
bool m_fullscreen;
HDC m_hdc;
HINSTANCE m_hinstance;
HGLRC m_hrc;
HWND m_hwnd;
LPSTR m_class;
RECT m_dimensions;
string m_appName;
};
| 18.363636 | 76 | 0.727723 |
f3ff6c41fe8a7588534afd2d05d941d030429844 | 9,454 | h | C | json.h | PiotrPeszko/Termikus | 9dc633c2bb1c11d9d7416f3dc19bff5ece4a601e | [
"MIT"
] | 3 | 2020-03-03T07:05:24.000Z | 2021-06-11T07:30:24.000Z | json.h | PiotrPeszko/Termikus | 9dc633c2bb1c11d9d7416f3dc19bff5ece4a601e | [
"MIT"
] | null | null | null | json.h | PiotrPeszko/Termikus | 9dc633c2bb1c11d9d7416f3dc19bff5ece4a601e | [
"MIT"
] | null | null | null | #ifndef JSON_H
#define JSON_H
/*
The file contains REST API definition for Termikus
Getting information from Termikus:
CHECKING
General configuration information (HTTP_GET):
curl -i http://192.168.1.104/get_info
Information on temperatures and relay status (HTTP_GET):
curl -i http://192.168.1.104/get_temp
Interval steering information (HTTP_GET):
curl -i http://192.168.1.104/get_interval
Program data information:
curl -i -X POST -d {\"PROGRAM\":\"read\",\"NUMBER\":\"1\"} http://192.168.1.104/get_prog
MODIFICATIONS
All object modification request are sent to the same address http://x.x.x.x/write with method HTTP_PU, but differs in paylod content.
Interval steering start:
curl -i -X PUT -d {\"INTERVAL\":\"true\",\"iTemp\":\"35\",\"iDuration\":\"15\"} http://192.168.1.104/write
Storing new program data:
curl -i -X PUT -d {\"PROGRAM\":\"1\",\"hSTART\":\"0\",\"mSTART\":\"0\",\"hSTOP\":\"6\",\"mSTOP\":\"0\",\"TEMP\":\"26.5\",\"PN\":\"1\",\"WT\":\"1\",\"SR\":\"1\",\"CZ\":\"1\",\"PT\":\"1\",\"SO\":\"1\",\"ND\":\"1\",\"ENABLE\":\"1\"} http://192.168.1.104/write
PROGRAM = program number 1-8
Storing new general temperature (program 9)
curl -i -X PUT -d {\"PROGRAM\":\"9\",\"TEMP\":\"35\"} http://192.168.1.104/write
*/
void get_status() {
StaticJsonBuffer<280> jsonBuffer;
JsonObject& jsonObj = jsonBuffer.createObject();
char JSONmessageBuffer[280];
jsonObj["DeviceName"] = (String)config.DeviceName;
jsonObj["DeviceNumber"] = (String)config.DeviceNumber;
jsonObj["SafetyStatus"] = (String)config.enableSafety + (String)config.enableSafetyTemp;
jsonObj["mainTemp"] = (String)config.baseTemp;
jsonObj["measurTemp"] = (String)measureTemp;
jsonObj["activeProg"] = (String)programFit;
jsonObj["progTemp"] = (String) setTemp;
jsonObj["relayStatus"] = relayStatus;
jsonObj["upHist"] = (String) config.histeresisUpper;
jsonObj["loHist"] = (String) config.histeresisLower;
jsonObj["dsRes"] = (String) resDS;
jsonObj["coolMode"] = config.coolMode;
jsonObj["thspStatus"] = (String) channelUpdateStatus;
jsonObj.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
server.send(200, "application/json", JSONmessageBuffer);
}
void get_temperatures() {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& jsonObj = jsonBuffer.createObject();
char JSONmessageBuffer[200];
jsonObj["measurTemp"] = (String)measureTemp;
jsonObj["mainTemp"] = (String)config.baseTemp;
jsonObj["activeProg"] = (String)programFit;
jsonObj["progTemp"] = (String) setTemp;
jsonObj["relayStatus"] = relayStatus;
jsonObj.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
server.send(200, "application/json", JSONmessageBuffer);
}
void get_interval() {
StaticJsonBuffer<115> jsonBuffer;
JsonObject& jsonObj = jsonBuffer.createObject();
char JSONmessageBuffer[115];
unsigned int timeToGo = timeToGoConv(); // interval elapsed time second to minutes convertion
jsonObj["interval"] = intervalMode;
jsonObj["iTemp"] = (String)intervalTemperature;
jsonObj["iDuration"] = (String)intervalDuration;
jsonObj["timeToGo"] = (String)timeToGo;
jsonObj.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
server.send(200, "application/json", JSONmessageBuffer);
}
void post_program(byte number){
StaticJsonBuffer<250> jsonBuffer;
JsonObject& jsonObj = jsonBuffer.createObject();
char JSONmessageBuffer[250];
jsonObj["PROGRAM"] = number;
jsonObj["hSTART"] = progData[number].startH;
jsonObj["mSTART"] = progData[number].startM;
jsonObj["hSTOP"] = progData[number].stopH;
jsonObj["mSTOP"] = progData[number].stopM;
jsonObj["TEMP"] = progData[number].tempProgramu;
jsonObj["PN"] = progData[number].Pn;
jsonObj["WT"] = progData[number].Wt;
jsonObj["SR"] = progData[number].Sr;
jsonObj["CZ"] = progData[number].Cz;
jsonObj["PT"] = progData[number].Pt;
jsonObj["SO"] = progData[number].So;
jsonObj["ND"] = progData[number].Nd;
jsonObj["ENABLE"] = progData[number].Enabled;
jsonObj.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
server.send(200, "application/json", JSONmessageBuffer);
}
void json_to_interval(JsonObject& jsonBody) {
float iTemp;
unsigned int iDuration;
iTemp = jsonBody["iTemp"];
iDuration = jsonBody["iDuration"];
if (iTemp > 125) iTemp = 125;
if (iTemp < -55) iTemp = -55;
if (iDuration < 0) iDuration = 0;
if (iDuration > 65000) iDuration = 65000;
Serial.println(iTemp);
Serial.println(iDuration);
intervalTemperature = iTemp;
intervalDuration = iDuration;
}
void json_to_program (JsonObject& jsonBody, byte number) {
byte hStart, mStart, hStop, mStop;
float Temperature;
boolean pn, wt, sr, cz, pt, so, nd, enabled;
hStart = jsonBody["hSTART"];
mStart = jsonBody["mSTART"];
hStop = jsonBody["hSTOP"];
mStop = jsonBody["mSTOP"];
Temperature = jsonBody["TEMP"];
pn = jsonBody["PN"]; // weekdays starting Monday
wt = jsonBody["WT"];
sr = jsonBody["SR"];
cz = jsonBody["CZ"];
pt = jsonBody["PT"];
so = jsonBody["SO"];
nd = jsonBody["ND"];
enabled = jsonBody["ENABLE"];
if (hStart > 23 || hStart < 0) hStart = 0;
if (hStop > 23 || hStop < 0) hStop = 0;
if (mStart > 59 || mStart < 0) mStart = 0;
if (mStop > 59 || mStop < 0) mStop = 0;
if (Temperature > 125) Temperature = 125;
if (Temperature < -55) Temperature = -55;
if (Temperature > -55 && Temperature < 125) progData[number].tempProgramu = Temperature;
if (hStart >= 0 || hStart <= 23) progData[number].startH = hStart;
if (mStart >= 0 || mStart <= 59) progData[number].startM = mStart;
if (hStop >= 1 || hStop <= 23) progData[number].stopH = hStop;
if (mStop >= 0 || mStop <= 59) progData[number].stopM = mStop;
if (pn == false || pn == true) progData[number].Pn = pn;
if (wt == false || wt == true) progData[number].Wt = wt;
if (sr == false || sr == true) progData[number].Sr = sr;
if (cz == false || cz == true) progData[number].Cz = cz;
if (pt == false || pt == true) progData[number].Pt = pt;
if (so == false || so == true) progData[number].So = so;
if (nd == false || nd == true) progData[number].Nd = nd;
if (enabled == true || enabled == false) progData[number].Enabled = enabled;
writeProgram(number);
}
void json_to_temperature(JsonObject& jsonBody) {
float Temperature;
Temperature = jsonBody["TEMP"];
if (Temperature > 125) Temperature = 125;
if (Temperature < -55) Temperature = -55;
config.baseTemp = Temperature;
EEPROMWritelong(50, config.baseTemp);
EEPROM.commit();
}
void post_put() {
if (config.enableAPI == false) {
server.send(400);
return;
}
StaticJsonBuffer<500> jsonBuffer;
String post_body = server.arg("plain");
Serial.println(post_body);
JsonObject& jsonBody = jsonBuffer.parseObject(post_body);
Serial.print("HTTP Method: ");
Serial.println(server.method());
if (!jsonBody.success()) {
Serial.println("error in parsin json body");
server.send(400);
}
else {
if (server.method() == HTTP_PUT) {
if (jsonBody["INTERVAL"] == true) {
json_to_interval(jsonBody);
unsigned int duration = jsonBody["iDuration"];
float temperature = jsonBody["iTemp"];
server.sendHeader("Location", "/interval/" + String(temperature) + "stC/" + String(duration) + "min.");
server.send(200);
} else if (jsonBody["PROGRAM"]) {
int progNumber = jsonBody["PROGRAM"];
if (progNumber <= 0 || progNumber > 9) { // program number must be in range 1-8 or memory address selection fail
server.send(404);
} else if (progNumber == 9){ // 9 is program number for main temperature modification
float Temperature = jsonBody["TEMP"];
json_to_temperature(jsonBody);
server.sendHeader("Location", "/temperature/" + String(Temperature));
server.send(200);
} else {
json_to_program(jsonBody, progNumber);
server.sendHeader("Location", "/program/" + String(progNumber));
server.send(200);
}
} else
server.send(404);
} else if (server.method() == HTTP_POST) {
if (jsonBody["PROGRAM"] == "read") {
byte progNumber = jsonBody["NUMBER"];
if (progNumber > 8 || progNumber == 0) { // program number must be in range 1-8 or memory address selection fail
server.send(404);
} else {
server.sendHeader("Location", "/Program/" + String(progNumber));
post_program (progNumber);
}
} else
server.send(404);
}
}
}
#endif
| 37.816 | 259 | 0.59414 |
286efea6f8f19ce19e5599bf15201a04146fb56b | 4,806 | h | C | src/txt/FontManager.h | Potion/Cinder-Text | c08210a45d384b9461bf01c2ba6a1e06ed84053b | [
"MIT"
] | 5 | 2018-08-10T18:49:03.000Z | 2019-10-22T18:04:47.000Z | src/txt/FontManager.h | Potion/Cinder-Text | c08210a45d384b9461bf01c2ba6a1e06ed84053b | [
"MIT"
] | 2 | 2019-09-27T17:29:35.000Z | 2020-03-17T11:16:09.000Z | src/txt/FontManager.h | Potion/Cinder-Text | c08210a45d384b9461bf01c2ba6a1e06ed84053b | [
"MIT"
] | 3 | 2018-08-06T01:35:10.000Z | 2021-05-12T03:16:29.000Z | #pragma once
#include <memory>
#include <unordered_map>
#include <freetype2\ft2build.h>
#include FT_FREETYPE_H
#include <freetype/ftcache.h>
#include "cinder/Filesystem.h"
#include "cinder/Vector.h"
#include "cinder/app/App.h"
#include "txt/Font.h"
namespace txt
{
// Lookup tables for family + style to face id
// Convenience struct to transform font family + style to lowercase
// gives a better chance of matching
struct FaceFamilyAndStyle {
FaceFamilyAndStyle()
{
}
FaceFamilyAndStyle( FT_Face face )
: FaceFamilyAndStyle( face->family_name, face->style_name ) {}
FaceFamilyAndStyle( std::string family, std::string style )
: family( family )
, style( style )
{
std::transform( this->family.begin(), this->family.end(), this->family.begin(), ::tolower );
std::transform( this->style.begin(), this->style.end(), this->style.begin(), ::tolower );
}
FaceFamilyAndStyle( const FaceFamilyAndStyle& familyStyle ) : FaceFamilyAndStyle( familyStyle.family, familyStyle.style ) { }
std::string family;
std::string style;
bool operator==( const FaceFamilyAndStyle& other ) const
{
bool match = ( this->family == other.family && this->style == other.style );
return match;
}
FaceFamilyAndStyle& FaceFamilyAndStyle::operator=( const Font& other )
{
return *this;
}
};
}
// FaceFamilyStyle Hash Function
namespace std
{
template <>
struct hash<txt::FaceFamilyAndStyle> {
std::size_t operator()( const txt::FaceFamilyAndStyle& k ) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ( ( hash < std::string>()( ( k.family ) )
^ ( hash<std::string>()( k.style ) << 1 ) ) >> 1 );
}
};
}
namespace txt
{
class FontManager;
typedef std::shared_ptr<FontManager> FontManagerRef;
class FontManager
{
friend struct Font;
public:
static FontManagerRef get();
// Preload a face so that it can be referenced in rich text
// If family or style are not provided they will be read from the font
void loadFace( const ci::fs::path& path, const std::string& family = "", const std::string& style = "" );
void loadFace( const ci::DataSourceRef& dataSource, const std::string& family = "", const std::string& style = "" );
// Get the font family or style for a previously loaded or system font
std::string getFontFamily( const Font& font );
std::string getFontStyle( const Font& font );
// Freetype functions, used by renderers and shapers
uint32_t getGlyphIndex( const Font& font, FT_UInt32 charCode, FT_Int mapIndex = 0 );
std::vector<uint32_t> getGlyphIndices( const Font& font, std::string string = "" );
FT_Glyph getGlyph( const Font& font, unsigned int glyphIndex );
FT_BitmapGlyph getGlyphBitmap( const Font& font, unsigned int glyphIndex );
unsigned int getNumGlyphs( const Font& font );
ci::vec2 getGlyphSize( const Font& font, unsigned int glyphIndex );
ci::vec2 getMaxGlyphSize( const Font& font );
float getLineHeight( const Font& font );
FT_Face getFace( const Font& font );
FT_Face getFace( uint32_t faceId );
FT_Face getFace( FTC_FaceID faceId );
FT_Size getSize( const Font& font );
FTC_ScalerRec_ getScaler( const Font& font );
protected:
FontManager();
// Load freetype libs
void initFreetype();
// Callback function used by FTCache, loads fonts when not present and requested
static FT_Error faceRequestor( FTC_FaceID face_id, FT_Library library, FT_Pointer req_data, FT_Face* aface );
// FT Error message wrapper
static void checkForFTError( FT_Error error, std::string description );
static const char* getFTErrorMessage( FT_Error error );
uint32_t getFaceId( const ci::fs::path& path );
uint32_t getFaceId( std::string family, std::string style );
void loadFace( const FaceFamilyAndStyle& familyStyle );
void removeFace( FTC_FaceID id );
private:
uint32_t mNextFaceId;
// Lookup tables for FTC_FaceID caching
std::unordered_map <std::string, FTC_FaceID > mFaceIDsForPaths;
std::unordered_map < FTC_FaceID, std::string > mFacePathsForFaceID;
void registerFamilyStyleForFaceID( const FaceFamilyAndStyle& familyStyle, FTC_FaceID id );
std::unordered_map<FTC_FaceID, FaceFamilyAndStyle > mFamilyAndStyleForFaceIDs;
std::unordered_map<FaceFamilyAndStyle, FTC_FaceID> mFaceIDsForFamilyAndStyle;
// Freetype libs + caches
FT_Library mFTLibrary;
FTC_Manager mFTCacheManager;
FTC_CMapCache mFTCMapCache;
FTC_ImageCache mFTCImageCache;
};
} | 30.611465 | 128 | 0.686017 |
4f2a80a03b0d0ae9cbd3a3cdeea61c649568dcea | 749 | h | C | doc/pages/functions.h | picrap/vaca | 377070c2124bb71649313f6a144c6bd40fdee723 | [
"MIT"
] | null | null | null | doc/pages/functions.h | picrap/vaca | 377070c2124bb71649313f6a144c6bd40fdee723 | [
"MIT"
] | null | null | null | doc/pages/functions.h | picrap/vaca | 377070c2124bb71649313f6a144c6bd40fdee723 | [
"MIT"
] | null | null | null | namespace vaca {
/**
@page page_functions Functions
@beginOverviewTable
@titleRow{Macros}
@itemRow{VACA_MAIN}
@itemRow{VACA_TRACE}
@titleRow{Base}
@itemRow{clamp_value}
@itemRow{max_value}
@itemRow{min_value}
@titleRow{Containers}
@itemRow{remove_from_container}
@titleRow{Memory}
@itemRow{delete_widget}
@titleRow{Strings}
@itemRow{format_string}
@itemRow{trim_string}
@itemRow{convert_to}
@itemRow{copy_string_to}
@titleRow{Filenames}
@itemRow{file_extension}
@itemRow{file_name}
@itemRow{file_path}
@itemRow{file_title}
@titleRow{URL}
@itemRow{decode_url}
@itemRow{encode_url}
@titleRow{Bindings}
@itemRow{page_bind, Adapts functions or methods to be connected to signals.}
@itemRow{Ref}
@endTable
*/
}
| 18.725 | 78 | 0.755674 |
1a37f387190ee5f7f29a7c685a5628ddc33c9227 | 470 | h | C | shared_include/registered-ema/RegisteredEmaData.h | ahewer/mri-shape-tools | 4268499948f1330b983ffcdb43df62e38ca45079 | [
"MIT"
] | null | null | null | shared_include/registered-ema/RegisteredEmaData.h | ahewer/mri-shape-tools | 4268499948f1330b983ffcdb43df62e38ca45079 | [
"MIT"
] | 2 | 2017-05-29T09:43:01.000Z | 2017-05-29T09:50:05.000Z | shared_include/registered-ema/RegisteredEmaData.h | ahewer/mri-shape-tools | 4268499948f1330b983ffcdb43df62e38ca45079 | [
"MIT"
] | 4 | 2017-05-17T11:56:02.000Z | 2022-03-05T09:12:24.000Z | #ifndef __REGISTERED_EMA_DATA_H__
#define __REGISTERED_EMA_DATA_H__
#include <vector>
#include <armadillo>
class RegisteredEmaData{
public:
std::vector<arma::vec> speakerWeights;
std::vector<arma::vec> phonemeWeights;
std::vector<arma::vec> speakerVariations;
std::vector<arma::vec> phonemeVariations;
std::vector< std::vector<arma::vec> > targetPoints;
std::vector<double> timeStamps;
double samplingFrequency;
int boundarySize = 0;
};
#endif
| 17.407407 | 53 | 0.746809 |
4d4de623c1c4cf56698acfb5f59303926af79fc9 | 114 | h | C | include_wo/sakuragl/erisa/sgl_erisa_sound_file_player.h | SegaraRai/EntisGLS4Build | 2587390738802394a38b3aaf2adc80295dde7ec4 | [
"CC0-1.0",
"Unlicense"
] | 3 | 2021-11-05T08:02:17.000Z | 2022-02-26T18:03:18.000Z | include_woe/sakuragl/erisa/sgl_erisa_sound_file_player.h | SegaraRai/EntisGLS4Build | 2587390738802394a38b3aaf2adc80295dde7ec4 | [
"CC0-1.0",
"Unlicense"
] | null | null | null | include_woe/sakuragl/erisa/sgl_erisa_sound_file_player.h | SegaraRai/EntisGLS4Build | 2587390738802394a38b3aaf2adc80295dde7ec4 | [
"CC0-1.0",
"Unlicense"
] | null | null | null | #include "../../../gls4s.05.2015.04.18/EntisGLS4s.05/Include/common/sakuragl/erisa/sgl_erisa_sound_file_player.h"
| 57 | 113 | 0.77193 |
94ca692a0211a37096e2aa37ad18c2ffd1444b1b | 215 | h | C | HotFix/HotFix/JavaScriptCoreDemoVC.h | emiyagjy/iOS-HotFix | 1446eb0ef812f5786c01348075ae9d112e0b4e2c | [
"Apache-2.0"
] | null | null | null | HotFix/HotFix/JavaScriptCoreDemoVC.h | emiyagjy/iOS-HotFix | 1446eb0ef812f5786c01348075ae9d112e0b4e2c | [
"Apache-2.0"
] | null | null | null | HotFix/HotFix/JavaScriptCoreDemoVC.h | emiyagjy/iOS-HotFix | 1446eb0ef812f5786c01348075ae9d112e0b4e2c | [
"Apache-2.0"
] | null | null | null | //
// JavaScriptCoreDemoVC.h
// HotFix
//
// Created by GujyHy on 2018/3/22.
// Copyright © 2018年 Gujy. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface JavaScriptCoreDemoVC : UIViewController
@end
| 15.357143 | 50 | 0.702326 |
7f5afdbc40450fb8a86a7c089b8259ba6f477c95 | 2,551 | c | C | src/libav/libavutil/adler32.c | fillest/rtmp_load | 12845c868d144195688f7158eb4126c582cfdce3 | [
"MIT"
] | 10 | 2015-05-19T08:08:02.000Z | 2020-09-26T00:58:57.000Z | src/libav/libavutil/adler32.c | fillest/rtmp_load | 12845c868d144195688f7158eb4126c582cfdce3 | [
"MIT"
] | null | null | null | src/libav/libavutil/adler32.c | fillest/rtmp_load | 12845c868d144195688f7158eb4126c582cfdce3 | [
"MIT"
] | 3 | 2016-07-05T12:35:52.000Z | 2022-03-31T09:13:02.000Z | /*
* Compute the Adler-32 checksum of a data stream.
* This is a modified version based on adler32.c from the zlib library.
*
* Copyright (C) 1995 Mark Adler
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "config.h"
#include "adler32.h"
#define BASE 65521L /* largest prime smaller than 65536 */
#define DO1(buf) { s1 += *buf++; s2 += s1; }
#define DO4(buf) DO1(buf); DO1(buf); DO1(buf); DO1(buf);
#define DO16(buf) DO4(buf); DO4(buf); DO4(buf); DO4(buf);
unsigned long av_adler32_update(unsigned long adler, const uint8_t * buf,
unsigned int len)
{
unsigned long s1 = adler & 0xffff;
unsigned long s2 = adler >> 16;
while (len > 0) {
#if CONFIG_SMALL
while (len > 4 && s2 < (1U << 31)) {
DO4(buf);
len -= 4;
}
#else
while (len > 16 && s2 < (1U << 31)) {
DO16(buf);
len -= 16;
}
#endif
DO1(buf); len--;
s1 %= BASE;
s2 %= BASE;
}
return (s2 << 16) | s1;
}
#ifdef TEST
#include <string.h>
#include "log.h"
#include "timer.h"
#define LEN 7001
static volatile int checksum;
int main(int argc, char **argv)
{
int i;
char data[LEN];
av_log_set_level(AV_LOG_DEBUG);
for (i = 0; i < LEN; i++)
data[i] = ((i * i) >> 3) + 123 * i;
if (argc > 1 && !strcmp(argv[1], "-t")) {
for (i = 0; i < 1000; i++) {
START_TIMER;
checksum = av_adler32_update(1, data, LEN);
STOP_TIMER("adler");
}
} else {
checksum = av_adler32_update(1, data, LEN);
}
av_log(NULL, AV_LOG_DEBUG, "%X (expected 50E6E508)\n", checksum);
return checksum == 0x50e6e508 ? 0 : 1;
}
#endif
| 28.344444 | 77 | 0.607997 |
369784795129d7bcf0e7c7ad815e595ad61ff46d | 121,192 | c | C | bcftools/vcfannotate.c | arogozhnikov/pysam | 22626cd835503c33f777e8e9f4684130e87177f9 | [
"MIT"
] | 1 | 2020-11-12T09:46:51.000Z | 2020-11-12T09:46:51.000Z | bcftools/vcfannotate.c | fo40225/pysam | 7cfb1ead3393c901d6eaf33cc0b945ef480af586 | [
"MIT"
] | null | null | null | bcftools/vcfannotate.c | fo40225/pysam | 7cfb1ead3393c901d6eaf33cc0b945ef480af586 | [
"MIT"
] | null | null | null | /* vcfannotate.c -- Annotate and edit VCF/BCF files.
Copyright (C) 2013-2019 Genome Research Ltd.
Author: Petr Danecek <pd3@sanger.ac.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#include <stdio.h>
#include <strings.h>
#include <unistd.h>
#include <getopt.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <math.h>
#include <inttypes.h>
#include <htslib/vcf.h>
#include <htslib/synced_bcf_reader.h>
#include <htslib/kseq.h>
#include <htslib/khash_str2int.h>
#include "bcftools.h"
#include "vcmp.h"
#include "filter.h"
#include "convert.h"
#include "smpl_ilist.h"
#include "regidx.h"
struct _args_t;
typedef struct _rm_tag_t
{
char *key;
int hdr_id;
void (*handler)(struct _args_t *, bcf1_t *, struct _rm_tag_t *);
}
rm_tag_t;
typedef struct
{
char **cols;
int ncols, mcols;
char **als;
int nals, mals;
kstring_t line;
int rid, start, end;
}
annot_line_t;
#define REPLACE_MISSING 0 // replace only missing values
#define REPLACE_ALL 1 // replace both missing and existing values
#define REPLACE_NON_MISSING 2 // replace only if tgt is not missing
#define SET_OR_APPEND 3 // set new value if missing or non-existent, append otherwise
#define MM_FIRST 0 // if multiple annotation lines overlap a VCF record, use the first, discarding the rest
#define MM_APPEND 1 // append, possibly multiple times
#define MM_UNIQUE 2 // append, only unique values
#define MM_SUM 3
#define MM_AVG 4
#define MM_MIN 5
#define MM_MAX 6
typedef struct _annot_col_t
{
int icol, replace, number; // number: one of BCF_VL_* types
char *hdr_key_src, *hdr_key_dst;
int (*setter)(struct _args_t *, bcf1_t *, struct _annot_col_t *, void*);
int merge_method; // one of the MM_* defines
khash_t(str2int) *mm_str_hash; // lookup table to ensure uniqueness of added string values
kstring_t mm_kstr;
double
mm_dbl_nalloc, // the allocated size --merge-logic values array
mm_dbl_nused, // the number of used elements in the mm_dbl array
mm_dbl_ndat, // the number of merged rows (for calculating the average)
*mm_dbl;
}
annot_col_t;
// Logic of the filters: include or exclude sites which match the filters?
#define FLT_INCLUDE 1
#define FLT_EXCLUDE 2
#define MARK_LISTED 1
#define MARK_UNLISTED 2
typedef struct _args_t
{
bcf_srs_t *files;
bcf_hdr_t *hdr, *hdr_out;
htsFile *out_fh;
int output_type, n_threads;
bcf_sr_regions_t *tgts;
regidx_t *tgt_idx;
regitr_t *tgt_itr;
int tgt_is_bed;
filter_t *filter;
char *filter_str;
int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
int keep_sites;
rm_tag_t *rm; // tags scheduled for removal
int nrm;
int flt_keep_pass; // when all filters removed, reset to PASS
vcmp_t *vcmp; // for matching annotation and VCF lines by allele
annot_line_t *alines; // buffered annotation lines
int nalines, malines;
int ref_idx, alt_idx, chr_idx, beg_idx, end_idx; // -1 if not present
annot_col_t *cols; // column indexes and setters
int ncols;
char *set_ids_fmt;
convert_t *set_ids;
int set_ids_replace;
int nsmpl_annot;
int *sample_map, nsample_map, sample_is_file; // map[idst] -> isrc
uint8_t *src_smpl_pld, *dst_smpl_pld; // for Number=G format fields
int mtmpi, mtmpf, mtmps;
int mtmpi2, mtmpf2, mtmps2;
int mtmpi3, mtmpf3, mtmps3;
int32_t *tmpi, *tmpi2, *tmpi3;
float *tmpf, *tmpf2, *tmpf3;
char *tmps, *tmps2, **tmpp, **tmpp2;
kstring_t tmpks;
char **argv, *output_fname, *targets_fname, *regions_list, *header_fname;
char *remove_annots, *columns, *rename_chrs, *sample_names, *mark_sites;
char *merge_method_str;
int argc, drop_header, record_cmd_line, tgts_is_vcf, mark_sites_logic, force, single_overlaps;
}
args_t;
char *msprintf(const char *fmt, ...);
int parse_with_payload(const char *line, char **chr_beg, char **chr_end, uint32_t *beg, uint32_t *end, void *payload, void *usr)
{
args_t *args = (args_t*) usr;
int ret = args->tgt_is_bed ? regidx_parse_bed(line, chr_beg, chr_end, beg, end, NULL, NULL) : regidx_parse_tab(line, chr_beg, chr_end, beg, end, NULL, NULL);
if ( ret<0 ) return ret;
*((char **)payload) = strdup(line);
return 0;
}
void free_payload(void *payload)
{
char *str = *((char**)payload);
free(str);
}
void remove_id(args_t *args, bcf1_t *line, rm_tag_t *tag)
{
bcf_update_id(args->hdr,line,NULL);
}
void remove_filter(args_t *args, bcf1_t *line, rm_tag_t *tag)
{
if ( tag->key && tag->hdr_id<0 )
{
error("Error: Cannot proceed, not even with the --force option, bad things could happen.\n"
" Note that \"bcftools annotate -x FILTER\" can be used to remove ALL filters.\n"
" Even better, use \"bcftools view -h\" and \"bcftools reheader\" to fix the header!\n"
);
}
if ( !tag->key ) bcf_update_filter(args->hdr, line, NULL, args->flt_keep_pass);
else bcf_remove_filter(args->hdr, line, tag->hdr_id, args->flt_keep_pass);
}
void remove_qual(args_t *args, bcf1_t *line, rm_tag_t *tag)
{
bcf_float_set_missing(line->qual);
}
void remove_info(args_t *args, bcf1_t *line, rm_tag_t *tag)
{
// remove all INFO fields
if ( !(line->unpacked & BCF_UN_INFO) ) bcf_unpack(line, BCF_UN_INFO);
int i;
for (i=0; i<line->n_info; i++)
{
bcf_info_t *inf = &line->d.info[i];
if ( inf->vptr_free )
{
free(inf->vptr - inf->vptr_off);
inf->vptr_free = 0;
}
line->d.shared_dirty |= BCF1_DIRTY_INF;
inf->vptr = NULL;
inf->vptr_off = inf->vptr_len = 0;
}
}
void remove_info_tag(args_t *args, bcf1_t *line, rm_tag_t *tag)
{
bcf_update_info(args->hdr, line, tag->key, NULL, 0, BCF_HT_INT); // the type does not matter with n=0
}
void remove_format_tag(args_t *args, bcf1_t *line, rm_tag_t *tag)
{
bcf_update_format(args->hdr, line, tag->key, NULL, 0, BCF_HT_INT); // the type does not matter with n=0
}
void remove_format(args_t *args, bcf1_t *line, rm_tag_t *tag)
{
// remove all FORMAT fields except GT
if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
int i;
for (i=0; i<line->n_fmt; i++)
{
bcf_fmt_t *fmt = &line->d.fmt[i];
const char *key = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id);
if ( key[0]=='G' && key[1]=='T' && !key[2] ) continue;
if ( fmt->p_free )
{
free(fmt->p - fmt->p_off);
fmt->p_free = 0;
}
line->d.indiv_dirty = 1;
fmt->p = NULL;
}
}
#include "htslib/khash.h"
KHASH_MAP_INIT_STR(vdict, bcf_idinfo_t)
typedef khash_t(vdict) vdict_t;
static void remove_hdr_lines(bcf_hdr_t *hdr, int type)
{
int i = 0, nrm = 0;
while ( i<hdr->nhrec )
{
if ( hdr->hrec[i]->type!=type ) { i++; continue; }
bcf_hrec_t *hrec = hdr->hrec[i];
if ( type==BCF_HL_FMT || type==BCF_HL_INFO || type==BCF_HL_FMT || type== BCF_HL_CTG )
{
// everything except FORMAT/GT
int id = bcf_hrec_find_key(hrec, "ID");
if ( id>=0 )
{
if ( type==BCF_HL_FMT && !strcmp(hrec->vals[id],"GT") ) { i++; continue; }
vdict_t *d = type==BCF_HL_CTG ? (vdict_t*)hdr->dict[BCF_DT_CTG] : (vdict_t*)hdr->dict[BCF_DT_ID];
khint_t k = kh_get(vdict, d, hdr->hrec[i]->vals[id]);
kh_val(d, k).hrec[type==BCF_HL_CTG?0:type] = NULL;
kh_val(d, k).info[type] |= 0xf;
}
}
nrm++;
hdr->nhrec--;
if ( i < hdr->nhrec )
memmove(&hdr->hrec[i],&hdr->hrec[i+1],(hdr->nhrec-i)*sizeof(bcf_hrec_t*));
bcf_hrec_destroy(hrec);
}
if ( nrm ) {
if (bcf_hdr_sync(hdr) < 0)
error_errno("[%s] Failed to update header", __func__);
}
}
static void init_remove_annots(args_t *args)
{
int keep_info = 0, keep_fmt = 0, keep_flt = 0;
void *keep = khash_str2int_init();
kstring_t str = {0,0,0};
char *ss = args->remove_annots;
while ( *ss )
{
args->nrm++;
args->rm = (rm_tag_t*) realloc(args->rm,sizeof(rm_tag_t)*args->nrm);
rm_tag_t *tag = &args->rm[args->nrm-1];
tag->key = NULL;
int type = BCF_HL_GEN;
if ( !strncasecmp("INFO/",ss,5) ) { type = BCF_HL_INFO; ss += 5; }
else if ( !strncasecmp("INF/",ss,4) ) { type = BCF_HL_INFO; ss += 4; }
else if ( !strncasecmp("FORMAT/",ss,7) ) { type = BCF_HL_FMT; ss += 7; }
else if ( !strncasecmp("FMT/",ss,4) ) { type = BCF_HL_FMT; ss += 4; }
else if ( !strncasecmp("FILTER/",ss,7) ) { type = BCF_HL_FLT; ss += 7; }
else if ( !strncasecmp("^INFO/",ss,6) ) { type = BCF_HL_INFO; ss += 6; keep_info = 1; }
else if ( !strncasecmp("^INF/",ss,5) ) { type = BCF_HL_INFO; ss += 5; keep_info = 1; }
else if ( !strncasecmp("^FORMAT/",ss,8) ) { type = BCF_HL_FMT; ss += 8; keep_fmt = 1; }
else if ( !strncasecmp("^FMT/",ss,5) ) { type = BCF_HL_FMT; ss += 5; keep_fmt = 1; }
else if ( !strncasecmp("^FILTER/",ss,8) ) { type = BCF_HL_FLT; ss += 8; keep_flt = 1; }
char *se = ss;
while ( *se && *se!=',' ) se++;
str.l = 0;
kputsn(ss, se-ss, &str);
if ( type==BCF_HL_FLT )
{
if ( !keep_flt )
{
args->flt_keep_pass = 1;
tag->handler = remove_filter;
tag->key = strdup(str.s);
tag->hdr_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, tag->key);
if ( !bcf_hdr_idinfo_exists(args->hdr,BCF_HL_FLT,tag->hdr_id) )
{
if ( args->keep_sites )
error("Error: The filter \"%s\" is not defined in the header, cannot use the -k option\n", str.s);
else
fprintf(stderr,"Warning: The filter \"%s\" is not defined in the header\n", str.s);
}
else if ( !args->keep_sites ) bcf_hdr_remove(args->hdr_out,BCF_HL_FLT,tag->key);
}
else
{
int value, ret = khash_str2int_get(keep, str.s, &value);
if ( ret==-1 ) khash_str2int_set(keep, strdup(str.s),1<<BCF_HL_FLT);
else khash_str2int_set(keep, str.s, value | 1<<BCF_HL_FLT);
args->nrm--;
}
}
else if ( type!=BCF_HL_GEN )
{
int id = bcf_hdr_id2int(args->hdr,BCF_DT_ID,str.s);
if ( !bcf_hdr_idinfo_exists(args->hdr,type,id) )
{
if ( args->keep_sites )
error("Error: The tag \"%s\" is not defined in the header, cannot use the -k option\n", str.s);
else
fprintf(stderr,"Warning: The tag \"%s\" not defined in the header\n", str.s);
tag->key = strdup(str.s);
if ( type==BCF_HL_INFO ) tag->handler = remove_info_tag;
else if ( type==BCF_HL_FMT ) tag->handler = remove_format_tag;
}
else if ( (type==BCF_HL_FMT && keep_fmt) || (type==BCF_HL_INFO && keep_info) )
{
int value, ret = khash_str2int_get(keep, str.s, &value);
if ( ret==-1 ) khash_str2int_set(keep, strdup(str.s),1<<type);
else khash_str2int_set(keep, str.s, value | 1<<type);
args->nrm--;
}
else
{
tag->key = strdup(str.s);
if ( type==BCF_HL_INFO ) tag->handler = remove_info_tag;
else if ( type==BCF_HL_FMT ) tag->handler = remove_format_tag;
if ( !args->keep_sites ) bcf_hdr_remove(args->hdr_out,type,tag->key);
}
}
else if ( !strcasecmp("ID",str.s) ) tag->handler = remove_id;
else if ( !strcasecmp("FILTER",str.s) )
{
tag->handler = remove_filter;
if ( !args->keep_sites ) remove_hdr_lines(args->hdr_out,BCF_HL_FLT);
}
else if ( !strcasecmp("QUAL",str.s) ) tag->handler = remove_qual;
else if ( !strcasecmp("INFO",str.s) )
{
tag->handler = remove_info;
if ( !args->keep_sites ) remove_hdr_lines(args->hdr_out,BCF_HL_INFO);
}
else if ( !strcasecmp("FMT",str.s) || !strcasecmp("FORMAT",str.s) )
{
tag->handler = remove_format;
if ( !args->keep_sites ) remove_hdr_lines(args->hdr_out,BCF_HL_FMT);
}
else if ( str.l )
{
if ( !args->keep_sites )
{
if ( str.s[0]=='#' && str.s[1]=='#' )
bcf_hdr_remove(args->hdr_out,BCF_HL_GEN,str.s+2);
else
bcf_hdr_remove(args->hdr_out,BCF_HL_STR,str.s);
}
args->nrm--;
}
ss = *se ? se+1 : se;
}
free(str.s);
if ( keep_flt || keep_info || keep_fmt )
{
int j;
for (j=0; j<args->hdr->nhrec; j++)
{
bcf_hrec_t *hrec = args->hdr->hrec[j];
if ( hrec->type!=BCF_HL_FLT && hrec->type!=BCF_HL_INFO && hrec->type!=BCF_HL_FMT ) continue;
if ( !keep_flt && hrec->type==BCF_HL_FLT ) continue;
if ( !keep_info && hrec->type==BCF_HL_INFO ) continue;
if ( !keep_fmt && hrec->type==BCF_HL_FMT ) continue;
int k = bcf_hrec_find_key(hrec,"ID");
assert( k>=0 ); // this should always be true for valid VCFs
int value, ret = khash_str2int_get(keep,hrec->vals[k],&value);
if ( ret==0 && value>>hrec->type ) // keep
{
if ( hrec->type==BCF_HL_FLT && !strcmp("PASS",hrec->vals[k]) ) args->flt_keep_pass = 1;
continue;
}
args->nrm++;
args->rm = (rm_tag_t*) realloc(args->rm,sizeof(rm_tag_t)*args->nrm);
rm_tag_t *tag = &args->rm[args->nrm-1];
if ( hrec->type==BCF_HL_INFO ) tag->handler = remove_info_tag;
else if ( hrec->type==BCF_HL_FMT ) tag->handler = remove_format_tag;
else
{
tag->handler = remove_filter;
tag->hdr_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, hrec->vals[k]);
}
tag->key = strdup(hrec->vals[k]);
if ( !args->keep_sites ) bcf_hdr_remove(args->hdr_out,hrec->type,tag->key);
}
}
khash_str2int_destroy_free(keep);
if ( !args->nrm ) error("No matching tag in -x %s\n", args->remove_annots);
if (bcf_hdr_sync(args->hdr_out) < 0)
error_errno("[%s] Failed to update header", __func__);
}
static void init_header_lines(args_t *args)
{
htsFile *file = hts_open(args->header_fname, "rb");
if ( !file ) error("Error reading %s\n", args->header_fname);
kstring_t str = {0,0,0};
while ( hts_getline(file, KS_SEP_LINE, &str) > 0 )
{
if ( bcf_hdr_append(args->hdr_out,str.s) ) error("Could not parse %s: %s\n", args->header_fname, str.s);
bcf_hdr_append(args->hdr,str.s); // the input file may not have the header line if run with -h (and nothing else)
}
if ( hts_close(file)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->header_fname);
free(str.s);
if (bcf_hdr_sync(args->hdr_out) < 0)
error_errno("[%s] Failed to update output header", __func__);
if (bcf_hdr_sync(args->hdr) < 0)
error_errno("[%s] Failed to update input header", __func__);
}
static int setter_filter(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
if ( !data ) error("Error: the --merge-logic option cannot be used with FILTER (yet?)\n");
// note: so far this works only with one filter, not a list of filters
annot_line_t *tab = (annot_line_t*) data;
if ( tab->cols[col->icol] && tab->cols[col->icol][0]=='.' && !tab->cols[col->icol][1] ) return 0; // don't replace with "."
hts_expand(int,1,args->mtmpi,args->tmpi);
args->tmpi[0] = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, tab->cols[col->icol]);
if ( args->tmpi[0]<0 ) error("The FILTER is not defined in the header: %s\n", tab->cols[col->icol]);
if ( col->replace==SET_OR_APPEND ) { bcf_add_filter(args->hdr_out,line,args->tmpi[0]); return 0; }
if ( col->replace!=REPLACE_MISSING )
{
bcf_update_filter(args->hdr_out,line,NULL,0);
bcf_update_filter(args->hdr_out,line,args->tmpi,1);
return 0;
}
// only update missing FILTER
if ( !(line->unpacked & BCF_UN_FLT) ) bcf_unpack(line, BCF_UN_FLT);
if ( !line->d.n_flt )
bcf_update_filter(args->hdr_out,line,args->tmpi,1);
return 0;
}
static int vcf_setter_filter(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
int i;
bcf1_t *rec = (bcf1_t*) data;
if ( !(rec->unpacked & BCF_UN_FLT) ) bcf_unpack(rec, BCF_UN_FLT);
if ( !(line->unpacked & BCF_UN_FLT) ) bcf_unpack(line, BCF_UN_FLT);
if ( !rec->d.n_flt ) return 0; // don't overwrite with a missing value
if ( col->replace==SET_OR_APPEND || col->replace==REPLACE_MISSING )
{
if ( col->replace==REPLACE_MISSING && line->d.n_flt ) return 0; // only update missing FILTER
for (i=0; i<rec->d.n_flt; i++)
{
const char *flt = bcf_hdr_int2id(args->files->readers[1].header, BCF_DT_ID, rec->d.flt[i]);
bcf_add_filter(args->hdr_out,line,bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, flt));
}
return 0;
}
hts_expand(int,rec->d.n_flt,args->mtmpi,args->tmpi);
for (i=0; i<rec->d.n_flt; i++)
{
const char *flt = bcf_hdr_int2id(args->files->readers[1].header, BCF_DT_ID, rec->d.flt[i]);
args->tmpi[i] = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, flt);
}
bcf_update_filter(args->hdr_out,line,NULL,0);
bcf_update_filter(args->hdr_out,line,args->tmpi,rec->d.n_flt);
return 0;
}
static int setter_id(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
if ( !data ) error("Error: the --merge-logic option cannot be used with ID (yet?)\n");
// possible cases:
// IN ANNOT OUT ACHIEVED_BY
// x y x -c +ID
// x y y -c ID
// x y x,y -c =ID
// x . x -c +ID, ID
// x . . -x ID
// . y y -c +ID, -c ID
//
annot_line_t *tab = (annot_line_t*) data;
if ( tab->cols[col->icol] && tab->cols[col->icol][0]=='.' && !tab->cols[col->icol][1] ) return 0; // don't replace with "."
if ( col->replace==SET_OR_APPEND ) return bcf_add_id(args->hdr_out,line,tab->cols[col->icol]);
if ( col->replace!=REPLACE_MISSING ) return bcf_update_id(args->hdr_out,line,tab->cols[col->icol]);
// running with +ID, only update missing ids
if ( !line->d.id || (line->d.id[0]=='.' && !line->d.id[1]) )
return bcf_update_id(args->hdr_out,line,tab->cols[col->icol]);
return 0;
}
static int vcf_setter_id(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
if ( rec->d.id && rec->d.id[0]=='.' && !rec->d.id[1] ) return 0; // don't replace with "."
if ( col->replace==SET_OR_APPEND ) return bcf_add_id(args->hdr_out,line,rec->d.id);
if ( col->replace!=REPLACE_MISSING ) return bcf_update_id(args->hdr_out,line,rec->d.id);
// running with +ID, only update missing ids
if ( !line->d.id || (line->d.id[0]=='.' && !line->d.id[1]) )
return bcf_update_id(args->hdr_out,line,rec->d.id);
return 0;
}
static int vcf_setter_ref(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
if ( !strcmp(rec->d.allele[0],line->d.allele[0]) ) return 0; // no update necessary
const char **als = (const char**) malloc(sizeof(char*)*line->n_allele);
als[0] = rec->d.allele[0];
int i;
for (i=1; i<line->n_allele; i++) als[i] = line->d.allele[i];
bcf_update_alleles(args->hdr_out, line, als, line->n_allele);
free(als);
return 0;
}
static int vcf_setter_alt(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
int i;
if ( rec->n_allele==line->n_allele )
{
for (i=1; i<rec->n_allele; i++) if ( strcmp(rec->d.allele[i],line->d.allele[i]) ) break;
if ( i==rec->n_allele ) return 0; // no update necessary
}
const char **als = (const char**) malloc(sizeof(char*)*rec->n_allele);
als[0] = line->d.allele[0];
for (i=1; i<rec->n_allele; i++) als[i] = rec->d.allele[i];
bcf_update_alleles(args->hdr_out, line, als, rec->n_allele);
free(als);
return 0;
}
static int setter_qual(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
if ( !data ) error("Error: the --merge-logic option cannot be used with QUAL (yet?)\n");
annot_line_t *tab = (annot_line_t*) data;
char *str = tab->cols[col->icol];
if ( str[0]=='.' && str[1]==0 ) return 0; // empty
if ( col->replace==REPLACE_MISSING && !bcf_float_is_missing(line->qual) ) return 0;
line->qual = strtod(str, &str);
if ( str == tab->cols[col->icol] )
error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
return 0;
}
static int vcf_setter_qual(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
if ( bcf_float_is_missing(rec->qual) ) return 0;
if ( col->replace==REPLACE_MISSING && !bcf_float_is_missing(line->qual) ) return 0;
line->qual = rec->qual;
return 0;
}
static int setter_info_flag(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
if ( !data ) error("Error: the --merge-logic option cannot be used with INFO type=Flag (yet?)\n");
annot_line_t *tab = (annot_line_t*) data;
char *str = tab->cols[col->icol];
if ( str[0]=='.' && str[1]==0 ) return 0;
if ( str[0]=='1' && str[1]==0 ) return bcf_update_info_flag(args->hdr_out,line,col->hdr_key_dst,NULL,1);
if ( str[0]=='0' && str[1]==0 ) return bcf_update_info_flag(args->hdr_out,line,col->hdr_key_dst,NULL,0);
error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
return -1;
}
static int vcf_setter_info_flag(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
int flag = bcf_get_info_flag(args->files->readers[1].header,rec,col->hdr_key_src,NULL,NULL);
bcf_update_info_flag(args->hdr_out,line,col->hdr_key_dst,NULL,flag);
return 0;
}
static int setter_ARinfo_int32(args_t *args, bcf1_t *line, annot_col_t *col, int nals, char **als, int ntmpi)
{
if ( col->number==BCF_VL_A && ntmpi!=nals-1 && (ntmpi!=1 || args->tmpi[0]!=bcf_int32_missing || args->tmpi[1]!=bcf_int32_vector_end) )
error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", ntmpi,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
else if ( col->number==BCF_VL_R && ntmpi!=nals && (ntmpi!=1 || args->tmpi[0]!=bcf_int32_missing || args->tmpi[1]!=bcf_int32_vector_end) )
error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", ntmpi,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int ndst = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
int *map = vcmp_map_ARvalues(args->vcmp,ndst,nals,als,line->n_allele,line->d.allele);
if ( !map ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
// fill in any missing values in the target VCF (or all, if not present)
int ntmpi2 = bcf_get_info_float(args->hdr, line, col->hdr_key_dst, &args->tmpi2, &args->mtmpi2);
if ( ntmpi2 < ndst ) hts_expand(int32_t,ndst,args->mtmpi2,args->tmpi2);
int i;
for (i=0; i<ndst; i++)
{
if ( map[i]<0 )
{
if ( ntmpi2 < ndst ) args->tmpi2[i] = bcf_int32_missing;
continue;
}
if ( ntmpi2==ndst && col->replace==REPLACE_MISSING
&& args->tmpi2[i]!=bcf_int32_missing
&& args->tmpi2[i]!=bcf_int32_vector_end ) continue;
args->tmpi2[i] = args->tmpi[ map[i] ];
}
bcf_update_info_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi2,ndst);
return 0;
}
static int setter_info_int(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
annot_line_t *tab = (annot_line_t*) data;
if ( !tab )
{
if ( col->merge_method!=MM_SUM && col->merge_method!=MM_AVG && col->merge_method!=MM_MIN && col->merge_method!=MM_MAX && col->merge_method!=MM_APPEND )
error("Error: at the moment only the sum,avg,min,max,append options are supported with --merge-logic for INFO type=Integer\n");
}
int i,ntmpi = 0;
if ( tab )
{
char *str = tab->cols[col->icol], *end = str;
if ( str[0]=='.' && str[1]==0 ) return 0;
while ( *end )
{
int val = strtol(str, &end, 10);
if ( end==str )
error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
ntmpi++;
hts_expand(int32_t,ntmpi,args->mtmpi,args->tmpi);
args->tmpi[ntmpi-1] = val;
str = end+1;
}
if ( col->merge_method!=MM_FIRST )
{
if ( !col->mm_dbl_nused )
{
col->mm_dbl_nused = ntmpi;
hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
for (i=0; i<ntmpi; i++)
col->mm_dbl[i] = args->tmpi[i];
}
else
{
if ( col->merge_method==MM_APPEND )
{
int nori = col->mm_dbl_nused;
col->mm_dbl_nused += ntmpi;
hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
for (i=0; i<ntmpi; i++)
col->mm_dbl[i+nori] = args->tmpi[i];
}
else
{
if ( ntmpi!=col->mm_dbl_nused ) error("Error: cannot merge fields of unequal length\n");
if ( col->merge_method==MM_SUM || col->merge_method==MM_AVG )
for (i=0; i<ntmpi; i++) col->mm_dbl[i] += args->tmpi[i];
else if ( col->merge_method==MM_MIN )
for (i=0; i<ntmpi; i++) { if ( col->mm_dbl[i] > args->tmpi[i] ) col->mm_dbl[i] = args->tmpi[i]; }
else if ( col->merge_method==MM_MAX )
for (i=0; i<ntmpi; i++) { if ( col->mm_dbl[i] < args->tmpi[i] ) col->mm_dbl[i] = args->tmpi[i]; }
}
}
col->mm_dbl_ndat++;
}
}
else if ( col->merge_method==MM_SUM || col->merge_method==MM_MIN || col->merge_method==MM_MAX || col->merge_method==MM_APPEND )
{
ntmpi = col->mm_dbl_nused;
hts_expand(int32_t,ntmpi,args->mtmpi,args->tmpi);
for (i=0; i<ntmpi; i++) args->tmpi[i] = col->mm_dbl[i];
col->mm_dbl_nused = col->mm_dbl_ndat = 0;
}
else if ( col->merge_method==MM_AVG )
{
ntmpi = col->mm_dbl_nused;
hts_expand(int32_t,ntmpi,args->mtmpi,args->tmpi);
for (i=0; i<ntmpi; i++) args->tmpi[i] = col->mm_dbl[i]/col->mm_dbl_ndat;
col->mm_dbl_nused = col->mm_dbl_ndat = 0;
}
if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
return setter_ARinfo_int32(args,line,col,tab->nals,tab->als,ntmpi);
if ( col->replace==REPLACE_MISSING )
{
int ret = bcf_get_info_int32(args->hdr, line, col->hdr_key_dst, &args->tmpi2, &args->mtmpi2);
if ( ret>0 && args->tmpi2[0]!=bcf_int32_missing ) return 0;
}
bcf_update_info_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi,ntmpi);
return 0;
}
static int vcf_setter_info_int(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
int ntmpi = bcf_get_info_int32(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpi,&args->mtmpi);
if ( ntmpi < 0 ) return 0; // nothing to add
if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
return setter_ARinfo_int32(args,line,col,rec->n_allele,rec->d.allele,ntmpi);
if ( col->replace==REPLACE_MISSING )
{
int ret = bcf_get_info_int32(args->hdr, line, col->hdr_key_dst, &args->tmpi2, &args->mtmpi2);
if ( ret>0 && args->tmpi2[0]!=bcf_int32_missing ) return 0;
}
bcf_update_info_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi,ntmpi);
return 0;
}
static int setter_ARinfo_real(args_t *args, bcf1_t *line, annot_col_t *col, int nals, char **als, int ntmpf)
{
if ( col->number==BCF_VL_A && ntmpf!=nals-1 && (ntmpf!=1 || !bcf_float_is_missing(args->tmpf[0]) || !bcf_float_is_vector_end(args->tmpf[0])) )
error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", ntmpf,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
else if ( col->number==BCF_VL_R && ntmpf!=nals && (ntmpf!=1 || !bcf_float_is_missing(args->tmpf[0]) || !bcf_float_is_vector_end(args->tmpf[0])) )
error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", ntmpf,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int ndst = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
int *map = vcmp_map_ARvalues(args->vcmp,ndst,nals,als,line->n_allele,line->d.allele);
if ( !map ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
// fill in any missing values in the target VCF (or all, if not present)
int ntmpf2 = bcf_get_info_float(args->hdr, line, col->hdr_key_dst, &args->tmpf2, &args->mtmpf2);
if ( ntmpf2 < ndst ) hts_expand(float,ndst,args->mtmpf2,args->tmpf2);
int i;
for (i=0; i<ndst; i++)
{
if ( map[i]<0 )
{
if ( ntmpf2 < ndst ) bcf_float_set_missing(args->tmpf2[i]);
continue;
}
if ( ntmpf2==ndst && col->replace==REPLACE_MISSING
&& !bcf_float_is_missing(args->tmpf2[i])
&& !bcf_float_is_vector_end(args->tmpf2[i]) ) continue;
args->tmpf2[i] = args->tmpf[ map[i] ];
}
bcf_update_info_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf2,ndst);
return 0;
}
static int setter_info_real(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
annot_line_t *tab = (annot_line_t*) data;
if ( !tab )
{
if ( col->merge_method!=MM_SUM && col->merge_method!=MM_AVG && col->merge_method!=MM_MIN && col->merge_method!=MM_MAX && col->merge_method!=MM_APPEND )
error("Error: at the moment only the sum,avg,min,max,append options are supported with --merge-logic for INFO type=Float\n");
}
int i,ntmpf = 0;
if ( tab )
{
char *str = tab->cols[col->icol], *end = str;
if ( str[0]=='.' && str[1]==0 ) return 0;
while ( *end )
{
double val = strtod(str, &end);
if ( end==str )
error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
ntmpf++;
hts_expand(float,ntmpf,args->mtmpf,args->tmpf);
args->tmpf[ntmpf-1] = val;
str = end+1;
}
if ( col->merge_method!=MM_FIRST )
{
if ( !col->mm_dbl_nused )
{
col->mm_dbl_nused = ntmpf;
hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
for (i=0; i<ntmpf; i++)
col->mm_dbl[i] = args->tmpf[i];
}
else
{
if ( col->merge_method==MM_APPEND )
{
int nori = col->mm_dbl_nused;
col->mm_dbl_nused += ntmpf;
hts_expand(double,col->mm_dbl_nused,col->mm_dbl_nalloc,col->mm_dbl);
for (i=0; i<ntmpf; i++)
col->mm_dbl[i+nori] = args->tmpf[i];
}
else
{
if ( ntmpf!=col->mm_dbl_nused ) error("Error: cannot merge fields of unequal length\n");
if ( col->merge_method==MM_SUM || col->merge_method==MM_AVG )
for (i=0; i<ntmpf; i++) col->mm_dbl[i] += args->tmpf[i];
else if ( col->merge_method==MM_MIN )
for (i=0; i<ntmpf; i++) { if ( col->mm_dbl[i] > args->tmpf[i] ) col->mm_dbl[i] = args->tmpf[i]; }
else if ( col->merge_method==MM_MAX )
for (i=0; i<ntmpf; i++) { if ( col->mm_dbl[i] < args->tmpf[i] ) col->mm_dbl[i] = args->tmpf[i]; }
}
}
col->mm_dbl_ndat++;
}
}
else if ( col->merge_method==MM_SUM || col->merge_method==MM_MIN || col->merge_method==MM_MAX || col->merge_method==MM_APPEND )
{
ntmpf = col->mm_dbl_nused;
hts_expand(int32_t,ntmpf,args->mtmpf,args->tmpf);
for (i=0; i<ntmpf; i++) args->tmpf[i] = col->mm_dbl[i];
col->mm_dbl_nused = col->mm_dbl_ndat = 0;
}
else if ( col->merge_method==MM_AVG )
{
ntmpf = col->mm_dbl_nused;
hts_expand(int32_t,ntmpf,args->mtmpf,args->tmpf);
for (i=0; i<ntmpf; i++) args->tmpf[i] = col->mm_dbl[i]/col->mm_dbl_ndat;
col->mm_dbl_nused = col->mm_dbl_ndat = 0;
}
if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
return setter_ARinfo_real(args,line,col,tab->nals,tab->als,ntmpf);
if ( col->replace==REPLACE_MISSING )
{
int ret = bcf_get_info_float(args->hdr, line, col->hdr_key_dst, &args->tmpf2, &args->mtmpf2);
if ( ret>0 && !bcf_float_is_missing(args->tmpf2[0]) ) return 0;
}
bcf_update_info_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf,ntmpf);
return 0;
}
static int vcf_setter_info_real(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
int ntmpf = bcf_get_info_float(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpf,&args->mtmpf);
if ( ntmpf < 0 ) return 0; // nothing to add
if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
return setter_ARinfo_real(args,line,col,rec->n_allele,rec->d.allele,ntmpf);
if ( col->replace==REPLACE_MISSING )
{
int ret = bcf_get_info_float(args->hdr, line, col->hdr_key_dst, &args->tmpf2, &args->mtmpf2);
if ( ret>0 && !bcf_float_is_missing(args->tmpf2[0]) ) return 0;
}
bcf_update_info_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf,ntmpf);
return 0;
}
int copy_string_field(char *src, int isrc, int src_len, kstring_t *dst, int idst); // see vcfmerge.c
static int setter_ARinfo_string(args_t *args, bcf1_t *line, annot_col_t *col, int nals, char **als)
{
assert( col->merge_method==MM_FIRST );
int nsrc = 1, lsrc = 0;
while ( args->tmps[lsrc] )
{
if ( args->tmps[lsrc]==',' ) nsrc++;
lsrc++;
}
if ( col->number==BCF_VL_A && nsrc!=nals-1 && (nsrc!=1 || args->tmps[0]!='.' || args->tmps[1]!=0 ) )
error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", nsrc,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
else if ( col->number==BCF_VL_R && nsrc!=nals && (nsrc!=1 || args->tmps[0]!='.' || args->tmps[1]!=0 ) )
error("Incorrect number of values (%d) for the %s tag at %s:%"PRId64"\n", nsrc,col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int ndst = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
int *map = vcmp_map_ARvalues(args->vcmp,ndst,nals,als,line->n_allele,line->d.allele);
if ( !map ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
// fill in any missing values in the target VCF (or all, if not present)
int i, empty = 0, nstr, mstr = args->tmpks.m;
nstr = bcf_get_info_string(args->hdr, line, col->hdr_key_dst, &args->tmpks.s, &mstr);
args->tmpks.m = mstr;
if ( nstr<0 || (nstr==1 && args->tmpks.s[0]=='.' && args->tmpks.s[1]==0) )
{
empty = 0;
args->tmpks.l = 0;
kputc('.',&args->tmpks);
for (i=1; i<ndst; i++) kputs(",.",&args->tmpks);
}
else args->tmpks.l = nstr;
for (i=0; i<ndst; i++)
{
if ( map[i]<0 )
{
if ( empty ) copy_string_field(".",0,1,&args->tmpks,i);
continue;
}
if ( col->replace==REPLACE_MISSING )
{
// Do not replace filled values. The field must be looked up again because
// of realloc in copy_string_field
int n = 0;
char *str = args->tmpks.s;
while ( *str && n<i )
{
if ( *str==',' ) n++;
str++;
}
if ( str[0]!='.' || (str[1]!=',' && str[1]!=0) ) continue; // value already set
}
int ret = copy_string_field(args->tmps,map[i],lsrc,&args->tmpks,i);
assert( ret==0 );
}
bcf_update_info_string(args->hdr_out,line,col->hdr_key_dst,args->tmpks.s);
return 0;
}
void khash_str2int_clear_free(void *_hash)
{
khash_t(str2int) *hash = (khash_t(str2int)*)_hash;
khint_t k;
if (hash == 0) return;
for (k = 0; k < kh_end(hash); ++k)
if (kh_exist(hash, k)) free((char*)kh_key(hash, k));
kh_clear(str2int, hash);
}
static int setter_info_str(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
if ( col->replace==REPLACE_MISSING && col->number!=BCF_VL_A && col->number!=BCF_VL_R )
{
int ret = bcf_get_info_string(args->hdr, line, col->hdr_key_dst, &args->tmps2, &args->mtmps2);
if ( ret>0 && (args->tmps2[0]!='.' || args->tmps2[1]!=0) ) return 0;
}
annot_line_t *tab = (annot_line_t*) data;
int len = 0;
if ( tab )
{
len = strlen(tab->cols[col->icol]);
if ( !len ) return 0;
if ( len==1 && tab->cols[col->icol][0]=='.' ) return 0;
}
if ( col->merge_method!=MM_FIRST )
{
if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
error("Error: the --merge-logic option cannot be used with INFO tags Type=String,Number={A,R,G}\n");
if ( data )
{
assert( col->merge_method==MM_APPEND || col->merge_method==MM_UNIQUE );
if ( col->merge_method==MM_UNIQUE )
{
if ( !col->mm_str_hash ) col->mm_str_hash = (khash_t(str2int)*)khash_str2int_init();
if ( khash_str2int_has_key(col->mm_str_hash, tab->cols[col->icol]) ) return 0;
khash_str2int_inc(col->mm_str_hash, strdup(tab->cols[col->icol]));
}
if ( col->mm_kstr.l ) kputc(',',&col->mm_kstr);
kputs(tab->cols[col->icol], &col->mm_kstr);
return 0;
}
if ( col->mm_kstr.l )
{
hts_expand(char,col->mm_kstr.l+1,args->mtmps,args->tmps);
memcpy(args->tmps,col->mm_kstr.s,col->mm_kstr.l+1);
}
else
return 0;
if ( !data ) // flush the line
{
if ( col->merge_method==MM_UNIQUE )
khash_str2int_clear_free(col->mm_str_hash);
col->mm_kstr.l = 0;
}
}
else
{
assert(tab);
hts_expand(char,len+1,args->mtmps,args->tmps);
memcpy(args->tmps,tab->cols[col->icol],len+1);
if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
return setter_ARinfo_string(args,line,col,tab->nals,tab->als);
}
bcf_update_info_string(args->hdr_out,line,col->hdr_key_dst,args->tmps);
return 0;
}
static int vcf_setter_info_str(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
int ntmps = bcf_get_info_string(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmps,&args->mtmps);
if ( ntmps < 0 ) return 0; // nothing to add
if ( col->number==BCF_VL_A || col->number==BCF_VL_R )
return setter_ARinfo_string(args,line,col,rec->n_allele,rec->d.allele);
if ( col->replace==REPLACE_MISSING )
{
int ret = bcf_get_info_string(args->hdr, line, col->hdr_key_dst, &args->tmps2, &args->mtmps2);
if ( ret>0 && (args->tmps2[0]!='.' || args->tmps2[1]!=0) ) return 0;
}
bcf_update_info_string(args->hdr_out,line,col->hdr_key_dst,args->tmps);
return 0;
}
static int genotypes_to_string(args_t *args, int nsrc1, int32_t *src, int nsmpl_dst, kstring_t *str)
{
int i, isrc, idst;
int blen = nsrc1 > 1 ? nsrc1 + 1 : 1; // typically the genotypes take three bytes 0/1, no 0-termination is needed
gt_length_too_big:
str->l = 0;
for (idst=0; idst<nsmpl_dst; idst++)
{
isrc = args->sample_map ? args->sample_map[idst] : idst;
if ( isrc==-1 )
{
kputc_('.', str);
for (i=1; i < blen; i++) kputc_(0, str);
continue;
}
size_t plen = str->l;
int32_t *ptr = src + isrc*nsrc1;
for (i=0; i<nsrc1 && ptr[i]!=bcf_int32_vector_end; i++)
{
if ( i ) kputc("/|"[bcf_gt_is_phased(ptr[i])], str);
if ( bcf_gt_is_missing(ptr[i]) ) kputc('.', str);
else kputw(bcf_gt_allele(ptr[i]), str);
}
if ( i==0 ) kputc('.', str);
if ( str->l - plen > blen )
{
// too many alternate alleles or ploidy is too large, the genotype does not fit
// three characters ("0/0" vs "10/10").
blen *= 2;
goto gt_length_too_big;
}
plen = str->l - plen;
while ( plen < blen )
{
kputc_(0, str);
plen++;
}
}
return 0;
}
static int vcf_setter_format_gt(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
int nsrc = bcf_get_genotypes(args->files->readers[1].header,rec,&args->tmpi,&args->mtmpi);
if ( nsrc==-3 ) return 0; // the tag is not present
if ( nsrc<=0 ) return 1; // error
// Genotypes are internally represented as integers. This is a complication when
// adding as a different Type=String field, such as FMT/newGT:=GT
if ( strcmp(col->hdr_key_src,col->hdr_key_dst) )
{
int nsmpl_dst = bcf_hdr_nsamples(args->hdr_out);
int nsmpl_src = bcf_hdr_nsamples(args->files->readers[1].header);
genotypes_to_string(args,nsrc/nsmpl_src,args->tmpi,nsmpl_dst,&args->tmpks);
return bcf_update_format_char(args->hdr_out,line,col->hdr_key_dst,args->tmpks.s,args->tmpks.l);
}
if ( !args->sample_map )
return bcf_update_genotypes(args->hdr_out,line,args->tmpi,nsrc);
int i, j, ndst = bcf_get_genotypes(args->hdr,line,&args->tmpi2,&args->mtmpi2);
if ( ndst > 0 ) ndst /= bcf_hdr_nsamples(args->hdr_out);
nsrc /= bcf_hdr_nsamples(args->files->readers[1].header);
if ( ndst<=0 ) // field not present in dst file
{
if ( col->replace==REPLACE_NON_MISSING ) return 0;
hts_expand(int32_t, nsrc*bcf_hdr_nsamples(args->hdr_out), args->mtmpi2, args->tmpi2);
for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
{
int32_t *dst = args->tmpi2 + nsrc*i;
if ( args->sample_map[i]==-1 )
{
dst[0] = bcf_gt_missing;
for (j=1; j<nsrc; j++) dst[j] = bcf_int32_vector_end;
}
else
{
int32_t *src = args->tmpi + nsrc*args->sample_map[i];
for (j=0; j<nsrc; j++) dst[j] = src[j];
}
}
return bcf_update_genotypes(args->hdr_out,line,args->tmpi2,nsrc*bcf_hdr_nsamples(args->hdr_out));
}
else if ( ndst >= nsrc )
{
for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
{
if ( args->sample_map[i]==-1 ) continue;
int32_t *src = args->tmpi + nsrc*args->sample_map[i];
int32_t *dst = args->tmpi2 + ndst*i;
if ( col->replace==REPLACE_NON_MISSING && bcf_gt_is_missing(dst[0]) ) continue;
if ( col->replace==REPLACE_MISSING && !bcf_gt_is_missing(dst[0]) ) continue;
for (j=0; j<nsrc; j++) dst[j] = src[j];
for (; j<ndst; j++) dst[j] = bcf_int32_vector_end;
}
return bcf_update_genotypes(args->hdr_out,line,args->tmpi2,ndst*bcf_hdr_nsamples(args->hdr_out));
}
else // ndst < nsrc
{
hts_expand(int32_t, nsrc*bcf_hdr_nsamples(args->hdr_out), args->mtmpi3, args->tmpi3);
for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
{
int32_t *ori = args->tmpi2 + ndst*i;
int32_t *dst = args->tmpi3 + nsrc*i;
int keep_ori = 0;
if ( args->sample_map[i]==-1 ) keep_ori = 1;
else if ( col->replace==REPLACE_NON_MISSING && bcf_gt_is_missing(ori[0]) ) keep_ori = 1;
else if ( col->replace==REPLACE_MISSING && !bcf_gt_is_missing(ori[0]) ) keep_ori = 1;
if ( keep_ori )
{
for (j=0; j<ndst; j++) dst[j] = ori[j];
for (; j<nsrc; j++) dst[j] = bcf_int32_vector_end;
}
else
{
int32_t *src = args->tmpi + nsrc*args->sample_map[i];
for (j=0; j<nsrc; j++) dst[j] = src[j];
}
}
return bcf_update_genotypes(args->hdr_out,line,args->tmpi3,nsrc*bcf_hdr_nsamples(args->hdr_out));
}
}
static int count_vals(annot_line_t *tab, int icol_beg, int icol_end)
{
int i, nmax = 1;
for (i=icol_beg; i<icol_end; i++)
{
char *str = tab->cols[i], *end = str;
if ( str[0]=='.' && !str[1] )
{
// missing value
if ( !nmax ) nmax = 1;
continue;
}
int n = 1;
while ( *end )
{
if ( *end==',' ) n++;
end++;
}
if ( nmax<n ) nmax = n;
}
return nmax;
}
static int core_setter_format_int(args_t *args, bcf1_t *line, annot_col_t *col, int32_t *vals, int nvals)
{
if ( !args->sample_map )
return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,vals,nvals*args->nsmpl_annot);
int i, j, ndst = bcf_get_format_int32(args->hdr,line,col->hdr_key_dst,&args->tmpi2,&args->mtmpi2);
if ( ndst > 0 ) ndst /= bcf_hdr_nsamples(args->hdr_out);
if ( ndst<=0 )
{
if ( col->replace==REPLACE_NON_MISSING ) return 0; // overwrite only if present
hts_expand(int32_t, nvals*bcf_hdr_nsamples(args->hdr_out), args->mtmpi2, args->tmpi2);
for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
{
int32_t *dst = args->tmpi2 + nvals*i;
if ( args->sample_map[i]==-1 )
{
dst[0] = bcf_int32_missing;
for (j=1; j<nvals; j++) dst[j] = bcf_int32_vector_end;
}
else
{
int32_t *src = vals + nvals*args->sample_map[i];
for (j=0; j<nvals; j++) dst[j] = src[j];
}
}
return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi2,nvals*bcf_hdr_nsamples(args->hdr_out));
}
else if ( ndst >= nvals )
{
for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
{
if ( args->sample_map[i]==-1 ) continue;
int32_t *src = vals + nvals*args->sample_map[i];
int32_t *dst = args->tmpi2 + ndst*i;
// possible cases:
// in annot out
// x y x TAG,-TAG,=TAG .. REPLACE_ALL, REPLACE_NON_MISSING, SET_OR_APPEND
// x y y +TAG .. REPLACE_MISSING
// . y . =TAG .. SET_OR_APPEND
// . y y TAG,+TAG,-TAG .. REPLACE_ALL, REPLACE_MISSING, REPLACE_NON_MISSING
// x . x TAG,+TAG .. REPLACE_ALL, REPLACE_MISSING
// x . . -TAG .. REPLACE_NON_MISSING
if ( col->replace==REPLACE_NON_MISSING ) { if ( dst[0]==bcf_int32_missing ) continue; }
else if ( col->replace==REPLACE_MISSING ) { if ( dst[0]!=bcf_int32_missing ) continue; }
else if ( col->replace==REPLACE_ALL ) { if ( src[0]==bcf_int32_missing ) continue; }
for (j=0; j<nvals; j++) dst[j] = src[j];
for (; j<ndst; j++) dst[j] = bcf_int32_vector_end;
}
return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi2,ndst*bcf_hdr_nsamples(args->hdr_out));
}
else // ndst < nvals
{
hts_expand(int32_t, nvals*bcf_hdr_nsamples(args->hdr_out), args->mtmpi3, args->tmpi3);
for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
{
int32_t *ann = vals + nvals*args->sample_map[i];
int32_t *ori = args->tmpi2 + ndst*i; // ori vcf line
int32_t *dst = args->tmpi3 + nvals*i; // expanded buffer
int use_new_ann = 1;
if ( args->sample_map[i]==-1 ) use_new_ann = 0;
else if ( col->replace==REPLACE_NON_MISSING ) { if ( ori[0]==bcf_int32_missing ) use_new_ann = 0; }
else if ( col->replace==REPLACE_MISSING ) { if ( ori[0]!=bcf_int32_missing ) use_new_ann = 0; }
else if ( col->replace==REPLACE_ALL ) { if ( ann[0]==bcf_int32_missing ) use_new_ann = 0; }
if ( !use_new_ann )
{
for (j=0; j<ndst; j++) dst[j] = ori[j];
for (; j<nvals; j++) dst[j] = bcf_int32_vector_end;
}
else
for (j=0; j<nvals; j++) dst[j] = ann[j];
}
return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi3,nvals*bcf_hdr_nsamples(args->hdr_out));
}
}
static int core_setter_format_real(args_t *args, bcf1_t *line, annot_col_t *col, float *vals, int nvals)
{
if ( !args->sample_map )
return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,vals,nvals*args->nsmpl_annot);
int i, j, ndst = bcf_get_format_float(args->hdr,line,col->hdr_key_dst,&args->tmpf2,&args->mtmpf2);
if ( ndst > 0 ) ndst /= bcf_hdr_nsamples(args->hdr_out);
if ( ndst<=0 )
{
if ( col->replace==REPLACE_NON_MISSING ) return 0; // overwrite only if present
hts_expand(float, nvals*bcf_hdr_nsamples(args->hdr_out), args->mtmpf2, args->tmpf2);
for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
{
float *dst = args->tmpf2 + nvals*i;
if ( args->sample_map[i]==-1 )
{
bcf_float_set_missing(dst[0]);
for (j=1; j<nvals; j++) bcf_float_set_vector_end(dst[j]);
}
else
{
float *src = vals + nvals*args->sample_map[i];
for (j=0; j<nvals; j++) dst[j] = src[j];
}
}
return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf2,nvals*bcf_hdr_nsamples(args->hdr_out));
}
else if ( ndst >= nvals )
{
for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
{
if ( args->sample_map[i]==-1 ) continue;
float *src = vals + nvals*args->sample_map[i];
float *dst = args->tmpf2 + ndst*i;
if ( col->replace==REPLACE_NON_MISSING ) { if ( bcf_float_is_missing(dst[0]) ) continue; }
else if ( col->replace==REPLACE_MISSING ) { if ( !bcf_float_is_missing(dst[0]) ) continue; }
else if ( col->replace==REPLACE_ALL ) { if ( bcf_float_is_missing(src[0]) ) continue; }
for (j=0; j<nvals; j++) dst[j] = src[j];
for (; j<ndst; j++) bcf_float_set_vector_end(dst[j]);
}
return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf2,ndst*bcf_hdr_nsamples(args->hdr_out));
}
else // ndst < nvals
{
hts_expand(float, nvals*bcf_hdr_nsamples(args->hdr_out), args->mtmpf3, args->tmpf3);
for (i=0; i<bcf_hdr_nsamples(args->hdr_out); i++)
{
float *ann = vals + nvals*args->sample_map[i];
float *ori = args->tmpf2 + ndst*i; // ori vcf line
float *dst = args->tmpf3 + nvals*i; // expanded buffer
int use_new_ann = 1;
if ( args->sample_map[i]==-1 ) use_new_ann = 0;
else if ( col->replace==REPLACE_NON_MISSING ) { if ( bcf_float_is_missing(ori[0]) ) use_new_ann = 0; }
else if ( col->replace==REPLACE_MISSING ) { if ( !bcf_float_is_missing(ori[0]) ) use_new_ann = 0; }
else if ( col->replace==REPLACE_ALL ) { if ( bcf_float_is_missing(ann[0]) ) use_new_ann = 0; }
if ( !use_new_ann )
{
for (j=0; j<ndst; j++) dst[j] = ori[j];
for (; j<nvals; j++) bcf_float_set_vector_end(dst[j]);
}
else
for (j=0; j<nvals; j++) dst[j] = ann[j];
}
return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf3,nvals*bcf_hdr_nsamples(args->hdr_out));
}
}
static int core_setter_format_str(args_t *args, bcf1_t *line, annot_col_t *col, char **vals)
{
if ( !args->sample_map )
return bcf_update_format_string(args->hdr_out,line,col->hdr_key_dst,(const char**)vals,args->nsmpl_annot);
int i;
args->tmpp2[0] = args->tmps2;
int ret = bcf_get_format_string(args->hdr,line,col->hdr_key_dst,&args->tmpp2,&args->mtmps2);
args->tmps2 = args->tmpp2[0]; // tmps2 might be realloced
int nsmpl = bcf_hdr_nsamples(args->hdr_out);
if ( ret<=0 ) // not present in dst
{
hts_expand(char,bcf_hdr_nsamples(args->hdr_out)*2,args->mtmps2,args->tmps2);
char *tmp = args->tmps2;
for (i=0; i<nsmpl; i++)
{
tmp[0] = '.';
tmp[1] = 0;
args->tmpp2[i] = tmp;
tmp += 2;
}
}
for (i=0; i<nsmpl; i++)
{
if ( args->sample_map[i]==-1 ) continue;
char **src = vals + args->sample_map[i];
char **dst = args->tmpp2 + i;
if ( col->replace==REPLACE_NON_MISSING ) { if ( (*dst)[0]=='.' && (*dst)[1]==0 ) continue; }
else if ( col->replace==REPLACE_MISSING ) { if ( (*dst)[0]!='.' || (*dst)[1]!=0 ) continue; }
else if ( col->replace==REPLACE_ALL ) { if ( (*src)[0]=='.' && (*src)[1]==0 ) continue; }
*dst = *src;
}
return bcf_update_format_string(args->hdr_out,line,col->hdr_key_dst,(const char**)args->tmpp2,nsmpl);
}
static int setter_format_int(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
if ( !data ) error("Error: the --merge-logic option cannot be used with FORMAT tags (yet?)\n");
annot_line_t *tab = (annot_line_t*) data;
if ( col->icol+args->nsmpl_annot > tab->ncols )
error("Incorrect number of values for %s at %s:%"PRId64"\n",col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int nvals = count_vals(tab,col->icol,col->icol+args->nsmpl_annot);
hts_expand(int32_t,nvals*args->nsmpl_annot,args->mtmpi,args->tmpi);
int icol = col->icol, ismpl;
for (ismpl=0; ismpl<args->nsmpl_annot; ismpl++)
{
int32_t *ptr = args->tmpi + ismpl*nvals;
int ival = 0;
char *str = tab->cols[icol];
while ( *str )
{
if ( str[0]=='.' && (!str[1] || str[1]==',') ) // missing value
{
ptr[ival++] = bcf_int32_missing;
str += str[1] ? 2 : 1;
continue;
}
char *end = str;
ptr[ival] = strtol(str, &end, 10);
if ( end==str )
error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
ival++;
str = *end ? end+1 : end;
}
while ( ival<nvals ) ptr[ival++] = bcf_int32_vector_end;
icol++;
}
return core_setter_format_int(args,line,col,args->tmpi,nvals);
}
static int setter_format_real(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
if ( !data ) error("Error: the --merge-logic option cannot be used with FORMAT tags (yet?)\n");
annot_line_t *tab = (annot_line_t*) data;
if ( col->icol+args->nsmpl_annot > tab->ncols )
error("Incorrect number of values for %s at %s:%"PRId64"\n",col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int nvals = count_vals(tab,col->icol,col->icol+args->nsmpl_annot);
hts_expand(float,nvals*args->nsmpl_annot,args->mtmpf,args->tmpf);
int icol = col->icol, ismpl;
for (ismpl=0; ismpl<args->nsmpl_annot; ismpl++)
{
float *ptr = args->tmpf + ismpl*nvals;
int ival = 0;
char *str = tab->cols[icol];
while ( *str )
{
if ( str[0]=='.' && (!str[1] || str[1]==',') ) // missing value
{
bcf_float_set_missing(ptr[ival]);
ival++;
str += str[1] ? 2 : 1;
continue;
}
char *end = str;
ptr[ival] = strtod(str, &end);
if ( end==str )
error("Could not parse %s at %s:%"PRId64" .. [%s]\n", col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1,tab->cols[col->icol]);
ival++;
str = *end ? end+1 : end;
}
while ( ival<nvals ) { bcf_float_set_vector_end(ptr[ival]); ival++; }
icol++;
}
return core_setter_format_real(args,line,col,args->tmpf,nvals);
}
static int setter_format_str(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
if ( !data ) error("Error: the --merge-logic option cannot be used with FORMAT tags (yet?)\n");
annot_line_t *tab = (annot_line_t*) data;
if ( col->icol+args->nsmpl_annot > tab->ncols )
error("Incorrect number of values for %s at %s:%"PRId64"\n",col->hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int ismpl;
for (ismpl=0; ismpl<args->nsmpl_annot; ismpl++)
args->tmpp[ismpl] = tab->cols[col->icol + ismpl];
return core_setter_format_str(args,line,col,args->tmpp);
}
static int determine_ploidy(int nals, int *vals, int nvals1, uint8_t *smpl, int nsmpl)
{
int i, j, ndip = nals*(nals+1)/2, max_ploidy = 0;
for (i=0; i<nsmpl; i++)
{
int *ptr = vals + i*nvals1;
int has_value = 0;
for (j=0; j<nvals1; j++)
{
if ( ptr[j]==bcf_int32_vector_end ) break;
if ( ptr[j]!=bcf_int32_missing ) has_value = 1;
}
if ( has_value )
{
if ( j==ndip )
{
smpl[i] = 2;
max_ploidy = 2;
}
else if ( j==nals )
{
smpl[i] = 1;
if ( !max_ploidy ) max_ploidy = 1;
}
else return -j;
}
else smpl[i] = 0;
}
return max_ploidy;
}
static int vcf_setter_format_int(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
int nsrc = bcf_get_format_int32(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpi,&args->mtmpi);
if ( nsrc==-3 ) return 0; // the tag is not present
if ( nsrc<=0 ) return 1; // error
int nsmpl_src = bcf_hdr_nsamples(args->files->readers[1].header);
int nsrc1 = nsrc / nsmpl_src;
if ( col->number!=BCF_VL_G && col->number!=BCF_VL_R && col->number!=BCF_VL_A )
return core_setter_format_int(args,line,col,args->tmpi,nsrc1);
// create mapping from src to dst genotypes, haploid and diploid version
int nmap_hap = col->number==BCF_VL_G || col->number==BCF_VL_R ? rec->n_allele : rec->n_allele - 1;
int *map_hap = vcmp_map_ARvalues(args->vcmp,nmap_hap,line->n_allele,line->d.allele,rec->n_allele,rec->d.allele);
if ( !map_hap ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int i, j;
if ( rec->n_allele==line->n_allele )
{
// alleles unchanged?
for (i=0; i<rec->n_allele; i++) if ( map_hap[i]!=i ) break;
if ( i==rec->n_allele )
return core_setter_format_int(args,line,col,args->tmpi,nsrc1);
}
int nsmpl_dst = rec->n_sample;
int ndst = bcf_get_format_int32(args->hdr,line,col->hdr_key_dst,&args->tmpi2,&args->mtmpi2);
int ndst1 = ndst / nsmpl_dst;
if ( ndst <= 0 )
{
if ( col->replace==REPLACE_NON_MISSING ) return 0; // overwrite only if present
if ( col->number==BCF_VL_G )
ndst1 = line->n_allele*(line->n_allele+1)/2;
else
ndst1 = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
hts_expand(int, ndst1*nsmpl_dst, args->mtmpi2, args->tmpi2);
for (i=0; i<nsmpl_dst; i++)
{
int32_t *dst = args->tmpi2 + i*ndst1;
for (j=0; j<ndst1; j++) dst[j] = bcf_int32_missing;
}
}
int nmap_dip = 0, *map_dip = NULL;
if ( col->number==BCF_VL_G )
{
map_dip = vcmp_map_dipGvalues(args->vcmp, &nmap_dip);
if ( !args->src_smpl_pld )
{
args->src_smpl_pld = (uint8_t*) malloc(nsmpl_src);
args->dst_smpl_pld = (uint8_t*) malloc(nsmpl_dst);
}
int pld_src = determine_ploidy(rec->n_allele, args->tmpi, nsrc1, args->src_smpl_pld, nsmpl_src);
if ( pld_src<0 )
error("Unexpected number of %s values (%d) for %d alleles at %s:%"PRId64"\n", col->hdr_key_src,-pld_src, rec->n_allele, bcf_seqname(bcf_sr_get_header(args->files,1),rec),(int64_t) rec->pos+1);
int pld_dst = determine_ploidy(line->n_allele, args->tmpi2, ndst1, args->dst_smpl_pld, nsmpl_dst);
if ( pld_dst<0 )
error("Unexpected number of %s values (%d) for %d alleles at %s:%"PRId64"\n", col->hdr_key_src,-pld_dst, line->n_allele, bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int ndst1_new = pld_dst==1 ? line->n_allele : line->n_allele*(line->n_allele+1)/2;
if ( ndst1_new != ndst1 )
{
if ( ndst1 ) error("todo: %s ndst1!=ndst .. %d %d at %s:%"PRId64"\n",col->hdr_key_src,ndst1_new,ndst1,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
ndst1 = ndst1_new;
hts_expand(int32_t, ndst1*nsmpl_dst, args->mtmpi2, args->tmpi2);
}
}
else if ( !ndst1 )
{
ndst1 = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
hts_expand(int32_t, ndst1*nsmpl_dst, args->mtmpi2, args->tmpi2);
}
for (i=0; i<nsmpl_dst; i++)
{
int ii = args->sample_map ? args->sample_map[i] : i;
int32_t *ptr_src = args->tmpi + i*nsrc1;
int32_t *ptr_dst = args->tmpi2 + ii*ndst1;
if ( col->number==BCF_VL_G )
{
if ( args->src_smpl_pld[ii] > 0 && args->dst_smpl_pld[i] > 0 && args->src_smpl_pld[ii]!=args->dst_smpl_pld[i] )
error("Sample ploidy differs at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
if ( !args->dst_smpl_pld[i] )
for (j=0; j<ndst1; j++) ptr_dst[j] = bcf_int32_missing;
}
if ( col->number!=BCF_VL_G || args->src_smpl_pld[i]==1 )
{
for (j=0; j<nmap_hap; j++)
{
int k = map_hap[j];
if ( k>=0 ) ptr_dst[k] = ptr_src[j];
}
if ( col->number==BCF_VL_G )
for (j=line->n_allele; j<ndst1; j++) ptr_dst[j++] = bcf_int32_vector_end;
}
else
{
for (j=0; j<nmap_dip; j++)
{
int k = map_dip[j];
if ( k>=0 ) ptr_dst[k] = ptr_src[j];
}
}
}
return bcf_update_format_int32(args->hdr_out,line,col->hdr_key_dst,args->tmpi2,nsmpl_dst*ndst1);
}
static int vcf_setter_format_real(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
int nsrc = bcf_get_format_float(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpf,&args->mtmpf);
if ( nsrc==-3 ) return 0; // the tag is not present
if ( nsrc<=0 ) return 1; // error
int nsmpl_src = bcf_hdr_nsamples(args->files->readers[1].header);
int nsrc1 = nsrc / nsmpl_src;
if ( col->number!=BCF_VL_G && col->number!=BCF_VL_R && col->number!=BCF_VL_A )
return core_setter_format_real(args,line,col,args->tmpf,nsrc1);
// create mapping from src to dst genotypes, haploid and diploid version
int nmap_hap = col->number==BCF_VL_G || col->number==BCF_VL_R ? rec->n_allele : rec->n_allele - 1;
int *map_hap = vcmp_map_ARvalues(args->vcmp,nmap_hap,line->n_allele,line->d.allele,rec->n_allele,rec->d.allele);
if ( !map_hap ) error("REF alleles not compatible at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int i, j;
if ( rec->n_allele==line->n_allele )
{
// alleles unchanged?
for (i=0; i<rec->n_allele; i++) if ( map_hap[i]!=i ) break;
if ( i==rec->n_allele )
return core_setter_format_real(args,line,col,args->tmpf,nsrc1);
}
int nsmpl_dst = rec->n_sample;
int ndst = bcf_get_format_float(args->hdr,line,col->hdr_key_dst,&args->tmpf2,&args->mtmpf2);
int ndst1 = ndst / nsmpl_dst;
if ( ndst <= 0 )
{
if ( col->replace==REPLACE_NON_MISSING ) return 0; // overwrite only if present
if ( col->number==BCF_VL_G )
ndst1 = line->n_allele*(line->n_allele+1)/2;
else
ndst1 = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
hts_expand(float, ndst1*nsmpl_dst, args->mtmpf2, args->tmpf2);
for (i=0; i<nsmpl_dst; i++)
{
float *dst = args->tmpf2 + i*ndst1;
for (j=0; j<ndst1; j++) bcf_float_set_missing(dst[j]);
}
}
int nmap_dip = 0, *map_dip = NULL;
if ( col->number==BCF_VL_G )
{
map_dip = vcmp_map_dipGvalues(args->vcmp, &nmap_dip);
if ( !args->src_smpl_pld )
{
args->src_smpl_pld = (uint8_t*) malloc(nsmpl_src);
args->dst_smpl_pld = (uint8_t*) malloc(nsmpl_dst);
}
int pld_src = determine_ploidy(rec->n_allele, args->tmpi, nsrc1, args->src_smpl_pld, nsmpl_src);
if ( pld_src<0 )
error("Unexpected number of %s values (%d) for %d alleles at %s:%"PRId64"\n", col->hdr_key_src,-pld_src, rec->n_allele, bcf_seqname(bcf_sr_get_header(args->files,1),rec),(int64_t) rec->pos+1);
int pld_dst = determine_ploidy(line->n_allele, args->tmpi2, ndst1, args->dst_smpl_pld, nsmpl_dst);
if ( pld_dst<0 )
error("Unexpected number of %s values (%d) for %d alleles at %s:%"PRId64"\n", col->hdr_key_src,-pld_dst, line->n_allele, bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
int ndst1_new = pld_dst==1 ? line->n_allele : line->n_allele*(line->n_allele+1)/2;
if ( ndst1_new != ndst1 )
{
if ( ndst1 ) error("todo: %s ndst1!=ndst .. %d %d at %s:%"PRId64"\n",col->hdr_key_src,ndst1_new,ndst1,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
ndst1 = ndst1_new;
hts_expand(float, ndst1*nsmpl_dst, args->mtmpf2, args->tmpf2);
}
}
else if ( !ndst1 )
{
ndst1 = col->number==BCF_VL_A ? line->n_allele - 1 : line->n_allele;
hts_expand(float, ndst1*nsmpl_dst, args->mtmpf2, args->tmpf2);
}
for (i=0; i<nsmpl_dst; i++)
{
int ii = args->sample_map ? args->sample_map[i] : i;
float *ptr_src = args->tmpf + i*nsrc1;
float *ptr_dst = args->tmpf2 + ii*ndst1;
if ( col->number==BCF_VL_G )
{
if ( args->src_smpl_pld[ii] > 0 && args->dst_smpl_pld[i] > 0 && args->src_smpl_pld[ii]!=args->dst_smpl_pld[i] )
error("Sample ploidy differs at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
if ( !args->dst_smpl_pld[i] )
for (j=0; j<ndst1; j++) bcf_float_set_missing(ptr_dst[j]);
}
if ( col->number!=BCF_VL_G || args->src_smpl_pld[i]==1 )
{
for (j=0; j<nmap_hap; j++)
{
int k = map_hap[j];
if ( k>=0 )
{
if ( bcf_float_is_missing(ptr_src[j]) ) bcf_float_set_missing(ptr_dst[k]);
else if ( bcf_float_is_vector_end(ptr_src[j]) ) bcf_float_set_vector_end(ptr_dst[k]);
else ptr_dst[k] = ptr_src[j];
}
}
if ( col->number==BCF_VL_G )
for (j=line->n_allele; j<ndst1; j++) bcf_float_set_vector_end(ptr_dst[j]);
}
else
{
for (j=0; j<nmap_dip; j++)
{
int k = map_dip[j];
if ( k>=0 )
{
if ( bcf_float_is_missing(ptr_src[j]) ) bcf_float_set_missing(ptr_dst[k]);
else if ( bcf_float_is_vector_end(ptr_src[j]) ) bcf_float_set_vector_end(ptr_dst[k]);
else ptr_dst[k] = ptr_src[j];
}
}
}
}
return bcf_update_format_float(args->hdr_out,line,col->hdr_key_dst,args->tmpf2,nsmpl_dst*ndst1);
}
static int vcf_setter_format_str(args_t *args, bcf1_t *line, annot_col_t *col, void *data)
{
bcf1_t *rec = (bcf1_t*) data;
args->tmpp[0] = args->tmps;
int ret = bcf_get_format_string(args->files->readers[1].header,rec,col->hdr_key_src,&args->tmpp,&args->mtmps);
args->tmps = args->tmpp[0]; // tmps might be realloced
if ( ret==-3 ) return 0; // the tag is not present
if ( ret<=0 ) return 1; // error
if ( strcmp("GT",col->hdr_key_dst) )
return core_setter_format_str(args,line,col,args->tmpp);
// Genotypes are internally represented as integers. This is a complication for FMT/GT:=oldGT
// First determine the maximum number of alleles per-sample ndst1
int nsmpl_src = bcf_hdr_nsamples(args->files->readers[1].header);
int nsmpl_dst = bcf_hdr_nsamples(args->hdr_out);
int isrc,idst, ndst1 = 0, nsrc1 = ret / nsmpl_src;
char *ptr = args->tmps, *ptr_end = ptr + ret;
while ( ptr < ptr_end )
{
char *smpl_end = ptr + nsrc1;
int n = 1;
while ( ptr < smpl_end )
{
if ( *ptr=='/' || *ptr=='|' ) n++;
ptr++;
}
if ( ndst1 < n ) ndst1 = n;
}
assert( ndst1 );
int ndst = ndst1*nsmpl_dst;
hts_expand(int32_t,ndst,args->mtmpi,args->tmpi);
hts_expand(char,ret+1,args->mtmps,args->tmps); args->tmps[ret] = 0; // the FORMAT string may not be 0-terminated
for (idst=0; idst<nsmpl_dst; idst++)
{
int i = 0, is_phased = 0;
int32_t *dst = args->tmpi + idst*ndst1;
isrc = args->sample_map ? args->sample_map[idst] : idst;
if ( isrc==-1 )
{
dst[0] = bcf_gt_missing;
for (i=1; i<ndst1; i++) dst[i] = bcf_int32_vector_end;
continue;
}
char *beg = args->tmps + isrc*nsrc1, *tmp;
char *keep_ptr = beg+nsrc1, keep = *keep_ptr; *keep_ptr = 0;
while ( *beg )
{
char *end = beg;
while ( *end && *end!='/' && *end!='|' ) end++;
if ( *beg=='.' && end-beg==1 ) dst[i] = bcf_gt_missing;
else
{
if ( *end=='|' ) is_phased = 1;
dst[i] = strtol(beg, &tmp, 10);
if ( tmp!=end )
error("Could not parse the %s field at %s:%"PRId64" in %s\n", col->hdr_key_src,bcf_seqname(args->files->readers[1].header,rec),(int64_t) rec->pos+1,args->targets_fname);
if ( dst[i] >= line->n_allele )
error("The source allele index is bigger than the number of destination alleles at %s:%"PRId64"\n", bcf_seqname(args->files->readers[1].header,rec),(int64_t) rec->pos+1);
dst[i] = is_phased ? bcf_gt_phased(dst[i]) : bcf_gt_unphased(dst[i]);
}
beg = *end ? end+1 : end;
i++;
}
*keep_ptr = keep;
for (; i<ndst1; i++) dst[i] = bcf_int32_vector_end;
}
return bcf_update_genotypes(args->hdr_out,line,args->tmpi,ndst);
}
static int init_sample_map(args_t *args, bcf_hdr_t *src, bcf_hdr_t *dst)
{
int i;
if ( !args->sample_names )
{
args->nsmpl_annot = bcf_hdr_nsamples(dst);
// tab annotation file, expecting that all samples are present: sample map not needed
if ( !src ) return 0;
int nmatch = 0, order_ok = 1;
for (i=0; i<bcf_hdr_nsamples(src); i++)
{
int id = bcf_hdr_id2int(dst, BCF_DT_SAMPLE, src->samples[i]);
if ( id!=-1 )
{
nmatch++;
if ( i!=id ) order_ok = 0;
}
}
if ( bcf_hdr_nsamples(src)==bcf_hdr_nsamples(dst) && nmatch==bcf_hdr_nsamples(src) && order_ok ) return 0; // not needed
if ( !nmatch ) return -1; // No matching samples found in the source and the destination file
args->nsample_map = bcf_hdr_nsamples(dst);
args->sample_map = (int*) malloc(sizeof(int)*args->nsample_map);
for (i=0; i<args->nsample_map; i++)
{
int id = bcf_hdr_id2int(src, BCF_DT_SAMPLE, dst->samples[i]);
args->sample_map[i] = id; // idst -> isrc, -1 if not present
}
return 1;
}
args->nsample_map = bcf_hdr_nsamples(dst);
args->sample_map = (int*) malloc(sizeof(int)*args->nsample_map);
for (i=0; i<args->nsample_map; i++) args->sample_map[i] = -1;
int flags = !src ? SMPL_STRICT|SMPL_SINGLE : SMPL_STRICT|SMPL_SINGLE|SMPL_PAIR2; // is vcf vs tab annotation file
smpl_ilist_t *ilist = smpl_ilist_init(dst, args->sample_names, args->sample_is_file, flags); // gives mapping dst->src
if ( !ilist || !ilist->n ) error("Could not parse the samples: %s\n", args->sample_names);
args->nsmpl_annot = ilist->n;
int need_sample_map = args->nsmpl_annot==bcf_hdr_nsamples(dst) ? 0 : 1;
for (i=0; i<args->nsmpl_annot; i++)
{
int idst = ilist->idx[i];
const char *src_name = ilist->pair && ilist->pair[i] ? ilist->pair[i] : bcf_hdr_int2id(dst, BCF_DT_SAMPLE, idst);
int isrc = i;
if ( src ) // the annotation file is a VCF, not a tab-delimited file
{
isrc = bcf_hdr_id2int(src, BCF_DT_SAMPLE, src_name);
if ( isrc==-1 ) error("Sample \"%s\" not found in the annotation file\n", src_name);
}
if ( isrc!=idst ) need_sample_map = 1;
args->sample_map[idst] = isrc;
}
smpl_ilist_destroy(ilist);
return need_sample_map;
}
static char *columns_complement(char *columns, void **skip_info, void **skip_fmt)
{
kstring_t str = {0,0,0};
char *ss = columns, *se = ss;
while ( *ss )
{
if ( *se && *se!=',' ) { se++; continue; }
if ( *ss!='^' )
{
if ( str.l ) kputc(',',&str);
kputsn(ss, se-ss, &str);
if ( !*se ) break;
ss = ++se;
continue;
}
if ( !strncasecmp("^INFO/",ss,6) )
{
if ( !*skip_info )
{
*skip_info = khash_str2int_init();
if ( str.l ) kputc(',',&str);
kputs("INFO",&str);
}
char tmp = *se; *se = 0;
khash_str2int_inc(*skip_info, strdup(ss+6));
*se = tmp;
}
else if ( !strncasecmp("^FORMAT/",ss,8) || !strncasecmp("^FMT/",ss,5) )
{
int n = !strncasecmp("^FMT/",ss,5) ? 5 : 8;
if ( !*skip_fmt )
{
*skip_fmt = khash_str2int_init();
if ( str.l ) kputc(',',&str);
kputs("FORMAT",&str);
}
char tmp = *se; *se = 0;
khash_str2int_inc(*skip_fmt, strdup(ss+n));
*se = tmp;
}
else
{
if ( !*skip_info )
{
*skip_info = khash_str2int_init();
if ( str.l ) kputc(',',&str);
kputs("INFO",&str);
}
char tmp = *se; *se = 0;
khash_str2int_inc(*skip_info, strdup(ss+1));
*se = tmp;
}
if ( !*se ) break;
ss = ++se;
}
free(columns);
return str.s;
}
static void bcf_hrec_format_rename(bcf_hrec_t *hrec, char *tag, kstring_t *str)
{
int j, nout = 0;
ksprintf(str, "##%s=<", hrec->key);
for (j=0; j<hrec->nkeys; j++)
{
if ( !strcmp("IDX",hrec->keys[j]) ) continue;
if ( nout ) kputc(',',str);
if ( !strcmp("ID", hrec->keys[j]) )
ksprintf(str,"%s=%s", hrec->keys[j], tag);
else
ksprintf(str,"%s=%s", hrec->keys[j], hrec->vals[j]);
nout++;
}
ksprintf(str,">\n");
}
static void init_columns(args_t *args)
{
int need_sample_map = 0;
int sample_map_ok = init_sample_map(args, args->tgts_is_vcf?args->files->readers[1].header:NULL, args->hdr);
void *skip_fmt = NULL, *skip_info = NULL;
if ( args->tgts_is_vcf )
args->columns = columns_complement(args->columns, &skip_info, &skip_fmt);
kstring_t str = {0,0,0}, tmp = {0,0,0};
char *ss = args->columns, *se = ss;
args->ncols = 0;
int icol = -1, has_fmt_str = 0;
while ( *ss )
{
if ( *se && *se!=',' ) { se++; continue; }
int replace = REPLACE_ALL;
if ( *ss=='+' ) { replace = REPLACE_MISSING; ss++; }
else if ( *ss=='-' ) { replace = REPLACE_NON_MISSING; ss++; }
else if ( *ss=='=' ) { replace = SET_OR_APPEND; ss++; }
icol++;
str.l = 0;
kputsn(ss, se-ss, &str);
if ( !str.s[0] || !strcasecmp("-",str.s) ) ;
else if ( !strcasecmp("CHROM",str.s) ) args->chr_idx = icol;
else if ( !strcasecmp("POS",str.s) ) args->beg_idx = icol;
else if ( !strcasecmp("FROM",str.s) || !strcasecmp("BEG",str.s) ) args->beg_idx = icol;
else if ( !strcasecmp("TO",str.s) || !strcasecmp("END",str.s) ) args->end_idx = icol;
else if ( !strcasecmp("REF",str.s) )
{
if ( args->tgts_is_vcf )
{
args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
annot_col_t *col = &args->cols[args->ncols-1];
col->setter = vcf_setter_ref;
col->hdr_key_src = strdup(str.s);
col->hdr_key_dst = strdup(str.s);
}
else args->ref_idx = icol;
}
else if ( !strcasecmp("ALT",str.s) )
{
if ( args->tgts_is_vcf )
{
args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
annot_col_t *col = &args->cols[args->ncols-1];
col->setter = vcf_setter_alt;
col->hdr_key_src = strdup(str.s);
col->hdr_key_dst = strdup(str.s);
}
else args->alt_idx = icol;
}
else if ( !strcasecmp("ID",str.s) )
{
if ( replace==REPLACE_NON_MISSING ) error("Apologies, the -ID feature has not been implemented yet.\n");
args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
annot_col_t *col = &args->cols[args->ncols-1];
col->icol = icol;
col->replace = replace;
col->setter = args->tgts_is_vcf ? vcf_setter_id : setter_id;
col->hdr_key_src = strdup(str.s);
col->hdr_key_dst = strdup(str.s);
}
else if ( !strcasecmp("FILTER",str.s) )
{
if ( replace==REPLACE_NON_MISSING ) error("Apologies, the -FILTER feature has not been implemented yet.\n");
args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
annot_col_t *col = &args->cols[args->ncols-1];
col->icol = icol;
col->replace = replace;
col->setter = args->tgts_is_vcf ? vcf_setter_filter : setter_filter;
col->hdr_key_src = strdup(str.s);
col->hdr_key_dst = strdup(str.s);
if ( args->tgts_is_vcf )
{
bcf_hdr_t *tgts_hdr = args->files->readers[1].header;
int j;
for (j=0; j<tgts_hdr->nhrec; j++)
{
bcf_hrec_t *hrec = tgts_hdr->hrec[j];
if ( hrec->type!=BCF_HL_FLT ) continue;
int k = bcf_hrec_find_key(hrec,"ID");
assert( k>=0 ); // this should always be true for valid VCFs
tmp.l = 0;
bcf_hrec_format(hrec, &tmp);
bcf_hdr_append(args->hdr_out, tmp.s);
}
if (bcf_hdr_sync(args->hdr_out) < 0)
error_errno("[%s] Failed to update header", __func__);
}
}
else if ( !strcasecmp("QUAL",str.s) )
{
if ( replace==REPLACE_NON_MISSING ) error("Apologies, the -QUAL feature has not been implemented yet.\n");
if ( replace==SET_OR_APPEND ) error("Apologies, the =QUAL feature has not been implemented yet.\n");
args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
annot_col_t *col = &args->cols[args->ncols-1];
col->icol = icol;
col->replace = replace;
col->setter = args->tgts_is_vcf ? vcf_setter_qual : setter_qual;
col->hdr_key_src = strdup(str.s);
col->hdr_key_dst = strdup(str.s);
}
else if ( args->tgts_is_vcf && !strcasecmp("INFO",str.s) ) // All INFO fields
{
if ( replace==REPLACE_NON_MISSING ) error("Apologies, the -INFO/TAG feature has not been implemented yet.\n");
if ( replace==SET_OR_APPEND ) error("Apologies, the =INFO/TAG feature has not been implemented yet.\n");
bcf_hdr_t *tgts_hdr = args->files->readers[1].header;
int j;
for (j=0; j<tgts_hdr->nhrec; j++)
{
bcf_hrec_t *hrec = tgts_hdr->hrec[j];
if ( hrec->type!=BCF_HL_INFO ) continue;
int k = bcf_hrec_find_key(hrec,"ID");
assert( k>=0 ); // this should always be true for valid VCFs
if ( skip_info && khash_str2int_has_key(skip_info,hrec->vals[k]) ) continue;
tmp.l = 0;
bcf_hrec_format(hrec, &tmp);
bcf_hdr_append(args->hdr_out, tmp.s);
if (bcf_hdr_sync(args->hdr_out) < 0)
error_errno("[%s] Failed to update header", __func__);
int hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, hrec->vals[k]);
args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
annot_col_t *col = &args->cols[args->ncols-1];
col->icol = -1;
col->replace = replace;
col->hdr_key_src = strdup(hrec->vals[k]);
col->hdr_key_dst = strdup(hrec->vals[k]);
col->number = bcf_hdr_id2length(args->hdr_out,BCF_HL_INFO,hdr_id);
switch ( bcf_hdr_id2type(args->hdr_out,BCF_HL_INFO,hdr_id) )
{
case BCF_HT_FLAG: col->setter = vcf_setter_info_flag; break;
case BCF_HT_INT: col->setter = vcf_setter_info_int; break;
case BCF_HT_REAL: col->setter = vcf_setter_info_real; break;
case BCF_HT_STR: col->setter = vcf_setter_info_str; break;
default: error("The type of %s not recognised (%d)\n", str.s,bcf_hdr_id2type(args->hdr_out,BCF_HL_INFO,hdr_id));
}
}
}
else if ( args->tgts_is_vcf && (!strcasecmp("FORMAT",str.s) || !strcasecmp("FMT",str.s)) ) // All FORMAT fields
{
bcf_hdr_t *tgts_hdr = args->files->readers[1].header;
need_sample_map = 1;
int j;
for (j=0; j<tgts_hdr->nhrec; j++)
{
bcf_hrec_t *hrec = tgts_hdr->hrec[j];
if ( hrec->type!=BCF_HL_FMT) continue;
int k = bcf_hrec_find_key(hrec,"ID");
assert( k>=0 ); // this should always be true for valid VCFs
if ( skip_fmt && khash_str2int_has_key(skip_fmt,hrec->vals[k]) ) continue;
tmp.l = 0;
bcf_hrec_format(hrec, &tmp);
bcf_hdr_append(args->hdr_out, tmp.s);
if (bcf_hdr_sync(args->hdr_out) < 0)
error_errno("[%s] Failed to update header", __func__);
int hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, hrec->vals[k]);
args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
annot_col_t *col = &args->cols[args->ncols-1];
col->icol = -1;
col->replace = replace;
col->hdr_key_src = strdup(hrec->vals[k]);
col->hdr_key_dst = strdup(hrec->vals[k]);
if ( !strcasecmp("GT",col->hdr_key_src) ) col->setter = vcf_setter_format_gt;
else
switch ( bcf_hdr_id2type(args->hdr_out,BCF_HL_FMT,hdr_id) )
{
case BCF_HT_INT: col->setter = vcf_setter_format_int; break;
case BCF_HT_REAL: col->setter = vcf_setter_format_real; break;
case BCF_HT_STR: col->setter = vcf_setter_format_str; has_fmt_str = 1; break;
default: error("The type of %s not recognised (%d)\n", str.s,bcf_hdr_id2type(args->hdr_out,BCF_HL_FMT,hdr_id));
}
hdr_id = bcf_hdr_id2int(tgts_hdr, BCF_DT_ID, hrec->vals[k]);
col->number = bcf_hdr_id2length(tgts_hdr,BCF_HL_FMT,hdr_id);
}
}
else if ( !strncasecmp("FORMAT/",str.s, 7) || !strncasecmp("FMT/",str.s,4) )
{
char *key_dst = str.s + (!strncasecmp("FMT/",str.s,4) ? 4 : 7);
char *key_src = strstr(key_dst,":=");
if ( key_src )
{
*key_src = 0;
key_src += 2;
if ( !strncasecmp("FORMAT/",key_src,7) ) key_src += 7;
else if ( !strncasecmp("FMT/",key_src,4) ) key_src += 4;
}
else
key_src = key_dst;
need_sample_map = 1;
if ( args->tgts_is_vcf )
{
bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->files->readers[1].header, BCF_HL_FMT, "ID", key_src, NULL);
if ( !hrec ) error("No such annotation \"%s\" in %s\n", key_src,args->targets_fname);
tmp.l = 0;
bcf_hrec_format_rename(hrec, key_dst, &tmp);
bcf_hdr_append(args->hdr_out, tmp.s);
if (bcf_hdr_sync(args->hdr_out) < 0)
error_errno("[%s] Failed to update header", __func__);
}
int hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, key_dst);
if ( !bcf_hdr_idinfo_exists(args->hdr_out,BCF_HL_FMT,hdr_id) )
error("The tag \"%s\" is not defined in %s\n", str.s, args->targets_fname);
args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
annot_col_t *col = &args->cols[args->ncols-1];
if ( !args->tgts_is_vcf )
{
col->icol = icol;
icol += args->nsmpl_annot - 1;
}
else
col->icol = -1;
col->replace = replace;
col->hdr_key_src = strdup(key_src);
col->hdr_key_dst = strdup(key_dst);
if ( !strcasecmp("GT",key_src) ) col->setter = vcf_setter_format_gt;
else
switch ( bcf_hdr_id2type(args->hdr_out,BCF_HL_FMT,hdr_id) )
{
case BCF_HT_INT: col->setter = args->tgts_is_vcf ? vcf_setter_format_int : setter_format_int; break;
case BCF_HT_REAL: col->setter = args->tgts_is_vcf ? vcf_setter_format_real : setter_format_real; break;
case BCF_HT_STR: col->setter = args->tgts_is_vcf ? vcf_setter_format_str : setter_format_str; has_fmt_str = 1; break;
default: error("The type of %s not recognised (%d)\n", str.s,bcf_hdr_id2type(args->hdr_out,BCF_HL_FMT,hdr_id));
}
if ( args->tgts_is_vcf )
{
bcf_hdr_t *tgts_hdr = args->files->readers[1].header;
hdr_id = bcf_hdr_id2int(tgts_hdr, BCF_DT_ID, col->hdr_key_src);
col->number = bcf_hdr_id2length(tgts_hdr,BCF_HL_FMT,hdr_id);
}
}
else
{
if ( replace==REPLACE_NON_MISSING ) error("Apologies, the -INFO/TAG feature has not been implemented yet.\n");
if ( replace==SET_OR_APPEND ) error("Apologies, the =INFO/TAG feature has not been implemented yet.\n");
int explicit_info = 0;
char *key_dst;
if ( !strncasecmp("INFO/",str.s,5) )
{
key_dst = str.s + 5;
explicit_info = 1;
}
else
key_dst = str.s;
char *key_src = strstr(key_dst,":=");
if ( key_src )
{
*key_src = 0;
key_src += 2;
if ( !strncasecmp("INFO/",key_src,5) )
{
key_src += 5;
explicit_info = 1;
}
else if ( !strncasecmp("FMT/",key_src,4) || !strncasecmp("FORMAT/",key_src,5) )
{
key_src[-2] = ':';
error("Did you mean \"FMT/%s\" rather than \"%s\"?\n",str.s,str.s);
}
}
else
key_src = key_dst;
int hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, key_dst);
if ( !bcf_hdr_idinfo_exists(args->hdr_out,BCF_HL_INFO,hdr_id) )
{
if ( args->tgts_is_vcf ) // reading annotations from a VCF, add a new header line
{
bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->files->readers[1].header, BCF_HL_INFO, "ID", key_src, NULL);
if ( !hrec )
{
if ( !explicit_info && bcf_hdr_get_hrec(args->files->readers[1].header, BCF_HL_FMT, "ID", key_src, NULL) )
error("Did you mean \"FMT/%s\" rather than \"%s\"?\n",str.s,str.s);
fprintf(stderr,"[%s] %d\n",key_src,explicit_info);
error("The tag \"%s\" is not defined in %s\n", key_src,args->files->readers[1].fname);
}
tmp.l = 0;
bcf_hrec_format_rename(hrec, key_dst, &tmp);
bcf_hdr_append(args->hdr_out, tmp.s);
if (bcf_hdr_sync(args->hdr_out) < 0)
error_errno("[%s] Failed to update header", __func__);
hdr_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, key_dst);
}
else
error("The tag \"%s\" is not defined in %s\n", key_src, args->targets_fname);
assert( bcf_hdr_idinfo_exists(args->hdr_out,BCF_HL_INFO,hdr_id) );
}
args->ncols++; args->cols = (annot_col_t*) realloc(args->cols,sizeof(annot_col_t)*args->ncols);
annot_col_t *col = &args->cols[args->ncols-1];
col->icol = icol;
col->replace = replace;
col->hdr_key_src = strdup(key_src);
col->hdr_key_dst = strdup(key_dst);
col->number = bcf_hdr_id2length(args->hdr_out,BCF_HL_INFO,hdr_id);
switch ( bcf_hdr_id2type(args->hdr_out,BCF_HL_INFO,hdr_id) )
{
case BCF_HT_FLAG: col->setter = args->tgts_is_vcf ? vcf_setter_info_flag : setter_info_flag; break;
case BCF_HT_INT: col->setter = args->tgts_is_vcf ? vcf_setter_info_int : setter_info_int; break;
case BCF_HT_REAL: col->setter = args->tgts_is_vcf ? vcf_setter_info_real : setter_info_real; break;
case BCF_HT_STR: col->setter = args->tgts_is_vcf ? vcf_setter_info_str : setter_info_str; break;
default: error("The type of %s not recognised (%d)\n", str.s,bcf_hdr_id2type(args->hdr_out,BCF_HL_INFO,hdr_id));
}
}
if ( !*se ) break;
ss = ++se;
}
free(str.s);
free(tmp.s);
free(args->columns);
if ( skip_info ) khash_str2int_destroy_free(skip_info);
if ( skip_fmt ) khash_str2int_destroy_free(skip_fmt);
if ( has_fmt_str )
{
int n = bcf_hdr_nsamples(args->hdr_out);
if ( args->tgts_is_vcf && n<bcf_hdr_nsamples(args->files->readers[1].header) ) n = bcf_hdr_nsamples(args->files->readers[1].header);
args->tmpp = (char**)malloc(sizeof(char*)*n);
args->tmpp2 = (char**)malloc(sizeof(char*)*n);
}
if ( !need_sample_map )
{
free(args->sample_map);
args->sample_map = NULL;
}
else if ( sample_map_ok<0 )
error("No matching samples in source and destination file?\n");
}
static void init_merge_method(args_t *args)
{
int i;
for (i=0; i<args->ncols; i++)
{
args->cols[i].merge_method = MM_FIRST;
args->cols[i].mm_str_hash = NULL;
args->cols[i].mm_dbl = NULL;
args->cols[i].mm_dbl_nalloc = args->cols[i].mm_dbl_nused = args->cols[i].mm_dbl_ndat = 0;
memset(&args->cols[i].mm_kstr, 0, sizeof(args->cols[i].mm_kstr));
}
if ( !args->merge_method_str ) return;
if ( args->tgts_is_vcf ) error("Error: the --merge-logic is intended for use with BED or TAB-delimited files only.\n");
if ( !args->tgt_idx ) error("Error: BEG,END (or FROM,TO) columns are expected with the --merge-logic option.\n");
char *sb = args->merge_method_str;
while ( *sb )
{
char *se = sb;
while ( *se && *se!=',' ) se++;
args->tmpks.l = 0;
kputsn(sb, se-sb, &args->tmpks);
kputc(0, &args->tmpks);
char *mm_type_str = args->tmpks.s + args->tmpks.l;
while ( *mm_type_str!=':' && mm_type_str > args->tmpks.s ) mm_type_str--;
if ( *mm_type_str!=':' )
error("Error: could not parse the argument to --merge-logic: %s\n", args->merge_method_str);
*mm_type_str = 0;
mm_type_str++;
int mm_type = MM_FIRST;
if ( !strcasecmp("unique",mm_type_str) ) mm_type = MM_UNIQUE;
else if ( !strcasecmp("append",mm_type_str) ) mm_type = MM_APPEND;
else if ( !strcasecmp("sum",mm_type_str) ) mm_type = MM_SUM;
else if ( !strcasecmp("avg",mm_type_str) ) mm_type = MM_AVG;
else if ( !strcasecmp("min",mm_type_str) ) mm_type = MM_MIN;
else if ( !strcasecmp("max",mm_type_str) ) mm_type = MM_MAX;
else error("Error: could not parse --merge-logic %s, the logic \"%s\" is not recognised\n", args->merge_method_str,mm_type_str);
for (i=0; i<args->ncols; i++)
{
if ( strcmp(args->cols[i].hdr_key_dst,args->tmpks.s) ) continue;
if ( mm_type==MM_APPEND && args->cols[i].number!=BCF_VL_VAR )
error("Error: --merge-logic append can be requested only for tags of variable length (Number=.)\n");
args->cols[i].merge_method = mm_type;
break;
}
if ( i==args->ncols ) error("No such tag in the destination file: %s\n", args->tmpks.s);
sb = *se ? se + 1 : se;
}
}
static void rename_chrs(args_t *args, char *fname)
{
int n, i;
char **map = hts_readlist(fname, 1, &n);
if ( !map ) error("Could not read: %s\n", fname);
for (i=0; i<n; i++)
{
char *ss = map[i];
while ( *ss && !isspace(*ss) ) ss++;
if ( !*ss ) error("Could not parse: %s\n", fname);
*ss = 0;
int rid = bcf_hdr_name2id(args->hdr_out, map[i]);
bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->hdr_out, BCF_HL_CTG, "ID", map[i], NULL);
if ( !hrec ) continue; // the sequence not present
int j = bcf_hrec_find_key(hrec, "ID");
assert( j>=0 );
free(hrec->vals[j]);
ss++;
while ( *ss && isspace(*ss) ) ss++;
char *se = ss;
while ( *se && !isspace(*se) ) se++;
*se = 0;
hrec->vals[j] = strdup(ss);
args->hdr_out->id[BCF_DT_CTG][rid].key = hrec->vals[j];
}
for (i=0; i<n; i++) free(map[i]);
free(map);
}
static void init_data(args_t *args)
{
args->hdr = args->files->readers[0].header;
args->hdr_out = bcf_hdr_dup(args->hdr);
if ( args->remove_annots ) init_remove_annots(args);
if ( args->header_fname ) init_header_lines(args);
if ( args->targets_fname && args->tgts_is_vcf )
{
// reading annots from a VCF
if ( !bcf_sr_add_reader(args->files, args->targets_fname) )
error("Failed to open %s: %s\n", args->targets_fname,bcf_sr_strerror(args->files->errnum));
}
if ( args->columns ) init_columns(args);
if ( args->targets_fname && !args->tgts_is_vcf )
{
if ( !args->columns ) error("The -c option not given\n");
if ( args->chr_idx==-1 ) error("The -c CHROM option not given\n");
if ( args->beg_idx==-1 ) error("The -c POS option not given\n");
if ( args->single_overlaps && args->merge_method_str ) error("The options --merge-logic and --single-overlaps cannot be combined\n");
if ( args->end_idx==-1 || (args->single_overlaps && !args->merge_method_str) )
{
args->end_idx = -args->beg_idx - 1;
args->tgts = bcf_sr_regions_init(args->targets_fname,1,args->chr_idx,args->beg_idx,args->end_idx);
if ( !args->tgts ) error("Could not initialize the annotation file: %s\n", args->targets_fname);
if ( !args->tgts->tbx ) error("Expected tabix-indexed annotation file: %s\n", args->targets_fname);
}
else
{
if ( args->ref_idx!=-1 ) error("Error: the REF columns will be ignored when BEG,END (or FROM,TO) is present. Replace END (or TO) with \"-\".\n");
int len = strlen(args->targets_fname);
if ( len>=7 && !strcasecmp(".bed.gz",args->targets_fname+len-7) ) args->tgt_is_bed = 1;
else if ( len>=8 && !strcasecmp(".bed.bgz",args->targets_fname+len-8) ) args->tgt_is_bed = 1;
else if ( len>=4 && !strcasecmp(".bed",args->targets_fname+len-4) ) args->tgt_is_bed = 1;
args->tgt_idx = regidx_init(args->targets_fname,parse_with_payload,free_payload,sizeof(char*),args);
if ( !args->tgt_idx ) error("Failed to parse: %s\n", args->targets_fname);
args->tgt_itr = regitr_init(args->tgt_idx);
args->nalines++;
hts_expand0(annot_line_t,args->nalines,args->malines,args->alines);
}
}
init_merge_method(args);
args->vcmp = vcmp_init();
if ( args->filter_str )
args->filter = filter_init(args->hdr, args->filter_str);
if ( args->set_ids_fmt )
{
if ( args->set_ids_fmt[0]=='+' ) { args->set_ids_replace = 0; args->set_ids_fmt++; }
args->set_ids = convert_init(args->hdr_out, NULL, 0, args->set_ids_fmt);
}
if ( args->mark_sites )
{
if ( !args->targets_fname ) error("The -a option not given\n");
bcf_hdr_printf(args->hdr_out,"##INFO=<ID=%s,Number=0,Type=Flag,Description=\"Sites %slisted in %s\">",
args->mark_sites,args->mark_sites_logic==MARK_LISTED?"":"not ",args->mark_sites);
}
if (args->record_cmd_line) bcf_hdr_append_version(args->hdr_out, args->argc, args->argv, "bcftools_annotate");
if ( !args->drop_header )
{
if ( args->rename_chrs ) rename_chrs(args, args->rename_chrs);
args->out_fh = hts_open(args->output_fname,hts_bcf_wmode(args->output_type));
if ( args->out_fh == NULL ) error("[%s] Error: cannot write to \"%s\": %s\n", __func__,args->output_fname, strerror(errno));
if ( args->n_threads )
hts_set_opt(args->out_fh, HTS_OPT_THREAD_POOL, args->files->p);
if ( bcf_hdr_write(args->out_fh, args->hdr_out)!=0 ) error("[%s] Error: failed to write the header to %s\n", __func__,args->output_fname);
}
}
static void destroy_data(args_t *args)
{
int i;
for (i=0; i<args->nrm; i++) free(args->rm[i].key);
free(args->rm);
if ( args->hdr_out ) bcf_hdr_destroy(args->hdr_out);
if (args->vcmp) vcmp_destroy(args->vcmp);
for (i=0; i<args->ncols; i++)
{
free(args->cols[i].hdr_key_src);
free(args->cols[i].hdr_key_dst);
free(args->cols[i].mm_kstr.s);
if ( args->cols[i].mm_str_hash ) khash_str2int_destroy_free(args->cols[i].mm_str_hash);
free(args->cols[i].mm_dbl);
}
free(args->cols);
for (i=0; i<args->malines; i++)
{
free(args->alines[i].cols);
free(args->alines[i].als);
free(args->alines[i].line.s);
}
free(args->alines);
if ( args->tgt_idx )
{
regidx_destroy(args->tgt_idx);
regitr_destroy(args->tgt_itr);
}
if ( args->tgts ) bcf_sr_regions_destroy(args->tgts);
free(args->tmpks.s);
free(args->tmpi);
free(args->tmpf);
free(args->tmps);
free(args->tmpp);
free(args->tmpi2);
free(args->tmpf2);
free(args->tmps2);
free(args->tmpp2);
free(args->tmpi3);
free(args->tmpf3);
free(args->src_smpl_pld);
free(args->dst_smpl_pld);
if ( args->set_ids )
convert_destroy(args->set_ids);
if ( args->filter )
filter_destroy(args->filter);
if (args->out_fh) hts_close(args->out_fh);
free(args->sample_map);
}
static void parse_annot_line(args_t *args, char *str, annot_line_t *tmp)
{
tmp->line.l = 0;
kputs(str, &tmp->line);
char *s = tmp->line.s;
tmp->ncols = 1;
hts_expand(char*,tmp->ncols,tmp->mcols,tmp->cols);
tmp->cols[0] = s;
while ( *s )
{
if ( *s=='\t' )
{
tmp->ncols++;
hts_expand(char*,tmp->ncols,tmp->mcols,tmp->cols);
tmp->cols[tmp->ncols-1] = s+1;
*s = 0;
}
s++;
}
if ( args->ref_idx != -1 )
{
if ( args->ref_idx >= tmp->ncols )
error("Could not parse the line, expected %d+ columns, found %d:\n\t%s\n",args->ref_idx+1,tmp->ncols,str);
if ( args->alt_idx >= tmp->ncols )
error("Could not parse the line, expected %d+ columns, found %d:\n\t%s\n",args->alt_idx+1,tmp->ncols,str);
tmp->nals = 2;
hts_expand(char*,tmp->nals,tmp->mals,tmp->als);
tmp->als[0] = tmp->cols[args->ref_idx];
tmp->als[1] = s = tmp->cols[args->alt_idx];
while ( *s )
{
if ( *s==',' )
{
tmp->nals++;
hts_expand(char*,tmp->nals,tmp->mals,tmp->als);
tmp->als[tmp->nals-1] = s+1;
*s = 0;
}
s++;
}
}
}
static void buffer_annot_lines(args_t *args, bcf1_t *line, int start_pos, int end_pos)
{
if ( args->nalines && args->alines[0].rid != line->rid ) args->nalines = 0;
int i = 0;
while ( i<args->nalines )
{
if ( line->pos > args->alines[i].end )
{
args->nalines--;
if ( args->nalines && i<args->nalines )
{
annot_line_t tmp = args->alines[i];
memmove(&args->alines[i],&args->alines[i+1],(args->nalines-i)*sizeof(annot_line_t));
args->alines[args->nalines] = tmp;
}
}
else i++;
}
if ( args->ref_idx==-1 && args->nalines ) return;
while ( !bcf_sr_regions_overlap(args->tgts, bcf_seqname(args->hdr,line), start_pos,end_pos) )
{
args->nalines++;
hts_expand0(annot_line_t,args->nalines,args->malines,args->alines);
annot_line_t *tmp = &args->alines[args->nalines-1];
tmp->rid = line->rid;
tmp->start = args->tgts->start;
tmp->end = args->tgts->end;
parse_annot_line(args, args->tgts->line.s, tmp);
if ( args->ref_idx != -1 )
{
int iseq = args->tgts->iseq;
if ( bcf_sr_regions_next(args->tgts)<0 || args->tgts->iseq!=iseq ) break;
}
else break;
}
}
static void annotate(args_t *args, bcf1_t *line)
{
int i, j;
for (i=0; i<args->nrm; i++)
args->rm[i].handler(args, line, &args->rm[i]);
int has_overlap = 0;
if ( args->tgt_idx )
{
if ( regidx_overlap(args->tgt_idx, bcf_seqname(args->hdr,line),line->pos,line->pos+line->rlen-1, args->tgt_itr) )
{
while ( regitr_overlap(args->tgt_itr) )
{
annot_line_t *tmp = &args->alines[0];
tmp->rid = line->rid;
tmp->start = args->tgt_itr->beg;
tmp->end = args->tgt_itr->end;
parse_annot_line(args, regitr_payload(args->tgt_itr,char*), tmp);
for (j=0; j<args->ncols; j++)
if ( args->cols[j].setter(args,line,&args->cols[j],tmp) )
error("fixme: Could not set %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
}
has_overlap = 1;
}
for (j=0; j<args->ncols; j++)
if ( args->cols[j].merge_method != MM_FIRST )
args->cols[j].setter(args,line,&args->cols[j],NULL);
}
else if ( args->tgts )
{
// Buffer annotation lines. When multiple ALT alleles are present in the
// annotation file, at least one must match one of the VCF alleles.
int len = 0;
bcf_get_variant_types(line);
for (i=1; i<line->n_allele; i++)
if ( len > line->d.var[i].n ) len = line->d.var[i].n;
int end_pos = len<0 ? line->pos - len : line->pos;
buffer_annot_lines(args, line, line->pos, end_pos);
for (i=0; i<args->nalines; i++)
{
if ( line->pos > args->alines[i].end || end_pos < args->alines[i].start ) continue;
if ( args->ref_idx != -1 )
{
if ( vcmp_set_ref(args->vcmp, line->d.allele[0], args->alines[i].als[0]) < 0 ) continue; // refs not compatible
for (j=1; j<args->alines[i].nals; j++)
{
if ( line->n_allele==1 && args->alines[i].als[j][0]=='.' && args->alines[i].als[j][1]==0 ) break; // no ALT allele in VCF and annot file has "."
if ( vcmp_find_allele(args->vcmp, line->d.allele+1, line->n_allele - 1, args->alines[i].als[j]) >= 0 ) break;
}
if ( j==args->alines[i].nals ) continue; // none of the annot alleles present in VCF's ALT
}
break;
}
if ( i<args->nalines )
{
// there is a matching line
for (j=0; j<args->ncols; j++)
if ( args->cols[j].setter(args,line,&args->cols[j],&args->alines[i]) )
error("fixme: Could not set %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
}
has_overlap = i<args->nalines ? 1 : 0;
}
else if ( args->files->nreaders == 2 )
{
if ( bcf_sr_has_line(args->files,1) )
{
bcf1_t *aline = bcf_sr_get_line(args->files,1);
for (j=0; j<args->ncols; j++)
if ( args->cols[j].setter(args,line,&args->cols[j],aline) )
error("fixme: Could not set %s at %s:%"PRId64"\n", args->cols[j].hdr_key_src,bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
has_overlap = 1;
}
}
if ( args->set_ids )
{
args->tmpks.l = 0;
convert_line(args->set_ids, line, &args->tmpks);
if ( args->tmpks.l )
{
int replace = 0;
if ( args->set_ids_replace ) replace = 1;
else if ( !line->d.id || (line->d.id[0]=='.' && !line->d.id[1]) ) replace = 1;
if ( replace )
bcf_update_id(args->hdr_out,line,args->tmpks.s);
}
}
if ( args->mark_sites )
{
// ideally, we'd like to be far more general than this in future, see https://github.com/samtools/bcftools/issues/87
if ( args->mark_sites_logic==MARK_LISTED )
bcf_update_info_flag(args->hdr_out,line,args->mark_sites,NULL,has_overlap?1:0);
else
bcf_update_info_flag(args->hdr_out,line,args->mark_sites,NULL,has_overlap?0:1);
}
}
static void usage(args_t *args)
{
fprintf(stderr, "\n");
fprintf(stderr, "About: Annotate and edit VCF/BCF files.\n");
fprintf(stderr, "Usage: bcftools annotate [options] <in.vcf.gz>\n");
fprintf(stderr, "\n");
fprintf(stderr, "Options:\n");
fprintf(stderr, " -a, --annotations <file> VCF file or tabix-indexed file with annotations: CHR\\tPOS[\\tVALUE]+\n");
fprintf(stderr, " --collapse <string> matching records by <snps|indels|both|all|some|none>, see man page for details [some]\n");
fprintf(stderr, " -c, --columns <list> list of columns in the annotation file, e.g. CHROM,POS,REF,ALT,-,INFO/TAG. See man page for details\n");
fprintf(stderr, " -e, --exclude <expr> exclude sites for which the expression is true (see man page for details)\n");
fprintf(stderr, " --force continue despite parsing error (at your own risk!)\n");
fprintf(stderr, " -h, --header-lines <file> lines which should be appended to the VCF header\n");
fprintf(stderr, " -I, --set-id [+]<format> set ID column, see man page for details\n");
fprintf(stderr, " -i, --include <expr> select sites for which the expression is true (see man page for details)\n");
fprintf(stderr, " -k, --keep-sites leave -i/-e sites unchanged instead of discarding them\n");
fprintf(stderr, " -l, --merge-logic <tag:type> merge logic for multiple overlapping regions (see man page for details), EXPERIMENTAL\n");
fprintf(stderr, " -m, --mark-sites [+-]<tag> add INFO/tag flag to sites which are (\"+\") or are not (\"-\") listed in the -a file\n");
fprintf(stderr, " --no-version do not append version and command line to the header\n");
fprintf(stderr, " -o, --output <file> write output to a file [standard output]\n");
fprintf(stderr, " -O, --output-type <b|u|z|v> b: compressed BCF, u: uncompressed BCF, z: compressed VCF, v: uncompressed VCF [v]\n");
fprintf(stderr, " -r, --regions <region> restrict to comma-separated list of regions\n");
fprintf(stderr, " -R, --regions-file <file> restrict to regions listed in a file\n");
fprintf(stderr, " --rename-chrs <file> rename sequences according to map file: from\\tto\n");
fprintf(stderr, " -s, --samples [^]<list> comma separated list of samples to annotate (or exclude with \"^\" prefix)\n");
fprintf(stderr, " -S, --samples-file [^]<file> file of samples to annotate (or exclude with \"^\" prefix)\n");
fprintf(stderr, " --single-overlaps keep memory low by avoiding complexities arising from handling multiple overlapping intervals\n");
fprintf(stderr, " -x, --remove <list> list of annotations (e.g. ID,INFO/DP,FORMAT/DP,FILTER) to remove (or keep with \"^\" prefix). See man page for details\n");
fprintf(stderr, " --threads <int> number of extra output compression threads [0]\n");
fprintf(stderr, "\n");
exit(1);
}
int main_vcfannotate(int argc, char *argv[])
{
int c;
args_t *args = (args_t*) calloc(1,sizeof(args_t));
args->argc = argc; args->argv = argv;
args->files = bcf_sr_init();
args->output_fname = "-";
args->output_type = FT_VCF;
args->n_threads = 0;
args->record_cmd_line = 1;
args->ref_idx = args->alt_idx = args->chr_idx = args->beg_idx = args->end_idx = -1;
args->set_ids_replace = 1;
int regions_is_file = 0, collapse = 0;
static struct option loptions[] =
{
{"keep-sites",no_argument,NULL,'k'},
{"mark-sites",required_argument,NULL,'m'},
{"set-id",required_argument,NULL,'I'},
{"output",required_argument,NULL,'o'},
{"output-type",required_argument,NULL,'O'},
{"threads",required_argument,NULL,9},
{"annotations",required_argument,NULL,'a'},
{"merge-logic",required_argument,NULL,'l'},
{"collapse",required_argument,NULL,2},
{"include",required_argument,NULL,'i'},
{"exclude",required_argument,NULL,'e'},
{"regions",required_argument,NULL,'r'},
{"regions-file",required_argument,NULL,'R'},
{"remove",required_argument,NULL,'x'},
{"columns",required_argument,NULL,'c'},
{"rename-chrs",required_argument,NULL,1},
{"header-lines",required_argument,NULL,'h'},
{"samples",required_argument,NULL,'s'},
{"samples-file",required_argument,NULL,'S'},
{"single-overlaps",no_argument,NULL,10},
{"no-version",no_argument,NULL,8},
{"force",no_argument,NULL,'f'},
{NULL,0,NULL,0}
};
while ((c = getopt_long(argc, argv, "h:?o:O:r:R:a:x:c:i:e:S:s:I:m:kl:f",loptions,NULL)) >= 0)
{
switch (c) {
case 'f': args->force = 1; break;
case 'k': args->keep_sites = 1; break;
case 'm':
args->mark_sites_logic = MARK_LISTED;
if ( optarg[0]=='+' ) args->mark_sites = optarg+1;
else if ( optarg[0]=='-' ) { args->mark_sites = optarg+1; args->mark_sites_logic = MARK_UNLISTED; }
else args->mark_sites = optarg;
break;
case 'l': args->merge_method_str = optarg; break;
case 'I': args->set_ids_fmt = optarg; break;
case 's': args->sample_names = optarg; break;
case 'S': args->sample_names = optarg; args->sample_is_file = 1; break;
case 'c': args->columns = strdup(optarg); break;
case 'o': args->output_fname = optarg; break;
case 'O':
switch (optarg[0]) {
case 'b': args->output_type = FT_BCF_GZ; break;
case 'u': args->output_type = FT_BCF; break;
case 'z': args->output_type = FT_VCF_GZ; break;
case 'v': args->output_type = FT_VCF; break;
default: error("The output type \"%s\" not recognised\n", optarg);
};
break;
case 'e': args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
case 'i': args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
case 'x': args->remove_annots = optarg; break;
case 'a': args->targets_fname = optarg; break;
case 'r': args->regions_list = optarg; break;
case 'R': args->regions_list = optarg; regions_is_file = 1; break;
case 'h': args->header_fname = optarg; break;
case 1 : args->rename_chrs = optarg; break;
case 2 :
if ( !strcmp(optarg,"snps") ) collapse |= COLLAPSE_SNPS;
else if ( !strcmp(optarg,"indels") ) collapse |= COLLAPSE_INDELS;
else if ( !strcmp(optarg,"both") ) collapse |= COLLAPSE_SNPS | COLLAPSE_INDELS;
else if ( !strcmp(optarg,"any") ) collapse |= COLLAPSE_ANY;
else if ( !strcmp(optarg,"all") ) collapse |= COLLAPSE_ANY;
else if ( !strcmp(optarg,"some") ) collapse |= COLLAPSE_SOME;
else if ( !strcmp(optarg,"none") ) collapse = COLLAPSE_NONE;
else error("The --collapse string \"%s\" not recognised.\n", optarg);
break;
case 9 : args->n_threads = strtol(optarg, 0, 0); break;
case 8 : args->record_cmd_line = 0; break;
case 10 : args->single_overlaps = 1; break;
case '?': usage(args); break;
default: error("Unknown argument: %s\n", optarg);
}
}
char *fname = NULL;
if ( optind>=argc )
{
if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
else usage(args);
}
else fname = argv[optind];
if ( args->regions_list )
{
if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
error("Failed to read the regions: %s\n", args->regions_list);
}
if ( args->targets_fname )
{
htsFile *fp = hts_open(args->targets_fname,"r");
if ( !fp ) error("Failed to open %s\n", args->targets_fname);
htsFormat type = *hts_get_format(fp);
hts_close(fp);
if ( type.format==vcf || type.format==bcf )
{
args->tgts_is_vcf = 1;
args->files->require_index = 1;
args->files->collapse = collapse ? collapse : COLLAPSE_SOME;
}
}
if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n");
if ( !bcf_sr_add_reader(args->files, fname) ) error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum));
static int line_errcode_warned = 0;
init_data(args);
while ( bcf_sr_next_line(args->files) )
{
if ( !bcf_sr_has_line(args->files,0) ) continue;
bcf1_t *line = bcf_sr_get_line(args->files,0);
if ( line->errcode )
{
if ( !args->force )
error("Encountered an error, cannot proceed. Please check the error output above.\n"
"If feeling adventurous, use the --force option. (At your own risk!)\n");
else if ( !line_errcode_warned )
{
fprintf(stderr,
"Warning: Encountered an error, proceeding only because --force was given.\n"
" Note that this can result in a segfault or a silent corruption of the output file!\n");
line_errcode_warned = 1;
line->errcode = 0;
}
}
if ( args->filter )
{
int pass = filter_test(args->filter, line, NULL);
if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
if ( !pass )
{
if ( args->keep_sites && bcf_write1(args->out_fh, args->hdr_out, line)!=0 ) error("[%s] Error: failed to write to %s\n", __func__,args->output_fname);
continue;
}
}
annotate(args, line);
if ( bcf_write1(args->out_fh, args->hdr_out, line)!=0 ) error("[%s] Error: failed to write to %s\n", __func__,args->output_fname);
}
destroy_data(args);
bcf_sr_destroy(args->files);
free(args);
return 0;
}
| 43.282857 | 204 | 0.55804 |
cfbdae582ec5399640aa7ffad2ddced50a255b8b | 3,290 | c | C | Parcial2/Practica5/PSO/PSO.c | DiegoMontano2705/MachineLearning | 0b78f78b31dfaf615226566b26dcc9c267082882 | [
"MIT"
] | null | null | null | Parcial2/Practica5/PSO/PSO.c | DiegoMontano2705/MachineLearning | 0b78f78b31dfaf615226566b26dcc9c267082882 | [
"MIT"
] | null | null | null | Parcial2/Practica5/PSO/PSO.c | DiegoMontano2705/MachineLearning | 0b78f78b31dfaf615226566b26dcc9c267082882 | [
"MIT"
] | null | null | null | /*
Running & Testing Commands:
g++ -o PSO PSO.c rand.cpp
./PSO 2 100 100 3 -3 1
./PSO 2 100 100 3.5 2.3 0.9 1
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rand.h"
#define PI 3.141592654
#define UB 5
#define LB -5
typedef struct{
double *x; // current position
double *v; // current velocity vector
double *y; // local best position
double f;
}Particle;
Particle *Swarm, gBest;
int n, N, Gmax;
double c1, c2, *r1, *r2, w;
double f(double *x){
double tmp = 0.0;
int i;
for(i = 0; i < n; i++)
tmp += x[i]*x[i];
return tmp;
}
void initialize(){
for (int i = 0; i < N; ++i){
for (int j = 0; j < n; ++j){
Swarm[i].x[j] = rndreal(LB, UB);
Swarm[i].y[j] = Swarm[i].x[j];
}
Swarm[i].f = INFINITY;
}
gBest.f = INFINITY;
}
void allocate_mem(){
int i;
Swarm = (Particle *)malloc(N*sizeof(Particle));
for(i = 0; i < N; i++){
Swarm[i].x = (double *)calloc(n, sizeof(double));
Swarm[i].v = (double *)calloc(n, sizeof(double));
Swarm[i].y = (double *)calloc(n, sizeof(double));
}
gBest.x = (double *)calloc(n, sizeof(double));
gBest.v = (double *)calloc(n, sizeof(double));
gBest.y = (double *)calloc(n, sizeof(double));
r1 = (double *)calloc(n, sizeof(double));
r2 = (double *)calloc(n, sizeof(double));
}
void gBestPSO(int run){
FILE *file;
FILE *fileMov;
char filename[50];
sprintf(filename, "conv_%d.dat", run);
file = fopen(filename, "w");
fileMov = fopen("answer.txt","w");
if(file == NULL){
printf("Error! file %s couldn't be opened!\n", filename);
exit(-1);
}
initialize();
int t = 0;
while(t < Gmax){
for(int i = 0; i < N; i++){
double fx = f(Swarm[i].x);
if(fx < Swarm[i].f){
// Update local best position
memcpy(Swarm[i].y, Swarm[i].x, n*sizeof(double));
Swarm[i].f = fx;
}
if(Swarm[i].f < gBest.f){
// Update gBest based on comparisons with all particles
memcpy(gBest.x, Swarm[i].y, n*sizeof(double));
gBest.f = Swarm[i].f;
}
}
for(int r = 0; r < n; r++){
r1[r] = rndreal(0, 1);
r2[r] = rndreal(0, 1);
}
for(int i = 0; i < N; i++){
// Set values for vectors r1 and r2 from a uniform distribution in range [0, 1]
for(int j = 0; j < n; j++){
Swarm[i].v[j] = w*Swarm[i].v[j] + c1*r1[j]*(Swarm[i].y[j] - Swarm[i].x[j]) + c2*r2[j]*(gBest.x[j] - Swarm[i].x[j]);
Swarm[i].x[j] = Swarm[i].x[j] + Swarm[i].v[j];
// If out of bounds, force x_j to be inside the feasible region
if(Swarm[i].x[j] < LB)
Swarm[i].x[j] = LB;
else if(Swarm[i].x[j] > UB)
Swarm[i].x[j] = UB;
// Save in file position of particle
fprintf(fileMov,"%lf " ,Swarm[i].x[j]);
fprintf(file, "%lf ", Swarm[i].x[j]);
}
}
fprintf(file, "%n");
fprintf(fileMov,"\n ");
t++;
}
fclose(file);
fclose(fileMov);
}
int main(int argc, char *argv[]){
int RUN_MAX;
if(argc != 8){
printf("Syntax error! %s dim numParticles Gmax c1 c2 w RUNs\n", argv[0]);
exit(-1);
}
n = atoi(argv[1]);
N = atoi(argv[2]);
Gmax = atoi(argv[3]);
c1 = atof(argv[4]);
c2 = atof(argv[5]);
w = atof(argv[6]);
RUN_MAX = atoi(argv[7]);
initrandom(time(0));
allocate_mem();
int run;
for(run = 0; run < RUN_MAX; run++){
gBestPSO(run);
printf("%lf\n", gBest.f);
}
} | 23.169014 | 119 | 0.558967 |
cfd233d1a870abe867182247b138cc70516a980c | 827 | h | C | public/net/net_server_socket.h | lvnux/midden | 261e2661690e9212ccb90dc64a02fde40f6ce1a7 | [
"MIT"
] | 1 | 2021-06-13T14:13:31.000Z | 2021-06-13T14:13:31.000Z | public/net/net_server_socket.h | lvnux/midden | 261e2661690e9212ccb90dc64a02fde40f6ce1a7 | [
"MIT"
] | null | null | null | public/net/net_server_socket.h | lvnux/midden | 261e2661690e9212ccb90dc64a02fde40f6ce1a7 | [
"MIT"
] | null | null | null | /*
* net_server_socket.h
* 服务端socket
*/
#ifndef __NET_SERVER_SOCKET_H__
#define __NET_SERVER_SOCKET_H__
#include "ihandler.h"
#include "net_address.h"
#include "base_thread.h"
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
class TAcceptSocketMsg : public BaseMsg
{
public:
int socket;
NetAddress address;
};
class NetServiceManager;
class NetServerSocket : public IHandler
{
public:
NetServerSocket(NetServiceManager* manager, BaseThread* thread);
~NetServerSocket();
public:
bool listen(const NetAddress& address, int backlog=128);
void close();
protected:
virtual int get_descriptor();
virtual void on_read();
virtual void on_write();
private:
int socket_;
NetServiceManager* manager_;
BaseThread* thread_;
};
#endif // __NET_SERVER_SOCKET_H__ | 17.978261 | 68 | 0.727932 |
cfdb7d9c536571da533cacb9eadb52f4087e7a99 | 1,538 | h | C | src/include/catalog/postgres/pg_type.h | LiuXiaoxuanPKU/terrier | 35916e9435201016903d8a01e3f587b8edb36f0b | [
"MIT"
] | 1 | 2019-08-18T21:33:57.000Z | 2019-08-18T21:33:57.000Z | src/include/catalog/postgres/pg_type.h | LiuXiaoxuanPKU/terrier | 35916e9435201016903d8a01e3f587b8edb36f0b | [
"MIT"
] | null | null | null | src/include/catalog/postgres/pg_type.h | LiuXiaoxuanPKU/terrier | 35916e9435201016903d8a01e3f587b8edb36f0b | [
"MIT"
] | null | null | null | #pragma once
#include "catalog/schema.h"
#include "storage/projected_row.h"
#include "storage/sql_table.h"
#include "storage/storage_defs.h"
#include "transaction/transaction_context.h"
namespace terrier::catalog::postgres {
constexpr table_oid_t TYPE_TABLE_OID = table_oid_t(51);
constexpr index_oid_t TYPE_OID_INDEX_OID = index_oid_t(52);
constexpr index_oid_t TYPE_NAME_INDEX_OID = index_oid_t(53);
constexpr index_oid_t TYPE_NAMESPACE_INDEX_OID = index_oid_t(54);
/*
* Column names of the form "TYP[name]_COL_OID" are present in the PostgreSQL
* catalog specification and columns of the form "TYP_[name]_COL_OID" are
* terrier-specific addtions (generally pointers to internal objects).
*/
constexpr col_oid_t TYPOID_COL_OID = col_oid_t(1); // INTEGER (pkey)
constexpr col_oid_t TYPNAME_COL_OID = col_oid_t(2); // VARCHAR
constexpr col_oid_t TYPNAMESPACE_COL_OID = col_oid_t(3); // INTEGER (fkey: pg_namespace)
constexpr col_oid_t TYPLEN_COL_OID = col_oid_t(4); // SMALLINT
constexpr col_oid_t TYPBYVAL_COL_OID = col_oid_t(5); // BOOLEAN
constexpr col_oid_t TYPTYPE_COL_OID = col_oid_t(6); // CHAR
constexpr std::array<col_oid_t, 6> PG_TYPE_ALL_COL_OIDS = {TYPOID_COL_OID, TYPNAME_COL_OID, TYPNAMESPACE_COL_OID,
TYPLEN_COL_OID, TYPBYVAL_COL_OID, TYPTYPE_COL_OID};
enum class Type : char {
BASE = 'b',
COMPOSITE = 'c',
PG_DOMAIN = 'd',
ENUM = 'e',
PSEUDO = 'p',
RANGE = 'r',
};
} // namespace terrier::catalog::postgres
| 38.45 | 114 | 0.724967 |
d60ef500972fbd84b647f1fedb2edab5f854a291 | 2,252 | h | C | components/render/scene_render/interchange/include/render/scene/interchange/inprocess_exchange_storage.h | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/render/scene_render/interchange/include/render/scene/interchange/inprocess_exchange_storage.h | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/render/scene_render/interchange/include/render/scene/interchange/inprocess_exchange_storage.h | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #ifndef RENDER_SCENE_INTERCHANGE_INPROCESS_EXCHANGE_STORAGE_HEADER
#define RENDER_SCENE_INTERCHANGE_INPROCESS_EXCHANGE_STORAGE_HEADER
#include <typeinfo>
#include <xtl/functional_fwd>
#include <render/scene/interchange/types.h>
namespace render
{
namespace scene
{
namespace interchange
{
namespace detail
{
struct BasicAttachment;
template <class T> struct Attachment;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///Хранилище для обмена объектами внутри одного процесса
///////////////////////////////////////////////////////////////////////////////////////////////////
class InprocessExchangeStorage
{
public:
///////////////////////////////////////////////////////////////////////////////////////////////////
///Выделение идентификатора владельца
///////////////////////////////////////////////////////////////////////////////////////////////////
static object_id_t AllocateOwnerId ();
static void DeallocateOwnerId (object_id_t);
///////////////////////////////////////////////////////////////////////////////////////////////////
///Регистрация объекта
///////////////////////////////////////////////////////////////////////////////////////////////////
template <class T> static object_id_t Attach (object_id_t owner_id, const T& object);
static void Detach (object_id_t id);
static void DetachAllWithOwner (object_id_t owner_id);
///////////////////////////////////////////////////////////////////////////////////////////////////
///Получение объекта
///////////////////////////////////////////////////////////////////////////////////////////////////
template <class T> static T& Attachment (object_id_t id);
template <class T> static T* FindAttachment (object_id_t id);
private:
static object_id_t Attach (detail::BasicAttachment*);
static detail::BasicAttachment* FindAttachment (object_id_t id, const std::type_info& type);
static void RaiseAttachmentError (const char*, object_id_t, const std::type_info&);
};
#include <render/scene/interchange/detail/inprocess_exchange_storage.inl>
}
}
}
#endif
| 33.61194 | 107 | 0.458703 |
d62c573848c7db6183543f97665b2063029b8315 | 588 | h | C | IPQueueDispatcher/Classes/Models/CoreData/IPMessageURLEntity/IPMessageURLEntity+CoreDataProperties.h | ph1lb4/IPQueueDispatcher | 383b2931e9c6f37edafc77e28ae2886338c6000f | [
"MIT"
] | null | null | null | IPQueueDispatcher/Classes/Models/CoreData/IPMessageURLEntity/IPMessageURLEntity+CoreDataProperties.h | ph1lb4/IPQueueDispatcher | 383b2931e9c6f37edafc77e28ae2886338c6000f | [
"MIT"
] | null | null | null | IPQueueDispatcher/Classes/Models/CoreData/IPMessageURLEntity/IPMessageURLEntity+CoreDataProperties.h | ph1lb4/IPQueueDispatcher | 383b2931e9c6f37edafc77e28ae2886338c6000f | [
"MIT"
] | 2 | 2016-08-16T11:55:25.000Z | 2020-07-16T12:06:39.000Z | //
// IPMessageURLEntity+CoreDataProperties.h
// Pods
//
// Created by Ilias Pavlidakis on 15/06/2016.
//
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
#import "IPMessageURLEntity.h"
NS_ASSUME_NONNULL_BEGIN
@interface IPMessageURLEntity (CoreDataProperties)
@property (nullable, nonatomic, retain) NSString *baseURL;
@property (nullable, nonatomic, retain) NSString *path;
@property (nullable, nonatomic, retain) IPMessageEntity *message;
@end
NS_ASSUME_NONNULL_END
| 23.52 | 76 | 0.772109 |
aab21f33abc5dd9a67744365ab0493b5aa0ca97f | 2,101 | h | C | QuEST/src/QuEST_debug.h | QTechTheory/ArcusQuESTBenchmarks | a57ca624fc479864884ed377a236f6a0817b71da | [
"MIT"
] | 1 | 2020-01-11T15:53:29.000Z | 2020-01-11T15:53:29.000Z | QuEST/src/QuEST_debug.h | QTechTheory/BenchmarkWithQuEST | a57ca624fc479864884ed377a236f6a0817b71da | [
"MIT"
] | null | null | null | QuEST/src/QuEST_debug.h | QTechTheory/BenchmarkWithQuEST | a57ca624fc479864884ed377a236f6a0817b71da | [
"MIT"
] | null | null | null | // Distributed under MIT licence. See https://github.com/QuEST-Kit/QuEST/blob/master/LICENCE.txt for details
/** @file
* Developer functions used for unit testing and debugging, which are not part of the public API.
* May contain functions that are incomplete or untested.
*
* @author Ania Brown
* @author Tyson Jones (architecture)
*/
# ifndef QUEST_DEBUG_H
# define QUEST_DEBUG_H
# include "QuEST_precision.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Initialise the state vector of probability amplitudes such that one qubit is set to 'outcome' and all other qubits are in an equal superposition of zero and one.
* @param[in,out] qureg object representing the set of qubits to be initialised
* @param[in] qubitId id of qubit to set to state 'outcome'
* @param[in] outcome value of qubit 'qubitId' to set
*/
void initStateOfSingleQubit(Qureg *qureg, int qubitId, int outcome);
/**
* Initialise the state vector of probability amplitudes to an (unphysical) state with
* each component of each probability amplitude a unique floating point value. For debugging processes
* @param[in,out] qureg object representing the set of qubits to be initialised
*/
void initStateDebug(Qureg qureg);
/** Initialises the wavefunction amplitudes according to those specified in a file.
* For debugging purpsoses
*/
void initStateFromSingleFile(Qureg *qureg, char filename[200], QuESTEnv env);
/** Return whether two given wavefunctions are equivalent within a given precision
* Global phase included in equivalence check. For debugging purposes.
*/
int compareStates(Qureg mq1, Qureg mq2, qreal precision);
/** Set elements in the underlying state vector represenation of a density matrix. Not exposed in the public
* API as this requires an understanding of how the state vector is used to represent a density matrix.
* Currently can only be used to set all amps.
*/
void setDensityAmps(Qureg qureg, qreal* reals, qreal* imags);
/** Return the precision of qreal for use in testing
* */
int QuESTPrecision(void);
#ifdef __cplusplus
}
#endif
# endif // QUEST_DEBUG_H
| 33.349206 | 164 | 0.75821 |
c580e3a9a3efc6311b00c7bbde11637ffa9a586e | 267 | h | C | timelib/timelib.h | ADLabidi/stmclock | 202ba32d6f946a085c91f6395d64cce0867259f0 | [
"MIT"
] | null | null | null | timelib/timelib.h | ADLabidi/stmclock | 202ba32d6f946a085c91f6395d64cce0867259f0 | [
"MIT"
] | null | null | null | timelib/timelib.h | ADLabidi/stmclock | 202ba32d6f946a085c91f6395d64cce0867259f0 | [
"MIT"
] | null | null | null | /*
* timelib.h
*
* Created on: Mar 14, 2021
* Author: ASUS
*/
#ifndef TIMELIB_H_
#define TIMELIB_H_
#include "stdint.h"
void timelib_updateTimeCount();
void timelib_init();
uint64_t timelib_getRawTime();
void timelib_printTime();
#endif /* TIMELIB_H_ */
| 15.705882 | 31 | 0.700375 |
cf906f222dd1222063ff13d6a6d00c5ddf976222 | 3,748 | c | C | nitan/d/wudang/obj/cypress.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/d/wudang/obj/cypress.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/d/wudang/obj/cypress.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // cypress.c 柏樹
// Last Modified by winder on Aug. 18 2002
#include <ansi.h>
inherit ITEM;
int start_collapse = 0;
int chop_times = 0;
void create()
{
set_name(HIG"青柏樹"NOR,({"cypress"}));
set_weight(900000);
if (clonep())
set_default_object(__FILE__);
else {
set("long", "這是一棵蒼翠的青柏樹。\n");
set("unit", "棵");
set("value", 8);
set("no_get", 1);
}
setup();
}
void init()
{
add_action("do_chop", "chop");
add_action("do_chop", "砍");
}
int do_chop(string arg)
{
object weapon, me = this_player();
object piece;
if( !arg || arg!="cypress" && arg != "樹" )
return notify_fail("你要砍甚麼?\n");
if( !objectp(weapon=query_temp("weapon", me)) )
{
message_vision(HIR"$N揮手朝柏樹一陣猛砍,弄得雙手鮮血淋淋。\n"NOR, me);
me->receive_damage("qi", 50, "流血過多死了");
return 1;
}else if( query("skill_type", weapon) != "sword" &&
query("skill_type", weapon) != "blade" &&
query("skill_type", weapon) != "axe" )
{
message_vision(HIW"$N揮起手中" + weapon->name() + HIW"朝柏樹一陣猛砍。\n"NOR, me);
message_vision(HIW"結果「啪」地一聲,$N手中的" + weapon->name() + HIW"已經斷為兩截!\n"NOR , me );
weapon->unequip();
seteuid(getuid());
piece = new("/clone/misc/piece");
piece->set_name("斷掉的"+query("name", weapon),({query("id", weapon),"piece"}));
piece->move(environment(me));
destruct(weapon);
return 1;
}
message_vision(HIW"$N操起手中" + weapon->name() + HIW",吭吃吭吃地砍樹。\n"NOR, me);
me->receive_damage("qi",5+random(35-query("str", me)),"砍樹累死了");
chop_times++;
if ( !start_collapse && random(chop_times) )
{
start_collapse = 1;
chop_times = 0;
message_vision(HIC"柏樹開始鬆動起來,吱吱呀呀發出響聲。\n"NOR, this_object());
call_out("collapse", 20, me);
}
return 1;
}
void collapse(object me)
{
object ob, obn;
object *inv;
int i;
ob = this_object();
if ( !objectp(me) ) return;
if ( chop_times <= 0 || random(chop_times) < 2)
{
message_vision(HIC"柏樹搖擺了兩下,又站住了。\n"NOR, ob);
start_collapse = 0;
return;
}
message_vision(RED"柏樹轟的一聲倒了下來…\n"NOR, ob);
if ( random(chop_times) > 5 )
if ( present(me, environment(ob)) )
{
message_vision(HIR"正砸在$n頭上!\n"NOR, ob, me);
me->receive_damage("qi", 30*chop_times, "被柏樹幹砸死了");
me->receive_wound("qi", 20*chop_times, "被柏樹幹砸死了");
}
else
{
inv = all_inventory(environment(ob));
for (i = 0; i < sizeof(inv); i++)
if (userp(inv[i]))
{
message_vision(HIR"正砸在$n頭上!\n"NOR, ob, inv[i]);
inv[i]->receive_damage("qi",30*chop_times, "被柏樹幹砸死了");
inv[i]->receive_wound("qi", 20*chop_times, "被柏樹幹砸死了");
}
}
if (chop_times >= 13) chop_times = 13;
set("wdjob/wage", chop_times, me);
if ( objectp(environment(ob)) )
{
obn = new(__DIR__"cypress_bole");
obn->move(environment(ob));
}
destruct(ob);
} | 30.721311 | 103 | 0.447172 |
fda70e93e5284c406e7f328c79fcf930dee8a3f3 | 1,345 | h | C | System/Library/Frameworks/CloudKit.framework/CKSyncEngineBatch.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/Frameworks/CloudKit.framework/CKSyncEngineBatch.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/Frameworks/CloudKit.framework/CKSyncEngineBatch.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Friday, April 30, 2021 at 11:35:22 AM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/Frameworks/CloudKit.framework/CloudKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
@class NSArray;
@interface CKSyncEngineBatch : NSObject {
BOOL _atomic;
NSArray* _recordsToSave;
NSArray* _recordIDsToDelete;
}
@property (assign,getter=isAtomic,nonatomic) BOOL atomic; //@synthesize atomic=_atomic - In the implementation block
@property (nonatomic,readonly) NSArray * recordsToSave; //@synthesize recordsToSave=_recordsToSave - In the implementation block
@property (nonatomic,readonly) NSArray * recordIDsToDelete; //@synthesize recordIDsToDelete=_recordIDsToDelete - In the implementation block
-(id)description;
-(id)initWithRecordsToSave:(id)arg1 recordIDsToDelete:(id)arg2 ;
-(void)setAtomic:(BOOL)arg1 ;
-(id)CKDescriptionPropertiesWithPublic:(BOOL)arg1 private:(BOOL)arg2 shouldExpand:(BOOL)arg3 ;
-(NSArray *)recordsToSave;
-(NSArray *)recordIDsToDelete;
-(BOOL)isAtomic;
@end
| 42.03125 | 153 | 0.677323 |
802025dea446159702373817e22e41036ec18158 | 2,310 | c | C | demos/models/suchai-flight-software/src/system/taskWatchdog.c | osoco/comprendiendo-software-creando-herramientas | 64b07b29a876ce180b3ba03dfd1d1770d5fc6f6e | [
"CC0-1.0"
] | 1 | 2022-02-06T10:48:13.000Z | 2022-02-06T10:48:13.000Z | demos/models/suchai-flight-software/src/system/taskWatchdog.c | osoco/comprendiendo-software-creando-herramientas | 64b07b29a876ce180b3ba03dfd1d1770d5fc6f6e | [
"CC0-1.0"
] | null | null | null | demos/models/suchai-flight-software/src/system/taskWatchdog.c | osoco/comprendiendo-software-creando-herramientas | 64b07b29a876ce180b3ba03dfd1d1770d5fc6f6e | [
"CC0-1.0"
] | 1 | 2022-02-06T10:48:15.000Z | 2022-02-06T10:48:15.000Z | /* SUCHAI
* NANOSATELLITE FLIGHT SOFTWARE
*
* Copyright 2020, Carlos Gonzalez Cortes, carlgonz@uchile.cl
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "taskWatchdog.h"
static const char *tag = "WDT";
void taskWatchdog(void *param)
{
LOGI(tag, "Started");
portTick delay_ms = 1000; //Task period in [ms]
unsigned int max_obc_wdt = SCH_MAX_WDT_TIMER; // Seconds to send "reset_wdt" command
unsigned int max_gnd_wdt = SCH_MAX_GND_WDT_TIMER; // Seconds to send "reset" command
unsigned int elapsed_obc_timer = 0; // OBC timer counter
unsigned int elapsed_sw_timer = 0; // Software timer counter
portTick xLastWakeTime = osTaskGetTickCount();
while(1)
{
// Sleep task to count seconds
osTaskDelayUntil(&xLastWakeTime, delay_ms);
elapsed_obc_timer++; // Increase timer to reset the obc wdt
elapsed_sw_timer = (unsigned int)dat_get_system_var(dat_obc_sw_wdt) + 1; //Increase software timer counter. Should be cleared by a gnd command
dat_set_system_var(dat_obc_sw_wdt, (int) elapsed_sw_timer); // Save increased software timer
// Periodically reset the OBC watchdog
if(elapsed_obc_timer > max_obc_wdt)
{
elapsed_obc_timer = 0;
cmd_t *rst_wdt = cmd_get_str("obc_reset_wdt");
cmd_send(rst_wdt);
}
// If nobody clears elapsed_gnd_timer, then reset the OBC
if(elapsed_sw_timer > max_gnd_wdt)
{
LOGW(tag, "Software watchdog overflow")
cmd_t *rst_obc = cmd_get_str("obc_reset");
cmd_send(rst_obc);
}
}
}
| 38.5 | 151 | 0.665368 |
806333315105adf52fcc960aa4d4c3a4f8a6a89d | 3,198 | h | C | third_party/gecko-2/win32/include/rdfISerializer.h | akiellor/selenium | 239490f9c5f3c7e7d4082bbe53c86eb5158d70a3 | [
"Apache-2.0"
] | 1 | 2018-08-24T18:01:34.000Z | 2018-08-24T18:01:34.000Z | third_party/gecko-2/win32/include/rdfISerializer.h | akiellor/selenium | 239490f9c5f3c7e7d4082bbe53c86eb5158d70a3 | [
"Apache-2.0"
] | 1 | 2021-10-18T12:23:37.000Z | 2021-10-18T12:23:37.000Z | third_party/gecko-2/win32/include/rdfISerializer.h | akiellor/selenium | 239490f9c5f3c7e7d4082bbe53c86eb5158d70a3 | [
"Apache-2.0"
] | 2 | 2018-04-30T21:35:30.000Z | 2021-05-14T08:11:46.000Z | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/rdf/base/idl/rdfISerializer.idl
*/
#ifndef __gen_rdfISerializer_h__
#define __gen_rdfISerializer_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class rdfIDataSource; /* forward declaration */
class nsIOutputStream; /* forward declaration */
/* starting interface: rdfISerializer */
#define RDFISERIALIZER_IID_STR "f0edfcdd-8bca-4d32-9226-7421001396a4"
#define RDFISERIALIZER_IID \
{0xf0edfcdd, 0x8bca, 0x4d32, \
{ 0x92, 0x26, 0x74, 0x21, 0x00, 0x13, 0x96, 0xa4 }}
/**
* Interface used to serialize RDF.
*
* @status PLASMA
*/
class NS_NO_VTABLE NS_SCRIPTABLE rdfISerializer : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(RDFISERIALIZER_IID)
/**
* Synchronously serialize the given datasource to the outputstream.
*
* Implementations are not required to implement any buffering or
* other stream-based optimizations.
*
* @param aDataSource The RDF data source to be serialized.
* @param aOut The output stream to use.
*/
/* void serialize (in rdfIDataSource aDataSource, in nsIOutputStream aOut); */
NS_SCRIPTABLE NS_IMETHOD Serialize(rdfIDataSource *aDataSource, nsIOutputStream *aOut) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(rdfISerializer, RDFISERIALIZER_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_RDFISERIALIZER \
NS_SCRIPTABLE NS_IMETHOD Serialize(rdfIDataSource *aDataSource, nsIOutputStream *aOut);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_RDFISERIALIZER(_to) \
NS_SCRIPTABLE NS_IMETHOD Serialize(rdfIDataSource *aDataSource, nsIOutputStream *aOut) { return _to Serialize(aDataSource, aOut); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_RDFISERIALIZER(_to) \
NS_SCRIPTABLE NS_IMETHOD Serialize(rdfIDataSource *aDataSource, nsIOutputStream *aOut) { return !_to ? NS_ERROR_NULL_POINTER : _to->Serialize(aDataSource, aOut); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class _MYCLASS_ : public rdfISerializer
{
public:
NS_DECL_ISUPPORTS
NS_DECL_RDFISERIALIZER
_MYCLASS_();
private:
~_MYCLASS_();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(_MYCLASS_, rdfISerializer)
_MYCLASS_::_MYCLASS_()
{
/* member initializers and constructor code */
}
_MYCLASS_::~_MYCLASS_()
{
/* destructor code */
}
/* void serialize (in rdfIDataSource aDataSource, in nsIOutputStream aOut); */
NS_IMETHODIMP _MYCLASS_::Serialize(rdfIDataSource *aDataSource, nsIOutputStream *aOut)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_rdfISerializer_h__ */
| 29.072727 | 167 | 0.731707 |
b7c15ce39af524e7052dc68ea02678768fe8f900 | 10,634 | c | C | db_arena.c | KinderRiven/Database | b1eaa994c991fdcc620b6304302390bb50b9ff84 | [
"BSD-2-Clause"
] | 3 | 2015-12-09T12:22:00.000Z | 2017-08-07T11:13:30.000Z | db_arena.c | KinderRiven/DataBase | b1eaa994c991fdcc620b6304302390bb50b9ff84 | [
"BSD-2-Clause"
] | null | null | null | db_arena.c | KinderRiven/DataBase | b1eaa994c991fdcc620b6304302390bb50b9ff84 | [
"BSD-2-Clause"
] | null | null | null | #ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#ifndef apple
#define _XOPEN_SOURCE 600
#include <malloc.h>
#endif
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#endif
#include <inttypes.h>
#include "db.h"
#include "db_arena.h"
#include "db_map.h"
#include "db_object.h"
#include "db_frame.h"
#include "db_redblack.h"
#include "db_skiplist.h"
bool mapSeg (DbMap *map, uint32_t currSeg);
void mapZero(DbMap *map, uint64_t size);
void mapAll (DbMap *map);
uint64_t totalMemoryReq[1];
extern DbMap memMap[1];
// open map given database red/black rbEntry
DbMap *arenaRbMap(DbMap *parent, RedBlack *rbEntry) {
ArenaDef *arenaDef = (ArenaDef *)(rbEntry + 1);
DbMap *map;
if (*arenaDef->dead & KILL_BIT)
return NULL;
map = openMap(parent, rbkey(rbEntry), rbEntry->keyLen, arenaDef, rbEntry);
return map;
}
// open/create an Object database/store/index arena file
DbMap *openMap(DbMap *parent, char *name, uint32_t nameLen, ArenaDef *arenaDef, RedBlack *rbEntry) {
DbMap *map = NULL, **childMap = NULL;
DbArena *segZero = NULL;
SkipEntry *entry;
int amt;
// see if we've opened this
// map in this process already
if (parent) {
lockLatch(parent->childMaps->latch);
entry = skipAdd(memMap, parent->childMaps, arenaDef->id);
childMap = (DbMap **)entry->val;
if ((map = *childMap)) {
waitNonZero(map->type);
atomicAdd32(parent->openCnt, 1);
unlockLatch(parent->childMaps->latch);
return map;
}
}
map = db_malloc(sizeof(DbMap) + arenaDef->mapXtra, true);
if ((map->parent = parent)) {
*childMap = map;
unlockLatch(parent->childMaps->latch);
}
// are we opening a database?
// a database is its own db
if (parent && parent->parent)
map->db = parent->db;
else
map->db = map;
if (!arenaDef->params[OnDisk].boolVal) {
#ifdef _WIN32
map->hndl = INVALID_HANDLE_VALUE;
#else
map->hndl = -1;
#endif
return initArena(map, arenaDef, name, nameLen, rbEntry);
}
getPath(map, name, nameLen, arenaDef->nxtVer);
// open the onDisk arena file
// and read segZero
#ifdef _WIN32
segZero = VirtualAlloc(NULL, sizeof(DbArena), MEM_COMMIT, PAGE_READWRITE);
#else
segZero = valloc(sizeof(DbArena));
#endif
amt = readSegZero(map, segZero);
if (amt < 0) {
fprintf (stderr, "Unable to read %d bytes from %s, error = %d\n", (int)sizeof(DbArena), map->arenaPath, errno);
#ifdef _WIN32
VirtualFree(segZero, 0, MEM_RELEASE);
#else
free(segZero);
#endif
db_free(map->arenaPath);
db_free(map);
return NULL;
}
// did we create the arena file?
if (amt < sizeof(DbArena)) {
if ((map = initArena(map, arenaDef, name, nameLen, rbEntry)))
unlockArena(map->hndl, map->arenaPath);
#ifdef _WIN32
VirtualFree(segZero, 0, MEM_RELEASE);
#else
free(segZero);
#endif
return map;
}
// since segment zero exists,
// initialize the map
// and map seg zero
assert(segZero->segs->size > 0);
mapZero(map, segZero->segs->size);
#ifdef _WIN32
VirtualFree(segZero, 0, MEM_RELEASE);
#else
free(segZero);
#endif
if (map->arena->rbAddr->addr)
rbEntry = getObj(map, *map->arena->rbAddr);
map->arenaDef = (ArenaDef *)(rbEntry + 1);
map->objSize = map->arena->objSize;
map->rbEntry = rbEntry;
map->type[0] = map->arenaDef->arenaType;
unlockArena(map->hndl, map->arenaPath);
// wait for initialization to finish
waitNonZero(map->arena->type);
return map;
}
// finish creating new arena
// call with arena locked
DbMap *initArena (DbMap *map, ArenaDef *arenaDef, char *name, uint32_t nameLen, RedBlack *rbEntry) {
uint64_t initSize = arenaDef->params[InitSize].intVal;
uint32_t segOffset;
uint32_t bits;
// compute seg zero size multiple of cache line size
segOffset = sizeof(DbArena) + arenaDef->baseSize;
segOffset += 63;
segOffset &= -64;
if (initSize < segOffset)
initSize = segOffset;
if (initSize < MIN_segsize)
initSize = MIN_segsize;
initSize += 65535;
initSize &= -65536;
#ifdef DEBUG
if (map->arenaPath)
fprintf(stderr, "InitMap %s at %llu bytes\n", map->arenaPath, initSize);
#endif
#ifdef _WIN32
_BitScanReverse((unsigned long *)&bits, (unsigned long)initSize - 1);
bits++;
#else
bits = 32 - (__builtin_clz (initSize - 1));
#endif
// create initial segment on unix, windows will automatically do it
initSize = 1ULL << bits;
#ifndef _WIN32
if (map->hndl != -1)
if (ftruncate(map->hndl, initSize)) {
fprintf (stderr, "Unable to initialize file %s, error = %d\n", map->arenaPath, errno);
close(map->hndl);
db_free(map);
return NULL;
}
#endif
// initialize new arena segment zero
assert(initSize > 0);
mapZero(map, initSize);
map->arena->segs->nextObject.offset = segOffset >> 4;
map->arena->baseSize = arenaDef->baseSize;
map->arena->objSize = arenaDef->objSize;
map->arena->segs->size = initSize;
map->arena->delTs = 1;
// are we a catalog or database?
if (!rbEntry || !map->parent->parent) {
rbEntry = rbNew(map, name, nameLen, sizeof(ArenaDef));
map->arenaDef = (ArenaDef *)(rbEntry + 1);
map->arena->rbAddr->bits = rbEntry->addr.bits;
memcpy(map->arenaDef, arenaDef, sizeof(ArenaDef));
} else
map->arenaDef = arenaDef;
map->objSize = map->arena->objSize;
map->rbEntry = rbEntry;
map->type[0] = arenaDef->arenaType;
return map;
}
// initialize arena segment zero
void mapZero(DbMap *map, uint64_t size) {
assert(size > 0);
map->arena = mapMemory (map, 0, size, 0);
map->base[0] = (char *)map->arena;
map->numSeg = 1;
mapAll(map);
}
// extend arena into new segment
// return FALSE if out of memor from acceptance of all parties
bool newSeg(DbMap *map, uint32_t minSize) {
uint64_t size = map->arena->segs[map->arena->currSeg].size;
uint64_t off = map->arena->segs[map->arena->currSeg].off;
uint32_t nextSeg = map->arena->currSeg + 1;
uint64_t nextSize;
nextSize = size * 2; // double current size
off += size;
while (nextSize < minSize)
if (nextSize < MAX_segsize)
nextSize += nextSize;
else
fprintf(stderr, "newSeg segment overrun: %d\n", minSize), exit(1);
if (nextSize > MAX_segsize)
nextSize = MAX_segsize;
#ifdef _WIN32
assert(__popcnt64(nextSize) == 1);
#else
assert(__builtin_popcountll(nextSize) == 1);
#endif
map->arena->segs[nextSeg].off = off;
map->arena->segs[nextSeg].size = nextSize;
map->arena->segs[nextSeg].nextObject.segment = nextSeg;
map->arena->segs[nextSeg].nextId.seg = nextSeg;
// extend the disk file, windows does this automatically
#ifndef _WIN32
if (map->hndl != -1)
if (ftruncate(map->hndl, nextSize + off)) {
fprintf (stderr, "Unable to extend file %s to %" PRIu64 ", error = %d\n", map->arenaPath, nextSize + off, errno);
return false;
}
#endif
if (!mapSeg(map, nextSeg))
return false;
map->arena->currSeg = nextSeg;
map->numSeg = nextSeg + 1;
return true;
}
// allocate an object from frame list
// return 0 if out of memory.
uint64_t allocObj(DbMap* map, DbAddr *free, DbAddr *wait, int type, uint32_t size, bool zeroit ) {
uint32_t bits, amt;
DbAddr slot;
size += 15;
size &= -16;
if (!size)
size = 16;
if (type < 0) {
#ifdef _WIN32
_BitScanReverse((unsigned long *)&bits, size - 1);
bits++;
#else
bits = 32 - (__builtin_clz (size - 1));
#endif
amt = size;
type = bits * 2;
size = 1 << bits;
// implement half-bit sizing
if (bits > 4 && amt <= 3 * size / 4)
size -= size / 4;
else
type++;
free += type;
if (wait)
wait += type;
} else
amt = size;
lockLatch(free->latch);
while (!(slot.bits = getNodeFromFrame(map, free) & ADDR_BITS)) {
if (!getNodeWait(map, free, wait))
if (!initObjFrame(map, free, type, size)) {
unlockLatch(free->latch);
return 0;
}
}
unlockLatch(free->latch);
if (zeroit)
memset (getObj(map, slot), 0, amt);
*slot.latch = type << BYTE_SHIFT;
return slot.bits;
}
void freeBlk(DbMap *map, DbAddr addr) {
addSlotToFrame(map, &map->arena->freeBlk[addr.type], NULL, addr.bits);
}
void freeId(DbMap *map, ObjId objId) {
addSlotToFrame(map, &map->arena->freeBlk[ObjIdType], NULL, objId.bits);
}
uint64_t allocBlk(DbMap *map, uint32_t size, bool zeroit) {
return allocObj(map, map->arena->freeBlk, NULL, -1, size, zeroit);
}
void mapAll (DbMap *map) {
lockLatch(map->mapMutex);
while (map->numSeg <= map->arena->currSeg)
if (mapSeg (map, map->numSeg))
map->numSeg++;
else
fprintf(stderr, "Unable to map segment %d on map %s\n", map->numSeg, map->arenaPath), exit(1);
unlockLatch(map->mapMutex);
}
void* getObj(DbMap *map, DbAddr slot) {
if (!slot.addr) {
fprintf (stderr, "Invalid zero DbAddr: %s\n", map->arenaPath);
exit(1);
}
// catch up segment mappings
if (slot.segment >= map->numSeg)
mapAll(map);
return map->base[slot.segment] + slot.offset * 16ULL;
}
// allocate raw space in the current segment
// or return 0 if out of memory.
uint64_t allocMap(DbMap *map, uint32_t size) {
uint64_t max, addr, off;
lockLatch(map->arena->mutex);
max = map->arena->segs[map->arena->currSeg].size
- map->arena->segs[map->arena->objSeg].nextId.idx * map->objSize;
// round request up to cache line size
size += 63;
size &= -64;
#ifdef DEBUG
atomicAdd64 (totalMemoryReq, size);
#endif
// see if existing segment has space
// otherwise allocate a new segment.
off = map->arena->segs[map->arena->currSeg].nextObject.offset;
if (off * 16ULL + size > max) {
if (!newSeg(map, size)) {
unlockLatch (map->arena->mutex);
return 0;
}
}
addr = map->arena->segs[map->arena->currSeg].nextObject.bits;
map->arena->segs[map->arena->currSeg].nextObject.offset += size >> 4;
unlockLatch(map->arena->mutex);
return addr;
}
bool mapSeg (DbMap *map, uint32_t currSeg) {
uint64_t size = map->arena->segs[currSeg].size;
uint64_t off = map->arena->segs[currSeg].off;
assert(size > 0);
if ((map->base[currSeg] = mapMemory (map, off, size, currSeg)))
return true;
return false;
}
// return pointer to Obj slot
void *fetchIdSlot (DbMap *map, ObjId objId) {
if (!objId.idx) {
fprintf (stderr, "Invalid zero document index: %s\n", map->arenaPath);
exit(1);
}
if (objId.seg >= map->numSeg)
mapAll(map);
return map->base[objId.seg] + map->arena->segs[objId.seg].size - objId.idx * map->objSize;
}
//
// allocate next available object id
//
uint64_t allocObjId(DbMap *map, DbAddr *free, DbAddr *wait) {
ObjId objId;
lockLatch(free->latch);
// see if there is a free object in the free queue
// otherwise create a new frame of new objects
while (!(objId.bits = getNodeFromFrame(map, free) & ADDR_BITS)) {
if (!getNodeWait(map, free, wait))
if (!initObjIdFrame(map, free)) {
unlockLatch(free->latch);
return 0;
}
}
unlockLatch(free->latch);
return objId.bits;
}
| 22.246862 | 115 | 0.673782 |
a12f2e4b93a9cd815a4d67083ff9e34c7046ac97 | 1,273 | h | C | System/Library/Frameworks/Foundation.framework/_NSJSONWriter.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 5 | 2021-04-29T04:31:43.000Z | 2021-08-19T18:59:58.000Z | System/Library/Frameworks/Foundation.framework/_NSJSONWriter.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | null | null | null | System/Library/Frameworks/Foundation.framework/_NSJSONWriter.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 1 | 2022-03-19T11:16:23.000Z | 2022-03-19T11:16:23.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 28, 2021 at 9:01:35 PM Mountain Standard Time
* Operating System: Version 14.5 (Build 18L204)
* Image Source: /System/Library/Frameworks/Foundation.framework/Foundation
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <Foundation/Foundation-Structs.h>
@class NSOutputStream, NSError;
@interface _NSJSONWriter : NSObject {
NSOutputStream* outputStream;
int kind;
char* dataBuffer;
unsigned long long dataBufferLen;
unsigned long long dataLen;
BOOL freeDataBuffer;
char* tempBuffer;
unsigned long long tempBufferLen;
long long totalDataWritten;
NSError* _failure;
}
@property (retain) NSError * failure; //@synthesize failure=_failure - In the implementation block
-(id)init;
-(void)dealloc;
-(id)dataWithRootObject:(id)arg1 options:(unsigned long long)arg2 ;
-(long long)writeRootObject:(id)arg1 toStream:(id)arg2 options:(unsigned long long)arg3 ;
-(BOOL)appendString:(id)arg1 range:(NSRange)arg2 ;
-(NSError *)failure;
-(void)setFailure:(NSError *)arg1 ;
@end
| 33.5 | 130 | 0.674784 |
a248538c2fcb449fb45dfdb0e017109521ba5717 | 1,827 | h | C | System/Library/PrivateFrameworks/ITMLKit.framework/IKJSTimerContext.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | 2 | 2021-04-15T10:50:21.000Z | 2021-08-19T19:00:09.000Z | System/Library/PrivateFrameworks/ITMLKit.framework/IKJSTimerContext.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/ITMLKit.framework/IKJSTimerContext.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 14, 2021 at 2:25:34 PM Mountain Standard Time
* Operating System: Version 14.4 (Build 18K802)
* Image Source: /System/Library/PrivateFrameworks/ITMLKit.framework/ITMLKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
@class NSTimer, JSManagedValue, IKJSManagedArray;
@interface IKJSTimerContext : NSObject {
BOOL _isRepeating;
NSTimer* _timer;
id _ownerObject;
JSManagedValue* _managedCallback;
IKJSManagedArray* _managedArgs;
}
@property (nonatomic,retain) NSTimer * timer; //@synthesize timer=_timer - In the implementation block
@property (nonatomic,retain,readonly) id ownerObject; //@synthesize ownerObject=_ownerObject - In the implementation block
@property (nonatomic,retain,readonly) JSManagedValue * managedCallback; //@synthesize managedCallback=_managedCallback - In the implementation block
@property (nonatomic,retain,readonly) IKJSManagedArray * managedArgs; //@synthesize managedArgs=_managedArgs - In the implementation block
@property (nonatomic,readonly) BOOL isRepeating; //@synthesize isRepeating=_isRepeating - In the implementation block
-(id)description;
-(void)dealloc;
-(void)setTimer:(NSTimer *)arg1 ;
-(NSTimer *)timer;
-(BOOL)isRepeating;
-(id)ownerObject;
-(void)removeManagedReferences;
-(id)initWithCallback:(id)arg1 callbackArgs:(id)arg2 repeating:(BOOL)arg3 ownerObject:(id)arg4 timer:(id)arg5 ;
-(JSManagedValue *)managedCallback;
-(IKJSManagedArray *)managedArgs;
@end
| 46.846154 | 161 | 0.67214 |
c80b6c18a5804e4660609aee2b819637fe682e68 | 13,845 | c | C | core/src/tbox/src/tbox/coroutine/stackless/scheduler.c | 0x17de/xmake | f4781b3cbc4d8e61eddb888ea4e7d258adc70c5b | [
"Apache-2.0"
] | 1 | 2021-03-23T19:40:36.000Z | 2021-03-23T19:40:36.000Z | src/tbox/coroutine/stackless/scheduler.c | dreamsxin/tbox | 34e35eef30ec53722e25cc461c7a8b6b19e21636 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/tbox/coroutine/stackless/scheduler.c | dreamsxin/tbox | 34e35eef30ec53722e25cc461c7a8b6b19e21636 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | /*!The Treasure Box Library
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2009 - 2019, TBOOX Open Source Group.
*
* @author ruki
* @file scheduler.h
* @ingroup scheduler
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "scheduler"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "scheduler.h"
#include "../impl/impl.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* macros
*/
// the dead cache maximum count
#if defined(TB_CONFIG_MICRO_ENABLE)
# define TB_SCHEDULER_DEAD_CACHE_MAXN (8)
#elif defined(__tb_small__)
# define TB_SCHEDULER_DEAD_CACHE_MAXN (64)
#else
# define TB_SCHEDULER_DEAD_CACHE_MAXN (256)
#endif
/* //////////////////////////////////////////////////////////////////////////////////////
* globals
*/
#if !defined(TB_CONFIG_MICRO_ENABLE) && !defined(__tb_thread_local__)
// the self scheduler local
static tb_thread_local_t g_scheduler_self = TB_THREAD_LOCAL_INIT;
#endif
// the global scheduler for the exclusive mode
#ifdef __tb_thread_local__
static __tb_thread_local__ tb_lo_scheduler_t* g_scheduler_self_ex = tb_null;
#else
static tb_lo_scheduler_t* g_scheduler_self_ex = tb_null;
#endif
/* //////////////////////////////////////////////////////////////////////////////////////
* private implementation
*/
static tb_void_t tb_lo_scheduler_free(tb_list_entry_head_ref_t coroutines)
{
// check
tb_assert(coroutines);
// free all coroutines
while (tb_list_entry_size(coroutines))
{
// get the next entry from head
tb_list_entry_ref_t entry = tb_list_entry_head(coroutines);
tb_assert(entry);
// remove it from the ready coroutines
tb_list_entry_remove_head(coroutines);
// exit this coroutine
tb_lo_coroutine_exit((tb_lo_coroutine_t*)tb_list_entry(coroutines, entry));
}
}
static tb_void_t tb_lo_scheduler_make_ready(tb_lo_scheduler_t* scheduler, tb_lo_coroutine_t* coroutine)
{
// check
tb_assert(scheduler && coroutine);
// mark ready state
tb_lo_core_state_set(coroutine, TB_STATE_READY);
// insert this coroutine to ready coroutines
if (scheduler->running)
{
// .. -> coroutine(inserted) -> running -> ..
tb_list_entry_insert_prev(&scheduler->coroutines_ready, &scheduler->running->entry, &coroutine->entry);
}
else
{
// .. last -> coroutine(inserted)
tb_list_entry_insert_tail(&scheduler->coroutines_ready, &coroutine->entry);
}
}
static tb_void_t tb_lo_scheduler_make_dead(tb_lo_scheduler_t* scheduler, tb_lo_coroutine_t* coroutine)
{
// check
tb_assert(scheduler && coroutine);
tb_assert(tb_lo_core_state(coroutine) == TB_STATE_END);
// trace
tb_trace_d("finish coroutine(%p)", coroutine);
// free the user private data first
if (coroutine->free) coroutine->free(coroutine->priv);
// remove this coroutine from the ready coroutines
tb_list_entry_remove(&scheduler->coroutines_ready, &coroutine->entry);
// append this coroutine to dead coroutines
tb_list_entry_insert_tail(&scheduler->coroutines_dead, &coroutine->entry);
}
static tb_void_t tb_lo_scheduler_make_suspend(tb_lo_scheduler_t* scheduler, tb_lo_coroutine_t* coroutine)
{
// check
tb_assert(scheduler && coroutine);
tb_assert(tb_lo_core_state(coroutine) == TB_STATE_SUSPEND);
// trace
tb_trace_d("suspend coroutine(%p)", coroutine);
// remove this coroutine from the ready coroutines
tb_list_entry_remove(&scheduler->coroutines_ready, &coroutine->entry);
// append this coroutine to suspend coroutines
tb_list_entry_insert_tail(&scheduler->coroutines_suspend, &coroutine->entry);
}
static __tb_inline__ tb_lo_coroutine_t* tb_lo_scheduler_next_ready(tb_lo_scheduler_t* scheduler)
{
// check
tb_assert(scheduler && tb_list_entry_size(&scheduler->coroutines_ready));
// get the next entry
tb_list_entry_ref_t entry_next = scheduler->running? tb_list_entry_next(&scheduler->running->entry) : tb_list_entry_head(&scheduler->coroutines_ready);
tb_assert(entry_next);
// is list header? skip it and get the first entry
if (entry_next == (tb_list_entry_ref_t)&scheduler->coroutines_ready)
entry_next = tb_list_entry_next(entry_next);
// get the next ready coroutine
return (tb_lo_coroutine_t*)tb_list_entry(&scheduler->coroutines_ready, entry_next);
}
static tb_void_t tb_lo_scheduler_switch(tb_lo_scheduler_t* scheduler, tb_lo_coroutine_t* coroutine)
{
// check
tb_assert(scheduler && coroutine && coroutine->func);
tb_assert(tb_lo_core_state(coroutine) == TB_STATE_READY);
// trace
tb_trace_d("switch to coroutine(%p) from coroutine(%p)", coroutine, scheduler->running);
// mark the given coroutine as running
scheduler->running = coroutine;
// call the coroutine function
coroutine->func((tb_lo_coroutine_ref_t)coroutine, coroutine->priv);
}
tb_bool_t tb_lo_scheduler_start(tb_lo_scheduler_t* scheduler, tb_lo_coroutine_func_t func, tb_cpointer_t priv, tb_lo_coroutine_free_t free)
{
// check
tb_assert(func);
// done
tb_bool_t ok = tb_false;
tb_lo_coroutine_t* coroutine = tb_null;
do
{
// trace
tb_trace_d("start ..");
// get the current scheduler
if (!scheduler) scheduler = (tb_lo_scheduler_t*)tb_lo_scheduler_self_();
tb_assert_and_check_break(scheduler);
// have been stopped? do not continue to start new coroutines
tb_check_break(!scheduler->stopped);
// reuses dead coroutines in init function
if (tb_list_entry_size(&scheduler->coroutines_dead))
{
// get the next entry from head
tb_list_entry_ref_t entry = tb_list_entry_head(&scheduler->coroutines_dead);
tb_assert_and_check_break(entry);
// remove it from the ready coroutines
tb_list_entry_remove_head(&scheduler->coroutines_dead);
// get the dead coroutine
coroutine = (tb_lo_coroutine_t*)tb_list_entry(&scheduler->coroutines_dead, entry);
// reinit this coroutine
tb_lo_coroutine_reinit(coroutine, func, priv, free);
}
// init coroutine
if (!coroutine) coroutine = tb_lo_coroutine_init((tb_lo_scheduler_ref_t)scheduler, func, priv, free);
tb_assert_and_check_break(coroutine);
// ready coroutine
tb_lo_scheduler_make_ready(scheduler, coroutine);
// the dead coroutines is too much? free some coroutines
while (tb_list_entry_size(&scheduler->coroutines_dead) > TB_SCHEDULER_DEAD_CACHE_MAXN)
{
// get the next entry from head
tb_list_entry_ref_t entry = tb_list_entry_head(&scheduler->coroutines_dead);
tb_assert(entry);
// remove it from the ready coroutines
tb_list_entry_remove_head(&scheduler->coroutines_dead);
// exit this coroutine
tb_lo_coroutine_exit((tb_lo_coroutine_t*)tb_list_entry(&scheduler->coroutines_dead, entry));
}
// ok
ok = tb_true;
} while (0);
// trace
tb_trace_d("start %s", ok? "ok" : "no");
// ok?
return ok;
}
tb_void_t tb_lo_scheduler_resume(tb_lo_scheduler_t* scheduler, tb_lo_coroutine_t* coroutine)
{
// check
tb_assert(scheduler && coroutine);
tb_assert(tb_lo_core_state(coroutine) == TB_STATE_SUSPEND);
// remove it from the suspend coroutines
tb_list_entry_remove(&scheduler->coroutines_suspend, &coroutine->entry);
// make it as ready
tb_lo_scheduler_make_ready(scheduler, coroutine);
}
tb_lo_scheduler_ref_t tb_lo_scheduler_self_()
{
// get self scheduler on the current thread
#if defined(TB_CONFIG_MICRO_ENABLE) || defined(__tb_thread_local__)
return (tb_lo_scheduler_ref_t)g_scheduler_self_ex;
#else
return (tb_lo_scheduler_ref_t)(g_scheduler_self_ex? g_scheduler_self_ex : tb_thread_local_get(&g_scheduler_self));
#endif
}
/* //////////////////////////////////////////////////////////////////////////////////////
* public implementation
*/
tb_lo_scheduler_ref_t tb_lo_scheduler_init()
{
// done
tb_bool_t ok = tb_false;
tb_lo_scheduler_t* scheduler = tb_null;
do
{
// make scheduler
scheduler = tb_malloc0_type(tb_lo_scheduler_t);
tb_assert_and_check_break(scheduler);
// init dead coroutines
tb_list_entry_init(&scheduler->coroutines_dead, tb_lo_coroutine_t, entry, tb_null);
// init ready coroutines
tb_list_entry_init(&scheduler->coroutines_ready, tb_lo_coroutine_t, entry, tb_null);
// init suspend coroutines
tb_list_entry_init(&scheduler->coroutines_suspend, tb_lo_coroutine_t, entry, tb_null);
// ok
ok = tb_true;
} while (0);
// failed?
if (!ok)
{
// exit it
if (scheduler) tb_lo_scheduler_exit((tb_lo_scheduler_ref_t)scheduler);
scheduler = tb_null;
}
// ok?
return (tb_lo_scheduler_ref_t)scheduler;
}
tb_void_t tb_lo_scheduler_exit(tb_lo_scheduler_ref_t self)
{
// check
tb_lo_scheduler_t* scheduler = (tb_lo_scheduler_t*)self;
tb_assert_and_check_return(scheduler);
// must be stopped
tb_assert(scheduler->stopped);
// exit io scheduler first
if (scheduler->scheduler_io) tb_lo_scheduler_io_exit(scheduler->scheduler_io);
scheduler->scheduler_io = tb_null;
// check coroutines
tb_assert(!tb_list_entry_size(&scheduler->coroutines_ready));
tb_assert(!tb_list_entry_size(&scheduler->coroutines_suspend));
// free all dead coroutines
tb_lo_scheduler_free(&scheduler->coroutines_dead);
// free all ready coroutines
tb_lo_scheduler_free(&scheduler->coroutines_ready);
// free all suspend coroutines
tb_lo_scheduler_free(&scheduler->coroutines_suspend);
// exit dead coroutines
tb_list_entry_exit(&scheduler->coroutines_dead);
// exit ready coroutines
tb_list_entry_exit(&scheduler->coroutines_ready);
// exit suspend coroutines
tb_list_entry_exit(&scheduler->coroutines_suspend);
// exit the scheduler
tb_free(scheduler);
}
tb_void_t tb_lo_scheduler_kill(tb_lo_scheduler_ref_t self)
{
// check
tb_lo_scheduler_t* scheduler = (tb_lo_scheduler_t*)self;
tb_assert_and_check_return(scheduler);
// stop it
scheduler->stopped = tb_true;
}
tb_void_t tb_lo_scheduler_loop(tb_lo_scheduler_ref_t self, tb_bool_t exclusive)
{
// check
tb_lo_scheduler_t* scheduler = (tb_lo_scheduler_t*)self;
tb_assert_and_check_return(scheduler);
#ifdef __tb_thread_local__
g_scheduler_self_ex = scheduler;
#else
// is exclusive mode?
if (exclusive) g_scheduler_self_ex = scheduler;
# ifndef TB_CONFIG_MICRO_ENABLE
else
{
// init self scheduler local
if (!tb_thread_local_init(&g_scheduler_self, tb_null)) return ;
// update and overide the current scheduler
tb_thread_local_set(&g_scheduler_self, self);
}
# else
else
{
// trace
tb_trace_e("non-exclusive is not suspported in micro mode!");
}
# endif
#endif
// schedule all ready coroutines
while (tb_list_entry_size(&scheduler->coroutines_ready) && !scheduler->stopped)
{
// trace
tb_trace_d("[loop]: ready %lu", tb_list_entry_size(&scheduler->coroutines_ready));
// get the next ready coroutine
tb_lo_coroutine_t* coroutine_next = tb_lo_scheduler_next_ready(scheduler);
tb_assert(coroutine_next);
// process the running coroutine
if (scheduler->running)
{
// get the state of running coroutine
tb_size_t state = tb_lo_core_state(scheduler->running);
// mark this coroutine as dead if the running coroutine(root level) have been finished
if (state == TB_STATE_END)
tb_lo_scheduler_make_dead(scheduler, scheduler->running);
// suspend the running coroutine
else if (state == TB_STATE_SUSPEND)
tb_lo_scheduler_make_suspend(scheduler, scheduler->running);
}
// switch to it if the next coroutine (may be running coroutine) is ready
if (tb_lo_core_state(coroutine_next) == TB_STATE_READY)
tb_lo_scheduler_switch(scheduler, coroutine_next);
}
// stop it
scheduler->stopped = tb_true;
#ifdef __tb_thread_local__
g_scheduler_self_ex = tb_null;
#else
// is exclusive mode?
if (exclusive) g_scheduler_self_ex = tb_null;
# ifndef TB_CONFIG_MICRO_ENABLE
else
{
// clear the current scheduler
tb_thread_local_set(&g_scheduler_self, tb_null);
}
# endif
#endif
}
| 32.423888 | 155 | 0.669917 |
bd55d98b7c1d6b70eab36f5796f64737a2c1f4e1 | 1,296 | h | C | llvm-7.0.0.src/include/llvm/Support/raw_sha1_ostream.h | sillywalk/grazz | a0adb1a90d41ff9006d8c1476546263f728b3c83 | [
"Apache-2.0"
] | 171 | 2018-09-17T13:15:12.000Z | 2022-03-18T03:47:04.000Z | llvm-7.0.0.src/include/llvm/Support/raw_sha1_ostream.h | sillywalk/grazz | a0adb1a90d41ff9006d8c1476546263f728b3c83 | [
"Apache-2.0"
] | 51 | 2019-10-23T11:55:08.000Z | 2021-12-21T06:32:11.000Z | llvm-7.0.0.src/include/llvm/Support/raw_sha1_ostream.h | sillywalk/grazz | a0adb1a90d41ff9006d8c1476546263f728b3c83 | [
"Apache-2.0"
] | 55 | 2018-02-01T07:11:49.000Z | 2022-03-04T01:20:23.000Z | //==- raw_sha1_ostream.h - raw_ostream that compute SHA1 --*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the raw_sha1_ostream class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SUPPORT_RAW_SHA1_OSTREAM_H
#define LLVM_SUPPORT_RAW_SHA1_OSTREAM_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/SHA1.h"
#include "llvm/Support/raw_ostream.h"
namespace llvm {
/// A raw_ostream that hash the content using the sha1 algorithm.
class raw_sha1_ostream : public raw_ostream {
SHA1 State;
/// See raw_ostream::write_impl.
void write_impl(const char *Ptr, size_t Size) override {
State.update(ArrayRef<uint8_t>((const uint8_t *)Ptr, Size));
}
public:
/// Return the current SHA1 hash for the content of the stream
StringRef sha1() {
flush();
return State.result();
}
/// Reset the internal state to start over from scratch.
void resetHash() { State.init(); }
uint64_t current_pos() const override { return 0; }
};
} // end llvm namespace
#endif
| 27 | 80 | 0.608796 |
08bcc1f96cd49c25be43a361c4a5777cf3f38860 | 633 | h | C | RXVerifyExample/RXVerifyExample/Verify/NUI/MultThread/RXMultThreadView.h | Explorer1092/RXVerifyExample | 344f954c155457c34d52db6831f928b5ac400bbc | [
"MIT"
] | null | null | null | RXVerifyExample/RXVerifyExample/Verify/NUI/MultThread/RXMultThreadView.h | Explorer1092/RXVerifyExample | 344f954c155457c34d52db6831f928b5ac400bbc | [
"MIT"
] | null | null | null | RXVerifyExample/RXVerifyExample/Verify/NUI/MultThread/RXMultThreadView.h | Explorer1092/RXVerifyExample | 344f954c155457c34d52db6831f928b5ac400bbc | [
"MIT"
] | null | null | null | //
// RXMultThreadView.h
// RXVerifyExample
//
// Created by Rush.D.Xzj on 2020/9/4.
// Copyright © 2020 Rush.D.Xzj. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class RXMultThreadView;
@protocol RXMultThreadViewLoadDelegate <NSObject>
- (void)multThreadViewWillRender:(RXMultThreadView *)multThreadView;
- (void)multThreadViewDidRender:(RXMultThreadView *)multThreadView;
@end
@interface RXMultThreadView : UIView
- (void)render_really;
@property (nonatomic, assign) NSInteger renderIndex;
@property (nonatomic, weak) id<RXMultThreadViewLoadDelegate> loadDelegate;
@end
NS_ASSUME_NONNULL_END
| 21.827586 | 74 | 0.78357 |
d91794429517e2ebd17916a026c3f3642e919dba | 795 | h | C | Source/FSDEngine/Public/CarveSplineSegment.h | trumank/DRG-Mods | 2febc879f2ffe83498ac913c114d0e933427e93e | [
"MIT"
] | null | null | null | Source/FSDEngine/Public/CarveSplineSegment.h | trumank/DRG-Mods | 2febc879f2ffe83498ac913c114d0e933427e93e | [
"MIT"
] | null | null | null | Source/FSDEngine/Public/CarveSplineSegment.h | trumank/DRG-Mods | 2febc879f2ffe83498ac913c114d0e933427e93e | [
"MIT"
] | null | null | null | #pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "CarveSplineSegment.generated.h"
USTRUCT(BlueprintType)
struct FCarveSplineSegment {
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FVector SplineStart;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FVector SplineStartTangent;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FVector SplineEnd;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FVector SplineEndTangent;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float Radius;
FSDENGINE_API FCarveSplineSegment();
};
| 28.392857 | 79 | 0.763522 |
83f18bc8a3d43eceb115b2714226afde9cf0151a | 4,970 | h | C | modules/jni/src/main/native/utilities.h | GratefulTony/tensorflow_scala | 54cb42f9fcada562de9847aa09d9d11a93400d9a | [
"Apache-2.0"
] | 936 | 2017-05-22T03:13:25.000Z | 2022-03-29T09:05:45.000Z | modules/jni/src/main/native/utilities.h | GratefulTony/tensorflow_scala | 54cb42f9fcada562de9847aa09d9d11a93400d9a | [
"Apache-2.0"
] | 178 | 2017-05-30T22:06:13.000Z | 2022-03-02T19:45:57.000Z | modules/jni/src/main/native/utilities.h | GratefulTony/tensorflow_scala | 54cb42f9fcada562de9847aa09d9d11a93400d9a | [
"Apache-2.0"
] | 116 | 2017-06-05T11:57:03.000Z | 2022-02-27T16:28:33.000Z | /* Copyright 2017-19, Emmanouil Antonios Platanios. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
#ifndef TENSORFLOW_JNI_UTILITIES_H_
#define TENSORFLOW_JNI_UTILITIES_H_
#include <sstream>
#include "exception.h"
namespace {
template <typename T>
std::string pointerToString(
T pointer,
typename std::enable_if<std::is_pointer<T>::value>::type* = nullptr
) {
std::stringstream ss;
ss << pointer;
return ss.str();
}
template <typename T>
T pointerFromString(
const std::string &text,
typename std::enable_if<std::is_pointer<T>::value>::type* = nullptr
) {
std::stringstream ss(text);
void* pointer;
ss >> pointer;
return (T) pointer;
}
template <class T>
inline T* require_handle(
JNIEnv* env,
jlong handle,
const char* object_name
) {
static_assert(sizeof(jlong) >= sizeof(T*), "Cannot package C object pointers as a Java long");
if (handle == 0) {
std::stringstream msg;
msg << "Object '" << object_name << "' has been disposed already.";
throw_exception(env, tf_invalid_argument_exception, msg.str().c_str());
return nullptr;
}
return reinterpret_cast<T*>(handle);
}
template<class T>
inline void require_handles(
JNIEnv* env,
jlongArray src_array,
T** dst_array,
jint src_array_length
) {
jint len = env->GetArrayLength(src_array);
if (len != src_array_length) {
std::stringstream msg;
msg << "Expected " << src_array_length << " handles, but got " << len << " handles, instead.";
throw_exception(env, tf_invalid_argument_exception, msg.str().c_str());
return;
}
jlong* src_start = env->GetLongArrayElements(src_array, nullptr);
jlong* src = src_start;
for (int i = 0; i < src_array_length; ++i, ++src, ++dst_array) {
if (*src == 0) {
std::stringstream msg;
msg << "Invalid handle (# " << i << " of " << src_array_length << ").";
throw_exception(env, tf_invalid_argument_exception, msg.str().c_str());
return;
}
*dst_array = reinterpret_cast<T*>(*src);
}
env->ReleaseLongArrayElements(src_array, src_start, JNI_ABORT);
}
inline void require_outputs(
JNIEnv* env,
jlongArray src_ops,
jintArray src_indices,
TF_Output* dst_array,
jint src_ops_length
) {
jint len = env->GetArrayLength(src_ops);
if (len != src_ops_length) {
std::stringstream msg;
msg << "Expected " << src_ops_length << " ops, but got " << len << ", instead.";
throw_exception(env, tf_invalid_argument_exception, msg.str().c_str());
return;
}
len = env->GetArrayLength(src_indices);
if (len != src_ops_length) {
std::stringstream msg;
msg << "Expected " << src_ops_length << " op output indices, but got " << len << ", instead.";
throw_exception(env, tf_invalid_argument_exception, msg.str().c_str());
return;
}
jlong* op_handles = env->GetLongArrayElements(src_ops, nullptr);
jint* indices = env->GetIntArrayElements(src_indices, nullptr);
for (int i = 0; i < src_ops_length; ++i) {
if (op_handles[i] == 0) {
std::stringstream msg;
msg << "Invalid op handle (# " << i << " of " << src_ops_length << ").";
throw_exception(env, tf_invalid_argument_exception, msg.str().c_str());
return;
}
dst_array[i] = TF_Output{reinterpret_cast<TF_Operation*>(op_handles[i]), static_cast<int>(indices[i])};
}
env->ReleaseIntArrayElements(src_indices, indices, JNI_ABORT);
env->ReleaseLongArrayElements(src_ops, op_handles, JNI_ABORT);
}
} // namespace
#define REQUIRE_HANDLE(name, type, variable_name, null_return_value) \
type* name = require_handle<type>(env, variable_name, #variable_name); \
if (name == nullptr) return null_return_value;
#define REQUIRE_HANDLES(src_array, dst_array, src_array_length, null_return_value) \
require_handles(env, src_array, dst_array, src_array_length); \
if (env->ExceptionCheck()) return null_return_value;
#define REQUIRE_OUTPUTS(src_ops, src_indices, dst_array, src_ops_length, null_return_value) \
require_outputs(env, src_ops, src_indices, dst_array, src_ops_length); \
if (env->ExceptionCheck()) return null_return_value;
#endif // TENSORFLOW_JNI_UTILITIES_H_
| 35.755396 | 109 | 0.652515 |
2fd913bf81a3258528220625995695772070dd46 | 3,386 | h | C | engine/src/execution_graph/logic_controllers/LogicPrimitives.h | msadang/blazingsql | 5fe3e418dbee4a3961998b0e25ec81100a1a1490 | [
"Apache-2.0"
] | null | null | null | engine/src/execution_graph/logic_controllers/LogicPrimitives.h | msadang/blazingsql | 5fe3e418dbee4a3961998b0e25ec81100a1a1490 | [
"Apache-2.0"
] | null | null | null | engine/src/execution_graph/logic_controllers/LogicPrimitives.h | msadang/blazingsql | 5fe3e418dbee4a3961998b0e25ec81100a1a1490 | [
"Apache-2.0"
] | null | null | null |
#pragma once
#include "cudf/column/column_view.hpp"
#include "cudf/table/table.hpp"
#include "cudf/table/table_view.hpp"
#include <memory>
#include <string>
#include <vector>
#include <string>
#include <bmr/BlazingMemoryResource.h>
#include "execution_graph/logic_controllers/BlazingColumn.h"
#include "BlazingHostTable.h"
typedef cudf::table CudfTable;
typedef cudf::table_view CudfTableView;
typedef cudf::column CudfColumn;
typedef cudf::column_view CudfColumnView;
namespace ral {
namespace frame {
class BlazingTable;
class BlazingTableView;
class BlazingHostTable;
class BlazingTable {
public:
BlazingTable(std::vector<std::unique_ptr<BlazingColumn>> columns, const std::vector<std::string> & columnNames);
BlazingTable(std::unique_ptr<CudfTable> table, const std::vector<std::string> & columnNames);
BlazingTable(const CudfTableView & table, const std::vector<std::string> & columnNames);
BlazingTable(BlazingTable &&) = default;
BlazingTable & operator=(BlazingTable const &) = delete;
BlazingTable & operator=(BlazingTable &&) = delete;
CudfTableView view() const;
cudf::size_type num_columns() const { return columns.size(); }
cudf::size_type num_rows() const { return columns.size() == 0 ? 0 : (columns[0] == nullptr ? 0 : columns[0]->view().size()); }
std::vector<std::string> names() const;
std::vector<cudf::data_type> get_schema() const;
// set columnNames
void setNames(const std::vector<std::string> & names) { this->columnNames = names; }
BlazingTableView toBlazingTableView() const;
operator bool() const { return columns.size() != 0; }
std::unique_ptr<CudfTable> releaseCudfTable();
std::vector<std::unique_ptr<BlazingColumn>> releaseBlazingColumns();
unsigned long long sizeInBytes();
void ensureOwnership();
private:
std::vector<std::string> columnNames;
std::vector<std::unique_ptr<BlazingColumn>> columns;
};
class BlazingTableView {
public:
BlazingTableView();
BlazingTableView(CudfTableView table, std::vector<std::string> columnNames);
BlazingTableView(BlazingTableView const &) = default;
BlazingTableView(BlazingTableView &&) = default;
BlazingTableView & operator=(BlazingTableView const &) = default;
BlazingTableView & operator=(BlazingTableView &&) = default;
CudfTableView view() const;
cudf::column_view const & column(cudf::size_type column_index) const { return table.column(column_index); }
std::vector<std::unique_ptr<BlazingColumn>> toBlazingColumns() const;
std::vector<cudf::data_type> get_schema() const;
std::vector<std::string> names() const;
void setNames(const std::vector<std::string> & names) { this->columnNames = names; }
cudf::size_type num_columns() const { return table.num_columns(); }
cudf::size_type num_rows() const { return table.num_rows(); }
unsigned long long sizeInBytes();
std::unique_ptr<BlazingTable> clone() const;
private:
std::vector<std::string> columnNames;
CudfTableView table;
};
std::unique_ptr<ral::frame::BlazingTable> createEmptyBlazingTable(std::vector<cudf::data_type> column_types,
std::vector<std::string> column_names);
std::unique_ptr<ral::frame::BlazingTable> createEmptyBlazingTable(std::vector<cudf::type_id> column_types,
std::vector<std::string> column_names);
std::vector<std::unique_ptr<BlazingColumn>> cudfTableViewToBlazingColumns(const CudfTableView & table);
} // namespace frame
} // namespace ral
| 32.873786 | 127 | 0.750738 |
2ff8113061c1d81537bfb26a61c126c8ed7139aa | 1,610 | h | C | src/include/gpopt/utils/CMemoryPoolPalloc.h | Tylarb/gpdb | 15e1341cfbac7f70d2086a9a1d46149a82765b5e | [
"PostgreSQL",
"Apache-2.0"
] | 202 | 2021-10-13T09:21:34.000Z | 2022-03-31T09:52:47.000Z | src/include/gpopt/utils/CMemoryPoolPalloc.h | Tylarb/gpdb | 15e1341cfbac7f70d2086a9a1d46149a82765b5e | [
"PostgreSQL",
"Apache-2.0"
] | 9 | 2021-11-01T09:10:56.000Z | 2022-03-28T14:24:23.000Z | src/include/gpopt/utils/CMemoryPoolPalloc.h | Tylarb/gpdb | 15e1341cfbac7f70d2086a9a1d46149a82765b5e | [
"PostgreSQL",
"Apache-2.0"
] | 47 | 2021-10-21T07:15:26.000Z | 2022-03-29T11:37:15.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2019 Pivotal, Inc.
//
// @filename:
// CMemoryPoolPalloc.h
//
// @doc:
// CMemoryPool implementation that uses PostgreSQL memory
// contexts.
//
//---------------------------------------------------------------------------
#ifndef GPDXL_CMemoryPoolPalloc_H
#define GPDXL_CMemoryPoolPalloc_H
#include "gpos/base.h"
#include "gpos/memory/CMemoryPool.h"
namespace gpos
{
// Memory pool that maps to a Postgres MemoryContext.
class CMemoryPoolPalloc : public CMemoryPool
{
private:
MemoryContext m_cxt;
// When destroying arrays, we need to call the destructor of each element
// To do this, we need the size of the allocation, which we then divide by the
// the size of the element to get number of elements to iterate through.
// This struct is only used for array allocations (GPOS_NEW_ARRAY())
struct SArrayAllocHeader
{
ULONG m_user_size;
};
public:
// ctor
CMemoryPoolPalloc();
// allocate memory
void *NewImpl
(
const ULONG bytes,
const CHAR *file,
const ULONG line,
CMemoryPool::EAllocationType eat
);
// free memory
static void DeleteImpl(void *ptr, CMemoryPool::EAllocationType eat);
// prepare the memory pool to be deleted
void TearDown();
// return total allocated size include management overhead
ULLONG TotalAllocatedSize() const;
// get user requested size of allocation
static ULONG UserSizeOfAlloc(const void *ptr);
};
}
#endif // !GPDXL_CMemoryPoolPalloc_H
// EOF
| 23 | 81 | 0.639752 |
6438724602ace5e95ad2ec77df533ad2df87ae9e | 14,047 | h | C | assets/labs/lab4/lab4_skeleton/ar_track_alvar/ar_track_alvar/include/ar_track_alvar/Util.h | tiffanyec/ee106a-fa192 | e14da45a754c46ad5c1efde7e19602e35723c5e3 | [
"MIT"
] | 6 | 2020-01-14T17:56:03.000Z | 2021-08-10T18:57:04.000Z | assets/labs/lab4/lab4_skeleton/ar_track_alvar/ar_track_alvar/include/ar_track_alvar/Util.h | tiffanyec/ee106a-fa192 | e14da45a754c46ad5c1efde7e19602e35723c5e3 | [
"MIT"
] | null | null | null | assets/labs/lab4/lab4_skeleton/ar_track_alvar/ar_track_alvar/include/ar_track_alvar/Util.h | tiffanyec/ee106a-fa192 | e14da45a754c46ad5c1efde7e19602e35723c5e3 | [
"MIT"
] | 3 | 2019-12-21T02:50:39.000Z | 2022-01-04T02:53:07.000Z | /*
* This file is part of ALVAR, A Library for Virtual and Augmented Reality.
*
* Copyright 2007-2012 VTT Technical Research Centre of Finland
*
* Contact: VTT Augmented Reality Team <alvar.info@vtt.fi>
* <http://www.vtt.fi/multimedia/alvar.html>
*
* ALVAR 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 ALVAR; if not, see
* <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>.
*/
#ifndef UTIL_H
#define UTIL_H
/**
* \file Util.h
*
* \brief This file implements generic utility functions and a serialization
* interface.
*/
#include "Alvar.h"
#include "AlvarException.h"
#include <vector>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cxcore.h>
#include <cv.h>
#include <cmath> //for abs
#include <map>
#include <opencv2/calib3d/calib3d_c.h> //Compatibility with OpenCV 3.x
namespace alvar {
const double PI = 3.14159265;
/**
* \brief Returns the sign of a number.
*/
template<class C> inline
int ALVAR_EXPORT Sign(const C& v)
{
return (v<0?-1:1);
}
/**
* \brief Converts an angle from radians to degrees.
*/
template<class C> inline
double ALVAR_EXPORT Rad2Deg(const C& v)
{
return v*(180/PI);
}
/**
* \brief Converts an angle from degrees to radians.
*/
template<class C> inline
double ALVAR_EXPORT Deg2Rad(const C& v)
{
return v*(PI/180);
}
/**
* \brief Simple \e Point class meant to be inherited from OpenCV point-classes. For example: Point<CvPoint2D64f> p
*/
template<class C, class D = int>
struct ALVAR_EXPORT Point : public C
{
/**
* \brief Additional value can be related to the point.
*/
D val;
Point(int vx=0, int vy=0)
{
C::x = vx;
C::y = vy;
}
Point(double vx, double vy)
{
C::x = vx;
C::y = vy;
}
};
/**
* \brief The default integer point type.
*/
typedef ALVAR_EXPORT Point<CvPoint> PointInt;
/**
* \brief The default double point type.
*/
typedef ALVAR_EXPORT Point<CvPoint2D64f> PointDouble;
/** \brief Returns the squared distance of two points.
* \param p1 First point.
* \param p2 Second point.
* \return Squared distance.
*/
template<class PointType>
double PointSquaredDistance(PointType p1, PointType p2) {
return ((p1.x-p2.x)*(p1.x-p2.x)) +
((p1.y-p2.y)*(p1.y-p2.y));
}
//ttesis start
/**
* \brief Computes dot product AB.BC
* \param A,B and C points defining lines (line segments) AB and BC
*/
int ALVAR_EXPORT dot(CvPoint *A, CvPoint *B, CvPoint *C);
/**
* \brief Computes the cross product AB x AC
* \param A,B and C points defining lines (line segments) AB and AC
* \param
*/
int ALVAR_EXPORT cross(CvPoint *A,CvPoint *B, CvPoint *C);
/**
* \brief Compute the distance from A to B
* \param A and B points
*/
double ALVAR_EXPORT distance(CvPoint *A,CvPoint *B);
/**
* \brief Computes the distance from point C to line (segment) AB.
* \param isSegment If isSegment is true, AB is a segment, not a line.
* \param C point
* \param A abd B points defining line (segment) AB
*/
double ALVAR_EXPORT linePointDist(CvPoint *A,CvPoint *B,CvPoint *C, bool isSegment);
/**
* \brief Computes the angle between lines AB and CD
* \param isDirectionDependent If isDirectionDependent = 1, angle depends on the order of the points. Otherwise returns smaller angle.
* \param A start point of first line
* \param B end point of first line
* \param C start point of second line
* \param D end point of second line
*/
double ALVAR_EXPORT angle(CvPoint *A,CvPoint *B, CvPoint *C,CvPoint *D, int isDirectionDependent);
/**
* \brief Calculates minimum distance from Point C to Polygon whose points are in list PointList
* \brief Returns distance
* \param index index of point A in pointlist, where A is the starting point of the closest polygon segment
* \param isClosedPolygon is true if polygon is closed (segment of the first and last point is also checked)
*/
double ALVAR_EXPORT polyLinePointDist(CvPoint *PointList, int nPnts,CvPoint *C, int *index, int isClosedPolygon);
//ttesis end
/**
* \brief Uses OpenCV routine to fit ellipse to a vector of points.
* \param points Vector of points on the ellipse edge.
* \param ellipse_box OpenCV struct for the fitted ellipse.
*/
void ALVAR_EXPORT FitCVEllipse(const std::vector<PointDouble> &points, CvBox2D& ellipse_box);
int ALVAR_EXPORT exp_filt2(std::vector<double> &v,std:: vector<double> &ret, bool clamp);
/**
* \brief Calculates the difference between the consecutive vector elements.
* \param v Source elements.
* \param ret The difference vector. This is cleared and then resized.
* \return The number of elements.
*/
template<class C> inline
int ALVAR_EXPORT diff(const std::vector<C> &v, std::vector<C> &ret)
{
ret.clear();
if (v.size() == 1) {
ret.push_back(0);
} else if (v.size() > 1) {
ret.push_back(v.at(1)-v.at(0));
for(size_t i = 1; i < v.size(); ++i)
{
ret.push_back(v.at(i)-v.at(i-1));
}
}
return int(ret.size());
}
/**
* \brief Finds zero crossings of given vector elements (sequence).
* \param v Sequence of numbers from where the zero crossings are found.
* \param corners Resulting index list of zero crossings.
* \param offs
* \return Number of zero crossings found.
*/
int ALVAR_EXPORT find_zero_crossings(const std::vector<double>& v, std::vector<int> &corners, int offs = 20);
/**
* \brief Output OpenCV matrix for debug purposes.
*/
void ALVAR_EXPORT out_matrix(const CvMat *m, const char *name);
/**
* \brief Limits a number to between two values.
* \param val Input value.
* \param min_val Minimum value for the result.
* \param max_val Maximum value for the result.
* \return Resulting value that is between \e min_val and \e max_val.
*/
double ALVAR_EXPORT Limit(double val, double min_val, double max_val);
/**
* \brief Class for N-dimensional index to be used e.g. with STL maps
*
* The idea is that if you want to sort N-dimensional pointers (e.g.
* when they are stored in STL maps) it is enough to have the 'operator<'
* working, instead of needing to calculate something like i=z*x_res*y_res + y*x_res + x;
*/
struct ALVAR_EXPORT Index {
/** \brief The indices for each dimension are stored in \e val (last being the most significant) */
std::vector<int> val;
/** \brief Constructor for 1D index */
Index(int a);
/** \brief Constructor for 2D index */
Index(int a, int b);
/** \brief Constructor for 3D index */
Index(int a, int b, int c);
/** \brief Operator used for sorting the multidimensional indices (last dimension being the most significant) */
bool operator<(const Index &index) const;
};
/**
* \brief Class for N-dimensional Histograms
*/
class ALVAR_EXPORT Histogram {
protected:
std::map<Index, int> bins;
std::vector<int> dim_binsize;
int DimIndex(int dim, double val);
double DimVal(int dim, int index);
public:
/** \brief Add dimension with a binsize
*/
void AddDimension(int binsize);
/** \brief Clear the histogram */
void Clear();
/** \brief Increase the histogram for given dimensions */
void Inc(double dim0, double dim1=0, double dim2=0);
/** \brief Get the maximum from the histogram
* This returns the value in the middle of the 'bin' instead of bin-number
*/
int GetMax(double *dim0, double *dim1=0, double *dim2=0);
};
/**
* \brief N-dimensional Histograms calculating also the subpixel average for max bin
*/
class ALVAR_EXPORT HistogramSubpixel : public Histogram {
protected:
std::map<Index, double> acc_dim0;
std::map<Index, double> acc_dim1;
std::map<Index, double> acc_dim2;
public:
/** \brief Clear the histogram */
void Clear();
/** \brief Increase the histogram for given dimensions */
void Inc(double dim0, double dim1=0, double dim2=0);
/** \brief Get the maximum from the histogram
* This finds the maximum bin(s) and averages the original
* values contained there to achieve subpixel accuracy.
*/
int GetMax(double *dim0, double *dim1=0, double *dim2=0);
};
#if (_MSC_VER >= 1400)
inline void STRCPY(char *to, rsize_t size, const char *src) {
strcpy_s(to,size,src);
}
#else
inline void STRCPY(char *to, size_t size, const char *src) {
strncpy(to,src,size-1);
}
#endif
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
/** \brief Class for serializing class content to/from file or std::iostream
*
* The class is mainly meant to serialize classes that implement
* two required methods \e SerializeId and \e Serialize . For example
* alvar::Camera implements the following to make it serializable:
* \code
* const char *SerializeId { return "camera"; };
* bool Serialize(Serialization *ser) {
* if (!ser->Serialize(calib_x_res, "width")) return false;
* if (!ser->Serialize(calib_y_res, "height")) return false;
* if (!ser->Serialize(calib_K, "intrinsic_matrix")) return false;
* if (!ser->Serialize(calib_D, "distortion")) return false;
* return true;
* }
* \endcode
* In your classes \e Serialize -method you can use the overloaded
* \e Serialize method of the \e Serialization class to serialize
* data or data arrays. In addition you can use \e SerializeClass
* to serialize inner serializable classes.
*
* After the class is serializable i.e. it implements the above two
* methods you can serialize it as follows (some examples):
* \code
* alvar::Camera cam;
* cam.SetCalib("calib.xml", 320, 240);
* Serialization sero(std::cout);
* sero<<cam;
* \endcode
* \code
* std::stringstream ss;
* Serialization sero(ss);
* sero<<cam;
* std::cout<<ss.str()<<std::endl;
* // ...
* Serialization seri(ss);
* seri>>cam;
* \endcode
*
* See the constructor \e Serialization::Serialization documentation for
* further use examples.
*/
class ALVAR_EXPORT Serialization {
protected:
bool input;
std::string filename;
//std::iostream *stream;
std::ios *stream;
void *formatter_handle;
bool Output();
bool Input();
bool Descend(const char *id);
bool Ascend();
public:
/** \brief Constructor for serializing to/from specified filename
*
* \code
* Serialization sero("test1.xml");
* sero<<cam;
* \endcode
* \code
* Serialization seri("test1.xml");
* seri>>cam;
* \endcode
*
* Note that this is not identical to:
* \code
* ofstream ofs("test1.xml");
* Serialization sero(ofs);
* sero<<cam;
* \endcode
* \code
* ifstream ifs("test1.xml");
* Serialization seri(ifs);
* sero>>cam;
* \endcode
*
* There are differences with these approaches. When using the constructor
* with 'filename', we use the tinyxml Save and Load methods, while with
* iostream we use tinyxml operators for << and >> . The prior approach
* uses properly indented xml-files with XML declaration <?...?>. In the
* latter approach the indentations and the XML declaration are left out.
* The XML declaration <?...?> is left out because for some reason tinyxml
* doesn't parse it correctly when using operator>> .
*/
Serialization(std::string _filename);
/** \brief Constructor for serializing any iostream (e.g. std::stringstream) */
Serialization(std::basic_iostream<char> &_stream);
/** \brief Constructor for serializing any istream (e.g. std::cin) */
Serialization(std::basic_istream<char> &_stream);
/** \brief Constructor for serializing any ostream (e.g. std::cout) */
Serialization(std::basic_ostream<char> &_stream);
/** \brief Destructor */
~Serialization();
/** \brief Operator for outputting a serializable class into the defined filename or std::iostream */
template <class C>
Serialization& operator<<(C &serializable) {
input=false;
if (!SerializeClass(serializable) || !Output()) {
throw(AlvarException("Serialization failure"));
}
return *this;
}
/** \brief Operator for reading a serializable class from the defined filename or std::iostream */
template <class C>
Serialization& operator>>(C &serializable) {
input=true;
if (!Input() || !SerializeClass(serializable)) {
throw(AlvarException("Serialization failure"));
}
return *this;
}
/** \brief Method for serializing a serializable class. Used by operators << and >> .
*
* Note, in the future this should be usable also from your serializable class
* for adding nested serializable classes.
*/
template <class C>
bool SerializeClass(C &serializable) {
std::string s = serializable.SerializeId();
if (!Descend(s.c_str()) || !serializable.Serialize(this) || !Ascend()) {
return false;
}
return true;
}
/** \brief Method for serializing 'int' data element. Used from your serializable class. */
bool Serialize(int &data, const std::string &name);
/** \brief Method for serializing 'int' data element. Used from your serializable class. */
bool Serialize(unsigned short &data, const std::string &name);
/** \brief Method for serializing 'int' data element. Used from your serializable class. */
bool Serialize(unsigned long &data, const std::string &name);
/** \brief Method for serializing 'double' data element. Used from your serializable class. */
bool Serialize(double &data, const std::string &name);
/** \brief Method for serializing 'std::string' data element. Used from your serializable class. */
bool Serialize(std::string &data, const std::string &name);
/** \brief Method for serializing 'CvMat' data element. Used from your serializable class. */
bool Serialize(CvMat &data, const std::string &name);
/** \brief Method for checking if we are inputting or outputting. Can be used from your serializable class. */
bool IsInput() { return input; }
};
} // namespace alvar
#endif
| 30.940529 | 136 | 0.700149 |
c18ea10bfb5110e7dbec3a848010187f9d151d6d | 3,712 | h | C | include/queue.h | afatom/core-program | 7886acf67f6b81bd06edef41f6ddab83cc993927 | [
"MIT"
] | null | null | null | include/queue.h | afatom/core-program | 7886acf67f6b81bd06edef41f6ddab83cc993927 | [
"MIT"
] | null | null | null | include/queue.h | afatom/core-program | 7886acf67f6b81bd06edef41f6ddab83cc993927 | [
"MIT"
] | null | null | null |
#ifndef _QUEUE_H_
#define _QUEUE_H_
#include <stddef.h> /*<< size_t*/
typedef struct Queue Queue;
typedef enum QueueResult{
QUEUE_SUCCESS = 0,
QUEUE_UNINITIALIZED_ERROR,
QUEUE_UNDERFLOW,
QUEUE_ALLOCATION_ERROR,
QUEUE_INVALID_ITEM
}QueueResult;
typedef int (*ItemPrint)(void *item, void *context);
typedef void (*_elementDestroy)(void* _item);
/*******************************************************************************
*[Description]:Creating Queue Datat Structure.
*[Input]:size of the Queue (its also the size of the array in the structure)
*[output]:Memory allocation to Queue pointer
*[Errors]:(1) ERR_OK (creation operation seccess) (2) ERR_NOT_INITIALIZED
*(when pointer points to NULL) (3) ERR_ALLOCATION_FAILED (when Malloc fails)
*******************************************************************************/
Queue* QueueCreate(void);
/*******************************************************************************
*[Description]:Deleting Queue Datat Structure.
*[Input]:pointer to Queue.
*[output]:No output (Memory freeing)
*[Errors]:(1) ERR_OK (deleting operation seccess) (2) ERR_NOT_INITIALIZED
*(when pointer points to NULL)
*******************************************************************************/
void QueueDestroy(Queue**_queue, void (*_elementDestroy)(void* _item));
/*******************************************************************************
*[Description]:Inserting elements to Queue Datat Structure (FIFO Logic)
*[Input]:pointer to Queue and item to insert.
*[output]:Err status of insertion
*[Errors]:(1) ERR_OK (insertion operation seccess) (2) ERR_NOT_INITIALIZED
*(when pointer points to NULL) (3) ERR_OVERFLOW (4) ERR_UNDERFLOW
*******************************************************************************/
QueueResult QueueInsert(Queue *_queue, void* _item);
/*******************************************************************************
*[Description]:Deleting elements From Queue Datat Structure (FIFO Logic)
*[Input]:pointer to Queue and pointer to Removed item.
*[output]:Err status of Removing
*[Errors]:(1) ERR_OK (Removing operation seccess) (2) ERR_NOT_INITIALIZED
*(when pointer points to NULL) (3) ERR_UNDERFLOW = removing from empty Queue
*******************************************************************************/
QueueResult QueueRemove(Queue *_queue, void** _pItem);
/*******************************************************************************
*[Description]:Check if Queue Datat Structure is empty
*[Input]:pointer to Queue
*[output]:int (1= empty, 0=not empty -1=Null)
*[Errors]:NULL queue pointer or null int array
*******************************************************************************/
int IsEmptyQueue(Queue *_queue);
/*******************************************************************************
*[Description]:My Own Function Queue items number. this function was written for
*Test uses.
*[Input]:pointer to Queue and pointer to numofitems for return.
*[Return]:Num of items in Q
*[Errors]: ERR_OK in success case ERR_NOT_INITIALIZED (when pointer points to NULL)
*and ERR_GENERAL When NULL sent to function
*******************************************************************************/
size_t QueueItemsNum(Queue *_queue);
/*******************************************************************************
*[Description]:for test use only. prints queue elements
*[Input]:pointer to Queue
*[output]:void (prints to stdout)
*[Errors]:NULL queue pointer or null int array
*******************************************************************************/
/*for each maybe*/
void QueueItemsPrint(const Queue *_queue, ItemPrint _fp, void *_context);
#endif /* _QUEUE_H_ */
| 41.707865 | 83 | 0.525323 |
8c252a759d1a1c2c7781e7983216922d3d2f132d | 483 | h | C | ios/versioned-react-native/ABI36_0_0/Expo/ExpoKit/Core/UniversalModules/EXScopedFileSystem/ABI36_0_0EXScopedFilePermissionModule.h | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 3 | 2020-09-06T17:32:53.000Z | 2021-05-20T19:04:48.000Z | ios/versioned-react-native/ABI36_0_0/Expo/ExpoKit/Core/UniversalModules/EXScopedFileSystem/ABI36_0_0EXScopedFilePermissionModule.h | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 16 | 2021-03-01T21:18:59.000Z | 2022-02-27T08:18:52.000Z | ios/versioned-react-native/ABI36_0_0/Expo/ExpoKit/Core/UniversalModules/EXScopedFileSystem/ABI36_0_0EXScopedFilePermissionModule.h | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 2 | 2020-04-25T16:31:11.000Z | 2020-04-25T16:31:13.000Z | // Copyright 2015-present 650 Industries. All rights reserved.
#if __has_include(<ABI36_0_0EXFileSystem/ABI36_0_0EXFilePermissionModule.h>)
#import <ABI36_0_0EXFileSystem/ABI36_0_0EXFilePermissionModule.h>
#import "ABI36_0_0EXConstantsBinding.h"
NS_ASSUME_NONNULL_BEGIN
@interface ABI36_0_0EXScopedFilePermissionModule : ABI36_0_0EXFilePermissionModule
- (instancetype)initWithConstantsBinding:(ABI36_0_0EXConstantsBinding *)constantsBinding;
@end
NS_ASSUME_NONNULL_END
#endif
| 28.411765 | 89 | 0.867495 |
5316edc965437f1aa6edcde1c5b701f4430139c1 | 1,783 | c | C | palacios/src/palacios/svm_halt.c | tsinghua-os-spring-2013/palacios | 7ee817d2495b48dc882df66ded9e8ebf2c4803d9 | [
"BSD-3-Clause"
] | 1 | 2015-03-09T04:25:00.000Z | 2015-03-09T04:25:00.000Z | palacios/src/palacios/svm_halt.c | tsinghua-os-spring-2013/palacios | 7ee817d2495b48dc882df66ded9e8ebf2c4803d9 | [
"BSD-3-Clause"
] | null | null | null | palacios/src/palacios/svm_halt.c | tsinghua-os-spring-2013/palacios | 7ee817d2495b48dc882df66ded9e8ebf2c4803d9 | [
"BSD-3-Clause"
] | null | null | null | /*
* This file is part of the Palacios Virtual Machine Monitor developed
* by the V3VEE Project with funding from the United States National
* Science Foundation and the Department of Energy.
*
* The V3VEE Project is a joint project between Northwestern University
* and the University of New Mexico. You can find out more at
* http://www.v3vee.org
*
* Copyright (c) 2008, Peter Dinda <pdinda@northwestern.edu>
* Copyright (c) 2008, Jack Lange <jarusl@cs.northwestern.edu>
* Copyright (c) 2008, The V3VEE Project <http://www.v3vee.org>
* All rights reserved.
*
* Author: Peter Dinda <pdinda@northwestern.edu>
*
* This is free software. You are permitted to use,
* redistribute, and modify it as specified in the file "V3VEE_LICENSE".
*/
#include <palacios/svm_halt.h>
#include <palacios/vmm_intr.h>
#ifndef DEBUG_HALT
#undef PrintDebug
#define PrintDebug(fmt, args...)
#endif
//
// This should trigger a #GP if cpl!=0, otherwise, yield to host
//
int v3_handle_svm_halt(struct guest_info * info)
{
if (info->cpl!=0) {
v3_raise_exception(info, GPF_EXCEPTION);
} else {
// What we should do is starting waiting on an OS event that will
// result in an injection of an interrupt.
// What we will hackishly do instead is resume on any event
// Plus is this totally GeekOS specific
ullong_t yield_start = 0;
ullong_t yield_stop = 0;
uint32_t gap = 0;
PrintDebug("GeekOS Yield\n");
rdtscll(yield_start);
V3_Yield();
rdtscll(yield_stop);
//v3_update_time(info, yield_stop - yield_start);
gap = yield_stop - yield_start;
v3_raise_irq(info, 0);
PrintDebug("GeekOS Yield Done (%d cycles)\n", gap);
info->rip+=1;
}
return 0;
}
| 23.460526 | 72 | 0.675827 |
88bf1a3b0121f82da3ea8e9f39499303ee31a3fb | 1,323 | h | C | analyzer/analyzer_sensor_health.h | Aeronavics/dronekit-la | 6b9b48aec5dcc610ad87631514aad12b67b753a9 | [
"Apache-2.0"
] | 33 | 2016-02-08T19:54:14.000Z | 2022-03-22T22:25:38.000Z | analyzer/analyzer_sensor_health.h | hnjm/dronekit-la | 68c11b61e049e72ca8217cf9f9b94fab93c12eab | [
"Apache-2.0"
] | 48 | 2016-01-27T06:22:42.000Z | 2022-03-29T21:54:14.000Z | analyzer/analyzer_sensor_health.h | hnjm/dronekit-la | 68c11b61e049e72ca8217cf9f9b94fab93c12eab | [
"Apache-2.0"
] | 32 | 2016-01-27T17:24:32.000Z | 2022-03-15T00:54:49.000Z | #ifndef ANALYZER_SENSOR_HEALTH_H
#define ANALYZER_SENSOR_HEALTH_H
/*
* analyzer_sensor_health
*
*/
#include "analyzer.h"
#include "data_sources.h"
class Analyzer_Sensor_Health_Result : public Analyzer_Result_Period {
public:
Analyzer_Sensor_Health_Result(std::string sensor_name) :
_sensor_name(sensor_name)
{ }
const std::string sensor_name() const { return _sensor_name; }
void to_json(Json::Value &root) const;
private:
const std::string _sensor_name;
};
class Analyzer_Sensor_Health : public Analyzer {
public:
Analyzer_Sensor_Health(AnalyzerVehicle::Base *&vehicle, Data_Sources &data_sources) :
Analyzer(vehicle, data_sources)
{ }
const std::string name() const override { return "Sensor Health"; }
const std::string description() const override {
return "A UAV can self-assess its sensors' health. This test will FAIL if any sensor is detected as failed.";
}
bool configure(INIReader *config) override;
private:
std::map<const std::string, bool> _sensor_health = { };
std::map<const std::string, Analyzer_Sensor_Health_Result*> _results = { };
void evaluate() override;
void close_result(std::string name);
void open_result(std::string name);
void end_of_log(uint32_t packet_count) override;
};
#endif
| 23.625 | 118 | 0.715797 |
49ccd13469c5f3ad70266b704be83b6fcd02ffe5 | 2,002 | c | C | LASD/GB/GB.c | mikymaione/KCammini | 50c3c3601fa937c340effa675847f54d3f31f83b | [
"MIT"
] | 1 | 2019-10-28T13:53:28.000Z | 2019-10-28T13:53:28.000Z | LASD/GB/GB.c | mikymaione/KCammini | 50c3c3601fa937c340effa675847f54d3f31f83b | [
"MIT"
] | null | null | null | LASD/GB/GB.c | mikymaione/KCammini | 50c3c3601fa937c340effa675847f54d3f31f83b | [
"MIT"
] | null | null | null | #include <string.h>
#include <stdlib.h>
char * bool_ul_to_str(unsigned long l)
{
return (l == 0 ? "false" : "true");
}
char * bool_l_to_str(long l)
{
return (l == 0 ? "false" : "true");
}
char * bool_ui_to_str(unsigned int l)
{
return (l == 0 ? "false" : "true");
}
char * bool_i_to_str(int l)
{
return (l == 0 ? "false" : "true");
}
long random_number(long min_num, long max_num) //chiamare prima srand(time(NULL));
{
long low_num = 0;
long hi_num = 0;
if (min_num > max_num)
max_num = min_num + 1;
if (min_num < max_num)
{
low_num = min_num;
hi_num = max_num + 1;
}
else
{
low_num = max_num + 1;
hi_num = min_num;
}
long r = ((rand() % (hi_num - low_num)) + low_num);
if (r < min_num)
r = min_num;
else if (r > max_num)
r = max_num;
return r;
}
char *random_string(unsigned long lunghezza) //chiamare prima srand(time(NULL));
{
int x;
unsigned long i;
char * Lettere = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char * r = calloc(lunghezza, sizeof (char));
size_t le = strlen(Lettere);
for (i = 0; i < lunghezza; i++)
{
x = rand() % le;
r[i] = Lettere[x];
}
return r;
}
char *CharAppend(const char *a, const char *b)
{
size_t na = 0;
size_t nb = 0;
size_t nc = 0;
if (a)
na = sizeof a / sizeof (char);
if (b)
nb = sizeof b / sizeof (char);
if (na < 1)
na = 0;
if (nb < 1)
nb = 0;
nc = na + nb;
if (nc > 0)
{
size_t i, x;
char *c = calloc(nc, sizeof (char));
x = 0;
if (na > 0)
for (i = 0; i < na; i++)
{
c[x] = a[i];
x += 1;
}
if (nb > 0)
for (i = 0; i < nb; i++)
{
c[x] = b[i];
x += 1;
}
return c;
}
return "";
} | 17.561404 | 86 | 0.466533 |
a0b37f321119344390af3892a90fc6369e69f623 | 5,847 | h | C | modules/HVCAENx527/libHVCAENx527App/src/HVCAENx527.h | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | modules/HVCAENx527/libHVCAENx527App/src/HVCAENx527.h | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | modules/HVCAENx527/libHVCAENx527App/src/HVCAENx527.h | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | /* $Header: HVCAENx527/libHVCAENx527App/src/HVCAENx527.h 1.13.1.2 2014/04/29 23:04:40CST Ru Igarashi (igarasr) Exp $
*/
#include <stdio.h>
#include <string.h>
#include <dbDefs.h>
#include <dbAccess.h>
#include <recSup.h>
#include <devSup.h>
#include <callback.h>
#include <sys/time.h>
#include <epicsVersion.h>
#if (EPICS_VERSION == 3) && (EPICS_REVISION == 14) && (EPICS_MODIFICATION > 6)
#include <errlog.h>
#endif
#include <CAENHVWrapper.h>
#if (CAENHVWrapperVERSION / 100 > 2)
/* max length of string values was arbitrarily chosen.
* If there is a need for longer strings, there should
* not be any problem in increasing this. */
#define MAX_VAL_STRING 64
#endif
#define EVNTNO_UPDATE 10
#define EVNTNO_T1 11
#define EVNTNO_T2 12
#define EVNTNO_T3 13
/* Turn on (1) or off (0) scan server mode */
/* This may be needed if the CAEN driver can't handle asynchronous
monitoring of parameters, i.e. a get for one channel is mixed up
with the get for another. */
/* Update: This definitely is needed. */
#define SCAN_SERVER 0
typedef struct ParProp
{
char pname[16];
/* Note: these unions must NOT be used directly in argument lists
of any of the wrapper interfaces */
union
{
float f;
int l;
double d;
short s;
char *c;
} pval;
union
{
float f;
int l;
double d;
short s;
char *c;
} pvalset;
unsigned long Type, Mode;
float Minval, Maxval;
unsigned short Unit; /* engineering unit */
short Exp; /* exponent of numbers, e.g. +3 = kilo */
char Onstate[32], Offstate[32]; /* Labels associated with state */
#if (CAENHVWrapperVERSION / 100 > 2)
float *Enum; /* array of enum values */
#endif /* CAENHVWrapperVERSION */
struct HVChan *hvchan;
/* EPICS-related variables */
char PVname[32];
/* "period" is here for future implementation */
double period; /* desired scan period, -1 == not scanned */
int evntno; /* EPICS event number, -1 == not scanned */
struct dbAddr PVaddr;
CALLBACK pcallback;
} PARPROP;
typedef struct HVChan
{
unsigned short *crate, slot, chan; /* crate, slot, channel number */
char chaddr[16];
char chname[16];
/* The Channel Name is an oddball parameter. The CAEN driver
treats it separately from other channel parameters, so
we're treating its scan parameters specially here, too */
double chname_period;
int chname_evntno;
short npar;
PARPROP *pplist; /* parameters list */
struct HVCrate *hvcrate; /* crate data connector */
/* EPICS-related variables */
short epicsenabled; /* 1 = PV exists, 0 = no PV */
} HVCHAN;
typedef struct HVSlot
{
char slname[64];
short nchan;
HVCHAN **hvchan; /* channel list */
} HVSLOT;
typedef struct CrateScanList
{
char pname[16];
double period; /* default desired scan period, -1 == not scanned */
int evntno; /* default EPICS event number, -1 == not scanned */
/* RU! consider putting the channel number lists here */
struct CrateScanList *next;
} CRATESCANLIST;
typedef struct HVCrate
{
char name[64];
char IPaddr[64];
unsigned short crate; /* crate number */
short nsl; /* max number of slots in crate */
short nchan; /* total number of channels (#slot * #nchperslot) */
HVCHAN *hvchan; /* list of HV channels controlled by this crate */
HVSLOT *hvchmap; /* slot X chan lookup table of *hvchan */
CRATESCANLIST *csl;
short connected;
#if (CAENHVWrapperVERSION / 100 > 2)
int handle; /* handle or ID code for this crate */
CAENHV_SYSTEM_TYPE_t type; /* type of system or crate */
#endif /* CAENHVWrapperVERSION */
} HVCRATE;
extern short DEBUG;
#define PDEBUG(LEVEL) if( DEBUG >= LEVEL)
/*
DEBUG level guideline
0 - none
1 - unrepeated initialization and shutdown messages,
messages about the crate and slots that appear only once
during run-time
2 - messages about the crate that appear once per crate scan
3 - messages about channels that appear only once during run-time
4 - messages about channel parameters that appear only once
during run-time
5 - messages about channels that appear once per crate scan
6 - messages about channels parameters that appear once per crate scan
10 - all messages
*/
float ScanChannelsPeriod;
#if (CAENHVWrapperVERSION / 100 == 2)
int ConnectCrate( char *name, char *linkaddr, char *user, char *pw);
#else
int ConnectCrate( char *name, char *linkaddr, CAENHV_SYSTEM_TYPE_t type, char *user, char *pw);
#endif /* CAENHVWrapperVERSION */
void ParseCrateAddr( char (*straddr)[], short naddr);
#if (CAENHVWrapperVERSION / 100 > 2)
int ParseSystemType( char *strtype);
#endif /* CAENHVWrapperVERSION */
void Shutdown();
#if 0
void iCallback( CALLBACK *pcallback);
void oCallback( CALLBACK *pcallback);
#endif
void *CAENx527ParseDevArgs( char *saddr);
void *CAENx527GetChParVal( PARPROP *pp);
int CAENx527SetChParVal( PARPROP *pp);
char *CAENx527GetChName( HVCHAN *hvch);
int CAENx527SetChName( HVCHAN *hvch, char *chname);
short CAENx527mbbi2state( PARPROP *pp);
void CAENx527mbbi2bits( PARPROP *pp, char *bits, short nbits);
char *CAENx527GetParUnit( PARPROP *pp, char *fieldval);
/*
* $Log: HVCAENx527/libHVCAENx527App/src/HVCAENx527.h $
* Revision 1.13.1.2 2014/04/29 23:04:40CST Ru Igarashi (igarasr)
* Member moved from HVCAENx527/HVCAENx527App/src/HVCAENx527.h in project e:/MKS_Home/archive/cs/epics_local/drivers/CAENx527HV/project.pj to HVCAENx527/libHVCAENx527App/src/HVCAENx527.h in project e:/MKS_Home/archive/cs/epics_local/drivers/CAENx527HV/project.pj.
* Revision 1.13.1.1 2014/04/29 19:24:23CST Ru Igarashi (igarasr)
* implemented support of new CAEN wrapper API
* Revision 1.13 2007/06/01 13:32:57CST Ru Igarashi (igarasr)
* Member moved from EPICS/HVCAENx527App/src/HVCAENx527.h in project e:/MKS_Home/archive/cs/epics_local/drivers/CAENx527HV/project.pj to HVCAENx527/HVCAENx527App/src/HVCAENx527.h in project e:/MKS_Home/archive/cs/epics_local/drivers/CAENx527HV/project.pj.
*/
| 33.221591 | 264 | 0.724987 |
6f82f6e19f698f72e892f0e32e7a2b83d95f7348 | 2,766 | h | C | DataFormats/Candidate/interface/CompositeRefBaseCandidate.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | DataFormats/Candidate/interface/CompositeRefBaseCandidate.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | DataFormats/Candidate/interface/CompositeRefBaseCandidate.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #ifndef Candidate_CompositeRefBaseCandidate_h
#define Candidate_CompositeRefBaseCandidate_h
#include "DataFormats/Candidate/interface/LeafCandidate.h"
/** \class reco::CompositeRefBaseCandidate
*
* a reco::Candidate composed of daughters.
* The daughters has persistent references (edm::RefToBase<...>)
* to reco::Candidate stored in a separate collection.
*
* \author Luca Lista, INFN
*
*
*/
namespace reco {
class CompositeRefBaseCandidate : public LeafCandidate {
public:
/// collection of references to daughters
typedef std::vector<CandidateBaseRef> daughters;
/// default constructor
CompositeRefBaseCandidate() : LeafCandidate() { }
/// constructor from values
CompositeRefBaseCandidate( Charge q, const LorentzVector & p4, const Point & vtx = Point( 0, 0, 0 ),
int pdgId = 0, int status = 0, bool integerCharge = true ) :
LeafCandidate( q, p4, vtx, pdgId, status, integerCharge ) { }
/// constructor from values
CompositeRefBaseCandidate( Charge q, const PolarLorentzVector & p4, const Point & vtx = Point( 0, 0, 0 ),
int pdgId = 0, int status = 0, bool integerCharge = true ) :
LeafCandidate( q, p4, vtx, pdgId, status, integerCharge ) { }
/// constructor from a particle
explicit CompositeRefBaseCandidate( const Candidate & c ) : LeafCandidate( c ) { }
/// destructor
~CompositeRefBaseCandidate() override;
/// returns a clone of the candidate
CompositeRefBaseCandidate * clone() const override;
/// number of daughters
size_t numberOfDaughters() const override;
/// number of mothers
size_t numberOfMothers() const override;
/// return daughter at a given position, i = 0, ... numberOfDaughters() - 1 (read only mode)
const Candidate * daughter( size_type ) const override;
/// return mother at a given position, i = 0, ... numberOfMothers() - 1 (read only mode)
const Candidate * mother( size_type ) const override;
/// return daughter at a given position, i = 0, ... numberOfDaughters() - 1
Candidate * daughter( size_type ) override;
using reco::LeafCandidate::daughter; // avoid hiding the base
/// add a daughter via a reference
void addDaughter( const CandidateBaseRef & );
/// clear daughter references
void clearDaughters() { dau.clear(); }
/// reference to daughter at given position
CandidateBaseRef daughterRef( size_type i ) const { return dau[ i ]; }
private:
/// collection of references to daughters
daughters dau;
/// check overlap with another candidate
bool overlap( const Candidate & ) const override;
};
inline void CompositeRefBaseCandidate::addDaughter( const CandidateBaseRef & cand ) {
dau.push_back( cand );
}
}
#endif
| 40.676471 | 109 | 0.693059 |
17511d988c38287ac5d5e36b5da717b953bad2fc | 1,474 | h | C | engines/ep/tests/mock/mock_executor_pool.h | BenHuddleston/kv_engine | 78123c9aa2c2feb24b7c31eecc862bf2ed6325e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | engines/ep/tests/mock/mock_executor_pool.h | BenHuddleston/kv_engine | 78123c9aa2c2feb24b7c31eecc862bf2ed6325e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | engines/ep/tests/mock/mock_executor_pool.h | BenHuddleston/kv_engine | 78123c9aa2c2feb24b7c31eecc862bf2ed6325e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2019-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#pragma once
#include "cb3_executorpool.h"
#include "task_type.h"
/*
* Wrapper to ExecutorPool, exposes protected members for testing.
*/
class MockExecutorPool : public CB3ExecutorPool {
public:
explicit MockExecutorPool()
: CB3ExecutorPool(4 /*maxThreads*/,
ThreadPoolConfig::ThreadCount(1) /*maxReaders*/,
ThreadPoolConfig::ThreadCount(1) /*maxWriters*/,
1 /*maxAuxIO*/,
1 /*maxNonIO*/) {
}
/**
* Replaces the ExecutorPool instance with a MockExecutorPool one.
* Useful for checking the internal state of ExecutorPool.
*/
static void replaceExecutorPoolWithMock();
/**
* @param queueType
* @param taskName
* @return true if the given task (of the given type) is scheduled,
* false otherwise
*/
bool isTaskScheduled(const task_type_t queueType,
const std::string& taskName);
};
| 33.5 | 79 | 0.628901 |
c0dd0b1a2307ed20850f7af1d514efa641242652 | 20,022 | c | C | src/PolyCEID/hamiltonians/PolyCEID_hamiltonian_single_CHAIN_MOD2.c | lstella77/polyceid | 133fbe5aef2fda9d4927244d5bb609adcdb31c61 | [
"MIT"
] | null | null | null | src/PolyCEID/hamiltonians/PolyCEID_hamiltonian_single_CHAIN_MOD2.c | lstella77/polyceid | 133fbe5aef2fda9d4927244d5bb609adcdb31c61 | [
"MIT"
] | null | null | null | src/PolyCEID/hamiltonians/PolyCEID_hamiltonian_single_CHAIN_MOD2.c | lstella77/polyceid | 133fbe5aef2fda9d4927244d5bb609adcdb31c61 | [
"MIT"
] | null | null | null |
/******************************************************************************
Copyright (C) 2011-2012 by Lorenzo Stella <lorenzo DOT stella77 AT gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
******************************************************************************/
#include "config.h"
#include "PolyCEID_hamiltonian_single_CHAIN_MOD2.h"
/*********************
FUNCTIONS & MACROS
*********************/
/* H_matrix_single_CHAIN_MOD2 update */
int H_matrix_single_CHAIN_MOD2_update( const constants constants, state_p state_p, config_p config_p, matrix_p matrix_p ){
/* constants */
int N_electrons;
int N_atoms;
double a_spacing;
// double delta_energy;
double k_harmonic;
double t_hopping;
double alpha_coupling;
double dimerisation;
/* state */
rvector_p positions_p;
/* dummies */
int index;
int i;
int info=0;
double distance;
double dummy;
double dummy2;
double extreem1;
double extreem2;
double sigma;
N_electrons = constants.N_electrons;
N_atoms = constants.N_atoms;
a_spacing = constants.hamiltonian.par_extra[0];
// delta_energy = constants.hamiltonian.par_extra[1];
k_harmonic = constants.hamiltonian.par_extra[2]/(double) N_electrons; // WARNING: rescaling
t_hopping = constants.hamiltonian.par_extra[3];
alpha_coupling = constants.hamiltonian.par_extra[4];
dimerisation = constants.hamiltonian.par_extra[5];
extreem1 = constants.hamiltonian.par_extra[6];
extreem2 = constants.hamiltonian.par_extra[7];
positions_p = &config_p->atoms.positions;
if( !info ){
dummy = 0.0e0;
/* set matrix to zero */
if( MATRIX_ZERO( *matrix_p ) ) info=1; // Important
// fprintf( stdout, "extreems: %le, %le\n", extreem1, extreem2 );
// first par_extra term
i=-1;
distance = ( positions_p->rvector[ 0 ] - extreem1 );
sigma = dimerisation;
// fprintf( stdout, "i = %d, sigma = %le\n", i, sigma );
#ifdef __DEBUG__
if( distance < EPS ){
fprintf( stderr, "ERROR: the distance between particle %d and %d is not positive [%le]\n", i, i+1, distance );
fflush( stderr );
info=1;
}
#endif /* __DEBUG__ */
if( alpha_coupling *( distance -a_spacing )< 1.0e0 +sigma ){
dummy2 = t_hopping *( 1.0e0 -alpha_coupling *( distance -a_spacing ) +sigma );
//
index = ELECTRON_SINGLE_INDEX( i+1, i+2 );
matrix_p->matrix[ index ].z[0] = -dummy2;
//
index = ELECTRON_SINGLE_INDEX( i+2, i+1 );
matrix_p->matrix[ index ].z[0] = -dummy2;
}
else{
fprintf( stdout, "WARNING: jump at time %le\n", config_p->time );
}
/* harmonic term update */
dummy += ( distance -a_spacing ) *( distance -a_spacing );
// second par_extra term
i=N_atoms-1;
distance = ( extreem2 -positions_p->rvector[ N_atoms-1 ]);
sigma = dimerisation *( 2*(i%2) -1 );
// fprintf( stdout, "i = %d, sigma = %le\n", i, sigma );
#ifdef __DEBUG__
if( distance < EPS ){
fprintf( stderr, "ERROR: the distance between particle %d and %d is not positive [%le]\n", i, i+1, distance );
fflush( stderr );
info=1;
}
#endif /* __DEBUG__ */
if( alpha_coupling *( distance -a_spacing )< 1.0e0 +sigma ){
dummy2 = t_hopping *( 1.0e0 -alpha_coupling *( distance -a_spacing ) +sigma );
//
index = ELECTRON_SINGLE_INDEX( i+1, i+2 );
matrix_p->matrix[ index ].z[0] = -dummy2;
//
index = ELECTRON_SINGLE_INDEX( i+2, i+1 );
matrix_p->matrix[ index ].z[0] = -dummy2;
}
else{
fprintf( stdout, "WARNING: jump at time %le\n", config_p->time );
}
/* harmonic term update */
dummy += ( distance -a_spacing ) *( distance -a_spacing );
// main loop
for( i=0;i<N_atoms-1;i++){
distance = ( positions_p->rvector[ i+1 ] - positions_p->rvector[ i ] );
sigma = dimerisation *( 2*(i%2) -1 );
// fprintf( stdout, "i = %d, sigma = %le\n", i, sigma );
#ifdef __DEBUG__
if( distance < EPS ){
fprintf( stderr, "ERROR: the distance between particle %d and %d is not positive [%le]\n", i, i+1, distance );
fflush( stderr );
info=1;
break;
}
#endif /* __DEBUG__ */
// fprintf( stdout, "i = %d, distance = %le, a_spacing = %le\n", i, distance, a_spacing );
if( alpha_coupling *( distance -a_spacing )< 1.0e0 +sigma ){
dummy2 = t_hopping *( 1.0e0 -alpha_coupling *( distance -a_spacing ) +sigma );
//
index = ELECTRON_SINGLE_INDEX( i+1, i+2 );
matrix_p->matrix[ index ].z[0] = -dummy2;
//
index = ELECTRON_SINGLE_INDEX( i+2, i+1 );
matrix_p->matrix[ index ].z[0] = -dummy2;
}
else{
fprintf( stdout, "WARNING: jump at time %le\n", config_p->time );
}
/* harmonic term update */
dummy += ( distance -a_spacing ) *( distance -a_spacing );
} /* i loop */
if( positions_p->rvector[ 0 ] - extreem1 < EPS || extreem2 - positions_p->rvector[ N_atoms -1 ] < EPS ){
fprintf( stderr, "ERROR: invalid boundary conditions is not positive \n" );
fflush( stderr );
info=1;
}
/* Classical part */
for( i=0; i<N_atoms+2; i++ ){
matrix_p->matrix[ ELECTRON_SINGLE_INDEX( i, i ) ].z[0] = 0.5e0 *k_harmonic *dummy; //WARNING: diagonal only
}
}
return info;
}
//------------------------------------------
/* F_matrix_single_CHAIN_MOD2 update */
int F_matrix_single_CHAIN_MOD2_update( const constants constants, state_p state_p, config_p config_p, int r, matrix_p matrix_p ){
/* constants */
int N_electrons;
int N_atoms;
double a_spacing;
// double delta_energy;
double k_harmonic;
double t_hopping;
double alpha_coupling;
double dimerisation;
/* state */
rvector_p positions_p;
/* dummies */
int index;
int i;
double distance;
double dummy;
int info=0;
double extreem1;
double extreem2;
double sigma;
N_electrons = constants.N_electrons;
N_atoms = constants.N_atoms;
a_spacing = constants.hamiltonian.par_extra[0];
// delta_energy = constants.hamiltonian.par_extra[1];
k_harmonic = constants.hamiltonian.par_extra[2]/(double) N_electrons; // WARNING: rescaling
t_hopping = constants.hamiltonian.par_extra[3];
alpha_coupling = constants.hamiltonian.par_extra[4];
dimerisation = constants.hamiltonian.par_extra[5];
extreem1 = constants.hamiltonian.par_extra[6];
extreem2 = constants.hamiltonian.par_extra[7];
positions_p = &config_p->atoms.positions;
if( !info ){
/* set matrix to zero */
if( MATRIX_ZERO( *matrix_p ) ) info=1; // Important!
dummy = t_hopping *alpha_coupling;
//
if( r > 0 ){
distance = ( positions_p->rvector[ r ] - positions_p->rvector[ r-1 ] );
}
else{
distance = ( positions_p->rvector[ 0 ] - extreem1 );
}
sigma = dimerisation *( 1 - 2*(r%2) );
if( alpha_coupling *( distance -a_spacing ) < 1.0e0 +sigma ){
//
index = ELECTRON_SINGLE_INDEX( r, r+1 );
matrix_p->matrix[ index ].z[0] = -dummy;
//
index = ELECTRON_SINGLE_INDEX( r+1, r );
matrix_p->matrix[ index ].z[0] = -dummy;
}
//
if( r < N_atoms-1 ){
distance = ( positions_p->rvector[ r+1 ] - positions_p->rvector[ r ] );
}
else{
distance = ( extreem2 - positions_p->rvector[ r ] );
}
sigma = dimerisation *( 2*(r%2) -1 );
if( alpha_coupling *( distance -a_spacing ) < 1.0e0 +sigma ){
//
index = ELECTRON_SINGLE_INDEX( r+1, r+2 );
matrix_p->matrix[ index ].z[0] = dummy;
//
index = ELECTRON_SINGLE_INDEX( r+2, r+1 );
matrix_p->matrix[ index ].z[0] = dummy;
}
if( r==0 ){
dummy = k_harmonic *( positions_p->rvector[ r+1 ] -2.0e0 *positions_p->rvector[ r ] +extreem1 );
}
else if( r == N_atoms-1 ){
dummy = k_harmonic *( extreem2 -2.0e0 *positions_p->rvector[ r ] +positions_p->rvector[ r-1 ] );
}
else{
dummy = k_harmonic *( positions_p->rvector[ r+1 ] - 2.0e0 *positions_p->rvector[ r ] +positions_p->rvector[ r-1 ] );
}
for( i=0;i<N_atoms+2;i++){
index = ELECTRON_SINGLE_INDEX( i, i );
matrix_p->matrix[ index ].z[0] = dummy;
}
}
return info;
}
//------------------------------------------
/* K_matrix_single_CHAIN_MOD2 update */
int K_matrix_single_CHAIN_MOD2_update( const constants constants, state_p state_p, config_p config_p, int r, int s, matrix_p matrix_p ){
/* constants */
int N_electrons;
int N_atoms;
// double delta_energy;
double k_harmonic;
// double t_hopping;
//double alpha_coupling;
/* state */
/* dummies */
int i;
int index;
int info=0;
N_electrons = constants.N_electrons;
N_atoms = constants.N_atoms;
// delta_energy = constants.hamiltonian.par_extra[1];
k_harmonic = constants.hamiltonian.par_extra[2]/(double) N_electrons; // WARNING: rescaling
// t_hopping = constants.hamiltonian.par_extra[3];
// alpha_coupling = constants.hamiltonian.par_extra[4];
if( !info ){
/* set matrix to zero */
if( MATRIX_ZERO( *matrix_p ) ) info=1; // Important
for( i=0;i<N_atoms+2;i++){
index = ELECTRON_SINGLE_INDEX( i, i );
//
if( s == r+1 || s == r-1 ){
matrix_p->matrix[ index ].z[0] = -k_harmonic;
}
//
if( s == r ){
matrix_p->matrix[ index ].z[0] = 2.0e0 *k_harmonic;
}
} /* end i loop*/
}
return info;
}
//------------------------------------------
//------------------------------------------
/* utilities */
//------------------------------------------
int Hamiltonian_single_CHAIN_MOD2_parameters_check( const constants constants ){
/*constants */
int sdim;
int N_atoms;
int N_levels_single;
/* dummies */
int info=0;
sdim = constants.spacial_dimension;
N_atoms = constants.N_atoms;
N_levels_single = constants.N_levels_single;
#ifdef __DEBUG__
fprintf( stdout, "#----------\n" );
fprintf( stdout, "HAMILTONIAN_SINGLE: using CHAIN_MOD2\n" );
#endif /* __DEBUG__ */
if( sdim != 1 ){
fprintf( stderr, "ERROR: this Hamiltonian_single works only for sdim = 1.\n" );
fflush( stderr );
info=1;
}
if( N_levels_single != N_atoms +2 ){
fprintf( stderr, "ERROR: this Hamiltonian_single works only for N_levels_single = N_atoms +2.\n" );
fflush( stderr );
info=1;
}
if( N_atoms < 2 ){
fprintf( stderr, "ERROR: this Hamiltonian_single works only for N_atoms > 1.\n" );
fflush( stderr );
info=1;
}
if( constants.hamiltonian.N_par_extra != 8 ){
fprintf( stderr, "ERROR: this Hamiltonian_single works only with 8 parameters: a_spacing, delta_energy, k_harmonic, t_hopping, alpha_coupling, dimerisation, extreme1, extreme2\n" );
fflush( stderr );
info=1;
}
#ifdef __DEBUG__
if( !info ){
fprintf( stdout, "# a_spacing = %le\n", constants.hamiltonian.par_extra[ 0 ] );
fprintf( stdout, "# delta_energy = %le\n", constants.hamiltonian.par_extra[ 1 ] );
fprintf( stdout, "# k_harmonic = %le\n", constants.hamiltonian.par_extra[ 2 ] );
fprintf( stdout, "# t_hopping = %le\n", constants.hamiltonian.par_extra[ 3 ] );
fprintf( stdout, "# alpha_coupling = %le\n", constants.hamiltonian.par_extra[ 4 ] );
fprintf( stdout, "# dimerisation = %le\n", constants.hamiltonian.par_extra[ 5 ] );
fprintf( stdout, "# extreem1 = %le\n", constants.hamiltonian.par_extra[ 6 ] );
fprintf( stdout, "# extreem2 = %le\n", constants.hamiltonian.par_extra[ 7 ] );
fprintf( stdout, "#----------\n" );
}
#endif /* __DEBUG__ */
return info;
}
//------------------------------------------
/* H_matrix_single_CHAIN_MOD2_check */
int H_matrix_single_CHAIN_MOD2_check( const constants constants, rvector_p positions_p, matrix_p matrix_p ){
/* constants */
int N_electrons;
int N_atoms;
double a_spacing;
// double delta_energy;
double k_harmonic;
double t_hopping;
double alpha_coupling;
double dimerisation;
/* dummies */
int index;
int i;
int info=0;
double distance;
double dummy;
double dummy2;
double extreem1;
double extreem2;
double sigma;
N_electrons = constants.N_electrons;
N_atoms = constants.N_atoms;
a_spacing = constants.hamiltonian.par_extra[0];
// delta_energy = constants.hamiltonian.par_extra[1];
k_harmonic = constants.hamiltonian.par_extra[2]/(double) N_electrons; // WARNING: rescaling
t_hopping = constants.hamiltonian.par_extra[3];
alpha_coupling = constants.hamiltonian.par_extra[4];
dimerisation = constants.hamiltonian.par_extra[5];
extreem1 = constants.hamiltonian.par_extra[6];
extreem2 = constants.hamiltonian.par_extra[7];
if( !info ){
dummy = 0.0e0;
/* set matrix to zero */
if( MATRIX_ZERO( *matrix_p ) ) info=1; // Important
// fprintf( stdout, "extreems: %le, %le [chk]\n", extreem1, extreem2 );
// first par_extra term
i=-1;
distance = ( positions_p->rvector[ 0 ] - extreem1 );
sigma = dimerisation;
// fprintf( stdout, "i = %d, sigma = %le\n", i, sigma );
#ifdef __DEBUG__
if( distance < EPS ){
fprintf( stderr, "ERROR: the distance between particle %d and %d is not positive [%le]\n", i, i+1, distance );
fflush( stderr );
info=1;
}
#endif /* __DEBUG__ */
if( alpha_coupling *( distance -a_spacing )< 1.0e0 +sigma ){
dummy2 = t_hopping *( 1.0e0 -alpha_coupling *( distance -a_spacing ) +sigma );
//
index = ELECTRON_SINGLE_INDEX( i+1, i+2 );
matrix_p->matrix[ index ].z[0] = -dummy2;
//
index = ELECTRON_SINGLE_INDEX( i+2, i+1 );
matrix_p->matrix[ index ].z[0] = -dummy2;
}
/* harmonic term update */
dummy += ( distance -a_spacing ) *( distance -a_spacing );
// first par_extra term
i=N_atoms-1;
distance = ( extreem2 -positions_p->rvector[ N_atoms-1 ]);
sigma = dimerisation *( 2*(i%2) -1 );
// fprintf( stdout, "i = %d, sigma = %le\n", i, sigma );
#ifdef __DEBUG__
if( distance < EPS ){
fprintf( stderr, "ERROR: the distance between particle %d and %d is not positive [%le]\n", i, i+1, distance );
fflush( stderr );
info=1;
}
#endif /* __DEBUG__ */
if( alpha_coupling *( distance -a_spacing )< 1.0e0 +sigma ){
dummy2 = t_hopping *( 1.0e0 -alpha_coupling *( distance -a_spacing ) +sigma );
//
index = ELECTRON_SINGLE_INDEX( i+1, i+2 );
matrix_p->matrix[ index ].z[0] = -dummy2;
//
index = ELECTRON_SINGLE_INDEX( i+2, i+1 );
matrix_p->matrix[ index ].z[0] = -dummy2;
}
/* harmonic term update */
dummy += ( distance -a_spacing ) *( distance -a_spacing );
// main loop
for( i=0;i<N_atoms-1;i++){
distance = ( positions_p->rvector[ i+1 ] - positions_p->rvector[ i ] );
sigma = dimerisation *( 2*(i%2) -1 );
// fprintf( stdout, "i = %d, sigma = %le\n", i, sigma );
#ifdef __DEBUG__
if( distance < EPS ){
fprintf( stderr, "ERROR: the distance between particle %d and %d is not positive [chk, %le]\n", i, i+1, distance );
fflush( stderr );
info=1;
break;
}
#endif /* __DEBUG__ */
// fprintf( stdout, "i = %d, distance = %le, a_spacing = %le\n", i, distance, a_spacing );
if( alpha_coupling *( distance -a_spacing )< 1.0e0 +sigma ){
dummy2 = t_hopping *( 1.0e0 -alpha_coupling *( distance -a_spacing ) +sigma );
//
index = ELECTRON_SINGLE_INDEX( i+1, i+2 );
matrix_p->matrix[ index ].z[0] = -dummy2;
//
index = ELECTRON_SINGLE_INDEX( i+2, i+1 );
matrix_p->matrix[ index ].z[0] = -dummy2;
}
/* harmonic term update */
dummy += ( distance -a_spacing ) *( distance -a_spacing );
} /* i loop */
if( positions_p->rvector[ 0 ] - extreem1 < EPS || extreem2 - positions_p->rvector[ N_atoms -1 ] < EPS ){
fprintf( stderr, "ERROR: invalid boundary conditions is not positive \n" );
fflush( stderr );
info=1;
}
/* Classical part */
for( i=0; i<N_atoms+2; i++ ){
matrix_p->matrix[ ELECTRON_SINGLE_INDEX( i, i ) ].z[0] = 0.5e0 *k_harmonic *dummy; //WARNING: diagonal only
}
}
return info;
}
//------------------------------------------
/* classical_dipole_single_CHAIN_MOD2_update */
int classical_dipole_single_CHAIN_MOD2_update( const constants constants, state_p state_p, config_p config_p, int comp, matrix_p matrix_p ){
/* constants */
int N_atoms;
/* state */
rvector_p positions_p;
rvector_p centre_of_mass_p;
/* dummies */
int index;
int i;
int info=0;
double extreem1;
double extreem2;
N_atoms = constants.N_atoms;
extreem1 = constants.hamiltonian.par_extra[6];
extreem2 = constants.hamiltonian.par_extra[7];
positions_p = &(config_p->atoms.positions);
centre_of_mass_p = &(config_p->atoms.centre_of_mass);
if( !info ){
/* set matrix to zero */
if( MATRIX_ZERO( *matrix_p ) ) info=1; // Important
// fprintf( stdout, "extreems: %le, %le [chk]\n", extreem1, extreem2 );
// first par_extra term
index = ELECTRON_SINGLE_INDEX( 0, 0 );
matrix_p->matrix[ index ].z[0] = extreem1 -( centre_of_mass_p->rvector[ comp ] );
// second par_extra term
index = ELECTRON_SINGLE_INDEX( N_atoms +1, N_atoms +1 );
matrix_p->matrix[ index ].z[0] = extreem2 -( centre_of_mass_p->rvector[ comp ] );
// main loop
for( i=0;i<N_atoms;i++){
index = ELECTRON_SINGLE_INDEX( i+1, i+1 );
matrix_p->matrix[ index ].z[0] = positions_p->rvector[ i ] -( centre_of_mass_p->rvector[ comp ] );
} /* i loop */
if( positions_p->rvector[ 0 ] - extreem1 < EPS || extreem2 - positions_p->rvector[ N_atoms -1 ] < EPS ){
fprintf( stderr, "ERROR: invalid boundary conditions is not positive \n" );
fflush( stderr );
info=1;
}
}
return info;
}
//------------------------------------------
| 23.978443 | 185 | 0.576666 |
a5bcd5db80d02f9c6b6a4685cea3d20c1fcf84d6 | 1,398 | h | C | react-native/react-native-flipper/ios/FlipperReactNativeJavaScriptPluginManager.h | FairyWorld/tool_flipper | f0c0011d69e71477b92fbfbd76a9ac5d8d67ca52 | [
"MIT"
] | 1 | 2022-03-26T05:15:39.000Z | 2022-03-26T05:15:39.000Z | react-native/react-native-flipper/ios/FlipperReactNativeJavaScriptPluginManager.h | FairyWorld/tool_flipper | f0c0011d69e71477b92fbfbd76a9ac5d8d67ca52 | [
"MIT"
] | 133 | 2020-04-24T19:58:15.000Z | 2021-09-23T16:23:35.000Z | react-native/react-native-flipper/ios/FlipperReactNativeJavaScriptPluginManager.h | FairyWorld/tool_flipper | f0c0011d69e71477b92fbfbd76a9ac5d8d67ca52 | [
"MIT"
] | 1 | 2022-03-30T04:22:36.000Z | 2022-03-30T04:22:36.000Z | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifdef DEBUG
#import <React/RCTBridgeModule.h>
#import <FlipperKit/FlipperClient.h>
NS_ASSUME_NONNULL_BEGIN
@class FlipperModule;
@interface FlipperReactNativeJavaScriptPluginManager : NSObject
+ (instancetype)sharedInstance;
- (void)registerPluginWithModule:(FlipperModule*)module
pluginId:(NSString*)pluginId
inBackground:(BOOL)inBackground
statusCallback:(RCTResponseSenderBlock)statusCallback;
- (void)sendWithPluginId:(NSString*)pluginId
method:(NSString*)method
data:(NSString*)data;
- (void)reportErrorWithMetadata:(NSString*)reason
stackTrace:(NSString*)stackTrace
pluginId:(NSString*)pluginId;
- (void)reportError:(NSString*)error pluginId:(NSString*)pluginId;
- (void)subscribeWithModule:(FlipperModule*)module
pluginId:(NSString*)pluginId
method:(NSString*)method;
- (void)respondSuccessWithResponderId:(NSString*)responderId
data:(NSString*)data;
- (void)respondErrorWithResponderId:(NSString*)responderId data:(NSString*)data;
@end
NS_ASSUME_NONNULL_END
#endif
| 27.411765 | 80 | 0.674535 |
cb82b24246447cac7ee2e55db02cf125f0f01bdb | 375 | h | C | mpers-m32/struct_sg_req_info.h | ipduh/strace | 30b9ef95e1256812dc0dedb68558fdc9d8a6c32b | [
"BSD-3-Clause"
] | 22 | 2018-10-05T07:19:06.000Z | 2022-02-24T07:12:55.000Z | mpers-m32/struct_sg_req_info.h | ipduh/strace | 30b9ef95e1256812dc0dedb68558fdc9d8a6c32b | [
"BSD-3-Clause"
] | 1 | 2020-11-10T11:06:08.000Z | 2020-11-10T11:06:08.000Z | mpers-m32/struct_sg_req_info.h | ipduh/strace | 30b9ef95e1256812dc0dedb68558fdc9d8a6c32b | [
"BSD-3-Clause"
] | 10 | 2018-10-05T07:19:06.000Z | 2022-03-23T14:24:53.000Z | #include <stdint.h>
#ifndef mpers_ptr_t_is_uint32_t
typedef uint32_t mpers_ptr_t;
#define mpers_ptr_t_is_uint32_t
#endif
typedef
struct {
char req_state;
char orphan;
char sg_io_owned;
char problem;
int32_t pack_id;
mpers_ptr_t usr_ptr;
uint32_t duration;
int32_t unused;
} ATTRIBUTE_PACKED m32_struct_sg_req_info;
#define MPERS_m32_struct_sg_req_info m32_struct_sg_req_info
| 20.833333 | 59 | 0.853333 |
3ebcc637c9b346a5f9e43c8e7b365dc3593922e6 | 990 | h | C | src/represent/representer.h | OneMoreGres/ScreenTranslator | 2ce8e0edc363e98bcdeb24d06094ba080658d048 | [
"MIT"
] | 442 | 2015-01-10T04:24:05.000Z | 2022-03-31T05:18:30.000Z | src/represent/representer.h | JavierPieschacon/ScreenTranslator | a4e09d88c61d4985393ab373df793693696d79ab | [
"MIT"
] | 92 | 2016-01-31T01:49:20.000Z | 2022-03-26T13:36:08.000Z | src/represent/representer.h | JavierPieschacon/ScreenTranslator | a4e09d88c61d4985393ab373df793693696d79ab | [
"MIT"
] | 77 | 2015-01-03T07:27:30.000Z | 2022-03-25T13:48:19.000Z | #pragma once
#include "stfwd.h"
#include <QObject>
enum class ResultMode;
class ResultWidget;
class ResultEditor;
class Representer : public QObject
{
Q_OBJECT
public:
Representer(Manager &manager, TrayIcon &tray, const Settings &settings,
const CommonModels &models);
~Representer();
void showLast();
void clipboardLast();
void represent(const TaskPtr &task);
bool isVisible() const;
void hide();
void updateSettings();
void clipboardText(const TaskPtr &task);
void clipboardImage(const TaskPtr &task);
void edit(const TaskPtr &task);
bool eventFilter(QObject *watched, QEvent *event) override;
private:
void showTooltip(const TaskPtr &task);
void showWidget(const TaskPtr &task);
Manager &manager_;
TrayIcon &tray_;
const Settings &settings_;
const CommonModels &models_;
Generation generation_{};
std::vector<std::unique_ptr<ResultWidget>> widgets_;
std::unique_ptr<ResultEditor> editor_;
TaskPtr lastTooltipTask_;
};
| 22 | 73 | 0.733333 |
124a329eebdb49c8e08f53ae6c36da4c7b0be9db | 1,727 | h | C | SAObjects.framework/SAMPSetQueue.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 4 | 2021-10-06T12:15:26.000Z | 2022-02-21T02:26:00.000Z | SAObjects.framework/SAMPSetQueue.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | null | null | null | SAObjects.framework/SAMPSetQueue.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 1 | 2021-10-08T07:40:53.000Z | 2021-10-08T07:40:53.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/SAObjects.framework/SAObjects
*/
@interface SAMPSetQueue : SADomainCommand
@property (nonatomic, copy) NSString *assetInfo;
@property (nonatomic) bool dryRun;
@property (nonatomic, copy) NSArray *filters;
@property (nonatomic, copy) NSArray *hashedRouteUIDs;
@property (nonatomic, retain) SAMPCollection *mediaItems;
@property (nonatomic, copy) NSString *recommendationId;
@property (nonatomic) bool shouldOverrideManuallyCuratedUpNext;
@property (nonatomic) bool shouldReloadQueue;
@property (nonatomic) bool shouldShuffle;
@property (nonatomic, copy) NSArray *sort;
@property (nonatomic, copy) NSNumber *startPlaying;
// Image: /System/Library/PrivateFrameworks/SAObjects.framework/SAObjects
+ (id)setQueue;
+ (id)setQueueWithDictionary:(id)arg1 context:(id)arg2;
- (id)assetInfo;
- (bool)dryRun;
- (id)encodedClassName;
- (id)filters;
- (id)groupIdentifier;
- (id)hashedRouteUIDs;
- (id)mediaItems;
- (bool)mutatingCommand;
- (id)recommendationId;
- (bool)requiresResponse;
- (void)setAssetInfo:(id)arg1;
- (void)setDryRun:(bool)arg1;
- (void)setFilters:(id)arg1;
- (void)setHashedRouteUIDs:(id)arg1;
- (void)setMediaItems:(id)arg1;
- (void)setRecommendationId:(id)arg1;
- (void)setShouldOverrideManuallyCuratedUpNext:(bool)arg1;
- (void)setShouldReloadQueue:(bool)arg1;
- (void)setShouldShuffle:(bool)arg1;
- (void)setSort:(id)arg1;
- (void)setStartPlaying:(id)arg1;
- (bool)shouldOverrideManuallyCuratedUpNext;
- (bool)shouldReloadQueue;
- (bool)shouldShuffle;
- (id)sort;
- (id)startPlaying;
// Image: /System/Library/PrivateFrameworks/AssistantServices.framework/AssistantServices
- (void)af_addEntriesToAnalyticsContext:(id)arg1;
@end
| 30.839286 | 89 | 0.775333 |
3e21d0390806d2448537a4019bcaa50a34f0e0e4 | 2,369 | h | C | SLAVCam/SLAVCam/Classes/SCRecord/SCSwipeableFilterView.h | cslmark/SLAVCam | 38a3ad28e4fbce359867754b257f4a507fdf2c7a | [
"MIT"
] | null | null | null | SLAVCam/SLAVCam/Classes/SCRecord/SCSwipeableFilterView.h | cslmark/SLAVCam | 38a3ad28e4fbce359867754b257f4a507fdf2c7a | [
"MIT"
] | null | null | null | SLAVCam/SLAVCam/Classes/SCRecord/SCSwipeableFilterView.h | cslmark/SLAVCam | 38a3ad28e4fbce359867754b257f4a507fdf2c7a | [
"MIT"
] | null | null | null | //
// SCFilterSwitcherView.h
// SCRecorderExamples
//
// Created by Simon CORSIN on 29/05/14.
//
//
#import <UIKit/UIKit.h>
#import "SCPlayer.h"
#import "SCFilterImageView.h"
@class SCSwipeableFilterView;
@protocol SCSwipeableFilterViewDelegate <NSObject>
- (void)swipeableFilterView:(SCSwipeableFilterView *__nonnull)swipeableFilterView didScrollToFilter:(SCFilter *__nullable)filter;
@optional
- (void)swipeableFilterViewDidBeginScroll:(SCSwipeableFilterView *__nonnull)swipeableFilterView;
- (void)swipeableFilterViewDidEndScroll:(SCSwipeableFilterView *__nonnull)swipeableFilterView;
@end
/**
A filter selector view that works like the Snapchat presentation of the available filters.
Filters are swipeable from horizontally.
*/
@interface SCSwipeableFilterView : SCImageView<UIScrollViewDelegate>
/**
The available filterGroups that this SCFilterSwitcherView shows
If you want to show an empty filter (no processing), just add a [NSNull null]
entry instead of an instance of SCFilterGroup
*/
@property (strong, nonatomic) NSArray *__nullable filters;
/**
The currently selected filter group.
This changes when scrolling in the underlying UIScrollView.
This value is Key-Value observable.
*/
@property (strong, nonatomic) SCFilter *__nullable selectedFilter;
/**
A filter that is applied before applying the selected filter
*/
@property (strong, nonatomic) SCFilter *__nullable preprocessingFilter;
/**
The delegate that will receive messages
*/
@property (weak, nonatomic) id<SCSwipeableFilterViewDelegate> __nullable delegate;
/**
The underlying scrollView used for scrolling between filterGroups.
You can freely add your views inside.
*/
@property (readonly, nonatomic) UIScrollView *__nonnull selectFilterScrollView;
/**
Whether the current image should be redraw with the new contentOffset
when the UIScrollView is scrolled. If disabled, scrolling will never
show up the other filters, until it receives a new CIImage.
On some device it seems better to disable it when the SCSwipeableFilterView
is set inside a SCPlayer.
Default is YES
*/
@property (assign, nonatomic) BOOL refreshAutomaticallyWhenScrolling;
@property (nonatomic) BOOL horizontalScroll; // default true; when false, scroll vertical.
/**
Scrolls to a specific filter
*/
- (void)scrollToFilter:(SCFilter *__nonnull)filter animated:(BOOL)animated;
@end
| 30.766234 | 129 | 0.791895 |
e35025295486955cf9dc1d2dfc7887aca12fe907 | 1,248 | c | C | d/av_rooms/mystra/inn7.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/av_rooms/mystra/inn7.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/av_rooms/mystra/inn7.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | // File created with /daemon/persistent_room_d.c
#include <std.h>
inherit "/cmds/avatar/avatar_room.c";
void create()
{
::create();
set_name("inn7");
set_property("indoors",1);
set_property("light",2);
set_property("no teleport",1);
set_terrain("wood building");
set_travel("slick floor");
set_climate("temperate");
set_short("%^BOLD%^%^BLACK%^Southern Hallway%^RESET%^");
set_long("It is slightly darker here than in other portions of the inn. %^BOLD%^%^YELLOW%^Light %^RESET%^from the chandelier in the main hall barely reaches this far into the hallway and no sconces or candles "
"can be found hanging on the walls for fear of damaging the many %^MAGENTA%^paintings %^RESET%^hanging about. At the end of the hallway here is a large %^BOLD%^white door%^RESET%^. It is mostly plain"
" in design with only four lightly-beveled squares the only thing seperating it from a painted slab of %^ORANGE%^wood%^RESET%^."
);
set_smell("default","
%^CYAN%^The hallway smells fresh and clean%^RESET%^");
set_listen("default","%^BOLD%^%^YELLOW%^It is quiet in this part of the inn%^RESET%^");
set_exits(([
"south" : "/d/av_rooms/mystra/inn10",
"north" : "/d/av_rooms/mystra/inn5",
]));
} | 36.705882 | 215 | 0.680288 |
420e149072a38816df3008de030fc664f1607a4f | 2,918 | h | C | codes/net/slimfly.h | minitu/codes | 1449aaf45e56fe41fedcd6b4a7f44787cb6f41ca | [
"BSD-3-Clause"
] | 22 | 2019-06-23T11:25:31.000Z | 2022-03-31T09:03:23.000Z | codes/net/slimfly.h | minitu/codes | 1449aaf45e56fe41fedcd6b4a7f44787cb6f41ca | [
"BSD-3-Clause"
] | 63 | 2019-07-05T15:38:06.000Z | 2021-08-20T17:35:20.000Z | codes/net/slimfly.h | minitu/codes | 1449aaf45e56fe41fedcd6b4a7f44787cb6f41ca | [
"BSD-3-Clause"
] | 18 | 2019-07-10T21:03:55.000Z | 2022-01-06T22:02:12.000Z | /*
* Copyright (C) 2014 University of Chicago.
* See COPYRIGHT notice in top-level directory.
*
*/
#ifndef SLIMFLY_H
#define SLIMFLY_H
#include <ross.h>
typedef struct slim_terminal_message slim_terminal_message;
/* this message is used for both dragonfly compute nodes and routers */
struct slim_terminal_message
{
/* magic number */
int magic;
/* flit travel start time*/
tw_stime travel_start_time;
/* packet ID of the flit */
unsigned long long packet_ID;
/* event type of the flit */
short type;
/* category: comes from codes */
char category[CATEGORY_NAME_MAX];
/* final destination LP ID, this comes from codes can be a server or any other LP type*/
tw_lpid final_dest_gid;
/*sending LP ID from CODES, can be a server or any other LP type */
tw_lpid sender_lp;
tw_lpid sender_mn_lp; // source modelnet id
/* destination terminal ID of the dragonfly */
tw_lpid dest_terminal_id;
/* source terminal ID of the dragonfly */
unsigned int src_terminal_id;
/* local LP ID to calculate the radix of the sender node/router */
unsigned int local_id;
/* message originating router id */
unsigned int origin_router_id;
/* number of hops traversed by the packet */
short my_N_hop;
short my_l_hop, my_g_hop;
short saved_channel;
/* Intermediate LP ID from which this message is coming */
unsigned int intm_lp_id;
short new_vc;
short saved_vc;
/* last hop of the message, can be a terminal, local router or global router */
short last_hop;
/* For routing */
int intm_group_id;
int intm_router_id;
uint64_t chunk_id;
uint64_t packet_size;
uint64_t message_id;
uint64_t total_size;
int saved_remote_esize;
int remote_event_size_bytes;
int local_event_size_bytes;
// For buffer message
short vc_index;
short rail_id;
int sender_radix;
int output_chan;
model_net_event_return event_rc;
int is_pull;
uint64_t pull_size;
/* for reverse computation */
short path_type;
tw_stime saved_available_time;
tw_stime saved_avg_time;
tw_stime saved_rcv_time;
tw_stime saved_busy_time;
tw_stime saved_total_time;
int saved_send_loop;
// tw_stime saved_credit_time;
// tw_stime saved_collective_init_time;
tw_stime saved_hist_start_time;
tw_stime msg_start_time;
int rng_calls; //counter for rng calls so they can be rolled back in a single loop
short saved_completed_chunks;
int saved_hist_num;
int saved_occupancy;
/* for reverse computation of a node's fan in*/
int saved_fan_nodes;
tw_lpid sender_svr;
/* LP ID of the sending node, has to be a network node in the dragonfly */
tw_lpid sender_node;
tw_lpid next_stop;
struct sfly_qhash_entry * saved_hash;
};
#endif /* end of include guard: DRAGONFLY_H */
/*
* Local variables:
* c-indent-level: 4
* c-basic-offset: 4
* End:
*
* vim: ft=c ts=8 sts=4 sw=4 expandtab
*/
| 25.596491 | 90 | 0.72207 |
e9c29ee645bc1e59ed09bb8c2b0b9cdee47247e4 | 2,101 | h | C | LEDA/incl/LEDA/internal/std/sgi_filebuf.h | 2ashish/smallest_enclosing_circle | 889916a3011ab2b649ab7f1fc1e042f879acecce | [
"MIT"
] | null | null | null | LEDA/incl/LEDA/internal/std/sgi_filebuf.h | 2ashish/smallest_enclosing_circle | 889916a3011ab2b649ab7f1fc1e042f879acecce | [
"MIT"
] | null | null | null | LEDA/incl/LEDA/internal/std/sgi_filebuf.h | 2ashish/smallest_enclosing_circle | 889916a3011ab2b649ab7f1fc1e042f879acecce | [
"MIT"
] | null | null | null | /*******************************************************************************
+
+ LEDA 6.3
+
+
+ sgi_filebuf.h
+
+
+ Copyright (c) 1995-2010
+ by Algorithmic Solutions Software GmbH
+ All rights reserved.
+
*******************************************************************************/
#ifndef _LEDA_SGI_FILEBUF_H_
#define _LEDA_SGI_FILEBUF_H_
#include <LEDA/internal/std/string.h>
/*
There is a bug in the filebuf implementation of SGI CC:
When we read until we reach an EOF, the class goes to an error state and
we cannot do seekoff/seekpos anymore (to rewind to the beginning).
Work-around:
We derive a class that stores the filename and reopens the file if a seek
operation fails.
Known problems:
- Since the open-method is not virtual, our method is bypassed if a
leda_filebuf* is converted to filebuf*.
- We cannot work-around a relative seekoff (i.e. way == ios_base::cur).
*/
class leda_filebuf : public filebuf {
public:
typedef filebuf base;
public:
leda_filebuf() : FileName(0) {}
virtual ~leda_filebuf() { assign_filename(0); }
leda_filebuf* open(const char* name, ios_base::openmode mode)
{ assign_filename(name); Mode = mode; base::open(name, mode); return this; }
protected:
virtual streampos seekoff(streamoff off, ios::seekdir way, ios_base::openmode which)
{
streampos res = base::seekoff(off, way, which);
if (res >= 0 || way == ios_base::cur) return res;
base::close(); base::open(FileName, Mode);
return base::seekoff(off, way, which);
}
virtual streampos seekpos(streampos sp, ios_base::openmode which)
{
streampos res = base::seekpos(sp, which);
if (res >= 0) return res;
base::close(); base::open(FileName, Mode);
return base::seekpos(sp, which);
}
private:
void assign_filename(const char* name)
{
delete FileName; FileName = 0;
if (name) { int n = strlen(name); FileName = new char[n]; strcpy(FileName, name); }
}
private:
char* FileName;
ios_base::openmode Mode;
};
#endif
// The following must be OUTSIDE the #ifndef / #endif
#undef filebuf
#define filebuf leda_filebuf
| 25.938272 | 85 | 0.645407 |
e9c3c0908f7e0482c81a678fdd21aff4dbc366ba | 897 | h | C | OpenCVFunc/Threshold.h | iryachi/OpenCV_test | eff56990897b44d07dce90695cef290901c3f502 | [
"BSD-3-Clause"
] | null | null | null | OpenCVFunc/Threshold.h | iryachi/OpenCV_test | eff56990897b44d07dce90695cef290901c3f502 | [
"BSD-3-Clause"
] | null | null | null | OpenCVFunc/Threshold.h | iryachi/OpenCV_test | eff56990897b44d07dce90695cef290901c3f502 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "FilterBase.h"
using namespace System;
using namespace System::Collections::Generic;
namespace OpenCVFunc {
public ref class Threshold : public FilterBase
{
// TODO: このクラスのメソッドをここに追加します。
public:
String^ threshold_exec(double thresh, double maxval, int type,int imageInNo, int imageOutNo)
{
cv::Mat* inImage = ImageMemManager::GetImage(imageInNo);
if (inImage == nullptr) { return "no input image"; }
cv::Mat* outImage = new cv::Mat();
cv::Mat dst = cv::Mat();
cv::Mat src = cv::Mat();
getImages(inImage, outImage, &src, &dst);
try {
cv::threshold(src, dst, thresh, maxval, type);
}
catch (...) {
inImage = NULL;
delete (outImage);
throw;
}
ImageMemManager::SetImage(outImage, imageOutNo);
String^ retStr = Util::GetInOutParam(inImage, outImage);
inImage = NULL;
return retStr;
}
};
}
| 20.386364 | 94 | 0.649944 |
e9ced6150fe4d8ea3a51bb477d62034b94d7ced1 | 213 | h | C | CollectionViewDemo/CollectionViewDemo/Util/UITableViewCell+Nib.h | ALittleNasty/CollectionViewDemo | 80f4da735a9c1cba2e39542b6f6c01c6ea6e6225 | [
"MIT"
] | null | null | null | CollectionViewDemo/CollectionViewDemo/Util/UITableViewCell+Nib.h | ALittleNasty/CollectionViewDemo | 80f4da735a9c1cba2e39542b6f6c01c6ea6e6225 | [
"MIT"
] | null | null | null | CollectionViewDemo/CollectionViewDemo/Util/UITableViewCell+Nib.h | ALittleNasty/CollectionViewDemo | 80f4da735a9c1cba2e39542b6f6c01c6ea6e6225 | [
"MIT"
] | null | null | null | //
// UITableViewCell+Nib.h
// StarCredit
//
// Created by 胡阳 on 16/3/21.
// Copyright © 2016年 VCredit. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UITableViewCell (Nib)
+ (UINib*)nib;
@end
| 13.3125 | 51 | 0.657277 |
d40864e6f88dcc6d4b7ddf2d4b47d4044d9ee83d | 949 | c | C | src/nth_psc.c | theoden8/matcalc | ff71e31d5aa854547b1f32280a83486e21a4e6a1 | [
"WTFPL"
] | null | null | null | src/nth_psc.c | theoden8/matcalc | ff71e31d5aa854547b1f32280a83486e21a4e6a1 | [
"WTFPL"
] | null | null | null | src/nth_psc.c | theoden8/matcalc | ff71e31d5aa854547b1f32280a83486e21a4e6a1 | [
"WTFPL"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
// nth_psc means nth row in the pascal triangle
//
// being a genius of math you do understand that this is a sequence of binomial
// coefficients c(n, 0..n)
//
// c(n, k) / c(n, k - 1) = (n - k) / (k + 1) or smth like that, whatever works
#define NPSC_SIZE(x) (((x) >> 1) + 1)
static void calc_nth_row(mpz_t num, int k, int n) {
if(k == NPSC_SIZE(n))
return;
mpz_t me;
mpz_init(me);
mpz_set(me, num);
gmp_printf("%Zd\n", me);
mpz_mul_ui(num, num, n - k);
mpz_fdiv_q_ui(num, num, k + 1);
calc_nth_row(num, k + 1, n);
if(!(k == NPSC_SIZE(n) - 1)|| n & 1)
gmp_printf("%Zd\n", me);
mpz_clear(me);
}
void calc_nth_psc(size_t n) {
mpz_t num;
mpz_init(num);
mpz_set_si(num, 1);
calc_nth_row(num, 0, n);
mpz_clear(num);
}
main(int argc, char *argv[]) {
if(argc != 2)
return EXIT_FAILURE;
int n = 0;
sscanf(argv[1], " %d", &n);
calc_nth_psc(n);
}
#undef NPSC_SIZE
| 18.25 | 79 | 0.615385 |
1d322db55e9d1bae47ebbdf1a2177863289a68fc | 1,935 | h | C | test/tests/LibcxxTester.h | asidorov95/momo | ebede4ba210ac1fa614bb2571a526e7591a92b56 | [
"MIT"
] | null | null | null | test/tests/LibcxxTester.h | asidorov95/momo | ebede4ba210ac1fa614bb2571a526e7591a92b56 | [
"MIT"
] | null | null | null | test/tests/LibcxxTester.h | asidorov95/momo | ebede4ba210ac1fa614bb2571a526e7591a92b56 | [
"MIT"
] | null | null | null | /**********************************************************\
This file is distributed under the MIT License.
See https://github.com/morzhovets/momo/blob/master/LICENSE
for details.
tests/LibcxxTester.h
\**********************************************************/
#pragma once
#include <iostream>
#include <cfloat>
#include <string>
#include <cmath>
#ifdef _MSC_VER
#if _MSC_VER == 1900 && !defined(_DEBUG)
#define LIBCPP_VS2015_RELEASE //?
#endif
#else
#if __cplusplus < 201402L
#define LIBCPP_HAS_NO_TRANSPARENT_OPERATORS
#endif
#endif
//#define LIBCPP_TEST_DEDUCTION_GUIDES
//#define LIBCPP_HAS_BAD_NEWS_FOR_MOMO
//#define LIBCPP_TEST_MIN_ALLOCATOR
#include "libcxx/support/MoveOnly.h"
#include "libcxx/support/Copyable.h"
#include "libcxx/support/NotConstructible.h"
#include "libcxx/support/DefaultOnly.h"
#include "libcxx/support/Emplaceable.h"
#include "libcxx/support/Counter.h"
#include "libcxx/support/Moveable.h"
#include "libcxx/support/stack_allocator.h"
#include "libcxx/support/test_allocator.h"
#include "libcxx/support/test_iterators.h"
#include "libcxx/support/test_compare.h"
#include "libcxx/support/test_hash.h"
#include "libcxx/support/private_constructor.h"
#include "libcxx/support/is_transparent.h"
#include "libcxx/support/test_macros.h"
//#include "libcxx/support/min_allocator.h"
struct LibcppIntHash
{
typedef int argument_type;
size_t operator()(int key) const noexcept
{
return static_cast<size_t>(key);
}
};
#define LIBCPP_CATCH(expr) try { (void)(expr); assert(false); } catch (...) {}
#define LIBCXX_TEST_BEGIN(name) \
namespace name { \
void main(); \
int TestLibcxx() \
{ \
std::cout << LIBCXX_TEST_PREFIX << "_" << #name << ": " << std::flush; \
main(); \
std::cout << "ok" << std::endl; \
return 0; \
} \
static int testLibcxx = (TestLibcxx(), 0);
#define LIBCXX_TEST_END }
| 24.493671 | 79 | 0.659948 |
0dea46560cc5ade623089a1be1d34717733ae594 | 7,701 | h | C | components/ssl_errors/error_classification.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/ssl_errors/error_classification.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/ssl_errors/error_classification.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // 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 COMPONENTS_SSL_ERRORS_ERROR_CLASSIFICATION_H_
#define COMPONENTS_SSL_ERRORS_ERROR_CLASSIFICATION_H_
#include <string>
#include <vector>
namespace base {
class Time;
}
class GURL;
namespace net {
class X509Certificate;
}
namespace network_time {
class NetworkTimeTracker;
}
namespace ssl_errors {
typedef std::vector<std::string> HostnameTokens;
// Methods for identifying specific error causes. ------------------------------
// These values are written to logs. New enum values can be added, but existing
// enums must never be renumbered or deleted and reused.
enum SSLInterstitialCause {
CLOCK_PAST = 0,
CLOCK_FUTURE = 1,
WWW_SUBDOMAIN_MATCH = 2, // Deprecated in M59.
SUBDOMAIN_MATCH = 3, // Deprecated in M59.
SUBDOMAIN_INVERSE_MATCH = 4, // Deprecated in M59.
SUBDOMAIN_OUTSIDE_WILDCARD = 5, // Deprecated in M59.
HOST_NAME_NOT_KNOWN_TLD = 6,
LIKELY_MULTI_TENANT_HOSTING = 7, // Deprecated in M59.
LOCALHOST = 8,
PRIVATE_URL = 9,
AUTHORITY_ERROR_CAPTIVE_PORTAL = 10, // Deprecated in M47.
SELF_SIGNED = 11,
EXPIRED_RECENTLY = 12,
LIKELY_SAME_DOMAIN = 13, // Deprecated in M59.
NO_SUBJECT_ALT_NAME = 14,
WWW_SUBDOMAIN_MATCH2 = 15,
SUBDOMAIN_MATCH2 = 16,
SUBDOMAIN_INVERSE_MATCH2 = 17,
SUBDOMAIN_OUTSIDE_WILDCARD2 = 18,
LIKELY_MULTI_TENANT_HOSTING2 = 19,
LIKELY_SAME_DOMAIN2 = 20,
SSL_INTERSTITIAL_CAUSE_MAX
};
// What is known about the accuracy of system clock. Do not change or
// reorder; these values are used in an UMA histogram.
enum ClockState {
// Not known whether system clock is close enough.
CLOCK_STATE_UNKNOWN,
// System clock is "close enough", per network time.
CLOCK_STATE_OK,
// System clock is behind.
CLOCK_STATE_PAST,
// System clock is ahead.
CLOCK_STATE_FUTURE,
CLOCK_STATE_MAX,
};
// Describes the result of getting network time and if it was
// unavailable, why it was unavailable. This enum is being histogrammed
// so do not reorder or remove values.
//
// Exposed for testing.
enum NetworkClockState {
// Value 0 was NETWORK_CLOCK_STATE_UNKNOWN_NO_SYNC, which is obsolete
// in favor of the finer-grained values below.
// The clock state relative to network time is unknown because the
// user's clock has fallen out of sync with the latest information
// from the network (due to e.g. suspend/resume).
NETWORK_CLOCK_STATE_UNKNOWN_SYNC_LOST = 1,
// The clock is "close enough" to the network time.
NETWORK_CLOCK_STATE_OK,
// The clock is in the past relative to network time.
NETWORK_CLOCK_STATE_CLOCK_IN_PAST,
// The clock is in the future relative to network time.
NETWORK_CLOCK_STATE_CLOCK_IN_FUTURE,
// The clock state relative to network time is unknown because no sync
// attempt has been made yet.
NETWORK_CLOCK_STATE_UNKNOWN_NO_SYNC_ATTEMPT,
// The clock state relative to network time is unknown because one or
// more sync attempts has failed.
NETWORK_CLOCK_STATE_UNKNOWN_NO_SUCCESSFUL_SYNC,
// The clock state relative to network time is unknown because the
// first sync attempt is still pending.
NETWORK_CLOCK_STATE_UNKNOWN_FIRST_SYNC_PENDING,
// The clock state relative to network time is unknown because one or
// more time query attempts have failed, and a subsequent sync attempt
// is still pending.
NETWORK_CLOCK_STATE_UNKNOWN_SUBSEQUENT_SYNC_PENDING,
NETWORK_CLOCK_STATE_MAX
};
// Compares |now_system| to the build time and to the current network time, and
// returns an inference about the state of the system clock. A result from
// network time, if available, will always be preferred to a result from the
// build time. Calling this function records UMA statistics: it's assumed that
// it's called in the course of handling an SSL error.
ClockState GetClockState(
const base::Time& now_system,
const network_time::NetworkTimeTracker* network_time_tracker);
// Returns true if |hostname| is too broad for the scope of a wildcard
// certificate. E.g.:
// a.b.example.com ~ *.example.com --> true
// b.example.com ~ *.example.com --> false
bool IsSubDomainOutsideWildcard(const GURL& request_url,
const net::X509Certificate& cert);
// Returns true if the certificate is a shared certificate. Note - This
// function should be used with caution (only for UMA histogram) as an
// attacker could easily get a certificate with more than 5 names in the SAN
// fields.
bool IsCertLikelyFromMultiTenantHosting(const GURL& request_url,
const net::X509Certificate& cert);
// Returns true if the hostname in |request_url_| has the same domain
// (effective TLD + 1 label) as at least one of the subject
// alternative names in |cert_|.
bool IsCertLikelyFromSameDomain(const GURL& request_url,
const net::X509Certificate& cert);
// Returns true if the site's hostname differs from one of the DNS names in
// |dns_names| only by the presence or absence of the single-label prefix "www".
// The matching name from the certificate is returned in |www_match_host_name|.
bool GetWWWSubDomainMatch(const GURL& request_url,
const std::vector<std::string>& dns_names,
std::string* www_match_host_name);
// Method for recording results. -----------------------------------------------
void RecordUMAStatistics(bool overridable,
const base::Time& current_time,
const GURL& request_url,
int cert_error,
const net::X509Certificate& cert);
// Specialization of |RecordUMAStatistics| to be used when the bad clock
// interstitial is shown. |cert_error| is required only for sanity-checking: it
// must always be |ssl_errors::ErrorInfo::CERT_DATE_INVALID|.
void RecordUMAStatisticsForClockInterstitial(bool overridable,
ssl_errors::ClockState clock_state,
int cert_error);
// Helper methods for classification. ------------------------------------------
// Tokenize DNS names and hostnames.
HostnameTokens Tokenize(const std::string& name);
// Sets a clock for browser tests that check the build time. Used by
// GetClockState().
void SetBuildTimeForTesting(const base::Time& testing_time);
// Returns true if the hostname has a known Top Level Domain.
bool HostNameHasKnownTLD(const std::string& host_name);
// Returns true if any one of the following conditions hold:
// 1.|hostname| is an IP Address in an IANA-reserved range.
// 2.|hostname| is a not-yet-assigned by ICANN gTLD.
// 3.|hostname| is a dotless domain.
bool IsHostnameNonUniqueOrDotless(const std::string& hostname);
// Returns true if |child| is a subdomain of any of the |potential_parents|.
bool NameUnderAnyNames(const HostnameTokens& child,
const std::vector<HostnameTokens>& potential_parents);
// Returns true if any of the |potential_children| is a subdomain of the
// |parent|. The inverse case should be treated carefully as this is most
// likely a MITM attack. We don't want foo.appspot.com to be able to MITM for
// appspot.com.
bool AnyNamesUnderName(const std::vector<HostnameTokens>& potential_children,
const HostnameTokens& parent);
// Exposed for teshting.
size_t GetLevenshteinDistance(const std::string& str1, const std::string& str2);
} // namespace ssl_errors
#endif // COMPONENTS_SSL_ERRORS_ERROR_CLASSIFICATION_H_
| 39.091371 | 80 | 0.714193 |
d4d6c3858fed26371c18301a1f1b45f013b66fac | 5,459 | h | C | src/bolusGUI/bolus.h | dreamshader/bolus | b63ae2e1821019f920cb8adeff373bafbb5e0008 | [
"Apache-2.0"
] | null | null | null | src/bolusGUI/bolus.h | dreamshader/bolus | b63ae2e1821019f920cb8adeff373bafbb5e0008 | [
"Apache-2.0"
] | null | null | null | src/bolusGUI/bolus.h | dreamshader/bolus | b63ae2e1821019f920cb8adeff373bafbb5e0008 | [
"Apache-2.0"
] | null | null | null | /*
***********************************************************************
*
* bolus.h - class for re/store settings
*
* Copyright (C) 2018 Dreamshader (aka Dirk Schanz)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***********************************************************************
*/
#ifndef _BOLUS_H_
#define _BOLUS_H_
#ifndef IS_FRONTEND // set by the GUI source
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <ctype.h>
#include "settings.h"
#include "datafile.h"
#endif // IS_FRONTEND
#ifdef __cplusplus
extern "C" {
#endif
using namespace std;
#ifndef IS_FRONTEND // set by the GUI source
#define W_BOLUS_IDLE 1
#define E_BOLUS_OK 0
#define E_BOLUS_SETTINGS -1
#define E_BOLUS_INIT -2
#define E_BOLUS_DATAFILE -3
#define E_BOLUS_CARB_N_BREAD -4
#define E_BOLUS_RUN_MODE -5
#define E_BOLUS_NULL -6
#define E_BOLUS_TIMEBLK -7
#define BOLUS_NO_MODE 0
#define BOLUS_IMPORT_MODE 1
#define BOLUS_EXPORT_MODE 2
#define BOLUS_INTERACTIVE_MODE 3
#define BOLUS_LIST_MODE 4
#define BOLUS_CALC_BREAD_MODE 5
#define BOLUS_CALC_CARB_MODE 6
#define BOLUS_EDIT_MODE 7
#define BOLUS_QUERY_MODE 8
#define BOLUS_CALIBRATE_MODE 9
#define SECONDS_A_MINUTE 60
#define SECONDS_A_HOUR (60 * SECONDS_A_MINUTE)
#define SECONDS_A_DAY (24 * SECONDS_A_HOUR)
#define BOLUS_FACTOR_CARB2BREAD 12
#define BOLUS_EDIT_CMD_AA 'a'
#define BOLUS_EDIT_CMD_BB 'b'
#define BOLUS_EDIT_CMD_ENDEDIT 'x'
#define BOLUS_EDIT_CMD_WRITE 'w'
#define BOLUS_EDIT_CMD_READ 'r'
#define BOLUS_EDIT_CMD_REJECT 'c'
#define BOLUS_EDIT_CMD_INVAL '!'
#define BOLUS_EDIT_CMD_HELP '?'
#define BOLUS_INTERACT_NONE '\0'
#define BOLUS_INTERACT_SKIP 's'
#define BOLUS_INTERACT_BACK 'b'
#define BOLUS_INTERACT_REJECT 'c'
#define BOLUS_INTERACT_INVAL '!'
#define BOLUS_INTERACT_HELP '?'
#define BOLUS_INTERACT_YES_DE 'j'
#define BOLUS_INTERACT_NO 'n'
#define BOLUS_INTERACT_YES_EN 'y'
#define BOLUS_INTERACT_U_YES_DE 'J'
#define BOLUS_INTERACT_U_NO 'N'
#define BOLUS_INTERACT_U_YES_EN 'Y'
#define BOLUS_FIELD_TIMESTAMP 0
#define BOLUS_FIELD_RECNUM 1
#define BOLUS_FIELD_GLUCOSE 2
#define BOLUS_FIELD_MEAL 3
#define BOLUS_FIELD_CARBON 4
#define BOLUS_FIELD_ADJUST 5
#define BOLUS_FIELD_UNITS 6
#define BOLUS_FIELD_BASALUNITS 7
#define BOLUS_FIELD_TYPE 8
#define BOLUS_FIELD_ACTUNITS 9
#define BOLUS_FIELD_ACTBASUNITS 10
#define BOLUS_FIELD_ASK_YESNO 11
#define BOLUS_COMMAND_BUFSIZE 128
#define BOLUS_DIALOG_BUFSIZE 128
#endif // IS_FRONTEND
struct _bolus_param {
bool fail;
int glucose;
int carb;
double bread;
char mealType;
char measType;
char adjustType;
int adjust;
bool last;
char editType;
char exportType;
char *importFile;
bool interactive;
bool noStore;
bool offset;
bool query;
int timeBlockNumber;
bool timeBlockCount;
bool calibrate;
int freestyleValue;
int acucheckValue;
bool qFactors;
bool qGlobals;
bool qBlocks;
};
#ifndef IS_FRONTEND // set by the GUI source
class bolus {
private:
bool initialized = false;
int mode = BOLUS_NO_MODE;
public:
settings *pSettings;
datafile *pDatafile;
struct _bolus_param callerArgs;
protected:
void dumpArgs( void );
void resetArgs( void );
void setArgs( struct _bolus_param *pParam );
int checkArgs( void );
int runImport( void );
int runExport( void );
int runInteractive( FILE *pIn, FILE *pOut );
int runListLast( void );
int runCalcBread( void );
int runCalcCarb( void );
int runEditor( void );
int runQuery( void );
int runCalibrate( void );
int calcBolus( int timeBlk, struct _record *pLastData, struct _record *pNewData );
public:
bolus( void ) {
callerArgs.importFile = NULL;
mode = BOLUS_NO_MODE;
};
~bolus( void ) {
if( pSettings != NULL )
{
pSettings->end();
delete pSettings;
}
if( pDatafile != NULL )
{
delete pDatafile;
}
if( callerArgs.importFile != NULL )
{
free( callerArgs.importFile );
callerArgs.importFile = NULL;
}
};
int init( struct _bolus_param *pParam );
int end( void );
int run( void );
int use( int year, int month );
int getMode( void ) {
return mode;
};
int countTimeBlocks( void );
};
#endif // IS_FRONTEND
#ifdef __cplusplus
}
#endif
#endif // _BOLUS_H_
| 24.926941 | 88 | 0.634548 |
d9becc404435cd692ac3da5671024af22c4e0466 | 1,033 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/RVASessionDelegateProtocol-Protocol.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/RVASessionDelegateProtocol-Protocol.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/RVASessionDelegateProtocol-Protocol.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-04-17T03:24:04.000Z | 2022-03-30T05:42:17.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import "NSObject-Protocol.h"
@class NSDictionary, RVASession, UIViewController;
@protocol RVASessionDelegateProtocol <NSObject>
- (UIViewController *)rootViewControllerInSession:(RVASession *)arg1;
@optional
- (_Bool)sessionShouldTerminate:(RVASession *)arg1;
- (_Bool)sessionShouldStart:(RVASession *)arg1 params:(NSDictionary *)arg2;
- (void)sessionWillTerminate:(RVASession *)arg1 animated:(_Bool)arg2;
- (void)session:(RVASession *)arg1 didResumeWithOptions:(NSDictionary *)arg2;
- (void)session:(RVASession *)arg1 willResumeWithOptions:(NSDictionary *)arg2;
- (void)sessionDidPause:(RVASession *)arg1;
- (void)sessionWillPause:(RVASession *)arg1;
- (void)sessionDidFinishLaunching:(RVASession *)arg1;
- (void)session:(RVASession *)arg1 willStartLaunchingWithOptions:(NSDictionary *)arg2;
- (void)sessionDidCreate:(RVASession *)arg1;
@end
| 38.259259 | 90 | 0.762827 |
8a536a514a3a86ab042b96b8237f4c46759f16d1 | 151 | h | C | src/stdint.h | UNIVERSAL-IT-SYSTEMS/LBW | f61138c8efba55d0dddb07f434f85f575c332a63 | [
"MIT"
] | 37 | 2015-10-05T06:50:47.000Z | 2022-03-29T08:55:01.000Z | src/stdint.h | davidgiven/LBW | f61138c8efba55d0dddb07f434f85f575c332a63 | [
"MIT"
] | null | null | null | src/stdint.h | davidgiven/LBW | f61138c8efba55d0dddb07f434f85f575c332a63 | [
"MIT"
] | 9 | 2016-05-01T09:27:20.000Z | 2022-02-05T17:19:00.000Z | /* © 2010 David Given.
* LBW is licensed under the MIT open source license. See the COPYING
* file in this distribution for the full text.
*/
| 25.166667 | 70 | 0.688742 |
e1f015474bb44fcd9eb902dc13b6ba2d038a9bff | 500 | h | C | src/common/random.h | varlosq/login | f69c6f40dd92ebaa51f09c56ab9ae534a391fabf | [
"Apache-2.0"
] | null | null | null | src/common/random.h | varlosq/login | f69c6f40dd92ebaa51f09c56ab9ae534a391fabf | [
"Apache-2.0"
] | null | null | null | src/common/random.h | varlosq/login | f69c6f40dd92ebaa51f09c56ab9ae534a391fabf | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
// For more information, see LICENCE in the main folder
#ifndef _RANDOM_H_
#define _RANDOM_H_
#include "../common/cbasetypes.h"
void rnd_init(void);
void rnd_seed(uint32);
uint32 rnd(void);// [0, UINT32_MAX]
uint32 rnd_roll(uint32 dice_faces);// [0, dice_faces)
int32 rnd_value(int32 min, int32 max);// [min, max]
double rnd_uniform(void);// [0.0, 1.0)
double rnd_uniform53(void);// [0.0, 1.0)
#endif /* _RANDOM_H_ */
| 26.315789 | 59 | 0.688 |
c084ef0730884629188944c104eea3e9ef180f2e | 660 | c | C | programme/number-triangle-pattern/number-triangle-pattern.c | NeelPatel31/codinasion | 8b2ba5e1cda65111ea1c438630c89a1ea2e8f2a9 | [
"MIT"
] | null | null | null | programme/number-triangle-pattern/number-triangle-pattern.c | NeelPatel31/codinasion | 8b2ba5e1cda65111ea1c438630c89a1ea2e8f2a9 | [
"MIT"
] | 4 | 2022-01-27T11:32:33.000Z | 2022-01-29T18:30:13.000Z | programme/number-triangle-pattern/number-triangle-pattern.c | NeelPatel31/codinasion | 8b2ba5e1cda65111ea1c438630c89a1ea2e8f2a9 | [
"MIT"
] | null | null | null | // Write a program to print number triangle pattern
#include <stdio.h>
void pattern(int a)
{
printf("Output :\n");
for (int i = 1; i <= a; i++)
{
int c = 1;
for (int k = a; k > i; k--)
{
printf(" ");
}
for (int j = 1; j <= 2 * i - 1; j++)
{
if (j < i)
{
printf("%d", c);
c++;
}
else
{
printf("%d", c);
c--;
}
}
printf("\n");
}
}
int main()
{
int a;
printf("Input : ");
scanf("%d", &a);
pattern(a);
return 0;
}
| 17.368421 | 51 | 0.310606 |
dcf059705164bcc6327214cea79114a2bcd0a791 | 457 | c | C | A05/test_ppm.c | brookejbarton/assignments | af583695e32cc451f5beb45fd6168de7017d335b | [
"MIT"
] | null | null | null | A05/test_ppm.c | brookejbarton/assignments | af583695e32cc451f5beb45fd6168de7017d335b | [
"MIT"
] | null | null | null | A05/test_ppm.c | brookejbarton/assignments | af583695e32cc451f5beb45fd6168de7017d335b | [
"MIT"
] | 1 | 2022-03-03T19:23:20.000Z | 2022-03-03T19:23:20.000Z | #include <stdio.h>
#include "read_ppm.h"
#include <stdlib.h>
int main(int argc, char** argv) {
struct ppm_pixel *pic;
int w = 0;
int h = 0;
pic = read_ppm(argv[1], &w, &h);
printf("Testing file %s: %d %d\n", argv[1], w, h);
for (int i = 0; i < h; i++){
for (int j = 0; j < w; j++){
printf("(%d, %d, %d) ", pic[i*w+j].red, pic[i*w+j].green, pic[i*w+j].blue);
}
printf("\n");
}
free(pic);
pic = NULL;
return 0;
}
| 17.576923 | 81 | 0.498906 |
722695864be07333792f792fb61055fdb97ff97f | 471 | h | C | Singleton/Registry/PrinterProvider.h | PacktPublishing/Creational-Design-Patterns-in-Modern-C-plus-plus | c18b99ac05b237b972092f693b11a728e70e680d | [
"MIT"
] | 3 | 2021-10-01T23:23:57.000Z | 2021-12-30T07:41:36.000Z | Singleton/Registry/PrinterProvider.h | PacktPublishing/Creational-Design-Patterns-in-Modern-C-plus-plus | c18b99ac05b237b972092f693b11a728e70e680d | [
"MIT"
] | null | null | null | Singleton/Registry/PrinterProvider.h | PacktPublishing/Creational-Design-Patterns-in-Modern-C-plus-plus | c18b99ac05b237b972092f693b11a728e70e680d | [
"MIT"
] | 4 | 2021-04-18T12:23:02.000Z | 2021-11-13T02:43:34.000Z | #pragma once
#include <mutex>
#include <unordered_map>
#include "Printer.h"
//Registry of singletons
//Multiton
class PrinterProvider
{
inline static std::mutex m_mtx ;
inline static std::unordered_map<std::string, Printer *> m_Printers{} ;
PrinterProvider() = default ;
public:
static void RegisterPrinter(const std::string &key, Printer *p) ;
static Printer * GetPrinterPtr(const std::string &key) ;
static Printer & GetPrinterRef(const std::string &key) ;
};
| 24.789474 | 72 | 0.738854 |
b8114f633778f34f29dcb3ce1ac59d56a54da643 | 1,075 | h | C | Classes/IntroScene/Layers/IntroScene_MainLayer.h | phuctm97/game-tap-tap-dash | 33380d0e2facdb6a42ac2ae42ccc171a12a3eb8b | [
"MIT"
] | null | null | null | Classes/IntroScene/Layers/IntroScene_MainLayer.h | phuctm97/game-tap-tap-dash | 33380d0e2facdb6a42ac2ae42ccc171a12a3eb8b | [
"MIT"
] | null | null | null | Classes/IntroScene/Layers/IntroScene_MainLayer.h | phuctm97/game-tap-tap-dash | 33380d0e2facdb6a42ac2ae42ccc171a12a3eb8b | [
"MIT"
] | 1 | 2021-05-23T06:15:07.000Z | 2021-05-23T06:15:07.000Z | #ifndef __INTRO_SCENE_MAIN_LAYER_H__
#define __INTRO_SCENE_MAIN_LAYER_H__
#include <cocos2d.h>
#include <ui/CocosGUI.h>
namespace IntroScene
{
class MainLayer : public cocos2d::Layer
{
private:
cocos2d::Sprite* _logo;
cocos2d::ui::Button* _btnStart;
cocos2d::Sprite* _background;
cocos2d::ui::CheckBox* _chkSound;
cocos2d::ui::Button* _btnFb;
cocos2d::LayerColor* _layer;
public:
MainLayer()
: _logo( nullptr ),
_btnStart( nullptr ),
_background( nullptr ),
_chkSound( nullptr ),
_btnFb( nullptr ),
_layer( nullptr ) {}
static MainLayer* create();
bool init() override;
void reset();
private:
bool initGraphics();
bool initEvents();
void onBtnStartClicked( cocos2d::Ref* pSender, cocos2d::ui::Widget::TouchEventType type );
void onBtnFbClicked( cocos2d::Ref* pSender, cocos2d::ui::Widget::TouchEventType type );
void onChkSoundClicked( cocos2d::Ref* pSender, cocos2d::ui::Widget::TouchEventType type );
void createLogoAnimation();
};
}
#endif //!__INTRO_SCENE_MAIN_LAYER_H__
| 21.5 | 92 | 0.694884 |
5060a8c40cef04b6982eb183ba85b6f8a26b2868 | 8,776 | c | C | SampleCode/StdDriver/SPI_HalfDuplex/main.c | OpenNuvoton/M2351BSP | 5e272d7a5980344c5e24de8a598d47f5e5a14e55 | [
"Apache-2.0"
] | 15 | 2018-09-12T01:28:05.000Z | 2021-04-06T23:29:15.000Z | SampleCode/StdDriver/SPI_HalfDuplex/main.c | OpenNuvoton/M2351BSP | 5e272d7a5980344c5e24de8a598d47f5e5a14e55 | [
"Apache-2.0"
] | 12 | 2018-10-08T14:28:52.000Z | 2021-02-07T18:06:53.000Z | SampleCode/StdDriver/SPI_HalfDuplex/main.c | OpenNuvoton/M2351BSP | 5e272d7a5980344c5e24de8a598d47f5e5a14e55 | [
"Apache-2.0"
] | 11 | 2019-01-17T16:05:19.000Z | 2022-01-21T08:59:42.000Z | /**************************************************************************//**
* @file main.c
* @version V3.00
* @brief
* Demonstrate SPI half-duplex mode.
* SPI0 will be configured as Master mode and SPI1 will be configured as Slave mode.
* Both SPI0 and SPI1 will be configured as half-duplex mode.
*
* @copyright (C) 2019 Nuvoton Technology Corp. All rights reserved.
******************************************************************************/
#include <stdio.h>
#include "NuMicro.h"
#define TEST_COUNT 4
static uint32_t s_au32DestinationData[TEST_COUNT];
static volatile uint32_t s_u32RxDataCount;
/* Function prototype declaration */
void SYS_Init(void);
void SPI_Init(void);
void SYS_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
/* Enable HIRC clock */
CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN_Msk);
/* Waiting for HIRC clock ready */
CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk);
/* Select HCLK clock source as HIRC and HCLK source divider as 1 */
CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV0_HCLK(1));
/* Enable HXT clock */
CLK_EnableXtalRC(CLK_PWRCTL_HXTEN_Msk);
/* Wait for HXT clock ready */
CLK_WaitClockReady(CLK_STATUS_HXTSTB_Msk);
/* Enable PLL */
CLK->PLLCTL = CLK_PLLCTL_128MHz_HIRC;
/* Waiting for PLL stable */
CLK_WaitClockReady(CLK_STATUS_PLLSTB_Msk);
/* Select HCLK clock source as PLL and HCLK source divider as 2 */
CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_PLL, CLK_CLKDIV0_HCLK(2));
/* Select UART module clock source as HXT and UART module clock divider as 1 */
CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UART0SEL_HXT, CLK_CLKDIV0_UART0(1));
/* Select PCLK as the clock source of SPI0 and SPI1 */
CLK_SetModuleClock(SPI0_MODULE, CLK_CLKSEL2_SPI0SEL_PCLK1, MODULE_NoMsk);
CLK_SetModuleClock(SPI1_MODULE, CLK_CLKSEL2_SPI1SEL_PCLK0, MODULE_NoMsk);
/* Enable UART peripheral clock */
CLK_EnableModuleClock(UART0_MODULE);
/* Enable SPI0 peripheral clock */
CLK_EnableModuleClock(SPI0_MODULE);
/* Enable SPI1 peripheral clock */
CLK_EnableModuleClock(SPI1_MODULE);
/* Update System Core Clock */
/* User can use SystemCoreClockUpdate() to calculate SystemCoreClock and CyclesPerUs automatically. */
SystemCoreClockUpdate();
/*---------------------------------------------------------------------------------------------------------*/
/* Init I/O Multi-function */
/*---------------------------------------------------------------------------------------------------------*/
/* Set multi-function pins for UART0 RXD and TXD */
SYS->GPB_MFPH = (SYS->GPB_MFPH & (~(UART0_RXD_PB12_Msk | UART0_TXD_PB13_Msk))) | UART0_RXD_PB12 | UART0_TXD_PB13;
/* Configure SPI0 related multi-function pins. GPD[3,2,0] : SPI1_SS, SPI1_CLK, SPI1_MOSI. */
SYS->GPD_MFPL &= ~(SYS_GPD_MFPL_PD3MFP_Msk | SYS_GPD_MFPL_PD2MFP_Msk | SYS_GPD_MFPL_PD0MFP_Msk);
SYS->GPD_MFPL |= (SYS_GPD_MFPL_PD3MFP_SPI0_SS | SYS_GPD_MFPL_PD2MFP_SPI0_CLK | SYS_GPD_MFPL_PD0MFP_SPI0_MOSI);
/* Configure SPI1 related multi-function pins. GPH[7:5] : SPI1_SS, SPI1_CLK, SPI1_MOSI. */
SYS->GPH_MFPL &= ~(SYS_GPH_MFPL_PH7MFP_Msk | SYS_GPH_MFPL_PH6MFP_Msk | SYS_GPH_MFPL_PH5MFP_Msk);
SYS->GPH_MFPL |= (SYS_GPH_MFPL_PH7MFP_SPI1_SS | SYS_GPH_MFPL_PH6MFP_SPI1_CLK | SYS_GPH_MFPL_PH5MFP_SPI1_MOSI);
}
void SPI_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init SPI */
/*---------------------------------------------------------------------------------------------------------*/
/* Configure as a master, clock idle low, 32-bit transaction, drive output on falling clock edge and latch input on rising edge. */
/* Set IP clock divider. SPI clock rate = 2MHz */
SPI_Open(SPI0, SPI_MASTER, SPI_MODE_0, 32, 2000000);
/* Enable the automatic hardware slave select function. Select the SS pin and configure as low-active. */
SPI_EnableAutoSS(SPI0, SPI_SS, SPI_SS_ACTIVE_LOW);
/* Configure SPI1 */
/* Configure SPI1 as a slave, clock idle low, 32-bit transaction, drive output on falling clock edge and latch input on rising edge. */
/* Configure SPI1 as a low level active device. SPI peripheral clock rate = f_PCLK0 */
SPI_Open(SPI1, SPI_SLAVE, SPI_MODE_0, 32, (uint32_t)NULL);
}
int main(void)
{
uint32_t u32DataCount;
/* Unlock protected registers */
SYS_UnlockReg();
/* Init System, IP clock and multi-function I/O. */
SYS_Init();
/* Configure UART0: 115200, 8-bit word, no parity bit, 1 stop bit. */
UART_Open(UART0, 115200);
/* Init SPI */
SPI_Init();
printf("\n\n");
printf("+----------------------------------------------------------------------+\n");
printf("| SPI Half-duplex Mode Sample Code |\n");
printf("+----------------------------------------------------------------------+\n");
printf("\n");
printf("Configure SPI0 as a master and SPI1 as a slave.\n");
printf("Set both SPI0 and SPI1 to half-duplex.\n");
printf("Bit length of a transaction: 32\n");
printf("Please connect below I/O connections for SPI0 and SPI1:\n");
printf(" SPI0_SS(PD3) <-> SPI1_SS(PH7)\n");
printf(" SPI0_CLK(PD2) <-> SPI1_CLK(PH6)\n");
printf(" SPI0_MOSI(PD0) <-> SPI1_MOSI(PH5)\n\n");
printf("After the transfer is done, the received data will be printed out.\n");
/* Set slave SPI1 to half-duplex mode */
SPI1->CTL |= SPI_CTL_HALFDPX_Msk;
/* Enable half-duplex will produce TXFBCLR (SPIx_FIFOCTL[9]) and RXFBCLR (SPIx_FIFOCTL[8])*/
while(SPI1->STATUS & SPI_STATUS_TXRXRST_Msk) {}
/* Set slave SPI1 data direction to output */
SPI1->CTL |= SPI_CTL_DATDIR_Msk;
/* Slave SPI1 prepare data to TX FIFO */
SPI_WRITE_TX(SPI1, 0x55AA0000);
SPI_WRITE_TX(SPI1, 0x55AA0001);
SPI_WRITE_TX(SPI1, 0x55AA0002);
SPI_WRITE_TX(SPI1, 0x55AA0003);
/* Set master SPI0 to half-duplex mode */
SPI0->CTL |= SPI_CTL_HALFDPX_Msk;
/* Enable half-duplex will produce TXFBCLR (SPIx_FIFOCTL[9]) and RXFBCLR (SPIx_FIFOCTL[8])*/
while(SPI0->STATUS & SPI_STATUS_TXRXRST_Msk) {}
/* Set master SPI0 data direction to input */
SPI0->CTL &= ~SPI_CTL_DATDIR_Msk;
/* Master SPI0 receive four data from slave SPI1 */
for(s_u32RxDataCount = 0; s_u32RxDataCount < 4; s_u32RxDataCount++)
{
/* Master write TX for generating clock */
SPI_WRITE_TX(SPI0, 0);
/* Wait for Rx FIFO not empty */
while(SPI_GET_RX_FIFO_EMPTY_FLAG(SPI0)) {}
/* Read data from RX register */
s_au32DestinationData[s_u32RxDataCount] = SPI_READ_RX(SPI0);
}
/* Print the received data */
printf("SPI0 Received data:\n");
for(u32DataCount = 0; u32DataCount < TEST_COUNT; u32DataCount++)
{
printf("%d:\t0x%X\n", u32DataCount, s_au32DestinationData[u32DataCount]);
}
/* Reset slave RX related flags. */
SPI1->FIFOCTL |= SPI_FIFOCTL_RXRST_Msk;
/* Set master SPI0 data direction to output */
SPI0->CTL |= SPI_CTL_DATDIR_Msk;
/* Set slave SPI1 data direction to input */
SPI1->CTL &= ~SPI_CTL_DATDIR_Msk;
/* Master SPI0 prepare data to TX FIFO */
SPI_WRITE_TX(SPI0, 0xAA550000);
SPI_WRITE_TX(SPI0, 0xAA550001);
SPI_WRITE_TX(SPI0, 0xAA550002);
SPI_WRITE_TX(SPI0, 0xAA550003);
/* Slave SPI1 receive four data from master SPI0 */
for(s_u32RxDataCount = 0; s_u32RxDataCount < 4; s_u32RxDataCount++)
{
/* Wait for Rx FIFO not empty */
while(SPI_GET_RX_FIFO_EMPTY_FLAG(SPI1)) {}
/* Read data from RX register */
s_au32DestinationData[s_u32RxDataCount] = SPI_READ_RX(SPI1);
}
/* Print the received data */
printf("SPI1 Received data:\n");
for(u32DataCount = 0; u32DataCount < TEST_COUNT; u32DataCount++)
{
printf("%d:\t0x%X\n", u32DataCount, s_au32DestinationData[u32DataCount]);
}
printf("The data transfer was done.\n");
printf("\n\nExit SPI driver sample code.\n");
/* Reset SPI0 */
SPI_Close(SPI0);
/* Reset SPI1 */
SPI_Close(SPI1);
while(1);
}
/*** (C) COPYRIGHT 2019 Nuvoton Technology Corp. ***/
| 40.818605 | 139 | 0.583067 |
92f1f0686275a794d51f7b401259c1c130d99148 | 2,598 | h | C | examples/semaphores/kernel/deployment.h | tsfdssm/pok | f15d386d0d5a48bdb2d24aa34e45f6237cfee058 | [
"BSD-2-Clause"
] | 1 | 2019-12-05T10:15:54.000Z | 2019-12-05T10:15:54.000Z | examples/semaphores/kernel/deployment.h | tsfdssm/pok | f15d386d0d5a48bdb2d24aa34e45f6237cfee058 | [
"BSD-2-Clause"
] | null | null | null | examples/semaphores/kernel/deployment.h | tsfdssm/pok | f15d386d0d5a48bdb2d24aa34e45f6237cfee058 | [
"BSD-2-Clause"
] | null | null | null | /*
* POK header
*
* The following file is a part of the POK project. Any modification should
* made according to the POK licence. You CANNOT use this file or a part of
* this file is this part of a file for your own project
*
* For more information on the POK licence, please see our LICENCE FILE
*
* Please follow the coding guidelines described in doc/CODING_GUIDELINES
*
* Copyright (c) 2007-2009 POK team
*
* Created by julien on Thu Jan 15 23:34:13 2009
*/
#ifndef __POK_KERNEL_GENERATED_DEPLOYMENT_H_
#define __POK_KERNEL_GENERATED_DEPLOYMENT_H_
#define POK_NEEEDS_DEBUG 1
#define POK_NEEDS_THREADS 1
#define POK_NEEDS_PARTITIONS 1
#define POK_NEEDS_SCHED 1
#define POK_NEEDS_TIME 1
#define POK_NEEDS_DEBUG 1
#define POK_NEEDS_CONSOLE 1
#define POK_NEEDS_LOCKOBJECTS 1
#define POK_NEEDS_FUNCTION_TIME_GET 1
//TODO add a marco to enable edf
#define POK_NEEDS_SCHED_EDF 1
//#define POK_NEEDS_SCHED_FIFO 1
#define POK_NEEDS_GETTICK
//TODO setup scheduler of wach partition
#define POK_CONFIG_PARTITIONS_SCHEDULER {POK_SCHED_EDF,POK_SCHED_EDF}
//#define POK_CONFIG_PARTITIONS_SCHEDULER {POK_SCHED_FIFO,POK_SCHED_FIFO}
#define POK_CONFIG_NB_THREADS 7
// the num of lock objects for each partition
#define POK_CONFIG_NB_LOCKOBJECTS 1
#define POK_CONFIG_NB_PARTITIONS 2
#define POK_CONFIG_PARTITIONS_SIZE {120 * 1024, 120 * 1024};
#define POK_CONFIG_PROGRAM_NAME {"pr1/pr1.elf", "pr2/pr2.elf"};
//the size of each slot
#define POK_CONFIG_SCHEDULING_SLOTS {600000, 600000, 600000, 600000}
//time when scheduling slots are repeated
#define POK_CONFIG_SCHEDULING_MAJOR_FRAME 2400000
//specified which partition is scheduling at which slot
#define POK_CONFIG_SCHEDULING_SLOTS_ALLOCATION \
{ \
0, 1, 0, 1 \
}
#define POK_CONFIG_SCHEDULING_NBSLOTS 4
#define POK_NEEDS_THREAD_SUSPEND 1
#define POK_NEEDS_THREAD_SLEEP 1
#define POK_CONFIG_PARTITIONS_NTHREADS \
{ \
3, 2 \
}
#define POK_CONFIG_PARTITIONS_NLOCKOBJECTS \
{ \
1, 0 \
}
typedef enum
{
pok_part_identifier_pr1 = 0,
pok_part_identifier_pr2 = 1
} pok_part_identifiers_t;
typedef enum
{
pok_part_id_pr1 = 0,
pok_part_id_pr2 = 1
} pok_part_id_t;
typedef enum
{
pok_nodes_node1 = 0
} pok_node_id_t;
#endif
| 28.549451 | 76 | 0.669746 |
dd8ca2dd468331dc68b0332cc28261363eb0e3f1 | 700 | h | C | XbeeAddress.h | dlmulder/xbeepp_NetBeans | da6c2ba65ccb9b56899c855df7b00bd6c1a79492 | [
"Apache-2.0"
] | 3 | 2017-04-14T01:36:25.000Z | 2017-09-20T01:52:50.000Z | XbeeAddress.h | dlmulder/xbeepp_NetBeans | da6c2ba65ccb9b56899c855df7b00bd6c1a79492 | [
"Apache-2.0"
] | null | null | null | XbeeAddress.h | dlmulder/xbeepp_NetBeans | da6c2ba65ccb9b56899c855df7b00bd6c1a79492 | [
"Apache-2.0"
] | 2 | 2018-05-27T20:58:42.000Z | 2020-07-02T12:51:03.000Z | #ifndef XBEEADDRESS_H
#define XBEEADDRESS_H
#define HEXBASE "0123456789abcdef"
#include <inttypes.h>
#include <string>
class XbeeAddress
{
public:
XbeeAddress();
XbeeAddress(uint32_t hi, uint32_t lo, uint16_t net);
bool operator == (const XbeeAddress &Ref) const;
std::string toString();
void setAddress(const uint32_t hi, const uint32_t lo, const uint16_t net);
void getAddress64(uint8_t *addr_buf);
uint64_t getAddressLong() { return addr64; }
void getAddressNet(uint8_t *addr_buf);
virtual ~XbeeAddress();
protected:
private:
uint64_t addr64;
uint16_t netAddr;
};
#endif // XBEEADDRESS_H
| 21.212121 | 82 | 0.66 |
2d56ac5120d200cb165fe8b523430a8e80066ad3 | 228 | h | C | yt/frontends/artio/artio_headers/artio_mpi.h | kastalpes/yt | b1e197ca84433fbd61eaf44b28ff5cdb37981d4c | [
"BSD-3-Clause-Clear"
] | 360 | 2017-04-24T05:06:04.000Z | 2022-03-31T10:47:07.000Z | yt/frontends/artio/artio_headers/artio_mpi.h | kastalpes/yt | b1e197ca84433fbd61eaf44b28ff5cdb37981d4c | [
"BSD-3-Clause-Clear"
] | 2,077 | 2017-04-20T20:36:07.000Z | 2022-03-31T16:39:43.000Z | yt/frontends/artio/artio_headers/artio_mpi.h | stonnes/yt | aad3cfa3b4ebab7838352ab467275a27c26ff363 | [
"BSD-3-Clause-Clear"
] | 257 | 2017-04-19T20:52:28.000Z | 2022-03-29T12:23:52.000Z | /*
* artio_mpi.h
*
* Created on: Mar 6, 2012
* Author: Nick Gnedin
*/
#ifndef __ARTIO_MPI_H__
#define __ARTIO_MPI_H__
#include <mpi.h>
struct artio_context_struct {
MPI_Comm comm;
};
#endif /* __ARTIO_MPI_H__ */
| 12.666667 | 29 | 0.675439 |
4026d015255cbf250b4fdf7fc9e5022f5107e18f | 1,073 | h | C | System/Library/PrivateFrameworks/AXMediaUtilities.framework/AXMText.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | System/Library/PrivateFrameworks/AXMediaUtilities.framework/AXMText.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/AXMediaUtilities.framework/AXMText.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:42:01 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/AXMediaUtilities.framework/AXMediaUtilities
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <AXMediaUtilities/AXMediaUtilities-Structs.h>
@class NSString;
@interface AXMText : NSObject {
NSString* _text;
double _confidence;
CGRect _boundingBox;
}
@property (nonatomic,retain) NSString * text; //@synthesize text=_text - In the implementation block
@property (assign,nonatomic) CGRect boundingBox; //@synthesize boundingBox=_boundingBox - In the implementation block
@property (assign,nonatomic) double confidence; //@synthesize confidence=_confidence - In the implementation block
-(double)confidence;
-(NSString *)text;
-(void)setBoundingBox:(CGRect)arg1 ;
-(void)setText:(NSString *)arg1 ;
-(CGRect)boundingBox;
-(void)setConfidence:(double)arg1 ;
@end
| 33.53125 | 130 | 0.744641 |
4cf64532bf2d6916c3fd16c8310f81311491b2e9 | 227 | h | C | samples/gl/Camerz.h | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | 6 | 2019-01-25T08:41:14.000Z | 2021-08-22T07:06:11.000Z | samples/gl/Camerz.h | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | null | null | null | samples/gl/Camerz.h | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | 3 | 2019-01-25T08:41:16.000Z | 2020-09-04T06:04:29.000Z | //
// Created by huangkun on 02/04/2018.
//
#ifndef GL_CAMERZ_H
#define GL_CAMERZ_H
#include "CustomDraw.h"
TEST_NODE_BEGIN(Camerz)
protected:
unsigned int texture2;
TEST_NODE_END(Camerz)
#endif //GL_CAMERZ_H
| 12.611111 | 37 | 0.718062 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.