max_stars_repo_path
stringlengths
2
976
max_stars_repo_name
stringlengths
5
109
max_stars_count
float64
0
191k
id
stringlengths
1
7
content
stringlengths
1
11.6M
score
float64
-0.83
3.86
int_score
int64
0
4
GenHid_07/Src/App/DkHID.h
prikarna/nano-codes-blog
0
7999483
#pragma once #define HID_TGT_VID 0x6A16 #define HID_TGT_PID 0x0143 #define DK_HID_MAX_BUF 2048 #include "TChar.h" #include "Windows.h" #include "SetupApi.h" #include "ObjBase.h" extern "C" { typedef struct _HIDD_ATTRIBUTES { ULONG Size; USHORT VendorID; USHORT ProductID; USHORT VersionNumber; } HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES; typedef struct _HIDP_PREPARSED_DATA * PHIDP_PREPARSED_DATA; typedef struct _HIDP_CAPS { USHORT Usage; USHORT UsagePage; USHORT InputReportByteLength; USHORT OutputReportByteLength; USHORT FeatureReportByteLength; USHORT Reserved[17]; USHORT NumberLinkCollectionNodes; USHORT NumberInputButtonCaps; USHORT NumberInputValueCaps; USHORT NumberInputDataIndices; USHORT NumberOutputButtonCaps; USHORT NumberOutputValueCaps; USHORT NumberOutputDataIndices; USHORT NumberFeatureButtonCaps; USHORT NumberFeatureValueCaps; USHORT NumberFeatureDataIndices; } HIDP_CAPS, *PHIDP_CAPS; void __stdcall HidD_GetHidGuid(OUT LPGUID HidGuid); BOOLEAN __stdcall HidD_GetAttributes(IN HANDLE HidDeviceObject, OUT PHIDD_ATTRIBUTES Attributes); BOOLEAN __stdcall HidD_GetPreparsedData(IN HANDLE HidDeviceObject, OUT PHIDP_PREPARSED_DATA *PreparsedData); BOOLEAN __stdcall HidD_FreePreparsedData(IN PHIDP_PREPARSED_DATA PreparsedData); NTSTATUS __stdcall HidP_GetCaps(IN PHIDP_PREPARSED_DATA PreparsedData, OUT PHIDP_CAPS Capabilities); BOOLEAN __stdcall HidD_GetProductString(IN HANDLE HidDeviceObject, OUT PVOID Buffer, IN ULONG BufferLength); BOOLEAN __stdcall HidD_GetManufacturerString(IN HANDLE HidDeviceObject, OUT PVOID Buffer, IN ULONG BufferLength); BOOLEAN __stdcall HidD_GetSerialNumberString(IN HANDLE HidDeviceObject, OUT PVOID Buffer, IN ULONG BufferLength); BOOLEAN __stdcall HidD_SetOutputReport(IN HANDLE HidDeviceObject, IN PVOID ReportBuffer, IN ULONG ReportBufferLength); BOOLEAN __stdcall HidD_GetInputReport(IN HANDLE HidDeviceObject, IN OUT PVOID ReportBuffer, IN ULONG ReportBufferLength); } #pragma comment(lib, "setupapi.lib") #pragma comment(lib, "hid.lib") class CDkHID { private: HANDLE _hHid; PHIDP_PREPARSED_DATA _pPrepDat; public: CDkHID(void); ~CDkHID(void); bool Open(); bool Open(unsigned short uVendId, unsigned short uProdId); void Close(); bool GetAttributes(PHIDD_ATTRIBUTES pHidAttr); bool GetDevCaps(PHIDP_CAPS pHidCaps); bool WriteReport(LPVOID pDat, ULONG uByteDatLen); bool ReadReport(LPVOID pDat, ULONG uButeDatLen); };
0.890625
1
src/materialsystem/shaderapidx9/wmi.h
DeadZoneLuna/csso-src
4
7999491
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #ifndef WMI_H #define WMI_H #ifdef _WIN32 #pragma once #endif uint64 GetVidMemBytes( void ); #endif // WMI_H
0.863281
1
deepstream/nvmsgconv/nvmsgconv.h
CMofjeld/Smart-Feeder
2
7999499
/* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * NVIDIA Corporation and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA Corporation is strictly prohibited. * */ /** * @file * <b>NVIDIA DeepStream: Message Schema Generation Library Interface</b> * * @b Description: This file specifies the NVIDIA DeepStream message schema generation * library interface. */ #ifndef NVMSGCONV_H_ #define NVMSGCONV_H_ #include "nvdsmeta_schema.h" #include <glib.h> #ifdef __cplusplus extern "C" { #endif /** * @ref NvDsMsg2pCtx is structure for library context. */ typedef struct NvDsMsg2pCtx { /** type of payload to be generated. */ NvDsPayloadType payloadType; /** private to component. Don't change this field. */ gpointer privData; } NvDsMsg2pCtx; /** * This function initializes the library with user defined options mentioned * in the file and returns the handle to the context. * Static fields which should be part of message payload can be added to * file instead of frame metadata. * * @param[in] file name of file to read static properties from. * @param[in] type type of payload to be generated. * * @return pointer to library context created. This context should be used in * other functions of library and should be freed with * @ref nvds_msg2p_ctx_destroy */ NvDsMsg2pCtx* nvds_msg2p_ctx_create (const gchar *file, NvDsPayloadType type); /** * Release the resources allocated during context creation. * * @param[in] ctx pointer to library context. */ void nvds_msg2p_ctx_destroy (NvDsMsg2pCtx *ctx); /** * This function will parse the @ref NvDsEventMsgMeta and will generate message * payload. Payload will be combination of static values read from * configuration file and dynamic values received in meta. * Payload will be generated based on the @ref NvDsPayloadType type provided * in context creation (e.g. Deepstream, Custom etc.). * * @param[in] ctx pointer to library context. * @param[in] events pointer to array of event objects. * @param[in] size number of objects in array. * * @return pointer to @ref NvDsPayload generated or NULL in case of error. * This payload should be freed with @ref nvds_msg2p_release */ NvDsPayload* nvds_msg2p_generate (NvDsMsg2pCtx *ctx, NvDsEvent *events, guint size); /** * This function will parse the @ref NvDsEventMsgMeta and will generate multiple * message payloads. Payloads will be combination of static values read from * configuration file and dynamic values received in meta. * Payloads will be generated based on the @ref NvDsPayloadType type provided * in context creation (e.g. Deepstream, Custom etc.). * * @param[in] ctx pointer to library context. * @param[in] events pointer to array of event objects. * @param[in] size number of objects in array. * @param[out] payloadCount number of payloads being returned by the function. * * @return pointer to @ref array of NvDsPayload pointers generated or NULL in * case of error. The number of payloads in the array is returned through * payloadCount. This pointer should be freed by calling g_free() and the * individual payloads should be freed with @ref nvds_msg2p_release */ NvDsPayload** nvds_msg2p_generate_multiple (NvDsMsg2pCtx *ctx, NvDsEvent *events, guint size, guint *payloadCount); /** * This function should be called to release memory allocated for payload. * * @param[in] ctx pointer to library context. * @param[in] payload pointer to object that needs to be released. */ void nvds_msg2p_release (NvDsMsg2pCtx *ctx, NvDsPayload *payload); #ifdef __cplusplus } #endif #endif /* NVMSGCONV_H_ */
1.023438
1
mechanics/src/hooks/PaintTraverse.h
robindittmar/mechanics
0
7999507
#ifndef __PAINTTRAVERSE_H__ #define __PAINTTRAVERSE_H__ struct PaintTraverseParam { unsigned int vguiPanel; bool forceRepaint; bool allowForce; }; typedef void(__thiscall *PaintTraverse_t)(void*, unsigned int, bool, bool); extern PaintTraverse_t g_pPaintTraverse; void __fastcall hk_PaintTraverse(void* ecx, void* edx, unsigned int vguiPanel, bool forceRepaint, bool allowForce); #endif // __PAINTTRAVERSE_H__
0.416016
0
laboratories/lab-08/examples/mpi_hello.c
mateibarbu19/parallel-and-distributed-algorithms
3
7999515
#include "mpi.h" #include <stdio.h> #include <stdlib.h> #define MASTER 0 int main(int argc, char *argv[]) { int numtasks, rank, len; char hostname[MPI_MAX_PROCESSOR_NAME]; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numtasks); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Get_processor_name(hostname, &len); if (rank == MASTER) { printf("MASTER: Number of MPI tasks is: %d\n", numtasks); printf("HOSTNAME: %s\n", hostname); } else { printf("WORKER: Rank: %d\n", rank); } MPI_Finalize(); return 0; }
1.648438
2
tools/captionparser/libaribb24captions/tests/pts/ptstest.c
jeeb/tsanalyzer
0
7999523
#include <stdio.h> #include <stdlib.h> #include <stdint.h> int main(int argc, char** argv){ //uint8_t pts[] = { 0x27,0x4E,0xDF,0xB5,0x7F }; //uint8_t pts[] = { 0x27, 0x4E, 0xE1, 0x07, 0x99}; uint8_t pts[] = { 0x27,0x4E,0xA3,0x83, 0x1B}; parsePTStoString(pts); return 0; }
1.242188
1
mwc/romana/relic/a/usr/bob/uusrc/src/uulog.c
gspu/Coherent
20
7999531
/* * uulog.c * * Dump the UUCP uucico or uuxqt log files. */ #include "dcp.h" #define LOGSDIR ".Log" char logdir[LOGFLEN]; char command[BUFSIZ]; char *sysname = NULL; char *process = "uucico"; int fflag = 0; int tailnum = 0; extern int optind; extern int optopt; extern char *optarg; main(argc, argv) int argc; char *argv[]; { int ch, exstat=0; while ( (ch=getopt(argc, argv, "f:n:vVx")) != EOF ) { switch (ch) { case 'f': fflag = 1; sysname = optarg; break; case 'n': tailnum = atoi(optarg); break; case 'x': process = "uuxqt"; break; case 'v': case 'V': fatal("uulog: Version %s", VERSION); case '?': default: usage("Improper option usage: %c", optopt); } } sprintf(logdir, "%s/%s/%s", SPOOLDIR, LOGSDIR, process); if ( fflag ) { if ( optind < argc ) usage("only one system with -f flag"); if ( tailnum > 0 ) sprintf(command, "tail -%df %s/%s", tailnum, logdir, sysname); else sprintf(command, "tail -f %s/%s", logdir, sysname); exit( system(command) ); } if ( optind >= argc ) { if ( tailnum > 0 ) sprintf(command, "for zz in `uuname`; do \ tail -%d %s/$zz; done", tailnum, logdir); else sprintf(command, "for zz in `uuname`; do \ cat %s/$zz; done", logdir); exit( system(command) ); } for (;optind<argc; optind++) { if ( tailnum > 0 ) sprintf(command, "tail -%d %s/%s", tailnum, logdir, argv[optind]); else sprintf(command, "cat %s/%s", logdir, argv[optind]); exstat |= system(command); } exit(exstat); } usage(x) { fatal("\n%r\n\ Usage: uulog [ -n <tail-numlines> ] [ -x ] [ -f <sys> ]\n\ uulog [ -n <tail-numlines> ] [ -x ] [ system ... ]\n\ ", &x); }
1.390625
1
texture.h
chl9797/EmbeddedDeformation
3
7999539
/******************************************************************* ** This code is part of Breakout. ** ** Breakout is free software: you can redistribute it and/or modify ** it under the terms of the CC BY 4.0 license as published by ** Creative Commons, either version 4 of the License, or (at your ** option) any later version. ******************************************************************/ #ifndef TEXTURE_H #define TEXTURE_H #include <GL/glew.h> // Texture2D is able to store and configure a texture in OpenGL. // It also hosts utility functions for easy management. class Texture2D { public: // Holds the ID of the texture object, used for all texture operations to reference to this particular texture GLuint ID; GLuint Index; // Texture image dimensions GLuint Width, Height; // Width and height of loaded image in pixels // Texture Format GLint Internal_Format; // Format of texture object GLuint Image_Format; // Format of loaded image // Texture configuration GLuint Wrap_S; // Wrapping mode on S axis GLuint Wrap_T; // Wrapping mode on T axis GLuint Filter_Min; // Filtering mode if texture pixels < screen pixels GLuint Filter_Max; // Filtering mode if texture pixels > screen pixels // Constructor (sets default texture modes) Texture2D(GLuint index = 0); // Constructor (this constructor is used for frame buffer). Texture2D(GLuint width, GLuint height, GLint internalFormat, GLuint imageFormat, GLuint index = 0); // Generates texture from image data void Generate(GLuint width, GLuint height, unsigned char *data); // Binds the texture as the current active GL_TEXTURE_2D texture object void Bind() const; void Unbind() const; void Resize(int width_, int height_); void SetTextureIndex(GLuint index); // Overloaded operator. bool operator==(Texture2D &texture) { return this->ID == texture.ID; } }; // Texture3D is designed to store cloud textures from .ex5 files. class Texture3D { public: // Holds the ID of the texture object, used for all texture operations to reference to this particular texture. GLuint ID; // Texture image dimensions GLuint Width, Height, Depth; // Texture configuration GLuint Wrap_S; // Wrapping mode on S axis GLuint Wrap_T; // Wrapping mode on T axis GLuint Wrap_R; // Wrapping mode on R axis GLuint Filter_Min; // Filtering mode if texture pixels < screen pixels GLuint Filter_Max; // Filtering mode if texture pixels > screen pixels // Constructor (sets default texture modes) Texture3D(); // Generates texture from image data void Generate(GLuint width, GLuint height, GLuint depth, unsigned char *data); }; #endif
1.773438
2
MOO-1.8.1/net_mplex.h
coyotebringsfire/MuMoo
0
7999547
/****************************************************************************** Copyright (c) 1992, 1995, 1996 Xerox Corporation. All rights reserved. Portions of this code were written by <NAME>, aka ghond. Use and copying of this software and preparation of derivative works based upon this software are permitted. Any distribution of this software or derivative works must comply with all applicable United States export control laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. Any person obtaining a copy of this software is requested to send their name and post office or electronic mail address to: <NAME> Xerox PARC 3333 Coyote Hill Rd. Palo Alto, CA 94304 <EMAIL> *****************************************************************************/ /* This describes the complete set of procedures that a multiplexing wait * implementation must provide. * * The `mplex' abstraction provides a way to wait until it is possible to * perform an I/O operation on any of a set of file descriptors without * blocking. Uses of the abstraction always have the following form: * * mplex_clear(); * { mplex_add_reader(fd) or mplex_add_writer(fd) }* * timed_out = mplex_wait(timeout); * { mplex_is_readable(fd) or mplex_is_writable(fd) }* * * The set of file descriptors maintained by the abstraction is referred to * below as the `wait set'. Each file descriptor in the wait set is marked * with the kind of I/O (i.e., reading, writing, or both) desired. */ #ifndef Net_MPlex_H #define Net_MPlex_H 1 extern void mplex_clear(void); /* Reset the wait set to be empty. */ extern void mplex_add_reader(int fd); /* Add the given file descriptor to the wait * set, marked for reading. */ extern void mplex_add_writer(int fd); /* Add the given file descriptor to the wait * set, marked for writing. */ extern int mplex_wait(unsigned timeout); /* Wait until it is possible either to do the * appropriate kind of I/O on some descriptor * in the wait set or until `timeout' seconds * have elapsed. Return true iff the timeout * expired without any I/O becoming possible. */ extern int mplex_is_readable(int fd); /* Return true iff the most recent mplex_wait() * call terminated (in part) because reading * had become possible on the given descriptor. */ extern int mplex_is_writable(int fd); /* Return true iff the most recent mplex_wait() * call terminated (in part) because reading * had become possible on the given descriptor. */ #endif /* !Net_MPlex_H */ /* * $Log: net_mplex.h,v $ * Revision 1.3 1998/12/14 13:18:30 nop * Merge UNSAFE_OPTS (ref fixups); fix Log tag placement to fit CVS whims * * Revision 1.2 1997/03/03 04:19:05 nop * GNU Indent normalization * * Revision 1.1.1.1 1997/03/03 03:45:04 nop * LambdaMOO 1.8.0p5 * * Revision 2.1 1996/02/08 06:18:23 pavel * Updated copyright notice for 1996. Release 1.8.0beta1. * * Revision 2.0 1995/11/30 04:53:08 pavel * New baseline version, corresponding to release 1.8.0alpha1. * * Revision 1.2 1992/10/23 23:03:47 pavel * Added copyright notice. * * Revision 1.1 1992/09/23 17:14:17 pavel * Initial RCS-controlled version. */
1.34375
1
src/vin.c
clpo13/vinnie
0
7999555
// Vinnie - simple VIN decoder // Copyright (c) 2018-2019 <NAME> // SPDX-License-Identifier: MIT #include "vin.h" /** * @brief Convert a given character to a corresponding number between 0 and 9. * * The letters I, O, and Q are not used. * * @param c a character to convert to a digit * @return a number between 0 and 9 */ int transliterate(char c) { const char *alphanum = "0123456789.ABCDEFGH..JKLMN.P.R..STUVWXYZ"; return indexOf(alphanum, c) % 10; } /** * @brief Calculate the check digit for a given VIN. * * The weights used here are sourced from 49 CFR 565.15 Table IV, which can be * viewed online at https://www.law.cornell.edu/cfr/text/49/565.15. * * @param vin a 17-character vehicle identification number * @return the value of the check digit (0-9 or X) */ char getCheckDigit(char *vin) { const char *map = "0123456789X"; // X is a stand-in for 10. const char *weights = "8765432X098765432"; // here too int sum = 0; for (int i = 0; i < 17; i++) { sum += transliterate(vin[i]) * indexOf(map, weights[i]); } return map[sum % 11]; } /** * @brief Validate a given VIN by its length and check digit. * * @param vin a 17-character vehicle identification number * @return true if the VIN is valid, false otherwise */ bool validate(char *vin) { if (strlen(vin) != 17) { return false; } return getCheckDigit(vin) == vin[8]; } /** * @brief Get the index of a character in a string. * * @param string an arbitrary string * @param c the character to find in the string * @return the position of the character within the string * or -1 if not found */ int indexOf(const char *string, char c) { char *posc = strchr(string, c); int pos = posc ? posc - string : -1; return pos; }
2.734375
3
server/src/building/IRParser.h
UnitTestBot/UTBotCpp
22
7999563
#ifndef UNITTESTBOT_IRPARSER_H #define UNITTESTBOT_IRPARSER_H #include "PathSubstitution.h" #include "Tests.h" #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> class IRParser { public: bool parseModule(const fs::path &rootBitcode, tests::TestsMap &tests); private: std::unique_ptr<llvm::Module> getModule(const fs::path &rootBitcode, llvm::LLVMContext &context); }; #endif // UNITTESTBOT_IRPARSER_H
0.691406
1
Code/Projects/Rosa/src/PEs/wbperosaconvoselector.h
dphrygian/zeta
6
7999571
#ifndef WBPEROSACONVOSELECTOR_H #define WBPEROSACONVOSELECTOR_H #include "wbpe.h" #include "wbparamevaluator.h" class WBPERosaConvoSelector : public WBPE { public: WBPERosaConvoSelector(); virtual ~WBPERosaConvoSelector(); DEFINE_WBPE_FACTORY( RosaConvoSelector ); virtual void InitializeFromDefinition( const SimpleString& DefinitionName ); virtual void Evaluate( const WBParamEvaluator::SPEContext& Context, WBParamEvaluator::SEvaluatedParam& EvaluatedParam ) const; protected: Map<HashedString, SimpleString> m_Selections; }; #endif // WBPEROSACONVOSELECTOR_H
0.753906
1
mycode/cpp/thread/oo_pc/TaskQueue.h
stdbilly/CS_Note
2
7999579
#pragma once #include <queue> #include "Condition.h" #include "MutexLock.h" using std::queue; namespace wd { using ElemType = int; class TaskQueue { public: TaskQueue(size_t quesize); bool empty() const; bool full() const; void push(ElemType); ElemType pop(); private: size_t _queSize; queue<ElemType> _que; MutexLock _mutex; Condition _notFull; Condition _notEmpty; }; } // namespace wd
1.28125
1
src/ssd/Host_Interface_NVMe.h
adweathers/MQSim
5
7999587
#ifndef HOST_INTERFACE_NVME_H #define HOST_INTERFACE_NVME_H #include <vector> #include <list> #include <map> #include "../sim/Sim_Event.h" #include "Host_Interface_Base.h" #include "User_Request.h" #include "Host_Interface_Defs.h" namespace SSD_Components { class Input_Stream_NVMe : public Input_Stream_Base { public: Input_Stream_NVMe(IO_Flow_Priority_Class priority_class, LHA_type start_logical_sector_address, LHA_type end_logical_sector_address, uint64_t submission_queue_base_address, uint16_t submission_queue_size, uint64_t completion_queue_base_address, uint16_t completion_queue_size) : Input_Stream_Base(), Priority_class(priority_class), Start_logical_sector_address(start_logical_sector_address), End_logical_sector_address(end_logical_sector_address), Submission_queue_base_address(submission_queue_base_address), Submission_queue_size(submission_queue_size), Completion_queue_base_address(completion_queue_base_address), Completion_queue_size(completion_queue_size), Submission_head(0), Submission_head_informed_to_host(0), Submission_tail(0), Completion_head(0), Completion_tail(0), On_the_fly_requests(0){} ~Input_Stream_NVMe(); IO_Flow_Priority_Class Priority_class; LHA_type Start_logical_sector_address; LHA_type End_logical_sector_address; uint64_t Submission_queue_base_address; uint16_t Submission_queue_size; uint64_t Completion_queue_base_address; uint16_t Completion_queue_size; uint16_t Submission_head; uint16_t Submission_head_informed_to_host;//To avoide race condition, the submission head must not be informed to host until the request info of the head is successfully arrived uint16_t Submission_tail; uint16_t Completion_head; uint16_t Completion_tail; std::list<User_Request*> Waiting_user_requests;//The list of requests that have been fetch to the device queue and are getting serviced std::list<User_Request*> Completed_user_requests;//The list of requests that are completed but have not been informed to the host due to full CQ std::list<User_Request*> Waiting_write_data_transfers;//The list of write requests that are waiting for data uint16_t On_the_fly_requests;// the number of requests that are either being fetch from host or waiting in the device queue }; class Input_Stream_Manager_NVMe : public Input_Stream_Manager_Base { public: Input_Stream_Manager_NVMe(Host_Interface_Base* host_interface, uint16_t queue_fetch_szie); unsigned int Queue_fetch_size; stream_id_type Create_new_stream(IO_Flow_Priority_Class priority_class, LHA_type start_logical_sector_address, LHA_type end_logical_sector_address, uint64_t submission_queue_base_address, uint16_t submission_queue_size, uint64_t completion_queue_base_address, uint16_t completion_queue_size); void Submission_queue_tail_pointer_update(stream_id_type stream_id, uint16_t tail_pointer_value); void Completion_queue_head_pointer_update(stream_id_type stream_id, uint16_t head_pointer_value); void Handle_new_arrived_request(User_Request* request); void Handle_arrived_write_data(User_Request* request); void Handle_serviced_request(User_Request* request); uint16_t Get_submission_queue_depth(stream_id_type stream_id); uint16_t Get_completion_queue_depth(stream_id_type stream_id); IO_Flow_Priority_Class Get_priority_class(stream_id_type stream_id); private: void segment_user_request(User_Request* user_request); void inform_host_request_completed(stream_id_type stream_id, User_Request* request); }; class Request_Fetch_Unit_NVMe : public Request_Fetch_Unit_Base { public: Request_Fetch_Unit_NVMe(Host_Interface_Base* host_interface); void Fetch_next_request(stream_id_type stream_id); void Fetch_write_data(User_Request* request); void Send_read_data(User_Request* request); void Send_completion_queue_element(User_Request* request, uint16_t sq_head_value); void Process_pcie_write_message(uint64_t, void *, unsigned int); void Process_pcie_read_message(uint64_t, void *, unsigned int); private: uint16_t current_phase; uint32_t number_of_sent_cqe; }; class Host_Interface_NVMe : public Host_Interface_Base { friend class Input_Stream_Manager_NVMe; friend class Request_Fetch_Unit_NVMe; public: Host_Interface_NVMe(const sim_object_id_type& id, LHA_type max_logical_sector_address, uint16_t submission_queue_depth, uint16_t completion_queue_depth, unsigned int no_of_input_streams, uint16_t queue_fetch_size, unsigned int sectors_per_page, Data_Cache_Manager_Base* cache); stream_id_type Create_new_stream(IO_Flow_Priority_Class priority_class, LHA_type start_logical_sector_address, LHA_type end_logical_sector_address, uint64_t submission_queue_base_address, uint64_t completion_queue_base_address); void Start_simulation(); void Validate_simulation_config(); void Execute_simulator_event(MQSimEngine::Sim_Event*); uint16_t Get_submission_queue_depth(); uint16_t Get_completion_queue_depth(); void Report_results_in_XML(std::string name_prefix, Utils::XmlWriter& xmlwriter); private: uint16_t submission_queue_depth, completion_queue_depth; unsigned int no_of_input_streams; }; } #endif // !HOSTINTERFACE_NVME_H
1.226563
1
src/demo/coroutine/stackless/process_pipe.c
OhOhOhOhOhOhOhOh/tbox
0
7999595
/* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "../../demo.h" /* ////////////////////////////////////////////////////////////////////////////////////// * macros */ #define COUNT (50) /* ////////////////////////////////////////////////////////////////////////////////////// * types */ // the process type typedef struct __tb_demo_lo_process_t { // the process tb_process_ref_t proc; // the arguments tb_char_t** argv; // the pipe files tb_pipe_file_ref_t file[2]; // the process attributes tb_process_attr_t attr; // id tb_size_t id; // read variables tb_size_t read; tb_byte_t data[8192]; tb_size_t size; tb_bool_t wait; tb_long_t real; }tb_demo_lo_process_t, *tb_demo_lo_process_ref_t; /* ////////////////////////////////////////////////////////////////////////////////////// * implementation */ static tb_void_t tb_demo_lo_coroutine_func(tb_lo_coroutine_ref_t coroutine, tb_cpointer_t priv) { // get arguments tb_demo_lo_process_ref_t process = (tb_demo_lo_process_ref_t)priv; tb_assert_and_check_return(process && process->argv); // enter coroutine tb_lo_coroutine_enter(coroutine) { // init pipe files if (tb_pipe_file_init_pair(process->file, 0)) { // init process process->attr.outpipe = process->file[1]; process->attr.outtype = TB_PROCESS_REDIRECT_TYPE_PIPE; process->proc = tb_process_init(process->argv[1], (tb_char_t const**)(process->argv + 1), &process->attr); if (process->proc) { // read pipe data while (process->read < process->size) { process->real = tb_pipe_file_read(process->file[0], process->data + process->read, process->size - process->read); if (process->real > 0) { process->read += process->real; process->wait = tb_false; } else if (!process->real && !process->wait) { // wait pipe tb_lo_coroutine_wait_pipe(process->file[0], TB_PIPE_EVENT_READ, 1000); tb_check_break(tb_lo_coroutine_wait_result() > 0); process->wait = tb_true; } else break; } // dump data tb_trace_i("[%lu]: read pipe: %ld", process->id, process->read); // wait process tb_lo_coroutine_wait_proc(process->proc, -1); // trace tb_trace_i("[%lu]: run: %s, status: %ld", process->id, process->argv[1], tb_lo_coroutine_proc_status()); // exit process tb_process_exit(process->proc); } // exit pipe files tb_pipe_file_exit(process->file[0]); tb_pipe_file_exit(process->file[1]); } } } /* ////////////////////////////////////////////////////////////////////////////////////// * main */ tb_int_t tb_demo_lo_coroutine_process_pipe_main(tb_int_t argc, tb_char_t** argv) { // init scheduler tb_lo_scheduler_ref_t scheduler = tb_lo_scheduler_init(); if (scheduler) { // start coroutines tb_size_t count = COUNT; tb_demo_lo_process_t processes[COUNT]; tb_memset(processes, 0, sizeof(processes)); while (count--) { processes[count].argv = argv; processes[count].id = count; processes[count].size = sizeof(processes[count].data); tb_lo_coroutine_start(scheduler, tb_demo_lo_coroutine_func, &processes[count], 0); } // run scheduler tb_lo_scheduler_loop(scheduler, tb_true); // exit scheduler tb_lo_scheduler_exit(scheduler); } return 0; }
1.03125
1
project759/src/component496/headers/component496/lib29.h
gradle/perf-native-large
2
7999603
#ifndef PROJECT_HEADER_component496_29_H #define PROJECT_HEADER_component496_29_H int component496_29(); #endif // PROJECT_HEADER_component496_29_H
-0.246094
0
legacy/deploy/serving/seg-serving/op/image_seg_op.h
veritas0505yg/PaddleSeg
2
7999611
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <vector> #include "paddle/fluid/inference/paddle_inference_api.h" #include "seg-serving/image_seg.pb.h" namespace baidu { namespace paddle_serving { namespace serving { // rename static const char* IMAGE_CLASSIFICATION_MODEL_NAME = "image_seg_deeplabv3p"; class ImageSegOp : public baidu::paddle_serving::predictor::OpWithChannel< baidu::paddle_serving::image_segmentation:: ImageSegResponse> { public: typedef std::vector<paddle::PaddleTensor> TensorVector; DECLARE_OP(ImageSegOp); int inference(); private: std::vector<unsigned char> mask_raw; }; } // namespace serving } // namespace paddle_serving } // namespace baidu
1.203125
1
third_party/NordicSemiconductor/drivers/radio/nrf_802154_swi.h
simonlingoogle/ot-nrf528xx
19
7999619
/* Copyright (c) 2017 - 2019, Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef NRF_802154_SWI_H__ #define NRF_802154_SWI_H__ #include <stdbool.h> #include <stdint.h> #include "nrf_802154.h" #include "nrf_802154_const.h" #include "nrf_802154_notification.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup nrf_802154_swi 802.15.4 driver SWI management * @{ * @ingroup nrf_802154 * @brief SWI manager for the 802.15.4 driver. */ /** * @brief Initializes the SWI module. */ void nrf_802154_swi_init(void); /** * @brief Notifies the next higher layer that a frame was received. * * The notification is triggered from the SWI priority level. * * @param[in] p_data Pointer to a buffer that contains PHR and PSDU of the received frame. * @param[in] power RSSI measured during the frame reception. * @param[in] lqi LQI that indicates the measured link quality during the frame reception. */ void nrf_802154_swi_notify_received(uint8_t * p_data, int8_t power, uint8_t lqi); /** * @brief Notifies the next higher layer that the reception of a frame failed. * * @param[in] error Error code that indicates reason of the failure. */ void nrf_802154_swi_notify_receive_failed(nrf_802154_rx_error_t error); /** * @brief Notifies the next higher layer that a frame was transmitted * * The notification is triggered from the SWI priority level. * * @param[in] p_frame Pointer to a buffer that contains PHR and PSDU of the transmitted frame. * @param[in] p_ack Pointer to a buffer that contains PHR and PSDU of ACK frame. NULL if ACK was * not requested. * @param[in] power RSSI of the received frame, or 0 if ACK was not requested. * @param[in] lqi LQI of the received frame, or 0 if ACK was not requested. */ void nrf_802154_swi_notify_transmitted(const uint8_t * p_frame, uint8_t * p_data, int8_t power, uint8_t lqi); /** * @brief Notifies the next higher layer that a frame was not transmitted from the SWI priority * level. * * @param[in] p_frame Pointer to a buffer that contains PHR and PSDU of the frame that failed * the transmission. * @param[in] error Reason of the transmission failure. */ void nrf_802154_swi_notify_transmit_failed(const uint8_t * p_frame, nrf_802154_tx_error_t error); /** * @brief Notifies the next higher layer that the energy detection procedure ended from * the SWI priority level. * * @param[in] result Detected energy level. */ void nrf_802154_swi_notify_energy_detected(uint8_t result); /** * @brief Notifies the next higher layer that the energy detection procedure failed from * the SWI priority level. * * @param[in] error Reason of the energy detection failure. */ void nrf_802154_swi_notify_energy_detection_failed(nrf_802154_ed_error_t error); /** * @brief Notifies the next higher layer that the Clear Channel Assessment (CCA) procedure ended. * * The notification is triggered from the SWI priority level. * * @param[in] channel_free If a free channel was detected. */ void nrf_802154_swi_notify_cca(bool channel_free); /** * @brief Notifies the next higher layer that the Clear Channel Assessment (CCA) procedure failed. * * The notification is triggered from the SWI priority level. * * @param[in] error Reason of the CCA failure. */ void nrf_802154_swi_notify_cca_failed(nrf_802154_cca_error_t error); /** * @brief Requests a stop of the HF clock. * * The notification is triggered from the SWI priority level. * * @note This function is to be called through notification module to prevent calling it from * the arbiter context. */ void nrf_802154_swi_hfclk_stop(void); /** * @brief Terminates the stopping of the HF clock. * * @note This function terminates the stopping of the HF clock only if it has not been performed * yet. */ void nrf_802154_swi_hfclk_stop_terminate(void); /** * @brief Requests entering the @ref RADIO_STATE_SLEEP state from the SWI priority. * * @param[in] term_lvl Termination level of this request. Selects procedures to abort. * @param[out] p_result Result of entering the sleep state. */ void nrf_802154_swi_sleep(nrf_802154_term_t term_lvl, bool * p_result); /** * @brief Requests entering the @ref RADIO_STATE_RX state from the SWI priority. * * @param[in] term_lvl Termination level of this request. Selects procedures to abort. * @param[in] req_orig Module that originates this request. * @param[in] notify_function Function called to notify the status of the procedure. May be NULL. * @param[in] notify_abort If abort notification should be triggered automatically. * @param[out] p_result Result of entering the receive state. */ void nrf_802154_swi_receive(nrf_802154_term_t term_lvl, req_originator_t req_orig, nrf_802154_notification_func_t notify_function, bool notify_abort, bool * p_result); /** * @biref Requests entering the @ref RADIO_STATE_TX state from the SWI priority. * * @param[in] term_lvl Termination level of this request. Selects procedures to abort. * @param[in] req_orig Module that originates this request. * @param[in] p_data Pointer to a buffer that contains PHR and PSDU of the frame to be * transmitted. * @param[in] cca If the driver should perform the CCA procedure before transmission. * @param[in] immediate If true, the driver schedules transmission immediately or never; * if false, the transmission may be postponed until TX preconditions * are met. * @param[in] notify_function Function called to notify the status of this procedure instead of * the default notification. If NULL, the default notification * is used. * @param[out] p_result Result of entering the transmit state. */ void nrf_802154_swi_transmit(nrf_802154_term_t term_lvl, req_originator_t req_orig, const uint8_t * p_data, bool cca, bool immediate, nrf_802154_notification_func_t notify_function, bool * p_result); /** * @brief Requests entering the @ref RADIO_STATE_ED state from the SWI priority. * * @param[in] term_lvl Termination level of this request. Selects procedures to abort. * @param[in] time_us Requested duration of the energy detection procedure. * @param[out] p_result Result of entering the energy detection state. */ void nrf_802154_swi_energy_detection(nrf_802154_term_t term_lvl, uint32_t time_us, bool * p_result); /** * @brief Requests entering the @ref RADIO_STATE_CCA state from the SWI priority. * * @param[in] term_lvl Termination level of this request. Selects procedures to abort. * @param[out] p_result Result of entering the CCA state. */ void nrf_802154_swi_cca(nrf_802154_term_t term_lvl, bool * p_result); /** * @brief Requests entering the @ref RADIO_STATE_CONTINUOUS_CARRIER state from the SWI priority. * * @param[in] term_lvl Termination level of this request. Selects procedures to abort. * @param[out] p_result Result of entering the continuous carrier state. */ void nrf_802154_swi_continuous_carrier(nrf_802154_term_t term_lvl, bool * p_result); /** * @brief Notifies the core module that the given buffer is not used anymore and can be freed. * * @param[in] p_data Pointer to the buffer to be freed. */ void nrf_802154_swi_buffer_free(uint8_t * p_data, bool * p_result); /** * @brief Notifies the core module that the next higher layer has requested a channel change. */ void nrf_802154_swi_channel_update(bool * p_result); /** * @brief Notifies the core module that the next higher layer has requested a CCA configuration * change. */ void nrf_802154_swi_cca_cfg_update(bool * p_result); /** * @brief Notifies the core module that the next higher layer requested the RSSI measurement. */ void nrf_802154_swi_rssi_measure(bool * p_result); /** * @brief Gets the last RSSI measurement result from the core module. */ void nrf_802154_swi_rssi_measurement_get(int8_t * p_rssi, bool * p_result); /** *@} **/ #ifdef __cplusplus } #endif #endif // NRF_802154_SWI_H__
1.132813
1
lib/wizards/kaappi/dcity/rooms/park22.c
vlehtola/questmud
0
7999627
inherit "room/room"; object mob,mob2; reset(arg) { if(!mob) { mob = clone_object("/wizards/kaappi/dcity/mobs/kids.c"); move_object(mob, this_object()); } if(!mob2) { mob2 = clone_object("/wizards/kaappi/dcity/mobs/kids.c"); move_object(mob2, this_object()); } if(arg) return; add_exit("west", "park21.c"); add_exit("north", "park19.c"); add_exit("northwest", "park18.c"); short_desc = "A park"; long_desc = "The trees and bushes are growing straight from the rock.\n"+ "A beautiful green grass covers the ground. Some most commonly\n"+ "used paths can clearly be seen on the ground.\n"; set_light(3); }
1.148438
1
QuantumGateLib/Concurrency/ThreadSafe.h
Colorfingers/QuantumGate
87
7999635
// This file is part of the QuantumGate project. For copyright and // licensing information refer to the license file(s) in the project root. #pragma once #include "..\Common\Traits.h" #include <shared_mutex> namespace QuantumGate::Implementation::Concurrency { // Inspired by "Enforcing Correct Mutex Usage with Synchronized Values" by <NAME> // http://www.drdobbs.com/cpp/enforcing-correct-mutex-usage-with-synch/225200269 template<typename T, typename M = std::mutex> class ThreadSafe final { template<typename ThS, typename Lck = std::unique_lock<M>> class Value final { public: Value() noexcept(std::is_nothrow_default_constructible_v<Lck>) {} Value(ThS* ths) noexcept(std::is_nothrow_constructible_v<Lck, M>) : m_ThS(ths), m_Lock(ths->m_Mutex) {} Value(ThS* ths, std::adopt_lock_t t) noexcept(std::is_nothrow_constructible_v<Lck, M, std::adopt_lock_t>) : m_ThS(ths), m_Lock(ths->m_Mutex, t) {} Value(ThS* ths, std::defer_lock_t t) noexcept(std::is_nothrow_constructible_v<Lck, M, std::defer_lock_t>) : m_ThS(ths), m_Lock(ths->m_Mutex, t) {} Value(const Value&) = delete; Value(Value&& other) noexcept : m_ThS(other.m_ThS), m_Lock(std::move(other.m_Lock)) { other.m_ThS = nullptr; } ~Value() = default; Value& operator=(const Value&) = delete; Value& operator=(Value&& other) noexcept { m_ThS = std::exchange(other.m_ThS, nullptr); m_Lock = std::move(other.m_Lock); return *this; } inline std::conditional_t<std::is_const_v<ThS>, const T*, T*> operator->() noexcept { assert(*this); return &m_ThS->m_Data; } inline const T* operator->() const noexcept { assert(*this); return &m_ThS->m_Data; } inline std::conditional_t<std::is_const_v<ThS>, const T&, T&> operator*() noexcept { assert(*this); return m_ThS->m_Data; } inline const T& operator*() const noexcept { assert(*this); return m_ThS->m_Data; } template<typename Arg, typename ThS2 = ThS, typename = std::enable_if_t<!std::is_const_v<ThS2>>> inline auto& operator[](Arg&& arg) noexcept(noexcept(m_ThS->m_Data[std::forward<Arg>(arg)])) { assert(*this); return m_ThS->m_Data[std::forward<Arg>(arg)]; } template<typename Arg, typename ThS2 = ThS, typename = std::enable_if_t<std::is_const_v<ThS2>>> inline const auto& operator[](Arg&& arg) const noexcept(noexcept(m_ThS->m_Data[std::forward<Arg>(arg)])) { assert(*this); return m_ThS->m_Data[std::forward<Arg>(arg)]; } template<typename... Args, typename ThS2 = ThS, typename = std::enable_if_t<!std::is_const_v<ThS2>>> inline auto operator()(Args&&... args) noexcept(noexcept(m_ThS->m_Data(std::forward<Args>(args)...))) { assert(*this); return m_ThS->m_Data(std::forward<Args>(args)...); } template<typename... Args, typename ThS2 = ThS, typename = std::enable_if_t<std::is_const_v<ThS2>>> inline auto operator()(Args&&... args) const noexcept(noexcept(m_ThS->m_Data(std::forward<Args>(args)...))) { assert(*this); return m_ThS->m_Data(std::forward<Args>(args)...); } inline Value& operator=(const T& other) noexcept(std::is_nothrow_copy_assignable_v<T>) { assert(*this); m_ThS->m_Data = other; return *this; } inline Value& operator=(T&& other) noexcept(std::is_nothrow_move_assignable_v<T>) { assert(*this); m_ThS->m_Data = std::move(other); return *this; } inline bool operator==(const T& other) const noexcept { assert(*this); return (m_ThS->m_Data == other); } inline bool operator!=(const T& other) const noexcept { assert(*this); return !(m_ThS->m_Data == other); } inline explicit operator bool() const noexcept { return (m_ThS != nullptr && m_Lock.owns_lock()); } template<typename Lck2 = Lck, typename = std::enable_if_t<std::is_same_v<Lck2, std::unique_lock<M>>>> inline void Lock() noexcept(noexcept(m_Lock.lock())) { assert(!m_Lock.owns_lock()); m_Lock.lock(); } template<typename Lck2 = Lck, typename = std::enable_if_t<std::is_same_v<Lck2, std::unique_lock<M>>>> inline bool TryLock() noexcept(noexcept(m_Lock.try_lock())) { assert(!m_Lock.owns_lock()); return m_Lock.try_lock(); } template<typename Lck2 = Lck, typename = std::enable_if_t<std::is_same_v<Lck2, std::unique_lock<M>>>> inline void Unlock() noexcept(noexcept(m_Lock.unlock())) { assert(m_Lock.owns_lock()); m_Lock.unlock(); } template<typename Lck2 = Lck, typename = std::enable_if_t<std::is_same_v<Lck2, std::shared_lock<M>>>> inline void LockShared() noexcept(noexcept(m_Lock.lock())) { assert(!m_Lock.owns_lock()); m_Lock.lock(); } template<typename Lck2 = Lck, typename = std::enable_if_t<std::is_same_v<Lck2, std::shared_lock<M>>>> inline bool TryLockShared() noexcept(noexcept(m_Lock.try_lock())) { assert(!m_Lock.owns_lock()); return m_Lock.try_lock(); } template<typename Lck2 = Lck, typename = std::enable_if_t<std::is_same_v<Lck2, std::shared_lock<M>>>> inline void UnlockShared() noexcept(noexcept(m_Lock.unlock())) { assert(m_Lock.owns_lock()); m_Lock.unlock(); } inline void Reset() noexcept(noexcept(m_Lock.owns_lock()) && noexcept(m_Lock.unlock())) { m_ThS = nullptr; if (m_Lock.owns_lock()) m_Lock.unlock(); } template<typename F, typename Lck2 = Lck, typename = std::enable_if_t<std::is_same_v<Lck2, std::unique_lock<M>>>> inline void WhileUnlocked(F&& function) noexcept(noexcept(Unlock()) && noexcept(function()) && noexcept(Lock())) { assert(m_Lock.owns_lock()); Unlock(); function(); Lock(); } template<typename F, typename Lck2 = Lck, typename = std::enable_if_t<std::is_same_v<Lck2, std::shared_lock<M>>>> inline void WhileUnlockedShared(F&& function) noexcept(noexcept(UnlockShared()) && noexcept(function()) && noexcept(LockShared())) { assert(m_Lock.owns_lock()); UnlockShared(); function(); LockShared(); } private: ThS* m_ThS{ nullptr }; Lck m_Lock; }; public: using UniqueLockedType = Value<ThreadSafe, std::unique_lock<M>>; using UniqueLockedConstType = Value<const ThreadSafe, std::unique_lock<M>>; using SharedLockedConstType = Value<const ThreadSafe, std::shared_lock<M>>; constexpr ThreadSafe() noexcept(std::is_nothrow_default_constructible_v<T> && std::is_nothrow_default_constructible_v<M>) {} template<typename... Args, typename = std::enable_if_t<!AreSameV<ThreadSafe<T, M>, std::decay_t<Args>...>>> constexpr ThreadSafe(Args&&... args) noexcept(std::is_nothrow_constructible_v<T, Args...> && std::is_nothrow_constructible_v<M>) : m_Data(std::forward<Args>(args)...) {} ThreadSafe(const ThreadSafe&) = delete; ThreadSafe(ThreadSafe&&) = delete; ~ThreadSafe() = default; ThreadSafe& operator=(const ThreadSafe&) = delete; ThreadSafe& operator=(ThreadSafe&&) = delete; inline UniqueLockedType WithUniqueLock() noexcept(std::is_nothrow_constructible_v<UniqueLockedType, ThreadSafe>) { return { this }; } inline UniqueLockedConstType WithUniqueLock() const noexcept(std::is_nothrow_constructible_v<UniqueLockedConstType, ThreadSafe>) { return { this }; } template<typename F> inline auto WithUniqueLock(F&& function) noexcept(noexcept(function(*WithUniqueLock()))) { return function(*WithUniqueLock()); } template<typename F> inline auto WithUniqueLock(F&& function) const noexcept(noexcept(function(*WithUniqueLock()))) { return function(*WithUniqueLock()); } template<typename F, typename M2 = M, typename = std::enable_if_t<std::is_member_function_pointer_v<decltype(&M2::try_lock)>>> inline bool IfUniqueLock(F&& function) noexcept(noexcept(m_Mutex.try_lock()) && noexcept(function(m_Data)) && noexcept(m_Mutex.unlock())) { if (m_Mutex.try_lock()) { function(m_Data); m_Mutex.unlock(); return true; } return false; } template<typename F, typename M2 = M, typename = std::enable_if_t<std::is_member_function_pointer_v<decltype(&M2::try_lock)>>> inline bool IfUniqueLock(F&& function) const noexcept(noexcept(m_Mutex.try_lock()) && noexcept(function(m_Data)) && noexcept(m_Mutex.unlock())) { if (m_Mutex.try_lock()) { function(m_Data); m_Mutex.unlock(); return true; } return false; } template<typename M2 = M, typename = std::enable_if_t<std::is_member_function_pointer_v<decltype(&M2::try_lock)>>> inline UniqueLockedType TryWithUniqueLock() noexcept(noexcept(m_Mutex.try_lock()) && noexcept(UniqueLockedType(this, std::adopt_lock)) && noexcept(UniqueLockedType(this, std::defer_lock))) { if (m_Mutex.try_lock()) { return UniqueLockedType(this, std::adopt_lock); } return UniqueLockedType(this, std::defer_lock); } template<typename M2 = M, typename = std::enable_if_t<std::is_member_function_pointer_v<decltype(&M2::try_lock)>>> inline UniqueLockedConstType TryWithUniqueLock() const noexcept(noexcept(m_Mutex.try_lock()) && noexcept(UniqueLockedConstType(this, std::adopt_lock)) && noexcept(UniqueLockedConstType(this, std::defer_lock))) { if (m_Mutex.try_lock()) { return UniqueLockedConstType(this, std::adopt_lock); } return UniqueLockedConstType(this, std::defer_lock); } template<typename M2 = M, typename = std::enable_if_t<std::is_member_function_pointer_v<decltype(&M2::lock_shared)>>> inline SharedLockedConstType WithSharedLock() const noexcept(std::is_nothrow_constructible_v<SharedLockedConstType, ThreadSafe>) { return { this }; } template<typename F, typename M2 = M, typename = std::enable_if_t<std::is_member_function_pointer_v<decltype(&M2::lock_shared)>>> inline auto WithSharedLock(F&& function) const noexcept(noexcept(function(*WithSharedLock()))) { return function(*WithSharedLock()); } template<typename F, typename M2 = M, typename = std::enable_if_t<std::is_member_function_pointer_v<decltype(&M2::try_lock_shared)>>> inline bool IfSharedLock(F&& function) const noexcept(noexcept(m_Mutex.try_lock_shared()) && noexcept(function(m_Data)) && noexcept(m_Mutex.unlock_shared())) { if (m_Mutex.try_lock_shared()) { function(m_Data); m_Mutex.unlock_shared(); return true; } return false; } template<typename M2 = M, typename = std::enable_if_t<std::is_member_function_pointer_v<decltype(&M2::try_lock_shared)>>> inline SharedLockedConstType TryWithSharedLock() const noexcept(noexcept(m_Mutex.try_lock_shared()) && noexcept(SharedLockedConstType(this, std::adopt_lock)) && noexcept(SharedLockedConstType(this, std::defer_lock))) { if (m_Mutex.try_lock_shared()) { return SharedLockedConstType(this, std::adopt_lock); } return SharedLockedConstType(this, std::defer_lock); } private: T m_Data; mutable M m_Mutex; }; }
1.734375
2
Frameworks/IMCore.framework/Headers/IMPeopleCollection.h
CarlAmbroselli/barcelona
13
7999643
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import "IMPeople.h" @class NSArray, NSMutableArray; @interface IMPeopleCollection : IMPeople { NSMutableArray *_collectedPeople; } @property(retain, nonatomic) NSMutableArray *_collectedPeople; // @synthesize _collectedPeople; - (BOOL)containsPerson:(id)arg1; - (id)groups; - (id)people; - (void)_collectionNotification:(id)arg1; - (void)removeIMPeople:(id)arg1; - (void)addIMPeople:(id)arg1; - (BOOL)collectsIMPeople:(id)arg1; @property(readonly, nonatomic) NSArray *collectedIMPeople; - (id)init; @end
0.972656
1
SpringBoardFoundation/SBFWallpaperParallaxSettings.h
LacertosusRepo/headers
182
7999651
#import <Foundation/Foundation.h> @interface SBFWallpaperParallaxSettings : NSObject + (CGSize)minimumWallpaperSizeForCurrentDevice; @end
0.108887
0
formats.h
abannert/plethora
0
7999659
/* $Id: formats.h,v 1.4 2007/03/21 16:49:23 aaron Exp $ */ /* Copyright 2006-2007 Codemass, Inc. All rights reserved. * Use is subject to license terms. * * 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. */ /** * @file formats.h * @brief Handy-dandy string formatting routines, useful in various places. * @author <NAME> (<EMAIL>) */ #ifndef __formats_h #define __formats_h #include "config.h" #include "metrics.h" /** * Treat the given double as a high-precision microsecond (us) timer * and format it into pretty-printable units. * Returns the number of bytes written. */ int format_double_timer(char *buf, size_t buflen, double time_us); /** * Pretty-print the given timeval. * Returns the number of bytes written. */ int format_double_timeval(char *buf, size_t buflen, struct timeval *tv); /** * Format the given double as bytes into pretty-printable units. * Returns the number of bytes written. */ int format_double_bytes(char *buf, size_t buflen, double bytes); /** * Format the given bytes into pretty-printable units. * Returns the number of bytes written. */ int format_bytes(char *buf, size_t buflen, unsigned long long bytes); #endif /* __formats_h */
1.421875
1
include/coros.h
jfjia/coros
5
7999667
#ifndef COROS_H #define COROS_H #pragma once #include <uv.h> #include <cstddef> #include <cstring> #include <cassert> #include <atomic> #include <functional> #include <string> #include <mutex> #include <vector> #include <thread> #include <condition_variable> #include <boost/context/detail/fcontext.hpp> #include <boost/context/fixedsize_stack.hpp> #if defined(_WIN32) #define BAD_SOCKET (uintptr_t)(~0) #else #define BAD_SOCKET (-1) #endif namespace coros { struct Unwind {}; enum State { STATE_READY = 0, STATE_RUNNING = 1, STATE_WAITING = 2, STATE_COMPUTE = 3, STATE_DONE = 4, }; enum Event { EVENT_WAKEUP = 0, EVENT_CANCEL = 1, EVENT_READABLE = 2, EVENT_WRITABLE = 3, EVENT_TIMEOUT = 4, EVENT_JOIN = 5, EVENT_COND = 6, EVENT_POLLERR = 7, EVENT_DISCONNECT = 8, }; class Scheduler; class Coroutine; class Condition; class Socket { friend class Scheduler; public: Socket(uv_os_sock_t s = BAD_SOCKET); void Attach(uv_os_sock_t s); void Close(); void SetDeadline(int timeout_secs); int GetDeadline(); bool ListenByHost(const std::string& host, int port, int backlog = 1024); bool ListenByIp(const std::string& ip, int port, int backlog = 1024); uv_os_sock_t Accept(); bool ConnectHost(const std::string& host, int port); bool ConnectIp(const std::string& ip, int port); int ReadSome(char* buf, int len); int ReadExactly(char* buf, int len); int ReadAtLeast(char* buf, int len, int min_len); int WriteSome(const char* buf, int len); int WriteExactly(const char* buf, int len); Event WaitReadable(Condition* cond = nullptr); Event WaitWritable(); protected: uv_os_sock_t s_; uv_poll_t poll_; int timeout_secs_{ 0 }; Coroutine* coro_{ nullptr }; }; template<int N> class Buffer { public: Buffer(Socket* s = nullptr); void Attach(Socket* s); int EnsureData(int n); char* Data(); int Size(); void Skip(int n); int EnsureSpace(int n); char* Space(); int SpaceSize(); void Commit(int n); void Clear(); int Flush(); void Compact(); protected: char data_[N]; int read_index_{ 0 }; int write_index_{ 0 }; Socket* s_{ nullptr }; }; class Coroutine { public: static Coroutine* Self(); static Coroutine* Create(Scheduler* sched, const std::function<void()>& fn, const std::function<void(Coroutine*)>& exit_fn, std::size_t cls_size = 0, std::size_t stack_size = boost::context::stack_traits::default_size()); void Destroy(); void Resume(); void Suspend(State new_state); void Join(Coroutine* coro); void Cancel(); void Wakeup(Event new_event = EVENT_WAKEUP); State GetState() const; Event GetEvent() const; Scheduler* GetScheduler() const; std::size_t GetId() const; void Nice(); void Wait(long millisecs); void BeginCompute(); void EndCompute(); void SetTimeout(int seconds); bool CheckBuget(); void* GetCls() const; private: friend class Scheduler; void CheckTimeout(); static std::size_t NextId(); private: boost::context::detail::fcontext_t ctx_{ nullptr }; boost::context::detail::fcontext_t caller_{ nullptr }; boost::context::stack_context stack_; std::size_t cls_size_{ 0 }; std::function<void()> fn_; std::function<void(Coroutine*)> exit_fn_; Scheduler* sched_{ nullptr }; State state_{ STATE_READY }; Event event_; int timeout_secs_{ 0 }; Coroutine* joined_{ nullptr }; std::size_t id_{ 0 }; int buget_{ 0 }; }; typedef std::vector<Coroutine* > CoroutineList; class Condition { public: void Wait(Coroutine* coro); void NotifyOne(); void NotifyAll(); protected: CoroutineList waiting_; }; class Scheduler { public: static Scheduler* Get(); Scheduler(bool is_default, int compute_threads_n = 2); ~Scheduler(); void AddCoroutine(Coroutine* coro); // for current thread void PostCoroutine(Coroutine* coro, bool is_compute = false); // for different thread void Wait(Coroutine* coro, long millisecs); void Wait(Coroutine* coro, Socket& s, int flags); void BeginCompute(Coroutine* coro); void Run(); Coroutine* GetCurrent() const; uv_loop_t* GetLoop(); std::size_t GetId() const; void Stop(); void SetScheduleParams(int tight_loop, int coro_buget); protected: void Pre(); void Check(); void Async(); void Sweep(); void RunCoros(); void Cleanup(CoroutineList& cl); static std::size_t NextId(); protected: bool is_default_; std::size_t id_{ 0 }; uv_loop_t loop_; uv_loop_t* loop_ptr_{ nullptr }; uv_prepare_t pre_; uv_check_t check_; uv_async_t async_; uv_timer_t sweep_timer_; Coroutine* current_{ nullptr }; CoroutineList ready_; CoroutineList waiting_; std::mutex lock_; int outstanding_{ 0 }; CoroutineList posted_; CoroutineList compute_done_; std::atomic<bool> shutdown_{ false }; int tight_loop_{ 512 }; int coro_buget_{ 32 }; }; class Schedulers { public: Schedulers(int N); Scheduler* GetNext(); void Stop(); protected: void Fn(int n); protected: int N_; std::vector<std::thread> threads_; std::vector<Scheduler*> scheds_; int rr_index_{ 0 }; std::mutex lock_; std::condition_variable cond_; int created_{ 0 }; }; inline Socket::Socket(uv_os_sock_t s) : s_(s) { poll_.data = this; coro_ = Coroutine::Self(); if (s != BAD_SOCKET) { uv_poll_init_socket(Scheduler::Get()->GetLoop(), &poll_, s_); } } inline void Socket::Attach(uv_os_sock_t s) { s_ = s; uv_poll_init_socket(Scheduler::Get()->GetLoop(), &poll_, s_); } inline void Socket::SetDeadline(int timeout_secs) { timeout_secs_ = timeout_secs; } inline int Socket::GetDeadline() { return timeout_secs_; } inline int Socket::ReadExactly(char* buf, int len) { return ReadAtLeast(buf, len, len); } template<int N> inline Buffer<N>::Buffer(Socket* s) : s_(s) { } template<int N> inline void Buffer<N>::Attach(Socket* s) { s_ = s; } template<int N> inline void Buffer<N>::Clear() { read_index_ = write_index_ = 0; } template<int N> inline char* Buffer<N>::Data() { return &data_[read_index_]; } template<int N> inline int Buffer<N>::Size() { return write_index_ - read_index_; } template<int N> inline void Buffer<N>::Skip(int n) { if (n >= Size()) { Clear(); } else { read_index_ += n; } } template<int N> inline void Buffer<N>::Commit(int n) { if ((Size() + n) <= N) { write_index_ += n; } } template<int N> inline void Buffer<N>::Compact() { int size = Size(); memmove(&data_[0], &data_[read_index_], size); read_index_ = 0; write_index_ = size; } template<int N> inline char* Buffer<N>::Space() { return &data_[write_index_]; } template<int N> inline int Buffer<N>::EnsureSpace(int n) { if (SpaceSize() >= n) { return n; } if ((N - Size()) >= n) { Compact(); return n; } if (N < n) { return -1; } int rc = s_->WriteExactly(Data(), Size()); if (rc != Size()) { return rc; } Clear(); return n; } template<int N> inline int Buffer<N>::SpaceSize() { return N - write_index_; } template<int N> inline int Buffer<N>::Flush() { int size = Size(); int rc = s_->WriteExactly(Data(), size); if (rc != size) { return rc; } Clear(); return size; } template<int N> inline int Buffer<N>::EnsureData(int n) { assert(n <= N); if (Size() >= n) { return n; } if ((N - read_index_) < n) { Compact(); } int rc = s_->ReadAtLeast(Space(), SpaceSize(), n - Size()); if (rc <= 0) { return rc; } Commit(rc); return n; } inline Coroutine* Coroutine::Self() { Scheduler* sched = Scheduler::Get(); if (sched) { return sched->GetCurrent(); } else { return nullptr; } } inline void Coroutine::Join(Coroutine* coro) { if (coro->GetState() == STATE_DONE) { return; } coro->joined_ = this; Suspend(STATE_WAITING); } inline void Coroutine::Cancel() { Wakeup(EVENT_CANCEL); } inline void Coroutine::Wait(long millisecs) { sched_->Wait(this, millisecs); } inline void Coroutine::Wakeup(Event new_event) { state_ = STATE_READY; event_ = new_event; } inline State Coroutine::GetState() const { return state_; } inline Event Coroutine::GetEvent() const { return event_; } inline bool Coroutine::CheckBuget() { buget_ --; return (buget_ >= 0); } inline void Coroutine::Resume() { state_ = STATE_RUNNING; ctx_ = boost::context::detail::jump_fcontext(ctx_, (void*)this).fctx; } inline void Coroutine::Suspend(State new_state) { state_ = new_state; caller_ = boost::context::detail::jump_fcontext(caller_, (void*)this).fctx; if (event_ == EVENT_CANCEL) { throw Unwind(); } } inline Scheduler* Coroutine::GetScheduler() const { return sched_; } inline std::size_t Coroutine::GetId() const { return id_; } inline void Coroutine::Nice() { Suspend(STATE_READY); } inline void Coroutine::BeginCompute() { sched_->BeginCompute(this); } inline void Coroutine::EndCompute() { Suspend(STATE_READY); } inline void Coroutine::SetTimeout(int seconds) { timeout_secs_ = seconds; } inline void Coroutine::CheckTimeout() { if (state_ == STATE_WAITING) { if (timeout_secs_ > 0) { timeout_secs_ --; if (timeout_secs_ == 0) { state_ = STATE_READY; event_ = EVENT_TIMEOUT; } } } } inline void* Coroutine::GetCls() const { return static_cast<char*>(stack_.sp); } inline void Condition::Wait(Coroutine* coro) { waiting_.push_back(coro); coro->Suspend(STATE_WAITING); } inline void Condition::NotifyOne() { if (waiting_.size() > 0) { Coroutine* coro = waiting_.back(); waiting_.pop_back(); coro->Wakeup(EVENT_COND); } } inline void Condition::NotifyAll() { for (auto it = waiting_.begin(); it != waiting_.end(); it++) { (*it)->Wakeup(EVENT_COND); } waiting_.clear(); } inline Coroutine* Scheduler::GetCurrent() const { return current_; } inline uv_loop_t* Scheduler::GetLoop() { return loop_ptr_; } inline std::size_t Scheduler::GetId() const { return id_; } inline void Scheduler::SetScheduleParams(int tight_loop, int coro_buget) { tight_loop_ = tight_loop; coro_buget_ = coro_buget; } inline void Scheduler::BeginCompute(Coroutine* coro) { coro->Suspend(STATE_COMPUTE); } inline Scheduler* Schedulers::GetNext() { return scheds_[(rr_index_ ++) % N_]; } } // coros #endif // COROS_H
1.835938
2
c/public/lib/source/tx_shared/cff2.h
gitter-badger/afdko
732
7999675
"[-cff2 options: defaults -S, -b]\n" "+/-S do/don't subroutinize\n" "+/-b do/don't preserve glyph order\n" "-n remove hints\n" "-no_opt disable charstring optimizations (e.g.: x 0 rmoveto => x hmoveto)\n" "-maxs N set the maximum number of subroutines (0 means 32765)\n" "\n" "CFF2 mode writes a CFF2 conversion of an abstract font.\n" "\n" "To generate an instance (a.k.a. snapshot) of a CFF2 input font, use\n" "the option -U to specify the user design vector.\n" "\n" "For example, the command:\n" "\n" " tx -t1 -U 345,200 varfont.otf\n" "\n" "creates a Type 1 font from an OpenType-CFF2 font instantiated at\n" "(first axis) 345 and (second axis) 200.\n" "\n" "Use the option -UNC to not clamp the design vector to the min/max\n" "of font's design space.\n"
1.796875
2
problems/067/067.c
melwyncarlo/ProjectEuler
0
7999683
#include <stdio.h> #include <stdlib.h> #include <string.h> /* Copyright 2021 <NAME> */ int main() { int TRIANGLE[100][100]; int i = 0; FILE *fp; char triangle_num_row[301] = { 0 }; const char* FILE_NAME = "problems/067/p067_triangle.txt"; fp = fopen(FILE_NAME, "r"); while (fgets(triangle_num_row, 301, fp) != NULL) { char triangle_num[3] = { 0 }; int j = 0; int digits_n = 0; for (int digits_i = 0; digits_i < (int)strlen(triangle_num_row); digits_i++) { if (digits_n <= 1) { triangle_num[digits_n++] = triangle_num_row[digits_i]; } else { TRIANGLE[i][j++] = atoi(triangle_num); digits_n = 0; } } if (j < 100) { while (j != 100) { TRIANGLE[i][j++] = 0; } } i++; } fclose(fp); for (int i = 98; i >= 0; i--) { for (int j = 0; j <= i; j++) { if (TRIANGLE[i+1][j] >= TRIANGLE[i+1][j+1]) TRIANGLE[i][j] += TRIANGLE[i+1][j]; else TRIANGLE[i][j] += TRIANGLE[i+1][j+1]; } } printf("%d\n", TRIANGLE[0][0]); return 0; }
2.0625
2
src/prod/src/Federation/SiteNodeSavedInfo.h
AnthonyM/service-fabric
2,542
7999691
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Federation { class SiteNodeSavedInfo : public Serialization::FabricSerializable { public: explicit SiteNodeSavedInfo(uint64 inVal):instanceId_(inVal){}; __declspec (property(get=getInstanceId,put=setInstanceId)) uint64 InstanceId; uint64 getInstanceId() const { return instanceId_; } void setInstanceId(uint64 inInsId) { instanceId_ = inInsId; } void WriteTo(Common::TextWriter& w, Common::FormatOptions const&) const { w.Write("{0}", instanceId_ ); }; FABRIC_FIELDS_01(instanceId_); private: uint64 instanceId_; }; }
0.96875
1
Frameworks/UIKit.framework/UIFocusAnimationCoordinator.h
shaojiankui/iOS10-Runtime-Headers
36
7999699
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/UIKit.framework/UIKit */ @interface UIFocusAnimationCoordinator : NSObject { long long _activeFocusAnimation; NSMutableDictionary * _configurations; NSMutableDictionary * _coordinatedAnimations; NSMutableDictionary * _coordinatedCompletions; UIFocusUpdateContext * _focusUpdateContext; bool _locked; } @property (getter=_activeAnimationDuration, nonatomic, readonly) double activeAnimationDuration; @property (getter=_activeConfiguration, nonatomic, readonly, copy) _UIFocusAnimationConfiguration *activeConfiguration; @property (nonatomic, readonly) long long activeFocusAnimation; @property (getter=_animationDelay, nonatomic, readonly) double animationDelay; @property (getter=_animationOptions, nonatomic, readonly) unsigned long long animationOptions; @property (getter=_configurations, nonatomic, readonly) NSMutableDictionary *configurations; @property (getter=_coordinatedAnimations, nonatomic, readonly) NSMutableDictionary *coordinatedAnimations; @property (getter=_coordinatedCompletions, nonatomic, readonly) NSMutableDictionary *coordinatedCompletions; @property (getter=_focusUpdateContext, nonatomic, readonly) UIFocusUpdateContext *focusUpdateContext; @property (getter=_focusingAnimationDuration, nonatomic, readonly) double focusingAnimationDuration; @property (getter=_isLocked, nonatomic, readonly) bool locked; @property (getter=_unfocusingAnimationDuration, nonatomic, readonly) double unfocusingAnimationDuration; @property (getter=_unfocusingRepositionAnimationDuration, nonatomic, readonly) double unfocusingRepositionAnimationDuration; + (id)_focusAnimationCoordinatorForAnimationType:(long long)arg1 withConfiguration:(id)arg2 inContext:(id)arg3; + (id)_focusingAnimationCoordinatorWithConfiguration:(id)arg1 inContext:(id)arg2; + (id)_unfocusingAnimationCoordinatorWithConfiguration:(id)arg1 inContext:(id)arg2; - (void).cxx_destruct; - (double)_activeAnimationDuration; - (id)_activeConfiguration; - (void)_animate; - (void)_animateFocusAnimation:(long long)arg1; - (double)_animationDelay; - (unsigned long long)_animationOptions; - (void)_applyBlocks:(id)arg1 releaseBlocks:(id /* block */)arg2; - (void)_cancelFocusAnimation:(long long)arg1; - (id)_configurationForFocusAnimation:(long long)arg1; - (id)_configurations; - (void)_configureWithFocusUpdateContext:(id)arg1; - (id)_coordinatedAnimations; - (id)_coordinatedAnimationsForFocusAnimation:(long long)arg1 createIfNeeded:(bool)arg2; - (id)_coordinatedCompletions; - (id)_coordinatedCompletionsForFocusAnimation:(long long)arg1 createIfNeeded:(bool)arg2; - (id)_focusUpdateContext; - (double)_focusingAnimationDuration; - (id)_initWithFocusUpdateContext:(id)arg1; - (bool)_isLocked; - (void)_prepareForFocusAnimation:(long long)arg1; - (void)_setConfiguration:(id)arg1 forFocusAnimation:(long long)arg2; - (double)_unfocusingAnimationDuration; - (double)_unfocusingRepositionAnimationDuration; - (long long)activeFocusAnimation; - (void)addCoordinatedAnimations:(id /* block */)arg1 completion:(id /* block */)arg2; - (void)addCoordinatedAnimationsForAnimation:(long long)arg1 animations:(id /* block */)arg2 completion:(id /* block */)arg3; - (id)init; @end
0.507813
1
SDK/Example/How_to/OpenNCC-EMMC/VSC/How_to_use_sdk/inc/moviFloat32.h
EyecloudAi/OpenNCC-SDK
2
7999707
// *************************************************************************** // Copyright(C)2011 Movidius Ltd. All rights reserved // --------------------------------------------------------------------------- // File : moviFloat32.h // Description: Header file for float operations // --------------------------------------------------------------------------- // HISTORY // Version | Date | Owner | Purpose // --------------------------------------------------------------------------- // 0.1 | | <NAME> | Initial version // *************************************************************************** #ifndef __MVFLOAT32_H__ #define __MVFLOAT32_H__ #define MOVIDIUS_FP32 // rounding modes #define F32_RND_NEAREST_EVEN 0 #define F32_RND_MINUS_INF 1 #define F32_RND_PLUS_INF 2 #define F32_RND_TO_ZERO 3 // detect tinyness mode #define F32_DETECT_TINY_AFTER_RND 0 #define F32_DETECT_TINY_BEFORE_RND 1 // exceptions #define F32_EX_INEXACT 0x00000001//0x00000020 #define F32_EX_DIV_BY_ZERO 0x00000002//0x00000004 #define F32_EX_INVALID 0x00000004//0x00000001 #define F32_EX_UNDERFLOW 0x00000008//0x00000010 #define F32_EX_OVERFLOW 0x00000010//0x00000008 #define F32_NAN_DEFAULT 0xFFC00000 #define F64_NAN_DEFAULT_H 0xFFF80000 #define F64_NAN_DEFAULT_L 0x00000000 //Macros #define EXTRACT_F16_SIGN(x) ((x >> 15) & 0x1) #define EXTRACT_F16_EXP(x) ((x >> 10) & 0x1F) #define EXTRACT_F16_FRAC(x) (x & 0x000003FF) #define EXTRACT_F32_SIGN(x) ((x >> 31) & 0x1) #define EXTRACT_F32_EXP(x) ((x >> 23) & 0xFF) #define EXTRACT_F32_FRAC(x) (x & 0x007FFFFF) #define EXTRACT_F64_FRAC_H(x) (x & 0x000FFFFF) #define EXTRACT_F64_EXP(x) ((x >> 20) & 0x7FF) #define EXTRACT_F64_SIGN(x) ((x >> 31) & 0x1) #define RESET_SNAN_BIT(x) x = x | 0x00400000 #define PACK_F32(x, y, z) ((x << 31) + (y << 23) + z) #define PACK_F16(x, y, z) ((x << 15) + (y << 10) + z) typedef struct { unsigned int low; unsigned int high; } T_F64; #define F16_IS_NAN(x) ((x & 0x7FFF)> 0x7C00) #define F16_IS_SNAN(x) (((x & 0x7E00) == 0x7C00)&&((x & 0x1FF)> 0)) #define F32_IS_NAN(x) ((x & 0x7FFFFFFF)> 0x7F800000) #define F32_IS_SNAN(x) (((x & 0x7FC00000) == 0x7F800000)&&((x & 0x3FFFFF)> 0)) #define F64_IS_NAN(x) ((0xFFE00000 <=(x.high << 1))&&((x.low != 0)||((x.high & 0x000FFFFF) != 0))) #define F64_IS_SNAN(x) ((((x.high >> 19)& 0xFFF) == 0xFFE)&&((x.low != 0)||((x.high & 0x0007FFFF) != 0))) unsigned int u32_to_f32_conv(int x, unsigned int rnd_mode, unsigned int* exceptions); unsigned int i32_to_f32_conv(int x, unsigned int rnd_mode, unsigned int* exceptions); int f32_to_i32_conv(unsigned int x, unsigned int rnd_mode, unsigned int* exceptions); T_F64 f32_to_f64_conv(unsigned int x, unsigned int* exceptions); unsigned int f64_to_f32_conv(unsigned int high, unsigned int low, unsigned int rnd_mode, unsigned int* exceptions); unsigned int round_f32_to_i32(unsigned int x, unsigned int rnd_mode, unsigned int* exceptions); unsigned int f16_to_f32_conv(unsigned int x, unsigned int* exceptions); unsigned int f32_to_f16_conv(unsigned int x, unsigned int rnd_mode, unsigned int* exceptions); unsigned int f32_add(unsigned int op1, unsigned int op2, unsigned int rnd_mode, unsigned int* exceptions); unsigned int f32_sub(unsigned int op1, unsigned int op2, unsigned int rnd_mode, unsigned int* exceptions); unsigned int f32_mul(unsigned int op1, unsigned int op2, unsigned int rnd_mode, unsigned int* exceptions); unsigned int f32_div(unsigned int op1, unsigned int op2, unsigned int rnd_mode, unsigned int* exceptions); unsigned int f32_sqrt(unsigned int x, unsigned int rnd_mode, unsigned int* exceptions); T_F64 f64_add(T_F64 op1, T_F64 op2, unsigned int rnd_mode, unsigned int* exceptions); T_F64 f64_sub(T_F64 op1, T_F64 op2, unsigned int rnd_mode, unsigned int* exceptions); #endif
1.039063
1
Pods/Target Support Files/Pods-eKTSforIOS/Pods-eKTSforIOS-umbrella.h
jisooooo04/capstone09_ekts
0
7999715
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double Pods_eKTSforIOSVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_eKTSforIOSVersionString[];
0.296875
0
c_src/ex_quic/lsquic_utils.h
mickel8/ex_quic
5
7999723
#pragma once #ifndef LSQUIC_DEMO_LSQUIC_UTILS_H #define LSQUIC_DEMO_LSQUIC_UTILS_H #endif //LSQUIC_DEMO_LSQUIC_UTILS_H #include <stdio.h> #include <stdlib.h> #include <lsquic.h> char *get_conn_status_str(enum LSQUIC_CONN_STATUS status); void init_logger(char *level);
0.855469
1
dtndht/rating.h
ibrdtn/dtndht
3
7999731
/* * rating.h * * Created on: 06.02.2012 * Author: <NAME> */ #ifndef RATING_H_ #define RATING_H_ #include "config.h" #include "bloom.h" #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #ifdef HAVE_OPENSSL_SHA_H #include <openssl/sha.h> #else #include "sha1.h" #define SHA_CTX sha1_context #define SHA_DIGEST_LENGTH 20 #define SHA1_Init( CTX ) \ sha1_starts( (CTX) ) #define SHA1( BUF, LEN, OUT) \ sha1((BUF), (unsigned char *)(LEN), (OUT)) #define SHA1_Update( CTX, BUF, LEN ) \ sha1_update( (CTX), (unsigned char *)(BUF), (LEN) ) #define SHA1_Final( OUT, CTX ) \ sha1_finish( (CTX), (OUT) ) #endif struct dht_result_rating { struct sockaddr_storage *ss; BLOOM *frombloom; int rating; struct dht_result_rating *next; }; struct dht_rating_entry { unsigned char key[SHA_DIGEST_LENGTH]; time_t updated; struct dht_result_rating *ratings; struct dht_rating_entry *next; }; /** * return the rating of the given sockaddr_storage as target for this id * this function adds the sender to a bloom filter to prevent double counting * If the head does not exist, it will be created and returned, otherwise the old head is returned */ int get_rating(unsigned char *info_hash, const struct sockaddr_storage *target, const struct sockaddr *from, int fromlen); // Destroys the all ratings void free_ratings(); #endif /* RATING_H_ */
1.53125
2
src/be_byteslib.c
Skiars/berry
211
7999739
/******************************************************************** ** Copyright (c) 2018-2020 <NAME> - <NAME> ** This file is part of the Berry default interpreter. ** <EMAIL>, https://github.com/Skiars/berry ** See Copyright Notice in the LICENSE file or at ** https://github.com/Skiars/berry/blob/master/LICENSE ********************************************************************/ #include "be_object.h" #include "be_string.h" #include "be_strlib.h" #include "be_list.h" #include "be_func.h" #include "be_exec.h" #include "be_vm.h" #include "be_mem.h" #include "be_constobj.h" #include <string.h> #include <ctype.h> #define BYTES_DEFAULT_SIZE 28 // default pre-reserved size for buffer (keep 4 bytes for len/size) #define BYTES_MAX_SIZE (32*1024) // max 32Kb #define BYTES_OVERHEAD 4 // bytes overhead to be added when allocating (used to store len and size) #define BYTES_HEADROOM 8 // keep a natural headroom of 8 bytes when resizing #define BYTES_SIZE_FIXED -1 // if size is -1, then the bytes object cannot be reized #define BYTES_SIZE_MAPPED -2 // if size is -2, then the bytes object is mapped to a fixed memory region, i.e. cannot be resized #define BYTES_RESIZE_ERROR "attribute_error" #define BYTES_RESIZE_MESSAGE "bytes object size if fixed and cannot be resized" /* be_raise(vm, BYTES_RESIZE_ERROR, BYTES_RESIZE_MESSAGE); */ typedef struct buf_impl { int32_t size; // size in bytes of the buffer int32_t len; // current size of the data in buffer. Invariant: len <= size uint8_t *bufptr; // the actual data int32_t prev_size; // previous value read from the instance int32_t prev_len; // previous value read from the instance uint8_t *prev_bufptr; bbool fixed; // is size fixed? (actually encoded as negative size) bbool mapped; } buf_impl; /******************************************************************** ** Base64 lib from https://github.com/Densaugeo/base64_arduino ** ********************************************************************/ /* binary_to_base64: * Description: * Converts a single byte from a binary value to the corresponding base64 character * Parameters: * v - Byte to convert * Returns: * ascii code of base64 character. If byte is >= 64, then there is not corresponding base64 character * and 255 is returned */ static unsigned char binary_to_base64(unsigned char v); /* base64_to_binary: * Description: * Converts a single byte from a base64 character to the corresponding binary value * Parameters: * c - Base64 character (as ascii code) * Returns: * 6-bit binary value */ static unsigned char base64_to_binary(unsigned char c); /* encode_base64_length: * Description: * Calculates length of base64 string needed for a given number of binary bytes * Parameters: * input_length - Amount of binary data in bytes * Returns: * Number of base64 characters needed to encode input_length bytes of binary data */ static unsigned int encode_base64_length(unsigned int input_length); /* decode_base64_length: * Description: * Calculates number of bytes of binary data in a base64 string * Parameters: * input - Base64-encoded null-terminated string * Returns: * Number of bytes of binary data in input */ static unsigned int decode_base64_length(unsigned char input[]); /* encode_base64: * Description: * Converts an array of bytes to a base64 null-terminated string * Parameters: * input - Pointer to input data * input_length - Number of bytes to read from input pointer * output - Pointer to output string. Null terminator will be added automatically * Returns: * Length of encoded string in bytes (not including null terminator) */ static unsigned int encode_base64(unsigned char input[], unsigned int input_length, unsigned char output[]); /* decode_base64: * Description: * Converts a base64 null-terminated string to an array of bytes * Parameters: * input - Pointer to input string * output - Pointer to output array * Returns: * Number of bytes in the decoded binary */ static unsigned int decode_base64(unsigned char input[], unsigned char output[]); static unsigned char binary_to_base64(unsigned char v) { // Capital letters - 'A' is ascii 65 and base64 0 if(v < 26) return v + 'A'; // Lowercase letters - 'a' is ascii 97 and base64 26 if(v < 52) return v + 71; // Digits - '0' is ascii 48 and base64 52 if(v < 62) return v - 4; // '+' is ascii 43 and base64 62 if(v == 62) return '+'; // '/' is ascii 47 and base64 63 if(v == 63) return '/'; return 64; } static unsigned char base64_to_binary(unsigned char c) { // Capital letters - 'A' is ascii 65 and base64 0 if('A' <= c && c <= 'Z') return c - 'A'; // Lowercase letters - 'a' is ascii 97 and base64 26 if('a' <= c && c <= 'z') return c - 71; // Digits - '0' is ascii 48 and base64 52 if('0' <= c && c <= '9') return c + 4; // '+' is ascii 43 and base64 62 if(c == '+') return 62; // '/' is ascii 47 and base64 63 if(c == '/') return 63; return 255; } static unsigned int encode_base64_length(unsigned int input_length) { return (input_length + 2)/3*4; } static unsigned int decode_base64_length(unsigned char input[]) { unsigned char *start = input; while(base64_to_binary(input[0]) < 64) { ++input; } unsigned int input_length = input - start; unsigned int output_length = input_length/4*3; switch(input_length % 4) { default: return output_length; case 2: return output_length + 1; case 3: return output_length + 2; } } static unsigned int encode_base64(unsigned char input[], unsigned int input_length, unsigned char output[]) { unsigned int full_sets = input_length/3; // While there are still full sets of 24 bits... for(unsigned int i = 0; i < full_sets; ++i) { output[0] = binary_to_base64( input[0] >> 2); output[1] = binary_to_base64((input[0] & 0x03) << 4 | input[1] >> 4); output[2] = binary_to_base64((input[1] & 0x0F) << 2 | input[2] >> 6); output[3] = binary_to_base64( input[2] & 0x3F); input += 3; output += 4; } switch(input_length % 3) { case 0: output[0] = '\0'; break; case 1: output[0] = binary_to_base64( input[0] >> 2); output[1] = binary_to_base64((input[0] & 0x03) << 4); output[2] = '='; output[3] = '='; output[4] = '\0'; break; case 2: output[0] = binary_to_base64( input[0] >> 2); output[1] = binary_to_base64((input[0] & 0x03) << 4 | input[1] >> 4); output[2] = binary_to_base64((input[1] & 0x0F) << 2); output[3] = '='; output[4] = '\0'; break; } return encode_base64_length(input_length); } static unsigned int decode_base64(unsigned char input[], unsigned char output[]) { unsigned int output_length = decode_base64_length(input); // While there are still full sets of 24 bits... for(unsigned int i = 2; i < output_length; i += 3) { output[0] = base64_to_binary(input[0]) << 2 | base64_to_binary(input[1]) >> 4; output[1] = base64_to_binary(input[1]) << 4 | base64_to_binary(input[2]) >> 2; output[2] = base64_to_binary(input[2]) << 6 | base64_to_binary(input[3]); input += 4; output += 3; } switch(output_length % 3) { case 1: output[0] = base64_to_binary(input[0]) << 2 | base64_to_binary(input[1]) >> 4; break; case 2: output[0] = base64_to_binary(input[0]) << 2 | base64_to_binary(input[1]) >> 4; output[1] = base64_to_binary(input[1]) << 4 | base64_to_binary(input[2]) >> 2; break; } return output_length; } /******************************************************************** ** Buffer low-level implementation ** ** Extracted from Tasmota SBuffer lib ********************************************************************/ // static inline uint8_t* buf_get_buf(buf_impl* attr) // { // return &attr->bufptr[0]; // } // shrink or increase. If increase, fill with zeores. Cannot go beyond `size` static void buf_set_len(buf_impl* attr, const size_t len) { uint16_t old_len = attr->len; attr->len = ((int32_t)len <= attr->size) ? (int32_t)len : attr->size; if (old_len < attr->len) { memset((void*) &attr->bufptr[old_len], 0, attr->len - old_len); } } static size_t buf_add1(buf_impl* attr, const uint8_t data) // append 8 bits value { if (attr->len < attr->size) { // do we have room for 1 byte attr->bufptr[attr->len++] = data; } return attr->len; } static size_t buf_add2_le(buf_impl* attr, const uint16_t data) // append 16 bits value { if (attr->len < attr->size - 1) { // do we have room for 2 bytes attr->bufptr[attr->len++] = data; attr->bufptr[attr->len++] = data >> 8; } return attr->len; } static size_t buf_add2_be(buf_impl* attr, const uint16_t data) // append 16 bits value { if (attr->len < attr->size - 1) { // do we have room for 2 bytes attr->bufptr[attr->len++] = data >> 8; attr->bufptr[attr->len++] = data; } return attr->len; } static size_t buf_add4_le(buf_impl* attr, const uint32_t data) // append 32 bits value { if (attr->len < attr->size - 3) { // do we have room for 4 bytes attr->bufptr[attr->len++] = data; attr->bufptr[attr->len++] = data >> 8; attr->bufptr[attr->len++] = data >> 16; attr->bufptr[attr->len++] = data >> 24; } return attr->len; } size_t buf_add4_be(buf_impl* attr, const uint32_t data) // append 32 bits value { if (attr->len < attr->size - 3) { // do we have room for 4 bytes attr->bufptr[attr->len++] = data >> 24; attr->bufptr[attr->len++] = data >> 16; attr->bufptr[attr->len++] = data >> 8; attr->bufptr[attr->len++] = data; } return attr->len; } static size_t buf_add_buf(buf_impl* attr, buf_impl* attr2) { if (attr->len + attr2->len <= attr->size) { for (int32_t i = 0; i < attr2->len; i++) { attr->bufptr[attr->len++] = attr2->bufptr[i]; } } return attr->len; } static uint8_t buf_get1(buf_impl* attr, int offset) { if ((offset >= 0) && (offset < attr->len)) { return attr->bufptr[offset]; } return 0; } static void buf_set1(buf_impl* attr, size_t offset, uint8_t data) { if ((int32_t)offset < attr->len) { attr->bufptr[offset] = data; } } static void buf_set2_le(buf_impl* attr, size_t offset, uint16_t data) { if ((int32_t)offset + 1 < attr->len) { attr->bufptr[offset] = data & 0xFF; attr->bufptr[offset+1] = data >> 8; } } static void buf_set2_be(buf_impl* attr, size_t offset, uint16_t data) { if ((int32_t)offset + 1 < attr->len) { attr->bufptr[offset+1] = data & 0xFF; attr->bufptr[offset] = data >> 8; } } static uint16_t buf_get2_le(buf_impl* attr, size_t offset) { if ((int32_t)offset + 1 < attr->len) { return attr->bufptr[offset] | (attr->bufptr[offset+1] << 8); } return 0; } static uint16_t buf_get2_be(buf_impl* attr, size_t offset) { if ((int32_t)offset + 1 < attr->len) { return attr->bufptr[offset+1] | (attr->bufptr[offset] << 8); } return 0; } static void buf_set4_le(buf_impl* attr, size_t offset, uint32_t data) { if ((int32_t)offset + 3 < attr->len) { attr->bufptr[offset] = data & 0xFF; attr->bufptr[offset+1] = (data >> 8) & 0xFF; attr->bufptr[offset+2] = (data >> 16) & 0xFF; attr->bufptr[offset+3] = data >> 24; } } static void buf_set4_be(buf_impl* attr, size_t offset, uint32_t data) { if ((int32_t)offset + 3 < attr->len) { attr->bufptr[offset+3] = data & 0xFF; attr->bufptr[offset+2] = (data >> 8) & 0xFF; attr->bufptr[offset+1] = (data >> 16) & 0xFF; attr->bufptr[offset] = data >> 24; } } static uint32_t buf_get4_le(buf_impl* attr, size_t offset) { if ((int32_t)offset + 3 < attr->len) { return attr->bufptr[offset] | (attr->bufptr[offset+1] << 8) | (attr->bufptr[offset+2] << 16) | (attr->bufptr[offset+3] << 24); } return 0; } static uint32_t buf_get4_be(buf_impl* attr, size_t offset) { if ((int32_t)offset + 3 < attr->len) { return attr->bufptr[offset+3] | (attr->bufptr[offset+2] << 8) | (attr->bufptr[offset+1] << 16) | (attr->bufptr[offset] << 24); } return 0; } // nullptr accepted static bbool buf_equals(buf_impl* buf1, buf_impl* buf2) { if (buf1 == buf2) { return btrue; } if (!buf1 || !buf2) { return bfalse; } // at least one attr is not empty // we know that both buf1 and buf2 are non-null if (buf1->len != buf2->len) { return bfalse; } size_t len = buf1->len; for (uint32_t i=0; i<len; i++) { if (buf_get1(buf1, i) != buf_get1(buf2, i)) { return bfalse; } } return btrue; } static uint8_t asc2byte(char chr) { uint8_t rVal = 0; if (isdigit(chr)) { rVal = chr - '0'; } else if (chr >= 'A' && chr <= 'F') { rVal = chr + 10 - 'A'; } else if (chr >= 'a' && chr <= 'f') { rVal = chr + 10 - 'a'; } return rVal; } // does not check if there is enough room before hand, truncated if buffer too small static void buf_add_hex(buf_impl* attr, const char *hex, size_t len) { uint8_t val; for (; len > 1; len -= 2) { val = asc2byte(*hex++) << 4; val |= asc2byte(*hex++); buf_add1(attr, val); } } /******************************************************************** ** Wrapping into lib ********************************************************************/ /* load instance attribute into a single structure, and store 'previous' values in order to later update only the changed ones */ /* stack item 1 must contain the instance */ buf_impl m_read_attributes(bvm *vm, int idx) { buf_impl attr; be_getmember(vm, idx, ".p"); attr.bufptr = attr.prev_bufptr = be_tocomptr(vm, -1); be_pop(vm, 1); be_getmember(vm, idx, ".len"); attr.len = attr.prev_len = be_toint(vm, -1); be_pop(vm, 1); be_getmember(vm, idx, ".size"); int32_t signed_size = be_toint(vm, -1); attr.fixed = bfalse; attr.mapped = bfalse; if (signed_size < 0) { if (signed_size == BYTES_SIZE_MAPPED) { attr.mapped = btrue; } signed_size = attr.len; attr.fixed = btrue; } attr.size = attr.prev_size = signed_size; be_pop(vm, 1); return attr; } /* Write back attributes to the bytes instance, only if values changed after loading */ /* stack item 1 must contain the instance */ void m_write_attributes(bvm *vm, int rel_idx, const buf_impl * attr) { int idx = be_absindex(vm, rel_idx); if (attr->bufptr != attr->prev_bufptr) { be_pushcomptr(vm, attr->bufptr); be_setmember(vm, idx, ".p"); be_pop(vm, 1); } if (attr->len != attr->prev_len) { be_pushint(vm, attr->len); be_setmember(vm, idx, ".len"); be_pop(vm, 1); } int32_t new_size = attr->size; if (attr->mapped) { new_size = BYTES_SIZE_MAPPED; } else if (attr->fixed) { new_size = BYTES_SIZE_FIXED; } if (new_size != attr->prev_size) { be_pushint(vm, new_size); be_setmember(vm, idx, ".size"); be_pop(vm, 1); } } // buf_impl * bytes_realloc(bvm *vm, buf_impl *oldbuf, int32_t size) void bytes_realloc(bvm *vm, buf_impl * attr, int32_t size) { if (!attr->fixed && size < 4) { size = 4; } if (size > BYTES_MAX_SIZE) { size = BYTES_MAX_SIZE; } size_t oldsize = attr->bufptr ? attr->size : 0; attr->bufptr = (uint8_t*) be_realloc(vm, attr->bufptr, oldsize, size); /* malloc */ attr->size = size; if (!attr->bufptr) { attr->len = 0; /* allocate a new buffer */ } } /* allocate a new `bytes` object with pre-allocated size */ static void bytes_new_object(bvm *vm, size_t size) { be_getbuiltin(vm, "bytes"); be_pushint(vm, size); be_call(vm, 1); be_pop(vm, 1); } /* * constructor for bytes() * Arg0 is always self * * Option 1: main use * Arg1: string - a string representing the bytes in HEX * * Option 2: * Arg1: string - a string representing the bytes in HEX * Arg2: int - pre-reserved buffer size. If negative, size is fixed and cannot be later changed * * Option 3: used by subclasses like ctypes * Arg1: int - pre-reserved buffer size. If negative, size is fixed and cannot be later changed * * Option 4: mapped buffer * Arg1: comptr - buffer address of the mapped buffer * Arg2: int - buffer size. Always fixed (negative or positive) * * */ static int m_init(bvm *vm) { int argc = be_top(vm); buf_impl attr = { 0, 0, NULL, 0, -1, NULL, bfalse, bfalse }; /* initialize prev_values to invalid to force a write at the end */ /* size cannot be 0, len cannot be negative */ const char * hex_in = NULL; int32_t size_arg = 0; if (argc > 1 && be_isint(vm, 2)) { size_arg = be_toint(vm, 2); /* raw size arg, can be positive or negative */ } else if (argc > 2 && be_isint(vm, 3)) { size_arg = be_toint(vm, 3); /* raw size arg, can be positive or negative */ } if (argc > 1 && be_iscomptr(vm, 2)) { if (size_arg) { attr.len = (size_arg < 0) ? -size_arg : size_arg; attr.bufptr = be_tocomptr(vm, 2); attr.fixed = btrue; attr.mapped = btrue; m_write_attributes(vm, 1, &attr); /* write attributes back to instance */ be_return_nil(vm); } else { be_raise(vm, "value_error", "size is required"); } } if (size_arg == 0) { size_arg = BYTES_DEFAULT_SIZE; } /* if not specified, use default size */ /* compute actual size to be reserved */ if (size_arg >= 0) { size_arg += BYTES_HEADROOM; /* add automatic headroom to slightly overallocate */ if (size_arg > attr.size) { attr.size = size_arg; } } else { attr.size = -size_arg; /* set the size to a fixed negative value */ attr.fixed = btrue; } size_arg = attr.size; /* if arg1 is string, we convert hex */ if (argc > 1 && be_isstring(vm, 2)) { hex_in = be_tostring(vm, 2); if (hex_in) { size_arg = strlen(hex_in) / 2; /* allocate headroom */ } /* check if fixed size that we have the right size */ if (size_arg > attr.size) { if (attr.fixed) { be_raise(vm, BYTES_RESIZE_ERROR, BYTES_RESIZE_MESSAGE); } else { attr.size = size_arg; } } } /* allocate */ bytes_realloc(vm, &attr, attr.size); /* allocate new buffer */ if (!attr.bufptr) { be_throw(vm, BE_MALLOC_FAIL); } if (hex_in) { buf_add_hex(&attr, hex_in, strlen(hex_in)); } /* if fixed size, set len to size */ if (attr.fixed) { buf_set_len(&attr, attr.size); } m_write_attributes(vm, 1, &attr); /* write attributes back to instance */ be_return_nil(vm); } /* deallocate buffer */ static int m_deinit(bvm *vm) { buf_impl attr = m_read_attributes(vm, 1); if (attr.bufptr != NULL && !attr.mapped) { be_realloc(vm, attr.bufptr, attr.size, 0); } attr.size = 0; attr.len = 0; attr.bufptr = NULL; m_write_attributes(vm, 1, &attr); be_return_nil(vm); } /* grow or shrink to the exact value */ /* stack item 1 must contain the instance */ void _bytes_resize(bvm *vm, buf_impl * attr, size_t new_size) { bytes_realloc(vm, attr, new_size); if (!attr->bufptr) { be_throw(vm, BE_MALLOC_FAIL); } } /* grow if needed but don't shrink */ /* if grow, then add some headroom */ /* stack item 1 must contain the instance */ void bytes_resize(bvm *vm, buf_impl * attr, size_t new_size) { if (attr->mapped) { return; } /* if mapped, don't bother with allocation */ /* when resized to smaller, we introduce a new heurstic */ /* If the buffer is 64 bytes or smaller, don't shrink */ /* Shrink buffer only if target size is smaller than half the original size */ if (attr->size >= (int32_t)new_size) { /* enough room, consider if need to shrink */ if (attr->size <= 64) { return; } /* don't shrink if below 64 bytes */ if (attr->size < (int32_t)new_size * 2) { return; } } _bytes_resize(vm, attr, new_size); } buf_impl bytes_check_data(bvm *vm, size_t add_size) { buf_impl attr = m_read_attributes(vm, 1); /* check if the `size` is big enough */ if (attr.len + (int32_t)add_size > attr.size) { /* it does not fit so we need to realocate the buffer */ bytes_resize(vm, &attr, attr.len + add_size); } return attr; } static size_t tohex(char * out, size_t outsz, const uint8_t * in, size_t insz) { static const char * hex = "0123456789ABCDEF"; const uint8_t * pin = in; char * pout = out; for (; pin < in + insz; pout += 2, pin++) { pout[0] = hex[((*pin)>>4) & 0xF]; pout[1] = hex[ (*pin) & 0xF]; if (pout + 3 > out + outsz) { break; } /* check overflow */ } pout[0] = 0; /* terminating Nul char */ return pout - out; } static int m_tostring(bvm *vm) { int argc = be_top(vm); int32_t max_len = 32; /* limit to 32 bytes by default */ int truncated = 0; if (argc > 1 && be_isint(vm, 2)) { max_len = be_toint(vm, 2); /* you can specify the len as second argument, or 0 for unlimited */ } buf_impl attr = m_read_attributes(vm, 1); int32_t len = attr.len; if (max_len > 0 && len > max_len) { len = max_len; /* limit output size */ truncated = 1; } size_t hex_len = len * 2 + 5 + 2 + 2 + 1 + truncated * 3; /* reserve size for `bytes("")\0` - 9 chars */ char * hex_out = be_pushbuffer(vm, hex_len); size_t l = be_strlcpy(hex_out, "bytes('", hex_len); l += tohex(&hex_out[l], hex_len - l, attr.bufptr, len); if (truncated) { l += be_strlcpy(&hex_out[l], "...", hex_len - l); } l += be_strlcpy(&hex_out[l], "')", hex_len - l); be_pushnstring(vm, hex_out, l); /* make escape string from buffer */ be_remove(vm, -2); /* remove buffer */ be_return(vm); } /* * Copy the buffer into a string without any changes */ static int m_asstring(bvm *vm) { buf_impl attr = bytes_check_data(vm, 0); be_pushnstring(vm, (const char*) attr.bufptr, attr.len); be_return(vm); } static int m_fromstring(bvm *vm) { int argc = be_top(vm); if (argc >= 2 && be_isstring(vm, 2)) { const char *s = be_tostring(vm, 2); int32_t len = be_strlen(vm, 2); /* calling be_strlen to support null chars in string */ buf_impl attr = bytes_check_data(vm, 0); if (attr.fixed && attr.len != len) { be_raise(vm, BYTES_RESIZE_ERROR, BYTES_RESIZE_MESSAGE); } bytes_resize(vm, &attr, len); /* resize if needed */ if (len > attr.size) { len = attr.size; } /* avoid overflow */ memmove(attr.bufptr, s, len); attr.len = len; be_pop(vm, 1); /* remove arg to leave instance */ m_write_attributes(vm, 1, &attr); /* update attributes */ be_return(vm); } be_raise(vm, "type_error", "operand must be a string"); be_return_nil(vm); } /* * Add an int made of 1, 2 or 4 bytes, in little or big endian * `add(value:int[, size:int = 1]) -> instance` * * size: may be 1, 2, 4 (little endian), or -1, -2, -4 (big endian) * obvisouly -1 is idntical to 1 * size==0 does nothing */ static int m_add(bvm *vm) { int argc = be_top(vm); buf_impl attr = bytes_check_data(vm, 4); /* we reserve 4 bytes anyways */ if (attr.fixed) { be_raise(vm, BYTES_RESIZE_ERROR, BYTES_RESIZE_MESSAGE); } if (argc >= 2 && be_isint(vm, 2)) { int32_t v = be_toint(vm, 2); int vsize = 1; if (argc >= 3 && be_isint(vm, 3)) { vsize = be_toint(vm, 3); } switch (vsize) { case 0: break; case -1: /* fallback below */ case 1: buf_add1(&attr, v); break; case 2: buf_add2_le(&attr, v); break; case 4: buf_add4_le(&attr, v); break; case -2: buf_add2_be(&attr, v); break; case -4: buf_add4_be(&attr, v); break; default: be_raise(vm, "type_error", "size must be -4, -2, -1, 0, 1, 2 or 4."); } be_pop(vm, argc - 1); m_write_attributes(vm, 1, &attr); /* update attributes */ be_return(vm); } be_return_nil(vm); } /* * Get an int made of 1, 2 or 4 bytes, in little or big endian * `get(index:int[, size:int = 1]) -> int` * * size: may be 1, 2, 4 (little endian), or -1, -2, -4 (big endian) * obvisouly -1 is identical to 1 * 0 returns nil */ static int m_get(bvm *vm, bbool sign) { int argc = be_top(vm); buf_impl attr = bytes_check_data(vm, 0); /* we reserve 4 bytes anyways */ if (argc >=2 && be_isint(vm, 2)) { int32_t idx = be_toint(vm, 2); int vsize = 1; if (argc >= 3 && be_isint(vm, 3)) { vsize = be_toint(vm, 3); } int ret = 0; switch (vsize) { case 0: break; case -1: /* fallback below */ case 1: ret = buf_get1(&attr, idx); if (sign) { ret = (int8_t)(uint8_t) ret; } break; case 2: ret = buf_get2_le(&attr, idx); if (sign) { ret = (int16_t)(uint16_t) ret; } break; case 4: ret = buf_get4_le(&attr, idx); break; case -2: ret = buf_get2_be(&attr, idx); if (sign) { ret = (int16_t)(uint16_t) ret; } break; case -4: ret = buf_get4_be(&attr, idx); break; default: be_raise(vm, "type_error", "size must be -4, -2, -1, 0, 1, 2 or 4."); } be_pop(vm, argc - 1); if (vsize != 0) { be_pushint(vm, ret); } else { be_pushnil(vm); } be_return(vm); } be_return_nil(vm); } /* signed int */ static int m_geti(bvm *vm) { return m_get(vm, 1); } /* unsigned int */ static int m_getu(bvm *vm) { return m_get(vm, 0); } /* * Set an int made of 1, 2 or 4 bytes, in little or big endian * `set(index:int, value:int[, size:int = 1]) -> nil` * * size: may be 1, 2, 4 (little endian), or -1, -2, -4 (big endian) * obvisouly -1 is identical to 1 * 0 returns nil */ static int m_set(bvm *vm) { int argc = be_top(vm); buf_impl attr = bytes_check_data(vm, 0); /* we reserve 4 bytes anyways */ if (argc >=3 && be_isint(vm, 2) && be_isint(vm, 3)) { int32_t idx = be_toint(vm, 2); int32_t value = be_toint(vm, 3); int vsize = 1; if (argc >= 4 && be_isint(vm, 4)) { vsize = be_toint(vm, 4); } switch (vsize) { case 0: break; case -1: /* fallback below */ case 1: buf_set1(&attr, idx, value); break; case 2: buf_set2_le(&attr, idx, value); break; case 4: buf_set4_le(&attr, idx, value); break; case -2: buf_set2_be(&attr, idx, value); break; case -4: buf_set4_be(&attr, idx, value); break; default: be_raise(vm, "type_error", "size must be -4, -2, -1, 0, 1, 2 or 4."); } be_pop(vm, argc - 1); m_write_attributes(vm, 1, &attr); /* update attributes */ be_return_nil(vm); } be_return_nil(vm); } static int m_setitem(bvm *vm) { int argc = be_top(vm); buf_impl attr = bytes_check_data(vm, 0); /* we reserve 4 bytes anyways */ if (argc >=3 && be_isint(vm, 2) && be_isint(vm, 3)) { int index = be_toint(vm, 2); int val = be_toint(vm, 3); if (index >= 0 && index < attr.len) { buf_set1(&attr, index, val); m_write_attributes(vm, 1, &attr); /* update attributes */ be_return_nil(vm); } } be_raise(vm, "index_error", "bytes index out of range or value non int"); be_return_nil(vm); } static int m_item(bvm *vm) { int argc = be_top(vm); buf_impl attr = bytes_check_data(vm, 0); /* we reserve 4 bytes anyways */ if (argc >=2 && be_isint(vm, 2)) { /* single byte */ int index = be_toint(vm,2); if (index < 0) { index += attr.len; } if (index >= 0 && index < attr.len) { be_pushint(vm, buf_get1(&attr, index)); be_return(vm); } } if (argc >= 2 && be_isinstance(vm, 2)) { const char *cname = be_classname(vm, 2); if (!strcmp(cname, "range")) { bint lower, upper; bint size = attr.len; /* get index range */ be_getmember(vm, 2, "__lower__"); lower = be_toint(vm, -1); be_pop(vm, 1); be_getmember(vm, 2, "__upper__"); upper = be_toint(vm, -1); be_pop(vm, 1); /* handle negative limits */ if (upper < 0) { upper += attr.len; } if (lower < 0) { lower += attr.len; } /* protection scope */ upper = upper < size ? upper : size - 1; lower = lower < 0 ? 0 : lower; /* construction result list instance */ bytes_new_object(vm, upper > lower ? upper-lower : 0); buf_impl attr2 = m_read_attributes(vm, -1); for (; lower <= upper; ++lower) { buf_add1(&attr2, attr.bufptr[lower]); } m_write_attributes(vm, -1, &attr2); /* update instance */ be_return(vm); } } be_raise(vm, "index_error", "bytes index out of range"); be_return_nil(vm); } static int m_size(bvm *vm) { buf_impl attr = m_read_attributes(vm, 1); be_pushint(vm, attr.len); be_return(vm); } static int m_resize(bvm *vm) { int argc = be_top(vm); buf_impl attr = m_read_attributes(vm, 1); if (argc <= 1 || !be_isint(vm, 2)) { be_raise(vm, "type_error", "size must be of type 'int'"); } int new_len = be_toint(vm, 2); if (new_len < 0) { new_len = 0; } if (attr.fixed && attr.len != new_len) { be_raise(vm, BYTES_RESIZE_ERROR, BYTES_RESIZE_MESSAGE); } bytes_resize(vm, &attr, new_len); buf_set_len(&attr, new_len); be_pop(vm, 1); m_write_attributes(vm, 1, &attr); /* update instance */ be_return(vm); } static int m_clear(bvm *vm) { buf_impl attr = m_read_attributes(vm, 1); if (attr.fixed) { be_raise(vm, BYTES_RESIZE_ERROR, BYTES_RESIZE_MESSAGE); } attr.len = 0; m_write_attributes(vm, 1, &attr); /* update instance */ be_return_nil(vm); } static int m_merge(bvm *vm) { int argc = be_top(vm); buf_impl attr = m_read_attributes(vm, 1); /* no resize yet */ if (argc >= 2 && be_isbytes(vm, 2)) { buf_impl attr2 = m_read_attributes(vm, 2); /* allocate new object */ bytes_new_object(vm, attr.len + attr2.len); buf_impl attr3 = m_read_attributes(vm, -1); buf_add_buf(&attr3, &attr); buf_add_buf(&attr3, &attr2); m_write_attributes(vm, -1, &attr3); /* update instance */ be_return(vm); /* return self */ } be_raise(vm, "type_error", "operand must be bytes"); be_return_nil(vm); /* return self */ } static int m_copy(bvm *vm) { buf_impl attr = m_read_attributes(vm, 1); bytes_new_object(vm, attr.len); buf_impl attr2 = m_read_attributes(vm, -1); buf_add_buf(&attr2, &attr); m_write_attributes(vm, -1, &attr2); /* update instance */ be_return(vm); /* return self */ } /* accept bytes or int as operand */ static int m_connect(bvm *vm) { int argc = be_top(vm); buf_impl attr = m_read_attributes(vm, 1); if (attr.fixed) { be_raise(vm, BYTES_RESIZE_ERROR, BYTES_RESIZE_MESSAGE); } if (argc >= 2 && (be_isbytes(vm, 2) || be_isint(vm, 2))) { if (be_isint(vm, 2)) { bytes_resize(vm, &attr, attr.len + 1); /* resize */ buf_add1(&attr, be_toint(vm, 2)); m_write_attributes(vm, 1, &attr); /* update instance */ be_pushvalue(vm, 1); be_return(vm); /* return self */ } else { buf_impl attr2 = m_read_attributes(vm, 2); bytes_resize(vm, &attr, attr.len + attr2.len); /* resize buf1 for total size */ buf_add_buf(&attr, &attr2); m_write_attributes(vm, 1, &attr); /* update instance */ be_pushvalue(vm, 1); be_return(vm); /* return self */ } } be_raise(vm, "type_error", "operand must be bytes or int"); be_return_nil(vm); /* return self */ } static int bytes_equal(bvm *vm, bbool iseq) { bbool ret; buf_impl attr1 = m_read_attributes(vm, 1); if (!be_isbytes(vm, 2)) { ret = !iseq; } else { buf_impl attr2 = m_read_attributes(vm, 2); if (buf_equals(&attr1, &attr2)) { ret = iseq; } else { ret = !iseq; } } be_pushbool(vm, ret); be_return(vm); } static int m_equal(bvm *vm) { return bytes_equal(vm, btrue); } static int m_nequal(bvm *vm) { return bytes_equal(vm, bfalse); } /* * Converts bytes() to a base64 string * * Note: there are no line breaks inserted * * `b.tob64() -> string` */ static int m_tob64(bvm *vm) { buf_impl attr = m_read_attributes(vm, 1); int32_t len = attr.len; int32_t b64_len = encode_base64_length(len) + 1; /* size of base64 encoded string for this binary length, add NULL terminator */ char * b64_out = be_pushbuffer(vm, b64_len); size_t converted = encode_base64(attr.bufptr, len, (unsigned char*)b64_out); be_pushnstring(vm, b64_out, converted); /* make string from buffer */ be_remove(vm, -2); /* remove buffer */ be_return(vm); } /* * Converts base63 to bytes() * * `bytes().fromb64() -> bytes()` */ static int m_fromb64(bvm *vm) { int argc = be_top(vm); if (argc >= 2 && be_isstring(vm, 2)) { const char *s = be_tostring(vm, 2); int32_t bin_len = decode_base64_length((unsigned char*)s); /* do a first pass to calculate the buffer size */ buf_impl attr = m_read_attributes(vm, 1); if (attr.fixed && attr.len != bin_len) { be_raise(vm, BYTES_RESIZE_ERROR, BYTES_RESIZE_MESSAGE); } bytes_resize(vm, &attr, bin_len); /* resize if needed */ if (bin_len > attr.size) { /* avoid overflow */ be_raise(vm, "memory_error", "cannot allocate buffer"); } int32_t bin_len_final = decode_base64((unsigned char*)s, attr.bufptr); /* decode */ attr.len = bin_len_final; be_pop(vm, 1); /* remove arg to leave instance */ m_write_attributes(vm, 1, &attr); /* update instance */ be_return(vm); } be_raise(vm, "type_error", "operand must be a string"); be_return_nil(vm); } /* * Advanced API */ /* * Retrieve the memory address of the raw buffer * to be used in C functions. * * Note: the address is guaranteed not to move unless you * resize the buffer * * `_buffer() -> comptr` */ static int m_buffer(bvm *vm) { buf_impl attr = m_read_attributes(vm, 1); be_pushcomptr(vm, attr.bufptr); be_return(vm); } /* * External API */ BERRY_API void * be_pushbytes(bvm *vm, const void * bytes, size_t len) { bytes_new_object(vm, len); buf_impl attr = m_read_attributes(vm, -1); if ((int32_t)len > attr.size) { len = attr.size; } /* double check if the buffer allocated was smaller */ if (bytes) { /* if bytes is null, buffer is filled with zeros */ memmove((void*)attr.bufptr, bytes, len); } else { memset((void*)attr.bufptr, 0, len); } attr.len = len; m_write_attributes(vm, -1, &attr); /* update instance */ /* bytes instance is on top of stack */ return (void*)attr.bufptr; } BERRY_API const void *be_tobytes(bvm *vm, int rel_index, size_t *len) { int index = be_absindex(vm, rel_index); if (be_isbytes(vm, index)) { buf_impl attr = m_read_attributes(vm, index); if (len) { *len = attr.len; } return (void*) attr.bufptr; } if (len) { *len = 0; } return NULL; } BERRY_API bbool be_isbytes(bvm *vm, int rel_index) { bbool ret = bfalse; int index = be_absindex(vm, rel_index); if (be_isinstance(vm, index)) { be_getbuiltin(vm, "bytes"); if (be_isderived(vm, index)) { ret = btrue; } be_pop(vm, 1); } return ret; } /* Helper code to compile bytecode class Bytes : bytes #------------------------------------------------------------- #- 'getbits' function #- #- Reads a bit-field in a `bytes()` object #- #- Input: #- offset_bits (int): bit number to start reading from (0 = LSB) #- len_bits (int): how many bits to read #- Output: #- valuer (int) #-------------------------------------------------------------# def getbits(offset_bits, len_bits) if len_bits <= 0 || len_bits > 32 raise "value_error", "length in bits must be between 0 and 32" end var ret = 0 var offset_bytes = offset_bits >> 3 offset_bits = offset_bits % 8 var bit_shift = 0 #- bit number to write to -# while (len_bits > 0) var block_bits = 8 - offset_bits # how many bits to read in the current block (block = byte) -# if block_bits > len_bits block_bits = len_bits end var mask = ( (1<<block_bits) - 1) << offset_bits ret = ret | ( ((self[offset_bytes] & mask) >> offset_bits) << bit_shift) #- move the input window -# bit_shift += block_bits len_bits -= block_bits offset_bits = 0 #- start at full next byte -# offset_bytes += 1 end return ret end #------------------------------------------------------------- #- 'setbits' function #- #- Writes a bit-field in a `bytes()` object #- #- Input: #- offset_bits (int): bit number to start writing to (0 = LSB) #- len_bits (int): how many bits to write #- val (int): value to set #-------------------------------------------------------------# def setbits(offset_bits, len_bits, val) if len_bits < 0 || len_bits > 32 raise "value_error", "length in bits must be between 0 and 32" end val = int(val) #- convert bool or others to int -# var offset_bytes = offset_bits >> 3 offset_bits = offset_bits % 8 while (len_bits > 0) var block_bits = 8 - offset_bits #- how many bits to write in the current block (block = byte) -# if block_bits > len_bits block_bits = len_bits end var mask_val = (1<<block_bits) - 1 #- mask to the n bits to get for this block -# var mask_b_inv = 0xFF - (mask_val << offset_bits) self[offset_bytes] = (self[offset_bytes] & mask_b_inv) | ((val & mask_val) << offset_bits) #- move the input window -# val >>= block_bits len_bits -= block_bits offset_bits = 0 #- start at full next byte -# offset_bytes += 1 end return self end end */ /******************************************************************** ** Solidified function: getbits ********************************************************************/ be_local_closure(getbits, /* name */ be_nested_proto( 9, /* nstack */ 3, /* argc */ 0, /* varg */ 0, /* has upvals */ NULL, /* no upvals */ 0, /* has sup protos */ NULL, /* no sub protos */ 1, /* has constants */ ( &(const bvalue[ 5]) { /* constants */ /* K0 */ be_const_int(0), /* K1 */ be_nested_string("value_error", 773297791, 11), /* K2 */ be_nested_string("length in bits must be between 0 and 32", -1710458168, 39), /* K3 */ be_const_int(3), /* K4 */ be_const_int(1), }), (be_nested_const_str("getbits", -1200798317, 7)), (be_nested_const_str("input", -103256197, 5)), ( &(const binstruction[32]) { /* code */ 0x180C0500, // 0000 LE R3 R2 K0 0x740E0002, // 0001 JMPT R3 #0005 0x540E001F, // 0002 LDINT R3 32 0x240C0403, // 0003 GT R3 R2 R3 0x780E0000, // 0004 JMPF R3 #0006 0xB0060302, // 0005 RAISE 1 K1 K2 0x580C0000, // 0006 LDCONST R3 K0 0x3C100303, // 0007 SHR R4 R1 K3 0x54160007, // 0008 LDINT R5 8 0x10040205, // 0009 MOD R1 R1 R5 0x58140000, // 000A LDCONST R5 K0 0x24180500, // 000B GT R6 R2 K0 0x781A0011, // 000C JMPF R6 #001F 0x541A0007, // 000D LDINT R6 8 0x04180C01, // 000E SUB R6 R6 R1 0x241C0C02, // 000F GT R7 R6 R2 0x781E0000, // 0010 JMPF R7 #0012 0x5C180400, // 0011 MOVE R6 R2 0x381E0806, // 0012 SHL R7 K4 R6 0x041C0F04, // 0013 SUB R7 R7 K4 0x381C0E01, // 0014 SHL R7 R7 R1 0x94200004, // 0015 GETIDX R8 R0 R4 0x2C201007, // 0016 AND R8 R8 R7 0x3C201001, // 0017 SHR R8 R8 R1 0x38201005, // 0018 SHL R8 R8 R5 0x300C0608, // 0019 OR R3 R3 R8 0x00140A06, // 001A ADD R5 R5 R6 0x04080406, // 001B SUB R2 R2 R6 0x58040000, // 001C LDCONST R1 K0 0x00100904, // 001D ADD R4 R4 K4 0x7001FFEB, // 001E JMP #000B 0x80040600, // 001F RET 1 R3 }) ) ); /*******************************************************************/ /******************************************************************** ** Solidified function: setbits ********************************************************************/ be_local_closure(setbits, /* name */ be_nested_proto( 10, /* nstack */ 4, /* argc */ 0, /* varg */ 0, /* has upvals */ NULL, /* no upvals */ 0, /* has sup protos */ NULL, /* no sub protos */ 1, /* has constants */ ( &(const bvalue[ 5]) { /* constants */ /* K0 */ be_const_int(0), /* K1 */ be_nested_string("value_error", 773297791, 11), /* K2 */ be_nested_string("length in bits must be between 0 and 32", -1710458168, 39), /* K3 */ be_const_int(3), /* K4 */ be_const_int(1), }), (be_nested_const_str("setbits", -1532559129, 7)), (be_nested_const_str("input", -103256197, 5)), ( &(const binstruction[37]) { /* code */ 0x14100500, // 0000 LT R4 R2 K0 0x74120002, // 0001 JMPT R4 #0005 0x5412001F, // 0002 LDINT R4 32 0x24100404, // 0003 GT R4 R2 R4 0x78120000, // 0004 JMPF R4 #0006 0xB0060302, // 0005 RAISE 1 K1 K2 0x60100009, // 0006 GETGBL R4 G9 0x5C140600, // 0007 MOVE R5 R3 0x7C100200, // 0008 CALL R4 1 0x5C0C0800, // 0009 MOVE R3 R4 0x3C100303, // 000A SHR R4 R1 K3 0x54160007, // 000B LDINT R5 8 0x10040205, // 000C MOD R1 R1 R5 0x24140500, // 000D GT R5 R2 K0 0x78160014, // 000E JMPF R5 #0024 0x54160007, // 000F LDINT R5 8 0x04140A01, // 0010 SUB R5 R5 R1 0x24180A02, // 0011 GT R6 R5 R2 0x781A0000, // 0012 JMPF R6 #0014 0x5C140400, // 0013 MOVE R5 R2 0x381A0805, // 0014 SHL R6 K4 R5 0x04180D04, // 0015 SUB R6 R6 K4 0x541E00FE, // 0016 LDINT R7 255 0x38200C01, // 0017 SHL R8 R6 R1 0x041C0E08, // 0018 SUB R7 R7 R8 0x94200004, // 0019 GETIDX R8 R0 R4 0x2C201007, // 001A AND R8 R8 R7 0x2C240606, // 001B AND R9 R3 R6 0x38241201, // 001C SHL R9 R9 R1 0x30201009, // 001D OR R8 R8 R9 0x98000808, // 001E SETIDX R0 R4 R8 0x3C0C0605, // 001F SHR R3 R3 R5 0x04080405, // 0020 SUB R2 R2 R5 0x58040000, // 0021 LDCONST R1 K0 0x00100904, // 0022 ADD R4 R4 K4 0x7001FFE8, // 0023 JMP #000D 0x80040000, // 0024 RET 1 R0 }) ) ); /*******************************************************************/ #if !BE_USE_PRECOMPILED_OBJECT void be_load_byteslib(bvm *vm) { static const bnfuncinfo members[] = { { ".p", NULL }, { ".size", NULL }, { ".len", NULL }, { "_buffer", m_buffer }, { "init", m_init }, { "deinit", m_deinit }, { "tostring", m_tostring }, { "asstring", m_asstring }, { "fromstring", m_fromstring }, { "tob64", m_tob64 }, { "fromb64", m_fromb64 }, { "add", m_add }, { "get", m_getu }, { "geti", m_geti }, { "set", m_set }, { "seti", m_set }, // setters for signed and unsigned are identical { "item", m_item }, { "setitem", m_setitem }, { "size", m_size }, { "resize", m_resize }, { "clear", m_clear }, { "copy", m_copy }, { "+", m_merge }, { "..", m_connect }, { "==", m_equal }, { "!=", m_nequal }, { NULL, (bntvfunc) BE_CLOSURE }, /* mark section for berry closures */ { "getbits", (bntvfunc) &getbits_closure }, { "setbits", (bntvfunc) &setbits_closure }, { NULL, NULL } }; be_regclass(vm, "bytes", members); } #else /* @const_object_info_begin class be_class_bytes (scope: global, name: bytes) { .p, var .size, var .len, var _buffer, func(m_buffer) init, func(m_init) deinit, func(m_deinit) tostring, func(m_tostring) asstring, func(m_asstring) fromstring, func(m_fromstring) tob64, func(m_tob64) fromb64, func(m_fromb64) add, func(m_add) get, func(m_getu) geti, func(m_geti) set, func(m_set) seti, func(m_set) item, func(m_item) setitem, func(m_setitem) size, func(m_size) resize, func(m_resize) clear, func(m_clear) copy, func(m_copy) +, func(m_merge) .., func(m_connect) ==, func(m_equal) !=, func(m_nequal) getbits, closure(getbits_closure) setbits, closure(setbits_closure) } @const_object_info_end */ #include "../generate/be_fixed_be_class_bytes.h" #endif
1.734375
2
3party/gtk+-3.12.1/gtk/gtkcssshadowsvalue.c
kongaraju/antkorp
1
7999747
/* GTK - The GIMP Toolkit * Copyright (C) 2011 Red Hat, Inc. * * Author: <NAME> <<EMAIL>> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "gtkcssshadowsvalueprivate.h" #include "gtkcairoblurprivate.h" #include "gtkcssshadowvalueprivate.h" #include <string.h> struct _GtkCssValue { GTK_CSS_VALUE_BASE guint len; GtkCssValue *values[1]; }; static GtkCssValue * gtk_css_shadows_value_new (GtkCssValue **values, guint len); static void gtk_css_value_shadows_free (GtkCssValue *value) { guint i; for (i = 0; i < value->len; i++) { _gtk_css_value_unref (value->values[i]); } g_slice_free1 (sizeof (GtkCssValue) + sizeof (GtkCssValue *) * (value->len - 1), value); } static GtkCssValue * gtk_css_value_shadows_compute (GtkCssValue *value, guint property_id, GtkStyleProviderPrivate *provider, int scale, GtkCssComputedValues *values, GtkCssComputedValues *parent_values, GtkCssDependencies *dependencies) { GtkCssValue *result; GtkCssDependencies child_deps; guint i; if (value->len == 0) return _gtk_css_value_ref (value); result = gtk_css_shadows_value_new (value->values, value->len); for (i = 0; i < value->len; i++) { result->values[i] = _gtk_css_value_compute (value->values[i], property_id, provider, scale, values, parent_values, &child_deps); *dependencies = _gtk_css_dependencies_union (*dependencies, child_deps); } return result; } static gboolean gtk_css_value_shadows_equal (const GtkCssValue *value1, const GtkCssValue *value2) { guint i; /* XXX: Should we fill up here? */ if (value1->len != value2->len) return FALSE; for (i = 0; i < value1->len; i++) { if (!_gtk_css_value_equal (value1->values[i], value2->values[i])) return FALSE; } return TRUE; } static GtkCssValue * gtk_css_value_shadows_transition (GtkCssValue *start, GtkCssValue *end, guint property_id, double progress) { guint i, len; GtkCssValue **values; /* catches the important case of 2 none values */ if (start == end) return _gtk_css_value_ref (start); if (start->len > end->len) len = start->len; else len = end->len; values = g_newa (GtkCssValue *, len); for (i = 0; i < MIN (start->len, end->len); i++) { values[i] = _gtk_css_value_transition (start->values[i], end->values[i], property_id, progress); if (values[i] == NULL) { while (i--) _gtk_css_value_unref (values[i]); return NULL; } } if (start->len > end->len) { for (; i < len; i++) { GtkCssValue *fill = _gtk_css_shadow_value_new_for_transition (start->values[i]); values[i] = _gtk_css_value_transition (start->values[i], fill, property_id, progress); _gtk_css_value_unref (fill); if (values[i] == NULL) { while (i--) _gtk_css_value_unref (values[i]); return NULL; } } } else { for (; i < len; i++) { GtkCssValue *fill = _gtk_css_shadow_value_new_for_transition (end->values[i]); values[i] = _gtk_css_value_transition (fill, end->values[i], property_id, progress); _gtk_css_value_unref (fill); if (values[i] == NULL) { while (i--) _gtk_css_value_unref (values[i]); return NULL; } } } return gtk_css_shadows_value_new (values, len); } static void gtk_css_value_shadows_print (const GtkCssValue *value, GString *string) { guint i; if (value->len == 0) { g_string_append (string, "none"); return; } for (i = 0; i < value->len; i++) { if (i > 0) g_string_append (string, ", "); _gtk_css_value_print (value->values[i], string); } } static const GtkCssValueClass GTK_CSS_VALUE_SHADOWS = { gtk_css_value_shadows_free, gtk_css_value_shadows_compute, gtk_css_value_shadows_equal, gtk_css_value_shadows_transition, gtk_css_value_shadows_print }; static GtkCssValue none_singleton = { &GTK_CSS_VALUE_SHADOWS, 1, 0, { NULL } }; GtkCssValue * _gtk_css_shadows_value_new_none (void) { return _gtk_css_value_ref (&none_singleton); } static GtkCssValue * gtk_css_shadows_value_new (GtkCssValue **values, guint len) { GtkCssValue *result; g_return_val_if_fail (values != NULL, NULL); g_return_val_if_fail (len > 0, NULL); result = _gtk_css_value_alloc (&GTK_CSS_VALUE_SHADOWS, sizeof (GtkCssValue) + sizeof (GtkCssValue *) * (len - 1)); result->len = len; memcpy (&result->values[0], values, sizeof (GtkCssValue *) * len); return result; } GtkCssValue * _gtk_css_shadows_value_parse (GtkCssParser *parser) { GtkCssValue *value, *result; GPtrArray *values; if (_gtk_css_parser_try (parser, "none", TRUE)) return _gtk_css_shadows_value_new_none (); values = g_ptr_array_new (); do { value = _gtk_css_shadow_value_parse (parser); if (value == NULL) { g_ptr_array_set_free_func (values, (GDestroyNotify) _gtk_css_value_unref); g_ptr_array_free (values, TRUE); return NULL; } g_ptr_array_add (values, value); } while (_gtk_css_parser_try (parser, ",", TRUE)); result = gtk_css_shadows_value_new ((GtkCssValue **) values->pdata, values->len); g_ptr_array_free (values, TRUE); return result; } void _gtk_css_shadows_value_paint_layout (const GtkCssValue *shadows, cairo_t *cr, PangoLayout *layout) { guint i; g_return_if_fail (shadows->class == &GTK_CSS_VALUE_SHADOWS); for (i = 0; i < shadows->len; i++) { _gtk_css_shadow_value_paint_layout (shadows->values[i], cr, layout); } } void _gtk_css_shadows_value_paint_icon (const GtkCssValue *shadows, cairo_t *cr) { guint i; g_return_if_fail (shadows->class == &GTK_CSS_VALUE_SHADOWS); for (i = 0; i < shadows->len; i++) { _gtk_css_shadow_value_paint_icon (shadows->values[i], cr); } } void _gtk_css_shadows_value_paint_spinner (const GtkCssValue *shadows, cairo_t *cr, gdouble radius, gdouble progress) { guint i; g_return_if_fail (shadows->class == &GTK_CSS_VALUE_SHADOWS); for (i = 0; i < shadows->len; i++) { _gtk_css_shadow_value_paint_spinner (shadows->values[i], cr, radius, progress); } } void _gtk_css_shadows_value_paint_box (const GtkCssValue *shadows, cairo_t *cr, const GtkRoundedBox *padding_box, gboolean inset) { guint i; g_return_if_fail (shadows->class == &GTK_CSS_VALUE_SHADOWS); for (i = 0; i < shadows->len; i++) { if (inset == _gtk_css_shadow_value_get_inset (shadows->values[i])) _gtk_css_shadow_value_paint_box (shadows->values[i], cr, padding_box); } } void _gtk_css_shadows_value_get_extents (const GtkCssValue *shadows, GtkBorder *border) { guint i; GtkBorder b = { 0 }; const GtkCssValue *shadow; gdouble hoffset, voffset, spread, radius, clip_radius; g_return_if_fail (shadows->class == &GTK_CSS_VALUE_SHADOWS); for (i = 0; i < shadows->len; i++) { shadow = shadows->values[i]; if (_gtk_css_shadow_value_get_inset (shadow)) continue; _gtk_css_shadow_value_get_geometry (shadow, &hoffset, &voffset, &radius, &spread); clip_radius = _gtk_cairo_blur_compute_pixels (radius); b.top = MAX (0, clip_radius + spread - voffset); b.right = MAX (0, clip_radius + spread + hoffset); b.bottom = MAX (0, clip_radius + spread + voffset); b.left = MAX (0, clip_radius + spread - hoffset); border->top = MAX (border->top, b.top); border->right = MAX (border->right, b.right); border->bottom = MAX (border->bottom, b.bottom); border->left = MAX (border->left, b.left); } }
1.109375
1
System/Library/PrivateFrameworks/BusinessChatService.framework/BCSVisibility.h
zhangkn/iOS14Header
1
7999755
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:54:00 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/BusinessChatService.framework/BusinessChatService * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <BusinessChatService/BusinessChatService-Structs.h> #import <ProtocolBuffer/PBCodable.h> #import <libobjc.A.dylib/NSCopying.h> @class NSString; @interface BCSVisibility : PBCodable <NSCopying> { double _ratio; NSString* _country; NSString* _language; SCD_Struct_BC1 _has; } @property (nonatomic,readonly) BOOL hasLanguage; @property (nonatomic,retain) NSString * language; //@synthesize language=_language - In the implementation block @property (nonatomic,readonly) BOOL hasCountry; @property (nonatomic,retain) NSString * country; //@synthesize country=_country - In the implementation block @property (assign,nonatomic) BOOL hasRatio; @property (assign,nonatomic) double ratio; //@synthesize ratio=_ratio - In the implementation block -(id)copyWithZone:(NSZone*)arg1 ; -(void)writeTo:(id)arg1 ; -(NSString *)country; -(BOOL)readFrom:(id)arg1 ; -(NSString *)language; -(void)setLanguage:(NSString *)arg1 ; -(double)ratio; -(void)setRatio:(double)arg1 ; -(BOOL)hasLanguage; -(void)setCountry:(NSString *)arg1 ; -(void)mergeFrom:(id)arg1 ; -(void)copyTo:(id)arg1 ; -(BOOL)isEqual:(id)arg1 ; -(BOOL)hasCountry; -(unsigned long long)hash; -(id)description; -(id)dictionaryRepresentation; -(void)setHasRatio:(BOOL)arg1 ; -(BOOL)hasRatio; @end
0.714844
1
sdk-overrides/include/ets_sys.h
RomanYudintsev/nodemcu-firmware
4
7999763
#ifndef SDK_OVERRIDES_INCLUDE_ETS_SYS_H_ #define SDK_OVERRIDES_INCLUDE_ETS_SYS_H_ #include_next "ets_sys.h" #include "../libc/c_stdarg.h" int ets_sprintf(char *str, const char *format, ...) __attribute__ ((format (printf, 2, 3))); int ets_vsprintf (char *d, const char *s, va_list ap); extern ETSTimer *timer_list; #endif /* SDK_OVERRIDES_INCLUDE_ETS_SYS_H_ */
0.072266
0
Engine/Source/Core/Intersectable/IndexedKdtree/IndexedItemEndpoint.h
jasonoscar88/Photon-v2
88
7999771
#pragma once #include "Common/primitive_type.h" namespace ph { enum class EEndpoint { MIN, MAX }; struct IndexedItemEndpoint { real position; int index; EEndpoint type; }; }// end namespace ph
0.613281
1
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Experimental.Http.Htt-2465a87a.h
marferfer/SpinOff-LoL
0
7999779
// This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Experimental.Http/1.9.0/HttpResponseHeader.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Experimental{namespace Http{struct HttpResponseHeader;}}} namespace g{namespace Uno{namespace Collections{struct Dictionary;}}} namespace g{ namespace Experimental{ namespace Http{ // public sealed class HttpResponseHeader :7 // { uType* HttpResponseHeader_typeof(); void HttpResponseHeader__ctor__fn(HttpResponseHeader* __this); void HttpResponseHeader__get_Headers_fn(HttpResponseHeader* __this, ::g::Uno::Collections::Dictionary** __retval); void HttpResponseHeader__set_Headers_fn(HttpResponseHeader* __this, ::g::Uno::Collections::Dictionary* value); void HttpResponseHeader__New1_fn(HttpResponseHeader** __retval); void HttpResponseHeader__get_ReasonPhrase_fn(HttpResponseHeader* __this, uString** __retval); void HttpResponseHeader__set_ReasonPhrase_fn(HttpResponseHeader* __this, uString* value); void HttpResponseHeader__get_StatusCode_fn(HttpResponseHeader* __this, int32_t* __retval); void HttpResponseHeader__set_StatusCode_fn(HttpResponseHeader* __this, int32_t* value); struct HttpResponseHeader : uObject { uStrong< ::g::Uno::Collections::Dictionary*> _Headers; uStrong<uString*> _ReasonPhrase; int32_t _StatusCode; void ctor_(); ::g::Uno::Collections::Dictionary* Headers(); void Headers(::g::Uno::Collections::Dictionary* value); uString* ReasonPhrase(); void ReasonPhrase(uString* value); int32_t StatusCode(); void StatusCode(int32_t value); static HttpResponseHeader* New1(); }; // } }}} // ::g::Experimental::Http
1.007813
1
Src/Math/vector3.h
bouzi71/STM32LedCube
1
7999787
#ifndef __VECTOR3_H #define __VECTOR3_H class Matrix3; class Matrix4; class Vector3 { public: Vector3() : x(), y(), z() {} Vector3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} explicit Vector3(float _xyz) : x(_xyz), y(_xyz), z(_xyz) {} Vector3(const Vector3& o) : x(o.x), y(o.y), z(o.z) {} public: const Vector3& operator+=(const Vector3& o); const Vector3& operator-=(const Vector3& o); const Vector3& operator*=(float f); const Vector3& operator/=(float f); Vector3& operator*=(const Matrix3& mat); Vector3& operator*=(const Matrix4& mat); float operator[](unsigned int i) const; float& operator[](unsigned int i); bool operator==(const Vector3& other) const; bool operator!=(const Vector3& other) const; bool operator <(const Vector3& other) const; bool Equal(const Vector3& other, float epsilon = 1e-6) const; public: /** @brief Set the components of a vector * @param pX X component * @param pY Y component * @param pZ Z component */ void Set(float pX, float pY, float pZ); /** @brief Get the squared length of the vector * @return Square length */ float SquareLength() const; /** @brief Get the length of the vector * @return length */ float Length() const; /** @brief Normalize the vector */ Vector3& Normalize(); /** @brief Normalize the vector with extra check for zero vectors */ Vector3& NormalizeSafe(); /** @brief Componentwise multiplication of two vectors * * Note that vec*vec yields the dot product. * @param o Second factor */ const Vector3 SymMul(const Vector3& o); float x, y, z; }; #endif
2.015625
2
Other Sources/Frameworks/Cedar-iOS.framework/Versions/A/Headers/CedarDoubleImpl.h
nybex/NYMnemonic
43
7999795
#import "StubbedMethod.h" #import "RejectedMethod.h" @protocol CedarDouble; typedef enum { CDRStubMethodNotStubbed = 0, CDRStubMethodInvoked, CDRStubWrongArguments, } CDRStubInvokeStatus; @interface CedarDoubleImpl : NSObject @property (nonatomic, retain, readonly) NSMutableArray *sent_messages; + (void)afterEach; - (id)initWithDouble:(NSObject<CedarDouble> *)parent_double; - (void)reset_sent_messages; - (Cedar::Doubles::StubbedMethod &)add_stub:(const Cedar::Doubles::StubbedMethod &)stubbed_method; - (BOOL)has_stubbed_method_for:(SEL)selector; - (void)reject_method:(const Cedar::Doubles::RejectedMethod &)rejected_method; - (BOOL)has_rejected_method_for:(SEL)selector; - (Cedar::Doubles::StubbedMethod::selector_map_t &)stubbed_methods; - (CDRStubInvokeStatus)invoke_stubbed_method:(NSInvocation *)invocation; - (void)record_method_invocation:(NSInvocation *)invocation; @end
0.933594
1
images/core/context/free5gc/lib/nextepc/core/include/core_atomic.h
my5G/OPlaceRAN
1
7999803
#ifndef __CORE_ATOMIC_H__ #define __CORE_ATOMIC_H__ #include "core.h" #include "core_errno.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * this function is required on some platforms to initialize the * atomic operation's internal structures * @param p pool * @return APR_SUCCESS on successful completion * @remark Programs do NOT need to call this directly. APR will call this * automatically from apr_initialize. * @internal */ CORE_DECLARE(status_t) atomic_init(); CORE_DECLARE(status_t) atomic_final(); /* * Atomic operations on 32-bit values * Note: Each of these functions internally implements a memory barrier * on platforms that require it */ /** * atomically read an c_uint32_t from memory * @param mem the pointer */ CORE_DECLARE(c_uint32_t) atomic_read32(volatile c_uint32_t *mem); /** * atomically set an c_uint32_t in memory * @param mem pointer to the object * @param val value that the object will assume */ CORE_DECLARE(void) atomic_set32(volatile c_uint32_t *mem, c_uint32_t val); /** * atomically add 'val' to an c_uint32_t * @param mem pointer to the object * @param val amount to add * @return old value pointed to by mem */ CORE_DECLARE(c_uint32_t) atomic_add32(volatile c_uint32_t *mem, c_uint32_t val); /** * atomically subtract 'val' from an c_uint32_t * @param mem pointer to the object * @param val amount to subtract */ CORE_DECLARE(void) atomic_sub32(volatile c_uint32_t *mem, c_uint32_t val); /** * atomically increment an c_uint32_t by 1 * @param mem pointer to the object * @return old value pointed to by mem */ CORE_DECLARE(c_uint32_t) atomic_inc32(volatile c_uint32_t *mem); /** * atomically decrement an c_uint32_t by 1 * @param mem pointer to the atomic value * @return zero if the value becomes zero on decrement, otherwise non-zero */ CORE_DECLARE(int) atomic_dec32(volatile c_uint32_t *mem); /** * compare an c_uint32_t's value with 'cmp'. * If they are the same swap the value with 'with' * @param mem pointer to the value * @param with what to swap it with * @param cmp the value to compare it to * @return the old value of *mem */ CORE_DECLARE(c_uint32_t) atomic_cas32(volatile c_uint32_t *mem, c_uint32_t with, c_uint32_t cmp); /** * exchange an c_uint32_t's value with 'val'. * @param mem pointer to the value * @param val what to swap it with * @return the old value of *mem */ CORE_DECLARE(c_uint32_t) atomic_xchg32(volatile c_uint32_t *mem, c_uint32_t val); /** * compare the pointer's value with cmp. * If they are the same swap the value with 'with' * @param mem pointer to the pointer * @param with what to swap it with * @param cmp the value to compare it to * @return the old value of the pointer */ CORE_DECLARE(void*) atomic_casptr(void *volatile *mem, void *with, const void *cmp); /** * exchange a pair of pointer values * @param mem pointer to the pointer * @param with what to swap it with * @return the old value of the pointer */ CORE_DECLARE(void*) atomic_xchgptr(void *volatile *mem, void *with); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* !__CORE_ATOMIC_H__ */
1.601563
2
src/game.c
johpetsc/Auto-Chess
0
7999811
#include "../header/game.h" void roundManager() { int check_end = 0; stage = 1; end = 1; while(end){ printf("[Game] ROUND %d\n", stage); boardManager(); printf("HP TABLE\n"); for(int i=0; i<PLAYERS; i++){ if(HPs[i]>0) printf("HP player %d: %d\n", i+1, HPs[i]); else printf("Player %d is dead.\n", i+1); } check_end = endGame(); if(check_end){ printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("Winner: %d\n", check_end); end = 0; } stage += 1; sleep(2); } } void boardManager() { int played = 0; while(played != alive_players){ pthread_mutex_lock(&mutex_board); if (board < 2) { pthread_cond_wait(&cond_full, &mutex_board); } else { if(HPs[battle_ids[0]] < 0) printf("[Game] Player %d is battling in the arena against a ghost!\n", battle_ids[1]); else if(HPs[battle_ids[1]] < 0) printf("[Game] Player %d is battling in the arena against a ghost!\n", battle_ids[0]); else printf("[Game] Players %d and %d are battling in the arena!\n", battle_ids[0], battle_ids[1]); //sleep(1); int winner_id, loser_id; winner(battle_ids[0], battle_ids[1], &winner_id, &loser_id); int damage_amt = loserDamage(winner_id, loser_id); HPs[loser_id-1] -= damage_amt; printf("[Game] Player %d Won and Player %d lost %d health points\n", winner_id, loser_id, damage_amt); board = 0; played += 2; magic = 0; } pthread_mutex_unlock(&mutex_board); } } void *generalManager() { int *id; pthread_t players[PLAYERS]; pthread_t winners[PLAYERS]; setHealth(); createPool(); for(int i=0; i<PLAYERS; i++){ pthread_mutex_init(&mutex_round[i], NULL); } for(int i=0; i<PLAYERS; i++){ pthread_cond_init(&buy_condition[i], NULL); } pthread_mutex_init(&mutex_pool, NULL); pthread_mutex_init(&mutex_board, NULL); pthread_cond_init(&cond_full, 0); pthread_cond_init(&cond_empty, 0); for (int i = 0; i < PLAYERS; i++) { id = (int*)malloc(sizeof(int)); *id = i; pthread_create(&PLAYERS[i], NULL, player, (void*)id); pthread_create(&winners[i], NULL, winner, (void*)id); } roundManager(); for (int i = 0; i < PLAYERS; i++) { pthread_join(players[i], NULL); pthread_join(winners[i], NULL); } pthread_exit(NULL); } int initGame(){ pthread_t game; pthread_create(&game, NULL, generalManager, NULL); pthread_join(game, NULL); }
1.679688
2
src/lts-lib/lts_access.c
LieuweVinkhuijzen/ltsmin
40
7999819
// -*- tab-width:4 ; indent-tabs-mode:nil -*- #include <hre/config.h> #include <lts-lib/lts.h> #include <hre/user.h> uint32_t lts_state_get_label(lts_t lts,uint32_t state_no,uint32_t label_no){ if (lts->prop_idx!=NULL){ return (uint32_t)TreeDBSGet(lts->prop_idx,lts->properties[state_no],(int)label_no); } else if (label_no==0) { return lts->properties[state_no]; } else { Abort("illegal index %d",label_no); } }
0.859375
1
experiments/test_direct.c
alevy/beetle
4
7999827
#include <time.h> #include <bluetooth/bluetooth.h> #include <bluetooth/l2cap.h> #include <bluetooth/hci.h> #include <bluetooth/hci_lib.h> #include <unistd.h> #include <stdio.h> int main(int argc, char** argv) { int hciSocket = hci_open_dev(0); int l2capSock = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP); struct sockaddr_l2 sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.l2_family = AF_BLUETOOTH; bacpy(&sockAddr.l2_bdaddr, BDADDR_ANY); sockAddr.l2_cid = htobs(4); if(bind(l2capSock, (struct sockaddr*)&sockAddr, sizeof(sockAddr)) < 0) { perror("bind"); } memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.l2_family = AF_BLUETOOTH; str2ba(argv[1], &sockAddr.l2_bdaddr); sockAddr.l2_bdaddr_type = strcmp(argv[2], "random") == 0 ? BDADDR_LE_RANDOM : BDADDR_LE_PUBLIC; sockAddr.l2_cid = htobs(4); if(connect(l2capSock, (struct sockaddr*)&sockAddr, sizeof(sockAddr)) < 0) { perror("connect"); } struct l2cap_conninfo l2capConnInfo; int l2capConnInfoLen = sizeof(l2capConnInfo); if(getsockopt(l2capSock, SOL_L2CAP, L2CAP_CONNINFO, &l2capConnInfo, &l2capConnInfoLen) < 0) { perror("conninfo"); } int hciHandle = l2capConnInfo.hci_handle; FILE* out = fopen(argv[3], "w+"); char req[3] = { 0x0A, 0x06, 0x00 }; char buf[48]; struct timespec start; struct timespec end; uint16_t interval; for (interval = 6; interval <= 800; interval *= 2) { if(hci_le_conn_update(hciSocket, l2capConnInfo.hci_handle, interval, interval, 0, 0x03E8, 0) < 0) { perror("conn_update"); } int i = 0; for (i = 0; i < 30; i++) { clock_gettime(CLOCK_REALTIME, &start); if(write(l2capSock, req, 3) < 0){ perror("write"); } int red; if((red = read(l2capSock, buf, 48)) < 0){ perror("read"); } clock_gettime(CLOCK_REALTIME, &end); printf("%f,%d\n", interval * 1.25, (end.tv_nsec - start.tv_nsec) / 1000000 + (end.tv_sec - start.tv_sec) * 1000); fprintf(out, "%f,%d\n", interval * 1.25, (end.tv_nsec - start.tv_nsec) / 1000000 + (end.tv_sec - start.tv_sec) * 1000); sync(); int skip = rand(); double skipd = ((double)skip / RAND_MAX) * interval * 1.25 * 1000; usleep((long)skipd); } } fclose(out); return 0; }
1.539063
2
src/audio/ambienceplayer.h
Eae02/tank-game
0
7999835
#pragma once #include "audiobuffer.h" #include "audiosource.h" #include "../utils/filesystem.h" #include <vector> #include <random> namespace TankGame { class AmbiencePlayer { public: explicit AmbiencePlayer(const fs::path& dirPath); void Start() { m_isPlaying = true; } void Stop(); void Update(); private: AudioSource m_source; float m_volume = 1; bool m_isPlaying = false; std::vector<AudioBuffer> m_tracks; size_t m_currentTrack; std::uniform_int_distribution<size_t> m_trackDistribution; }; }
1.382813
1
src/crypto/ConversionUtil.h
ltc-mweb/libmw
24
7999843
#pragma once #include "Context.h" #include <mw/models/crypto/Commitment.h> #include <mw/models/crypto/PublicKey.h> #include <mw/models/crypto/Signature.h> class ConversionUtil { public: ConversionUtil(const Locked<Context>& context) : m_context(context) { } PublicKey ToPublicKey(const Commitment& commitment) const; PublicKey ToPublicKey(const secp256k1_pubkey& pubkey) const; Commitment ToCommitment(const secp256k1_pedersen_commitment& commitment) const; CompactSignature ToCompact(const Signature& signature) const; CompactSignature ToCompact(const secp256k1_ecdsa_signature& signature) const; secp256k1_pubkey ToSecp256k1(const PublicKey& publicKey) const; std::vector<secp256k1_pubkey> ToSecp256k1(const std::vector<PublicKey>& publicKeys) const; secp256k1_pedersen_commitment ToSecp256k1(const Commitment& commitment) const; std::vector<secp256k1_pedersen_commitment> ToSecp256k1(const std::vector<Commitment>& commitments) const; secp256k1_ecdsa_signature ToSecp256k1(const CompactSignature& signature) const; std::vector<secp256k1_ecdsa_signature> ToSecp256k1(const std::vector<CompactSignature>& signatures) const; secp256k1_schnorrsig ToSecp256k1(const Signature& signature) const; std::vector<secp256k1_schnorrsig> ToSecp256k1(const std::vector<const Signature*>& signatures) const; Signature ToSignature(const secp256k1_schnorrsig& signature) const; private: Locked<Context> m_context; };
0.980469
1
JAMA firmware/include/SistemasdeControle/headers/restrictedOptimization/recursiveactiveset.h
tuliofalmeida/jama
6
7999851
#ifndef RECURSIVEACTIVESET_H #define RECURSIVEACTIVESET_H #ifdef testModel #include "../../../headers/restrictedOptimization/quadprog.h" #else #include "SistemasdeControle/headers/restrictedOptimization/quadprog.h" #endif namespace restrictedOptimizationHandler{ template <typename Type> class RecursiveActiveSet : public QuadProg <Type> { public: RecursiveActiveSet(){this->tol = 1e-3;} void optimize(); private: Type cost; LinAlg::Matrix<Type> activeRestrictions(const LinAlg::Matrix<Type> &A, const LinAlg::Matrix<Type> &b, Type tol = 1e-2); void RKKT(LinAlg::Matrix<Type> A, LinAlg::Matrix<Type> b, LinAlg::Matrix<Type> &P, LinAlg::Matrix<Type> &x); }; } #ifdef testModel #include "../../../src/restrictedOptimization/recursiveactiveset.hpp" #else #include "SistemasdeControle/src/restrictedOptimization/recursiveactiveset.hpp" #endif #endif // RECURSIVEACTIVESET_H
1.25
1
Desktop/test/HighwayToll_iOS/Utility/LXCategory/NSObject/NSObjcet+MAC.h
1037390459/test1
0
7999859
// // NSObjcet+MAC.h // WeiSchoolTeacher // // Created by MacKun on 15/12/14. // Copyright © 2015年 MacKun. All rights reserved. // #import <Foundation/Foundation.h> @interface NSObject(MAC) /** * 将Base64Json基类转为Json字典 */ - (id)jsonBase64Value; +(NSMutableArray*)macObjectToArray; @end
0.90625
1
Other/Headers/MMChatBackupSessionInfo.h
XWJACK/WeChatPlugin-MacOS
2
7999867
// // 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 <NAME>. // #import <objc/NSObject.h> @class NSString; @interface MMChatBackupSessionInfo : NSObject { NSString *_sessionName; long long _totalSize; NSString *_nickName; } @property(retain, nonatomic) NSString *nickName; // @synthesize nickName=_nickName; @property(nonatomic) long long totalSize; // @synthesize totalSize=_totalSize; @property(retain, nonatomic) NSString *sessionName; // @synthesize sessionName=_sessionName; - (void).cxx_destruct; - (id)init; @end
0.535156
1
WirePlanet/EffectCreators.h
CdecPGL/Shooting-Game-WirePlanet
0
7999875
#pragma once #include"NormalEffectCreator.h" class EnemySpawnEffectCreator : public CreatorTemplate < Effect > { public: EnemySpawnEffectCreator() = default; ~EnemySpawnEffectCreator() = default; std::shared_ptr<Effect> Create(const std::string&)override; }; class ScoreEffectCreator : public CreatorTemplate < Effect > { public: ScoreEffectCreator() = default; ~ScoreEffectCreator() = default; std::shared_ptr<Effect> Create(const std::string&)override; };
0.769531
1
Pod/Classes/SBRMacros.h
pegurov/SBRProjectBase
0
7999883
// // SBRMacros.h // Pods // // Created by <NAME> on 09/03/16. // // #ifndef SBRMacros_h #define SBRMacros_h #define DIRECTORY_LIBRARY [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject] #define DEFAULTS [NSUserDefaults standardUserDefaults] #define DEFAULTS_OBJ(__KEY__) [[NSUserDefaults standardUserDefaults] objectForKey:__KEY__] #define SIGNUP_FOR_NOTIFICATION(__NAME__,__SELECTOR__) [[NSNotificationCenter defaultCenter] addObserver:self selector:__SELECTOR__ name:__NAME__ object:nil] #define REMOVE_NOTIFICATION(__NAME__) [[NSNotificationCenter defaultCenter] removeObserver:self name:__NAME__ object:nil] #define POST_NOTIFICATION(__NAME__) [[NSNotificationCenter defaultCenter] postNotificationName:__NAME__ object:nil userInfo:nil] #define NSLS(__KEY__) NSLocalizedStringWithDefaultValue(__KEY__, @"Localizable", [NSBundle mainBundle], nil, nil) #define APPLICATION_VERSION [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]] #define BUILD_VERSION [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]] #define SECS_IN_DAY 86400 #define SECS_IN_HOUR 3600 #define SECS_IN_30_MINS 1800 #define IPHONE5_SCREEN_HEIGHT 568. #define IPHONE5_SCREEN_SCALE 2. #endif /* SBRMacros_h */
0.59375
1
Modules/Radiometry/OpticalCalibration/include/otbImageMetadataCorrectionParameters.h
lfyater/Orfeo
2
7999891
/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbImageMetadataCorrectionParameters_h #define otbImageMetadataCorrectionParameters_h #include "OTBOpticalCalibrationExport.h" #include "itkObject.h" #include "itkVariableSizeMatrix.h" #include "itkVariableLengthVector.h" #include "otbObjectList.h" #include "otbFilterFunctionValues.h" #include <vector> #include <iostream> namespace otb { /** \class ImageMetadataCorrectionParameters * \brief This class contains all atmospheric correction parameters. * * Each value can be read in the metadata of an image (ex: SPOT5, ...) or directly set by the user. * * \ingroup Radiometry * * * \ingroup OTBOpticalCalibration */ class OTBOpticalCalibration_EXPORT ImageMetadataCorrectionParameters : public itk::DataObject { public: /** Standard typedefs */ typedef ImageMetadataCorrectionParameters Self; typedef itk::Object Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Type macro */ itkTypeMacro(ImageMetadataCorrectionParameters, Object); /** Creation through object factory macro */ itkNewMacro(Self); typedef ObjectList<FilterFunctionValues> InternalWavelengthSpectralBandVectorType; typedef InternalWavelengthSpectralBandVectorType::Pointer WavelengthSpectralBandVectorType; /** * Set/Get the solar zenithal angle. */ itkSetMacro(SolarZenithalAngle, double); itkGetMacro(SolarZenithalAngle, double); /** * Set/Get the solar azimutal angle. */ itkSetMacro(SolarAzimutalAngle, double); itkGetMacro(SolarAzimutalAngle, double); /** * Set/Get the viewing zenithal angle. */ itkSetMacro(ViewingZenithalAngle, double); itkGetMacro(ViewingZenithalAngle, double); /** * Set/Get the viewing azimutal angle. */ itkSetMacro(ViewingAzimutalAngle, double); itkGetMacro(ViewingAzimutalAngle, double); /** * Set/Get the month. */ itkSetClampMacro(Month, unsigned int, 1, 12); itkGetMacro(Month, unsigned int); /** * Set/Get the day. */ itkSetClampMacro(Day, unsigned int, 1, 31); itkGetMacro(Day, unsigned int); /** * Set/Get the year. */ itkSetMacro(Year, unsigned int); itkGetMacro(Year, unsigned int); /** Get/Set FilterFunction file name. */ itkSetMacro(FilterFunctionValuesFileName, std::string); itkGetMacro(FilterFunctionValuesFileName, std::string); /** * Set/Get the wavelength spectral band. */ void SetWavelengthSpectralBand(const WavelengthSpectralBandVectorType& waveband) { m_WavelengthSpectralBand = waveband; } void SetWavelengthSpectralBandWithIndex(unsigned int id, const FilterFunctionValues::Pointer& function) { if (m_WavelengthSpectralBand->Size() < id + 1) { for (unsigned int j = 0; j < (id + 1 - m_WavelengthSpectralBand->Size()); ++j) { FilterFunctionValues::Pointer temp; m_WavelengthSpectralBand->PushBack(temp); } } m_WavelengthSpectralBand->SetNthElement(id, function); } WavelengthSpectralBandVectorType GetWavelengthSpectralBand() const { return m_WavelengthSpectralBand; } const WavelengthSpectralBandVectorType * GetWavelengthSpectralBandRef() const { return &m_WavelengthSpectralBand; } /** * Read a file that contains filter function values on the 6S format. */ void LoadFilterFunctionValue(const std::string& filename); void LoadFilterFunctionValue() { this->LoadFilterFunctionValue(m_FilterFunctionValuesFileName); } /** Constructor */ ImageMetadataCorrectionParameters(); /** Destructor */ ~ImageMetadataCorrectionParameters() ITK_OVERRIDE {} protected: /**PrintSelf method */ void PrintSelf(std::ostream& os, itk::Indent indent) const ITK_OVERRIDE; private: ImageMetadataCorrectionParameters(const Self &); //purposely not implemented void operator =(const Self&); //purposely not implemented /** The Solar zenithal angle */ double m_SolarZenithalAngle; /** The Solar azimutal angle */ double m_SolarAzimutalAngle; /** The Viewing zenithal angle */ double m_ViewingZenithalAngle; /** The Viewing azimutal angle */ double m_ViewingAzimutalAngle; /** The Month */ unsigned int m_Month; /** The Day (in the month) */ unsigned int m_Day; /** The Year */ unsigned int m_Year; std::string m_FilterFunctionValuesFileName; /** Wavelength for the each spectral band definition */ WavelengthSpectralBandVectorType m_WavelengthSpectralBand; }; } // end namespace otb #endif
1.179688
1
src/Engine/Headers/decodeP.h
fmccabe/cafe
6
7999899
// // Created by <NAME> on 2/3/17. // #ifndef STAR_ENCODEDP_H #define STAR_ENCODEDP_H #include "encoding.h" #include "decode.h" #include "stringBuffer.h" #include "streamDecodeP.h" typedef struct _encoding_support_ { char *errorMsg; /* Place to put error messages */ long msgSize; /* How big is that buffer */ heapPo R; /* Where should the roots go? */ } EncodeSupport, *encodePo; retCode decode(ioPo in, encodePo S, heapPo H, termPo *tgt, strBufferPo strBuffer); #endif //STAR_ENCODEDP_H
1.09375
1
find_length_longest_palindromic_substring/find_length_longest_palindromic_substring.c
ggupta2005/Programming-and-Algorithm-Questions
1
7999907
/* * This program finds the length of the longest palindromic substring * in a string. For more information on the problem, please visit the * following link: http://www.geeksforgeeks.org/longest-palindromic-substring-set-2/ */ #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<string.h> #include<stdbool.h> /* * This function returns the length of the longest palindromic substring * in a given string. If there is no palindromic substring of length * greater than one, then this function returns one. If the input string * is not valid, then this function returns zero as the the length of the * longest palindromic substring. The time complexity of this function is * O(n^2) where 'n' is the number of number of characters in the string. * The space complexity of this function is O(1). */ int get_length_longest_palindromic_substring (char* ch) { int inner_index, index, max_len, cur_len, len; /* * If the input string is NULL or its length is zero, * then return zero */ if (!ch || !strlen(ch)) { return(0); } len = strlen(ch); /* * Set the maximum length of palindromic string to zero */ max_len = 0; /* * Iterate over the length of the entire string */ for (index = 0; index < len; ++index) { inner_index = index; /* * Find the length for the odd length palindromic string with the * central character being at 'index'. */ cur_len = 1; for (inner_index = 1; ((index - inner_index) >= 0) && ((index + inner_index) < len); ++inner_index) { if (ch[index - inner_index] == ch[index + inner_index]) { /* * If the equi-distant characters around 'index' are equal, * then increment the length of current palindromic sub-string * by two */ cur_len += 2; } else { /* * Since the characters are not same, so break */ break; } } /* * If the length of the odd length palindromic substring is greater * than the current maximum length, then update the maximum length */ if (cur_len > max_len) { max_len = cur_len; } /* * Find the length for the evem length palindromic string with finding * the matching character starting at 'index'. */ cur_len = 0; for (inner_index = 1; ((index - (inner_index - 1)) >= 0) && ((index + inner_index) < len); ++inner_index) { /* * If the two characters are same, then increment the length of * current palindromic sub-string by two */ if (ch[index - (inner_index - 1)] == ch[index + inner_index]) { cur_len += 2; } else { /* * Since the characters are not same, so break */ break; } } /* * If the length of the even length palindromic substring is greater * than the current maximum length, then update the maximum length */ if (cur_len > max_len) { max_len = cur_len; } } /* * Return the length of longest palindromic substring */ return(max_len); } int main () { /* * Test 0: Test the case when the input string is NULL or empty. * The length of longest palindromic substring should be * zero. */ assert(0 == get_length_longest_palindromic_substring(NULL)); assert(0 == get_length_longest_palindromic_substring("")); /* * Test 1: Test the case when there is only one palindromic * substring in the input string and its length is odd. */ assert(1 == get_length_longest_palindromic_substring("a")); assert(3 == get_length_longest_palindromic_substring("aba")); assert(5 == get_length_longest_palindromic_substring("zabcbau")); /* * Test 2: Test the case when there is only one palindromic * substring in the input string and its length is even. */ assert(2 == get_length_longest_palindromic_substring("aa")); assert(4 == get_length_longest_palindromic_substring("xabbaz")); /* * Test 3: Test the case when there are many palindromic substrings * within a string but the length of the longest palindromic * substring is returned. */ assert(10 == get_length_longest_palindromic_substring( "abbaxbbbbbbbbbb")); assert(11 == get_length_longest_palindromic_substring( "abbbbbbbbbaxbbbbbbbbbb")); /* * Test 4: Test the case when there are no palindromic substrings of * length greater than one. */ assert(1 == get_length_longest_palindromic_substring("water")); assert(1 == get_length_longest_palindromic_substring("waterwater")); return(0); }
3.359375
3
CSVWriter.h
malord/prime
0
7999915
#ifndef PRIME_CSVWRITER_H #define PRIME_CSVWRITER_H #include "ArrayView.h" #include "Config.h" #include "StreamBuffer.h" namespace Prime { class PRIME_PUBLIC CSVWriter { public: /// Returns the total size of the escaped output. If the return value >= bufferSize then the output was /// truncated (the output will always be null terminated). If buffer is null then nothing is written and /// the size is computed. static size_t escape(char* buffer, size_t bufferSize, StringView string); /// Returns the total size of the escaped output. If the return value >= bufferSize then the output was /// truncated (the output will always be null terminated). If buffer is null then nothing is written and /// the size is computed. static size_t escapeInQuotes(char* buffer, size_t bufferSize, StringView string); static std::string escape(StringView string); static std::string escapeInQuotes(StringView string); CSVWriter(); enum { defaultBufferSize = 65536u }; /// Assign the Stream and Log to write to. If buffer is null, allocate a buffer of the specified size, /// otherwise use the supplied memory for the buffer. CSVWriter(Stream* outputStream, Log* log, size_t bufferSize = defaultBufferSize, void* buffer = NULL); void init(Stream* stream, Log* log, size_t bufferSize = defaultBufferSize, void* buffer = NULL); Log* getLog() const { return _log; } bool getErrorFlag() const { return _error; } /// The error flag is set to true if the write callback fails. void setErrorFlag(bool value) { _error = value; } /// Set the newline sequence. Defaults to \r\n. void setNewline(StringView newline); /// Returns false if the error flag is set. bool writeCell(StringView cell); /// Write a printf formatted string to the next cell. bool printfCell(const char* format, ...); /// Write a printf formatted string given a va_list. bool vprintfCell(const char* format, va_list argptr); /// Doesn't escape the text. bool writeRaw(StringView text); /// Returns false if the error flag is set. bool endRow(); /// Write an entire row followed by a newline. Calls endRow(). bool writeRow(ArrayView<const StringView> cells); /// Returns false if the error flag is set. bool flush(); private: void construct(); void beginWrite(); StreamBuffer _streamBuffer; RefPtr<Log> _log; std::string _newline; bool _needComma; std::string _cellBuffer; bool _error; PRIME_UNCOPYABLE(CSVWriter); }; } #endif
1.414063
1
MPMissions/TZK_Scripts_4_0_5/description_dlg_05.h
TZKdeveloperIF/TZK_2.12-MPMissions
1
7999923
class TemporaryAIOrderDialog: Menu { idd = -1; movingEnable = true; controlsBackground[] = {Sub_BG, Sub_BG_Light}; objects[] = {}; controls[] = { CommandAITitle, GroupOrdersLabel, GroupOrders, SendOrder, OrderLabel, TemporaryOrder, Param0Label, Param0, Param1Label, Param1, Param2Label, Param2, Param3Label, Param3, Param4Label, Param4, Exit, ReturnToAIOrder}; class Sub_BG: BackgroundWindow { x = 0.0; y = 0.0; w = 1.0; h = 0.71; }; class Sub_BG_Light: Light_BG_Window { x = 0.0; y = 0.0; w = 1.0; h = 0.71; }; class CommandAITitle: Title { style = ST_CENTER; x = 0.0; y = 0.0; w = 1.0; text = "Temporary AI Group Orders"; }; class GroupOrdersLabel: Label { x = 0.0; y = 0.02; w = 0.4; text = "Group, Last Temporary Order"; }; class GroupOrders: ListBox { idc = IDC+0; x = 0.0; y = 0.05; w = 1.0; h = 0.30 }; class OrderLabel: Label { SizeEx = 0.021; idc = IDC+1; x = 0.0; y = 0.38; w = 0.1; text = "Order"; }; class SendOrder: Button { idc = IDC+2 x = 0.1 y = 0.38 w = 0.1 h = 0.03 text = "Send" action = "btnSendOrder = true" }; class TemporaryOrder: ListBox { SizeEx = 0.021; idc = IDC+3 x = 0.0; y = 0.41; w = 0.2; h = 10*0.03; }; class Param0Label: Label { SizeEx = 0.021; idc = IDC+4 x = 0.2; y = 0.38; w = 0.16; text = "Param0"; }; class Param0: ListBox { SizeEx = 0.021; idc = IDC+5 x = 0.2; y = 0.41; w = 0.16; h = 10*0.03; }; class Param1Label: Label { SizeEx = 0.021; idc = IDC+6 x = 0.36; y = 0.38; w = 0.16; text = "Param1"; }; class Param1: ListBox { SizeEx = 0.021; idc = IDC+7 x = 0.36; y = 0.41; w = 0.16; h = 10*0.03; }; class Param2Label: Label { SizeEx = 0.021; idc = IDC+8 x = 0.52; y = 0.38; w = 0.16; text = "Param2"; }; class Param2: ListBox { SizeEx = 0.021; idc = IDC+9 x = 0.52; y = 0.41; w = 0.16; h = 10*0.03; }; class Param3Label: Label { SizeEx = 0.021; idc = IDC+10 x = 0.68; y = 0.38; w = 0.16; text = "Param3"; }; class Param3: ListBox { SizeEx = 0.021; idc = IDC+11 x = 0.68; y = 0.41; w = 0.16; h = 10*0.03; }; class Param4Label: Label { SizeEx = 0.021; idc = IDC+12 x = 0.84; y = 0.38; w = 0.16; text = "Param4"; }; class Param4: ListBox { SizeEx = 0.021; idc = IDC+13 x = 0.84; y = 0.41; w = 0.16; h = 10*0.03; }; class Exit: Button { x = 0.95 y = 0.0 w = 0.05 h = 0.03 text = "Exit" action = "closeDialog 0" }; class ReturnToAIOrder: Button { x = 0.65 y = 0.0 w = 0.3 h = 0.03 text = "Return To AI Groups Order" action = "btnReturn = true" }; }; class CommandAIDialog: Menu { idd = -1; movingEnable = true; controlsBackground[] = {Sub_BG_Light, Sub_BG}; objects[] = { }; controls[] = { CommandAITitle, GroupOrdersLabel, GroupOrders, Setting0Label, Setting0, Setting1Label, Setting1, Setting2Label, Setting2, Setting3Label, Setting3, Setting4Label, Setting4, Setting5Label, Setting5, Setting6Label, Setting6, Setting7Label, Setting7, Setting8Label, Setting8, Setting9Label, Setting9, Setting10Label, Setting10, Setting11Label, Setting11, Setting12Label, Setting12, Setting13Label, Setting13, Setting14Label, Setting14, Setting15Label, Setting15, Setting16Label, Setting16, Setting17Label, Setting17, Setting18Label, Setting18, SendOrder, OrderLabel, Order, Param0Label, Param0, Param1Label, Param1, Param2Label, Param2, Exit, Setting19Label, Setting19, Setting20Label, Setting20, Setting21Label, Setting21, Setting22Label, Setting22, Setting23Label, Setting23, Setting24Label, Setting24, Setting25Label, Setting25, TemporaryDialog }; class Sub_BG: BackgroundWindow { x = 0.0; y = 0.0; w = 1.0; h = 0.71; }; class Sub_BG_Light: Light_BG_Window { x = 0.0; y = 0.0; w = 1.0; h = 0.71; }; class Sub_BG_Dark: Dark_BG_Window { x = 0.0; y = 0.0; w = 1.0; h = 0.71; }; class CommandAITitle: Title { style = ST_CENTER; x = 0.0; y = 0.0; w = 1.0; text = "AI Group Orders"; }; class GroupOrdersLabel: Label { x = 0.0; y = 0.02; text = "Group, Current Order"; }; class GroupOrders: ListBox { idc = IDC+0; x = 0.0; y = 0.05; w = 0.6; h = 0.30 }; class SettingLabel: Label { SizeEx = 0.021; }; class SettingComboBox: ComboBox { colortext[] = {0.22,0.2,0.3,1}; SizeEx = 0.021; }; class Setting0Label: SettingLabel { idc = IDC+100; x = 0.6; y = 0.02; w = 0.4; text = "Setting0"; }; class Setting0: SettingComboBox { idc = IDC+200; x = 0.6; y = 0.05; w = 0.1; }; class Setting1Label: SettingLabel { idc = IDC+101; x = 0.7; y = 0.02; w = 0.1; text = "Setting1"; }; class Setting1: SettingComboBox { idc = IDC+201 x = 0.7; y = 0.05; w = 0.1; }; class Setting2Label: SettingLabel { idc = IDC+102; x = 0.8; y = 0.02; w = 0.1; text = "Setting2"; }; class Setting2: SettingComboBox { idc = IDC+202; x = 0.8; y = 0.05; w = 0.1; }; class Setting3Label: SettingLabel { idc = IDC+103; x = 0.9; y = 0.02; w = 0.1; text = "Setting3"; }; class Setting3: SettingComboBox { idc = IDC+203 x = 0.9; y = 0.05; w = 0.1; }; class Setting4Label: SettingLabel { idc = IDC+104; x = 0.6; y = 0.09; w = 0.2; text = "Setting4"; }; class Setting4: SettingComboBox { idc = IDC+204; x = 0.6; y = 0.12; w = 0.1; }; class Setting5Label: SettingLabel { idc = IDC+105; x = 0.7; y = 0.09; w = 0.1; text = "Setting5"; }; class Setting5: SettingComboBox { idc = IDC+205; x = 0.7; y = 0.12; w = 0.1; }; class Setting6Label: SettingLabel { idc = IDC+106; x = 0.8; y = 0.09; w = 0.2; text = "Setting6"; }; class Setting6: SettingComboBox { idc = IDC+206; x = 0.8; y = 0.12; w = 0.2; }; class Setting7Label: SettingLabel { idc = IDC+107; x = 0.8 y = 0.16 w = 0.2 text = "Setting7"; }; class Setting7: SettingComboBox { idc = IDC+207; x = 0.8 y = 0.19 w = 0.1 }; class Setting8Label: SettingLabel { idc = IDC+108; x = 0.9 y = 0.16 w = 0.1 text = "Setting8"; }; class Setting8: SettingComboBox { idc = IDC+208; x = 0.9 y = 0.19 w = 0.1 }; class Setting9Label: SettingLabel { idc = IDC+109; x = 0.8 y = 0.23 w = 0.2 text = "Setting9"; }; class Setting9: SettingComboBox { idc = IDC+209; x = 0.8 y = 0.26 w = 0.1 }; class Setting10Label: SettingLabel { idc = IDC+110; x = 0.9 y = 0.23 w = 0.1 text = "Setting10"; }; class Setting10: SettingComboBox { idc = IDC+210; x = 0.9 y = 0.26 w = 0.1 }; class Setting11Label: SettingLabel { idc = IDC+111; x = 0.6 y = 0.16 w = 0.1 text = "Setting11"; }; class Setting11: SettingComboBox { idc = IDC+211; x = 0.6 y = 0.19 w = 0.1 }; class Setting12Label: SettingLabel { idc = IDC+112; x = 0.7 y = 0.16 w = 0.1 text = "Setting12"; }; class Setting12: SettingComboBox { idc = IDC+212; x = 0.7 y = 0.19 w = 0.1 }; class Setting13Label: SettingLabel { idc = IDC+113; x = 0.6 y = 0.23 w = 0.1 text = "Setting13"; }; class Setting13: SettingComboBox { idc = IDC+213; x = 0.6 y = 0.26 w = 0.1 }; class Setting14Label: SettingLabel { idc = IDC+114; x = 0.7 y = 0.23 w = 0.1 text = "Setting14"; }; class Setting14: SettingComboBox { idc = IDC+214; x = 0.7 y = 0.26 w = 0.1 }; class Setting15Label: SettingLabel { idc = IDC+115; x = 0.8 y = 0.30 w = 0.1 text = "Setting15"; }; class Setting15: SettingComboBox { idc = IDC+215; x = 0.8 y = 0.33 w = 0.1 }; class Setting16Label: SettingLabel { idc = IDC+116; x = 0.8 y = 0.37 w = 0.1 text = "Setting16"; }; class Setting16: SettingComboBox { idc = IDC+216; x = 0.8 y = 0.40 w = 0.1 }; class Setting17Label: SettingLabel { idc = IDC+117; x = 0.8 y = 0.44 w = 0.1 text = "Setting17"; }; class Setting17: SettingComboBox { idc = IDC+217; x = 0.8 y = 0.47 w = 0.1 }; class Setting18Label: SettingLabel { idc = IDC+118; x = 0.9 y = 0.30 w = 0.1 text = "Setting18"; }; class Setting18: SettingComboBox { idc = IDC+218; x = 0.9 y = 0.33 w = 0.1 }; class Setting19Label: SettingLabel { idc = IDC+119; x = 0.9 y = 0.37 w = 0.2 text = "Setting19"; }; class Setting19: SettingComboBox { idc = IDC+219; x = 0.9 y = 0.40 w = 0.1 }; class Setting20Label: SettingLabel { idc = IDC+120; x = 0.9 y = 0.44 w = 0.1 text = "Setting20"; }; class Setting20: SettingComboBox { idc = IDC+220; x = 0.9 y = 0.47 w = 0.1 }; class Setting21Label: SettingLabel { idc = IDC+121; x = 0.8 y = 0.51 w = 0.2 text = "Setting21"; }; class Setting21: SettingComboBox { idc = IDC+221; x = 0.8 y = 0.54 w = 0.1 }; class Setting22Label: SettingLabel { idc = IDC+122; x = 0.9 y = 0.51 w = 0.2 text = "Setting22"; }; class Setting22: SettingComboBox { idc = IDC+222; x = 0.9 y = 0.54 w = 0.1 }; class Setting23Label: SettingLabel { idc = IDC+123; x = 0.8 y = 0.58 w = 0.2 text = "Setting23"; }; class Setting23: SettingComboBox { idc = IDC+223; x = 0.8 y = 0.61 w = 0.1 }; class Setting24Label: SettingLabel { idc = IDC+124; x = 0.9 y = 0.58 w = 0.2 text = "Setting24"; }; class Setting24: SettingComboBox { idc = IDC+224; x = 0.9 y = 0.61 w = 0.1 }; class Setting25Label: SettingLabel { idc = IDC+125; x = 0.6 y = 0.30 w = 0.1 text = "Setting25"; }; class Setting25: SettingComboBox { idc = IDC+225; x = 0.6 y = 0.33 w = 0.1 }; class TemporaryDialog: Button { x = 0.65 y = 0.0 w = 0.3 h = 0.03 text = "Temporary Order" action = "btnTemporaryOrder = true" }; class OrderLabel: Label { idc = IDC+1; x = 0.0; y = 0.38; w = 0.1; text = "Order"; }; class SendOrder: Button { idc = IDC+2 x = 0.1 y = 0.38 w = 0.1 h = 0.03 text = "Send" action = "btnSendOrder = true" }; class Order: ListBox { idc = IDC+3 x = 0.0; y = 0.41; w = 0.2; h = 10*0.03; }; class Param0Label: Label { idc = IDC+4 x = 0.2; y = 0.38; w = 0.2; text = "Param0"; }; class Param0: ListBox { idc = IDC+5 x = 0.2; y = 0.41; w = 0.2; h = 10*0.03; }; class Param1Label: Label { idc = IDC+6 x = 0.4; y = 0.38; w = 0.2; text = "Param1"; }; class Param1: ListBox { idc = IDC+7 x = 0.4; y = 0.41; w = 0.2; h = 10*0.03; }; class Param2Label: Label { idc = IDC+8 x = 0.6; y = 0.38; w = 0.2; text = "Param2"; }; class Param2: ListBox { idc = IDC+9 x = 0.6; y = 0.41; w = 0.2; h = 10*0.03; }; class Exit: Button { x = 0.95 y = 0.0 w = 0.05 h = 0.03 text = "Exit" action = "closeDialog 0" }; }; class CommandPlayerDialog: Menu { idd = -1; movingEnable = true; controlsBackground[] = {CommandPlayerDialogBackgroundWindow, Sub_BG_Light}; objects[] = { }; controls[] = { CommandPlayerTitle, GroupOrdersLabel, GroupOrders, SendOrder, OrderLabel, Order, Param0Label, Param0, Param1Label, Param1, Exit }; class CommandPlayerDialogBackgroundWindow: BackgroundWindow { x = 0.39; y = 0.0; w = 0.61; h = 0.68; }; class Sub_BG_Light: Light_BG_Window { x = 0.39; y = 0.0; w = 0.61; h = 0.68; }; class GroupOrdersLabel: Label { x = 0.4; y = 0.02; text = "Group, Current Order"; }; class GroupOrders: ListBox { idc = IDC_PLAYER_ORDER_CURRENT; x = 0.4; y = 0.05; w = 0.6; h = 0.30 }; class OrderLabel: Label { idc = IDC_PLAYER_ORDER_ORDERLABEL; x = 0.4; y = 0.38; w = 0.1; text = "Order"; }; class SendOrder: Button { idc = IDC_PLAYER_ORDER_SENDORDER x = 0.5 y = 0.33 w = 0.1 h = 0.03 text = "Send" action = "btnSendOrder = true" }; class Order: ListBox { idc = IDC_PLAYER_ORDER_ORDER x = 0.4; y = 0.41; w = 0.2; h = 10*0.03; }; class Param0Label: Label { idc = IDC_PLAYER_ORDER_PAR0LABEL x = 0.6; y = 0.38; w = 0.2; text = "Param0"; }; class Param0: ListBox { idc = IDC_PLAYER_ORDER_PAR0 x = 0.6; y = 0.41; w = 0.2; h = 10*0.03; }; class Param1Label: Label { idc = IDC_PLAYER_ORDER_PAR1LABEL x = 0.8; y = 0.38; w = 0.2; text = "Param1"; }; class Param1: ListBox { idc = IDC_PLAYER_ORDER_PAR1 x = 0.8; y = 0.41; w = 0.2; h = 10*0.03; }; class Exit: Button { x = 0.95 y = 0.0 w = 0.05 h = 0.03 text = "Exit" action = "closeDialog 0" }; }; // EOF
1.203125
1
blas_bench/parallel_dgemm.c
qoofyk/task-bench
0
7999931
/* Copyright 2019 Los Alamos National Laboratory * Copyright 2009-2018 Purdue University and Purdue University Research Foundation * * 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. */ /******************************************************************************* * This example demonstrates threading impact on computing real matrix product * C=alpha*A*B+beta*C using Intel(R) MKL subroutine DGEMM, where A, B, and C * are matrices and alpha and beta are double precision scalars. * * In this simple example, practices such as memory management, data alignment, * and I/O that are necessary for good programming style and high Intel(R) MKL * performance are omitted to improve readability. ********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <mkl.h> #include <omp.h> #include <string.h> #include <sys/time.h> double get_cur_time(){ struct timeval tv; struct timezone tz; double cur_time; gettimeofday(&tv, &tz); cur_time= tv.tv_sec + tv.tv_usec/1000000.0; return cur_time; } /* Consider adjusting LOOP_COUNT based on the performance of your computer */ /* to make sure that total run time is at least 1 second */ #define LOOP_COUNT 50 int main(int argc, char** argv) { double time[128]; int N = 256; int loop_cnt; int nb_threads = 1; //parse command line for (int k = 1; k < argc; k++) { if (!strcmp(argv[k], "-size")) { N = atoi(argv[++k]); } if (!strcmp(argv[k], "-cnt")) { loop_cnt = atoi(argv[++k]); } if (!strcmp(argv[k], "-thread")) { nb_threads = atoi(argv[++k]); } } omp_set_dynamic(0); omp_set_num_threads(nb_threads); #pragma omp parallel { int myid = omp_get_thread_num(); double *A = NULL; double *B = NULL; double *C = NULL; int i, j, r, max_threads; double alpha, beta; double s_initial, s_elapsed; loop_cnt = LOOP_COUNT; alpha = 1.0; beta = 1.0; A = (double *)mkl_malloc( N*N*sizeof( double ), 64 ); B = (double *)mkl_malloc( N*N*sizeof( double ), 64 ); C = (double *)mkl_malloc( N*N*sizeof( double ), 64 ); if (A == NULL || B == NULL || C == NULL) { printf( "\n ERROR: Can't allocate memory for matrices. Aborting... \n\n"); if (A != NULL) mkl_free(A); if (B != NULL) mkl_free(B); if (C != NULL) mkl_free(C); // return 1; } for (i = 0; i < (N * N); i++) { A[i] = (double)(i+1); B[i] = (double)(-i-1); C[i] = 0.0; } mkl_set_num_threads(1); // warmup for (r = 0; r < 10; r++) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, N, N, alpha, A, N, B, N, beta, C, N); } s_initial = get_cur_time(); for (r = 0; r < loop_cnt; r++) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, N, N, alpha, A, N, B, N, beta, C, N); } s_elapsed = (get_cur_time() - s_initial) / loop_cnt; time[myid] = s_elapsed * 1000; printf ("Thread #%d, MKL DGEMM N=%d, time %.5f milliseconds, GFLOPS=%.3f\n", myid, N, (s_elapsed * 1000), 2*(double)N*(double)N*(double)N/s_elapsed*1e-9); mkl_free(A); mkl_free(B); mkl_free(C); if (s_elapsed < 0.9/loop_cnt) { s_elapsed=1.0/loop_cnt/s_elapsed; i=(int)(s_elapsed*loop_cnt)+1; if (myid == 0) printf(" It is highly recommended to define LOOP_COUNT for this example on your \n" " computer as %i to have total execution time about 1 second for reliability \n" " of measurements\n\n", i); } } // compute average double average=0.0; for (int i=0; i < nb_threads; i++) average += time[i]; average = average / nb_threads; printf(" AE= %.3f ms, Each thread uses %.3f MB\n", average, (double)N*(double)N*sizeof(double)/(1024*1024)); printf (" Example completed. \n\n"); return 0; }
1.75
2
src/strategy/values/MasterTargetValue.h
htc16/mod-playerbots
12
7999939
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version. */ #ifndef _PLAYERBOT_MASTERTARGETVALUE_H #define _PLAYERBOT_MASTERTARGETVALUE_H #include "Value.h" class PlayerbotAI; class Unit; class MasterTargetValue : public UnitCalculatedValue { public: MasterTargetValue(PlayerbotAI* botAI, std::string const name = "master target") : UnitCalculatedValue(botAI, name) { } Unit* Calculate() override; }; #endif
1.15625
1
Include/stream.h
cyb3rpunk452/aos-avos
0
7999947
/* * Copyright 2017 <NAME> * * 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 _STREAM_H #define _STREAM_H #include "av.h" #include "frame_q.h" #include "athread.h" #include "id3tag.h" #include "cbe.h" #include "stream_common.h" #include "stream_parser.h" #include "stream_filter_audio.h" #include "stream_rc.h" #include "audio_interface.h" // forward declare STREAM struct STREAM; #include "stream_io.h" #include "stream_buffer.h" #include <pthread.h> #define STREAM_DEFAULT_BUFFER_SIZE 64 #define STREAM_LARGE_BUFFER_SIZE 128 #define STREAM_MAX_FRAMES 64 // in sync with android/vendor/archos/frameworks/ArchosFrameworks/java/com/archos/frameworks/media/AvosPlayer.java typedef enum { STREAM_SPEED_NORMAL = 0, STREAM_SPEED_SLOW_2, STREAM_SPEED_SLOW_4, STREAM_SPEED_SLOW_8, STREAM_SPEED_FAST_2, STREAM_SPEED_FAST_4, STREAM_SPEED_FAST_8, } STREAM_SPEED; typedef enum { STREAM_NO_ERROR = 0, STREAM_ERROR = 1, // ... STREAM_ERROR_FATAL = 99, } STREAM_ERROR_TYPE; typedef enum { STREAM_MEM_NRM = 0, STREAM_MEM_DMA, STREAM_MEM_DMA_CACHED, STREAM_MEM_TILER, STREAM_MEM_ION, STREAM_MEM_ANDROID, STREAM_MEM_CMA, STREAM_MEM_BYO, } STREAM_MEM_TYPE; enum { CHUNK_FREE = 0, CHUNK_VALID, }; typedef struct STREAM_CHUNK { int type; // audio or video chunk unsigned int valid; // 0: free, 1: valid unsigned int key; // key frame int frm_type; // (video) frame type UINT64 pos; // absolute position in stream UINT buf; // address relative to buffer start int size; // size of chunk int payload_size; // size of payload UINT frame; // frame number of this chunk int time; // presentation time in msec UINT audio_skip; // audio time skip when playing this chunk UINT video_skip; // video time skip when playing this chunk int buf2; // from buffer2? int stream; // number of stream this chunk is from UINT64 sample_ID; // for CARDEA } STREAM_CHUNK; typedef struct STREAM_CHUNK_STORE { STREAM_CHUNK *c; int read; int write; int max; } STREAM_CHUNK_STORE; typedef struct CLEVER_BUFFER { unsigned char *data; unsigned int size; } CLEVER_BUFFER; int malloc_clever_buffer ( CLEVER_BUFFER *buffer, int size ); int realloc_clever_buffer( CLEVER_BUFFER *buffer, int min_size ); void free_clever_buffer ( CLEVER_BUFFER *buffer ); typedef struct STREAM_CDATA { int valid; int type; int frame; int time; int size; int key; int video_skip; int audio_skip; int audio_skip_time; int frm_type; // (video) frame type int offset; int count; int fields; int ref_time; int top; int user_ID; int crypt; // bits from coding extension int tff; int rff; int pro; UINT64 pos; AV_PROPERTIES *changed; } STREAM_CDATA; // forward declare CBE struct CBE; // // DEC_AUDIO // typedef int (*DEC_AUDIO_NEW ) ( AUDIO_PROPERTIES *audio ); typedef int (*DEC_AUDIO_OPEN ) ( AUDIO_PROPERTIES *audio ); typedef int (*DEC_AUDIO_RE_OPEN)( AUDIO_PROPERTIES *audio ); typedef int (*DEC_AUDIO_CLOSE) ( AUDIO_PROPERTIES *audio ); typedef int (*DEC_AUDIO_DECODE) ( AUDIO_PROPERTIES *audio, UCHAR *data, int size, AUDIO_FRAME *frame, int *decoded, int *time ); typedef int (*DEC_AUDIO_FLUSH) ( AUDIO_PROPERTIES *audio ); typedef int (*DEC_AUDIO_DELAY) ( AUDIO_PROPERTIES *audio ); typedef int (*DEC_AUDIO_GET_RC) ( AUDIO_PROPERTIES *audio, STREAM_RC *rc ); typedef int (*DEC_AUDIO_DELETE) ( AUDIO_PROPERTIES *audio ); typedef int (*DEC_AUDIO_IS_SUPPORTED) ( AUDIO_PROPERTIES *audio ); typedef struct STREAM_DEC_AUDIO { const char *name; DEC_AUDIO_NEW new; DEC_AUDIO_OPEN open; DEC_AUDIO_OPEN re_open; DEC_AUDIO_CLOSE close; DEC_AUDIO_DECODE decode; DEC_AUDIO_FLUSH flush; DEC_AUDIO_DELAY delay; DEC_AUDIO_GET_RC get_rc; DEC_AUDIO_DELETE delete; DEC_AUDIO_IS_SUPPORTED is_supported; } STREAM_DEC_AUDIO; // // SINK_AUDIO // typedef int (*SINK_AUDIO_OPEN ) ( struct STREAM *s ); typedef int (*SINK_AUDIO_CLOSE) ( struct STREAM *s ); typedef int (*SINK_AUDIO_START ) ( struct STREAM *s ); typedef int (*SINK_AUDIO_STOP) ( struct STREAM *s ); typedef int (*SINK_AUDIO_WRITE) ( struct STREAM *s, AUDIO_FRAME *frame ); typedef int (*SINK_AUDIO_PRELOAD)( struct STREAM *s ); typedef int (*SINK_AUDIO_FLUSH) ( struct STREAM *s ); typedef int (*SINK_AUDIO_END) ( struct STREAM *s ); typedef int (*SINK_AUDIO_SYNC) ( struct STREAM *s ); typedef int (*SINK_AUDIO_DELAY) ( struct STREAM *s ); typedef int (*SINK_AUDIO_CAN_WR) ( struct STREAM *s, int len ); typedef int (*SINK_AUDIO_SET_PASS)( struct STREAM *s, int pass ); typedef int (*SINK_AUDIO_GET_PASS)( struct STREAM *s ); typedef int (*SINK_AUDIO_MUTE) ( struct STREAM *s, int mute ); typedef int (*SINK_AUDIO_SET_VOL)( struct STREAM *s ); typedef int (*SINK_AUDIO_GET_SESSION_ID)( struct STREAM *s ); typedef struct STREAM_SINK_AUDIO { const char *name; SINK_AUDIO_OPEN open; SINK_AUDIO_CLOSE close; SINK_AUDIO_START start; SINK_AUDIO_STOP stop; SINK_AUDIO_WRITE write; SINK_AUDIO_PRELOAD preload; SINK_AUDIO_FLUSH flush; SINK_AUDIO_END end; SINK_AUDIO_SYNC syncable; SINK_AUDIO_SYNC delay; SINK_AUDIO_CAN_WR can_write; SINK_AUDIO_SET_PASS set_passthrough; SINK_AUDIO_GET_PASS get_passthrough; SINK_AUDIO_MUTE mute; SINK_AUDIO_SET_VOL set_vol; SINK_AUDIO_GET_SESSION_ID get_session_id; } STREAM_SINK_AUDIO; // // DEC_VIDEO // #include "stream_dec_video.h" // // DEC_SUB // #include "stream_dec_sub.h" // // VIDEO_MANGLER // typedef int (*STREAM_VIDEO_INIT_MANGLER) ( struct STREAM *s, int time ); typedef int (*STREAM_VIDEO_PRE_MANGLER) ( struct STREAM *s, struct CBE *cbe, STREAM_CDATA *cdata ); typedef int (*STREAM_VIDEO_POST_MANGLER) ( struct STREAM *s, VIDEO_FRAME **p_frame ); typedef int (*STREAM_VIDEO_FLUSH_MANGLER)( struct STREAM *s ); typedef struct STREAM_VIDEO_MANGLER { const char *name; STREAM_VIDEO_INIT_MANGLER init; STREAM_VIDEO_PRE_MANGLER pre; STREAM_VIDEO_POST_MANGLER post; STREAM_VIDEO_FLUSH_MANGLER flush; } STREAM_VIDEO_MANGLER; // // SINK_VIDEO // #include "stream_sink_video.h" // // PARSER // typedef int (*PARSER_OPEN) ( struct STREAM *s, int buffer_size, int flags ); typedef int (*PARSER_CLOSE) ( struct STREAM *s ); typedef int (*PARSER_PAUSE) ( struct STREAM *s, int pause ); typedef int (*PARSER_PARSE) ( struct STREAM *s ); typedef int (*PARSER_PARSE_CHUNK) ( struct STREAM *s, STREAM_CHUNK *sc ); typedef int (*PARSER_CALC_RATE) ( struct STREAM *s ); typedef int (*PARSER_SET_AUDIO_STREAM)( struct STREAM *s, int audio_stream ); typedef int (*PARSER_GET_AUDIO_CDATA)( struct STREAM *s, CLEVER_BUFFER *buffer, STREAM_CDATA *cdata ); typedef int (*PARSER_GET_VIDEO_CDATA)( struct STREAM *s, struct CBE *cbe, STREAM_CDATA *cdata ); typedef int (*PARSER_GET_SUBTITLE_CDATA)( struct STREAM *s, CLEVER_BUFFER *buffer, STREAM_CDATA *cdata ); typedef struct STREAM_CHUNK * (*PARSER_PEEK_N_AUDIO_CHUNK)( struct STREAM *s, int n, UINT8 **data ); typedef int (*PARSER_SEEK_TIME) ( struct STREAM *s, int time, int dir, int flags, int force_reload, STREAM_CHUNK *sc ); typedef int (*PARSER_SEEK_POS) ( struct STREAM *s, int pos, int dir, int flags, int force_reload, STREAM_CHUNK *sc ); typedef int (*PARSER_SEEK_BY_INDEX) ( struct STREAM *s, int idx_size, void *idx_data, int force_reload, STREAM_CHUNK *sc ); typedef int (*PARSER_SEEKABLE) ( struct STREAM *s ); typedef int (*PARSER_PAUSEABLE) ( struct STREAM *s ); typedef int (*PARSER_GET_INDEX) ( struct STREAM *s, int *time, void **data, int *size ); typedef int (*PARSER_START_NEXT) ( struct STREAM *s ); typedef struct STREAM_PARSER_STATS * (*PARSER_GET_STATS) ( struct STREAM *s, struct STREAM_PARSER_STATS *stats ); typedef int (*PARSER_GET_TIME) ( struct STREAM *s, int *total ); typedef int (*PARSER_GET_TIME_FOR_POS)( struct STREAM *s, UINT64 for_pos ); typedef struct stream_parser_str { const char *name; PARSER_OPEN open; PARSER_CLOSE close; PARSER_PAUSE pause; PARSER_PARSE parse; PARSER_PARSE_CHUNK parse_chunk; PARSER_SET_AUDIO_STREAM set_audio_stream; PARSER_CALC_RATE calc_rate; PARSER_GET_AUDIO_CDATA get_audio_cdata; PARSER_GET_VIDEO_CDATA get_video_cdata; PARSER_GET_SUBTITLE_CDATA get_subtitle_cdata; PARSER_PEEK_N_AUDIO_CHUNK peek_n_audio_chunk; PARSER_SEEK_TIME seek_time; PARSER_SEEK_POS seek_pos; PARSER_SEEK_BY_INDEX seek_by_index; PARSER_SEEKABLE seekable; PARSER_SEEKABLE pauseable; PARSER_GET_INDEX get_index; PARSER_START_NEXT start_next; PARSER_GET_STATS get_stats; PARSER_GET_TIME get_time; PARSER_GET_TIME_FOR_POS get_time_for_pos; } STREAM_PARSER; // // DUMPER // typedef int (*DUMPER_OPEN) ( struct STREAM *s, int buffer_size, int flags ); typedef int (*DUMPER_CLOSE) ( struct STREAM *s ); typedef int (*DUMPER_WRITE) ( struct STREAM *s, UCHAR *data, STREAM_CDATA *cdata ); typedef struct stream_dumper_str { const char *name; DUMPER_OPEN open; DUMPER_CLOSE close; DUMPER_WRITE write; } STREAM_DUMPER; // // CHAPTER // #define STREAM_MAX_CHAPTERS 256 typedef struct STREAM_CHAPTER { char title[MAX_TAG_LENGTH + 1]; UINT64 start; UINT64 end; } STREAM_CHAPTER; #define STREAM_MAX_PARTS 99 #define CHUNK_CACHE_MAX 16 typedef struct STREAM_CHUNK_CACHE { int use_cache; int write; int read; UCHAR *data[CHUNK_CACHE_MAX]; STREAM_CDATA cdata[CHUNK_CACHE_MAX]; } STREAM_CHUNK_CACHE; typedef struct VCODEC_CTRL { unsigned char *data; unsigned int data_size; VIDEO_FRAME *decode_frame; volatile int done; volatile int decoded; int time; // for debugging int time2; // for debugging } VCODEC_CTRL; typedef void (*STOP_HANDLER) ( struct STREAM *s ); typedef void (*PROGRESS_HANDLER) ( struct STREAM *s, int total, int progress ); typedef void (*PER_FRAME_HANDLER) ( struct STREAM *s, VIDEO_FRAME *frame ); enum { STREAM_SYNC_CDATA = 0, STREAM_SYNC_SAMPLES, }; typedef enum { STREAM_AUDIO_PROPS_CHANGED = 1, STREAM_VIDEO_PROPS_CHANGED, STREAM_SUB_PROPS_CHANGED, STREAM_SUBTITLE_CHANGED, STREAM_DECODER_CHANGED, } STREAM_MESSAGE; typedef enum { STREAM_CPU_ANY = 0, STREAM_CPU_ARM = 1, STREAM_CPU_ARM2 = 2, STREAM_CPU_DSP2 = 3, STREAM_CPU_DSP3 = 4, STREAM_CPU_DSP4 = 5, STREAM_CPU_DSP = STREAM_CPU_DSP4, } STREAM_CPU; typedef void (*STREAM_MESSAGE_CB) ( struct STREAM *s, STREAM_MESSAGE message ); typedef int (*STREAM_ASK_AUDIO) ( struct STREAM *s, AUDIO_PROPERTIES *audio, int *answer ); typedef int (*STREAM_ASK_VIDEO) ( struct STREAM *s, VIDEO_PROPERTIES *video, int *answer ); typedef void (*STREAM_PLAYER) ( struct STREAM *s ); typedef struct STREAM { // **************************************** // these members must be the same in VIDEO! // **************************************** int _type; int etype; int audio_end; AUDIO_PROPERTIES *audio; // **************************************** // end of common area // **************************************** int open; int flags; int start_time; int stop_time; int start_pos; // some streams have no known duration int idx_size; // size of index data entry unsigned char idx_data[64]; // for videos, index entry data to start stream from int max_size; int max_time; STOP_HANDLER stop; PROGRESS_HANDLER progress; int do_progress; ABORT_HANDLER user_abort; // abort handler provided by the user ABORT_HANDLER abort; // internal abort handler int aborted; // remember that we are aborting! PER_FRAME_HANDLER per_frame; STREAM_MESSAGE_CB message_cb; STREAM_ASK_AUDIO ask_audio; STREAM_ASK_VIDEO ask_video; int video_max_width; int video_max_height; int audio_max_channels; STREAM_URL src; char src_query[STREAM_MAX_PATH_LEN + 1]; int dump_audio_fd; int dump_video_fd; int dump_pcm_fd; // for multi segment recordings STREAM_PART parts[STREAM_MAX_PARTS]; int num_parts; int total_time; VIDEO_PROPERTIES *video; SUB_PROPERTIES *subtitle; AV_PROPERTIES av; STREAM_CHAPTER *chapters[STREAM_MAX_CHAPTERS]; int num_chapters; int aspect_n; // aspect ratio set by user int aspect_d; // aspect ratio set by user UINT64 size; int duration; int no_duration; // this stream has no duration! int frame_count; // for DVDs int vob; int sink_delay; // delay between video and it's sink int sink_delay_count; // delay between video and it's sink int sync_mode; int av_delay; // user provided AV delay int audio_time; int audio_ref_time; int audio_samples; UINT64 audio_pos; int video_time; UINT64 video_pos; int video_drop; int delay; int delay_valid; int delay_fb; int sink_ref_time; int vid_ref_time; int drop; int drop_count; int drop_B; int drop_P; int has_index; UCHAR *index_buffer; int archos_dvr; int data_rate; int vtime_parsed; int vcurrent_rate; int atime_parsed; int acurrent_rate; int time_parsed; int current_rate; int crypt; void *crypt_key; DRM_CTX drm_ctx; DRM_PROPERTIES drm; // for JANUS pthread_mutex_t drm_lock; STREAM_IO_SETUP io_setup; void *io_setup_ctx; STREAM_IO_META io_meta; void *io_meta_ctx; pthread_t control_thread_handle; THREAD_STATE control_tstate; pthread_t parser_thread_handle; THREAD_STATE parser_tstate; pthread_t sub_thread_handle; THREAD_STATE sub_tstate; pthread_t engine_thread_handle; THREAD_STATE engine_tstate; int engine_yield; pthread_t audio_thread_handle; THREAD_STATE audio_tstate; int audio_yield; VCODEC_CTRL vcodec; pthread_t codec_thread_handle; pthread_mutex_t codec_mutex; int codec_run; pthread_cond_t codec_code; pthread_mutex_t video_done_mutex; pthread_cond_t video_done; volatile int video_state; int video_flush; int video_output; int buffer_size; int buffer_flags; void *buffer_opaque; STREAM_BUFFER *buffer; STREAM_BUFFER *buffer2; int buffer_chunk; int error; int audio_parse_end; // parser has parsed complete file int video_parse_end; // parser has parsed complete file int video_end; // video is at the end of file int stream_end; // stream is at it's end STREAM_CHUNK_STORE aud; STREAM_CHUNK_STORE vid; STREAM_CHUNK_STORE sub; void *ro_ctx; // reorder context for stupid codecs STREAM_IO *io; STREAM_IO *io2; STREAM_PARSER *parser; int parser_open; int parser_extern; // parser is not opened/closed by us! int parser_paused; int parser_error; int parser_mindata_size; int parser_flags; int parser_halt; int parser_audio_discon; int parser_video_discon; pthread_mutex_t parser_buffer_mutex; void *parser_priv; // private data for parser STREAM_PARSER *real_parser; STREAM_GET_PART_NAME get_part_name; int parser_parse_once; STREAM_PLAYER player; void *mangler_priv; // private data for mangler STREAM_DUMPER *video_dumper; STREAM_DUMPER *audio_dumper; STREAM_DEC_AUDIO *audio_dec; STREAM_RC audio_rc; STREAM_FILTER_AUDIO *audio_filter; int audio_filter_enabled; int audio_filter_level; int audio_filter_night_on; STREAM_SINK_AUDIO *audio_sink; int audio_sink_open; pthread_mutex_t audio_sink_mutex; int audio_session_id; STREAM_DEC_VIDEO *video_dec; int video_dec_open; STREAM_RC video_rc; STREAM_VIDEO_MANGLER *video_mangler; STREAM_DEC_SUB *sub_dec; int sub_dec_open; STREAM_SINK_VIDEO *video_sink; pthread_mutex_t video_sink_mutex; int video_sink_count; VIDEO_FRAME *frames[STREAM_MAX_FRAMES]; int num_frames; FRAME_Q decode_q; FRAME_Q disp_q; FRAME_Q locked_q; FRAME_Q codec_q; VIDEO_FRAME *decode_frame; VIDEO_FRAME *current_frame; VIDEO_FRAME *current_out_frame; VIDEO_FRAME *out_frame; int use_sink_frames; int vtime_post_sink; void (*output_frame_fn)( struct STREAM *s, VIDEO_FRAME *frame, VIDEO_FRAME **qframe ); int seek; STREAM_CDATA cdata_now; STREAM_CDATA cdata_next; struct CBE *cbe; STREAM_CHUNK_CACHE cc; CLEVER_BUFFER audio_now; unsigned char *video_now; int video_now_size; // current audio chunk size and read offset int audio_buffer_size; unsigned char *audio_buffer; char *sub_url[SUB_STREAM_MAX + 1 + 1]; // current path in slot "0" VIDEO_FRAME *subtitle_frame; int subtitle_offset; int subtitle_ratio_n; // allow to scale sub timestamps with a given ratio int subtitle_ratio_d; void *subtitle_priv; // private data for subtitles // current subtitle chunk STREAM_CDATA cdata_sub; CLEVER_BUFFER sub_buffer; int subtitle_changed; int error_count; int video_error; int video_error_qualifier; char video_error_desc[STREAM_MAX_PATH_LEN + 1]; int audio_error_qualifier; int paused; int paused_internal; int speed; int seek_paused; int seek_epoch; int muted; int sync_audio; int sync_video; int sync_v_time; int sync_a_time; int audio_preload; int audio_stuff_zero; int play_n_video_frames; int play_n_video_one; int play_n_audio_frames; int play_n_video_time; int play_n_old_time; int seek_frame; int slideshow; // this stream is a slideshow (fps < 1) ID3_TAG tag; int tag_new; APIC apic; int apic_new; audio_ctx_t *audio_ctx; void *user_ctx; int vol_l; int vol_r; int cpu_prio; int fps_start; int fps_count; void *surface_handle; } STREAM; #define STREAM_POS_MAX 1000 // // PUBLIC STREAM PLAYER API // #define STREAM_PAUSED 0x0001 // open the stream, but pause it immediately #define STREAM_THUMB 0x0002 // open the stream for thumbnail extraction #define STREAM_NO_AUDIO 0x0004 // play without sound even if there is audio #define STREAM_NO_INDEX 0x0008 // do not try to read the AVI/ASF index #define STREAM_LOOP 0x0010 // loop back to start at end of file #define STREAM_THUMB_PLAY 0x0020 // open the stream for thumbnail animation #define STREAM_NO_AUDIO_CODEC 0x0040 // do not encode/decode audio, just pass through the compressed data #define STREAM_NO_VIDEO_CODEC 0x0080 // do not encode/decode video, just pass through the compressed data #define STREAM_UNCUT 0x0100 // do not take editing into account when playin the stream #define STREAM_LATE_INDEX 0x0200 // read index asynchrously to speed up video start time #define STREAM_MULTI 0x0400 // rec: split the recorded stream into multiple segments if max file_size reached // play: play all segments of a multirecorded file #define STREAM_NO_VIDEO 0x0800 // play without video even if there is video #define STREAM_NO_DEINT 0x1000 // do not use deinterlacer #define STREAM_FILE_NONLOCAL 0x2000 // the file is not local, so there is no drive to sleep #define STREAM_THUMB_DRM 0x4000 // open the stream for thumbnail animation with drm #define STREAM_NOT_INTERLEAVED 0x8000 // force the parser to treat the file as not interleaved #define STREAM_NO_SUBTITLES 0x10000 // play without subtitles #define STREAM_TIMESHIFT 0x20000 // for live streams, write/read data from the HDD if we do not play fast enough #define STREAM_RESIZE_BUFFER 0x40000 // allow to resize buffer #define STREAM_MPEG_SKIP_PSI_PREPARSE 0x80000 // skipping preparse MPEG PSI that come from RTSP #define STREAM_SUBTITLES_CLEAN_TAGS 0x100000 // clean html tags in subtitles STREAM *stream_new( void ); int stream_delete( STREAM **s ); int stream_open (STREAM *s, // STREAM structure STREAM_URL *src, int etype, // extended type int flags ); // see above flags definition int stream_start( STREAM *s ); int stream_stop( STREAM *s ); enum { STREAM_SEEK_FORWARD = 0, STREAM_SEEK_BACKWARD, }; enum { STREAM_SEEK_STRICT = 0, STREAM_SEEK_RELAXED, }; int stream_seekable ( STREAM *s ); int stream_pauseable ( STREAM *s ); int stream_seek_time ( STREAM *s, int time, int dir, int flags ); int stream_seek_pos ( STREAM *s, int pos, int dir, int flags ); int stream_seek_frame( STREAM *s, int frame, int dir, int force_reload ); int stream_set_speed( STREAM *s, STREAM_SPEED speed ); int stream_set_audio_stream( STREAM *s, int audio_stream ); int stream_set_audio_filter_level( STREAM *s, int level, int night_on ); void stream_set_audio_downmix( int downmix ); int stream_check_subtitles( STREAM *s ); int stream_set_subtitle_stream( STREAM *s, int sub_stream ); void stream_audio_mute ( STREAM *s ); void stream_audio_unmute ( STREAM *s ); int stream_audio_is_muted( STREAM *s ); int stream_pause ( STREAM *s ); void stream_un_pause ( STREAM *s, int was_paused ); int stream_is_paused( STREAM *s ); int stream_get_current_speed( STREAM *s ); int stream_get_current_time ( STREAM *s, int *total_time ); int stream_get_buffered_time( STREAM *s, int *total_time ); int stream_get_current_pos ( STREAM *s, int *total_pos ); int stream_get_buffered_pos ( STREAM *s, int *total_pos ); int stream_get_current_audio_stream( STREAM *s ); int stream_get_audio_session_id( STREAM *s ); VIDEO_FRAME *stream_get_current_frame( STREAM *s ); int stream_resize( STREAM *s ); int stream_redraw( STREAM *s ); int stream_set_stop_handler ( STREAM *s, STOP_HANDLER stop ); int stream_set_abort_handler ( STREAM *s, ABORT_HANDLER abort ); int stream_set_progress_handler ( STREAM *s, PROGRESS_HANDLER progress ); int stream_set_per_frame_handler( STREAM *s, PER_FRAME_HANDLER per_frame ); int stream_set_av_delay ( STREAM *s, int av_delay ); int stream_set_crypt( STREAM *s, int crypt, void *key ); void stream_set_size( STREAM *s, UINT64 size ); void stream_set_buffer_size( STREAM *s, int buffer_size ); void stream_set_buffer_flags( STREAM *s, int flags, void *opaque ); void stream_set_aspect_ratio( STREAM *s, int aspect_n, int aspect_d ); void stream_set_max_video_dimensions( STREAM *s, int max_width, int max_height ); void stream_set_audio_max_channels( STREAM *s, int max_channels ); void stream_set_message_cb( STREAM *s, STREAM_MESSAGE_CB message_cb ); void stream_set_ask_audio( STREAM *s, STREAM_ASK_AUDIO ask ); void stream_set_ask_video( STREAM *s, STREAM_ASK_VIDEO ask ); void stream_set_drm_ctx( STREAM *s, DRM_CTX *drm_ctx ); void stream_set_user_ctx( STREAM *s, void *ctx ); void *stream_get_user_ctx( STREAM *s); int stream_get_tag_state( STREAM *s, int *tag_new, int *apic_new ); int stream_get_tag ( STREAM *s, ID3_TAG *tag, APIC *apic ); int stream_get_chapter ( STREAM *s, int num, STREAM_CHAPTER *chapter ); void stream_set_subtitle_offset( STREAM *s, int offset ); void stream_set_subtitle_ratio( STREAM *s, int n, int d ); void stream_set_subtitle_url( STREAM *s, const char **url_list ); int stream_set_abort( STREAM *s ); int stream_set_volume( STREAM *s, int vol_l, int vol_r ); void stream_set_surface_handle( STREAM *s, void *surface_handle ); void *stream_get_surface_handle( STREAM *s ); void stream_set_start_time( STREAM *s, int time ); void stream_set_stop_time ( STREAM *s, int time ); void stream_set_video_sink( STREAM *s, STREAM_SINK_VIDEO *sink ); void stream_set_audio_sink( STREAM *s, STREAM_SINK_AUDIO *sink ); STREAM_SINK_VIDEO *stream_get_video_sink( STREAM *s ); STREAM_SINK_AUDIO *stream_get_audio_sink( STREAM *s ); int stream_get_index( STREAM *s, int *time, void **data, int *size ); void stream_get_part_name( char *part_name, const char *full_path, int part_num ); int stream_is_part_name ( const char *full_path, const char *ext ); void stream_set_cpu_priority( STREAM *s, int cpu_prio ); // // INTERNAL API // #define VIDEO_MINDATA_SIZE (1024 * 1536 * 2) #define VIDEO_OVERLAP_SIZE VIDEO_MINDATA_SIZE int stream_init ( STREAM *s ); int stream_close( STREAM *s ); int stream_drive_sleep( STREAM *s ); int stream_check_parts( const char *full_path ); int stream_parse_parts( STREAM *s ); int stream_set_error( STREAM *s, int error ); int stream_get_error( STREAM *s ); void stream_show_flags( int flags ); void stream_show_props( STREAM *s ); void stream_show_short_props( STREAM *s ); void stream_show_rc( STREAM_RC *rc ); void *stream_audio_dec_thread( void *data ); void stream_audio_flush( STREAM *s ); int stream_sync_video( STREAM *s, int video_time ); int stream_sync_audio( STREAM *s, int audio_time ); int stream_lock_frame ( STREAM *s, void *tag ); VIDEO_FRAME *stream_unlock_frame( STREAM *s, void *tag ); VIDEO_FRAME *stream_get_frame ( STREAM *s, void *tag ); static inline UINT64 stream_get_size( STREAM *s ) { return s->size; } int stream_get_time_default( STREAM *s, int *total_time ); int stream_get_total_rate( STREAM *s ); int stream_abort( STREAM *s ); void stream_CDATA_from_SC( STREAM_CDATA *cdata, STREAM_CHUNK *sc ); void stream_yield( void ); void stream_yield_RT( void ); int stream_add_chapter( STREAM *s, UINT64 start, UINT64 end, const char *title ); void stream_set_audio_name( AUDIO_PROPERTIES *audio, int track_num ); void stream_set_subtitle_name( SUB_PROPERTIES *subtitle, int track_num ); int stream_put_chunk_cache( STREAM_CHUNK_CACHE *cc, CBE *cbe, STREAM_CDATA *cdata ); int stream_get_chunk_cache( STREAM_CHUNK_CACHE *cc, CBE *cbe, STREAM_CDATA *cdata ); STREAM_SINK_VIDEO *stream_get_default_video_sink( STREAM *s ); STREAM_SINK_AUDIO *stream_get_default_audio_sink( void ); // // STREAM BUFFER // static inline int stream_buffer_chunk( STREAM *s ) { return s->buffer_chunk; } static inline void stream_set_buffer_chunk( STREAM *s, int size ) { s->buffer_chunk = size / 512 * 512; } static inline UINT64 pad_to_buffer_chunk( STREAM *s, UINT64 size ) { UINT64 STREAM_BUFFER_CHUNK = stream_buffer_chunk( s ); return ((size + STREAM_BUFFER_CHUNK - 1 ) / STREAM_BUFFER_CHUNK) * STREAM_BUFFER_CHUNK; } enum { BUFFER_RDWR = 0, BUFFER_SLEEP, BUFFER_NO_SLEEP, }; int stream_buffer_open ( STREAM_BUFFER *buffer, STREAM *s, STREAM_IO *io, int buffer_size, int overlap_size, UINT64 start, UINT64 end, UINT32 flags, const char *tag ); int stream_buffer_split ( STREAM_BUFFER *buffer, STREAM *s, STREAM_IO *io, int buffer_size, int overlap_size, UINT64 start, UINT64 end, UINT32 flags, const char *tag, STREAM_BUFFER *src ); int stream_buffer_resize_and_rebuffer( STREAM_BUFFER *buffer, int new_size ); int stream_buffer_flush ( STREAM_BUFFER *buffer ); static inline UINT stream_sink_buffer_get_pos( STREAM_BUFFER *buffer ) { return buffer->buf_write_pos; } static inline int stream_buffer_end( STREAM_BUFFER *buffer ) { return buffer->buf_end; } int stream_buffer_set_pos( STREAM_BUFFER *buffer, UINT64 pos, int force_reload ); int stream_buffer_set_pos_seek( STREAM_BUFFER *buffer, UINT64 pos, int force_reload ); UINT64 stream_buffer_get_pos( STREAM_BUFFER *buffer ); UINT stream_buffer_get_buf_pos( STREAM_BUFFER *buffer ); UCHAR *stream_buffer_get_pointer( STREAM_BUFFER *buffer ); UCHAR stream_buffer_peek_byte( STREAM_BUFFER *buffer, int offset ); UCHAR stream_buffer_read_byte( STREAM_BUFFER *buffer ); void stream_buffer_read ( STREAM_BUFFER *buffer, UCHAR *data, int size ); UINT64 stream_buffer_skip ( STREAM_BUFFER *buffer, int offset ); int stream_buffer_write ( STREAM_BUFFER *buffer, const UCHAR *data, int size ); int stream_buffer_EOF( STREAM_BUFFER *buffer ); int stream_buffer_get_free( STREAM_BUFFER *buffer ); int stream_buffer_get_used( STREAM_BUFFER *buffer ); int stream_buffer_get_head( STREAM_BUFFER *buffer ); int stream_buffer_get_tail( STREAM_BUFFER *buffer ); void stream_buffer_skip_buf_pos( STREAM_BUFFER *buffer, int offset ); void stream_buffer_skip_pos ( STREAM_BUFFER *buffer, INT64 offset ); void stream_buffer_free_data ( STREAM_BUFFER *buffer, STREAM_CHUNK *sc ); void stream_buffer_free_all_data( STREAM_BUFFER *buffer, UINT64 pos, UINT buf ); // // STREAM PARSER // #define STREAM_INDEX_SIZE (384 * 1024) #define STREAM_PARSER_LIVE 0x0001 // the stream is live, not from HDD #define STREAM_PARSER_NO_PREBUFFER 0x0002 // #define STREAM_PARSER_FILE_NONLOCAL 0x0004 // #define STREAM_PARSER_TIMESHIFT 0x0008 #define STREAM_PARSER_MPEG_SKIP_PSI_PREPARSE 0x0010 int stream_parser_open ( STREAM *s, int buffer_size, int flags ); int stream_parser_close( STREAM *s ); int stream_parser_pause( STREAM *s, int paused ); int stream_parser_prebuffer( STREAM *s, STREAM_BUFFER *buffer, int min_data ); int stream_parser_can_parse( STREAM_BUFFER *buffer, int *end ); int stream_parser_can_output( STREAM *s ); int stream_parser_parse( STREAM *s ); int stream_parser_parse_not_interleaved( STREAM *s, PARSER_PARSE_CHUNK parse_video, PARSER_PARSE_CHUNK parse_audio ); int stream_parser_guess_msPerFrame(STREAM *s); int stream_parser_calc_rate( STREAM *s ); int stream_parser_add_chunk( STREAM *s, STREAM_CHUNK *sc ); int stream_parser_can_add_chunks( STREAM *s ); void stream_parser_clear_chunks( STREAM *s ); int stream_parser_set_audio_stream( STREAM *s, int audio_stream ); int stream_parser_preparse(STREAM *s); int stream_parser_audio_chunk_num( STREAM *s ); int stream_parser_video_chunk_num( STREAM *s ); int stream_parser_subtitle_chunk_num( STREAM *s ); int stream_parser_audio_chunk_max( STREAM *s ); int stream_parser_video_chunk_max( STREAM *s ); int stream_parser_subtitle_chunk_max( STREAM *s ); int stream_parser_put_audio_chunk ( STREAM *s, STREAM_CHUNK *c ); int stream_parser_put_video_chunk ( STREAM *s, STREAM_CHUNK *c ); int stream_parser_put_subtitle_chunk( STREAM *s, STREAM_CHUNK *c ); int stream_parser_get_audio_chunk ( STREAM *s, STREAM_CHUNK *c ); int stream_parser_get_video_chunk ( STREAM *s, STREAM_CHUNK *c ); int stream_parser_get_subtitle_chunk( STREAM *s, STREAM_CHUNK *c ); void stream_parser_clear_audio_chunks ( STREAM *s ); void stream_parser_clear_video_chunks ( STREAM *s ); void stream_parser_clear_subtitle_chunks( STREAM *s ); void stream_parser_send_video_extra( VIDEO_PROPERTIES *video, CBE *cbe, int *size ); STREAM_CHUNK *stream_parser_peek_n_audio_chunk(STREAM *s, int n, UCHAR **data ); STREAM_CHUNK *stream_parser_peek_video_chunk( STREAM *s, STREAM_CHUNK *c ); STREAM_CHUNK *stream_parser_peek_audio_chunk( STREAM *s, STREAM_CHUNK *c ); STREAM_CHUNK *stream_parser_peek_sub_chunk ( STREAM *s, STREAM_CHUNK *c ); int stream_parser_get_audio_cdata ( STREAM *s, CLEVER_BUFFER *audio_buffer, STREAM_CDATA *cdata ); int stream_parser_get_audio_cdata_header( STREAM *s, CLEVER_BUFFER *audio_buffer, STREAM_CDATA *cdata ); int stream_parser_get_subtitle_cdata ( STREAM *s, CLEVER_BUFFER *sub_buffer, STREAM_CDATA *cdata ); int stream_parser_pauseable( STREAM *s ); // // STREAM VIDEO MANGLER // extern STREAM_VIDEO_MANGLER stream_video_mangler_MPEG2; extern STREAM_VIDEO_MANGLER stream_video_mangler_H264; extern STREAM_VIDEO_MANGLER stream_video_mangler_REAL; #include "stream_config.h" #endif
1.234375
1
game/gamedata/shaders/r3/common.h
ipl-adm/xray-oxygen
1
7999955
#ifndef COMMON_H #define COMMON_H #include "shared\common.h" #include "common_defines.h" #include "common_policies.h" #include "common_iostructs.h" #include "common_samplers.h" #include "common_cbuffers.h" #include "common_functions.h" // #define USE_SUPER_SPECULAR #ifdef USE_R2_STATIC_SUN # define xmaterial float(1.0h/4.h) #else # define xmaterial float(L_material.w) #endif #define FXPS technique _render{pass _code{PixelShader=compile ps_3_0 main();}} #define FXVS technique _render{pass _code{VertexShader=compile vs_3_0 main();}} #endif
0.882813
1
ElevatorGUI/ElevatorController_arduino/ElevatorController_arduino_AMIS/AMIS30543.h
kemerelab/elevator
16
7999963
// Copyright Pololu Corporation. For more information, see http://www.pololu.com/ /*! \file AMIS30543.h * * This is the main header file for the AMIS30543 library, a library for * controllering the AMIS-30543 micro-stepping stepper motor driver. * * For more information about this library, see: * * https://github.com/pololu/amis-30543-arduino * * That is the main repository for this library. * */ #pragma once #include <stdint.h> #include <Arduino.h> #include <SPI.h> /*! This class provides low-level functions for reading and writing from the SPI * interface of an AMIS-30543 micro-stepping stepper motor driver. * * Most users should use the AMIS30543 class, which provides a higher-level * interface, instead of this class. */ class AMIS30543SPI { public: /*! Configures this object to use the specified pin as a slave select pin. * You must use a slave select pin; the AMIS-30543 requires it. */ void init(uint8_t slaveSelectPin) { ssPin = slaveSelectPin; digitalWrite(ssPin, HIGH); pinMode(ssPin, OUTPUT); } /*! Reads the register at the given address and returns its raw value. */ uint8_t readReg(uint8_t address) { selectChip(); transfer(address & 0b11111); uint8_t dataOut = transfer(0); deselectChip(); return dataOut; } /*! Writes the specified value to a register. */ void writeReg(uint8_t address, uint8_t value) { selectChip(); transfer(0x80 | (address & 0b11111)); transfer(value); // The CS line must go high after writing for the value to actually take // effect. deselectChip(); } private: SPISettings settings = SPISettings(500000, MSBFIRST, SPI_MODE0); uint8_t transfer(uint8_t value) { return SPI.transfer(value); } void selectChip() { digitalWrite(ssPin, LOW); SPI.beginTransaction(settings); } void deselectChip() { digitalWrite(ssPin, HIGH); SPI.endTransaction(); // The CS high time is specified as 2.5 us in the AMIS-30543 datasheet. delayMicroseconds(3); } uint8_t ssPin; }; /*! This class provides high-level functions for controlling an AMIS-30543 * micro-stepping motor driver. * * It provides access to all the features of the AMIS-30543 SPI interface * except the watchdog timer. */ class AMIS30543 { public: /*! The default constructor. */ AMIS30543() { wr = cr0 = cr1 = cr2 = cr3 = 0; } /*! Possible arguments to setStepMode(). */ enum stepMode { MicroStep128 = 128, MicroStep64 = 64, MicroStep32 = 32, MicroStep16 = 16, MicroStep8 = 8, MicroStep4 = 4, MicroStep2 = 2, MicroStep1 = 1, CompensatedHalf = MicroStep2, CompensatedFullTwoPhaseOn = MicroStep1, CompensatedFullOnePhaseOn = 200, UncompensatedHalf = 201, UncompensatedFull = 202, }; /*! Bitmasks for the return value of readNonLatchedStatusFlags(). */ enum nonLatchedStatusFlag { OPENY = (1 << 2), OPENX = (1 << 3), WD = (1 << 4), CPFAIL = (1 << 5), TW = (1 << 6), }; /*! Bitmasks for the return value of readLatchedStatusFlagsAndClear(). */ enum latchedStatusFlag { OVCXNB = (1 << 3), OVCXNT = (1 << 4), OVCXPB = (1 << 5), OVCXPT = (1 << 6), TSD = (1 << 10), OVCYNB = (1 << 11), OVCYNT = (1 << 12), OVCYPB = (1 << 13), OVCYPT = (1 << 14), }; /*! Addresses of control and status registers. */ enum regAddr { WR = 0x0, CR0 = 0x1, CR1 = 0x2, CR2 = 0x3, CR3 = 0x9, SR0 = 0x4, SR1 = 0x5, SR2 = 0x6, SR3 = 0x7, SR4 = 0xA, }; /*! Configures this object to use the specified pin as a slave select pin. * You must use a slave select pin; the AMIS-30543 requires it. */ void init(uint8_t slaveSelectPin) { driver.init(slaveSelectPin); } /*! Changes all of the driver's settings back to their default values. * * It is good to call this near the beginning of your program to ensure that * There are no settings left over from an earlier time that might affect the * operation of the driver. */ void resetSettings() { wr = cr0 = cr1 = cr2 = cr3 = 0; applySettings(); } /*! Reads back all the SPI control registers from the device and * verifies that they are equal to the cached copies stored in this class. * * This can be used to verify that the driver is powered on and has not lost * them due to a power failure. However this function will probably return * true if the driver is not powered and all of the cached settings are the * default values. Therefore, we only recommend calling this after you have * changed at least one of the settings from its default value, for example * by calling enableDriver(). * * @return 1 if the settings from the device match the cached copies, 0 if * they do not. */ bool verifySettings() { return driver.readReg(WR) == wr && driver.readReg(CR0) == cr0 && driver.readReg(CR1) == cr1 && driver.readReg(CR2) == cr2 && driver.readReg(CR3) == cr3; } /*! Re-writes the cached settings stored in this class to the device. * * You should not normally need to call this function because settings are * written to the device whenever they are changed. However, if * verifySettings() returns false (due to a power interruption, for * instance), then you could use applySettings to get the device's settings * back into the desired state. */ void applySettings() { // Because of power interruption considerations, the register that // contains the MOTEN bit (CR2) must be written first, and whenever we // write to it we should also write to all the other registers. // CR2 is written first, because it contains the MOTEN bit, and there is // a risk that there might be a power interruption to the driver right // before CR2 is written. This could result in the motor being enabled // with incorrect settings. Also, whenever we do write to CR2, we want to // also write the other registers to make sure they are in the correct state. driver.writeReg(CR2, cr2); writeWR(); writeCR0(); writeCR1(); writeCR3(); } /*! Sets the MOTEN bit to 1, enabling the driver. * * Please read the note about this function in README.md. */ void enableDriver() { cr2 |= 0b10000000; applySettings(); } /*! Sets the MOTEN bit to 0, disabling the driver. * * Please read the note about this function in README.md. */ void disableDriver() { cr2 &= ~0b10000000; applySettings(); } /*! Sets the per-coil current limit equal to the highest available setting * that is less than the given current, in units of milliamps. * * Refer to Table 13 of the AMIS-30543 datasheet to see which current limits * are available. */ void setCurrentMilliamps(uint16_t current) { // This comes from Table 13 of the AMIS-30543 datasheet. uint8_t code = 0; if (current >= 3000) { code = 0b11001; } else if (current >= 2845) { code = 0b11000; } else if (current >= 2700) { code = 0b10111; } else if (current >= 2440) { code = 0b10110; } else if (current >= 2240) { code = 0b10101; } else if (current >= 2070) { code = 0b10100; } else if (current >= 1850) { code = 0b10011; } else if (current >= 1695) { code = 0b10010; } else if (current >= 1520) { code = 0b10001; } else if (current >= 1405) { code = 0b10000; } else if (current >= 1260) { code = 0b01111; } else if (current >= 1150) { code = 0b01110; } else if (current >= 1060) { code = 0b01101; } else if (current >= 955) { code = 0b01100; } else if (current >= 870) { code = 0b01011; } else if (current >= 780) { code = 0b01010; } else if (current >= 715) { code = 0b01001; } else if (current >= 640) { code = 0b01000; } else if (current >= 585) { code = 0b00111; } else if (current >= 540) { code = 0b00110; } else if (current >= 485) { code = 0b00101; } else if (current >= 445) { code = 0b00100; } else if (current >= 395) { code = 0b00011; } else if (current >= 355) { code = 0b00010; } else if (current >= 245) { code = 0b00001; } cr0 = (cr0 & 0b11100000) | code; writeCR0(); } /*! Reads the current microstepping position, which is a number between 0 * and 511. * * The different positions and their corresponding coil values are listed in * Table 9 of the AMIS-30543 datasheet. * * The lower two bits of this return value might be inaccurate if the step * pin is being toggled while this function runs (e.g. from an interrupt or * a PWM signal). * * Our tests indicated that the return value of this function might be wrong * if you read it within 25 microseconds of commanding the driver to take a * step. Therefore we recommend delaying for at least 100 microseconds after * taking a step and before calling this function. */ uint16_t readPosition() { uint8_t sr3 = readStatusReg(SR3); uint8_t sr4 = readStatusReg(SR4); return ((uint16_t)sr3 << 2) | (sr4 & 3); } /*! Sets the value of the DIRCTRL configuration bit. * * Allowed values are 0 or 1. * * You can use this command to control the direction of the stepper motor * and simply leave the DIR pin disconnected. */ void setDirection(bool value) { if (value) { cr1 |= 0x80; } else { cr1 &= ~0x80; } writeCR1(); } /*! Returns the cached value of the DIRCTRL configuration bit. * * This does not perform any SPI communication with the driver. */ bool getDirection() { return cr1 >> 7 & 1; } /*! Configures the driver to have the specified stepping mode. * * This affects many things about the performance of the motor, including * how much the output moves for each step taken and how much current flows * through the coils in each stepping position. * * The argument to this function should be one of the members of the * #stepMode enum. * * If an invalid stepping mode is passed to this function, then it selects * 1/32 micro-step, which is the driver's default. */ void setStepMode(uint8_t mode) { // Pick 1/32 micro-step by default. uint8_t esm = 0b000; uint8_t sm = 0b000; // The order of these cases matches the order in Table 12 of the // AMIS-30543 datasheet. switch(mode) { case MicroStep32: sm = 0b000; break; case MicroStep16: sm = 0b001; break; case MicroStep8: sm = 0b010; break; case MicroStep4: sm = 0b011; break; case CompensatedHalf: sm = 0b100; break; /* a.k.a. MicroStep2 */ case UncompensatedHalf: sm = 0b101; break; case UncompensatedFull: sm = 0b110; break; case MicroStep128: esm = 0b001; break; case MicroStep64: esm = 0b010; break; case CompensatedFullTwoPhaseOn: esm = 0b011; break; /* a.k.a. MicroStep 1 */ case CompensatedFullOnePhaseOn: esm = 0b100; break; } cr0 = (cr0 & ~0b11100000) | (sm << 5); cr3 = (cr3 & ~0b111) | esm; writeCR0(); writeCR3(); } /*! Sets the SLP bit 1, enabling sleep mode. * * According to the AMIS-30543 datasheet, the motor supply voltage must be * at least 9 V before entering sleep mode. * * You can call sleepStop() to disable sleep mode. * * Please read the note about this function in README.md. */ void sleep() { cr2 |= (1 << 6); applySettings(); } /*! Sets the SLP bit 0, disabling sleep mode. * * Please read the note about this function in README.md. */ void sleepStop() { cr2 &= ~(1 << 6); applySettings(); } /*! Sets the value of the NXTP configuration bit to 0, which means that new * steps are triggered by a rising edge on the NXT/STEP pin. This is the * default behavior. */ void stepOnRisingEdge() { cr1 &= ~0b01000000; writeCR1(); } /*! Sets the value of the NXTP configuration bit to 1, which means that new * steps are triggered by a falling edge on the NXT/STEP pin. */ void stepOnFallingEdge() { cr1 |= 0b01000000; writeCR1(); } /*! Sets the PWMF bit to 1, which doubles the PWM frequency (45.6 kHz) .*/ void setPwmFrequencyDouble() { cr1 |= (1 << 3); writeCR1(); } /*! Clears the PWMF bit, which sets the PWM frequency to its default value * (22.8 kHz). */ void setPwmFrequencyDefault() { cr1 &= ~(1 << 3); writeCR1(); } /*! Sets the PWMJ bit, which enables artificial jittering in the PWM signal * used to control the current to each coil. */ void setPwmJitterOn() { cr1 |= (1 << 2); writeCR1(); } /*! Clears the PWMJ bit, which disables artificial jittering in the PWM * signal used to control the current to each coil. This is the default * setting. */ void setPwmJitterOff() { cr1 &= ~(1 << 2); writeCR1(); } /*! This sets the EMC[1:0] bits, which determine how long it takes the PWM * signal to rise or fall. Valid values are 0 through 3. Higher values * correspond to longer rise and fall times. **/ void setPwmSlope(uint8_t emc) { cr1 = (cr1 & ~0b11) | (emc & 0b11); writeCR1(); } /*! Clears the SLAG bit, which configures the signal on SLA pin to have a * gain of 0.5 (the default). * * Please read the note about this function in README.md. */ void setSlaGainDefault() { cr2 &= ~(1 << 5); applySettings(); } /*! Sets the SLAG bit to 1, which configures the signal on SLA pin to have a * gain of 0.25 (half of the default). * * Please read the note about this function in README.md. */ void setSlaGainHalf() { cr2 |= (1 << 5); applySettings(); } /*! Set the SLAT bit to 0 (the default), which disables transparency on the * SLA pin. See the AMIS-30543 datasheet for more information. * * Please read the note about this function in README.md. */ void setSlaTransparencyOff() { cr2 &= ~(1 << 4); applySettings(); } /*! Sets the SLAT bit to 1, which enables transparency on the SLA pin. * See the AMIS-30543 datasheet for more information. * * Please read the note about this function in README.md. */ void setSlaTransparencyOn() { cr2 |= (1 << 4); applySettings(); } /*! Reads the status flags from registers SR0. These flags are not latched, * which means they will be cleared as soon as the condition causing them is * no longer detected. See the AMIS-30543 datasheet for more information. * * This function returns the raw value of SR0, with the parity bit set to 0. * You can simply compare the return value to 0 to see if any of the status * flags are set, or you can use the logical AND operator (`&`) and the * #nonLatchedStatusFlag enum to check individual flags. * * ~~~~{.cpp} * uint16_t flags = stepper.readNonLatchedStatusFlags(); * if (flags) * { * // At least one flag is set. * * if (flags & AMIS30543::OPENX) * { * // Thermal shutdown flag is set. * } * * } * ~~~~ */ uint16_t readNonLatchedStatusFlags() { return readStatusReg(SR0); } /*! Reads the latched status flags from registers SR1 and SR2. They are * cleared as a side effect. * * The return value is a 16-bit unsigned integer that has one bit for each * status flag. You can simply compare the return value to 0 to see if any * of the status flags are set, or you can use the logical and operator (`&`) * and the #latchedStatusFlag enum to check individual flags. * * WARNING: Calling this function clears the latched error bits in SR1 and * SR2, which might allow the motor driver outputs to reactivate. The * AMIS-30543 datasheet says "successive reading the SPI Status Registers 1 * and 2 in case of a short circuit condition, may lead to damage to the * drivers". */ uint16_t readLatchedStatusFlagsAndClear() { uint8_t sr1 = readStatusReg(SR1); uint8_t sr2 = readStatusReg(SR2); return (sr2 << 8) | sr1; } protected: uint8_t wr, cr0, cr1, cr2, cr3; /*! Reads a status register and returns the lower 7 bits (the parity bit is * set to 0 in the return value). */ uint8_t readStatusReg(uint8_t address) { // Mask off the parity bit. // (Later we might add code here to check the parity // bit and record errors.) return driver.readReg(address) & 0x7F; } /*! Writes the cached value of the WR register to the device. */ void writeWR() { driver.writeReg(WR, wr); } /*! Writes the cached value of the CR0 register to the device. */ void writeCR0() { driver.writeReg(CR0, cr0); } /*! Writes the cached value of the CR1 register to the device. */ void writeCR1() { driver.writeReg(CR1, cr1); } /*! Writes the cached value of the CR3 register to the device. */ void writeCR3() { driver.writeReg(CR3, cr3); } public: /*! This object handles all the communication with the AMIS-30543. It is * only marked as public for the purpose of testing this library; you should * not use it in your code. */ AMIS30543SPI driver; };
1.726563
2
src/Library-Management-System/borrower.h
aminbeigi/Library-Management-System
0
7999971
#ifndef GUARD_BORROWER_H #define GUARD_BORROWER_H #include <string> class Borrower { public: Borrower(); void set_id(unsigned int); void set_name(std::string name); unsigned int get_id(); std::string get_name(); private: std::string name; unsigned int id = 0; }; #endif
1.320313
1
chrome/browser/subresource_redirect/subresource_redirect_util.h
Ron423c/chromium
575
7999979
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SUBRESOURCE_REDIRECT_SUBRESOURCE_REDIRECT_UTIL_H_ #define CHROME_BROWSER_SUBRESOURCE_REDIRECT_SUBRESOURCE_REDIRECT_UTIL_H_ #include "base/macros.h" #include "base/time/time.h" #include "url/gurl.h" #include "url/origin.h" namespace content { class NavigationHandle; class WebContents; } // namespace content namespace subresource_redirect { class OriginRobotsRulesCache; // Returns whether LiteMode is enabled for the profile associated with the // |web_contents|. bool IsLiteModeEnabled(content::WebContents* web_contents); // Returns whether image compression should be applied for this web_contents. // Also shows an one-time InfoBar on Android if needed. bool ShowInfoBarAndGetImageCompressionState( content::WebContents* web_contents, content::NavigationHandle* navigation_handle); // Notifies to LiteMode that image compression fetch had failed. void NotifyCompressedImageFetchFailed(content::WebContents* web_contents, base::TimeDelta retry_after); // Returns the LitePages robots rules server endpoint URL to fetch for the given // |origin|. GURL GetRobotsServerURL(const url::Origin& origin); // Returns the robots rules cache for the profile of |web_contents|. OriginRobotsRulesCache* GetOriginRobotsRulesCache( content::WebContents* web_contents); // Returns the maximum number of origin robots rules the browser should cache // in-memory to be sent to the renderers immediately. int MaxOriginRobotsRulesCacheSize(); // Returns a random duration LitePages service should bypass for, when a // LitePages response fails without RetryAfter header. base::TimeDelta GetLitePagesBypassRandomDuration(); // Returns the maximum duration LitePages service should be bypassed. base::TimeDelta GetLitePagesBypassMaxDuration(); } // namespace subresource_redirect #endif // CHROME_BROWSER_SUBRESOURCE_REDIRECT_SUBRESOURCE_REDIRECT_UTIL_H_
1.203125
1
Source/GridRuntime/Public/GridInfo.h
LaudateCorpus1/Grid
183
7999987
#pragma once #include "CoreMinimal.h" #include "Engine/EngineTypes.h" #include "GameplayTagContainer.h" #include "GridInfo.generated.h" class UGrid; /** * */ UCLASS(Blueprintable) class GRIDRUNTIME_API UGridInfo : public UObject { GENERATED_BODY() public: UGridInfo(); virtual ~UGridInfo(); UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "GridInfo") void Clear(); virtual void Clear_Implementation(); /** property has changed, notify GridPainter refresh grid state */ UFUNCTION(BlueprintCallable, Category = "GridInfo") void Dirty(); UPROPERTY(BlueprintReadWrite, Category = "GridInfo") FHitResult HitResult; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GridInfo") FGameplayTagContainer GameplayTags; UGrid* ParentGrid; };
1.070313
1
frotz/src/common/files.c
saulpw/frotzos
7
7999995
/* files.c - Transscription, recording and playback * Copyright (c) 1995-1997 <NAME> * * This file is part of Frotz. * * Frotz is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Frotz is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include <stdio.h> #include <string.h> #include "frotz.h" #ifndef SEEK_SET #define SEEK_SET 0 #define SEEK_CUR 1 #define SEEK_END 2 #endif extern void set_more_prompts (bool); extern bool is_terminator (zchar); extern bool read_yes_or_no (const char *); char script_name[MAX_FILE_NAME + 1] = DEFAULT_SCRIPT_NAME; char command_name[MAX_FILE_NAME + 1] = DEFAULT_COMMAND_NAME; #ifdef __MSDOS__ extern char latin1_to_ibm[]; #endif static int script_width = 0; static FILE *sfp = NULL; static FILE *rfp = NULL; static FILE *pfp = NULL; /* * script_open * * Open the transscript file. 'AMFV' makes this more complicated as it * turns transscription on/off several times to exclude some text from * the transscription file. This wasn't a problem for the original V4 * interpreters which always sent transscription to the printer, but it * means a problem to modern interpreters that offer to open a new file * every time transscription is turned on. Our solution is to append to * the old transscription file in V1 to V4, and to ask for a new file * name in V5+. * */ void script_open (void) { static bool script_valid = FALSE; char new_name[MAX_FILE_NAME + 1]; h_flags &= ~SCRIPTING_FLAG; if (h_version >= V5 || !script_valid) { if (!os_read_file_name (new_name, script_name, FILE_SCRIPT)) goto done; strcpy (script_name, new_name); } /* Opening in "at" mode doesn't work for script_erase_input... */ if ((sfp = fopen (script_name, "r+t")) != NULL || (sfp = fopen (script_name, "w+t")) != NULL) { fseek (sfp, 0, SEEK_END); h_flags |= SCRIPTING_FLAG; script_valid = TRUE; ostream_script = TRUE; script_width = 0; } else print_string ("Cannot open file\n"); done: SET_WORD (H_FLAGS, h_flags); }/* script_open */ /* * script_close * * Stop transscription. * */ void script_close (void) { h_flags &= ~SCRIPTING_FLAG; SET_WORD (H_FLAGS, h_flags); fclose (sfp); ostream_script = FALSE; }/* script_close */ /* * script_new_line * * Write a newline to the transscript file. * */ void script_new_line (void) { if (fputc ('\n', sfp) == EOF) script_close (); script_width = 0; }/* script_new_line */ /* * script_char * * Write a single character to the transscript file. * */ void script_char (zchar c) { if (c == ZC_INDENT && script_width != 0) c = ' '; if (c == ZC_INDENT) { script_char (' '); script_char (' '); script_char (' '); return; } if (c == ZC_GAP) { script_char (' '); script_char (' '); return; } #ifdef __MSDOS__ if (c >= ZC_LATIN1_MIN) c = latin1_to_ibm[c - ZC_LATIN1_MIN]; #endif fputc (c, sfp); script_width++; }/* script_char */ /* * script_word * * Write a string to the transscript file. * */ void script_word (const zchar *s) { int width; int i; if (*s == ZC_INDENT && script_width != 0) script_char (*s++); for (i = 0, width = 0; s[i] != 0; i++) if (s[i] == ZC_NEW_STYLE || s[i] == ZC_NEW_FONT) i++; else if (s[i] == ZC_GAP) width += 3; else if (s[i] == ZC_INDENT) width += 2; else width += 1; if (f_setup.script_cols != 0 && script_width + width > f_setup.script_cols) { if (*s == ' ' || *s == ZC_INDENT || *s == ZC_GAP) s++; script_new_line (); } for (i = 0; s[i] != 0; i++) if (s[i] == ZC_NEW_FONT || s[i] == ZC_NEW_STYLE) i++; else script_char (s[i]); }/* script_word */ /* * script_write_input * * Send an input line to the transscript file. * */ void script_write_input (const zchar *buf, zchar key) { int width; int i; for (i = 0, width = 0; buf[i] != 0; i++) width++; if (f_setup.script_cols != 0 && script_width + width > f_setup.script_cols) script_new_line (); for (i = 0; buf[i] != 0; i++) script_char (buf[i]); if (key == ZC_RETURN) script_new_line (); }/* script_write_input */ /* * script_erase_input * * Remove an input line from the transscript file. * */ void script_erase_input (const zchar *buf) { int width; int i; for (i = 0, width = 0; buf[i] != 0; i++) width++; fseek (sfp, -width, SEEK_CUR); script_width -= width; }/* script_erase_input */ /* * script_mssg_on * * Start sending a "debugging" message to the transscript file. * */ void script_mssg_on (void) { if (script_width != 0) script_new_line (); script_char (ZC_INDENT); }/* script_mssg_on */ /* * script_mssg_off * * Stop writing a "debugging" message. * */ void script_mssg_off (void) { script_new_line (); }/* script_mssg_off */ /* * record_open * * Open a file to record the player's input. * */ void record_open (void) { char new_name[MAX_FILE_NAME + 1]; if (os_read_file_name (new_name, command_name, FILE_RECORD)) { strcpy (command_name, new_name); if ((rfp = fopen (new_name, "wt")) != NULL) ostream_record = TRUE; else print_string ("Cannot open file\n"); } }/* record_open */ /* * record_close * * Stop recording the player's input. * */ void record_close (void) { fclose (rfp); ostream_record = FALSE; }/* record_close */ /* * record_code * * Helper function for record_char. * */ static void record_code (int c, bool force_encoding) { if (force_encoding || c == '[' || c < 0x20 || c > 0x7e) { int i; fputc ('[', rfp); for (i = 10000; i != 0; i /= 10) if (c >= i || i == 1) fputc ('0' + (c / i) % 10, rfp); fputc (']', rfp); } else fputc (c, rfp); }/* record_code */ /* * record_char * * Write a character to the command file. * */ static void record_char (zchar c) { if (c != ZC_RETURN) { if (c < ZC_HKEY_MIN || c > ZC_HKEY_MAX) { record_code (translate_to_zscii (c), FALSE); if (c == ZC_SINGLE_CLICK || c == ZC_DOUBLE_CLICK) { record_code (mouse_x, TRUE); record_code (mouse_y, TRUE); } } else record_code (1000 + c - ZC_HKEY_MIN, TRUE); } }/* record_char */ /* * record_write_key * * Copy a keystroke to the command file. * */ void record_write_key (zchar key) { record_char (key); if (fputc ('\n', rfp) == EOF) record_close (); }/* record_write_key */ /* * record_write_input * * Copy a line of input to a command file. * */ void record_write_input (const zchar *buf, zchar key) { zchar c; while ((c = *buf++) != 0) record_char (c); record_char (key); if (fputc ('\n', rfp) == EOF) record_close (); }/* record_write_input */ /* * replay_open * * Open a file of commands for playback. * */ void replay_open (void) { char new_name[MAX_FILE_NAME + 1]; if (os_read_file_name (new_name, command_name, FILE_PLAYBACK)) { strcpy (command_name, new_name); if ((pfp = fopen (new_name, "rt")) != NULL) { set_more_prompts (read_yes_or_no ("Do you want MORE prompts")); istream_replay = TRUE; } else print_string ("Cannot open file\n"); } }/* replay_open */ /* * replay_close * * Stop playback of commands. * */ void replay_close (void) { set_more_prompts (TRUE); fclose (pfp); istream_replay = FALSE; }/* replay_close */ /* * replay_code * * Helper function for replay_key and replay_line. * */ static int replay_code (void) { int c; if ((c = fgetc (pfp)) == '[') { int c2; c = 0; while ((c2 = fgetc (pfp)) != EOF && c2 >= '0' && c2 <= '9') c = 10 * c + c2 - '0'; return (c2 == ']') ? c : EOF; } else return c; }/* replay_code */ /* * replay_char * * Read a character from the command file. * */ static zchar replay_char (void) { int c; if ((c = replay_code ()) != EOF) { if (c != '\n') { if (c < 1000) { c = translate_from_zscii (c); if (c == ZC_SINGLE_CLICK || c == ZC_DOUBLE_CLICK) { mouse_x = replay_code (); mouse_y = replay_code (); } return c; } else return ZC_HKEY_MIN + c - 1000; } ungetc ('\n', pfp); return ZC_RETURN; } else return ZC_BAD; }/* replay_char */ /* * replay_read_key * * Read a keystroke from a command file. * */ zchar replay_read_key (void) { zchar key; key = replay_char (); if (fgetc (pfp) != '\n') { replay_close (); return ZC_BAD; } else return key; }/* replay_read_key */ /* * replay_read_input * * Read a line of input from a command file. * */ zchar replay_read_input (zchar *buf) { zchar c; for (;;) { c = replay_char (); if (c == ZC_BAD || is_terminator (c)) break; *buf++ = c; } *buf = 0; if (fgetc (pfp) != '\n') { replay_close (); return ZC_BAD; } else return c; }/* replay_read_input */
1.398438
1