max_stars_repo_path
stringlengths
5
126
max_stars_repo_name
stringlengths
8
65
max_stars_count
float64
0
34.4k
id
stringlengths
5
7
content
stringlengths
58
511k
score
float64
0.38
1
label
stringclasses
3 values
lib/os/assert.c
lemrey/zephyr
35
816321
/* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <misc/__assert.h> #include <zephyr.h> /** * * @brief Assert Action Handler * * This routine implements the action to be taken when an assertion fails. * * System designers may wish to substitute this implementation to take other * actions, such as logging program counter, line number, debug information * to a persistent repository and/or rebooting the system. * * @param N/A * * @return N/A */ __weak void assert_post_action(const char *file, unsigned int line) { ARG_UNUSED(file); ARG_UNUSED(line); k_panic(); }
0.832031
high
system/book_apue/apue_copy/chapter17/clientmgr.c
larryjiang/cs_study
0
849089
<reponame>larryjiang/cs_study #include "opend.h" #define NALLOC 10 static void client_alloc(void){ int i; if(client == NULL){ client = malloc(NALLOC * sizeof (Client)); }else{ client = realloc(client,(client_size + NALLOC) * sizeof (Client)); }; if(client == NULL){ err_sys("can't alloc for client array"); }; for(i = client_size; i< client_size + NALLOC; i++){ client[i].fd = -1; }; client_size += NALLOC; }; int client_add(int fd, uid_t uid){ int i; if(client == NULL){ client_alloc(); }; again: for(i = 0; i< client_size; i++){ if(client[i].fd ==-1){ client[i].fd = fd; client[i].uid = uid; return (i); }; }; client_alloc(); goto again; }; void client_del(int fd){ int i; for(i = 0; i < client_size; i++){ if(client[i].fd == fd){ client[i].fd = -1; return; }; }; log_quit("can not find client entry for fd %d", fd); };
0.921875
high
srcs/utils/help.c
tkomatsu/push_swap
0
881857
<reponame>tkomatsu/push_swap /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* help.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tkomatsu <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/31 17:19:29 by tkomatsu #+# #+# */ /* Updated: 2021/04/09 20:42:16 by tkomatsu ### ########.fr */ /* */ /* ************************************************************************** */ #include "utils.h" void print_description(char *app) { if (!ft_strcasecmp(app, "checker")) { ft_putstr_fd("Takes integer args and reads ", STDOUT); ft_putendl_fd("instructions on STDIN.", STDOUT); ft_putstr_fd("Once read, cheker executes ", STDOUT); ft_putendl_fd("them and display result.\n", STDOUT); } else if (!ft_strcasecmp(app, "push_swap")) { ft_putstr_fd("Calcurates and displays instruction ", STDOUT); ft_putendl_fd("that sorts args on STDOUT\n", STDOUT); } } void print_usage(char *app, int color) { if (color) ft_putstr_fd(YELLOW, STDOUT); ft_putendl_fd("USAGE: ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putstr_fd(" ", STDOUT); ft_putstr_fd(app, STDOUT); ft_putendl_fd(" [OPTIONS] [NUMBERS]...\n", STDOUT); } void print_options(void) { ft_putstr_fd(YELLOW, STDOUT); ft_putendl_fd("OPTIONS:", STDOUT); ft_putstr_fd(END, STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" -c ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd("Show in colors the last operation.", STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" -h ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd("Print help message.", STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" -v ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd("Display the stacks's status.", STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" -a ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd("Clear terminal each operation.\n", STDOUT); } void print_args(void) { ft_putstr_fd(YELLOW, STDOUT); ft_putendl_fd("ARGS:", STDOUT); ft_putstr_fd(END, STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" <NUMBERS>... ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putstr_fd("Integer number(s) separated by ", STDOUT); ft_putendl_fd("one or more space(s).\n", STDOUT); } void help(char *app_path) { char *app; char *url; url = "https://projects.intra.42.fr/projects/42cursus-push_swap"; app = ft_strrchr(app_path, '/') + 1; ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(app, STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd(" 1.0", STDOUT); print_description(app); print_usage(app, 1); print_options(); print_args(); ft_putstr_fd(BOLD, STDOUT); ft_putstr_fd("To get more information, check intranet at ", STDOUT); ft_putendl_fd(url, STDOUT); ft_putstr_fd(END, STDOUT); exit(EXIT_SUCCESS); }
0.886719
high
G39_Lab2 - Stacks, Subroutines, and C/address_map_arm.h
ismailfaruk/ECSE324--Computer-Organization
3
914625
<filename>G39_Lab2 - Stacks, Subroutines, and C/address_map_arm.h /* This files provides address values that exist in the system */ #define BOARD "DE1-SoC" /* Memory */ #define DDR_BASE 0x00000000 #define DDR_END 0x3FFFFFFF #define A9_ONCHIP_BASE 0xFFFF0000 #define A9_ONCHIP_END 0xFFFFFFFF #define SDRAM_BASE 0xC0000000 #define SDRAM_END 0xC3FFFFFF #define FPGA_ONCHIP_BASE 0xC8000000 #define FPGA_ONCHIP_END 0xC803FFFF #define FPGA_CHAR_BASE 0xC9000000 #define FPGA_CHAR_END 0xC9001FFF /* Cyclone V FPGA devices */ #define LEDR_BASE 0xFF200000 #define HEX3_HEX0_BASE 0xFF200020 #define HEX5_HEX4_BASE 0xFF200030 #define SW_BASE 0xFF200040 #define KEY_BASE 0xFF200050 #define JP1_BASE 0xFF200060 #define JP2_BASE 0xFF200070 #define PS2_BASE 0xFF200100 #define PS2_DUAL_BASE 0xFF200108 #define JTAG_UART_BASE 0xFF201000 #define JTAG_UART_2_BASE 0xFF201008 #define IrDA_BASE 0xFF201020 #define TIMER_BASE 0xFF202000 #define TIMER_2_BASE 0xFF202020 #define AV_CONFIG_BASE 0xFF203000 #define PIXEL_BUF_CTRL_BASE 0xFF203020 #define CHAR_BUF_CTRL_BASE 0xFF203030 #define AUDIO_BASE 0xFF203040 #define VIDEO_IN_BASE 0xFF203060 #define ADC_BASE 0xFF204000 /* Cyclone V HPS devices */ #define HPS_GPIO1_BASE 0xFF709000 #define I2C0_BASE 0xFFC04000 #define I2C1_BASE 0xFFC05000 #define I2C2_BASE 0xFFC06000 #define I2C3_BASE 0xFFC07000 #define HPS_TIMER0_BASE 0xFFC08000 #define HPS_TIMER1_BASE 0xFFC09000 #define HPS_TIMER2_BASE 0xFFD00000 #define HPS_TIMER3_BASE 0xFFD01000 #define FPGA_BRIDGE 0xFFD0501C /* ARM A9 MPCORE devices */ #define PERIPH_BASE 0xFFFEC000 // base address of peripheral devices #define MPCORE_PRIV_TIMER 0xFFFEC600 // PERIPH_BASE + 0x0600 /* Interrupt controller (GIC) CPU interface(s) */ #define MPCORE_GIC_CPUIF 0xFFFEC100 // PERIPH_BASE + 0x100 #define ICCICR 0x00 // offset to CPU interface control reg #define ICCPMR 0x04 // offset to interrupt priority mask reg #define ICCIAR 0x0C // offset to interrupt acknowledge reg #define ICCEOIR 0x10 // offset to end of interrupt reg /* Interrupt controller (GIC) distributor interface(s) */ #define MPCORE_GIC_DIST 0xFFFED000 // PERIPH_BASE + 0x1000 #define ICDDCR 0x00 // offset to distributor control reg #define ICDISER 0x100 // offset to interrupt set-enable regs #define ICDICER 0x180 // offset to interrupt clear-enable regs #define ICDIPTR 0x800 // offset to interrupt processor targets regs #define ICDICFR 0xC00 // offset to interrupt configuration regs
0.988281
high
firmware/xmc4500_relax_kit/smart_logger/deffs.h
hmz06967/smart_logger
1
7080617
/** * @file deffs.h * * @date 28.2.19 * @author <NAME> * @brief definitions and variables file for the application. */ #ifndef DEFFS_H_ #define DEFFS_H_ // definitions #define LED1 P1_1 ///< LED1 on XMC4500 relax kit connected to the Port 1.1. #define LED2 P1_0 ///< LED2 on XMC4500 relax kit connected to the Port 1.0. #define BUTTON1 P1_14 ///< Button 1 on XMC4500 relax kit connected to the Port 1.14. #define BUTTON2 P1_15 ///< Button 2 on XMC4500 relax kit connected to the Port 1.15. #define SAMPLING_PERIOD 1 #define CELL_VOLTAGES_SAMPLING_PERIOD 10 #define CAN_TIMEOUT 5 #define CELL_VOLTAGES_FLOW_COUNT 8 #define CELL_VOLTAGES_DATA_FLOW_COUNT 4 #define CELL_COUNTS 93 #define SET_TIME_MENU_ITEMS_COUNT 8 ///< Timer set menu items count uint8_t dataUpdated = 0; uint8_t cellVoltagesUpdated=0; unsigned long int sampleCounter=0; void UpdateLCD(void); FATFS FatFs; ///< FatFs work area needed for each volume. FIL Fil; ///< File object needed for each open file. XMC_RTC_TIME_t current_time; XMC_RTC_TIME_t set_time; uint8_t setTimeOnProcces=0; ///< Process indicator variable for the time set state machine. uint8_t setTimeMenu = 0; ///< Menu variable for time set uint8_t button2Pressed=0; enum timeSetStates { SET_TIME_IDLE = 0, ///< Idle state. SET_TIME_INIT, ///< Init state. YEAR, ///< Year set state. MONTH, ///< Month set state. DAY, ///< Day set state. HOUR, ///< Hour set state. MINUTE, ///< Minute set state. SET_OK ///< Time set ok state }; //uint8_t timeSetState= SET_TIME_IDLE; ///< State holder variable for the time set state machine. enum enumStates{ IDLE=0, ///< Idle state. GET_VELOCITY, ///< Get Smart velocity value. GET_BATT_AMP, ///< Get battery current. GET_BATT_VOLTAGE, ///< Get battery main voltage. GET_MODULE_TEMPS, ///< Get battery module temperatures. GET_CELL_VOLTAGES ///< Get battery cell voltages. }; uint8_t state = IDLE; ///< State holder variable for the main state machine. enum enumBattVoltStates{ BATT_VOLT_IDLE = 0, ///< Batt voltage idle state. BATT_VOLT_REQ_RESPONSE, ///< Batt voltage request response state. BATT_VOLT_FLOW_RESPONSE ///< Batt voltage flow control response state. }; uint8_t stateBattVolt = BATT_VOLT_IDLE; ///< State holder variable for battery voltage state machine. enum enumModuleTempsStates{ MODULE_TEMPS_IDLE = 0, ///< Module temperatures idle state. MODULE_TEMPS_REQ_RESPONSE, ///< Module temperatures request response state. MODULE_TEMPS_FLOW_RESPONSE ///< Module temperatures flow control response state. }; uint8_t stateModuleTemps = MODULE_TEMPS_IDLE; ///< State holder variable for module temperatures state machine. enum enumCellVoltagesStates{ CELL_VOLTAGES_IDLE = 0, ///< Cell voltages idle state. CELL_VOLTAGES_REQ_RESPONSE, ///< Cell voltages request response state. CELL_VOLTAGES_FLOW_CONTROL, ///< Cell voltages flow control response state. CELL_VOLTAGES_LAST_FLOW_PACKAGE ///< Cell voltages last flow package state }; uint8_t stateCellVoltages = CELL_VOLTAGES_IDLE; ///< State holder variable for module temperatures state machine. uint8_t cellVoltagesFlowCounter = 0; uint8_t onProcess = 0; ///< Process indicator variable for the main state machine. uint8_t samplingTimer=0; uint8_t canTimeoutTimerEnable=0; uint8_t canTimeoutCounter=0; /// Flow control package. uint8_t flowControl[8] = {0x30, 0x08, 0x14, 0xff, 0xff, 0xff, 0xff, 0xff}; /// Battery amp request package. uint8_t reqBattAmp[8] = {0x03, 0x22, 0x02, 0x03, 0xff, 0xff, 0xff, 0xff}; /// Battery voltage request package. uint8_t reqBattVolt[8] = {0x03, 0x22, 0x02, 0x04, 0xff, 0xff, 0xff, 0xff}; /// Module temperatures request package. uint8_t reqModuleTemps[8] = {0x03, 0x22, 0x02, 0x02, 0xff, 0xff, 0xff, 0xff}; /// Battery cell voltages request package. uint8_t reqCellVoltages[8] = {0x03, 0x22, 0x02, 0x08, 0xff, 0xff, 0xff, 0xff}; typedef struct { uint16_t velocitiy; float battAmp; float battVolt; float battPower; float battEnergy; float bms; uint8_t tempRawBytes[18]; float temps[9]; union { uint8_t cellVotlagesBytes[CELL_VOLTAGES_DATA_FLOW_COUNT*56+4]; ///< Byte array for cell voltages to read easily from can frames. uint16_t cellVoltages[CELL_VOLTAGES_DATA_FLOW_COUNT*28+2]; ///< Word array for cell voltages to represent in milliVolts. }; } smartData_t; smartData_t smartdata; #endif /* DEFFS_H_ */
0.988281
high
linux-2.6.35.3/drivers/mxc/security/sahara2/include/sah_kernel.h
isabella232/wireless-media-drive
10
7113385
<filename>linux-2.6.35.3/drivers/mxc/security/sahara2/include/sah_kernel.h /* * Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. */ /* * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License * Version 2 or later at the following locations: * * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ /* * @file sah_kernel.h * * @brief Provides definitions for items that user-space and kernel-space share. */ /****************************************************************************** * * This file needs to be PORTED to a non-Linux platform */ #ifndef SAH_KERNEL_H #define SAH_KERNEL_H #if defined(__KERNEL__) #if defined(CONFIG_ARCH_MXC91321) || defined(CONFIG_ARCH_MXC91231) \ || defined(CONFIG_ARCH_MX27) || defined(CONFIG_ARCH_MXC92323) #include <mach/hardware.h> #define SAHA_BASE_ADDR SAHARA_BASE_ADDR #define SAHARA_IRQ MXC_INT_SAHARA #elif defined(CONFIG_ARCH_MX5) #include <mach/hardware.h> #define SAHA_BASE_ADDR SAHARA_BASE_ADDR #define SAHARA_IRQ MXC_INT_SAHARA_H0 #else #include <mach/mx2.h> #endif #endif /* KERNEL */ /* IO Controls */ /* The magic number 'k' is reserved for the SPARC architecture. (See <kernel * source root>/Documentation/ioctl-number.txt. * * Note: Numbers 8-13 were used in a previous version of the API and should * be avoided. */ #define SAH_IOC_MAGIC 'k' #define SAHARA_HWRESET _IO(SAH_IOC_MAGIC, 0) #define SAHARA_SET_HA _IO(SAH_IOC_MAGIC, 1) #define SAHARA_CHK_TEST_MODE _IOR(SAH_IOC_MAGIC,2, int) #define SAHARA_DAR _IO(SAH_IOC_MAGIC, 3) #define SAHARA_GET_RESULTS _IO(SAH_IOC_MAGIC, 4) #define SAHARA_REGISTER _IO(SAH_IOC_MAGIC, 5) #define SAHARA_DEREGISTER _IO(SAH_IOC_MAGIC, 6) /* 7 */ /* 8 */ /* 9 */ /* 10 */ /* 11 */ /* 12 */ /* 13 */ #define SAHARA_SCC_DROP_PERMS _IOWR(SAH_IOC_MAGIC, 14, scc_partition_info_t) #define SAHARA_SCC_SFREE _IOWR(SAH_IOC_MAGIC, 15, scc_partition_info_t) #define SAHARA_SK_ALLOC _IOWR(SAH_IOC_MAGIC, 16, scc_slot_t) #define SAHARA_SK_DEALLOC _IOWR(SAH_IOC_MAGIC, 17, scc_slot_t) #define SAHARA_SK_LOAD _IOWR(SAH_IOC_MAGIC, 18, scc_slot_t) #define SAHARA_SK_UNLOAD _IOWR(SAH_IOC_MAGIC, 19, scc_slot_t) #define SAHARA_SK_SLOT_ENC _IOWR(SAH_IOC_MAGIC, 20, scc_slot_t) #define SAHARA_SK_SLOT_DEC _IOWR(SAH_IOC_MAGIC, 21, scc_slot_t) #define SAHARA_SCC_ENCRYPT _IOWR(SAH_IOC_MAGIC, 22, scc_region_t) #define SAHARA_SCC_DECRYPT _IOWR(SAH_IOC_MAGIC, 23, scc_region_t) #define SAHARA_GET_CAPS _IOWR(SAH_IOC_MAGIC, 24, fsl_shw_pco_t) #define SAHARA_SCC_SSTATUS _IOWR(SAH_IOC_MAGIC, 25, scc_partition_info_t) #define SAHARA_SK_READ _IOWR(SAH_IOC_MAGIC, 29, scc_slot_t) /*! This is the name that will appear in /proc/interrupts */ #define SAHARA_NAME "SAHARA" /*! * SAHARA IRQ number. See page 9-239 of TLICS - Motorola Semiconductors H.K. * TAHITI-Lite IC Specification, Rev 1.1, Feb 2003. * * TAHITI has two blocks of 32 interrupts. The SAHARA IRQ is number 27 * in the second block. This means that the SAHARA IRQ is 27 + 32 = 59. */ #ifndef SAHARA_IRQ #define SAHARA_IRQ (27+32) #endif /*! * Device file definition. The #ifndef is here to support the unit test code * by allowing it to specify a different test device. */ #ifndef SAHARA_DEVICE_SHORT #define SAHARA_DEVICE_SHORT "sahara" #endif #ifndef SAHARA_DEVICE #define SAHARA_DEVICE "/dev/"SAHARA_DEVICE_SHORT #endif #endif /* SAH_KERNEL_H */ /* End of sah_kernel.h */
0.992188
high
bob/bob.h
embeddedawesome/BOB
1
7146153
<reponame>embeddedawesome/BOB #pragma once #include <set> #include <string> namespace bob { typedef std::set<std::string> component_list_t; typedef std::set<std::string> feature_list_t; static std::string component_dotname_to_id(const std::string dotname) { return dotname.find_last_of(".") != std::string::npos ? dotname.substr(dotname.find_last_of(".")+1) : dotname; } std::string exec( const std::string_view command_text, const std::string_view& arg_text ); }
0.878906
high
walleve/walleve/entry/entry.h
FissionAndFusion/FnFnMvWallet-Pre
22
7178921
// Copyright (c) 2016-2019 The Multiverse developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef WALLEVE_ENTRY_H #define WALLEVE_ENTRY_H #include <string> #include <boost/asio.hpp> #include <boost/interprocess/sync/file_lock.hpp> namespace walleve { class CWalleveEntry { public: CWalleveEntry(); ~CWalleveEntry(); bool TryLockFile(const std::string& strLockFile); virtual bool Run(); virtual void Stop(); protected: void HandleSignal(const boost::system::error_code& error,int signal_number); protected: boost::asio::io_service ioService; boost::asio::signal_set ipcSignals; boost::interprocess::file_lock lockFile; }; } // namespace walleve #endif //WALLEVE_ENTRY_H
0.992188
high
bzip2/win32/bzip2_version.h
jhpark16/PHT3D-Viewer-OpenGL
0
945073
#define BZIP2_VERSION_STR "1.0.6" #define BZIP2_VER_MAJOR 1 #define BZIP2_VER_MINOR 0 #define BZIP2_VER_REVISION 6
0.498047
low
src/lib/module/Effect_table.h
cyberixae/kunquat
0
977841
/* * Author: <NAME>, Finland 2011-2014 * * This file is part of Kunquat. * * CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/ * * To the extent possible under law, Kunquat Affirmers have waived all * copyright and related or neighboring rights to Kunquat. */ #ifndef K_EFFECT_TABLE_H #define K_EFFECT_TABLE_H #include <stdbool.h> #include <devices/Effect.h> /** * This is the storage object for Effects. */ typedef struct Effect_table Effect_table; /** * Create a new Effect table. * * \param size The table size -- must be > \c 0. * * \return The new Effect table if successful, or \c NULL if memory * allocation failed. */ Effect_table* new_Effect_table(int size); /** * Insert a new Effect into the Effect table. * * If the target index already contains an Effect, it will be deleted. * * \param table The Effect table -- must not be \c NULL. * \param index The target index -- must be >= \c 0 and less than * the table size. * \param eff The Effect to be inserted -- must not be \c NULL or * an Effect already stored in the table. * * \return \c true if successful, or \c false if memory allocation failed. */ bool Effect_table_set(Effect_table* table, int index, Effect* eff); /** * Get an Effect from the Effect table. * * \param table The Effect table -- must not be \c NULL. * \param index The target index -- must be >= \c 0 and less than * the table size. * * \return The Effect if found, otherwise \c NULL. */ const Effect* Effect_table_get(const Effect_table* table, int index); /** * Get a mutable Effect from the Effect table. * * \param table The Effect table -- must not be \c NULL. * \param index The target index -- must be >= \c 0 and less than * the table size. * * \return The Effect if found, otherwise \c NULL. */ Effect* Effect_table_get_mut(Effect_table* table, int index); /** * Remove an Effect from the Effect table. * * \param table The Effect table -- must not be \c NULL. * \param index The target index -- must be >= \c 0 and less than * the table size. */ void Effect_table_remove(Effect_table* table, int index); /** * Clear the Effect table. * * \param table The Effect table -- must not be \c NULL. */ void Effect_table_clear(Effect_table* table); /** * Destroy an existing Effect table. * * \param table The Effect table, or \c NULL. */ void del_Effect_table(Effect_table* table); #endif // K_EFFECT_TABLE_H
0.996094
high
user-rs/libkernel/native_stubs/stubs.c
gkanwar/gullfoss-os
0
2410609
<reponame>gkanwar/gullfoss-os // kernel void spawn() {} void yield() {} void exit() {} void send() {} void accept() {} // graphics void get_framebuffer() {}
0.847656
low
include/dynamic_obstacle_avoidance_planner/dynamic_local_costmap_generator.h
amslabtech/dynamic_obstacle_avoidance_planner
33
2443377
<gh_stars>10-100 #ifndef __DYNAMIC_LOCAL_COSTMAP_GENERATOR_H #define __DYNAMIC_LOCAL_COSTMAP_GENERATOR_H #include <ros/ros.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> #include <geometry_msgs/TransformStamped.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/PoseArray.h> #include <nav_msgs/OccupancyGrid.h> #include <std_msgs/Int32.h> #include <Eigen/Dense> #include "dynamic_obstacle_avoidance_planner/obstacle_tracker_kf.h" class DynamicLocalCostmapGenerator { public: DynamicLocalCostmapGenerator(void); void process(void); void robot_path_callback(const geometry_msgs::PoseArrayConstPtr&); void obstacle_pose_callback(const geometry_msgs::PoseArrayConstPtr&); void setup_map(void); bool predict_intersection(geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose); void predict_intersection_point(geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::PoseStamped&); bool predict_approaching(geometry_msgs::Pose, geometry_msgs::Pose); bool predict_approaching(geometry_msgs::Pose&, geometry_msgs::Pose&, geometry_msgs::Pose&); void set_cost_with_velocity(geometry_msgs::PoseStamped&, geometry_msgs::Twist&, geometry_msgs::Twist&); inline int get_i_from_x(double); inline int get_j_from_y(double); inline int get_index(double, double); inline int get_distance_grid(int, int, int, int); private: double PREDICTION_TIME;// [s], trafjectory prediction time double HZ; double DT;// [s] int PREDICTION_STEP; double MAP_WIDTH;// [m] double RESOLUTION;// [m] double RADIUS;// radius for collision check[m] double COST_COLLISION; double MIN_COST; double MAX_COST; std::string WORLD_FRAME; std::string OBS_FRAME; std::string ROBOT_FRAME; ros::NodeHandle nh; ros::NodeHandle local_nh; ros::Publisher costmap_pub; ros::Publisher obstacles_predicted_path_pub; ros::Subscriber robot_predicted_path_sub; ros::Subscriber obstacle_pose_sub; tf::TransformListener listener; geometry_msgs::PoseArray robot_path; geometry_msgs::PoseArray obstacle_paths; geometry_msgs::PoseArray obstacle_pose; nav_msgs::OccupancyGrid local_costmap; int obs_num; ObstacleTrackerKF tracker; }; #endif// __DYNAMIC_LOCAL_COSTMAP_GENERATOR_H
0.988281
high
Data_types/double_dynamic_array.c
UAH-s-Telematics-Engineering-Tasks/c_basics
0
2476145
<gh_stars>0 #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { char** array; char aux_str[20]; int size; printf("Size of the main array: "); /*do { scanf("%d", &size); while(getchar() != '\n'); } while (size < 1); array = (char**) malloc(size * sizeof(char*)); for (int i = 0; i < size; i++) { printf("String to be entered: "); fgets(aux_str, 20, stdin); aux_str[strlen(aux_str) - 1] = '\0'; array[i] = (char*) malloc((strlen(aux_str) + 1) * sizeof(char)); if (array[i] != NULL) { strcpy(array[i], aux_str); } else { printf("ERROR!!\n"); return -1; } }*/ printf("\n\n\n"); for (int i = 0; i < size; i++) { printf("String at position %d: %s\n", i, array[i]); } for (int i = 0; i < size; i++) { free(array[i]); } free(array); return 0; } char** function_1(int* size) { char aux_arr[20], char** f_array; printf("Number of rows: "); scanf("%d", size); f_array = (char**) malloc(sizeof(char*) * (*size)); if (f_array == NULL) { return NULL } else { for (int i = 0; i < size; i++) { printf("Enter a string: "); fgets(aux_str, 20, stdin); aux_str[strlen(aux_str) - 1] = '\0'; f_array[i] = (char*) malloc(sizeof(char) * (strlen(aux_str) + 1)); if (f_array[i] != NULL) { strcpy(f_array[i], aux_str); } else { printf("ERROR!!\n"); f_array[i] = NULL; } } } return f_array; } void function_2(char*** ptr, int rows) { char aux_str[20]; char** array = *ptr; array = (char**) malloc(sizeof(char*) * rows); if (array != NULL) { for (int i = 0; i < rows; i++) { printf("Enter a string: "); fgets(aux_str, 20, stdin); aux_str[strlen(aux_str) - 1] = '\0'; array[i] = (char*) malloc((strlen(aux_str) + 1) * sizeof(char)); if (array[i] != NULL) { strcpy(array[i], aux_str); } else { printf("ERROR!!\n"); array[i] = NULL; } } } *ptr = array; }
0.847656
high
Pod/Classes/SVGPathSegmentClosePath.h
cotkjaer/SilverbackScalableVectorGraphics
1
2508913
// // SVGPathElementSegmentClosePath.h // Pods // // Created by <NAME> on 16/12/14. // // #import "SVGPathSegment.h" @interface SVGPathSegmentClosePath : SVGPathSegment @end
0.664063
low
include/sra_board.h
ombhilare999/sra-board-component
2
2541681
<reponame>ombhilare999/sra-board-component #ifndef SRA_BOARD_H #define SRA_BOARD_H #include "adc.h" #include "bar_graph.h" #include "switches.h" #include "lsa.h" #include "motor_driver.h" #include "mpu6050.h" #include "servo.h" #include "pin_defs.h" #include "utils.h" #endif
0.511719
high
Colleges/Análise e Desenvolvimento de Sistemas/Lógica de Programação/1º Prova/Prova EX4.c
jlenon7/progress
2
2574449
#include <stdio.h> int main() { int i=1, menor=30, maior=50,soma=0,tempo; float media; while (i <= 4) { printf("Informe a temperaturo de hoje dia"); scanf("%d",&tempo); if (tempo > menor) maior = tempo; if (tempo < maior) menor = tempo; soma = soma +tempo; i++; } media = tempo /4; printf("A menor temperatura do ano foi %d\n",menor); printf("A maior temperatura do ano foi %d\n",maior); printf("A media anual foi %1.f",media); return 0; }
0.496094
low
libft/ft_memchr.c
amnotme/42_Libft
4
4007217
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_memchr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lhernand <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/09/28 16:34:11 by lhernand #+# #+# */ /* Updated: 2017/12/14 02:16:29 by lhernand ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /* ** The ft_memchr() function locates the first occurrence of c (converted to ** an unsigned char) in string s. ** ** The ft_memchr() function returns a pointer to the byte located, or NULL ** if no such byte exists within n bytes. */ void *ft_memchr(const void *s, int c, size_t n) { const unsigned char *s1; unsigned char ch; s1 = s; ch = c; while (n > 0) { if (*s1 == ch) return ((unsigned char *)s1); s1++; n--; } return (NULL); }
0.980469
high
port/target/atmegaxx4/utils/bootload_avr.h
n3rd-bugs/tiny-rtos
6
4039985
/* * bootload_avr.h * * Copyright (c) 2016 <NAME> <<EMAIL>> All rights reserved. * * This file is part of a non-commercial software. For more details please * refer to the license agreement that comes with this software. * * If you have not received a license file please contact: * <NAME> <<EMAIL>> * */ #ifndef _BOOTLOAD_AVR_H_ #define _BOOTLOAD_AVR_H_ #include <kernel.h> #ifdef CONFIG_BOOTLOAD #include <bootload_avr_config.h> /* Error code definitions. */ #define BOOTLOAD_COMPLETE -21000 #define BOOTLOAD_ERROR -21001 /* Serial configurations for boot loader. */ #define BOOTLOAD_BAUD_RATE (115200) #define BOOTLOAD_BAUD_TOL (2) /* Macro to be used to move a function in the boot loader section. */ #define BOOTLOAD_SECTION __attribute__ ((section (".boot"))) #define BOOTVECTOR_SECTION __attribute__ ((section (".boot_vector"))) #if defined(AVR_MCU_atmega644p) #define BOOTLOAD_RESET 0xF000 #elif defined(AVR_MCU_atmega1284p) #define BOOTLOAD_RESET 0x1F000 #else #error "Bootloader is not supported on sepecified AVR target" #endif /* Defines the condition when we need to perform boot load operation. */ #define BOOTLOAD_COND_INIT (DDRA &= ((uint8_t)~(1 << 6))) #define BOOTLOAD_COND ((PINA & (1 << 6)) == 0) /* Helper macros. */ #define BOOTLOAD_BTOH(a) (((a) > 9) ? (a) + 0x37 : (a) + '0') /* Link the boot loader API. */ #define BOOTLOAD bootload_entry /* Function prototypes. */ void bootload_entry(void); #ifndef BOOTLOADER_LOADED void bootload_avr(void) BOOTLOAD_SECTION; int32_t bootload_disk_initialize(uint8_t *) BOOTLOAD_SECTION; int32_t bootload_disk_read(uint8_t, uint8_t *, uint32_t, uint32_t, uint32_t *) BOOTLOAD_SECTION; #if _USE_WRITE int32_t bootload_disk_write(uint8_t, const uint8_t *, uint32_t, uint32_t) BOOTLOAD_SECTION; #endif #if _USE_IOCTL int32_t bootload_disk_ioctl(uint8_t, void *) BOOTLOAD_SECTION; #endif #endif /* BOOTLOADER_LOADED */ #endif /* CONFIG_BOOTLOAD */ #endif /* _BOOTLOAD_AVR_H_ */
0.992188
high
MogaSerial_MFC/vJoy/public.h
kvanderlaag/MogaSerial
108
4072753
<gh_stars>100-1000 /*++ Copyright (c) <NAME>. All rights reserved. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Module Name: public.h Abstract: Public header file for the vJoy project Developpers that need to interface with vJoy need to include this file Author: Environment: kernel mode and User mode Notes: Revision History: --*/ #ifndef _PUBLIC_H #define _PUBLIC_H // Compilation directives #define PPJOY_MODE #undef PPJOY_MODE // Comment-out for compatibility mode #ifdef PPJOY_MODE #include "PPJIoctl.h" #endif #include <INITGUID.H> // Definitions for controlling GUID initialization // Sideband comunication with vJoy Device //{781EF630-72B2-11d2-B852-00C04FAD5101} DEFINE_GUID(GUID_DEVINTERFACE_VJOY, 0x781EF630, 0x72B2, 0x11d2, 0xB8, 0x52, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x01); // // Usage example: // CreateFile(TEXT("\\\\.\\vJoy"), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); #ifdef PPJOY_MODE #define DEVICENAME_STRING "PPJoyIOCTL1" #else #define DEVICENAME_STRING "vJoy" #endif #define NTDEVICE_NAME_STRING "\\Device\\"DEVICENAME_STRING #define SYMBOLIC_NAME_STRING "\\DosDevices\\"DEVICENAME_STRING #define DOS_FILE_NAME "\\\\.\\"DEVICENAME_STRING #define VJOY_INTERFACE L"Device_" // Version parts #define VER_X_ 0 #define VER_H_ 2 #define VER_M_ 1 #define VER_L_ 6 #define STRINGIFY_1(x) #x #define STRINGIFY(x) STRINGIFY_1(x) #define PASTE(x, y) x##y #define MAKEWIDE(x) PASTE(L,x) // Device Attributes // #define VENDOR_N_ID 0x1234 #define PRODUCT_N_ID 0xBEAD #define VERSION_N (VER_L_ + 0x10*VER_M_ + 0x100*VER_H_ + 0x1000*VER_X_) // Device Strings // #define VENDOR_STR_ID L"<NAME>" #define PRODUCT_STR_ID L"vJoy - Virtual Joystick" #define SERIALNUMBER_STR MAKEWIDE(STRINGIFY(VER_H_)) L"." MAKEWIDE(STRINGIFY(VER_M_)) L"." MAKEWIDE(STRINGIFY(VER_L_)) // Function codes; //#define LOAD_POSITIONS 0x910 //#define GETATTRIB 0x911 // #define GET_FFB_DATA 0x00222912 // METHOD_OUT_DIRECT + FILE_DEVICE_UNKNOWN + FILE_ANY_ACCESS //#define SET_FFB_STAT 0x913 // METHOD_NEITHER //#define GET_FFB_STAT 0x916 #define F_LOAD_POSITIONS 0x910 #define F_GETATTRIB 0x911 #define F_GET_FFB_DATA 0x912 #define F_SET_FFB_STAT 0x913 #define F_GET_FFB_STAT 0x916 #define F_GET_DEV_INFO 0x917 #define F_IS_DRV_FFB_CAP 0x918 #define F_IS_DRV_FFB_EN 0x919 #define F_GET_DRV_DEV_MAX 0x91A #define F_GET_DRV_DEV_EN 0x91B #define F_IS_DEV_FFB_START 0x91C #define F_GET_DEV_STAT 0x91D #define F_GET_DRV_INFO 0x91E #define F_RESET_DEV 0x91F // IO Device Control codes; #define IOCTL_VJOY_GET_ATTRIB CTL_CODE (FILE_DEVICE_UNKNOWN, GETATTRIB, METHOD_BUFFERED, FILE_WRITE_ACCESS) #define LOAD_POSITIONS CTL_CODE (FILE_DEVICE_UNKNOWN, F_LOAD_POSITIONS, METHOD_BUFFERED, FILE_WRITE_ACCESS) #define GET_FFB_DATA CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_FFB_DATA, METHOD_OUT_DIRECT, FILE_ANY_ACCESS) #define SET_FFB_STAT CTL_CODE (FILE_DEVICE_UNKNOWN, F_SET_FFB_STAT, METHOD_NEITHER, FILE_ANY_ACCESS) #define GET_FFB_STAT CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_FFB_STAT, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DEV_INFO CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DEV_INFO, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IS_DRV_FFB_CAP CTL_CODE (FILE_DEVICE_UNKNOWN, F_IS_DRV_FFB_CAP, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IS_DRV_FFB_EN CTL_CODE (FILE_DEVICE_UNKNOWN, F_IS_DRV_FFB_EN, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DRV_DEV_MAX CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DRV_DEV_MAX, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DRV_DEV_EN CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DRV_DEV_EN, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IS_DEV_FFB_START CTL_CODE (FILE_DEVICE_UNKNOWN, F_IS_DEV_FFB_START, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DEV_STAT CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DEV_STAT, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DRV_INFO CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DRV_INFO, METHOD_BUFFERED, FILE_ANY_ACCESS) #define RESET_DEV CTL_CODE (FILE_DEVICE_UNKNOWN, F_RESET_DEV, METHOD_BUFFERED, FILE_WRITE_ACCESS) #ifndef __HIDPORT_H__ // Copied from hidport.h #define IOCTL_HID_SET_FEATURE 0xB0191 #define IOCTL_HID_WRITE_REPORT 0xB000F #define MAX_N_DEVICES 16 // Maximum number of vJoy devices typedef struct _HID_DEVICE_ATTRIBUTES { ULONG Size; // // sizeof (struct _HID_DEVICE_ATTRIBUTES) // // // Vendor ids of this hid device // USHORT VendorID; USHORT ProductID; USHORT VersionNumber; USHORT Reserved[11]; } HID_DEVICE_ATTRIBUTES, * PHID_DEVICE_ATTRIBUTES; #endif // Error levels for status report enum ERRLEVEL {INFO, WARN, ERR, FATAL, APP}; // Status report function prototype #ifdef WINAPI typedef BOOL (WINAPI *StatusMessageFunc)(void * output, TCHAR * buffer, enum ERRLEVEL level); #endif /////////////////////////////////////////////////////////////// /////////////////////// Joystick Position /////////////////////// // // This structure holds data that is passed to the device from // an external application such as SmartPropoPlus. // // Usage example: // JOYSTICK_POSITION iReport; // : // DeviceIoControl (hDevice, 100, &iReport, sizeof(HID_INPUT_REPORT), NULL, 0, &bytes, NULL) typedef struct _JOYSTICK_POSITION { BYTE bDevice; // Index of device. 1-based. LONG wThrottle; LONG wRudder; LONG wAileron; LONG wAxisX; LONG wAxisY; LONG wAxisZ; LONG wAxisXRot; LONG wAxisYRot; LONG wAxisZRot; LONG wSlider; LONG wDial; LONG wWheel; LONG wAxisVX; LONG wAxisVY; LONG wAxisVZ; LONG wAxisVBRX; LONG wAxisVBRY; LONG wAxisVBRZ; LONG lButtons; // 32 buttons: 0x00000001 means button1 is pressed, 0x80000000 -> button32 is pressed DWORD bHats; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch DWORD bHatsEx1; // 16-bit of continuous HAT switch DWORD bHatsEx2; // 16-bit of continuous HAT switch DWORD bHatsEx3; // 16-bit of continuous HAT switch } JOYSTICK_POSITION, *PJOYSTICK_POSITION; // Superset of JOYSTICK_POSITION // Extension of JOYSTICK_POSITION with Buttons 33-128 appended to the end of the structure. typedef struct _JOYSTICK_POSITION_V2 { /// JOYSTICK_POSITION BYTE bDevice; // Index of device. 1-based. LONG wThrottle; LONG wRudder; LONG wAileron; LONG wAxisX; LONG wAxisY; LONG wAxisZ; LONG wAxisXRot; LONG wAxisYRot; LONG wAxisZRot; LONG wSlider; LONG wDial; LONG wWheel; LONG wAxisVX; LONG wAxisVY; LONG wAxisVZ; LONG wAxisVBRX; LONG wAxisVBRY; LONG wAxisVBRZ; LONG lButtons; // 32 buttons: 0x00000001 means button1 is pressed, 0x80000000 -> button32 is pressed DWORD bHats; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch DWORD bHatsEx1; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch DWORD bHatsEx2; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch DWORD bHatsEx3; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch LONG lButtonsEx1; // Buttons 33-64 /// JOYSTICK_POSITION_V2 Extenssion LONG lButtonsEx1; // Buttons 33-64 LONG lButtonsEx2; // Buttons 65-96 LONG lButtonsEx3; // Buttons 97-128 } JOYSTICK_POSITION_V2, *PJOYSTICK_POSITION_V2; // HID Descriptor definitions - Axes #define HID_USAGE_X 0x30 #define HID_USAGE_Y 0x31 #define HID_USAGE_Z 0x32 #define HID_USAGE_RX 0x33 #define HID_USAGE_RY 0x34 #define HID_USAGE_RZ 0x35 #define HID_USAGE_SL0 0x36 #define HID_USAGE_SL1 0x37 #define HID_USAGE_WHL 0x38 #define HID_USAGE_POV 0x39 // HID Descriptor definitions - FFB Effects #define HID_USAGE_CONST 0x26 // Usage ET Constant Force #define HID_USAGE_RAMP 0x27 // Usage ET Ramp #define HID_USAGE_SQUR 0x30 // Usage ET Square #define HID_USAGE_SINE 0x31 // Usage ET Sine #define HID_USAGE_TRNG 0x32 // Usage ET Triangle #define HID_USAGE_STUP 0x33 // Usage ET Sawtooth Up #define HID_USAGE_STDN 0x34 // Usage ET Sawtooth Down #define HID_USAGE_SPRNG 0x40 // Usage ET Spring #define HID_USAGE_DMPR 0x41 // Usage ET Damper #define HID_USAGE_INRT 0x42 // Usage ET Inertia #define HID_USAGE_FRIC 0x43 // Usage ET Friction // HID Descriptor definitions - FFB Report IDs #define HID_ID_STATE 0x02 // Usage PID State report #define HID_ID_EFFREP 0x01 // Usage Set Effect Report #define HID_ID_ENVREP 0x02 // Usage Set Envelope Report #define HID_ID_CONDREP 0x03 // Usage Set Condition Report #define HID_ID_PRIDREP 0x04 // Usage Set Periodic Report #define HID_ID_CONSTREP 0x05 // Usage Set Constant Force Report #define HID_ID_RAMPREP 0x06 // Usage Set Ramp Force Report #define HID_ID_CSTMREP 0x07 // Usage Custom Force Data Report #define HID_ID_SMPLREP 0x08 // Usage Download Force Sample #define HID_ID_EFOPREP 0x0A // Usage Effect Operation Report #define HID_ID_BLKFRREP 0x0B // Usage PID Block Free Report #define HID_ID_CTRLREP 0x0C // Usage PID Device Control #define HID_ID_GAINREP 0x0D // Usage Device Gain Report #define HID_ID_SETCREP 0x0E // Usage Set Custom Force Report #define HID_ID_NEWEFREP 0x01 // Usage Create New Effect Report #define HID_ID_BLKLDREP 0x02 // Usage Block Load Report #define HID_ID_POOLREP 0x03 // Usage PID Pool Report #endif
0.988281
high
tags/rel_4_0-RC3/lib/hobbitrrd.c
eagle-1/xymon
0
4105521
<reponame>eagle-1/xymon<gh_stars>0 /*----------------------------------------------------------------------------*/ /* bbgen toolkit */ /* */ /* This is a library module, part of libbbgen. */ /* It contains routines for working with LARRD graphs. */ /* */ /* Copyright (C) 2002-2004 <NAME> <<EMAIL>> */ /* */ /* This program is released under the GNU General Public License (GPL), */ /* version 2. See the file "COPYING" for details. */ /* */ /*----------------------------------------------------------------------------*/ static char rcsid[] = "$Id: hobbitrrd.c,v 1.21 2005-02-22 14:14:50 henrik Exp $"; #include <ctype.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <time.h> #include "libbbgen.h" #include "version.h" #include "bblarrd.h" /* This is for mapping a status-name -> RRD file */ larrdrrd_t *larrdrrds = NULL; /* This is the information needed to generate links to larrd-grapher.cgi */ larrdgraph_t *larrdgraphs = NULL; static const char *bblinkfmt = "<br><A HREF=\"%s\"><IMG BORDER=0 SRC=\"%s&amp;graph=hourly\" ALT=\"larrd is accumulating %s\"></A>\n"; static const char *hobbitlinkfmt = "<table summary=\"Graph\"><tr><td><A HREF=\"%s&amp;action=menu\"><IMG BORDER=0 SRC=\"%s&amp;graph=hourly&amp;action=view\" ALT=\"hobbit graph %s\"></A></td><td> <td align=\"left\" valign=\"top\"> <a href=\"%s&amp;graph=hourly&amp;action=selzoom\"> <img src=\"%s/zoom.gif\" border=0 alt=\"Zoom graph\" style='padding: 3px'> </a> </td></tr></table>\n"; static const char *metafmt = "<RRDGraph>\n <GraphLink><![CDATA[%s]]></GraphLink>\n <GraphImage><![CDATA[%s&graph=hourly]]></GraphImage>\n</RRDGraph>\n"; /* * Define the mapping between BB columns and LARRD graphs. * Normally they are identical, but some RRD's use different names. */ static void larrd_setup(void) { static int setup_done = 0; char *lenv, *ldef, *p, *tcptests; int count; larrdrrd_t *lrec; larrdgraph_t *grec; /* Do nothing if we have been called within the past 5 minutes */ if ((setup_done + 300) >= time(NULL)) return; /* Must free any old data first */ lrec = larrdrrds; while (lrec) { if (lrec->larrdrrdname != lrec->bbsvcname) xfree(lrec->larrdrrdname); xfree(lrec->bbsvcname); lrec++; } if (larrdrrds) xfree(larrdrrds); grec = larrdgraphs; while (grec) { if (grec->larrdpartname) xfree(grec->larrdpartname); xfree(grec->larrdrrdname); grec++; } if (larrdgraphs) xfree(larrdgraphs); /* Get the tcp services, and count how many there are */ tcptests = strdup(init_tcp_services()); count = 0; p = strtok(tcptests, " "); while (p) { count++; p = strtok(NULL, " "); } strcpy(tcptests, init_tcp_services()); /* Setup the larrdrrds table, mapping test-names to RRD files */ lenv = (char *)malloc(strlen(xgetenv("LARRDS")) + strlen(tcptests) + count*strlen(",=tcp") + 1); strcpy(lenv, xgetenv("LARRDS")); p = lenv+strlen(lenv)-1; if (*p == ',') *p = '\0'; /* Drop a trailing comma */ p = strtok(tcptests, " "); while (p) { sprintf(lenv+strlen(lenv), ",%s=tcp", p); p = strtok(NULL, " "); } xfree(tcptests); count = 0; p = lenv; do { count++; p = strchr(p+1, ','); } while (p); larrdrrds = (larrdrrd_t *)calloc(sizeof(larrdrrd_t), (count+1)); lrec = larrdrrds; ldef = strtok(lenv, ","); while (ldef) { p = strchr(ldef, '='); if (p) { *p = '\0'; lrec->bbsvcname = strdup(ldef); lrec->larrdrrdname = strdup(p+1); } else { lrec->bbsvcname = lrec->larrdrrdname = strdup(ldef); } ldef = strtok(NULL, ","); lrec++; } xfree(lenv); /* Setup the larrdgraphs table, describing how to make graphs from an RRD */ lenv = strdup(xgetenv("GRAPHS")); p = lenv+strlen(lenv)-1; if (*p == ',') *p = '\0'; /* Drop a trailing comma */ count = 0; p = lenv; do { count++; p = strchr(p+1, ','); } while (p); larrdgraphs = (larrdgraph_t *)calloc(sizeof(larrdgraph_t), (count+1)); grec = larrdgraphs; ldef = strtok(lenv, ","); while (ldef) { p = strchr(ldef, ':'); if (p) { *p = '\0'; grec->larrdrrdname = strdup(ldef); grec->larrdpartname = strdup(p+1); p = strchr(grec->larrdpartname, ':'); if (p) { *p = '\0'; grec->maxgraphs = atoi(p+1); if (strlen(grec->larrdpartname) == 0) { xfree(grec->larrdpartname); grec->larrdpartname = NULL; } } } else { grec->larrdrrdname = strdup(ldef); } ldef = strtok(NULL, ","); grec++; } xfree(lenv); setup_done = time(NULL); } larrdrrd_t *find_larrd_rrd(char *service, char *flags) { /* Lookup an entry in the larrdrrds table */ larrdrrd_t *lrec; larrd_setup(); if (flags && (strchr(flags, 'R') != NULL)) { /* Dont do LARRD for reverse tests, since they have no data */ return NULL; } lrec = larrdrrds; while (lrec->bbsvcname && strcmp(lrec->bbsvcname, service)) lrec++; return (lrec->bbsvcname ? lrec : NULL); } larrdgraph_t *find_larrd_graph(char *rrdname) { /* Lookup an entry in the larrdgraphs table */ larrdgraph_t *grec; int found = 0; char *dchar; larrd_setup(); grec = larrdgraphs; while (!found && (grec->larrdrrdname != NULL)) { found = (strncmp(grec->larrdrrdname, rrdname, strlen(grec->larrdrrdname)) == 0); if (found) { /* Check that it's not a partial match, e.g. "ftp" matches "ftps" */ dchar = rrdname + strlen(grec->larrdrrdname); if ( (*dchar != '.') && (*dchar != ',') && (*dchar != '\0') ) found = 0; } if (!found) grec++; } return (found ? grec : NULL); } static char *larrd_graph_text(char *hostname, char *dispname, char *service, larrdgraph_t *graphdef, int itemcount, int larrd043, int hobbitd, const char *fmt) { static char *rrdurl = NULL; static int rrdurlsize = 0; char *svcurl; int svcurllen, rrdparturlsize; char rrdservicename[100]; MEMDEFINE(rrdservicename); dprintf("rrdlink_url: host %s, rrd %s (partname:%s, maxgraphs:%d, count=%d), larrd043=%d\n", hostname, graphdef->larrdrrdname, textornull(graphdef->larrdpartname), graphdef->maxgraphs, itemcount, larrd043); if ((service != NULL) && (strcmp(graphdef->larrdrrdname, "tcp") == 0)) { sprintf(rrdservicename, "tcp:%s", service); } else { strcpy(rrdservicename, graphdef->larrdrrdname); } svcurllen = 2048 + strlen(xgetenv("CGIBINURL")) + strlen(hostname) + strlen(rrdservicename) + (dispname ? strlen(urlencode(dispname)) : 0); svcurl = (char *) malloc(svcurllen); rrdparturlsize = 2048 + strlen(fmt) + 3*svcurllen + strlen(rrdservicename) + strlen(xgetenv("BBSKIN")); if (rrdurl == NULL) { rrdurlsize = rrdparturlsize; rrdurl = (char *) malloc(rrdurlsize); } *rrdurl = '\0'; if (hobbitd) { char *rrdparturl; int first = 1; int step = 5; if (itemcount > 0) { int gcount = (itemcount / 5); if ((gcount*5) != itemcount) gcount++; step = (itemcount / gcount); } rrdparturl = (char *) malloc(rrdparturlsize); do { if (itemcount > 0) { sprintf(svcurl, "%s/hobbitgraph.sh?host=%s&amp;service=%s&amp;first=%d&amp;count=%d", xgetenv("CGIBINURL"), hostname, rrdservicename, first, step); } else { sprintf(svcurl, "%s/hobbitgraph.sh?host=%s&amp;service=%s", xgetenv("CGIBINURL"), hostname, rrdservicename); } if (dispname) { strcat(svcurl, "&amp;disp="); strcat(svcurl, urlencode(dispname)); } sprintf(rrdparturl, fmt, svcurl, svcurl, rrdservicename, svcurl, xgetenv("BBSKIN")); if ((strlen(rrdparturl) + strlen(rrdurl) + 1) >= rrdurlsize) { rrdurlsize += (4096 + (itemcount - (first+step-1))*rrdparturlsize); rrdurl = (char *) realloc(rrdurl, rrdurlsize); } strcat(rrdurl, rrdparturl); first += step; } while (first <= itemcount); xfree(rrdparturl); } else if (larrd043 && graphdef->larrdpartname && (itemcount > 0)) { char *rrdparturl; int first = 0; rrdparturl = (char *) malloc(rrdparturlsize); do { int last; last = (first-1)+graphdef->maxgraphs; if (last > itemcount) last = itemcount; sprintf(svcurl, "%s/larrd-grapher.cgi?host=%s&amp;service=%s&amp;%s=%d..%d", xgetenv("CGIBINURL"), hostname, rrdservicename, graphdef->larrdpartname, first, last); if (dispname) { strcat(svcurl, "&amp;disp="); strcat(svcurl, urlencode(dispname)); } sprintf(rrdparturl, fmt, svcurl, svcurl, rrdservicename, svcurl, xgetenv("BBSKIN")); if ((strlen(rrdparturl) + strlen(rrdurl) + 1) >= rrdurlsize) { rrdurlsize += (4096 + (itemcount - last)*rrdparturlsize); rrdurl = (char *) realloc(rrdurl, rrdurlsize); } strcat(rrdurl, rrdparturl); first = last+1; } while (first < itemcount); xfree(rrdparturl); } else { sprintf(svcurl, "%s/larrd-grapher.cgi?host=%s&amp;service=%s", xgetenv("CGIBINURL"), hostname, rrdservicename); if (dispname) { strcat(svcurl, "&amp;disp="); strcat(svcurl, urlencode(dispname)); } sprintf(rrdurl, fmt, svcurl, svcurl, rrdservicename, svcurl, xgetenv("BBSKIN")); } dprintf("URLtext: %s\n", rrdurl); xfree(svcurl); MEMUNDEFINE(rrdservicename); return rrdurl; } char *larrd_graph_data(char *hostname, char *dispname, char *service, larrdgraph_t *graphdef, int itemcount, int larrd043, int hobbitd, int wantmeta) { if (wantmeta) return larrd_graph_text(hostname, dispname, service, graphdef, itemcount, 1, 0, metafmt); else if (hobbitd) return larrd_graph_text(hostname, dispname, service, graphdef, itemcount, larrd043, hobbitd, hobbitlinkfmt); else return larrd_graph_text(hostname, dispname, service, graphdef, itemcount, larrd043, hobbitd, bblinkfmt); }
0.992188
high
ios/HRFramework.framework/Headers/HRNavigationController.h
HerenMA/HRFramework
0
4138289
<filename>ios/HRFramework.framework/Headers/HRNavigationController.h // // HRNavigationController.h // HRFramework // // Created by 尹建军 on 2017/4/5. // Copyright © 2017年 浙江和仁科技股份有限公司. All rights reserved. // #import <UIKit/UIKit.h> /** 导航条 */ @interface HRNavigationController : UINavigationController /// 状态栏样式 @property (assign, nonatomic) UIStatusBarStyle statusBarStyle; /// 背景颜色 @property (strong, nonatomic) UIColor *backgroundColor; /// 标题颜色 @property (strong, nonatomic) UIColor *titleColor; /// 着色颜色 @property (strong, nonatomic) UIColor *tintColor; /// 返回按钮标题 @property (strong, nonatomic) NSString *backTitle; /// 返回按钮图片 @property (strong, nonatomic) UIImage *backImage; /// 隐藏分隔线 @property (assign, nonatomic) BOOL hideSeparator; /// 分隔线颜色 @property (strong, nonatomic) UIColor *separatorColor; /// 设备方向 @property (assign, nonatomic) UIInterfaceOrientation interfaceOrientation; /// 屏幕旋转方向 @property (assign, nonatomic) UIInterfaceOrientationMask interfaceOrientationMask; /** Returns the popped controller. @param animationTransition <#animationTransition description#> @return <#return value description#> */ - (UIViewController *)popViewControllerAnimationTransition:(UIViewAnimationTransition)animationTransition; /** Uses a horizontal slide transition. Has no effect if the view controller is already in the stack. @param viewController <#viewController description#> @param animationTransition <#animationTransition description#> */ - (void)pushViewController:(UIViewController *)viewController animationTransition:(UIViewAnimationTransition)animationTransition; @end
0.933594
high
soundgen.c
bharadwaj-raju/SoundGen
2
4171057
#include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <math.h> #include "wavfile.h" #define TRUE 1 #define FALSE 0 struct Tone { float duration; float frequency; float amplitude_perc; }; short * calculate_tone(double duration, double frequency, double amplitude) { int n_samples = (int) WAVFILE_SAMPLES_PER_SECOND * duration; int volume = (int) 32768 * (amplitude / 100); short * waveform = malloc(sizeof(short) * n_samples); for (int i=0; i<n_samples;i++) { double t = (double) i / WAVFILE_SAMPLES_PER_SECOND; waveform[i] = (int) volume * sin(frequency * t * 2 * M_PI); } return waveform; } int main(int argc, char * argv[]) { int opt_play = FALSE; if (argc < 3) { printf("Not enough arguments.\n"); printf("Usage: %s tones_file wav_output_file [--play]\n", argv[0]); return 1; } if (argc == 3) { if (access(argv[1], F_OK) == -1) { printf("File %s does not exist.\n", argv[1]); return 1; } } if (argc > 3) { if (strcmp(argv[3], "--play") == 0) { opt_play = TRUE; } } FILE * tones_fp = fopen(argv[1], "r"); if (tones_fp == NULL) { printf("Could not open file %s for reading.\n", argv[1]); return 1; } char line[512]; char **lines = NULL; int n_tones = 0; while (fgets(line, sizeof(line), tones_fp)) { lines = (char **) realloc(lines, (n_tones+1) * sizeof(char *)); lines[n_tones++] = strdup(line); } struct Tone tones[n_tones]; float d, f, a = 0.0; char sd[256], sf[256], sa[256]; float total_duration = 0.0; for (int i=0; i<n_tones; i++) { sscanf(lines[i], "%s %s %s\n", sd, sf, sa); d = atof(sd); f = atof(sf); a = atof(sa); tones[i].duration = d; tones[i].frequency = f; tones[i].amplitude_perc = a; total_duration += d; free(lines[i]); } int total_samples = (int) (total_duration * WAVFILE_SAMPLES_PER_SECOND); short * final_waveform = malloc(total_samples * sizeof(short)); printf("%d\n", total_samples); int samples_done = 0; for (int i=0; i<n_tones; i++) { int n_samples = (int) WAVFILE_SAMPLES_PER_SECOND * tones[i].duration; short * wavepart = calculate_tone(tones[i].duration, tones[i].frequency, tones[i].amplitude_perc); memcpy(final_waveform + samples_done, wavepart, n_samples * sizeof(short)); samples_done += n_samples; printf("Tone %d: d=%f f=%f a=%f n_samp=%d samp_done=%d\n", i, tones[i].duration, tones[i].frequency, tones[i].amplitude_perc, n_samples, samples_done); free(wavepart); } FILE * out_fp = wavfile_open(argv[2]); if (out_fp == NULL) { printf("Could not open file %s for writing.\n", argv[2]); return 1; } wavfile_write(out_fp, final_waveform, total_samples); wavfile_close(out_fp); fclose(tones_fp); free(final_waveform); free(lines); char commandbuffer[512]; sprintf(commandbuffer, "aplay '%500s'", argv[2]); if (opt_play == TRUE) { system(commandbuffer); } }
0.984375
high
games/sail/pl_7.c
lambdaxymox/DragonFlyBSD
432
5603825
/* $NetBSD: pl_7.c,v 1.42 2011/08/26 06:18:18 dholland Exp $ */ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> #ifndef lint #if 0 static char sccsid[] = "@(#)pl_7.c 8.1 (Berkeley) 5/31/93"; #else __RCSID("$NetBSD: pl_7.c,v 1.42 2011/08/26 06:18:18 dholland Exp $"); #endif #endif /* not lint */ #include <curses.h> #include <err.h> #include <errno.h> #include <signal.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "array.h" #include "extern.h" #include "player.h" #include "display.h" /* * Use values above KEY_MAX for custom keycodes. (blymn@ says this is ok) */ #define KEY_ESC(ch) (KEY_MAX+10+ch) /* * Display interface */ static void draw_view(void); static void draw_turn(void); static void draw_stat(void); static void draw_slot(void); static void draw_board(void); static struct stringarray *sc_lines; static unsigned sc_scrollup; static bool sc_hasprompt; static bool sc_hideprompt; static const char *sc_prompt; static const char *sc_buf; static WINDOW *view_w; static WINDOW *turn_w; static WINDOW *stat_w; static WINDOW *slot_w; static WINDOW *scroll_w; static bool obp[3]; static bool dbp[3]; int done_curses; static bool ingame; int loaded, fired, changed, repaired; int dont_adjust; static int viewrow, viewcol; char movebuf[sizeof SHIP(0)->file->movebuf]; int player; struct ship *ms; /* memorial structure, &cc->ship[player] */ struct File *mf; /* ms->file */ struct shipspecs *mc; /* ms->specs */ //////////////////////////////////////////////////////////// // overall initialization static void define_esc_key(int ch) { char seq[3] = { '\x1b', ch, 0 }; define_key(seq, KEY_ESC(ch)); } void initscreen(void) { int ch; sc_lines = stringarray_create(); if (sc_lines == NULL) { err(1, "malloc"); } if (signal(SIGTSTP, SIG_DFL) == SIG_ERR) { err(1, "signal(SIGTSTP)"); } if (initscr() == NULL) { errx(1, "Can't sail on this terminal."); } if (STAT_R >= COLS || SCROLL_Y <= 0) { errx(1, "Window/terminal not large enough."); } view_w = newwin(VIEW_Y, VIEW_X, VIEW_T, VIEW_L); slot_w = newwin(SLOT_Y, SLOT_X, SLOT_T, SLOT_L); scroll_w = newwin(SCROLL_Y, SCROLL_X, SCROLL_T, SCROLL_L); stat_w = newwin(STAT_Y, STAT_X, STAT_T, STAT_L); turn_w = newwin(TURN_Y, TURN_X, TURN_T, TURN_L); if (view_w == NULL || slot_w == NULL || scroll_w == NULL || stat_w == NULL || turn_w == NULL) { endwin(); errx(1, "Curses initialization failed."); } leaveok(view_w, 1); leaveok(slot_w, 1); leaveok(stat_w, 1); leaveok(turn_w, 1); noecho(); cbreak(); /* * Define esc-x keys */ #if 0 for (ch = 0; ch < 127; ch++) { if (ch != '[' && ch != 'O') { define_esc_key(ch); } } #else (void)ch; (void)define_esc_key; #endif keypad(stdscr, 1); keypad(view_w, 1); keypad(slot_w, 1); keypad(scroll_w, 1); keypad(stat_w, 1); keypad(turn_w, 1); done_curses++; } void cleanupscreen(void) { /* alarm already turned off */ if (done_curses) { if (ingame) { wmove(scroll_w, SCROLL_Y - 1, 0); wclrtoeol(scroll_w); display_redraw(); } else { move(LINES-1, 0); clrtoeol(); } endwin(); } } //////////////////////////////////////////////////////////// // curses utility functions /* * fill to eol with spaces * (useful with A_REVERSE since cleartoeol() does not clear to reversed) */ static void filltoeol(void) { int x; for (x = getcurx(stdscr); x < COLS; x++) { addch(' '); } } /* * Add a maybe-selected string. * * Place strings starting at (Y0, X0); this is string ITEM; CURITEM * is the selected one; WIDTH is the total width. STR is the string. */ static void mvaddselstr(int y, int x0, int item, int curitem, size_t width, const char *str) { size_t i, len; len = strlen(str); move(y, x0); if (curitem == item) { attron(A_REVERSE); } addstr(str); if (curitem == item) { for (i=len; i<width; i++) { addch(' '); } attroff(A_REVERSE); } } /* * Likewise but a printf. */ static void __printflike(6, 7) mvselprintw(int y, int x0, int item, int curitem, size_t width, const char *fmt, ...) { va_list ap; size_t x; move(y, x0); if (curitem == item) { attron(A_REVERSE); } va_start(ap, fmt); vw_printw(stdscr, fmt, ap); va_end(ap); if (curitem == item) { for (x = getcurx(stdscr); x < x0 + width; x++) { addch(' '); } attroff(A_REVERSE); } } /* * Move up by 1, scrolling if needed. */ static void up(int *posp, int *scrollp) { if (*posp > 0) { (*posp)--; } if (scrollp != NULL) { if (*posp < *scrollp) { *scrollp = *posp; } } } /* * Move down by 1, scrolling if needed. MAX is the total number of * items; VISIBLE is the number that can be visible at once. */ static void down(int *posp, int *scrollp, int max, int visible) { if (max > 0 && *posp < max - 1) { (*posp)++; } if (scrollp != NULL) { if (*posp > *scrollp + visible - 1) { *scrollp = *posp - visible + 1; } } } /* * Complain briefly. */ static void __printflike(3, 4) oops(int y, int x, const char *fmt, ...) { int oy, ox; va_list ap; oy = getcury(stdscr); ox = getcurx(stdscr); move(y, x); va_start(ap, fmt); vw_printw(stdscr, fmt, ap); va_end(ap); move(oy, ox); wrefresh(stdscr); sleep(1); } //////////////////////////////////////////////////////////// // scrolling message area static void scrollarea_add(const char *text) { char *copy; int errsave; copy = strdup(text); if (copy == NULL) { goto nomem; } if (stringarray_add(sc_lines, copy, NULL)) { goto nomem; } return; nomem: /* * XXX this should use leave(), but that won't * currently work right. */ errsave = errno; #if 0 leave(LEAVE_MALLOC); #else cleanupscreen(); sync_close(!hasdriver); errno = errsave; err(1, "malloc"); #endif } static void draw_scroll(void) { unsigned total_lines; unsigned visible_lines; unsigned index_of_top; unsigned index_of_y; unsigned y; unsigned cursorx; werase(scroll_w); /* XXX: SCROLL_Y and whatnot should be unsigned too */ visible_lines = SCROLL_Y - 1; total_lines = stringarray_num(sc_lines); if (total_lines > visible_lines) { index_of_top = total_lines - visible_lines; } else { index_of_top = 0; } if (index_of_top < sc_scrollup) { index_of_top = 0; } else { index_of_top -= sc_scrollup; } for (y = 0; y < visible_lines; y++) { index_of_y = index_of_top + y; if (index_of_y >= total_lines) { break; } wmove(scroll_w, y, 0); waddstr(scroll_w, stringarray_get(sc_lines, index_of_y)); } if (sc_hasprompt && !sc_hideprompt) { wmove(scroll_w, SCROLL_Y-1, 0); waddstr(scroll_w, sc_prompt); waddstr(scroll_w, sc_buf); cursorx = strlen(sc_prompt) + strlen(sc_buf); wmove(scroll_w, SCROLL_Y-1, cursorx); } else { wmove(scroll_w, SCROLL_Y-1, 0); } } /*VARARGS2*/ void Signal(const char *fmt, struct ship *ship, ...) { va_list ap; char format[BUFSIZ]; char buf[BUFSIZ]; if (!done_curses) return; va_start(ap, ship); if (*fmt == '\a') { beep(); fmt++; } fmtship(format, sizeof(format), fmt, ship); vsnprintf(buf, sizeof(buf), format, ap); va_end(ap); scrollarea_add(buf); } /*VARARGS2*/ void Msg(const char *fmt, ...) { va_list ap; char buf[BUFSIZ]; if (!done_curses) return; va_start(ap, fmt); if (*fmt == '\a') { beep(); fmt++; } vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); scrollarea_add(buf); } static void prompt(const char *p, struct ship *ship) { static char buf[BUFSIZ]; fmtship(buf, sizeof(buf), p, ship); sc_prompt = buf; sc_buf = ""; sc_hasprompt = true; } static void endprompt(void) { sc_prompt = NULL; sc_buf = NULL; sc_hasprompt = false; } /* * Next two functions called from newturn() to poke display. Shouldn't * exist... XXX */ void display_hide_prompt(void) { sc_hideprompt = true; draw_scroll(); wrefresh(scroll_w); } void display_reshow_prompt(void) { sc_hideprompt = false; draw_scroll(); wrefresh(scroll_w); } int sgetch(const char *p, struct ship *ship, int flag) { int c; char input[2]; prompt(p, ship); input[0] = '\0'; input[1] = '\0'; sc_buf = input; blockalarm(); draw_scroll(); wrefresh(scroll_w); fflush(stdout); unblockalarm(); while ((c = wgetch(scroll_w)) == EOF) ; if (flag && c >= ' ' && c < 0x7f) { blockalarm(); input[0] = c; draw_scroll(); wrefresh(scroll_w); fflush(stdout); unblockalarm(); } endprompt(); return c; } void sgetstr(const char *pr, char *buf, int n) { int c; char *p = buf; prompt(pr, (struct ship *)0); sc_buf = buf; for (;;) { *p = 0; blockalarm(); draw_scroll(); wrefresh(scroll_w); fflush(stdout); unblockalarm(); while ((c = wgetch(scroll_w)) == EOF) ; switch (c) { case '\n': case '\r': endprompt(); return; case '\b': if (p > buf) { /*waddstr(scroll_w, "\b \b");*/ p--; } break; default: if (c >= ' ' && c < 0x7f && p < buf + n - 1) { *p++ = c; /*waddch(scroll_w, c);*/ } else beep(); } } } //////////////////////////////////////////////////////////// // drawing of other panes void display_force_full_redraw(void) { clear(); } void display_redraw(void) { draw_board(); draw_view(); draw_turn(); draw_stat(); draw_slot(); draw_scroll(); /* move the cursor */ wrefresh(scroll_w); /* paranoia */ fflush(stdout); } static void draw_view(void) { struct ship *sp; werase(view_w); foreachship(sp) { if (sp->file->dir && sp->file->row > viewrow && sp->file->row < viewrow + VIEW_Y && sp->file->col > viewcol && sp->file->col < viewcol + VIEW_X) { wmove(view_w, sp->file->row - viewrow, sp->file->col - viewcol); waddch(view_w, colours(sp)); wmove(view_w, sternrow(sp) - viewrow, sterncol(sp) - viewcol); waddch(view_w, sterncolour(sp)); } } wrefresh(view_w); } static void draw_turn(void) { wmove(turn_w, 0, 0); wprintw(turn_w, "%cTurn %d", dont_adjust?'*':'-', turn); wrefresh(turn_w); } static void draw_stat(void) { wmove(stat_w, STAT_1, 0); wprintw(stat_w, "Points %3d\n", mf->points); wprintw(stat_w, "Fouls %2d\n", fouled(ms)); wprintw(stat_w, "Grapples %2d\n", grappled(ms)); wmove(stat_w, STAT_2, 0); wprintw(stat_w, " 0 %c(%c)\n", maxmove(ms, winddir + 3, -1) + '0', maxmove(ms, winddir + 3, 1) + '0'); waddstr(stat_w, " \\|/\n"); wprintw(stat_w, " -^-%c(%c)\n", maxmove(ms, winddir + 2, -1) + '0', maxmove(ms, winddir + 2, 1) + '0'); waddstr(stat_w, " /|\\\n"); wprintw(stat_w, " | %c(%c)\n", maxmove(ms, winddir + 1, -1) + '0', maxmove(ms, winddir + 1, 1) + '0'); wprintw(stat_w, " %c(%c)\n", maxmove(ms, winddir, -1) + '0', maxmove(ms, winddir, 1) + '0'); wmove(stat_w, STAT_3, 0); wprintw(stat_w, "Load %c%c %c%c\n", loadname[mf->loadL], readyname(mf->readyL), loadname[mf->loadR], readyname(mf->readyR)); wprintw(stat_w, "Hull %2d\n", mc->hull); wprintw(stat_w, "Crew %2d %2d %2d\n", mc->crew1, mc->crew2, mc->crew3); wprintw(stat_w, "Guns %2d %2d\n", mc->gunL, mc->gunR); wprintw(stat_w, "Carr %2d %2d\n", mc->carL, mc->carR); wprintw(stat_w, "Rigg %d %d %d ", mc->rig1, mc->rig2, mc->rig3); if (mc->rig4 < 0) waddch(stat_w, '-'); else wprintw(stat_w, "%d", mc->rig4); wrefresh(stat_w); } void draw_slot(void) { int i; if (!boarding(ms, 0)) { mvwaddstr(slot_w, 0, 0, " "); mvwaddstr(slot_w, 1, 0, " "); } else { wmove(slot_w, 0, 0); for (i = 0; i < 3; i++) { waddch(slot_w, obp[i] ? '1'+i : ' '); } mvwaddstr(slot_w, 1, 0, "OBP"); } if (!boarding(ms, 1)) { mvwaddstr(slot_w, 2, 0, " "); mvwaddstr(slot_w, 3, 0, " "); } else { wmove(slot_w, 2, 0); for (i = 0; i < 3; i++) { waddch(slot_w, dbp[i] ? '1'+i : ' '); } mvwaddstr(slot_w, 3, 0, "DBP"); } wmove(slot_w, SLOT_Y-4, 0); if (mf->RH) wprintw(slot_w, "%dRH", mf->RH); else waddstr(slot_w, " "); wmove(slot_w, SLOT_Y-3, 0); if (mf->RG) wprintw(slot_w, "%dRG", mf->RG); else waddstr(slot_w, " "); wmove(slot_w, SLOT_Y-2, 0); if (mf->RR) wprintw(slot_w, "%dRR", mf->RR); else waddstr(slot_w, " "); #define Y (SLOT_Y/2) wmove(slot_w, 7, 1); wprintw(slot_w,"%d", windspeed); mvwaddch(slot_w, Y, 0, ' '); mvwaddch(slot_w, Y, 2, ' '); mvwaddch(slot_w, Y-1, 0, ' '); mvwaddch(slot_w, Y-1, 1, ' '); mvwaddch(slot_w, Y-1, 2, ' '); mvwaddch(slot_w, Y+1, 0, ' '); mvwaddch(slot_w, Y+1, 1, ' '); mvwaddch(slot_w, Y+1, 2, ' '); wmove(slot_w, Y - dr[winddir], 1 - dc[winddir]); switch (winddir) { case 1: case 5: waddch(slot_w, '|'); break; case 2: case 6: waddch(slot_w, '/'); break; case 3: case 7: waddch(slot_w, '-'); break; case 4: case 8: waddch(slot_w, '\\'); break; } mvwaddch(slot_w, Y + dr[winddir], 1 + dc[winddir], '+'); wrefresh(slot_w); } void draw_board(void) { int n; erase(); werase(view_w); werase(slot_w); werase(scroll_w); werase(stat_w); werase(turn_w); move(BOX_T, BOX_L); for (n = 0; n < BOX_X; n++) addch('-'); move(BOX_B, BOX_L); for (n = 0; n < BOX_X; n++) addch('-'); for (n = BOX_T+1; n < BOX_B; n++) { mvaddch(n, BOX_L, '|'); mvaddch(n, BOX_R, '|'); } mvaddch(BOX_T, BOX_L, '+'); mvaddch(BOX_T, BOX_R, '+'); mvaddch(BOX_B, BOX_L, '+'); mvaddch(BOX_B, BOX_R, '+'); refresh(); #if 0 #define WSaIM "Wooden Ships & Iron Men" wmove(view_w, 2, (VIEW_X - sizeof WSaIM - 1) / 2); waddstr(view_w, WSaIM); wmove(view_w, 4, (VIEW_X - strlen(cc->name)) / 2); waddstr(view_w, cc->name); wrefresh(view_w); #endif move(LINE_T, LINE_L); printw("Class %d %s (%d guns) '%s' (%c%c)", mc->class, classname[mc->class], mc->guns, ms->shipname, colours(ms), sterncolour(ms)); refresh(); } void display_set_obp(int which, bool show) { obp[which] = show; } void display_set_dbp(int which, bool show) { dbp[which] = show; } //////////////////////////////////////////////////////////// // external actions on the display void display_scroll_pageup(void) { unsigned total_lines, visible_lines, limit; unsigned pagesize = SCROLL_Y - 2; total_lines = stringarray_num(sc_lines); visible_lines = SCROLL_Y - 1; limit = total_lines - visible_lines; sc_scrollup += pagesize; if (sc_scrollup > limit) { sc_scrollup = limit; } } void display_scroll_pagedown(void) { unsigned pagesize = SCROLL_Y - 2; if (sc_scrollup < pagesize) { sc_scrollup = 0; } else { sc_scrollup -= pagesize; } } void centerview(void) { viewrow = mf->row - VIEW_Y / 2; viewcol = mf->col - VIEW_X / 2; } void upview(void) { viewrow -= VIEW_Y / 3; } void downview(void) { viewrow += VIEW_Y / 3; } void leftview(void) { viewcol -= VIEW_X / 5; } void rightview(void) { viewcol += VIEW_X / 5; } /* Called from newturn()... rename? */ void display_adjust_view(void) { if (dont_adjust) return; if (mf->row < viewrow + VIEW_Y/4) viewrow = mf->row - (VIEW_Y - VIEW_Y/4); else if (mf->row > viewrow + (VIEW_Y - VIEW_Y/4)) viewrow = mf->row - VIEW_Y/4; if (mf->col < viewcol + VIEW_X/8) viewcol = mf->col - (VIEW_X - VIEW_X/8); else if (mf->col > viewcol + (VIEW_X - VIEW_X/8)) viewcol = mf->col - VIEW_X/8; } //////////////////////////////////////////////////////////// // starting game static bool shipselected; static int loadpos; static int nextload(int load) { switch (load) { case L_ROUND: return L_GRAPE; case L_GRAPE: return L_CHAIN; case L_CHAIN: return L_DOUBLE; case L_DOUBLE: return L_ROUND; } return L_ROUND; } static int loadbychar(int ch) { switch (ch) { case 'r': return L_ROUND; case 'g': return L_GRAPE; case 'c': return L_CHAIN; case 'd': return L_DOUBLE; } return L_ROUND; } static const char * loadstr(int load) { switch (load) { case L_ROUND: return "round"; case L_GRAPE: return "grape"; case L_CHAIN: return "chain"; case L_DOUBLE: return "double"; } return "???"; } static void displayshiplist(void) { struct ship *sp; int which; erase(); attron(A_BOLD); mvaddstr(1, 4, cc->name); attroff(A_BOLD); which = 0; foreachship(sp) { mvselprintw(which + 3, 4, which, player, 60, " %2d: %-10s %-15s (%-2d pts) %s", sp->file->index, countryname[sp->nationality], sp->shipname, sp->specs->pts, saywhat(sp, 1)); which++; } if (!shipselected) { mvaddstr(15, 4, "Choose your ship"); move(player + 3, 63); } else { mvselprintw(15, 4, 0, loadpos, 32, "Initial left broadside: %s", loadstr(mf->loadL)); mvselprintw(16, 4, 1, loadpos, 32, "Initial right broadside: %s", loadstr(mf->loadR)); mvselprintw(17, 4, 2, loadpos, 32, "Set sail"); move(loadpos+15, 35); } wrefresh(stdscr); } static int pickship(void) { struct File *fp; struct ship *sp; bool done; int ch; for (;;) { foreachship(sp) if (sp->file->captain[0] == 0 && !sp->file->struck && sp->file->captured == 0) break; if (sp >= ls) { return -1; } player = sp - SHIP(0); if (randomize) { /* nothing */ } else { done = false; while (!done) { displayshiplist(); ch = getch(); switch (ch) { case 12 /*^L*/: clear(); break; case '\r': case '\n': done = true; break; case 7 /*^G*/: case 8 /*^H*/: case 27 /*ESC*/: case 127 /*^?*/: beep(); break; case 16 /*^P*/: case KEY_UP: up(&player, NULL); break; case 14 /*^N*/: case KEY_DOWN: down(&player, NULL, cc->vessels, cc->vessels); break; default: beep(); break; } } } if (player < 0) continue; if (Sync() < 0) leave(LEAVE_SYNC); fp = SHIP(player)->file; if (fp->captain[0] || fp->struck || fp->captured != 0) oops(16, 4, "That ship is taken."); else break; } return 0; } static void pickload(void) { bool done; int ch; mf->loadL = L_ROUND; mf->loadR = L_ROUND; loadpos = 0; done = false; while (!done) { displayshiplist(); ch = getch(); switch (ch) { case 12 /*^L*/: clear(); break; case 'r': case 'g': case 'c': case 'd': switch (loadpos) { case 0: mf->loadL = loadbychar(ch); break; case 1: mf->loadR = loadbychar(ch); break; case 2: beep(); break; } break; case '\r': case '\n': switch (loadpos) { case 0: mf->loadL = nextload(mf->loadL); break; case 1: mf->loadR = nextload(mf->loadR); break; case 2: done = true; break; } break; case 7 /*^G*/: case 8 /*^H*/: case 27 /*ESC*/: case 127 /*^?*/: beep(); break; case 16 /*^P*/: case KEY_UP: up(&loadpos, NULL); break; case 14 /*^N*/: case KEY_DOWN: down(&loadpos, NULL, 3, 3); break; default: beep(); break; } } mf->readyR = R_LOADED|R_INITIAL; mf->readyL = R_LOADED|R_INITIAL; } static void startgame(void) { ingame = true; shipselected = false; pl_main_init(); hasdriver = sync_exists(game); if (sync_open() < 0) { oops(21, 10, "syncfile: %s", strerror(errno)); pl_main_uninit(); ingame = false; return; } if (hasdriver) { mvaddstr(21, 10, "Synchronizing with the other players..."); wrefresh(stdscr); fflush(stdout); if (Sync() < 0) leave(LEAVE_SYNC); } else { mvaddstr(21, 10, "Starting driver..."); wrefresh(stdscr); fflush(stdout); startdriver(); } if (pickship() < 0) { oops(21, 10, "All ships taken in that scenario."); sync_close(0); people = 0; pl_main_uninit(); ingame = false; return; } shipselected = true; ms = SHIP(player); mf = ms->file; mc = ms->specs; pickload(); pl_main(); ingame = false; } //////////////////////////////////////////////////////////// // scenario picker static int pickerpos; static int pickerscroll; static const char * absdirectionname(int dir) { switch (dir) { case 1: return "South"; case 2: return "Southwest"; case 3: return "West"; case 4: return "Northwest"; case 5: return "North"; case 6: return "Northeast"; case 7: return "East"; case 8: return "Southeast"; } return "?"; } static const char * windname(int wind) { switch (wind) { case 0: return "calm"; case 1: return "light breeze"; case 2: return "moderate breeze"; case 3: return "fresh breeze"; case 4: return "strong breeze"; case 5: return "gale"; case 6: return "full gale"; case 7: return "hurricane"; } return "???"; } static const char * nationalityname(int nationality) { switch (nationality) { case N_A: return "a"; case N_B: return "b"; case N_S: return "s"; case N_F: return "f"; case N_J: return "j"; case N_D: return "d"; case N_K: return "k"; case N_O: return "o"; } return "?"; } static void drawpicker(void) { int y, sc, i; struct ship *ship; erase(); mvaddstr(0, 0, "## SHIPS TITLE"); for (y=1; y<LINES-11; y++) { sc = (y-1) + pickerscroll; if (sc < NSCENE) { mvselprintw(y, 0, sc, pickerpos, 56, "%-2d %-5d %s", sc, scene[sc].vessels, scene[sc].name); } } mvprintw(2, 60 + 2, "%s wind", absdirectionname(scene[pickerpos].winddir)); mvprintw(3, 60 + 2, "(%s)", windname(scene[pickerpos].windspeed)); for (i=0; i<scene[pickerpos].vessels; i++) { ship = &scene[pickerpos].ship[i]; mvprintw(LINES-10 + i, 0, "(%s) %-16s %3d gun %s (%s crew) (%d pts)", nationalityname(ship->nationality), ship->shipname, ship->specs->guns, shortclassname[ship->specs->class], qualname[ship->specs->qual], ship->specs->pts); } move(1 + pickerpos - pickerscroll, 55); wrefresh(stdscr); } static int pickscenario(int initpos) { int ch; pickerpos = initpos; if (pickerpos < 0) { pickerpos = 0; } while (1) { drawpicker(); ch = getch(); switch (ch) { case 12 /*^L*/: clear(); break; case '\r': case '\n': return pickerpos; case 7 /*^G*/: case 8 /*^H*/: case 27 /*ESC*/: case 127 /*^?*/: return initpos; case 16 /*^P*/: case KEY_UP: up(&pickerpos, &pickerscroll); break; case 14 /*^N*/: case KEY_DOWN: down(&pickerpos, &pickerscroll, NSCENE, LINES-12); break; default: beep(); break; } } return pickerpos; } //////////////////////////////////////////////////////////// // setup menus #define MAINITEMS_NUM 5 #define STARTITEMS_NUM 4 #define OPTIONSITEMS_NUM 5 static int mainpos; static bool connected; static bool joinactive; static int joinpos; static int joinscroll; static int joinable[NSCENE]; static int numjoinable; static bool startactive; static int startpos; static int startscenario; static bool optionsactive; static int optionspos; static char o_myname[MAXNAMESIZE]; static bool o_randomize; static bool o_longfmt; static bool o_nobells; /* * this and sgetstr() should share code */ static void startup_getstr(int y, int x, char *buf, size_t max) { size_t pos = 0; int ch; for (;;) { buf[pos] = 0; move(y, x); addstr(buf); clrtoeol(); wrefresh(stdscr); fflush(stdout); ch = getch(); switch (ch) { case '\n': case '\r': return; case '\b': if (pos > 0) { /*waddstr(scroll_w, "\b \b");*/ pos--; } break; default: if (ch >= ' ' && ch < 0x7f && pos < max - 1) { buf[pos++] = ch; } else { beep(); } } } } static void changename(void) { mvaddstr(LINES-2, COLS/2, "Enter your name:"); startup_getstr(LINES-1, COLS/2, o_myname, sizeof(o_myname)); } static void checkforgames(void) { int i; int prev; if (numjoinable > 0) { prev = joinable[joinpos]; } else { prev = 0; } numjoinable = 0; for (i = 0; i < NSCENE; i++) { if (!sync_exists(i)) { continue; } if (i < prev) { joinpos = numjoinable; } joinable[numjoinable++] = i; } if (joinpos > numjoinable) { joinpos = (numjoinable > 0) ? numjoinable - 1 : 0; } if (joinscroll > joinpos) { joinscroll = (joinpos > 0) ? joinpos - 1 : 0; } } static void drawstartmenus(void) { const int mainy0 = 8; const int mainx0 = 12; erase(); mvaddstr(5, 10, "Wooden Ships & Iron Men"); mvaddselstr(mainy0+0, mainx0, 0, mainpos, 17, "Join a game"); mvaddselstr(mainy0+1, mainx0, 1, mainpos, 17, "Start a game"); mvaddselstr(mainy0+2, mainx0, 2, mainpos, 17, "Options"); mvaddselstr(mainy0+3, mainx0, 3, mainpos, 17, "Show high scores"); mvaddselstr(mainy0+4, mainx0, 4, mainpos, 17, "Quit"); mvprintw(15, 10, "Captain %s", myname); if (connected) { mvaddstr(16, 10, "Connected via scratch files."); } else { mvaddstr(16, 10, "Not connected."); } if (joinactive) { int y0, leavey = 0, i, sc; mvaddstr(0, COLS/2, "## SHIPS TITLE"); y0 = 1; for (i = 0; i < numjoinable; i++) { if (i >= joinscroll && i < joinscroll + LINES-1) { move(y0 + i - joinscroll, COLS/2); if (i == joinpos) { attron(A_REVERSE); } sc = joinable[i]; printw("%-2d %-5d %s", sc, scene[sc].vessels, scene[sc].name); if (i == joinpos) { filltoeol(); attroff(A_REVERSE); leavey = y0 + i - joinscroll; } } } mvaddstr(19, 10, "(Esc to abort)"); if (numjoinable > 0) { mvaddstr(18, 10, "Choose a game to join."); move(leavey, COLS-1); } else { mvaddstr(2, COLS/2, "No games."); mvaddstr(18, 10, "Press return to refresh."); } } else if (startactive) { const char *name; mvaddstr(18, 10, "Start a new game"); mvaddstr(19, 10, "(Esc to abort)"); mvaddstr(2, COLS/2, "New game"); name = (startscenario < 0) ? "not selected" : scene[startscenario].name; mvselprintw(4, COLS/2, 0, startpos, COLS/2 - 1, "Scenario: %s", name); mvaddselstr(5, COLS/2, 1, startpos, COLS/2 - 1, "Visibility: local"); mvaddselstr(6, COLS/2, 2, startpos, COLS/2 - 1, "Password: <PASSWORD>"); mvaddselstr(7, COLS/2, 3, startpos, COLS/2 - 1, "Start game"); move(4+startpos, COLS - 2); } else if (optionsactive) { mvaddstr(18, 10, "Adjust options"); mvaddstr(19, 10, "(Esc to abort)"); mvaddstr(2, COLS/2, "Adjust options"); mvselprintw(4, COLS/2, 0, optionspos, COLS/2-1, "Your name: %s", o_myname); mvselprintw(5, COLS/2, 1, optionspos, COLS/2-1, "Auto-pick ships: %s", o_randomize ? "ON" : "off"); mvselprintw(6, COLS/2, 2, optionspos, COLS/2-1, "Usernames in scores: %s", o_longfmt ? "ON" : "off"); mvselprintw(7, COLS/2, 3, optionspos, COLS/2-1, "Beeping: %s", o_nobells ? "OFF" : "on"); mvselprintw(8, COLS/2, 4, optionspos, COLS/2-1, "Apply changes"); move(4+optionspos, COLS - 2); } else { move(mainy0 + mainpos, mainx0 + 16); } wrefresh(stdscr); fflush(stdout); } void startup(void) { int ch; connected = false; mainpos = 0; joinactive = false; joinpos = 0; joinscroll = 0; numjoinable = 0; startactive = false; startpos = 0; startscenario = -1; optionsactive = false; optionspos = 0; while (1) { if (joinactive) { checkforgames(); } drawstartmenus(); ch = getch(); switch (ch) { case 12 /*^L*/: clear(); break; case '\r': case '\n': if (joinactive && numjoinable > 0) { game = joinable[joinpos]; startgame(); joinactive = false; } else if (startactive) { switch (startpos) { case 0: startscenario = pickscenario(startscenario); startpos = 3; break; case 1: case 2: oops(21, 10, "That doesn't work yet."); break; case 3: if (startscenario >= 0) { game = startscenario; /* can't do this here yet */ /*startdriver();*/ startgame(); startactive = false; startscenario = -1; } else { oops(21, 10, "Pick a scenario."); } break; } } else if (optionsactive) { switch (optionspos) { case 0: changename(); break; case 1: o_randomize = !o_randomize; break; case 2: o_longfmt = !o_longfmt; break; case 3: o_nobells = !o_nobells; break; case 4: strlcpy(myname, o_myname, sizeof(myname)); randomize = o_randomize; longfmt = o_longfmt; nobells = o_nobells; optionsactive = false; break; } } else { switch (mainpos) { case 0: joinactive = true; break; case 1: startactive = true; break; case 2: strlcpy(o_myname, myname, sizeof(o_myname)); o_randomize = randomize; o_longfmt = longfmt; o_nobells = nobells; optionsactive = true; break; case 3: lo_curses(); break; case 4: return; } } break; case 7 /*^G*/: case 8 /*^H*/: case 27 /*ESC*/: case 127 /*^?*/: if (joinactive) { joinactive = false; } else if (startactive) { startactive = false; } else if (optionsactive) { optionsactive = false; } else { /* nothing */ } break; case 16 /*^P*/: case KEY_UP: if (joinactive) { up(&joinpos, &joinscroll); } else if (startactive) { up(&startpos, NULL); } else if (optionsactive) { up(&optionspos, NULL); } else { up(&mainpos, NULL); } break; case 14 /*^N*/: case KEY_DOWN: if (joinactive) { down(&joinpos, &joinscroll, numjoinable, LINES-1); } else if (startactive) { down(&startpos, NULL, STARTITEMS_NUM, STARTITEMS_NUM); } else if (optionsactive) { down(&optionspos, NULL, OPTIONSITEMS_NUM, OPTIONSITEMS_NUM); } else { down(&mainpos, NULL, MAINITEMS_NUM, MAINITEMS_NUM); } break; default: beep(); break; } } }
0.96875
high
ProcessLib/RichardsMechanics/RichardsMechanicsFEM.h
WanlongCai/ogs
0
5636593
/** * \file * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #pragma once #include <memory> #include <vector> #include "IntegrationPointData.h" #include "LocalAssemblerInterface.h" #include "MaterialLib/SolidModels/LinearElasticIsotropic.h" #include "MathLib/KelvinVector.h" #include "MathLib/LinAlg/Eigen/EigenMapTools.h" #include "NumLib/DOF/DOFTableUtil.h" #include "NumLib/Fem/InitShapeMatrices.h" #include "NumLib/Fem/ShapeMatrixPolicy.h" #include "ParameterLib/Parameter.h" #include "ProcessLib/Deformation/BMatrixPolicy.h" #include "ProcessLib/Deformation/LinearBMatrix.h" #include "ProcessLib/LocalAssemblerTraits.h" #include "RichardsMechanicsProcessData.h" namespace ProcessLib { namespace RichardsMechanics { namespace MPL = MaterialPropertyLib; /// Used for the extrapolation of the integration point values. It is ordered /// (and stored) by integration points. template <typename ShapeMatrixType> struct SecondaryData { std::vector<ShapeMatrixType, Eigen::aligned_allocator<ShapeMatrixType>> N_u; }; template <typename ShapeFunctionDisplacement, typename ShapeFunctionPressure, typename IntegrationMethod, int DisplacementDim> class RichardsMechanicsLocalAssembler : public LocalAssemblerInterface<DisplacementDim> { public: using ShapeMatricesTypeDisplacement = ShapeMatrixPolicyType<ShapeFunctionDisplacement, DisplacementDim>; using ShapeMatricesTypePressure = ShapeMatrixPolicyType<ShapeFunctionPressure, DisplacementDim>; using GlobalDimMatrixType = typename ShapeMatricesTypePressure::GlobalDimMatrixType; using BMatricesType = BMatrixPolicyType<ShapeFunctionDisplacement, DisplacementDim>; using KelvinVectorType = typename BMatricesType::KelvinVectorType; using IpData = IntegrationPointData<BMatricesType, ShapeMatricesTypeDisplacement, ShapeMatricesTypePressure, DisplacementDim, ShapeFunctionDisplacement::NPOINTS>; static int const KelvinVectorSize = MathLib::KelvinVector::KelvinVectorDimensions<DisplacementDim>::value; using Invariants = MathLib::KelvinVector::Invariants<KelvinVectorSize>; using SymmetricTensor = Eigen::Matrix<double, KelvinVectorSize, 1>; RichardsMechanicsLocalAssembler(RichardsMechanicsLocalAssembler const&) = delete; RichardsMechanicsLocalAssembler(RichardsMechanicsLocalAssembler&&) = delete; RichardsMechanicsLocalAssembler( MeshLib::Element const& e, std::size_t const /*local_matrix_size*/, bool const is_axially_symmetric, unsigned const integration_order, RichardsMechanicsProcessData<DisplacementDim>& process_data); /// \return the number of read integration points. std::size_t setIPDataInitialConditions( std::string const& name, double const* values, int const integration_order) override; void setInitialConditionsConcrete(std::vector<double> const& local_x, double const t, bool const use_monolithic_scheme, int const process_id) override; void assemble(double const t, double const dt, std::vector<double> const& local_x, std::vector<double> const& local_xdot, std::vector<double>& local_M_data, std::vector<double>& local_K_data, std::vector<double>& local_rhs_data) override; void assembleWithJacobian(double const t, double const dt, std::vector<double> const& local_x, std::vector<double> const& local_xdot, const double /*dxdot_dx*/, const double /*dx_dx*/, std::vector<double>& /*local_M_data*/, std::vector<double>& /*local_K_data*/, std::vector<double>& local_rhs_data, std::vector<double>& local_Jac_data) override; void assembleWithJacobianForStaggeredScheme( double const t, double const dt, Eigen::VectorXd const& local_x, Eigen::VectorXd const& local_xdot, const double dxdot_dx, const double dx_dx, int const process_id, std::vector<double>& local_M_data, std::vector<double>& local_K_data, std::vector<double>& local_b_data, std::vector<double>& local_Jac_data) override; void initializeConcrete() override { unsigned const n_integration_points = _integration_method.getNumberOfPoints(); for (unsigned ip = 0; ip < n_integration_points; ip++) { auto& ip_data = _ip_data[ip]; /// Set initial stress from parameter. if (_process_data.initial_stress != nullptr) { ParameterLib::SpatialPosition const x_position{ boost::none, _element.getID(), ip, MathLib::Point3d(NumLib::interpolateCoordinates< ShapeFunctionDisplacement, ShapeMatricesTypeDisplacement>( _element, ip_data.N_u))}; ip_data.sigma_eff = MathLib::KelvinVector::symmetricTensorToKelvinVector< DisplacementDim>((*_process_data.initial_stress)( std::numeric_limits< double>::quiet_NaN() /* time independent */, x_position)); } ip_data.pushBackState(); } } void postTimestepConcrete(std::vector<double> const& /*local_x*/, double const /*t*/, double const /*dt*/) override { unsigned const n_integration_points = _integration_method.getNumberOfPoints(); for (unsigned ip = 0; ip < n_integration_points; ip++) { _ip_data[ip].pushBackState(); } } void computeSecondaryVariableConcrete( double const t, double const dt, std::vector<double> const& local_x, std::vector<double> const& local_x_dot) override; void postNonLinearSolverConcrete(std::vector<double> const& local_x, std::vector<double> const& local_xdot, double const t, double const dt, bool const use_monolithic_scheme, int const process_id) override; Eigen::Map<const Eigen::RowVectorXd> getShapeMatrix( const unsigned integration_point) const override { auto const& N_u = _secondary_data.N_u[integration_point]; // assumes N is stored contiguously in memory return Eigen::Map<const Eigen::RowVectorXd>(N_u.data(), N_u.size()); } std::vector<double> getSigma() const override; std::vector<double> const& getIntPtDarcyVelocity( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getSaturation() const override; std::vector<double> const& getIntPtSaturation( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getPorosity() const override; std::vector<double> const& getIntPtPorosity( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getTransportPorosity() const override; std::vector<double> const& getIntPtTransportPorosity( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> const& getIntPtSigma( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getSwellingStress() const override; std::vector<double> const& getIntPtSwellingStress( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getEpsilon() const override; std::vector<double> const& getIntPtEpsilon( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> const& getIntPtDryDensitySolid( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; private: /** * Assemble local matrices and vectors arise from the linearized discretized * weak form of the residual of the momentum balance equation, * \f[ * \nabla (\sigma - \alpha_b p \mathrm{I}) = f * \f] * where \f$ \sigma\f$ is the effective stress tensor, \f$p\f$ is the pore * pressure, \f$\alpha_b\f$ is the Biot constant, \f$\mathrm{I}\f$ is the * identity tensor, and \f$f\f$ is the body force. * * @param t Time * @param dt Time increment * @param local_x Nodal values of \f$x\f$ of an element. * @param local_xdot Nodal values of \f$\dot{x}\f$ of an element. * @param dxdot_dx Value of \f$\dot{x} \cdot dx\f$. * @param dx_dx Value of \f$ x \cdot dx\f$. * @param local_M_data Mass matrix of an element, which takes the form of * \f$ \int N^T N\mathrm{d}\Omega\f$. Not used. * @param local_K_data Laplacian matrix of an element, which takes the * form of \f$ \int (\nabla N)^T K \nabla N\mathrm{d}\Omega\f$. * Not used. * @param local_b_data Right hand side vector of an element. * @param local_Jac_data Element Jacobian matrix for the Newton-Raphson * method. */ void assembleWithJacobianForDeformationEquations( double const t, double const dt, Eigen::VectorXd const& local_x, Eigen::VectorXd const& local_xdot, const double dxdot_dx, const double dx_dx, std::vector<double>& local_M_data, std::vector<double>& local_K_data, std::vector<double>& local_b_data, std::vector<double>& local_Jac_data); /** * Assemble local matrices and vectors arise from the linearized discretized * weak form of the residual of the mass balance equation of single phase * flow, * \f[ * \alpha \cdot{p} - \nabla (K (\nabla p + \rho g \nabla z) + * \alpha_b \nabla \cdot \dot{u} = Q * \f] * where \f$ alpha\f$ is a coefficient may depend on storage or the fluid * density change, \f$ \rho\f$ is the fluid density, \f$g\f$ is the * gravitational acceleration, \f$z\f$ is the vertical coordinate, \f$u\f$ * is the displacement, and \f$Q\f$ is the source/sink term. * * @param t Time * @param dt Time increment * @param local_x Nodal values of \f$x\f$ of an element. * @param local_xdot Nodal values of \f$\dot{x}\f$ of an element. * @param dxdot_dx Value of \f$\dot{x} \cdot dx\f$. * @param dx_dx Value of \f$ x \cdot dx\f$. * @param local_M_data Mass matrix of an element, which takes the form of * \f$ \int N^T N\mathrm{d}\Omega\f$. Not used. * @param local_K_data Laplacian matrix of an element, which takes the * form of \f$ \int (\nabla N)^T K \nabla N\mathrm{d}\Omega\f$. * Not used. * @param local_b_data Right hand side vector of an element. * @param local_Jac_data Element Jacobian matrix for the Newton-Raphson * method. */ void assembleWithJacobianForPressureEquations( double const t, double const dt, Eigen::VectorXd const& local_x, Eigen::VectorXd const& local_xdot, const double dxdot_dx, const double dx_dx, std::vector<double>& local_M_data, std::vector<double>& local_K_data, std::vector<double>& local_b_data, std::vector<double>& local_Jac_data); unsigned getNumberOfIntegrationPoints() const override; typename MaterialLib::Solids::MechanicsBase< DisplacementDim>::MaterialStateVariables const& getMaterialStateVariablesAt(unsigned integration_point) const override; private: RichardsMechanicsProcessData<DisplacementDim>& _process_data; std::vector<IpData, Eigen::aligned_allocator<IpData>> _ip_data; IntegrationMethod _integration_method; MeshLib::Element const& _element; bool const _is_axially_symmetric; SecondaryData< typename ShapeMatricesTypeDisplacement::ShapeMatrices::ShapeType> _secondary_data; static const int pressure_index = 0; static const int pressure_size = ShapeFunctionPressure::NPOINTS; static const int displacement_index = ShapeFunctionPressure::NPOINTS; static const int displacement_size = ShapeFunctionDisplacement::NPOINTS * DisplacementDim; }; } // namespace RichardsMechanics } // namespace ProcessLib #include "RichardsMechanicsFEM-impl.h"
1
high
xspec/XSFit/FitMethod/Minuit/minuit2/inc/Minuit2/ABSum.h
DougBurke/xspeclmodels
0
5669361
// @(#)root/minuit2:$Id$ // Authors: <NAME>, <NAME>, <NAME>, <NAME> 2003-2005 /********************************************************************** * * * Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT * * * **********************************************************************/ #ifndef ROOT_Minuit2_ABSum #define ROOT_Minuit2_ABSum #include "Minuit2/ABObj.h" namespace ROOT { namespace Minuit2 { template<class M1, class M2> class ABSum { private: ABSum() : fA(M1()), fB(M2()) {} ABSum& operator=(const ABSum&) {return *this;} template<class MI1, class MI2> ABSum& operator=(const ABSum<MI1,MI2>&) {return *this;} public: ABSum(const M1& a, const M2& b): fA(a), fB(b) {} ~ABSum() {} ABSum(const ABSum& sum) : fA(sum.fA), fB(sum.fB) {} template<class MI1, class MI2> ABSum(const ABSum<MI1,MI2>& sum) : fA(M1(sum.A() )), fB(M2(sum.B() )) {} const M1& A() const {return fA;} const M2& B() const {return fB;} private: M1 fA; M2 fB; }; // ABObj + ABObj template<class atype, class A, class btype, class B, class T> inline ABObj<typename AlgebraicSumType<atype, btype>::Type, ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >,T> operator+(const ABObj<atype,A,T>& a, const ABObj<btype,B,T>& b) { return ABObj<typename AlgebraicSumType<atype,btype>::Type, ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >,T>(ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >(a, b)); } // ABObj - ABObj template<class atype, class A, class btype, class B, class T> inline ABObj<typename AlgebraicSumType<atype, btype>::Type, ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >,T> operator-(const ABObj<atype,A,T>& a, const ABObj<btype,B,T>& b) { return ABObj<typename AlgebraicSumType<atype,btype>::Type, ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >,T>(ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >(a, ABObj<btype,B,T>(b.Obj(), T(-1.)*b.f()))); } } // namespace Minuit2 } // namespace ROOT #endif // ROOT_Minuit2_ABSum
0.996094
high
d/azha/town/market1.c
Dbevan/SunderingShadows
13
5702129
// Inside Market Square, Azha // Thorn@ShadowGate // 4/8/95 // Town of Azha #include <std.h> #include "/d/azha/azha.h" #include "/d/tsarven/include/southern.h" inherit ROOM; void create() { room::create(); set_terrain(CITY); set_travel(PAVED_ROAD); set_light(2); set_indoors(0); set_short("%^BOLD%^%^MAGENTA%^Inside Market Square, %^ORANGE%^Azha"); set_long( query_short() + " %^RESET%^%^ORANGE%^All around you are people haggling, trading and just admiring some of the things in the colorful %^MAGENTA%^booths%^ORANGE%^ sprawed all around you. Merchants are shouting to you and whoever else will listen, about thequality or the exquisiteness of their particular works. Its amiracle that you can hear yourself think in this strange place. The market wall prevents movement out of the market.\n" ); set_exits(([ "north" : "/d/azha/town/market4", "east" : "/d/azha/town/market2", "northeast" : "/d/azha/town/market5", ])); set_smell("default", "The smells here are so strong and varied that they overwhelm you."); set_items(([ "booths" : "The booths are of many shapes: tents, wooden stalls, or sometimes just piles of goods, marked by a sign.\n", ])); } reset() { ::reset(); AOVER->setup_monsters(TO, "street"); }
0.6875
medium
uvm_tb/csrc/rmar.h
veereshk619/spi_check
2
5734897
<filename>uvm_tb/csrc/rmar.h #ifndef _RMAR1_H_ #define _RMAR1_H_ #ifdef __cplusplus extern "C" { #endif #ifndef __DO_RMAHDR_ #include "rmar0.h" #endif /*__DO_RMAHDR_*/ extern UP rmaFunctionRtlArray[]; #ifdef __cplusplus } #endif #endif
0.882813
low
tdutils/td/utils/HazardPointers.h
beastzx18/td
1
5767665
// // Copyright <NAME> (<EMAIL>), <NAME> (<EMAIL>) 2014-2022 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include "td/utils/common.h" #include <array> #include <atomic> #include <memory> namespace td { template <class T, int MaxPointersN = 1, class Deleter = std::default_delete<T>> class HazardPointers { public: explicit HazardPointers(size_t threads_n) : threads_(threads_n) { for (auto &data : threads_) { for (auto &ptr : data.hazard_) { // workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64658 #if TD_GCC && GCC_VERSION <= 40902 ptr = nullptr; #else std::atomic_init(&ptr, static_cast<T *>(nullptr)); #endif } } } HazardPointers(const HazardPointers &other) = delete; HazardPointers &operator=(const HazardPointers &other) = delete; HazardPointers(HazardPointers &&other) = delete; HazardPointers &operator=(HazardPointers &&other) = delete; class Holder { public: template <class S> S *protect(std::atomic<S *> &to_protect) { return do_protect(hazard_ptr_, to_protect); } Holder(HazardPointers &hp, size_t thread_id, size_t pos) : Holder(hp.get_hazard_ptr(thread_id, pos)) { CHECK(hazard_ptr_.load() == 0); hazard_ptr_.store(reinterpret_cast<T *>(1)); } Holder(const Holder &other) = delete; Holder &operator=(const Holder &other) = delete; Holder(Holder &&other) = delete; Holder &operator=(Holder &&other) = delete; ~Holder() { clear(); } void clear() { hazard_ptr_.store(nullptr, std::memory_order_release); } private: friend class HazardPointers; explicit Holder(std::atomic<T *> &ptr) : hazard_ptr_(ptr) { } std::atomic<T *> &hazard_ptr_; }; void retire(size_t thread_id, T *ptr = nullptr) { CHECK(thread_id < threads_.size()); auto &data = threads_[thread_id]; if (ptr) { data.to_delete_.push_back(std::unique_ptr<T, Deleter>(ptr)); } for (auto it = data.to_delete_.begin(); it != data.to_delete_.end();) { if (!is_protected(it->get())) { it->reset(); it = data.to_delete_.erase(it); } else { ++it; } } } // old inteface T *protect(size_t thread_id, size_t pos, std::atomic<T *> &ptr) { return do_protect(get_hazard_ptr(thread_id, pos), ptr); } void clear(size_t thread_id, size_t pos) { do_clear(get_hazard_ptr(thread_id, pos)); } size_t to_delete_size_unsafe() const { size_t res = 0; for (auto &thread : threads_) { res += thread.to_delete_.size(); } return res; } private: struct ThreadData { std::array<std::atomic<T *>, MaxPointersN> hazard_; char pad[TD_CONCURRENCY_PAD - sizeof(std::array<std::atomic<T *>, MaxPointersN>)]; // stupid gc std::vector<std::unique_ptr<T, Deleter>> to_delete_; char pad2[TD_CONCURRENCY_PAD - sizeof(std::vector<std::unique_ptr<T, Deleter>>)]; }; std::vector<ThreadData> threads_; char pad2[TD_CONCURRENCY_PAD - sizeof(std::vector<ThreadData>)]; template <class S> static S *do_protect(std::atomic<T *> &hazard_ptr, std::atomic<S *> &to_protect) { T *saved = nullptr; T *to_save; while ((to_save = to_protect.load()) != saved) { hazard_ptr.store(to_save); saved = to_save; } return static_cast<S *>(saved); } static void do_clear(std::atomic<T *> &hazard_ptr) { hazard_ptr.store(nullptr, std::memory_order_release); } bool is_protected(T *ptr) { for (auto &thread : threads_) { for (auto &hazard_ptr : thread.hazard_) { if (hazard_ptr.load() == ptr) { return true; } } } return false; } std::atomic<T *> &get_hazard_ptr(size_t thread_id, size_t pos) { CHECK(thread_id < threads_.size()); return threads_[thread_id].hazard_[pos]; } }; } // namespace td
1
high
oros/sfifos/tests/test_blocks/BlockS.c
manub686/atomix
3
7333809
<reponame>manub686/atomix /** Atomix project, ./test_blocks/BlockS.c, TODO: insert summary here Copyright (c) 2015 Stanford University Released under the Apache License v2.0. See the LICENSE file for details. Author(s): <NAME> */ #include <c6x.h> #include <osl/inc/swpform.h> #include <ti/csl/csl_tsc.h> #include <oros/sfifos/fifoFactory.h> #include <oros/sfifos/fifoManager.h> #include "BlockS.h" #include "BlockS_internal.h" void BlockS_setup( BlockS *bli, FIFO_Handle ff_inp, //input fifo from which to split out FIFO_Handle ff_out1, //output fifo 1 into which the input is being split FIFO_Handle ff_out2 //output fifo 2 into which the input is being split ) { bli->ff_inp = ff_inp; bli->ff_out1 = ff_out1; bli->ff_out2 = ff_out2; } void BlockS_do ( BlockS *bli //Uint32 *log_sumX, //log //Uint32 log_nextIdx ) { FIFO_BufferHandle bhi1, bhi2, bho1, bho2; bhi1 = FIFO_getNextReadBuffer(bli->ff_inp); bhi2 = FIFO_getNextReadBuffer(bli->ff_inp); bho1 = FIFO_getNextWriteBuffer(bli->ff_out1); bho2 = FIFO_getNextWriteBuffer(bli->ff_out2); BlockS_do_internal( bhi1->mem, bhi2->mem, bho1->mem, bho2->mem, bhi1->lengthInBytes //log_sumX, log_nextIdx ); FIFO_readDone(bli->ff_inp, bhi1); FIFO_readDone(bli->ff_inp, bhi2); FIFO_writeDone(bli->ff_out1, bho1); FIFO_writeDone(bli->ff_out2, bho2); printf("S: Split buffer seq no. %2d and %2d\n", bhi1->seqNo, bhi2->seqNo); }
0.914063
high
include/Audio/AudioPlayer.h
Sytten/ARMUS
1
7366577
/* ============================================================================ Name : AudioPlayer Author : <NAME> Modified on: 2015-11-29 Description : Wrapper on the libarmus API calls ============================================================================ */ #ifndef AUDIOPLAYER_H_ #define AUDIOPLAYER_H_ #include <libarmus.h> #include "Audio/Notes.h" /** * Using the sent parameter, plays the good audio file * @param notes Value that will select the good audio file, recommended to be used with Audio/Notes.h defines * @return The audio playfile system stream ID */ unsigned int PlayNote(int notes); /** * Stops the stream at the parameters ID * @param ID Stream ID to stop */ void StopNote(unsigned int ID); #endif /*CHOOSINGNTOES_H_*/
0.722656
high
RecoTracker/CkfPattern/plugins/TrajectoryLessByFoundHits.h
ckamtsikis/cmssw
852
7399345
<gh_stars>100-1000 #ifndef TrajectoryLessByFoundHits_h_ #define TrajectoryLessByFoundHits_h_ #include "TrackingTools/PatternTools/interface/Trajectory.h" #include <TrackingTools/PatternTools/interface/TempTrajectory.h> inline bool lessByFoundHits(const Trajectory& a, const Trajectory& b) { return a.foundHits() < b.foundHits(); } inline bool lessByFoundHits(const TempTrajectory& a, const TempTrajectory& b) { return a.foundHits() < b.foundHits(); } struct TrajectoryLessByFoundHits { bool operator()(const Trajectory& a, const Trajectory& b) const { return a.foundHits() < b.foundHits(); } bool operator()(const TempTrajectory& a, const TempTrajectory& b) const { return a.foundHits() < b.foundHits(); } }; #endif
0.914063
high
lib/wizards/walla/peepseye/monsters/guard2.c
vlehtola/questmud
0
1032113
inherit "obj/monster"; reset(arg) { object money; object armour,weapon; ::reset(arg); if(arg) { return; } call_other(this_object(), "set_level", 30); call_other(this_object(), "set_name", "guard"); call_other(this_object(), "set_alias", "vorticon"); call_other(this_object(), "set_short", "A Vorticon guard"); call_other(this_object(), "set_long", "The guard looks like a sort of bear that stands on \n" + "its back feet. It doesn't seem to be wearing any clothes but it still \n" + "has somekind of natural armour on itself. The animal stands \n" + "about 7 feet tall towards you and makes strange noises.\n"); call_other(this_object(), "set_al", -10); call_other(this_object(), "set_aggressive", 0); set_block_dir("portal"); }
0.710938
medium
connectivity/drivers/emac/TARGET_RENESAS_EMAC/TARGET_RZ_A2XX/r_ether_rza2/src/targets/TARGET_GR_MANGO/r_ether_rza2_config.h
mcheah-bose/mbed-os
3,897
1064881
<reponame>mcheah-bose/mbed-os /*********************************************************************************************************************** * DISCLAIMER * This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No * other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all * applicable laws, including copyright laws. * THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING * THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM * EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES * SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS * SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of * this software. By using this software, you agree to the additional terms and conditions found by accessing the * following link: * http://www.renesas.com/disclaimer * * Copyright (C) 2018-2020 Renesas Electronics Corporation. All rights reserved. ***********************************************************************************************************************/ /* Copyright (c) 2018-2020 Renesas Electronics Corporation. * SPDX-License-Identifier: Apache-2.0 * * 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 Name : r_ether_rza2_config.h * Version : 1.00 * Description : Ethernet module device driver ***********************************************************************************************************************/ /* Guards against multiple inclusion */ #ifndef R_ETHER_RZA2_CONFIG_H #define R_ETHER_RZA2_CONFIG_H #ifdef __cplusplus extern "C" { #endif /*********************************************************************************************************************** Macro definitions ***********************************************************************************************************************/ /* Ethernet channel select. 0 = disable 1 = enable If only one of them is enabled, the API argument "channel" value is not referenced. */ #define ETHER_CH0_EN (0) #define ETHER_CH1_EN (1) /* Ethernet interface select. 0 = MII (Media Independent Interface) 1 = RMII (Reduced Media Independent Interface) */ #define ETHER_CFG_MODE_SEL (0) /* PHY-LSI address setting for ETHER0/1. */ #define ETHER_CFG_CH0_PHY_ADDRESS (0) /* Please define the PHY-LSI address in the range of 0-31. */ #define ETHER_CFG_CH1_PHY_ADDRESS (0) /* Please define the PHY-LSI address in the range of 0-31. */ /* The number of Rx descriptors. */ #define ETHER_CFG_EMAC_RX_DESCRIPTORS (8) /* The number of Tx descriptors. */ #define ETHER_CFG_EMAC_TX_DESCRIPTORS (8) /* Please define the size of the sending and receiving buffer in the value where one frame can surely be stored because the driver is single-frame/single-buffer processing. */ #define ETHER_CFG_BUFSIZE (1536) /* Must be 32-byte aligned */ /* Define the access timing of MII/RMII register */ #define ETHER_CFG_PHY_MII_WAIT (8) /* Plese define the value of 1 or more */ /* Define the waiting time for reset completion of PHY-LSI */ #define ETHER_CFG_PHY_DELAY_RESET (0x00020000L) /** * Link status read from LMON bit of ETHERC PSR register. The state is hardware dependent. */ #define ETHER_CFG_LINK_PRESENT (0) /* Use LINKSTA signal for detect link status changes 0 = unused (use PHY-LSI status register) 1 = use (use LINKSTA signal) */ #define ETHER_CFG_USE_LINKSTA (0) /* This setting is reflected in all channels */ /* Definition of whether or not to use KSZ8041NL of the Micrel Inc. 0 = unused 1 = use */ #define ETHER_CFG_USE_PHY_KSZ8041NL (0) /*********************************************************************************************************************** Typedef definitions ***********************************************************************************************************************/ /*********************************************************************************************************************** Exported global variables ***********************************************************************************************************************/ /*********************************************************************************************************************** Exported global functions (to be accessed by other files) ***********************************************************************************************************************/ #ifdef __cplusplus } #endif #endif /* R_ETHER_RZA2_CONFIG_H */
0.992188
high
cl_dll/subtitles.h
BlueNightHawk/halflife-updated
1
7230897
<reponame>BlueNightHawk/halflife-updated<gh_stars>1-10 #ifndef SUBTITLES_H #define SUBTITLES_H #include "SDL2\SDL.h" #include "SDL2\SDL_opengl.h" #include "..\imgui\imgui.h" #include "..\imgui\imgui_impl_sdl.h" #include <vector> #include "nl_defs.h" struct SubtitleOutput { float delay; float duration; int ignoreLongDistances; Vector color; Vector pos; std::string text; float alpha; }; struct SubtitleColor { float r; float g; float b; }; struct Subtitle { float delay; float duration; std::string colorKey; std::string text; }; void Subtitles_Init(); void Subtitles_ParseSubtitles( const std::string &filePath, const std::string &language ); void Subtitles_Draw(); bool Subtitle_IsFarAwayFromPlayer( const SubtitleOutput &subtitle ); void Subtitles_Push( const std::string &key, int ignoreLongDistances, const Vector &pos ); void Subtitles_Push( const std::string &key, const std::string &text, float duration, const Vector &color, const Vector &pos, float delay = 0.0f, int ignoreLongDistances = 0 ); int Subtitles_OnSound( const char *pszName, int iSize, void *pbuf ); int Subtitles_SubtClear( const char *pszName, int iSize, void *pbuf ); int Subtitles_SubtRemove( const char *pszName, int iSize, void *pbuf ); const std::vector<Subtitle> Subtitles_GetByKey( const std::string &key ); const SubtitleColor Subtitles_GetSubtitleColorByKey( const std::string &key ); #endif // SUBTITLES_H
0.988281
high
include/dsn/cpp/function_traits.h
chen-hwera/rDSN
953
7263665
<reponame>chen-hwera/rDSN /* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * Function traits to help extract the type of various callbacks * * Revision history: * 2016-01-15, <NAME>, first version */ #pragma once #include <type_traits> namespace dsn { template <typename T> struct function_traits : public function_traits<decltype(&T::operator())> {}; template <typename ReturnType, typename... Args> struct function_traits<ReturnType(Args...)> { using return_t = ReturnType; static constexpr size_t const arity = sizeof...(Args); template <size_t i> using arg_t = typename std::tuple_element<i, std::tuple<Args...>>::type; }; template <typename ReturnType, typename... Args> struct function_traits<ReturnType(*)(Args...)> : public function_traits<ReturnType(Args...)> {}; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...)> : public function_traits<ReturnType(Args...)> { typedef ClassType& owner_type; }; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...) const> : public function_traits<ReturnType(Args...)> { typedef const ClassType& owner_type; }; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...) volatile> : public function_traits<ReturnType(Args...)> { typedef volatile ClassType& owner_type; }; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...) const volatile> : public function_traits<ReturnType(Args...)> { typedef const volatile ClassType& owner_type; }; template <typename FunctionType> struct function_traits<std::function<FunctionType>> : public function_traits<FunctionType> {}; template <typename T> struct function_traits<T&> : public function_traits<T> {}; template <typename T> struct function_traits<const T&> : public function_traits<T> {}; template <typename T> struct function_traits<volatile T&> : public function_traits<T> {}; template <typename T> struct function_traits<const volatile T&> : public function_traits<T> {}; template <typename T> struct function_traits<T&&> : public function_traits<T> {}; template <typename T> struct function_traits<const T&&> : public function_traits<T> {}; template <typename T> struct function_traits<volatile T&&> : public function_traits<T> {}; template <typename T> struct function_traits<const volatile T&&> : public function_traits<T> {}; }
0.992188
high
UWP/RadialDevice/winrt/Windows.Devices.Pwm.Provider.h
megayuchi/RadialController
23
7296433
<gh_stars>10-100 // C++ for the Windows Runtime v1.0.161012.5 // Copyright (c) 2016 Microsoft Corporation. All rights reserved. #pragma once #include "internal/Windows.Foundation.Collections.3.h" #include "internal/Windows.Devices.Pwm.Provider.3.h" #include "Windows.Devices.Pwm.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::Devices::Pwm::Provider::IPwmControllerProvider> : produce_base<D, Windows::Devices::Pwm::Provider::IPwmControllerProvider> { HRESULT __stdcall get_PinCount(int32_t * value) noexcept override { try { *value = detach(this->shim().PinCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ActualFrequency(double * value) noexcept override { try { *value = detach(this->shim().ActualFrequency()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetDesiredFrequency(double frequency, double * value) noexcept override { try { *value = detach(this->shim().SetDesiredFrequency(frequency)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MaxFrequency(double * value) noexcept override { try { *value = detach(this->shim().MaxFrequency()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MinFrequency(double * value) noexcept override { try { *value = detach(this->shim().MinFrequency()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_AcquirePin(int32_t pin) noexcept override { try { this->shim().AcquirePin(pin); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_ReleasePin(int32_t pin) noexcept override { try { this->shim().ReleasePin(pin); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_EnablePin(int32_t pin) noexcept override { try { this->shim().EnablePin(pin); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_DisablePin(int32_t pin) noexcept override { try { this->shim().DisablePin(pin); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetPulseParameters(int32_t pin, double dutyCycle, bool invertPolarity) noexcept override { try { this->shim().SetPulseParameters(pin, dutyCycle, invertPolarity); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Pwm::Provider::IPwmProvider> : produce_base<D, Windows::Devices::Pwm::Provider::IPwmProvider> { HRESULT __stdcall abi_GetControllers(abi_arg_out<Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::Provider::IPwmControllerProvider>> result) noexcept override { try { *result = detach(this->shim().GetControllers()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; } namespace Windows::Devices::Pwm::Provider { template <typename D> int32_t impl_IPwmControllerProvider<D>::PinCount() const { int32_t value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->get_PinCount(&value)); return value; } template <typename D> double impl_IPwmControllerProvider<D>::ActualFrequency() const { double value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->get_ActualFrequency(&value)); return value; } template <typename D> double impl_IPwmControllerProvider<D>::SetDesiredFrequency(double frequency) const { double value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_SetDesiredFrequency(frequency, &value)); return value; } template <typename D> double impl_IPwmControllerProvider<D>::MaxFrequency() const { double value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->get_MaxFrequency(&value)); return value; } template <typename D> double impl_IPwmControllerProvider<D>::MinFrequency() const { double value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->get_MinFrequency(&value)); return value; } template <typename D> void impl_IPwmControllerProvider<D>::AcquirePin(int32_t pin) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_AcquirePin(pin)); } template <typename D> void impl_IPwmControllerProvider<D>::ReleasePin(int32_t pin) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_ReleasePin(pin)); } template <typename D> void impl_IPwmControllerProvider<D>::EnablePin(int32_t pin) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_EnablePin(pin)); } template <typename D> void impl_IPwmControllerProvider<D>::DisablePin(int32_t pin) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_DisablePin(pin)); } template <typename D> void impl_IPwmControllerProvider<D>::SetPulseParameters(int32_t pin, double dutyCycle, bool invertPolarity) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_SetPulseParameters(pin, dutyCycle, invertPolarity)); } template <typename D> Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::Provider::IPwmControllerProvider> impl_IPwmProvider<D>::GetControllers() const { Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::Provider::IPwmControllerProvider> result; check_hresult(static_cast<const IPwmProvider &>(static_cast<const D &>(*this))->abi_GetControllers(put(result))); return result; } } }
0.996094
high
algorithms/easy/1480. Running Sum of 1d Array.h
MultivacX/letcode2020
0
7329201
<gh_stars>0 // 1480. Running Sum of 1d Array // https://leetcode.com/problems/running-sum-of-1d-array/ // Runtime: 4 ms, faster than 83.95% of C++ online submissions for Running Sum of 1d Array. // Memory Usage: 8.7 MB, less than 99.71% of C++ online submissions for Running Sum of 1d Array. class Solution { public: vector<int> runningSum(vector<int>& nums) { for (int i = 1; i < nums.size(); ++i) nums[i] += nums[i - 1]; return nums; } };
0.945313
high
SQMagnet/SQMagnet/Main/SQNavigationController.h
13701777868/iOS-Extension-Objective-C
264
1095345
// // SQNavigationController.h // SQMagnet // // Created by 朱双泉 on 2019/7/12. // Copyright © 2019 Castie!. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface SQNavigationController : UINavigationController @end NS_ASSUME_NONNULL_END
0.613281
high
src/utils.c
dlobashevsky/hugefile
0
1128113
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <sched.h> #include <errno.h> #include <time.h> #include <sys/time.h> #include <sys/stat.h> #include "common.h" #include "utils.h" #define HIRES_TIME_STACK_LEVEL 128 uint64_t utils_getclock(void) { struct timeval t; gettimeofday(&t,0); return t.tv_sec*1000ULL+(t.tv_usec+500ULL)/1000ULL; } typedef struct string_list_t { char* key; char* val; struct string_list_t* next; } string_list_t; utils_line_t* utils_line_parse(char* buf) { if(!buf) return 0; if(!*buf || *buf=='\t' || *buf=='\n' || *buf=='\r') return 0; char* p=strchr(buf,'\n'); if(p) *p=0; p=strchr(buf,'\r'); if(p) *p=0; // right trim input line ssize_t z=strlen(buf); while(--z && buf[z]=='\t') buf[z]=0; utils_line_t* rv=calloc(1,sizeof(*rv)); rv->name=buf; rv->source=buf; p=strchr(buf,'\t'); if(!p) return rv; *p++=0; string_list_t* l=0; char* pair=0; while(pair=strsep(&p,"\t\n\r")) if(*pair) { if(*pair==':') { rv->source= ++pair; continue; } char* div=strchr(pair,':'); if(!div) continue; *div++=0; rv->metas++; string_list_t* new=malloc(sizeof(*new)); new->next=l; new->key=pair; new->val=div; l=new; } rv->keys=malloc(rv->metas*2*sizeof(rv->keys[0])); rv->vals=rv->keys+rv->metas; size_t i=0; while(l) { rv->keys[i]=l->key; rv->vals[i++]=l->val; string_list_t* next=l->next; free(l); l=next; } return rv; } void utils_line_free(utils_line_t* s) { if(!s) return; free(s->keys); free(s); } int utils_mkpath(char* file_path, mode_t mode) { if(!file_path || !*file_path) return -1; char* p; for (p=strchr(file_path+1, '/'); p; p=strchr(p+1, '/')) { *p='\0'; if (mkdir(file_path, mode)==-1) { if (errno!=EEXIST) { *p='/'; return -1; } } *p='/'; } return 0; } static const uint8_t hex_tbl[16]= { '0','1','2','3','4','5','6','7', '8','9','a','b','c','d','e','f' }; int utils_bin2hex(char* res,const uint8_t* src,size_t sz) { if(!res || !src) return 0; *res=0; if(!sz) return 0; while(sz--) { *res++=hex_tbl[(*src&0xf0)>>4]; *res++=hex_tbl[*src&0xf]; src++; } *res=0; return 0; } size_t utils_getCPUs(void) { size_t rv=0; cpu_set_t np; sched_getaffinity(0,sizeof(np),&np); for(size_t i=0;i<sizeof(np);i++) rv+=!!(CPU_ISSET(i,&np)); return rv; } uintmax_t utils_time_cpu(void) { struct timespec tm; clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&tm); return tm.tv_sec*1000000ULL+(tm.tv_nsec+500ULL)/1000ULL; } uintmax_t utils_time_cpu_res(void) { struct timespec tm; clock_getres(CLOCK_PROCESS_CPUTIME_ID,&tm); if(tm.tv_sec) abort(); return tm.tv_nsec; } static __thread struct { ssize_t depth; uintmax_t data[HIRES_TIME_STACK_LEVEL]; } hirestime={depth:-1}; uintmax_t utils_time_abs(void) { struct timeval t; gettimeofday(&t,0); return t.tv_sec*1000ULL+(t.tv_usec+500ULL)/1000ULL; } void utils_time_push(void) { if(hirestime.depth+1>=HIRES_TIME_STACK_LEVEL) abort(); hirestime.data[++hirestime.depth]=utils_time_abs(); } uintmax_t utils_time_get(void) { return utils_time_abs()-hirestime.data[hirestime.depth]; } uintmax_t utils_time_pop(void) { return utils_time_abs()-hirestime.data[(hirestime.depth>=0)?hirestime.depth--:0]; } char* utils_time_format(uintmax_t time) { char *bf; if(time<60000) { asprintf(&bf,"%ju ms",time); return bf; } uintmax_t secs=time/1000U; uintmax_t mins=secs/60; uintmax_t hours=mins/60; uintmax_t days=hours/24; uintmax_t weeks=days/7; secs%=60; mins%=60; hours%=24; days%=7; if(weeks) { asprintf(&bf,"%ju weeks %ju days %02ju:%02ju:%02ju.%03ju",weeks,days,hours,mins,secs,time%1000); return bf; } if(days) { asprintf(&bf,"%ju days %02ju:%02ju:%02ju.%03ju",days,hours,mins,secs,time%1000); return bf; } asprintf(&bf,"%02ju:%02ju:%02ju.%03ju",hours,mins,secs,time%1000); return bf; }
0.996094
high
typeClassDefs/FSMState.h
mipalgu/gusimplewhiteboard
0
1160881
<reponame>mipalgu/gusimplewhiteboard #include "FSMState.hpp"
0.957031
low
Sample/ToDoViewController.h
delonchen2011/ViperC
0
1193649
<filename>Sample/ToDoViewController.h // // ToDoViewController.h // Sample // // Created by <NAME> on 26/04/2017. // Copyright © 2017 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "ToDoProtocols.h" #import "ToDoPresenter.h" NS_ASSUME_NONNULL_BEGIN @interface ToDoViewController : UIViewController<ToDoViewable, UITableViewDelegate, UITableViewDataSource> @property (nonatomic, nullable) ToDoPresenter *presenter; @property (weak, nonatomic) IBOutlet UITableView *tableView; @end NS_ASSUME_NONNULL_END
0.59375
medium
ccnx/forwarder/metis/messenger/metis_Messenger.c
parc-ccnx-archive/Metis
0
2626417
/* * Copyright (c) 2013-2015, Xerox Corporation (Xerox) and Palo Alto Research Center, Inc (PARC) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL XEROX OR PARC 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. * * ################################################################################ * # * # PATENT NOTICE * # * # This software is distributed under the BSD 2-clause License (see LICENSE * # file). This BSD License does not make any patent claims and as such, does * # not act as a patent grant. The purpose of this section is for each contributor * # to define their intentions with respect to intellectual property. * # * # Each contributor to this source code is encouraged to state their patent * # claims and licensing mechanisms for any contributions made. At the end of * # this section contributors may each make their own statements. Contributor's * # claims and grants only apply to the pieces (source code, programs, text, * # media, etc) that they have contributed directly to this software. * # * # There is no guarantee that this section is complete, up to date or accurate. It * # is up to the contributors to maintain their portion of this section and up to * # the user of the software to verify any claims herein. * # * # Do not remove this header notification. The contents of this section must be * # present in all distributions of the software. You may only modify your own * # intellectual property statements. Please provide contact information. * * - Palo Alto Research Center, Inc * This software distribution does not grant any rights to patents owned by Palo * Alto Research Center, Inc (PARC). Rights to these patents are available via * various mechanisms. As of January 2016 PARC has committed to FRAND licensing any * intellectual property used by its contributions to this software. You may * contact PARC at <EMAIL> for more information or visit http://www.ccnx.org */ /** * * The messenger is contructued with a reference to the forwarder's dispatcher so it can * schedule future events. When someone calls metisMessenger_Send(...), it will put the * message on a queue. If the queue was empty, it will scheudle itself to be run. * By running the queue in a future dispatcher slice, it guarantees that there will be * no re-entrant behavior between callers and message listeners. * * A recipient will receive a reference counted copy of the missive, so it must call * {@link metisMissive_Release} on it. * * @author <NAME>, Palo Alto Research Center (Xerox PARC) * @copyright (c) 2013-2015, Xerox Corporation (Xerox) and Palo Alto Research Center, Inc (PARC). All rights reserved. */ #include <config.h> #include <stdio.h> #include <LongBow/runtime.h> #include <parc/algol/parc_Memory.h> #include <parc/algol/parc_ArrayList.h> #include <parc/algol/parc_EventScheduler.h> #include <parc/algol/parc_Event.h> #include <ccnx/forwarder/metis/messenger/metis_Messenger.h> #include <ccnx/forwarder/metis/messenger/metis_MissiveDeque.h> struct metis_messenger { PARCArrayList *callbacklist; MetisDispatcher *dispatcher; MetisMissiveDeque *eventQueue; PARCEventTimer *timerEvent; }; static void metisMessenger_Dequeue(int fd, PARCEventType which_event, void *messengerVoidPtr); // ========================================= // Public API MetisMessenger * metisMessenger_Create(MetisDispatcher *dispatcher) { MetisMessenger *messenger = parcMemory_AllocateAndClear(sizeof(MetisMessenger)); assertNotNull(messenger, "parcMemory_AllocateAndClear(%zu) returned NULL", sizeof(MetisMessenger)); // NULL destroyer because we're storing structures owned by the caller messenger->dispatcher = dispatcher; messenger->callbacklist = parcArrayList_Create(NULL); messenger->eventQueue = metisMissiveDeque_Create(); // creates the timer, but does not start it messenger->timerEvent = metisDispatcher_CreateTimer(dispatcher, false, metisMessenger_Dequeue, messenger); return messenger; } void metisMessenger_Destroy(MetisMessenger **messengerPtr) { assertNotNull(messengerPtr, "Parameter must be non-null double pointer"); assertNotNull(*messengerPtr, "Parameter must dereference to non-null pointer"); MetisMessenger *messenger = *messengerPtr; parcArrayList_Destroy(&messenger->callbacklist); metisMissiveDeque_Release(&messenger->eventQueue); metisDispatcher_DestroyTimerEvent(messenger->dispatcher, &messenger->timerEvent); parcMemory_Deallocate((void **) &messenger); *messengerPtr = NULL; } void metisMessenger_Send(MetisMessenger *messenger, MetisMissive *missive) { assertNotNull(messenger, "Parameter messenger must be non-null"); assertNotNull(missive, "Parameter event must be non-null"); metisMissiveDeque_Append(messenger->eventQueue, missive); if (metisMissiveDeque_Size(messenger->eventQueue) == 1) { // We need to scheudle ourself when an event is added to an empty queue // precondition: timer should not be running. struct timeval immediateTimeout = { 0, 0 }; metisDispatcher_StartTimer(messenger->dispatcher, messenger->timerEvent, &immediateTimeout); } } static void removeRecipient(MetisMessenger *messenger, const MetisMessengerRecipient *recipient) { // don't increment i in the loop for (size_t i = 0; i < parcArrayList_Size(messenger->callbacklist); ) { const void *p = parcArrayList_Get(messenger->callbacklist, i); if (p == recipient) { // removing will compact the list, so next element will also be at i. parcArrayList_RemoveAndDestroyAtIndex(messenger->callbacklist, i); } else { i++; } } } /** * @function metisEventMessenger_Register * @abstract Receive all event messages * @discussion * <#Discussion#> * * @param <#param1#> * @return <#return#> */ void metisMessenger_Register(MetisMessenger *messenger, const MetisMessengerRecipient *recipient) { assertNotNull(messenger, "Parameter messenger must be non-null"); assertNotNull(recipient, "Parameter recipient must be non-null"); // do not allow duplicates removeRecipient(messenger, recipient); parcArrayList_Add(messenger->callbacklist, recipient); } /** * @function metisEventMessenger_Unregister * @abstract Stop receiving event messages * @discussion * <#Discussion#> * * @param <#param1#> * @return <#return#> */ void metisMessenger_Unregister(MetisMessenger *messenger, const MetisMessengerRecipient *recipient) { assertNotNull(messenger, "Parameter messenger must be non-null"); assertNotNull(recipient, "Parameter recipient must be non-null"); removeRecipient(messenger, recipient); } /** * Called by event scheduler to give us a slice in which to dequeue events * * Called inside an event callback, so we now have exclusive access to the system. * Dequeues all pending events and calls all the listeners for each one. * * @param [in] fd unused, required for compliance with function prototype * @param [in] which_event unused, required for compliance with function prototype * @param [in] messengerVoidPtr A void* to MetisMessenger * * @return <#value#> <#explanation#> * * Example: * @code * <#example#> * @endcode */ static void metisMessenger_Dequeue(int fd, PARCEventType which_event, void *messengerVoidPtr) { MetisMessenger *messenger = (MetisMessenger *) messengerVoidPtr; assertNotNull(messenger, "Called with null messenger pointer"); MetisMissive *missive; while ((missive = metisMissiveDeque_RemoveFirst(messenger->eventQueue)) != NULL) { for (size_t i = 0; i < parcArrayList_Size(messenger->callbacklist); i++) { MetisMessengerRecipient *recipient = parcArrayList_Get(messenger->callbacklist, i); assertTrue(recipient, "Recipient is null at index %zu", i); metisMessengerRecipient_Deliver(recipient, metisMissive_Acquire(missive)); } // now let go of our reference to the missive metisMissive_Release(&missive); } }
0.996094
high
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/CustomBSP/CCollisionManager.h
domydev/Dark-Basic-Pro
231
2659185
<gh_stars>100-1000 #ifndef _COLLISIONMGR_H__ #define _COLLISIONMGR_H__ #include <d3d9.h> #include <d3dx9.h> #include "CCustomBSPData.h" struct VECTOR3 : public D3DXVECTOR3 { VECTOR3 ( ) {}; VECTOR3 ( const float *f ) { x = *f; y = *f; z = *f; } VECTOR3 ( const D3DVECTOR& v ) { x = v.x; y = v.y; z = v.z; } VECTOR3 ( float x, float y, float z ) { this->x = x; this->y = y; this->z = z; } VECTOR3& operator *= ( const VECTOR3 v ) { x *= v.x; y *= v.y; z *= v.z; return* this; } VECTOR3& operator /= ( const VECTOR3 v ) { x /= v.x; y /= v.y; z /= v.z; return* this; } VECTOR3& operator *= ( const float f ) { x *= f; y *= f; z *= f; return* this; } friend VECTOR3 operator * ( const VECTOR3& v1, const VECTOR3& v2 ) { return VECTOR3 ( v1.x * v2.x, v1.y * v2.y, v1.z * v2.z ); } friend VECTOR3 operator / ( const VECTOR3& v1, const VECTOR3& v2 ) { return VECTOR3 ( v1.x / v2.x, v1.y / v2.y, v1.z / v2.z ); } friend VECTOR3 operator / ( const float d, const VECTOR3& v2 ) { return VECTOR3 ( d / v2.x, d / v2.y, d / v2.z ); } }; class CCollisionManager { public: CCollisionManager ( void ); ~CCollisionManager ( void ); public: enum COLLISION_TYPE { COLLIDE_AND_SLIDE, COLLIDE_AND_STOP, COLLIDE_AND_BOUNCE, COLLIDE_NONE }; VECTOR3 collisionDetection ( VECTOR3& origin, VECTOR3& velocityVector, float fdeltaTime ); __inline void setGravity ( VECTOR3& g ) { m_gravity = g; } __inline void setFriction ( VECTOR3& f ) { m_friction = f; } __inline void setEllipsoid ( VECTOR3& radius ) { m_ellipRadius = radius; } __inline void setEyePoint ( VECTOR3& eye ) { m_eyePoint = eye; } __inline void setCollisionType ( COLLISION_TYPE type ) { m_collisionType = type; } __inline void enableCollisions ( bool enable = true ) { m_enableCollisionDetection = enable; } __inline VECTOR3 getGravity ( void ) { return m_gravity; } __inline VECTOR3 getFriction ( void ) { return m_friction; } __inline VECTOR3 getEllipsoid ( void ) { return m_ellipRadius; } __inline VECTOR3 getEyePoint ( void ) { return m_eyePoint; } __inline COLLISION_TYPE getCollisionType ( void ) { return m_collisionType; } __inline bool getCollisionsEnabled ( void ) { return m_enableCollisionDetection; } __inline int getNumPolysChecked ( void ) { return m_numPolysChecked; } private: VECTOR3 collideAndStop ( VECTOR3& origin, VECTOR3& velocityVector ); VECTOR3 collideAndSlide ( VECTOR3 origin, VECTOR3 velocityVector ); VECTOR3 collideAndBounce ( VECTOR3& origin, VECTOR3& velocityVector ); POLYGON* getAABBColliders ( VECTOR3 origin, VECTOR3 velocityVector ); void copyAndScalePolygon ( POLYGON* polyToCopy, POLYGON* scaledPoly, VECTOR3 &scalar ); VECTOR3 m_gravity; VECTOR3 m_friction; VECTOR3 m_ellipRadius; VECTOR3 m_eyePoint; COLLISION_TYPE m_collisionType; bool m_enableCollisionDetection; int m_numPolysChecked; }; #endif
0.996094
high
Logger.h
yyc12345/BallanceModLoader
36
2691953
#pragma once #include "ILogger.h" #include <cstdarg> class BML_EXPORT Logger : public ILogger { friend class ModLoader; public: Logger(const char* modname); virtual void Info(const char* fmt, ...) override; virtual void Warn(const char* fmt, ...) override; virtual void Error(const char* fmt, ...) override; private: void Log(const char* level, const char* fmt, va_list args); const char* m_modname; };
0.929688
high
chapter-06/memory.c
elephantscale/x86-labs
0
2724721
<reponame>elephantscale/x86-labs<gh_stars>0 #include <stdio.h> #include <stdlib.h> int data = 99; int bss; int main(void) { int stack = 86; int *heap = malloc(sizeof(*heap)); printf("stack: %p\n", &stack); printf(" heap: %p\n", heap); printf(" bss: %p\n", &bss); printf(" data: %p\n", &data); printf(" text: %p\n", main); free(heap); }
0.722656
high
groups/bsl/bslalg/bslalg_hashtableanchor.h
emeryberger/bde
1
3759480
// bslalg_hashtableanchor.h -*-C++-*- #ifndef INCLUDED_BSLALG_HASHTABLEANCHOR #define INCLUDED_BSLALG_HASHTABLEANCHOR #include <bsls_ident.h> BSLS_IDENT("$Id: $") //@PURPOSE: Provide a type holding the constituent parts of a hash table. // //@CLASSES: // bslalg::HashTableAnchor: (in-core) bucket-array and node list // //@SEE_ALSO: bslstl_hashtable, bslalg_hashtableimputil // //@DESCRIPTION: This component provides a single, complex-constrained // *in*-*core* (value-semantic) attribute class, 'bslalg::HashTableAnchor', // that is used to hold (not own) the array of buckets and the list of nodes // that form the key data elements of a hash-table. This class is typically // used with the utilities provided in 'bslstl_hashtableimputil'. Note that // the decision to store nodes in a linked list (i.e., resolving collisions // through chaining) is intended to facilitate a hash-table implementation // meeting the requirements of a C++11 standard unordered container. // ///Attributes ///---------- //.. // Name Type Simple Constraints // ------------------ ------------------- ------------------ // bucketArrayAddress HashTableBucket * none // // bucketArraySize size_t none // // listRootAddress BidirectionalLink * none // // // Complex Constraint // ------------------------------------------------------------------------- // 'bucketArrayAddress' must refer to a contiguous sequence of valid // 'bslalg::HashTableBucket' objects of at least the specified // 'bucketArraySize' or both 'bucketArrayAddress' and 'bucketArraySize' must // be 0. //.. // //: o 'listRootAddress': address of the head of the linked list of nodes //: holding the elements contained in a hash table //: //: o 'bucketArrayAddress': address of the first element of the sequence of //: 'HashTableBucket' objects, each of which refers to the first and last //: node (from 'listRootAddress') in that bucket //: //: o 'bucketArraySize': the number of (contiguous) buckets in the array of //: buckets at 'bucketArrayAddress' // ///Usage ///----- // This section illustrates intended use of this component. // // Suppose we want to create a hash table that keeps track of pointers. // Pointers can be added ('insert'ed) or removed ('erase'd) from the table, and // the table will keep track, at any time, of whether a pointer is currently // stored in the table using the 'count' method. It will also be able to // return the total number of objects stored in the table (the 'size' method). // Redundant 'insert's have no effect -- a given pointer may only be stored in // the table once. // // First, we create our class: //.. // class PtrHashSet : public bslalg::HashTableAnchor { // // PRIVATE TYPES // typedef bsls::Types::UintPtr UintPtr; // typedef bslalg::BidirectionalNode<void *> Node; // typedef bslalg::HashTableBucket Bucket; // typedef bslalg::BidirectionalLinkListUtil Util; // // // DATA // double d_maxLoadFactor; // unsigned d_numNodes; // bslma::Allocator *d_allocator_p; // // // PRIVATE MANIPULATORS // void grow(); // // Roughly double the number of buckets, such that the number of // // buckets shall always be '2^N - 1'. // // // PRIVATE ACCESSORS // bool checkInvariants() const; // // Perform sanity checks on this table, returning 'true' if all the // // tests pass and 'false' otherwise. Note that many of the checks // // are done with the 'ASSERTV' macro and will cause messages to be // // written to the console. // // bool find(Node **node, Bucket **bucket, const void *ptr) const; // // If the specified value 'ptr' is stored in this table, return // // pointers to its node and bucket in the specified 'node' and // // 'bucket'. If it is not in this table, return the bucket it // // should be in, and a pointer to the first node, if any, in that // // bucket. If the bucket is empty, return with // // '*node == listRootAddress()'. Return 'true' if 'ptr' was found // // in the table and 'false' otherwise. Note that it is permissible // // to pass 0 to 'node' and / or 'bucket', in which case these // // arguments are ignored. // // private: // // NOT IMPLEMENTED // PtrHashSet(const PtrHashSet&, bslma::Allocator *); // PtrHashSet& operator=(const PtrHashSet&); // // public: // // CREATORS // explicit // PtrHashSet(bslma::Allocator *allocator = 0); // // Create a 'PtrHashSet', using the specified 'allocator'. If no // // allocator is specified, use the default allocator. // // ~PtrHashSet(); // // Destroy this 'PtrHashSet', freeing all its memory. // // // MANIPULATORS // bool insert(void *ptr); // // If the specfied 'ptr' is not in this hash table, add it, // // returning 'true'. If it is already in the table, return 'false' // // with no action taken. // // bool erase(void *ptr); // // If the specfied 'ptr' is in this hash table, remove it, // // returning 'true'. If it is not found in the table, return // // 'false' with no action taken. // // // ACCESSORS // native_std::size_t count(void *ptr) const; // // Return 1 if the specified value 'ptr' is in this table and 0 // // otherwise. // // native_std::size_t size() const; // // Return the number of discrete values that are stored in this // // table. // }; // // // PRIVATE MANIPULATORS // void PtrHashSet::grow() // { // // 'bucketArraySize' will always be '2^N - 1', so that when pointers // // are aligned by some 2^N they're likely to be relatively prime. // // native_std::size_t newBucketArraySize = bucketArraySize() * 2 + 1; // native_std::size_t newBucketArraySizeInBytes = // newBucketArraySize * sizeof(Bucket); // memset(bucketArrayAddress(), 0x5a, size() * sizeof(Bucket)); // d_allocator_p->deallocate(bucketArrayAddress()); // setBucketArrayAddressAndSize( // (Bucket *) d_allocator_p->allocate(newBucketArraySizeInBytes), // newBucketArraySize); // memset(bucketArrayAddress(), 0, newBucketArraySizeInBytes); // Node *newListRootAddress = 0; // // unsigned numNodes = 0; // for (Node *node = (Node *) listRootAddress(); node; ++numNodes) { // Node *rippedOut = node; // node = (Node *) node->nextLink(); // // native_std::size_t index = // (UintPtr) rippedOut->value() % bucketArraySize(); // Bucket& bucket = bucketArrayAddress()[index]; // if (bucket.first()) { // if (0 == bucket.first()->previousLink()) { // newListRootAddress = rippedOut; // } // Util::insertLinkBeforeTarget(rippedOut, bucket.first()); // bucket.setFirst(rippedOut); // } // else { // Util::insertLinkBeforeTarget(rippedOut, // newListRootAddress); // newListRootAddress = rippedOut; // bucket.setFirstAndLast(rippedOut, rippedOut); // } // } // assert(size() == numNodes); // // setListRootAddress(newListRootAddress); // // checkInvariants(); // } // // // PRIVATE ACCESSORS // bool PtrHashSet::checkInvariants() const // { // bool ok; // // unsigned numNodes = 0; // Node *prev = 0; // for (Node *node = (Node *) listRootAddress(); node; // prev = node, node = (Node *) node->nextLink()) { // ok = node->previousLink() == prev; // assert(ok && "node->previousLink() == prev"); // if (!ok) return false; // RETURN // ++numNodes; // } // ok = size() == numNodes; // assert(ok && "size() == numNodes"); // if (!ok) return false; // RETURN // // numNodes = 0; // for (unsigned i = 0; i < bucketArraySize(); ++i) { // Bucket& bucket = bucketArrayAddress()[i]; // if (bucket.first()) { // ++numNodes; // for (Node *node = (Node *) bucket.first(); // bucket.last() != node; // node = (Node *) node->nextLink()) { // ++numNodes; // } // } // else { // ok = !bucket.last(); // assert(ok && "!bucket.last()"); // if (!ok) return false; // RETURN // } // } // ok = size() == numNodes; // assert(ok && "size() == numNodes"); // // return ok; // } // // bool PtrHashSet::find(Node **node, Bucket **bucket, const void *ptr) const // { // Node *dummyNodePtr; // Bucket *dummyBucketPtr; // if (!node ) node = &dummyNodePtr; // if (!bucket) bucket = &dummyBucketPtr; // // Node *& nodePtrRef = *node; // unsigned index = (UintPtr) ptr % bucketArraySize(); // Bucket& bucketRef = bucketArrayAddress()[index]; // *bucket = &bucketRef; // if (bucketRef.first()) { // Node *begin = (Node *) bucketRef.first(); // Node * const end = (Node *) bucketRef.last()->nextLink(); // for (Node *n = begin; end != n; n = (Node *) n->nextLink()) { // if (n->value() == ptr) { // // found // // nodePtrRef = n; // return true; // RETURN // } // } // // not found // // nodePtrRef = begin; // return false; // RETURN // } // // empty bucket // // nodePtrRef = (Node *) listRootAddress(); // return false; // } // // // CREATORS // PtrHashSet::PtrHashSet(bslma::Allocator *allocator) // : HashTableAnchor(0, 0, 0) // , d_maxLoadFactor(0.4) // , d_numNodes(0) // { // enum { NUM_BUCKETS = 3 }; // // d_allocator_p = bslma::Default::allocator(allocator); // native_std::size_t bucketArraySizeInBytes = // NUM_BUCKETS * sizeof(Bucket); // setBucketArrayAddressAndSize( // (Bucket *) d_allocator_p->allocate(bucketArraySizeInBytes), // NUM_BUCKETS); // memset(bucketArrayAddress(), 0, bucketArraySizeInBytes); // } // // PtrHashSet::~PtrHashSet() // { // BSLS_ASSERT_SAFE(checkInvariants()); // // for (Node *node = (Node *) listRootAddress(); node; ) { // Node *toDelete = node; // node = (Node *) node->nextLink(); // // memset(toDelete, 0x5a, sizeof(*toDelete)); // d_allocator_p->deallocate(toDelete); // } // // d_allocator_p->deallocate(bucketArrayAddress()); // } // // // MANIPULATORS // bool PtrHashSet::erase(void *ptr) // { // Bucket *bucket; // Node *node; // // if (!find(&node, &bucket, ptr)) { // return false; // RETURN // } // // if (bucket->first() == node) { // if (bucket->last() == node) { // bucket->reset(); // } // else { // bucket->setFirst(node->nextLink()); // } // } // else if (bucket->last() == node) { // bucket->setLast(node->previousLink()); // } // // --d_numNodes; // Util::unlink(node); // // d_allocator_p->deallocate(node); // // checkInvariants(); // // return true; // } // // bool PtrHashSet::insert(void *ptr) // { // Bucket *bucket; // Node *insertionPoint; // // if (find(&insertionPoint, &bucket, ptr)) { // // Already in set, do nothing. // // return false; // RETURN // } // // if (bucketArraySize() * d_maxLoadFactor < d_numNodes + 1) { // grow(); // bool found = find(&insertionPoint, &bucket, ptr); // BSLS_ASSERT_SAFE(!found); // } // // ++d_numNodes; // Node *node = (Node *) d_allocator_p->allocate(sizeof(Node)); // // Util::insertLinkBeforeTarget(node, insertionPoint); // node->value() = ptr; // if (listRootAddress() == insertionPoint) { // BSLS_ASSERT_SAFE(0 == node->previousLink()); // setListRootAddress(node); // } // // if (bucket->first()) { // BSLS_ASSERT_SAFE(bucket->first() == insertionPoint); // // bucket->setFirst(node); // } // else { // BSLS_ASSERT_SAFE(!bucket->last()); // // bucket->setFirstAndLast(node, node); // } // // assert(count(ptr)); // // checkInvariants(); // // return true; // } // // // ACCESSORS // native_std::size_t PtrHashSet::count(void *ptr) const // { // return find(0, 0, ptr); // } // // native_std::size_t PtrHashSet::size() const // { // return d_numNodes; // } //.. // Then, in 'main', we create a test allocator for use in this example to // ensure that no memory is leaked: //.. // bslma::TestAllocator ta("test", veryVeryVeryVerbose); //.. // Next, we declare our table using that allocator: //.. // PtrHashSet phs(&ta); //.. // Then, we create an area of memory from which our pointers will come: //.. // enum { SEGMENT_LENGTH = 1000 }; // char *pc = (char *) ta.allocate(SEGMENT_LENGTH); //.. // Next, we iterate through the length of the segment, insert those pointers // for which 'ptr - pc == N * 7' is true. We keep a count of the number of // items we insert into the table in the variable 'sevens': //.. // unsigned sevens = 0; // for (int i = 0; i < SEGMENT_LENGTH; i += 7) { // ++sevens; // bool status = phs.insert(&pc[i]); // assert(status); // } //.. // Then, we verify the number of objects we've placed in the table: //.. // assert(phs.size() == sevens); //.. // Next, we iterate through ALL pointers in the 'pc' array, using the 'count' // method to verify that the ones we expect are in the table: //.. // for (int i = 0; i < SEGMENT_LENGTH; ++i) { // assert(phs.count(&pc[i]) == (0 == i % 7)); // } //.. // Then, we iterate, deleting all elements from the table for which // 'ptr - pc == 3 * N' is true. We keep a count of the number of elements that // were deleted from the table in the variable 'killed': //.. // unsigned killed = 0; // for (int i = 0; i < SEGMENT_LENGTH; i += 3) { // const bool deleted = phs.erase(&pc[i]); // assert(deleted == (0 == i % 7)); // killed += deleted; // } //.. // Next, we verify the number of remaining elements in the table: //.. // assert(killed < sevens); // assert(phs.size() == sevens - killed); //.. // Then, in verbose mode we print our tallies: //.. // if (verbose) { // printf("sevens = %u, killed = %u, phs.size() = %u\n", sevens, // killed, (unsigned) phs.size()); // } //.. // Now, we iterate through every element of the 'pc' array, verifying that the // surviving elements are exactly those for which 'ptr - pc' was divisible by 7 // and not by 3: //.. // for (int i = 0; i < SEGMENT_LENGTH; ++i) { // const bool present = phs.count(&pc[i]); // assert(present == ((0 == i % 7) && (0 != i % 3))); // } //.. // Finally, we clean up our 'pc' array: //.. // ta.deallocate(pc); //.. #include <bslscm_version.h> #include <bslalg_bidirectionallink.h> #include <bslalg_scalarprimitives.h> #include <bslmf_istriviallycopyable.h> #include <bslmf_nestedtraitdeclaration.h> #include <bsls_assert.h> #include <bsls_nativestd.h> #include <cstddef> namespace BloombergLP { namespace bslalg { struct HashTableBucket; // This is known to be a POD struct. // ============================= // class bslalg::HashTableAnchor // ============================= class HashTableAnchor { // This complex constrained *in*-*core* (value-semantic) attribute class // characterizes the key data elements of a hash table. See the // "Attributes" section under @DESCRIPTION in the component-level // documentation for/ information on the class attributes. Note that the // class invariant is the identically the complex constraint of this // component. // // This class: //: o supports a complete set of *value-semantic* operations //: o except for 'bdex' serialization and default construction //: o is *in-core* //: o is *exception-neutral* (agnostic) //: o is *alias-safe* //: o is 'const' *thread-safe* // For terminology see 'bsldoc_glossary'. // DATA HashTableBucket *d_bucketArrayAddress_p; // address of the array of // buckets (held, not owned) native_std::size_t d_bucketArraySize; // size of 'd_bucketArray' BidirectionalLink *d_listRootAddress_p; // head of the list of // elements in the hash-table // (held, not owned) public: // TRAITS BSLMF_NESTED_TRAIT_DECLARATION(HashTableAnchor, bsl::is_trivially_copyable); // CREATORS HashTableAnchor(HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize, BidirectionalLink *listRootAddress); // Create a 'bslalg::HashTableAnchor' object having the specified // 'bucketArrayAddress', 'bucketArraySize', and 'listRootAddress' // attributes. The behavior is undefined unless 'bucketArrayAddress' // refers to a contiguous sequence of valid 'bslalg::HashTableBucket' // objects of at least 'bucketArraySize' or unless both // 'bucketArrayAddress' and 'bucketArraySize' are 0. HashTableAnchor(const HashTableAnchor& original); // Create a 'bslalg::HashTableAnchor' object having the same value // as the specified 'original' object. // ~bslalg::HashTableAnchor(); = default // Destroy this object. // MANIPULATORS bslalg::HashTableAnchor& operator=(const bslalg::HashTableAnchor& rhs); // Assign to this object the value of the specified 'rhs' object, and // return a reference providing modifiable access to this object. void setBucketArrayAddressAndSize(HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize); // Set the bucket array address and bucket array size attributes of // this object to the specified 'bucketArrayAddress' and // 'bucketArraySize' values. The behavior is undefined unless // 'bucketArrayAddress' refers to a contiguous sequence of valid // 'bslalg::HashTableBucket' objects of at least 'bucketArraySize', or // unless both 'bucketArrayAddress' and 'bucketArraySize' are 0. void setListRootAddress(BidirectionalLink *value); // Set the 'listRootAddress' attribute of this object to the // specified 'value'. // Aspects void swap(HashTableAnchor& other); // Efficiently exchange the value of this object with the value of the // specified 'other' object. This method provides the no-throw // exception-safety guarantee. // ACCESSORS HashTableBucket *bucketArrayAddress() const; // Return the value of the 'bucketArrayAddress' attribute of this // object. native_std::size_t bucketArraySize() const; // Return the value of the 'bucketArraySize' attribute of this object. BidirectionalLink *listRootAddress() const; // Return the value 'listRootAddress' attribute of this object. }; // FREE OPERATORS bool operator==(const HashTableAnchor& lhs, const HashTableAnchor& rhs); // Return 'true' if the specified 'lhs' and 'rhs' objects have the same // value, and 'false' otherwise. Two 'bslalg::HashTableAnchor' objects // have the same value if all of the corresponding values of their // 'bucketArrayAddress', 'bucketArraySize', and 'listRootAddress' // attributes are the same. bool operator!=(const HashTableAnchor& lhs, const HashTableAnchor& rhs); // Return 'true' if the specified 'lhs' and 'rhs' objects do not have the // same value, and 'false' otherwise. Two 'bslalg::HashTableAnchor' // objects do not have the same value if any of the corresponding values of // their 'bucketArrayAddress', 'bucketArraySize', or 'listRootAddress' // attributes are not the same. // FREE FUNCTIONS void swap(HashTableAnchor& a, HashTableAnchor& b); // Efficiently exchange the values of the specified 'a' and 'b' objects. // This function provides the no-throw exception-safety guarantee. The // behavior is undefined unless the two objects were created with the same // allocator. // ============================================================================ // INLINE FUNCTION DEFINITIONS // ============================================================================ // ----------------------------- // class bslalg::HashTableAnchor // ----------------------------- // CREATORS inline HashTableAnchor::HashTableAnchor(bslalg::HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize, bslalg::BidirectionalLink *listRootAddress) : d_bucketArrayAddress_p(bucketArrayAddress) , d_bucketArraySize(bucketArraySize) , d_listRootAddress_p(listRootAddress) { BSLS_ASSERT_SAFE( (!bucketArrayAddress && !bucketArraySize) || (bucketArrayAddress && 0 < bucketArraySize)); BSLS_ASSERT_SAFE(!listRootAddress || !(listRootAddress->previousLink())); } inline HashTableAnchor::HashTableAnchor(const HashTableAnchor& original) : d_bucketArrayAddress_p(original.d_bucketArrayAddress_p) , d_bucketArraySize(original.d_bucketArraySize) , d_listRootAddress_p(original.d_listRootAddress_p) { } // MANIPULATORS inline HashTableAnchor& HashTableAnchor::operator=(const HashTableAnchor& rhs) { d_bucketArrayAddress_p = rhs.d_bucketArrayAddress_p; d_bucketArraySize = rhs.d_bucketArraySize; d_listRootAddress_p = rhs.d_listRootAddress_p; return *this; } inline void HashTableAnchor::setBucketArrayAddressAndSize( HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize) { BSLS_ASSERT_SAFE(( bucketArrayAddress && 0 < bucketArraySize) || (!bucketArrayAddress && !bucketArraySize)); d_bucketArrayAddress_p = bucketArrayAddress; d_bucketArraySize = bucketArraySize; } inline void HashTableAnchor::setListRootAddress(BidirectionalLink *value) { BSLS_ASSERT_SAFE(!value || !value->previousLink()); d_listRootAddress_p = value; } // Aspects inline void HashTableAnchor::swap(HashTableAnchor& other) { bslalg::ScalarPrimitives::swap(*this, other); } // ACCESSORS inline BidirectionalLink *HashTableAnchor::listRootAddress() const { return d_listRootAddress_p; } inline std::size_t HashTableAnchor::bucketArraySize() const { return d_bucketArraySize; } inline HashTableBucket *HashTableAnchor::bucketArrayAddress() const { return d_bucketArrayAddress_p; } } // close package namespace // FREE OPERATORS inline void bslalg::swap(bslalg::HashTableAnchor& a, bslalg::HashTableAnchor& b) { a.swap(b); } inline bool bslalg::operator==(const bslalg::HashTableAnchor& lhs, const bslalg::HashTableAnchor& rhs) { return lhs.bucketArrayAddress() == rhs.bucketArrayAddress() && lhs.bucketArraySize() == rhs.bucketArraySize() && lhs.listRootAddress() == rhs.listRootAddress(); } inline bool bslalg::operator!=(const bslalg::HashTableAnchor& lhs, const bslalg::HashTableAnchor& rhs) { return lhs.bucketArrayAddress() != rhs.bucketArrayAddress() || lhs.bucketArraySize() != rhs.bucketArraySize() || lhs.listRootAddress() != rhs.listRootAddress(); } } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
1
high
teleop_and_haptics/local_planners/src/cvxgen_quad/testsolver.c
atp42/jks-ros-pkg
3
3792248
/* Produced by CVXGEN, 2012-09-18 18:21:14 -0700. */ /* CVXGEN is Copyright (C) 2006-2011 <NAME>, <EMAIL>. */ /* The code in this file is Copyright (C) 2006-2011 <NAME>. */ /* CVXGEN, or solvers produced by CVXGEN, cannot be used for commercial */ /* applications without prior written permission from <NAME>. */ /* Filename: testsolver.c. */ /* Description: Basic test harness for solver.c. */ #include "solver.h" Vars vars; Params params; Workspace work; Settings settings; #define NUMTESTS 0 int main(int argc, char **argv) { int num_iters; #if (NUMTESTS > 0) int i; double time; double time_per; #endif set_defaults(); setup_indexing(); load_default_data(); /* Solve problem instance for the record. */ settings.verbose = 1; num_iters = solve(); #ifndef ZERO_LIBRARY_MODE #if (NUMTESTS > 0) /* Now solve multiple problem instances for timing purposes. */ settings.verbose = 0; tic(); for (i = 0; i < NUMTESTS; i++) { solve(); } time = tocq(); printf("Timed %d solves over %.3f seconds.\n", NUMTESTS, time); time_per = time / NUMTESTS; if (time_per > 1) { printf("Actual time taken per solve: %.3g s.\n", time_per); } else if (time_per > 1e-3) { printf("Actual time taken per solve: %.3g ms.\n", 1e3*time_per); } else { printf("Actual time taken per solve: %.3g us.\n", 1e6*time_per); } #endif #endif return 0; } void load_default_data(void) { params.weight_x[0] = 1.10159580514915; params.x_d[0] = 0.832591290472419; params.x_d[1] = -0.836381044348223; params.x_d[2] = 0.0433104207906521; params.J_v[0] = 1.57178781739062; params.J_v[1] = 1.58517235573375; params.J_v[2] = -1.49765875814465; params.J_v[3] = -1.17102848744725; params.J_v[4] = -1.79413118679668; params.J_v[5] = -0.236760625397454; params.J_v[6] = -1.88049515648573; params.J_v[7] = -0.172667102421156; params.J_v[8] = 0.596576190459043; params.J_v[9] = -0.886050869408099; params.J_v[10] = 0.705019607920525; params.J_v[11] = 0.363451269665403; params.J_v[12] = -1.90407247049134; params.J_v[13] = 0.235416351963528; params.J_v[14] = -0.962990212370138; params.J_v[15] = -0.339595211959721; params.J_v[16] = -0.865899672914725; params.J_v[17] = 0.772551673251985; params.J_v[18] = -0.238185129317042; params.J_v[19] = -1.37252904610015; params.J_v[20] = 0.178596072127379; params.weight_w[0] = 1.56062952902273; params.w_d[0] = -0.774545870495281; params.w_d[1] = -1.11216846427127; params.w_d[2] = -0.448114969777405; params.J_w[0] = 1.74553459944172; params.J_w[1] = 1.90398168989174; params.J_w[2] = 0.689534703651255; params.J_w[3] = 1.61133643415359; params.J_w[4] = 1.38300348517272; params.J_w[5] = -0.488023834684443; params.J_w[6] = -1.6311319645131; params.J_w[7] = 0.613643610094145; params.J_w[8] = 0.231363049553804; params.J_w[9] = -0.553740947749688; params.J_w[10] = -1.09978198064067; params.J_w[11] = -0.373920334495006; params.J_w[12] = -0.124239005203324; params.J_w[13] = -0.923057686995755; params.J_w[14] = -0.83282890309827; params.J_w[15] = -0.169254402708088; params.J_w[16] = 1.44213565178771; params.J_w[17] = 0.345011617871286; params.J_w[18] = -0.866048550271161; params.J_w[19] = -0.888089973505595; params.J_w[20] = -0.181511697912213; params.weight_q[0] = 0.410820689209975; params.q_min[0] = -1.19448515582771; params.q_min[1] = 0.0561402392697676; params.q_min[2] = -1.65108252487678; params.q_min[3] = -0.0656578705936539; params.q_min[4] = -0.551295150448667; params.q_min[5] = 0.830746487262684; params.q_min[6] = 0.986984892408018; params.q[0] = 0.764371687423057; params.q[1] = 0.756721655019656; params.q[2] = -0.505599503404287; params.q[3] = 0.67253921894107; params.q[4] = -0.640605344172728; params.q[5] = 0.2911754794755; params.q[6] = -0.696771367740502; params.q_max[0] = -0.219419802945872; params.q_max[1] = -1.75388427668024; params.q_max[2] = -1.02929831126265; params.q_max[3] = 1.88641042469427; params.q_max[4] = -1.0776631825797; params.q_max[5] = 0.765910043789321; params.q_max[6] = 0.601907432854958; }
0.976563
high
Demo/CORTEX_STM32F100_Atollic/Simple_Demo_Source/main.c
Chomtana/FreeRTOS-Embedded-Lab-6
0
5225016
<reponame>Chomtana/FreeRTOS-Embedded-Lab-6 /* * FreeRTOS Kernel V10.3.1 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* This simple demo project runs on the STM32 Discovery board, which is populated with an STM32F100RB Cortex-M3 microcontroller. The discovery board makes an ideal low cost evaluation platform, but the 8K of RAM provided on the STM32F100RB does not allow the simple application to demonstrate all of all the FreeRTOS kernel features. Therefore, this simple demo only actively demonstrates task, queue, timer and interrupt functionality. In addition, the demo is configured to include malloc failure, idle and stack overflow hook functions. The idle hook function: The idle hook function queries the amount of FreeRTOS heap space that is remaining (see vApplicationIdleHook() defined in this file). The demo application is configured to use 7K of the available 8K of RAM as the FreeRTOS heap. Memory is only allocated from this heap during initialisation, and this demo only actually uses 1.6K bytes of the configured 7K available - leaving 5.4K bytes of heap space unallocated. The main() Function: main() creates one software timer, one queue, and two tasks. It then starts the scheduler. The Queue Send Task: The queue send task is implemented by the prvQueueSendTask() function in this file. prvQueueSendTask() sits in a loop that causes it to repeatedly block for 200 milliseconds, before sending the value 100 to the queue that was created within main(). Once the value is sent, the task loops back around to block for another 200 milliseconds. The Queue Receive Task: The queue receive task is implemented by the prvQueueReceiveTask() function in this file. prvQueueReceiveTask() sits in a loop where it repeatedly blocks on attempts to read data from the queue that was created within main(). When data is received, the task checks the value of the data, and if the value equals the expected 100, toggles the green LED. The 'block time' parameter passed to the queue receive function specifies that the task should be held in the Blocked state indefinitely to wait for data to be available on the queue. The queue receive task will only leave the Blocked state when the queue send task writes to the queue. As the queue send task writes to the queue every 200 milliseconds, the queue receive task leaves the Blocked state every 200 milliseconds, and therefore toggles the green LED every 200 milliseconds. The LED Software Timer and the Button Interrupt: The user button B1 is configured to generate an interrupt each time it is pressed. The interrupt service routine switches the red LED on, and resets the LED software timer. The LED timer has a 5000 millisecond (5 second) period, and uses a callback function that is defined to just turn the red LED off. Therefore, pressing the user button will turn the red LED on, and the LED will remain on until a full five seconds pass without the button being pressed. */ /* Kernel includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "timers.h" /* STM32 Library includes. */ #include "stm32f10x.h" #include "STM32vldiscovery.h" /* Priorities at which the tasks are created. */ #define mainQUEUE_RECEIVE_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 ) #define mainQUEUE_SEND_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) /* The rate at which data is sent to the queue, specified in milliseconds, and converted to ticks using the portTICK_PERIOD_MS constant. */ #define mainQUEUE_SEND_FREQUENCY_MS ( 200 / portTICK_PERIOD_MS ) /* The number of items the queue can hold. This is 1 as the receive task will remove items as they are added, meaning the send task should always find the queue empty. */ #define mainQUEUE_LENGTH ( 1 ) /*-----------------------------------------------------------*/ /* * Setup the NVIC, LED outputs, and button inputs. */ static void prvSetupHardware( void ); /* * The tasks as described in the comments at the top of this file. */ static void prvQueueReceiveTask( void *pvParameters ); static void prvQueueSendTask( void *pvParameters ); /* * The LED timer callback function. This does nothing but switch the red LED * off. */ static void vLEDTimerCallback( TimerHandle_t xTimer ); /*-----------------------------------------------------------*/ /* The queue used by both tasks. */ static QueueHandle_t xQueue = NULL; /* The LED software timer. This uses vLEDTimerCallback() as its callback * function. */ static TimerHandle_t xLEDTimer = NULL; /*-----------------------------------------------------------*/ int main(void) { /* Configure the NVIC, LED outputs and button inputs. */ prvSetupHardware(); /* Create the queue. */ xQueue = xQueueCreate( mainQUEUE_LENGTH, sizeof( unsigned long ) ); if( xQueue != NULL ) { /* Start the two tasks as described in the comments at the top of this file. */ xTaskCreate( prvQueueReceiveTask, "Rx", configMINIMAL_STACK_SIZE, NULL, mainQUEUE_RECEIVE_TASK_PRIORITY, NULL ); xTaskCreate( prvQueueSendTask, "TX", configMINIMAL_STACK_SIZE, NULL, mainQUEUE_SEND_TASK_PRIORITY, NULL ); /* Create the software timer that is responsible for turning off the LED if the button is not pushed within 5000ms, as described at the top of this file. */ xLEDTimer = xTimerCreate( "LEDTimer", /* A text name, purely to help debugging. */ ( 5000 / portTICK_PERIOD_MS ),/* The timer period, in this case 5000ms (5s). */ pdFALSE, /* This is a one-shot timer, so xAutoReload is set to pdFALSE. */ ( void * ) 0, /* The ID is not used, so can be set to anything. */ vLEDTimerCallback /* The callback function that switches the LED off. */ ); /* Start the tasks and timer running. */ vTaskStartScheduler(); } /* If all is well, the scheduler will now be running, and the following line will never be reached. If the following line does execute, then there was insufficient FreeRTOS heap memory available for the idle and/or timer tasks to be created. See the memory management section on the FreeRTOS web site for more details. */ for( ;; ); } /*-----------------------------------------------------------*/ static void vLEDTimerCallback( TimerHandle_t xTimer ) { /* The timer has expired - so no button pushes have occurred in the last five seconds - turn the LED off. NOTE - accessing the LED port should use a critical section because it is accessed from multiple tasks, and the button interrupt - in this trivial case, for simplicity, the critical section is omitted. */ STM32vldiscovery_LEDOff( LED4 ); } /*-----------------------------------------------------------*/ /* The ISR executed when the user button is pushed. */ void EXTI0_IRQHandler( void ) { portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE; /* The button was pushed, so ensure the LED is on before resetting the LED timer. The LED timer will turn the LED off if the button is not pushed within 5000ms. */ STM32vldiscovery_LEDOn( LED4 ); /* This interrupt safe FreeRTOS function can be called from this interrupt because the interrupt priority is below the configMAX_SYSCALL_INTERRUPT_PRIORITY setting in FreeRTOSConfig.h. */ xTimerResetFromISR( xLEDTimer, &xHigherPriorityTaskWoken ); /* Clear the interrupt before leaving. */ EXTI_ClearITPendingBit( EXTI_Line0 ); /* If calling xTimerResetFromISR() caused a task (in this case the timer service/daemon task) to unblock, and the unblocked task has a priority higher than or equal to the task that was interrupted, then xHigherPriorityTaskWoken will now be set to pdTRUE, and calling portEND_SWITCHING_ISR() will ensure the unblocked task runs next. */ portEND_SWITCHING_ISR( xHigherPriorityTaskWoken ); } /*-----------------------------------------------------------*/ static void prvQueueSendTask( void *pvParameters ) { TickType_t xNextWakeTime; const unsigned long ulValueToSend = 100UL; /* Initialise xNextWakeTime - this only needs to be done once. */ xNextWakeTime = xTaskGetTickCount(); for( ;; ) { /* Place this task in the blocked state until it is time to run again. The block time is specified in ticks, the constant used converts ticks to ms. While in the Blocked state this task will not consume any CPU time. */ vTaskDelayUntil( &xNextWakeTime, mainQUEUE_SEND_FREQUENCY_MS ); /* Send to the queue - causing the queue receive task to unblock and toggle an LED. 0 is used as the block time so the sending operation will not block - it shouldn't need to block as the queue should always be empty at this point in the code. */ xQueueSend( xQueue, &ulValueToSend, 0 ); } } /*-----------------------------------------------------------*/ static void prvQueueReceiveTask( void *pvParameters ) { unsigned long ulReceivedValue; for( ;; ) { /* Wait until something arrives in the queue - this task will block indefinitely provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. */ xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY ); /* To get here something must have been received from the queue, but is it the expected value? If it is, toggle the green LED. */ if( ulReceivedValue == 100UL ) { /* NOTE - accessing the LED port should use a critical section because it is accessed from multiple tasks, and the button interrupt - in this trivial case, for simplicity, the critical section is omitted. */ STM32vldiscovery_LEDToggle( LED3 ); } } } /*-----------------------------------------------------------*/ static void prvSetupHardware( void ) { /* Ensure that all 4 interrupt priority bits are used as the pre-emption priority. */ NVIC_PriorityGroupConfig( NVIC_PriorityGroup_4 ); /* Set up the LED outputs and the button inputs. */ STM32vldiscovery_LEDInit( LED3 ); STM32vldiscovery_LEDInit( LED4 ); STM32vldiscovery_PBInit( BUTTON_USER, BUTTON_MODE_EXTI ); /* Start with the LEDs off. */ STM32vldiscovery_LEDOff( LED3 ); STM32vldiscovery_LEDOff( LED4 ); } /*-----------------------------------------------------------*/ void vApplicationMallocFailedHook( void ) { /* Called if a call to pvPortMalloc() fails because there is insufficient free memory available in the FreeRTOS heap. pvPortMalloc() is called internally by FreeRTOS API functions that create tasks, queues, software timers, and semaphores. The size of the FreeRTOS heap is set by the configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */ for( ;; ); } /*-----------------------------------------------------------*/ void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName ) { ( void ) pcTaskName; ( void ) pxTask; /* Run time stack overflow checking is performed if configconfigCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook function is called if a stack overflow is detected. */ for( ;; ); } /*-----------------------------------------------------------*/ void vApplicationIdleHook( void ) { volatile size_t xFreeStackSpace; /* This function is called on each cycle of the idle task. In this case it does nothing useful, other than report the amout of FreeRTOS heap that remains unallocated. */ xFreeStackSpace = xPortGetFreeHeapSize(); if( xFreeStackSpace > 100 ) { /* By now, the kernel has allocated everything it is going to, so if there is a lot of heap remaining unallocated then the value of configTOTAL_HEAP_SIZE in FreeRTOSConfig.h can be reduced accordingly. */ } }
0.996094
high
ShelfMagnetic/ShelfMagnetic/Demo/MagneticDemo5Controller.h
jenson21/shelfmagnetic
2
5257784
// // MagneticDemo5Controller.h // ShelfMagnetic // // Created by Jenson on 2021/7/4. // Copyright © 2021 Jenson. All rights reserved. // #import "MagneticController.h" NS_ASSUME_NONNULL_BEGIN @interface MagneticDemo5Controller : MagneticController @end NS_ASSUME_NONNULL_END
0.605469
high
triangle/src/main/cpp/inc/LogUtils.h
birthmark/OpenGLSample
22
5290576
#ifndef _LOG_UTILS_H_ #define _LOG_UTILS_H_ #include <android/log.h> #include <string.h> #define DEBUG // 可以通过 CmakeLists.txt 来定义在这个宏,实现动态打开和关闭LOG // Windows 和 Linux 这两个宏是在 CMakeLists.txt 通过 ADD_DEFINITIONS 定义的 #ifdef Windows #define __FILENAME__ (strrchr(__FILE__, '\\') + 1) // Windows下文件目录层级是'\\' #elif Linux #define __FILENAME__ (strrchr(__FILE__, '/') + 1) // Linux下文件目录层级是'/' #else #define __FILENAME__ (strrchr(__FILE__, '/') + 1) // 默认使用这种方式 #endif #ifdef DEBUG #define TAG "JNI" #define LOGV(format, ...) __android_log_print(ANDROID_LOG_VERBOSE, TAG,\ "[%s][%s][%d]: " format, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__); #define LOGD(format, ...) __android_log_print(ANDROID_LOG_DEBUG, TAG,\ "[%s][%s][%d]: " format, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__); #define LOGI(format, ...) __android_log_print(ANDROID_LOG_INFO, TAG,\ "[%s][%s][%d]: " format, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__); #define LOGW(format, ...) __android_log_print(ANDROID_LOG_WARN, TAG,\ "[%s][%s][%d]: " format, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__); #define LOGE(format, ...) __android_log_print(ANDROID_LOG_ERROR, TAG,\ "[%s][%s][%d]: " format, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__); #else #define LOGV(format, ...); #define LOGD(format, ...); #define LOGI(format, ...); #define LOGW(format, ...); #define LOGE(format, ...); #endif // DEBUG #endif // _LOG_UTILS_H_
0.984375
high
Codes/ALGO_2.3/FalsePosition/FalsePositionFunc.c
primeyo2004/NumericalMethods
0
5323344
#include "FalsePositionFunc.h" /* * Function name : computeFalsePosition * Description : Computes the root using the false position method. * Parameter(s) : * nA [in] Point A. * nB [in] Point B. * fFunction [in] The function to evaluate f(x). * nMaxIter [in] The maximum number of iteration. * nPrint [in] Flag for printing the output on screen, * pOutput [out] The root. * pDx [out] The difference between the iteration. * Return : * int 0 - Success, -1 - Same sign. */ int _cdecl computeFalsePosition(double nA,double nB,double (*fFunction)(double),int nMaxIter,int nPrint,double *pOutput,double* pDx) { int nRet = 0; static const double nDelta = 10e-8; /* Tolerance for change in X */ static const double nEpsilon = 10e-8; /* Tolerance for f(C) */ double nDx = 0; /* Change in X */ int nSatisfied = 0; /* If 1, the calculation is satisfied */ int i; double nYA,nYB,nYC,nC; nYA = fFunction(nA); nYB = fFunction(nB); if(GETSIGN(nYA) == GETSIGN(nYB)) nRet = -1; /* Check for the signs */ if(nRet == 0) { if(nPrint) { printf("\n\n N %-10s \t %-10s %-10s %-8s %-8s %-8s " ,"A","B","C","f(A)","f(B)","f(C)"); printf("\n--------------------------------------------------------------"); } for(i = 1; i <= nMaxIter && nSatisfied == 0 ; i++) { /* Get the change in X */ nDx = nYB * (nB-nA) /(nYB- nYA); nC = nB - nDx; nYC = fFunction(nC); if(nPrint) printf("\n %2d %2.8lf %2.8lf %2.8lf %2.6lf %2.6lf %2.6lf " ,i,nA,nB,nC,nYA,nYB,nYC); if(nYC == 0) { nSatisfied = 1; /* Root is found */ } else if(GETSIGN(nYB) == GETSIGN(nYC)) { nB = nC; nYB = nYC; } else { nA = nC; nYA = nYC; } if(fabs(nDx) < nDelta && fabs(nYC) < nEpsilon) { nSatisfied = 1; *pOutput = nC; *pDx = nDx; } } if(nPrint) printf("\n-------------------------------------------------------------"); } return nRet; }
0.984375
high
falg/include/falg.h
ousttrue/dtla
0
5356112
<filename>falg/include/falg.h #pragma once #include <array> #include <cmath> #include <limits> #include <vector> #define _USE_MATH_DEFINES #include <math.h> /// /// float algebra /// /// TODO: use ROW vector & ROW major matrix /// /// [COL vector] => x /// R|T X X' /// -+- * Y = Y' /// 0|1 Z Z' /// #multiply order /// root * parent * local * col vector => vector /// /// [ROW vector] /// R|0 /// XYZ * -+- = X'Y'Z' /// T|1 /// #multiply order /// row vector * local * parent * root => vector /// /// [ROW major] /// matrix { m11, m12, m13, ... } /// /// [COL major] => x /// matrix { m11, m21, m31, ... } /// /// tradeoff /// => get translation from matrix /// => matrix apply vector function /// => matrix conversion function(ex. quaterion to matrix, decompose... etc) /// /// upload [ROW vector][ROW major] matrix to d3d constant buffer /// mul(matrix, float4) [ROW vector usage] /// OK /// /// if /// mul(float4, world) [COL vector usage] /// world is inversed /// namespace falg { using float2 = std::array<float, 2>; using float3 = std::array<float, 3>; using float4 = std::array<float, 4>; using float16 = std::array<float, 16>; const float PI = (float)M_PI; const float TO_RADIANS = PI / 180.0f; template <typename T, typename S> inline const T &size_cast(const S &s) { static_assert(sizeof(S) == sizeof(T), "must same size"); return *((T *)&s); } template <typename T, typename S> inline T &size_cast(S &s) { static_assert(sizeof(S) == sizeof(T), "must same size"); return *((T *)&s); } struct range { const void *begin; const void *end; size_t size() const { return (uint8_t *)end - (uint8_t *)begin; } }; template <typename T, typename S> inline const T &vector_cast(const std::vector<S> &s) { range r{s.data(), s.data() + s.size()}; if (r.size() != sizeof(T)) { throw; } return *(const T *)r.begin; } struct xyz { float x; float y; float z; }; struct xyzw { float x; float y; float z; float w; }; struct row_matrix { float _11; float _12; float _13; float _14; float _21; float _22; float _23; float _24; float _31; float _32; float _33; float _34; float _41; float _42; float _43; float _44; }; template <size_t MOD, size_t N> struct mul4 { // SFINAE for MOD not 0 }; template <size_t N> struct mul4<0, N> { static const size_t value = N; }; template <typename T> struct float_array { static const size_t length = mul4<sizeof(T) % 4, sizeof(T) / 4>::value; using type = std::array<float, length>; template <typename S> static const type &cast(const S &s) { return size_cast<type>(s); } }; template <typename T> inline bool Nearly(const T &lhs, const T &rhs) { using ARRAY = float_array<T>; auto &l = ARRAY::cast(lhs); auto &r = ARRAY::cast(rhs); const auto EPSILON = 1e-5f; for (size_t i = 0; i < ARRAY::length; ++i) { if (abs(l[i] - r[i]) > EPSILON) { return false; } } return true; } template <typename T> inline T MulScalar(const T &value, float f) { using ARRAY = float_array<T>; auto v = ARRAY::cast(value); for (size_t i = 0; i < ARRAY::length; ++i) { v[i] *= f; } return size_cast<T>(v); } template <typename T> inline T Add(const T &lhs, const T &rhs) { using ARRAY = float_array<T>; auto &l = ARRAY::cast(lhs); auto &r = ARRAY::cast(rhs); T value; for (size_t i = 0; i < ARRAY::length; ++i) { value[i] = l[i] + r[i]; } return size_cast<T>(value); } template <typename T> inline T Sub(const T &lhs, const T &rhs) { using ARRAY = float_array<T>; auto &l = ARRAY::cast(lhs); auto &r = ARRAY::cast(rhs); T value; for (size_t i = 0; i < ARRAY::length; ++i) { value[i] = l[i] - r[i]; } return size_cast<T>(value); } template <typename T> inline T EachMul(const T &lhs, const T &rhs) { using ARRAY = float_array<T>; auto &l = ARRAY::cast(lhs); auto &r = ARRAY::cast(rhs); T value; for (size_t i = 0; i < ARRAY::length; ++i) { value[i] = l[i] * r[i]; } return size_cast<T>(value); } template <typename T> inline float Dot(const T &lhs, const T &rhs) { using ARRAY = float_array<T>; auto &l = ARRAY::cast(lhs); auto &r = ARRAY::cast(rhs); float value = 0; for (size_t i = 0; i < ARRAY::length; ++i) { value += l[i] * r[i]; } return value; } template <typename T> inline float Length(const T &src) { return std::sqrt(Dot(src, src)); } template <typename T> inline T Normalize(const T &src) { using ARRAY = float_array<T>; auto value = ARRAY::cast(src); auto factor = 1.0f / Length(src); for (size_t i = 0; i < ARRAY::length; ++i) { value[i] *= factor; } return size_cast<T>(value); } template <typename T> inline T Cross(const T &lhs, const T &rhs) { auto &l = size_cast<xyz>(lhs); auto &r = size_cast<xyz>(rhs); xyz value{ l.y * r.z - l.z * r.y, l.z * r.x - l.x * r.z, l.x * r.y - l.y * r.x, }; return size_cast<T>(value); } inline float Dot4(const float *row, const float *col, int step = 1) { auto i = 0; auto a = row[0] * col[i]; i += step; auto b = row[1] * col[i]; i += step; auto c = row[2] * col[i]; i += step; auto d = row[3] * col[i]; auto value = a + b + c + d; return value; } template <typename M, typename T> float3 RowMatrixApplyPosition(const M &_m, const T &_t) { auto m = size_cast<row_matrix>(_m); auto &t = size_cast<xyz>(_t); std::array<float, 4> v = {t.x, t.y, t.z, 1}; return {Dot4(v.data(), &m._11, 4), Dot4(v.data(), &m._12, 4), Dot4(v.data(), &m._13, 4)}; } // inline std::array<float, 16> RowMatrixMul(const std::array<float, 16> &l, const std::array<float, 16> &r) { auto _11 = Dot4(&l[0], &r[0], 4); auto _12 = Dot4(&l[0], &r[1], 4); auto _13 = Dot4(&l[0], &r[2], 4); auto _14 = Dot4(&l[0], &r[3], 4); auto _21 = Dot4(&l[4], &r[0], 4); auto _22 = Dot4(&l[4], &r[1], 4); auto _23 = Dot4(&l[4], &r[2], 4); auto _24 = Dot4(&l[4], &r[3], 4); auto _31 = Dot4(&l[8], &r[0], 4); auto _32 = Dot4(&l[8], &r[1], 4); auto _33 = Dot4(&l[8], &r[2], 4); auto _34 = Dot4(&l[8], &r[3], 4); auto _41 = Dot4(&l[12], &r[0], 4); auto _42 = Dot4(&l[12], &r[1], 4); auto _43 = Dot4(&l[12], &r[2], 4); auto _44 = Dot4(&l[12], &r[3], 4); return std::array<float, 16>{ _11, _12, _13, _14, _21, _22, _23, _24, _31, _32, _33, _34, _41, _42, _43, _44, }; } } // namespace falg namespace std { inline falg::float16 operator*(const falg::float16 &lhs, const falg::float16 &rhs) { return falg::RowMatrixMul(lhs, rhs); } } // namespace std namespace falg { inline void Transpose(std::array<float, 16> &m) { std::swap(m[1], m[4]); std::swap(m[2], m[8]); std::swap(m[3], m[12]); std::swap(m[6], m[9]); std::swap(m[7], m[13]); std::swap(m[11], m[14]); } inline std::array<float, 16> IdentityMatrix() { return std::array<float, 16>{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, }; } inline std::array<float, 16> YawMatrix(float yawRadians) { auto ys = (float)sin(yawRadians); auto yc = (float)cos(yawRadians); std::array<float, 16> yaw = { yc, 0, ys, 0, 0, 1, 0, 0, -ys, 0, yc, 0, 0, 0, 0, 1, }; return yaw; } inline std::array<float, 16> PitchMatrix(float pitchRadians) { auto ps = (float)sin(pitchRadians); auto pc = (float)cos(pitchRadians); std::array<float, 16> pitch = { 1, 0, 0, 0, 0, pc, ps, 0, 0, -ps, pc, 0, 0, 0, 0, 1, }; return pitch; } inline std::array<float, 16> TranslationMatrix(float x, float y, float z) { std::array<float, 16> t = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1, }; return t; } inline double Cot(double value) { return 1.0f / tan(value); } inline void PerspectiveRHGL(float projection[16], float fovYRadians, float aspectRatio, float zNear, float zFar) { const float f = static_cast<float>(Cot(fovYRadians / 2.0)); projection[0] = f / aspectRatio; projection[1] = 0.0f; projection[2] = 0.0f; projection[3] = 0.0f; projection[4] = 0.0f; projection[5] = f; projection[6] = 0.0f; projection[7] = 0.0f; projection[8] = 0.0f; projection[9] = 0.0f; projection[10] = (zNear + zFar) / (zNear - zFar); projection[11] = -1; projection[12] = 0.0f; projection[13] = 0.0f; projection[14] = (2 * zFar * zNear) / (zNear - zFar); projection[15] = 0.0f; } inline void PerspectiveRHDX(float projection[16], float fovYRadians, float aspectRatio, float zNear, float zFar) { auto yScale = (float)Cot(fovYRadians / 2); auto xScale = yScale / aspectRatio; projection[0] = xScale; projection[1] = 0.0f; projection[2] = 0.0f; projection[3] = 0.0f; projection[4] = 0.0f; projection[5] = yScale; projection[6] = 0.0f; projection[7] = 0.0f; projection[8] = 0.0f; projection[9] = 0.0f; projection[10] = zFar / (zNear - zFar); projection[11] = -1; projection[12] = 0.0f; projection[13] = 0.0f; projection[14] = (zFar * zNear) / (zNear - zFar); projection[15] = 0.0f; } inline float4 QuaternionAxisAngle(const float3 &axis, float angle) { auto angle_half = angle / 2; auto sin = std::sin(angle_half); auto cos = std::cos(angle_half); return {axis[0] * sin, axis[1] * sin, axis[2] * sin, cos}; } // inline float4 QuaternionMul(const float4 &lhs, const float4 &rhs) // { // return {lhs[0] * rhs[3] + lhs[3] * rhs[0] + lhs[1] * rhs[2] - lhs[2] * // rhs[1], // lhs[1] * rhs[3] + lhs[3] * rhs[1] + lhs[2] * rhs[0] - lhs[0] * // rhs[2], lhs[2] * rhs[3] + lhs[3] * rhs[2] + lhs[0] * rhs[1] - // lhs[1] * rhs[0], lhs[3] * rhs[3] - lhs[0] * rhs[0] - lhs[1] * // rhs[1] - lhs[2] * rhs[2]}; // } template <typename T> inline float4 QuaternionMul(const T &l, T r) { if (Dot(l, r) < 0) { r = {-r[0], -r[1], -r[2], -r[3]}; } const auto &lhs = size_cast<xyzw>(l); const auto &rhs = size_cast<xyzw>(r); return {rhs.x * lhs.w + rhs.w * lhs.x + rhs.y * lhs.z - rhs.z * lhs.y, rhs.y * lhs.w + rhs.w * lhs.y + rhs.z * lhs.x - rhs.x * lhs.z, rhs.z * lhs.w + rhs.w * lhs.z + rhs.x * lhs.y - rhs.y * lhs.x, rhs.w * lhs.w - rhs.x * lhs.x - rhs.y * lhs.y - rhs.z * lhs.z}; } // inline float4 operator*(const float4 &lhs, const float4 &rhs) // { // float ax = lhs[0]; // float ay = lhs[1]; // float az = lhs[2]; // float aw = lhs[3]; // float bx = rhs[0]; // float by = rhs[1]; // float bz = rhs[2]; // float bw = rhs[3]; // return { // ax * bw + aw * bx + ay * bz - az * by, // ay * bw + aw * by + az * bx - ax * bz, // az * bw + aw * bz + ax * by - ay * bx, // aw * bw - ax * bx - ay * by - az * bz, // }; // } inline float4 QuaternionConjugate(const float4 &v) { return {-v[0], -v[1], -v[2], v[3]}; } inline float3 QuaternionXDir(const float4 &v) { auto x = v[0]; auto y = v[1]; auto z = v[2]; auto w = v[3]; return {w * w + x * x - y * y - z * z, (x * y + z * w) * 2, (z * x - y * w) * 2}; } inline float3 QuaternionYDir(const float4 &v) { auto x = v[0]; auto y = v[1]; auto z = v[2]; auto w = v[3]; return {(x * y - z * w) * 2, w * w - x * x + y * y - z * z, (y * z + x * w) * 2}; } inline float3 QuaternionZDir(const float4 &v) { auto x = v[0]; auto y = v[1]; auto z = v[2]; auto w = v[3]; return {(z * x + y * w) * 2, (y * z - x * w) * 2, w * w - x * x - y * y + z * z}; } inline std::array<float, 16> QuaternionMatrix(const float4 &q) { auto x = QuaternionXDir(q); auto y = QuaternionYDir(q); auto z = QuaternionZDir(q); return {x[0], x[1], x[2], 0, y[0], y[1], y[2], 0, z[0], z[1], z[2], 0, 0, 0, 0, 1}; } inline std::array<float, 16> ScaleMatrix(const float3 &s) { return {s[0], 0, 0, 0, 0, s[1], 0, 0, 0, 0, s[2], 0, 0, 0, 0, 1}; } inline std::array<float, 16> ScaleMatrix(float x, float y, float z) { return ScaleMatrix({x, y, z}); } inline float3 QuaternionRotateFloat3(const float4 &q, const float3 &v) { auto x = QuaternionXDir(q); auto y = QuaternionYDir(q); auto z = QuaternionZDir(q); return Add(MulScalar(x, v[0]), Add(MulScalar(y, v[1]), MulScalar(z, v[2]))); } struct Transform { float3 translation{0, 0, 0}; float4 rotation{0, 0, 0, 1}; Transform operator*(const Transform &rhs) const { return { Add(QuaternionRotateFloat3(rhs.rotation, translation), rhs.translation), QuaternionMul(rotation, rhs.rotation)}; } std::array<float, 16> RowMatrix() const { auto r = QuaternionMatrix(rotation); r[12] = translation[0]; r[13] = translation[1]; r[14] = translation[2]; return r; } Transform Inverse() const { auto inv_r = QuaternionConjugate(rotation); auto inv_t = QuaternionRotateFloat3(inv_r, MulScalar(translation, -1)); return {inv_t, inv_r}; } float3 ApplyPosition(const float3 &v) const { return Add(QuaternionRotateFloat3(rotation, v), translation); } float3 ApplyDirection(const float3 &v) const { return QuaternionRotateFloat3(rotation, v); } }; struct TRS { union { Transform transform; struct { float3 translation; float4 rotation; }; }; float3 scale; TRS() : translation({0, 0, 0}), rotation({0, 0, 0, 1}), scale({1, 1, 1}) {} TRS(const float3 &t, const float4 &r, const float3 &s) : translation(t), rotation(r), scale(s) {} std::array<float, 16> RowMatrix() const { return ScaleMatrix(scale) * transform.RowMatrix(); } }; static_assert(sizeof(TRS) == 40, "TRS"); template <typename T> std::array<float, 4> RowMatrixToQuaternion(const T &m); template <typename T> TRS RowMatrixDecompose(const T &_m) { auto &m = size_cast<row_matrix>(_m); auto s1 = Length(float3{m._11, m._12, m._13}); auto s2 = Length(float3{m._21, m._22, m._23}); auto s3 = Length(float3{m._31, m._32, m._33}); TRS trs({m._41, m._42, m._43}, RowMatrixToQuaternion(_m), {s1, s2, s3}); return trs; } struct Ray { float3 origin; float3 direction; Ray(const float3 &_origin, const float3 &_direction) : origin(_origin), direction(_direction) {} template <typename T> Ray(const T &t) { static_assert(sizeof(T) == sizeof(Ray), "Ray::Ray()"); auto &ray = size_cast<Ray>(t); origin = ray.origin; direction = ray.direction; } Ray ToLocal(const falg::Transform &t) const { auto toLocal = t.Inverse(); return {toLocal.ApplyPosition(origin), falg::QuaternionRotateFloat3(toLocal.rotation, direction)}; } float3 SetT(float t) const { return Add(origin, MulScalar(direction, t)); } Ray Transform(const falg::Transform &t) const { return { t.ApplyPosition(origin), t.ApplyDirection(direction), }; } }; struct Plane { float3 normal; float3 pointOnPlane; Plane(const float3 &n, const float3 &point_on_plane) : normal(n), pointOnPlane(point_on_plane) {} }; inline float operator>>(const Ray &ray, const Plane &plane) { auto NV = Dot(plane.normal, ray.direction); if (NV == 0) { // not intersect return -std::numeric_limits<float>::infinity(); } auto Q = Sub(plane.pointOnPlane, ray.origin); auto NQ = Dot(plane.normal, Q); return NQ / NV; } struct Triangle { float3 v0; float3 v1; float3 v2; }; // float intersect_ray_triangle(const ray &ray, const minalg::float3 &v0, const // minalg::float3 &v1, const minalg::float3 &v2) inline float operator>>(const Ray &ray, const Triangle &triangle) { auto e1 = Sub(triangle.v1, triangle.v0); auto e2 = Sub(triangle.v2, triangle.v0); auto h = Cross(ray.direction, e2); auto a = Dot(e1, h); if (std::abs(a) == 0) return std::numeric_limits<float>::infinity(); float f = 1 / a; auto s = Sub(ray.origin, triangle.v0); auto u = f * Dot(s, h); if (u < 0 || u > 1) return std::numeric_limits<float>::infinity(); auto q = Cross(s, e1); auto v = f * Dot(ray.direction, q); if (v < 0 || u + v > 1) return std::numeric_limits<float>::infinity(); auto t = f * Dot(e2, q); if (t < 0) return std::numeric_limits<float>::infinity(); return t; } struct Matrix2x3 { float3 x; float3 y; float3 Apply(const float2 &value) const { return { x[0] * value[0] + y[0] * value[1], x[1] * value[0] + y[1] * value[1], x[2] * value[0] + y[2] * value[1], }; } }; struct m16 { float _11, _12, _13, _14; float _21, _22, _23, _24; float _31, _32, _33, _34; float _41, _42, _43, _44; }; inline std::array<float, 3> MatrixToTranslation(const m16 &m) { return {m._41, m._42, m._43}; } template <typename T> std::array<float, 3> MatrixToTranslation(const T &m) { return MatrixToTranslation(size_cast<m16>(m)); } inline std::array<float, 4> ColMatrixToQuaternion(const m16 &m) { float x, y, z, w; float trace = m._11 + m._22 + m._33; // I removed + 1.0f; see discussion with Ethan if (trace > 0) { // I changed M_EPSILON to 0 float s = 0.5f / sqrtf(trace + 1.0f); w = 0.25f / s; x = (m._32 - m._23) * s; y = (m._13 - m._31) * s; z = (m._21 - m._12) * s; } else { if (m._11 > m._22 && m._22 > m._33) { float s = 2.0f * sqrtf(1.0f + m._11 - m._22 - m._33); w = (m._32 - m._23) / s; x = 0.25f * s; y = (m._12 + m._21) / s; z = (m._13 + m._31) / s; } else if (m._22 > m._33) { float s = 2.0f * sqrtf(1.0f + m._22 - m._11 - m._33); w = (m._13 - m._31) / s; x = (m._12 + m._21) / s; y = 0.25f * s; z = (m._23 + m._32) / s; } else { float s = 2.0f * sqrtf(1.0f + m._33 - m._11 - m._22); w = (m._21 - m._12) / s; x = (m._13 + m._31) / s; y = (m._23 + m._32) / s; z = 0.25f * s; } } return {x, y, z, w}; } template <typename T> std::array<float, 4> ColMatrixToQuaternion(const T &m) { return ColMatrixToQuaternion(size_cast<m16>(m)); } template <typename T> std::array<float, 4> RowMatrixToQuaternion(const T &m) { return QuaternionConjugate(ColMatrixToQuaternion(size_cast<m16>(m))); } } // namespace falg ///////////////////////////////////////////////////////////////////////////// // std ///////////////////////////////////////////////////////////////////////////// namespace std { // for std::array inline falg::float3 operator-(const falg::float3 &lhs) { return {-lhs[0], -lhs[1], -lhs[2]}; } inline falg::float3 operator+(const falg::float3 &lhs, const falg::float3 &rhs) { return {lhs[0] + rhs[0], lhs[1] + rhs[1], lhs[2] + rhs[2]}; } inline falg::float3 &operator+=(falg::float3 &lhs, const falg::float3 &rhs) { lhs[0] += rhs[0]; lhs[1] += rhs[1]; lhs[2] += rhs[2]; return lhs; } inline falg::float3 operator-(const falg::float3 &lhs, const falg::float3 &rhs) { return {lhs[0] - rhs[0], lhs[1] - rhs[1], lhs[2] - rhs[2]}; } inline falg::float3 operator*(const falg::float3 &lhs, float scalar) { return {lhs[0] * scalar, lhs[1] * scalar, lhs[2] * scalar}; } } // namespace std
1
high
release/src-rt-6.x.4708/linux/linux-2.6.36/arch/x86/include/asm/i387.h
afeng11/tomato-arm
4
5388880
<filename>release/src-rt-6.x.4708/linux/linux-2.6.36/arch/x86/include/asm/i387.h<gh_stars>1-10 /* * Copyright (C) 1994 <NAME> * * Pentium III FXSR, SSE support * General FPU state handling cleanups * <NAME> <<EMAIL>>, May 2000 * x86-64 work by <NAME> 2002 */ #ifndef _ASM_X86_I387_H #define _ASM_X86_I387_H #ifndef __ASSEMBLY__ #include <linux/sched.h> #include <linux/kernel_stat.h> #include <linux/regset.h> #include <linux/hardirq.h> #include <linux/slab.h> #include <asm/asm.h> #include <asm/cpufeature.h> #include <asm/processor.h> #include <asm/sigcontext.h> #include <asm/user.h> #include <asm/uaccess.h> #include <asm/xsave.h> extern unsigned int sig_xstate_size; extern void fpu_init(void); extern void mxcsr_feature_mask_init(void); extern int init_fpu(struct task_struct *child); extern asmlinkage void math_state_restore(void); extern void __math_state_restore(void); extern int dump_fpu(struct pt_regs *, struct user_i387_struct *); extern user_regset_active_fn fpregs_active, xfpregs_active; extern user_regset_get_fn fpregs_get, xfpregs_get, fpregs_soft_get, xstateregs_get; extern user_regset_set_fn fpregs_set, xfpregs_set, fpregs_soft_set, xstateregs_set; /* * xstateregs_active == fpregs_active. Please refer to the comment * at the definition of fpregs_active. */ #define xstateregs_active fpregs_active extern struct _fpx_sw_bytes fx_sw_reserved; #ifdef CONFIG_IA32_EMULATION extern unsigned int sig_xstate_ia32_size; extern struct _fpx_sw_bytes fx_sw_reserved_ia32; struct _fpstate_ia32; struct _xstate_ia32; extern int save_i387_xstate_ia32(void __user *buf); extern int restore_i387_xstate_ia32(void __user *buf); #endif #define X87_FSW_ES (1 << 7) /* Exception Summary */ static __always_inline __pure bool use_xsaveopt(void) { return static_cpu_has(X86_FEATURE_XSAVEOPT); } static __always_inline __pure bool use_xsave(void) { return static_cpu_has(X86_FEATURE_XSAVE); } extern void __sanitize_i387_state(struct task_struct *); static inline void sanitize_i387_state(struct task_struct *tsk) { if (!use_xsaveopt()) return; __sanitize_i387_state(tsk); } #ifdef CONFIG_X86_64 /* Ignore delayed exceptions from user space */ static inline void tolerant_fwait(void) { asm volatile("1: fwait\n" "2:\n" _ASM_EXTABLE(1b, 2b)); } static inline int fxrstor_checking(struct i387_fxsave_struct *fx) { int err; asm volatile("1: rex64/fxrstor (%[fx])\n\t" "2:\n" ".section .fixup,\"ax\"\n" "3: movl $-1,%[err]\n" " jmp 2b\n" ".previous\n" _ASM_EXTABLE(1b, 3b) : [err] "=r" (err) : [fx] "cdaSDb" (fx), "m" (*fx), "0" (0)); return err; } /* AMD CPUs don't save/restore FDP/FIP/FOP unless an exception is pending. Clear the x87 state here by setting it to fixed values. The kernel data segment can be sometimes 0 and sometimes new user value. Both should be ok. Use the PDA as safe address because it should be already in L1. */ static inline void fpu_clear(struct fpu *fpu) { struct xsave_struct *xstate = &fpu->state->xsave; struct i387_fxsave_struct *fx = &fpu->state->fxsave; /* * xsave header may indicate the init state of the FP. */ if (use_xsave() && !(xstate->xsave_hdr.xstate_bv & XSTATE_FP)) return; if (unlikely(fx->swd & X87_FSW_ES)) asm volatile("fnclex"); alternative_input(ASM_NOP8 ASM_NOP2, " emms\n" /* clear stack tags */ " fildl %%gs:0", /* load to clear state */ X86_FEATURE_FXSAVE_LEAK); } static inline void clear_fpu_state(struct task_struct *tsk) { fpu_clear(&tsk->thread.fpu); } static inline int fxsave_user(struct i387_fxsave_struct __user *fx) { int err; /* * Clear the bytes not touched by the fxsave and reserved * for the SW usage. */ err = __clear_user(&fx->sw_reserved, sizeof(struct _fpx_sw_bytes)); if (unlikely(err)) return -EFAULT; asm volatile("1: rex64/fxsave (%[fx])\n\t" "2:\n" ".section .fixup,\"ax\"\n" "3: movl $-1,%[err]\n" " jmp 2b\n" ".previous\n" _ASM_EXTABLE(1b, 3b) : [err] "=r" (err), "=m" (*fx) : [fx] "cdaSDb" (fx), "0" (0)); if (unlikely(err) && __clear_user(fx, sizeof(struct i387_fxsave_struct))) err = -EFAULT; /* No need to clear here because the caller clears USED_MATH */ return err; } static inline void fpu_fxsave(struct fpu *fpu) { /* Using "rex64; fxsave %0" is broken because, if the memory operand uses any extended registers for addressing, a second REX prefix will be generated (to the assembler, rex64 followed by semicolon is a separate instruction), and hence the 64-bitness is lost. */ __asm__ __volatile__("rex64/fxsave (%1)" : "=m" (fpu->state->fxsave) : "cdaSDb" (&fpu->state->fxsave)); } static inline void fpu_save_init(struct fpu *fpu) { if (use_xsave()) fpu_xsave(fpu); else fpu_fxsave(fpu); fpu_clear(fpu); } static inline void __save_init_fpu(struct task_struct *tsk) { fpu_save_init(&tsk->thread.fpu); task_thread_info(tsk)->status &= ~TS_USEDFPU; } #else /* CONFIG_X86_32 */ #ifdef CONFIG_MATH_EMULATION extern void finit_soft_fpu(struct i387_soft_struct *soft); #else static inline void finit_soft_fpu(struct i387_soft_struct *soft) {} #endif static inline void tolerant_fwait(void) { asm volatile("fnclex ; fwait"); } /* perform fxrstor iff the processor has extended states, otherwise frstor */ static inline int fxrstor_checking(struct i387_fxsave_struct *fx) { /* * The "nop" is needed to make the instructions the same * length. */ alternative_input( "nop ; frstor %1", "fxrstor %1", X86_FEATURE_FXSR, "m" (*fx)); return 0; } /* We need a safe address that is cheap to find and that is already in L1 during context switch. The best choices are unfortunately different for UP and SMP */ #ifdef CONFIG_SMP #define safe_address (__per_cpu_offset[0]) #else #define safe_address (kstat_cpu(0).cpustat.user) #endif /* * These must be called with preempt disabled */ static inline void fpu_save_init(struct fpu *fpu) { if (use_xsave()) { struct xsave_struct *xstate = &fpu->state->xsave; struct i387_fxsave_struct *fx = &fpu->state->fxsave; fpu_xsave(fpu); /* * xsave header may indicate the init state of the FP. */ if (!(xstate->xsave_hdr.xstate_bv & XSTATE_FP)) goto end; if (unlikely(fx->swd & X87_FSW_ES)) asm volatile("fnclex"); /* * we can do a simple return here or be paranoid :) */ goto clear_state; } /* Use more nops than strictly needed in case the compiler varies code */ alternative_input( "fnsave %[fx] ;fwait;" GENERIC_NOP8 GENERIC_NOP4, "fxsave %[fx]\n" "bt $7,%[fsw] ; jnc 1f ; fnclex\n1:", X86_FEATURE_FXSR, [fx] "m" (fpu->state->fxsave), [fsw] "m" (fpu->state->fxsave.swd) : "memory"); clear_state: /* AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception is pending. Clear the x87 state here by setting it to fixed values. safe_address is a random variable that should be in L1 */ alternative_input( GENERIC_NOP8 GENERIC_NOP2, "emms\n\t" /* clear stack tags */ "fildl %[addr]", /* set F?P to defined value */ X86_FEATURE_FXSAVE_LEAK, [addr] "m" (safe_address)); end: ; } static inline void __save_init_fpu(struct task_struct *tsk) { fpu_save_init(&tsk->thread.fpu); task_thread_info(tsk)->status &= ~TS_USEDFPU; } #endif /* CONFIG_X86_64 */ static inline int fpu_fxrstor_checking(struct fpu *fpu) { return fxrstor_checking(&fpu->state->fxsave); } static inline int fpu_restore_checking(struct fpu *fpu) { if (use_xsave()) return fpu_xrstor_checking(fpu); else return fpu_fxrstor_checking(fpu); } static inline int restore_fpu_checking(struct task_struct *tsk) { return fpu_restore_checking(&tsk->thread.fpu); } /* * Signal frame handlers... */ extern int save_i387_xstate(void __user *buf); extern int restore_i387_xstate(void __user *buf); static inline void __unlazy_fpu(struct task_struct *tsk) { if (task_thread_info(tsk)->status & TS_USEDFPU) { __save_init_fpu(tsk); stts(); } else tsk->fpu_counter = 0; } static inline void __clear_fpu(struct task_struct *tsk) { if (task_thread_info(tsk)->status & TS_USEDFPU) { tolerant_fwait(); task_thread_info(tsk)->status &= ~TS_USEDFPU; stts(); } } static inline void kernel_fpu_begin(void) { struct thread_info *me = current_thread_info(); preempt_disable(); if (me->status & TS_USEDFPU) __save_init_fpu(me->task); else clts(); } static inline void kernel_fpu_end(void) { stts(); preempt_enable(); } static inline bool irq_fpu_usable(void) { struct pt_regs *regs; return !in_interrupt() || !(regs = get_irq_regs()) || \ user_mode(regs) || (read_cr0() & X86_CR0_TS); } /* * Some instructions like VIA's padlock instructions generate a spurious * DNA fault but don't modify SSE registers. And these instructions * get used from interrupt context as well. To prevent these kernel instructions * in interrupt context interacting wrongly with other user/kernel fpu usage, we * should use them only in the context of irq_ts_save/restore() */ static inline int irq_ts_save(void) { /* * If in process context and not atomic, we can take a spurious DNA fault. * Otherwise, doing clts() in process context requires disabling preemption * or some heavy lifting like kernel_fpu_begin() */ if (!in_atomic()) return 0; if (read_cr0() & X86_CR0_TS) { clts(); return 1; } return 0; } static inline void irq_ts_restore(int TS_state) { if (TS_state) stts(); } #ifdef CONFIG_X86_64 static inline void save_init_fpu(struct task_struct *tsk) { __save_init_fpu(tsk); stts(); } #define unlazy_fpu __unlazy_fpu #define clear_fpu __clear_fpu #else /* CONFIG_X86_32 */ /* * These disable preemption on their own and are safe */ static inline void save_init_fpu(struct task_struct *tsk) { preempt_disable(); __save_init_fpu(tsk); stts(); preempt_enable(); } static inline void unlazy_fpu(struct task_struct *tsk) { preempt_disable(); __unlazy_fpu(tsk); preempt_enable(); } static inline void clear_fpu(struct task_struct *tsk) { preempt_disable(); __clear_fpu(tsk); preempt_enable(); } #endif /* CONFIG_X86_64 */ /* * i387 state interaction */ static inline unsigned short get_fpu_cwd(struct task_struct *tsk) { if (cpu_has_fxsr) { return tsk->thread.fpu.state->fxsave.cwd; } else { return (unsigned short)tsk->thread.fpu.state->fsave.cwd; } } static inline unsigned short get_fpu_swd(struct task_struct *tsk) { if (cpu_has_fxsr) { return tsk->thread.fpu.state->fxsave.swd; } else { return (unsigned short)tsk->thread.fpu.state->fsave.swd; } } static inline unsigned short get_fpu_mxcsr(struct task_struct *tsk) { if (cpu_has_xmm) { return tsk->thread.fpu.state->fxsave.mxcsr; } else { return MXCSR_DEFAULT; } } static bool fpu_allocated(struct fpu *fpu) { return fpu->state != NULL; } static inline int fpu_alloc(struct fpu *fpu) { if (fpu_allocated(fpu)) return 0; fpu->state = kmem_cache_alloc(task_xstate_cachep, GFP_KERNEL); if (!fpu->state) return -ENOMEM; WARN_ON((unsigned long)fpu->state & 15); return 0; } static inline void fpu_free(struct fpu *fpu) { if (fpu->state) { kmem_cache_free(task_xstate_cachep, fpu->state); fpu->state = NULL; } } static inline void fpu_copy(struct fpu *dst, struct fpu *src) { memcpy(dst->state, src->state, xstate_size); } extern void fpu_finit(struct fpu *fpu); #endif /* __ASSEMBLY__ */ #define PSHUFB_XMM5_XMM0 .byte 0x66, 0x0f, 0x38, 0x00, 0xc5 #define PSHUFB_XMM5_XMM6 .byte 0x66, 0x0f, 0x38, 0x00, 0xf5 #endif /* _ASM_X86_I387_H */
0.992188
high
bin/varnishd/storage/storage_persistent_silo.c
konstantin-f/varnish-cache
0
685001
<filename>bin/varnishd/storage/storage_persistent_silo.c<gh_stars>0 /*- * Copyright (c) 2008-2011 Varnish Software AS * All rights reserved. * * Author: <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Persistent storage method * * XXX: Before we start the client or maybe after it stops, we should give the * XXX: stevedores a chance to examine their storage for consistency. * */ #include "config.h" #include "cache/cache.h" #include <stdio.h> #include <stdlib.h> #include "storage/storage.h" #include "storage/storage_simple.h" #include "hash/hash_slinger.h" #include "vsha256.h" #include "vend.h" #include "vtim.h" #include "storage/storage_persistent.h" /* * We use the top bit to mark objects still needing fixup * In theory this may need to be platform dependent */ #define NEED_FIXUP (1U << 31) /*-------------------------------------------------------------------- * Write the segmentlist back to the silo. * * We write the first copy, sync it synchronously, then write the * second copy and sync it synchronously. * * Provided the kernel doesn't lie, that means we will always have * at least one valid copy on in the silo. */ static void smp_save_seg(const struct smp_sc *sc, struct smp_signspace *spc) { struct smp_segptr *ss; struct smp_seg *sg; uint64_t length; Lck_AssertHeld(&sc->mtx); smp_reset_signspace(spc); ss = SIGNSPACE_DATA(spc); length = 0; VTAILQ_FOREACH(sg, &sc->segments, list) { assert(sg->p.offset < sc->mediasize); assert(sg->p.offset + sg->p.length <= sc->mediasize); *ss = sg->p; ss++; length += sizeof *ss; } smp_append_signspace(spc, length); smp_sync_sign(&spc->ctx); } void smp_save_segs(struct smp_sc *sc) { struct smp_seg *sg, *sg2; Lck_AssertHeld(&sc->mtx); /* * Remove empty segments from the front of the list * before we write the segments to disk. */ VTAILQ_FOREACH_SAFE(sg, &sc->segments, list, sg2) { if (sg->nobj > 0) break; if (sg == sc->cur_seg) continue; VTAILQ_REMOVE(&sc->segments, sg, list); AN(VTAILQ_EMPTY(&sg->objcores)); FREE_OBJ(sg); } smp_save_seg(sc, &sc->seg1); smp_save_seg(sc, &sc->seg2); } /*-------------------------------------------------------------------- * Load segments * * The overall objective is to register the existence of an object, based * only on the minimally sized struct smp_object, without causing the * main object to be faulted in. * * XXX: We can test this by mprotecting the main body of the segment * XXX: until the first fixup happens, or even just over this loop, * XXX: However: the requires that the smp_objects starter further * XXX: into the segment than a page so that they do not get hit * XXX: by the protection. */ void smp_load_seg(struct worker *wrk, const struct smp_sc *sc, struct smp_seg *sg) { struct smp_object *so; struct objcore *oc; struct ban *ban; uint32_t no; double t_now = VTIM_real(); struct smp_signctx ctx[1]; ASSERT_SILO_THREAD(sc); CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(sg, SMP_SEG_MAGIC); assert(sg->flags & SMP_SEG_MUSTLOAD); sg->flags &= ~SMP_SEG_MUSTLOAD; AN(sg->p.offset); if (sg->p.objlist == 0) return; smp_def_sign(sc, ctx, sg->p.offset, "SEGHEAD"); if (smp_chk_sign(ctx)) return; /* test SEGTAIL */ /* test OBJIDX */ so = (void*)(sc->base + sg->p.objlist); sg->objs = so; no = sg->p.lobjlist; /* Clear the bogus "hold" count */ sg->nobj = 0; for (;no > 0; so++,no--) { if (EXP_WHEN(so) < t_now) continue; ban = BAN_FindBan(so->ban); AN(ban); oc = ObjNew(wrk); oc->stobj->stevedore = sc->parent; smp_init_oc(oc, sg, no); VTAILQ_INSERT_TAIL(&sg->objcores, oc, lru_list); oc->stobj->priv2 |= NEED_FIXUP; EXP_COPY(oc, so); sg->nobj++; oc->refcnt++; HSH_Insert(wrk, so->hash, oc, ban); AN(oc->ban); HSH_DerefBoc(wrk, oc); // XXX Keep it an stream resurrection? (void)HSH_DerefObjCore(wrk, &oc, HSH_RUSH_POLICY); wrk->stats->n_vampireobject++; } Pool_Sumstat(wrk); sg->flags |= SMP_SEG_LOADED; } /*-------------------------------------------------------------------- * Create a new segment */ void smp_new_seg(struct smp_sc *sc) { struct smp_seg tmpsg; struct smp_seg *sg; AZ(sc->cur_seg); Lck_AssertHeld(&sc->mtx); /* XXX: find where it goes in silo */ INIT_OBJ(&tmpsg, SMP_SEG_MAGIC); tmpsg.sc = sc; tmpsg.p.offset = sc->free_offset; /* XXX: align */ assert(tmpsg.p.offset >= sc->ident->stuff[SMP_SPC_STUFF]); assert(tmpsg.p.offset < sc->mediasize); tmpsg.p.length = sc->aim_segl; tmpsg.p.length = RDN2(tmpsg.p.length, 8); if (smp_segend(&tmpsg) > sc->mediasize) /* XXX: Consider truncation in this case */ tmpsg.p.offset = sc->ident->stuff[SMP_SPC_STUFF]; assert(smp_segend(&tmpsg) <= sc->mediasize); sg = VTAILQ_FIRST(&sc->segments); if (sg != NULL && tmpsg.p.offset <= sg->p.offset) { if (smp_segend(&tmpsg) > sg->p.offset) /* No more space, return (cur_seg will be NULL) */ /* XXX: Consider truncation instead of failing */ return; assert(smp_segend(&tmpsg) <= sg->p.offset); } if (tmpsg.p.offset == sc->ident->stuff[SMP_SPC_STUFF]) printf("Wrapped silo\n"); ALLOC_OBJ(sg, SMP_SEG_MAGIC); if (sg == NULL) return; *sg = tmpsg; VTAILQ_INIT(&sg->objcores); sg->p.offset = IRNUP(sc, sg->p.offset); sg->p.length -= sg->p.offset - tmpsg.p.offset; sg->p.length = IRNDN(sc, sg->p.length); assert(sg->p.offset + sg->p.length <= tmpsg.p.offset + tmpsg.p.length); sc->free_offset = sg->p.offset + sg->p.length; VTAILQ_INSERT_TAIL(&sc->segments, sg, list); /* Neuter the new segment in case there is an old one there */ AN(sg->p.offset); smp_def_sign(sc, sg->ctx, sg->p.offset, "SEGHEAD"); smp_reset_sign(sg->ctx); smp_sync_sign(sg->ctx); /* Set up our allocation points */ sc->cur_seg = sg; sc->next_bot = sg->p.offset + IRNUP(sc, SMP_SIGN_SPACE); sc->next_top = smp_segend(sg); sc->next_top -= IRNUP(sc, SMP_SIGN_SPACE); IASSERTALIGN(sc, sc->next_bot); IASSERTALIGN(sc, sc->next_top); sg->objs = (void*)(sc->base + sc->next_top); } /*-------------------------------------------------------------------- * Close a segment */ void smp_close_seg(struct smp_sc *sc, struct smp_seg *sg) { uint64_t left, dst, len; void *dp; Lck_AssertHeld(&sc->mtx); CHECK_OBJ_NOTNULL(sg, SMP_SEG_MAGIC); assert(sg == sc->cur_seg); AN(sg->p.offset); sc->cur_seg = NULL; if (sg->nalloc == 0) { /* If segment is empty, delete instead */ VTAILQ_REMOVE(&sc->segments, sg, list); assert(sg->p.offset >= sc->ident->stuff[SMP_SPC_STUFF]); assert(sg->p.offset < sc->mediasize); sc->free_offset = sg->p.offset; AN(VTAILQ_EMPTY(&sg->objcores)); FREE_OBJ(sg); return; } /* * If there is enough space left, that we can move the smp_objects * down without overwriting the present copy, we will do so to * compact the segment. */ left = smp_spaceleft(sc, sg); len = sizeof(struct smp_object) * sg->p.lobjlist; if (len < left) { dst = sc->next_bot + IRNUP(sc, SMP_SIGN_SPACE); dp = sc->base + dst; assert((uintptr_t)dp + len < (uintptr_t)sg->objs); memcpy(dp, sg->objs, len); sc->next_top = dst; sg->objs = dp; sg->p.length = (sc->next_top - sg->p.offset) + len + IRNUP(sc, SMP_SIGN_SPACE); (void)smp_spaceleft(sc, sg); /* for the asserts */ } /* Update the segment header */ sg->p.objlist = sc->next_top; /* Write the (empty) OBJIDX signature */ sc->next_top -= IRNUP(sc, SMP_SIGN_SPACE); assert(sc->next_top >= sc->next_bot); smp_def_sign(sc, sg->ctx, sc->next_top, "OBJIDX"); smp_reset_sign(sg->ctx); smp_sync_sign(sg->ctx); /* Write the (empty) SEGTAIL signature */ smp_def_sign(sc, sg->ctx, sg->p.offset + sg->p.length - IRNUP(sc, SMP_SIGN_SPACE), "SEGTAIL"); smp_reset_sign(sg->ctx); smp_sync_sign(sg->ctx); /* Save segment list */ smp_save_segs(sc); sc->free_offset = smp_segend(sg); } /*--------------------------------------------------------------------- */ static struct smp_object * smp_find_so(const struct smp_seg *sg, unsigned priv2) { struct smp_object *so; priv2 &= ~NEED_FIXUP; assert(priv2 > 0); assert(priv2 <= sg->p.lobjlist); so = &sg->objs[sg->p.lobjlist - priv2]; return (so); } /*--------------------------------------------------------------------- * Check if a given storage structure is valid to use */ static int smp_loaded_st(const struct smp_sc *sc, const struct smp_seg *sg, const struct storage *st) { struct smp_seg *sg2; const uint8_t *pst; uint64_t o; (void)sg; /* XXX: faster: Start search from here */ pst = (const void *)st; if (pst < (sc->base + sc->ident->stuff[SMP_SPC_STUFF])) return (0x01); /* Before silo payload start */ if (pst > (sc->base + sc->ident->stuff[SMP_END_STUFF])) return (0x02); /* After silo end */ o = pst - sc->base; /* Find which segment contains the storage structure */ VTAILQ_FOREACH(sg2, &sc->segments, list) if (o > sg2->p.offset && (o + sizeof(*st)) < sg2->p.objlist) break; if (sg2 == NULL) return (0x04); /* No claiming segment */ if (!(sg2->flags & SMP_SEG_LOADED)) return (0x08); /* Claiming segment not loaded */ /* It is now safe to access the storage structure */ if (st->magic != STORAGE_MAGIC) return (0x10); /* Not enough magic */ if (o + st->space >= sg2->p.objlist) return (0x20); /* Allocation not inside segment */ if (st->len > st->space) return (0x40); /* Plain bad... */ /* * XXX: We could patch up st->stevedore and st->priv here * XXX: but if things go right, we will never need them. */ return (0); } /*--------------------------------------------------------------------- * objcore methods for persistent objects */ struct object * __match_proto__(sml_getobj_f) smp_sml_getobj(struct worker *wrk, struct objcore *oc) { struct object *o; struct smp_seg *sg; struct smp_object *so; struct storage *st; uint64_t l; int bad; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC); AN(oc->stobj->stevedore); CAST_OBJ_NOTNULL(sg, oc->stobj->priv, SMP_SEG_MAGIC); so = smp_find_so(sg, oc->stobj->priv2); o = (void*)(sg->sc->base + so->ptr); /* * The object may not be in this segment since we allocate it * In a separate operation than the smp_object. We could check * that it is in a later segment, but that would be complicated. * XXX: For now, be happy if it is inside the silo */ ASSERT_PTR_IN_SILO(sg->sc, o); CHECK_OBJ_NOTNULL(o, OBJECT_MAGIC); /* * If this flag is not set, it will not be, and the lock is not * needed to test it. */ if (!(oc->stobj->priv2 & NEED_FIXUP)) return (o); Lck_Lock(&sg->sc->mtx); /* Check again, we might have raced. */ if (oc->stobj->priv2 & NEED_FIXUP) { /* We trust caller to have a refcnt for us */ bad = 0; l = 0; VTAILQ_FOREACH(st, &o->list, list) { bad |= smp_loaded_st(sg->sc, sg, st); if (bad) break; l += st->len; } if (l != vbe64dec(o->fa_len)) bad |= 0x100; if (bad) { EXP_ZERO(oc); EXP_ZERO(so); } sg->nfixed++; wrk->stats->n_object++; wrk->stats->n_vampireobject--; oc->stobj->priv2 &= ~NEED_FIXUP; } Lck_Unlock(&sg->sc->mtx); return (o); } void __match_proto__(objfree_f) smp_oc_objfree(struct worker *wrk, struct objcore *oc) { struct smp_seg *sg; struct smp_object *so; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC); CAST_OBJ_NOTNULL(sg, oc->stobj->priv, SMP_SEG_MAGIC); so = smp_find_so(sg, oc->stobj->priv2); Lck_Lock(&sg->sc->mtx); EXP_ZERO(so); so->ptr = 0; assert(sg->nobj > 0); sg->nobj--; if (oc->stobj->priv2 & NEED_FIXUP) { wrk->stats->n_vampireobject--; } else { assert(sg->nfixed > 0); sg->nfixed--; wrk->stats->n_object--; } VTAILQ_REMOVE(&sg->objcores, oc, lru_list); Lck_Unlock(&sg->sc->mtx); memset(oc->stobj, 0, sizeof oc->stobj); } /*--------------------------------------------------------------------*/ void smp_init_oc(struct objcore *oc, struct smp_seg *sg, unsigned objidx) { AZ(objidx & NEED_FIXUP); oc->stobj->priv = sg; oc->stobj->priv2 = objidx; } /*--------------------------------------------------------------------*/ void __match_proto__(obj_event_f) smp_oc_event(struct worker *wrk, void *priv, struct objcore *oc, unsigned ev) { struct stevedore *st; struct smp_seg *sg; struct smp_object *so; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CAST_OBJ_NOTNULL(st, priv, STEVEDORE_MAGIC); CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC); if (oc->stobj->stevedore != st) return; CAST_OBJ_NOTNULL(sg, oc->stobj->priv, SMP_SEG_MAGIC); CHECK_OBJ_NOTNULL(sg->sc, SMP_SC_MAGIC); so = smp_find_so(sg, oc->stobj->priv2); if (sg == sg->sc->cur_seg) { /* Lock necessary, we might race close_seg */ Lck_Lock(&sg->sc->mtx); if (ev & (OEV_BANCHG|OEV_INSERT)) so->ban = BAN_Time(oc->ban); if (ev & (OEV_TTLCHG|OEV_INSERT)) EXP_COPY(so, oc); Lck_Unlock(&sg->sc->mtx); } else { if (ev & (OEV_BANCHG|OEV_INSERT)) so->ban = BAN_Time(oc->ban); if (ev & (OEV_TTLCHG|OEV_INSERT)) EXP_COPY(so, oc); } }
0.996094
high
src/memu/config.h
Memotech-Bill/MEMU
2
717769
<reponame>Memotech-Bill/MEMU /* config.h - Display a user interface for setting configuration options */ #ifndef H_CONFIG #define H_CONFIG #include "types.h" #include "win.h" #define WINCFG_WTH 80 #define WINCFG_HGT 24 #define STY_NORMAL 0 // ( 16 * CLR_NORMAL + CLR_BACKGROUND ) #define STY_HIGHLIGHT 1 // ( 16 * CLR_HIGHLIGHT + CLR_HIGHBACK ) #define STY_DISABLED 2 // ( 16 * CLR_DISABLED + CLR_BACKGROUND ) #define STY_HELP 3 // ( 16 * CLR_HELP + CLR_BACKGROUND ) #define STY_COUNT 4 // extern void config (void); extern void config (void); extern void config_set_file (const char *psFile); extern BOOLEAN test_cfg_key (int wk); extern BOOLEAN read_config (const char *psFile, int *pargc, const char ***pargv); extern BOOLEAN cfg_options (int *pargc, const char ***pargv, int *pi); extern void cfg_usage (void); extern void cfg_set_disk_dir (const char *psDir); extern BOOLEAN cfg_test_file (const char *psPath); extern char * cfg_find_file (const char *argv0); extern WIN * get_cfg_win (void); extern void cfg_keypress(int wk); extern void cfg_keyrelease(int wk); #endif
0.867188
high
src/qt/include/QtGui/qfontdialog.h
ant0ine/phantomjs
46
750537
<gh_stars>10-100 #include "../../src/gui/dialogs/qfontdialog.h"
0.992188
low
System/Library/Frameworks/UIKit.framework/UIActionSheetiOSDismissActionView.h
lechium/tvOS10Headers
4
783305
<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Wednesday, March 22, 2017 at 9:02:49 AM Mountain Standard Time * Operating System: Version 10.1 (Build 14U593) * Image Source: /System/Library/Frameworks/UIKit.framework/UIKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <UIKit/UIKit-Structs.h> #import <UIKit/UIView.h> #import <UIKit/UIActionSheetPresentationControllerDismissActionView.h> @class NSString, UIButton; @interface UIActionSheetiOSDismissActionView : UIView <UIActionSheetPresentationControllerDismissActionView> { BOOL _usesShortCompactVerticalLayout; UIButton* _dismissButton; } @property (nonatomic,retain) UIButton * dismissButton; //@synthesize dismissButton=_dismissButton - In the implementation block @property (assign,nonatomic) BOOL usesShortCompactVerticalLayout; //@synthesize usesShortCompactVerticalLayout=_usesShortCompactVerticalLayout - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (nonatomic,copy) NSString * title; -(id)init; -(void)setTitle:(NSString *)arg1 ; -(CGSize)sizeThatFits:(CGSize)arg1 ; -(NSString *)title; -(void)setHighlighted:(BOOL)arg1 ; -(void)setUsesShortCompactVerticalLayout:(BOOL)arg1 ; -(BOOL)usesShortCompactVerticalLayout; -(id)initWithContinuousCornerRadius:(double)arg1 ; -(void)_setupDismissButton; -(void)_applyContinuousCornerRadius:(double)arg1 ; -(void)setDismissButton:(UIButton *)arg1 ; -(UIButton *)dismissButton; -(double)_heightForTraitCollection:(id)arg1 ; @end
0.574219
high
apiwznm/WznmQJob1NSensitivity.h
mpsitech/wznm-WhizniumSBE
3
6819336
<filename>apiwznm/WznmQJob1NSensitivity.h<gh_stars>1-10 /** * \file WznmQJob1NSensitivity.h * API code for table TblWznmQJob1NSensitivity (declarations) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author <NAME> (auto-generation) * \date created: 5 Dec 2020 */ // IP header --- ABOVE #ifndef WZNMQJOB1NSENSITIVITY_H #define WZNMQJOB1NSENSITIVITY_H #include <sbecore/Xmlio.h> /** * WznmQJob1NSensitivity */ class WznmQJob1NSensitivity { public: WznmQJob1NSensitivity(const Sbecore::uint jnum = 0, const std::string stubRef = ""); public: Sbecore::uint jnum; std::string stubRef; public: bool readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false); }; /** * ListWznmQJob1NSensitivity */ class ListWznmQJob1NSensitivity { public: ListWznmQJob1NSensitivity(); ListWznmQJob1NSensitivity(const ListWznmQJob1NSensitivity& src); ListWznmQJob1NSensitivity& operator=(const ListWznmQJob1NSensitivity& src); ~ListWznmQJob1NSensitivity(); void clear(); public: std::vector<WznmQJob1NSensitivity*> nodes; public: bool readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false); }; #endif
0.902344
high
Sources/Core/cpp/Dictionaries/OrderingRussianFeature.h
elzin/SentimentAnalysisService
2
6852104
<filename>Sources/Core/cpp/Dictionaries/OrderingRussianFeature.h #pragma once namespace SS { namespace Dictionary { namespace Virtual { struct SOrderingFeature { TIDForm idForm; SS::Core::Features::Types::CaseType ct; SS::Core::Features::Types::GenderType gt; SS::Core::Features::Types::NumberType nt; SS::Core::Features::Types::AnimInAnimType at; }; struct SConvertedFeature { int iMorphoInfo; int iSpecialMorpho; }; typedef std::list<SConvertedFeature> TConvFeatureList; class COrderingRussianFeature { public: COrderingRussianFeature(); ~COrderingRussianFeature(); public: void Init(IAMConverterMorpho* pAMConverter); TConvFeatureList* GetConvertedFeature(TIDForm idForm, UINT uiValue); LPCWSTR GetSuffix(TIDForm idForm); TIDForm GetIDForm(LPCWSTR szSuffix); int GetSuffixCount(); private: typedef std::vector<TConvFeatureList> TFeatureVect; void InitVect(TFeatureVect* pVect, SOrderingFeature* rgFeatures, int iCount, IAMConverterMorpho* pAMConverter); private: CMorphoFeature m_oMorphoFeature; TFeatureVect m_vFeatures_490; TFeatureVect m_vFeatures_491; TFeatureVect m_vFeatures_511; TFeatureVect m_vFeatures_510; TFeatureVect m_vFeatures_512; TFeatureVect m_vFeatures_513; }; } } }
0.988281
high
skse/Hooks_Handlers.h
Schwarz-Hexe/YAMMS
1
6884872
<filename>skse/Hooks_Handlers.h #pragma once void Hooks_Handlers_Init(void); void Hooks_Handlers_Commit(void);
0.914063
low
chara.h
ataronus/3DActionShooting_Opengl
0
6917640
<filename>chara.h #pragma once #include <vector> #include <GL/glut.h> #include <iostream> #include <random> #include <ctime> #include "OBB.h" class model : public OBBCube{ public: string kind,name; Vec4 color; vector<model> child; model(string name, string kind, Vec3 pos, Vec3 rot, Vec3 radius, Vec4 color) { this->kind = kind; this->pos = pos; this->rot = rot; this->radius = radius; this->color = color; weight = 0; } }; class Chara : public OBBCube { public: vector<model> mm; float HP; float damage; Chara(){} Chara(Vec3 p, Vec3 r, Vec3 a, Vec4 col,float wei) { pos = p; rot = a; radius = r; weight = wei; } void setHP(float hp) { HP = hp; } void setDamage(float dam) { damage = dam; } void Damage(float dam) { HP -= dam; if (HP < 0) HP = 0; } void setOBBColor(Vec4 col) { color = col; } void addModel(string name, string kind, Vec3 pos, Vec3 rot, Vec3 radius, Vec4 color) { mm.push_back(model(name, kind,pos,rot,radius,color)); } void addChild(string pare_nm, string name, string kind, Vec3 pos, Vec3 rot, Vec3 radius, Vec4 color) { for (model parent : mm) { if (pare_nm == parent.name) parent.child.push_back(model(name, kind, pos, rot, radius, color)); } } void render(bool isobb) { if (isobb) this->DrawOBBCube(false); glPushMatrix(); { glTranslatef(pos.x, pos.y, pos.z); glRotatef(rot.z, 0, 0, 1); glRotatef(rot.x, 1, 0, 0); glRotatef(rot.y, 0, 1, 0); render_models(mm); }glPopMatrix(); } void render_models(vector<model> ms) { GLfloat glcolor[4]; for (int i = 0;i < ms.size();i++) { glPushMatrix(); { glTranslatef(ms[i].pos.x, ms[i].pos.y, ms[i].pos.z); glRotatef(ms[i].rot.z, 0, 0, 1); glRotatef(ms[i].rot.x, 1, 0, 0); glRotatef(ms[i].rot.y, 0, 1, 0); glScaled(ms[i].radius.x, ms[i].radius.y, ms[i].radius.z); setGLColor(glcolor, ms[i].color.x, ms[i].color.y, ms[i].color.z, ms[i].color.w); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, glcolor); if (ms[i].kind == "Cube") { glutSolidCube(1); } else if (ms[i].kind == "Sphere") { glutSolidSphere(1, 16, 16); } else if (ms[i].kind == "Cone") { glutSolidCone(1, 1, 16, 16); } if(!ms[i].child.empty())render_models(ms[i].child); }glPopMatrix(); } } }; class mychr : public Chara { public: mychr(float hp, float wei) { HP = hp; weight = wei; radius = Vec3(3, 2.5, 3); addModel("body", "Sphere", Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(2.5, 2.5, 2.5), Vec4(1, 0, 0, 1)); addModel("right_arm", "Cube", Vec3(0, 0, 2), Vec3(0, 0, 45), Vec3(0.5, 2, 2), Vec4(1, 1, 0, 1)); addModel("left_arm", "Cube", Vec3(0, 0, -2), Vec3(0, 0, 45), Vec3(0.5, 2, 2), Vec4(1, 1, 0, 1)); addModel("right_leg", "Cone", Vec3(0, -1.7, 1.6), Vec3(30, 0, 0), Vec3(1, 1, 2), Vec4(1, 1, 0, 1)); addModel("left_leg", "Cone", Vec3(0, -1.7, -1.6), Vec3(-30, 180, 0), Vec3(1, 1, 2), Vec4(1, 1, 0, 1)); } }; class enemy : public Chara { public: float point; enemy(float hp,float wei, float dam, float point) { HP = hp; weight = wei; damage = dam; radius = Vec3(3, 2.5, 3); this->point = point; addModel("body", "Sphere", Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(2.5, 2.5, 2.5), Vec4(1, 0, 1, 1)); addModel("canon1", "Cube", Vec3(0, 0, 2), Vec3(0, 0, 0), Vec3(1, 1, 1), Vec4(0, 1, 1, 1)); addModel("canon2", "Cube", Vec3(0, 0, -2), Vec3(0, 0, 0), Vec3(1, 1, 1), Vec4(0, 1, 1, 1)); addModel("canon3", "Cube", Vec3(2, 0, 0), Vec3(0, 0, 0), Vec3(1, 1, 1), Vec4(0, 1, 1, 1)); addModel("canon4", "Cube", Vec3(-2, 0, 0), Vec3(0, 0, 0), Vec3(1, 1, 1), Vec4(0, 1, 1, 1)); } }; class Shot : public Chara { public: Shot(float dam, float wei) { damage = dam; weight = wei; radius = Vec3(1,0.5,0.5); setOBBColor(Vec4(1, 1, 1, 1)); addModel("s1", "Sphere", Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(1, 0.5, 0.5), Vec4(0.8, 0.8, 0.8, 1)); //addModel("s2", "Cube", Vec3(-0.5, 0, 0), Vec3(0, 0, 0), Vec3(2, 1, 1), Vec4(0.8, 0.8, 0.8, 1)); } }; class Ene_Shot : public Chara { public: Ene_Shot(float dam, float wei) { damage = dam; weight = wei; radius = Vec3(2, 1, 1)*0.7; setOBBColor(Vec4(0, 0, 0, 1)); addModel("s1", "Sphere", Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(2, 1, 1)*0.7, Vec4(0.2, 0.2, 0.2, 1)); } }; class burst : public Chara { public: mt19937 mt; burst() { //uniform_int_distribution<> rand100(0, 100); //mt.seed(static_cast<unsigned int>(time(nullptr))); addModel("b1", "Sphere", Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(2.5, 2.5, 2.5), Vec4(1, 0, 0, 1)); } void render(bool isobb) { if (isobb) this->DrawOBBCube(false); glPushMatrix(); { glTranslatef(pos.x, pos.y, pos.z); glRotatef(rot.z, 0, 0, 1); glRotatef(rot.x, 1, 0, 0); glRotatef(rot.y, 0, 1, 0); render_models(mm); }glPopMatrix(); } };
0.964844
high
Algorithms/linked list/singly linked list.c
TeacherManoj0131/HacktoberFest2020-Contributions
256
8483840
<gh_stars>100-1000 #include <stdio.h> #include <stdlib.h> struct node { int key; struct node* link; }; typedef struct node NODE; struct list { NODE *head; }; typedef struct list LIST; void init(LIST*); void read_priority(LIST*); void insert_at_pos(LIST*); void insert_at_head(LIST*); void insert_at_tail(LIST*); void delete_priority(LIST*); void delete_at_pos(LIST*); void delete_head(LIST*); void delete_tail(LIST*); void delete_first_occurence(LIST*); void delete_last_occurence(LIST*); void delete_all_occurence(LIST*); void display(LIST*); void display_recursive(NODE*); void find(LIST*); int count(LIST*); void merge(LIST*, LIST*); void merge_sorted(LIST*, LIST*); void union_lists(LIST*,LIST*,LIST*); void intersection(LIST*,LIST*,LIST*); void reverse(LIST*); void destroy(LIST*); int main() { LIST *l = (LIST*)malloc(sizeof(LIST)); init(l); int n; printf("Enter number of nodes for list 1 : "); scanf("%d",&n); for (int i = 0;i<n;i++) read_priority(l); display(l); reverse(l); display(l); //insert_at_tail(l); //insert_at_pos(l); //insert_at_head(l); //insert_at_tail(l); //delete_priority(l); //delete_head(l); //delete_tail(l); //delete_at_pos(l); //delete_first_occurence(l); //delete_last_occurence(l); //delete_all_occurence(l); //printf("Number of nodes = %d\n", count(l)); //find(l); //display_recursive(l->head); #if 0 LIST *l2 = (LIST*)malloc(sizeof(LIST)); init(l2); printf("Enter number of nodes for list 2 : "); scanf("%d",&n); for (int i = 0;i<n;i++) read_priority(l2); display(l2); #endif #if 0 LIST *l3 = (LIST*)malloc(sizeof(LIST)); LIST *l4 = (LIST*)malloc(sizeof(LIST)); init(l3); init(l4); union_lists(l,l2,l3); intersection(l,l2,l4); display(l3); display(l4); #endif destroy(l); } void init(LIST* l) { l->head = NULL; } void read_priority(LIST* l) { NODE* node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; printf("Enter value : "); scanf("%d", &(node->key)); if (l->head == NULL) { l->head = node; } else { NODE *prev = NULL; NODE *pres = l->head; while (pres!=NULL && pres->key<node->key) { prev = pres; pres = pres->link; } if (prev==NULL) { node->link = l->head; l->head = node; } else { prev->link = node; node->link = pres; } } } void display(LIST* l) { NODE* node = l->head; while(node!=NULL) { printf("%d ",node->key); node = node->link; } printf("\n"); } void display_recursive(NODE *node) { if(node!=NULL) { printf("%d ",node->key); display_recursive(node->link); } } void insert_at_pos(LIST* l) { //printf("Inserting at position\n"); NODE* node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; printf("Enter value : "); scanf("%d", &(node->key)); printf("Enter a position : "); int pos; scanf("%d", &pos); if(l->head==NULL) { l->head = node; } else { NODE *prev = NULL; NODE *pres = l->head; int ctr = 0; while(pres!=NULL && ctr<pos) { prev = pres; pres = pres->link; ctr++; } if (prev == NULL) { node->link = l->head; l->head = node; } else { prev->link = node; node->link = pres; } } } void insert_at_head(LIST* l) { //printf("Inserting at head\n"); NODE *node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; printf("Enter value : "); scanf("%d", &(node->key)); if(l->head == NULL) l->head = node; else { node->link = l->head; l->head = node; } } void insert_at_tail(LIST *l) { //printf("Inserting at tail\n"); NODE *node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; printf("Enter value : "); scanf("%d", &(node->key)); if(l->head == NULL) l->head = node; else { NODE *prev = NULL; NODE *pres = l->head; while (pres!=NULL) { prev = pres; pres = pres->link; } prev->link = node; node->link = pres; //pres is null } } void delete_priority(LIST *l) { if(l->head != NULL) { NODE* prev = NULL; NODE* pres = l->head; NODE* max = NULL; int mval = l->head->key; while(pres!=NULL) { if(pres->key>mval) { max = prev; mval = pres->key; } prev = pres; pres = pres->link; } if (max == NULL) { NODE *temp = l->head; l->head = l->head->link; free(temp); } else { NODE* temp = max->link; max->link = max->link->link; free(temp); } } } void delete_at_pos(LIST* l) { int pos; printf("Enter position to delete at : "); scanf("%d", &pos); if(l->head!=NULL) { NODE* prev = NULL; NODE* pres = l->head; int ctr = 0; while(pres!=NULL && ctr<pos) { prev = pres; pres = pres->link; ctr++; } if (prev==NULL) { l->head = pres->link; free(pres); } else { prev->link = pres->link; free(pres); } } } void delete_tail(LIST *l) { NODE *prev = NULL; NODE *pres = l->head; if (pres == NULL) printf("EMPTY\n"); else { while (pres->link!=NULL) { prev = pres; pres = pres->link; } if(prev==NULL) l->head = NULL; else prev->link = NULL; free(pres); } } void delete_head(LIST *l) { if(l->head != NULL) { NODE *temp = l->head; l->head = l->head->link; free(temp); } } void delete_first_occurence(LIST *l) { if (l->head != NULL) { printf("Enter element to delete : "); int val; scanf("%d", &val); NODE* prev = NULL; NODE* pres = l->head; while(pres!=NULL) { if (pres->key == val) { if (prev == NULL) { NODE *temp = l->head; l->head = l->head->link; free(temp); } else { prev->link = pres->link; free(pres); } break; } prev = pres; pres = pres->link; } } } void delete_last_occurence(LIST *l) { if(l->head!=NULL) { int pos = 0, ctr = 0; printf("Enter element to delete : "); int val; scanf("%d", &val); NODE* prev = NULL; NODE* pres = l->head; while(pres!=NULL) { if(pres->key == val) pos = ctr; prev = pres; pres = pres->link; ctr+=1; } prev = NULL; pres = l->head; ctr = 0; while(pres!=NULL && ctr<pos) { prev = pres; pres = pres->link; ctr++; } if (prev==NULL) { l->head = pres->link; free(pres); } else { prev->link = pres->link; free(pres); } } } void delete_all_occurence(LIST *l) { if(l->head != NULL) { printf("Enter element to delete : "); int val; scanf("%d", &val); NODE* prev = NULL; NODE* pres = l->head; while(pres!=NULL) { if(pres->key == val) { if(prev==NULL) { pres=pres->link; l->head = pres; } else { pres = pres->link; prev->link = pres; } } else { prev = pres; pres = pres->link; } } } } int count(LIST *l) { int ctr = 0; if (l->head == NULL) return 0; else { NODE *node = l->head; while (node!=NULL) { ctr++; node = node->link; } return ctr; } } void destroy(LIST *l) { NODE *prev = NULL; NODE *pres = l->head; while(pres!=NULL) { prev = pres; pres = pres->link; free(prev); } } void find(LIST *l) { printf("Enter element to find : "); int s; scanf("%d", &s); int pos = -1; if(l->head == NULL) printf("Index = %d\n", pos); else { int ctr = 0; NODE* prev = NULL; NODE* pres = l->head; while(pres!=NULL) { if(s==pres->key) pos = ctr; prev = pres; pres = pres->link; ctr++; } printf("Index = %d\n", pos); } } void merge(LIST *l1, LIST *l2) { if(l1->head==NULL) { if(l2->head!=NULL) { l1->head=l2->head; l2->head=NULL; } } else { NODE *prev = NULL; NODE *pres = l1->head; while(pres!=NULL) { prev = pres; pres=pres->link; } prev->link = l2->head; l2->head=NULL; } } void merge_sorted(LIST *l1, LIST *l2) { if (l1->head!=NULL && l2->head!=NULL) { NODE *prev = NULL; NODE *pres = l2->head; NODE *temp1 = NULL; NODE *temp2 = l1->head; while(pres!=NULL) { NODE *node = (NODE*)malloc(sizeof(NODE)); node->key = pres->key; node->link = NULL; temp1 = NULL; temp2 = l1->head; while(temp2!=NULL && temp2->key<=node->key) { temp1 = temp2; temp2=temp2->link; } if (temp1==NULL) { node->link = l1->head; l1->head = node; } else { temp1->link = node; node->link = temp2; } pres = pres->link; } } } void insert(LIST *l, int val) { NODE* node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; node->key = val; if (l->head == NULL) { l->head = node; } else { NODE *prev = NULL; NODE *pres = l->head; while (pres!=NULL && pres->key<node->key) { prev = pres; pres = pres->link; } if (prev==NULL) { node->link = l->head; l->head = node; } else { prev->link = node; node->link = pres; } } } void check(LIST *l1,LIST *l3) { NODE *pres1 = l1->head; while(pres1!=NULL) { NODE *pres2 = l3->head; int ctr = 0; while(pres2!=NULL) { if (pres1->key==pres2->key) ctr++; pres2 = pres2->link; } if (ctr==0) { insert(l3,pres1->key); } pres1 = pres1->link; } } void union_lists(LIST* l1, LIST *l2, LIST *l3) { check(l1,l3); check(l2,l3); } void intersection(LIST *l1, LIST *l2, LIST *l3) { NODE *node1 = l1->head; int flag; while(node1!=NULL) { flag = 0; NODE *node2 = l2->head; while(node2!=NULL) { if (node2->key==node1->key) { flag = 1; break; } node2 = node2->link; } if (flag==1) { insert(l3,node1->key); } node1=node1->link; } } void reverse(LIST *l) { NODE *pres = l->head; NODE *prev = NULL; NODE *temp = NULL; while(pres!=NULL) { temp = pres->link; pres->link = prev; prev = pres; pres = temp; } l->head = prev; }
0.976563
high
framework/msg_route/msg_route_client/msg_route_client.h
KooWu/v2x
0
8516608
#ifndef MSG_ROUTE_SERVER #define MSG_ROUTE_SERVER #include <stdint.h> #include <stdbool.h> #include "msg_route_comm.h" typedef int32_t (*MsgRouteClientCallback)(MsgRouteDataInfo *msgData); typedef struct { int32_t msgType; MsgRouteClientCallback rxFunc; } MsgRouteClientSubscribeInfo; int32_t MsgRouteClientInit(int32_t appId); void MsgRouteClientDeinit(void); int32_t MsgRouteClientSendMsg(MsgRouteDataInfo *sendData, bool isBroadcast); int32_t MsgRouteClientSubscribeMsg(MsgRouteClientSubscribeInfo *subscribeInfo); int32_t MsgRouteClientUnsubscribeMsg(MsgRouteClientSubscribeInfo *subscribeInfo); #endif
0.953125
high
pydk-template/{{ cookiecutter.formal_name }}/app/src/main/cpp/pythonsupport.c
pmp-p/projects
0
612585
<filename>pydk-template/{{ cookiecutter.formal_name }}/app/src/main/cpp/pythonsupport.c<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "logger.h" #if __EMSCRIPTEN__ #include "cpy-wasm/cpython_wasm.c" #else #include "cpy-aosp/cpython_aosp.c" #endif
0.695313
low
lib/include/struct.h
loonydev/wrap_demo
0
645353
typedef struct struct_test{ int a; int b; } struct_test; int minus(struct_test a);
0.625
low
src/planner/exploration/local_topo/exploration_map.h
h2ssh/Vulcan
6
6948096
<gh_stars>1-10 /* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of <NAME>, <EMAIL>. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file exploration_map.h * \author <NAME> * * Declaration of LocalTopoExplorationMap. */ #ifndef PLANNER_EXPLORATION_LOCAL_TOPO_EXPLORATION_MAP_H #define PLANNER_EXPLORATION_LOCAL_TOPO_EXPLORATION_MAP_H #include <planner/exploration/local_topo/target_impl.h> #include <hssh/local_topological/event.h> #include <system/message_traits.h> #include <cereal/access.hpp> #include <cereal/types/memory.hpp> #include <cereal/types/vector.hpp> namespace vulcan { namespace hssh { class LocalTopoMap; } struct pose_t; namespace planner { /** * LocalTopoExplorationMap maintains the list of all explored and unexplored areas in the environment. The map provides * methods for selecting a random unvisited target, as well as iterating over all visited and unvisited targets * remaining in the map. * * The exploration order used by LocalTopoExplorationMap is: * * 1) Visit all areas. * * As the robot drives, each topological event results in one or more targets being visited. A target doesn't have to be * the goal of the robot's navigation in order to be considered visited, it just needs to be visited at some point while * the robot is driving through the environment. */ class LocalTopoExplorationMap { public: using const_iterator = std::vector<LocalAreaTarget*>::const_iterator; /** * Default constructor for LocalTopoExplorationMap. * * Create an empty map. */ LocalTopoExplorationMap(void) { } /** * Constructor for LocalTopoExplorationMap. * * \param topoMap Map from which to extract the exploration map */ LocalTopoExplorationMap(const hssh::LocalTopoMap& topoMap); /** * Destructor for LocalTopoExplorationMap. */ ~LocalTopoExplorationMap(void); /** * selectRandomTarget selects a random unvisited target in the map. * * \return A randomly selected unvisited target. If no unvisited targets remain, then nullptr is returned. */ LocalAreaTarget* selectRandomTarget(void); /** * identifyVisitedTargets identifies new targets that have been visited by the robot based on new topological events * that have been generated. * * \param events Collection of topological events that occurred * \return Number of new areas that were visited during these events. */ int identifyVisitedTargets(const hssh::LocalAreaEventVec& events); // Iterator support for the map std::size_t sizeVisited(void) const { return visitedTargets_.size(); } const_iterator beginVisited(void) const { return visitedTargets_.begin(); } const_iterator endVisited(void) const { return visitedTargets_.end(); } std::size_t sizeUnvisited(void) const { return unvisitedTargets_.size(); } const_iterator beginUnvisited(void) const { return unvisitedTargets_.begin(); } const_iterator endUnvisited(void) const { return unvisitedTargets_.end(); } private: std::vector<std::shared_ptr<LocalAreaTarget>> targets_; std::vector<LocalAreaTarget*> visitedTargets_; std::vector<LocalAreaTarget*> unvisitedTargets_; // Serialization support friend class cereal::access; // Split the load and save because need to repopulate the visited/unvisited vectors after loading template <class Archive> void save(Archive& ar) const { ar(targets_); } template <class Archive> void load(Archive& ar) { ar(targets_); for(auto& t : targets_) { if(t->wasVisited()) { visitedTargets_.push_back(t.get()); } else { unvisitedTargets_.push_back(t.get()); } } } }; } // namespace planner } // namespace vulcan DEFINE_DEBUG_MESSAGE(planner::LocalTopoExplorationMap, ("DEBUG_LOCAL_TOPO_EXPLORATION_MAP")) #endif // PLANNER_EXPLORATION_LOCAL_TOPO_EXPLORATION_MAP_H
0.996094
high
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/CCDNPreDownloadResourcePB.h
ceekay1991/AliPayForDebug
5
6980864
// // 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 "APDPBGeneratedMessage.h" @class NSArray; @interface CCDNPreDownloadResourcePB : APDPBGeneratedMessage { } + (CDStruct_af61540b *)_fieldInfos; // Remaining properties @property(nonatomic) int cache_type; // @dynamic cache_type; @property(nonatomic) int delay; // @dynamic delay; @property(readonly) _Bool hasCache_type; // @dynamic hasCache_type; @property(readonly) _Bool hasDelay; // @dynamic hasDelay; @property(readonly) _Bool hasRandom; // @dynamic hasRandom; @property(nonatomic) int random; // @dynamic random; @property(retain, nonatomic) NSArray *resource_info; // @dynamic resource_info; @end
0.554688
medium
oss_c_sdk/oss_live.c
wangdxh/aliyun-oss-c-sdk
146
8413632
#include "aos_log.h" #include "aos_define.h" #include "aos_util.h" #include "aos_string.h" #include "aos_status.h" #include "oss_auth.h" #include "oss_util.h" #include "oss_xml.h" #include "oss_api.h" aos_status_t *oss_create_live_channel(const oss_request_options_t *options, const aos_string_t *bucket, oss_live_channel_configuration_t *config, aos_list_t *publish_url_list, aos_list_t *play_url_list, aos_table_t **resp_headers) { int res = AOSE_OK; aos_status_t *s = NULL; aos_http_request_t *req = NULL; aos_http_response_t *resp = NULL; aos_table_t *query_params = NULL; aos_table_t *headers = NULL; aos_list_t body; oss_ensure_bucket_name_valid(bucket); //init params query_params = aos_table_create_if_null(options, query_params, 1); apr_table_add(query_params, OSS_LIVE_CHANNEL, ""); //init headers headers = aos_table_create_if_null(options, headers, 0); oss_init_live_channel_request(options, bucket, &config->name, HTTP_PUT, &req, query_params, headers, &resp); // build body build_create_live_channel_body(options->pool, config, &body); oss_write_request_body_from_buffer(&body, req); s = oss_process_request(options, req, resp); oss_fill_read_response_header(resp, resp_headers); if (!aos_status_is_ok(s)) { return s; } // parse result res = oss_create_live_channel_parse_from_body(options->pool, &resp->body, publish_url_list, play_url_list); if (res != AOSE_OK) { aos_xml_error_status_set(s, res); } return s; } aos_status_t *oss_put_live_channel_status(const oss_request_options_t *options, const aos_string_t *bucket, const aos_string_t *live_channel, const aos_string_t *live_channel_status, aos_table_t **resp_headers) { aos_status_t *s = NULL; aos_http_request_t *req = NULL; aos_http_response_t *resp = NULL; aos_table_t *query_params = NULL; aos_table_t *headers = NULL; oss_ensure_bucket_name_valid(bucket); //init params query_params = aos_table_create_if_null(options, query_params, 2); apr_table_add(query_params, OSS_LIVE_CHANNEL, ""); apr_table_add(query_params, OSS_LIVE_CHANNEL_STATUS, live_channel_status->data); //init headers, forbid 'Expect' and 'Transfer-Encoding' of HTTP headers = aos_table_create_if_null(options, headers, 2); apr_table_set(headers, "Expect", ""); apr_table_set(headers, "Transfer-Encoding", ""); oss_init_live_channel_request(options, bucket, live_channel, HTTP_PUT, &req, query_params, headers, &resp); s = oss_process_request(options, req, resp); oss_fill_read_response_header(resp, resp_headers); return s; } aos_status_t *oss_get_live_channel_info(const oss_request_options_t *options, const aos_string_t *bucket, const aos_string_t *live_channel, oss_live_channel_configuration_t *info, aos_table_t **resp_headers) { int res = AOSE_OK; aos_status_t *s = NULL; aos_http_request_t *req = NULL; aos_http_response_t *resp = NULL; aos_table_t *query_params = NULL; aos_table_t *headers = NULL; oss_ensure_bucket_name_valid(bucket); //init query_params query_params = aos_table_create_if_null(options, query_params, 1); apr_table_add(query_params, OSS_LIVE_CHANNEL, ""); //init headers headers = aos_table_create_if_null(options, headers, 0); oss_init_live_channel_request(options, bucket, live_channel, HTTP_GET, &req, query_params, headers, &resp); s = oss_process_request(options, req, resp); oss_fill_read_response_header(resp, resp_headers); if (!aos_status_is_ok(s)) { return s; } // parse result res = oss_live_channel_info_parse_from_body(options->pool, &resp->body, info); if (res != AOSE_OK) { aos_xml_error_status_set(s, res); } aos_str_set(&info->name, aos_pstrdup(options->pool, live_channel)); return s; } aos_status_t *oss_get_live_channel_stat(const oss_request_options_t *options, const aos_string_t *bucket, const aos_string_t *live_channel, oss_live_channel_stat_t *stat, aos_table_t **resp_headers) { int res = AOSE_OK; aos_status_t *s = NULL; aos_http_request_t *req = NULL; aos_http_response_t *resp = NULL; aos_table_t *query_params = NULL; aos_table_t *headers = NULL; oss_ensure_bucket_name_valid(bucket); //init params query_params = aos_table_create_if_null(options, query_params, 2); apr_table_add(query_params, OSS_LIVE_CHANNEL, ""); apr_table_add(query_params, OSS_COMP, OSS_LIVE_CHANNEL_STAT); //init headers headers = aos_table_create_if_null(options, headers, 0); oss_init_live_channel_request(options, bucket, live_channel, HTTP_GET, &req, query_params, headers, &resp); s = oss_process_request(options, req, resp); oss_fill_read_response_header(resp, resp_headers); if (!aos_status_is_ok(s)) { return s; } // parse result res = oss_live_channel_stat_parse_from_body(options->pool, &resp->body, stat); if (res != AOSE_OK) { aos_xml_error_status_set(s, res); } return s; } aos_status_t *oss_delete_live_channel(const oss_request_options_t *options, const aos_string_t *bucket, const aos_string_t *live_channel, aos_table_t **resp_headers) { aos_status_t *s = NULL; aos_http_request_t *req = NULL; aos_http_response_t *resp = NULL; aos_table_t *query_params = NULL; aos_table_t *headers = NULL; oss_ensure_bucket_name_valid(bucket); //init params query_params = aos_table_create_if_null(options, query_params, 1); apr_table_add(query_params, OSS_LIVE_CHANNEL, ""); //init headers headers = aos_table_create_if_null(options, headers, 0); oss_init_live_channel_request(options, bucket, live_channel, HTTP_DELETE, &req, query_params, headers, &resp); s = oss_process_request(options, req, resp); oss_fill_read_response_header(resp, resp_headers); return s; } aos_status_t *oss_list_live_channel(const oss_request_options_t *options, const aos_string_t *bucket, oss_list_live_channel_params_t *params, aos_table_t **resp_headers) { int res = AOSE_OK; aos_status_t *s = NULL; aos_http_request_t *req = NULL; aos_http_response_t *resp = NULL; aos_table_t *query_params = NULL; aos_table_t *headers = NULL; oss_ensure_bucket_name_valid(bucket); //init params query_params = aos_table_create_if_null(options, query_params, 4); apr_table_add(query_params, OSS_LIVE_CHANNEL, ""); apr_table_add(query_params, OSS_PREFIX, params->prefix.data); apr_table_add(query_params, OSS_MARKER, params->marker.data); aos_table_add_int(query_params, OSS_MAX_KEYS, params->max_keys); //init headers headers = aos_table_create_if_null(options, headers, 0); oss_init_bucket_request(options, bucket, HTTP_GET, &req, query_params, headers, &resp); s = oss_process_request(options, req, resp); oss_fill_read_response_header(resp, resp_headers); if (!aos_status_is_ok(s)) { return s; } // parse result res = oss_list_live_channel_parse_from_body(options->pool, &resp->body, &params->live_channel_list, &params->next_marker, &params->truncated); if (res != AOSE_OK) { aos_xml_error_status_set(s, res); } return s; } aos_status_t *oss_get_live_channel_history(const oss_request_options_t *options, const aos_string_t *bucket, const aos_string_t *live_channel, aos_list_t *live_record_list, aos_table_t **resp_headers) { int res = AOSE_OK; aos_status_t *s = NULL; aos_http_request_t *req = NULL; aos_http_response_t *resp = NULL; aos_table_t *query_params = NULL; aos_table_t *headers = NULL; oss_ensure_bucket_name_valid(bucket); //init params query_params = aos_table_create_if_null(options, query_params, 2); apr_table_add(query_params, OSS_LIVE_CHANNEL, ""); apr_table_add(query_params, OSS_COMP, OSS_LIVE_CHANNEL_HISTORY); //init headers headers = aos_table_create_if_null(options, headers, 0); oss_init_live_channel_request(options, bucket, live_channel, HTTP_GET, &req, query_params, headers, &resp); s = oss_process_request(options, req, resp); oss_fill_read_response_header(resp, resp_headers); if (!aos_status_is_ok(s)) { return s; } // parse result res = oss_live_channel_history_parse_from_body(options->pool, &resp->body, live_record_list); if (res != AOSE_OK) { aos_xml_error_status_set(s, res); } return s; } aos_status_t *oss_gen_vod_play_list(const oss_request_options_t *options, const aos_string_t *bucket, const aos_string_t *live_channel, const aos_string_t *play_list_name, const int64_t start_time, const int64_t end_time, aos_table_t **resp_headers) { aos_status_t *s = NULL; aos_http_request_t *req = NULL; aos_http_response_t *resp = NULL; aos_table_t *query_params = NULL; aos_table_t *headers = NULL; char *resource = NULL; aos_string_t resource_str; oss_ensure_bucket_name_valid(bucket); //init params query_params = aos_table_create_if_null(options, query_params, 3); apr_table_add(query_params, OSS_LIVE_CHANNEL_VOD, ""); apr_table_add(query_params, OSS_LIVE_CHANNEL_START_TIME, apr_psprintf(options->pool, "%" APR_INT64_T_FMT, start_time)); apr_table_add(query_params, OSS_LIVE_CHANNEL_END_TIME, apr_psprintf(options->pool, "%" APR_INT64_T_FMT, end_time)); //init headers headers = aos_table_create_if_null(options, headers, 1); apr_table_set(headers, OSS_CONTENT_TYPE, OSS_MULTIPART_CONTENT_TYPE); resource = apr_psprintf(options->pool, "%s/%s", live_channel->data, play_list_name->data); aos_str_set(&resource_str, resource); oss_init_live_channel_request(options, bucket, &resource_str, HTTP_POST, &req, query_params, headers, &resp); s = oss_process_request(options, req, resp); oss_fill_read_response_header(resp, resp_headers); return s; } char *oss_gen_rtmp_signed_url(const oss_request_options_t *options, const aos_string_t *bucket, const aos_string_t *live_channel, const aos_string_t *play_list_name, const int64_t expires) { aos_string_t signed_url; char *expires_str = NULL; aos_string_t expires_time; int res = AOSE_OK; aos_http_request_t *req = NULL; aos_table_t *params = NULL; expires_str = apr_psprintf(options->pool, "%" APR_INT64_T_FMT, expires); aos_str_set(&expires_time, expires_str); req = aos_http_request_create(options->pool); oss_get_rtmp_uri(options, bucket, live_channel, req); res = oss_get_rtmp_signed_url(options, req, &expires_time, play_list_name, params, &signed_url); if (res != AOSE_OK) { return NULL; } return signed_url.data; }
0.96875
high
C/Sources/fs_byte_buffer_is_readable.c
Tylerian/Fuse
0
8446400
<reponame>Tylerian/Fuse // // fs_byte_buffer_is_readable.c // Fuse // // Created by <NAME> on 19/05/18. // Copyright © 2018 Tylerian. All rights reserved. // #include "fuse_private.h" int fs_byte_buffer_is_readable(fs_byte_buffer_t *buffer) { return (buffer->writer_index > buffer->reader_index) ? FS_YES: FS_NO; } int fs_byte_buffer_is_readable_by_length(fs_byte_buffer_t *buffer, uint32_t length) { return fs_byte_buffer_is_readable_by_length_at_offset(buffer, length, buffer->reader_index); } int fs_byte_buffer_is_readable_by_length_at_offset(fs_byte_buffer_t *buffer, uint32_t length, uint32_t offset) { return (buffer->writer_index - offset >= length) ? FS_YES: FS_NO; }
0.941406
high
08_Structs/src/main.c
rjbernaldo/c-programming-for-beginners
1
3875897
<filename>08_Structs/src/main.c #include <stdio.h> #include <string.h> #define NUMBER_OF_CDS 1 typedef struct cd CD; typedef char Str50[50]; struct cd { Str50 name[50]; Str50 artist[50]; int trackcount; int rating; }; CD cd_collection[NUMBER_OF_CDS]; void create_cd_collection() { strcpy(cd_collection[0].name, "Name"); strcpy(cd_collection[0].artist, "Artist"); cd_collection[0].trackcount = 1; cd_collection[0].rating = 10; } void display_cd_collection() { int i; CD thiscd; for (i = 0; i < NUMBER_OF_CDS; i++) { thiscd = cd_collection[i]; printf("CD #%d: %s - %s - %d - %d", i, thiscd.name, thiscd.artist, thiscd.trackcount, thiscd.rating); } } int main() { create_cd_collection(); display_cd_collection(); }
0.972656
high
app/native/jni/src/dictionary/structure/v4/content/probability_entry.h
dhavalgoti24/BoxIt-IME-indic
121
3908665
<filename>app/native/jni/src/dictionary/structure/v4/content/probability_entry.h /* * Copyright (C) 2013, The Android Open Source Project * * 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 LATINIME_PROBABILITY_ENTRY_H #define LATINIME_PROBABILITY_ENTRY_H #include <climits> #include <cstdint> #include "defines.h" #include "dictionary/property/historical_info.h" #include "dictionary/property/ngram_property.h" #include "dictionary/property/unigram_property.h" #include "dictionary/structure/v4/ver4_dict_constants.h" namespace latinime { class ProbabilityEntry { public: ProbabilityEntry(const ProbabilityEntry &probabilityEntry) : mFlags(probabilityEntry.mFlags), mProbability(probabilityEntry.mProbability), mHistoricalInfo(probabilityEntry.mHistoricalInfo) {} // Dummy entry ProbabilityEntry() : mFlags(Ver4DictConstants::FLAG_NOT_A_VALID_ENTRY), mProbability(NOT_A_PROBABILITY), mHistoricalInfo() {} // Entry without historical information ProbabilityEntry(const int flags, const int probability) : mFlags(flags), mProbability(probability), mHistoricalInfo() {} // Entry with historical information. ProbabilityEntry(const int flags, const HistoricalInfo *const historicalInfo) : mFlags(flags), mProbability(NOT_A_PROBABILITY), mHistoricalInfo(*historicalInfo) {} // Create from unigram property. ProbabilityEntry(const UnigramProperty *const unigramProperty) : mFlags(createFlags(unigramProperty->representsBeginningOfSentence(), unigramProperty->isNotAWord(), unigramProperty->isBlacklisted(), unigramProperty->isPossiblyOffensive())), mProbability(unigramProperty->getProbability()), mHistoricalInfo(unigramProperty->getHistoricalInfo()) {} // Create from ngram property. // TODO: Set flags. ProbabilityEntry(const NgramProperty *const ngramProperty) : mFlags(0), mProbability(ngramProperty->getProbability()), mHistoricalInfo(ngramProperty->getHistoricalInfo()) {} bool isValid() const { return (mFlags & Ver4DictConstants::FLAG_NOT_A_VALID_ENTRY) == 0; } bool hasHistoricalInfo() const { return mHistoricalInfo.isValid(); } uint8_t getFlags() const { return mFlags; } int getProbability() const { return mProbability; } const HistoricalInfo *getHistoricalInfo() const { return &mHistoricalInfo; } bool representsBeginningOfSentence() const { return (mFlags & Ver4DictConstants::FLAG_REPRESENTS_BEGINNING_OF_SENTENCE) != 0; } bool isNotAWord() const { return (mFlags & Ver4DictConstants::FLAG_NOT_A_WORD) != 0; } bool isBlacklisted() const { return (mFlags & Ver4DictConstants::FLAG_BLACKLISTED) != 0; } bool isPossiblyOffensive() const { return (mFlags & Ver4DictConstants::FLAG_POSSIBLY_OFFENSIVE) != 0; } uint64_t encode(const bool hasHistoricalInfo) const { uint64_t encodedEntry = static_cast<uint8_t>(mFlags); if (hasHistoricalInfo) { encodedEntry = (encodedEntry << (Ver4DictConstants::TIME_STAMP_FIELD_SIZE * CHAR_BIT)) | static_cast<uint32_t>(mHistoricalInfo.getTimestamp()); encodedEntry = (encodedEntry << (Ver4DictConstants::WORD_LEVEL_FIELD_SIZE * CHAR_BIT)) | static_cast<uint8_t>(mHistoricalInfo.getLevel()); encodedEntry = (encodedEntry << (Ver4DictConstants::WORD_COUNT_FIELD_SIZE * CHAR_BIT)) | static_cast<uint16_t>(mHistoricalInfo.getCount()); } else { encodedEntry = (encodedEntry << (Ver4DictConstants::PROBABILITY_SIZE * CHAR_BIT)) | static_cast<uint8_t>(mProbability); } return encodedEntry; } static ProbabilityEntry decode(const uint64_t encodedEntry, const bool hasHistoricalInfo) { if (hasHistoricalInfo) { const int flags = readFromEncodedEntry(encodedEntry, Ver4DictConstants::FLAGS_IN_LANGUAGE_MODEL_SIZE, Ver4DictConstants::TIME_STAMP_FIELD_SIZE + Ver4DictConstants::WORD_LEVEL_FIELD_SIZE + Ver4DictConstants::WORD_COUNT_FIELD_SIZE); const int timestamp = readFromEncodedEntry(encodedEntry, Ver4DictConstants::TIME_STAMP_FIELD_SIZE, Ver4DictConstants::WORD_LEVEL_FIELD_SIZE + Ver4DictConstants::WORD_COUNT_FIELD_SIZE); const int level = readFromEncodedEntry(encodedEntry, Ver4DictConstants::WORD_LEVEL_FIELD_SIZE, Ver4DictConstants::WORD_COUNT_FIELD_SIZE); const int count = readFromEncodedEntry(encodedEntry, Ver4DictConstants::WORD_COUNT_FIELD_SIZE, 0 /* pos */); const HistoricalInfo historicalInfo(timestamp, level, count); return ProbabilityEntry(flags, &historicalInfo); } else { const int flags = readFromEncodedEntry(encodedEntry, Ver4DictConstants::FLAGS_IN_LANGUAGE_MODEL_SIZE, Ver4DictConstants::PROBABILITY_SIZE); const int probability = readFromEncodedEntry(encodedEntry, Ver4DictConstants::PROBABILITY_SIZE, 0 /* pos */); return ProbabilityEntry(flags, probability); } } private: // Copy constructor is public to use this class as a type of return value. DISALLOW_ASSIGNMENT_OPERATOR(ProbabilityEntry); const uint8_t mFlags; const int mProbability; const HistoricalInfo mHistoricalInfo; static int readFromEncodedEntry(const uint64_t encodedEntry, const int size, const int pos) { return static_cast<int>( (encodedEntry >> (pos * CHAR_BIT)) & ((1ull << (size * CHAR_BIT)) - 1)); } static uint8_t createFlags(const bool representsBeginningOfSentence, const bool isNotAWord, const bool isBlacklisted, const bool isPossiblyOffensive) { uint8_t flags = 0; if (representsBeginningOfSentence) { flags |= Ver4DictConstants::FLAG_REPRESENTS_BEGINNING_OF_SENTENCE; } if (isNotAWord) { flags |= Ver4DictConstants::FLAG_NOT_A_WORD; } if (isBlacklisted) { flags |= Ver4DictConstants::FLAG_BLACKLISTED; } if (isPossiblyOffensive) { flags |= Ver4DictConstants::FLAG_POSSIBLY_OFFENSIVE; } return flags; } }; } // namespace latinime #endif /* LATINIME_PROBABILITY_ENTRY_H */
0.996094
high
source/biometrics/iris/vasir/source/MasekAlg/Masek.h
HarmonIQ/noid
6
3941433
#pragma once #include "global.h" /** * This class gives all Masek methods a unified namespace, and makes it easy * to overload the methods, i.e. to change the internal logic. * * All methods unless specified otherwise were original written by * <NAME>, and ported to C by <NAME>. * * @author <NAME> */ //class MASEK_API Masek class Masek { public: /** \defgroup GlobalH Global Types and Constants found in global.h */ /*@{*/ //static const double PI; //static const double AdjPrecision; #define PI (double)3.14159265358979 #define AdjPrecision (double)0.0000000000005 typedef struct mat_data MAT_DATA; typedef struct _image IMAGE; typedef struct _filter filter; typedef struct a_complex Complex; /*@}*/ /** * Adjusts image gamma. * * @author <NAME> * * @param im image to be processed * @param g image gamma value.\n * Values in the range 0-1 enhance contrast of bright regions, * values > 1 enhance contrast in dark regions. * @return the modified filter */ filter* adjgamma(filter* im, double g); /** * Canny edge detection * * Function to perform Canny edge detection. Code uses modifications as * suggested by Fleck (IEEE PAMI No. 3, Vol. 14. March 1992. pp 337-345) * * @author <NAME> * @author <NAME> * * @param im image to be procesed * @param sigma standard deviation of Gaussian smoothing filter * (typically 1) * @param scaling factor to reduce input image by * @param vert weighting for vertical gradients * @param horz weighting for horizontal gradients * @param gradient (OUT) edge strength image (gradient amplitude) * @param orND (OUT) orientation image (in degrees 0-180, positive * anti-clockwise) * @return the modified image * * @see nonmaxsup, hysthresh */ IMAGE* canny(IMAGE* im, double sigma, double scaling, double vert, double horz, filter* gradient, filter* orND); /** * Returns the pixel coordinates of a circle defined by the radius and * x, y coordinates of its centre. * * @param x0 centre coordinates of the circle (x) * @param y0 centre coordinates of the circle (y) * @param r the radius of the circle * @param imgsize size of the image array to plot coordinates onto * @param _nsides the circle is actually approximated by a polygon, this * argument gives the number of sides used in this * approximation. Default is 600. * @param x (OUT) an array containing x coordinates of circle * boundary points * @param y (OUT) an array containing y coordinates of circle * boundary points */ int circlecoords(double x0, double y0, double r, int* imgsize, double _nsides, int** x, int** y); /** * Generates a biometric template from an iris in an eye image. * * Arguments: * @param eyeimage_filename the file name of the eye image * @param _template (OUT) the binary iris biometric template * @param mask (OUT) the binary iris noise mask */ void createiristemplate(char* eyeimage_filename, int nscales, int** _template, int** mask, int* width, int* height); /** * Generates a biometric template from the normalised iris region, also * generates corresponding noise mask * * @param polar_array normalised iris region * @param noise_array corresponding normalised noise region map * @param nscales number of filters to use in encoding * @param minWaveLength base wavelength * @param mult multicative factor between each filter * @param sigmaOnf bandwidth parameter * @param _template (OUT) the binary iris biometric template * @param mask (OUT) the binary iris noise mask */ void encode(filter* polar_array, IMAGE* noise_array, int nscales, int minWaveLength, int mult, double sigmaOnf, int** _template, int** mask, int* width, int* height); /** * Returns the coordinates of a circle in an image using the Hough * transform and Canny edge detection to create the edge map. * * The output depends on the input: * - \b circleiris centre coordinates and radius of the detected iris * boundary * - \b circlepupil centre coordinates and radius of the detected pupil * boundary * - \b imagewithnoise original eye image, but with location of noise * marked with NaN values * * @param image the image in which to find circles * @param lradius lower radius to search for * @param uradius upper radius to search for * @param scaling scaling factor for speeding up the Hough transform * @param sigma amount of Gaussian smoothing to apply for creating * edge map. * @param hithres threshold for creating edge map * @param lowthres threshold for connected edges * @param vert vertical edge contribution (0-1) * @param horz horizontal edge contribution (0-1) * @param _row (OUT) center x-coordinate * @param _col (OUT) center x-coordinate * @param _r (OUT) radius */ void findcircle(IMAGE* image, int lradius, int uradius, double scaling, double sigma, double hithres, double lowthres, double vert, double horz, int* _row, int* _col, int* _r); /** * Returns the coordinates of a line in an image using the linear Hough * transform and Canny edge detection to create the edge map. * * @param image the input image * @param lines (OUT) parameters of the detected line in polar form.\n * 0=cos(t), 1=sin(t), 2=r * @return number of lines */ int findline(IMAGE* image, double* *lines); /** * Function for convolving each row of an image with 1D log-Gabor filters * * @author <NAME> * @author <NAME> * * @param im the image to convolve * @param nscale number of filters to use * @param minWaveLength wavelength of the basis filter * @param mult multiplicative factor between each filter * @param sigmaOnf ratio of the standard deviation of the Gaussian * describing the log Gabor filter's transfer * function in the frequency domain to the filter * center frequency. * @param EO (OUT) an 1D cell array of complex valued * comvolution results */ void gaborconvolve(filter* im, int nscale, int minWaveLength, int mult, double sigmaOnf, Complex*** EO, double** filtersum, int* EOh, int* EOw); /** * Takes an edge map image, and performs the Hough transform for finding * circles in the image. * * @param m_edgeim the edge map image to be transformed * @param rmin the minimum radius values of circles to search for * @param rmax the maximum radius values of circles to search for * @return the Hough transform */ double* houghcircle(filter* m_edgeim, int rmin, int rmax); /** * Hysteresis thresholding * * Function performs hysteresis thresholding of an image. * All pixels with values above threshold T1 are marked as edges * All pixels that are adjacent to points that have been marked as edges * and with values above threshold T2 are also marked as edges. Eight * connectivity is used. * * @author <NAME> * * @param im image to be thresholded (assumed to be non-negative) * @param T1 upper threshold value * @param T2 lower threshold value * @return the thresholded image (containing values 0 or 1) */ filter* hysthresh(filter* im, double T1, double T2); /** * INTERP2 2-D interpolation (table lookup). * Linear interpolation. * * ZI = INTERP2(Z,XI,YI) interpolates to find ZI, the values of the * underlying 2-D function Z at the points in matrices XI and YI. * * @author MathWorks, Inc. * * @param z underlying z-function * @param xi row vector (matrix w/ constant columns) * @param yi column vector (matrix w/ constant rows) * @param zi (OUT) created matrix */ void interp2(filter* z, filter* xi, filter* yi, filter* zi); /** * Returns the x y coordinates of positions along a line. * * @param lines an array containing parameters of the line in form * @param row height of the image, needed so that x y coordinates are * within the image boundary * @param cols width of the image * @param x (OUT) x-coordinates * @param y (OUT) y-coordinates */ void linescoords(double* lines, int row, int col, int* x, int* y); /** * Function for performing non-maxima suppression on an image using an * orientation image. It is assumed that the orientation image gives * feature normal orientation angles in degrees (0-180). * * Note: This function is slow (1 - 2 mins to process a 256x256 image). * * @author <NAME> * * @param inimage image to be non-maxima suppressed. * @param orient image containing feature normal orientation angles in * degrees (0-180), angles positive anti-clockwise. * @param radius distance in pixel units to be looked at on each side of * each pixel when determining whether it is a local maxima * or not.\n * (Suggested value about 1.2 - 1.5) */ filter* nonmaxsup(filter* inimage, filter* orient, double radius); /** * Performs normalisation of the iris region by unwraping the circular * region into a rectangular block of constant dimensions. * * * @param image the input eye image to extract iris data from * @param xiris the x coordinate of the circle defining the * iris boundary * @param yiris the y coordinate of the circle defining the * iris boundary * @param riris the radius of the circle defining the iris * boundary * @param xpupil the x coordinate of the circle defining the * pupil boundary * @param ypupil the y coordinate of the circle defining the * pupilboundary * @param rpupil the radius of the circle defining the pupil * boundary * @param eyeimage_filename original filename of the input eye image * @param radpixels radial resolution, defines vertical dimension * of normalised representation * @param angulardiv angular resolution, defines horizontal * dimension of normalised representation * @param polar_array (OUT) * @param polar_noise (OUT) */ void normaliseiris(filter* image, int xiris, int yiris, int riris, int xpupil, int ypupil, int rpupil, char* eyeimage_filename, int radpixels, int angulardiv, filter* polar_array, IMAGE* polar_noise); /** * Radon transform. * * Evaluates the Radon transform P, of I along the angles specified by the * vector THETA. THETA values measure angle counter-clockwise from the * horizontal axis. THETA defaults to [0:179] if not specified. * * @author MathWorks, Inc. * * @param I image * @param THETA Thetas (must contain \c numangles elements) * @param imgrow image height * @param imgcol image width * @param numangles Number of angles * @param P (OUT) Transformation * @param R (OUT) Is a vector giving the values of r corresponding to * the rows of P. * @return number of elements in \c R */ int radonc(double* I, double* THETA, int imgrow, int imgcol, int numangles, double** P, double** R); /** * Saves a biometric template. * * @param filedir directory containing the image * @param _eyeimage_filename the file name of the eye image * @param templatedir directory where the template should be stored * @param segdir directory containing the segmentation data * @param nscales number of filters to use in encoding * @param _template the binary iris biometric template * @param _mask the binary iris noise mask * @param mode \c 1=\c, \c 2= \c segmentiris_gt, * \c 3 = \c segmentiris_iridian * @param eyelidon search eyelid * @param highlighton highlight eyelashes/ eyelid (yes=1) * @param highlightvalue value to be used for highlighting the eyelashes */ void saveiristemplate(const char* filedir, const char* templatedir, const char *segdir, const char* _eyeimage_filename, int nscales, int** _template, int** mask, int* width, int* height, int mode, int eyelidon, int highlighton, int highlightvalue); /** * Peforms automatic segmentation of the iris region from an eye image. Also * isolates noise areas such as occluding eyelids and eyelashes. * * Usage: * [circleiris, circlepupil, imagewithnoise] = segmentiris(image) * * @param eyeimage the input eye image * @param circleiris (OUT) centre coordinates and radius of the detected * iris boundary * @param circlepupil (OUT) centre coordinates and radius of the detected * pupil boundary * @param imagewithnoise (OUT) original eye image, but with location of noise * marked with NaN values * @param eyelidon search eyelid * @param highlighton highlight eyelashes/ eyelid (yes=1) * @param highlightvalue value to be used for highlighting the eyelashes */ void segmentiris(IMAGE* eyeimage, int* circleiris, int* circlepupil, double* imagewithnoise, int eyelidon, int highlighton, int highlightvalue); /** * Function to shift the bit-wise iris patterns in order to provide the best * match each shift is by two bit values and left to right, since one pixel * value in the normalised iris pattern gives two bit values in the template * also takes into account the number of scales used. * * @param template the template to shift * @param width width of the template * @param height height of the template * @param noshifts number of shifts to perform to the right, a negative * value results in shifting to the left * @param nscales number of filters used for encoding, needed to determine * how many bits to move in a shift * @param templatene (OUT) the shifted template */ void shiftbits(int* templates, int width, int height, int noshifts,int nscales, int* templatenew); double gethammingdistance(int *template1, int *mask1, int *template2, int *mask2, int scales, int width, int height); /** \defgroup GlobalCPP global.cpp */ /*@{*/ void printfilter(filter* mfilter, char* filename); void printimage(IMAGE* m, char* filename); /*@}*/ /** \defgroup MyMatCPP mymat.cpp */ /*@{*/ int loadtemplate(const char *file, MAT_DATA** m_data); int savetemplate(const char *file, MAT_DATA* m_data); int loadsegmentation(const char *file, MAT_DATA** m_data); int savesegmentation(const char *file, MAT_DATA* m_data); /*@}*/ /** \defgroup GlobalH global.h */ /*@{*/ //int roundND(double); //int fix(double); /*@}*/ //LEE /** imread.cpp */ IMAGE* imread(const char *name); /** imwrite.cpp */ void imwrite (const char* filename, IMAGE* image); /** * Round Double and return Int * * @param x Input double type * @return Int type value */ int roundND(double); /** * Change Double to Int. * * @param double Input double type * @return Int type */ int fix(double); /*@}*/ /** \defgroup GaborconvolveCPP gaborconvolve.cpp */ /*@{*/ /** Shift zero-frequency component to center of spectrum. * For vectors, FFTSHIFT(X) swaps the left and right halves of X. For * matrices, FFTSHIFT(X) swaps the first and third quadrants and the * second and fourth quadrants. For N-D arrays, FFTSHIFT(X) swaps * "half-spaces" of X along each dimension. * \c fftshift(x,dim) applies the FFTSHIFT operation along the dimension * DIM. * * @author MathWorks, Inc. */ void fftshift(double *x, int numDims, int size[]); void dft(Complex* x, Complex* y, int N); Complex* fft(Complex* x, int N); /** * Compute the inverse FFT of \c x[], assuming its length is a power of 2. */ Complex* ifft(Masek::Complex* x, int N); /*@}*/ protected: /** \defgroup GaussCPP gauss.cpp */ /*@{*/ int CREATEGAUSS(int size[2], double sigma, filter *out); filter* filter2(filter gaussian, IMAGE *im); filter* imresize(filter *im, double scaling); /*@}*/ /** \defgroup SegmentIrisCPP segmentiris.cpp */ /*@{*/ #if 1 int segmentiris_gt(IMAGE* eyeimage, char* gndfilename, int* circleiris, int* circlepupil, double* imagewithnoise, int eyelidon, int highlighton, int highlightvalue); int segmentiris_iridian(IMAGE* eyeimage, char* gndfilename, int* circleiris, int* circlepupil, double *imagewithnoise, int eyelidon, int highlighton, int highlightvalue); #endif /*@}*/ };
0.996094
high
samples/subsys/usb/cdc_acm/src/main.c
lemrey/zephyr
8
3974201
/* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ /** * @file * @brief Sample app for CDC ACM class driver * * Sample app for USB CDC ACM class driver. The received data is echoed back * to the serial port. */ #include <stdio.h> #include <string.h> #include <device.h> #include <uart.h> #include <zephyr.h> static const char *banner1 = "Send characters to the UART device\r\n"; static const char *banner2 = "Characters read:\r\n"; static volatile bool data_transmitted; static volatile bool data_arrived; static char data_buf[64]; static void interrupt_handler(struct device *dev) { uart_irq_update(dev); if (uart_irq_tx_ready(dev)) { data_transmitted = true; } if (uart_irq_rx_ready(dev)) { data_arrived = true; } } static void write_data(struct device *dev, const char *buf, int len) { uart_irq_tx_enable(dev); while (len) { int written; data_transmitted = false; written = uart_fifo_fill(dev, (const u8_t *)buf, len); while (data_transmitted == false) { k_yield(); } len -= written; buf += written; } uart_irq_tx_disable(dev); } static void read_and_echo_data(struct device *dev, int *bytes_read) { while (data_arrived == false) ; data_arrived = false; /* Read all data and echo it back */ while ((*bytes_read = uart_fifo_read(dev, (u8_t *)data_buf, sizeof(data_buf)))) { write_data(dev, data_buf, *bytes_read); } } void main(void) { struct device *dev; u32_t baudrate, bytes_read, dtr = 0U; int ret; dev = device_get_binding(CONFIG_CDC_ACM_PORT_NAME_0); if (!dev) { printf("CDC ACM device not found\n"); return; } printf("Wait for DTR\n"); while (1) { uart_line_ctrl_get(dev, LINE_CTRL_DTR, &dtr); if (dtr) break; } printf("DTR set, start test\n"); /* They are optional, we use them to test the interrupt endpoint */ ret = uart_line_ctrl_set(dev, LINE_CTRL_DCD, 1); if (ret) printf("Failed to set DCD, ret code %d\n", ret); ret = uart_line_ctrl_set(dev, LINE_CTRL_DSR, 1); if (ret) printf("Failed to set DSR, ret code %d\n", ret); /* Wait 1 sec for the host to do all settings */ k_busy_wait(1000000); ret = uart_line_ctrl_get(dev, LINE_CTRL_BAUD_RATE, &baudrate); if (ret) printf("Failed to get baudrate, ret code %d\n", ret); else printf("Baudrate detected: %d\n", baudrate); uart_irq_callback_set(dev, interrupt_handler); write_data(dev, banner1, strlen(banner1)); write_data(dev, banner2, strlen(banner2)); /* Enable rx interrupts */ uart_irq_rx_enable(dev); /* Echo the received data */ while (1) { read_and_echo_data(dev, (int *) &bytes_read); } }
0.96875
high
B2G/gecko/embedding/browser/webBrowser/nsWebBrowserContentPolicy.h
wilebeast/FireFox-OS
3
2206833
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsIContentPolicy.h" /* f66bc334-1dd1-11b2-bab2-90e04fe15c19 */ #define NS_WEBBROWSERCONTENTPOLICY_CID \ { 0xf66bc334, 0x1dd1, 0x11b2, { 0xba, 0xb2, 0x90, 0xe0, 0x4f, 0xe1, 0x5c, 0x19 } } #define NS_WEBBROWSERCONTENTPOLICY_CONTRACTID "@mozilla.org/embedding/browser/content-policy;1" class nsWebBrowserContentPolicy : public nsIContentPolicy { public: nsWebBrowserContentPolicy(); virtual ~nsWebBrowserContentPolicy(); NS_DECL_ISUPPORTS NS_DECL_NSICONTENTPOLICY };
0.996094
high
Gwc/Gwc/Model/BaseModel/NBBaseModel.h
dianziguan1234/Gweicheng
0
2239601
<filename>Gwc/Gwc/Model/BaseModel/NBBaseModel.h // // NBBaseModel.h // LawMonkey // // Created by 刘彬 on 16/3/19. // Copyright © 2016年 AiFa. All rights reserved. // #import <Foundation/Foundation.h> @interface NBBaseModel : NSObject<NSCoding,NSCopying> @property(nonatomic,strong) NSError *error; - (id)initWithJsonString:(NSString*)str; - (id)initWithDictionary:(NSDictionary*)dict; - (id)initWithObject:(NSObject *)obj; - (void)setPropertyWithObject:(NSObject*)object; - (void)setPropertyWithDictionary:(NSDictionary*)attrMapDic; - (NSString *)customDescription; - (NSString *)description; - (NSData*)getArchivedData; - (id)convert2object:(NSObject*)obj; - (NSMutableDictionary *)convert2Dictionary; @end
0.730469
high
PyCommon/externalLibs/dependencies/gmm-3.0/include/gmm/gmm_dense_lu.h
hpgit/HumanFoot
0
2272369
<reponame>hpgit/HumanFoot // -*- c++ -*- (enables emacs c++ mode) //=========================================================================== // // Copyright (C) 2003-2008 <NAME> // // This file is a part of GETFEM++ // // Getfem++ is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. // // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. // //=========================================================================== // This file is a modified version of lu.h from MTL. // See http://osl.iu.edu/research/mtl/ // Following the corresponding Copyright notice. //=========================================================================== // Copyright (c) 2001-2003 The Trustees of Indiana University. // All rights reserved. // Copyright (c) 1998-2001 University of Notre Dame. All rights reserved. // Authors: <NAME>, <NAME>, <NAME> // // This file is part of the Matrix Template Library // // Indiana University has the exclusive rights to license this product under // the following license. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. All redistributions of source code must retain the above copyright // notice, the list of authors in the original source code, this list // of conditions and the disclaimer listed in this license; // 2. All redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the disclaimer listed // in this license in the documentation and/or other materials provided // with the distribution; // 3. Any documentation included with all redistributions must include the // following acknowledgement: // "This product includes software developed at the University of // Notre Dame and the Pervasive Technology Labs at Indiana University. // For technical information contact <NAME> at the Pervasive // Technology Labs at Indiana University. // For administrative and license questions contact the Advanced // Research and Technology Institute at 1100 Waterway Blvd. // Indianapolis, Indiana 46202, phone 317-274-5905, fax 317-274-5902." // Alternatively, this acknowledgement may appear in the software // itself, and wherever such third-party acknowledgments normally appear. // 4. The name "MTL" shall not be used to endorse or promote products // derived from this software without prior written permission from // Indiana University. For written permission, please contact Indiana // University Advanced Research & Technology Institute. // 5. Products derived from this software may not be called "MTL", nor // may "MTL" appear in their name, without prior written permission // of Indiana University Advanced Research & Technology Institute. // // Indiana University provides no reassurances that the source code provided // does not infringe the patent or any other intellectual property rights of // any other entity. Indiana University disclaims any liability to any // recipient for claims brought by any other entity based on infringement of // intellectual property rights or otherwise. // // LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO // WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY // GIVES NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF // INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. // INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", // "VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE. // LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR // ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF // INFORMATION GENERATED USING SOFTWARE. //=========================================================================== /**@file gmm_dense_lu.h @author <NAME>, <NAME>, <NAME>, <NAME> @date June 5, 2003. @brief LU factorizations and determinant computation for dense matrices. */ #ifndef GMM_DENSE_LU_H #define GMM_DENSE_LU_H #include "gmm_dense_Householder.h" #include "gmm_opt.h" namespace gmm { /** LU Factorization of a general (dense) matrix (real or complex). This is the outer product (a level-2 operation) form of the LU Factorization with pivoting algorithm . This is equivalent to LAPACK's dgetf2. Also see "Matrix Computations" 3rd Ed. by Golub and Van Loan section 3.2.5 and especially page 115. The pivot indices in ipvt are indexed starting from 1 so that this is compatible with LAPACK (Fortran). */ template <typename DenseMatrix, typename Pvector> size_type lu_factor(DenseMatrix& A, Pvector& ipvt) { typedef typename linalg_traits<DenseMatrix>::value_type T; typedef typename number_traits<T>::magnitude_type R; size_type info(0), i, j, jp, M(mat_nrows(A)), N(mat_ncols(A)); size_type NN = std::min(M, N); std::vector<T> c(M), r(N); GMM_ASSERT2(ipvt.size()+1 >= NN, "IPVT too small"); for (i = 0; i+1 < NN; ++i) ipvt[i] = i; if (M || N) { for (j = 0; j+1 < NN; ++j) { R max = gmm::abs(A(j,j)); jp = j; for (i = j+1; i < M; ++i) /* find pivot. */ if (gmm::abs(A(i,j)) > max) { jp = i; max = gmm::abs(A(i,j)); } ipvt[j] = jp + 1; if (max == R(0)) { info = j + 1; break; } if (jp != j) for (i = 0; i < N; ++i) std::swap(A(jp, i), A(j, i)); for (i = j+1; i < M; ++i) { A(i, j) /= A(j,j); c[i-j-1] = -A(i, j); } for (i = j+1; i < N; ++i) r[i-j-1] = A(j, i); // avoid the copy ? rank_one_update(sub_matrix(A, sub_interval(j+1, M-j-1), sub_interval(j+1, N-j-1)), c, conjugated(r)); } ipvt[j] = j + 1; } return info; } /** LU Solve : Solve equation Ax=b, given an LU factored matrix.*/ // Thanks to <NAME> for this routine! template <typename DenseMatrix, typename VectorB, typename VectorX, typename Pvector> void lu_solve(const DenseMatrix &LU, const Pvector& pvector, VectorX &x, const VectorB &b) { typedef typename linalg_traits<DenseMatrix>::value_type T; copy(b, x); for(size_type i = 0; i < pvector.size(); ++i) { size_type perm = pvector[i]-1; // permutations stored in 1's offset if(i != perm) { T aux = x[i]; x[i] = x[perm]; x[perm] = aux; } } /* solve Ax = b -> LUx = b -> Ux = L^-1 b. */ lower_tri_solve(LU, x, true); upper_tri_solve(LU, x, false); } template <typename DenseMatrix, typename VectorB, typename VectorX> void lu_solve(const DenseMatrix &A, VectorX &x, const VectorB &b) { typedef typename linalg_traits<DenseMatrix>::value_type T; dense_matrix<T> B(mat_nrows(A), mat_ncols(A)); std::vector<int> ipvt(mat_nrows(A)); gmm::copy(A, B); size_type info = lu_factor(B, ipvt); GMM_ASSERT1(!info, "Singular system, pivot = " << info); lu_solve(B, ipvt, x, b); } template <typename DenseMatrix, typename VectorB, typename VectorX, typename Pvector> void lu_solve_transposed(const DenseMatrix &LU, const Pvector& pvector, VectorX &x, const VectorB &b) { typedef typename linalg_traits<DenseMatrix>::value_type T; copy(b, x); lower_tri_solve(transposed(LU), x, false); upper_tri_solve(transposed(LU), x, true); for(size_type i = pvector.size(); i > 0; --i) { size_type perm = pvector[i-1]-1; // permutations stored in 1's offset if(i-1 != perm) { T aux = x[i-1]; x[i-1] = x[perm]; x[perm] = aux; } } } ///@cond DOXY_SHOW_ALL_FUNCTIONS template <typename DenseMatrixLU, typename DenseMatrix, typename Pvector> void lu_inverse(const DenseMatrixLU& LU, const Pvector& pvector, DenseMatrix& AInv, col_major) { typedef typename linalg_traits<DenseMatrixLU>::value_type T; std::vector<T> tmp(pvector.size(), T(0)); std::vector<T> result(pvector.size()); for(size_type i = 0; i < pvector.size(); ++i) { tmp[i] = T(1); lu_solve(LU, pvector, result, tmp); copy(result, mat_col(AInv, i)); tmp[i] = T(0); } } template <typename DenseMatrixLU, typename DenseMatrix, typename Pvector> void lu_inverse(const DenseMatrixLU& LU, const Pvector& pvector, DenseMatrix& AInv, row_major) { typedef typename linalg_traits<DenseMatrixLU>::value_type T; std::vector<T> tmp(pvector.size(), T(0)); std::vector<T> result(pvector.size()); for(size_type i = 0; i < pvector.size(); ++i) { tmp[i] = T(1); // to be optimized !! // on peut sur le premier tri solve reduire le systeme // et peut etre faire un solve sur une serie de vecteurs au lieu // de vecteur a vecteur (accumulation directe de l'inverse dans la // matrice au fur et a mesure du calcul ... -> evite la copie finale lu_solve_transposed(LU, pvector, result, tmp); copy(result, mat_row(AInv, i)); tmp[i] = T(0); } } ///@endcond /** Given an LU factored matrix, build the inverse of the matrix. */ template <typename DenseMatrixLU, typename DenseMatrix, typename Pvector> void lu_inverse(const DenseMatrixLU& LU, const Pvector& pvector, const DenseMatrix& AInv_) { DenseMatrix& AInv = const_cast<DenseMatrix&>(AInv_); lu_inverse(LU, pvector, AInv, typename principal_orientation_type<typename linalg_traits<DenseMatrix>::sub_orientation>::potype()); } /** Given a dense matrix, build the inverse of the matrix, and return the determinant */ template <typename DenseMatrix> typename linalg_traits<DenseMatrix>::value_type lu_inverse(const DenseMatrix& A_) { typedef typename linalg_traits<DenseMatrix>::value_type T; DenseMatrix& A = const_cast<DenseMatrix&>(A_); dense_matrix<T> B(mat_nrows(A), mat_ncols(A)); std::vector<int> ipvt(mat_nrows(A)); gmm::copy(A, B); size_type info = lu_factor(B, ipvt); GMM_ASSERT1(!info, "Non invertible matrix, pivot = " << info); lu_inverse(B, ipvt, A); return lu_det(B, ipvt); } /** Compute the matrix determinant (via a LU factorization) */ template <typename DenseMatrixLU, typename Pvector> typename linalg_traits<DenseMatrixLU>::value_type lu_det(const DenseMatrixLU& LU, const Pvector &pvector) { typedef typename linalg_traits<DenseMatrixLU>::value_type T; T det(1); for (size_type j = 0; j < std::min(mat_nrows(LU), mat_ncols(LU)); ++j) det *= LU(j,j); for(size_type i = 0; i < pvector.size(); ++i) if (i != size_type(pvector[i]-1)) { det = -det; } return det; } template <typename DenseMatrix> typename linalg_traits<DenseMatrix>::value_type lu_det(const DenseMatrix& A) { typedef typename linalg_traits<DenseMatrix>::value_type T; dense_matrix<T> B(mat_nrows(A), mat_ncols(A)); std::vector<int> ipvt(mat_nrows(A)); gmm::copy(A, B); lu_factor(B, ipvt); return lu_det(B, ipvt); } } #endif
0.867188
high
L1Trigger/DTPhase2Trigger/interface/MuonPathAnalyzerPerSL.h
jaimeleonh/cmssw
1
2305137
<reponame>jaimeleonh/cmssw<filename>L1Trigger/DTPhase2Trigger/interface/MuonPathAnalyzerPerSL.h #ifndef L1Trigger_DTPhase2Trigger_MuonPathAnalyzerPerSL_cc #define L1Trigger_DTPhase2Trigger_MuonPathAnalyzerPerSL_cc #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/MuonDetId/interface/DTChamberId.h" #include "DataFormats/MuonDetId/interface/DTSuperLayerId.h" #include "DataFormats/MuonDetId/interface/DTLayerId.h" #include "DataFormats/MuonDetId/interface/DTWireId.h" #include "DataFormats/DTDigi/interface/DTDigiCollection.h" #include "L1Trigger/DTPhase2Trigger/interface/muonpath.h" #include "L1Trigger/DTPhase2Trigger/interface/analtypedefs.h" #include "L1Trigger/DTPhase2Trigger/interface/constants.h" #include "L1Trigger/DTPhase2Trigger/interface/MuonPathAnalyzer.h" #include "CalibMuon/DTDigiSync/interface/DTTTrigBaseSync.h" #include "CalibMuon/DTDigiSync/interface/DTTTrigSyncFactory.h" #include "L1Trigger/DTSectorCollector/interface/DTSectCollPhSegm.h" #include "L1Trigger/DTSectorCollector/interface/DTSectCollThSegm.h" #include "Geometry/Records/interface/MuonGeometryRecord.h" #include "Geometry/DTGeometry/interface/DTGeometry.h" #include "Geometry/DTGeometry/interface/DTLayer.h" #include <iostream> #include <fstream> // =============================================================================== // Previous definitions and declarations // =============================================================================== // =============================================================================== // Class declarations // =============================================================================== class MuonPathAnalyzerPerSL : public MuonPathAnalyzer { public: // Constructors and destructor MuonPathAnalyzerPerSL(const edm::ParameterSet& pset); virtual ~MuonPathAnalyzerPerSL(); // Main methods void initialise(const edm::EventSetup& iEventSetup); void run(edm::Event& iEvent, const edm::EventSetup& iEventSetup, std::vector<MuonPath*> &inMpath, std::vector<metaPrimitive> &metaPrimitives); void run(edm::Event& iEvent, const edm::EventSetup& iEventSetup, std::vector<MuonPath*> &inMpath, std::vector<MuonPath*> &outMPath) {}; void finish(); // Other public methods void setBXTolerance(int t); int getBXTolerance(void); void setChiSquareThreshold(float ch2Thr); void setMinimumQuality(MP_QUALITY q); MP_QUALITY getMinimumQuality(void); bool hasPosRF(int wh,int sec) { return wh>0 || (wh==0 && sec%4>1); }; // Public attributes edm::ESHandle<DTGeometry> dtGeo; //ttrig edm::FileInPath ttrig_filename; std::map<int,float> ttriginfo; //z edm::FileInPath z_filename; std::map<int,float> zinfo; //shift edm::FileInPath shift_filename; std::map<int,float> shiftinfo; int chosen_sl; private: // Private methods void analyze(MuonPath *inMPath, std::vector<metaPrimitive> &metaPrimitives); void setCellLayout(const int layout[4]); void buildLateralities(void); bool isStraightPath(LATERAL_CASES sideComb[4]); /* Determina si los valores de 4 primitivas forman una trayectoria Los valores tienen que ir dispuestos en el orden de capa: 0 -> Capa más próxima al centro del detector, 1, 2 -> Siguientes capas 3 -> Capa más externa */ void evaluatePathQuality(MuonPath *mPath); void evaluateLateralQuality(int latIdx, MuonPath *mPath, LATQ_TYPE *latQuality); /* Función que evalua, mediante el criterio de mean-timer, la bondad de una trayectoria. Involucra 3 celdas en 3 capas distintas, ordenadas de abajo arriba siguiendo el índice del array. Es decir: 0-> valor temporal de la capa inferior, 1-> valor temporal de la capa intermedia 2-> valor temporal de la capa superior Internamente implementa diferentes funciones según el paso de la partícula dependiendo de la lateralidad por la que atraviesa cada celda (p. ej.: LLR => Left (inferior); Left (media); Right (superior)) En FPGA debería aplicarse la combinación adecuada para cada caso, haciendo uso de funciones que generen el código en tiempo de síntesis, aunque la función software diseñada debería ser exportable directamente a VHDL */ void validate(LATERAL_CASES sideComb[3], int layerIndex[3], MuonPath* mPath, PARTIAL_LATQ_TYPE *latq); int eqMainBXTerm(LATERAL_CASES sideComb[2], int layerIdx[2], MuonPath* mPath); int eqMainTerm(LATERAL_CASES sideComb[2], int layerIdx[2], MuonPath* mPath, int bxValue); void getLateralCoeficients(LATERAL_CASES sideComb[2], int *coefs); bool sameBXValue(PARTIAL_LATQ_TYPE *latq); void calculatePathParameters(MuonPath *mPath); void calcTanPhiXPosChamber (MuonPath *mPath); void calcCellDriftAndXcoor (MuonPath *mPath); void calcChiSquare (MuonPath *mPath); void calcTanPhiXPosChamber3Hits(MuonPath *mPath); void calcTanPhiXPosChamber4Hits(MuonPath *mPath); int getOmittedHit(int idx); // Private attributes /* Combinaciones verticales de 3 celdas sobre las que se va a aplicar el mean-timer */ static const int LAYER_ARRANGEMENTS[4][3]; /* El máximo de combinaciones de lateralidad para 4 celdas es 16 grupos Es feo reservar todo el posible bloque de memoria de golpe, puesto que algunas combinaciones no serán válidas, desperdiciando parte de la memoria de forma innecesaria, pero la alternativa es complicar el código con vectores y reserva dinámica de memoria y, ¡bueno! ¡si hay que ir se va, pero ir p'a n'á es tontería! */ LATERAL_CASES lateralities[16][4]; LATQ_TYPE latQuality[16]; int totalNumValLateralities; /* Posiciones horizontales de cada celda (una por capa), en unidades de semilongitud de celda, relativas a la celda de la capa inferior (capa 0). Pese a que la celda de la capa 0 siempre está en posición 0 respecto de sí misma, se incluye en el array para que el código que hace el procesamiento sea más homogéneo y sencillo */ int bxTolerance; MP_QUALITY minQuality; float chiSquareThreshold; Bool_t debug; double chi2Th; double chi2corTh; double tanPhiTh; int cellLayout[4]; }; #endif
0.972656
high
examples/STM32_LAN8720/FullyFeatured_STM32_LAN8720/defines.h
khoih-prog/AsyncMQTT_Generic
4
2337889
/**************************************************************************************************************************** defines.h defines.h AsyncMqttClient_Generic is a library for ESP32, ESP8266, Protenta_H7, STM32F7, etc. with current AsyncTCP support Based on and modified from : 1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client) Built by <NAME> https://github.com/khoih-prog/AsyncMqttClient_Generic *****************************************************************************************************************************/ #ifndef defines_h #define defines_h #if !( defined(ARDUINO_BLACK_F407VE) || defined(ARDUINO_BLACK_F407VG) || defined(ARDUINO_BLACK_F407ZE) || defined(ARDUINO_BLACK_F407ZG) || \ defined(ARDUINO_BLUE_F407VE_Mini) || defined(ARDUINO_DIYMORE_F407VGT) || defined(ARDUINO_FK407M1) || defined(ARDUINO_NUCLEO_F429ZI) || \ defined(ARDUINO_DISCO_F746NG) || defined(ARDUINO_NUCLEO_F746ZG) || defined(ARDUINO_NUCLEO_F756ZG) || defined(ARDUINO_NUCLEO_H743ZI) ) //#error This code is designed to run on some STM32F407XX NUCLEO-F429ZI, STM32F746 and STM32F756 platform! Please check your Tools->Board setting. #endif // Use from 0 to 4. Higher number, more debugging messages and memory usage. #define _ASYNC_MQTT_LOGLEVEL_ 1 #define USING_LAN8720 true #if defined(STM32F0) #warning STM32F0 board selected #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #warning STM32F1 board selected #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #warning STM32F2 board selected #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #warning STM32F3 board selected #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #warning STM32F4 board selected #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #warning STM32F7 board selected #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #warning STM32L0 board selected #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #warning STM32L1 board selected #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #warning STM32L4 board selected #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #warning STM32H7 board selected #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #warning STM32G0 board selected #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #warning STM32G4 board selected #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #warning STM32WB board selected #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #warning STM32MP1 board selected #define BOARD_TYPE "STM32MP1" #else #warning STM32 unknown board selected #define BOARD_TYPE "STM32 Unknown" #endif #ifndef BOARD_NAME #define BOARD_NAME BOARD_TYPE #endif #define SHIELD_TYPE "LAN8720 Ethernet" #include <LwIP.h> #include <STM32Ethernet.h> //#include <AsyncWebServer_STM32.h> // Enter a MAC address and IP address for your controller below. #define NUMBER_OF_MAC 20 byte mac[][NUMBER_OF_MAC] = { { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x01 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x02 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x03 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x04 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x05 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x06 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x07 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x08 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x09 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0A }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0B }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0C }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0D }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0E }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0F }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x10 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x11 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x12 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x13 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x14 }, }; // Select the IP address according to your local network IPAddress ip(192, 168, 2, 232); #endif //defines_h
0.972656
high
src/nlops/chain.h
Zhitao-Li/bart
189
2370657
<filename>src/nlops/chain.h<gh_stars>100-1000 struct nlop_s; extern struct nlop_s* nlop_chain(const struct nlop_s* a, const struct nlop_s* b); extern struct nlop_s* nlop_chain_FF(const struct nlop_s* a, const struct nlop_s* b); extern struct nlop_s* nlop_chain2(const struct nlop_s* a, int o, const struct nlop_s* b, int i); extern struct nlop_s* nlop_chain2_FF(const struct nlop_s* a, int o, const struct nlop_s* b, int i); extern struct nlop_s* nlop_chain2_swap_FF(const struct nlop_s* a, int o, const struct nlop_s* b, int i); extern struct nlop_s* nlop_chain2_keep(const struct nlop_s* a, int o, const struct nlop_s* b, int i); extern struct nlop_s* nlop_chain2_keep_FF(const struct nlop_s* a, int o, const struct nlop_s* b, int i); extern struct nlop_s* nlop_chain2_keep_swap_FF(const struct nlop_s* a, int o, const struct nlop_s* b, int i); extern struct nlop_s* nlop_append_FF(const struct nlop_s* a, int o, const struct nlop_s* b); extern struct nlop_s* nlop_prepend_FF(const struct nlop_s* a, const struct nlop_s* b, int i); extern struct nlop_s* nlop_combine(const struct nlop_s* a, const struct nlop_s* b); extern struct nlop_s* nlop_combine_FF(const struct nlop_s* a, const struct nlop_s* b); extern struct nlop_s* nlop_link(const struct nlop_s* x, int oo, int ii); extern struct nlop_s* nlop_link_F(const struct nlop_s* x, int oo, int ii); extern struct nlop_s* nlop_permute_inputs(const struct nlop_s* x, int I2, const int perm[__VLA(I2)]); extern struct nlop_s* nlop_permute_outputs(const struct nlop_s* x, int O2, const int perm[__VLA(O2)]); extern struct nlop_s* nlop_permute_inputs_F(const struct nlop_s* x, int I2, const int perm[__VLA(I2)]); extern struct nlop_s* nlop_permute_outputs_F(const struct nlop_s* x, int O2, const int perm[__VLA(O2)]); extern struct nlop_s* nlop_dup(const struct nlop_s* x, int a, int b); extern struct nlop_s* nlop_dup_F(const struct nlop_s* x, int a, int b); extern struct nlop_s* nlop_stack_inputs(const struct nlop_s* x, int a, int b, int stack_dim); extern struct nlop_s* nlop_stack_inputs_F(const struct nlop_s* x, int a, int b, int stack_dim); extern struct nlop_s* nlop_stack_outputs(const struct nlop_s* x, int a, int b, int stack_dim); extern struct nlop_s* nlop_stack_outputs_F(const struct nlop_s* x, int a, int b, int stack_dim); extern struct nlop_s* nlop_shift_input(const struct nlop_s* x, int new_index, int old_index); extern struct nlop_s* nlop_shift_input_F(const struct nlop_s* x, int new_index, int old_index); extern struct nlop_s* nlop_shift_output(const struct nlop_s* x, int new_index, int old_index); extern struct nlop_s* nlop_shift_output_F(const struct nlop_s* x, int new_index, int old_index); extern struct nlop_s* nlop_stack_multiple_F(int N, const struct nlop_s* nlops[N], int II, int in_stack_dim[II], int OO, int out_stack_dim[OO]);
0.800781
high
chrome/browser/media_galleries/media_galleries_preferences.h
GnorTech/chromium
1
3803425
<reponame>GnorTech/chromium<gh_stars>1-10 // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_GALLERIES_PREFERENCES_H_ #define CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_GALLERIES_PREFERENCES_H_ #include <map> #include <set> #include <string> #include "base/basictypes.h" #include "base/files/file_path.h" #include "base/observer_list.h" #include "base/string16.h" #include "base/time.h" #include "chrome/browser/profiles/profile_keyed_service.h" #include "chrome/browser/storage_monitor/removable_storage_observer.h" class PrefRegistrySyncable; class Profile; namespace base { class DictionaryValue; } namespace extensions { class Extension; class ExtensionPrefs; } namespace chrome { typedef uint64 MediaGalleryPrefId; const MediaGalleryPrefId kInvalidMediaGalleryPrefId = 0; struct MediaGalleryPermission { MediaGalleryPrefId pref_id; bool has_permission; }; struct MediaGalleryPrefInfo { enum Type { kAutoDetected, // Auto added to the list of galleries. kUserAdded, // Explicitly added by the user. kBlackListed, // Auto added but then removed by the user. kInvalidType, }; MediaGalleryPrefInfo(); ~MediaGalleryPrefInfo(); // The absolute path of the gallery. base::FilePath AbsolutePath() const; // The ID that identifies this gallery in this Profile. MediaGalleryPrefId pref_id; // The user-visible name of this gallery. string16 display_name; // A string which uniquely and persistently identifies the device that the // gallery lives on. std::string device_id; // The root of the gallery, relative to the root of the device. base::FilePath path; // The type of gallery. Type type; // The volume label of the volume/device on which the gallery // resides. Empty if there is no such label or it is unknown. string16 volume_label; // Vendor name for the volume/device on which the gallery is located. // Will be empty if unknown. string16 vendor_name; // Model name for the volume/device on which the gallery is located. // Will be empty if unknown. string16 model_name; // The capacity in bytes of the volume/device on which the gallery is // located. Will be zero if unknown. uint64 total_size_in_bytes; // If the gallery is on a removable device, the time that device was last // attached. It is stored in preferences by the base::Time internal value, // which is microseconds since the epoch. base::Time last_attach_time; // Set to true if the volume metadata fields (volume_label, vendor_name, // model_name, total_size_in_bytes) were set. False if these fields were // never written. bool volume_metadata_valid; // 0 if the display_name is set externally and always used for display. // 1 if the display_name is only set externally when it is overriding // the name constructed from volume metadata. int prefs_version; }; typedef std::map<MediaGalleryPrefId, MediaGalleryPrefInfo> MediaGalleriesPrefInfoMap; typedef std::set<MediaGalleryPrefId> MediaGalleryPrefIdSet; // A class to manage the media gallery preferences. There is one instance per // user profile. class MediaGalleriesPreferences : public ProfileKeyedService, public RemovableStorageObserver { public: class GalleryChangeObserver { public: // |extension_id| specifies the extension affected by this change. // It is empty if the gallery change affects all extensions. virtual void OnGalleryChanged(MediaGalleriesPreferences* pref, const std::string& extension_id) {} protected: virtual ~GalleryChangeObserver(); }; explicit MediaGalleriesPreferences(Profile* profile); virtual ~MediaGalleriesPreferences(); void AddGalleryChangeObserver(GalleryChangeObserver* observer); void RemoveGalleryChangeObserver(GalleryChangeObserver* observer); // RemovableStorageObserver implementation. virtual void OnRemovableStorageAttached( const StorageMonitor::StorageInfo& info) OVERRIDE; // Lookup a media gallery and fill in information about it and return true if // it exists. Return false if it does not, filling in default information. // TODO(vandebo) figure out if we want this to be async, in which case: // void LookUpGalleryByPath(base::FilePath& path, // callback(const MediaGalleryInfo&)) bool LookUpGalleryByPath(const base::FilePath& path, MediaGalleryPrefInfo* gallery) const; MediaGalleryPrefIdSet LookUpGalleriesByDeviceId( const std::string& device_id) const; // Returns the absolute file path of the gallery specified by the // |gallery_id|. Returns an empty file path if the |gallery_id| is invalid. // Set |include_unpermitted_galleries| to true to get the file path of the // gallery to which this |extension| has no access permission. base::FilePath LookUpGalleryPathForExtension( MediaGalleryPrefId gallery_id, const extensions::Extension* extension, bool include_unpermitted_galleries); // Teaches the registry about a new gallery. // Returns the gallery's pref id. MediaGalleryPrefId AddGallery(const std::string& device_id, const base::FilePath& relative_path, bool user_added, const string16& volume_label, const string16& vendor_name, const string16& model_name, uint64 total_size_in_bytes, base::Time last_attach_time); // Teaches the registry about a new gallery. // Returns the gallery's pref id. MediaGalleryPrefId AddGalleryWithName(const std::string& device_id, const string16& display_name, const base::FilePath& relative_path, bool user_added); // Teach the registry about a user added registry simply from the path. // Returns the gallery's pref id. MediaGalleryPrefId AddGalleryByPath(const base::FilePath& path); // Removes the gallery identified by |id| from the store. void ForgetGalleryById(MediaGalleryPrefId id); MediaGalleryPrefIdSet GalleriesForExtension( const extensions::Extension& extension) const; void SetGalleryPermissionForExtension(const extensions::Extension& extension, MediaGalleryPrefId pref_id, bool has_permission); const MediaGalleriesPrefInfoMap& known_galleries() const { return known_galleries_; } // ProfileKeyedService implementation: virtual void Shutdown() OVERRIDE; static void RegisterUserPrefs(PrefRegistrySyncable* registry); // Returns true if the media gallery preferences system has ever been used // for this profile. To be exact, it checks if a gallery has ever been added // (including defaults). static bool APIHasBeenUsed(Profile* profile); private: friend class MediaGalleriesPreferencesTest; typedef std::map<std::string /*device id*/, MediaGalleryPrefIdSet> DeviceIdPrefIdsMap; // Populates the default galleries if this is a fresh profile. void AddDefaultGalleriesIfFreshProfile(); // Builds |known_galleries_| from the persistent store. // Notifies GalleryChangeObservers if |notify_observers| is true. void InitFromPrefs(bool notify_observers); // Notifies |gallery_change_observers_| about changes in |known_galleries_|. void NotifyChangeObservers(const std::string& extension_id); MediaGalleryPrefId AddGalleryInternal(const std::string& device_id, const string16& display_name, const base::FilePath& relative_path, bool user_added, const string16& volume_label, const string16& vendor_name, const string16& model_name, uint64 total_size_in_bytes, base::Time last_attach_time, bool volume_metadata_valid, int prefs_version); extensions::ExtensionPrefs* GetExtensionPrefs() const; // The profile that owns |this|. Profile* profile_; // An in-memory cache of known galleries. MediaGalleriesPrefInfoMap known_galleries_; // A mapping from device id to the set of gallery pref ids on that device. // All pref ids in |device_map_| are also in |known_galleries_|. DeviceIdPrefIdsMap device_map_; ObserverList<GalleryChangeObserver> gallery_change_observers_; DISALLOW_COPY_AND_ASSIGN(MediaGalleriesPreferences); }; } // namespace chrome #endif // CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_GALLERIES_PREFERENCES_H_
0.996094
high
ios/BaiduSDK/BaiduBCEVOD.framework/Versions/A/Headers/VODGenerateMediaIDModel.h
bingofree2015/react-native-baidubce
0
3836193
<reponame>bingofree2015/react-native-baidubce<gh_stars>0 /* * Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ #import <BaiduBCEVOD/VODMediaRelatedModel.h> /** The generate media ID request. */ @interface VODGenerateMediaIDRequest : VODMediaRelatedRequest /** Transcoding mode. Leave empty, means transcoding. For more mode, please visit https://cloud.baidu.com/doc/VOD/API.html#.E7.94.B3.E8.AF.B7.E5.AA.92.E8.B5.84. */ @property(nonatomic, copy) NSString* mode; @end /** The generate media ID response. */ @interface VODGenerateMediaIDResponse : BCEResponse /** The media ID. */ @property(nonatomic, copy) NSString* mediaID; /** The source bucket managed by BOS that media file should upload to. */ @property(nonatomic, copy) NSString* sourceBucket; /** The source key in the source bucket. */ @property(nonatomic, copy) NSString* sourceKey; /** The host of the BOS server. BOS client endpoint should be 'http[s]://<host>'. */ @property(nonatomic, copy) NSString* host; @end
0.988281
high
sys/dev/firmload.c
ArrogantWombatics/openbsd-src
1
5402353
/* $OpenBSD: firmload.c,v 1.14 2015/12/29 04:46:28 mmcc Exp $ */ /* * Copyright (c) 2004 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/syslimits.h> #include <sys/namei.h> #include <sys/vnode.h> #include <sys/errno.h> #include <sys/malloc.h> #include <sys/proc.h> #include <sys/device.h> int loadfirmware(const char *name, u_char **bufp, size_t *buflen) { struct proc *p = curproc; struct nameidata nid; char *path, *ptr; struct iovec iov; struct uio uio; struct vattr va; int error; if (!rootvp || !vcount(rootvp)) return (EIO); path = malloc(MAXPATHLEN, M_TEMP, M_NOWAIT); if (path == NULL) return (ENOMEM); if (snprintf(path, MAXPATHLEN, "/etc/firmware/%s", name) >= MAXPATHLEN) { error = ENAMETOOLONG; goto err; } NDINIT(&nid, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE, path, p); error = namei(&nid); #ifdef RAMDISK_HOOKS /* try again with mounted disk */ if (error) { if (snprintf(path, MAXPATHLEN, "/mnt/etc/firmware/%s", name) >= MAXPATHLEN) { error = ENAMETOOLONG; goto err; } NDINIT(&nid, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE, path, p); error = namei(&nid); } #endif if (error) goto err; error = VOP_GETATTR(nid.ni_vp, &va, p->p_ucred, p); if (error) goto fail; if (nid.ni_vp->v_type != VREG || va.va_size == 0) { error = EINVAL; goto fail; } if (va.va_size > FIRMWARE_MAX) { error = E2BIG; goto fail; } ptr = malloc(va.va_size, M_DEVBUF, M_NOWAIT); if (ptr == NULL) { error = ENOMEM; goto fail; } iov.iov_base = ptr; iov.iov_len = va.va_size; uio.uio_iov = &iov; uio.uio_iovcnt = 1; uio.uio_offset = 0; uio.uio_resid = va.va_size; uio.uio_segflg = UIO_SYSSPACE; uio.uio_rw = UIO_READ; uio.uio_procp = p; error = VOP_READ(nid.ni_vp, &uio, 0, p->p_ucred); if (error == 0) { *bufp = ptr; *buflen = va.va_size; } else free(ptr, M_DEVBUF, va.va_size); fail: vput(nid.ni_vp); err: free(path, M_TEMP, MAXPATHLEN); return (error); }
0.988281
high
Sony_MDXC7900R/src/mdx7900r.c
kbiva/stm32f103_projects
19
5435121
/* * mdx7900r.c * * Sony MDX-C7900R face plate demo * * Author: <NAME> */ #include "stm32f10x_conf.h" #include "mdx7900r.h" static uint8_t data[32]; static uint8_t symbols_set[8]; static PIN pins[]={ {{CLK_Pin,CLK_Speed,CLK_Mode},CLK_Port,CLK_Bus}, {{DO_Pin,DO_Speed,DO_Mode},DO_Port,DO_Bus}, {{CE_Pin, CE_Speed, CE_Mode}, CE_Port, CE_Bus}, {{KEYIN0_Pin, KEYIN0_Speed, KEYIN0_Mode}, KEYIN0_Port, KEYIN0_Bus}, {{KEYIN1_Pin, KEYIN1_Speed, KEYIN1_Mode}, KEYIN1_Port, KEYIN1_Bus}, {{DBASS_Pin, DBASS_Speed, DBASS_Mode}, DBASS_Port, DBASS_Bus}, {{VOLMINUS_Pin, VOLMINUS_Speed, VOLMINUS_Mode}, VOLMINUS_Port, VOLMINUS_Bus}, {{VOLPLUS_Pin, VOLPLUS_Speed, VOLPLUS_Mode}, VOLPLUS_Port, VOLPLUS_Bus}, }; void GPIO_Configuration(void) { uint32_t i; SPI_InitTypeDef SPI_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct; // Pins GPIO configuration for(i=0;i<sizeof(pins)/sizeof(PIN);i++) { RCC_APB2PeriphClockCmd(pins[i].GPIO_Bus,ENABLE); GPIO_Init(pins[i].GPIOx,&pins[i].GPIO_InitStructure); } // SPI2 configuration RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); SPI_InitStructure.SPI_Direction = SPI_Direction_1Line_Tx; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_32; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(SPI2, &SPI_InitStructure); SPI_Cmd(SPI2, ENABLE); // Encoder configuration RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE); TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStruct.TIM_Period=1; TIM_TimeBaseInitStruct.TIM_Prescaler=0; TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStruct); TIM_EncoderInterfaceConfig(TIM4,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising); TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE); TIM_Cmd(TIM4, ENABLE); NVIC_EnableIRQ(TIM4_IRQn); } void MDX7900R_init(void) { GPIO_ResetBits(CE_Port,CE_Pin); data[0]=CMD_DISPLAY_SETTING| CMD_DISPLAY_SETTING_VOLTAGE_INTERNAL| CMD_DISPLAY_SETTING_MASTER| CMD_DISPLAY_SETTING_1_8_DUTY; MDX7900R_send(1); data[0]=CMD_STATUS| CMD_STATUS_TEST_OFF| CMD_STATUS_STANDBY_OFF| CMD_STATUS_KEY_SCAN_CONTROL_STOP| CMD_STATUS_LED_OFF| CMD_STATUS_LCD_OFF; MDX7900R_send(1); data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_FIXED| CMD_DATA_SETTING_WRITE_LED_OUTPUT_LATCH; data[1]=LEDS_OFF; MDX7900R_send(2); data[0]=CMD_STATUS| CMD_STATUS_TEST_OFF| CMD_STATUS_STANDBY_OFF| CMD_STATUS_KEY_SCAN_CONTROL_STOP| CMD_STATUS_LED_ON| CMD_STATUS_LCD_ON; MDX7900R_send(1); } void MDX7900R_backlight(BACKLIGHT val) { data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_FIXED| CMD_DATA_SETTING_WRITE_LED_OUTPUT_LATCH; data[1]=val; MDX7900R_send(2); } static void sendByte(uint8_t byte) { SPI_I2S_SendData(SPI2,byte); while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_BSY) == SET){}; } void MDX7900R_send(uint8_t length) { uint8_t i; GPIO_SetBits(CE_Port,CE_Pin); for(i=0;i<length;i++) { sendByte(data[i]); } GPIO_ResetBits(CE_Port,CE_Pin); } void MDX7900R_text(uint8_t pos,char* text,uint8_t clear) { uint8_t i=1; if(clear) { MDX7900R_clear_text(pos); } data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_INCREMENT| CMD_DATA_SETTING_WRITE_DISPLAY_DATA_RAM; MDX7900R_send(1); data[0]=CMD_ADDRESS_SETTING+pos; while(*text) { data[i++]=*text++; } MDX7900R_send(i); } void MDX7900R_clear_text(uint8_t start) { uint8_t i; data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_INCREMENT| CMD_DATA_SETTING_WRITE_DISPLAY_DATA_RAM; MDX7900R_send(1); data[0]=CMD_ADDRESS_SETTING+start; for(i=1;i<14-start;i++) { data[i]=' '; } MDX7900R_send(14-start); } void MDX7900R_clear_symbols(void) { uint8_t i; data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_INCREMENT| CMD_DATA_SETTING_WRITE_CHARACTER_DISPLAY; MDX7900R_send(1); data[0]=CMD_ADDRESS_SETTING; for(i=1;i<9;i++) { data[i]=0x00; symbols_set[i-1]=0; } MDX7900R_send(9); } void MDX7900R_create_char(uint8_t pos,uint8_t* character) { uint8_t i; data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_FIXED| CMD_DATA_SETTING_WRITE_CGRAM; MDX7900R_send(1); data[0]=CMD_ADDRESS_SETTING+pos; for(i=1;i<8;i++) { data[i]=*character++; } MDX7900R_send(8); } void MDX7900R_symbol(uint16_t symbol,uint8_t on) { data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_INCREMENT| CMD_DATA_SETTING_WRITE_CHARACTER_DISPLAY; MDX7900R_send(1); data[0]=CMD_ADDRESS_SETTING+(symbol>>8); if(on) { data[1]=symbols_set[symbol>>8]|symbol; symbols_set[symbol>>8]|=symbol; } else { data[1]=symbols_set[symbol>>8]&~symbol; symbols_set[symbol>>8]&=~symbol; } MDX7900R_send(2); } void MDX7900R_fill_symbols(void) { data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_INCREMENT| CMD_DATA_SETTING_WRITE_CHARACTER_DISPLAY; MDX7900R_send(1); data[0]=CMD_ADDRESS_SETTING; data[1]=(uint8_t)(SYMBOL_DOUBLE_COLON|SYMBOL_1|SYMBOL_2); symbols_set[0]=(uint8_t)(SYMBOL_DOUBLE_COLON|SYMBOL_1|SYMBOL_2); data[2]=(uint8_t)(SYMBOL_BIG1|SYMBOL_REG|SYMBOL_ST|SYMBOL_EON|SYMBOL_TP|SYMBOL_TA|SYMBOL_LCL|SYMBOL_AF); symbols_set[1]=(uint8_t)(SYMBOL_BIG1|SYMBOL_REG|SYMBOL_ST|SYMBOL_EON|SYMBOL_TP|SYMBOL_TA|SYMBOL_LCL|SYMBOL_AF); data[3]=(uint8_t)(SYMBOL_ARROW_LEFT|SYMBOL_BANK|SYMBOL_DISC); symbols_set[2]=(uint8_t)(SYMBOL_ARROW_LEFT|SYMBOL_BANK|SYMBOL_DISC); data[4]=(uint8_t)(SYMBOL_PLAYMODE|SYMBOL_SETUP); symbols_set[3]=(uint8_t)(SYMBOL_PLAYMODE|SYMBOL_SETUP); data[5]=(uint8_t)(SYMBOL_2REP|SYMBOL_1REP|SYMBOL_REP_TOP|SYMBOL_MONO|SYMBOL_TRACK|SYMBOL_ARROW_RIGHT); symbols_set[4]=(uint8_t)(SYMBOL_2REP|SYMBOL_1REP|SYMBOL_REP_TOP|SYMBOL_MONO|SYMBOL_TRACK|SYMBOL_ARROW_RIGHT); data[6]=(uint8_t)(SYMBOL_ALL|SYMBOL_1SHUF|SYMBOL_SHUF_TOP); symbols_set[5]=(uint8_t)(SYMBOL_ALL|SYMBOL_1SHUF|SYMBOL_SHUF_TOP); data[7]=(uint8_t)(SYMBOL_REP_BOTTOM|SYMBOL_ENTER); symbols_set[6]=(uint8_t)(SYMBOL_REP_BOTTOM|SYMBOL_ENTER); data[8]=(uint8_t)(SYMBOL_DBASS|SYMBOL_DIGITAL|SYMBOL_SHUF_BOTTOM); symbols_set[7]=(uint8_t)(SYMBOL_DBASS|SYMBOL_DIGITAL|SYMBOL_SHUF_BOTTOM); MDX7900R_send(9); } void MDX7900R_symbol_1(void) { data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_FIXED| CMD_DATA_SETTING_WRITE_CHARACTER_DISPLAY; MDX7900R_send(1); data[0]=CMD_ADDRESS_SETTING; data[1]=SYMBOL_1; MDX7900R_send(2); } void MDX7900R_symbol_2(void) { data[0]=CMD_DATA_SETTING| CMD_DATA_SETTING_ADDRESS_FIXED| CMD_DATA_SETTING_WRITE_CHARACTER_DISPLAY; MDX7900R_send(1); data[0]=CMD_ADDRESS_SETTING; data[1]=SYMBOL_2; MDX7900R_send(2); }
0.984375
high
Plugins/PulldownBuilder/Source/PulldownBuilder/Private/PulldownBuilder/Assets/PulldownContentsFactory.h
Naotsun19B/PulldownBuilder
3
5467889
// Copyright 2021 Naotsun. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Factories/Factory.h" #include "PulldownContentsFactory.generated.h" /** * Pulldown Contents Factory class that creates assets. */ UCLASS(NotBlueprintable, HideCategories = "Object") class PULLDOWNBUILDER_API UPulldownContentsFactory : public UFactory { GENERATED_UCLASS_BODY() public: // UFactory interface. virtual bool DoesSupportClass(UClass* Class) override; virtual UClass* ResolveSupportedClass() override; virtual UObject* FactoryCreateNew( UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn ) override; // End of UFactory interface. };
0.96875
high
ios/ArgumentAdapter.h
rongcloud/rongcloud-react-native-rtcsdk
0
5500657
// // ArgumentAdapter.hpp // rongcloud_rtc_wrapper_plugin // // Created by 潘铭达 on 2021/6/11. // #ifndef ArgumentAdapter_h #define ArgumentAdapter_h #import <RongRTCLibWrapper/RCRTCIWEngine.h> #ifdef __cplusplus extern "C" { #endif RCRTCIWMediaType toMediaType(int type); RCRTCIWCamera toCamera(int camera); RCRTCIWCameraCaptureOrientation toCameraCaptureOrientation(int orientation); RCRTCIWLiveMixLayoutMode toLiveMixLayoutMode(int mode); RCRTCIWLiveMixRenderMode toLiveMixRenderMode(int mode); RCRTCIWVideoResolution toVideoResolution(int resolution); RCRTCIWVideoFps toVideoFps(int fps); RCRTCIWAudioMixingMode toAudioMixingMode(int mode); RCRTCIWAudioCodecType toAudioCodecType(int type); RCRTCIWRole toRole(int role); RCRTCIWAudioQuality toAudioQuality(int quality); RCRTCIWAudioScenario toAudioScenario(int scenario); RCRTCIWEngineSetup *toEngineSetup(NSDictionary *arguments); RCRTCIWRoomSetup *toRoomSetup(NSDictionary *arguments); RCRTCIWAudioConfig *toAudioConfig(NSDictionary *arguments); RCRTCIWVideoConfig *toVideoConfig(NSDictionary *arguments); NSArray<RCRTCIWCustomLayout *> *toLiveMixCustomLayouts(NSArray<NSDictionary *> *arguments); NSDictionary *fromNetworkStats(RCRTCIWNetworkStats *stats); NSDictionary *fromLocalAudioStats(RCRTCIWLocalAudioStats *stats); NSDictionary *fromLocalVideoStats(RCRTCIWLocalVideoStats *stats); NSDictionary *fromRemoteAudioStats(RCRTCIWRemoteAudioStats *stats); NSDictionary *fromRemoteVideoStats(RCRTCIWRemoteVideoStats *stats); #ifdef __cplusplus } #endif #endif /* ArgumentAdapter_h */
0.96875
high
tests/demo/Demo.h
kan-xyz/Arc
4
5533425
#pragma once namespace Demo { void Demo(); }
0.929688
low
src/core/tc_hash.c
huayl/tcpcopy
3,474
5566193
#include <xcopy.h> static hash_node * hash_node_malloc(tc_pool_t *pool, uint64_t key, void *data) { hash_node *hn = (hash_node *) tc_palloc(pool, sizeof(hash_node)); if (hn != NULL) { hn->key = key; hn->data = data; hn->create_time = tc_time(); hn->access_time = tc_time(); } else { tc_log_info(LOG_ERR, errno, "can't malloc memory for hash node"); } return hn; } static p_link_node hash_find_link_node(hash_table *table, uint64_t key) { bool first = true; hash_node *hn; link_list *l = get_link_list(table, key); p_link_node ln = link_list_first(l); while (ln) { hn = (hash_node *) ln->data; if (hn->key == key) { hn->access_time = tc_time(); if (!first) { /* put the lastest item to the head of the linked list */ link_list_remove(l, ln); link_list_push(l, ln); } return ln; } ln = link_list_get_next(l, ln); first = false; } return NULL; } hash_table * hash_create(tc_pool_t *pool, uint32_t size) { size_t i; hash_table *ht = (hash_table *) tc_pcalloc(pool, sizeof(hash_table)); if (ht != NULL) { ht->pool = pool; ht->size = size; ht->lists = (link_list **) tc_pcalloc(pool, size * sizeof(link_list *)); if (ht->lists != NULL) { for (i = 0; i < size; i++) { ht->lists[i] = link_list_create(pool); } } else { tc_log_info(LOG_ERR, errno, "can't calloc memory for hash lists"); ht = NULL; } } else { tc_log_info(LOG_ERR, errno, "can't calloc memory for hash table"); } return ht; } void * hash_find(hash_table *table, uint64_t key) { hash_node *hn; p_link_node ln = hash_find_link_node(table, key); if (ln != NULL) { hn = (hash_node *) ln->data; return hn->data; } return NULL; } hash_node * hash_find_node(hash_table *table, uint64_t key) { hash_node *hn; p_link_node ln = hash_find_link_node(table, key); if (ln != NULL) { hn = (hash_node *) ln->data; return hn; } return NULL; } bool hash_add(hash_table *table, tc_pool_t *pool, uint64_t key, void *data) { hash_node *hn, *tmp; link_list *l; p_link_node ln; ln = hash_find_link_node(table, key); if (ln == NULL) { tmp = hash_node_malloc(pool, key, data); if (tmp != NULL) { l = get_link_list(table, key); ln = link_node_malloc(pool, tmp); if (ln != NULL) { link_list_push(l, ln); table->total++; return true; } else { return false; } } else { return false; } } else { hn = (hash_node *) ln->data; hn->data = data; return false; } } bool hash_del(hash_table *table, tc_pool_t *pool, uint64_t key) { link_list *l = get_link_list(table, key); p_link_node ln = hash_find_link_node(table, key); if (ln != NULL) { table->total--; link_list_remove(l, ln); tc_pfree(pool, ln->data); tc_pfree(pool, ln); return true; } else { return false; } }
0.996094
high
examples/computers/phones.h
Pendar-Tech/QttpServer
0
5598961
<filename>examples/computers/phones.h<gh_stars>0 #ifndef PHONES_H #define PHONES_H #include <qttp_action.h> class Phones : public qttp::Action { public: Phones() : Action(), phones({ { "iphone", "apple" }, { "pixel", "google" }, { "nexus", "google" }, { "galaxy", "samsung" } }) { } const char* getName() const { return "phone-action"; } QJsonArray allPhoneModels() { QJsonArray models; for(QString phone : phones.keys()) models.append(phone); return models; } void onGet(qttp::HttpData& data) { const QJsonObject& request = data.getRequest().getJson(); if(request.contains("model")) { bool containsModel = phones.contains(request["model"].toString()); if(containsModel) { QString model = request["model"].toString(); QString make = phones[model]; data.getResponse().getJson()[model] = make; } data.getResponse().setStatus(containsModel ? qttp::HttpStatus::OK : qttp::HttpStatus::BAD_REQUEST); return; } // If a model was not specified return all models. data.getResponse().getJson()["list"] = allPhoneModels(); } void onPut(qttp::HttpData& data) { bool isSuccessful = false; QJsonValue model = data.getRequest().getJson()["model"]; QJsonValue make = data.getRequest().getJson()["make"]; // The request should contain a model and a make to insert. if(model.isString() && make.isString()) { phones.insert(model.toString(), make.toString()); isSuccessful = true; } // List all models after updating the list of phones; data.getResponse().getJson()["list"] = allPhoneModels(); data.getResponse().getJson()["success"] = isSuccessful; data.getResponse().setStatus(isSuccessful ? qttp::HttpStatus::OK : qttp::HttpStatus::BAD_REQUEST); } QHash<QString, QString> phones; }; #endif // PHONES_H
0.917969
high
ns3-sat-sim/simulator/contrib/basic-sim/helper/core/point-to-point-ab-helper.h
kalelpida/hypatia
1
7031729
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Simon * Adapted from PointToPointHelper by: * Author: <NAME> <<EMAIL>> */ #ifndef POINT_TO_POINT_AB_HELPER_H #define POINT_TO_POINT_AB_HELPER_H #include <string> #include "ns3/object-factory.h" #include "ns3/net-device-container.h" #include "ns3/node-container.h" #include "ns3/trace-helper.h" namespace ns3 { class NetDevice; class Node; class PointToPointAbHelper { public: PointToPointAbHelper(); void SetQueueFactoryA(ObjectFactory queueFactoryA); void SetQueueFactoryB(ObjectFactory queueFactoryB); void SetDeviceAttributeA(std::string name, const AttributeValue &value); void SetDeviceAttributeB(std::string name, const AttributeValue &value); void SetChannelAttribute(std::string name, const AttributeValue &value); NetDeviceContainer Install(Ptr <Node> a, Ptr <Node> b); private: ObjectFactory m_queueFactoryA; //!< Queue Factory A ObjectFactory m_deviceFactoryA; //!< Device Factory A ObjectFactory m_queueFactoryB; //!< Queue Factory B ObjectFactory m_deviceFactoryB; //!< Device Factory B ObjectFactory m_channelFactory; //!< Channel Factory #ifdef NS3_MPI ObjectFactory m_remoteChannelFactory; //!< Remote Channel Factory #endif }; } // namespace ns3 #endif /* POINT_TO_POINT_AB_HELPER_H */
0.996094
high
src/output/sketch/LCD.h
MakeNTU/2021_team02_
0
7064497
<filename>src/output/sketch/LCD.h<gh_stars>0 #ifndef LIQUID_CRYSTAL #define LIQUID_CRYSTAL #include <LiquidCrystal.h> #include "myPinMap.h" LiquidCrystal lcd(rs, en, d4, d5, d6, d7); #endif
0.929688
low
src/bpf_dump_helpers.h
lumontec/lsmtrace
14
3232552
// Copyright 2020 (C) <NAME> <<EMAIL>> // // 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 __BPF_HELPERS_H #define __BPF_HELPERS_H #include "vmlinux.h" #include <bpf/bpf_helpers.h> #include <bpf/bpf_tracing.h> #include <bpf/bpf_core_read.h> #include "events.h" #define FILTER_CATHEGORY_INT(CATH) \ if (CATH != cathegory && cathegory != ALL_CATH) \ return 0; #define FILTER_CATHEGORY_VOID(CATH) \ if (CATH != cathegory && cathegory != ALL_CATH) \ return ; #define FILTER_OWN_PID_INT() \ int pid = bpf_get_current_pid_tgid() >> 32; \ if (pid != my_pid) \ return 0; #define FILTER_OWN_PID_VOID() \ int pid = bpf_get_current_pid_tgid() >> 32; \ if (pid != my_pid) \ return; /* Maps declaration */ struct { __uint(type, BPF_MAP_TYPE_RINGBUF); __uint(max_entries, 1 << 24); } ringbuf SEC(".maps"); /* Globals */ long ringbuffer_flags = 0; int my_pid = 0; const volatile enum { ALL_CATH = 0, PROG_EXEC_CATH = 1, MOUNT_FS_CATH = 2, FILE_CATH = 10, INODE_CATH = 20 } cathegory; char struct_dump_label[MAX_MSG_SIZE] = "STRUCT_DUMP"; /* Dirty macro hacks to work around libbpf lack of string locals */ #define DUMP_FUNC(FNAME, ...) { \ const char func_call_name[] = #FNAME; \ const char func_call_args[] = #__VA_ARGS__; \ dump_func(func_call_name, func_call_args); \ } #define DUMP_MEMBER_SUINT(...) { \ const char dump_member_name[] = #__VA_ARGS__; \ short unsigned int mptr = BPF_CORE_READ(__VA_ARGS__); \ dump_suint_member(dump_member_name, mptr); \ } #define DUMP_MEMBER_UINT(...) { \ const char dump_member_name[] = #__VA_ARGS__; \ unsigned int mptr = BPF_CORE_READ(__VA_ARGS__); \ dump_uint_member(dump_member_name, mptr); \ } #define DUMP_MEMBER_LUINT(...) { \ const char dump_member_name[] = #__VA_ARGS__; \ long unsigned int mptr = BPF_CORE_READ(__VA_ARGS__); \ dump_luint_member(dump_member_name, mptr); \ } #define DUMP_MEMBER_LINT(...) { \ const char dump_member_name[] = #__VA_ARGS__; \ long int mptr = BPF_CORE_READ(__VA_ARGS__); \ dump_lint_member(dump_member_name, mptr); \ } #define DUMP_MEMBER_LLINT(...) { \ const char dump_member_name[] = #__VA_ARGS__; \ long long int mptr = BPF_CORE_READ(__VA_ARGS__); \ dump_llint_member(dump_member_name, mptr); \ } #define DUMP_MEMBER_USTR(...) { \ const char dump_member_name[] = #__VA_ARGS__; \ const unsigned char *mptr = BPF_CORE_READ(__VA_ARGS__); \ dump_ustr_member(dump_member_name, mptr); \ } #define DUMP_MEMBER_STR(...) { \ const char dump_member_name[] = #__VA_ARGS__; \ const char *mptr = BPF_CORE_READ(__VA_ARGS__); \ dump_str_member(dump_member_name, mptr); \ } static int dump_func(const char *fname, const char *fargs) { struct func_call_Event *evt; char func_call_label[] = "HOOK_CALL"; evt = bpf_ringbuf_reserve(&ringbuf, sizeof(*evt), ringbuffer_flags); if (!evt) return -1; evt->super.etype = FUNCTION_CALL; bpf_probe_read_str(evt->super.label, sizeof(evt->super.label), func_call_label); bpf_probe_read_str(evt->name, sizeof(evt->name), fname); bpf_probe_read_str(evt->args, sizeof(evt->args), fargs); bpf_ringbuf_submit(evt, ringbuffer_flags); return 0; } static int dump_suint_member(const char *mname, short unsigned int mptr) { struct suint_member_Event *evt; char suint_member_label[] = "MEMBER_DUMP"; evt = bpf_ringbuf_reserve(&ringbuf, sizeof(*evt), ringbuffer_flags); if (!evt) return -1; evt->super.etype = MEMBER_SUINT; bpf_probe_read_str(evt->super.label, sizeof(evt->super.label), suint_member_label); evt->member = mptr; bpf_probe_read_str(evt->msg, sizeof(evt->msg), mname); bpf_ringbuf_submit(evt, ringbuffer_flags); return 0; } static int dump_uint_member(const char *mname, unsigned int mptr) { struct uint_member_Event *evt; char uint_member_label[] = "MEMBER_DUMP"; evt = bpf_ringbuf_reserve(&ringbuf, sizeof(*evt), ringbuffer_flags); if (!evt) return -1; evt->super.etype = MEMBER_UINT; bpf_probe_read_str(evt->super.label, sizeof(evt->super.label), uint_member_label); evt->member = mptr; bpf_probe_read_str(evt->msg, sizeof(evt->msg), mname); bpf_ringbuf_submit(evt, ringbuffer_flags); return 0; } static int dump_luint_member(const char *mname, long unsigned int mptr) { struct luint_member_Event *evt; char luint_member_label[] = "MEMBER_DUMP"; evt = bpf_ringbuf_reserve(&ringbuf, sizeof(*evt), ringbuffer_flags); if (!evt) return -1; evt->super.etype = MEMBER_LUINT; bpf_probe_read_str(evt->super.label, sizeof(evt->super.label), luint_member_label); evt->member = mptr; bpf_probe_read_str(evt->msg, sizeof(evt->msg), mname); bpf_ringbuf_submit(evt, ringbuffer_flags); return 0; } static long dump_lint_member(const char *mname, unsigned int mptr) { struct lint_member_Event *evt; char lint_member_label[] = "MEMBER_DUMP"; evt = bpf_ringbuf_reserve(&ringbuf, sizeof(*evt), ringbuffer_flags); if (!evt) return -1; evt->super.etype = MEMBER_LINT; bpf_probe_read_str(evt->super.label, sizeof(evt->super.label), lint_member_label); evt->member = mptr; bpf_probe_read_str(evt->msg, sizeof(evt->msg), mname); bpf_ringbuf_submit(evt, ringbuffer_flags); return 0; } static long dump_llint_member(const char *mname, unsigned int mptr) { struct llint_member_Event *evt; char llint_member_label[] = "MEMBER_DUMP"; evt = bpf_ringbuf_reserve(&ringbuf, sizeof(*evt), ringbuffer_flags); if (!evt) return -1; evt->super.etype = MEMBER_LLINT; bpf_probe_read_str(evt->super.label, sizeof(evt->super.label), llint_member_label); evt->member = mptr; bpf_probe_read_str(evt->msg, sizeof(evt->msg), mname); bpf_ringbuf_submit(evt, ringbuffer_flags); return 0; } static int dump_str_member(const char *mname, const char *mptr) { struct str_member_Event *evt; char uint_member_label[] = "MEMBER_DUMP"; evt = bpf_ringbuf_reserve(&ringbuf, sizeof(*evt), ringbuffer_flags); if (!evt) return -1; evt->super.etype = MEMBER_STR; bpf_probe_read_str(evt->super.label, sizeof(evt->super.label), uint_member_label); bpf_probe_read_str(evt->member, sizeof(evt->member), mptr); bpf_probe_read_str(evt->msg, sizeof(evt->msg), mname); bpf_ringbuf_submit(evt, ringbuffer_flags); return 0; } static int dump_ustr_member(const char *mname, const unsigned char *mptr) { struct str_member_Event *evt; char uint_member_label[] = "MEMBER_DUMP"; evt = bpf_ringbuf_reserve(&ringbuf, sizeof(*evt), ringbuffer_flags); if (!evt) return -1; evt->super.etype = MEMBER_STR; bpf_probe_read_str(evt->super.label, sizeof(evt->super.label), uint_member_label); bpf_probe_read_str(evt->member, sizeof(evt->member), mptr); bpf_probe_read_str(evt->msg, sizeof(evt->msg), mname); bpf_ringbuf_submit(evt, ringbuffer_flags); return 0; } #endif /* _BPF_HELPERS_H */
0.996094
high
mach/proto/ncg/fillem.h
Godzil/ack
6
3265320
<gh_stars>1-10 /* * The Amsterdam Compiler Kit * See the copyright notice in the ACK home directory, in the file "Copyright". */ #ifndef MACH_PROTO_NCG_FILLEM_H #define MACH_PROTO_NCG_FILLEM_H /* mach/proto/ncg/fillem.c */ long our_atol(char *s); void in_init(char *filename); void in_start(void); void in_finish(void); void fillemlines(void); void dopseudo(void); int getarg(int typset); int table1(void); int table2(void); int table3(int i); int get16(void); long get32(void); void getstring(void); char *strarg(int t); void bss(int n, int t, int b); long con(int t); void swtxt(void); void switchseg(int s); void savelab(void); void dumplab(void); void xdumplab(void); void part_flush(void); string holstr(long n); #endif /* MACH_PROTO_NCG_FILLEM_H */
0.941406
high
camera/QCamera2/stack/mm-camera-test/inc/mm_qcamera_main_menu.h
radu-v/android_device_nokia_nb1
1
3298088
/* Copyright (c) 2013, 2016, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __MM_QCAMERA_MAIN_MENU_H__ #define __MM_QCAMERA_MAIN_MENU_H__ // Camera dependencies #include "mm_camera_interface.h" #include "mm_jpeg_interface.h" #define VIDEO_BUFFER_SIZE (PREVIEW_WIDTH * PREVIEW_HEIGHT * 3/2) #define THUMBNAIL_BUFFER_SIZE (THUMBNAIL_WIDTH * THUMBNAIL_HEIGHT * 3/2) #define SNAPSHOT_BUFFER_SIZE (PICTURE_WIDTH * PICTURE_HEIGHT * 3/2) /*=========================================================================== * Macro *===========================================================================*/ #define PREVIEW_FRAMES_NUM 5 #define VIDEO_FRAMES_NUM 5 #define THUMBNAIL_FRAMES_NUM 1 #define SNAPSHOT_FRAMES_NUM 1 #define MAX_NUM_FORMAT 32 typedef enum { START_PREVIEW, STOP_PREVIEW, SET_WHITE_BALANCE, SET_TINTLESS_ENABLE, TOGGLE_SHDR, SET_EXP_METERING, TOGGLE_IRLED, TOGGLE_EZTUNE, SET_ISO, BRIGHTNESS_GOTO_SUBMENU, CONTRAST_GOTO_SUBMENU, EV_GOTO_SUBMENU, SATURATION_GOTO_SUBMENU, SET_ZOOM, SET_SHARPNESS, TAKE_JPEG_SNAPSHOT, START_RECORDING, STOP_RECORDING, BEST_SHOT, LIVE_SHOT, FLASH_MODES, TOGGLE_ZSL, TAKE_RAW_SNAPSHOT, SWITCH_SNAP_RESOLUTION, TOGGLE_WNR, SPECIAL_EFFECTS, SET_MN_WHITE_BALANCE, ANTI_BANDING, SET_FLIP_MODE, BURST_MODE_SNAPSHOT, CONCURRENT_NDR_NONHDR, EXIT } Camera_main_menu_t; typedef enum { ACTION_NO_ACTION, ACTION_START_PREVIEW, ACTION_STOP_PREVIEW, ACTION_SET_WHITE_BALANCE, ACTION_SET_MN_WHITE_BALANCE, ACTION_SET_TINTLESS_ENABLE, ACTION_TOGGLE_SHDR, ACTION_SET_EXP_METERING, ACTION_TOGGLE_IR_MODE, ACTION_TOGGLE_AFR, ACTION_TOGGLE_EZTUNE, ACTION_SET_ISO, ACTION_BRIGHTNESS_INCREASE, ACTION_BRIGHTNESS_DECREASE, ACTION_CONTRAST_INCREASE, ACTION_CONTRAST_DECREASE, ACTION_EV_INCREASE, ACTION_EV_DECREASE, ACTION_SATURATION_INCREASE, ACTION_SATURATION_DECREASE, ACTION_SET_ZOOM, ACTION_SHARPNESS_INCREASE, ACTION_SHARPNESS_DECREASE, ACTION_TAKE_JPEG_SNAPSHOT, ACTION_START_RECORDING, ACTION_STOP_RECORDING, ACTION_SET_BESTSHOT_MODE, ACTION_TAKE_LIVE_SNAPSHOT, ACTION_SET_FLASH_MODE, ACTION_SWITCH_CAMERA, ACTION_TOGGLE_ZSL, ACTION_TAKE_RAW_SNAPSHOT, ACTION_SWITCH_RESOLUTION, ACTION_TOGGLE_WNR, ACTION_SPECIAL_EFFECTS, ACTION_ANTI_BANDING, ACTION_BURST_MODE_SNAPSHOT, ACTION_FLIP_MODE, ACTION_CONCURRENT_NDR_NONHDR, ACTION_EXIT } camera_action_t; #define INVALID_KEY_PRESS 0 #define BASE_OFFSET ('Z' - 'A' + 1) #define BASE_OFFSET_NUM ('Z' - 'A' + 2) #define PAD_TO_WORD(a) (((a)+3)&~3) #define SQCIF_WIDTH 128 #define SQCIF_HEIGHT 96 #define QCIF_WIDTH 176 #define QCIF_HEIGHT 144 #define QVGA_WIDTH 320 #define QVGA_HEIGHT 240 #define HD_THUMBNAIL_WIDTH 256 #define HD_THUMBNAIL_HEIGHT 144 #define CIF_WIDTH 352 #define CIF_HEIGHT 288 #define VGA_WIDTH 640 #define VGA_HEIGHT 480 #define WVGA_WIDTH 800 #define WVGA_HEIGHT 480 #define WVGA_PLUS_WIDTH 960 #define WVGA_PLUS_HEIGHT 720 #define MP1_WIDTH 1280 #define MP1_HEIGHT 960 #define MP2_WIDTH 1600 #define MP2_HEIGHT 1200 #define MP3_WIDTH 2048 #define MP3_HEIGHT 1536 #define MP5_WIDTH 2592 #define MP5_HEIGHT 1944 #define MP8_WIDTH 3264 #define MP8_HEIGHT 2448 #define MP12_WIDTH 4000 #define MP12_HEIGHT 3000 #define SVGA_WIDTH 800 #define SVGA_HEIGHT 600 #define XGA_WIDTH 1024 #define XGA_HEIGHT 768 #define HD720_WIDTH 1280 #define HD720_HEIGHT 720 #define HD720_PLUS_WIDTH 1440 #define HD720_PLUS_HEIGHT 1080 #define WXGA_WIDTH 1280 #define WXGA_HEIGHT 768 #define HD1080_WIDTH 1920 #define HD1080_HEIGHT 1080 #define ONEMP_WIDTH 1280 #define SXGA_WIDTH 1280 #define UXGA_WIDTH 1600 #define QXGA_WIDTH 2048 #define FIVEMP_WIDTH 2560 #define ONEMP_HEIGHT 960 #define SXGA_HEIGHT 1024 #define UXGA_HEIGHT 1200 #define QXGA_HEIGHT 1536 #define FIVEMP_HEIGHT 1920 typedef enum { RESOLUTION_MIN, QCIF = RESOLUTION_MIN, QVGA, VGA, WVGA, WVGA_PLUS , HD720, HD720_PLUS, HD1080, RESOLUTION_PREVIEW_VIDEO_MAX = HD1080, WXGA, MP1, MP2, MP3, MP5, MP8, MP12, RESOLUTION_MAX = MP12, } Camera_Resolution; typedef struct{ uint16_t width; uint16_t height; char * name; char * str_name; int supported; } DIMENSION_TBL_T; typedef enum { WHITE_BALANCE_STATE, WHITE_BALANCE_TEMPERATURE, BRIGHTNESS_CTRL, EV, CONTRAST_CTRL, SATURATION_CTRL, SHARPNESS_CTRL } Get_Ctrl_modes; typedef enum { AUTO_EXP_FRAME_AVG, AUTO_EXP_CENTER_WEIGHTED, AUTO_EXP_SPOT_METERING, AUTO_EXP_SMART_METERING, AUTO_EXP_USER_METERING, AUTO_EXP_SPOT_METERING_ADV, AUTO_EXP_CENTER_WEIGHTED_ADV, AUTO_EXP_MAX } Exp_Metering_modes; typedef enum { ISO_AUTO, ISO_DEBLUR, ISO_100, ISO_200, ISO_400, ISO_800, ISO_1600, ISO_MAX } ISO_modes; typedef enum { BESTSHOT_AUTO, BESTSHOT_ACTION, BESTSHOT_PORTRAIT, BESTSHOT_LANDSCAPE, BESTSHOT_NIGHT, BESTSHOT_NIGHT_PORTRAIT, BESTSHOT_THEATRE, BESTSHOT_BEACH, BESTSHOT_SNOW, BESTSHOT_SUNSET, BESTSHOT_ANTISHAKE, BESTSHOT_FIREWORKS, BESTSHOT_SPORTS, BESTSHOT_PARTY, BESTSHOT_CANDLELIGHT, BESTSHOT_ASD, BESTSHOT_BACKLIGHT, BESTSHOT_FLOWERS, BESTSHOT_AR, BESTSHOT_HDR, BESTSHOT_MAX }Bestshot_modes; typedef enum { SPL_EFFECT_OFF, SPL_EFFECT_MONO, SPL_EFFECT_NEGATIVE, SPL_EFFECT_SOLARIZE, SPL_EFFECT_SEPIA, SPL_EFFECT_POSTERIZE, SPL_EFFECT_WHITEBOARD, SPL_EFFECT_BLACKBOARD, SPL_EFFECT_AQUA, SPL_EFFECT_EMBOSS, SPL_EFFECT_SKETCH, SPL_EFFECT_NEON, SPL_EFFECT_BEAUTY, SPL_EFFECT_MAX } spl_effect_modes; typedef enum { ANTIBANDING_OFF, ANTIBANDING_60HZ, ANTIBANDING_50HZ, ANTIBANDING_AUTO, ANTIBANDING_MAX, }antibanding_types; typedef enum { MODE_NO_FLIP, MODE_FLIP_H, MODE_FLIP_V, MODE_FLIP_V_H, MODE_FLIP_MAX, }flipmodes_types; typedef enum { FLASH_MODE_OFF, FLASH_MODE_AUTO, FLASH_MODE_ON, FLASH_MODE_TORCH, FLASH_MODE_MAX, }Flash_modes; typedef enum { WB_OFF, WB_AUTO, WB_INCANDESCENT, WB_FLUORESCENT, WB_WARM_FLUORESCENT, WB_DAYLIGHT, WB_CLOUDY_DAYLIGHT, WB_TWILIGHT, WB_SHADE, WB_MANUAL, WB_MAX } White_Balance_modes; typedef enum { MANUAL_WB_CCT, MANUAL_WB_GAIN, MANUAL_WB_MAX }Manual_wb_modes; typedef enum { MENU_ID_MAIN, MENU_ID_WHITEBALANCECHANGE, MENU_ID_EXPMETERINGCHANGE, MENU_ID_GET_CTRL_VALUE, MENU_ID_TOGGLEAFR, MENU_ID_ISOCHANGE, MENU_ID_BRIGHTNESSCHANGE, MENU_ID_CONTRASTCHANGE, MENU_ID_EVCHANGE, MENU_ID_SATURATIONCHANGE, MENU_ID_ZOOMCHANGE, MENU_ID_SHARPNESSCHANGE, MENU_ID_BESTSHOT, MENU_ID_FLASHMODE, MENU_ID_SENSORS, MENU_ID_SWITCH_RES, MENU_ID_SPECIAL_EFFECTS, MENU_ID_WHITEBALANCE_MANUAL, MENU_ID_ANTI_BANDING, MENU_ID_FLIP_MODE, MENU_ID_INVALID, } menu_id_change_t; typedef enum { DECREASE_ZOOM, INCREASE_ZOOM, INCREASE_STEP_ZOOM, DECREASE_STEP_ZOOM, } Camera_Zoom; typedef enum { INC_CONTRAST, DEC_CONTRAST, } Camera_Contrast_changes; typedef enum { INC_BRIGHTNESS, DEC_BRIGHTNESS, } Camera_Brightness_changes; typedef enum { INCREASE_EV, DECREASE_EV, } Camera_EV_changes; typedef enum { INC_SATURATION, DEC_SATURATION, } Camera_Saturation_changes; typedef enum { INC_ISO, DEC_ISO, } Camera_ISO_changes; typedef enum { INC_SHARPNESS, DEC_SHARPNESS, } Camera_Sharpness_changes; typedef enum { ZOOM_IN, ZOOM_OUT, } Zoom_direction; typedef struct{ Camera_main_menu_t main_menu; char * menu_name; } CAMERA_MAIN_MENU_TBL_T; typedef struct{ char * menu_name; int present; } CAMERA_SENSOR_MENU_TLB_T; typedef struct{ Camera_Resolution cs_id; uint16_t width; uint16_t height; char * name; char * str_name; } PREVIEW_DIMENSION_TBL_T; typedef struct { White_Balance_modes wb_id; char * wb_name; } WHITE_BALANCE_TBL_T; typedef struct { Manual_wb_modes wb_id; char * wb_name; } MN_WHITE_BALANCE_TBL_T; typedef struct { Get_Ctrl_modes get_ctrl_id; char * get_ctrl_name; } GET_CTRL_TBL_T; typedef struct{ Exp_Metering_modes exp_metering_id; char * exp_metering_name; } EXP_METERING_TBL_T; typedef struct { Bestshot_modes bs_id; char *name; } BESTSHOT_MODE_TBT_T; typedef struct { spl_effect_modes sp_id; char *name; } SPECIAL_EFFECT_MODE_TBT_T; typedef struct { antibanding_types sp_id; char *name; } ANTI_BANDING_TBT_T; typedef struct { flipmodes_types sp_id; char *name; }FLIP_MODES_TBT_T; typedef struct { Flash_modes bs_id; char *name; } FLASH_MODE_TBL_T; typedef struct { ISO_modes iso_modes; char *iso_modes_name; } ISO_TBL_T; typedef struct { Zoom_direction zoom_direction; char * zoom_direction_name; } ZOOM_TBL_T; typedef struct { Camera_Sharpness_changes sharpness_change; char *sharpness_change_name; } SHARPNESS_TBL_T; typedef struct { Camera_Brightness_changes bc_id; char * brightness_name; } CAMERA_BRIGHTNESS_TBL_T; typedef struct { Camera_Contrast_changes cc_id; char * contrast_name; } CAMERA_CONTRST_TBL_T; typedef struct { Camera_EV_changes ec_id; char * EV_name; } CAMERA_EV_TBL_T; typedef struct { Camera_Saturation_changes sc_id; char * saturation_name; } CAMERA_SATURATION_TBL_T; typedef struct { Camera_Sharpness_changes bc_id; char * sharpness_name; } CAMERA_SHARPNESS_TBL_T; #endif /* __MM_QCAMERA_MAIN_MENU_H__ */
0.980469
high
Libraries/LibJS/Interpreter.h
jcs/serenity
9
3330856
<reponame>jcs/serenity /* * Copyright (c) 2020, <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <AK/FlyString.h> #include <AK/HashMap.h> #include <AK/String.h> #include <AK/Vector.h> #include <LibJS/Forward.h> #include <LibJS/Heap/Heap.h> #include <LibJS/Runtime/Exception.h> #include <LibJS/Runtime/Value.h> namespace JS { enum class ScopeType { None, Function, Block, Try, Breakable, Continuable, }; struct Variable { Value value; DeclarationKind declaration_kind; }; struct ScopeFrame { ScopeType type; NonnullRefPtr<ScopeNode> scope_node; HashMap<FlyString, Variable> variables; }; struct CallFrame { Value this_value; Vector<Value> arguments; }; struct Argument { FlyString name; Value value; }; typedef Vector<Argument, 8> ArgumentVector; class Interpreter { public: template<typename GlobalObjectType, typename... Args> static NonnullOwnPtr<Interpreter> create(Args&&... args) { auto interpreter = adopt_own(*new Interpreter); interpreter->m_global_object = interpreter->heap().allocate<GlobalObjectType>(forward<Args>(args)...); return interpreter; } ~Interpreter(); Value run(const Statement&, ArgumentVector = {}, ScopeType = ScopeType::Block); GlobalObject& global_object(); const GlobalObject& global_object() const; Heap& heap() { return m_heap; } void unwind(ScopeType type) { m_unwind_until = type; } void stop_unwind() { m_unwind_until = ScopeType::None; } bool should_unwind_until(ScopeType type) const { return m_unwind_until == type; } bool should_unwind() const { return m_unwind_until != ScopeType::None; } Optional<Value> get_variable(const FlyString& name); void set_variable(const FlyString& name, Value, bool first_assignment = false); void declare_variable(const FlyString& name, DeclarationKind); void gather_roots(Badge<Heap>, HashTable<Cell*>&); void enter_scope(const ScopeNode&, ArgumentVector, ScopeType); void exit_scope(const ScopeNode&); Value call(Function*, Value this_value = {}, const Vector<Value>& arguments = {}); CallFrame& push_call_frame() { m_call_stack.append({ js_undefined(), {} }); return m_call_stack.last(); } void pop_call_frame() { m_call_stack.take_last(); } const CallFrame& call_frame() { return m_call_stack.last(); } size_t argument_count() const { if (m_call_stack.is_empty()) return 0; return m_call_stack.last().arguments.size(); } Value argument(size_t index) const { if (m_call_stack.is_empty()) return {}; auto& arguments = m_call_stack.last().arguments; return index < arguments.size() ? arguments[index] : js_undefined(); } Value this_value() const { if (m_call_stack.is_empty()) return m_global_object; return m_call_stack.last().this_value; } Shape* empty_object_shape() { return m_empty_object_shape; } Object* string_prototype() { return m_string_prototype; } Object* object_prototype() { return m_object_prototype; } Object* array_prototype() { return m_array_prototype; } Object* error_prototype() { return m_error_prototype; } Object* date_prototype() { return m_date_prototype; } Object* function_prototype() { return m_function_prototype; } Object* number_prototype() { return m_number_prototype; } Object* boolean_prototype() { return m_boolean_prototype; } Exception* exception() { return m_exception; } void clear_exception() { m_exception = nullptr; } template<typename T, typename... Args> Value throw_exception(Args&&... args) { return throw_exception(heap().allocate<T>(forward<Args>(args)...)); } Value throw_exception(Exception*); Value throw_exception(Value value) { return throw_exception(heap().allocate<Exception>(value)); } Value last_value() const { return m_last_value; } private: Interpreter(); Heap m_heap; Value m_last_value; Vector<ScopeFrame> m_scope_stack; Vector<CallFrame> m_call_stack; Shape* m_empty_object_shape { nullptr }; Object* m_global_object { nullptr }; Object* m_string_prototype { nullptr }; Object* m_object_prototype { nullptr }; Object* m_array_prototype { nullptr }; Object* m_error_prototype { nullptr }; Object* m_date_prototype { nullptr }; Object* m_function_prototype { nullptr }; Object* m_number_prototype { nullptr }; Object* m_boolean_prototype { nullptr }; Exception* m_exception { nullptr }; ScopeType m_unwind_until { ScopeType::None }; }; }
1
high
tests/core/test_uname.c
albertobarri/idk
9,724
1696840
/* * Copyright 2016 The Emscripten Authors. All rights reserved. * Emscripten is available under two separate licenses, the MIT license and the * University of Illinois/NCSA Open Source License. Both these licenses can be * found in the LICENSE file. */ #include <stdio.h> #include <sys/utsname.h> int main() { struct utsname u; printf("ret: %d\n", uname(&u)); printf("sysname: %s\n", u.sysname); printf("nodename: %s\n", u.nodename); printf("release: %s\n", u.release); printf("version: %s\n", u.version); printf("machine: %s\n", u.machine); printf("invalid: %d\n", uname(0)); return 0; }
0.878906
high
xdk-asf-3.51.0/common/services/cpu/reset_cause_example/reset_cause_example_sam4l.c
j3270/SAMD_Experiments
0
1729608
/** * \file * * \brief CPU reset cause example for SAM4L * * Copyright (c) 2012-2018 Microchip Technology Inc. and its subsidiaries. * * \asf_license_start * * \page License * * Subject to your compliance with these terms, you may use Microchip * software and any derivatives exclusively with Microchip products. * It is your responsibility to comply with third party license terms applicable * to your use of third party software (including open source software) that * may accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, * WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, * INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE * LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL * LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE * SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE * POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT * ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY * RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. * * \asf_license_stop * */ /** * \mainpage CPU reset cause example * * \section Purpose * * This example demonstrates how to use the reset cause interface. * * \section Requirements * * This example can be used with SAM4L boards. * * \section Description * * The program turns LED0 on when the power-on reset happens and outputs * different informaiton on the terminal, depending on the reset cause. * * Type different commands to generate different reset. To generate Core BOD * reset or I/O BOD reset, press reset button after typing 'c' or 'i'. * * \section Usage * * - Build the program and download it to the board. * -# On the computer, open and configure a terminal application * (e.g., HyperTerminal on Microsoft Windows) with these settings: * - 115200 bauds * - 8 bits of data * - No parity * - 1 stop bit * - No flow control * -# Start the application. * -# In the terminal window, the following text should appear: * \code -- Reset_Cause Example xxx -- -- xxxxxx-xx -- Compiled: xxx xx xxxx xx:xx:xx -- \endcode * -# Choose the item in the following menu to test. * \code Menu : ------Please select reset cause way-------- c: Generate core BOD reset i: Generate I/O BOD reset w: Generate watchdog reset s: Generate system reset \endcode */ /* * Support and FAQ: visit <a href="https://www.microchip.com/support/">Microchip Support</a> */ #include "asf.h" #define STRING_EOL "\r" #define STRING_HEADER "-- Reset_Cause Example --\r\n" \ "-- "BOARD_NAME" --\r\n" \ "-- Compiled: "__DATE__" "__TIME__" --"STRING_EOL /** * \brief Configure UART console. */ static void configure_console(void) { const usart_serial_options_t uart_serial_options = { .baudrate = CONF_UART_BAUDRATE, #ifdef CONF_UART_CHAR_LENGTH .charlength = CONF_UART_CHAR_LENGTH, #endif .paritytype = CONF_UART_PARITY, #ifdef CONF_UART_STOP_BITS .stopbits = CONF_UART_STOP_BITS, #endif }; /* Configure console UART. */ stdio_serial_init(CONF_UART, &uart_serial_options); } /** * \brief Main function. */ int main(void) { uint8_t key; /* Initialize the SAM system. */ sysclk_init(); board_init(); /* Initialize the UART console. */ configure_console(); /* Output example information. */ puts(STRING_HEADER); puts("------ Please select which reset is to be generated ----------\r\n" " c: Generate core BOD reset\r\n" " i: Generate I/O BOD reset\r\n" " w: Generate watchdog reset\r\n" " s: Generate system reset \r"); if (reset_cause_is_power_on_reset()) { LED_On(LED0); } if (reset_cause_is_cpu_brown_out_detected()) { puts("-- Reset Cause is Core browm out reset --\r"); } if (reset_cause_is_io_brown_out_detected()) { puts("-- Reset Cause is I/O brown out reset --\r"); } if (reset_cause_is_ocd()) { puts("-- Reset Cause is system reset request --\r"); } if (reset_cause_is_external_reset()) { puts("-- Reset Cause is external reset --\r"); } if (reset_cause_is_watchdog()) { puts("-- Reset Cause is watchdog reset --\r"); } while(1) { scanf("%c", (char *)&key); switch (key) { case 'c': puts("-- Please press reset button --\r"); BSCIF->BSCIF_BOD18CTRL = BSCIF_BOD18CTRL_EN | BSCIF_BOD18CTRL_ACTION(1) | BSCIF_BOD18CTRL_HYST | BSCIF_BOD18CTRL_FCD; BSCIF->BSCIF_BOD18LEVEL |= BSCIF_BOD18LEVEL_VAL(0x3F); break; case 'i': puts("-- Please press reset button --\r"); BSCIF->BSCIF_BOD33CTRL = BSCIF_BOD33CTRL_EN | BSCIF_BOD33CTRL_ACTION(1) | BSCIF_BOD33CTRL_HYST | BSCIF_BOD33CTRL_FCD; BSCIF->BSCIF_BOD33LEVEL = BSCIF_BOD33LEVEL_VAL(0x3F); break; case 'w': wdt_reset_mcu(); break; case 's': reset_do_soft_reset(); break; } } }
0.988281
high
LKPlayerModule/Classes/LGTableViewCell.h
kaige1123/LKPlayerModule
0
1762376
<gh_stars>0 // // LGTableViewCell.h // LGVideo // // Created by LG on 24/03/2018. // Copyright © 2018 LG. All rights reserved. // #import <UIKit/UIKit.h> @interface LGTableViewCell : UITableViewCell - (void)configWithData:(id)data; @end
0.699219
medium
copasi/sbml/unittests/test000103.h
bmoreau/COPASI
0
1795144
// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/sbml/unittests/test000103.h,v $ // $Revision: 1.1 $ // $Name: $ // $Author: gauges $ // $Date: 2011/12/24 11:14:48 $ // End CVS Header // Copyright (C) 2011 by <NAME>, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #ifndef TEST_000103_H__ #define TEST_000103_H__ #include <cppunit/TestFixture.h> #include <cppunit/TestSuite.h> #include <cppunit/TestResult.h> #include <cppunit/extensions/HelperMacros.h> class CCopasiDataModel; // in earlier version of COPASI, setting the SBML id on a model prior to exporting it // had no effect (bug 1743) class test000103 : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(test000103); CPPUNIT_TEST(test_bug1743_l2); CPPUNIT_TEST(test_bug1743_l3); CPPUNIT_TEST_SUITE_END(); protected: // SBML model for the test static const char* SBML_STRING; CCopasiDataModel* pDataModel; public: void setUp(); void tearDown(); void test_bug1743_l2(); void test_bug1743_l3(); }; #endif /* TEST000103_H__ */
0.515625
high
text/text_position.h
abarth/zi
2
161136
<gh_stars>1-10 // Copyright (c) 2016, Google Inc. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #pragma once #include <stddef.h> #include "text/text_affinity.h" namespace zi { class TextPosition { public: TextPosition(); explicit TextPosition(size_t offset, TextAffinity affinity = TextAffinity::Downstream); ~TextPosition(); size_t offset() const { return offset_; } TextAffinity affinity() const { return affinity_; } private: size_t offset_ = 0; TextAffinity affinity_ = TextAffinity::Downstream; }; } // namespace zi
0.992188
high
source/server/vmessageinputthread.h
xvela/code-vault
2
193904
<gh_stars>1-10 /* Copyright c1997-2014 <NAME>. All rights reserved. This file is part of the Code Vault version 4.1 http://www.bombaydigital.com/ License: MIT. See LICENSE.md in the Vault top level directory. */ #ifndef vmessageinputthread_h #define vmessageinputthread_h /** @file */ #include "vsocketthread.h" #include "vsocketstream.h" #include "vserver.h" #include "vbinaryiostream.h" #include "vmessage.h" class VMessageHandler; /** @ingroup vsocket */ /** VMessageInputThread understands how to perform blocking input reads of VMessage objects (finding and calling a VMessageHandler) from its i/o stream. You can also write to its i/o stream, but if you are doing asynchronous i/o you'll instead post messages to a VMessageOutputThread. */ class VMessageInputThread : public VSocketThread { public: /** Constructs the socket thread with the specified socket, owner thread, and server. @param threadBaseName a distinguishing base name for the thread, useful for debugging purposes; the thread name will be composed of this and the socket's IP address and port @param socket the socket this thread is managing @param ownerThread the thread that created this one @param server the server we're running for @param messageFactory a factory that instantiates messages suitable for this thread's input (The caller owns the factory.) */ VMessageInputThread(const VString& threadBaseName, VSocket* socket, VListenerThread* ownerThread, VServer* server, const VMessageFactory* messageFactory); /** Virtual destructor. */ virtual ~VMessageInputThread(); /** Handles requests for the socket; returns only when the thread has been stopped, the socket is closed, or an exception is thrown that is not properly caught. */ virtual void run(); /** Attaches the thread to its session, so that message handlers on this thread can reference session state. @param session the session on whose behalf we are running */ void attachSession(VClientSessionPtr session); /** Sets or clears the mHasOutputThread that controls whether this input thread must wait before returning from run(). This is used when separate in/out threads are handling i/o and the destruction sequence requires the input thread to wait for the output thread to die before dying itself. */ void setHasOutputThread(bool hasOutputThread) { mHasOutputThread = hasOutputThread; } protected: /** Pulls the next message from the socket (blocking until there is data), and then calls dispatchMessage() to handle the message. */ virtual void _processNextRequest(); /** Handles the message by finding or creating a handler and calling it to process the message, returning when it's OK to read the next message. @param message the message to handle */ virtual void _dispatchMessage(VMessagePtr message); /** This method is called by _dispatchMessage if it cannot find the handler for the message being handled. How to handle this is protocol-specific, but a subclass could send an error response back to the sender if the protocol allows that. The implementation must NOT release the message, and the message WILL be released by _dispatchMessage() upon return. */ virtual void _handleNoMessageHandler(VMessagePtr /*message*/) {} /** This method is intended for use by loopback testing, where the test code can see (and potentially preprocess) a message that it sent that is about to be handled in the normal fashion. */ virtual void _beforeProcessMessage(VMessageHandler* /*handler*/, VMessagePtr /*message*/) {} /** This method is where we actually call the message handler to process the message it was constructed with. A subclass might override this to wrap the call to super in a try/catch block if it wants to take action other than logging in response to an exception. */ virtual void _callProcessMessage(VMessageHandler* handler); /** This method is intended for use by loopback testing, where the test code can see (and potentially post-process) a message that it sent that has just been handled in the normal fashion. */ virtual void _afterProcessMessage(VMessageHandler* /*handler*/) {} VSocketStream mSocketStream; ///< The underlying raw stream from which data is read. VBinaryIOStream mInputStream; ///< The formatted stream from which data is directly read. bool mConnected; ///< True if the client has completed the connection sequence. VClientSessionPtr mSession; ///< The session object we are associated with. VServer* mServer; ///< The server object that owns us. const VMessageFactory* mMessageFactory; ///< Factory for instantiating new messages to read from input stream. volatile bool mHasOutputThread; ///< True if we are dependent on an output thread completion before returning from run(). (see run() code) private: VMessageInputThread(const VMessageInputThread&); // not copyable VMessageInputThread& operator=(const VMessageInputThread&); // not assignable }; /** VBentoMessageInputThread is a VMessageInputThread that can automatically handle no-such-handler or uncaught message dispatch exceptions, and in response send a Bento-based error reply back to the sender. */ class VBentoMessageInputThread : public VMessageInputThread { public: VBentoMessageInputThread(const VString& threadBaseName, VSocket* socket, VListenerThread* ownerThread, VServer* server, const VMessageFactory* messageFactory); ~VBentoMessageInputThread() {} protected: virtual void _handleNoMessageHandler(VMessagePtr message); virtual void _callProcessMessage(VMessageHandler* handler); }; #endif /* vmessageinputthread_h */
0.996094
high