content
stringlengths
12
2.72M
<reponame>WilliamPat/SpaceGeneratorDLL #pragma once #include "GeneratedElement.h" class Planet : public GeneratedElement { public: Planet(std::string name) : GeneratedElement(name) { } Planet(int s) :GeneratedElement(s) { } ~Planet(); private: void GeneratePlanet(int s); };
<reponame>freepvps/hseos<filename>src/sockets/example/types.c #include "types.h" #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> static int eo_parse_addr_limited(const char* s, size_t n, in_port_t port, eo_addr_t* dest) { if (n > INET6_ADDRSTRLEN) { n = INET6_ADDRSTRLEN; } if (n >= 2 && *s == '[' && s[n - 1] == ']') { s += 1; n -= 2; } char buf[INET6_ADDRSTRLEN + 1] = {0}; memcpy(buf, s, n); if (inet_pton(AF_INET6, buf, &dest->v6.sin6_addr) > 0) { dest->v6.sin6_port = (in_port_t)htons(port); dest->v6.sin6_family = AF_INET6; return 0; } if (inet_pton(AF_INET, buf, &dest->v4.sin_addr) > 0) { dest->v4.sin_port = (in_port_t)htons(port); dest->v4.sin_family = AF_INET; return 0; } return -1; } int eo_parse_addr(const char* s, in_port_t port, eo_addr_t* dest) { return eo_parse_addr_limited(s, strlen(s), port, dest); } int eo_parse_addr_port(const char* s, eo_addr_t* dest) { size_t n = strlen(s); for (size_t i = n; i-- > 0;) { if (s[i] == ':') { char* err; int value = atoi(&s[i + 1]); if (value <= 0 || value > SHRT_MAX) { return -1; } in_port_t port = (in_port_t)value; if (err != NULL) { return -1; } return eo_parse_addr_limited(s, i, port, dest); } } return -1; } int eo_is_v4_addr(const eo_addr_t* addr) { return addr->base.sa_family == AF_INET; } int eo_is_v6_addr(const eo_addr_t* addr) { return addr->base.sa_family == AF_INET6; } int eo_addr_to_str(const eo_addr_t* addr, eo_addr_str_t* dest) { char buf[INET6_ADDRSTRLEN + 1] = {0}; in_port_t port; if (eo_is_v4_addr(addr)) { inet_ntop(AF_INET, &addr->v4.sin_addr.s_addr, buf, INET_ADDRSTRLEN); port = (in_port_t)ntohs(addr->v4.sin_port); } else if (eo_is_v6_addr(addr)) { inet_ntop(AF_INET6, &addr->v6.sin6_addr.s6_addr, buf, INET6_ADDRSTRLEN); port = (in_port_t)ntohs(addr->v6.sin6_port); } else { return -1; } sprintf(*dest, "%s:%"PRIu16, buf, port); return 0; } size_t eo_addr_size(const eo_addr_t* addr) { return ( eo_is_v4_addr(addr) ? sizeof(struct sockaddr_in) : eo_is_v6_addr(addr) ? sizeof(struct sockaddr_in6) : 0 ); }
/* */ #ifndef _MPU9250_REGISTER_MAP_H_ #define _MPU9250_REGISTER_MAP_H_ const uint8_t MPU9250_BIT_RESET = 0x80; const uint8_t MPU9250_SELF_TEST_X_GYRO = 0x00; const uint8_t MPU9250_SELF_TEST_Y_GYRO = 0x01; const uint8_t MPU9250_SELF_TEST_Z_GYRO = 0x02; const uint8_t MPU9250_SELF_TEST_X_ACCEL = 0x0D; const uint8_t MPU9250_SELF_TEST_Y_ACCEL = 0x0E; const uint8_t MPU9250_SELF_TEST_Z_ACCEL = 0x0F; const uint8_t MPU9250_XG_OFFSET_H = 0x13; const uint8_t MPU9250_XG_OFFSET_L = 0x14; const uint8_t MPU9250_YG_OFFSET_H = 0x15; const uint8_t MPU9250_YG_OFFSET_L = 0x16; const uint8_t MPU9250_ZG_OFFSET_H = 0x17; const uint8_t MPU9250_ZG_OFFSET_L = 0x18; const uint8_t MPU9250_SMPLRT_DIV = 0x19; const uint8_t MPU9250_CONFIG = 0x1A; const uint8_t MPU9250_GYRO_CONFIG = 0x1B; const uint8_t MPU9250_ACCEL_CONFIG = 0x1C; const uint8_t MPU9250_ACCEL_CONFIG_2 = 0x1D; const uint8_t MPU9250_LP_ACCEL_ODR = 0x1E; const uint8_t MPU9250_WOM_THR = 0x1F; const uint8_t MPU9250_FIFO_EN = 0x23; const uint8_t MPU9250_I2C_MST_CTRL = 0x24; const uint8_t MPU9250_I2C_SLV0_ADDR = 0x25; const uint8_t MPU9250_I2C_SLV0_REG = 0x26; const uint8_t MPU9250_I2C_SLV0_CTRL = 0x27; const uint8_t MPU9250_I2C_SLV1_ADDR = 0x28; const uint8_t MPU9250_I2C_SLV1_REG = 0x29; const uint8_t MPU9250_I2C_SLV1_CTRL = 0x2A; const uint8_t MPU9250_I2C_SLV2_ADDR = 0x2B; const uint8_t MPU9250_I2C_SLV2_REG = 0x2C; const uint8_t MPU9250_I2C_SLV2_CTRL = 0x2D; const uint8_t MPU9250_I2C_SLV3_ADDR = 0x2E; const uint8_t MPU9250_I2C_SLV3_REG = 0x2F; const uint8_t MPU9250_I2C_SLV3_CTRL = 0x30; const uint8_t MPU9250_I2C_SLV4_ADDR = 0x31; const uint8_t MPU9250_I2C_SLV4_REG = 0x32; const uint8_t MPU9250_I2C_SLV4_DO = 0x33; const uint8_t MPU9250_I2C_SLV4_CTRL = 0x34; const uint8_t MPU9250_I2C_SLV4_DI = 0x35; const uint8_t MPU9250_I2C_MST_STATUS = 0x36; const uint8_t MPU9250_INT_PIN_CFG = 0x37; const uint8_t MPU9250_INT_ENABLE = 0x38; const uint8_t MPU9250_INT_STATUS = 0x3A; const uint8_t MPU9250_ACCEL_XOUT_H = 0x3B; const uint8_t MPU9250_ACCEL_XOUT_L = 0x3C; const uint8_t MPU9250_ACCEL_YOUT_H = 0x3D; const uint8_t MPU9250_ACCEL_YOUT_L = 0x3E; const uint8_t MPU9250_ACCEL_ZOUT_H = 0x3F; const uint8_t MPU9250_ACCEL_ZOUT_L = 0x40; const uint8_t MPU9250_TEMP_OUT_H = 0x41; const uint8_t MPU9250_TEMP_OUT_L = 0x42; const uint8_t MPU9250_GYRO_XOUT_H = 0x43; const uint8_t MPU9250_GYRO_XOUT_L = 0x44; const uint8_t MPU9250_GYRO_YOUT_H = 0x45; const uint8_t MPU9250_GYRO_YOUT_L = 0x46; const uint8_t MPU9250_GYRO_ZOUT_H = 0x47; const uint8_t MPU9250_GYRO_ZOUT_L = 0x48; const uint8_t MPU9250_EXT_SENS_DATA_00 = 0x49; const uint8_t MPU9250_EXT_SENS_DATA_01 = 0x4A; const uint8_t MPU9250_EXT_SENS_DATA_02 = 0x4B; const uint8_t MPU9250_EXT_SENS_DATA_03 = 0x4C; const uint8_t MPU9250_EXT_SENS_DATA_04 = 0x4D; const uint8_t MPU9250_EXT_SENS_DATA_05 = 0x4E; const uint8_t MPU9250_EXT_SENS_DATA_06 = 0x4F; const uint8_t MPU9250_EXT_SENS_DATA_07 = 0x50; const uint8_t MPU9250_EXT_SENS_DATA_08 = 0x51; const uint8_t MPU9250_EXT_SENS_DATA_09 = 0x52; const uint8_t MPU9250_EXT_SENS_DATA_10 = 0x53; const uint8_t MPU9250_EXT_SENS_DATA_11 = 0x54; const uint8_t MPU9250_EXT_SENS_DATA_12 = 0x55; const uint8_t MPU9250_EXT_SENS_DATA_13 = 0x56; const uint8_t MPU9250_EXT_SENS_DATA_14 = 0x57; const uint8_t MPU9250_EXT_SENS_DATA_15 = 0x58; const uint8_t MPU9250_EXT_SENS_DATA_16 = 0x59; const uint8_t MPU9250_EXT_SENS_DATA_17 = 0x5A; const uint8_t MPU9250_EXT_SENS_DATA_18 = 0x5B; const uint8_t MPU9250_EXT_SENS_DATA_19 = 0x5C; const uint8_t MPU9250_EXT_SENS_DATA_20 = 0x5D; const uint8_t MPU9250_EXT_SENS_DATA_21 = 0x5E; const uint8_t MPU9250_EXT_SENS_DATA_22 = 0x5F; const uint8_t MPU9250_EXT_SENS_DATA_23 = 0x60; const uint8_t MPU9250_I2C_SLV0_DO = 0x63; const uint8_t MPU9250_I2C_SLV1_DO = 0x64; const uint8_t MPU9250_I2C_SLV2_DO = 0x65; const uint8_t MPU9250_I2C_SLV3_DO = 0x66; const uint8_t MPU9250_I2C_MST_DELAY_CTRL =0x67; const uint8_t MPU9250_SIGNAL_PATH_RESET = 0x68; const uint8_t MPU9250_MOT_DETECT_CTRL = 0x69; const uint8_t MPU9250_USER_CTRL = 0x6A; const uint8_t MPU9250_PWR_MGMT_1 = 0x6B; const uint8_t MPU9250_PWR_MGMT_2 = 0x6C; const uint8_t MPU9250_FIFO_COUNTH = 0x72; const uint8_t MPU9250_FIFO_COUNTL = 0x73; const uint8_t MPU9250_FIFO_R_W = 0x74; const uint8_t MPU9250_WHO_AM_I = 0x75; const uint8_t MPU9250_XA_OFFSET_H = 0x77; const uint8_t MPU9250_XA_OFFSET_L = 0x78; const uint8_t MPU9250_YA_OFFSET_H = 0x7A; const uint8_t MPU9250_YA_OFFSET_L = 0x7B; const uint8_t MPU9250_ZA_OFFSET_H = 0x7D; const uint8_t MPU9250_ZA_OFFSET_L = 0x7E; enum interrupt_status_bits { INT_STATUS_RAW_DATA_RDY_INT = 0, INT_STATUS_FSYNC_INT = 3, INT_STATUS_FIFO_OVERFLOW_INT = 4, INT_STATUS_WOM_INT = 6, }; enum gyro_config_bits { GYRO_CONFIG_FCHOICE_B = 0, GYRO_CONFIG_GYRO_FS_SEL = 3, GYRO_CONFIG_ZGYRO_CTEN = 5, GYRO_CONFIG_YGYRO_CTEN = 6, GYRO_CONFIG_XGYRO_CTEN = 7, }; #define MPU9250_GYRO_FS_SEL_MASK 0x3 #define MPU9250_GYRO_FCHOICE_MASK 0x3 enum accel_config_bit { ACCEL_CONFIG_ACCEL_FS_SEL = 3, ACCEL_CONFIG_AZ_ST_EN = 5, ACCEL_CONFIG_AY_ST_EN = 6, ACCEL_CONFIG_AX_ST_EN = 7, }; #define MPU9250_ACCEL_FS_SEL_MASK 0x3 enum accel_config_2_bits { ACCEL_CONFIG_2_A_DLPFCFG = 0, ACCEL_CONFIG_2_ACCEL_FCHOICE_B = 3, }; enum pwr_mgmt_1_bits { PWR_MGMT_1_CLKSEL = 0, PWR_MGMT_1_PD_PTAT = 3, PWR_MGMT_1_GYRO_STANDBY = 4, PWR_MGMT_1_CYCLE = 5, PWR_MGMT_1_SLEEP = 6, PWR_MGMT_1_H_RESET = 7 }; enum pwr_mgmt_2_bits { PWR_MGMT_2_DISABLE_ZG = 0, PWR_MGMT_2_DISABLE_YG = 1, PWR_MGMT_2_DISABLE_XG = 2, PWR_MGMT_2_DISABLE_ZA = 3, PWR_MGMT_2_DISABLE_YA = 4, PWR_MGMT_2_DISABLE_XA = 5, }; enum int_enable_bits { INT_ENABLE_RAW_RDY_EN = 0, INT_ENABLE_FSYNC_INT_EN = 3, INT_ENABLE_FIFO_OVERFLOW_EN = 4, INT_ENABLE_WOM_EN = 6, }; enum int_pin_cfg_bits { INT_PIN_CFG_BYPASS_EN = 1, INT_PIN_CFG_FSYNC_INT_MODE_EN = 2, INT_PIN_CFG_ACTL_FSYNC = 3, INT_PIN_CFG_INT_ANYRD_2CLEAR = 4, INT_PIN_CFG_LATCH_INT_EN = 5, INT_PIN_CFG_OPEN = 6, INT_PIN_CFG_ACTL = 7, }; #define INT_PIN_CFG_INT_MASK 0xF0 #define MPU9250_WHO_AM_I_RESULT 0x71 const uint8_t AK8963_WHO_AM_I = 0x0; const uint8_t AK8963_INFO = 0x1; const uint8_t AK8963_ST1 = 0x2; const uint8_t AK8963_XOUT_L = 0x3; const uint8_t AK8963_XOUT_H = 0x4; const uint8_t AK8963_YOUT_L = 0x5; const uint8_t AK8963_YOUT_H = 0x6; const uint8_t AK8963_ZOUT_L = 0x7; const uint8_t AK8963_ZOUT_H = 0x8; const uint8_t AK8963_ST2 = 0x9; const uint8_t AK8963_CNTL = 0xA; const uint8_t AK8963_RSV = 0xB; const uint8_t AK8963_ASTC = 0xC; const uint8_t AK8963_TS1 = 0xD; const uint8_t AK8963_TS2 = 0xE; const uint8_t AK8963_I2CDIS = 0xF; const uint8_t AK8963_ASAX = 0x10; const uint8_t AK8963_ASAY = 0x11; const uint8_t AK8963_ASAZ = 0x12; #define MAG_CTRL_OP_MODE_MASK 0xF #define AK8963_ST1_DRDY_BIT 0 #define AK8963_WHO_AM_I_RESULT 0x48 #endif // _MPU9250_REGISTER_MAP_H_
/* * Copyright (c) 1980 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. * * @(#)gmon.h 5.1 (Berkeley) 5/30/85 */ struct phdr { char *lpc; char *hpc; int ncnt; }; /* * histogram counters are unsigned shorts (according to the kernel). */ #define HISTCOUNTER unsigned short /* * fraction of text space to allocate for histogram counters * here, 1/2 */ #define HISTFRACTION 2 /* * Fraction of text space to allocate for from hash buckets. * The value of HASHFRACTION is based on the minimum number of bytes * of separation between two subroutine call points in the object code. * Given MIN_SUBR_SEPARATION bytes of separation the value of * HASHFRACTION is calculated as: * * HASHFRACTION = MIN_SUBR_SEPARATION / (2 * sizeof(short) - 1); * * For the VAX, the shortest two call sequence is: * * calls $0,(r0) * calls $0,(r0) * * which is separated by only three bytes, thus HASHFRACTION is * calculated as: * * HASHFRACTION = 3 / (2 * 2 - 1) = 1 * * Note that the division above rounds down, thus if MIN_SUBR_FRACTION * is less than three, this algorithm will not work! */ #define HASHFRACTION 1 /* * percent of text space to allocate for tostructs * with a minimum. */ #define ARCDENSITY 2 #define MINARCS 50 struct tostruct { char *selfpc; long count; unsigned short link; }; /* * a raw arc, * with pointers to the calling site and the called site * and a count. */ struct rawarc { unsigned long raw_frompc; unsigned long raw_selfpc; long raw_count; }; /* * general rounding functions. */ #define ROUNDDOWN(x,y) (((x)/(y))*(y)) #define ROUNDUP(x,y) ((((x)+(y)-1)/(y))*(y))
<gh_stars>1-10 //------------------------------------------------------------------------------ /* This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, <NAME> <<EMAIL>> 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. */ //============================================================================== #ifndef BEAST_CXX14_TYPE_TRAITS_H_INCLUDED #define BEAST_CXX14_TYPE_TRAITS_H_INCLUDED #include <beast/cxx14/config.h> #include <tuple> #include <type_traits> #include <utility> namespace std { // Ideas from Howard Hinnant // // Specializations of is_constructible for pair and tuple which // work around an apparent defect in the standard that causes well // formed expressions involving pairs or tuples of non default-constructible // types to generate compile errors. // template <class T, class U> struct is_constructible <pair <T, U>> : integral_constant <bool, is_default_constructible <T>::value && is_default_constructible <U>::value> { }; namespace detail { template <bool...> struct compile_time_all; template <> struct compile_time_all <> { static const bool value = true; }; template <bool Arg0, bool ... Argn> struct compile_time_all <Arg0, Argn...> { static const bool value = Arg0 && compile_time_all <Argn...>::value; }; } template <class ...T> struct is_constructible <tuple <T...>> : integral_constant <bool, detail::compile_time_all < is_default_constructible <T>::value...>::value> { }; //------------------------------------------------------------------------------ #if ! BEAST_NO_CXX14_COMPATIBILITY // From http://llvm.org/svn/llvm-project/libcxx/trunk/include/type_traits // const-volatile modifications: template <class T> using remove_const_t = typename remove_const<T>::type; // C++14 template <class T> using remove_volatile_t = typename remove_volatile<T>::type; // C++14 template <class T> using remove_cv_t = typename remove_cv<T>::type; // C++14 template <class T> using add_const_t = typename add_const<T>::type; // C++14 template <class T> using add_volatile_t = typename add_volatile<T>::type; // C++14 template <class T> using add_cv_t = typename add_cv<T>::type; // C++14 // reference modifications: template <class T> using remove_reference_t = typename remove_reference<T>::type; // C++14 template <class T> using add_lvalue_reference_t = typename add_lvalue_reference<T>::type; // C++14 template <class T> using add_rvalue_reference_t = typename add_rvalue_reference<T>::type; // C++14 // sign modifications: template <class T> using make_signed_t = typename make_signed<T>::type; // C++14 template <class T> using make_unsigned_t = typename make_unsigned<T>::type; // C++14 // array modifications: template <class T> using remove_extent_t = typename remove_extent<T>::type; // C++14 template <class T> using remove_all_extents_t = typename remove_all_extents<T>::type; // C++14 // pointer modifications: template <class T> using remove_pointer_t = typename remove_pointer<T>::type; // C++14 template <class T> using add_pointer_t = typename add_pointer<T>::type; // C++14 // other transformations: #if 0 // This is not easy to implement in C++11 template <size_t Len, std::size_t Align=std::alignment_of<max_align_t>::value> using aligned_storage_t = typename aligned_storage<Len,Align>::type; // C++14 template <std::size_t Len, class... Types> using aligned_union_t = typename aligned_union<Len,Types...>::type; // C++14 #endif template <class T> using decay_t = typename decay<T>::type; // C++14 template <bool b, class T=void> using enable_if_t = typename enable_if<b,T>::type; // C++14 template <bool b, class T, class F> using conditional_t = typename conditional<b,T,F>::type; // C++14 template <class... T> using common_type_t = typename common_type<T...>::type; // C++14 template <class T> using underlying_type_t = typename underlying_type<T>::type; // C++14 template <class F, class... ArgTypes> using result_of_t = typename result_of<F(ArgTypes...)>::type; // C++14 #endif } #endif
<reponame>tilast/courseWork #ifndef SVGFIGUREPARSER_H #define SVGFIGUREPARSER_H #include "svgparser.h" #include "svgstyleparse.h" #include "QtShapeHeaders.h" #include <QtXml/qdom.h> class SVGFigureParser: public SVGStyleParse { public: SVGFigureParser() {}; void setContent(const QString &string) {__content = string;} QString getContent() {return __content;} static QStringList parsePoints(const QString &string); static QtShape2D* parseFigure(const QDomElement &e) { QtShape2D *shape = NULL; //Parse form if (e.tagName() == "rect") shape = parseRect(e); if (e.tagName() == "polygon") shape = parsePolygon(e); if (e.tagName() == "polyline") shape = parseCurve(e); if (e.tagName() == "arrow") shape = parseArrow(e); if (shape == NULL) return NULL; //Style parsing float red = 0, green = 0, blue = 0; if (!e.attribute("style").isEmpty()) { QString style = e.attribute("style"); SVGStyleParse styleParse(style); //Parse style Css if (!style.isEmpty()) { //Fill color QStringList fillColorStr = styleParse.getFillColor(); if (!fillColorStr.isEmpty()) { red = fillColorStr[1].toFloat() / 255.0; green = fillColorStr[2].toFloat() / 255.0; blue = fillColorStr[3].toFloat() / 255.0; } //Line color; } } Color fillColor(red, green, blue); if (shape != NULL) { shape->getStyle().setStyle(Color(0,0,0), fillColor); } return shape; } static QtRectangle* parseRect(const QDomElement &element); //Polygons static QtShape2D *parsePolygon(const QDomElement &element); static QtParallelogram *parseParallelogram(const QDomElement &element); static QtRhombus *parseRhombus(const QDomElement &element); //Polylines static QtZigzag *parseCurve(const QDomElement &element); //Arrow static QtArrow *parseArrow(const QDomElement &element); private: QString __content; }; #endif // SVGFIGUREPARSER_H
#ifndef _SEGMENT_CONCATENATED_H #define _SEGMENT_CONCATENATED_H #include <glog/gbsegment.h> #include <glog/gbgraph.h> class CompositeTGSegment : public TGSegment { private: const size_t nodeId; const GBGraph &g; std::vector<size_t> nodes; std::vector<int> copyVarPos; bool f_isSorted; size_t sortedField; const SegProvenanceType provenanceType; const bool sortBeforeAccess; const bool removeDuplBeforeAccess; const bool replaceOffsets; size_t nProvenanceColumns; std::shared_ptr<const TGSegment> merge() const; public: CompositeTGSegment(size_t nodeId, const GBGraph &g, const std::vector<size_t> &nodes, const std::vector<int> &copyVarPos, bool isSorted=false, uint8_t sortedField = 0, SegProvenanceType provenanceType = SEG_NOPROV, bool sortBeforeAccess = false, bool removeDuplBeforeAccess = false, bool replaceOffsets = false) : nodeId(nodeId), g(g), nodes(nodes), copyVarPos(copyVarPos), f_isSorted(isSorted), sortedField(sortedField), provenanceType(provenanceType), sortBeforeAccess(sortBeforeAccess), removeDuplBeforeAccess(removeDuplBeforeAccess), replaceOffsets(replaceOffsets) { assert(provenanceType != SEG_NOPROV); #ifdef DEBUG //There should not be repeated variables in copyVarPos, I'm //not sure it works if there are std::set<size_t> s; for(auto c : copyVarPos) s.insert(c); if (s.size() != copyVarPos.size()) { LOG(ERRORL) << "Case not implemented"; throw 10; } #endif nProvenanceColumns = 0; if (provenanceType == SEG_FULLPROV) { if (replaceOffsets) { nProvenanceColumns = 2; //node + offset } else { for (auto n : nodes) { auto off = g.getNodeData(n)->getNOffsetColumns(); if (off > nProvenanceColumns) { if (nProvenanceColumns > 0 && off != nProvenanceColumns) { throw 10; //The case when nodes have provenance of multiple sizes //is not supported yet } nProvenanceColumns = off; } } } } else if (provenanceType != SEG_NOPROV) { nProvenanceColumns = 1; } } CompositeTGSegment(const GBGraph &g, const std::vector<size_t> &nodes, const std::vector<int> &copyVarPos, bool isSorted=false, uint8_t sortedField = 0, SegProvenanceType provenanceType = SEG_NOPROV, bool sortBeforeAccess = false, bool removeDuplBeforeAccess = false, bool replaceOffsets = false) : CompositeTGSegment(nodes.size() == 1 ? nodes[0] : ~0ul, g, nodes, copyVarPos, isSorted, sortedField, provenanceType, sortBeforeAccess, removeDuplBeforeAccess, replaceOffsets) { } std::string getName() const { return "CompositeTGSegment"; } size_t getNColumns() const { return copyVarPos.size(); } bool isSorted() const { return f_isSorted && sortedField == 0; } bool isEmpty() const { return false; } bool isNodeConstant() const { return nodes.size() <= 1; } SegProvenanceType getProvenanceType() const { assert(provenanceType != SEG_SAMENODE || nodes.size() == 1); assert(provenanceType != SEG_DIFFNODES || nodes.size() > 1); return provenanceType; } size_t getNOffsetColumns() const { return nProvenanceColumns; } size_t getNodeId() const { return nodeId; } std::shared_ptr<const TGSegment> slice(const size_t start, const size_t end) const; std::shared_ptr<TGSegment> slice(const size_t nodeId, const size_t start, const size_t end) const; size_t getNRows() const; std::shared_ptr<TGSegment> swap() const; std::unique_ptr<TGSegmentItr> iterator( std::shared_ptr<const TGSegment> selfref = NULL) const; bool isSortedBy(std::vector<uint8_t> &fields) const; std::shared_ptr<const TGSegment> sort() const; void argsort(std::vector<size_t> &indices) const; std::shared_ptr<TGSegment> sortBy(std::vector<uint8_t> &fields) const; std::shared_ptr<const TGSegment> sortByProv(size_t ncols, std::vector<size_t> &idxs, std::vector<size_t> &nodes) const; std::shared_ptr<const TGSegment> sortByProv() const; std::shared_ptr<const TGSegment> unique() const; void argunique(std::vector<size_t> &idxs) const; void projectTo(const std::vector<int> &posFields, std::vector<std::shared_ptr<Column>> &out) const; std::vector<std::shared_ptr<const TGSegment>> sliceByNodes( size_t startNodeIdx, std::vector<size_t> &provNodes) const; void appendTo(uint8_t colPos, std::vector<Term_t> &out) const; void appendTo(uint8_t colPos, std::vector<std::pair<Term_t, Term_t>> &out) const; void appendTo(uint8_t colPos1, uint8_t colPos2, std::vector<BinWithProv> &out) const; }; #endif
// LED_Hander.h #ifndef _LED_HANDER_h #define _LED_HANDER_h #if defined(ARDUINO) && ARDUINO >= 100 #include "arduino.h" #else #include "WProgram.h" #endif class LED { public: LED(uint8_t pin, bool on_state); ~LED(); void setLED(bool state); void toggleLED(); bool getLED(); protected: uint8_t _pin; bool _on_state; bool _state; }; #endif
/* * (C) Copyright 2020-2020 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #pragma once #include <iomanip> #include <iostream> #include <string> #include <vector> #include "oops/mpi/mpi.h" namespace util { // ----------------------------------------------------------------------------- /// Collects prints from all the tasks in communicator to print in reproducible order /// on task 0. template <typename T> void gatherPrint(std::ostream & os, const T & obj, const eckit::mpi::Comm & comm) { if (comm.size() > 1) { size_t maxlen = 10000; std::stringstream ss; ss << std::setprecision(os.precision()) << obj; std::string sloc = ss.str(); std::vector<char> vloc(sloc.begin(), sloc.end()); for (size_t jj = vloc.size(); jj < maxlen; ++jj) vloc.push_back('#'); std::vector<char> vglob(maxlen*comm.size()); comm.gather(vloc, vglob, 0); if (comm.rank() == 0) { auto it = vglob.begin(); for (size_t jpe = 0; jpe < comm.size(); ++jpe) { std::string spe(it, it + maxlen); std::size_t last = spe.find_last_not_of('#'); if (last != std::string::npos) spe.erase(last+1); os << spe; it += maxlen; } } } else { oops::Log::warning() << "No need to call gatherPrint"; } } // ----------------------------------------------------------------------------- } // namespace util
<filename>client/includes/textures/chell_texture/chell_stand_right_sprite.h<gh_stars>0 #ifndef CHELL_STAND_RIGHT_SPRITE_H #define CHELL_STAND_RIGHT_SPRITE_H #include "../common_texture/dynamic_sprite.h" class ChellStandRightSprite { public: /* Devuelve un sprite dinamico de Chell parada (mirando hacia la derecha). Este sprite dinamico corresponde a una serie de sprites de la imagen ALL_CHELL_SPRITES, de images_path.h. */ static DynamicSprite get_sprite(); }; #endif // CHELL_STAND_RIGHT_SPRITE_H
<filename>lltest/fromc.c /* Voici un petit exemple d'utilisation de Le-Lisp pilote' par C. Le programme principal (au sens UNIX: main) n'est plus un simple appel a "inlelisp" (lequel lance Le-Lisp) (cf llmain.c) mais un ve'ritable programme C qui fait ce qu'il veut avant d'appeler Lisp, lequel peut , soit appeler C au moyen du CALLEXTERN habituel, soit <revenir> a` C, dans l'environnement initial du programme principal C. Dans l'exemple qui suit (cf fromc.c & fromc.ll), on de'marre dans C avec le programme principal, puis on de'marre Lisp, d'ou` on charge l'exemple contenu dans fromc.ll. Ce code Lisp commence par <revenir> dans le monde C une premie`re fois, duquel on repart dans le monde Lisp a` l'aide cette fois d'un LISPCALL habituel, de Lisp on execute une simple addition re'alise'e en C mais a` l'aide de l'ope'rateur Lisp ADD et d'un LISPCALL, puis on <revient> a` C dans l'environnement de de'part, pour revenir dans le programme principal (main) ou` on s'are`te --ouf !--- */ #include <setjmp.h> /* Le system Call magique */ #include "lelisp.h" /* pour les LISPCALL de l'exemple */ /* main C --setjmp--> lelisp | v C <-- defextern longjmp(1) | v test_call_lisp --LISPCALL--> lelisp --------------- | v test_c_from_lisp_from_c <--CALLEXTERN--(I) test_lisp_from_c ^ defextern longjmp(2)--(II) | \ v \--> C --> retour main. LISPCALL <--> lelisp | ^ v | add */ jmp_buf env; /* le garant de l'environnement */ void do_longjmp(val)/* pour re'aliser la connection avec Le-Lisp */ int val; { longjmp(env,val); } test_call_lisp () /* le petit exemple de C qui appele Lisp */ { int test_lisp_from_c; test_lisp_from_c=(int)getsym("test_lisp_from_c"); printf("\n C: Appel a` Le-Lisp par LISPCALL. \n\r"); lispcall(LLT_T,0,test_lisp_from_c); } test_c_from_lisp_from_c (a, b) /* l'exemple de C appele' par Lisp */ int a,b; { int add,res; add = (int) getsym("add"); pusharg(LLT_FIX,a); pusharg(LLT_FIX,b); res = (int) lispcall(LLT_FIX,2,add); printf("\n C: Appel a` Le-Lisp par LISPCALL: (add %d %d) = %d \n\r",a,b,res); } init_lelisp (argc,argv,envp) /* le vrai code C! */ int argc; char **argv, **envp; { int code; switch (setjmp(env)) { case 2: printf("\n C: Retour a` C No 2, apre`s Le-Lisp.\n\r"); return; break; case 1: printf("\n C: Retour a` C No 1, apre`s Le-Lisp.\n\r"); test_call_lisp (); return; break; case 0: printf("\n C: Exemple de passage dans C avant Le-Lisp.\n\n\n\r"); printf(";; On de'marre le-Lisp:\n\r"); printf(";; Charger fromc.ll : ^Lfromc\n\r"); inlelisp(argc,argv,envp); printf("Fin de Le-Lisp\n\r"); return; default: printf("\n ** error in C code before Le-Lisp call.\n\r"); return; } } /* * Le programme principal */ main (argc,argv,envp) int argc; char **argv, **envp; { init_lelisp(argc,argv,envp); printf("\n C: Suite et fin du code en C apre`s Le-Lisp\n\r"); exit(0); }
typedef int ElementType; struct StackRecord; typedef struct StackRecord *Stack; int IsEmpty(Stack S); int IsFull(Stack S); Stack CreateStack(int MaxElements); void DisposeStack(Stack S); void MakeEmpty(Stack S); void Push(ElementType X, Stack S); ElementType Top(Stack S); void Pop(Stack S); ElementType TopAndPop(Stack S);
/* ========================= eCAL LICENSE ================================= * * Copyright (C) 2016 - 2019 Continental Corporation * * 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. * * ========================= eCAL LICENSE ================================= */ /** * @file ecal_service_info.h * @brief eCAL service info **/ #pragma once #include <ecal/cimpl/ecal_service_info_cimpl.h> #include <functional> #include <string> #include <vector> namespace eCAL { /** * @brief Service response struct containing the (responding) server informations and the response itself. **/ struct SServiceResponse { SServiceResponse() { ret_state = 0; call_state = call_state_none; }; std::string host_name; //!< service host name std::string service_name; //!< name of the service std::string service_id; //!< id of the service std::string method_name; //!< name of the service method std::string error_msg; //!< human readable error message int ret_state; //!< return state of the called service method eCallState call_state; //!< call state (see eCallState) std::string response; //!< service response }; typedef std::vector<SServiceResponse> ServiceResponseVecT; //!< vector of multiple service responses /** * @brief Service method callback function type (low level server interface). * * @param method_ The method name. * @param req_type_ The type of the method request. * @param resp_type_ The type of the method response. * @param request_ The request. * @param response_ The response returned from the method call. **/ typedef std::function<int(const std::string& method_, const std::string& req_type_, const std::string& resp_type_, const std::string& request_, std::string& response_)> MethodCallbackT; /** * @brief Service response callback function type (low level client interface). * * @param service_response_ Service response struct containing the (responding) server informations and the response itself. **/ typedef std::function<void(const struct SServiceResponse& service_response_)> ResponseCallbackT; };
<gh_stars>0 #include <efi.h> #include <efilib.h> EFI_STATUS readFile( // show one bmp IN EFI_FILE *dir, IN INT32 index, IN EFI_SYSTEM_TABLE *systab, IN VOID *buf ); EFI_STATUS tostring( // convert digital to string with ".bmp", for example : 9 -> 9.bmp IN INT32 index, OUT CHAR16 *filename ); EFI_STATUS tostring(INT32 index, CHAR16 *filename) { if (index==0) { StrCpy(filename, L"0.story"); return EFI_SUCCESS; } INT32 x=100000; INT32 c=0; while(index/x==0){x=x/10;} while(TRUE) { filename[c]=index/x+48; index=index%x; c++; x=x/10; if(x==0) break; } StrCpy(filename+c, L".story"); return EFI_SUCCESS; } EFI_STATUS readFile( IN EFI_FILE *dir, IN INT32 index, IN EFI_SYSTEM_TABLE *systab, IN VOID *buf ) { EFI_STATUS status; EFI_FILE *file; CHAR16 filename[10]; // Allow up to 9999 stories (Probably going to have to increase buffer size when this engine gets super popular :) INT32 index tostring(index, filename); Status=dir->Open(dir, &file, filename, EFI_FILE_MODE_READ, EFI_FILE_READ_ONLY); // open the file EFI_FILE_INFO *fileinfo; UINTN infosize = SIZE_OF_EFI_FILE_INFO; EFI_GUID info_type = EFI_FILE_INFO_ID; status = file->GetInfo(file, &info_type, &infosize, NULL); // get the info size of file systab->BootServices->AllocatePool(AllocateAnyPages, infosize, (VOID **)&fileinfo); status=file->GetInfo(file, &info_type, &infosize, fileinfo); // get info of file UINTN filesize = fileinfo->FileSize; // get filesize from info systab->BootServices->AllocatePool(AllocateAnyPages, filesize, (VOID **)&buf); // Allocate some room status=file->Read(file, &filesize, buf); systab->BootServices->FreePool(buf); systab->BootServices->FreePool(fileinfo); return EFI_SUCCESS; } EFI_STATUS EFIAPI efi_main(EFI_HANDLE image_handle, EFI_SYSTEM_TABLE *systab) { InitializeLib(image_handle, systab); EFI_STATUS Status; systab->ConOut->ClearScreen(systab->ConOut); // CLEAR! EFI_GUID simplefs_guid = SIMPLE_FILE_SYSTEM_PROTOCOL; // a simple file system protocol in efi // (different from UEFI specification. In specification, this is called EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID ) EFI_FILE_IO_INTERFACE *simplefs; // the simple file system's interface // (different from UEFI specification. In specification, this is called EFI_SIMPLE_FILE_SYSTEM_PROTOCOL) EFI_FILE *root; // root directory EFI_FILE *dir; CHAR16 *dirname=L"\\stories"; // name of the directory where bmp pictures are put status=systab->BootServices->LocateProtocol(&simplefs_guid, NULL, (VOID **)&simplefs); if(EFI_ERROR(status)) Print(L"locate protocol failed \n"); status=simplefs->OpenVolume(simplefs, &root); if(EFI_ERROR(status)) Print(L"open volume failed\n"); status=root->Open(root, &dir, dirname, EFI_FILE_MODE_READ, EFI_FILE_READ_ONLY); if(EFI_ERROR(status)) Print(L"open directory failed\n"); VOID *buf; INT32 index=1; status = readFile(dir, index, systab, buf); // Put the contents of 1.story into buf Print(L"%s", buf); WaitForSingleEvent(ST->ConIn->WaitForKey, 0); uefi_call_wrapper(ST->ConIn->ReadKeyStroke, 2, ST->ConIn, &Key); return Status; }
<gh_stars>100-1000 /*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #ifndef _createK2_h #define _createK2_h #include <petsc.h> #include <petscmat.h> #include <petscvec.h> #include <petscksp.h> PetscErrorCode bsscr_buildK2(KSP ksp); PetscErrorCode bsscr_DGMiGtD( Mat *_K2, Mat K, Mat G, Mat M); PetscErrorCode bsscr_GMiGt( Mat *_K2, Mat K, Mat G, Mat M); PetscErrorCode bsscr_GGt( Mat *_K2, Mat K, Mat G); #endif
<reponame>fossabot/rosbaz #pragma once #include <functional> #include <mutex> #include <thread> #include <vector> namespace rosbaz { namespace io { /// Spawn at most \p max_threads to process \p work_items. void process_async(std::mutex& sync, std::vector<std::function<void(void)>>& work_items, std::size_t max_threads = std::thread::hardware_concurrency()); } // namespace io } // namespace rosbaz
<gh_stars>10-100 #include <stddef.h> #include "lua.h" #include "lauxlib.h" static const char *get_source_filename(lua_State *L, lua_Integer level) { lua_Debug ar; if (!lua_getstack(L, level - 1, &ar)) { return NULL; } lua_getinfo(L, "S", &ar); if (ar.source[0] == '@') { return ar.source + 1; } else { /* ** Ignore Lua code loaded from raw strings, ** unless runner.configuration.codefromstrings is true. */ int codefromstrings; lua_getfield(L, lua_upvalueindex(1), "configuration"); lua_getfield(L, -1, "codefromstrings"); codefromstrings = lua_toboolean(L, -1); lua_pop(L, 2); return codefromstrings ? ar.source : NULL; } } static int l_debug_hook(lua_State *L) { const char *filename; lua_Integer line_nr, max_line_nr; lua_Integer hits, max_hits; lua_Integer steps_after_save, save_step_size; lua_Integer level; line_nr = luaL_checkinteger(L, 2); level = luaL_optinteger(L, 3, 2); lua_settop(L, 0); lua_getfield(L, lua_upvalueindex(1), "initialized"); if (!lua_toboolean(L, -1)) { return 0; } lua_pop(L, 1); filename = get_source_filename(L, level); if (filename == NULL) { return 0; } lua_getfield(L, lua_upvalueindex(1), "data"); lua_getfield(L, -1, filename); if (!lua_istable(L, -1)) { /* New or ignored file. */ lua_pop(L, 1); lua_getfield(L, lua_upvalueindex(2), filename); if (lua_toboolean(L, -1)) { /* Ignored file. */ return 0; } lua_pop(L, 1); /* New file, have to call runner.file_included. */ lua_getfield(L, lua_upvalueindex(1), "file_included"); lua_pushstring(L, filename); lua_call(L, 1, 1); if (!lua_toboolean(L, -1)) { /* Remember this file as ignored. */ lua_pushboolean(L, 1); lua_setfield(L, lua_upvalueindex(2), filename); return 0; } lua_pop(L, 1); /* Construct file data table for this new file. */ lua_newtable(L); lua_pushinteger(L, 0); lua_setfield(L, -2, "max"); lua_pushinteger(L, 0); lua_setfield(L, -2, "max_hits"); /* Copy file data table and save it as data[filename]. */ lua_pushvalue(L, -1); lua_setfield(L, -3, filename); } /* Update max line number for this file if necessary. */ lua_getfield(L, -1, "max"); max_line_nr = lua_tointeger(L, -1); lua_pop(L, 1); if (line_nr > max_line_nr) { lua_pushinteger(L, line_nr); lua_setfield(L, -2, "max"); } /* Increment file_data[line_nr]. */ lua_pushinteger(L, line_nr); lua_pushinteger(L, line_nr); lua_gettable(L, -3); /* Conveniently, lua_tointeger returns 0 on non-number. */ hits = lua_tointeger(L, -1) + 1; lua_pop(L, 1); lua_pushinteger(L, hits); lua_settable(L, -3); /* Update max number of hits if necessary. */ lua_getfield(L, -1, "max_hits"); max_hits = lua_tointeger(L, -1); lua_pop(L, 1); if (hits > max_hits) { lua_pushinteger(L, hits); lua_setfield(L, -2, "max_hits"); } /* Handle runner.tick. */ lua_getfield(L, lua_upvalueindex(1), "tick"); if (!lua_toboolean(L, -1)) { return 0; } lua_getfield(L, lua_upvalueindex(1), "configuration"); lua_getfield(L, -1, "savestepsize"); save_step_size = lua_tointeger(L, -1); lua_pop(L, 2); steps_after_save = lua_tointeger(L, lua_upvalueindex(3)) + 1; if (steps_after_save == save_step_size) { int paused; steps_after_save = 0; /* Unless runner.paused, save data. */ lua_getfield(L, lua_upvalueindex(1), "paused"); paused = lua_toboolean(L, -1); lua_pop(L, 1); if (!paused) { lua_getfield(L, lua_upvalueindex(1), "save_stats"); lua_call(L, 0, 0); } } lua_pushinteger(L, steps_after_save); lua_replace(L, lua_upvalueindex(3)); return 0; } int l_new_hook(lua_State *L) { /* ** Upvalues for the debug hook: ** runner module (already on the stack), ** ignored files set ** and steps counter. */ lua_settop(L, 1); lua_newtable(L); lua_pushinteger(L, 0); lua_pushcclosure(L, l_debug_hook, 3); return 1; } int luaopen_cluacov_hook(lua_State *L) { lua_newtable(L); lua_pushcfunction(L, l_new_hook); lua_setfield(L, -2, "new"); return 1; }
#pragma once #include <glm/glm.hpp> namespace Glide3D { /* 1) Position ~ 12 bytes 2) Normals ~ 12 bytes 3) Texture UV Coordinates ~ 8 Bytes 4) Tangent ~ 12 bytes 5) Bi Tangent ~ 12 bytes Total : 56 bytes per vertex */ struct Vertex { glm::vec3 position; glm::vec3 normals; glm::vec2 tex_coords; glm::vec3 tangent; glm::vec3 bitangent; }; }
/* cdwSnyderomeStepLink - Help fill out cdwStep tables for snyderome test set. */ #include "common.h" #include "linefile.h" #include "hash.h" #include "options.h" #include "jksql.h" #include "cdw.h" #include "cdwLib.h" #include "cdwStep.h" void usage() /* Explain usage and exit. */ { errAbort( "cdwSnyderomeStepLink - Help fill out cdwStep tables for snyderome test set\n" "usage:\n" " cdwSnyderomeStepLink output.sql\n" "options:\n" " -xxx=XXX\n" ); } /* Command line validation table. */ static struct optionSpec options[] = { {NULL, 0}, }; struct slInt *getWgsData(struct sqlConnection *conn, char *format) /* Get list of file IDs for fastq files from snyderome */ { char query[1024]; sqlSafef(query, sizeof(query), "select file_id from cdwFileTags where format='%s' and data_set_id='Snyderome' " " and assay='WGS'", format); return sqlQuickNumList(conn, query); } struct slName *getChromList(struct sqlConnection *conn) /* Get all chroms used by snyderome */ { char query[1024]; sqlSafef(query, sizeof(query), "select distinct(chrom) from cdwFileTags where chrom like 'chr%%' and data_set_id='Snyderome'"); return sqlQuickList(conn, query); } void cdwSnyderomeStepLink(char *sqlOutput) /* cdwSnyderomeStepLink - Help fill out cdwStep tables for snyderome test set. */ { struct sqlConnection *conn = cdwConnect(); struct slInt *fastqList = getWgsData(conn, "fastq"); struct slInt *bamList = getWgsData(conn, "bam"); FILE *f = mustOpen(sqlOutput, "w"); /* Loop through and create input records */ int stepRunId = 2; // Just entered this manually struct slInt *fastq; int ix = 0; for (fastq = fastqList; fastq != NULL; fastq = fastq->next) { fprintf(f, "insert into cdwStepIn (stepRunId,name,ix,fileId) values " " (%d,'reads',%d, %d);\n" , stepRunId, ix, fastq->val); ++ix; } /* Create output records */ struct slInt *bam; ix = 0; for (bam = bamList; bam != NULL; bam = bam->next) { fprintf(f, "insert into cdwStepOut (stepRunId,name,ix,fileId) values " " (%d,'alignments',%d, %d);\n" , stepRunId, ix, bam->val); ++ix; } struct slName *chrom, *chromList = getChromList(conn); int vcfStepDef = 4; for (chrom = chromList; chrom != NULL; chrom = chrom->next) { ++stepRunId; // Just entered this manually fprintf(f, "insert into cdwStepRun (stepDef,stepVersion) values (%d,'unknown');\n", vcfStepDef); /* Figure out the bam */ char query[1024]; sqlSafef(query, sizeof(query), "select file_id from cdwFileTags where chrom='%s' " " and format='BAM' and data_set_id='Snyderome' and assay='WGS'" , chrom->name); int bamId = sqlQuickNum(conn, query); if (bamId == 0) errAbort("Can't find bam for %s", chrom->name); /* Get the VCFs, there should be three */ sqlSafef(query, sizeof(query), "select file_id,submit_file_name from cdwFileTags where chrom='%s' " " and format='VCF' and data_set_id='Snyderome' and assay='WGS'" , chrom->name); struct sqlResult *sr = sqlGetResult(conn, query); char **row; fprintf(f, "insert into cdwStepIn (stepRunId,name,ix,fileId) values (%d,'%s', 0, %d);\n" , stepRunId, "alignments", bamId); while ((row = sqlNextRow(sr)) != NULL) { int vcfId = sqlUnsigned(row[0]); char *fileName = row[1]; char *outName = NULL; if (endsWith(fileName, ".snp.raw.vcf.gz")) outName = "SNP"; else if (endsWith(fileName, ".indel.raw.vcf.gz")) outName = "indel"; else if (endsWith(fileName, ".dindel.indel.vcf.gz")) outName = "dindel"; else errAbort("Unrecognized file ending in %s", fileName); fprintf(f, "insert into cdwStepOut (stepRunId,name,ix,fileId) values " " (%d, '%s', 0, %d);\n" , stepRunId, outName, vcfId); } sqlFreeResult(&sr); } carefulClose(&f); } int main(int argc, char *argv[]) /* Process command line. */ { optionInit(&argc, argv, options); if (argc != 2) usage(); cdwSnyderomeStepLink(argv[1]); return 0; }
<filename>inc/delegate.h // ____________________________________________________________________________________________________________________________________________ // DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE // ____________________________________________________________________________________________________________________________________________ // DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE // ____________________________________________________________________________________________________________________________________________ // DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE...DELEGATE #ifndef _DELEGATE_H_ #define _DELEGATE_H_ #include "utility.h" // nije thread safe u smislu da ne moze vise thread-ova da ga koristi i da pritom jedan od njih pozove destruktor class Delegate { // internal state private: List<SignalHandler>* hlist; // methods private: Delegate(List<SignalHandler>* _hlist); public: Delegate(); ~Delegate(); public: bool add(SignalHandler h); bool swap(SignalHandler h1, SignalHandler h2); uns4 signal(); uns4 size(); Delegate* copy(); void clear(); ostream& print(ostream& os = cout) const; friend ostream& operator <<(ostream& os, const Delegate& d); }; // signalhandler list tools bool match_signal_handler_container(SignalHandler* h, void* args); // args je u stvari kontejner signalhandler-a koga trazimo bool map_call_signal_handler(SignalHandler* h, void*); // zove signal handler ako je ispravno prosledjen signal handler kontejner void print_signal_handler(ostream& os, const SignalHandler* h); // ispisuje signal handler na izlazu SignalHandler* copy_signal_handler_container(SignalHandler* h); // kopira kontejner signalhander-a (pokazivac na prosto polje tipa signalhandler) void delete_signal_handler_container(SignalHandler* h); // brise kontejner signalhandler-a #endif//_DELEGATE_H_
#include "splicing.h" #include "splicing_error.h" #include <math.h> #ifndef M_LN_SQRT_2PI #define M_LN_SQRT_2PI 0.918938533204672741780329736406 /* log(sqrt(2*pi)) == log(2*pi)/2 */ #endif #ifndef M_1_SQRT_2PI #define M_1_SQRT_2PI 0.398942280401432677939946059934 /* 1/sqrt(2pi) */ #endif double splicing_i_dnorm(double x, double mu, double sigma, int plog) { if (sigma <= 0) { splicing_error("Invalid `sigma' for normal", __FILE__, __LINE__, SPLICING_EINVAL); } x = (x - mu) / sigma; return (plog ? -(M_LN_SQRT_2PI + 0.5 * x * x + log(sigma)) : M_1_SQRT_2PI * exp(-0.5 * x * x) / sigma); } double splicing_dnorm(double x, double mu, double sigma) { return splicing_i_dnorm(x, mu, sigma, /*log=*/ 0); } double splicing_logdnorm(double x, double mu, double sigma) { return splicing_i_dnorm(x, mu, sigma, /*log=*/ 1); }
/* Screen Doors*/ #define STRICT #include <windows.h> #include "Init_End.h" #include "kbmain.h" //keyboard header file from 3keyboar #include "resource.h" /*************************************************************/ //Functions in this file /*************************************************************/ #include "sdgutil.h" /************************************************************/ //Functions in other files /************************************************************/ #include "fileutil.h" #include "dgsett.h" BOOL rSetWindowPos(void); BOOL Read_Map_Setting(LPCSTR filename); BOOL BringUpBowser(void); /*************************************************************/ //Global vars /*************************************************************/ LOGFONT lf; extern BOOL Setting_ReadSuccess=FALSE; extern DWORD platform; /**************************************************************************/ /* SendInitErrorMessage - error msg */ /**************************************************************************/ void SendErrorMessage(UINT ids_string) { TCHAR str[256]=TEXT(""); TCHAR title[256]=TEXT(""); LoadString(hInst, ids_string, &str[0], 256); LoadString(hInst, IDS_TITLE1, &title[0], 256); MessageBox(kbmainhwnd, str, title,MB_ICONHAND | MB_OK); }// SendErrorMessage /******************************************************************************/ //initially set all the preferences (except some keyboard preference which // set at kbmain.c) /******************************************************************************/ void PredictInit(void) { // *** use the setting read from Registry *** if(Setting_ReadSuccess=OpenUserSetting()) { g_margin = kbPref->g_margin; // Margin between rows and columns smallKb = kbPref->smallKb; // TRUE when working with Small Keyboard PrefTextKeyColor = kbPref->PrefTextKeyColor; // Prefered Color for text in keys PrefCharKeyColor = kbPref->PrefCharKeyColor; // ditto normal key PrefModifierKeyColor= kbPref->PrefModifierKeyColor; // ditto modifier key PrefDeadKeyColor = kbPref->PrefDeadKeyColor; // ditto dead key PrefBackgroundColor = kbPref->PrefBackgroundColor; // ditto Keyboard backgraund PrefDeltakeysize = kbPref->PrefDeltakeysize; // Preference increment in key size PrefshowActivekey = kbPref->PrefshowActivekey; // Show cap letters in keys KBLayout = kbPref->KBLayout; // 101, 102, 106, KB layout Pref3dkey = kbPref->Pref3dkey = FALSE; // ONLY Use 2d keys Prefusesound = kbPref->Prefusesound; // Use click sound PrefAlwaysontop = kbPref->PrefAlwaysontop; // windows always on top //if Scanning on, we don't want hilite key if(kbPref->PrefScanning) Prefhilitekey = FALSE; else Prefhilitekey = kbPref->Prefhilitekey = TRUE; //hilite key under cursor PrefDwellinkey = kbPref->PrefDwellinkey; // TRUE for dwelling PrefDwellTime = kbPref->PrefDwellTime; // How long to dwell PrefScanning = kbPref->PrefScanning; PrefScanTime = kbPref->PrefScanTime; g_fShowWarningAgain = kbPref->fShowWarningAgain; // Show initial warning message again prefUM = CheckUM(); // font plf = &lf; // pointer to the actual font plf->lfHeight = kbPref->lf.lfHeight; plf->lfWidth = kbPref->lf.lfWidth; plf->lfEscapement = kbPref->lf.lfEscapement; plf->lfOrientation = kbPref->lf.lfOrientation; plf->lfWeight = kbPref->lf.lfWeight; plf->lfItalic = kbPref->lf.lfItalic ; plf->lfUnderline = kbPref->lf.lfUnderline; plf->lfStrikeOut = kbPref->lf.lfStrikeOut; plf->lfCharSet = kbPref->lf.lfCharSet; plf->lfOutPrecision = kbPref->lf.lfOutPrecision; plf->lfClipPrecision = kbPref->lf.lfClipPrecision; plf->lfQuality = kbPref->lf.lfQuality ; plf->lfPitchAndFamily = kbPref->lf.lfPitchAndFamily; wsprintf(plf->lfFaceName, TEXT("%hs"), kbPref->lf.lfFaceName); //"MS SHELL DLG" is the alias to default font //wsprintf(plf->lfFaceName, TEXT("%hs"), "MS SHELL DLG"); newFont = TRUE; //Use 101 keyboard layout (default is 101 and Actual layout) if(KBLayout == 101) { //The setting say use Block layout, so switch to Block structure if(!kbPref->Actual) BlockKB(); } // Use 102 keyboard layout else if(KBLayout == 102) EuropeanKB(); //Use 106 keyboard layout else JapaneseKB(); } else { SendErrorMessage(IDS_SETTING_DAMAGE); ExitProcess(0); } } /**************************************************************/ DWORD WhatPlatform(void) { OSVERSIONINFO osverinfo; osverinfo.dwOSVersionInfoSize = (DWORD)sizeof(OSVERSIONINFO); GetVersionEx(&osverinfo); return osverinfo.dwPlatformId; } /**************************************************************/ // Check to see the keyboard is out of screen or not with the given // Screen resoultion (scrCX, scrCY) /**************************************************************/ BOOL IsOutOfScreen(int scrCX, int scrCY) { //Check left and top if(kbPref->KB_Rect.left < 0 || kbPref->KB_Rect.top < 0) return TRUE; //Check right and bottom if(kbPref->KB_Rect.right > scrCX || kbPref->KB_Rect.bottom > scrCY) return TRUE; return FALSE; }
<gh_stars>10-100 /* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ /* */ /* * Constants defining the rescheduling of acqproc polling */ /* * CONTANT FUNCTION * ============= ======== * TIME_OFF turn off timer * TIME_ON initalize service routine for time interupts and * then do a TIME_RESET * TIME_RESET set timing interval to 5 seconds and start timer * TIME_NORMAL use current timing interval and start timer * TIME_FAST set timing interval to 0.01 seconds and start timer * TIME_FASTER decrease timing interval by 0.05 seconds and start timer * TIME_SLOWER increase timing interval by 0.01 seconds if an experiment * is active and by 0.05 seconds if no experiment is active * and start timer * TIME_NEXT_FAST set the next current timing interval to 0.01 seconds but * do NOT set timer * TIME_NEXT_SLOW set the next current timing interval to 5 seconds but * do NOT set timer * */ #define TIME_OFF 1 #define TIME_ON 2 #define TIME_RESET 3 #define TIME_NORMAL 4 #define TIME_FAST 5 #define TIME_FASTER 6 #define TIME_SLOWER 7 #define TIME_NEXT_FAST 8 #define TIME_NEXT_SLOW 9
<gh_stars>0 /* SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause */ /****************************************************************************** * Copyright (c) 2020, STMicroelectronics - All Rights Reserved This file is part of VL53L1 and is dual licensed, either GPL-2.0+ or 'BSD 3-clause "New" or "Revised" License' , at your option. ****************************************************************************** */ #ifndef _VL53L1_PLATFORM_USER_DATA_H_ #define _VL53L1_PLATFORM_USER_DATA_H_ #ifndef __KERNEL__ #include <stdlib.h> #endif #include "vl53l1_def.h" #ifdef __cplusplus extern "C" { #endif typedef struct { VL53L1_DevData_t Data; uint8_t i2c_slave_address; uint8_t comms_type; uint16_t comms_speed_khz; uint32_t new_data_ready_poll_duration_ms; } VL53L1_Dev_t; typedef VL53L1_Dev_t *VL53L1_DEV; #define VL53L1DevDataGet(Dev, field) (Dev->Data.field) #define VL53L1DevDataSet(Dev, field, VL53L1_p_002) ((Dev->Data.field) = (VL53L1_p_002)) #define VL53L1DevStructGetLLDriverHandle(Dev) (&Dev->Data.LLData) #define VL53L1DevStructGetLLResultsHandle(Dev) (&Dev->Data.llresults) #ifdef __cplusplus } #endif #endif
<reponame>elk-audio/lkjb-plugins /* ============================================================================== This file was auto-generated by the Introjucer! It contains the basic startup code for a Juce application. ============================================================================== */ #ifndef __PLUGINEDITOR_H_3BD4AE6E__ #define __PLUGINEDITOR_H_3BD4AE6E__ #include "../JuceLibraryCode/JuceHeader.h" #include "PluginProcessor.h" #include "gui/pitcheddelaytab.h" #include "gui/DelayGraph.h" #include "presetmanager.h" class PitchedDelayLookAndFeel : public LookAndFeel_V2 { public: PitchedDelayLookAndFeel() { setColour(Slider::thumbColourId, Colours::lightgrey); setColour(TextButton::buttonColourId, Colours::lightgrey); setColour(TextButton::buttonOnColourId, Colours::grey); setColour(ComboBox::buttonColourId, Colours::lightgrey); setColour(TextEditor::focusedOutlineColourId, Colours::transparentBlack); setColour(TextEditor::highlightColourId, Colours::darkgrey.withAlpha(0.25f)); } private: }; //============================================================================== /** */ class CallbackTab : public TabbedComponent { public: CallbackTab(TabbedButtonBar::Orientation orientation, PitchedDelayAudioProcessor* processor_) : TabbedComponent(orientation), processor(processor_) { } void currentTabChanged(int newCurrentTabIndex, const String& /*newCurrentTabName*/) { processor->currentTab = newCurrentTabIndex; } private: PitchedDelayAudioProcessor* processor; }; class PitchedDelayAudioProcessorEditor : public AudioProcessorEditor, public Timer, public ActionListener, public Slider::Listener, public Button::Listener, public ComboBox::Listener { public: PitchedDelayAudioProcessorEditor (PitchedDelayAudioProcessor* ownerFilter); ~PitchedDelayAudioProcessorEditor(); //============================================================================== // This is just a standard Juce paint method... void paint (Graphics& g); void resized(); void timerCallback(); void actionListenerCallback (const String& message); void sliderValueChanged (Slider* slider); void buttonClicked (Button* button); void comboBoxChanged (ComboBox* comboBoxThatHasChanged); private: void updatePresets(); PitchedDelayAudioProcessor* getProcessor() { return static_cast<PitchedDelayAudioProcessor*> (getAudioProcessor()); } CallbackTab tabs; OwnedArray<PitchedDelayTab> delays; ScopedPointer<DelayGraph> graph; Slider dryVolume; Slider masterVolume; ToggleButton showTooltips; PitchedDelayLookAndFeel lookAndFeel; ScopedPointer<TooltipWindow> tooltipWindow; ScopedPointer<PresetManager> presetManager; TextButton addPreset; TextButton removePreset; ComboBox presetList; }; #endif // __PLUGINEDITOR_H_3BD4AE6E__
/* Copyright 2016 Nidium Inc. All rights reserved. Use of this source code is governed by a MIT license that can be found in the LICENSE file. */ #ifndef binding_jsimage_h__ #define binding_jsimage_h__ #include "Core/Messages.h" #include "IO/Stream.h" #include "Binding/ClassMapperWithEvents.h" using Nidium::Core::Path; namespace Nidium { namespace Graphics { class Image; } namespace Binding { class JSImage : public ClassMapperWithEvents<JSImage>, public Core::Messages { public: JSImage(); virtual ~JSImage(); static JSPropertySpec *ListProperties(); static JSImage *Constructor(JSContext *cx, JS::CallArgs &args, JS::HandleObject obj); static Graphics::Image *JSObjectToImage(JS::HandleObject obj); static void RegisterObject(JSContext *cx); static bool JSObjectIs(JSContext *cx, JS::HandleObject obj); static JSObject *BuildImageObject(JSContext *cx, Graphics::Image *image, const char name[] = NULL); void onMessage(const Core::SharedMessages::Message &msg); Graphics::Image *getImage() const { return m_Image; } protected: NIDIUM_DECL_JSGETTERSETTER(src); NIDIUM_DECL_JSGETTER(width); NIDIUM_DECL_JSGETTER(height); private: bool setupWithBuffer(buffer *buf); Graphics::Image *m_Image; IO::Stream *m_Stream; Path *m_Path; }; } // namespace Binding } // namespace Nidium #endif
/* { dg-do compile } */ /* { dg-options "-O3 -fcheck-pointer-bounds -mmpx -fno-inline" } */ #include "math.h" double test1 (double x, double y, double (*fn)(double, double)) { return fn (x, y); } double test2 (double x, double y) { return test1 (x, y, copysign); }
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ proc.h ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ <NAME>, 2005 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ typedef struct s_stackframe { /* proc_ptr points here ↑ Low */ u32 gs; /* ┓ │ */ u32 fs; /* ┃ │ */ u32 es; /* ┃ │ */ u32 ds; /* ┃ │ */ u32 edi; /* ┃ │ */ u32 esi; /* ┣ pushed by save() │ */ u32 ebp; /* ┃ │ */ u32 kernel_esp; /* <- 'popad' will ignore it │ */ u32 ebx; /* ┃ ↑栈从高地址往低地址增长*/ u32 edx; /* ┃ │ */ u32 ecx; /* ┃ │ */ u32 eax; /* ┛ │ */ u32 retaddr; /* return address for assembly code save() │ */ u32 eip; /* ┓ │ */ u32 cs; /* ┃ │ */ u32 eflags; /* ┣ these are pushed by CPU during interrupt │ */ u32 esp; /* ┃ │ */ u32 ss; /* ┛ ┷High */ }STACK_FRAME; typedef struct s_proc { STACK_FRAME regs; /* process registers saved in stack frame */ u16 ldt_sel; /* gdt selector giving ldt base and limit */ DESCRIPTOR ldts[LDT_SIZE]; /* local descriptors for code and data */ int ticks; /* remained ticks */ int priority; u32 pid; /* process id passed in from MM */ char p_name[16]; /* name of the process */ int sleep_ticks; }PROCESS; typedef struct s_task { task_f initial_eip; int stacksize; char name[32]; }TASK; /* Number of tasks */ #define NR_TASKS 6 /* stacks of tasks */ #define STACK_SIZE_TESTA 0x8000 #define STACK_SIZE_TESTB 0x8000 #define STACK_SIZE_TESTC 0x8000 #define STACK_SIZE_TESTD 0x8000 #define STACK_SIZE_TESTE 0x8000 #define STACK_SIZE_TESTF 0x8000 #define STACK_SIZE_TOTAL (STACK_SIZE_TESTA + STACK_SIZE_TESTB + \ STACK_SIZE_TESTC + STACK_SIZE_TESTD + \ STACK_SIZE_TESTE + STACK_SIZE_TESTF) /* PV Semaphore */ typedef struct{ int value; PROCESS * table[6]; } Semaphore; PUBLIC void init_semaphore(Semaphore S_table[]); PUBLIC PROCESS * null_proc; PUBLIC Semaphore S_table[3]; //mutex, re, w
/* * $Revision: 565 $ $Date: 2011-02-15 16:00:43 -0800 (Tue, 15 Feb 2011) $ * * Copyright by Astos Solutions GmbH, Germany * * this file is published under the Astos Solutions Free Public License * For details on copyright and terms of use see * http://www.astos.de/Astos_Solutions_Free_Public_License.html */ #ifndef _VESTA_FRAME_H_ #define _VESTA_FRAME_H_ #include "Object.h" #include <Eigen/Core> #include <Eigen/Geometry> namespace vesta { /** StateTransform is a 6x6 matrix used for converting a state vector from * one frame to a second frame. */ typedef Eigen::Matrix<double, 6, 6> StateTransform; /** Abstract base class for reference frames. A reference frame in vesta is a * simply set of three orthogonal axes that are potentiall rotating. * Subclasses must override the orientation() and angularVelocity() methods. * The orientation and angular velocity of a frame are reported relative to * the inertial International Celestial Reference Frame. */ class Frame : public Object { public: virtual ~Frame() {} /** Compute the orientation of the frame with respect to the ICRF at the * specified time. The orientation is returned as a unit quaternion. This * can be used to transform the vectors in the frame to ICRF. For example, * the following code will compute the frame's z direction in the ICRF: * * \code * Vector3d framePos(0.0, 0.0, 1.0); * Quaterniond q = frame.orientation(t); * Vector3d icrfPos = q * framePos; * \endcode * * \param tsec The time given as the number of seconds since 1 Jan 2000 12:00:00 TDB. */ virtual Eigen::Quaterniond orientation(double tsec) const = 0; /** Compute the angular of the frame at the specified time. The units * of angular velocity are radians per second. * * \param tsec The time given as the number of seconds since 1 Jan 2000 12:00:00 TDB. */ virtual Eigen::Vector3d angularVelocity(double tsec) const = 0; StateTransform stateTransform(double tsec) const; StateTransform inverseStateTransform(double tsec) const; static StateTransform stateTransform(const Frame* from, const Frame* to, double tsec); }; } #endif // _VESTA_FRAME_H_
<filename>wh_bsp/include/device/etimer.h /******************************************************************* * * PROJECT: W01 * * FILENAME: etimer.h * * FUNCTION: ETIMER header file * * AUTHOR: yexc * * DATE: 2018/11/09 * * IS_FINISH: NO * ********************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef SDJ2102_ETIMER_H #define SDJ2102_ETIMER_H /* Includes ------------------------------------------------------------------*/ #include "platform.h" /* Exported constants --------------------------------------------------------*/ /* External variables --------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ #define ETIMER_CR 0x0 #define CntNumLDR 0x2 #define CntNuHDR 0x3 #define ETIMER_INTSRC 0x4 #define CNTVAILDR 0x8 #define CNTVAIHDR 0x9 #define CCVAILDR 0xa #define CCVAIHDR 0xb #define PWMTIMVAIDR 0xc #define PWMTIMVAIHDR 0xd #define PWMTIMNUMLDR 0xe #define PWMTIMNUMHDR 0xf #define PLUSNUMLDR 0x10 #define PLUSNUMHDR 0x11 #define CYCLNUMLDR 0x12 #define CYCLNUMHDR 0x13 /* Exported functions ------------------------------------------------------- */ void etimer_pwm_mode(int cnt,int val,int count); void etimer_timer_mode(int cnt); void etimer_count_mode(int cnt); void etimer_event_mode(int cnt,char clk_edge_mode); void etimer_pwmtest_mode(int cnt,int val,int count); void etimer2_pwm_mode(int cnt,int val,int count); void etimer2_timer_mode(int cnt); void etimer2_count_mode(int cnt); void etimer2_event_mode(int cnt,char clk_edge_mode); void etimer2_pwmtest_mode(int cnt,int val,int count); #endif
<filename>DirectX11 Engine 2019/Engine/Models/Model.h #pragma once #undef min #undef max #include "pc.h" #include "Engine/Scene/Texture.h" #include "Engine/DirectX/Buffer.h" #include "Engine/DirectX/ConstantBuffer.h" #include "Engine/DirectX/IndexBuffer.h" #include "Engine/DirectX/VertexBuffer.h" #include "Engine/Models/Mesh.h" struct BaseTexturePreset { bool bDiffuse; bool bNormals; bool bOpacity; bool bSpecular; bool mEmpty[11]; BaseTexturePreset(): bDiffuse(true), bNormals(true), bOpacity(true), bSpecular(true) {}; BaseTexturePreset(bool diff, bool norm=false, bool opac=false, bool spec=false): bDiffuse(diff), bNormals(norm), bOpacity(opac), bSpecular(spec) {}; }; class Model: public DirectXChild { protected: static Texture *gDefaultTexture, *gDefaultTextureOpacity, *gDefaultTextureSpecular; static ID3D11ShaderResourceView* gNullRes; private: typedef enum { Diffuse, Normal, Bump, Opacity, Specular, Rougness } eTextureType; struct tTuple { aiString str; eTextureType type; tTuple(aiString s, eTextureType t): str(s), type(t) {}; }; const char* sName; // Model name std::vector<Mesh*> MeshBuffer; std::vector<tTuple*> FilenameBuffer; std::vector<aiString> FNB_Diffuse, FNB_Normal, FNB_Opacity, FNB_Specular, FNB_Rougness; std::vector<Texture*> DiffuseTextureBuffer, NormalTextureBuffer, OpacityTextureBuffer, SpecularTextureBuffer, RougnessTextureBuffer; std::vector<int> DiffuseMapIndex, NormalMapIndex, OpacityMapIndex, SpecularMapIndex, RougnessMapIndex; int num, mVertexSize; bool bUseDefaultTexture = true; ConstantBuffer *cbBoolTexturesInst; struct cbBoolTextures { bool bDiffuse; bool bNormals; bool bOpacity; bool bSpecular; bool bCubemap; bool PADDING[11]; }; //cbBoolTextures cbBoolTexturesInstData; public: Model(const char* name, int SizeOfVertex); Model(const char* name); static void SetDefaultTexture(Texture* def); static void SetDefaultTextureOpacity(Texture* def); static void SetDefaultTextureSpecular(Texture* def); void Render(UINT num=1, bool bBindTextures=true); //void Render(UINT num, bool bBindTextures=true); template<typename VertexT=Vertex_PNT/*, TexturesT=DefaultTexturePreset*/> void LoadModel(std::string fname, bool SRV=false); template<typename VertexT=Vertex_PNT> void ProcessNode(aiNode* node, const aiScene* scene, bool SRV=false); template<typename VertexT=Vertex_PNT> Mesh* ProcessMesh(aiMesh* mesh, const aiScene* scene, bool SRV=false); void Release(); void DisableDefaultTexture() { bUseDefaultTexture = false; }; void EnableDefaultTexture() { bUseDefaultTexture = true; }; const IndexBuffer* GetIB() const { return MeshBuffer[0]->GetIB(); } const VertexBuffer* GetVB() const { return MeshBuffer[0]->GetVB(); } }; /*template<typename VertexT> void LoadModel(std::string fname) { Model::LoadModel<VertexT>(fname); }*/ template<typename VertexT> void Model::LoadModel(std::string fname, bool SRV) { if( mVertexSize == 0 ) mVertexSize = sizeof(VertexT); Assimp::Importer importer; const aiScene *scene = importer.ReadFile(fname, aiProcess_Triangulate | aiProcess_CalcTangentSpace); if( !scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode ) { std::cout << "Can't load model! (" << fname << ")" << std::endl; return; } // Process scene ProcessNode<VertexT>(scene->mRootNode, scene, SRV); // Load textures stbi_set_flip_vertically_on_load(1); int i = 0, j = 0, k = 0, l = 0, m = 0; for( tTuple* f : FilenameBuffer ) { // Load texture Texture *tex = new Texture(); tex->Load(("../Models/" + std::string(f->str.C_Str())).c_str(), DXGI_FORMAT_R8G8B8A8_UNORM); switch( f->type ) { case eTextureType::Diffuse: DiffuseTextureBuffer.push_back(tex); // Use default texture if( tex->GetWidth() == 0 ) { DiffuseMapIndex.at(i) = -1; } else { std::cout << "Diffuse(" << f->str.C_Str() << ")" << std::endl; } i++; break; case eTextureType::Normal: NormalTextureBuffer.push_back(tex); // Use default texture if( tex->GetWidth() == 0 ) { NormalMapIndex.at(j) = -1; } else { std::cout << "Normal(" << f->str.C_Str() << ")" << std::endl; } j++; break; case eTextureType::Opacity: OpacityTextureBuffer.push_back(tex); // Use default texture if( tex->GetWidth() == 0 ) { OpacityMapIndex.at(k) = -1; } else { std::cout << "Opacity(" << f->str.C_Str() << ")" << std::endl; } k++; break; case eTextureType::Specular: SpecularTextureBuffer.push_back(tex); // Use default texture if( tex->GetWidth() == 0 ) { SpecularMapIndex.at(l) = -1; } else { std::cout << "Specular(" << f->str.C_Str() << ")" << std::endl; } l++; break; case eTextureType::Rougness: RougnessTextureBuffer.push_back(tex); // Use default texture if( tex->GetWidth() == 0 ) { RougnessMapIndex.at(l) = -1; } else { std::cout << "Rougness(" << f->str.C_Str() << ")" << std::endl; } m++; break; } } stbi_set_flip_vertically_on_load(0); // Clear buffer //FilenameBuffer.clear(); } template<typename VertexT> void Model::ProcessNode(aiNode* node, const aiScene* scene, bool SRV) { // Process meshes for( size_t i = 0; i < node->mNumMeshes; i++ ) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; MeshBuffer.push_back(ProcessMesh<VertexT>(mesh, scene)); } // Process children for( size_t i = 0; i < node->mNumChildren; i++ ) { ProcessNode<VertexT>(node->mChildren[i], scene, SRV); } } template<typename VertexT> Mesh* Model::ProcessMesh(aiMesh* inMesh, const aiScene* scene, bool SRV) { // Output Mesh* mesh = new Mesh; // Buffers VertexBuffer *vb = new VertexBuffer(); IndexBuffer *ib = new IndexBuffer(); // vb->SetSRV(SRV); ib->SetSRV(SRV); // Source data std::vector<int> indices; std::vector<VertexT> vertices;// vertices.resize(inMesh->mNumVertices); //Vertex* vertices = (Vertex*)malloc(sizeof(Vertex_PNT) * inMesh->mNumVertices); // Data size unsigned int IndexNum = 0; // Load mesh data // Process Vertices for( size_t i = 0; i < inMesh->mNumVertices; i++ ) { // Create new vertex VertexT v(inMesh, i); // Push new vertex vertices.push_back(v); } // Process indices for( size_t i = 0; i < inMesh->mNumFaces; i++ ) { aiFace face = inMesh->mFaces[i]; IndexNum += face.mNumIndices; for( size_t j = 0; j < face.mNumIndices; j++ ) { indices.push_back(face.mIndices[j]); } } // Process materials // ... // Load texture maps if( inMesh->mMaterialIndex >= 0 ) { aiMaterial *mat = scene->mMaterials[inMesh->mMaterialIndex]; aiString tFname; // Load diffuse textures tFname = " "; mat->GetTexture(aiTextureType_DIFFUSE, 0, &tFname); if( !strcmp(tFname.C_Str(), "") || !strcmp(tFname.C_Str(), " ") || tFname.length == 0 || tFname.length == 1 ) { DiffuseMapIndex.push_back(-1); } else { auto index = std::find(FNB_Diffuse.begin(), FNB_Diffuse.end(), tFname); if( index == FNB_Diffuse.end() ) { // This texture wasn't loaded prev. DiffuseMapIndex.push_back(static_cast<int>(FNB_Diffuse.size())); FilenameBuffer.push_back(new tTuple(tFname, eTextureType::Diffuse)); FNB_Diffuse.push_back(tFname); } else { DiffuseMapIndex.push_back(static_cast<int>(std::distance(FNB_Diffuse.begin(), index))); } } // Load normal textures tFname = " "; mat->GetTexture(aiTextureType_HEIGHT, 0, &tFname); if( !strcmp(tFname.C_Str(), "") || !strcmp(tFname.C_Str(), " ") || tFname.length == 0 || tFname.length == 1 ) { NormalMapIndex.push_back(-1); } else { auto index = std::find(FNB_Normal.begin(), FNB_Normal.end(), tFname); if( index == FNB_Normal.end() ) { // This texture wasn't loaded prev. NormalMapIndex.push_back(static_cast<int>(FNB_Normal.size())); FilenameBuffer.push_back(new tTuple(tFname, eTextureType::Normal)); FNB_Normal.push_back(tFname); } else { NormalMapIndex.push_back(static_cast<int>(std::distance(FNB_Normal.begin(), index))); } } // Load opacity textures tFname = " "; mat->GetTexture(aiTextureType_OPACITY, 0, &tFname); if( !strcmp(tFname.C_Str(), "") || !strcmp(tFname.C_Str(), " ") || tFname.length == 0 || tFname.length == 1 ) { OpacityMapIndex.push_back(-1); } else { auto index = std::find(FNB_Opacity.begin(), FNB_Opacity.end(), tFname); if( index == FNB_Opacity.end() ) { // This texture wasn't loaded prev. OpacityMapIndex.push_back(static_cast<int>(FNB_Opacity.size())); FilenameBuffer.push_back(new tTuple(tFname, eTextureType::Opacity)); FNB_Opacity.push_back(tFname); } else { OpacityMapIndex.push_back(static_cast<int>(std::distance(FNB_Opacity.begin(), index))); } } // Load specular textures tFname = " "; mat->GetTexture(aiTextureType_SPECULAR, 0, &tFname); if( !strcmp(tFname.C_Str(), "") || !strcmp(tFname.C_Str(), " ") || tFname.length == 0 || tFname.length == 1 ) { SpecularMapIndex.push_back(-1); } else { auto index = std::find(FNB_Specular.begin(), FNB_Specular.end(), tFname); if( index == FNB_Specular.end() ) { // This texture wasn't loaded prev. SpecularMapIndex.push_back(static_cast<int>(FNB_Specular.size())); FilenameBuffer.push_back(new tTuple(tFname, eTextureType::Specular)); FNB_Specular.push_back(tFname); } else { SpecularMapIndex.push_back(static_cast<int>(std::distance(FNB_Specular.begin(), index))); } } // Load roughness textures tFname = " "; mat->GetTexture(aiTextureType_UNKNOWN, 0, &tFname); if( !strcmp(tFname.C_Str(), "") || !strcmp(tFname.C_Str(), " ") || tFname.length == 0 || tFname.length == 1 ) { RougnessMapIndex.push_back(-1); } else { auto index = std::find(FNB_Rougness.begin(), FNB_Rougness.end(), tFname); if( index == FNB_Rougness.end() ) { // This texture wasn't loaded prev. RougnessMapIndex.push_back(static_cast<int>(FNB_Rougness.size())); FilenameBuffer.push_back(new tTuple(tFname, eTextureType::Rougness)); FNB_Rougness.push_back(tFname); } else { RougnessMapIndex.push_back(static_cast<int>(std::distance(FNB_Rougness.begin(), index))); } } } // Create buffers ib->CreateDefault(IndexNum, &indices[0]); vb->CreateDefault(inMesh->mNumVertices, mVertexSize, &vertices[0]); // Debug ib->SetName((std::string(sName) + std::string("'s Index Buffer")).c_str()); vb->SetName((std::string(sName) + std::string("'s Vertex Buffer")).c_str()); // Create mesh mesh->SetBuffer(vb, ib); // return mesh; }
/* * include File <contrib/md5gg.h> * * GG's utility functions for MD5 manipulation * * written: 1993-01-05: <<EMAIL>> * latest update: 1995-09-01 * */ #ifndef __contrib_md5gg__ #define __contrib_md5gg__ #include <gg/floskel.h> #ifdef __GG_dpp__ /* if <gg/dpp.h> is included, there are also these routines: */ # define MD5Digest2String(digest,string) bin_to_hex((digest),(string),16) # define MD5String2Digest(digest,string) hex_to_bin((string),(digest),16) #else int cdecl MD5Digest2String (char *digest, char *string); int cdecl MD5String2Digest (char *digest, char *string); #endif char *cdecl MD5check_string (unsigned char *str); char *cdecl MD5check_block (unsigned char *str, int lng); unsigned char *cdecl MD5chk2_block (unsigned char *str, int lng); unsigned char *cdecl MD5chk2_string (unsigned char *str); unsigned char *cdecl MD5chk2_block_array (unsigned char *str [], int lng [], int cnt); #ifdef _FILE_DEFINED unsigned char *cdecl MD5chk_stream (FILE *fi, long size); #endif /* _FILE_DEFINED */ unsigned char *MD5chk_file_block (char *fnm, long beg, long size); #define MD5chk_file(fnm) MD5chk_file_block((fnm), 0L, 0x7FFFFFFFL); #endif /* __contrib_md5gg__ */
#pragma once #ifdef LAMBDA_PLATFORM_WINDOWS #include "Time/API/Time.h" #include "Windows.h" namespace LambdaEngine { class Win32Time : public Time { public: DECL_STATIC_CLASS(Win32Time); static FORCEINLINE void PreInit() { ::QueryPerformanceFrequency(&s_Frequency); } static FORCEINLINE uint64 GetPerformanceCounter() { LARGE_INTEGER counter = {}; ::QueryPerformanceCounter(&counter); return uint64(counter.QuadPart); } static FORCEINLINE uint64 GetPerformanceFrequency() { return uint64(s_Frequency.QuadPart); } private: inline static LARGE_INTEGER s_Frequency = { 1 }; }; typedef Win32Time PlatformTime; } #endif
/*++ Copyright (c) 1990 Microsoft Corporation Module Name: heap.c Abstract: This function contains the default ntsd debugger extensions Author: <NAME> (bobday) 29-Feb-1992 Grabbed standard header Revision History: <NAME> (NeilSa) 15-Jan-1996 Merged with vdmexts --*/ #include <precomp.h> #pragma hdrstop BOOL bWalkOnly = FALSE; ULONG GetHeapBase( VOID ) { WORD selector; SELECTORINFO si; if (!ReadMemExpression("ntvdmd!DbgWowhGlobalHeap", &selector, sizeof(selector))) { return 0; } GetInfoFromSelector(selector, PROT_MODE, &si); return(si.Base + GetIntelBase()); } void GetFileNameFromOwner( LPSTR filename, LPSTR OwnerName ) { } VOID GetHeapOwnerInfo( HEAPENTRY *he ) { BOOL b; NEHEADER owner; ULONG base; UCHAR len; int i; ULONG offset; WORD wTemp; he->SegmentNumber = -1; he->OwnerName[0] = 0; if (he->gnode.pga_owner == 0) { strcpy(he->OwnerName, "free"); return; } else if (he->gnode.pga_owner>=0xFFF8) { strcpy(he->OwnerName, "sentinel"); return; } base = GetInfoFromSelector(he->gnode.pga_owner, PROT_MODE, NULL) + GetIntelBase(); b = READMEM((LPVOID)base, &owner, sizeof(owner)); if (b) { if (owner.ne_magic == 0x454e) { len = ReadByteSafe(base+owner.ne_restab); if (len>8) { len=8; } READMEM((LPVOID)(base+owner.ne_restab+1), he->OwnerName, 8); he->OwnerName[len] = 0; if (!_stricmp(he->OwnerName, "kernel")) { strcpy(he->FileName, "krnl386"); } else { strcpy(he->FileName, he->OwnerName); } offset = owner.ne_segtab; for (i=0; i<owner.ne_cseg; i++) { wTemp = ReadWordSafe(base+offset+8); //get handle if (wTemp == he->gnode.pga_handle) { he->SegmentNumber = i; break; } offset += 10; } } } } BOOL CheckGlobalHeap( BOOL bVerbose ) { PGHI32 pghi; DWORD offset, prevoffset; DWORD count, heapcount; DWORD p; GNODE32 gnode; PBYTE pFault = NULL; BOOL bError = FALSE; pghi = (PGHI32)GetHeapBase(); prevoffset = offset = (DWORD) ReadWord(&pghi->hi_first); heapcount = count = ReadWord(&pghi->hi_count); if (bVerbose) { PRINTF("Global Heap is at %08X\n", pghi); } while ((offset != 0) && (count)) { if (offset&0x1f) { PRINTF("Error! Kernel heap entry(%08X) contains invalid forward link (%08X)\n", prevoffset, offset); return FALSE; } p = (DWORD)pghi + offset; if (!ReadGNode32Safe(p, &gnode)) { PRINTF("Error! Kernel heap entry(%08X) contains invalid forward link (%08X)\n", prevoffset, offset); return FALSE; } if (count == heapcount) { // first entry if (offset != gnode.pga_prev) { PRINTF("Error! Kernel heap entry (%08X) contains invalid back link (%08X)\n", offset, gnode.pga_prev); PRINTF(" expecting (%08X)\n", offset); return FALSE; } } else { if (prevoffset != gnode.pga_prev) { PRINTF("Error! Kernel heap entry (%08X) contains invalid back link (%08X)\n", offset, gnode.pga_prev); PRINTF(" expecting (%08X)\n", prevoffset); return FALSE; } } prevoffset = offset; count--; if (offset == gnode.pga_next) { if (!count) { if (bVerbose) { PRINTF("%d entries scanned\n", heapcount); } return TRUE; } else { PRINTF("Error! Kernel heap count (%d) larger then forward chain (%d)\n", heapcount, heapcount-count); } } offset = gnode.pga_next; } PRINTF("Error! Kernel heap count (%d) smaller then forward chain\n", heapcount); return FALSE; } BOOL FindHeapEntry( HEAPENTRY *he, UINT FindMethod, BOOL bVerbose ) { PGHI32 pghi; DWORD offset; DWORD MaxEntries, count; DWORD p; PBYTE pFault = NULL; BOOL bError = FALSE; pghi = (PGHI32)GetHeapBase(); // // Verify that we are looking at a heap // offset = (DWORD) ReadWordSafe(&pghi->hi_first); p = (DWORD)pghi + offset; if (!ReadGNode32Safe(p, &he->gnode)) { if (bVerbose) { PRINTF("Heap not available\n"); } return FALSE; } if (offset != he->gnode.pga_prev) { if (bVerbose) { PRINTF("Heap not valid\n"); } return FALSE; } // // The caller has requested that we return the next heap // entry since the last invocation, or the first entry. // if (he->CurrentEntry == 0) { // get first entry offset = (DWORD) ReadWord(&pghi->hi_first); } else { if (he->CurrentEntry == he->NextEntry) { return FALSE; } // get next entry offset = he->NextEntry; } he->CurrentEntry = offset; if ((he->Selector == 0) && (FindMethod != FHE_FIND_MOD_ONLY)) { p = (DWORD)pghi + offset; if (!ReadGNode32(p, &he->gnode)) { return FALSE; } he->NextEntry = he->gnode.pga_next; GetHeapOwnerInfo(he); return TRUE; } // // If we get here, the caller wants us to scan the heap // MaxEntries = ReadWord(&pghi->hi_count); count = 0; while ((offset != 0) && (count <= MaxEntries)) { p = (DWORD)pghi + offset; if (!ReadGNode32(p, &he->gnode)) { return FALSE; } else { if (FindMethod == FHE_FIND_ANY) { WORD sel = he->Selector; if (((sel|1)==((WORD)he->gnode.pga_handle|1)) || ((sel|1)==((WORD)he->gnode.pga_owner|1)) || (sel==offset)) { he->NextEntry = he->gnode.pga_next; GetHeapOwnerInfo(he); return TRUE; } } else if (FindMethod == FHE_FIND_MOD_ONLY) { GetHeapOwnerInfo(he); if (!_stricmp(he->OwnerName, he->ModuleArg)) { he->NextEntry = he->gnode.pga_next; return TRUE; } } else { if ((he->Selector|1)==((WORD)he->gnode.pga_handle|1)) { he->NextEntry = he->gnode.pga_next; GetHeapOwnerInfo(he); return TRUE; } } } count++; if (offset == he->gnode.pga_next) { break; } offset = he->gnode.pga_next; he->CurrentEntry = offset; } return FALSE; } VOID chkheap( CMD_ARGLIST ) { CMD_INIT(); if (CheckGlobalHeap(TRUE)) { PRINTF("Heap checks OK\n"); } } //************************************************************* // dumpgheap xxx // where xxx is the 16-bit protect mode selector of the // Kernel global heap info. // //************************************************************* VOID dgh( CMD_ARGLIST ) { HEAPENTRY he = {0}; SELECTORINFO si; ULONG TotalAllocated = 0; ULONG TotalFree = 0; ULONG CountPrinted = 0; CMD_INIT(); if (GetNextToken()) { he.Selector = (WORD) EXPRESSION( lpArgumentString ); } PRINTF("Arena Base Limit Hnd Own Fl Lk Module Type Resid"); PRINTF("\n"); PRINTF("===== ======== ======== ==== ==== == == ======== ==== ====="); PRINTF("\n"); while (FindHeapEntry(&he, FHE_FIND_ANY, FHE_FIND_VERBOSE)) { PRINTF("%.5x", he.CurrentEntry); PRINTF(" %.8x", he.gnode.pga_address); PRINTF(" %.8X", he.gnode.pga_size); PRINTF(" %.4X", he.gnode.pga_handle); PRINTF(" %.4X", he.gnode.pga_owner); PRINTF(" %.2X", he.gnode.pga_flags); PRINTF(" %.2X", he.gnode.pga_count); PRINTF(" %-8.8s", he.OwnerName); GetInfoFromSelector((WORD)(he.gnode.pga_handle | 1), PROT_MODE, &si); PRINTF(" %s", si.bCode ? "Code" : "Data"); if (he.SegmentNumber != -1) { PRINTF(" %d", he.SegmentNumber+1); } PRINTF("\n"); if (!he.gnode.pga_owner) { TotalFree += he.gnode.pga_size; } else { TotalAllocated += he.gnode.pga_size; } CountPrinted++; } if (CountPrinted > 1) { PRINTF("\n Allocated = %dK, Free = %dK\n", TotalAllocated/1024, TotalFree/1024); } } VOID UpdateLockCount( int count ) { HEAPENTRY he = {0}; BYTE LockCount; if (GetNextToken()) { he.Selector = (WORD) EXPRESSION( lpArgumentString ); } else { PRINTF("Please enter a selector or handle\n"); return; } if (FindHeapEntry(&he, FHE_FIND_SEL_ONLY, FHE_FIND_VERBOSE)) { if (READMEM((LPVOID)(GetHeapBase()+he.CurrentEntry+0x14), &LockCount, 1)) { LockCount = (BYTE)((int) LockCount + count); WRITEMEM((LPVOID)(GetHeapBase()+he.CurrentEntry+0x14), &LockCount, 1); PRINTF("Lock count for %.4X is now %d\n", he.Selector, LockCount); } else { PRINTF("<can't read memory at that location>\n"); } } else { PRINTF("Can't find selector %4X in WOW heap\n", he.Selector); } } VOID glock( CMD_ARGLIST ) { CMD_INIT(); UpdateLockCount(1); } VOID gunlock( CMD_ARGLIST ) { CMD_INIT(); UpdateLockCount(-1); }
<filename>lib/my/my_str_isnum.c<gh_stars>1-10 /* ** EPITECH PROJECT, 2020 ** my_str_isnum ** File description: ** task13 */ int my_strlen(char const *str); int my_str_isnum(char const *str) { int nb = my_strlen(str); int i = 0; for (; i <= nb && str[i] >= '0' && str[i] <= '9'; i++); if (i == nb || nb == 0) return (1); else return (0); }
<gh_stars>1-10 /** * Project AnimationProgramming * @author <NAME> * @version 1.0 */ #pragma once #ifndef _EVENT_H #define _EVENT_H #include <functional> namespace AnimationProgramming::Tools { /** * A simple event that contains a vector of function callbacks. These functions will be called on invoke */ template<class... ArgTypes> class Event final { public: /** * Simple shortcut for a generic function without return value */ typedef std::function<void(ArgTypes...)> Callback; /** * Unordered map of [callbackID, callback] */ typedef std::unordered_map<uint64_t, Callback> CallbackMap; /** * The ID of a listener (Registered callback). * This value is needed to remove a listener from an event */ typedef uint64_t ListenerID; /** * Add a function callback to this event * @param p_call */ ListenerID AddListener(Callback p_callback) { uint64_t listenerID = m_currentHashCode; m_callbacks.emplace(m_currentHashCode++, p_callback); return listenerID; } /** * Remove a function callback to this event using a Listener (Created when calling AddListener) * @param p_listener */ bool RemoveListener(const ListenerID& p_listenerID) { return m_callbacks.erase(p_listenerID) != 0; } /** * Remove every listeners to this event */ void RemoveAllListeners() { m_callbacks.clear(); } /** * Return the number of callback registered */ uint64_t GetListenerCount() { return m_callbacks.size(); } /** * Call every callbacks attached to this event * @param p_args (Variadic) */ void Invoke(ArgTypes... p_args) { for (auto const&[key, val] : m_callbacks) val(p_args...); } private: CallbackMap m_callbacks; uint64_t m_currentHashCode = 0; }; } #endif // _EVENT_H
/** * @brief The function returns the arc sine of x within the range of -π/2 to π/2 radians. * * @param val [in] The val value between -1 and 1, the arc sine of which is to be calculated. * @return double Arc sine of the val number in radians within the range of -π/2 to π/2 radians. If val is less than -1 or more than 1, the function returns NaN (indeterminate value). * * @note Instead of the MathArcsin() function you can use asin(). */ double MathArcsin( double val // -1<value<1 ); /** * @brief The function returns the arc sine of x within the range of -π/2 to π/2 radians. * * @param val [in] The val value between -1 and 1, the arc sine of which is to be calculated. * @return double Arc sine of the val number in radians within the range of -π/2 to π/2 radians. If val is less than -1 or more than 1, the function returns NaN (indeterminate value). * * @note Instead of the MathArcsin() function you can use asin(). */ double asin( double val // -1<value<1 );
#include "vector.h" #include "SPTK.h" #ifndef SPTK_PITCH #define SPTK_PITCH vector sptk_pitch(vector data, PITCH_SETTINGS * settings); vector sptk_pitch_spec(vector data, PITCH_SETTINGS * settings, int count); #endif
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Rubber Band Library An audio time-stretching and pitch-shifting library. Copyright 2007-2014 Particular Programs Ltd. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. See the file COPYING included with this distribution for more information. Alternatively, if you have a valid commercial licence for the Rubber Band Library obtained by agreement with the copyright holders, you may redistribute and/or modify it under the terms described in that licence. If you wish to distribute code using the Rubber Band Library under terms other than those of the GNU General Public License, you must obtain a valid commercial licence before doing so. */ #ifndef _RUBBERBAND_VECTOR_OPS_H_ #define _RUBBERBAND_VECTOR_OPS_H_ #ifdef HAVE_IPP #ifndef _MSC_VER #include <inttypes.h> #endif #include <ipps.h> #include <ippac.h> #endif #ifdef HAVE_VDSP #include <Accelerate/Accelerate.h> #endif #include "pommier/sse_mathfun.h" extern "C" { # include <x86intrin.h> } #include <string.h> #include <cstring> #include <cmath> #include "sysutils.h" #include <memory> #include <algorithm> #include <utility> namespace Rubbers { // Note that all functions with a "target" vector have their arguments // in the same order as memcpy and friends, i.e. target vector first. // This is the reverse order from the IPP functions. // The ideal here is to write the basic loops in such a way as to be // auto-vectorizable by a sensible compiler (definitely gcc-4.3 on // Linux, ideally also gcc-4.0 on OS/X). template<typename T> constexpr T roundup(T x ){ x--; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>> ( sizeof(T)>1 ? 8 : 0 ); x|=x>> ( sizeof(T)>2 ? 16: 0 ); x|=x>> ( sizeof(T)>4 ? 32: 0 ); return x+1; } template<typename T> inline void v_zero(T *const ptr, const int count) {memset(ptr, 0, count*sizeof(T));} template<typename T> inline void v_zero_channels(T *const *const ptr, const int channels, const int count) {for (int c = 0; c < channels; ++c) {v_zero(ptr[c], count);}} template<typename T> inline void v_set(T *const ptr, const T value, const int count){for (int i = 0; i < count; ++i) {ptr[i] = value;}} template<typename T> inline void v_copy(T *const dst, const T *const src, const int count) {memmove(dst, src, count*sizeof(T));} template<typename T> inline void v_copy_channels(T *const *const dst, const T *const *const src, const int channels, const int count){for (int c = 0; c < channels; ++c) {v_copy(dst[c], src[c], count);}} // src and dst alias by definition, so not ed template<typename T> inline void v_move(T *const dst, const T *const src, const int count) {memmove(dst, src, count * sizeof(T));} template<typename T, typename U> inline void v_convert(U *const dst, const T *const src, const int count) {std::copy_n(src,count,dst);} template<typename T> inline void v_convert(T *const dst, const T * const src, const int count){ memmove(dst, src, count*sizeof(T)); } template<typename T, typename U> inline void v_convert_channels(U *const *const dst, const T *const *const src, const int channels, const int count) { for (int c = 0; c < channels; ++c) {v_convert(dst[c], src[c], count);} } template<typename T> inline void v_add(T *const dst, const T *const src, const int count) { auto _src=(const T*const )__builtin_assume_aligned(src,16); auto _dst =(T*const )__builtin_assume_aligned(dst,16); for (int i = 0; i < count; ++i) { _dst[i] += _src[i]; } } template<typename T> inline void v_add(T *const dst, const T value, const int count) { auto _dst = (T *const )__builtin_assume_aligned(dst,16); for (int i = 0; i < count; ++i) {dst[i] += value;} } template<typename T> inline void v_add_channels(T *const *const dst, const T *const *const src, const int channels, const int count) { for (int c = 0; c < channels; ++c) {v_add(dst[c], src[c], count);} } template<typename T, typename G> inline void v_add_with_gain(T *const dst, const T *const src, const G gain, const int count) { auto _dst = (__typeof__(dst))__builtin_assume_aligned(dst,16); auto _src = (__typeof__(src))__builtin_assume_aligned(src,16); for (int i = 0; i < count; ++i) {_dst[i] += _src[i] * gain;} } template<typename T, typename G> inline void v_add_channels_with_gain(T *const *const dst, const T *const *const src, const G gain, const int channels, const int count) { for (int c = 0; c < channels; ++c) {v_add_with_gain(dst[c], src[c], gain, count);} } template<typename T> inline void v_subtract(T *const dst, const T *const src, const int count) { int i = 0; while(((intptr_t)(dst+i))&15){dst[i] -=src[i];i++;} auto _dst = (__typeof__(dst))__builtin_assume_aligned(dst,16); auto _src = (__typeof__(src))__builtin_assume_aligned(src,16); for (i = 0; i < count; ++i) {_dst[i] -= _src[i];} } template<typename T, typename G> inline void v_scale(T *const dst, const G gain, const int count) { int i = 0; while(((intptr_t)(dst+i))&15){dst[i] =expf(dst[i]);i++;} auto srcdst = (__typeof__(dst))__builtin_assume_aligned(dst+i,16); for (i = 0; i < count; ++i) {srcdst[i] *= gain;} while(i<count){dst[i] = expf(dst[i]);} } template<typename T> inline void v_multiply(T *const dst, const T *const src, const int count) { auto _src = (__typeof__(src))__builtin_assume_aligned(src,16); auto _dst = (__typeof__(dst))__builtin_assume_aligned(dst,16); for (int i = 0; i < count; ++i) {_dst[i] *= _src[i];} } template<typename T> inline void v_multiply(T *const dst, const T *const src1, const T *const src2, const int count) { auto _src1 = (__typeof__(src1))__builtin_assume_aligned(src1,16); auto _src2 = (__typeof__(src2))__builtin_assume_aligned(src2,16); auto _dst = (__typeof__(dst))__builtin_assume_aligned(dst,16); for (int i = 0; i < count; ++i) {_dst[i] = _src1[i] * _src2[i];} } template<typename T> inline void v_divide( T *const dst , const T *const src , const int count) { auto _src = (__typeof__(src))__builtin_assume_aligned(src,16); auto _dst = (__typeof__(dst))__builtin_assume_aligned(dst,16); for (int i = 0; i < count; ++i) {_dst[i] /= _src[i];} } template<> inline void v_divide( float*const dst , const float *const src , const int count) { int i=0; auto _src = (__typeof__(src))__builtin_assume_aligned(src,16); auto _dst = (__typeof__(dst))__builtin_assume_aligned(dst,16); while(((intptr_t)(_dst+i))&15){_dst[i] /= (_src[i]);i++;} for(; i+3<count; i+=4){ *(v4sf*)(_dst+i)= _approx_div_ps( *(v4sf*)(_dst+i),*(v4sf*)(_src+i)); } for(;i<count;i++) _dst[i]/=_src[i]; } template<typename T> inline void v_multiply_and_add(T *const dst, const T *const src1, const T *const src2, const int count) { auto _src1 = (__typeof__(src1))__builtin_assume_aligned(src1,16); auto _src2 = (__typeof__(src2))__builtin_assume_aligned(src2,16); auto _dst = (__typeof__(dst))__builtin_assume_aligned(dst,16); for (int i = 0; i < count; ++i) {_dst[i] += _src1[i] * _src2[i];} } template<typename T> inline T v_sum(const T *const src, const int count) { T result = T(); for (int i = 0; i < count; ++i) {result += src[i];} return result; } template<> inline float v_sum(const float *const src, const int count) { v4sf accum = _mm_setzero_ps(); for(int i = 0; i+3<count; i+=4){accum = _mm_add_ps(accum,*(v4sf*)(src+i));} accum = _mm_hadd_ps(accum,accum); accum = _mm_hadd_ps(accum,accum); return accum[0]; } template<typename T> inline void v_log(T *const dst, const int count) { for (int i = 0; i < count; ++i) {dst[i] = log(dst[i]);} } template<typename T> inline void v_exp(T *const dst,const int count){for (int i = 0; i < count; ++i) {dst[i] = exp(dst[i]);}} template<> inline void v_exp(float *const dst, const int count) { int i=0; while(((intptr_t)(dst+i))&15){dst[i] = expf(dst[i]);i++;} for(; i + 4 < count; i+=4 ){ *(v4sf*)(dst+i)=log_ps(*(v4sf*)(dst+i)); } while(i<count){dst[i] = expf(dst[i]);} } template<> inline void v_log(float *const dst, const int count) { int i=0; while(((intptr_t)(dst+i))&15){dst[i] = logf(dst[i]);i++;} for(; i + 4 < count; i+=4 ){ *(v4sf*)(dst+i) = log_ps(*(v4sf*)(dst+i)); } while(i<count){dst[i] = logf(dst[i]);i++;} } #if defined HAVE_IPP template<> inline void v_exp(float *const dst, const int count) { ippsExp_32f_I(dst, count); } template<> inline void v_exp(double *const dst, const int count) { ippsExp_64f_I(dst, count); } #elif defined HAVE_VDSP // no in-place vForce functions for these -- can we use the // out-of-place functions with equal input and output vectors? can we // use an out-of-place one with temporary buffer and still be faster // than doing it any other way? template<> inline void v_exp(float *const dst, const int count) { float tmp[count]; vvexpf(tmp, dst, &count); v_copy(dst, tmp, count); } template<> inline void v_exp(double *const dst, const int count) { double tmp[count]; vvexp(tmp, dst, &count); v_copy(dst, tmp, count); } #endif template<typename T> inline void v_sqrt(T *const dst, const int count) { for (int i = 0; i < count; ++i) {dst[i] = sqrt(dst[i]);} } //#if defined(x86_64) || defined(AMD64) || defined(__x86_64__) || defined(__AMD64__) template<> inline void v_sqrt(float*const srcdst, const int count){ int i=0; for(i=0; i+3<count;i+=4){ *(v4sf*)(srcdst+i) = _approx_sqrt_ps (*(v4sf*)(srcdst+i)); } while(i<count){srcdst[i]=sqrtf(srcdst[i]);} } //#endif #if defined HAVE_IPP template<> inline void v_sqrt(float *const dst, const int count) { ippsSqrt_32f_I(dst, count); } template<> inline void v_sqrt(double *const dst, const int count) { ippsSqrt_64f_I(dst, count); } #elif defined HAVE_VDSP // no in-place vForce functions for these -- can we use the // out-of-place functions with equal input and output vectors? can we // use an out-of-place one with temporary buffer and still be faster // than doing it any other way? template<> inline void v_sqrt(float *const dst, const int count) { float tmp[count]; vvsqrtf(tmp, dst, &count); v_copy(dst, tmp, count); } template<> inline void v_sqrt(double *const dst, const int count) { double tmp[count]; vvsqrt(tmp, dst, &count); v_copy(dst, tmp, count); } #endif template<typename T> inline void v_square(T *const dst, const int count) { for (int i = 0; i < count; ++i) {dst[i] = dst[i] * dst[i];} } #if defined HAVE_IPP template<> inline void v_square(float *const dst, const int count) { ippsSqr_32f_I(dst, count); } template<> inline void v_square(double *const dst, const int count) { ippsSqr_64f_I(dst, count); } #endif template<typename T> inline void v_abs(T *const dst, const int count) { for (int i = 0; i < count; ++i) {dst[i] = fabs(dst[i]);} } template<> inline void v_abs(float *const dst, const int count) { int i=0; while(((intptr_t)(dst+i))&15){dst[i] = std::abs(dst[i]);i++;} for(; i + 4 < count; i+=4 ){ v4sf x = *(v4sf*)(dst+i); *(v4sf*)(dst+i) = fabs_ps(x); } while(i<count){dst[i] = fabs(dst[i]);i++;} } #if defined HAVE_IPP template<> inline void v_abs(float *const dst, const int count) { ippsAbs_32f_I(dst, count); } template<> inline void v_abs(double *const dst, const int count) { ippsAbs_64f_I(dst, count); } #elif defined HAVE_VDSP template<> inline void v_abs(float *const dst, const int count) { float tmp[count]; #if (defined(MACOSX_DEPLOYMENT_TARGET) && MACOSX_DEPLOYMENT_TARGET <= 1070 && MAC_OS_X_VERSION_MIN_REQUIRED <= 1070) vvfabf(tmp, dst, &count); #else vvfabsf(tmp, dst, &count); #endif v_copy(dst, tmp, count); } #endif template<typename T> inline void v_interleave(T *const dst, const T *const *const src, const int channels, const int count){ int idx = 0; switch (channels) { case 2: // common case, may be vectorized by compiler if hardcoded for (int i = 0; i < count; ++i) { for (int j = 0; j < 2; ++j) {dst[idx++] = src[j][i];} } return; case 1: v_copy(dst, src[0], count); return; default: for (int i = 0; i < count; ++i) { for (int j = 0; j < channels; ++j) {dst[idx++] = src[j][i];} } } } #if defined HAVE_IPP template<> inline void v_interleave(float *const dst, const float *const *const src, const int channels, const int count) { ippsInterleave_32f((const Ipp32f **)src, channels, count, dst); } // IPP does not (currently?) provide double-precision interleave #endif template<typename T> inline void v_deinterleave(T *const *const dst, const T *const src, const int channels, const int count) { int idx = 0; switch (channels) { case 2: // common case, may be vectorized by compiler if hardcoded for (int i = 0; i < count; ++i) {for (int j = 0; j < 2; ++j) {dst[j][i] = src[idx++];}} return; case 1: v_copy(dst[0], src, count); return; default: for (int i = 0; i < count; ++i) { for (int j = 0; j < channels; ++j) { dst[j][i] = src[idx++]; } } } } #if defined HAVE_IPP template<> inline void v_deinterleave(float *const *const dst, const float *const src, const int channels, const int count){ippsDeinterleave_32f((const Ipp32f *)src, channels, count, (Ipp32f **)dst);} // IPP does not (currently?) provide double-precision deinterleave #endif template<typename T> inline void v_fftshift(T *const ptr,const int count){ const int hs = count/2; for (int i = 0; i < hs; ++i) { T t = ptr[i]; ptr[i] = ptr[i + hs]; ptr[i + hs] = t; } } template<typename T> inline T v_mean(const T *const ptr, const int count) { T t = T(0); for (int i = 0; i < count; ++i) {t += ptr[i];} t /= T(count); return t; } template<typename T> inline T v_mean_channels(const T *const *const ptr, const int channels, const int count){ T t = T(0); for (int c = 0; c < channels; ++c) {t += v_mean(ptr[c], count);} t /= T(channels); return t; } } #endif
#pragma once #include "enum.h" // DEF_BITFIELD struct coord_def; enum feature_property_type { FPROP_NONE = 0, FPROP_SANCTUARY_1 = (1 << 0), FPROP_SANCTUARY_2 = (1 << 2), FPROP_BLOODY = (1 << 3), FPROP_UNUSED_2 = (1 << 4), // Used to be 'vault'. FPROP_HIGHLIGHT = (1 << 5), // Highlight on the X map for debugging. // NOTE: Bloody floor and sanctuary are exclusive. FPROP_UNUSED = (1 << 6), // used to be force_exclude FPROP_NO_CLOUD_GEN = (1 << 7), FPROP_NO_TELE_INTO = (1 << 8), FPROP_UNUSED_3 = (1 << 9), // used to be no_ctele_into // Squares that the tide should not affect. FPROP_NO_TIDE = (1 << 10), FPROP_NO_SUBMERGE = (1 << 11), FPROP_MOLD = (1 << 12), FPROP_GLOW_MOLD = (1 << 13), // Immune to spawning jellies and off-level eating. FPROP_NO_JIYVA = (1 << 14), // Permanent, unlike map memory. FPROP_SEEN_OR_NOEXP = (1 << 15), FPROP_BLOOD_WEST = (1 << 16), FPROP_BLOOD_NORTH = (1 << 17), FPROP_BLOOD_EAST = FPROP_BLOOD_WEST | FPROP_BLOOD_NORTH, FPROP_OLD_BLOOD = (1 << 18), }; DEF_BITFIELD(terrain_property_t, feature_property_type); bool is_sanctuary(const coord_def& p); bool is_bloodcovered(const coord_def& p); bool is_tide_immune(const coord_def &p); bool is_moldy(const coord_def & p); bool glowing_mold(const coord_def & p); void remove_mold(const coord_def & p); feature_property_type str_to_fprop(const string &str); char blood_rotation(const coord_def & p);
/* See LICENSE file in root folder */ #ifndef ___EVENT_TARGET_H___ #define ___EVENT_TARGET_H___ #include "Module_Sequences.h" #include "Module_Gui.h" #include "Module_Script.h" namespace Elypse { namespace Sequences { template< typename T > struct EventTargetEnum; template<> struct EventTargetEnum< Ogre::SceneNode > { static EventTargetType const value = EventTargetType::SceneNode; }; template<> struct EventTargetEnum< Script::ScriptNode > { static EventTargetType const value = EventTargetType::ScriptNode; }; template<> struct EventTargetEnum< Gui::EMOverlayGroup > { static EventTargetType const value = EventTargetType::OverlayGroup; }; template<> struct EventTargetEnum< Gui::EMOverlay > { static EventTargetType const value = EventTargetType::Overlay; }; template<> struct EventTargetEnum< Ogre::OverlayElement > { static EventTargetType const value = EventTargetType::OverlayElement; }; template<> struct EventTargetEnum< Sequence > { static EventTargetType const value = EventTargetType::Sequence; }; template< EventTargetType Type > struct EventTargetTyper; template<> struct EventTargetTyper< EventTargetType::SceneNode > { using type = Ogre::SceneNode; }; template<> struct EventTargetTyper< EventTargetType::ScriptNode > { using type = Script::ScriptNode; }; template<> struct EventTargetTyper< EventTargetType::OverlayGroup > { using type = Gui::EMOverlayGroup; }; template<> struct EventTargetTyper< EventTargetType::Overlay > { using type = Gui::EMOverlay; }; template<> struct EventTargetTyper< EventTargetType::OverlayElement > { using type = Ogre::OverlayElement; }; template<> struct EventTargetTyper< EventTargetType::Sequence > { using type = Sequence; }; class EventTargetBase { public: EventTargetBase( EventTargetType p_type ) : m_type{ p_type } { } ~EventTargetBase() { } template< typename T > T * GetAs()const { genlib_assert( m_type == EventTargetEnum< T >::value ); return reinterpret_cast< T * >( DoGet() ); } private: virtual void * DoGet()const = 0; protected: EventTargetType const m_type; }; template< EventTargetType Type > class EventTarget : public EventTargetBase { public: using TargetType = typename EventTargetTyper< Type >::type; public: EventTarget( TargetType * p_target ) : EventTargetBase{ Type } , m_target{ p_target } { } ~EventTarget() { } private: virtual void * DoGet()const { return m_target; } private: TargetType * m_target; }; template< typename T > std::unique_ptr< EventTarget< EventTargetEnum< T >::value > > make_target( T * p_target ) { return std::make_unique< EventTarget< EventTargetEnum< T >::value > >( p_target ); } } } #endif
extern void alku_tw_opengraph(); extern void tw_closegraph(); extern void alku_tw_putpixel(int x, int y, int color); extern int alku_tw_getpixel(int x, int y); extern void alku_tw_setpalette(void far *pal); extern void tw_setpalarea(void far *pal,int start,int cnt); extern void tw_setrgbpalette(int pal, int r, int g, int b); extern void tw_setstart(int start); extern void tw_pictovmem(void far *pic, int to, int len); extern void tw_crlscr(); extern int far scr_seg;
#pragma once #include <vector> #include <memory> #include <math/geometry/2d/shape/ConvexShape2D.h> #include <math/algebra/point/Point2.h> namespace urchin { template<class T> class ConvexHullShape2D : public ConvexShape2D { public: ConvexHullShape2D() = default; explicit ConvexHullShape2D(const std::vector<Point2<T>>&); ~ConvexHullShape2D() override = default; static std::unique_ptr<ConvexHullShape2D<T>> createFromCcwConvexPoints(const std::vector<Point2<T>>&); const std::vector<Point2<T>>& getPoints() const; Point2<T> getSupportPoint(const Vector2<T>&) const; T area() const; std::unique_ptr<ConvexHullShape2D<T>> resize(T) const; private: std::vector<Point2<T>> convexHullPoints; }; }
<gh_stars>1-10 #include <stdlib.h> typedef union { void* buffer; uint32_t number; } hash_t; hash_t hash_allocate (uint32_t seed); int hash_block_size(); void hash_update(hash_t*, void* buffer, int length); void hash_remainder(hash_t*, void* buffer, int length); hash_t hash_hash(void* buffer, int length, uint32_t seed); void hash_free (hash_t hash); char needed[];
<gh_stars>0 #ifndef __TIO_LRAUTOMATON #define __TIO_LRAUTOMATON #include<string> #include<vector> #include<memory> #include<map> #include<set> #include<stack> #include"symbol.h" namespace tio { struct atm_state { std::vector<lritem> head; std::vector<lritem> closure; }; class LRAutomaton { private: std::vector<atm_state> states; std::shared_ptr<std::vector<lritem>> items; int find_itemhd_in_state(const std::vector<lritem>& it); void cal_first(const symbol& smb); std::map<symbol, std::set<symbol>> first_set; public: std::map<std::pair<int, symbol>, int> Goto; std::map<std::pair<int, symbol>, std::pair<char, int>> Action; LRAutomaton(); void build_automaton(); void set_items(std::shared_ptr<std::vector<lritem>> itm); }; } #endif
#include "MITM.h" #include "common.h" #include "./src/interaction/mitm_ctrl.h" char ip_s[MAX_IPV4_LEN]; char mac_s[MAX_MAC_LEN]; int debug_level; bool manual=false; void usage(){ printf("MITM usage:\n" "MITM -i<interface name> -t<device_type> [-d<debug level>]...\n" " -h = show this help\n" " -d <level> = increase debugging verbosity\n" " -i = interface name\n" " -m = manual set interface information\n" " -f <filter> set packet filter\n" " -t <device_type(wireless/ethernet)> set the device type\n"); } static void mitm_eloop_terminate(int sig, void *signal_ctx) { eloop_terminate(); } int main(int argc,char* argv[]){ struct MITM *MITM; bool filter_set = false; int c ,exitcode; char user_filter[100]; struct packet_handler *handler; struct mitm_ctrl *ctrl; MITM = malloc(sizeof(struct MITM)); if (!MITM) return -ENOMEM; for(;;){ c=getopt(argc, argv,"i:hd:mf:w:t:p:"); if(c < 0)break; switch(c){ case 'd': debug_level = atoi(optarg); break; case 'h': usage(); return 0; break; case 'i': MITM->usr_dev = optarg; break; case 'm': manual=true; break; case 'f': strcpy(user_filter,optarg); filter_set = true; break; case 'w': MITM->pcapng_path = fopen(optarg, "w+"); break; case 't':; char *tmp; tmp = strdup(optarg); if (!strcmp("wireless", tmp)) { MITM->dev_type = wireless; } else if (!strcmp("ethernet", tmp)) { MITM->dev_type = ethernet; } else { printf("only supper wireless/ethernet type device\n"); usage(); return -1; } free(tmp); break; case 'p': MITM->dict_path = strdup(optarg); break; default: usage(); return 0; } } #if 0 create_monitor_interface: if(MITM->dev_type == wireless) { printf( "type (yes/no) to create a monitor type interface or not\n" "also you can key the device name" ", if you have already created a monitor mode interface:\n"); char create_interface[10]; if (scanf("%s", create_interface) == EOF) { log_printf(MSG_ERROR, "Invaild interface name."); return -1; } if (!strcmp(create_interface, "yes")) { MITM->monitor_dev = "mon0"; log_printf(MSG_DEBUG, "creating a monitor interface base on %s", MITM->usr_dev); char* interface_add_command[6] = {"dev", "interface", "add", MITM->monitor_dev,"type", "monitor"}; if(!nl80211_init()) { if(!interface_handler(interface_add_command)) { if(if_up(MITM->monitor_dev) < 0) return -1; log_printf(MSG_DEBUG, "hang up monitor interface %s successful", MITM->monitor_dev); } } } else if (!strcmp(create_interface, "no")) { log_printf(MSG_DEBUG, "seem you are a rebellious guy em...."); return -1; } else { if(!getifinfo(&MITM->monitor_buf, MITM->errbuf)) { if(!checkdevice(MITM->monitor_buf, create_interface)) { log_printf(MSG_INFO, "can't find the device %s," "please check again!\n",create_interface); goto create_monitor_interface; } else { //strcpy(monitor_dev, create_interface); MITM->monitor_dev = create_interface; } } } } #endif eloop_init(); if (MITM_init(MITM) || !MITM) { log_printf(MSG_ERROR, "initialize global MITM failed"); return -1; } if (!MITM->l2_packet) { log_printf(MSG_ERROR, "l2_packet_data alloc failed"); goto fail; } ctrl = mitm_server_open(MITM, MITM_CTRL_PATH); if (!ctrl) { log_printf(MSG_ERROR, "control server open failed"); goto fail; }else { log_printf(MSG_DEBUG, "control server is ready"); } eloop_run(); fail: MITM_deinit(MITM); return -1; }
/** * sabotage.c * * This work belongs to the Public Domain. Everyone is free to use, modify, * republish, sell or give away this work without prior consent from anybody. * * This software is provided on an "AS IS" basis, without warranty of any kind. * Use at your own risk! Under no circumstances shall the author(s) or * contributor(s) be liable for damages resulting directly or indirectly from * the use or non-use of this documentation. */ // BeginNoSabotage #include <ctype.h> #include <errno.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <sysexits.h> #include <unistd.h> /* Sabotage target */ struct sabot { char const * file; // file, such as "src/main.c", or NULL for any char const * func; // function, such as "main", or NULL for any double prob; // probablity range [0.0, 1.0] unsigned lnoc; // number of lines, or 0 for any unsigned lnov[16]; // line numbers unsigned cnt; // # of matches unsigned hit; // # of failures }; /* Token types */ enum tokenkind { TOK_ERR = -1, TOK_LIT = 0, // function, file, or line number TOK_END = ';', // the end of a target (also '\0') TOK_PERC = '%', TOK_PAR = '(', // actually "()" TOK_COLON = ':', TOK_COMMA = ',', }; /* A token */ struct token { char const * s; // start of token text char const * e; // char immediately following token text enum tokenkind k; }; /* List of sabotage targets */ static struct sabot sabotv[128]; static unsigned sabotc = 0; /* Seed for the random number generator (controlled by SABOTAGE_SEED env) */ static unsigned int seed = 0; /** Error number (controlled by SABOTAGE_ERRNO env)*/ static int eno = ENOMEM; /* Buffer for storing file and function names */ static char strbuf[1024]; static char * strptr = strbuf; /** * Skip whitespace. */ static inline const char * skip(char const * s) { while (*s && isspace(*s)) s++; return s; } /** * Consume a token of the target specification. */ static enum tokenkind next(char const ** const pp, struct token * const tok) { char const sep[] = ";%:,()"; enum tokenkind k; char const * s; char const * e; s = skip(*pp); e = s; switch (*s) { case '\0': k = TOK_END; break; case ';': case '%': case ':': case ',': k = *s; e = s + 1; break; case '(': if (s[1] != ')') k = TOK_ERR; else { k = *s; e = s + 2; } break; default: if (!isgraph(*s) || strchr(sep, *s)) k = TOK_ERR; else { k = TOK_LIT; for (; *e && isgraph(*e) && !strchr(sep, *e); e++) continue; } } if (tok) *tok = k == TOK_ERR ? (struct token) { s, s + 1, k } : (struct token) { s, e, k }; *pp = e; return k; } static int setfile(struct sabot * const t, struct token const * const tok) { size_t const len = tok->e - tok->s; size_t const need = len + 1; // len + '\0' size_t const remaining = strbuf + sizeof(strbuf) - strptr; if (need > remaining) return ENOSPC; t->file = strptr; memcpy(strptr, tok->s, len); strptr += len; *strptr++ = '\0'; return 0; } static int setfunc(struct sabot * const t, struct token const * const tok) { size_t const len = tok->e - tok->s; size_t const need = len + 1; // len + '\0' size_t const remaining = strbuf + sizeof(strbuf) - strptr; if (need > remaining) return ENOSPC; t->func = strptr; memcpy(strptr, tok->s, len); strptr += len; *strptr++ = '\0'; return 0; } static int setprob(struct sabot * const t, struct token const * const tok) { char buf[64]; size_t const len = tok->e - tok->s; if (!len || len >= sizeof(buf)) return EINVAL; memcpy(buf, tok->s, len); buf[len] = '\0'; char * endptr = NULL; long long const ll = strtol(buf, &endptr, 10); if (*endptr || ll < 0 || ll > 100) return EINVAL; t->prob = (double) ll / 100.0; return 0; } static int setline(struct sabot * const t, struct token const * const tok) { char buf[64]; if (t->lnoc >= sizeof(t->lnov) / sizeof(t->lnov[0])) return ENOSPC; size_t const len = tok->e - tok->s; if (!len || len >= sizeof(buf)) return EINVAL; memcpy(buf, tok->s, len); buf[len] = '\0'; char * endptr = NULL; long long const ll = strtol(buf, &endptr, 10); if (*endptr || ll <= 0 || ll > INT_MAX) return EINVAL; t->lnov[t->lnoc++] = ll; return 0; } /** * A shortcut for checking the return value of a function. used by * sabot_parse_one_target(). */ #define CHECK(f, msg) \ do { \ switch (f) { \ case 0: \ break; \ case ENOSPC: \ errmsg = "too many entries"; \ goto fail_syntax_err; \ default: \ errmsg = (msg); \ goto fail_syntax_err; \ } \ } while (0) /** * Expect a specific token next. Used by sabot_parse_one_target(). */ #define EXPECT(pp, tokknd, tokptr) \ do { \ if (next((pp), (tokptr)) != (tokknd)) \ goto fail_syntax_err; \ } while (0) /* Frequent error messages */ #define BAD_FILE_ERRMSG "invalid file name" #define BAD_FUNC_ERRMSG "invalid function name" #define BAD_LINE_ERRMSG "invalid line number" #define BAD_PROB_ERRMSG "invalid probability value" /** * Parse one sabotage target. */ static int sabot_parse_one_target( char const * const s, // the SABOTAGE string char const ** const pp, // current parse location in SABOTAGE struct sabot * const t ) { // Grammar: // // TARGET := [PROB] WHERE [ ";" TARGET ] // // PROB := literal "%" // // WHERE := FILE | FUNC // // FILE := literal [ ":" LINES | FUNC ] // // LINES := literal [ "," LINES ] // // FUNC := literal "()" // char const * errptr; // points to error location in SABOTAGE string char const * errmsg; // error message struct token tok; memset(t, 0, sizeof(*t)); t->prob = 1.0; // probability defaults to 100% /* To keep the code cleaner, we make use of a couple of macros: CHECK() * and EXPECT(). These expand to a "goto fail_syntax_err" on error. */ /* probability, file, or function */ errmsg = "expected probabilty, file name, or function"; errptr = *pp; EXPECT(pp, TOK_LIT, &tok); switch (next(pp, NULL)) { // \0 | ; | : | % | () case TOK_END: // file CHECK(setfile(t, &tok), BAD_FILE_ERRMSG); return 0; case TOK_COLON: // file: CHECK(setfile(t, &tok), BAD_FILE_ERRMSG); goto func_or_line; case TOK_PAR: // func() CHECK(setfunc(t, &tok), BAD_FUNC_ERRMSG); goto eol; case TOK_PERC: // prob% ... CHECK(setprob(t, &tok), BAD_PROB_ERRMSG); break; default: goto fail_syntax_err; } /* file name, a function name, or the end of target */ errmsg = "expected file name or function"; errptr = *pp; switch (next(pp, &tok)) { case TOK_END: return 0; case TOK_LIT: break; default: goto fail_syntax_err; } switch (next(pp, NULL)) { // \0 | ; | () | : case TOK_END: CHECK(setfile(t, &tok), BAD_FILE_ERRMSG); return 0; case TOK_PAR: CHECK(setfunc(t, &tok), BAD_FUNC_ERRMSG); goto eol; case TOK_COLON: CHECK(setfile(t, &tok), BAD_FILE_ERRMSG); break; default: goto fail_syntax_err; } func_or_line: /* function name or line number */ errmsg = "expected function name or line number"; errptr = *pp; EXPECT(pp, TOK_LIT, &tok); switch (next(pp, NULL)) { case TOK_PAR: // func() CHECK(setfunc(t, &tok), BAD_FUNC_ERRMSG); goto eol; case TOK_END: // line CHECK(setline(t, &tok), BAD_LINE_ERRMSG); return 0; case TOK_COMMA: // line, line, ... CHECK(setline(t, &tok), BAD_LINE_ERRMSG); errmsg = "expected a line number"; L: errptr = *pp; EXPECT(pp, TOK_LIT, &tok); CHECK(setline(t, &tok), BAD_LINE_ERRMSG); switch (next(pp, NULL)) { case TOK_END: return 0; case TOK_COMMA: goto L; default: goto fail_syntax_err; } default: goto fail_syntax_err; } eol: errmsg = "expected `;'"; errptr = *pp; EXPECT(pp, TOK_END, NULL); return 0; fail_syntax_err:; int const l = skip(errptr) - s; fprintf(stderr, "sabotage: syntax error: \"%s\"\n", s); fprintf(stderr, "sabotage: syntax error: %*s^ %s\n", l, "", errmsg); return EINVAL; } /** * Parse all sabotage targets. */ static int sabot_parse_all_targets(char const * s) { char const * const s0 = s; size_t const max = sizeof(sabotv) / sizeof(sabotv[0]); struct sabot const * const T = sabotv + max; struct sabot * t = sabotv; int err; for (s = skip(s); *s && t < T; t++) if ((err = sabot_parse_one_target(s0, &s, t))) return err; if (*s) { fputs("sabotage: error: too many targets\n", stderr); return ENOSPC; } sabotc = t - sabotv; return 0; } static int sabot_parse_seed(char const * const s, unsigned * const seed) { char * endptr = NULL; long long const ll = strtoll(s, &endptr, 10); if (*endptr || ll < 0 || ll > UINT_MAX) return EINVAL; *seed = (unsigned) ll; return 0; } static int sabot_parse_errno(char const * const s, int * const err) { char * endptr = NULL; long long const ll = strtoll(s, &endptr, 10); if (*endptr || ll < INT_MIN || ll > INT_MAX) return EINVAL; *err = (int) ll; return 0; } /** * Initialization */ __attribute__ ((constructor)) void sabot_init(void) { char const * env = NULL; /* read targets */ if ((env = getenv("SABOTAGE")) == NULL) return; if (sabot_parse_all_targets(env)) _exit(64); if (!sabotc) return; /* seed the random number generator */ if ((env = getenv("SABOTAGE_SEED")) == NULL) { struct timeval tv; gettimeofday(&tv, NULL); seed = tv.tv_sec * 1000000 + tv.tv_usec; } else if (sabot_parse_seed(env, &seed)) { fprintf(stderr, "sabotage: bad SABOTAGE_SEED: \"%s\"\n", env); return; } /* read error number */ if ((env = getenv("SABOTAGE_ERRNO")) && sabot_parse_errno(env, &eno)) { fprintf(stderr, "sabotage: bad SABOTAGE_ERRNO: \"%s\"\n", env); return; } fprintf(stderr, " __ __ __ __ __ __ __ __ __ __ __ __ __ \n" "_\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_\n" "\\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/\n\n"); fprintf(stderr, "Process %d is being sabotaged:\n", (int) getpid()); fprintf(stderr, "\"%s\"\n\n", getenv("SABOTAGE")); fprintf(stderr, "Seed: %u\n", seed); fprintf(stderr, "Errno: %d\n", eno); fprintf(stderr, "\nTargets:\n"); struct sabot const * t = sabotv; for (unsigned i = 0; i < sabotc; i++, t++) { fprintf(stderr, " %3d%%", (int) (t->prob * 100.0)); if (t->file) fprintf(stderr, " %s", t->file); if (t->func) fprintf(stderr, " %s()", t->func); if (t->lnoc) for (unsigned j = 0; j < t->lnoc; j++) fprintf(stderr, "%s%u", j ? ", " : ": ", t->lnov[j]); fputc('\n', stderr); } fprintf(stderr, " __ __ __ __ __ __ __ __ __ __ __ __ __ \n" "_\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_ _\\/_\n" "\\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/ \\/\\/\n\n"); } /** * Do sabotage. */ int __sabotage( char const * const file, char const * const func, unsigned int const line ) { struct sabot * t = sabotv; for (unsigned i = 0; i < sabotc; i++, t++) { if (t->file && strcmp(file, t->file)) continue; if (t->func && strcmp(func, t->func)) continue; if (t->lnoc) { bool matched = false; for (unsigned j = 0; j < t->lnoc && !matched; j++) matched = line == t->lnov[j]; if (!matched) continue; } t->cnt++; if ( t->prob == 0.0 || ( t->prob != 1.0 && rand_r(&seed) >= t->prob * ((double) RAND_MAX + 1))) return 0; t->hit++; fprintf(stderr, "sabotage: hit: file `%s', line %u, func %s() [%d%%]\n", file, line, func, (int) (100.0 * t->hit / t->cnt)); return eno; } return 0; } // EndNoSabotage
<reponame>msfschaffner/opentitan-bak // Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include <stdbool.h> #include <stdint.h> #include "sw/device/lib/base/mmio.h" #include "sw/device/lib/dif/dif_rstmgr.h" #include "sw/device/lib/runtime/log.h" #include "sw/device/lib/testing/sram_ctrl_testutils.h" #include "sw/device/lib/testing/test_framework/check.h" #include "sw/device/lib/testing/test_framework/ottf_main.h" #include "sw/device/lib/testing/test_framework/status.h" #include "hw/top_earlgrey/sw/autogen/top_earlgrey.h" #define SRAM_CTRL_BACKDOOR_TEST_WORDS 16 #define SRAM_CTRL_BACKDOOR_TEST_BYTES \ SRAM_CTRL_BACKDOOR_TEST_WORDS * sizeof(uint32_t) /* The offset into the retention SRAM where we will backdoor write data. * This can be anywhere except at the base address which is * already used in the test for the scramble check. * Using the midpoint of the SRAM. */ #define RET_OFFSET (TOP_EARLGREY_SRAM_CTRL_RET_AON_RAM_SIZE_BYTES / 8) const test_config_t kTestConfig; static dif_sram_ctrl_t sram_ctrl; static dif_rstmgr_t rstmgr; static volatile uint32_t integrity_exception_count; /** * Retention SRAM start address (inclusive). */ static const uintptr_t kRetSramStartAddr = TOP_EARLGREY_SRAM_CTRL_RET_AON_RAM_BASE_ADDR; /** * First test pattern to be written and read from SRAM. */ static const sram_ctrl_testutils_data_t kRamTestPattern1 = { .words = { 0xA5A5A5A5, 0xA5A5A5A5, 0xA5A5A5A5, 0xA5A5A5A5, }, }; /** * Second test pattern to be written and read from SRAM. */ static const sram_ctrl_testutils_data_t kRamTestPattern2 = { .words = { 0x5A5A5A5A, 0x5A5A5A5A, 0x5A5A5A5A, 0x5A5A5A5A, }, }; /** Expected data for the backdoor write test, to be written from the testbench. */ static const uint8_t kBackdoorExpectedBytes[SRAM_CTRL_BACKDOOR_TEST_BYTES]; /** * Tests that the written data to RAM can be read. * * This is a pre-requisite test to check that RAM can be written and read * successfully. The test write-read check one pattern, and then the second, * which prevents a false-negative in case of the value of the memory address * under test is already initialised to one of the patterns. */ static void test_ram_write_read_pattern(void) { // Write first pattern to the start of SRAM, and read it out. sram_ctrl_testutils_write(kRetSramStartAddr, &kRamTestPattern1); CHECK(sram_ctrl_testutils_read_check_eq(kRetSramStartAddr, &kRamTestPattern1), "Read-Write first pattern failed"); // Write second pattern to the start of SRAM, and read it out. sram_ctrl_testutils_write(kRetSramStartAddr, &kRamTestPattern2); CHECK(sram_ctrl_testutils_read_check_eq(kRetSramStartAddr, &kRamTestPattern2), "Read-Write second pattern failed"); } /** * Tests RAM Scrambling. * * This test first writes a pattern to the start and the end of RAM. It then * requests a new scrambling key via dif_sram_ctrl (which scrambles RAM * addresses as well as the data). Finally, it reads back the RAM addresses * and checks them against the original pattern. The scrambled data will cause * an ECC error when read back from SRAM and trigger an internal IRQ. * The ISR for this IRQ will count the number of exceptions. The test is * successful if this count is as expected and the read data mismatches. */ static void test_ram_scrambling(const dif_sram_ctrl_t *sram_ctrl) { // Write the pattern at the start of RAM. sram_ctrl_testutils_write(kRetSramStartAddr, &kRamTestPattern1); sram_ctrl_testutils_scramble(sram_ctrl); mmio_region_t region = mmio_region_from_addr(kRetSramStartAddr); for (int i = 0; i < SRAM_CTRL_TESTUTILS_DATA_NUM_WORDS; ++i) { uint32_t read_data = mmio_region_read32(region, sizeof(uint32_t) * i); CHECK(read_data != kRamTestPattern1.words[i]); } CHECK(integrity_exception_count == SRAM_CTRL_TESTUTILS_DATA_NUM_WORDS, "Scramble read exception count differs from expected."); } /** * Override internal IRQ interrupt service routine to count * the number of integrity exceptions. */ void ottf_internal_isr(void) { ++integrity_exception_count; } bool test_main(void) { CHECK_DIF_OK(dif_rstmgr_init( mmio_region_from_addr(TOP_EARLGREY_RSTMGR_AON_BASE_ADDR), &rstmgr)); CHECK_DIF_OK(dif_sram_ctrl_init( mmio_region_from_addr(TOP_EARLGREY_SRAM_CTRL_RET_AON_REGS_BASE_ADDR), &sram_ctrl)); sram_ctrl_testutils_wipe(&sram_ctrl); test_ram_write_read_pattern(); integrity_exception_count = 0; test_ram_scrambling(&sram_ctrl); sram_ctrl_testutils_check_backdoor_write(kRetSramStartAddr, SRAM_CTRL_BACKDOOR_TEST_WORDS, RET_OFFSET, kBackdoorExpectedBytes); CHECK_DIF_OK(dif_rstmgr_software_device_reset(&rstmgr)); return true; }
<reponame>NCUT-Coders/xv6-riscv-guide-for-chinese #include "kernel/types.h" #include "user/user.h" int main(int argc, char *argv[]) { int p_0[2]; // forward int p_1[2]; // behind char ret_info; int p_ret[2]; if (pipe(p_0)<0 || pipe(p_ret)<0) { printf("pipe error\n"); exit(1); } // TODO: try sys_wait? const int SOINT = sizeof(int); int upper = 35; int lower = 2; int i; for (i=lower; i<=upper; i++) write(p_0[1], &i, SOINT); int layer_Num = 0; loop: close(p_0[1]); int first_Num; if (read(p_0[0], &first_Num, SOINT)<SOINT) // last layer { close(p_0[0]); write(p_ret[1], " ", 1); goto finish; } printf("prime %d\n", first_Num); if (pipe(p_1)<0) { printf("pipe error\n"); exit(1); } int tmp; while (read(p_0[0], &tmp, SOINT)==SOINT) if (tmp%first_Num) write(p_1[1], &tmp, SOINT); close(p_0[0]); if (fork()==0) { close(p_1[0]); close(p_1[1]); goto finish; } else { p_0[0] = p_1[0]; p_0[1] = p_1[1]; layer_Num++; } goto loop; // main progress exit after ret_info has been sent. finish: if (layer_Num==0) read(p_ret[0], &ret_info, 1); close(p_ret[0]); close(p_ret[1]); exit(0); }
<reponame>Dbevan/SunderingShadows //thief_torm.c - reward for Riddle Quest. Thanks to Shar for //the item description! Circe 1/19/04 #include <std.h> #include "../../nereid.h" inherit NBOOTS; void create(){ ::create(); set_name("yellow boots"); set_id(({ "boots", "boots of the lion" })); set_short("%^YELLOW%^Boots of the Lion%^RESET%^"); set_obvious_short("A pair of tawny yellow leather boots"); set_long( @AVATAR %^YELLOW%^These riding boots are made from the hide of a lion. The golden tawny fur has been treated as to never loose it's luster and shine. The riding boots come to mid-shin and feature slighty hard soles, but with some give. The lion is seen as Torm's totem animal, and many say that Torm rides into battle on the back of a golden lion called Nobanion when he must do battle. The tops of the boots are trimed with a shaggy golden fur, possibly the mane of the lion. The leather is well cared for and the boots seem nearly flawless. AVATAR ); set_lore( @AVATAR The Boots of the Lion are a prized item by the faith of Torm. The boots are rumored to give the faithful of Torm the strength and courage of a lion when worn, but only those faithful to Torm. There are rumors that anyone who tires to wear the boots and unworthy to do so find themselves missing a leg or two, as if the boots ate their limb! AVATAR ); set_property("lore difficulty",12); set_remove((:TO,"remove_func":)); } int remove_func(){ tell_room(environment(ETO),"%^YELLOW%^"+ETOQCN+" pulls off the lionskin boots and places them in a safe place.",ETO); tell_object(ETO,"%^YELLOW%^You remove the boots, but take care to keep the safe. Such a rare gift should be cherished."); return 1; }
/* * Splat.h * * Created on: Apr 21, 2011 * Author: <NAME> */ #ifndef SPLAT_H_ #define SPLAT_H_ #include <fstream> #include <iostream> #include <stdio.h> #include "stdafx.h" #include "Reference.h" #include "Reads.h" #include "Scheduler.h" class Splat { public: Splat(int argc, char** argv) ; virtual ~Splat(); private: void outputUsage() ; }; #endif /* SPLAT_H_ */
//The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. //Find the sum of all the primes below two million. //COMPLETE #include <stdio.h> #include <stdbool.h> #define MAX 2000000 unsigned long long int sumList(bool boolArr[]); bool boolArr[MAX + 1]; int main() { for (int i = 0; i < MAX + 1; boolArr[i++] = true); unsigned long long int sum; for (int i = 2; i < MAX + 1; i++) { if (boolArr[i] == true) { for (int j = i + i; j < MAX + 1; j += i) { boolArr[j] = false; } } } sum = sumList(boolArr); printf("The sum of all the primes below two million is %llu\n", sum); return 0; } unsigned long long int sumList(bool boolArr[]) { unsigned long long int sum = 0; for (int i = 2; i < MAX + 1; i++) { if (boolArr[i] == true) { sum += i; } } return sum; }
<reponame>wyaneva/ParTeCL #include <stdio.h> #include <stdlib.h> int a[3] = {1, 2, 3}; int add(int a, int b) { return a + b; } int main(int argc, char* argv[]) { if(argc < 2) { printf("Please, enter integers you'd like to add.\n"); return 0; } int b = atoi(argv[1]); int sum[3]; for(int i = 0; i < 3; i++) { sum[i] = add(a[i], b); } for(int i = 0; i < 3; i++) { printf("%d\n", sum[i]); } }
<gh_stars>0 #include <MacTypes.h> #include <QuickDraw.h> #include <EventMgr.h> #include <WindowMgr.h> #include <FontMgr.h> #include <ScrapMgr.h> #include <DialogMgr.h> #include <MemoryMgr.h> #include <ColorToolbox.h> #include "hipl_format.h" #define STRCLASS extern #include "globals.h" extern FILE *info; #define X_SCALE_ID 129 #define Y_SCALE_ID 130 #define Z_SCALE_ID 131 /* convert from the original pixel coordinate system to the viewing ports' coordinate system * note that the viewing port might be a stretched one, or already a zoomed one. */ OriginalToWindowRect( index, w_ptr, orig_rect_ptr, wind_rect_ptr ) long index; WindowRecord *w_ptr; Rect *orig_rect_ptr; Rect *wind_rect_ptr; { Rect dest_rect, temp_rect; double hscale, vscale; dest_rect = ((CGrafPtr)w_ptr)->portRect; /*first find coordinates of the requested rect in the currently viweing pic_sorc_rect */ temp_rect.top = (*orig_rect_ptr).top - pic_sorc_rect[index].top; temp_rect.left = (*orig_rect_ptr).left - pic_sorc_rect[index].left; temp_rect.bottom = (*orig_rect_ptr).bottom - pic_sorc_rect[index].top; temp_rect.right = (*orig_rect_ptr).right - pic_sorc_rect[index].left; vscale = ((double)(dest_rect.bottom - dest_rect.top)) / ((double)(pic_sorc_rect[index].bottom - pic_sorc_rect[index].top)) ; hscale = ((double)(dest_rect.right - dest_rect.left)) / ((double)(pic_sorc_rect[index].right - pic_sorc_rect[index].left)) ; temp_rect.top = (int)((vscale * (double)temp_rect.top ) + 0.99); temp_rect.left = (int)((hscale * (double)temp_rect.left ) + 0.99); temp_rect.bottom = (int)((vscale * (double)temp_rect.bottom ) + 0.99); temp_rect.right = (int)((hscale * (double)temp_rect.right ) + 0.99); (*wind_rect_ptr) = temp_rect; } /* convert from the viewing ports' coordinate system to the original pixel coordinate system * note that the viewing port might be a stretched one, or already a zoomed one. */ WindowToOriginalRect( index, w_ptr, wind_rect_ptr, orig_rect_ptr ) long index; WindowRecord *w_ptr; Rect *orig_rect_ptr; Rect *wind_rect_ptr; { Rect dest_rect, temp, base_rect; double hscale, vscale; dest_rect = ((CGrafPtr)w_ptr)->portRect; /* digitize the rectangle to discrete coordinates of the pixel map*/ /* find the true coordinates of the ractangle that has been chosen, the current view on the screen may already be a zoomed one. The current view is in pic_sorc_rect */ base_rect = pic_sorc_rect[index]; vscale = ((double)(base_rect.bottom - base_rect.top)) / ((double)(dest_rect.bottom) ); hscale = ((double)(base_rect.right - base_rect.left)) / ((double)(dest_rect.right) ); temp.top = base_rect.top + vscale * (*wind_rect_ptr).top + 0.00; temp.left = base_rect.left + hscale * (*wind_rect_ptr).left + 0.00; temp.bottom = base_rect.top + vscale * (*wind_rect_ptr).bottom + 0.00; temp.right = base_rect.left + hscale * (*wind_rect_ptr).right + 0.00; /*if the chosen rect in the original picture ends up being of size zero, then set it to size 1 pixel */ if ( ( temp.bottom - temp.top ) == 0 && ( temp.right - temp.left ) == 0 ) { temp.bottom ++; temp.right ++; } (*orig_rect_ptr) = temp; } DiscretizeRect( r_ptr, index, w_ptr ) Rect *r_ptr; long index; WindowRecord *w_ptr; { Rect rect_on_pixmap; WindowToOriginalRect( index, w_ptr, r_ptr, &rect_on_pixmap ); OriginalToWindowRect( index, w_ptr, &rect_on_pixmap, r_ptr ); } /* * when this command is invoked the zoom_sorc_rect[index] already has a rect in it, * which defines the point as the top.left of the rect. */ SetXYCoordOrigin( ) { long index; WindowRecord *w_ptr; GetPort( &w_ptr ); index = w_ptr->refCon; if ( index < 0 || index >= MAXHIPS ) { fprintf(info,"Front window must be a picture window.\n"); return; } x_origin[index] = zoom_sorc_rect[index].left; y_origin[index] = zoom_sorc_rect[index].top; } /* * when this command is invoked the zoom_sorc_rect[index] already has a rect in it, * which defines the point as the top.left of the rect. */ SetXYCoordMaxs( ) { long index; WindowRecord *w_ptr; GetPort( &w_ptr ); index = w_ptr->refCon; if ( index < 0 || index >= MAXHIPS ) { fprintf(info,"Front window must be a picture window.\n"); return; } x_max[index] = zoom_sorc_rect[index].left; y_max[index] = zoom_sorc_rect[index].top; } /* * set default coordinate systems for the new opened window */ DefaultCoords(new) int new; { x_origin[new] = 0; y_origin[new] = hd[new].orows; z_origin[new] = 0; x_max[new] = hd[new].ocols; y_max[new] = 0; z_max[new] = 0; /*unused */ x_offset[new] = 0; y_offset[new] = 0; z_offset[new] = 0; x_scale_per_pixel[new] = 1; y_scale_per_pixel[new] = 1; z_scale_per_pixel[new] = 1; strcpy( x_units[new],"Units" ); strcpy( y_units[new],"Units" ); strcpy( z_units[new],"Units" ); } SetXScale() { DialogPtr dptr; int itemHit,kind; Handle itemH; Rect dbox; char text[256]; long index; WindowRecord *w_ptr; double max; GetPort( &w_ptr ); index = w_ptr->refCon; if ( index < 0 || index >= MAXHIPS ) { fprintf(info,"Front window must be a picture window.\n"); return; } dptr = GetNewDialog(X_SCALE_ID,NULL,-1L); do { ModalDialog(NULL,&itemHit); } while ( itemHit != OK && itemHit != Cancel ); if ( itemHit == OK ) { GetDItem(dptr,6,&kind,&itemH,&dbox); GetIText(itemH,text); PtoCstr(text); sscanf(text,"%le", &x_offset[index] ); GetDItem(dptr,7,&kind,&itemH,&dbox); GetIText(itemH,text); PtoCstr(text); sscanf(text,"%le", &max ); x_scale_per_pixel[index] = ( max - x_offset[index] ) / (double)(x_max[index] - x_origin[index] ); GetDItem(dptr,9,&kind,&itemH,&dbox); GetIText(itemH,x_units[index]); PtoCstr( x_units[index]); } DisposDialog(dptr); } SetYScale() { DialogPtr dptr; int itemHit,kind; Handle itemH; Rect dbox; char text[256]; long index; WindowRecord *w_ptr; double max; GetPort( &w_ptr ); index = w_ptr->refCon; if ( index < 0 || index >= MAXHIPS ) { fprintf(info,"Front window must be a picture window.\n"); return; } dptr = GetNewDialog(Y_SCALE_ID,NULL,-1L); do { ModalDialog(NULL,&itemHit); } while ( itemHit != OK && itemHit != Cancel ); if ( itemHit == OK ) { GetDItem(dptr,6,&kind,&itemH,&dbox); GetIText(itemH,text); PtoCstr(text); sscanf(text,"%le", &y_offset[index] ); GetDItem(dptr,7,&kind,&itemH,&dbox); GetIText(itemH,text); PtoCstr(text); sscanf(text,"%le", &max ); y_scale_per_pixel[index] = -( max - y_offset[index] ) / (double)(y_max[index] - y_origin[index] ); GetDItem(dptr,9,&kind,&itemH,&dbox); GetIText(itemH,y_units[index]); PtoCstr( y_units[index]); } DisposDialog(dptr); } SetZScale() { DialogPtr dptr; int itemHit,kind; Handle itemH; Rect dbox; char text[256]; long index; WindowRecord *w_ptr; double max; GetPort( &w_ptr ); index = w_ptr->refCon; if ( index < 0 || index >= MAXHIPS ) { fprintf(info,"Front window must be a picture window.\n"); return; } dptr = GetNewDialog(Z_SCALE_ID,NULL,-1L); do { ModalDialog(NULL,&itemHit); } while ( itemHit != OK && itemHit != Cancel ); if ( itemHit == OK ) { GetDItem(dptr,7,&kind,&itemH,&dbox); GetIText(itemH,text); PtoCstr(text); sscanf(text,"%le", &z_offset[index] ); /*value for black pixels */ GetDItem(dptr,6,&kind,&itemH,&dbox); GetIText(itemH,text); PtoCstr(text); sscanf(text,"%le", &max ); /*white*/ z_scale_per_pixel[index] = ( max - z_offset[index] ) / (double)(256); GetDItem(dptr,9,&kind,&itemH,&dbox); GetIText(itemH,z_units[index]); PtoCstr( z_units[index]); } DisposDialog(dptr); } CoordWindUpdate() { WindowRecord *w_ptr, *fw_ptr; long index; fw_ptr = (WindowRecord *)FrontWindow(); index = fw_ptr->refCon; /*get the ptr to the window that is to be updated. This should be the current one */ GetPort( &w_ptr ); TextFont( monaco ); TextSize( 12 ); BeginUpdate( w_ptr ); EraseRect( &((GrafPtr)w_ptr)->portRect ); EndUpdate( w_ptr ); } /* * if mouse is on top of a picture window, then give coord info. */ MouseCoord() { WindowRecord *w_ptr, *fw_ptr; long index; static Point p; static Point prev_p; char t[256]; Rect xyz_rect, point_rect, orig_rect; double x,y,z; char *pixel_value_pr; long pixel_value; RGBColor rgb; char temp[256]; fw_ptr = (WindowRecord *)FrontWindow(); index = fw_ptr->refCon; if ( index < 0 || index >= MAXHIPS ) return; SetPort ( fw_ptr ); prev_p = p; GetMouse( &p ); if ( !PtInRect( p, &(((GrafPtr)fw_ptr)->portRect) ) ) return; if ( (prev_p.v == p.v) && (prev_p.h == p.h) ) /*mouse has not moved */ return; SetPort( coord_wind_ptr ); xyz_rect.top = 0; xyz_rect.left = StringWidth("\pX value: "); xyz_rect.bottom = xyz_rect.top + 70; xyz_rect.right = xyz_rect.left + StringWidth("\p12345.123"); EraseRect( &xyz_rect ); /*convert the location info from local coordinates to the pixel map ones */ point_rect.top = p.v; point_rect.left = p.h; point_rect.bottom = p.v + 1; point_rect.right = p.h + 1; WindowToOriginalRect( index, fw_ptr, &point_rect, &orig_rect ); /*get the pixel value at that location */ pixel_value_pr = ( **(myCGrafPtr[index]->portPixMap) ).baseAddr + ((**(myCGrafPtr[index]->portPixMap) ).rowBytes & 0x7FFF) * (long)orig_rect.top + (long)orig_rect.left ; pixel_value = (long)(*pixel_value_pr) & 0x000000FF; Index2Color( pixel_value, &rgb ); /*look in color table */ pixel_value = (rgb.red >> 8) ; x = x_offset[index] + x_scale_per_pixel[index] * (orig_rect.left - x_origin[index]); MoveTo (2,15 ); TextFace( bold ); DrawString("\pX value: "); sprintf( t, "%9.3lf", x ); CtoPstr(t); TextFace( 0 ); DrawString(t); TextFace( bold ); Move(10,0); strcpy(temp,x_units[index]); CtoPstr(temp); DrawString( temp ); y = y_offset[index] + y_scale_per_pixel[index] * (- (orig_rect.top - y_origin[index]) ); MoveTo (2,30 ); TextFace( bold ); DrawString("\pY value: "); sprintf( t, "%9.3lf", y ); CtoPstr(t); TextFace( 0 ); DrawString(t); TextFace( bold ); Move(10,0); strcpy(temp,y_units[index]); CtoPstr(temp); DrawString( temp ); z = z_offset[index] + z_scale_per_pixel[index] * pixel_value ; MoveTo (2,45 ); TextFace( bold ); DrawString("\pZ value: "); sprintf( t, "%9.3lf", z ); CtoPstr(t); TextFace( 0 ); DrawString(t); TextFace( bold ); Move(10,0); strcpy(temp,z_units[index]); CtoPstr(temp); DrawString( temp ); } /* * */ SaveXYZScales() { long index; WindowRecord *w_ptr; char title[256]; FILE *fptr; w_ptr = (WindowRecord *)FrontWindow(); index = w_ptr->refCon; if ( index < 0 || index >= MAXHIPS ) { fprintf(info,"Front window must be a picture window.\n"); return; } GetWTitle( w_ptr, title ); PtoCstr( title ); strcat( title, ".coord" ); fptr = fopen( title , "w" ); fprintf( fptr, "%d\n", x_origin[index] ); fprintf( fptr, "%d\n", y_origin[index] ); fprintf( fptr, "%d\n", z_origin[index] ); fprintf( fptr, "%d\n", x_max[index] ); fprintf( fptr, "%d\n", y_max[index] ); fprintf( fptr, "%d\n", z_max[index] ); fprintf( fptr, "%le\n", x_offset[index] ); fprintf( fptr, "%le\n", y_offset[index] ); fprintf( fptr, "%le\n", z_offset[index] ); fprintf( fptr, "%le\n", x_scale_per_pixel[index] ); fprintf( fptr, "%le\n", y_scale_per_pixel[index] ); fprintf( fptr, "%le\n", z_scale_per_pixel[index] ); fprintf( fptr, "%s\n", x_units[index] ); fprintf( fptr, "%s\n", y_units[index] ); fprintf( fptr, "%s\n", z_units[index] ); fclose( fptr ); } /* * */ ReadCoords(fname,index) char *fname; int index; { char title[256]; FILE *fptr; strcpy(title, fname ); strcat( title, ".coord" ); fptr = fopen( title , "r" ); if ( fptr == NULL ) { fprintf(info,"No coordinates file. Will assume defaults.\n"); DefaultCoords(index); return; } fscanf( fptr, "%d", &x_origin[index] ); fscanf( fptr, "%d", &y_origin[index] ); fscanf( fptr, "%d", &z_origin[index] ); fscanf( fptr, "%d", &x_max[index] ); fscanf( fptr, "%d", &y_max[index] ); fscanf( fptr, "%d", &z_max[index] ); fscanf( fptr, "%le", &x_offset[index] ); fscanf( fptr, "%le", &y_offset[index] ); fscanf( fptr, "%le", &z_offset[index] ); fscanf( fptr, "%le", &x_scale_per_pixel[index] ); fscanf( fptr, "%le", &y_scale_per_pixel[index] ); fscanf( fptr, "%le", &z_scale_per_pixel[index] ); fscanf( fptr, "%s", x_units[index] ); fscanf( fptr, "%s", y_units[index] ); fscanf( fptr, "%s", z_units[index] ); fclose( fptr ); }
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | <EMAIL> so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #ifndef __DEPTH_FIRST_VISITOR_H__ #define __DEPTH_FIRST_VISITOR_H__ #include <compiler/analysis/block_scope.h> #include <compiler/expression/expression.h> #include <compiler/statement/statement.h> namespace HPHP { /////////////////////////////////////////////////////////////////////////////// template <class T> class DepthFirstVisitor { public: DepthFirstVisitor(T d) : m_data(d) {} ExpressionPtr visitExprRecur(ExpressionPtr e) { for (int i = 0, n = e->getKidCount(); i < n; i++) { if (ExpressionPtr kid = e->getNthExpr(i)) { ExpressionPtr rep = visitExprRecur(kid); if (rep) { e->getScope()->addUpdates(BlockScope::UseKindCaller); e->setNthKid(i, rep); } } } return this->visit(e); } StatementPtr visitStmtRecur(StatementPtr stmt) { BlockScopeRawPtr scope = boost::dynamic_pointer_cast<LoopStatement>(stmt) ? stmt->getScope() : BlockScopeRawPtr(); for (int i = 0, n = stmt->getKidCount(); i < n; i++) { if (ConstructPtr kid = stmt->getNthKid(i)) { if (StatementPtr s = boost::dynamic_pointer_cast<Statement>(kid)) { switch (s->getKindOf()) { case Statement::KindOfFunctionStatement: case Statement::KindOfMethodStatement: case Statement::KindOfClassStatement: case Statement::KindOfInterfaceStatement: continue; default: break; } if (scope) scope->incLoopNestedLevel(); if (StatementPtr rep = visitStmtRecur(s)) { stmt->setNthKid(i, rep); stmt->getScope()->addUpdates(BlockScope::UseKindCaller); } if (scope) scope->decLoopNestedLevel(); } else { ExpressionPtr e = boost::dynamic_pointer_cast<Expression>(kid); if (ExpressionPtr rep = visitExprRecur(e)) { stmt->setNthKid(i, rep); stmt->getScope()->addUpdates(BlockScope::UseKindCaller); } } } } return this->visit(stmt); } int visitScope(BlockScopeRawPtr scope) { int flags = 0, f; do { flags |= f = this->visit(scope); } while (f); return flags; } void visitDependencies(BlockScopeRawPtr scope, BlockScopeRawPtrQueue &queue) { scope->setMark(BlockScope::MarkProcessingDeps); const BlockScopeRawPtrVec &deps = scope->getDeps(); for (size_t i = 0; i < deps.size(); i++) { BlockScopeRawPtr dep = deps[i]; if (dep->getMark() == BlockScope::MarkWaitingInQueue) { this->visitDependencies(dep, queue); } } scope->setMark(BlockScope::MarkProcessing); if (int useKinds = this->visitScope(scope)) { scope->changed(queue, useKinds); } scope->setMark(BlockScope::MarkProcessedInQueue); } void visitDepthFirst(BlockScopeRawPtrQueue &scopes) { BlockScopeRawPtrQueue::iterator end = scopes.end(); for (BlockScopeRawPtrQueue::iterator it = scopes.begin(); it != end; ++it) { (*it)->setMark(BlockScope::MarkWaitingInQueue); } while (true) { BlockScopeRawPtrQueue::iterator it = scopes.begin(); if (it == end) break; if ((*it)->getMark() == BlockScope::MarkWaitingInQueue) { this->visitDependencies(*it, scopes); } assert((*it)->getMark() == BlockScope::MarkProcessedInQueue); (*it)->setMark(BlockScope::MarkProcessed); scopes.erase(it); } } ExpressionPtr visit(ExpressionPtr); StatementPtr visit(StatementPtr); int visit(BlockScopeRawPtr scope); private: T m_data; }; /////////////////////////////////////////////////////////////////////////////// } #endif // __DEPTH_FIRST_VISITOR_H__
#ifndef STATE_LOADING_H #define STATE_LOADING_H #include <StateMachine.h> class state_loading : public State { public: virtual void init() override; virtual void update() override; virtual void draw() override; }; int load_x = 0; void state_loading::init() { display.setFont(&FreeMonoBold12pt7b); display.setTextColor(INVERSE); } void state_loading::update() { if (load_x >= 104) { load_x = 0; nextState(1); // nextState(1); } load_x += 1; } void state_loading::draw() { display.fillRoundRect(12, 22, load_x, 23, 2, ON); display.drawRoundRect(10, 20, 108, 27, 3, ON); display.setCursor(15, 40); display.print("LOADING"); display.swapBuffer(); display.clear(); delay(20); } #endif
// // MyShowView.h // HSNavigationControllerDemo // // Created by 郝帅 on 2017/2/22. // Copyright © 2017年 hs. All rights reserved. // #import <UIKit/UIKit.h> typedef NS_ENUM(NSInteger, MyShowViewType) { MyShowViewTypeCircle = 0, // 圆形 MyShowViewTypeSquare, // 方形 }; @interface MyShowView : UIView + (instancetype)viewWithFrame:(CGRect) frame showViewType:(MyShowViewType) showViewType lineNum:(NSInteger) lineNum; @property (nonatomic, assign) MyShowViewType showViewType; @property (nonatomic, assign) NSInteger lineNum; @end
<filename>extra/news/src/sk/rz/rz-kauvir/rz-code-generators/rpi/rpi-stage-element.h // Copyright <NAME> 2019. // 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) #ifndef RPI_STAGE_ENEMENT__H #define RPI_STAGE_ENEMENT__H #include "accessors.h" #include "flags.h" #include <QString> #include <QMap> #include <QTextStream> #include "rzns.h" #include "relae-graph/relae-caon-ptr.h" #include "rz-function-def/rz-function-def-syntax.h" RZNS_(GBuild) class RZ_Lisp_Graph_Visitor; class RZ_Graph_Visitor_Phaon; _RZNS(GBuild) USING_RZNS(GBuild) RZNS_(PhrGraphCore) class PGB_IR_Build; _RZNS(PhrGraphCore) USING_RZNS(PhrGraphCore) RZNS_(GVal) class RPI_Stage_Form; enum class RPI_Stage_Element_Kinds { N_A, FGround_Symbol, S1_FGround_Symbol, Token, Form, S1_Symbol, Type_Default_Marker, Instruction_Symbol, Literal, String_Literal, Kernel_Type_Symbol, Raw_Symbol, Bridge_Symbol, Field_Index_Key, }; class RPI_Stage_Element { caon_ptr<RPI_Stage_Form> form_; RPI_Stage_Element_Kinds kind_; QString text_; public: RPI_Stage_Element(RPI_Stage_Element_Kinds kind, QString text); RPI_Stage_Element(caon_ptr<RPI_Stage_Form> form); RPI_Stage_Element(); ACCESSORS(RPI_Stage_Element_Kinds ,kind) ACCESSORS(QString ,text) ACCESSORS(caon_ptr<RPI_Stage_Form> ,form) }; _RZNS(GVal) #endif //RPI_STAGE_ENEMENT__H
// // consultHeadView.h // FreelyHeath // // Created by L on 2017/7/19. // Copyright © 2017年 深圳乐易住智能科技股份有限公司. All rights reserved. // #import <UIKit/UIKit.h> typedef void (^letAction)(); typedef void (^rightAction)(); typedef void (^evalute)(); @interface consultHeadView : UIView @property (nonatomic,strong)UIImageView *backGroungImage; @property (nonatomic,strong)letAction OneshotInterpretation; @property (nonatomic,strong)rightAction FreeConsultation; @property (nonatomic,strong)evalute eva; @end
#pragma once struct GameContext; class GameSpecs final { public: static void Update(const GameContext& context); static int GetFPS() { return m_FPS; } private: static int m_FPS; static float m_FpsElapsed; static int m_FpsFrames; };
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct{ // Start your code int nodes; int maxConnects; int totalConnects; double d; int* connectCount; int* source; int* dest; int* offset; double* oldPageRank; double* newPageRank; // End your code }Network; typedef struct{ int dest; int source; }Link; int destCompare(const void * u, const void * v){ Link *linkU = (Link*)u; Link *linkV = (Link*)v; return linkU->dest - linkV->dest; } Network networkReader(char* filename){ // Start your code Network g; int i, j, temp; FILE *fp; int source; int dest; int count=0; fp = fopen(filename, "r"); fscanf(fp, "%d,", &g.nodes); temp = fscanf(fp, "%d,", &g.maxConnects); g.connectCount = (int*)calloc(g.nodes, sizeof(int)); int* sourceArray = (int*)calloc(g.nodes * g.maxConnects, sizeof(int)); int* destArray = (int*)calloc(g.nodes * g.maxConnects, sizeof(int)); g.oldPageRank = (double*)calloc(g.nodes, sizeof(double)); g.newPageRank = (double*)calloc(g.nodes, sizeof(double)); // Check if fscanf has read to the End of File do{ temp = fscanf(fp, "%d,%d,", &source, &dest); if(temp==EOF) break; sourceArray[count]=source; destArray[count]=dest; g.connectCount[sourceArray[count]]++; count++; }while(temp != EOF); g.totalConnects = count; fclose(fp); Link links[g.totalConnects]; for(i = 0; i < g.totalConnects; i++){ links[i].source = sourceArray[i]; links[i].dest = destArray[i]; } free(sourceArray); free(destArray); qsort(&links, g.totalConnects, sizeof(Link), destCompare); g.source = (int*) calloc(g.totalConnects, sizeof(int)); g.dest = (int*) calloc(g.totalConnects, sizeof(int)); g.offset = (int*) calloc(g.nodes+1, sizeof(int)); for(i = 0; i < g.totalConnects; i++){ g.source[i] = links[i].source; g.dest[i] = links[i].dest; g.offset[g.dest[i]+1]++; } for(i = 1; i< g.nodes+1; i++){ g.offset[i]+=g.offset[i-1]; } return g; // End your code } double computeDiff(Network net){ int i; double diff = 0; for(i=0; i < net.nodes; i++){ diff += pow(net.oldPageRank[i] - net.newPageRank[i], 2); } return sqrt(diff); } double updatePageRank(Network net){ int j, i; int source; int dest; double L; double PR; for(i=0; i < net.nodes; i++){ for(j=net.offset[i]; j<net.offset[i+1]; j++){ dest = net.dest[j]; source = net.source[j]; L = (double) net.connectCount[source]; PR = net.oldPageRank[source]; net.newPageRank[dest] += net.d*(PR/L); } } return computeDiff(net); } void computePageRank(Network net){ double tol = 1e-6; double diff = 1; double* temp; int k; double nodes = (double) net.nodes; double constant = (1-net.d)/nodes; /* Initialize old PR vlaues */ for(k=0;k<net.nodes;k++){ net.oldPageRank[k] = 1/nodes; } while(diff > tol){ /* Set all new PR values to constant */ for(k=0;k<net.nodes;k++){ net.newPageRank[k] = constant; } /* Update PR based on connections */ diff = updatePageRank(net); /* Switch pointers updated values in oldPR array Gets us ready to run again */ temp = net.oldPageRank; net.oldPageRank = net.newPageRank; net.newPageRank = temp; } } void networkDestructor(Network net){ free(net.connectCount); free(net.source); free(net.dest); free(net.offset); free(net.oldPageRank); free(net.newPageRank); } int main(int argc, char** argv){ // Reads the filename of the data file char* filename = argv[1]; //Start your code int j; int k = 0; Network net = networkReader(filename); net.d = 0.85; computePageRank(net); for(j = 0; j < net.nodes; j++){ printf("PageRank of node %d is: %f\n", j, net.oldPageRank[j]); } networkDestructor(net); return 0; }
#ifndef _WORK_HEAD_H_ #define _WORK_HEAD_H_ #include <assert.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <pthread.h> #include <sys/cpuset.h> typedef void (*ev_clone_proc_pf) (void *cycle, void *data); #define MAX_PROCESS_NAME (48) struct ev_process_t{ pid_t pid; int32_t status; int32_t ev_channel_pair[2]; ev_clone_proc_pf proc; void *data; char name[MAX_PROCESS_NAME]; uint32_t detached:1; uint32_t exiting:1; uint32_t exited:1; }; #endif
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SHILL_NET_RTNL_LINK_STATS_H_ #define SHILL_NET_RTNL_LINK_STATS_H_ #include <stdint.h> // Pre-v4.6 layout for rtnl_link_stats64. Linux commit 6e7333d315a7 ("net: add // rx_nohandler stat counter") added an additional field, and for pre-v4.6 // compatibility, we just ignore it. // TODO(briannorris): drop this when older kernels are phased out. struct old_rtnl_link_stats64 { uint64_t rx_packets; uint64_t tx_packets; uint64_t rx_bytes; uint64_t tx_bytes; uint64_t rx_errors; uint64_t tx_errors; uint64_t rx_dropped; uint64_t tx_dropped; uint64_t multicast; uint64_t collisions; // detailed rx_errors uint64_t rx_length_errors; uint64_t rx_over_errors; uint64_t rx_crc_errors; uint64_t rx_frame_errors; uint64_t rx_fifo_errors; uint64_t rx_missed_errors; // detailed tx_errors uint64_t tx_aborted_errors; uint64_t tx_carrier_errors; uint64_t tx_fifo_errors; uint64_t tx_heartbeat_errors; uint64_t tx_window_errors; // for cslip etc uint64_t rx_compressed; uint64_t tx_compressed; }; #endif // SHILL_NET_RTNL_LINK_STATS_H_
// This defines the interfaces for the pyqtBoundSignal type. // // Copyright (c) 2017 Riverbank Computing Limited <<EMAIL>> // // This file is part of PyQt5. // // This file may be used under the terms of the GNU General Public License // version 3.0 as published by the Free Software Foundation and appearing in // the file LICENSE included in the packaging of this file. Please review the // following information to ensure the GNU General Public License version 3.0 // requirements will be met: http://www.gnu.org/copyleft/gpl.html. // // If you do not wish to use this file under the terms of the GPL version 3.0 // then you may purchase a commercial license. For more information contact // <EMAIL>. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #ifndef _QPYCORE_PYQTBOUNDSIGNAL_H #define _QPYCORE_PYQTBOUNDSIGNAL_H #include <Python.h> #include <sip.h> #include "qpycore_pyqtsignal.h" #include "qpycore_namespace.h" QT_BEGIN_NAMESPACE class QByteArray; class QObject; QT_END_NAMESPACE extern "C" { // This defines the structure of a bound PyQt signal. typedef struct { PyObject_HEAD // The unbound signal. qpycore_pyqtSignal *unbound_signal; // A borrowed reference to the wrapped QObject that is bound to the signal. PyObject *bound_pyobject; // The QObject that is bound to the signal. QObject *bound_qobject; } qpycore_pyqtBoundSignal; } // The type object. extern PyTypeObject *qpycore_pyqtBoundSignal_TypeObject; bool qpycore_pyqtBoundSignal_init_type(); PyObject *qpycore_pyqtBoundSignal_New(qpycore_pyqtSignal *unbound_signal, PyObject *bound_pyobject, QObject *bound_qobject); sipErrorState qpycore_get_receiver_slot_signature(PyObject *slot, QObject *transmitter, const Chimera::Signature *signal_signature, bool single_shot, QObject **receiver, QByteArray &slot_signature); #endif
<reponame>Dbevan/SunderingShadows<filename>d/deku/monster/bandit.c #include <std.h> #include "/d/deku/inherits/forest.h" #define H_RACES ({"werewolf","hag","ettin","giant","gnoll","goblin",\ "kobold","athach","drow","half-drow","goblin","owlbear","bugbear",\ "ogre","ogre-magi","ogre-mage"}) inherit MONSTER; int camped, attacked, exps; void create() { ::create(); set_name("bandit"); set_id(({"bandit","thief","human"})); set_race("human"); set_short("A human clad with black leather"); set_long("%^RESET%^This man is of average height and has a frail build. His hair and eyes are dark and unremarkable. He "+ "wears a suit of %^BOLD%^%^BLACK%^black leather%^RESET%^ armor that covers a great deal of his body. "+ "The exposed parts of his flesh are dirty, suggesting that he doesn't care much about keeping himself "+ "clean, and littered with nicks and scratches, some of which have already began to scab over. "+ "He carries a short sword in each hand."); set_class(!random(2) ? "thief" : "fighter"); set_guild_level(query_class(),20); set_mlevel(query_class(),query_guild_level(query_class())); set("aggressive","stab_them"); set_alignment(7); set_stats("strength",17 + random(2)); set_stats("intelligence",9); set_stats("wisdom",9); set_stats("dexterity",15); set_stats("charisma",8); set_stats("constitution",12); set_gender("male"); set_hp(395 + random(20)); set_new_exp(20, "normal"); new("/d/common/obj/weapon/shortsword")->move(TO); command("wield sword"); new("/d/common/obj/weapon/shortsword")->move(TO); command("wield sword"); new("/d/common/obj/armour/leather")->move(TO); command("wear leather"); add_search_path("/cmds/thief"); add_money("silver",random(400)); add_money("copper",random(800)); add_money("gold",800 + random(850)); set_max_level(25); if(is_class("fighter")) { set_funcs(({"flash_em"})); set_func_chance(25 + random(26)); add_search_path("/cmds/fighter"); } } void make_camp() { object ob, ob1; if(camped != 1 && !random(2)) { camped = 1; switch(random(4)) { case 0: ob = new("/d/common/obj/misc/sack"); ob1 = new("/std/obj/coins"); ob1->add_money("gold",200 + random(151)); ob1->move(ob); ob->move(TO); break; case 1: ob = new("/d/common/obj/misc/pouch"); new("/d/antioch/valley/obj/gem")->move(ob); ob->move(TO); command("wear pouch"); break; case 2: ob = new("/d/common/obj/misc/ssack"); ob1 = new("/std/obj/coins"); ob1->add_money("gold",455 + random(551)); ob1->add_money("electrum",500 + random(81)); ob1->add_money("silver",600 + random(101)); ob1->move(ob); ob->move(TO); break; case 3: ob = new("/d/common/obj/misc/pouch"); ob1 = new("/std/obj/coins"); ob1->add_money("platinum",300 + random(431)); ob1->move(ob); ob->move(TO); command("wear pouch"); break; } } set("aggressive",0); } void break_camp() { set("aggressive","stab_them"); } void stab_them() { if(!TP->query_invis() && objectp(TP) && attacked != 1) { command("say I'll have my share!"); if(TO->is_class("fighter")) { command(!random(2) ? "rush "+TPQN : "kill "+TPQN); } if(TO->is_class("thief")) { command(!random(2) ? "stab "+TPQN : "kill "+TPQN); command("kill "+TPQN); } } } void flash_em(object targ) { command("flash"); } void heart_beat() { ::heart_beat(); if(!objectp(TO)) return; if(!objectp(ETO)) return; /* if((int)TO->query_exp() > exps) { FENC->fix_exp(TO,exps); } */ if(sizeof(TO->query_current_attackers()) < 1 && attacked == 1) { attacked = 0; return; } } void init() { string msg; ::init(); if(!objectp(TO)) return; if(!objectp(ETO)) return; if(!objectp(TP)) return; if(TP->query_invis()) return; if(member_array((string)TP->query_race(),H_RACES) != -1) { switch(random(4)) { case 0: msg = "die ya damned abomination!!"; break; case 1: msg = "what the hell are ya doing here??? DIE!"; break; case 2: msg = "YA SON OF FILTHY FIEND!!! GET IN THE GROUND!!"; break; case 3: msg = "Time fer ya to get outta here!"; break; } command("say "+msg); if(!objectp(TP)) return; command("stab "+TPQN); if(!objectp(TP)) return; command("kill "+TPQN); attacked = 1; return; } }
<gh_stars>1-10 // Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FetchInitiatorTypeNames_h #define FetchInitiatorTypeNames_h #include "wtf/text/AtomicString.h" #include "core/CoreExport.h" // Generated from: // - fetch/FetchInitiatorTypeNames.in namespace blink { namespace FetchInitiatorTypeNames { CORE_EXPORT extern const WTF::AtomicString& beacon; CORE_EXPORT extern const WTF::AtomicString& css; CORE_EXPORT extern const WTF::AtomicString& document; CORE_EXPORT extern const WTF::AtomicString& icon; CORE_EXPORT extern const WTF::AtomicString& internal; CORE_EXPORT extern const WTF::AtomicString& link; CORE_EXPORT extern const WTF::AtomicString& ping; CORE_EXPORT extern const WTF::AtomicString& processinginstruction; CORE_EXPORT extern const WTF::AtomicString& texttrack; CORE_EXPORT extern const WTF::AtomicString& violationreport; CORE_EXPORT extern const WTF::AtomicString& xml; CORE_EXPORT extern const WTF::AtomicString& xmlhttprequest; CORE_EXPORT void init(); } // FetchInitiatorTypeNames } // namespace blink #endif
<reponame>chengwei45254/IPC.Bond #pragma once #include "OutputBuffer.h" #include "InputBuffer.h" #include "BufferPool.h" #include <bond/core/bond.h> #include <memory> #include <future> namespace IPC { namespace Bond { struct DefaultProtocols : bond::Protocols< bond::CompactBinaryReader<DefaultInputBuffer>, bond::SimpleBinaryReader<DefaultInputBuffer>, bond::FastBinaryReader<DefaultInputBuffer>, bond::SimpleJsonReader<DefaultInputBuffer>> {}; template <template <typename> typename Writer, typename Protocols = DefaultProtocols, typename BufferPool, typename T> typename BufferPool::ConstBuffer Serialize(std::shared_ptr<BufferPool> pool, const T& value, std::size_t minBlobSize = 0) { OutputBuffer<BufferPool> output{ std::move(pool), minBlobSize }; Writer<decltype(output)> writer{ output }; bond::Serialize<Protocols>(value, writer); return std::move(output).GetBuffer(); } template <typename Protocols = DefaultProtocols, typename BufferPool, typename T> typename BufferPool::ConstBuffer Serialize(bond::ProtocolType protocol, std::shared_ptr<BufferPool> pool, const T& value, std::size_t minBlobSize = 0) { OutputBuffer<BufferPool> output{ std::move(pool), minBlobSize }; bond::Apply<bond::Serializer, Protocols>(value, output, static_cast<std::uint16_t>(protocol)); return std::move(output).GetBuffer(); } template <template <typename> typename Reader, typename Protocols = DefaultProtocols, typename ConstBuffer, typename T> void Deserialize(ConstBuffer&& buffer, T& value, std::shared_ptr<SharedMemory> memory) { InputBuffer<std::decay_t<ConstBuffer>> input{ std::forward<ConstBuffer>(buffer), std::move(memory) }; Reader<decltype(input)> reader{ std::move(input) }; bond::Deserialize<Protocols>(reader, value); } template <typename Protocols = DefaultProtocols, typename ConstBuffer, typename T> void Deserialize(bond::ProtocolType protocol, ConstBuffer&& buffer, T& value, std::shared_ptr<SharedMemory> memory) { InputBuffer<std::decay_t<ConstBuffer>> input{ std::forward<ConstBuffer>(buffer), std::move(memory) }; bond::Apply<T, Protocols>(bond::To<T, Protocols>{ value }, input, static_cast<std::uint16_t>(protocol)); } template <template <typename> typename Writer, typename Protocols = DefaultProtocols, typename BufferPool, typename T> typename BufferPool::ConstBuffer Marshal(std::shared_ptr<BufferPool> pool, const T& value, std::size_t minBlobSize = 0) { OutputBuffer<BufferPool> output{ std::move(pool), minBlobSize }; Writer<decltype(output)> writer{ output }; bond::Marshal<Protocols>(value, writer); return std::move(output).GetBuffer(); } template <typename Protocols = DefaultProtocols, typename BufferPool, typename T> typename BufferPool::ConstBuffer Marshal(bond::ProtocolType protocol, std::shared_ptr<BufferPool> pool, const T& value, std::size_t minBlobSize = 0) { OutputBuffer<BufferPool> output{ std::move(pool), minBlobSize }; bond::Apply<bond::Marshaler, Protocols>(value, output, static_cast<std::uint16_t>(protocol)); return std::move(output).GetBuffer(); } template <typename Protocols = DefaultProtocols, typename ConstBuffer, typename T> void Unmarshal(ConstBuffer&& buffer, T& value, std::shared_ptr<SharedMemory> memory) { bond::Unmarshal<Protocols>(InputBuffer<std::decay_t<ConstBuffer>>{ std::forward<ConstBuffer>(buffer), std::move(memory) }, value); } template <typename BufferPool, typename ProtocolsT = DefaultProtocols> class Serializer // TODO: Add compile-time protocol support. { public: using Protocols = ProtocolsT; Serializer(bond::ProtocolType protocol, bool marshal, std::shared_ptr<BufferPool> outputPool, std::shared_ptr<SharedMemory> inputMemory, std::size_t minBlobSize = 0) : m_outputPool{ std::move(outputPool) }, m_inputMemory{ std::move(inputMemory) }, m_protocol{ protocol }, m_marshal{ marshal }, m_minBlobSize{ minBlobSize } {} bond::ProtocolType GetProtocolType() const { return m_protocol; } bool IsMarshaled() const { return m_marshal; } template <typename T> typename BufferPool::ConstBuffer Serialize(const T& value) { return m_marshal ? Bond::Marshal<Protocols>(m_protocol, m_outputPool, value, m_minBlobSize) : Bond::Serialize<Protocols>(m_protocol, m_outputPool, value, m_minBlobSize); } template <typename T> void Deserialize(typename BufferPool::ConstBuffer&& buffer, T& value) { m_marshal ? Bond::Unmarshal<Protocols>(std::move(buffer), value, m_inputMemory) : Bond::Deserialize<Protocols>(m_protocol, std::move(buffer), value, m_inputMemory); } template <typename T> std::future<T> Deserialize(typename BufferPool::ConstBuffer buffer) { std::packaged_task<T()> task{ [&] { T value; Deserialize(std::move(buffer), value); return value; } }; task(); return task.get_future(); } const std::shared_ptr<BufferPool>& GetOutputBufferPool() const { return m_outputPool; } const std::shared_ptr<SharedMemory>& GetInputMemory() const { return m_inputMemory; } private: std::shared_ptr<BufferPool> m_outputPool; std::shared_ptr<SharedMemory> m_inputMemory; bond::ProtocolType m_protocol; bool m_marshal; std::size_t m_minBlobSize; }; using DefaultSerializer = Serializer<DefaultBufferPool>; } // Bond } // IPC
#pragma once // Copyright (c) 2021 DNV AS // // 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 #include "Quantity.h" #include "IPhenomenon.h" #include "Volume.h" namespace DNVS {namespace MoFa {namespace Units { typedef Dimension<3, 0, 0, 0, 0> FirstMomentOfAreaDimension; class FirstMomentOfAreaPhenomenon : public IPhenomenon { public: typedef FirstMomentOfAreaDimension DimensionType; template<typename ReturnTypeT, typename CallbackT> static ReturnTypeT ComposeUnit(CallbackT& callback) { return Pow(callback(LengthDimension()),3); } static std::string GetName() { return "FirstMomentOfArea"; } }; typedef Quantity<FirstMomentOfAreaPhenomenon> FirstMomentOfArea; }}}
/** * @file common.h * Projekt: Implementace prekladace imperativniho jazyka IFJ21. * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @brief Header for common functions used in the entire project. */ #ifndef _COMMON_H_ #define _COMMON_H_ /** * @brief Structure for storing a string of * (possibly) infinite length */ typedef struct dynamic_string { char *content; unsigned size; unsigned limit; } dynamic_string_s; /** * @brief Stucture for storing the entire source file. * Inflatable array (vector) was used for implementation. */ typedef struct source_file { char **line; unsigned no_lines; unsigned limit; } source_file_s; /** * @brief An enumeration of valid return codes */ typedef enum rc { RC_OK = 0, /* Success */ RC_LEX_ERR = 1, /* Lexical analysis error*/ RC_SYN_ERR = 2, /* Syntactical analysis error */ RC_SEM_UNDEF_ERR = 3, /* Semantic error -undefined function/variable or redefine */ RC_SEM_ASSIGN_ERR = 4, /* Semantic error - assignment type incompatibility */ RC_SEM_CALL_ERR = 5, /* Semantic error - wrong number or type of paramaters or return values */ RC_SEM_EXP_ERR = 6, /* Semantic error - wrong type compatibility in expressions */ RC_SEM_OTHER_ERR = 7, /* Semantic error - other */ RC_RUN_NIL_ERR = 8, /* Run error - unexpected nil */ RC_RUN_ZERO_DIV_ERR = 9, /* Run error - zero division */ RC_INTERNAL_ERR = 99 /* Internal error - allocation errors, etc. */ } rc_e; /** * @brief Destructor for the data found inside a generic ADT. */ typedef void (*destructor)(void *); /** * @brief A macro for better freeing to avoid double frees. */ #define FREE(x) \ free(x); \ x = NULL; /** * @brief Free callback that calls the correct destructor for a generic ADT. */ #define FREE_VALUE(x, destructor) \ if (!destructor) { \ FREE(x->value); \ } else { \ (*destructor)(x->value); \ } /** * @brief A marco for unified handling of allocation failure. */ #define ALLOC_CHECK(x) \ if (!x) { \ fputs("Out of memory.", stderr); \ fprintf(stderr, "Allocation in %s:%d failed.\n", __FILE__, __LINE__); \ exit(RC_INTERNAL_ERR); \ } /** * @brief A macro for getting maximum of two numbers. */ #define MAX(a, b) (a > b ? a : b) /** * @brief A macro for getting absolute value of a number. */ #define ABS(a) (a < 0 ? -a : a) /** * @brief A macro for printing error messages. */ #define ERR_MSG(msg, line) fprintf(stderr, "Error on line %d: %s", line, msg); /** * @brief Duplicates the @p str. * * @param[in] str The string to duplicate. * * @return Pointer to a new string. NULL if memory allocation error. */ char *my_strdup(const char *str); /** * @brief Initialize the dynamic_string structure. * * @param[in,out] dynamic_string Dynamic string to initialize. */ void ds_init(dynamic_string_s *dynamic_string); /** * @brief Add a character to the end of dynamic string. * * @param[in,out] dynamic_string Dynamic string structure where the character c will be stored. * @param[in] c character to add. * * @return RC_OK on success. */ rc_e ds_add_char(dynamic_string_s *dynamic_string, const char c); /** * @brief Destructor for the dynamic_string structure. * * @param[in/out] source The structure to destroy. */ void ds_destroy(dynamic_string_s *dynamic_string); /** * @brief Initialization of the source_file structure. * * @param[in,out] source The structure to initialize. */ void sf_init(source_file_s *source); /** * @brief Add a line of source code to the structure. * * @param[in,out] source The structure where to add the line. * @param[in] line The line to add. * * @return RC_OK on success. * @return RC_INTERNAL_ERR when given invalid (NULL) line. */ rc_e sf_add_line(source_file_s *source, const char *line); /** * @brief Destructor for the source_file sturcture. * * @param[in,out] source The structure to destroy. */ void sf_destroy(source_file_s *source); /** * @brief Printer for token_types as words * * @param[in] value token value to be printed */ void printer(int value); /** * @brief Printer for token_types as symbols used for error messages. * * @note Only works for tokens that do not have a value (will work for TOKEN_ADD as +, but will not *work for TOKEN_ID) * @param[in] type token type to be printed to stderr. Should be token_type but is unsigned to avoid *cyclic include. */ void err_token_printer(unsigned type); #endif
// // AudioEngine.h // QuNeoDemo // // Created by <NAME> on 8/3/13. // Copyright 2013 __MyCompanyName__. All rights reserved. // #ifndef __AUDIO_ENGINE #define __AUDIO_ENGINE #include "../JuceLibraryCode/JuceHeader.h" #include "Oscillator.h" #include "Pad.h" #include "MenuBarObject.h" #include <iostream> //#include "Oscillator.cpp" class AudioEngine : public AudioSource { public: AudioEngine(); ~AudioEngine(); void prepareToPlay(int samplesPerBlockExpected, double sampleRate); void releaseResources(); void getNextAudioBlock(const AudioSourceChannelInfo& bufferToFill); //Oscillator methods void setLFO(int instance, double freq); void setPitch(int instance, double pitch); Pad* pad[16]; //Synths Synthesiser synth; Synthesiser oscSynth; //Synthesiser looper; float latestMagnitude; MidiBuffer* looperBuffer; void setMidiBuffer(MidiBuffer* bffr); IIRFilterAudioSource* filterSource; void setSamplerFilter(IIRFilterAudioSource* fS); MenuBarObject* menuBarObject; void setMenuBarObject(MenuBarObject *mb); //Filter IIRFilter* filter[2]; //Sample Rate int sR; private: }; #endif // __AUDIO_ENGINE
<reponame>fuchina/FSLocalTempLibrary<gh_stars>0 // // FSBestBZViewController.h // myhome // // Created by FudonFuchina on 2018/7/4. // Copyright © 2018年 fuhope. All rights reserved. // #import "FSBaseController.h" #import "FSBestMobanModel.h" @interface FSBestBZViewController : FSBaseController @property (nonatomic,copy) NSString *table; @property (nonatomic,assign) BOOL editMode; @property (nonatomic,copy) NSString *bz; @property (nonatomic,copy)void (^selectedBZ)(FSBestBZViewController *c,FSBestMobanModel *model); @property (nonatomic,copy)void (^deleteEvent)(FSBestBZViewController *c); @end
/* * This file belongs to the Galois project, a C++ library for exploiting parallelism. * The code is being released under the terms of the 3-Clause BSD License (a * copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ #ifndef GALOIS_UNORDERED_SET_H #define GALOIS_UNORDERED_SET_H #include "galois/substrate/PaddedLock.h" #include "galois/substrate/CompilerSpecific.h" #include <algorithm> #include <unordered_set> #include "galois/Mem.h" namespace galois { /** * Thread-safe unordered set. */ template <typename T> class ThreadSafeUnorderedSet { typedef std::unordered_set<T> Set; public: typedef Set container_type; typedef typename container_type::value_type value_type; typedef typename container_type::reference reference; typedef typename container_type::const_reference const_reference; typedef typename container_type::pointer pointer; typedef typename container_type::size_type size_type; typedef typename container_type::const_iterator iterator; typedef typename container_type::const_iterator const_iterator; typedef galois::substrate::SimpleLock Lock_ty; private: GALOIS_ATTRIBUTE_ALIGN_CACHE_LINE Lock_ty mutex; Set unorderedSet; public: template <typename _T> using retype = ThreadSafeUnorderedSet<_T>; explicit ThreadSafeUnorderedSet() {} template <typename Iter> ThreadSafeUnorderedSet(Iter b, Iter e) { for (; b != e; ++b) { unorderedSet.insert(*b); } } bool empty() const { mutex.lock(); bool ret = unorderedSet.empty(); mutex.unlock(); return ret; } size_type size() const { mutex.lock(); size_type sz = unorderedSet.size(); mutex.unlock(); return sz; } bool find(const value_type& x) const { mutex.lock(); bool ret = (unorderedSet.find(x) != unorderedSet.end()); mutex.unlock(); return ret; } bool push(const value_type& x) { mutex.lock(); auto p = unorderedSet.insert(x); mutex.unlock(); return p.second; } bool remove(const value_type& x) { mutex.lock(); size_type s = unorderedSet.erase(x); bool ret = (s > 0); mutex.unlock(); return ret; } void clear() { mutex.lock(); unorderedSet.clear(); mutex.unlock(); } const_iterator begin() const { return unorderedSet.begin(); } const_iterator end() const { return unorderedSet.end(); } }; } // namespace galois #endif
#pragma once #include "Stream_Base.h" namespace silk { namespace stream { template<Space SPACE_VALUE> class IDistanceT : public ISpatial_Stream<Semantic::DISTANCE, SPACE_VALUE> { public: typedef std::true_type can_be_filtered_t; typedef math::vec3f Value; //meters typedef stream::Sample<Value> Sample; virtual auto get_samples() const -> std::vector<Sample> const& = 0; }; typedef IDistanceT<Space::LOCAL> IDistance; typedef IDistanceT<Space::ENU> IENU_Distance; typedef IDistanceT<Space::ECEF> IECEF_Distance; } }
<reponame>MrRaffo/smallengine #include <stdio.h> #include <string.h> /* * arg * handles all command line argument checking code */ static int argc = 0; static char **argv = NULL; /* * pass the programs argument count and pointer to the arg module */ void arg_init(int arg_count, char **arg_ptr) { argc = arg_count; argv = arg_ptr; } /* * get number of arguments */ int arg_number(void) { return argc; } /* * check if a parameter exists and give its index in the list * returns 0 if parameter not found */ int arg_check(char *arg) { int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], arg) == 0) { return i; } } return 0; } /* * return a pointer to the argument at the given index, NULL on fail */ char *arg_get(int i) { if (i >= 0 && i < argc) { return argv[i]; } return NULL; }
<reponame>ggonei/FNT2 // // <NAME> @ University of York, 2020 // // This file compartmentalises all channels into one and applies a calibration // #ifndef CHANNELS_H #define CHANNELS_H //std libraries #include <cmath> #include <fstream> #include <string> #include <vector> //FNT2 libraries #include "../include/Gate.h" namespace fnt{ // create unique working area class Channel{ // object for channels public: Channel( char c, int n, double p = 0 ){ // default constructor channelNumber = n; // set channel number type = c; // set channel type pixelNumber = p; // set pixel number } // end default constructor ~Channel(){} // destructor void addCalibration( int t, char c, std::vector<double> vc, std::vector<double> ve ); // add calibration( offset, type, energy, efficiency ) void addGate( char c, unsigned long long low, unsigned long long high ); // add gate with ( type, low, high ) double adjE( double e ); // adjust energy with a calibration( energy ) double getPixelNumber(){ return pixelNumber; } // get pixel number char getType(){ return type; } // get detector type int getChannelNumber(){ return channelNumber; } // get channel number int getTOffset(){ return timeOffset; } // get time offset int passes( double e, char t = 'e', bool a = false ); // check if energy is inside gate( energy, type = energy, absolute = false ) double gatesTcover( int bpt ){ double s = 0; for( unsigned int i = 0; i < gates_t.size(); i++ ) s += gates_t[i]->percentage( bpt ); return s; }; Gate *getGate( unsigned long int g, char t = 'e' ){ return ( t == 'e' ? gates_e[g >= gates_e.size() ? 0 : g] : gates_t[g >= gates_t.size() ? 0 : g] ); } // get specific gate private: char type, calType; // detector type, calibration type double pixelNumber; // pixel number int channelNumber, timeOffset; // channel number, offset of channel to reference time std::vector<double> calTerms = {}, effTerms = {}; // calibration, efficiency terms std::vector<std::pair<Gate *, char>> gates_c = {}; // std::vector of coincidence gates applied on detector std::vector<Gate *> gates_e = {}; // std::vector of energy gates applied on detector std::vector<Gate *> gates_t = {}; // std::vector of time gates applied on detector }; } // end namespace fnt #endif
<filename>MC3672.h<gh_stars>1-10 #ifndef MC3672_h #define MC3672_h #include "Arduino.h" #include "Wire.h" /******************************************************************************* *** CONSTANT / DEFINE *******************************************************************************/ #define MC3672_RETCODE_SUCCESS (0) #define MC3672_RETCODE_ERROR_BUS (-1) #define MC3672_RETCODE_ERROR_NULL_POINTER (-2) #define MC3672_RETCODE_ERROR_STATUS (-3) #define MC3672_RETCODE_ERROR_SETUP (-4) #define MC3672_RETCODE_ERROR_GET_DATA (-5) #define MC3672_RETCODE_ERROR_IDENTIFICATION (-6) #define MC3672_RETCODE_ERROR_NO_DATA (-7) #define MC3672_RETCODE_ERROR_WRONG_ARGUMENT (-8) #define MC3672_FIFO_DEPTH 32 #define MC3672_REG_MAP_SIZE 64 /******************************************************************************* *** CONSTANT / DEFINE *******************************************************************************/ //============================================= #define MC3672_INTR_C_IPP_MODE_OPEN_DRAIN (0x00) #define MC3672_INTR_C_IPP_MODE_PUSH_PULL (0x01) #define MC3672_INTR_C_IAH_ACTIVE_LOW (0x00) #define MC3672_INTR_C_IAH_ACTIVE_HIGH (0x02) /******************************************************************************* *** Register Map *******************************************************************************/ //============================================= #define MC3672_REG_EXT_STAT_1 (0x00) #define MC3672_REG_EXT_STAT_2 (0x01) #define MC3672_REG_XOUT_LSB (0x02) #define MC3672_REG_XOUT_MSB (0x03) #define MC3672_REG_YOUT_LSB (0x04) #define MC3672_REG_YOUT_MSB (0x05) #define MC3672_REG_ZOUT_LSB (0x06) #define MC3672_REG_ZOUT_MSB (0x07) #define MC3672_REG_STATUS_1 (0x08) #define MC3672_REG_STATUS_2 (0x09) #define MC3672_REG_MODE_C (0x10) #define MC3672_REG_WAKE_C (0x11) #define MC3672_REG_SNIFF_C (0x12) #define MC3672_REG_SNIFFTH_C (0x13) #define MC3672_REG_SNIFF_CONF_C (0x14) #define MC3672_REG_RANGE_C (0x15) #define MC3672_REG_FIFO_C (0x16) #define MC3672_REG_INTR_C (0x17) #define MC3672_REG_PROD (0x18) #define MC3672_REG_DMX (0x20) #define MC3672_REG_DMY (0x21) #define MC3672_REG_GAIN (0x21) #define MC3672_REG_DMZ (0x22) #define MC3672_REG_RESET (0x24) #define MC3672_REG_XOFFL (0x2A) #define MC3672_REG_XOFFH (0x2B) #define MC3672_REG_YOFFL (0x2C) #define MC3672_REG_YOFFH (0x2D) #define MC3672_REG_ZOFFL (0x2E) #define MC3672_REG_ZOFFH (0x2F) #define MC3672_REG_XGAIN (0x30) #define MC3672_REG_YGAIN (0x31) #define MC3672_REG_ZGAIN (0x32) #define MC3672_REG_OPT (0x3B) #define MC3672_REG_LOC_X (0x3C) #define MC3672_REG_LOC_Y (0x3D) #define MC3672_REG_LOT_dAOFSZ (0x3E) #define MC3672_REG_WAF_LOT (0x3F) #define MC3672_NULL_ADDR (0) struct MC3672_acc_t { short XAxis; short YAxis; short ZAxis; float XAxis_g; float YAxis_g; float ZAxis_g; } ; typedef enum { MC3672_MODE_SLEEP = 0b000, MC3672_MODE_STANDBY = 0b001, MC3672_MODE_SNIFF = 0b010, MC3672_MODE_CWAKE = 0b101, MC3672_MODE_TRIG = 0b111, } MC3672_mode_t; typedef enum { MC3672_RANGE_2G = 0b000, MC3672_RANGE_4G = 0b001, MC3672_RANGE_8G = 0b010, MC3672_RANGE_16G = 0b011, MC3672_RANGE_12G = 0b100, MC3672_RANGE_END, } MC3672_range_t; typedef enum { MC3672_RESOLUTION_6BIT = 0b000, MC3672_RESOLUTION_7BIT = 0b001, MC3672_RESOLUTION_8BIT = 0b010, MC3672_RESOLUTION_10BIT = 0b011, MC3672_RESOLUTION_12BIT = 0b100, MC3672_RESOLUTION_14BIT = 0b101, //(Do not select if FIFO enabled) MC3672_RESOLUTION_END, } MC3672_resolution_t; typedef enum { MC3672_CWAKE_SR_DEFAULT_54Hz = 0b0000, MC3672_CWAKE_SR_14Hz = 0b0101, MC3672_CWAKE_SR_28Hz = 0b0110, MC3672_CWAKE_SR_54Hz = 0b0111, MC3672_CWAKE_SR_105Hz = 0b1000, MC3672_CWAKE_SR_210Hz = 0b1001, MC3672_CWAKE_SR_400Hz = 0b1010, MC3672_CWAKE_SR_600Hz = 0b1011, MC3672_CWAKE_SR_END, } MC3672_cwake_sr_t; typedef enum { MC3672_SNIFF_SR_DEFAULT_7Hz = 0b0000, MC3672_SNIFF_SR_0p4Hz = 0b0001, MC3672_SNIFF_SR_0p8Hz = 0b0010, MC3672_SNIFF_SR_1p5Hz = 0b0011, MC3672_SNIFF_SR_7Hz = 0b0100, MC3672_SNIFF_SR_14Hz = 0b0101, MC3672_SNIFF_SR_28Hz = 0b0110, MC3672_SNIFF_SR_54Hz = 0b0111, MC3672_SNIFF_SR_105Hz = 0b1000, MC3672_SNIFF_SR_210Hz = 0b1001, MC3672_SNIFF_SR_400Hz = 0b1010, MC3672_SNIFF_SR_600Hz = 0b1011, MC3672_SNIFF_SR_END, } MC3672_sniff_sr_t; typedef enum { MC3672_FIFO_CONTROL_DISABLE = 0, MC3672_FIFO_CONTROL_ENABLE, MC3672_FIFO_CONTROL_END, } MC3672_fifo_control_t; typedef enum { MC3672_FIFO_MODE_NORMAL = 0, MC3672_FIFO_MODE_WATERMARK, MC3672_FIFO_MODE_END, } MC3672_fifo_mode_t; typedef struct { unsigned char bWAKE; // Sensor wakes from sniff mode. unsigned char bACQ; // New sample is ready and acquired. unsigned char bFIFO_EMPTY; // FIFO is empty. unsigned char bFIFO_FULL; // FIFO is full. unsigned char bFIFO_THRESHOLD; // FIFO sample count is equal to or greater than the threshold count. unsigned char bRESV; unsigned char baPadding[2]; } MC3672_InterruptEvent; class MC3672{ public: /* general accel methods */ bool start(); // begin measurements void stop(); // end measurments void reset(); void SetMode(MC3672_mode_t); void SetRangeCtrl(MC3672_range_t); void SetResolutionCtrl(MC3672_resolution_t); void SetCWakeSampleRate(MC3672_cwake_sr_t); MC3672_resolution_t GetResolutionCtrl(void); MC3672_range_t GetRangeCtrl(void); MC3672_cwake_sr_t GetCWakeSampleRate(void); MC3672_acc_t readRawAccel(void); private: short x, y, z; MC3672_acc_t AccRaw; // Raw Accelerometer data uint8_t readRegister8(uint8_t reg); int16_t readRegister16(uint8_t reg); void readRegisters(uint8_t reg, byte *buffer, uint8_t len); bool readRegisterBit(uint8_t reg, uint8_t pos); void writeRegisterBit(uint8_t reg, uint8_t pos, bool state); void writeRegister16(uint8_t reg, int16_t value); void writeRegister8(uint8_t reg, uint8_t value); }; #endif
<filename>ArtNetControllerApp/src/net.h #ifndef NET_H_ #define NET_H_ #include <stdint.h> #include <stdbool.h> #include <stddef.h> #include "memory.h" #include "uip.h" typedef enum { NET_EVENT_START_DHCP = 0x01u, NET_EVENT_STOP_DHCP = 0x02u, NET_EVENT_LINK_UP = 0x04u, NET_EVENT_LINK_DOWN = 0x08u, }tNetworkEvent; typedef enum { NET_STATE_DHCP_IS_ON = 0x01u, NET_STATE_DHCP_IS_ACTIVE = 0x02u, NET_STATE_DHCP_CONFIG_RECEIVED = 0x04u, NET_STATE_LINK_IS_OK = 0x08u, }tNetworkStatus; typedef struct { uip_ip4addr_t ipAddress; uip_ip4addr_t subnetmask; uip_ip4addr_t defaultRouter; }tNetworkParams; typedef struct uip_eth_addr tEthernetAddress; void initNetwork(void); void processNetwork(void); void setNetworkEvent(tNetworkEvent event); tNetworkStatus getNetworkStatus(void); bool setNetworkParams(const tNetworkParams *params); void getNetworkParams(tNetworkParams *params); bool setEthernetAddress(const tEthernetAddress *eth); void getEthernetAddress(tEthernetAddress *eth); #endif /* NETWORK_H_ */
<filename>NFComm/NFNoSqlPlugin/NFCNoSqlDriverManager.h // ------------------------------------------------------------------------- // @FileName : NFCNoSqlDriverManager.h // @Author : LvSheng.Huang // @Date : 2017-01-13 // @Module : NFCNoSqlDriverManager // // ------------------------------------------------------------------------- #ifndef NFC_NOSQL_DRIVER_MANAGER_H #define NFC_NOSQL_DRIVER_MANAGER_H #include "NFCNoSqlDriver.h" #include "NFComm/NFPluginModule/NFPlatform.h" #include "NFComm/NFPluginModule/NFIPluginManager.h" #include "NFComm/NFPluginModule/NFINoSqlDriverManager.h" #include "NFComm/NFPluginModule/NFIClassModule.h" #include "NFComm/NFPluginModule/NFIElementModule.h" #include "NFComm/NFPluginModule/NFILogModule.h" class NFCNoSqlDriverManager : public NFINoSqlDriverManager { public: NFCNoSqlDriverManager(); virtual ~NFCNoSqlDriverManager(); virtual bool Init(); virtual bool Shut(); virtual bool Execute(); virtual bool AfterInit(); protected: NFINT64 mLastCheckTime; NFCConsistentHashMapEx<std::string, NFINoSqlDriver> mxNoSqlDriver; }; #endif
// // GTDiffDelta.h // ObjectiveGitFramework // // Created by <NAME> on 30/11/2012. // Copyright (c) 2012 GitHub, Inc. All rights reserved. // #import "git2.h" @class GTDiffFile; @class GTDiffHunk; // The type of change that this delta represents. // // GTDiffFileDeltaUnmodified - No Change. // GTDiffFileDeltaAdded - The file was added to the index. // GTDiffFileDeltaDeleted - The file was removed from the working directory. // GTDiffFileDeltaModified - The file was modified. // GTDiffFileDeltaRenamed - The file has been renamed. // GTDiffFileDeltaCopied - The file was duplicated. // GTDiffFileDeltaIgnored - The file was ignored by git. // GTDiffFileDeltaUntracked - The file has been added to the working directory // and is therefore currently untracked. // GTDiffFileDeltaTypeChange - The file has changed from a blob to either a // submodule, symlink or directory. Or vice versa. typedef enum { GTDiffFileDeltaUnmodified = GIT_DELTA_UNMODIFIED, GTDiffFileDeltaAdded = GIT_DELTA_ADDED, GTDiffFileDeltaDeleted = GIT_DELTA_DELETED, GTDiffFileDeltaModified = GIT_DELTA_MODIFIED, GTDiffFileDeltaRenamed = GIT_DELTA_RENAMED, GTDiffFileDeltaCopied = GIT_DELTA_COPIED, GTDiffFileDeltaIgnored = GIT_DELTA_IGNORED, GTDiffFileDeltaUntracked = GIT_DELTA_UNTRACKED, GTDiffFileDeltaTypeChange = GIT_DELTA_TYPECHANGE, } GTDiffDeltaType; // A class representing a single change within a diff. // // The change may not be simply a change of text within a given file, it could // be that the file was renamed, or added to the index. See `GTDiffDeltaType` // for the types of change represented. @interface GTDiffDelta : NSObject // The backing libgit2 `git_diff_patch` object. @property (nonatomic, readonly) git_diff_patch *git_diff_patch; // Whether the file(s) are to be treated as binary. @property (nonatomic, readonly, getter = isBinary) BOOL binary; // The file to the "left" of the diff. @property (nonatomic, readonly, copy) GTDiffFile *oldFile; // The file to the "right" of the diff. @property (nonatomic, readonly, copy) GTDiffFile *newFile __attribute__((ns_returns_not_retained)); // The type of change that this delta represents. // // Think "status" as in `git status`. @property (nonatomic, readonly) GTDiffDeltaType type; // The number of hunks represented by this delta. @property (nonatomic, readonly) NSUInteger hunkCount; // The number of added lines in this delta. // // Undefined if this delta is binary. @property (nonatomic, readonly) NSUInteger addedLinesCount; // The number of deleted lines in this delta. // // Undefined if this delta is binary. @property (nonatomic, readonly) NSUInteger deletedLinesCount; // The number of context lines in this delta. // // Undefined if this delta is binary. @property (nonatomic, readonly) NSUInteger contextLinesCount; // Designated initialiser. - (instancetype)initWithGitPatch:(git_diff_patch *)patch; // A convenience accessor to fetch the `git_diff_delta` represented by the // object. - (const git_diff_delta *)git_diff_delta __attribute__((objc_returns_inner_pointer)); // Enumerate the hunks contained in the delta. // // Blocks during enumeration. // // block - A block to be executed for each hunk. Setting `stop` to `YES` // immediately stops the enumeration. - (void)enumerateHunksWithBlock:(void (^)(GTDiffHunk *hunk, BOOL *stop))block; @end
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "attribute_collection_spec.h" #include <vespa/searchcommon/attribute/config.h> #include <vespa/searchcore/proton/common/alloc_strategy.h> #include <vespa/searchlib/common/serialnum.h> #include <vespa/config-attributes.h> namespace proton { /** * A factory for generating an AttributeCollectionSpec based on AttributesConfig * from the config server. */ class AttributeCollectionSpecFactory { private: typedef vespa::config::search::AttributesConfig AttributesConfig; const AllocStrategy _alloc_strategy; const bool _fastAccessOnly; public: AttributeCollectionSpecFactory(const AllocStrategy& alloc_strategy, bool fastAccessOnly); AttributeCollectionSpec::UP create(const AttributesConfig &attrCfg, uint32_t docIdLimit, search::SerialNum serialNum) const; }; } // namespace proton
#pragma once #include "xrUICore/Static/UIStatic.h" class XRUICORE_API UI_Arrow : public CUIStatic { private: typedef CUIStatic inherited; public: UI_Arrow(); virtual ~UI_Arrow(); void init_from_xml(CUIXml& xml, LPCSTR path, CUIWindow* parent); void SetNewValue(float new_value); void SetPos(float pos); IC float GetPos() { return m_pos; } private: float m_angle_begin; float m_angle_end; float m_ang_velocity; float m_angle_range; float m_temp_pos; float m_pos; }; // class UI_Arrow
<reponame>ecarnevale/HTMLKit<filename>Sources/include/HTMLKitErrorDomain.h // // HTMLKitErrorDomain.h // HTMLKit // // Created by Iska on 24/11/15. // Copyright © 2015 BrainCookie. All rights reserved. // #ifndef HTMLKitErrorDomain_h #define HTMLKitErrorDomain_h static NSString *const HTMLKitErrorDomain = @"HTMLKit"; static NSString *const HTMLKitSelectorErrorDomain = @"HTMLKitSelector"; static NSString *const CSSSelectorStringKey = @"CSSSelectorString"; static NSString *const CSSSelectorErrorLocationKey = @"CSSSelectorErrorLocation"; NS_ENUM(NSInteger) { HTMLKitSelectorParseError = 4200 }; #endif /* HTMLKitErrorDomain_h */
<reponame>best08618/asylo // { dg-do compile } /* { dg-skip-if "" { powerpc*-*-aix* } { "*" } { "" } } */ // { dg-options "-O2 -mpowerpc64" } // { dg-final { scan-assembler-not "stfd" } } // The register allocator should have allocated the temporary long long value in a floating point register. double d2ll2d (double d) { return (double)(long long)d; }
<reponame>Sunrisepeak/Linux2.6-Reading // SPDX-License-Identifier: GPL-2.0-only // // motu-register-dsp-message-parser.c - a part of driver for MOTU FireWire series // // Copyright (c) 2021 <NAME> <<EMAIL>> // Below models allow software to configure their DSP functions by asynchronous transaction // to access their internal registers. // * 828 mk2 // * 896hd // * Traveler // * 8 pre // * Ultralite // * 4 pre // * Audio Express // // Additionally, isochronous packets from the above models include messages to notify state of // DSP. The messages are two set of 3 byte data in 2nd and 3rd quadlet of data block. When user // operates hardware components such as dial and switch, corresponding messages are transferred. // The messages include Hardware metering and MIDI messages as well. #include "motu.h" #define MSG_FLAG_POS 4 #define MSG_FLAG_TYPE_MASK 0xf8 #define MSG_FLAG_MIDI_MASK 0x01 #define MSG_FLAG_MODEL_SPECIFIC_MASK 0x06 #define MSG_FLAG_8PRE 0x00 #define MSG_FLAG_ULTRALITE 0x04 #define MSG_FLAG_TRAVELER 0x04 #define MSG_FLAG_828MK2 0x04 #define MSG_FLAG_896HD 0x04 #define MSG_FLAG_4PRE 0x05 // MIDI mask is in 8th byte. #define MSG_FLAG_AUDIOEXPRESS 0x05 // MIDI mask is in 8th byte. #define MSG_FLAG_TYPE_SHIFT 3 #define MSG_VALUE_POS 5 #define MSG_MIDI_BYTE_POS 6 #define MSG_METER_IDX_POS 7 // In 4 pre and Audio express, meter index is in 6th byte. MIDI flag is in 8th byte and MIDI byte // is in 7th byte. #define MSG_METER_IDX_POS_4PRE_AE 6 #define MSG_MIDI_BYTE_POS_4PRE_AE 7 #define MSG_FLAG_MIDI_POS_4PRE_AE 8 enum register_dsp_msg_type { // Used for messages with no information. INVALID = 0x00, MIXER_SELECT = 0x01, MIXER_SRC_GAIN = 0x02, MIXER_SRC_PAN = 0x03, MIXER_SRC_FLAG = 0x04, MIXER_OUTPUT_PAIRED_VOLUME = 0x05, MIXER_OUTPUT_PAIRED_FLAG = 0x06, MAIN_OUTPUT_PAIRED_VOLUME = 0x07, HP_OUTPUT_PAIRED_VOLUME = 0x08, HP_OUTPUT_PAIRED_ASSIGNMENT = 0x09, // Transferred by all models but the purpose is still unknown. UNKNOWN_0 = 0x0a, // Specific to 828mk2, 896hd, Traveler. UNKNOWN_2 = 0x0c, // Specific to 828mk2, Traveler, and 896hd (not functional). LINE_INPUT_BOOST = 0x0d, // Specific to 828mk2, Traveler, and 896hd (not functional). LINE_INPUT_NOMINAL_LEVEL = 0x0e, // Specific to Ultralite, 4 pre, Audio express, and 8 pre (not functional). INPUT_GAIN_AND_INVERT = 0x15, // Specific to 4 pre, and Audio express. INPUT_FLAG = 0x16, // Specific to 4 pre, and Audio express. MIXER_SRC_PAIRED_BALANCE = 0x17, // Specific to 4 pre, and Audio express. MIXER_SRC_PAIRED_WIDTH = 0x18, // Transferred by all models. This type of message interposes the series of the other // messages. The message delivers signal level up to 96.0 kHz. In 828mk2, 896hd, and // Traveler, one of physical outputs is selected for the message. The selection is done // by LSB one byte in asynchronous write quadlet transaction to 0x'ffff'f000'0b2c. METER = 0x1f, }; #define EVENT_QUEUE_SIZE 16 struct msg_parser { spinlock_t lock; struct snd_firewire_motu_register_dsp_meter meter; bool meter_pos_quirk; struct snd_firewire_motu_register_dsp_parameter param; u8 prev_mixer_src_type; u8 mixer_ch; u8 mixer_src_ch; u8 input_ch; u8 prev_msg_type; u32 event_queue[EVENT_QUEUE_SIZE]; unsigned int push_pos; unsigned int pull_pos; }; int snd_motu_register_dsp_message_parser_new(struct snd_motu *motu) { struct msg_parser *parser; parser = devm_kzalloc(&motu->card->card_dev, sizeof(*parser), GFP_KERNEL); if (!parser) return -ENOMEM; spin_lock_init(&parser->lock); if (motu->spec == &snd_motu_spec_4pre || motu->spec == &snd_motu_spec_audio_express) parser->meter_pos_quirk = true; motu->message_parser = parser; return 0; } int snd_motu_register_dsp_message_parser_init(struct snd_motu *motu) { struct msg_parser *parser = motu->message_parser; parser->prev_mixer_src_type = INVALID; parser->mixer_ch = 0xff; parser->mixer_src_ch = 0xff; parser->prev_msg_type = INVALID; return 0; } // Rough implementaion of queue without overrun check. static void queue_event(struct snd_motu *motu, u8 msg_type, u8 identifier0, u8 identifier1, u8 val) { struct msg_parser *parser = motu->message_parser; unsigned int pos = parser->push_pos; u32 entry; if (!motu->hwdep || motu->hwdep->used == 0) return; entry = (msg_type << 24) | (identifier0 << 16) | (identifier1 << 8) | val; parser->event_queue[pos] = entry; ++pos; if (pos >= EVENT_QUEUE_SIZE) pos = 0; parser->push_pos = pos; } void snd_motu_register_dsp_message_parser_parse(struct snd_motu *motu, const struct pkt_desc *descs, unsigned int desc_count, unsigned int data_block_quadlets) { struct msg_parser *parser = motu->message_parser; bool meter_pos_quirk = parser->meter_pos_quirk; unsigned int pos = parser->push_pos; unsigned long flags; int i; spin_lock_irqsave(&parser->lock, flags); for (i = 0; i < desc_count; ++i) { const struct pkt_desc *desc = descs + i; __be32 *buffer = desc->ctx_payload; unsigned int data_blocks = desc->data_blocks; int j; for (j = 0; j < data_blocks; ++j) { u8 *b = (u8 *)buffer; u8 msg_type = (b[MSG_FLAG_POS] & MSG_FLAG_TYPE_MASK) >> MSG_FLAG_TYPE_SHIFT; u8 val = b[MSG_VALUE_POS]; buffer += data_block_quadlets; switch (msg_type) { case MIXER_SELECT: { u8 mixer_ch = val / 0x20; if (mixer_ch < SNDRV_FIREWIRE_MOTU_REGISTER_DSP_MIXER_COUNT) { parser->mixer_src_ch = 0; parser->mixer_ch = mixer_ch; } break; } case MIXER_SRC_GAIN: case MIXER_SRC_PAN: case MIXER_SRC_FLAG: case MIXER_SRC_PAIRED_BALANCE: case MIXER_SRC_PAIRED_WIDTH: { struct snd_firewire_motu_register_dsp_parameter *param = &parser->param; u8 mixer_ch = parser->mixer_ch; u8 mixer_src_ch = parser->mixer_src_ch; if (msg_type != parser->prev_mixer_src_type) mixer_src_ch = 0; else ++mixer_src_ch; parser->prev_mixer_src_type = msg_type; if (mixer_ch < SNDRV_FIREWIRE_MOTU_REGISTER_DSP_MIXER_COUNT && mixer_src_ch < SNDRV_FIREWIRE_MOTU_REGISTER_DSP_MIXER_SRC_COUNT) { u8 mixer_ch = parser->mixer_ch; switch (msg_type) { case MIXER_SRC_GAIN: if (param->mixer.source[mixer_ch].gain[mixer_src_ch] != val) { queue_event(motu, msg_type, mixer_ch, mixer_src_ch, val); param->mixer.source[mixer_ch].gain[mixer_src_ch] = val; } break; case MIXER_SRC_PAN: if (param->mixer.source[mixer_ch].pan[mixer_src_ch] != val) { queue_event(motu, msg_type, mixer_ch, mixer_src_ch, val); param->mixer.source[mixer_ch].pan[mixer_src_ch] = val; } break; case MIXER_SRC_FLAG: if (param->mixer.source[mixer_ch].flag[mixer_src_ch] != val) { queue_event(motu, msg_type, mixer_ch, mixer_src_ch, val); param->mixer.source[mixer_ch].flag[mixer_src_ch] = val; } break; case MIXER_SRC_PAIRED_BALANCE: if (param->mixer.source[mixer_ch].paired_balance[mixer_src_ch] != val) { queue_event(motu, msg_type, mixer_ch, mixer_src_ch, val); param->mixer.source[mixer_ch].paired_balance[mixer_src_ch] = val; } break; case MIXER_SRC_PAIRED_WIDTH: if (param->mixer.source[mixer_ch].paired_width[mixer_src_ch] != val) { queue_event(motu, msg_type, mixer_ch, mixer_src_ch, val); param->mixer.source[mixer_ch].paired_width[mixer_src_ch] = val; } break; default: break; } parser->mixer_src_ch = mixer_src_ch; } break; } case MIXER_OUTPUT_PAIRED_VOLUME: case MIXER_OUTPUT_PAIRED_FLAG: { struct snd_firewire_motu_register_dsp_parameter *param = &parser->param; u8 mixer_ch = parser->mixer_ch; if (mixer_ch < SNDRV_FIREWIRE_MOTU_REGISTER_DSP_MIXER_COUNT) { switch (msg_type) { case MIXER_OUTPUT_PAIRED_VOLUME: if (param->mixer.output.paired_volume[mixer_ch] != val) { queue_event(motu, msg_type, mixer_ch, 0, val); param->mixer.output.paired_volume[mixer_ch] = val; } break; case MIXER_OUTPUT_PAIRED_FLAG: if (param->mixer.output.paired_flag[mixer_ch] != val) { queue_event(motu, msg_type, mixer_ch, 0, val); param->mixer.output.paired_flag[mixer_ch] = val; } break; default: break; } } break; } case MAIN_OUTPUT_PAIRED_VOLUME: if (parser->param.output.main_paired_volume != val) { queue_event(motu, msg_type, 0, 0, val); parser->param.output.main_paired_volume = val; } break; case HP_OUTPUT_PAIRED_VOLUME: if (parser->param.output.hp_paired_volume != val) { queue_event(motu, msg_type, 0, 0, val); parser->param.output.hp_paired_volume = val; } break; case HP_OUTPUT_PAIRED_ASSIGNMENT: if (parser->param.output.hp_paired_assignment != val) { queue_event(motu, msg_type, 0, 0, val); parser->param.output.hp_paired_assignment = val; } break; case LINE_INPUT_BOOST: if (parser->param.line_input.boost_flag != val) { queue_event(motu, msg_type, 0, 0, val); parser->param.line_input.boost_flag = val; } break; case LINE_INPUT_NOMINAL_LEVEL: if (parser->param.line_input.nominal_level_flag != val) { queue_event(motu, msg_type, 0, 0, val); parser->param.line_input.nominal_level_flag = val; } break; case INPUT_GAIN_AND_INVERT: case INPUT_FLAG: { struct snd_firewire_motu_register_dsp_parameter *param = &parser->param; u8 input_ch = parser->input_ch; if (parser->prev_msg_type != msg_type) input_ch = 0; else ++input_ch; if (input_ch < SNDRV_FIREWIRE_MOTU_REGISTER_DSP_INPUT_COUNT) { switch (msg_type) { case INPUT_GAIN_AND_INVERT: if (param->input.gain_and_invert[input_ch] != val) { queue_event(motu, msg_type, input_ch, 0, val); param->input.gain_and_invert[input_ch] = val; } break; case INPUT_FLAG: if (param->input.flag[input_ch] != val) { queue_event(motu, msg_type, input_ch, 0, val); param->input.flag[input_ch] = val; } break; default: break; } parser->input_ch = input_ch; } break; } case UNKNOWN_0: case UNKNOWN_2: break; case METER: { u8 pos; if (!meter_pos_quirk) pos = b[MSG_METER_IDX_POS]; else pos = b[MSG_METER_IDX_POS_4PRE_AE]; if (pos < SNDRV_FIREWIRE_MOTU_REGISTER_DSP_METER_INPUT_COUNT) { parser->meter.data[pos] = val; } else if (pos >= 0x80) { pos -= (0x80 - SNDRV_FIREWIRE_MOTU_REGISTER_DSP_METER_INPUT_COUNT); if (pos < SNDRV_FIREWIRE_MOTU_REGISTER_DSP_METER_COUNT) parser->meter.data[pos] = val; } // The message for meter is interruptible to the series of other // types of messages. Don't cache it. fallthrough; } case INVALID: default: // Don't cache it. continue; } parser->prev_msg_type = msg_type; } } if (pos != parser->push_pos) wake_up(&motu->hwdep_wait); spin_unlock_irqrestore(&parser->lock, flags); } void snd_motu_register_dsp_message_parser_copy_meter(struct snd_motu *motu, struct snd_firewire_motu_register_dsp_meter *meter) { struct msg_parser *parser = motu->message_parser; unsigned long flags; spin_lock_irqsave(&parser->lock, flags); memcpy(meter, &parser->meter, sizeof(*meter)); spin_unlock_irqrestore(&parser->lock, flags); } void snd_motu_register_dsp_message_parser_copy_parameter(struct snd_motu *motu, struct snd_firewire_motu_register_dsp_parameter *param) { struct msg_parser *parser = motu->message_parser; unsigned long flags; spin_lock_irqsave(&parser->lock, flags); memcpy(param, &parser->param, sizeof(*param)); spin_unlock_irqrestore(&parser->lock, flags); } unsigned int snd_motu_register_dsp_message_parser_count_event(struct snd_motu *motu) { struct msg_parser *parser = motu->message_parser; if (parser->pull_pos > parser->push_pos) return EVENT_QUEUE_SIZE - parser->pull_pos + parser->push_pos; else return parser->push_pos - parser->pull_pos; } bool snd_motu_register_dsp_message_parser_copy_event(struct snd_motu *motu, u32 *event) { struct msg_parser *parser = motu->message_parser; unsigned int pos = parser->pull_pos; unsigned long flags; if (pos == parser->push_pos) return false; spin_lock_irqsave(&parser->lock, flags); *event = parser->event_queue[pos]; ++pos; if (pos >= EVENT_QUEUE_SIZE) pos = 0; parser->pull_pos = pos; spin_unlock_irqrestore(&parser->lock, flags); return true; }
/* * Copyright (c) 2005-2012 by KoanLogic s.r.l. <http://www.koanlogic.com> * All rights reserved. * * This file is part of KLone, and as such it is subject to the license stated * in the LICENSE file which you have received as part of this distribution. * * $Id: hookprv.h,v 1.1 2007/09/04 12:15:16 tat Exp $ */ #ifndef _KLONE_HOOK_PRV_H_ #define _KLONE_HOOK_PRV_H_ #include <klone/hook.h> #ifdef __cplusplus extern "C" { #endif #ifndef ENABLE_HOOKS #define hook_call( func, ... ) #else #define hook_call( func, ... ) \ do { if(ctx && ctx->hook && ctx->hook->func) \ ctx->hook->func( __VA_ARGS__ ); \ } while(0) struct hook_s { /* server hooks function pointers */ hook_server_init_t server_init; hook_server_term_t server_term; /* children hooks */ hook_child_init_t child_init; hook_child_term_t child_term; /* per-connection hook */ hook_request_t request; /* server loop hook */ hook_server_loop_t server_loop; }; #endif /* ENABLE_HOOKS */ #ifdef __cplusplus } #endif #endif
<reponame>anrl/JAMSamples int myid = -1; int getid(); void pingj(int num); jasync doping() { if (myid > 0) pingj(myid); } int main() { printf("Started...\n"); myid = getid(); }
<reponame>rhcad/vglite // LargeView1.h // Copyright (c) 2012-2013, https://github.com/rhcad/touchvg #import <UIKit/UIKit.h> @class GraphView1; @interface LargeView1 : UIScrollView<UIScrollViewDelegate> { GraphView1 *_subview; } - (id)initWithFrame:(CGRect)frame withFlags:(int)t; @end
// EMFeedbackManager.h // Emax_DebugKit_Example // // Created by HCC on 2019/3/8. // Copyright © 2019 chen0108_mbp. All rights reserved. // 不是即时通讯!! // 使用第三方云服务存取反馈消息,app进入前台时主动查询回复消息,暂时只保留最近的1条回复消息 #import <Foundation/Foundation.h> @interface EMFeedbackMessage : NSObject @property(nonatomic, copy ) NSString *messageId; @property(nonatomic, copy ) NSString *content; @property(nonatomic, strong) NSDate *date; - (NSString *)dateString; @end typedef void (^NewMessageHandler)(EMFeedbackMessage *message); @interface EMFeedbackManager : NSObject /// 初始化 + (void)setupAppID:(NSString *)appid appKey:(NSString *)appkey; + (void)setupDefaultAppIdKey; /// 有新消息时是否弹框,弹框配置 + (void)setEnableAlert:(BOOL)anableAlert titleAttribute:(NSDictionary<NSAttributedStringKey, id> *)titleAtt textAttribute:(NSDictionary<NSAttributedStringKey, id> *)textAtt; /// 获取本地最新的回复消息 + (EMFeedbackMessage *)getLastLocalMessage; /// 获取本地所有消息 + (NSDictionary *)getAllLocalMessage; /// 发送反馈消息 + (void)sendMessage:(NSString *)message content:(NSString *)ctent contact:(NSString *)contact; /// 如果有需要,调用这个方法请求最新回复数据 + (void)updateLastReplyMessage; /// 有新消息时的回调 + (void)didReceiveNewMessageHandle:(NewMessageHandler)handler; @end
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE 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) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file for memory management utilities * * The abstract memory model has a Host (think CPU) and a Device (think GPU) and * three basic types of memory management utilities: * * 1. Malloc(..., location) * location=LOCATION_DEVICE - malloc memory on the device * location=LOCATION_HOST - malloc memory on the host * 2. MemCopy(..., method) * method=HOST_TO_DEVICE - copy from host to device * method=DEVICE_TO_HOST - copy from device to host * method=DEVICE_TO_DEVICE - copy from device to device * 3. SetExecutionMode * location=LOCATION_DEVICE - execute on the device * location=LOCATION_HOST - execute on the host * * Although the abstract model does not explicitly reflect a managed memory * model (i.e., unified memory), it can support it. Here is a summary of how * the abstract model would be mapped to specific hardware scenarios: * * Not using a device, not using managed memory * Malloc(..., location) * location=LOCATION_DEVICE - host malloc e.g., malloc * location=LOCATION_HOST - host malloc e.g., malloc * MemoryCopy(..., locTo,locFrom) * locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from host to host e.g., memcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to host e.g., memcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from host to host e.g., memcpy * SetExecutionMode * location=LOCATION_DEVICE - execute on the host * location=LOCATION_HOST - execute on the host * * Using a device, not using managed memory * Malloc(..., location) * location=LOCATION_DEVICE - device malloc e.g., cudaMalloc * location=LOCATION_HOST - host malloc e.g., malloc * MemoryCopy(..., locTo,locFrom) * locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from device to host e.g., cudaMemcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to device e.g., cudaMemcpy * locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from device to device e.g., cudaMemcpy * SetExecutionMode * location=LOCATION_DEVICE - execute on the device * location=LOCATION_HOST - execute on the host * * Using a device, using managed memory * Malloc(..., location) * location=LOCATION_DEVICE - managed malloc e.g., cudaMallocManaged * location=LOCATION_HOST - host malloc e.g., malloc * MemoryCopy(..., locTo,locFrom) * locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from device to host e.g., cudaMallocManaged * locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to device e.g., cudaMallocManaged * locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from device to device e.g., cudaMallocManaged * SetExecutionMode * location=LOCATION_DEVICE - execute on the device * location=LOCATION_HOST - execute on the host * * Questions: * * 1. prefetch? * *****************************************************************************/ #ifndef hypre_MEMORY_HEADER #define hypre_MEMORY_HEADER #include <stdio.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif #define HYPRE_MEMORY_UNSET (-1) #define HYPRE_MEMORY_DEVICE ( 0) #define HYPRE_MEMORY_HOST ( 1) #define HYPRE_MEMORY_SHARED ( 2) #define HYPRE_MEMORY_HOST_PINNED ( 3) /*================================================================== * default def of memory location selected based memory env * +-------------------------------------------------------------+ * | | HYPRE_MEMORY_* | * | MEM \ LOC | HOST | DEVICE | SHARED | PINNED | * |---------------------------+---------------+-----------------| * | HYPRE_USING_HOST_MEMORY | HOST | HOST | HOST | HOST | * |---------------------------+---------------+-------- --------| * | HYPRE_USING_DEVICE_MEMORY | HOST | DEVICE | DEVICE | PINNED | * |---------------------------+---------------+-----------------| * | HYPRE_USING_UNIFIED_MEMORY| HOST | DEVICE | SHARED | PINNED | * +-------------------------------------------------------------+ *==================================================================*/ #if defined(HYPRE_USING_HOST_MEMORY) /* default memory model without device (host only) */ #define HYPRE_MEMORY_HOST_ACT HYPRE_MEMORY_HOST #define HYPRE_MEMORY_DEVICE_ACT HYPRE_MEMORY_HOST #define HYPRE_MEMORY_SHARED_ACT HYPRE_MEMORY_HOST #define HYPRE_MEMORY_HOST_PINNED_ACT HYPRE_MEMORY_HOST #elif defined(HYPRE_USING_DEVICE_MEMORY) /* default memory model with device and without unified memory */ #define HYPRE_MEMORY_HOST_ACT HYPRE_MEMORY_HOST #define HYPRE_MEMORY_DEVICE_ACT HYPRE_MEMORY_DEVICE #define HYPRE_MEMORY_SHARED_ACT HYPRE_MEMORY_DEVICE #define HYPRE_MEMORY_HOST_PINNED_ACT HYPRE_MEMORY_HOST_PINNED #elif defined(HYPRE_USING_UNIFIED_MEMORY) /* default memory model with device and with unified memory */ #define HYPRE_MEMORY_HOST_ACT HYPRE_MEMORY_HOST #define HYPRE_MEMORY_DEVICE_ACT HYPRE_MEMORY_DEVICE #define HYPRE_MEMORY_SHARED_ACT HYPRE_MEMORY_SHARED #define HYPRE_MEMORY_HOST_PINNED_ACT HYPRE_MEMORY_HOST_PINNED #else /* default */ #define HYPRE_MEMORY_HOST_ACT HYPRE_MEMORY_HOST #define HYPRE_MEMORY_DEVICE_ACT HYPRE_MEMORY_HOST #define HYPRE_MEMORY_SHARED_ACT HYPRE_MEMORY_HOST #define HYPRE_MEMORY_HOST_PINNED_ACT HYPRE_MEMORY_HOST #endif /* the above definitions might be overridden to customize a memory location */ /* #undef HYPRE_MEMORY_HOST_ACT */ /* #undef HYPRE_MEMORY_DEVICE_ACT */ /* #undef HYPRE_MEMORY_SHARED_ACT */ /* #undef HYPRE_MEMORY_PINNED_ACT */ /* #define HYPRE_MEMORY_HOST_ACT HYPRE_MEMORY_? */ /* #define HYPRE_MEMORY_DEVICE_ACT HYPRE_MEMORY_? */ /* #define HYPRE_MEMORY_SHARED_ACT HYPRE_MEMORY_? */ /* #define HYPRE_MEMORY_PINNED_ACT HYPRE_MEMORY_? */ #define HYPRE_MEM_PAD_LEN 1 /* #if defined(HYPRE_USING_CUDA) #define HYPRE_CUDA_GLOBAL __host__ __device__ #else #define HYPRE_CUDA_GLOBAL #endif */ /* OpenMP 4.5 */ #if defined(HYPRE_USING_DEVICE_OPENMP) #include "omp.h" /* stringification: * _Pragma(string-literal), so we need to cast argument to a string * The three dots as last argument of the macro tells compiler that this is a variadic macro. * I.e. this is a macro that receives variable number of arguments. */ #define HYPRE_STR(s...) #s #define HYPRE_XSTR(s...) HYPRE_STR(s) /* OpenMP 4.5 device memory management */ extern HYPRE_Int hypre__global_offload; extern HYPRE_Int hypre__offload_device_num; extern HYPRE_Int hypre__offload_host_num; /* stats */ extern size_t hypre__target_allc_count; extern size_t hypre__target_free_count; extern size_t hypre__target_allc_bytes; extern size_t hypre__target_free_bytes; extern size_t hypre__target_htod_count; extern size_t hypre__target_dtoh_count; extern size_t hypre__target_htod_bytes; extern size_t hypre__target_dtoh_bytes; /* DEBUG MODE: check if offloading has effect * (it is turned on when configured with --enable-debug) */ #ifdef HYPRE_OMP45_DEBUG /* if we ``enter'' an address, it should not exist in device [o.w NO EFFECT] if we ``exit'' or ''update'' an address, it should exist in device [o.w ERROR] hypre__offload_flag: 0 == OK; 1 == WRONG */ #define HYPRE_OFFLOAD_FLAG(devnum, hptr, type) \ HYPRE_Int hypre__offload_flag = (type[1] == 'n') == omp_target_is_present(hptr, devnum); #else #define HYPRE_OFFLOAD_FLAG(...) \ HYPRE_Int hypre__offload_flag = 0; /* non-debug mode, always OK */ #endif /* OMP 4.5 offloading macro */ #define hypre_omp45_offload(devnum, hptr, datatype, offset, count, type1, type2) \ {\ /* devnum: device number \ * hptr: host poiter \ * datatype \ * type1: ``e(n)ter'', ''e(x)it'', or ``u(p)date'' \ * type2: ``(a)lloc'', ``(t)o'', ``(d)elete'', ''(f)rom'' \ */ \ datatype *hypre__offload_hptr = (datatype *) hptr; \ /* if hypre__global_offload == 0, or * hptr (host pointer) == NULL, * this offload will be IGNORED */ \ if (hypre__global_offload && hypre__offload_hptr != NULL) { \ /* offloading offset and size (in datatype) */ \ size_t hypre__offload_offset = offset, hypre__offload_size = count; \ /* in HYPRE_OMP45_DEBUG mode, we test if this offload has effect */ \ HYPRE_OFFLOAD_FLAG(devnum, hypre__offload_hptr, type1) \ if (hypre__offload_flag) { \ printf("[!NO Effect! %s %d] device %d target: %6s %6s, data %p, [%ld:%ld]\n", __FILE__, __LINE__, devnum, type1, type2, (void *)hypre__offload_hptr, hypre__offload_offset, hypre__offload_size); exit(0); \ } else { \ size_t offload_bytes = count * sizeof(datatype); \ /* printf("[ %s %d] device %d target: %6s %6s, data %p, [%d:%d]\n", __FILE__, __LINE__, devnum, type1, type2, (void *)hypre__offload_hptr, hypre__offload_offset, hypre__offload_size); */ \ if (type1[1] == 'n' && type2[0] == 't') { \ /* enter to */\ hypre__target_allc_count ++; \ hypre__target_allc_bytes += offload_bytes; \ hypre__target_htod_count ++; \ hypre__target_htod_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target enter data map(to:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'n' && type2[0] == 'a') { \ /* enter alloc */ \ hypre__target_allc_count ++; \ hypre__target_allc_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target enter data map(alloc:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'x' && type2[0] == 'd') { \ /* exit delete */\ hypre__target_free_count ++; \ hypre__target_free_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target exit data map(delete:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'x' && type2[0] == 'f') {\ /* exit from */ \ hypre__target_free_count ++; \ hypre__target_free_bytes += offload_bytes; \ hypre__target_dtoh_count ++; \ hypre__target_dtoh_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target exit data map(from:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'p' && type2[0] == 't') { \ /* update to */ \ hypre__target_htod_count ++; \ hypre__target_htod_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target update to(hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else if (type1[1] == 'p' && type2[0] == 'f') {\ /* update from */ \ hypre__target_dtoh_count ++; \ hypre__target_dtoh_bytes += offload_bytes; \ _Pragma (HYPRE_XSTR(omp target update from(hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \ } else {\ printf("error: unrecognized offloading type combination!\n"); exit(-1); \ } \ } \ } \ } #endif /* #if defined(HYPRE_USING_DEVICE_OPENMP) */ /* #define hypre_InitMemoryDebug(id) #define hypre_FinalizeMemoryDebug() */ //#define TRACK_MEMORY_ALLOCATIONS #if defined(TRACK_MEMORY_ALLOCATIONS) typedef struct { char *file; size_t size; void *end; HYPRE_Int line; HYPRE_Int type;} pattr_t; pattr_t *patpush(void *ptr, pattr_t *ss); #define hypre_TAlloc(type, count, location) \ ( (type *)hypre_MAllocIns((size_t)(sizeof(type) * (count)), location,__FILE__,__LINE__) ) #define hypre_CTAlloc(type, count, location) \ ( (type *)hypre_CAllocIns((size_t)(count), (size_t)sizeof(type), location,__FILE__,__LINE__) ) #define hypre_TReAlloc(ptr, type, count, location) \ ( (type *)hypre_ReAllocIns((char *)ptr, (size_t)(sizeof(type) * (count)), location,__FILE__,__LINE__) ) void assert_check(void *ptr, char *file, HYPRE_Int line); void assert_check_host(void *ptr, char *file, HYPRE_Int line); #define ASSERT_MANAGED(ptr)\ ( assert_check((ptr),__FILE__,__LINE__)) #define ASSERT_HOST(ptr)\ ( assert_check_host((ptr),__FILE__,__LINE__)) #else #if 0 /* These Allocs are with printfs, for debug */ #define hypre_TAlloc(type, count, location) \ (\ /*printf("[%s:%d] MALLOC %ld B\n", __FILE__,__LINE__, (size_t)(sizeof(type) * (count))) ,*/ \ (type *) hypre_MAlloc((size_t)(sizeof(type) * (count)), location) \ ) #define hypre_CTAlloc(type, count, location) \ (\ {\ /* if (location == HYPRE_MEMORY_DEVICE) printf("[%s:%d] CTALLOC %.3f MB\n", __FILE__,__LINE__, (size_t)(sizeof(type) * (count))/1024.0/1024.0); */ \ (type *) hypre_CAlloc((size_t)(count), (size_t)sizeof(type), location); \ }\ ) #define hypre_TReAlloc(ptr, type, count, location) \ (\ /* printf("[%s:%d] TReALLOC %ld B\n", __FILE__,__LINE__, (size_t)(sizeof(type) * (count))) , */ \ (type *)hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count)), location) \ ) #else #define hypre_TAlloc(type, count, location) \ ( (type *) hypre_MAlloc((size_t)(sizeof(type) * (count)), location) ) #define hypre_CTAlloc(type, count, location) \ ( (type *) hypre_CAlloc((size_t)(count), (size_t)sizeof(type), location) ) #define hypre_TReAlloc(ptr, type, count, location) \ ( (type *) hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count)), location) ) #endif #endif #define hypre_TFree(ptr,location) \ ( hypre_Free((char *)ptr, location), ptr = NULL ) #define hypre_TMemcpy(dst, src, type, count, locdst, locsrc) \ (hypre_Memcpy((char *)(dst),(char *)(src),(size_t)(sizeof(type) * (count)),locdst, locsrc)) /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* hypre_memory.c */ #if 0 char *hypre_CAllocIns( size_t count , size_t elt_size , HYPRE_Int location,char *file, HYPRE_Int line); char *hypre_ReAllocIns( char *ptr , size_t size , HYPRE_Int location,char *file, HYPRE_Int line); char *hypre_MAllocIns( size_t size , HYPRE_Int location,char *file,HYPRE_Int line); char *hypre_MAllocPinned( size_t size ); #else void * hypre_MAlloc(size_t size, HYPRE_Int location); void * hypre_CAlloc( size_t count, size_t elt_size, HYPRE_Int location); void * hypre_ReAlloc(void *ptr, size_t size, HYPRE_Int location); void hypre_Memcpy(void *dst, void *src, size_t size, HYPRE_Int loc_dst, HYPRE_Int loc_src); void * hypre_Memset(void *ptr, HYPRE_Int value, size_t num, HYPRE_Int location); void hypre_Free(void *ptr, HYPRE_Int location); #endif /* char *hypre_CAllocHost( size_t count,size_t elt_size ); char *hypre_MAllocHost( size_t size ); char *hypre_ReAllocHost( char *ptr,size_t size ); void hypre_FreeHost( char *ptr ); char *hypre_SharedMAlloc ( size_t size ); char *hypre_SharedCAlloc ( size_t count , size_t elt_size ); char *hypre_SharedReAlloc ( char *ptr , size_t size ); void hypre_SharedFree ( char *ptr ); void hypre_MemcpyAsync( char *dst, char *src, size_t size, HYPRE_Int locdst, HYPRE_Int locsrc ); HYPRE_Real *hypre_IncrementSharedDataPtr ( HYPRE_Real *ptr , size_t size ); */ /* memory_dmalloc.c */ HYPRE_Int hypre_InitMemoryDebugDML( HYPRE_Int id ); HYPRE_Int hypre_FinalizeMemoryDebugDML( void ); char *hypre_MAllocDML( HYPRE_Int size , char *file , HYPRE_Int line ); char *hypre_CAllocDML( HYPRE_Int count , HYPRE_Int elt_size , char *file , HYPRE_Int line ); char *hypre_ReAllocDML( char *ptr , HYPRE_Int size , char *file , HYPRE_Int line ); void hypre_FreeDML( char *ptr , char *file , HYPRE_Int line ); #ifdef __cplusplus } #endif #endif
#ifndef __NATIVE_BRIDGE_H #define __NATIVE_BRIDGE_H #include "jni.h" #include <memory> using namespace std; namespace sdkbox { class Functor { public: virtual void operator()( const string& event, jobject params ) { } }; template< class T > class JNIEventListener : public Functor { typedef void(T::*Method)(const string& event, jobject params ); private: T* _callee; Method _method; public: JNIEventListener( T* obj, Method method ) : _callee(obj), _method(method) {} virtual void operator()( const string& event, jobject params ) { if ( _callee ) { (_callee->*_method)(event, params); } } }; typedef shared_ptr<Functor> SPCallback; typedef shared_ptr<const Functor> CSPCallback; /** * This class is a Booch utility with the responsibility of registering native callbacks in Java. * This is a common blueprint across all Cocos Service Center, where Java-side plugins need to * marshall Java events to native. * The mechanism is very simple: * * An event name is associated with a native side functor object. * * then, calling from Java the method * <code>ServicesRegistry.emit( String event, Object params )</code> will invoke the functor. * * This is much like an observer pattern, where all functors associated with the same Event will * be invocated. * * This object has method to only register and unregister callbacks: * <code>static void addEventListener( const char* event, SPCallback* callback );</code> * <code>static void removeEventListener( const char* event, SPCallback* callback );</code> * Warning: make the native callbacks fast since they will all be invoked in a row. */ class NativeBridge { private: NativeBridge(); ~NativeBridge(); NativeBridge(NativeBridge&); NativeBridge& operator=(NativeBridge&); NativeBridge& operator=(NativeBridge*); public: static void addEventListener( const char* event, SPCallback* callback ); static void removeEventListener( const char* event, SPCallback* callback ); }; } #endif
// // ItemDetailsViewController.h // ARIS // // Created by <NAME> on 4/2/09. // Copyright 2009 University of Wisconsin - Madison. All rights reserved. // #import <UIKit/UIKit.h> #import "AppModel.h" #import "Item.h" #import "ARISMoviePlayerViewController.h" #import "AsyncMediaImageView.h" #import "itemDetailsMode.h" @interface ItemDetailsViewController : UIViewController <UIWebViewDelegate,UITextViewDelegate> { Item *item; //ARISMoviePlayerViewController *mMoviePlayer; //only used if item is a video MPMoviePlayerViewController *mMoviePlayer; //only used if item is a video bool inInventory; bool descriptionShowing; IBOutlet UIToolbar *toolBar; IBOutlet UIBarButtonItem *dropButton; IBOutlet UIBarButtonItem *deleteButton; IBOutlet UIBarButtonItem *pickupButton; IBOutlet UIBarButtonItem *detailButton; IBOutlet UITextView *textBox; IBOutlet UIButton *saveButton; IBOutlet UIButton *backButton; IBOutlet AsyncMediaImageView *itemImageView; IBOutlet UIWebView *itemDescriptionView; IBOutlet UIWebView *itemWebView; IBOutlet UIScrollView *scrollView; UIButton *mediaPlaybackButton; ItemDetailsModeType mode; IBOutlet UIActivityIndicatorView *activityIndicator; BOOL isLink; NSObject *delegate; } @property(readwrite, assign) BOOL isLink; @property(readwrite) Item *item; @property(readwrite) bool inInventory; @property(readwrite) ItemDetailsModeType mode; @property(nonatomic) IBOutlet AsyncMediaImageView *itemImageView; @property(nonatomic) IBOutlet UIWebView *itemWebView; @property(nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator; @property(nonatomic) IBOutlet UIWebView *itemDescriptionView;; @property(nonatomic) IBOutlet UITextView *textBox; @property(nonatomic) UIScrollView *scrollView; @property(nonatomic) IBOutlet UIButton *saveButton; @property (nonatomic) NSObject *delegate; - (IBAction)dropButtonTouchAction:(id)sender; - (IBAction)deleteButtonTouchAction:(id)sender; - (IBAction)backButtonTouchAction:(id)sender; - (IBAction)pickupButtonTouchAction:(id)sender; - (IBAction)playMovie:(id)sender; - (IBAction)toggleDescription:(id)sender; - (void)doActionWithMode:(ItemDetailsModeType)itemMode quantity:(int)quantity; - (void)updateQuantityDisplay; - (void) showWaitingIndicator; - (void) dismissWaitingIndicator; @end
<reponame>miinslin/ProteoStorm /* * ExecDeconvoluteMS2.h * * Created on: Feb 28, 2011 * Author: aguthals */ #ifndef EXECDECONVOLUTEMS2_H_ #define EXECDECONVOLUTEMS2_H_ // Module Includes #include "ExecBase.h" #include "Logger.h" #include "FileUtils.h" #include "ParameterList.h" #include "ExecMergeConvert.h" // External Includes #include "DeconvSpectrum.h" #include "ms1.h" #include "utils.h" // System Includes #include <string> #include <vector> namespace specnets { class ExecMergeConvert; class ExecDeconvoluteMS2 : public ExecBase { public: ExecDeconvoluteMS2(void); ExecDeconvoluteMS2(const ParameterList & inputParams); ExecDeconvoluteMS2(const ParameterList & inputParams, SpecSet * inputSpectra, IsoEnvelope * m_inputEnv); ExecDeconvoluteMS2(const ParameterList & inputParams, SpecSet * inputSpectra, IsoEnvelope * m_inputEnv, SpecSet * outputSpectra); virtual ~ExecDeconvoluteMS2(void); virtual void setOwnInput(bool _ownInput); virtual ExecBase * clone(const ParameterList & input_params) const; virtual bool invoke(void); virtual bool loadInputData(void); virtual bool saveOutputData(void); virtual bool saveInputData(std::vector<std::string> & filenames); virtual bool loadOutputData(void); virtual std::vector<ExecBase *> const & split(int numSplit); virtual bool merge(void); virtual bool validateParams(std::string & error); private: SpecSet * m_inputSpectra; //! The set of input spectra IsoEnvelope * m_inputEnv; //! Input reference isotopic envelope SpecSet * m_outputSpectra; //! The set of output spectra ExecMergeConvert* m_loader; // Universal loader/converter vector<pair<int, int> >* m_loadedIndices; bool ownInput; //! Does this object "own" the input data structures (and hence have to free them) bool ownOutput; //! Does this object "own" the output data pointers (and hence have to free them) }; } #endif /* EXECDECONVOLUTEMS2_H_ */
#pragma once #include <memory> #include <vector> #include <string> #include <d3d11.h> #include <wrl.h> #include <unordered_map> #include "../AnimationModule/src/AnimationModule.h" using Microsoft::WRL::ComPtr; namespace AE { #pragma region AnimationClip typedef std::shared_ptr<Animation::Skeleton> SharedSkeleton; typedef SharedSkeleton SharedSkeletonData; class DifferenceClip; class BakedClip; typedef std::shared_ptr<Animation::AnimationClip> SharedAnimationData; class AnimationClip : std::enable_shared_from_this<AnimationClip> { public: AnimationClip(); virtual ~AnimationClip(); void SetSpeed(float speed); void SetMask(float maskValue, uint32_t jointIndex); void SetSkeleton(SharedSkeleton skeleton); void SetName(std::string name); void SetAnimationData(SharedAnimationData animationData); SharedSkeleton GetSkeleton(); uint32_t GetFrameCount(); std::shared_ptr<DifferenceClip> AsDifferenceClip(); std::shared_ptr<BakedClip> AsBakedClip(); Animation::SkeletonPose& operator[](size_t index); Animation::SkeletonPose& GetSkeletonPose(int index); std::string GetName() const; AE::SharedAnimationData GetAnimationData(); private: SharedAnimationData m_AnimationData = nullptr; SharedSkeletonData m_SkeletonData = nullptr; std::vector<float> m_JointMask; float m_AnimationSpeed = 1.0f; std::string m_Name = "N/A"; }; typedef AnimationClip RawClip; class DifferenceClip : public AnimationClip { public: DifferenceClip(); virtual ~DifferenceClip(); private: float m_BlendWeight = 1.0; std::shared_ptr<AnimationClip> m_OriginalSource = nullptr; std::shared_ptr<AnimationClip> m_OriginalReference = nullptr; }; class BakedClip : public AnimationClip { public: BakedClip(); virtual ~BakedClip(); private: float m_BakedWeight = 1.0; std::shared_ptr<AnimationClip> m_OriginalClip = nullptr; std::shared_ptr<AnimationClip> m_OriginalDifferenceClip = nullptr; }; typedef std::shared_ptr<AE::AnimationClip> SharedAnimationClip; typedef std::shared_ptr<AE::DifferenceClip> SharedDifferenceClip; #pragma endregion AnimationClip base and derived #pragma region AnimationHandler typedef std::unordered_map<std::string, std::shared_ptr<AnimationClip>> AnimationMap; typedef std::unordered_map<std::string, SharedSkeleton> SkeletonMap; enum class ANIMATION_TYPE : uint8_t { AUTO, RAW_CLIP, DIFFERENCE_CLIP, BAKED_CLIP, }; class AnimationHandler { public: AnimationHandler(); ~AnimationHandler(); bool LoadAnimation(std::string file, std::string name, ANIMATION_TYPE type, SharedSkeleton skeleton); bool LoadSkeleton(std::string file, std::string name); SharedAnimationClip GetRawClip(std::string key); SharedAnimationClip GetDifferenceClip(std::string key); SharedAnimationClip GetBakedClip(std::string key); AE::SharedSkeleton GetSkeleton(std::string key); std::string GetNameOfSkeleton(SharedSkeleton skeleton); void AddDifferenceClip(std::string key, AE::SharedDifferenceClip clip); std::unordered_map<std::string, AE::SharedSkeleton>& GetSkeletonMap(); std::unordered_map<std::string, AE::SharedAnimationClip>& GetRawClipMap(); private: AnimationMap m_RawClips; AnimationMap m_DifferenceClips; AnimationMap m_BakedClips; SkeletonMap m_Skeletons; }; struct AnimationClipPlaybackData { AE::SharedAnimationClip clip = nullptr; uint32_t frameCount = 0; uint16_t currentFrame = 0; uint8_t frameRate = 24; float speedScale = 1.0f; float currentTime = 0.0f; float weight = 1.0f; bool isPlaying = true; bool isLooping = true; }; struct AnimatedModelInformation { std::string skeletonName = "N/A"; std::string mainAnimationName = "N/A"; int frameCount = 0; float scale = 1.0f; }; typedef AnimationClipPlaybackData PlaybackData; typedef AnimationClipPlaybackData AnimationLayer; #pragma endregion AnimationClip and Skeleton handler #pragma region "Stuff" AE::SharedAnimationData MakeNewDifferenceClip(AE::SharedAnimationData sourceClip, AE::SharedAnimationData differenceClip); AE::SharedAnimationData MakeNewDifferenceClip(AE::SharedAnimationClip sourceClip, AE::SharedAnimationClip referenceClip); AE::SharedAnimationData MakeNewDifferenceClip(AE::SharedAnimationData sourceClip, AE::SharedSkeletonData skeleton); AE::SharedAnimationData MakeNewDifferenceClip(AE::SharedAnimationClip sourceClip, AE::SharedSkeleton skeleton); DirectX::XMMATRIX GetBindpose(DirectX::XMMATRIX inverseBindPose); DirectX::XMFLOAT4X4A GetBindpose(DirectX::XMFLOAT4X4A inverseBindPose); void BakeOntoBindpose(AE::SharedDifferenceClip animation); #pragma endregion "Stuff" }
/** **************************************************************************************** * * @file udss.c * * @brief User Data Service Server Implementation. * * Copyright (C) 2014. Dialog Semiconductor Ltd, unpublished work. This computer * program includes Confidential, Proprietary Information and is a Trade Secret of * Dialog Semiconductor Ltd. All use, disclosure, and/or reproduction is prohibited * unless authorized in writing. All Rights Reserved. * * <<EMAIL>> and contributors. * **************************************************************************************** */ /** **************************************************************************************** * @addtogroup UDSS * @{ **************************************************************************************** */ /* * INCLUDE FILES **************************************************************************************** */ #include "rwip_config.h" #if (BLE_UDS_SERVER) #include "attm_util.h" #include "atts_util.h" #include "udss.h" #include "udss_task.h" #include "prf_utils.h" /* * GLOBAL VARIABLE DEFINITIONS **************************************************************************************** */ /// User Data Service Server environment variable struct udss_env_tag udss_env __attribute__((section("retention_mem_area0"),zero_init)); //@RETENTION MEMORY /* * LOCAL VARIABLE DEFINITIONS **************************************************************************************** */ /// User Data Service task descriptor static const struct ke_task_desc TASK_DESC_UDSS = {udss_state_handler, &udss_default_handler, udss_state, UDSS_STATE_MAX, UDSS_IDX_MAX}; /* * FUNCTION DEFINITIONS **************************************************************************************** */ void udss_init(void) { // Reset environment memset(&udss_env, 0, sizeof(udss_env)); // Create UDSS task ke_task_create(TASK_UDSS, &TASK_DESC_UDSS); // Set task in disabled state ke_state_set(TASK_UDSS, UDSS_DISABLED); } void udss_disable(uint16_t conhdl) { // Inform the application about the disconnection struct udss_disable_ind *ind = KE_MSG_ALLOC(UDSS_DISABLE_IND, udss_env.con_info.appid, TASK_UDSS, udss_disable_ind); ind->conhdl = conhdl; ke_msg_send(ind); //Disable UDS in database attmdb_svc_set_permission(udss_env.shdl, PERM(SVC, DISABLE)); //Go to idle state ke_state_set(TASK_UDSS, UDSS_IDLE); } uint8_t udss_unpack_ucp_req(uint8_t *packed_val, uint16_t length, struct uds_ucp_req* ucp_req) { uint8_t cursor = 0; // Verify that enough data present if(length < 1) { return PRF_APP_ERROR; } // Retrieve function op code ucp_req->op_code = packed_val[cursor]; cursor++; // Clear user control point parameter structure memset(&(ucp_req->parameter), 0, sizeof(ucp_req->parameter)); // Check if op code is supported if((ucp_req->op_code < UDS_REQ_REG_NEW_USER) || (ucp_req->op_code > UDS_REQ_DEL_USER_DATA)) { return UDS_RSP_OP_CODE_NOT_SUP; } // Delete user data operation doesn't require any other parameter if(ucp_req->op_code == UDS_REQ_DEL_USER_DATA) { return PRF_ERR_OK; } // Register new user function if(ucp_req->op_code == UDS_REQ_REG_NEW_USER) { // Check sufficient data available if((length - cursor) < 2) { return UDS_RSP_INVALID_PARAMETER; } // Retrieve consent code ucp_req->parameter.reg_new_user.consent_code = co_read16p(packed_val + cursor); cursor +=2; if(ucp_req->parameter.reg_new_user.consent_code > UDS_CONSENT_CODE_MAX_VAL) { return UDS_RSP_INVALID_PARAMETER; } } // Consent function if(ucp_req->op_code == UDS_REQ_CONSENT) { // Check sufficient data available if((length - cursor) < 3) { return UDS_RSP_INVALID_PARAMETER; } // Retrieve user index ucp_req->parameter.consent.user_idx = *(packed_val + cursor); cursor++; // Retrieve consent code ucp_req->parameter.consent.consent_code = co_read16p(packed_val + cursor); cursor +=2; if(ucp_req->parameter.consent.consent_code > UDS_CONSENT_CODE_MAX_VAL) { return UDS_RSP_INVALID_PARAMETER; } } // No errors return PRF_ERR_OK; } uint8_t udss_pack_ucp_rsp(uint8_t *packed_val, struct uds_ucp_rsp* ucp_rsp) { uint8_t cursor = 0; // Set response op code packed_val[cursor] = ucp_rsp->op_code; cursor++; // Set request op code packed_val[cursor] = ucp_rsp->req_op_code; cursor++; // Set response value packed_val[cursor] = ucp_rsp->rsp_val; cursor++; // Fill in parameter with user index for register new user function if((ucp_rsp->req_op_code == UDS_REQ_REG_NEW_USER) &&(ucp_rsp->rsp_val == UDS_RSP_SUCCESS)) { *(packed_val+cursor) = ucp_rsp->parameter.reg_new_user.user_idx; cursor ++; } return cursor; } uint8_t udss_send_ucp_rsp(struct uds_ucp_rsp *ucp_rsp, uint16_t handle, ke_task_id_t ucp_ind_src) { uint8_t status = PRF_ERR_IND_DISABLED; struct attm_elmt * attm_elmt; // Retrieve attdb data value pointers attm_elmt = attmdb_get_attribute(handle); // Pack data (updates database) attm_elmt->length = udss_pack_ucp_rsp(attm_elmt->value, ucp_rsp); // Send indication through GATT prf_server_send_event((prf_env_struct *)&udss_env, true, handle); status = PRF_ERR_OK; return status; } #endif //BLE_UDS_SERVER /// @} UDSS
<filename>arcane/extras/NumericalModel/src/Utils/ArrayUtils.h // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- #ifndef ARRAYUTILS_H_ #define ARRAYUTILS_H_ #include "Utils/Utils.h" BEGIN_ARCGEOSIM_NAMESPACE inline void insert(Array<Integer>& list, Array<Real>& value, Integer entry) { if(entry==0) { list[0] = 0 ; return ; } Integer size = entry ; Integer i = size ; Real z = value[entry] ; for(Integer k=0;k<size;k++) { if(z>=value[list[k]]) { i=k ; break ; } } Integer tmp = entry ; Integer last = entry ; for(Integer j=i;j<size;j++) { tmp = list[j] ; list[j] = last ; last = tmp ; } list[size] = last ; } inline Real average(ArrayView<Real> x, ArrayView<Real> coef, Integer n) { Real xx = 0. ; for(Integer i=0;i<n;i++) xx += coef[i]*x[i] ; return xx ; } END_ARCGEOSIM_NAMESPACE #endif /*ARRAYUTILS_H_*/
<reponame>phatblat/macOSPrivateFrameworks<filename>PrivateFrameworks/GameKitServices/CDXClient.h // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @class NSData, NSError, NSMutableDictionary, NSObject<OS_dispatch_queue>, NSObject<OS_dispatch_source>, NSString; @interface CDXClient : NSObject { id <CDXClientDelegate> delegate_; long long holePunchAttemptCount_; NSData *preblob_; NSMutableDictionary *sessionLookup_; NSError *error_; int fd_; unsigned long long holePunchSID_; unsigned long long prevHolePunchSID_; NSString *server_; unsigned short port_; unsigned short localPort_; long long restartCount_; struct sockaddr_in cdxaddr_ipv4; struct addrinfo *cdxMappedIPv4Addr; double holePunchInterval_; BOOL preblobIsUpToDate_; BOOL willReconfigureShortly_; struct __SCDynamicStore *scDynamicStore_; struct __CFRunLoopSource *scDynamicStoreRunLoopSource_; NSObject<OS_dispatch_queue> *queue_; NSObject<OS_dispatch_source> *source_; NSObject<OS_dispatch_source> *holePunchTimer_; CDUnknownBlockType preblobCallback_; void *padding_[10]; } + (id)sharedClient; @property(nonatomic) id <CDXClientDelegate> delegate; // @synthesize delegate=delegate_; @property(copy, nonatomic) CDUnknownBlockType preblobCallback; // @synthesize preblobCallback=preblobCallback_; @property(readonly, nonatomic) NSObject<OS_dispatch_queue> *queue; // @synthesize queue=queue_; - (id)createSessionWithTicket:(id)arg1 sessionKey:(id)arg2; - (void)invalidateSession:(id)arg1; - (BOOL)sendRaw:(id)arg1; - (void)invalidate; - (void)stopHolePunchTimer; - (void)restart; - (void)start; - (void)dealloc; - (void)mapIPv4AddrToIPv6:(struct sockaddr_in *)arg1; - (unsigned char)currentSockAddrLen; - (const struct sockaddr *)currentSockAddr; - (id)initWithOptions:(id)arg1 delegate:(id)arg2; - (void)startListeningOnSockets; - (void)stopListeningOnSockets; - (void)networkDidChange; - (void)handleFDEvent; - (void)resetHolepunchTimer; - (BOOL)handleHolePunchEvent; - (void)sendHolePunch; - (void)setPreblob:(id)arg1; @property(readonly) NSData *preblob; // @synthesize preblob=preblob_; - (void)setError:(id)arg1; @property(readonly, nonatomic) NSError *error; // @synthesize error=error_; @end
/* * Copyright (c) 2020-2021, Arm Limited. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause * */ #include "array.h" #include "cy_device.h" #include "mmio_defs.h" #include "target_cfg.h" #include "tfm_api.h" #include "tfm_hal_defs.h" #include "tfm_multi_core.h" #include "tfm_plat_defs.h" #include "tfm_peripherals_def.h" #include "load/asset_defs.h" #include "load/spm_load_api.h" enum tfm_hal_status_t tfm_hal_set_up_static_boundaries(void) { Cy_PDL_Init(CY_DEVICE_CFG); if (smpu_init_cfg() != TFM_PLAT_ERR_SUCCESS) { return TFM_HAL_ERROR_GENERIC; } if (ppu_init_cfg() != TFM_PLAT_ERR_SUCCESS) { return TFM_HAL_ERROR_GENERIC; } if (bus_masters_cfg() != TFM_PLAT_ERR_SUCCESS) { return TFM_HAL_ERROR_GENERIC; } return TFM_HAL_SUCCESS; } enum tfm_hal_status_t tfm_hal_memory_has_access(uintptr_t base, size_t size, uint32_t attr) { enum tfm_status_e status; status = tfm_has_access_to_region((const void *)base, size, attr); if (status != TFM_SUCCESS) { return TFM_HAL_ERROR_MEM_FAULT; } return TFM_HAL_SUCCESS; } /* * Implementation of tfm_hal_bind_boundaries() on PSOC64: * * The API encodes some attributes into a handle and returns it to SPM. * The attributes include isolation boundaries, privilege, and MMIO information. * When scheduler switches running partitions, SPM compares the handle between * partitions to know if boundary update is necessary. If update is required, * SPM passes the handle to platform to do platform settings and update * isolation boundaries. */ enum tfm_hal_status_t tfm_hal_bind_boundaries( const struct partition_load_info_t *p_ldinf, void **pp_boundaries) { uint32_t i, j; bool privileged; const struct asset_desc_t *p_asset; if (!p_ldinf || !pp_boundaries) { return TFM_HAL_ERROR_GENERIC; } #if TFM_LVL == 1 privileged = true; #else privileged = !!(p_ldinf->flags & PARTITION_MODEL_PSA_ROT); #endif p_asset = (const struct asset_desc_t *)LOAD_INFO_ASSET(p_ldinf); /* * Validate if the named MMIO of partition is allowed by the platform. * Otherwise, skip validation. * * NOTE: Need to add validation of numbered MMIO if platform requires. */ for (i = 0; i < p_ldinf->nassets; i++) { if (!(p_asset[i].attr & ASSET_ATTR_NAMED_MMIO)) { continue; } for (j = 0; j < ARRAY_SIZE(partition_named_mmio_list); j++) { if (p_asset[i].dev.dev_ref == partition_named_mmio_list[j]) { break; } } if (j == ARRAY_SIZE(partition_named_mmio_list)) { return TFM_HAL_ERROR_GENERIC; } } *pp_boundaries = (void *)(((uint32_t)privileged) & HANDLE_ATTR_PRIV_MASK); return TFM_HAL_SUCCESS; } enum tfm_hal_status_t tfm_hal_update_boundaries( const struct partition_load_info_t *p_ldinf, void *p_boundaries) { CONTROL_Type ctrl; bool privileged = !!((uint32_t)p_boundaries & HANDLE_ATTR_PRIV_MASK); /* Privileged level is required to be set always */ ctrl.w = __get_CONTROL(); ctrl.b.nPRIV = privileged ? 0 : 1; __set_CONTROL(ctrl.w); return TFM_HAL_SUCCESS; }
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> #import "NSFastEnumeration-Protocol.h" @class NSFileHandle, NSString, SRMemoryMapping; @interface SRFrameStore : NSObject <NSFastEnumeration> { unsigned int _datastoreVersion; // 8 = 0x8 SRMemoryMapping *_frames; // 16 = 0x10 SRMemoryMapping *_header; // 24 = 0x18 unsigned long long _permission; // 32 = 0x20 NSString *_segmentName; // 40 = 0x28 double _lastAbsoluteTimestamp; // 48 = 0x30 NSFileHandle *_backingFile; // 56 = 0x38 } + (CDStruct_5ed3a199)segmentHeaderFromFile:(id)arg1 withVersion:(unsigned int)arg2; // IMP=0x00000001000326c8 + (void)initialize; // IMP=0x000000010003267c @property(retain) NSFileHandle *backingFile; // @synthesize backingFile=_backingFile; @property double lastAbsoluteTimestamp; // @synthesize lastAbsoluteTimestamp=_lastAbsoluteTimestamp; @property(copy, nonatomic) NSString *segmentName; // @synthesize segmentName=_segmentName; - (void)updateHeader; // IMP=0x00000001000334d0 - (unsigned long long)countByEnumeratingWithState:(CDStruct_70511ce9 *)arg1 objects:(id *)arg2 count:(unsigned long long)arg3; // IMP=0x00000001000333bc - (void *)frameAtOffset:(unsigned long long)arg1; // IMP=0x0000000100033324 - (_Bool)isValidFrame:(void *)arg1; // IMP=0x0000000100033210 - (_Bool)resizeBackingFileTo:(unsigned long long)arg1; // IMP=0x0000000100033184 - (void)dealloc; // IMP=0x0000000100032fe4 @end
<filename>apps/hid_basic_keyboard/firmware/src/config/sam_a7g5_ek/peripheral/flexcom/usart/plib_flexcom3_usart.c /******************************************************************************* FLEXCOM3 USART PLIB Company: Microchip Technology Inc. File Name: plib_flexcom3_usart.c Summary: FLEXCOM3 USART PLIB Implementation File Description This file defines the interface to the FLEXCOM3 USART peripheral library. This library provides access to and control of the associated peripheral instance. Remarks: None. *******************************************************************************/ /******************************************************************************* * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * 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. *******************************************************************************/ // ***************************************************************************** // ***************************************************************************** // Section: Included Files // ***************************************************************************** // ***************************************************************************** /* This section lists the other files that are included in this file. */ #include "plib_flexcom3_usart.h" #include "interrupts.h" #define FLEXCOM3_USART_HW_RX_FIFO_THRES 16 #define FLEXCOM3_USART_HW_TX_FIFO_THRES 16 // ***************************************************************************** // ***************************************************************************** // Section: FLEXCOM3 USART Implementation // ***************************************************************************** // ***************************************************************************** FLEXCOM_USART_OBJECT flexcom3UsartObj; void static FLEXCOM3_USART_ErrorClear( void ) { uint16_t dummyData = 0; if (FLEXCOM3_REGS->FLEX_US_CSR & (FLEX_US_CSR_OVRE_Msk | FLEX_US_CSR_FRAME_Msk | FLEX_US_CSR_PARE_Msk)) { /* Clear the error flags */ FLEXCOM3_REGS->FLEX_US_CR = FLEX_US_CR_RSTSTA_Msk; /* Flush existing error bytes from the RX FIFO */ while( FLEXCOM3_REGS->FLEX_US_CSR & FLEX_US_CSR_RXRDY_Msk ) { if (FLEXCOM3_REGS->FLEX_US_MR & FLEX_US_MR_MODE9_Msk) { dummyData = *((uint16_t*)&FLEXCOM3_REGS->FLEX_US_RHR) & FLEX_US_RHR_RXCHR_Msk; } else { dummyData = *((uint8_t*)&FLEXCOM3_REGS->FLEX_US_RHR); } } } /* Ignore the warning */ (void)dummyData; return; } void static FLEXCOM3_USART_ISR_RX_Handler( void ) { uint32_t rxPending = 0; uint32_t rxThreshold = 0; if(flexcom3UsartObj.rxBusyStatus == true) { while( (FLEXCOM3_REGS->FLEX_US_CSR & FLEX_US_CSR_RXRDY_Msk) && (flexcom3UsartObj.rxProcessedSize < flexcom3UsartObj.rxSize) ) { if (FLEXCOM3_REGS->FLEX_US_MR & FLEX_US_MR_MODE9_Msk) { ((uint16_t*)flexcom3UsartObj.rxBuffer)[flexcom3UsartObj.rxProcessedSize++] = *((uint16_t*)&FLEXCOM3_REGS->FLEX_US_RHR) & FLEX_US_RHR_RXCHR_Msk; } else { flexcom3UsartObj.rxBuffer[flexcom3UsartObj.rxProcessedSize++] = *((uint8_t*)&FLEXCOM3_REGS->FLEX_US_RHR); } } rxPending = flexcom3UsartObj.rxSize - flexcom3UsartObj.rxProcessedSize; if (rxPending > 0) { rxThreshold = (FLEXCOM3_REGS->FLEX_US_FMR & FLEX_US_FMR_RXFTHRES_Msk) >> FLEX_US_FMR_RXFTHRES_Pos; if (rxPending < rxThreshold) { FLEXCOM3_REGS->FLEX_US_FMR = (FLEXCOM3_REGS->FLEX_US_FMR & ~FLEX_US_FMR_RXFTHRES_Msk) | FLEX_US_FMR_RXFTHRES(rxPending); } } /* Check if the buffer is done */ if(flexcom3UsartObj.rxProcessedSize >= flexcom3UsartObj.rxSize) { flexcom3UsartObj.rxBusyStatus = false; /* Disable Read, Overrun, Parity and Framing error interrupts */ FLEXCOM3_REGS->FLEX_US_FIDR = FLEX_US_FIDR_RXFTHF_Msk; FLEXCOM3_REGS->FLEX_US_IDR = (FLEX_US_IDR_FRAME_Msk | FLEX_US_IDR_PARE_Msk | FLEX_US_IDR_OVRE_Msk); if(flexcom3UsartObj.rxCallback != NULL) { flexcom3UsartObj.rxCallback(flexcom3UsartObj.rxContext); } } } else { /* Nothing to process */ ; } return; } void static FLEXCOM3_USART_ISR_TX_Handler( void ) { if(flexcom3UsartObj.txBusyStatus == true) { while( (FLEXCOM3_REGS->FLEX_US_CSR & FLEX_US_CSR_TXRDY_Msk) && (flexcom3UsartObj.txProcessedSize < flexcom3UsartObj.txSize)) { if (FLEXCOM3_REGS->FLEX_US_MR & FLEX_US_MR_MODE9_Msk) { *((uint16_t*)&FLEXCOM3_REGS->FLEX_US_THR) = ((uint16_t*)flexcom3UsartObj.txBuffer)[flexcom3UsartObj.txProcessedSize++] & FLEX_US_THR_TXCHR_Msk; } else { *((uint8_t*)&FLEXCOM3_REGS->FLEX_US_THR) = ((uint8_t*)flexcom3UsartObj.txBuffer)[flexcom3UsartObj.txProcessedSize++]; } } /* Check if the buffer is done */ if(flexcom3UsartObj.txProcessedSize >= flexcom3UsartObj.txSize) { if (FLEXCOM3_REGS->FLEX_US_CSR & FLEX_US_CSR_TXEMPTY_Msk) { flexcom3UsartObj.txBusyStatus = false; FLEXCOM3_REGS->FLEX_US_FIDR = FLEX_US_FIDR_TXFTHF_Msk; FLEXCOM3_REGS->FLEX_US_IDR = FLEX_US_IDR_TXEMPTY_Msk; if(flexcom3UsartObj.txCallback != NULL) { flexcom3UsartObj.txCallback(flexcom3UsartObj.txContext); } } else { FLEXCOM3_REGS->FLEX_US_FIDR = FLEX_US_FIDR_TXFTHF_Msk; FLEXCOM3_REGS->FLEX_US_IER = FLEX_US_IER_TXEMPTY_Msk; } } } else { /* Nothing to process */ ; } return; } void FLEXCOM3_InterruptHandler( void ) { /* Channel status */ uint32_t channelStatus = FLEXCOM3_REGS->FLEX_US_CSR; uint32_t interruptMask = FLEXCOM3_REGS->FLEX_US_IMR; /* Error status */ uint32_t errorStatus = (channelStatus & (FLEX_US_CSR_OVRE_Msk | FLEX_US_CSR_FRAME_Msk | FLEX_US_CSR_PARE_Msk)); if((errorStatus != 0) && (interruptMask & (FLEX_US_IMR_RXRDY_Msk | FLEX_US_IMR_FRAME_Msk | FLEX_US_IMR_PARE_Msk | FLEX_US_IMR_OVRE_Msk))) { /* Save error to report it later */ flexcom3UsartObj.errorStatus = (FLEXCOM_USART_ERROR)errorStatus; /* Clear error flags and flush the error data */ FLEXCOM3_USART_ErrorClear(); /* Transfer complete. Clear the busy flag. */ flexcom3UsartObj.rxBusyStatus = false; FLEXCOM3_REGS->FLEX_US_FIDR = FLEX_US_FIDR_RXFTHF_Msk; /* Disable Read, Overrun, Parity and Framing error interrupts */ FLEXCOM3_REGS->FLEX_US_IDR = (FLEX_US_IDR_RXRDY_Msk | FLEX_US_IDR_FRAME_Msk | FLEX_US_IDR_PARE_Msk | FLEX_US_IDR_OVRE_Msk); /* USART errors are normally associated with the receiver, hence calling receiver context */ if( flexcom3UsartObj.rxCallback != NULL ) { flexcom3UsartObj.rxCallback(flexcom3UsartObj.rxContext); } } /* Clear the FIFO related interrupt flags */ FLEXCOM3_REGS->FLEX_US_CR = FLEX_US_CR_RSTSTA_Msk; FLEXCOM3_USART_ISR_RX_Handler(); FLEXCOM3_USART_ISR_TX_Handler(); } void FLEXCOM3_USART_Initialize( void ) { /* Set FLEXCOM USART operating mode */ FLEXCOM3_REGS->FLEX_MR = FLEX_MR_OPMODE_USART; /* Reset FLEXCOM3 USART */ FLEXCOM3_REGS->FLEX_US_CR = (FLEX_US_CR_RSTRX_Msk | FLEX_US_CR_RSTTX_Msk | FLEX_US_CR_RSTSTA_Msk | FLEX_US_CR_FIFOEN_Msk ); FLEXCOM3_REGS->FLEX_US_FMR = FLEX_US_FMR_TXFTHRES(FLEXCOM3_USART_HW_TX_FIFO_THRES) | FLEX_US_FMR_RXFTHRES(FLEXCOM3_USART_HW_RX_FIFO_THRES) ; /* Setup transmitter timeguard register */ FLEXCOM3_REGS->FLEX_US_TTGR = 0; /* Configure FLEXCOM3 USART mode */ FLEXCOM3_REGS->FLEX_US_MR = ( FLEX_US_MR_USART_MODE_NORMAL | FLEX_US_MR_USCLKS_MCK | FLEX_US_MR_CHRL_8_BIT | FLEX_US_MR_PAR_NO | FLEX_US_MR_NBSTOP_1_BIT | (0 << FLEX_US_MR_OVER_Pos)); /* Configure FLEXCOM3 USART Baud Rate */ FLEXCOM3_REGS->FLEX_US_BRGR = FLEX_US_BRGR_CD(108) | FLEX_US_BRGR_FP(4); /* Enable FLEXCOM3 USART */ FLEXCOM3_REGS->FLEX_US_CR = (FLEX_US_CR_TXEN_Msk | FLEX_US_CR_RXEN_Msk); /* Initialize instance object */ flexcom3UsartObj.rxBuffer = NULL; flexcom3UsartObj.rxSize = 0; flexcom3UsartObj.rxProcessedSize = 0; flexcom3UsartObj.rxBusyStatus = false; flexcom3UsartObj.rxCallback = NULL; flexcom3UsartObj.errorStatus = FLEXCOM_USART_ERROR_NONE; flexcom3UsartObj.txBuffer = NULL; flexcom3UsartObj.txSize = 0; flexcom3UsartObj.txProcessedSize = 0; flexcom3UsartObj.txBusyStatus = false; flexcom3UsartObj.txCallback = NULL; return; } FLEXCOM_USART_ERROR FLEXCOM3_USART_ErrorGet( void ) { FLEXCOM_USART_ERROR errorStatus = flexcom3UsartObj.errorStatus; flexcom3UsartObj.errorStatus = FLEXCOM_USART_ERROR_NONE; /* All errors are cleared, but send the previous error state */ return errorStatus; } static void FLEXCOM3_USART_BaudCalculate(uint32_t srcClkFreq, uint32_t reqBaud, uint8_t overSamp, uint32_t* cd, uint32_t* fp, uint32_t* baudError) { uint32_t actualBaud = 0; *cd = srcClkFreq / (reqBaud * 8 * (2 - overSamp)); if (*cd > 0) { *fp = ((srcClkFreq / (reqBaud * (2 - overSamp))) - ((*cd) * 8)); actualBaud = (srcClkFreq / (((*cd) * 8) + (*fp))) / (2 - overSamp); *baudError = ((100 * actualBaud)/reqBaud) - 100; } } bool FLEXCOM3_USART_SerialSetup( FLEXCOM_USART_SERIAL_SETUP *setup, uint32_t srcClkFreq ) { uint32_t baud = 0; uint32_t overSampVal = 0; uint32_t usartMode; uint32_t cd0, fp0, cd1, fp1, baudError0, baudError1; bool status = false; cd0 = fp0 = cd1 = fp1 = baudError0 = baudError1 = 0; if((flexcom3UsartObj.rxBusyStatus == true) || (flexcom3UsartObj.txBusyStatus == true)) { /* Transaction is in progress, so return without updating settings */ return false; } if (setup != NULL) { baud = setup->baudRate; if(srcClkFreq == 0) { srcClkFreq = FLEXCOM3_USART_FrequencyGet(); } /* Calculate baud register values for 8x/16x oversampling values */ FLEXCOM3_USART_BaudCalculate(srcClkFreq, baud, 0, &cd0, &fp0, &baudError0); FLEXCOM3_USART_BaudCalculate(srcClkFreq, baud, 1, &cd1, &fp1, &baudError1); if ( !(cd0 > 0 && cd0 <= 65535) && !(cd1 > 0 && cd1 <= 65535) ) { /* Requested baud cannot be generated with current clock settings */ return status; } if ( (cd0 > 0 && cd0 <= 65535) && (cd1 > 0 && cd1 <= 65535) ) { /* Requested baud can be generated with both 8x and 16x oversampling. Select the one with less % error. */ if (baudError1 < baudError0) { cd0 = cd1; fp0 = fp1; overSampVal = (1 << FLEX_US_MR_OVER_Pos) & FLEX_US_MR_OVER_Msk; } } else { /* Requested baud can be generated with either with 8x oversampling or with 16x oversampling. Select valid one. */ if (cd1 > 0 && cd1 <= 65535) { cd0 = cd1; fp0 = fp1; overSampVal = (1 << FLEX_US_MR_OVER_Pos) & FLEX_US_MR_OVER_Msk; } } /* Configure FLEXCOM3 USART mode */ usartMode = FLEXCOM3_REGS->FLEX_US_MR; usartMode &= ~(FLEX_US_MR_CHRL_Msk | FLEX_US_MR_MODE9_Msk | FLEX_US_MR_PAR_Msk | FLEX_US_MR_NBSTOP_Msk | FLEX_US_MR_OVER_Msk); FLEXCOM3_REGS->FLEX_US_MR = usartMode | ((uint32_t)setup->dataWidth | (uint32_t)setup->parity | (uint32_t)setup->stopBits | overSampVal); /* Configure FLEXCOM3 USART Baud Rate */ FLEXCOM3_REGS->FLEX_US_BRGR = FLEX_US_BRGR_CD(cd0) | FLEX_US_BRGR_FP(fp0); status = true; } return status; } bool FLEXCOM3_USART_Read( void *buffer, const size_t size ) { bool status = false; uint8_t* pBuffer = (uint8_t *)buffer; if(pBuffer != NULL) { /* Check if receive request is in progress */ if(flexcom3UsartObj.rxBusyStatus == false) { /* Clear errors that may have got generated when there was no active read request pending */ FLEXCOM3_USART_ErrorClear(); /* Clear the errors related to pervious read requests */ flexcom3UsartObj.errorStatus = FLEXCOM_USART_ERROR_NONE; flexcom3UsartObj.rxBuffer = pBuffer; flexcom3UsartObj.rxSize = size; flexcom3UsartObj.rxProcessedSize = 0; flexcom3UsartObj.rxBusyStatus = true; status = true; /* Clear RX FIFO */ FLEXCOM3_REGS->FLEX_US_CR = FLEX_US_CR_RXFCLR_Msk; if (flexcom3UsartObj.rxSize < FLEXCOM3_USART_HW_RX_FIFO_THRES) { FLEXCOM3_REGS->FLEX_US_FMR = (FLEXCOM3_REGS->FLEX_US_FMR & ~FLEX_US_FMR_RXFTHRES_Msk) | FLEX_US_FMR_RXFTHRES(flexcom3UsartObj.rxSize); } else { FLEXCOM3_REGS->FLEX_US_FMR = (FLEXCOM3_REGS->FLEX_US_FMR & ~FLEX_US_FMR_RXFTHRES_Msk) | FLEX_US_FMR_RXFTHRES(FLEXCOM3_USART_HW_RX_FIFO_THRES); } /* Enable Read, Overrun, Parity and Framing error interrupts */ FLEXCOM3_REGS->FLEX_US_IER = (FLEX_US_IER_FRAME_Msk | FLEX_US_IER_PARE_Msk | FLEX_US_IER_OVRE_Msk); /* Enable RX FIFO Threshold interrupt */ FLEXCOM3_REGS->FLEX_US_FIER = FLEX_US_FIER_RXFTHF_Msk; } } return status; } bool FLEXCOM3_USART_Write( void *buffer, const size_t size ) { bool status = false; uint8_t* pBuffer = (uint8_t *)buffer; if(pBuffer != NULL) { /* Check if transmit request is in progress */ if(flexcom3UsartObj.txBusyStatus == false) { flexcom3UsartObj.txBuffer = (uint8_t*)pBuffer; flexcom3UsartObj.txSize = size; flexcom3UsartObj.txProcessedSize = 0; flexcom3UsartObj.txBusyStatus = true; status = true; /* Initiate the transfer by sending first byte */ while( (FLEXCOM3_REGS->FLEX_US_CSR & FLEX_US_CSR_TXRDY_Msk) && (flexcom3UsartObj.txProcessedSize < flexcom3UsartObj.txSize) ) { if (FLEXCOM3_REGS->FLEX_US_MR & FLEX_US_MR_MODE9_Msk) { *((uint16_t*)&FLEXCOM3_REGS->FLEX_US_THR) = ((uint16_t*)flexcom3UsartObj.txBuffer)[flexcom3UsartObj.txProcessedSize++] & FLEX_US_THR_TXCHR_Msk; } else { *((uint8_t*)&FLEXCOM3_REGS->FLEX_US_THR) = ((uint8_t*)flexcom3UsartObj.txBuffer)[flexcom3UsartObj.txProcessedSize++]; } } if ( flexcom3UsartObj.txProcessedSize >= flexcom3UsartObj.txSize) { FLEXCOM3_REGS->FLEX_US_IER = FLEX_US_IER_TXEMPTY_Msk; } else { FLEXCOM3_REGS->FLEX_US_FIER = FLEX_US_FIER_TXFTHF_Msk; } } } return status; } void FLEXCOM3_USART_WriteCallbackRegister( FLEXCOM_USART_CALLBACK callback, uintptr_t context ) { flexcom3UsartObj.txCallback = callback; flexcom3UsartObj.txContext = context; } void FLEXCOM3_USART_ReadCallbackRegister( FLEXCOM_USART_CALLBACK callback, uintptr_t context ) { flexcom3UsartObj.rxCallback = callback; flexcom3UsartObj.rxContext = context; } bool FLEXCOM3_USART_WriteIsBusy( void ) { return flexcom3UsartObj.txBusyStatus; } bool FLEXCOM3_USART_ReadIsBusy( void ) { return flexcom3UsartObj.rxBusyStatus; } size_t FLEXCOM3_USART_WriteCountGet( void ) { return flexcom3UsartObj.txProcessedSize; } size_t FLEXCOM3_USART_ReadCountGet( void ) { return flexcom3UsartObj.rxProcessedSize; } bool FLEXCOM3_USART_ReadAbort(void) { if (flexcom3UsartObj.rxBusyStatus == true) { /* Disable Read, Overrun, Parity and Framing error interrupts */ FLEXCOM3_REGS->FLEX_US_IDR = (FLEX_US_IDR_RXRDY_Msk | FLEX_US_IDR_FRAME_Msk | FLEX_US_IDR_PARE_Msk | FLEX_US_IDR_OVRE_Msk); flexcom3UsartObj.rxBusyStatus = false; /* If required application should read the num bytes processed prior to calling the read abort API */ flexcom3UsartObj.rxSize = flexcom3UsartObj.rxProcessedSize = 0; } return true; }
<reponame>Vallest/Eclog-CPP<filename>Include/Eclog/Detail/TypeTraits.h // Eclog-CPP // Copyright (c) Vallest Systems LLC. All Rights Reserved. // Released under the MIT license. #ifndef ECLOG_CPP_DETAIL_TYPETRAITS_H_ #define ECLOG_CPP_DETAIL_TYPETRAITS_H_ #include <limits> // std::numeric_limits namespace vallest { namespace eclog { namespace detail { template<typename From, typename To> class IsConvertible { private: typedef char True[1]; typedef char False[2]; static True& test(To); static False& test(...); static From from(); public: enum { value = (sizeof(test(from())) == sizeof(True)) ? 1 : 0 }; }; template<typename Base, typename Derived> class IsBaseOf { public: enum { value = IsConvertible<const Derived*, const Base*>::value }; }; template <bool B, class T = void> class EnableIfCond { }; template <class T> class EnableIfCond<true, T> { public: typedef T Type; }; template <class Cond, class T = void> class EnableIf : public EnableIfCond<Cond::value, T> { }; template<typename T> class RemoveCV { public: typedef T Type; }; template<typename T> class RemoveCV<const T> { public: typedef T Type; }; template<typename T> class RemoveCV<volatile T> { public: typedef T Type; }; template<typename T> class RemoveCV<const volatile T> { public: typedef T Type; }; template<typename IntType> class IsSigned { public: enum { value = std::numeric_limits<IntType>::is_signed ? 1 : 0 }; }; } // detail } // eclog } // vallest #endif // ECLOG_CPP_DETAIL_TYPETRAITS_H_