hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
726aa9622fe9fb4a19058abb2351812058038cad | 882 | h | C | simulator/method.h | leandrohw/et2-simulator | ed87e38f1b62ab7e1a7bc684da3364d1154b5878 | [
"Apache-2.0"
] | null | null | null | simulator/method.h | leandrohw/et2-simulator | ed87e38f1b62ab7e1a7bc684da3364d1154b5878 | [
"Apache-2.0"
] | 11 | 2018-04-10T02:46:30.000Z | 2018-04-24T18:12:58.000Z | simulator/method.h | leandrohw/et2-simulator | ed87e38f1b62ab7e1a7bc684da3364d1154b5878 | [
"Apache-2.0"
] | null | null | null | #ifndef ET2_SIMULATOR_SIMULATOR_METHOD_H_
#define ET2_SIMULATOR_SIMULATOR_METHOD_H_
#include <string>
#include <map>
namespace et_simulator {
class Method;
typedef std::map<int, Method *> MethodMap;
class Method
{
private:
int id;
std::string class_name;
std::string method_name;
std::string signature;
static MethodMap allMethods;
public:
Method(int i, std::string cn, std::string mn, std::string sig)
: id(i),
class_name(cn),
method_name(mn),
signature(sig)
{
allMethods[i] = this;
}
const std::string & getClassName() const { return class_name; }
const std::string & getMethodName() const { return method_name; }
const std::string & getSignature() const { return signature; }
static Method * getMethod(int id) {
return allMethods[id];
}
};
} // namespace et_simulator
#endif // ET2_SIMULATOR_SIMULATOR_METHOD_H_
| 21.512195 | 67 | 0.701814 |
20a9c2eed7667706586196900459684840632656 | 2,506 | h | C | scene/camera.h | oceancx/DmitrysEngine | 67856be79b6970168e57acd67db913a625a3797a | [
"MIT"
] | null | null | null | scene/camera.h | oceancx/DmitrysEngine | 67856be79b6970168e57acd67db913a625a3797a | [
"MIT"
] | null | null | null | scene/camera.h | oceancx/DmitrysEngine | 67856be79b6970168e57acd67db913a625a3797a | [
"MIT"
] | 1 | 2020-03-10T13:47:12.000Z | 2020-03-10T13:47:12.000Z | /* Copyright (c) 2017-2019 Dmitry Stepanov a.k.a mr.DIMAS
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**
* @brief Camera component.
*/
typedef struct de_camera_t {
float fov; /**< Field-of-view in degrees. Read-only. */
float aspect; /**< Aspect ratio of camera viewport. Read-only. */
float z_near; /**< Distance to near clipping plane */
float z_far; /**< Distance to far clipping plane */
de_mat4_t view_matrix; /**< View matrix */
de_mat4_t projection_matrix; /**< Projection matrix */
de_mat4_t view_projection_matrix; /**< Combined view * projection matrix. Read-only. */
de_mat4_t inv_view_proj;
de_rectf_t viewport; /**< Viewport rectangle in ratio. Default: 0,0,1,1 */
float depth_hack_value;
bool in_depth_hack_mode;
} de_camera_t;
struct de_node_dispatch_table_t* de_camera_get_dispatch_table(void);
/**
* @brief Builds camera matrices. Camera have to be attached to some node.
* @param camera pointer to camera component
*/
void de_camera_update(de_camera_t* c);
/**
* @brief Sets camera viewport in pixels
* @param camera pointer to camera
* @param x
* @param y
* @param w
* @param h
*/
void de_camera_set_viewport(de_camera_t* camera, const de_rectf_t* viewport);
void de_camera_set_fov(de_camera_t* camera, float fov);
void de_camera_enter_depth_hack(de_camera_t* camera, float value);
void de_camera_leave_depth_hack(de_camera_t* camera); | 40.419355 | 89 | 0.725858 |
1f7dd2f1ad82eb7a9c1aeadf9366aee16b6a9313 | 601 | h | C | exerciceP10/general/integrateur/integrateur.h | Nebulean/projet-BA2 | df86436539b19becf1c806e9f3ce2c7cbb3e4161 | [
"MIT"
] | null | null | null | exerciceP10/general/integrateur/integrateur.h | Nebulean/projet-BA2 | df86436539b19becf1c806e9f3ce2c7cbb3e4161 | [
"MIT"
] | null | null | null | exerciceP10/general/integrateur/integrateur.h | Nebulean/projet-BA2 | df86436539b19becf1c806e9f3ce2c7cbb3e4161 | [
"MIT"
] | null | null | null | #ifndef H_INTEGRATEUR
#define H_INTEGRATEUR
#include "oscillateur.h"
/*!
* Classe de base des Intégrateurs.
*/
class Integrateur{
public:
/* Le constructeur par défaut est suffisent, car il n'y a
* rien à initialiser dans cette classe.
*/
virtual ~Integrateur() {}
//! Méthode qui fait évoluer l'oscillateur donné en argument.
/*!
* Elle est virtuelle pure, car on ne peut pas la définir ici, et ça force la
* substitution dans les autres intégrateurs.
*/
virtual void evolue(Oscillateur& oscillateur, double pas_de_temps, double temps) = 0;
};
#endif // H_INTEGRATEUR
| 24.04 | 87 | 0.710483 |
deb505fc81120fbd8fc4b8e4311bada7ccf45733 | 543 | h | C | src/Mesh.h | williamsandst/fractal-raymarcher | 2252f75051dc73452eb547b7d6eb9111879e1109 | [
"MIT"
] | 3 | 2020-08-08T19:23:22.000Z | 2020-08-09T06:28:40.000Z | src/Mesh.h | williamsandst/fractal-raymarcher | 2252f75051dc73452eb547b7d6eb9111879e1109 | [
"MIT"
] | null | null | null | src/Mesh.h | williamsandst/fractal-raymarcher | 2252f75051dc73452eb547b7d6eb9111879e1109 | [
"MIT"
] | null | null | null | #pragma once
#include "VBOWrapper.h"
struct Mesh
{
public:
Vec3i pos;
std::vector<GeometryVertexAttrib> vertices;
Mesh(Vec3i pos, std::vector<GeometryVertexAttrib>& vertices)
{
this->vertices = vertices;
this->pos = pos;
}
Mesh(Vec3i pos, std::vector<float>& fVertices)
{
vertices = std::vector<GeometryVertexAttrib>();
for (size_t i = 0; i < fVertices.size(); i += 3)
{
vertices.push_back(GeometryVertexAttrib(fVertices[i], fVertices[i + 1], fVertices[i + 2]));
}
this->pos = pos;
}
Mesh() {};
~Mesh() {};
};
| 17.516129 | 94 | 0.651934 |
46adbf475941099c4df081a7e945b7cfad842530 | 1,178 | c | C | release/src/router/busybox/applets/usage.c | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | null | null | null | release/src/router/busybox/applets/usage.c | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | null | null | null | release/src/router/busybox/applets/usage.c | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | null | null | null | /* vi: set sw=4 ts=4: */
/*
* Copyright (C) 2008 Denys Vlasenko.
*
* Licensed under GPLv2, see file LICENSE in this tarball for details.
*/
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "autoconf.h"
/* Since we can't use platform.h, have to do this again by hand: */
#if ENABLE_NOMMU
# define BB_MMU 0
# define USE_FOR_NOMMU(...) __VA_ARGS__
# define USE_FOR_MMU(...)
#else
# define BB_MMU 1
# define USE_FOR_NOMMU(...)
# define USE_FOR_MMU(...) __VA_ARGS__
#endif
#include "usage.h"
#define MAKE_USAGE(aname, usage) { aname, usage },
static struct usage_data {
const char *aname;
const char *usage;
} usage_array[] = {
#include "applets.h"
};
static int compare_func(const void *a, const void *b)
{
const struct usage_data *ua = a;
const struct usage_data *ub = b;
return strcmp(ua->aname, ub->aname);
}
int main(void)
{
int i;
int num_messages = sizeof(usage_array) / sizeof(usage_array[0]);
if (num_messages == 0)
return 0;
qsort(usage_array,
num_messages, sizeof(usage_array[0]),
compare_func);
for (i = 0; i < num_messages; i++)
write(STDOUT_FILENO, usage_array[i].usage, strlen(usage_array[i].usage) + 1);
return 0;
}
| 21.035714 | 79 | 0.687606 |
2047f420cf473ba97dbb33776e088633284fe31e | 648 | h | C | Rendering/ColoredRectangle.h | DeltaEngine/DeltaEngineCpp | 7be036473927750a89b8ccaefd425c07d7dd3319 | [
"Apache-2.0"
] | 7 | 2015-02-01T21:03:22.000Z | 2021-06-29T03:27:28.000Z | Rendering/ColoredRectangle.h | DeltaEngine/DeltaEngineCpp | 7be036473927750a89b8ccaefd425c07d7dd3319 | [
"Apache-2.0"
] | null | null | null | Rendering/ColoredRectangle.h | DeltaEngine/DeltaEngineCpp | 7be036473927750a89b8ccaefd425c07d7dd3319 | [
"Apache-2.0"
] | 7 | 2015-02-19T11:46:56.000Z | 2019-08-17T12:37:04.000Z | #include "Renderable.h"
#include "Renderer.h"
namespace DeltaEngine { namespace Rendering
{
// Keeps position, size and color for an automatically rendered rectangle on screen.
class RenderingLibrary ColoredRectangle : public Renderable
{
public:
ColoredRectangle(std::shared_ptr<Renderer> render, const Datatypes::Rectangle& rect,
const Datatypes::Color& color);
ColoredRectangle(std::shared_ptr<Renderer> render, const Datatypes::Point& center,
const Datatypes::Size& size, const Datatypes::Color& color);
~ColoredRectangle() { Dispose(); }
Datatypes::Rectangle Rect;
Datatypes::Color Color;
virtual void Render();
};
}} | 30.857143 | 86 | 0.753086 |
204935cd570236a61e7887271bf7b2674caa8519 | 664 | h | C | samples/net/ws_echo_server/src/config.h | SebastianBoe/fw-nrfconnect-zephyr | c74c0ef21daf7594b5c4d531e75cc72bae29f9b7 | [
"Apache-2.0"
] | 2 | 2018-12-17T21:00:20.000Z | 2019-02-03T09:47:38.000Z | samples/net/ws_echo_server/src/config.h | SebastianBoe/fw-nrfconnect-zephyr | c74c0ef21daf7594b5c4d531e75cc72bae29f9b7 | [
"Apache-2.0"
] | 6 | 2019-01-09T08:50:20.000Z | 2019-07-29T09:47:59.000Z | samples/net/ws_echo_server/src/config.h | SebastianBoe/fw-nrfconnect-zephyr | c74c0ef21daf7594b5c4d531e75cc72bae29f9b7 | [
"Apache-2.0"
] | 5 | 2018-07-24T11:06:52.000Z | 2018-12-26T06:39:50.000Z | /*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _CONFIG_H_
#define _CONFIG_H_
/* The startup time needs to be longish if DHCP is enabled as setting
* DHCP up takes some time.
*/
#define APP_STARTUP_TIME K_SECONDS(20)
#ifdef CONFIG_NET_CONFIG_SETTINGS
#ifdef CONFIG_NET_IPV6
#define ZEPHYR_ADDR CONFIG_NET_CONFIG_MY_IPV6_ADDR
#else
#define ZEPHYR_ADDR CONFIG_NET_CONFIG_MY_IPV4_ADDR
#endif
#else
#ifdef CONFIG_NET_IPV6
#define ZEPHYR_ADDR "2001:db8::1"
#else
#define ZEPHYR_ADDR "192.0.2.1"
#endif
#endif
#ifndef ZEPHYR_PORT
#define ZEPHYR_PORT 8080
#endif
#endif
| 19.529412 | 69 | 0.730422 |
5a75b397858ed8531084cdac33e22c0050689ca3 | 760 | h | C | sdk-6.5.20/include/soc/dnxc/swstate/auto_generated/access/dnx_sw_state_defragmented_chunk_access.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/include/soc/dnxc/swstate/auto_generated/access/dnx_sw_state_defragmented_chunk_access.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/include/soc/dnxc/swstate/auto_generated/access/dnx_sw_state_defragmented_chunk_access.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null |
/*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#ifndef __DNX_SW_STATE_DEFRAGMENTED_CHUNK_ACCESS_H__
#define __DNX_SW_STATE_DEFRAGMENTED_CHUNK_ACCESS_H__
#ifdef BCM_DNX_SUPPORT
#include <soc/dnxc/swstate/dnxc_sw_state_h_includes.h>
#include <soc/dnxc/swstate/auto_generated/types/dnx_sw_state_defragmented_chunk_types.h>
#include <bcm_int/dnx/algo/consistent_hashing/consistent_hashing_manager.h>
#include <soc/dnxc/swstate/types/sw_state_cb.h>
shr_error_e
sw_state_defragmented_cunk_move_cb_get_cb(sw_state_cb_t * cb_db, uint8 dryRun, sw_state_defragmented_cunk_move_cb * cb);
#endif
#endif
| 29.230769 | 134 | 0.828947 |
6e2f3db54bf9b7c76a9913ea7b29abfc29b22498 | 929 | h | C | Espruino/src/jswrap_arraybuffer.h | pgmsoul/jsuse | 9f95af72bf68d7c6393d0ec6281b1ba321f1f4f0 | [
"Apache-2.0"
] | 162 | 2019-01-04T14:23:52.000Z | 2021-12-26T05:51:34.000Z | Espruino/src/jswrap_arraybuffer.h | pgmsoul/jsuse | 9f95af72bf68d7c6393d0ec6281b1ba321f1f4f0 | [
"Apache-2.0"
] | 6 | 2019-01-04T14:32:15.000Z | 2020-08-07T06:47:34.000Z | Espruino/src/jswrap_arraybuffer.h | pgmsoul/jsuse | 9f95af72bf68d7c6393d0ec6281b1ba321f1f4f0 | [
"Apache-2.0"
] | 130 | 2019-01-04T14:24:33.000Z | 2021-06-25T16:48:56.000Z | /*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* JavaScript methods and functions in the global namespace
* ----------------------------------------------------------------------------
*/
#include "jsvar.h"
JsVar *jswrap_arraybuffer_constructor(JsVarInt byteLength);
JsVar *jswrap_typedarray_constructor(JsVarDataArrayBufferViewType type, JsVar *arr, JsVarInt byteOffset, JsVarInt length);
void jswrap_arraybufferview_set(JsVar *parent, JsVar *arr, int offset);
JsVar *jswrap_arraybufferview_map(JsVar *parent, JsVar *funcVar, JsVar *thisVar);
| 46.45 | 122 | 0.638321 |
6e6f64959f6287ab6c8ef56ba2f78e0e5db55d54 | 130,301 | c | C | suricata-4.1.4/src/detect-engine.c | runtest007/dpdk_surcata_4.1.1 | 5abf91f483b418b5d9c2dd410b5c850d6ed95c5f | [
"MIT"
] | 77 | 2019-06-17T07:05:07.000Z | 2022-03-07T03:26:27.000Z | suricata-4.1.4/src/detect-engine.c | clockdad/DPDK_SURICATA-4_1_1 | 974cc9eb54b0b1ab90eff12a95617e3e293b77d3 | [
"MIT"
] | 22 | 2019-07-18T02:32:10.000Z | 2022-03-24T03:39:11.000Z | suricata-4.1.4/src/detect-engine.c | clockdad/DPDK_SURICATA-4_1_1 | 974cc9eb54b0b1ab90eff12a95617e3e293b77d3 | [
"MIT"
] | 49 | 2019-06-18T03:31:56.000Z | 2022-03-13T05:23:10.000Z | /* Copyright (C) 2007-2010 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
*/
#include "suricata-common.h"
#include "suricata.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-private.h"
#include "flow-util.h"
#include "flow-worker.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "app-layer-parser.h"
#include "app-layer-htp.h"
#include "detect-parse.h"
#include "detect-engine-sigorder.h"
#include "detect-engine-siggroup.h"
#include "detect-engine-address.h"
#include "detect-engine-port.h"
#include "detect-engine-prefilter.h"
#include "detect-engine-mpm.h"
#include "detect-engine-iponly.h"
#include "detect-engine-tag.h"
#include "detect-engine-uri.h"
#include "detect-engine-hrhd.h"
#include "detect-engine-file.h"
#include "detect-engine.h"
#include "detect-engine-state.h"
#include "detect-engine-payload.h"
#include "detect-byte-extract.h"
#include "detect-content.h"
#include "detect-uricontent.h"
#include "detect-engine-threshold.h"
#include "detect-engine-content-inspection.h"
#include "detect-engine-loader.h"
#include "util-classification-config.h"
#include "util-reference-config.h"
#include "util-threshold-config.h"
#include "util-error.h"
#include "util-hash.h"
#include "util-byte.h"
#include "util-debug.h"
#include "util-unittest.h"
#include "util-action.h"
#include "util-magic.h"
#include "util-signal.h"
#include "util-spm.h"
#include "util-device.h"
#include "util-var-name.h"
#include "tm-threads.h"
#include "runmodes.h"
#ifdef PROFILING
#include "util-profiling.h"
#endif
#include "reputation.h"
#define DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT 3000
static DetectEngineThreadCtx *DetectEngineThreadCtxInitForReload(
ThreadVars *tv, DetectEngineCtx *new_de_ctx, int mt);
static int DetectEngineCtxLoadConf(DetectEngineCtx *);
static DetectEngineMasterCtx g_master_de_ctx = { SCMUTEX_INITIALIZER,
0, 99, NULL, NULL, TENANT_SELECTOR_UNKNOWN, NULL, NULL, 0};
static uint32_t TenantIdHash(HashTable *h, void *data, uint16_t data_len);
static char TenantIdCompare(void *d1, uint16_t d1_len, void *d2, uint16_t d2_len);
static void TenantIdFree(void *d);
static uint32_t DetectEngineTentantGetIdFromLivedev(const void *ctx, const Packet *p);
static uint32_t DetectEngineTentantGetIdFromVlanId(const void *ctx, const Packet *p);
static uint32_t DetectEngineTentantGetIdFromPcap(const void *ctx, const Packet *p);
static DetectEngineAppInspectionEngine *g_app_inspect_engines = NULL;
SCEnumCharMap det_ctx_event_table[ ] = {
#ifdef UNITTESTS
{ "TEST", DET_CTX_EVENT_TEST },
#endif
{ "NO_MEMORY", FILE_DECODER_EVENT_NO_MEM },
{ "INVALID_SWF_LENGTH", FILE_DECODER_EVENT_INVALID_SWF_LENGTH },
{ "INVALID_SWF_VERSION", FILE_DECODER_EVENT_INVALID_SWF_VERSION },
{ "Z_DATA_ERROR", FILE_DECODER_EVENT_Z_DATA_ERROR },
{ "Z_STREAM_ERROR", FILE_DECODER_EVENT_Z_STREAM_ERROR },
{ "Z_BUF_ERROR", FILE_DECODER_EVENT_Z_BUF_ERROR },
{ "Z_UNKNOWN_ERROR", FILE_DECODER_EVENT_Z_UNKNOWN_ERROR },
{ "LZMA_DECODER_ERROR", FILE_DECODER_EVENT_LZMA_DECODER_ERROR },
{ "LZMA_MEMLIMIT_ERROR", FILE_DECODER_EVENT_LZMA_MEMLIMIT_ERROR },
{ "LZMA_OPTIONS_ERROR", FILE_DECODER_EVENT_LZMA_OPTIONS_ERROR },
{ "LZMA_FORMAT_ERROR", FILE_DECODER_EVENT_LZMA_FORMAT_ERROR },
{ "LZMA_DATA_ERROR", FILE_DECODER_EVENT_LZMA_DATA_ERROR },
{ "LZMA_BUF_ERROR", FILE_DECODER_EVENT_LZMA_BUF_ERROR },
{ "LZMA_UNKNOWN_ERROR", FILE_DECODER_EVENT_LZMA_UNKNOWN_ERROR },
{ NULL, -1 },
};
/** \brief register inspect engine at start up time
*
* \note errors are fatal */
void DetectAppLayerInspectEngineRegister(const char *name,
AppProto alproto, uint32_t dir,
int progress, InspectEngineFuncPtr Callback)
{
DetectBufferTypeRegister(name);
const int sm_list = DetectBufferTypeGetByName(name);
if (sm_list == -1) {
FatalError(SC_ERR_INITIALIZATION,
"failed to register inspect engine %s", name);
}
if ((alproto >= ALPROTO_FAILED) ||
(!(dir == SIG_FLAG_TOSERVER || dir == SIG_FLAG_TOCLIENT)) ||
(sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) ||
(progress < 0 || progress >= SHRT_MAX) ||
(Callback == NULL))
{
SCLogError(SC_ERR_INVALID_ARGUMENTS, "Invalid arguments");
BUG_ON(1);
}
int direction;
if (dir == SIG_FLAG_TOSERVER) {
direction = 0;
} else {
direction = 1;
}
DetectEngineAppInspectionEngine *new_engine = SCMalloc(sizeof(DetectEngineAppInspectionEngine));
if (unlikely(new_engine == NULL)) {
exit(EXIT_FAILURE);
}
memset(new_engine, 0, sizeof(*new_engine));
new_engine->alproto = alproto;
new_engine->dir = direction;
new_engine->sm_list = sm_list;
new_engine->progress = progress;
new_engine->Callback = Callback;
if (g_app_inspect_engines == NULL) {
g_app_inspect_engines = new_engine;
} else {
DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
while (t->next != NULL) {
t = t->next;
}
t->next = new_engine;
}
}
/** \brief register inspect engine at start up time
*
* \note errors are fatal */
void DetectAppLayerInspectEngineRegister2(const char *name,
AppProto alproto, uint32_t dir, int progress,
InspectEngineFuncPtr2 Callback2,
InspectionBufferGetDataPtr GetData)
{
DetectBufferTypeRegister(name);
const int sm_list = DetectBufferTypeGetByName(name);
if (sm_list == -1) {
FatalError(SC_ERR_INITIALIZATION,
"failed to register inspect engine %s", name);
}
if ((alproto >= ALPROTO_FAILED) ||
(!(dir == SIG_FLAG_TOSERVER || dir == SIG_FLAG_TOCLIENT)) ||
(sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) ||
(progress < 0 || progress >= SHRT_MAX) ||
(Callback2 == NULL))
{
SCLogError(SC_ERR_INVALID_ARGUMENTS, "Invalid arguments");
BUG_ON(1);
} else if (Callback2 == DetectEngineInspectBufferGeneric && GetData == NULL) {
SCLogError(SC_ERR_INVALID_ARGUMENTS, "Invalid arguments: must register "
"GetData with DetectEngineInspectBufferGeneric");
BUG_ON(1);
}
int direction;
if (dir == SIG_FLAG_TOSERVER) {
direction = 0;
} else {
direction = 1;
}
DetectEngineAppInspectionEngine *new_engine = SCMalloc(sizeof(DetectEngineAppInspectionEngine));
if (unlikely(new_engine == NULL)) {
exit(EXIT_FAILURE);
}
memset(new_engine, 0, sizeof(*new_engine));
new_engine->alproto = alproto;
new_engine->dir = direction;
new_engine->sm_list = sm_list;
new_engine->progress = progress;
new_engine->v2.Callback = Callback2;
new_engine->v2.GetData = GetData;
if (g_app_inspect_engines == NULL) {
g_app_inspect_engines = new_engine;
} else {
DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
while (t->next != NULL) {
t = t->next;
}
t->next = new_engine;
}
}
/* copy an inspect engine with transforms to a new list id. */
static void DetectAppLayerInspectEngineCopy(
DetectEngineCtx *de_ctx,
int sm_list, int new_list,
const DetectEngineTransforms *transforms)
{
const DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
while (t) {
if (t->sm_list == sm_list) {
DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
if (unlikely(new_engine == NULL)) {
exit(EXIT_FAILURE);
}
new_engine->alproto = t->alproto;
new_engine->dir = t->dir;
new_engine->sm_list = new_list; /* use new list id */
new_engine->progress = t->progress;
new_engine->Callback = t->Callback;
new_engine->v2 = t->v2;
new_engine->v2.transforms = transforms; /* assign transforms */
if (de_ctx->app_inspect_engines == NULL) {
de_ctx->app_inspect_engines = new_engine;
} else {
DetectEngineAppInspectionEngine *list = de_ctx->app_inspect_engines;
while (list->next != NULL) {
list = list->next;
}
list->next = new_engine;
}
}
t = t->next;
}
}
/* copy inspect engines from global registrations to de_ctx list */
static void DetectAppLayerInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_ctx)
{
const DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
while (t) {
DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
if (unlikely(new_engine == NULL)) {
exit(EXIT_FAILURE);
}
new_engine->alproto = t->alproto;
new_engine->dir = t->dir;
new_engine->sm_list = t->sm_list;
new_engine->progress = t->progress;
new_engine->Callback = t->Callback;
new_engine->v2 = t->v2;
if (de_ctx->app_inspect_engines == NULL) {
de_ctx->app_inspect_engines = new_engine;
} else {
DetectEngineAppInspectionEngine *list = de_ctx->app_inspect_engines;
while (list->next != NULL) {
list = list->next;
}
list->next = new_engine;
}
t = t->next;
}
}
/** \internal
* \brief append the stream inspection
*
* If stream inspection is MPM, then prepend it.
*/
static void AppendStreamInspectEngine(Signature *s, SigMatchData *stream, int direction, uint32_t id)
{
bool prepend = false;
DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
if (unlikely(new_engine == NULL)) {
exit(EXIT_FAILURE);
}
if (SigMatchListSMBelongsTo(s, s->init_data->mpm_sm) == DETECT_SM_LIST_PMATCH) {
SCLogDebug("stream is mpm");
prepend = true;
new_engine->mpm = true;
}
new_engine->alproto = ALPROTO_UNKNOWN; /* all */
new_engine->dir = direction;
new_engine->stream = true;
new_engine->sm_list = DETECT_SM_LIST_PMATCH;
new_engine->smd = stream;
new_engine->Callback = DetectEngineInspectStream;
new_engine->progress = 0;
/* append */
if (s->app_inspect == NULL) {
s->app_inspect = new_engine;
new_engine->id = DE_STATE_FLAG_BASE; /* id is used as flag in stateful detect */
} else if (prepend) {
new_engine->next = s->app_inspect;
s->app_inspect = new_engine;
new_engine->id = id;
} else {
DetectEngineAppInspectionEngine *a = s->app_inspect;
while (a->next != NULL) {
a = a->next;
}
a->next = new_engine;
new_engine->id = id;
}
SCLogDebug("sid %u: engine %p/%u added", s->id, new_engine, new_engine->id);
}
/**
* \note for the file inspect engine, the id DE_STATE_ID_FILE_INSPECT
* is assigned.
*/
int DetectEngineAppInspectionEngine2Signature(DetectEngineCtx *de_ctx, Signature *s)
{
const int nlists = s->init_data->smlists_array_size;
SigMatchData *ptrs[nlists];
memset(&ptrs, 0, (nlists * sizeof(SigMatchData *)));
const int mpm_list = s->init_data->mpm_sm ?
SigMatchListSMBelongsTo(s, s->init_data->mpm_sm) :
-1;
const int files_id = DetectBufferTypeGetByName("files");
/* convert lists to SigMatchData arrays */
int i = 0;
for (i = DETECT_SM_LIST_DYNAMIC_START; i < nlists; i++) {
if (s->init_data->smlists[i] == NULL)
continue;
ptrs[i] = SigMatchList2DataArray(s->init_data->smlists[i]);
SCLogDebug("ptrs[%d] is set", i);
}
bool head_is_mpm = false;
uint32_t last_id = DE_STATE_FLAG_BASE;
const DetectEngineAppInspectionEngine *t = de_ctx->app_inspect_engines;
while (t != NULL) {
bool prepend = false;
if (t->sm_list >= nlists)
goto next;
if (ptrs[t->sm_list] == NULL)
goto next;
SCLogDebug("ptrs[%d] is set", t->sm_list);
if (t->alproto == ALPROTO_UNKNOWN) {
/* special case, inspect engine applies to all protocols */
} else if (s->alproto != ALPROTO_UNKNOWN && s->alproto != t->alproto)
goto next;
if (s->flags & SIG_FLAG_TOSERVER && !(s->flags & SIG_FLAG_TOCLIENT)) {
if (t->dir == 1)
goto next;
} else if (s->flags & SIG_FLAG_TOCLIENT && !(s->flags & SIG_FLAG_TOSERVER)) {
if (t->dir == 0)
goto next;
}
DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
if (unlikely(new_engine == NULL)) {
exit(EXIT_FAILURE);
}
if (mpm_list == t->sm_list) {
SCLogDebug("%s is mpm", DetectBufferTypeGetNameById(de_ctx, t->sm_list));
prepend = true;
head_is_mpm = true;
new_engine->mpm = true;
}
new_engine->alproto = t->alproto;
new_engine->dir = t->dir;
new_engine->sm_list = t->sm_list;
new_engine->smd = ptrs[new_engine->sm_list];
new_engine->Callback = t->Callback;
new_engine->progress = t->progress;
new_engine->v2 = t->v2;
SCLogDebug("sm_list %d new_engine->v2 %p/%p/%p",
new_engine->sm_list, new_engine->v2.Callback,
new_engine->v2.GetData, new_engine->v2.transforms);
if (s->app_inspect == NULL) {
s->app_inspect = new_engine;
if (new_engine->sm_list == files_id) {
SCLogDebug("sid %u: engine %p/%u is FILE ENGINE", s->id, new_engine, new_engine->id);
new_engine->id = DE_STATE_ID_FILE_INSPECT;
} else {
new_engine->id = DE_STATE_FLAG_BASE; /* id is used as flag in stateful detect */
}
/* prepend engine if forced or if our engine has a lower progress. */
} else if (prepend || (!head_is_mpm && s->app_inspect->progress > new_engine->progress)) {
new_engine->next = s->app_inspect;
s->app_inspect = new_engine;
if (new_engine->sm_list == files_id) {
SCLogDebug("sid %u: engine %p/%u is FILE ENGINE", s->id, new_engine, new_engine->id);
new_engine->id = DE_STATE_ID_FILE_INSPECT;
} else {
new_engine->id = ++last_id;
}
} else {
DetectEngineAppInspectionEngine *a = s->app_inspect;
while (a->next != NULL) {
if (a->next && a->next->progress > new_engine->progress) {
break;
}
a = a->next;
}
new_engine->next = a->next;
a->next = new_engine;
if (new_engine->sm_list == files_id) {
SCLogDebug("sid %u: engine %p/%u is FILE ENGINE", s->id, new_engine, new_engine->id);
new_engine->id = DE_STATE_ID_FILE_INSPECT;
} else {
new_engine->id = ++last_id;
}
}
SCLogDebug("sid %u: engine %p/%u added", s->id, new_engine, new_engine->id);
s->init_data->init_flags |= SIG_FLAG_INIT_STATE_MATCH;
next:
t = t->next;
}
if ((s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH) &&
s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL)
{
/* if engine is added multiple times, we pass it the same list */
SigMatchData *stream = SigMatchList2DataArray(s->init_data->smlists[DETECT_SM_LIST_PMATCH]);
BUG_ON(stream == NULL);
if (s->flags & SIG_FLAG_TOSERVER && !(s->flags & SIG_FLAG_TOCLIENT)) {
AppendStreamInspectEngine(s, stream, 0, last_id + 1);
} else if (s->flags & SIG_FLAG_TOCLIENT && !(s->flags & SIG_FLAG_TOSERVER)) {
AppendStreamInspectEngine(s, stream, 1, last_id + 1);
} else {
AppendStreamInspectEngine(s, stream, 0, last_id + 1);
AppendStreamInspectEngine(s, stream, 1, last_id + 1);
}
if (s->init_data->init_flags & SIG_FLAG_INIT_NEED_FLUSH) {
s->flags |= SIG_FLAG_FLUSH;
}
}
#ifdef DEBUG
const DetectEngineAppInspectionEngine *iter = s->app_inspect;
while (iter) {
SCLogDebug("%u: engine %s id %u progress %d %s", s->id,
DetectBufferTypeGetNameById(de_ctx, iter->sm_list), iter->id,
iter->progress,
iter->sm_list == mpm_list ? "MPM":"");
iter = iter->next;
}
#endif
return 0;
}
/** \brief free app inspect engines for a signature
*
* For lists that are registered multiple times, like http_header and
* http_cookie, making the engines owner of the lists is complicated.
* Multiple engines in a sig may be pointing to the same list. To
* address this the 'free' code needs to be extra careful about not
* double freeing, so it takes an approach to first fill an array
* of the to-free pointers before freeing them.
*/
void DetectEngineAppInspectionEngineSignatureFree(Signature *s)
{
int nlists = 0;
DetectEngineAppInspectionEngine *ie = s->app_inspect;
while (ie) {
nlists = MAX(ie->sm_list, nlists);
ie = ie->next;
}
if (nlists == 0)
return;
nlists++;
SigMatchData *ptrs[nlists];
memset(&ptrs, 0, (nlists * sizeof(SigMatchData *)));
/* free engines and put smd in the array */
ie = s->app_inspect;
while (ie) {
DetectEngineAppInspectionEngine *next = ie->next;
BUG_ON(ptrs[ie->sm_list] != NULL && ptrs[ie->sm_list] != ie->smd);
ptrs[ie->sm_list] = ie->smd;
SCFree(ie);
ie = next;
}
/* free the smds */
int i;
for (i = 0; i < nlists; i++)
{
if (ptrs[i] == NULL)
continue;
SigMatchData *smd = ptrs[i];
while(1) {
if (sigmatch_table[smd->type].Free != NULL) {
sigmatch_table[smd->type].Free(smd->ctx);
}
if (smd->is_last)
break;
smd++;
}
SCFree(ptrs[i]);
}
}
/* code for registering buffers */
#include "util-hash-lookup3.h"
static HashListTable *g_buffer_type_hash = NULL;
static int g_buffer_type_id = DETECT_SM_LIST_DYNAMIC_START;
static int g_buffer_type_reg_closed = 0;
static DetectEngineTransforms no_transforms = { .transforms = { 0 }, .cnt = 0, };
int DetectBufferTypeMaxId(void)
{
return g_buffer_type_id;
}
static uint32_t DetectBufferTypeHashFunc(HashListTable *ht, void *data, uint16_t datalen)
{
const DetectBufferType *map = (DetectBufferType *)data;
uint32_t hash = 0;
hash = hashlittle_safe(map->string, strlen(map->string), 0);
hash += hashlittle_safe((uint8_t *)&map->transforms, sizeof(map->transforms), 0);
hash %= ht->array_size;
return hash;
}
static char DetectBufferTypeCompareFunc(void *data1, uint16_t len1, void *data2,
uint16_t len2)
{
DetectBufferType *map1 = (DetectBufferType *)data1;
DetectBufferType *map2 = (DetectBufferType *)data2;
int r = (strcmp(map1->string, map2->string) == 0);
r &= (memcmp((uint8_t *)&map1->transforms, (uint8_t *)&map2->transforms, sizeof(map2->transforms)) == 0);
return r;
}
static void DetectBufferTypeFreeFunc(void *data)
{
DetectBufferType *map = (DetectBufferType *)data;
if (map != NULL) {
SCFree(map);
}
}
static int DetectBufferTypeInit(void)
{
BUG_ON(g_buffer_type_hash);
g_buffer_type_hash = HashListTableInit(256,
DetectBufferTypeHashFunc,
DetectBufferTypeCompareFunc,
DetectBufferTypeFreeFunc);
if (g_buffer_type_hash == NULL)
return -1;
return 0;
}
#if 0
static void DetectBufferTypeFree(void)
{
if (g_buffer_type_hash == NULL)
return;
HashListTableFree(g_buffer_type_hash);
g_buffer_type_hash = NULL;
return;
}
#endif
static int DetectBufferTypeAdd(const char *string)
{
DetectBufferType *map = SCCalloc(1, sizeof(*map));
if (map == NULL)
return -1;
map->string = string;
map->id = g_buffer_type_id++;
BUG_ON(HashListTableAdd(g_buffer_type_hash, (void *)map, 0) != 0);
SCLogDebug("buffer %s registered with id %d", map->string, map->id);
return map->id;
}
static DetectBufferType *DetectBufferTypeLookupByName(const char *string)
{
DetectBufferType map = { (char *)string, NULL, 0, 0, 0, 0, false, NULL, NULL, no_transforms };
DetectBufferType *res = HashListTableLookup(g_buffer_type_hash, &map, 0);
return res;
}
int DetectBufferTypeRegister(const char *name)
{
BUG_ON(g_buffer_type_reg_closed);
if (g_buffer_type_hash == NULL)
DetectBufferTypeInit();
DetectBufferType *exists = DetectBufferTypeLookupByName(name);
if (!exists) {
return DetectBufferTypeAdd(name);
} else {
return exists->id;
}
}
void DetectBufferTypeSupportsPacket(const char *name)
{
BUG_ON(g_buffer_type_reg_closed);
DetectBufferTypeRegister(name);
DetectBufferType *exists = DetectBufferTypeLookupByName(name);
BUG_ON(!exists);
exists->packet = TRUE;
SCLogDebug("%p %s -- %d supports packet inspection", exists, name, exists->id);
}
void DetectBufferTypeSupportsMpm(const char *name)
{
BUG_ON(g_buffer_type_reg_closed);
DetectBufferTypeRegister(name);
DetectBufferType *exists = DetectBufferTypeLookupByName(name);
BUG_ON(!exists);
exists->mpm = TRUE;
SCLogDebug("%p %s -- %d supports mpm", exists, name, exists->id);
}
void DetectBufferTypeSupportsTransformations(const char *name)
{
BUG_ON(g_buffer_type_reg_closed);
DetectBufferTypeRegister(name);
DetectBufferType *exists = DetectBufferTypeLookupByName(name);
BUG_ON(!exists);
exists->supports_transforms = true;
SCLogDebug("%p %s -- %d supports transformations", exists, name, exists->id);
}
int DetectBufferTypeGetByName(const char *name)
{
DetectBufferType *exists = DetectBufferTypeLookupByName(name);
if (!exists) {
return -1;
}
return exists->id;
}
const char *DetectBufferTypeGetNameById(const DetectEngineCtx *de_ctx, const int id)
{
BUG_ON(id < 0 || (uint32_t)id >= de_ctx->buffer_type_map_elements);
BUG_ON(de_ctx->buffer_type_map == NULL);
if (de_ctx->buffer_type_map[id] == NULL)
return NULL;
return de_ctx->buffer_type_map[id]->string;
}
static const DetectBufferType *DetectBufferTypeGetById(const DetectEngineCtx *de_ctx, const int id)
{
BUG_ON(id < 0 || (uint32_t)id >= de_ctx->buffer_type_map_elements);
BUG_ON(de_ctx->buffer_type_map == NULL);
return de_ctx->buffer_type_map[id];
}
void DetectBufferTypeSetDescriptionByName(const char *name, const char *desc)
{
DetectBufferType *exists = DetectBufferTypeLookupByName(name);
if (!exists) {
return;
}
exists->description = desc;
}
const char *DetectBufferTypeGetDescriptionById(const DetectEngineCtx *de_ctx, const int id)
{
const DetectBufferType *exists = DetectBufferTypeGetById(de_ctx, id);
if (!exists) {
return NULL;
}
return exists->description;
}
const char *DetectBufferTypeGetDescriptionByName(const char *name)
{
const DetectBufferType *exists = DetectBufferTypeLookupByName(name);
if (!exists) {
return NULL;
}
return exists->description;
}
bool DetectBufferTypeSupportsPacketGetById(const DetectEngineCtx *de_ctx, const int id)
{
const DetectBufferType *map = DetectBufferTypeGetById(de_ctx, id);
if (map == NULL)
return FALSE;
SCLogDebug("map %p id %d packet? %d", map, id, map->packet);
return map->packet;
}
bool DetectBufferTypeSupportsMpmGetById(const DetectEngineCtx *de_ctx, const int id)
{
const DetectBufferType *map = DetectBufferTypeGetById(de_ctx, id);
if (map == NULL)
return FALSE;
SCLogDebug("map %p id %d mpm? %d", map, id, map->mpm);
return map->mpm;
}
void DetectBufferTypeRegisterSetupCallback(const char *name,
void (*SetupCallback)(const DetectEngineCtx *, Signature *))
{
BUG_ON(g_buffer_type_reg_closed);
DetectBufferTypeRegister(name);
DetectBufferType *exists = DetectBufferTypeLookupByName(name);
BUG_ON(!exists);
exists->SetupCallback = SetupCallback;
}
void DetectBufferRunSetupCallback(const DetectEngineCtx *de_ctx,
const int id, Signature *s)
{
const DetectBufferType *map = DetectBufferTypeGetById(de_ctx, id);
if (map && map->SetupCallback) {
map->SetupCallback(de_ctx, s);
}
}
void DetectBufferTypeRegisterValidateCallback(const char *name,
_Bool (*ValidateCallback)(const Signature *, const char **sigerror))
{
BUG_ON(g_buffer_type_reg_closed);
DetectBufferTypeRegister(name);
DetectBufferType *exists = DetectBufferTypeLookupByName(name);
BUG_ON(!exists);
exists->ValidateCallback = ValidateCallback;
}
bool DetectBufferRunValidateCallback(const DetectEngineCtx *de_ctx,
const int id, const Signature *s, const char **sigerror)
{
const DetectBufferType *map = DetectBufferTypeGetById(de_ctx, id);
if (map && map->ValidateCallback) {
return map->ValidateCallback(s, sigerror);
}
return TRUE;
}
int DetectBufferSetActiveList(Signature *s, const int list)
{
BUG_ON(s->init_data == NULL);
if (s->init_data->list && s->init_data->transform_cnt) {
return -1;
}
s->init_data->list = list;
s->init_data->list_set = true;
return 0;
}
int DetectBufferGetActiveList(DetectEngineCtx *de_ctx, Signature *s)
{
BUG_ON(s->init_data == NULL);
if (s->init_data->list && s->init_data->transform_cnt) {
SCLogDebug("buffer %d has transform(s) registered: %d",
s->init_data->list, s->init_data->transforms[0]);
int new_list = DetectBufferTypeGetByIdTransforms(de_ctx, s->init_data->list,
s->init_data->transforms, s->init_data->transform_cnt);
if (new_list == -1) {
return -1;
}
SCLogDebug("new_list %d", new_list);
s->init_data->list = new_list;
s->init_data->list_set = false;
// reset transforms now that we've set up the list
s->init_data->transform_cnt = 0;
}
return 0;
}
void InspectionBufferClean(DetectEngineThreadCtx *det_ctx)
{
/* single buffers */
for (uint32_t i = 0; i < det_ctx->inspect.to_clear_idx; i++)
{
const uint32_t idx = det_ctx->inspect.to_clear_queue[i];
InspectionBuffer *buffer = &det_ctx->inspect.buffers[idx];
buffer->inspect = NULL;
}
det_ctx->inspect.to_clear_idx = 0;
/* multi buffers */
for (uint32_t i = 0; i < det_ctx->multi_inspect.to_clear_idx; i++)
{
const uint32_t idx = det_ctx->multi_inspect.to_clear_queue[i];
InspectionBufferMultipleForList *mbuffer = &det_ctx->multi_inspect.buffers[idx];
for (uint32_t x = 0; x <= mbuffer->max; x++) {
InspectionBuffer *buffer = &mbuffer->inspection_buffers[x];
buffer->inspect = NULL;
}
mbuffer->init = 0;
mbuffer->max = 0;
}
det_ctx->multi_inspect.to_clear_idx = 0;
}
InspectionBuffer *InspectionBufferGet(DetectEngineThreadCtx *det_ctx, const int list_id)
{
InspectionBuffer *buffer = &det_ctx->inspect.buffers[list_id];
if (buffer->inspect == NULL) {
det_ctx->inspect.to_clear_queue[det_ctx->inspect.to_clear_idx++] = list_id;
}
return buffer;
}
/** \brief for a InspectionBufferMultipleForList get a InspectionBuffer
* \param fb the multiple buffer array
* \param local_id the index to get a buffer
* \param buffer the inspect buffer or NULL in case of error */
InspectionBuffer *InspectionBufferMultipleForListGet(InspectionBufferMultipleForList *fb, uint32_t local_id)
{
if (local_id >= fb->size) {
uint32_t old_size = fb->size;
uint32_t new_size = local_id + 1;
uint32_t grow_by = new_size - old_size;
SCLogDebug("size is %u, need %u, so growing by %u", old_size, new_size, grow_by);
SCLogDebug("fb->inspection_buffers %p", fb->inspection_buffers);
void *ptr = SCRealloc(fb->inspection_buffers, (local_id + 1) * sizeof(InspectionBuffer));
if (ptr == NULL)
return NULL;
InspectionBuffer *to_zero = (InspectionBuffer *)ptr + old_size;
SCLogDebug("ptr %p to_zero %p", ptr, to_zero);
memset((uint8_t *)to_zero, 0, (grow_by * sizeof(InspectionBuffer)));
fb->inspection_buffers = ptr;
fb->size = new_size;
}
fb->max = MAX(fb->max, local_id);
InspectionBuffer *buffer = &fb->inspection_buffers[local_id];
SCLogDebug("using file_data buffer %p", buffer);
return buffer;
}
InspectionBufferMultipleForList *InspectionBufferGetMulti(DetectEngineThreadCtx *det_ctx, const int list_id)
{
InspectionBufferMultipleForList *buffer = &det_ctx->multi_inspect.buffers[list_id];
if (!buffer->init) {
det_ctx->multi_inspect.to_clear_queue[det_ctx->multi_inspect.to_clear_idx++] = list_id;
buffer->init = 1;
}
return buffer;
}
void InspectionBufferInit(InspectionBuffer *buffer, uint32_t initial_size)
{
memset(buffer, 0, sizeof(*buffer));
buffer->buf = SCCalloc(initial_size, sizeof(uint8_t));
if (buffer->buf != NULL) {
buffer->size = initial_size;
}
}
/** \brief setup the buffer with our initial data */
void InspectionBufferSetup(InspectionBuffer *buffer, const uint8_t *data, const uint32_t data_len)
{
buffer->inspect = buffer->orig = data;
buffer->inspect_len = buffer->orig_len = data_len;
buffer->len = 0;
}
void InspectionBufferFree(InspectionBuffer *buffer)
{
if (buffer->buf != NULL) {
SCFree(buffer->buf);
}
memset(buffer, 0, sizeof(*buffer));
}
/**
* \brief make sure that the buffer has at least 'min_size' bytes
* Expand the buffer if necessary
*/
void InspectionBufferCheckAndExpand(InspectionBuffer *buffer, uint32_t min_size)
{
if (likely(buffer->size >= min_size))
return;
uint32_t new_size = (buffer->size == 0) ? 4096 : buffer->size;
while (new_size < min_size) {
new_size *= 2;
}
void *ptr = SCRealloc(buffer->buf, new_size);
if (ptr != NULL) {
buffer->buf = ptr;
buffer->size = new_size;
}
}
void InspectionBufferCopy(InspectionBuffer *buffer, uint8_t *buf, uint32_t buf_len)
{
InspectionBufferCheckAndExpand(buffer, buf_len);
if (buffer->size) {
uint32_t copy_size = MIN(buf_len, buffer->size);
memcpy(buffer->buf, buf, copy_size);
buffer->inspect = buffer->buf;
buffer->inspect_len = copy_size;
}
}
void InspectionBufferApplyTransforms(InspectionBuffer *buffer,
const DetectEngineTransforms *transforms)
{
if (transforms) {
for (int i = 0; i < DETECT_TRANSFORMS_MAX; i++) {
const int id = transforms->transforms[i];
if (id == 0)
break;
BUG_ON(sigmatch_table[id].Transform == NULL);
sigmatch_table[id].Transform(buffer);
SCLogDebug("applied transform %s", sigmatch_table[id].name);
}
}
}
static void DetectBufferTypeSetupDetectEngine(DetectEngineCtx *de_ctx)
{
const int size = g_buffer_type_id;
BUG_ON(!(size > 0));
de_ctx->buffer_type_map = SCCalloc(size, sizeof(DetectBufferType *));
BUG_ON(!de_ctx->buffer_type_map);
de_ctx->buffer_type_map_elements = size;
SCLogDebug("de_ctx->buffer_type_map %p with %u members", de_ctx->buffer_type_map, size);
SCLogDebug("DETECT_SM_LIST_DYNAMIC_START %u", DETECT_SM_LIST_DYNAMIC_START);
HashListTableBucket *b = HashListTableGetListHead(g_buffer_type_hash);
while (b) {
DetectBufferType *map = HashListTableGetListData(b);
de_ctx->buffer_type_map[map->id] = map;
SCLogDebug("name %s id %d mpm %s packet %s -- %s. "
"Callbacks: Setup %p Validate %p", map->string, map->id,
map->mpm ? "true" : "false", map->packet ? "true" : "false",
map->description, map->SetupCallback, map->ValidateCallback);
b = HashListTableGetListNext(b);
}
de_ctx->buffer_type_hash = HashListTableInit(256,
DetectBufferTypeHashFunc,
DetectBufferTypeCompareFunc,
DetectBufferTypeFreeFunc);
if (de_ctx->buffer_type_hash == NULL) {
BUG_ON(1);
}
de_ctx->buffer_type_id = g_buffer_type_id;
PrefilterInit(de_ctx);
DetectMpmInitializeAppMpms(de_ctx);
DetectAppLayerInspectEngineCopyListToDetectCtx(de_ctx);
}
static void DetectBufferTypeFreeDetectEngine(DetectEngineCtx *de_ctx)
{
if (de_ctx) {
if (de_ctx->buffer_type_map)
SCFree(de_ctx->buffer_type_map);
if (de_ctx->buffer_type_hash)
HashListTableFree(de_ctx->buffer_type_hash);
DetectEngineAppInspectionEngine *ilist = de_ctx->app_inspect_engines;
while (ilist) {
DetectEngineAppInspectionEngine *next = ilist->next;
SCFree(ilist);
ilist = next;
}
DetectMpmAppLayerRegistery *mlist = de_ctx->app_mpms_list;
while (mlist) {
DetectMpmAppLayerRegistery *next = mlist->next;
SCFree(mlist);
mlist = next;
}
PrefilterDeinit(de_ctx);
}
}
void DetectBufferTypeCloseRegistration(void)
{
BUG_ON(g_buffer_type_hash == NULL);
g_buffer_type_reg_closed = 1;
}
int DetectBufferTypeGetByIdTransforms(DetectEngineCtx *de_ctx, const int id,
int *transforms, int transform_cnt)
{
const DetectBufferType *base_map = DetectBufferTypeGetById(de_ctx, id);
if (!base_map) {
return -1;
}
if (!base_map->supports_transforms) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "buffer '%s' does not support transformations",
base_map->string);
return -1;
}
DetectEngineTransforms t;
memset(&t, 0, sizeof(t));
for (int i = 0; i < transform_cnt; i++) {
t.transforms[i] = transforms[i];
}
t.cnt = transform_cnt;
DetectBufferType lookup_map = { (char *)base_map->string, NULL, 0, 0, 0, 0, false, NULL, NULL, t };
DetectBufferType *res = HashListTableLookup(de_ctx->buffer_type_hash, &lookup_map, 0);
SCLogDebug("res %p", res);
if (res != NULL) {
return res->id;
}
DetectBufferType *map = SCCalloc(1, sizeof(*map));
if (map == NULL)
return -1;
map->string = base_map->string;
map->id = de_ctx->buffer_type_id++;
map->parent_id = base_map->id;
map->transforms = t;
map->mpm = base_map->mpm;
map->SetupCallback = base_map->SetupCallback;
map->ValidateCallback = base_map->ValidateCallback;
DetectAppLayerMpmRegisterByParentId(de_ctx,
map->id, map->parent_id, &map->transforms);
BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash, (void *)map, 0) != 0);
SCLogDebug("buffer %s registered with id %d, parent %d", map->string, map->id, map->parent_id);
if (map->id >= 0 && (uint32_t)map->id >= de_ctx->buffer_type_map_elements) {
void *ptr = SCRealloc(de_ctx->buffer_type_map, (map->id + 1) * sizeof(DetectBufferType *));
BUG_ON(ptr == NULL);
SCLogDebug("de_ctx->buffer_type_map resized to %u (was %u)", (map->id + 1), de_ctx->buffer_type_map_elements);
de_ctx->buffer_type_map = ptr;
de_ctx->buffer_type_map[map->id] = map;
de_ctx->buffer_type_map_elements = map->id + 1;
DetectAppLayerInspectEngineCopy(de_ctx, map->parent_id, map->id,
&map->transforms);
}
return map->id;
}
/* code to control the main thread to do a reload */
enum DetectEngineSyncState {
IDLE, /**< ready to start a reload */
RELOAD, /**< command main thread to do the reload */
};
typedef struct DetectEngineSyncer_ {
SCMutex m;
enum DetectEngineSyncState state;
} DetectEngineSyncer;
static DetectEngineSyncer detect_sync = { SCMUTEX_INITIALIZER, IDLE };
/* tell main to start reloading */
int DetectEngineReloadStart(void)
{
int r = 0;
SCMutexLock(&detect_sync.m);
if (detect_sync.state == IDLE) {
detect_sync.state = RELOAD;
} else {
r = -1;
}
SCMutexUnlock(&detect_sync.m);
return r;
}
/* main thread checks this to see if it should start */
int DetectEngineReloadIsStart(void)
{
int r = 0;
SCMutexLock(&detect_sync.m);
if (detect_sync.state == RELOAD) {
r = 1;
}
SCMutexUnlock(&detect_sync.m);
return r;
}
/* main thread sets done when it's done */
void DetectEngineReloadSetIdle(void)
{
SCMutexLock(&detect_sync.m);
detect_sync.state = IDLE;
SCMutexUnlock(&detect_sync.m);
}
/* caller loops this until it returns 1 */
int DetectEngineReloadIsIdle(void)
{
int r = 0;
SCMutexLock(&detect_sync.m);
if (detect_sync.state == IDLE) {
r = 1;
}
SCMutexUnlock(&detect_sync.m);
return r;
}
/** \brief Do the content inspection & validation for a signature
*
* \param de_ctx Detection engine context
* \param det_ctx Detection engine thread context
* \param s Signature to inspect
* \param sm SigMatch to inspect
* \param f Flow
* \param flags app layer flags
* \param state App layer state
*
* \retval 0 no match
* \retval 1 match
*/
int DetectEngineInspectGenericList(ThreadVars *tv,
const DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
const Signature *s, const SigMatchData *smd,
Flow *f, const uint8_t flags,
void *alstate, void *txv, uint64_t tx_id)
{
SCLogDebug("running match functions, sm %p", smd);
if (smd != NULL) {
while (1) {
int match = 0;
#ifdef PROFILING
KEYWORD_PROFILING_START;
#endif
match = sigmatch_table[smd->type].
AppLayerTxMatch(tv, det_ctx, f, flags, alstate, txv, s, smd->ctx);
#ifdef PROFILING
KEYWORD_PROFILING_END(det_ctx, smd->type, (match == 1));
#endif
if (match == 0)
return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
if (match == 2) {
return DETECT_ENGINE_INSPECT_SIG_CANT_MATCH;
}
if (smd->is_last)
break;
smd++;
}
}
return DETECT_ENGINE_INSPECT_SIG_MATCH;
}
/**
* \brief Do the content inspection & validation for a signature
*
* \param de_ctx Detection engine context
* \param det_ctx Detection engine thread context
* \param s Signature to inspect
* \param f Flow
* \param flags app layer flags
* \param state App layer state
*
* \retval 0 no match.
* \retval 1 match.
* \retval 2 Sig can't match.
*/
int DetectEngineInspectBufferGeneric(
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
const DetectEngineAppInspectionEngine *engine,
const Signature *s,
Flow *f, uint8_t flags, void *alstate, void *txv, uint64_t tx_id)
{
const int list_id = engine->sm_list;
SCLogDebug("running inspect on %d", list_id);
const bool eof = (AppLayerParserGetStateProgress(f->proto, f->alproto, txv, flags) > engine->progress);
SCLogDebug("list %d mpm? %s transforms %p",
engine->sm_list, engine->mpm ? "true" : "false", engine->v2.transforms);
/* if prefilter didn't already run, we need to consider transformations */
const DetectEngineTransforms *transforms = NULL;
if (!engine->mpm) {
transforms = engine->v2.transforms;
}
const InspectionBuffer *buffer = engine->v2.GetData(det_ctx, transforms,
f, flags, txv, list_id);
if (unlikely(buffer == NULL)) {
return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH :
DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
}
const uint32_t data_len = buffer->inspect_len;
const uint8_t *data = buffer->inspect;
const uint64_t offset = buffer->inspect_offset;
uint8_t ci_flags = eof ? DETECT_CI_FLAGS_END : 0;
ci_flags |= (offset == 0 ? DETECT_CI_FLAGS_START : 0);
det_ctx->discontinue_matching = 0;
det_ctx->buffer_offset = 0;
det_ctx->inspection_recursion_counter = 0;
/* Inspect all the uricontents fetched on each
* transaction at the app layer */
int r = DetectEngineContentInspection(de_ctx, det_ctx,
s, engine->smd,
f,
(uint8_t *)data, data_len, offset, ci_flags,
DETECT_ENGINE_CONTENT_INSPECTION_MODE_STATE, NULL);
if (r == 1) {
return DETECT_ENGINE_INSPECT_SIG_MATCH;
} else {
return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH :
DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
}
}
/* nudge capture loops to wake up */
static void BreakCapture(void)
{
SCMutexLock(&tv_root_lock);
ThreadVars *tv = tv_root[TVT_PPT];
while (tv) {
/* find the correct slot */
TmSlot *slots = tv->tm_slots;
while (slots != NULL) {
if (suricata_ctl_flags != 0) {
SCMutexUnlock(&tv_root_lock);
return;
}
TmModule *tm = TmModuleGetById(slots->tm_id);
if (!(tm->flags & TM_FLAG_RECEIVE_TM)) {
slots = slots->slot_next;
continue;
}
/* signal capture method that we need a packet. */
TmThreadsSetFlag(tv, THV_CAPTURE_INJECT_PKT);
/* if the method supports it, BreakLoop. Otherwise we rely on
* the capture method's recv timeout */
if (tm->PktAcqLoop && tm->PktAcqBreakLoop) {
tm->PktAcqBreakLoop(tv, SC_ATOMIC_GET(slots->slot_data));
}
break;
}
tv = tv->next;
}
SCMutexUnlock(&tv_root_lock);
}
/** \internal
* \brief inject a pseudo packet into each detect thread that doesn't use the
* new det_ctx yet
*/
static void InjectPackets(ThreadVars **detect_tvs,
DetectEngineThreadCtx **new_det_ctx,
int no_of_detect_tvs)
{
int i;
/* inject a fake packet if the detect thread isn't using the new ctx yet,
* this speeds up the process */
for (i = 0; i < no_of_detect_tvs; i++) {
if (SC_ATOMIC_GET(new_det_ctx[i]->so_far_used_by_detect) != 1) {
if (detect_tvs[i]->inq != NULL) {
Packet *p = PacketGetFromAlloc();
if (p != NULL) {
p->flags |= PKT_PSEUDO_STREAM_END;
PacketQueue *q = &trans_q[detect_tvs[i]->inq->id];
SCMutexLock(&q->mutex_q);
PacketEnqueue(q, p);
SCCondSignal(&q->cond_q);
SCMutexUnlock(&q->mutex_q);
}
}
}
}
}
/** \internal
* \brief Update detect threads with new detect engine
*
* Atomically update each detect thread with a new thread context
* that is associated to the new detection engine(s).
*
* If called in unix socket mode, it's possible that we don't have
* detect threads yet.
*
* \retval -1 error
* \retval 0 no detection threads
* \retval 1 successful reload
*/
static int DetectEngineReloadThreads(DetectEngineCtx *new_de_ctx)
{
SCEnter();
int i = 0;
int no_of_detect_tvs = 0;
ThreadVars *tv = NULL;
/* count detect threads in use */
SCMutexLock(&tv_root_lock);
tv = tv_root[TVT_PPT];
while (tv) {
/* obtain the slots for this TV */
TmSlot *slots = tv->tm_slots;
while (slots != NULL) {
TmModule *tm = TmModuleGetById(slots->tm_id);
if (suricata_ctl_flags != 0) {
SCLogInfo("rule reload interupted by engine shutdown");
SCMutexUnlock(&tv_root_lock);
return -1;
}
if (!(tm->flags & TM_FLAG_DETECT_TM)) {
slots = slots->slot_next;
continue;
}
no_of_detect_tvs++;
break;
}
tv = tv->next;
}
SCMutexUnlock(&tv_root_lock);
/* can be zero in unix socket mode */
if (no_of_detect_tvs == 0) {
return 0;
}
/* prepare swap structures */
DetectEngineThreadCtx *old_det_ctx[no_of_detect_tvs];
DetectEngineThreadCtx *new_det_ctx[no_of_detect_tvs];
ThreadVars *detect_tvs[no_of_detect_tvs];
memset(old_det_ctx, 0x00, (no_of_detect_tvs * sizeof(DetectEngineThreadCtx *)));
memset(new_det_ctx, 0x00, (no_of_detect_tvs * sizeof(DetectEngineThreadCtx *)));
memset(detect_tvs, 0x00, (no_of_detect_tvs * sizeof(ThreadVars *)));
/* start the process of swapping detect threads ctxs */
/* get reference to tv's and setup new_det_ctx array */
SCMutexLock(&tv_root_lock);
tv = tv_root[TVT_PPT];
while (tv) {
/* obtain the slots for this TV */
TmSlot *slots = tv->tm_slots;
while (slots != NULL) {
TmModule *tm = TmModuleGetById(slots->tm_id);
if (suricata_ctl_flags != 0) {
SCMutexUnlock(&tv_root_lock);
goto error;
}
if (!(tm->flags & TM_FLAG_DETECT_TM)) {
slots = slots->slot_next;
continue;
}
old_det_ctx[i] = FlowWorkerGetDetectCtxPtr(SC_ATOMIC_GET(slots->slot_data));
detect_tvs[i] = tv;
new_det_ctx[i] = DetectEngineThreadCtxInitForReload(tv, new_de_ctx, 1);
if (new_det_ctx[i] == NULL) {
SCLogError(SC_ERR_LIVE_RULE_SWAP, "Detect engine thread init "
"failure in live rule swap. Let's get out of here");
SCMutexUnlock(&tv_root_lock);
goto error;
}
SCLogDebug("live rule swap created new det_ctx - %p and de_ctx "
"- %p\n", new_det_ctx[i], new_de_ctx);
i++;
break;
}
tv = tv->next;
}
BUG_ON(i != no_of_detect_tvs);
/* atomicly replace the det_ctx data */
i = 0;
tv = tv_root[TVT_PPT];
while (tv) {
/* find the correct slot */
TmSlot *slots = tv->tm_slots;
while (slots != NULL) {
if (suricata_ctl_flags != 0) {
SCMutexUnlock(&tv_root_lock);
return -1;
}
TmModule *tm = TmModuleGetById(slots->tm_id);
if (!(tm->flags & TM_FLAG_DETECT_TM)) {
slots = slots->slot_next;
continue;
}
SCLogDebug("swapping new det_ctx - %p with older one - %p",
new_det_ctx[i], SC_ATOMIC_GET(slots->slot_data));
FlowWorkerReplaceDetectCtx(SC_ATOMIC_GET(slots->slot_data), new_det_ctx[i++]);
break;
}
tv = tv->next;
}
SCMutexUnlock(&tv_root_lock);
/* threads now all have new data, however they may not have started using
* it and may still use the old data */
SCLogDebug("Live rule swap has swapped %d old det_ctx's with new ones, "
"along with the new de_ctx", no_of_detect_tvs);
InjectPackets(detect_tvs, new_det_ctx, no_of_detect_tvs);
for (i = 0; i < no_of_detect_tvs; i++) {
int break_out = 0;
usleep(1000);
while (SC_ATOMIC_GET(new_det_ctx[i]->so_far_used_by_detect) != 1) {
if (suricata_ctl_flags != 0) {
break_out = 1;
break;
}
BreakCapture();
usleep(1000);
}
if (break_out)
break;
SCLogDebug("new_det_ctx - %p used by detect engine", new_det_ctx[i]);
}
/* this is to make sure that if someone initiated shutdown during a live
* rule swap, the live rule swap won't clean up the old det_ctx and
* de_ctx, till all detect threads have stopped working and sitting
* silently after setting RUNNING_DONE flag and while waiting for
* THV_DEINIT flag */
if (i != no_of_detect_tvs) { // not all threads we swapped
tv = tv_root[TVT_PPT];
while (tv) {
/* obtain the slots for this TV */
TmSlot *slots = tv->tm_slots;
while (slots != NULL) {
TmModule *tm = TmModuleGetById(slots->tm_id);
if (!(tm->flags & TM_FLAG_DETECT_TM)) {
slots = slots->slot_next;
continue;
}
while (!TmThreadsCheckFlag(tv, THV_RUNNING_DONE)) {
usleep(100);
}
slots = slots->slot_next;
}
tv = tv->next;
}
}
/* free all the ctxs */
for (i = 0; i < no_of_detect_tvs; i++) {
SCLogDebug("Freeing old_det_ctx - %p used by detect",
old_det_ctx[i]);
DetectEngineThreadCtxDeinit(NULL, old_det_ctx[i]);
}
SRepReloadComplete();
return 1;
error:
for (i = 0; i < no_of_detect_tvs; i++) {
if (new_det_ctx[i] != NULL)
DetectEngineThreadCtxDeinit(NULL, new_det_ctx[i]);
}
return -1;
}
static DetectEngineCtx *DetectEngineCtxInitReal(enum DetectEngineType type, const char *prefix)
{
DetectEngineCtx *de_ctx = SCMalloc(sizeof(DetectEngineCtx));
if (unlikely(de_ctx == NULL))
goto error;
memset(de_ctx,0,sizeof(DetectEngineCtx));
memset(&de_ctx->sig_stat, 0, sizeof(SigFileLoaderStat));
TAILQ_INIT(&de_ctx->sig_stat.failed_sigs);
de_ctx->sigerror = NULL;
de_ctx->type = type;
if (type == DETECT_ENGINE_TYPE_DD_STUB || type == DETECT_ENGINE_TYPE_MT_STUB) {
de_ctx->version = DetectEngineGetVersion();
SCLogDebug("stub %u with version %u", type, de_ctx->version);
return de_ctx;
}
if (prefix != NULL) {
strlcpy(de_ctx->config_prefix, prefix, sizeof(de_ctx->config_prefix));
}
if (ConfGetBool("engine.init-failure-fatal", (int *)&(de_ctx->failure_fatal)) != 1) {
SCLogDebug("ConfGetBool could not load the value.");
}
de_ctx->mpm_matcher = PatternMatchDefaultMatcher();
de_ctx->spm_matcher = SinglePatternMatchDefaultMatcher();
SCLogConfig("pattern matchers: MPM: %s, SPM: %s",
mpm_table[de_ctx->mpm_matcher].name,
spm_table[de_ctx->spm_matcher].name);
de_ctx->spm_global_thread_ctx = SpmInitGlobalThreadCtx(de_ctx->spm_matcher);
if (de_ctx->spm_global_thread_ctx == NULL) {
SCLogDebug("Unable to alloc SpmGlobalThreadCtx.");
goto error;
}
if (DetectEngineCtxLoadConf(de_ctx) == -1) {
goto error;
}
SigGroupHeadHashInit(de_ctx);
MpmStoreInit(de_ctx);
ThresholdHashInit(de_ctx);
DetectParseDupSigHashInit(de_ctx);
DetectAddressMapInit(de_ctx);
DetectMetadataHashInit(de_ctx);
DetectBufferTypeSetupDetectEngine(de_ctx);
/* init iprep... ignore errors for now */
(void)SRepInit(de_ctx);
SCClassConfLoadClassficationConfigFile(de_ctx, NULL);
SCRConfLoadReferenceConfigFile(de_ctx, NULL);
if (ActionInitConfig() < 0) {
goto error;
}
de_ctx->version = DetectEngineGetVersion();
VarNameStoreSetupStaging(de_ctx->version);
SCLogDebug("dectx with version %u", de_ctx->version);
return de_ctx;
error:
if (de_ctx != NULL) {
DetectEngineCtxFree(de_ctx);
}
return NULL;
}
DetectEngineCtx *DetectEngineCtxInitStubForMT(void)
{
return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_MT_STUB, NULL);
}
DetectEngineCtx *DetectEngineCtxInitStubForDD(void)
{
return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_DD_STUB, NULL);
}
DetectEngineCtx *DetectEngineCtxInit(void)
{
return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_NORMAL, NULL);
}
DetectEngineCtx *DetectEngineCtxInitWithPrefix(const char *prefix)
{
if (prefix == NULL || strlen(prefix) == 0)
return DetectEngineCtxInit();
else
return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_NORMAL, prefix);
}
static void DetectEngineCtxFreeThreadKeywordData(DetectEngineCtx *de_ctx)
{
DetectEngineThreadKeywordCtxItem *item = de_ctx->keyword_list;
while (item) {
DetectEngineThreadKeywordCtxItem *next = item->next;
SCFree(item);
item = next;
}
de_ctx->keyword_list = NULL;
}
static void DetectEngineCtxFreeFailedSigs(DetectEngineCtx *de_ctx)
{
SigString *item = NULL;
SigString *sitem;
TAILQ_FOREACH_SAFE(item, &de_ctx->sig_stat.failed_sigs, next, sitem) {
SCFree(item->filename);
SCFree(item->sig_str);
if (item->sig_error) {
SCFree(item->sig_error);
}
TAILQ_REMOVE(&de_ctx->sig_stat.failed_sigs, item, next);
SCFree(item);
}
}
/**
* \brief Free a DetectEngineCtx::
*
* \param de_ctx DetectEngineCtx:: to be freed
*/
void DetectEngineCtxFree(DetectEngineCtx *de_ctx)
{
if (de_ctx == NULL)
return;
#ifdef PROFILING
if (de_ctx->profile_ctx != NULL) {
SCProfilingRuleDestroyCtx(de_ctx->profile_ctx);
de_ctx->profile_ctx = NULL;
}
if (de_ctx->profile_keyword_ctx != NULL) {
SCProfilingKeywordDestroyCtx(de_ctx);//->profile_keyword_ctx);
// de_ctx->profile_keyword_ctx = NULL;
}
if (de_ctx->profile_sgh_ctx != NULL) {
SCProfilingSghDestroyCtx(de_ctx);
}
SCProfilingPrefilterDestroyCtx(de_ctx);
#endif
/* Normally the hashes are freed elsewhere, but
* to be sure look at them again here.
*/
SigGroupHeadHashFree(de_ctx);
MpmStoreFree(de_ctx);
DetectParseDupSigHashFree(de_ctx);
SCSigSignatureOrderingModuleCleanup(de_ctx);
ThresholdContextDestroy(de_ctx);
SigCleanSignatures(de_ctx);
SCFree(de_ctx->app_mpms);
de_ctx->app_mpms = NULL;
if (de_ctx->sig_array)
SCFree(de_ctx->sig_array);
SCClassConfDeInitContext(de_ctx);
SCRConfDeInitContext(de_ctx);
SigGroupCleanup(de_ctx);
SpmDestroyGlobalThreadCtx(de_ctx->spm_global_thread_ctx);
MpmFactoryDeRegisterAllMpmCtxProfiles(de_ctx);
DetectEngineCtxFreeThreadKeywordData(de_ctx);
SRepDestroy(de_ctx);
DetectEngineCtxFreeFailedSigs(de_ctx);
DetectAddressMapFree(de_ctx);
DetectMetadataHashFree(de_ctx);
/* if we have a config prefix, remove the config from the tree */
if (strlen(de_ctx->config_prefix) > 0) {
/* remove config */
ConfNode *node = ConfGetNode(de_ctx->config_prefix);
if (node != NULL) {
ConfNodeRemove(node); /* frees node */
}
#if 0
ConfDump();
#endif
}
DetectPortCleanupList(de_ctx, de_ctx->tcp_whitelist);
DetectPortCleanupList(de_ctx, de_ctx->udp_whitelist);
DetectBufferTypeFreeDetectEngine(de_ctx);
/* freed our var name hash */
VarNameStoreFree(de_ctx->version);
SCFree(de_ctx);
//DetectAddressGroupPrintMemory();
//DetectSigGroupPrintMemory();
//DetectPortPrintMemory();
}
/** \brief Function that load DetectEngineCtx config for grouping sigs
* used by the engine
* \retval 0 if no config provided, 1 if config was provided
* and loaded successfuly
*/
static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx)
{
uint8_t profile = ENGINE_PROFILE_MEDIUM;
const char *max_uniq_toclient_groups_str = NULL;
const char *max_uniq_toserver_groups_str = NULL;
const char *sgh_mpm_context = NULL;
const char *de_ctx_profile = NULL;
(void)ConfGet("detect.profile", &de_ctx_profile);
(void)ConfGet("detect.sgh-mpm-context", &sgh_mpm_context);
ConfNode *de_ctx_custom = ConfGetNode("detect-engine");
ConfNode *opt = NULL;
if (de_ctx_custom != NULL) {
TAILQ_FOREACH(opt, &de_ctx_custom->head, next) {
if (de_ctx_profile == NULL) {
if (opt->val && strcmp(opt->val, "profile") == 0) {
de_ctx_profile = opt->head.tqh_first->val;
}
}
if (sgh_mpm_context == NULL) {
if (opt->val && strcmp(opt->val, "sgh-mpm-context") == 0) {
sgh_mpm_context = opt->head.tqh_first->val;
}
}
}
}
if (de_ctx_profile != NULL) {
if (strcmp(de_ctx_profile, "low") == 0 ||
strcmp(de_ctx_profile, "lowest") == 0) { // legacy
profile = ENGINE_PROFILE_LOW;
} else if (strcmp(de_ctx_profile, "medium") == 0) {
profile = ENGINE_PROFILE_MEDIUM;
} else if (strcmp(de_ctx_profile, "high") == 0 ||
strcmp(de_ctx_profile, "highest") == 0) { // legacy
profile = ENGINE_PROFILE_HIGH;
} else if (strcmp(de_ctx_profile, "custom") == 0) {
profile = ENGINE_PROFILE_CUSTOM;
} else {
SCLogError(SC_ERR_INVALID_YAML_CONF_ENTRY,
"invalid value for detect.profile: '%s'. "
"Valid options: low, medium, high and custom.",
de_ctx_profile);
return -1;
}
SCLogDebug("Profile for detection engine groups is \"%s\"", de_ctx_profile);
} else {
SCLogDebug("Profile for detection engine groups not provided "
"at suricata.yaml. Using default (\"medium\").");
}
/* detect-engine.sgh-mpm-context option parsing */
if (sgh_mpm_context == NULL || strcmp(sgh_mpm_context, "auto") == 0) {
/* for now, since we still haven't implemented any intelligence into
* understanding the patterns and distributing mpm_ctx across sgh */
if (de_ctx->mpm_matcher == MPM_AC || de_ctx->mpm_matcher == MPM_AC_TILE ||
#ifdef BUILD_HYPERSCAN
de_ctx->mpm_matcher == MPM_HS ||
#endif
de_ctx->mpm_matcher == MPM_AC_BS) {
de_ctx->sgh_mpm_context = ENGINE_SGH_MPM_FACTORY_CONTEXT_SINGLE;
} else {
de_ctx->sgh_mpm_context = ENGINE_SGH_MPM_FACTORY_CONTEXT_FULL;
}
} else {
if (strcmp(sgh_mpm_context, "single") == 0) {
de_ctx->sgh_mpm_context = ENGINE_SGH_MPM_FACTORY_CONTEXT_SINGLE;
} else if (strcmp(sgh_mpm_context, "full") == 0) {
de_ctx->sgh_mpm_context = ENGINE_SGH_MPM_FACTORY_CONTEXT_FULL;
} else {
SCLogError(SC_ERR_INVALID_YAML_CONF_ENTRY, "You have supplied an "
"invalid conf value for detect-engine.sgh-mpm-context-"
"%s", sgh_mpm_context);
exit(EXIT_FAILURE);
}
}
if (run_mode == RUNMODE_UNITTEST) {
de_ctx->sgh_mpm_context = ENGINE_SGH_MPM_FACTORY_CONTEXT_FULL;
}
/* parse profile custom-values */
opt = NULL;
switch (profile) {
case ENGINE_PROFILE_LOW:
de_ctx->max_uniq_toclient_groups = 15;
de_ctx->max_uniq_toserver_groups = 25;
break;
case ENGINE_PROFILE_HIGH:
de_ctx->max_uniq_toclient_groups = 75;
de_ctx->max_uniq_toserver_groups = 75;
break;
case ENGINE_PROFILE_CUSTOM:
(void)ConfGet("detect.custom-values.toclient-groups",
&max_uniq_toclient_groups_str);
(void)ConfGet("detect.custom-values.toserver-groups",
&max_uniq_toserver_groups_str);
if (de_ctx_custom != NULL) {
TAILQ_FOREACH(opt, &de_ctx_custom->head, next) {
if (opt->val && strcmp(opt->val, "custom-values") == 0) {
if (max_uniq_toclient_groups_str == NULL) {
max_uniq_toclient_groups_str = (char *)ConfNodeLookupChildValue
(opt->head.tqh_first, "toclient-sp-groups");
}
if (max_uniq_toclient_groups_str == NULL) {
max_uniq_toclient_groups_str = (char *)ConfNodeLookupChildValue
(opt->head.tqh_first, "toclient-groups");
}
if (max_uniq_toserver_groups_str == NULL) {
max_uniq_toserver_groups_str = (char *)ConfNodeLookupChildValue
(opt->head.tqh_first, "toserver-dp-groups");
}
if (max_uniq_toserver_groups_str == NULL) {
max_uniq_toserver_groups_str = (char *)ConfNodeLookupChildValue
(opt->head.tqh_first, "toserver-groups");
}
}
}
}
if (max_uniq_toclient_groups_str != NULL) {
if (ByteExtractStringUint16(&de_ctx->max_uniq_toclient_groups, 10,
strlen(max_uniq_toclient_groups_str),
(const char *)max_uniq_toclient_groups_str) <= 0)
{
de_ctx->max_uniq_toclient_groups = 20;
SCLogWarning(SC_ERR_SIZE_PARSE, "parsing '%s' for "
"toclient-groups failed, using %u",
max_uniq_toclient_groups_str,
de_ctx->max_uniq_toclient_groups);
}
} else {
de_ctx->max_uniq_toclient_groups = 20;
}
SCLogConfig("toclient-groups %u", de_ctx->max_uniq_toclient_groups);
if (max_uniq_toserver_groups_str != NULL) {
if (ByteExtractStringUint16(&de_ctx->max_uniq_toserver_groups, 10,
strlen(max_uniq_toserver_groups_str),
(const char *)max_uniq_toserver_groups_str) <= 0)
{
de_ctx->max_uniq_toserver_groups = 40;
SCLogWarning(SC_ERR_SIZE_PARSE, "parsing '%s' for "
"toserver-groups failed, using %u",
max_uniq_toserver_groups_str,
de_ctx->max_uniq_toserver_groups);
}
} else {
de_ctx->max_uniq_toserver_groups = 40;
}
SCLogConfig("toserver-groups %u", de_ctx->max_uniq_toserver_groups);
break;
/* Default (or no config provided) is profile medium */
case ENGINE_PROFILE_MEDIUM:
case ENGINE_PROFILE_UNKNOWN:
default:
de_ctx->max_uniq_toclient_groups = 20;
de_ctx->max_uniq_toserver_groups = 40;
break;
}
intmax_t value = 0;
if (ConfGetInt("detect.inspection-recursion-limit", &value) == 1)
{
if (value >= 0 && value <= INT_MAX) {
de_ctx->inspection_recursion_limit = (int)value;
}
/* fall back to old config parsing */
} else {
ConfNode *insp_recursion_limit_node = NULL;
char *insp_recursion_limit = NULL;
if (de_ctx_custom != NULL) {
opt = NULL;
TAILQ_FOREACH(opt, &de_ctx_custom->head, next) {
if (opt->val && strcmp(opt->val, "inspection-recursion-limit") != 0)
continue;
insp_recursion_limit_node = ConfNodeLookupChild(opt, opt->val);
if (insp_recursion_limit_node == NULL) {
SCLogError(SC_ERR_INVALID_YAML_CONF_ENTRY, "Error retrieving conf "
"entry for detect-engine:inspection-recursion-limit");
break;
}
insp_recursion_limit = insp_recursion_limit_node->val;
SCLogDebug("Found detect-engine.inspection-recursion-limit - %s:%s",
insp_recursion_limit_node->name, insp_recursion_limit_node->val);
break;
}
if (insp_recursion_limit != NULL) {
de_ctx->inspection_recursion_limit = atoi(insp_recursion_limit);
} else {
de_ctx->inspection_recursion_limit =
DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT;
}
}
}
if (de_ctx->inspection_recursion_limit == 0)
de_ctx->inspection_recursion_limit = -1;
SCLogDebug("de_ctx->inspection_recursion_limit: %d",
de_ctx->inspection_recursion_limit);
/* parse port grouping whitelisting settings */
const char *ports = NULL;
(void)ConfGet("detect.grouping.tcp-whitelist", &ports);
if (ports) {
SCLogConfig("grouping: tcp-whitelist %s", ports);
} else {
ports = "53, 80, 139, 443, 445, 1433, 3306, 3389, 6666, 6667, 8080";
SCLogConfig("grouping: tcp-whitelist (default) %s", ports);
}
if (DetectPortParse(de_ctx, &de_ctx->tcp_whitelist, ports) != 0) {
SCLogWarning(SC_ERR_INVALID_YAML_CONF_ENTRY, "'%s' is not a valid value "
"for detect.grouping.tcp-whitelist", ports);
}
DetectPort *x = de_ctx->tcp_whitelist;
for ( ; x != NULL; x = x->next) {
if (x->port != x->port2) {
SCLogWarning(SC_ERR_INVALID_YAML_CONF_ENTRY, "'%s' is not a valid value "
"for detect.grouping.tcp-whitelist: only single ports allowed", ports);
DetectPortCleanupList(de_ctx, de_ctx->tcp_whitelist);
de_ctx->tcp_whitelist = NULL;
break;
}
}
ports = NULL;
(void)ConfGet("detect.grouping.udp-whitelist", &ports);
if (ports) {
SCLogConfig("grouping: udp-whitelist %s", ports);
} else {
ports = "53, 135, 5060";
SCLogConfig("grouping: udp-whitelist (default) %s", ports);
}
if (DetectPortParse(de_ctx, &de_ctx->udp_whitelist, ports) != 0) {
SCLogWarning(SC_ERR_INVALID_YAML_CONF_ENTRY, "'%s' is not a valid value "
"forr detect.grouping.udp-whitelist", ports);
}
for (x = de_ctx->udp_whitelist; x != NULL; x = x->next) {
if (x->port != x->port2) {
SCLogWarning(SC_ERR_INVALID_YAML_CONF_ENTRY, "'%s' is not a valid value "
"for detect.grouping.udp-whitelist: only single ports allowed", ports);
DetectPortCleanupList(de_ctx, de_ctx->udp_whitelist);
de_ctx->udp_whitelist = NULL;
break;
}
}
de_ctx->prefilter_setting = DETECT_PREFILTER_MPM;
const char *pf_setting = NULL;
if (ConfGet("detect.prefilter.default", &pf_setting) == 1 && pf_setting) {
if (strcasecmp(pf_setting, "mpm") == 0) {
de_ctx->prefilter_setting = DETECT_PREFILTER_MPM;
} else if (strcasecmp(pf_setting, "auto") == 0) {
de_ctx->prefilter_setting = DETECT_PREFILTER_AUTO;
}
}
switch (de_ctx->prefilter_setting) {
case DETECT_PREFILTER_MPM:
SCLogConfig("prefilter engines: MPM");
break;
case DETECT_PREFILTER_AUTO:
SCLogConfig("prefilter engines: MPM and keywords");
break;
}
return 0;
}
/*
* getting & (re)setting the internal sig i
*/
//inline uint32_t DetectEngineGetMaxSigId(DetectEngineCtx *de_ctx)
//{
// return de_ctx->signum;
//}
void DetectEngineResetMaxSigId(DetectEngineCtx *de_ctx)
{
de_ctx->signum = 0;
}
static int DetectEngineThreadCtxInitGlobalKeywords(DetectEngineThreadCtx *det_ctx)
{
const DetectEngineMasterCtx *master = &g_master_de_ctx;
if (master->keyword_id > 0) {
// coverity[suspicious_sizeof : FALSE]
det_ctx->global_keyword_ctxs_array = (void **)SCCalloc(master->keyword_id, sizeof(void *));
if (det_ctx->global_keyword_ctxs_array == NULL) {
SCLogError(SC_ERR_DETECT_PREPARE, "setting up thread local detect ctx");
return TM_ECODE_FAILED;
}
det_ctx->global_keyword_ctxs_size = master->keyword_id;
const DetectEngineThreadKeywordCtxItem *item = master->keyword_list;
while (item) {
det_ctx->global_keyword_ctxs_array[item->id] = item->InitFunc(item->data);
if (det_ctx->global_keyword_ctxs_array[item->id] == NULL) {
SCLogError(SC_ERR_DETECT_PREPARE, "setting up thread local detect ctx "
"for keyword \"%s\" failed", item->name);
return TM_ECODE_FAILED;
}
item = item->next;
}
}
return TM_ECODE_OK;
}
static void DetectEngineThreadCtxDeinitGlobalKeywords(DetectEngineThreadCtx *det_ctx)
{
if (det_ctx->global_keyword_ctxs_array == NULL ||
det_ctx->global_keyword_ctxs_size == 0) {
return;
}
const DetectEngineMasterCtx *master = &g_master_de_ctx;
if (master->keyword_id > 0) {
const DetectEngineThreadKeywordCtxItem *item = master->keyword_list;
while (item) {
if (det_ctx->global_keyword_ctxs_array[item->id] != NULL)
item->FreeFunc(det_ctx->global_keyword_ctxs_array[item->id]);
item = item->next;
}
det_ctx->global_keyword_ctxs_size = 0;
SCFree(det_ctx->global_keyword_ctxs_array);
det_ctx->global_keyword_ctxs_array = NULL;
}
}
static int DetectEngineThreadCtxInitKeywords(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx)
{
if (de_ctx->keyword_id > 0) {
// coverity[suspicious_sizeof : FALSE]
det_ctx->keyword_ctxs_array = SCMalloc(de_ctx->keyword_id * sizeof(void *));
if (det_ctx->keyword_ctxs_array == NULL) {
SCLogError(SC_ERR_DETECT_PREPARE, "setting up thread local detect ctx");
return TM_ECODE_FAILED;
}
memset(det_ctx->keyword_ctxs_array, 0x00, de_ctx->keyword_id * sizeof(void *));
det_ctx->keyword_ctxs_size = de_ctx->keyword_id;
DetectEngineThreadKeywordCtxItem *item = de_ctx->keyword_list;
while (item) {
det_ctx->keyword_ctxs_array[item->id] = item->InitFunc(item->data);
if (det_ctx->keyword_ctxs_array[item->id] == NULL) {
SCLogError(SC_ERR_DETECT_PREPARE, "setting up thread local detect ctx "
"for keyword \"%s\" failed", item->name);
return TM_ECODE_FAILED;
}
item = item->next;
}
}
return TM_ECODE_OK;
}
static void DetectEngineThreadCtxDeinitKeywords(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx)
{
if (de_ctx->keyword_id > 0) {
DetectEngineThreadKeywordCtxItem *item = de_ctx->keyword_list;
while (item) {
if (det_ctx->keyword_ctxs_array[item->id] != NULL)
item->FreeFunc(det_ctx->keyword_ctxs_array[item->id]);
item = item->next;
}
det_ctx->keyword_ctxs_size = 0;
SCFree(det_ctx->keyword_ctxs_array);
det_ctx->keyword_ctxs_array = NULL;
}
}
/** NOTE: master MUST be locked before calling this */
static TmEcode DetectEngineThreadCtxInitForMT(ThreadVars *tv, DetectEngineThreadCtx *det_ctx)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
DetectEngineTenantMapping *map_array = NULL;
uint32_t map_array_size = 0;
uint32_t map_cnt = 0;
int max_tenant_id = 0;
DetectEngineCtx *list = master->list;
HashTable *mt_det_ctxs_hash = NULL;
if (master->tenant_selector == TENANT_SELECTOR_UNKNOWN) {
SCLogError(SC_ERR_MT_NO_SELECTOR, "no tenant selector set: "
"set using multi-detect.selector");
return TM_ECODE_FAILED;
}
uint32_t tcnt = 0;
while (list) {
if (list->tenant_id > max_tenant_id)
max_tenant_id = list->tenant_id;
list = list->next;
tcnt++;
}
mt_det_ctxs_hash = HashTableInit(tcnt * 2, TenantIdHash, TenantIdCompare, TenantIdFree);
if (mt_det_ctxs_hash == NULL) {
goto error;
}
if (tcnt == 0) {
SCLogInfo("no tenants left, or none registered yet");
} else {
max_tenant_id++;
DetectEngineTenantMapping *map = master->tenant_mapping_list;
while (map) {
map_cnt++;
map = map->next;
}
if (map_cnt > 0) {
map_array_size = map_cnt + 1;
map_array = SCCalloc(map_array_size, sizeof(*map_array));
if (map_array == NULL)
goto error;
/* fill the array */
map_cnt = 0;
map = master->tenant_mapping_list;
while (map) {
if (map_cnt >= map_array_size) {
goto error;
}
map_array[map_cnt].traffic_id = map->traffic_id;
map_array[map_cnt].tenant_id = map->tenant_id;
map_cnt++;
map = map->next;
}
}
/* set up hash for tenant lookup */
list = master->list;
while (list) {
SCLogDebug("tenant-id %u", list->tenant_id);
if (list->tenant_id != 0) {
DetectEngineThreadCtx *mt_det_ctx = DetectEngineThreadCtxInitForReload(tv, list, 0);
if (mt_det_ctx == NULL)
goto error;
if (HashTableAdd(mt_det_ctxs_hash, mt_det_ctx, 0) != 0) {
goto error;
}
}
list = list->next;
}
}
det_ctx->mt_det_ctxs_hash = mt_det_ctxs_hash;
mt_det_ctxs_hash = NULL;
det_ctx->mt_det_ctxs_cnt = max_tenant_id;
det_ctx->tenant_array = map_array;
det_ctx->tenant_array_size = map_array_size;
switch (master->tenant_selector) {
case TENANT_SELECTOR_UNKNOWN:
SCLogDebug("TENANT_SELECTOR_UNKNOWN");
break;
case TENANT_SELECTOR_VLAN:
det_ctx->TenantGetId = DetectEngineTentantGetIdFromVlanId;
SCLogDebug("TENANT_SELECTOR_VLAN");
break;
case TENANT_SELECTOR_LIVEDEV:
det_ctx->TenantGetId = DetectEngineTentantGetIdFromLivedev;
SCLogDebug("TENANT_SELECTOR_LIVEDEV");
break;
case TENANT_SELECTOR_DIRECT:
det_ctx->TenantGetId = DetectEngineTentantGetIdFromPcap;
SCLogDebug("TENANT_SELECTOR_DIRECT");
break;
}
return TM_ECODE_OK;
error:
if (map_array != NULL)
SCFree(map_array);
if (mt_det_ctxs_hash != NULL)
HashTableFree(mt_det_ctxs_hash);
return TM_ECODE_FAILED;
}
/** \internal
* \brief Helper for DetectThread setup functions
*/
static TmEcode ThreadCtxDoInit (DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx)
{
PatternMatchThreadPrepare(&det_ctx->mtc, de_ctx->mpm_matcher);
PatternMatchThreadPrepare(&det_ctx->mtcs, de_ctx->mpm_matcher);
PatternMatchThreadPrepare(&det_ctx->mtcu, de_ctx->mpm_matcher);
PmqSetup(&det_ctx->pmq);
det_ctx->spm_thread_ctx = SpmMakeThreadCtx(de_ctx->spm_global_thread_ctx);
if (det_ctx->spm_thread_ctx == NULL) {
return TM_ECODE_FAILED;
}
/* sized to the max of our sgh settings. A max setting of 0 implies that all
* sgh's have: sgh->non_pf_store_cnt == 0 */
if (de_ctx->non_pf_store_cnt_max > 0) {
det_ctx->non_pf_id_array = SCCalloc(de_ctx->non_pf_store_cnt_max, sizeof(SigIntId));
BUG_ON(det_ctx->non_pf_id_array == NULL);
}
/* IP-ONLY */
DetectEngineIPOnlyThreadInit(de_ctx,&det_ctx->io_ctx);
/* DeState */
if (de_ctx->sig_array_len > 0) {
det_ctx->match_array_len = de_ctx->sig_array_len;
det_ctx->match_array = SCMalloc(det_ctx->match_array_len * sizeof(Signature *));
if (det_ctx->match_array == NULL) {
return TM_ECODE_FAILED;
}
memset(det_ctx->match_array, 0,
det_ctx->match_array_len * sizeof(Signature *));
RuleMatchCandidateTxArrayInit(det_ctx, de_ctx->sig_array_len);
}
/* byte_extract storage */
det_ctx->bj_values = SCMalloc(sizeof(*det_ctx->bj_values) *
(de_ctx->byte_extract_max_local_id + 1));
if (det_ctx->bj_values == NULL) {
return TM_ECODE_FAILED;
}
/* Allocate space for base64 decoded data. */
if (de_ctx->base64_decode_max_len) {
det_ctx->base64_decoded = SCMalloc(de_ctx->base64_decode_max_len);
if (det_ctx->base64_decoded == NULL) {
return TM_ECODE_FAILED;
}
det_ctx->base64_decoded_len_max = de_ctx->base64_decode_max_len;
det_ctx->base64_decoded_len = 0;
}
det_ctx->inspect.buffers_size = de_ctx->buffer_type_id;
det_ctx->inspect.buffers = SCCalloc(det_ctx->inspect.buffers_size, sizeof(InspectionBuffer));
if (det_ctx->inspect.buffers == NULL) {
return TM_ECODE_FAILED;
}
det_ctx->inspect.to_clear_queue = SCCalloc(det_ctx->inspect.buffers_size, sizeof(uint32_t));
if (det_ctx->inspect.to_clear_queue == NULL) {
return TM_ECODE_FAILED;
}
det_ctx->inspect.to_clear_idx = 0;
det_ctx->multi_inspect.buffers_size = de_ctx->buffer_type_id;
det_ctx->multi_inspect.buffers = SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(InspectionBufferMultipleForList));
if (det_ctx->multi_inspect.buffers == NULL) {
return TM_ECODE_FAILED;
}
det_ctx->multi_inspect.to_clear_queue = SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(uint32_t));
if (det_ctx->multi_inspect.to_clear_queue == NULL) {
return TM_ECODE_FAILED;
}
det_ctx->multi_inspect.to_clear_idx = 0;
DetectEngineThreadCtxInitKeywords(de_ctx, det_ctx);
DetectEngineThreadCtxInitGlobalKeywords(det_ctx);
#ifdef PROFILING
SCProfilingRuleThreadSetup(de_ctx->profile_ctx, det_ctx);
SCProfilingKeywordThreadSetup(de_ctx->profile_keyword_ctx, det_ctx);
SCProfilingPrefilterThreadSetup(de_ctx->profile_prefilter_ctx, det_ctx);
SCProfilingSghThreadSetup(de_ctx->profile_sgh_ctx, det_ctx);
#endif
SC_ATOMIC_INIT(det_ctx->so_far_used_by_detect);
return TM_ECODE_OK;
}
/** \brief initialize thread specific detection engine context
*
* \note there is a special case when using delayed detect. In this case the
* function is called twice per thread. The first time the rules are not
* yet loaded. de_ctx->delayed_detect_initialized will be 0. The 2nd
* time they will be loaded. de_ctx->delayed_detect_initialized will be 1.
* This is needed to do the per thread counter registration before the
* packet runtime starts. In delayed detect mode, the first call will
* return a NULL ptr through the data ptr.
*
* \param tv ThreadVars for this thread
* \param initdata pointer to de_ctx
* \param data[out] pointer to store our thread detection ctx
*
* \retval TM_ECODE_OK if all went well
* \retval TM_ECODE_FAILED on serious erro
*/
TmEcode DetectEngineThreadCtxInit(ThreadVars *tv, void *initdata, void **data)
{
DetectEngineThreadCtx *det_ctx = SCMalloc(sizeof(DetectEngineThreadCtx));
if (unlikely(det_ctx == NULL))
return TM_ECODE_FAILED;
memset(det_ctx, 0, sizeof(DetectEngineThreadCtx));
det_ctx->tv = tv;
det_ctx->de_ctx = DetectEngineGetCurrent();
if (det_ctx->de_ctx == NULL) {
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
det_ctx->de_ctx = (DetectEngineCtx *)initdata;
} else {
DetectEngineThreadCtxDeinit(tv, det_ctx);
return TM_ECODE_FAILED;
}
#else
DetectEngineThreadCtxDeinit(tv, det_ctx);
return TM_ECODE_FAILED;
#endif
}
if (det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT)
{
if (ThreadCtxDoInit(det_ctx->de_ctx, det_ctx) != TM_ECODE_OK) {
DetectEngineThreadCtxDeinit(tv, det_ctx);
return TM_ECODE_FAILED;
}
}
/** alert counter setup */
det_ctx->counter_alerts = StatsRegisterCounter("detect.alert", tv);
#ifdef PROFILING
det_ctx->counter_mpm_list = StatsRegisterAvgCounter("detect.mpm_list", tv);
det_ctx->counter_nonmpm_list = StatsRegisterAvgCounter("detect.nonmpm_list", tv);
det_ctx->counter_fnonmpm_list = StatsRegisterAvgCounter("detect.fnonmpm_list", tv);
det_ctx->counter_match_list = StatsRegisterAvgCounter("detect.match_list", tv);
#endif
if (DetectEngineMultiTenantEnabled()) {
if (DetectEngineThreadCtxInitForMT(tv, det_ctx) != TM_ECODE_OK) {
DetectEngineThreadCtxDeinit(tv, det_ctx);
return TM_ECODE_FAILED;
}
}
/* pass thread data back to caller */
*data = (void *)det_ctx;
return TM_ECODE_OK;
}
/**
* \internal
* \brief initialize a det_ctx for reload cases
* \param new_de_ctx the new detection engine
* \param mt flag to indicate if MT should be set up for this det_ctx
* this should only be done for the 'root' det_ctx
*
* \retval det_ctx detection engine thread ctx or NULL in case of error
*/
static DetectEngineThreadCtx *DetectEngineThreadCtxInitForReload(
ThreadVars *tv, DetectEngineCtx *new_de_ctx, int mt)
{
DetectEngineThreadCtx *det_ctx = SCMalloc(sizeof(DetectEngineThreadCtx));
if (unlikely(det_ctx == NULL))
return NULL;
memset(det_ctx, 0, sizeof(DetectEngineThreadCtx));
det_ctx->tenant_id = new_de_ctx->tenant_id;
det_ctx->tv = tv;
det_ctx->de_ctx = DetectEngineReference(new_de_ctx);
if (det_ctx->de_ctx == NULL) {
SCFree(det_ctx);
return NULL;
}
/* most of the init happens here */
if (det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT)
{
if (ThreadCtxDoInit(det_ctx->de_ctx, det_ctx) != TM_ECODE_OK) {
DetectEngineDeReference(&det_ctx->de_ctx);
SCFree(det_ctx);
return NULL;
}
}
/** alert counter setup */
det_ctx->counter_alerts = StatsRegisterCounter("detect.alert", tv);
#ifdef PROFILING
uint16_t counter_mpm_list = StatsRegisterAvgCounter("detect.mpm_list", tv);
uint16_t counter_nonmpm_list = StatsRegisterAvgCounter("detect.nonmpm_list", tv);
uint16_t counter_fnonmpm_list = StatsRegisterAvgCounter("detect.fnonmpm_list", tv);
uint16_t counter_match_list = StatsRegisterAvgCounter("detect.match_list", tv);
det_ctx->counter_mpm_list = counter_mpm_list;
det_ctx->counter_nonmpm_list = counter_nonmpm_list;
det_ctx->counter_fnonmpm_list = counter_fnonmpm_list;
det_ctx->counter_match_list = counter_match_list;
#endif
if (mt && DetectEngineMultiTenantEnabled()) {
if (DetectEngineThreadCtxInitForMT(tv, det_ctx) != TM_ECODE_OK) {
DetectEngineDeReference(&det_ctx->de_ctx);
SCFree(det_ctx);
return NULL;
}
}
return det_ctx;
}
static void DetectEngineThreadCtxFree(DetectEngineThreadCtx *det_ctx)
{
#if DEBUG
SCLogDebug("PACKET PKT_STREAM_ADD: %"PRIu64, det_ctx->pkt_stream_add_cnt);
SCLogDebug("PAYLOAD MPM %"PRIu64"/%"PRIu64, det_ctx->payload_mpm_cnt, det_ctx->payload_mpm_size);
SCLogDebug("STREAM MPM %"PRIu64"/%"PRIu64, det_ctx->stream_mpm_cnt, det_ctx->stream_mpm_size);
SCLogDebug("PAYLOAD SIG %"PRIu64"/%"PRIu64, det_ctx->payload_persig_cnt, det_ctx->payload_persig_size);
SCLogDebug("STREAM SIG %"PRIu64"/%"PRIu64, det_ctx->stream_persig_cnt, det_ctx->stream_persig_size);
#endif
if (det_ctx->tenant_array != NULL) {
SCFree(det_ctx->tenant_array);
det_ctx->tenant_array = NULL;
}
#ifdef PROFILING
SCProfilingRuleThreadCleanup(det_ctx);
SCProfilingKeywordThreadCleanup(det_ctx);
SCProfilingPrefilterThreadCleanup(det_ctx);
SCProfilingSghThreadCleanup(det_ctx);
#endif
DetectEngineIPOnlyThreadDeinit(&det_ctx->io_ctx);
/** \todo get rid of this static */
if (det_ctx->de_ctx != NULL) {
PatternMatchThreadDestroy(&det_ctx->mtc, det_ctx->de_ctx->mpm_matcher);
PatternMatchThreadDestroy(&det_ctx->mtcs, det_ctx->de_ctx->mpm_matcher);
PatternMatchThreadDestroy(&det_ctx->mtcu, det_ctx->de_ctx->mpm_matcher);
}
PmqFree(&det_ctx->pmq);
if (det_ctx->spm_thread_ctx != NULL) {
SpmDestroyThreadCtx(det_ctx->spm_thread_ctx);
}
if (det_ctx->non_pf_id_array != NULL)
SCFree(det_ctx->non_pf_id_array);
if (det_ctx->match_array != NULL)
SCFree(det_ctx->match_array);
RuleMatchCandidateTxArrayFree(det_ctx);
if (det_ctx->bj_values != NULL)
SCFree(det_ctx->bj_values);
/* Decoded base64 data. */
if (det_ctx->base64_decoded != NULL) {
SCFree(det_ctx->base64_decoded);
}
if (det_ctx->inspect.buffers) {
for (uint32_t i = 0; i < det_ctx->inspect.buffers_size; i++) {
InspectionBufferFree(&det_ctx->inspect.buffers[i]);
}
SCFree(det_ctx->inspect.buffers);
}
if (det_ctx->inspect.to_clear_queue) {
SCFree(det_ctx->inspect.to_clear_queue);
}
if (det_ctx->multi_inspect.buffers) {
for (uint32_t i = 0; i < det_ctx->multi_inspect.buffers_size; i++) {
InspectionBufferMultipleForList *fb = &det_ctx->multi_inspect.buffers[i];
for (uint32_t x = 0; x < fb->size; x++) {
InspectionBufferFree(&fb->inspection_buffers[x]);
}
SCFree(fb->inspection_buffers);
}
SCFree(det_ctx->multi_inspect.buffers);
}
if (det_ctx->multi_inspect.to_clear_queue) {
SCFree(det_ctx->multi_inspect.to_clear_queue);
}
DetectEngineThreadCtxDeinitGlobalKeywords(det_ctx);
if (det_ctx->de_ctx != NULL) {
DetectEngineThreadCtxDeinitKeywords(det_ctx->de_ctx, det_ctx);
#ifdef UNITTESTS
if (!RunmodeIsUnittests() || det_ctx->de_ctx->ref_cnt > 0)
DetectEngineDeReference(&det_ctx->de_ctx);
#else
DetectEngineDeReference(&det_ctx->de_ctx);
#endif
}
AppLayerDecoderEventsFreeEvents(&det_ctx->decoder_events);
SCFree(det_ctx);
}
TmEcode DetectEngineThreadCtxDeinit(ThreadVars *tv, void *data)
{
DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;
if (det_ctx == NULL) {
SCLogWarning(SC_ERR_INVALID_ARGUMENTS, "argument \"data\" NULL");
return TM_ECODE_OK;
}
if (det_ctx->mt_det_ctxs_hash != NULL) {
HashTableFree(det_ctx->mt_det_ctxs_hash);
det_ctx->mt_det_ctxs_hash = NULL;
}
DetectEngineThreadCtxFree(det_ctx);
return TM_ECODE_OK;
}
void DetectEngineThreadCtxInfo(ThreadVars *t, DetectEngineThreadCtx *det_ctx)
{
/* XXX */
PatternMatchThreadPrint(&det_ctx->mtc, det_ctx->de_ctx->mpm_matcher);
PatternMatchThreadPrint(&det_ctx->mtcu, det_ctx->de_ctx->mpm_matcher);
}
/** \brief Register Thread keyword context Funcs
*
* \param de_ctx detection engine to register in
* \param name keyword name for error printing
* \param InitFunc function ptr
* \param data keyword init data to pass to Func
* \param FreeFunc function ptr
* \param mode 0 normal (ctx per keyword instance) 1 shared (one ctx per det_ct)
*
* \retval id for retrieval of ctx at runtime
* \retval -1 on error
*
* \note make sure "data" remains valid and it free'd elsewhere. It's
* recommended to store it in the keywords global ctx so that
* it's freed when the de_ctx is freed.
*/
int DetectRegisterThreadCtxFuncs(DetectEngineCtx *de_ctx, const char *name, void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *), int mode)
{
BUG_ON(de_ctx == NULL || InitFunc == NULL || FreeFunc == NULL || data == NULL);
if (mode) {
DetectEngineThreadKeywordCtxItem *item = de_ctx->keyword_list;
while (item != NULL) {
if (strcmp(name, item->name) == 0) {
return item->id;
}
item = item->next;
}
}
DetectEngineThreadKeywordCtxItem *item = SCMalloc(sizeof(DetectEngineThreadKeywordCtxItem));
if (unlikely(item == NULL))
return -1;
memset(item, 0x00, sizeof(DetectEngineThreadKeywordCtxItem));
item->InitFunc = InitFunc;
item->FreeFunc = FreeFunc;
item->data = data;
item->name = name;
item->next = de_ctx->keyword_list;
de_ctx->keyword_list = item;
item->id = de_ctx->keyword_id++;
return item->id;
}
/** \brief Retrieve thread local keyword ctx by id
*
* \param det_ctx detection engine thread ctx to retrieve the ctx from
* \param id id of the ctx returned by DetectRegisterThreadCtxInitFunc at
* keyword init.
*
* \retval ctx or NULL on error
*/
void *DetectThreadCtxGetKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id)
{
if (id < 0 || id > det_ctx->keyword_ctxs_size || det_ctx->keyword_ctxs_array == NULL)
return NULL;
return det_ctx->keyword_ctxs_array[id];
}
/** \brief Register Thread keyword context Funcs (Global)
*
* IDs stay static over reloads and between tenants
*
* \param name keyword name for error printing
* \param InitFunc function ptr
* \param FreeFunc function ptr
*
* \retval id for retrieval of ctx at runtime
* \retval -1 on error
*/
int DetectRegisterThreadCtxGlobalFuncs(const char *name,
void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *))
{
int id;
BUG_ON(InitFunc == NULL || FreeFunc == NULL);
DetectEngineMasterCtx *master = &g_master_de_ctx;
/* if already registered, return existing id */
DetectEngineThreadKeywordCtxItem *item = master->keyword_list;
while (item != NULL) {
if (strcmp(name, item->name) == 0) {
id = item->id;
return id;
}
item = item->next;
}
item = SCCalloc(1, sizeof(*item));
if (unlikely(item == NULL)) {
return -1;
}
item->InitFunc = InitFunc;
item->FreeFunc = FreeFunc;
item->name = name;
item->data = data;
item->next = master->keyword_list;
master->keyword_list = item;
item->id = master->keyword_id++;
id = item->id;
return id;
}
/** \brief Retrieve thread local keyword ctx by id
*
* \param det_ctx detection engine thread ctx to retrieve the ctx from
* \param id id of the ctx returned by DetectRegisterThreadCtxInitFunc at
* keyword init.
*
* \retval ctx or NULL on error
*/
void *DetectThreadCtxGetGlobalKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id)
{
if (id < 0 || id > det_ctx->global_keyword_ctxs_size ||
det_ctx->global_keyword_ctxs_array == NULL) {
return NULL;
}
return det_ctx->global_keyword_ctxs_array[id];
}
/** \brief Check if detection is enabled
* \retval bool true or false */
int DetectEngineEnabled(void)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
if (master->list == NULL) {
SCMutexUnlock(&master->lock);
return 0;
}
SCMutexUnlock(&master->lock);
return 1;
}
uint32_t DetectEngineGetVersion(void)
{
uint32_t version;
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
version = master->version;
SCMutexUnlock(&master->lock);
return version;
}
void DetectEngineBumpVersion(void)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
master->version++;
SCLogDebug("master version now %u", master->version);
SCMutexUnlock(&master->lock);
}
DetectEngineCtx *DetectEngineGetCurrent(void)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
DetectEngineCtx *de_ctx = master->list;
while (de_ctx) {
if (de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB ||
de_ctx->type == DETECT_ENGINE_TYPE_MT_STUB)
{
de_ctx->ref_cnt++;
SCLogDebug("de_ctx %p ref_cnt %u", de_ctx, de_ctx->ref_cnt);
SCMutexUnlock(&master->lock);
return de_ctx;
}
de_ctx = de_ctx->next;
}
SCMutexUnlock(&master->lock);
return NULL;
}
DetectEngineCtx *DetectEngineReference(DetectEngineCtx *de_ctx)
{
if (de_ctx == NULL)
return NULL;
de_ctx->ref_cnt++;
return de_ctx;
}
/** TODO locking? Not needed if this is a one time setting at startup */
int DetectEngineMultiTenantEnabled(void)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
return (master->multi_tenant_enabled);
}
/** \internal
* \brief load a tenant from a yaml file
*
* \param tenant_id the tenant id by which the config is known
* \param filename full path of a yaml file
* \param loader_id id of loader thread or -1
*
* \retval 0 ok
* \retval -1 failed
*/
static int DetectEngineMultiTenantLoadTenant(uint32_t tenant_id, const char *filename, int loader_id)
{
DetectEngineCtx *de_ctx = NULL;
char prefix[64];
snprintf(prefix, sizeof(prefix), "multi-detect.%d", tenant_id);
#ifdef OS_WIN32
struct _stat st;
if(_stat(filename, &st) != 0) {
#else
struct stat st;
if(stat(filename, &st) != 0) {
#endif /* OS_WIN32 */
SCLogError(SC_ERR_FOPEN, "failed to stat file %s", filename);
goto error;
}
de_ctx = DetectEngineGetByTenantId(tenant_id);
if (de_ctx != NULL) {
SCLogError(SC_ERR_MT_DUPLICATE_TENANT, "tenant %u already registered",
tenant_id);
DetectEngineDeReference(&de_ctx);
goto error;
}
ConfNode *node = ConfGetNode(prefix);
if (node == NULL) {
SCLogError(SC_ERR_CONF_YAML_ERROR, "failed to properly setup yaml %s", filename);
goto error;
}
de_ctx = DetectEngineCtxInitWithPrefix(prefix);
if (de_ctx == NULL) {
SCLogError(SC_ERR_INITIALIZATION, "initializing detection engine "
"context failed.");
goto error;
}
SCLogDebug("de_ctx %p with prefix %s", de_ctx, de_ctx->config_prefix);
de_ctx->type = DETECT_ENGINE_TYPE_TENANT;
de_ctx->tenant_id = tenant_id;
de_ctx->loader_id = loader_id;
if (SigLoadSignatures(de_ctx, NULL, 0) < 0) {
SCLogError(SC_ERR_NO_RULES_LOADED, "Loading signatures failed.");
goto error;
}
DetectEngineAddToMaster(de_ctx);
return 0;
error:
if (de_ctx != NULL) {
DetectEngineCtxFree(de_ctx);
}
return -1;
}
static int DetectEngineMultiTenantReloadTenant(uint32_t tenant_id, const char *filename, int reload_cnt)
{
DetectEngineCtx *old_de_ctx = DetectEngineGetByTenantId(tenant_id);
if (old_de_ctx == NULL) {
SCLogError(SC_ERR_INITIALIZATION, "tenant detect engine not found");
return -1;
}
char prefix[64];
snprintf(prefix, sizeof(prefix), "multi-detect.%d.reload.%d", tenant_id, reload_cnt);
reload_cnt++;
SCLogDebug("prefix %s", prefix);
if (ConfYamlLoadFileWithPrefix(filename, prefix) != 0) {
SCLogError(SC_ERR_INITIALIZATION,"failed to load yaml");
goto error;
}
ConfNode *node = ConfGetNode(prefix);
if (node == NULL) {
SCLogError(SC_ERR_CONF_YAML_ERROR, "failed to properly setup yaml %s", filename);
goto error;
}
DetectEngineCtx *new_de_ctx = DetectEngineCtxInitWithPrefix(prefix);
if (new_de_ctx == NULL) {
SCLogError(SC_ERR_INITIALIZATION, "initializing detection engine "
"context failed.");
goto error;
}
SCLogDebug("de_ctx %p with prefix %s", new_de_ctx, new_de_ctx->config_prefix);
new_de_ctx->type = DETECT_ENGINE_TYPE_TENANT;
new_de_ctx->tenant_id = tenant_id;
new_de_ctx->loader_id = old_de_ctx->loader_id;
if (SigLoadSignatures(new_de_ctx, NULL, 0) < 0) {
SCLogError(SC_ERR_NO_RULES_LOADED, "Loading signatures failed.");
goto error;
}
DetectEngineAddToMaster(new_de_ctx);
/* move to free list */
DetectEngineMoveToFreeList(old_de_ctx);
DetectEngineDeReference(&old_de_ctx);
return 0;
error:
DetectEngineDeReference(&old_de_ctx);
return -1;
}
typedef struct TenantLoaderCtx_ {
uint32_t tenant_id;
int reload_cnt; /**< used by reload */
const char *yaml;
} TenantLoaderCtx;
static int DetectLoaderFuncLoadTenant(void *vctx, int loader_id)
{
TenantLoaderCtx *ctx = (TenantLoaderCtx *)vctx;
SCLogDebug("loader %d", loader_id);
if (DetectEngineMultiTenantLoadTenant(ctx->tenant_id, ctx->yaml, loader_id) != 0) {
return -1;
}
return 0;
}
static int DetectLoaderSetupLoadTenant(uint32_t tenant_id, const char *yaml)
{
TenantLoaderCtx *t = SCCalloc(1, sizeof(*t));
if (t == NULL)
return -ENOMEM;
t->tenant_id = tenant_id;
t->yaml = yaml;
return DetectLoaderQueueTask(-1, DetectLoaderFuncLoadTenant, t);
}
static int DetectLoaderFuncReloadTenant(void *vctx, int loader_id)
{
TenantLoaderCtx *ctx = (TenantLoaderCtx *)vctx;
SCLogDebug("loader_id %d", loader_id);
if (DetectEngineMultiTenantReloadTenant(ctx->tenant_id, ctx->yaml, ctx->reload_cnt) != 0) {
return -1;
}
return 0;
}
static int DetectLoaderSetupReloadTenant(uint32_t tenant_id, const char *yaml, int reload_cnt)
{
DetectEngineCtx *old_de_ctx = DetectEngineGetByTenantId(tenant_id);
if (old_de_ctx == NULL)
return -ENOENT;
int loader_id = old_de_ctx->loader_id;
DetectEngineDeReference(&old_de_ctx);
TenantLoaderCtx *t = SCCalloc(1, sizeof(*t));
if (t == NULL)
return -ENOMEM;
t->tenant_id = tenant_id;
t->yaml = yaml;
t->reload_cnt = reload_cnt;
SCLogDebug("loader_id %d", loader_id);
return DetectLoaderQueueTask(loader_id, DetectLoaderFuncReloadTenant, t);
}
/** \brief Load a tenant and wait for loading to complete
*/
int DetectEngineLoadTenantBlocking(uint32_t tenant_id, const char *yaml)
{
int r = DetectLoaderSetupLoadTenant(tenant_id, yaml);
if (r < 0)
return r;
if (DetectLoadersSync() != 0)
return -1;
return 0;
}
/** \brief Reload a tenant and wait for loading to complete
*/
int DetectEngineReloadTenantBlocking(uint32_t tenant_id, const char *yaml, int reload_cnt)
{
int r = DetectLoaderSetupReloadTenant(tenant_id, yaml, reload_cnt);
if (r < 0)
return r;
if (DetectLoadersSync() != 0)
return -1;
return 0;
}
static int DetectEngineMultiTenantSetupLoadLivedevMappings(const ConfNode *mappings_root_node,
bool failure_fatal)
{
ConfNode *mapping_node = NULL;
int mapping_cnt = 0;
if (mappings_root_node != NULL) {
TAILQ_FOREACH(mapping_node, &mappings_root_node->head, next) {
ConfNode *tenant_id_node = ConfNodeLookupChild(mapping_node, "tenant-id");
if (tenant_id_node == NULL)
goto bad_mapping;
ConfNode *device_node = ConfNodeLookupChild(mapping_node, "device");
if (device_node == NULL)
goto bad_mapping;
uint32_t tenant_id = 0;
if (ByteExtractStringUint32(&tenant_id, 10, strlen(tenant_id_node->val),
tenant_id_node->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "tenant-id "
"of %s is invalid", tenant_id_node->val);
goto bad_mapping;
}
const char *dev = device_node->val;
LiveDevice *ld = LiveGetDevice(dev);
if (ld == NULL) {
SCLogWarning(SC_ERR_MT_NO_MAPPING, "device %s not found", dev);
goto bad_mapping;
}
if (ld->tenant_id_set) {
SCLogWarning(SC_ERR_MT_NO_MAPPING, "device %s already mapped to tenant-id %u",
dev, ld->tenant_id);
goto bad_mapping;
}
ld->tenant_id = tenant_id;
ld->tenant_id_set = true;
if (DetectEngineTentantRegisterLivedev(tenant_id, ld->id) != 0) {
goto error;
}
SCLogConfig("device %s connected to tenant-id %u", dev, tenant_id);
mapping_cnt++;
continue;
bad_mapping:
if (failure_fatal)
goto error;
}
}
SCLogConfig("%d device - tenant-id mappings defined", mapping_cnt);
return mapping_cnt;
error:
return 0;
}
static int DetectEngineMultiTenantSetupLoadVlanMappings(const ConfNode *mappings_root_node,
bool failure_fatal)
{
ConfNode *mapping_node = NULL;
int mapping_cnt = 0;
if (mappings_root_node != NULL) {
TAILQ_FOREACH(mapping_node, &mappings_root_node->head, next) {
ConfNode *tenant_id_node = ConfNodeLookupChild(mapping_node, "tenant-id");
if (tenant_id_node == NULL)
goto bad_mapping;
ConfNode *vlan_id_node = ConfNodeLookupChild(mapping_node, "vlan-id");
if (vlan_id_node == NULL)
goto bad_mapping;
uint32_t tenant_id = 0;
if (ByteExtractStringUint32(&tenant_id, 10, strlen(tenant_id_node->val),
tenant_id_node->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "tenant-id "
"of %s is invalid", tenant_id_node->val);
goto bad_mapping;
}
uint16_t vlan_id = 0;
if (ByteExtractStringUint16(&vlan_id, 10, strlen(vlan_id_node->val),
vlan_id_node->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "vlan-id "
"of %s is invalid", vlan_id_node->val);
goto bad_mapping;
}
if (vlan_id == 0 || vlan_id >= 4095) {
SCLogError(SC_ERR_INVALID_ARGUMENT, "vlan-id "
"of %s is invalid. Valid range 1-4094.", vlan_id_node->val);
goto bad_mapping;
}
if (DetectEngineTentantRegisterVlanId(tenant_id, (uint32_t)vlan_id) != 0) {
goto error;
}
SCLogConfig("vlan %u connected to tenant-id %u", vlan_id, tenant_id);
mapping_cnt++;
continue;
bad_mapping:
if (failure_fatal)
goto error;
}
}
return mapping_cnt;
error:
return 0;
}
/**
* \brief setup multi-detect / multi-tenancy
*
* See if MT is enabled. If so, setup the selector, tenants and mappings.
* Tenants and mappings are optional, and can also dynamically be added
* and removed from the unix socket.
*/
int DetectEngineMultiTenantSetup(void)
{
enum DetectEngineTenantSelectors tenant_selector = TENANT_SELECTOR_UNKNOWN;
DetectEngineMasterCtx *master = &g_master_de_ctx;
int unix_socket = ConfUnixSocketIsEnable();
int failure_fatal = 0;
(void)ConfGetBool("engine.init-failure-fatal", &failure_fatal);
int enabled = 0;
(void)ConfGetBool("multi-detect.enabled", &enabled);
if (enabled == 1) {
DetectLoadersInit();
TmModuleDetectLoaderRegister();
DetectLoaderThreadSpawn();
TmThreadContinueDetectLoaderThreads();
SCMutexLock(&master->lock);
master->multi_tenant_enabled = 1;
const char *handler = NULL;
if (ConfGet("multi-detect.selector", &handler) == 1) {
SCLogConfig("multi-tenant selector type %s", handler);
if (strcmp(handler, "vlan") == 0) {
tenant_selector = master->tenant_selector = TENANT_SELECTOR_VLAN;
int vlanbool = 0;
if ((ConfGetBool("vlan.use-for-tracking", &vlanbool)) == 1 && vlanbool == 0) {
SCLogError(SC_ERR_INVALID_VALUE, "vlan tracking is disabled, "
"can't use multi-detect selector 'vlan'");
SCMutexUnlock(&master->lock);
goto error;
}
} else if (strcmp(handler, "direct") == 0) {
tenant_selector = master->tenant_selector = TENANT_SELECTOR_DIRECT;
} else if (strcmp(handler, "device") == 0) {
tenant_selector = master->tenant_selector = TENANT_SELECTOR_LIVEDEV;
if (EngineModeIsIPS()) {
SCLogWarning(SC_ERR_MT_NO_MAPPING,
"multi-tenant 'device' mode not supported for IPS");
SCMutexUnlock(&master->lock);
goto error;
}
} else {
SCLogError(SC_ERR_INVALID_VALUE, "unknown value %s "
"multi-detect.selector", handler);
SCMutexUnlock(&master->lock);
goto error;
}
}
SCMutexUnlock(&master->lock);
SCLogConfig("multi-detect is enabled (multi tenancy). Selector: %s", handler);
/* traffic -- tenant mappings */
ConfNode *mappings_root_node = ConfGetNode("multi-detect.mappings");
if (tenant_selector == TENANT_SELECTOR_VLAN) {
int mapping_cnt = DetectEngineMultiTenantSetupLoadVlanMappings(mappings_root_node,
failure_fatal);
if (mapping_cnt == 0) {
/* no mappings are valid when we're in unix socket mode,
* they can be added on the fly. Otherwise warn/error
* depending on failure_fatal */
if (unix_socket) {
SCLogNotice("no tenant traffic mappings defined, "
"tenants won't be used until mappings are added");
} else {
if (failure_fatal) {
SCLogError(SC_ERR_MT_NO_MAPPING, "no multi-detect mappings defined");
goto error;
} else {
SCLogWarning(SC_ERR_MT_NO_MAPPING, "no multi-detect mappings defined");
}
}
}
} else if (tenant_selector == TENANT_SELECTOR_LIVEDEV) {
int mapping_cnt = DetectEngineMultiTenantSetupLoadLivedevMappings(mappings_root_node,
failure_fatal);
if (mapping_cnt == 0) {
if (failure_fatal) {
SCLogError(SC_ERR_MT_NO_MAPPING, "no multi-detect mappings defined");
goto error;
} else {
SCLogWarning(SC_ERR_MT_NO_MAPPING, "no multi-detect mappings defined");
}
}
}
/* tenants */
ConfNode *tenants_root_node = ConfGetNode("multi-detect.tenants");
ConfNode *tenant_node = NULL;
if (tenants_root_node != NULL) {
TAILQ_FOREACH(tenant_node, &tenants_root_node->head, next) {
ConfNode *id_node = ConfNodeLookupChild(tenant_node, "id");
if (id_node == NULL) {
goto bad_tenant;
}
ConfNode *yaml_node = ConfNodeLookupChild(tenant_node, "yaml");
if (yaml_node == NULL) {
goto bad_tenant;
}
uint32_t tenant_id = 0;
if (ByteExtractStringUint32(&tenant_id, 10, strlen(id_node->val),
id_node->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "tenant_id "
"of %s is invalid", id_node->val);
goto bad_tenant;
}
SCLogDebug("tenant id: %u, %s", tenant_id, yaml_node->val);
/* setup the yaml in this loop so that it's not done by the loader
* threads. ConfYamlLoadFileWithPrefix is not thread safe. */
char prefix[64];
snprintf(prefix, sizeof(prefix), "multi-detect.%d", tenant_id);
if (ConfYamlLoadFileWithPrefix(yaml_node->val, prefix) != 0) {
SCLogError(SC_ERR_CONF_YAML_ERROR, "failed to load yaml %s", yaml_node->val);
goto bad_tenant;
}
int r = DetectLoaderSetupLoadTenant(tenant_id, yaml_node->val);
if (r < 0) {
/* error logged already */
goto bad_tenant;
}
continue;
bad_tenant:
if (failure_fatal)
goto error;
}
}
/* wait for our loaders to complete their tasks */
if (DetectLoadersSync() != 0) {
goto error;
}
VarNameStoreActivateStaging();
} else {
SCLogDebug("multi-detect not enabled (multi tenancy)");
}
return 0;
error:
return -1;
}
static uint32_t DetectEngineTentantGetIdFromVlanId(const void *ctx, const Packet *p)
{
const DetectEngineThreadCtx *det_ctx = ctx;
uint32_t x = 0;
uint32_t vlan_id = 0;
if (p->vlan_idx == 0)
return 0;
vlan_id = p->vlan_id[0];
if (det_ctx == NULL || det_ctx->tenant_array == NULL || det_ctx->tenant_array_size == 0)
return 0;
/* not very efficient, but for now we're targeting only limited amounts.
* Can use hash/tree approach later. */
for (x = 0; x < det_ctx->tenant_array_size; x++) {
if (det_ctx->tenant_array[x].traffic_id == vlan_id)
return det_ctx->tenant_array[x].tenant_id;
}
return 0;
}
static uint32_t DetectEngineTentantGetIdFromLivedev(const void *ctx, const Packet *p)
{
const DetectEngineThreadCtx *det_ctx = ctx;
const LiveDevice *ld = p->livedev;
if (ld == NULL || det_ctx == NULL)
return 0;
SCLogDebug("using tenant-id %u for packet on device %s", ld->tenant_id, ld->dev);
return ld->tenant_id;
}
static int DetectEngineTentantRegisterSelector(enum DetectEngineTenantSelectors selector,
uint32_t tenant_id, uint32_t traffic_id)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
if (!(master->tenant_selector == TENANT_SELECTOR_UNKNOWN || master->tenant_selector == selector)) {
SCLogInfo("conflicting selector already set");
SCMutexUnlock(&master->lock);
return -1;
}
DetectEngineTenantMapping *m = master->tenant_mapping_list;
while (m) {
if (m->traffic_id == traffic_id) {
SCLogInfo("traffic id already registered");
SCMutexUnlock(&master->lock);
return -1;
}
m = m->next;
}
DetectEngineTenantMapping *map = SCCalloc(1, sizeof(*map));
if (map == NULL) {
SCLogInfo("memory fail");
SCMutexUnlock(&master->lock);
return -1;
}
map->traffic_id = traffic_id;
map->tenant_id = tenant_id;
map->next = master->tenant_mapping_list;
master->tenant_mapping_list = map;
master->tenant_selector = selector;
SCLogDebug("tenant handler %u %u %u registered", selector, tenant_id, traffic_id);
SCMutexUnlock(&master->lock);
return 0;
}
static int DetectEngineTentantUnregisterSelector(enum DetectEngineTenantSelectors selector,
uint32_t tenant_id, uint32_t traffic_id)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
if (master->tenant_mapping_list == NULL) {
SCMutexUnlock(&master->lock);
return -1;
}
DetectEngineTenantMapping *prev = NULL;
DetectEngineTenantMapping *map = master->tenant_mapping_list;
while (map) {
if (map->traffic_id == traffic_id &&
map->tenant_id == tenant_id)
{
if (prev != NULL)
prev->next = map->next;
else
master->tenant_mapping_list = map->next;
map->next = NULL;
SCFree(map);
SCLogInfo("tenant handler %u %u %u unregistered", selector, tenant_id, traffic_id);
SCMutexUnlock(&master->lock);
return 0;
}
prev = map;
map = map->next;
}
SCMutexUnlock(&master->lock);
return -1;
}
int DetectEngineTentantRegisterLivedev(uint32_t tenant_id, int device_id)
{
return DetectEngineTentantRegisterSelector(TENANT_SELECTOR_LIVEDEV, tenant_id, (uint32_t)device_id);
}
int DetectEngineTentantRegisterVlanId(uint32_t tenant_id, uint16_t vlan_id)
{
return DetectEngineTentantRegisterSelector(TENANT_SELECTOR_VLAN, tenant_id, (uint32_t)vlan_id);
}
int DetectEngineTentantUnregisterVlanId(uint32_t tenant_id, uint16_t vlan_id)
{
return DetectEngineTentantUnregisterSelector(TENANT_SELECTOR_VLAN, tenant_id, (uint32_t)vlan_id);
}
int DetectEngineTentantRegisterPcapFile(uint32_t tenant_id)
{
SCLogInfo("registering %u %d 0", TENANT_SELECTOR_DIRECT, tenant_id);
return DetectEngineTentantRegisterSelector(TENANT_SELECTOR_DIRECT, tenant_id, 0);
}
int DetectEngineTentantUnregisterPcapFile(uint32_t tenant_id)
{
SCLogInfo("unregistering %u %d 0", TENANT_SELECTOR_DIRECT, tenant_id);
return DetectEngineTentantUnregisterSelector(TENANT_SELECTOR_DIRECT, tenant_id, 0);
}
static uint32_t DetectEngineTentantGetIdFromPcap(const void *ctx, const Packet *p)
{
return p->pcap_v.tenant_id;
}
DetectEngineCtx *DetectEngineGetByTenantId(int tenant_id)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
if (master->list == NULL) {
SCMutexUnlock(&master->lock);
return NULL;
}
DetectEngineCtx *de_ctx = master->list;
while (de_ctx) {
if (de_ctx->type == DETECT_ENGINE_TYPE_TENANT &&
de_ctx->tenant_id == tenant_id)
{
de_ctx->ref_cnt++;
break;
}
de_ctx = de_ctx->next;
}
SCMutexUnlock(&master->lock);
return de_ctx;
}
void DetectEngineDeReference(DetectEngineCtx **de_ctx)
{
BUG_ON((*de_ctx)->ref_cnt == 0);
(*de_ctx)->ref_cnt--;
*de_ctx = NULL;
}
static int DetectEngineAddToList(DetectEngineCtx *instance)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
if (instance == NULL)
return -1;
if (master->list == NULL) {
master->list = instance;
} else {
instance->next = master->list;
master->list = instance;
}
return 0;
}
int DetectEngineAddToMaster(DetectEngineCtx *de_ctx)
{
int r;
if (de_ctx == NULL)
return -1;
SCLogDebug("adding de_ctx %p to master", de_ctx);
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
r = DetectEngineAddToList(de_ctx);
SCMutexUnlock(&master->lock);
return r;
}
int DetectEngineMoveToFreeList(DetectEngineCtx *de_ctx)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
DetectEngineCtx *instance = master->list;
if (instance == NULL) {
SCMutexUnlock(&master->lock);
return -1;
}
/* remove from active list */
if (instance == de_ctx) {
master->list = instance->next;
} else {
DetectEngineCtx *prev = instance;
instance = instance->next; /* already checked first element */
while (instance) {
DetectEngineCtx *next = instance->next;
if (instance == de_ctx) {
prev->next = instance->next;
break;
}
prev = instance;
instance = next;
}
if (instance == NULL) {
SCMutexUnlock(&master->lock);
return -1;
}
}
/* instance is now detached from list */
instance->next = NULL;
/* add to free list */
if (master->free_list == NULL) {
master->free_list = instance;
} else {
instance->next = master->free_list;
master->free_list = instance;
}
SCLogDebug("detect engine %p moved to free list (%u refs)", de_ctx, de_ctx->ref_cnt);
SCMutexUnlock(&master->lock);
return 0;
}
void DetectEnginePruneFreeList(void)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
DetectEngineCtx *prev = NULL;
DetectEngineCtx *instance = master->free_list;
while (instance) {
DetectEngineCtx *next = instance->next;
SCLogDebug("detect engine %p has %u ref(s)", instance, instance->ref_cnt);
if (instance->ref_cnt == 0) {
if (prev == NULL) {
master->free_list = next;
} else {
prev->next = next;
}
SCLogDebug("freeing detect engine %p", instance);
DetectEngineCtxFree(instance);
instance = NULL;
}
prev = instance;
instance = next;
}
SCMutexUnlock(&master->lock);
}
static int reloads = 0;
/** \brief Reload the detection engine
*
* \param filename YAML file to load for the detect config
*
* \retval -1 error
* \retval 0 ok
*/
int DetectEngineReload(const SCInstance *suri)
{
DetectEngineCtx *new_de_ctx = NULL;
DetectEngineCtx *old_de_ctx = NULL;
char prefix[128];
memset(prefix, 0, sizeof(prefix));
SCLogNotice("rule reload starting");
if (suri->conf_filename != NULL) {
snprintf(prefix, sizeof(prefix), "detect-engine-reloads.%d", reloads++);
if (ConfYamlLoadFileWithPrefix(suri->conf_filename, prefix) != 0) {
SCLogError(SC_ERR_CONF_YAML_ERROR, "failed to load yaml %s",
suri->conf_filename);
return -1;
}
ConfNode *node = ConfGetNode(prefix);
if (node == NULL) {
SCLogError(SC_ERR_CONF_YAML_ERROR, "failed to properly setup yaml %s",
suri->conf_filename);
return -1;
}
#if 0
ConfDump();
#endif
}
/* get a reference to the current de_ctx */
old_de_ctx = DetectEngineGetCurrent();
if (old_de_ctx == NULL)
return -1;
SCLogDebug("get ref to old_de_ctx %p", old_de_ctx);
/* only reload a regular 'normal' and 'delayed detect stub' detect engines */
if (!(old_de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
old_de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB))
{
DetectEngineDeReference(&old_de_ctx);
SCLogNotice("rule reload complete");
return -1;
}
/* get new detection engine */
new_de_ctx = DetectEngineCtxInitWithPrefix(prefix);
if (new_de_ctx == NULL) {
SCLogError(SC_ERR_INITIALIZATION, "initializing detection engine "
"context failed.");
DetectEngineDeReference(&old_de_ctx);
return -1;
}
if (SigLoadSignatures(new_de_ctx,
suri->sig_file, suri->sig_file_exclusive) != 0) {
DetectEngineCtxFree(new_de_ctx);
DetectEngineDeReference(&old_de_ctx);
return -1;
}
SCLogDebug("set up new_de_ctx %p", new_de_ctx);
/* add to master */
DetectEngineAddToMaster(new_de_ctx);
/* move to old free list */
DetectEngineMoveToFreeList(old_de_ctx);
DetectEngineDeReference(&old_de_ctx);
SCLogDebug("going to reload the threads to use new_de_ctx %p", new_de_ctx);
/* update the threads */
DetectEngineReloadThreads(new_de_ctx);
SCLogDebug("threads now run new_de_ctx %p", new_de_ctx);
/* walk free list, freeing the old_de_ctx */
DetectEnginePruneFreeList();
DetectEngineBumpVersion();
SCLogDebug("old_de_ctx should have been freed");
SCLogNotice("rule reload complete");
return 0;
}
static uint32_t TenantIdHash(HashTable *h, void *data, uint16_t data_len)
{
DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;
return det_ctx->tenant_id % h->array_size;
}
static char TenantIdCompare(void *d1, uint16_t d1_len, void *d2, uint16_t d2_len)
{
DetectEngineThreadCtx *det1 = (DetectEngineThreadCtx *)d1;
DetectEngineThreadCtx *det2 = (DetectEngineThreadCtx *)d2;
return (det1->tenant_id == det2->tenant_id);
}
static void TenantIdFree(void *d)
{
DetectEngineThreadCtxFree(d);
}
int DetectEngineMTApply(void)
{
DetectEngineMasterCtx *master = &g_master_de_ctx;
SCMutexLock(&master->lock);
if (master->tenant_selector == TENANT_SELECTOR_UNKNOWN) {
SCLogInfo("error, no tenant selector");
SCMutexUnlock(&master->lock);
return -1;
}
DetectEngineCtx *stub_de_ctx = NULL;
DetectEngineCtx *list = master->list;
for ( ; list != NULL; list = list->next) {
SCLogDebug("list %p tenant %u", list, list->tenant_id);
if (list->type == DETECT_ENGINE_TYPE_NORMAL ||
list->type == DETECT_ENGINE_TYPE_MT_STUB ||
list->type == DETECT_ENGINE_TYPE_DD_STUB)
{
stub_de_ctx = list;
break;
}
}
if (stub_de_ctx == NULL) {
stub_de_ctx = DetectEngineCtxInitStubForMT();
if (stub_de_ctx == NULL) {
SCMutexUnlock(&master->lock);
return -1;
}
if (master->list == NULL) {
master->list = stub_de_ctx;
} else {
stub_de_ctx->next = master->list;
master->list = stub_de_ctx;
}
}
/* update the threads */
SCLogDebug("MT reload starting");
DetectEngineReloadThreads(stub_de_ctx);
SCLogDebug("MT reload done");
SCMutexUnlock(&master->lock);
/* walk free list, freeing the old_de_ctx */
DetectEnginePruneFreeList();
SCLogDebug("old_de_ctx should have been freed");
return 0;
}
static int g_parse_metadata = 0;
void DetectEngineSetParseMetadata(void)
{
g_parse_metadata = 1;
}
void DetectEngineUnsetParseMetadata(void)
{
g_parse_metadata = 0;
}
int DetectEngineMustParseMetadata(void)
{
return g_parse_metadata;
}
const char *DetectSigmatchListEnumToString(enum DetectSigmatchListEnum type)
{
switch (type) {
case DETECT_SM_LIST_MATCH:
return "packet";
case DETECT_SM_LIST_PMATCH:
return "packet/stream payload";
case DETECT_SM_LIST_TMATCH:
return "tag";
case DETECT_SM_LIST_BASE64_DATA:
return "base64_data";
case DETECT_SM_LIST_POSTMATCH:
return "post-match";
case DETECT_SM_LIST_SUPPRESS:
return "suppress";
case DETECT_SM_LIST_THRESHOLD:
return "threshold";
case DETECT_SM_LIST_MAX:
return "max (internal)";
}
return "error";
}
/* events api */
void DetectEngineSetEvent(DetectEngineThreadCtx *det_ctx, uint8_t e)
{
AppLayerDecoderEventsSetEventRaw(&det_ctx->decoder_events, e);
det_ctx->events++;
}
AppLayerDecoderEvents *DetectEngineGetEvents(DetectEngineThreadCtx *det_ctx)
{
return det_ctx->decoder_events;
}
int DetectEngineGetEventInfo(const char *event_name, int *event_id,
AppLayerEventType *event_type)
{
*event_id = SCMapEnumNameToValue(event_name, det_ctx_event_table);
if (*event_id == -1) {
SCLogError(SC_ERR_INVALID_ENUM_MAP, "event \"%s\" not present in "
"det_ctx's enum map table.", event_name);
/* this should be treated as fatal */
return -1;
}
*event_type = APP_LAYER_EVENT_TYPE_TRANSACTION;
return 0;
}
/*************************************Unittest*********************************/
#ifdef UNITTESTS
static int DetectEngineInitYamlConf(const char *conf)
{
ConfCreateContextBackup();
ConfInit();
return ConfYamlLoadString(conf, strlen(conf));
}
static void DetectEngineDeInitYamlConf(void)
{
ConfDeInit();
ConfRestoreContextBackup();
return;
}
static int DetectEngineTest01(void)
{
const char *conf =
"%YAML 1.1\n"
"---\n"
"detect-engine:\n"
" - profile: medium\n"
" - custom-values:\n"
" toclient_src_groups: 2\n"
" toclient_dst_groups: 2\n"
" toclient_sp_groups: 2\n"
" toclient_dp_groups: 3\n"
" toserver_src_groups: 2\n"
" toserver_dst_groups: 4\n"
" toserver_sp_groups: 2\n"
" toserver_dp_groups: 25\n"
" - inspection-recursion-limit: 0\n";
DetectEngineCtx *de_ctx = NULL;
int result = 0;
if (DetectEngineInitYamlConf(conf) == -1)
return 0;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
result = (de_ctx->inspection_recursion_limit == -1);
end:
if (de_ctx != NULL)
DetectEngineCtxFree(de_ctx);
DetectEngineDeInitYamlConf();
return result;
}
static int DetectEngineTest02(void)
{
const char *conf =
"%YAML 1.1\n"
"---\n"
"detect-engine:\n"
" - profile: medium\n"
" - custom-values:\n"
" toclient_src_groups: 2\n"
" toclient_dst_groups: 2\n"
" toclient_sp_groups: 2\n"
" toclient_dp_groups: 3\n"
" toserver_src_groups: 2\n"
" toserver_dst_groups: 4\n"
" toserver_sp_groups: 2\n"
" toserver_dp_groups: 25\n"
" - inspection-recursion-limit:\n";
DetectEngineCtx *de_ctx = NULL;
int result = 0;
if (DetectEngineInitYamlConf(conf) == -1)
return 0;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
result = (de_ctx->inspection_recursion_limit == -1);
end:
if (de_ctx != NULL)
DetectEngineCtxFree(de_ctx);
DetectEngineDeInitYamlConf();
return result;
}
static int DetectEngineTest03(void)
{
const char *conf =
"%YAML 1.1\n"
"---\n"
"detect-engine:\n"
" - profile: medium\n"
" - custom-values:\n"
" toclient_src_groups: 2\n"
" toclient_dst_groups: 2\n"
" toclient_sp_groups: 2\n"
" toclient_dp_groups: 3\n"
" toserver_src_groups: 2\n"
" toserver_dst_groups: 4\n"
" toserver_sp_groups: 2\n"
" toserver_dp_groups: 25\n";
DetectEngineCtx *de_ctx = NULL;
int result = 0;
if (DetectEngineInitYamlConf(conf) == -1)
return 0;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
result = (de_ctx->inspection_recursion_limit ==
DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT);
end:
if (de_ctx != NULL)
DetectEngineCtxFree(de_ctx);
DetectEngineDeInitYamlConf();
return result;
}
static int DetectEngineTest04(void)
{
const char *conf =
"%YAML 1.1\n"
"---\n"
"detect-engine:\n"
" - profile: medium\n"
" - custom-values:\n"
" toclient_src_groups: 2\n"
" toclient_dst_groups: 2\n"
" toclient_sp_groups: 2\n"
" toclient_dp_groups: 3\n"
" toserver_src_groups: 2\n"
" toserver_dst_groups: 4\n"
" toserver_sp_groups: 2\n"
" toserver_dp_groups: 25\n"
" - inspection-recursion-limit: 10\n";
DetectEngineCtx *de_ctx = NULL;
int result = 0;
if (DetectEngineInitYamlConf(conf) == -1)
return 0;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
result = (de_ctx->inspection_recursion_limit == 10);
end:
if (de_ctx != NULL)
DetectEngineCtxFree(de_ctx);
DetectEngineDeInitYamlConf();
return result;
}
static int DetectEngineTest08(void)
{
const char *conf =
"%YAML 1.1\n"
"---\n"
"detect-engine:\n"
" - profile: custom\n"
" - custom-values:\n"
" toclient-groups: 23\n"
" toserver-groups: 27\n";
DetectEngineCtx *de_ctx = NULL;
int result = 0;
if (DetectEngineInitYamlConf(conf) == -1)
return 0;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
if (de_ctx->max_uniq_toclient_groups == 23 &&
de_ctx->max_uniq_toserver_groups == 27)
result = 1;
end:
if (de_ctx != NULL)
DetectEngineCtxFree(de_ctx);
DetectEngineDeInitYamlConf();
return result;
}
/** \test bug 892 bad values */
static int DetectEngineTest09(void)
{
const char *conf =
"%YAML 1.1\n"
"---\n"
"detect-engine:\n"
" - profile: custom\n"
" - custom-values:\n"
" toclient-groups: BA\n"
" toserver-groups: BA\n"
" - inspection-recursion-limit: 10\n";
DetectEngineCtx *de_ctx = NULL;
int result = 0;
if (DetectEngineInitYamlConf(conf) == -1)
return 0;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
if (de_ctx->max_uniq_toclient_groups == 20 &&
de_ctx->max_uniq_toserver_groups == 40)
result = 1;
end:
if (de_ctx != NULL)
DetectEngineCtxFree(de_ctx);
DetectEngineDeInitYamlConf();
return result;
}
#endif
void DetectEngineRegisterTests()
{
#ifdef UNITTESTS
UtRegisterTest("DetectEngineTest01", DetectEngineTest01);
UtRegisterTest("DetectEngineTest02", DetectEngineTest02);
UtRegisterTest("DetectEngineTest03", DetectEngineTest03);
UtRegisterTest("DetectEngineTest04", DetectEngineTest04);
UtRegisterTest("DetectEngineTest08", DetectEngineTest08);
UtRegisterTest("DetectEngineTest09", DetectEngineTest09);
#endif
return;
}
| 31.835084 | 150 | 0.621691 |
4c1da860f7dcf94e514cc40e243165793feac47d | 2,293 | h | C | MailHeaders/Catalina/MailUI/MailTableViewDelegate-Protocol.h | larkov/MailTrackerBlocker | 9b019adf2f37bf4403261c93e9c54e3353b84e08 | [
"BSD-3-Clause"
] | 1,062 | 2020-07-11T00:18:42.000Z | 2022-03-20T14:20:20.000Z | MailHeaders/Catalina/MailUI/MailTableViewDelegate-Protocol.h | JannikArndt/MailTrackerBlocker | 9c073c7b3bb37b4f82a1bf661ac9d34891f1c062 | [
"BSD-3-Clause"
] | 136 | 2020-07-29T02:10:09.000Z | 2022-03-13T07:02:45.000Z | MailHeaders/Catalina/MailUI/MailTableViewDelegate-Protocol.h | JannikArndt/MailTrackerBlocker | 9c073c7b3bb37b4f82a1bf661ac9d34891f1c062 | [
"BSD-3-Clause"
] | 32 | 2020-07-29T02:40:49.000Z | 2022-03-30T18:48:07.000Z | //
// Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import "NSTableViewDelegate-Protocol.h"
@class MailTableView, NSArray, NSDraggingSession, NSEvent, NSImage, NSIndexSet, NSMenu, NSString, NSTableColumn, NSWindow;
@protocol NSServicesMenuRequestor;
@protocol MailTableViewDelegate <NSTableViewDelegate>
@optional
- (double)floatingHeaderHeight:(MailTableView *)arg1;
- (id <NSServicesMenuRequestor>)mailTableView:(MailTableView *)arg1 validRequestorForSendType:(NSString *)arg2 returnType:(NSString *)arg3;
- (void)recordMessageSelectionDuringSearch;
- (NSArray *)accessibilityRowHeaderUIElementsForMailTableView:(MailTableView *)arg1;
- (NSArray *)accessibilityUILinkedViewsForMailTableView:(MailTableView *)arg1;
- (void)prepareContentInRange:(struct _NSRange)arg1;
- (void)userDidScrollInTableView:(MailTableView *)arg1;
- (NSMenu *)tableViewGetDefaultMenu:(MailTableView *)arg1;
- (void)mailTableViewDidResignFirstResponder:(MailTableView *)arg1;
- (void)mailTableViewDidBecomeFirstResponder:(MailTableView *)arg1;
- (BOOL)mailTableView:(MailTableView *)arg1 shouldAddTableColumn:(NSTableColumn *)arg2;
- (BOOL)mailTableView:(MailTableView *)arg1 shouldRemoveTableColumn:(NSTableColumn *)arg2;
- (void)mailTableView:(MailTableView *)arg1 didMouseDown:(NSEvent *)arg2;
- (void)mailTableView:(MailTableView *)arg1 willMouseDown:(NSEvent *)arg2;
- (void)mailTableView:(MailTableView *)arg1 gotEvent:(NSEvent *)arg2;
- (void)mailTableViewDidEndLiveResize:(MailTableView *)arg1;
- (void)mailTableViewWillStartLiveResize:(MailTableView *)arg1;
- (void)mailTableViewDidMoveToWindow:(MailTableView *)arg1;
- (void)mailTableView:(MailTableView *)arg1 willMoveToWindow:(NSWindow *)arg2;
- (long long)mailTableView:(MailTableView *)arg1 shouldScrollRowToVisible:(long long)arg2;
- (BOOL)mailTableView:(MailTableView *)arg1 doCommandBySelector:(SEL)arg2;
- (void)mailTableViewDraggingSession:(NSDraggingSession *)arg1 movedTo:(struct CGPoint)arg2;
- (void)mailTableViewDragWillEnd:(MailTableView *)arg1 operation:(unsigned long long)arg2;
- (NSImage *)mailTableView:(MailTableView *)arg1 dragImageForRowsWithIndexes:(NSIndexSet *)arg2 event:(NSEvent *)arg3 dragImageOffset:(struct CGPoint *)arg4;
@end
| 55.926829 | 157 | 0.800698 |
486cc54a47422ccc2b71894b96d93e6916ec4e0d | 1,185 | h | C | C/bison/Expression.h | Catamondium/scratch | c67dc76e11a66fc5cf0fe142f161791223ca6861 | [
"Unlicense"
] | null | null | null | C/bison/Expression.h | Catamondium/scratch | c67dc76e11a66fc5cf0fe142f161791223ca6861 | [
"Unlicense"
] | null | null | null | C/bison/Expression.h | Catamondium/scratch | c67dc76e11a66fc5cf0fe142f161791223ca6861 | [
"Unlicense"
] | null | null | null | /*
* Expression.h
* Definition of the structure used to build the syntax tree.
*/
#ifndef __EXPRESSION_H__
#define __EXPRESSION_H__
/**
* @brief The operation type
*/
typedef enum tagEOperationType
{
eVALUE,
eMULTIPLY,
eADD
} EOperationType;
/**
* @brief The expression structure
*/
typedef struct tagSExpression
{
EOperationType type; /* /< type of operation */
int value; /* /< valid only when type is eVALUE */
struct tagSExpression *left; /* /< left side of the tree */
struct tagSExpression *right; /* /< right side of the tree */
} SExpression;
/**
* @brief It creates an identifier
* @param value The number value
* @return The expression or NULL in case of no memory
*/
SExpression *createNumber(int value);
/**
* @brief It creates an operation
* @param type The operation type
* @param left The left operand
* @param right The right operand
* @return The expression or NULL in case of no memory
*/
SExpression *createOperation(EOperationType type, SExpression *left, SExpression *right);
/**
* @brief Deletes a expression
* @param b The expression
*/
void deleteExpression(SExpression *b);
#endif /* __EXPRESSION_H__ */
| 22.358491 | 89 | 0.701266 |
483bbe5d7b39089352b5dc6de7cab18616faae87 | 4,991 | h | C | Geometry.h | rems4e/CoreGL | ff2f0e2225c4c73c5676c077500f8bd9235a0c99 | [
"MIT"
] | null | null | null | Geometry.h | rems4e/CoreGL | ff2f0e2225c4c73c5676c077500f8bd9235a0c99 | [
"MIT"
] | null | null | null | Geometry.h | rems4e/CoreGL | ff2f0e2225c4c73c5676c077500f8bd9235a0c99 | [
"MIT"
] | null | null | null | //
// Geometry.h
// CoreGL
//
// Created by Rémi on 07/06/08.
// Additional contributor (2012): Marc Promé
//
#ifndef COREGL_GEOMETRY_H
#define COREGL_GEOMETRY_H
#include <iosfwd>
#define GLM_SWIZZLE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_access.hpp>
#include <type_traits>
namespace CoreGL {
using ::glm::ivec2;
using ::glm::vec2;
using ::glm::vec3;
using ::glm::vec4;
using ::glm::mat2;
using ::glm::mat3;
using ::glm::mat4;
typedef vec3::value_type coordinate_t;
typedef coordinate_t dimension_t;
namespace Geometry {
inline bool nullValue(coordinate_t v) {
return (v < 0 ? -v : v) < 0.00001f;
}
template <typename Vec>
inline bool nullVector(Vec const &v) {
for(int i = 0; i < v.length(); ++i)
if(!nullValue(v[i]))
return false;
return true;
}
template <typename Vec>
inline Vec orthogonalProjection(Vec const &vec, Vec const &projectionDirection) {
vec3 const v = glm::normalize(projectionDirection);
return projectionDirection * glm::dot(vec, v);
}
inline vec3 sphericToCartesian(vec3 const &coord) {
using float_t = vec3::value_type;
float_t const rho = coord.x;
float_t const theta = (coord.y + 90) / 180 * M_PI;
float_t const phi = coord.z / 180 * M_PI;
float_t const sinTheta = std::sin(theta);
float_t const cosTheta = std::cos(theta);
float_t const cosPhi = std::cos(phi);
float_t const sinPhi = std::sin(phi);
return vec3(sinTheta * cosPhi, cosTheta, sinTheta * sinPhi) * rho;
}
// Transformations
mat4 perspective(float angle, float ratio, float near, float far);
mat4 translate(vec3 const &vec);
mat4 scale(vec3 const &vec);
mat4 rotate(float angle, vec3 vec); // angle in degrees
// Camera
mat4 camera(vec3 const &position, vec3 const &target, vec3 const &up);
mat4 cameraSphere(vec3 const &relativeToSphere, vec3 const &target, vec3 const &up);
}
// Autoriser la multiplication/division entre un vecteur glm et autre chose qu'un float
template <typename T, typename Number>
inline std::enable_if_t<std::is_arithmetic<Number>::value && !std::is_same<T, Number>::value, glm::tvec2<T>>
operator/(glm::tvec2<T> v, Number const &nb) {
v /= nb;
return v;
}
template <typename T, typename Number>
inline std::enable_if_t<std::is_arithmetic<Number>::value && !std::is_same<T, Number>::value, glm::tvec3<T>>
operator/(glm::tvec3<T> v, Number const &nb) {
v /= nb;
return v;
}
template <typename T, typename Number>
inline std::enable_if_t<std::is_arithmetic<Number>::value && !std::is_same<T, Number>::value, glm::tvec4<T>>
operator/(glm::tvec4<T> v, Number const &nb) {
v /= nb;
return v;
}
template <typename T, typename Number>
inline std::enable_if_t<std::is_arithmetic<Number>::value && !std::is_same<T, Number>::value, glm::tvec2<T>>
operator*(glm::tvec2<T> v, Number const &nb) {
v *= nb;
return v;
}
template <typename T, typename Number>
inline std::enable_if_t<std::is_arithmetic<Number>::value && !std::is_same<T, Number>::value, glm::tvec3<T>>
operator*(glm::tvec3<T> v, Number const &nb) {
v *= nb;
return v;
}
template <typename T, typename Number>
inline std::enable_if_t<std::is_arithmetic<Number>::value, glm::tvec4<T>>
operator*(glm::tvec4<T> v, Number const &nb) {
v *= nb;
return v;
}
template <typename T, typename Number>
inline std::enable_if_t<std::is_arithmetic<Number>::value && !std::is_same<T, Number>::value, glm::tvec2<T>>
operator*(Number const &nb, glm::tvec2<T> v) {
v *= nb;
return v;
}
template <typename T, typename Number>
inline std::enable_if_t<std::is_arithmetic<Number>::value && !std::is_same<T, Number>::value, glm::tvec3<T>>
operator*(Number const &nb, glm::tvec3<T> v) {
v *= nb;
return v;
}
template <typename T, typename Number>
inline std::enable_if_t<std::is_arithmetic<Number>::value && !std::is_same<T, Number>::value, glm::tvec4<T>>
operator*(Number const &nb, glm::tvec4<T> v) {
v *= nb;
return v;
}
}
// Affichage des vecteurs/matrices
std::ostream &operator<<(std::ostream &s, glm::vec4 const &c);
std::ostream &operator<<(std::ostream &s, glm::vec3 const &c);
std::ostream &operator<<(std::ostream &s, glm::vec2 const &c);
std::ostream &operator<<(std::ostream &s, glm::ivec2 const &c);
std::ostream &operator<<(std::ostream &s, glm::mat4 const &m);
std::ostream &operator<<(std::ostream &s, glm::mat3 const &m);
std::ostream &operator<<(std::ostream &s, glm::mat2 const &m);
#include "Rectangle.h"
#endif
| 33.05298 | 112 | 0.608495 |
bc3ed41ad9d8daf5fc3a4d0874300b8ed6069023 | 7,295 | h | C | src/bint.h | dlbeer/libdlb | 03760de452dbed4b3cfe32e771520bf694cde000 | [
"0BSD"
] | 11 | 2017-04-04T16:39:04.000Z | 2021-11-26T22:07:46.000Z | src/bint.h | dlbeer/libdlb | 03760de452dbed4b3cfe32e771520bf694cde000 | [
"0BSD"
] | null | null | null | src/bint.h | dlbeer/libdlb | 03760de452dbed4b3cfe32e771520bf694cde000 | [
"0BSD"
] | 2 | 2017-08-26T03:57:49.000Z | 2022-03-23T08:51:36.000Z | /* libdlb - data structures and utilities library
* Copyright (C) 2011 Daniel Beer <dlbeer@gmail.com>
*
* 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 BINT_H_
#define BINT_H_
#include <stdint.h>
#include <stdlib.h>
/* This file defines big (arbitrary-precision) integer types. They are
* implemented as singly-linked lists of chunks, with the first chunk
* embedded in the type itself.
*
* This means that for small-ish integers, no memory allocation is
* required. Only integers that overflow the chunk size will degrade
* to dynamic memory allocation.
*
* The number of bits represented by a single chunk is BINT_CHUNK_SIZE * 32.
*
* Operations that fail will leave their operands in the same state they
* were before the operation was attempted.
*
* All struct bint * pointers passed as arguments must point to initialized
* structures. The only exception is the argument passed to bint_init().
*/
#ifndef BINT_CHUNK_SIZE
#define BINT_CHUNK_SIZE 4
#endif
struct bint_chunk {
uint32_t data[BINT_CHUNK_SIZE];
struct bint_chunk *next;
};
struct bint {
int negative;
struct bint_chunk digits;
};
/* Constant definitions. Constants are statically initialized, and
* don't need to be destroyed.
*/
#define BINT_DEF_CONSTANT(name, value) \
const struct bint name = { \
.negative = (value) < 0, \
.digits = { \
.next = NULL, \
.data = {(value) < 0 ? -(value) : (value), 0} \
} \
};
extern const struct bint bint_zero;
extern const struct bint bint_one;
/* Initialize and destroy big integers. */
void bint_init(struct bint *b, int32_t value);
void bint_destroy(struct bint *b);
/* Copy an integer. The destination is expected to be initialized
* already.
*
* Returns 0 on success or -1 if memory couldn't be allocated. If this
* operation fails, the destination is left unchanged.
*/
int bint_copy(struct bint *dst, const struct bint *src);
/* Swap two integers. This operation never fails. */
void bint_swap(struct bint *a, struct bint *b);
/* Set the value of an integer. This operation never fails, because a
* primitive int can always fit inside a single chunk.
*/
void bint_set(struct bint *b, int32_t value);
/* Cast big integer values back to primitive ints.
*
* Note that bint_get() will automatically cast the value, losing
* precision if it doesn't fit.
*/
int32_t bint_get(const struct bint *b);
/* Fetch and set the sign of an integer. Note that setting the sign of
* a zero-valued integer has no effect.
*
* bint_get_sign() returns -1/0/1 depending on whether the value is negative,
* zero or positive.
*/
int bint_get_sign(const struct bint *b);
void bint_set_sign(struct bint *b, int sign);
/* Compare two integers. Returns -1/0/1 depending on whether the first
* value is less than, equal, or greater than the second.
*/
int bint_compare(const struct bint *a, const struct bint *b);
/* Add/subtract the second integer to/from the first. Returns 0 on success
* or -1 if memory couldn't be allocated for an extra-large result.
*/
int bint_add(struct bint *dst, const struct bint *src);
int bint_sub(struct bint *dst, const struct bint *src);
/* Multiply two big integers to produce a third. Returns 0 on success or
* -1 if memory couldn't be allocated.
*
* The two source values may point to the same integer, but neither of
* them are allowed to point to the result.
*/
int bint_mul(struct bint *result, const struct bint *a, const struct bint *b);
/* Integer division. This operation divides the dividend by the divisor, and
* optionally returns the quotient and remainder. The remainder is
* of the same sign as the divisor and satisfies:
*
* dividend = divisor * quotient + remainder
*
* Returns 0 on success, -1 if memory couldn't be allocated, and 1 if the
* divisor was zero. Either, or both, of divisor/remainder may be NULL.
*/
int bint_div(struct bint *quotient, const struct bint *dividend,
const struct bint *divisor, struct bint *remainder);
/* Exponentiation. Raises the base to the power of the exponent and returns
* the result. Returns 0 on success or -1 if memory couldn't be allocated.
*/
int bint_expt(struct bint *result,
const struct bint *base, const struct bint *exponent);
/* Bitwise operations: bit set, length, clear and test. Set may fail if memory
* needs to be allocated, in which case -1 is returned.
*
* bint_bit_length() returns the index of the position after the most
* significant 1.
*/
int bint_bit_get(const struct bint *b, unsigned int pos);
unsigned int bint_bit_length(const struct bint *b);
int bint_bit_set(struct bint *b, unsigned int pos);
void bint_bit_clear(struct bint *b, unsigned int pos);
/* Bitwise operations: and, or and xor. All three of these may required memory
* allocation, and will return -1 on failure. Since bitwise not can't be
* implemented (because the result would logically be of infinite length), we
* provide an operation "bic":
*
* A bic B == A & ~B
*
* Note that these operations ignore the sign of the integer.
*/
int bint_or(struct bint *dst, const struct bint *src);
void bint_and(struct bint *dst, const struct bint *src);
void bint_bic(struct bint *dst, const struct bint *src);
int bint_xor(struct bint *dst, const struct bint *src);
/* Bitwise operations: shift left and right. Shift left might fail if memory
* can't be allocated, and will return -1 on failure. Shift right always
* succeeds.
*
* These operations ignore the sign of the integer.
*/
int bint_shift_left(struct bint *b, unsigned int count);
void bint_shift_right(struct bint *b, unsigned int count);
/* Base conversion functions. These functions treat the integer as a
* stack of digits in the given base, with the top of the stack being
* the least significant digit. They both ignore the sign of the integer.
*
* bint_digit_push() computes: b = b * base + digit. It returns 0 on
* success or -1 if memory couldn't be allocated.
*
* bint_digit_pop() divides b by the base and returns the remainder. It
* always succeeds. If the given base is 0, it returns 0.
*/
int bint_digit_push(struct bint *b, unsigned int base, unsigned int digit);
unsigned int bint_digit_pop(struct bint *b, unsigned int base);
/* These two functions comprise the chunk allocator. By default, malloc() and
* free() are used. If you want to provide your own allocator, these symbols
* should be overridden.
*
* bint_chunk_alloc() should return a block of memory of
* sizeof(struct bint_chunk), or NULL if allocation fails.
*/
struct bint_chunk *bint_chunk_alloc(void);
void bint_chunk_free(struct bint_chunk *c);
#endif
| 36.293532 | 78 | 0.736669 |
429ab1cb9228dcfcf437d78001c803ed74ad6667 | 420 | h | C | T194/Backend/blackBoard/node_modules/opencv4nodejs/cc/tracking/Trackers/TrackerCSRT.h | DevelopAppWithMe/Hackathon_5.0 | 6af503a995721c04986931d6a29d8f946ceaa067 | [
"MIT"
] | 1 | 2021-02-22T17:47:13.000Z | 2021-02-22T17:47:13.000Z | T194/Backend/blackBoard/node_modules/opencv4nodejs/cc/tracking/Trackers/TrackerCSRT.h | DevelopAppWithMe/Hackathon_5.0 | 6af503a995721c04986931d6a29d8f946ceaa067 | [
"MIT"
] | null | null | null | T194/Backend/blackBoard/node_modules/opencv4nodejs/cc/tracking/Trackers/TrackerCSRT.h | DevelopAppWithMe/Hackathon_5.0 | 6af503a995721c04986931d6a29d8f946ceaa067 | [
"MIT"
] | null | null | null | #include "../Tracker.h"
#if CV_VERSION_GREATER_EQUAL(3, 4, 1)
#ifndef __FF_TRACKERCSRT_H__
#define __FF_TRACKERCSRT_H__
class TrackerCSRT : public Tracker {
public:
cv::Ptr<cv::TrackerCSRT> tracker;
static NAN_MODULE_INIT(Init);
static NAN_METHOD(New);
static Nan::Persistent<v8::FunctionTemplate> constructor;
cv::Ptr<cv::Tracker> getTracker() {
return tracker;
}
};
#endif
#endif | 17.5 | 59 | 0.702381 |
0969b044a8ecedfea56f9f874c55c8b3681b228e | 5,517 | h | C | dev/Gems/StarterGameGem/Code/Source/StatComponent.h | horvay/lumberyardtutor | 63b0681a7ed2a98d651b699984de92951721353e | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Gems/StarterGameGem/Code/Source/StatComponent.h | horvay/lumberyardtutor | 63b0681a7ed2a98d651b699984de92951721353e | [
"AML"
] | null | null | null | dev/Gems/StarterGameGem/Code/Source/StatComponent.h | horvay/lumberyardtutor | 63b0681a7ed2a98d651b699984de92951721353e | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/Math/Transform.h>
#include <AzFramework/Entity/EntityContextBus.h>
#include <AzCore/Component/TickBus.h>
#include <AzCore/std/string/string.h>
#include <AzCore/std/any.h>
#include <GameplayEventBus.h>
namespace StarterGameGem
{
/*!
* StatRequests
* Messages serviced by the StatComponent.
*/
class StatRequests : public AZ::ComponentBus
{
public:
virtual ~StatRequests() {}
virtual void SetMax(float max) = 0;
virtual void SetMin(float min) = 0;
virtual void SetValue(float value) = 0;
virtual void SetRegenSpeed(float value) = 0;
virtual void SetRegenDelay(float value) = 0;
// making these const seems to cause problems
virtual float GetMax(float max) /*const*/ = 0;
virtual float GetMin(float min) /*const*/ = 0;
virtual float GetValue(float value) /*const*/ = 0;
virtual float GetRegenSpeed(float value) /*const*/ = 0;
virtual float GetRegenDelay(float value) /*const*/ = 0;
virtual void DeltaValue(float value) = 0;
virtual void Reset() = 0;
};
using StatRequestBus = AZ::EBus<StatRequests>;
class StatComponent
: public AZ::Component
, private StatRequestBus::Handler
, public AZ::GameplayNotificationBus::MultiHandler
, private AZ::TickBus::Handler
{
public:
AZ_COMPONENT(StatComponent, "{76D127CC-5E52-4DC9-8B36-DEE62A7BAC39}");
StatComponent();
//////////////////////////////////////////////////////////////////////////
// AZ::Component interface implementation
void Init() override {}
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// AZ::TickBus interface implementation
void OnTick(float deltaTime, AZ::ScriptTimePoint time) override;
//////////////////////////////////////////////////////////////////////////
// Required Reflect function.
static void Reflect(AZ::ReflectContext* context);
// Optional functions for defining provided and dependent services.
//static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
//{
// required.push_back(AZ_CRC("TransformService"));
//}
//////////////////////////////////////////////////////////////////////////
// StatComponentRequestBus::Handler
void SetMax(float max);
void SetMin(float min);
void SetValue(float value);
void SetRegenSpeed(float value);
void SetRegenDelay(float value);
void SetFullEvent(const char* name);
void SetEmptyEvent(const char* name);
void SetRegenStartEvent(const char* name);
void SetRegenEndEvent(const char* name);
void SetValueChangedEvent(const char* name);
float GetMax(float max) /*const*/;
float GetMin(float min) /*const*/;
float GetValue(float value) /*const*/;
float GetRegenSpeed(float value) /*const*/;
float GetRegenDelay(float value) /*const*/;
AZStd::string GetFullEvent() const;
AZStd::string GetEmptyEvent() const;
AZStd::string GetRegenStartEvent() const;
AZStd::string GetRegenEndEvent() const;
AZStd::string GetValueChangedEvent() const;
void DeltaValue(float value);
void Reset();
void OnEventBegin(const AZStd::any& value) override;
void OnEventUpdating(const AZStd::any&) override;
void OnEventEnd(const AZStd::any&) override;
protected:
float m_max;
float m_min;
float m_value;
float m_regenSpeed;
float m_regenDelay;
// storage for the initilised values, so i can be "reset"
float m_defaultMax;
float m_defaultMin;
float m_defaultValue;
float m_defaultRegenSpeed;
float m_defaultRegenDelay;
AZStd::string m_fullEventName;
AZStd::string m_emptyEventName;
AZStd::string m_regenStartEventName;
AZStd::string m_regenEndEventName;
AZStd::string m_valueChangedEventName;
AZStd::string m_setMaxEventName;
AZStd::string m_setMinEventName;
AZStd::string m_setRegenSpeedEventName;
AZStd::string m_setRegenDelayEventName;
AZStd::string m_setValueEventName;
AZStd::string m_deltaValueEventName;
AZStd::string m_resetEventName;
AZStd::string m_GetValueEventName;
AZStd::string m_SendValueEventName;
AZStd::string m_GetUsedCapacityEventName;
AZStd::string m_SendUsedCapacityEventName;
AZStd::string m_GetUnUsedCapacityEventName;
AZStd::string m_SendUnUsedCapacityEventName;
private:
float m_timer;
bool m_isRegening;
void ValueChanged(bool resetTimer = true, bool regenStarted = false);
AZ::GameplayNotificationId m_setMaxEventID;
AZ::GameplayNotificationId m_setMinEventID;
AZ::GameplayNotificationId m_setRegenSpeedEventID;
AZ::GameplayNotificationId m_setRegenDelayEventID;
AZ::GameplayNotificationId m_setValueEventID;
AZ::GameplayNotificationId m_deltaValueEventID;
AZ::GameplayNotificationId m_resetEventID;
AZ::GameplayNotificationId m_GetValueEventID;
AZ::GameplayNotificationId m_GetUsedCapacityEventID;
AZ::GameplayNotificationId m_GetUnUsedCapacityEventID;
};
}
| 31.706897 | 91 | 0.705093 |
ba49fd69f86edd8e87f6e314cd04f4db840bc627 | 10,076 | c | C | lib/tran.c | raphael-nutanix/muser | 50e7bfb5f86749070aef7dc3982875ef6129601b | [
"BSD-3-Clause"
] | 13 | 2019-10-11T08:59:20.000Z | 2020-11-22T09:18:27.000Z | lib/tran.c | raphael-nutanix/muser | 50e7bfb5f86749070aef7dc3982875ef6129601b | [
"BSD-3-Clause"
] | 82 | 2019-11-05T15:46:44.000Z | 2020-11-27T14:56:40.000Z | lib/tran.c | raphael-nutanix/muser | 50e7bfb5f86749070aef7dc3982875ef6129601b | [
"BSD-3-Clause"
] | 11 | 2019-10-07T08:39:22.000Z | 2020-06-29T20:29:08.000Z | /*
* Copyright (c) 2020 Nutanix Inc. All rights reserved.
*
* Authors: Thanos Makatos <thanos@nutanix.com>
* Swapnil Ingle <swapnil.ingle@nutanix.com>
* Felipe Franciosi <felipe@nutanix.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Nutanix nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*/
#include <sys/param.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <json.h>
#include "libvfio-user.h"
#include "migration.h"
#include "tran.h"
// FIXME: is this the value we want?
#define SERVER_MAX_FDS 8
/*
* Expected JSON is of the form:
*
* {
* "capabilities": {
* "max_msg_fds": 32,
* "max_data_xfer_size": 1048576
* "migration": {
* "pgsize": 4096
* }
* }
* }
*
* with everything being optional. Note that json_object_get_uint64() is only
* available in newer library versions, so we don't use it.
*/
int
tran_parse_version_json(const char *json_str, int *client_max_fdsp,
size_t *client_max_data_xfer_sizep, size_t *pgsizep)
{
struct json_object *jo_caps = NULL;
struct json_object *jo_top = NULL;
struct json_object *jo = NULL;
int ret = EINVAL;
if ((jo_top = json_tokener_parse(json_str)) == NULL) {
goto out;
}
if (!json_object_object_get_ex(jo_top, "capabilities", &jo_caps)) {
ret = 0;
goto out;
}
if (json_object_get_type(jo_caps) != json_type_object) {
goto out;
}
if (json_object_object_get_ex(jo_caps, "max_msg_fds", &jo)) {
if (json_object_get_type(jo) != json_type_int) {
goto out;
}
errno = 0;
*client_max_fdsp = (int)json_object_get_int64(jo);
if (errno != 0) {
goto out;
}
}
if (json_object_object_get_ex(jo_caps, "max_data_xfer_size", &jo)) {
if (json_object_get_type(jo) != json_type_int) {
goto out;
}
errno = 0;
*client_max_data_xfer_sizep = (int)json_object_get_int64(jo);
if (errno != 0) {
goto out;
}
}
if (json_object_object_get_ex(jo_caps, "migration", &jo)) {
struct json_object *jo2 = NULL;
if (json_object_get_type(jo) != json_type_object) {
goto out;
}
if (json_object_object_get_ex(jo, "pgsize", &jo2)) {
if (json_object_get_type(jo2) != json_type_int) {
goto out;
}
errno = 0;
*pgsizep = (size_t)json_object_get_int64(jo2);
if (errno != 0) {
goto out;
}
}
}
ret = 0;
out:
/* We just need to put our top-level object. */
json_object_put(jo_top);
if (ret != 0) {
return ERROR_INT(ret);
}
return 0;
}
static int
recv_version(vfu_ctx_t *vfu_ctx, uint16_t *msg_idp,
struct vfio_user_version **versionp)
{
struct vfio_user_version *cversion = NULL;
vfu_msg_t msg = { { 0 } };
int ret;
*versionp = NULL;
ret = vfu_ctx->tran->recv_msg(vfu_ctx, &msg);
if (ret < 0) {
vfu_log(vfu_ctx, LOG_ERR, "failed to receive version: %m");
return ret;
}
*msg_idp = msg.hdr.msg_id;
if (msg.hdr.cmd != VFIO_USER_VERSION) {
vfu_log(vfu_ctx, LOG_ERR, "msg%#hx: invalid cmd %hu (expected %u)",
*msg_idp, msg.hdr.cmd, VFIO_USER_VERSION);
ret = EINVAL;
goto out;
}
if (msg.in.nr_fds != 0) {
vfu_log(vfu_ctx, LOG_ERR,
"msg%#hx: VFIO_USER_VERSION: sent with %zu fds", *msg_idp,
msg.in.nr_fds);
ret = EINVAL;
goto out;
}
if (msg.in.iov.iov_len < sizeof(*cversion)) {
vfu_log(vfu_ctx, LOG_ERR,
"msg%#hx: VFIO_USER_VERSION: invalid size %lu",
*msg_idp, msg.in.iov.iov_len);
ret = EINVAL;
goto out;
}
cversion = msg.in.iov.iov_base;
if (cversion->major != LIB_VFIO_USER_MAJOR) {
vfu_log(vfu_ctx, LOG_ERR, "unsupported client major %hu (must be %u)",
cversion->major, LIB_VFIO_USER_MAJOR);
ret = EINVAL;
goto out;
}
vfu_ctx->client_max_fds = 1;
vfu_ctx->client_max_data_xfer_size = VFIO_USER_DEFAULT_MAX_DATA_XFER_SIZE;
if (msg.in.iov.iov_len > sizeof(*cversion)) {
const char *json_str = (const char *)cversion->data;
size_t len = msg.in.iov.iov_len - sizeof(*cversion);
size_t pgsize = 0;
if (json_str[len - 1] != '\0') {
vfu_log(vfu_ctx, LOG_ERR, "ignoring invalid JSON from client");
ret = EINVAL;
goto out;
}
ret = tran_parse_version_json(json_str, &vfu_ctx->client_max_fds,
&vfu_ctx->client_max_data_xfer_size,
&pgsize);
if (ret < 0) {
/* No client-supplied strings in the log for release build. */
#ifdef DEBUG
vfu_log(vfu_ctx, LOG_ERR, "failed to parse client JSON \"%s\"",
json_str);
#else
vfu_log(vfu_ctx, LOG_ERR, "failed to parse client JSON");
#endif
ret = errno;
goto out;
}
if (vfu_ctx->migration != NULL && pgsize != 0) {
ret = migration_set_pgsize(vfu_ctx->migration, pgsize);
if (ret != 0) {
vfu_log(vfu_ctx, LOG_ERR, "refusing client page size of %zu",
pgsize);
ret = errno;
goto out;
}
}
// FIXME: is the code resilient against ->client_max_fds == 0?
if (vfu_ctx->client_max_fds < 0 ||
vfu_ctx->client_max_fds > VFIO_USER_CLIENT_MAX_MSG_FDS_LIMIT) {
vfu_log(vfu_ctx, LOG_ERR, "refusing client max_msg_fds of %d",
vfu_ctx->client_max_fds);
ret = EINVAL;
goto out;
}
}
out:
if (ret != 0) {
vfu_msg_t rmsg = { { 0 } };
size_t i;
rmsg.hdr = msg.hdr;
(void) vfu_ctx->tran->reply(vfu_ctx, &rmsg, ret);
for (i = 0; i < msg.in.nr_fds; i++) {
if (msg.in.fds[i] != -1) {
close(msg.in.fds[i]);
}
}
free(msg.in.iov.iov_base);
*versionp = NULL;
return ERROR_INT(ret);
}
*versionp = cversion;
return 0;
}
static int
send_version(vfu_ctx_t *vfu_ctx, uint16_t msg_id,
struct vfio_user_version *cversion)
{
struct vfio_user_version sversion = { 0 };
struct iovec iovecs[2] = { { 0 } };
char server_caps[1024];
vfu_msg_t msg = { { 0 } };
int slen;
if (vfu_ctx->migration == NULL) {
slen = snprintf(server_caps, sizeof(server_caps),
"{"
"\"capabilities\":{"
"\"max_msg_fds\":%u,"
"\"max_data_xfer_size\":%u"
"}"
"}", SERVER_MAX_FDS, SERVER_MAX_DATA_XFER_SIZE);
} else {
slen = snprintf(server_caps, sizeof(server_caps),
"{"
"\"capabilities\":{"
"\"max_msg_fds\":%u,"
"\"max_data_xfer_size\":%u,"
"\"migration\":{"
"\"pgsize\":%zu"
"}"
"}"
"}", SERVER_MAX_FDS, SERVER_MAX_DATA_XFER_SIZE,
migration_get_pgsize(vfu_ctx->migration));
}
// FIXME: we should save the client minor here, and check that before trying
// to send unsupported things.
sversion.major = LIB_VFIO_USER_MAJOR;
sversion.minor = MIN(cversion->minor, LIB_VFIO_USER_MINOR);
iovecs[0].iov_base = &sversion;
iovecs[0].iov_len = sizeof(sversion);
iovecs[1].iov_base = server_caps;
/* Include the NUL. */
iovecs[1].iov_len = slen + 1;
msg.hdr.cmd = VFIO_USER_VERSION;
msg.hdr.msg_id = msg_id;
msg.out_iovecs = iovecs;
msg.nr_out_iovecs = 2;
return vfu_ctx->tran->reply(vfu_ctx, &msg, 0);
}
int
tran_negotiate(vfu_ctx_t *vfu_ctx)
{
struct vfio_user_version *client_version = NULL;
uint16_t msg_id = 0x0bad;
int ret;
ret = recv_version(vfu_ctx, &msg_id, &client_version);
if (ret < 0) {
vfu_log(vfu_ctx, LOG_ERR, "failed to recv version: %m");
return ret;
}
ret = send_version(vfu_ctx, msg_id, client_version);
free(client_version);
if (ret < 0) {
vfu_log(vfu_ctx, LOG_ERR, "failed to send version: %m");
}
return ret;
}
/* ex: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab: */
| 29.037464 | 80 | 0.577015 |
a7cf65fd5518a36d1950e4c069de42b4ae57e243 | 643 | h | C | server_utils.h | notdylanburns/c_http_server | d38d94d1ba18d9b938890c2070674025f312619e | [
"MIT"
] | null | null | null | server_utils.h | notdylanburns/c_http_server | d38d94d1ba18d9b938890c2070674025f312619e | [
"MIT"
] | null | null | null | server_utils.h | notdylanburns/c_http_server | d38d94d1ba18d9b938890c2070674025f312619e | [
"MIT"
] | null | null | null | #ifndef SERVER_UTILS_H_GUARD_
#define SERVER_UTILS_H_GUARD_
#include <stdio.h>
#include "server.h"
#include "http.h"
#define ROUTE(n) void n(struct HTTPRequest *req, struct HTTPResponse *res)
#define STATIC(n, filepath, mime) void n(struct HTTPRequest *req, struct HTTPresponse *res) { FILE *f = fopen(filepath, "rb"); if (f == NULL) { printf("Failed to open %s\n", filepath); return; }; fseek(f, 0, SEEK_END); int filesize = ftell(f); fseek(f, 0, SEEK_SET); char fileContents[filesize]; fread(fileContents, 1, filesize, f); set_content(res, mime, filesize, (Bytes)fileContents); }
#define RESOURCE(s, p, f) route(server, GET, p, &f)
#endif | 53.583333 | 389 | 0.718507 |
68c65c6c0e1f2042ae5ad7776e7394885291df44 | 234 | h | C | CrayWebViewController/MasterViewController.h | PlusR/CrayWebViewController | beff5dcb583180d965da4ea5fa67a5ef5e221731 | [
"MIT"
] | 5 | 2015-01-15T12:19:53.000Z | 2017-08-12T01:51:50.000Z | CrayWebViewController/MasterViewController.h | PlusR/CrayWebViewController | beff5dcb583180d965da4ea5fa67a5ef5e221731 | [
"MIT"
] | 1 | 2015-09-10T01:01:55.000Z | 2015-09-10T01:01:55.000Z | CrayWebViewController/MasterViewController.h | PlusR/CrayWebViewController | beff5dcb583180d965da4ea5fa67a5ef5e221731 | [
"MIT"
] | null | null | null | //
// MasterViewController.h
// CrayWebViewController
//
// Created by azu on 2014/05/15.
// Copyright (c) 2014 azu. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MasterViewController : UITableViewController
@end | 15.6 | 55 | 0.717949 |
844fdb9c5c85500ce897545fa4b1a3e5d4521355 | 1,714 | h | C | realsense2_camera/include/image_publisher.h | yushijinhun/realsense-ros | d227d612f91c83c526cc74e059f024b0d812499f | [
"Apache-2.0"
] | null | null | null | realsense2_camera/include/image_publisher.h | yushijinhun/realsense-ros | d227d612f91c83c526cc74e059f024b0d812499f | [
"Apache-2.0"
] | null | null | null | realsense2_camera/include/image_publisher.h | yushijinhun/realsense-ros | d227d612f91c83c526cc74e059f024b0d812499f | [
"Apache-2.0"
] | null | null | null | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2022 Intel Corporation. All Rights Reserved.
#pragma once
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/image.hpp>
#if defined( DASHING ) || defined( ELOQUENT )
#include <image_transport/image_transport.h>
#else
#include <image_transport/image_transport.hpp>
#endif
namespace realsense2_camera {
class image_publisher
{
public:
virtual void publish( sensor_msgs::msg::Image::UniquePtr image_ptr ) = 0;
virtual size_t get_subscription_count() const = 0;
virtual ~image_publisher() = default;
};
// Native RCL implementation of an image publisher (needed for intra-process communication)
class image_rcl_publisher : public image_publisher
{
public:
image_rcl_publisher( rclcpp::Node & node,
const std::string & topic_name,
const rmw_qos_profile_t & qos );
void publish( sensor_msgs::msg::Image::UniquePtr image_ptr ) override;
size_t get_subscription_count() const override;
private:
rclcpp::Publisher< sensor_msgs::msg::Image >::SharedPtr image_publisher_impl;
};
// image_transport implementation of an image publisher (adds a compressed image topic)
class image_transport_publisher : public image_publisher
{
public:
image_transport_publisher( rclcpp::Node & node,
const std::string & topic_name,
const rmw_qos_profile_t & qos );
void publish( sensor_msgs::msg::Image::UniquePtr image_ptr ) override;
size_t get_subscription_count() const override;
private:
std::shared_ptr< image_transport::Publisher > image_publisher_impl;
};
} // namespace realsense2_camera
| 32.339623 | 91 | 0.715869 |
ec48318580d731a395d174dc5497f50159cb5d69 | 1,874 | h | C | src/conv2d/direct/kernel_params.h | GeorgeWeb/SYCL-DNN | 50fe1357f5302d188d85512c58de1ae7ed8a0912 | [
"Apache-2.0"
] | 85 | 2018-06-04T08:07:20.000Z | 2022-03-30T15:53:46.000Z | src/conv2d/direct/kernel_params.h | GeorgeWeb/SYCL-DNN | 50fe1357f5302d188d85512c58de1ae7ed8a0912 | [
"Apache-2.0"
] | 8 | 2019-07-19T11:10:43.000Z | 2021-02-05T10:18:49.000Z | src/conv2d/direct/kernel_params.h | GeorgeWeb/SYCL-DNN | 50fe1357f5302d188d85512c58de1ae7ed8a0912 | [
"Apache-2.0"
] | 19 | 2018-12-28T12:09:22.000Z | 2022-01-08T02:55:14.000Z | /*
* Copyright 2018 Codeplay Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SYCLDNN_SRC_CONV2D_DIRECT_KERNEL_PARAMS_H_
#define SYCLDNN_SRC_CONV2D_DIRECT_KERNEL_PARAMS_H_
#include "sycldnn/conv2d/conv_type.h"
#include "sycldnn/conv2d/params.h"
#include <utility>
namespace sycldnn {
namespace conv2d {
namespace internal {
namespace direct {
/**
* Transform the user provided parameters into those expected by the kernels.
*/
template <typename ConvType>
static inline Conv2DParams get_kernel_params(Conv2DParams params) {
return params;
}
template <>
inline Conv2DParams get_kernel_params<conv_type::InputBackprop>(
Conv2DParams params) {
std::swap(params.channels, params.features);
return params;
}
template <>
inline Conv2DParams get_kernel_params<conv_type::FilterBackprop>(
Conv2DParams params) {
const auto window_rows =
params.out_rows * params.stride_rows - (params.stride_rows - 1);
const auto window_cols =
params.out_cols * params.stride_cols - (params.stride_cols - 1);
params.out_rows = params.window_rows;
params.out_cols = params.window_cols;
params.window_rows = window_rows;
params.window_cols = window_cols;
return params;
}
} // namespace direct
} // namespace internal
} // namespace conv2d
} // namespace sycldnn
#endif // SYCLDNN_SRC_CONV2D_DIRECT_KERNEL_PARAMS_H_
| 31.762712 | 77 | 0.762006 |
b9263d11b5496228a15b0152d72c5da255c917a8 | 1,445 | h | C | compiler_old/cStmtsNode.h | qwertymodo/stackl | b34769d41afff7e125bef8dde27c14a279fd304c | [
"MIT"
] | 11 | 2016-04-26T15:47:43.000Z | 2021-11-04T06:17:27.000Z | compiler_old/cStmtsNode.h | qwertymodo/stackl | b34769d41afff7e125bef8dde27c14a279fd304c | [
"MIT"
] | 8 | 2015-04-17T19:15:24.000Z | 2020-07-23T17:15:58.000Z | compiler_old/cStmtsNode.h | philip-w-howard/stackl | 2ac986e29ef9294aa93c08ed10c12968500273a4 | [
"MIT"
] | 3 | 2019-05-01T18:21:52.000Z | 2021-11-04T06:47:07.000Z | #pragma once
//*******************************************************
// Purpose: Class for a list of statements
//
// Author: Philip Howard
// Email: phil.howard@oit.edu
//
// Date: 2/20/2015
//
//*******************************************************
#include <string>
#include <list>
using std::list;
#include "cAstNode.h"
#include "cAstList.h"
class cStmtsNode : public cAstNode
{
public:
// create the list and insert the first statement
cStmtsNode(cStmtNode *stmt) : cAstNode()
{
mList = new list<cStmtNode *>();
if (stmt != NULL) mList->push_back(stmt);
}
// add a statement to the list
void AddNode(cStmtNode *stmt)
{
if (stmt != NULL) mList->push_back(stmt);
}
virtual int ComputeOffsets(int base)
{
for (list<cStmtNode *>::iterator it = mList->begin();
it != mList->end(); it++)
{
base = (*it)->ComputeOffsets(base);
}
return base;
}
virtual std::string toString()
{
std::string result("STMTS:\n{\n");
result += ListToString(mList, true);
result += "}\n";
return result;
}
virtual void GenerateCode()
{
for (list<cStmtNode *>::iterator it = mList->begin();
it != mList->end(); it++)
{
(*it)->GenerateCode();
}
}
protected:
list<cStmtNode *> *mList; // list of statements
};
| 21.893939 | 62 | 0.498962 |
f34e40dc851b5d2c17f58b10e07f3862813ca5fb | 3,605 | h | C | pathfinderai.h | vitorgodeiro/Labirinto | 3fe067b42c0b748d74928a74b4af66e625d417e6 | [
"MIT"
] | null | null | null | pathfinderai.h | vitorgodeiro/Labirinto | 3fe067b42c0b748d74928a74b4af66e625d417e6 | [
"MIT"
] | null | null | null | pathfinderai.h | vitorgodeiro/Labirinto | 3fe067b42c0b748d74928a74b4af66e625d417e6 | [
"MIT"
] | null | null | null | /**
* Projeto: Maze
* Versao: 1.0b
* Autores: Leno
* Raimundo
*/
#ifndef PATHFINDERAI_H
#define PATHFINDERAI_H
#include "labirinto.h"
#include <vector>
#include <QTimer>
#include <QObject>
#include <QMutex>
/**
* @brief Cria a inteligencia artificial para caminhar no labirinto ate atingir
* uma celula.
* A IA foi modelada usando o seguinte:
* - Tempo para tomar uma decisao, ou seja, o tempo para ir para a proxima celula;
* - Probabilidade de tomar a decisao certa, ou seja, a probabilidade de a proxima
* celula ser a certa;
* - Capacidade de memoria: quantidade de celulas ja visitadas que a AI consegue
* lembrar
*/
class PathFinderAI : public QObject
{
Q_OBJECT
public:
PathFinderAI();
~PathFinderAI();
/**
* @brief Inicia a procura pela celula final
* @return sempre true.
*/
bool start();
/**
* @brief Interrompe a procura pela celula final
* @return sempre true.
*/
bool stop();
/**
* @brief Obtem o coeficiente de inteligencia da busca pela celula final
*
* @return um inteiro de 1 a 200 que representa o coeficiente de
* inteligencia usado na busca
*/
int getIQ() const { return iq_;}
/**
* @brief Define o coeficiente de inteligencia da busca pela celula final
*
* @param iq um numero de 1 a 200. Quanto maior, mais rapida e eficiente e a
* busca pela celula final.
* @return sempre true.
*/
bool setIQ(int iq);
/**
* @brief Obtem o labirinto usado na busca.
* @return o labirinto usado na busca, ou NULL se ele nao existe.
*/
Labirinto *getLabirinto() const { return labirinto_;}
/**
* @brief Define o labirinto usado na busca
* @param labirinto um labirinto
*/
void setLabirinto(Labirinto* labirinto) { labirinto_ = labirinto;}
/**
* @brief Obtem a celula inicial, ou seja, aquela da qual comecara a busca.
* @return a celula inicial
*/
Labirinto::Cell getInitialCell() const { return initial_cell_; }
/**
* @brief Obtem a celula final, ou seja, aquela na qual terminara a busca.
* @return a celula final
*/
Labirinto::Cell getFinalCell() const { return final_cell_; }
/**
* @brief Obtem a celula atual na busca.
* @return a celula atual
*/
Labirinto::Cell getCurrentCell();
/**
* @brief Define a celula inicial
* @param cell uma celula valida
*/
void setInitialCell(const Labirinto::Cell& cell) { initial_cell_ = cell; }
/**
* @brief Define a celula final
* @param cell uma celula valida
*/
void setFinalCell(const Labirinto::Cell& cell) { final_cell_ = cell; }
/**
* @brief Define a celula atual
* @param cell uma celula valida
*/
void setCurrentCell(const Labirinto::Cell& cell) { current_cell_ = cell; }
private slots:
/**
* @brief Atualiza a posicao da celula na busca pela celula final.
*/
void update();
private:
QMutex mutex_; ///< garante exclusao mutua no acesso a celula atual
QTimer timer_; ///< timer usado na atualizacao da celula atual
Labirinto *labirinto_; ///< o labirinto usado na busca do caminho
Labirinto::Cell initial_cell_; ///< a celula inicial
Labirinto::Cell final_cell_; ///< a celula final
Labirinto::Cell current_cell_; ///< a celula atual
std::vector<Labirinto::Cell> memory_; ////< as ultimas celulas visitadas
int memory_size_; ///< define o tamanho maximo da memoria
int iq_; /// o coeficiente de inteligencia
};
#endif // PATHFINDERAI_H
| 26.902985 | 82 | 0.644383 |
b417eb953f43cf283de5f0f066eef1c99fe87622 | 1,277 | c | C | ncurses.c | WaryWolf/forest | 2025e05e3e8f9d1fd22a00ccf6398464cdddcdcd | [
"MIT"
] | 1 | 2019-09-14T12:14:06.000Z | 2019-09-14T12:14:06.000Z | ncurses.c | WaryWolf/forest | 2025e05e3e8f9d1fd22a00ccf6398464cdddcdcd | [
"MIT"
] | null | null | null | ncurses.c | WaryWolf/forest | 2025e05e3e8f9d1fd22a00ccf6398464cdddcdcd | [
"MIT"
] | null | null | null | #include "forest.h"
void init_ncurses(int x, int y) {
//system("resize -s 50 50");
initscr();
start_color();
init_pair(1, COLOR_BLACK, COLOR_BLACK);
init_pair(2, COLOR_RED, COLOR_RED);
init_pair(3, COLOR_GREEN, COLOR_GREEN);
wresize(stdscr, x, y);
}
void out_ncurses(forest* f) {
int x, y;
cell* c;
erase();
for (y = 0; y < f->dimY; y++) {
for (x = 0; x < f->dimX; x++) {
c = &f->newGrid[y][x];
switch(c->status) {
case EMPTY:
attron(COLOR_PAIR(1));
mvprintw(x,y,"X");
attroff(COLOR_PAIR(1));
break;
case BURN:
attron(COLOR_PAIR(2));
mvprintw(x,y,"X");
attroff(COLOR_PAIR(2));
break;
case TREE:
attron(COLOR_PAIR(3));
mvprintw(x,y,"X");
attroff(COLOR_PAIR(3));
break;
default:
mvprintw(x,y,"*");
break;
}
}
printw("\n");
}
refresh();
usleep(100000);
//getch();
//endwin();
//return 0;
}
| 20.934426 | 43 | 0.39859 |
2ab84f86010d38c6bd7aa17fdd7f2f2c5fb3e525 | 408 | c | C | mdns/libphidgets22/src/ext/mos/mos_dl-unix.c | rabarar/phidget_docker | ceca56c86d27f291a4300a1257c02096862335ec | [
"MIT"
] | null | null | null | mdns/libphidgets22/src/ext/mos/mos_dl-unix.c | rabarar/phidget_docker | ceca56c86d27f291a4300a1257c02096862335ec | [
"MIT"
] | null | null | null | mdns/libphidgets22/src/ext/mos/mos_dl-unix.c | rabarar/phidget_docker | ceca56c86d27f291a4300a1257c02096862335ec | [
"MIT"
] | null | null | null | #include <dlfcn.h>
#include "mos_dl.h"
void *
mos_dlopen(const char *path, int flags) {
return (dlopen(path, flags));
}
int
mos_dlclose(void *hdl) {
return (dlclose(hdl));
}
void *
mos_dlsym(void * __restrict hdl, const char * __restrict symname) {
return (dlsym(hdl, symname));
}
const char *
mos_dlerror(char *msgbuf, size_t bufsz) {
mos_strlcpy(msgbuf, dlerror(), bufsz);
return (msgbuf);
}
| 14.068966 | 67 | 0.683824 |
cc8e2b100d94ae96b6dc69252d5e416b19599799 | 245 | c | C | Recursion/100_1_rec.c | Srinujavahub/Cprogram | b8bdf9dc53f0742b663bf8c9559aa71a4ff7ee19 | [
"MIT"
] | null | null | null | Recursion/100_1_rec.c | Srinujavahub/Cprogram | b8bdf9dc53f0742b663bf8c9559aa71a4ff7ee19 | [
"MIT"
] | null | null | null | Recursion/100_1_rec.c | Srinujavahub/Cprogram | b8bdf9dc53f0742b663bf8c9559aa71a4ff7ee19 | [
"MIT"
] | null | null | null | #include<stdio.h>
void display(int);
void main()
{
int num;
printf("Enter the number\n");
scanf("%d",&num);
printf("%d\t",num);
display(num);
}
void display(int n)
{
if(n == 0)
return;
n = n-1;
printf("%d\t",n);
display(n);
}
| 9.8 | 30 | 0.559184 |
006168ea9dab6acdbebf3b981865559c2d8ba530 | 193 | h | C | PodTest/class/common/Model.h | SampleProjectsBooth/PodTest | beafa45ad9d318b422c4202db2edd01288e9dafe | [
"MIT"
] | null | null | null | PodTest/class/common/Model.h | SampleProjectsBooth/PodTest | beafa45ad9d318b422c4202db2edd01288e9dafe | [
"MIT"
] | null | null | null | PodTest/class/common/Model.h | SampleProjectsBooth/PodTest | beafa45ad9d318b422c4202db2edd01288e9dafe | [
"MIT"
] | null | null | null | //
// Model.h
// PodTest
//
// Created by LamTsanFeng on 2020/10/29.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Model : NSObject
@end
NS_ASSUME_NONNULL_END
| 11.352941 | 41 | 0.720207 |
6d123ecb757371d8c4ba4f15b56a3d6785af0692 | 2,771 | h | C | source/math/nckQuadtree.h | nczeroshift/nctoolkit | c9f0be533843d52036ec45200512ac54c1faeb11 | [
"MIT"
] | 2 | 2016-10-16T22:26:01.000Z | 2022-03-29T14:32:15.000Z | source/math/nckQuadtree.h | nczeroshift/nctoolkit | c9f0be533843d52036ec45200512ac54c1faeb11 | [
"MIT"
] | 1 | 2015-12-08T00:27:10.000Z | 2016-10-30T21:59:50.000Z | source/math/nckQuadtree.h | nczeroshift/nctoolkit | c9f0be533843d52036ec45200512ac54c1faeb11 | [
"MIT"
] | 2 | 2016-07-18T21:42:10.000Z | 2019-12-16T01:33:20.000Z |
/**
* NCtoolKit © 2007-2017 Luís F.Loureiro, under zlib software license.
* https://github.com/nczeroshift/nctoolkit
*/
#ifndef NCK_QUADTREE_H
#define NCK_QUADTREE_H
#include "nckBoundBox.h"
#include <list>
#include <vector>
_MATH_BEGIN
class Quadtree_Node;
/**
* Quadtree leaf abstract class. Implement the abstract methods on a
* subclass to complete the custom quadtree generation.
*/
class Quadtree_Leaf{
public:
/**
* Default constructor.
*/
Quadtree_Leaf();
/**
* Quadtree leaf constructor.
* @param id Leaf sequencial id number.
* @param parent Reference to parent node.
*/
Quadtree_Leaf(int id, Quadtree_Node * parent);
/**
* Destructor.
*/
virtual ~Quadtree_Leaf();
/**
* Setter for parent node reference.
*/
void SetParent(Quadtree_Node * parent);
/**
* Getter for the parent node reference.
*/
Quadtree_Node * GetParent();
/**
* Set neighbour leaf reference, assuming it touches the parent leaf
* node boundbox, it may touch up to 8 leafs.
* @param i Neighbour index, a number between 0 and 7.
* @param leaf Neighbour Quadtree leaf reference.
*/
void SetNeighbour(int i, Quadtree_Leaf * leaf);
/**
* Get neighbour leaf reference.
* @param i Neighbour index, a number between 0 and 7.
*/
Quadtree_Leaf * GetNeighbours(int i);
protected:
int m_Id;
Quadtree_Leaf * m_Neighbours[8];
Quadtree_Node * m_Parent;
};
/**
* Quadtree node abstract class. Implement the abstract methods on a
* subclass to complete the custom quadtree generation.
*/
class Quadtree_Node{
public:
/**
* Default constructor.
*/
Quadtree_Node();
/**
* Constructor with boundbox.
* @param bb Boundbox.
*/
Quadtree_Node(const BoundBox & bb);
virtual ~Quadtree_Node();
/**
* Get node boundbox.
*/
inline Math::BoundBox GetBoundbox() const {
return m_BoundBox;
}
/**
* Construct quadtree by "inserting" a boundbox through the datastructre.
* @param bb Object boundbox to be inserted.
* @param maxDepth Maximum depth when constructing the quadtree.
* @param foundLeaf Reference to the quadtree leaf.
*/
void Build(const BoundBox & bb, int maxDepth, Quadtree_Leaf ** foundLeaf,
Quadtree_Node * nodeAllocator(const BoundBox & bb));
/**
* Return reference to leaf.
*/
Quadtree_Leaf * GetLeaf();
protected:
/**
* Abstract method to be implemented when creating the leafs.
*/
virtual Quadtree_Leaf * CreateLeaf() = 0;
/**
* Compute boundbox for children id.
* @param id Number between 0 and 3 for each child.
*/
BoundBox ComputeBoundBox(int id);
/**
* Node boundbox.
*/
BoundBox m_BoundBox;
/**
* Reference to each node children nodes.
*/
Quadtree_Node * m_Children[4];
/**
* Reference to node leaf.
*/
Quadtree_Leaf * m_Leaf;
};
_MATH_END
#endif // #ifndef NCK_QUADTREE_H
| 19.377622 | 75 | 0.702634 |
a39d04a360ae8fd229e0abe3cd876aa17dc9ca4a | 8,945 | h | C | src/mpi/common/mpistr.h | hpourreza/Microsoft-MPI | 1dbbaee6373245d0458a8d775b2618b54df2a1eb | [
"mpich2",
"MIT"
] | 147 | 2019-05-07T05:35:01.000Z | 2022-02-08T06:36:22.000Z | src/mpi/common/mpistr.h | hpourreza/Microsoft-MPI | 1dbbaee6373245d0458a8d775b2618b54df2a1eb | [
"mpich2",
"MIT"
] | 39 | 2019-05-07T15:54:41.000Z | 2021-12-03T12:00:31.000Z | src/mpi/common/mpistr.h | hpourreza/Microsoft-MPI | 1dbbaee6373245d0458a8d775b2618b54df2a1eb | [
"mpich2",
"MIT"
] | 48 | 2019-05-10T10:21:36.000Z | 2022-03-13T18:04:17.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <strsafe.h>
#include <oacr.h>
/*@ MPIU_Strncpy - Copy a string with buffer size. Force null termination
Input Parameters:
. dst - String to copy into
+ src - String to copy
- n - 'dst' buffer size in chars (including null char)
Return value:
pointer to the end terminating null char
Notes:
This routine is the routine that you wish 'strncpy' was. In copying
'src' to 'dst', it stops when either the end of 'src' (the
null character) is seen or the maximum length 'n is reached.
Unlike 'strncpy', it does not add enough nulls to 'dst' after
copying 'src' in order to move precisely 'n' characters.
This routine is safer than strncpy; it always null terminates the dst
string. (except when the dst size is zero)
MPIU_Strncpy is implemented inline to help the compiler optimize
per use instance.
Module:
Utility
@*/
_Ret_z_
_Success_(return!=nullptr)
static inline char*
MPIU_Strncpy(
_Out_writes_z_(n) char* dst,
_In_z_ const char* src,
_In_ size_t n
)
{
char* end;
OACR_WARNING_SUPPRESS(USE_WIDE_API, "MSMPI uses only ANSI character set.");
HRESULT hr = StringCchCopyExA( dst, n, src, &end, nullptr, 0 );
if( hr == STRSAFE_E_INVALID_PARAMETER )
{
return nullptr;
}
return end;
}
_Ret_z_
_Success_(return!=nullptr)
static inline wchar_t*
MPIU_Strncpy(
_Out_writes_z_(n) wchar_t* dst,
_In_z_ const wchar_t* src,
_In_ size_t n
)
{
wchar_t* end;
HRESULT hr = StringCchCopyExW( dst, n, src, &end, nullptr, 0 );
if( hr == STRSAFE_E_INVALID_PARAMETER )
{
return nullptr;
}
return end;
}
//
// Summary:
// This is a convenient wrapper for StringCchCopyA
//
// Return: 0 if success, other errors if failure
//
_Success_(return == 0)
int
MPIU_Strcpy(
_Out_writes_z_(cchDest) char* dest,
_In_ size_t cchDest,
_In_z_ const char* src
);
//
// Summary:
// This is a convenient wrapper for StringCchCopyW
//
// Return: 0 if success, other errors if failure
//
_Success_(return == 0)
int
MPIU_Strcpy(
_Out_writes_z_(cchDest) wchar_t* dest,
_In_ size_t cchDest,
_In_z_ const wchar_t* src
);
/*@ MPIU_Szncpy - Copy a string into a fixed sized buffer; force null termination
MPIU_Szncpy is a helper macro provided for copying into fixed sized char arrays.
The macro computes the size (char count) of the dst array. Usage example,
char buffer[333];
...
-* copy max 333 chars into buffer; buffer will be null terminated. *-
MPIU_Szncpy(buffer, str);
@*/
#define MPIU_Szncpy(dst, src) MPIU_Strncpy(dst, src, _countof(dst))
/*@ MPIU_Strnapp - Append to a string with buffer size. Force null termination
Input Parameters:
. dst - String to copy into
+ src - String to append
- n - 'dst' buffer size in chars (including null char)
Output Parameter:
pointer to the end terminating null char
Notes:
This routine is similar to 'strncat' except that the 'n' argument
is the maximum total length of 'dst', rather than the maximum
number of characters to move from 'src'. Thus, this routine is
easier to use when the declared size of 'src' is known.
MPIU_Strnapp is implemented inline to help the compiler optimize
per use instance.
Module:
Utility
@*/
void MPIU_Strnapp(
_Out_writes_z_(n) char *dst,
_In_z_ const char *src,
_In_ size_t n);
void MPIU_Strnapp(
_Out_writes_z_(n) wchar_t *dst,
_In_z_ const wchar_t *src,
_In_ size_t n);
/*@ MPIU_Sznapp - Append a string into a fixed sized buffer; force null termination
MPIU_Sznapp is a helper macro provided for appending into fixed sized char arrays.
The macro computes the size (char count) of the dst array. Usage example,
char buffer[333] = "Initial string";
...
-* copy max 333 chars into buffer; buffer will be null terminated. *-
MPIU_Sznapp(buffer, str);
@*/
#define MPIU_Sznapp(dst, src) MPIU_Strnapp(dst, src, _countof(dst))
size_t MPIU_Strlen(
_In_ PCSTR src,
_In_ size_t cchMax = STRSAFE_MAX_CCH );
size_t MPIU_Strlen(
_In_ PCWSTR src,
_In_ size_t cchMax = STRSAFE_MAX_CCH );
/* ---------------------------------------------------------------------- */
/* FIXME - The string routines do not belong in the memory header file */
/* FIXME - The string error code such be MPICH2-usable error codes */
#define MPIU_STR_SUCCESS 0
#define MPIU_STR_FAIL -1
#define MPIU_STR_NOMEM 1
/* FIXME: TRUE/FALSE definitions should either not be used or be
used consistently. These also do not belong in the mpimem header file. */
#define MPIU_TRUE 1
#define MPIU_FALSE 0
/* FIXME: Global types like this need to be discussed and agreed to */
typedef int MPIU_BOOL;
/* FIXME: These should be scoped to only the routines that need them */
#ifdef USE_HUMAN_READABLE_TOKENS
#define MPIU_STR_QUOTE_CHAR '\"'
#define MPIU_STR_QUOTE_STR "\""
#define MPIU_STR_DELIM_CHAR '='
#define MPIU_STR_DELIM_STR "="
#define MPIU_STR_ESCAPE_CHAR '\\'
#define MPIU_STR_SEPAR_CHAR ' '
#define MPIU_STR_SEPAR_STR " "
#else
#define MPIU_STR_QUOTE_CHAR '\"'
#define MPIU_STR_QUOTE_STR "\""
#define MPIU_STR_DELIM_CHAR '#'
#define MPIU_STR_DELIM_STR "#"
#define MPIU_STR_ESCAPE_CHAR '\\'
#define MPIU_STR_SEPAR_CHAR '$'
#define MPIU_STR_SEPAR_STR "$"
#endif
_Success_(return == MPIU_STR_SUCCESS)
int
MPIU_Str_get_string_arg(
_In_opt_z_ const char* str,
_In_opt_z_ const char* key,
_Out_writes_z_(val_len) char* val,
_In_ size_t val_len
);
_Success_(return == MPIU_STR_SUCCESS)
int
MPIU_Str_get_int_arg(
_In_z_ const char *str,
_In_z_ const char *flag,
_Out_ int *val_ptr
);
_Success_(return == MPIU_STR_SUCCESS)
int
MPIU_Str_add_string_arg(
_Inout_ _Outptr_result_buffer_(*maxlen_ptr) PSTR*str_ptr,
_Inout_ int *maxlen_ptr,
_In_z_ const char *flag,
_In_z_ const char *val
);
_Success_(return == MPIU_STR_SUCCESS)
int
MPIU_Str_add_int_arg(
_Inout_ _Outptr_result_buffer_(*maxlen_ptr) PSTR*str_ptr,
_Inout_ int *maxlen_ptr,
_In_z_ const char *flag,
_In_ int val
);
_Success_(return == MPIU_STR_SUCCESS)
int
MPIU_Str_add_string(
_Inout_ _Outptr_result_buffer_(*maxlen_ptr) PSTR*str_ptr,
_Inout_ int *maxlen_ptr,
_In_z_ const char *val
);
_Success_(return == 0)
int
MPIU_Str_get_string(
_Inout_ _Outptr_result_maybenull_z_ PCSTR* str_ptr,
_Out_writes_z_(val_len)char *val,
_In_ size_t val_len
);
//
// Provide a fallback snprintf for systems that do not have one
//
_Success_(return >= 0 && return <= cchDest)
int
MPIU_Snprintf(
_Null_terminated_ _Out_writes_to_(cchDest, return) char* dest,
_In_ size_t cchDest,
_Printf_format_string_ const char* format,
...
);
//
// Overloaded function for wide characters
//
_Success_(return >= 0 && return <= cchDest)
int
MPIU_Snprintf(
_Null_terminated_ _Out_writes_to_(cchDest, return) wchar_t* dest,
_In_ size_t cchDest,
_Printf_format_string_ const wchar_t* format,
...
);
//
// Provide vsnprintf functionality by using strsafe's StringCchVPrintfEx
//
_Success_(return >= 0 && return <= cchDest)
int
MPIU_Vsnprintf(
_Null_terminated_ _Out_writes_to_(cchDest,return)char* dest,
_In_ size_t cchDest,
_Printf_format_string_ const char* format,
_In_ va_list args
);
//
// Overloaded function for wide characters
// Provide vsnprintf functionality by using strsafe's StringCchVPrintfEx
//
_Success_(return >= 0 && return <= cchDest)
int
MPIU_Vsnprintf(
_Null_terminated_ _Out_writes_to_(cchDest, return) wchar_t* dest,
_In_ size_t cchDest,
_Printf_format_string_ const wchar_t* format,
_In_ va_list args
);
//
// Provide _strdup functionality
//
_Ret_valid_ _Null_terminated_
_Success_(return != nullptr)
char*
MPIU_Strdup(
_In_z_ const char* str
);
_Ret_valid_ _Null_terminated_
_Success_(return != nullptr)
wchar_t*
MPIU_Strdup(
_In_z_ const wchar_t* str
);
//
// Callee will need to call delete[] to free the memory allocated
// for wname_ptr if the function succeeds.
//
_Success_(return == NOERROR)
DWORD
MPIU_MultiByteToWideChar(
_In_z_ const char* name,
_Outptr_result_z_ wchar_t** wname_ptr
);
//
// Callee will need to call delete[] to free the memory allocated
// for outputStr if the function succeeds.
//
_Success_(return == NOERROR)
DWORD
MPIU_WideCharToMultiByte(
_In_z_ const wchar_t* str,
_Outptr_result_z_ char** outputStr
);
| 24.373297 | 86 | 0.680268 |
a3fa54b686048e8fcb0b15a253ac24d4ac80c063 | 994 | h | C | TW/TW_Engine/TW_StopWatch.h | TWANG006/TW | 5f4ce9fc74dcc748730de5b75d75dcb5b7d71791 | [
"BSD-3-Clause"
] | 4 | 2019-07-21T07:06:42.000Z | 2020-11-26T02:37:08.000Z | TW/TW_Engine/TW_StopWatch.h | TWANG006/TW | 5f4ce9fc74dcc748730de5b75d75dcb5b7d71791 | [
"BSD-3-Clause"
] | null | null | null | TW/TW_Engine/TW_StopWatch.h | TWANG006/TW | 5f4ce9fc74dcc748730de5b75d75dcb5b7d71791 | [
"BSD-3-Clause"
] | 6 | 2019-07-02T14:20:24.000Z | 2022-03-11T03:06:29.000Z | #ifndef TW_STOPWATCH_H
#define TW_STOPWATCH_H
#include "TW.h"
#include <Windows.h>
namespace TW
{
class TW_LIB_DLL_EXPORTS StopWatch
{
public:
StopWatch();
~StopWatch();
void start(); //! Start timer
void stop(); //! Stop timer
void reset(); //! Reset timer
//! Get elapsed time after calling start() or time between
//! stop() and start()
double getElapsedTime();
//! Average time = TotalTime / number of stops
double getAverageTime();
private:
LARGE_INTEGER m_startTime; //! Start time
LARGE_INTEGER m_endTime; //! End time
double m_dElapsedTime; //! Time elapsed between the last start and stop
double m_dTotalTime; //! Time elapsed between all starts and stops
bool m_isRunning; //! Judge if timer is still running
int_t m_iNumClockSessions; //! Number of starts and stops
double m_dFreq; //! Frequency
bool m_isFreqSet; //! Judge if the frequency is set
};
} //!- namespace TW
#endif // !TW_STOPWATCH_H
| 24.243902 | 74 | 0.677062 |
9315c6af7c7da1e7383bdbdb3c13038714573686 | 3,341 | h | C | 3.15/src/ca/legacy/pcas/example/directoryService/directoryServer.h | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | 3.15/src/ca/legacy/pcas/example/directoryService/directoryServer.h | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | 3.15/src/ca/legacy/pcas/example/directoryService/directoryServer.h | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | /*************************************************************************\
* Copyright (c) 2002 The University of Chicago, as Operator of Argonne
* National Laboratory.
* Copyright (c) 2002 The Regents of the University of California, as
* Operator of Los Alamos National Laboratory.
* EPICS BASE Versions 3.13.7
* and higher are distributed subject to a Software License Agreement found
* in file LICENSE that is included with this distribution.
\*************************************************************************/
//
// Example EPICS CA directory server
//
//
// caServer
// |
// directoryServer
//
//
//
// ANSI C
//
#include <string.h>
#include <stdio.h>
//
// EPICS
//
#define epicsAssertAuthor "Jeff Hill johill@lanl.gov"
#define caNetAddrSock
#include "casdef.h"
#include "epicsAssert.h"
#include "resourceLib.h"
#ifndef NELEMENTS
# define NELEMENTS(A) (sizeof(A)/sizeof(A[0]))
#endif
class directoryServer;
//
// pvInfo
//
class pvInfo {
public:
pvInfo (const char *pNameIn, sockaddr_in addrIn) :
addr(addrIn), pNext(pvInfo::pFirst)
{
pvInfo::pFirst = this;
this->pName = new char [strlen(pNameIn)+1u];
strcpy(this->pName, pNameIn);
}
const struct sockaddr_in getAddr() const { return this->addr; }
const char *getName () const { return this->pName; }
const pvInfo *getNext () const { return this->pNext; }
static const pvInfo *getFirst () { return pvInfo::pFirst; }
private:
struct sockaddr_in addr;
char * pName;
const pvInfo * pNext;
static const pvInfo * pFirst;
};
//
// pvEntry
//
// o entry in the string hash table for the pvInfo
// o Since there may be aliases then we may end up
// with several of this class all referencing
// the same pv info class (justification
// for this breaking out into a seperate class
// from pvInfo)
//
class pvEntry
: public stringId, public tsSLNode<pvEntry> {
public:
pvEntry (const pvInfo &infoIn, directoryServer &casIn,
const char *pAliasName) :
stringId(pAliasName), info(infoIn), cas(casIn)
{
assert(this->stringId::resourceName()!=NULL);
}
inline ~pvEntry();
const pvInfo &getInfo() const { return this->info; }
inline void destroy ();
private:
const pvInfo &info;
directoryServer &cas;
};
//
// directoryServer
//
class directoryServer : public caServer {
public:
directoryServer ( const char * const pvPrefix, unsigned aliasCount );
~directoryServer();
void show ( unsigned level ) const;
void installAliasName ( const pvInfo &info, const char *pAliasName );
void removeAliasName ( pvEntry &entry );
private:
resTable < pvEntry, stringId > stringResTbl;
pvExistReturn pvExistTest ( const casCtx&,
const char *pPVName );
pvExistReturn pvExistTest ( const casCtx&,
const caNetAddr &, const char *pPVName );
};
//
// directoryServer::removeAliasName()
//
inline void directoryServer::removeAliasName ( pvEntry & entry )
{
pvEntry * pE = this->stringResTbl.remove ( entry );
assert ( pE == & entry );
}
//
// pvEntry::~pvEntry()
//
inline pvEntry::~pvEntry()
{
this->cas.removeAliasName(*this);
}
//
// pvEntry::destroy()
//
inline void pvEntry::destroy ()
{
//
// always created with new
//
delete this;
}
| 22.574324 | 75 | 0.630949 |
4f15f7b27d14fb770c52e1b6f5aade3900cdac92 | 26 | c | C | src/guest.c | Neopallium/cr-sys | 26450eacc001ac948de8e5a63a2e74a9249372ad | [
"MIT"
] | 1 | 2021-10-11T21:47:06.000Z | 2021-10-11T21:47:06.000Z | src/guest.c | Neopallium/cr-sys | 26450eacc001ac948de8e5a63a2e74a9249372ad | [
"MIT"
] | null | null | null | src/guest.c | Neopallium/cr-sys | 26450eacc001ac948de8e5a63a2e74a9249372ad | [
"MIT"
] | null | null | null | #include "../vendor/cr.h"
| 13 | 25 | 0.615385 |
9ee038cff05d318ec17f93db565186ac9cb6a9b8 | 1,974 | h | C | src/place.h | Angry-Potato/islander | 827dd809f79322b86360a3b2fac42a0acba03df4 | [
"MIT"
] | null | null | null | src/place.h | Angry-Potato/islander | 827dd809f79322b86360a3b2fac42a0acba03df4 | [
"MIT"
] | null | null | null | src/place.h | Angry-Potato/islander | 827dd809f79322b86360a3b2fac42a0acba03df4 | [
"MIT"
] | null | null | null | #ifndef PLACE_H
#define PLACE_H
#include <string>
#include <limits>
#include "vector2d.h"
#include "geometry.h"
struct Place {
Place(std::string id = "", long x = 0, long y = 0) : _id(id), _position(new Vector2D(x, y)) {
_nearestPlace = (Place*)0;
_isPotentialIsland = true;
_distanceToNearestPlace = -1;
};
~Place() {
delete _position;
};
inline const long X() const {return _position->X();};
inline const long Y() const {return _position->Y();};
inline const bool isPotentialIsland() const {return _isPotentialIsland;};
inline const std::string id() const {return _id;};
inline const Vector2D position() const {return *_position;};
inline const bool hasNearestPlace() const {return _nearestPlace != (Place*)0;};
inline const Place* nearestPlace() const {return _nearestPlace;};
inline const long distanceToNearestPlace() const {
return _distanceToNearestPlace;
};
inline void notPotentialIsland(long& potentialsRemaining) {
potentialsRemaining -= _isPotentialIsland ? 1 : 0;
_isPotentialIsland = false;
if (hasNearestPlace()) {
if (_nearestPlace->hasNearestPlace() && _id == _nearestPlace->nearestPlace()->id()) {
potentialsRemaining -= _nearestPlace->_isPotentialIsland ? 1 : 0;
_nearestPlace->_isPotentialIsland = false;
}
else {
_nearestPlace->notPotentialIsland(potentialsRemaining);
}
}
};
inline bool setNearestPlace(Place* place) {
if (place == (Place*)0 || _id == place->_id) {
return false;
}
_nearestPlace = place;
_distanceToNearestPlace = Geometry::squaredDistanceBetween(*_position, *_nearestPlace->_position);
return true;
};
inline const bool operator==(const Place& rhs) const {
return this->id() == rhs.id() && this->position() == rhs.position();
};
protected:
bool _isPotentialIsland;
std::string _id;
Vector2D* _position;
Place* _nearestPlace;
long _distanceToNearestPlace;
};
#endif
| 30.369231 | 102 | 0.679331 |
7fd9f2c1aae501af5e04ab140ac614e31a8e32ad | 265 | h | C | Classes/NumberPadReturn.h | t2health/T2-Mood-Tracker-iOS | 016133b596072662cab5425e21ac61aa2c1f7fc0 | [
"NASA-1.3"
] | 3 | 2015-04-12T15:05:49.000Z | 2021-08-09T17:09:35.000Z | Classes/NumberPadReturn.h | t2health/T2-Mood-Tracker-iOS | 016133b596072662cab5425e21ac61aa2c1f7fc0 | [
"NASA-1.3"
] | null | null | null | Classes/NumberPadReturn.h | t2health/T2-Mood-Tracker-iOS | 016133b596072662cab5425e21ac61aa2c1f7fc0 | [
"NASA-1.3"
] | 2 | 2015-08-15T10:16:22.000Z | 2018-09-13T17:58:06.000Z | //
// NumberPadReturn.h
// VAS002
//
// Created by Hasan Edain on 1/7/11.
// Copyright 2011 GDIT. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UIViewController (NumPadReturn)
- (void)addButtonToKeyboard;
@end
| 15.588235 | 45 | 0.709434 |
2c9426a1b0cce439587369855f9956ca4cd86027 | 888 | h | C | 1Projekt/include/Entity.h | Miki864/PSIOProject | 26a1b14191633a524e50433562c368c7c92c9c97 | [
"MIT"
] | null | null | null | 1Projekt/include/Entity.h | Miki864/PSIOProject | 26a1b14191633a524e50433562c368c7c92c9c97 | [
"MIT"
] | null | null | null | 1Projekt/include/Entity.h | Miki864/PSIOProject | 26a1b14191633a524e50433562c368c7c92c9c97 | [
"MIT"
] | null | null | null | #ifndef ENTITY_H
#define ENTITY_H
#include <iostream>
class Entity
{
public:
Entity(){}
virtual ~Entity(){}
void st_plus(int bonus=1){st+=bonus;}
void ag_plus(int bonus=1){ag+=bonus;}
void iq_plus(int bonus=1){iq+=bonus;}
void max_hp_plus(int bonus=1){max_hp+=bonus;}
void healing_skill_plus(int bonus=1){healing_skill+=bonus;}
void damage_given_plus(int bonus=1){damage_given+=bonus;}
void protection_plus(int bonus=1){protection+=bonus;}
void hurt(int dmg){hp=hp-dmg;}
void heal(int healing){hp=hp+healing;if(hp>max_hp){hp=max_hp;}}
int health(){return hp;}
virtual void action()=0;
protected:
int st=4, ag=4, iq=4;
std::string id;
int hp=10,max_hp=10,healing_skill=1,damage_given=3,protection=0;
private:
};
#endif
| 30.62069 | 73 | 0.601351 |
89c2bd1a19e9ef1ccdaec2a29589a0952162acfd | 1,495 | c | C | Foundation-of-CS/ics14_lab1-3/lab1/src/puzzles/float_half.c | chaohu/Daily-Learning | 0e8d14a3497ad319eda20bc4682cec08d5d6fb08 | [
"MIT"
] | 12 | 2016-04-09T15:43:02.000Z | 2022-03-22T01:58:25.000Z | Foundation-of-CS/ics14_lab1-3/lab1/src/puzzles/float_half.c | chaohu/Daily-Learning | 0e8d14a3497ad319eda20bc4682cec08d5d6fb08 | [
"MIT"
] | null | null | null | Foundation-of-CS/ics14_lab1-3/lab1/src/puzzles/float_half.c | chaohu/Daily-Learning | 0e8d14a3497ad319eda20bc4682cec08d5d6fb08 | [
"MIT"
] | 2 | 2018-08-23T07:34:59.000Z | 2019-06-20T10:17:31.000Z | #ifdef PROTOTYPE
unsigned float_half(unsigned);
unsigned test_float_half(unsigned);
#endif
#ifdef DECL
{"float_half", (funct_t) float_half, (funct_t) test_float_half, 1,
"$", 30, 4,
{{1, 1},{1,1},{1,1}}},
#endif
#ifdef CODE
/*
* float_half - Return bit-level equivalent of expression 0.5*f for
* floating point argument f.
* Both the argument and result are passed as unsigned int's, but
* they are to be interpreted as the bit-level representation of
* single-precision floating point values.
* When argument is NaN, return argument
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 30
* Rating: 4
*/
unsigned float_half(unsigned uf) {
#ifdef FIX
unsigned sign = uf>>31;
unsigned exp = uf>>23 & 0xFF;
unsigned frac = uf & 0x7FFFFF;
/* Only roundup case will be when rounding to even */
unsigned roundup = (frac & 0x3) == 3;
if (exp == 0) {
/* Denormalized. Must halve fraction */
frac = (frac >> 1) + roundup;
} else if (exp < 0xFF) {
/* Normalized. Decrease exponent */
exp--;
if (exp == 0) {
/* Denormalize, adding back leading one */
frac = (frac >> 1) + roundup + 0x400000;
}
}
/* NaN Infinity do not require any changes */
return (sign << 31) | (exp << 23) | frac;
#else
return 2;
#endif
}
#endif
#ifdef TEST
unsigned test_float_half(unsigned uf) {
float f = u2f(uf);
float hf = 0.5*f;
if (isnan(f))
return uf;
else
return f2u(hf);
}
#endif
| 26.22807 | 76 | 0.633445 |
326123444d455d30303a89d78d0206cb3f1671a1 | 25,470 | h | C | bebop_driver/include/bebop_driver/autogenerated/common_state_callback_includes.h | tongtybj/bebop_autonomy | 448153dc3acfac9083228c26d165161bba1d3060 | [
"BSD-3-Clause"
] | null | null | null | bebop_driver/include/bebop_driver/autogenerated/common_state_callback_includes.h | tongtybj/bebop_autonomy | 448153dc3acfac9083228c26d165161bba1d3060 | [
"BSD-3-Clause"
] | null | null | null | bebop_driver/include/bebop_driver/autogenerated/common_state_callback_includes.h | tongtybj/bebop_autonomy | 448153dc3acfac9083228c26d165161bba1d3060 | [
"BSD-3-Clause"
] | null | null | null | /**
Software License Agreement (BSD)
\file common_state_callback_includes.h
\authors Mani Monajjemi <mmonajje@sfu.ca>
\copyright Copyright (c) 2015, Autonomy Lab (Simon Fraser University), All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Autonomy Lab nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* common_state_callback_includes.h
* auto-generated from https://raw.githubusercontent.com/Parrot-Developers/libARCommands/5898658a925245555153459ea4684aa87f220e07/Xml/common_commands.xml
* Do not modify this file by hand. Check scripts/meta folder for generator files.
*/
#ifdef FORWARD_DECLARATIONS
namespace cb
{
class CommonCommonStateAllStatesChanged;
class CommonCommonStateBatteryStateChanged;
class CommonCommonStateMassStorageStateListChanged;
class CommonCommonStateMassStorageInfoStateListChanged;
class CommonCommonStateCurrentDateChanged;
class CommonCommonStateCurrentTimeChanged;
class CommonCommonStateMassStorageInfoRemainingListChanged;
class CommonCommonStateWifiSignalChanged;
class CommonCommonStateSensorsStatesListChanged;
class CommonCommonStateProductModel;
class CommonCommonStateCountryListKnown;
class CommonOverHeatStateOverHeatChanged;
class CommonOverHeatStateOverHeatRegulationChanged;
class CommonMavlinkStateMavlinkFilePlayingStateChanged;
class CommonMavlinkStateMavlinkPlayErrorStateChanged;
class CommonCalibrationStateMagnetoCalibrationStateChanged;
class CommonCalibrationStateMagnetoCalibrationRequiredState;
class CommonCalibrationStateMagnetoCalibrationAxisToCalibrateChanged;
class CommonCalibrationStateMagnetoCalibrationStartedChanged;
class CommonFlightPlanStateAvailabilityStateChanged;
class CommonFlightPlanStateComponentStateListChanged;
class CommonARLibsVersionsStateControllerLibARCommandsVersion;
class CommonARLibsVersionsStateSkyControllerLibARCommandsVersion;
class CommonARLibsVersionsStateDeviceLibARCommandsVersion;
class CommonAudioStateAudioStreamingRunning;
class CommonHeadlightsStateintensityChanged;
class CommonAnimationsStateList;
class CommonAccessoryStateSupportedAccessoriesListChanged;
class CommonAccessoryStateAccessoryConfigChanged;
class CommonAccessoryStateAccessoryConfigModificationEnabled;
class CommonChargerStateMaxChargeRateChanged;
class CommonChargerStateCurrentChargeStateChanged;
class CommonChargerStateLastChargeRateChanged;
class CommonChargerStateChargingInfo;
class CommonRunStateRunIdChanged;
} // namespace cb
#endif // FORWARD_DECLARATIONS
#ifdef DEFINE_SHARED_PTRS
// Define all callback wrappers
boost::shared_ptr<cb::CommonCommonStateAllStatesChanged>
common_commonstate_allstateschanged_ptr;
boost::shared_ptr<cb::CommonCommonStateBatteryStateChanged>
common_commonstate_batterystatechanged_ptr;
boost::shared_ptr<cb::CommonCommonStateMassStorageStateListChanged>
common_commonstate_massstoragestatelistchanged_ptr;
boost::shared_ptr<cb::CommonCommonStateMassStorageInfoStateListChanged>
common_commonstate_massstorageinfostatelistchanged_ptr;
boost::shared_ptr<cb::CommonCommonStateCurrentDateChanged>
common_commonstate_currentdatechanged_ptr;
boost::shared_ptr<cb::CommonCommonStateCurrentTimeChanged>
common_commonstate_currenttimechanged_ptr;
boost::shared_ptr<cb::CommonCommonStateMassStorageInfoRemainingListChanged>
common_commonstate_massstorageinforemaininglistchanged_ptr;
boost::shared_ptr<cb::CommonCommonStateWifiSignalChanged>
common_commonstate_wifisignalchanged_ptr;
boost::shared_ptr<cb::CommonCommonStateSensorsStatesListChanged>
common_commonstate_sensorsstateslistchanged_ptr;
boost::shared_ptr<cb::CommonCommonStateProductModel>
common_commonstate_productmodel_ptr;
boost::shared_ptr<cb::CommonCommonStateCountryListKnown>
common_commonstate_countrylistknown_ptr;
boost::shared_ptr<cb::CommonOverHeatStateOverHeatChanged>
common_overheatstate_overheatchanged_ptr;
boost::shared_ptr<cb::CommonOverHeatStateOverHeatRegulationChanged>
common_overheatstate_overheatregulationchanged_ptr;
boost::shared_ptr<cb::CommonMavlinkStateMavlinkFilePlayingStateChanged>
common_mavlinkstate_mavlinkfileplayingstatechanged_ptr;
boost::shared_ptr<cb::CommonMavlinkStateMavlinkPlayErrorStateChanged>
common_mavlinkstate_mavlinkplayerrorstatechanged_ptr;
boost::shared_ptr<cb::CommonCalibrationStateMagnetoCalibrationStateChanged>
common_calibrationstate_magnetocalibrationstatechanged_ptr;
boost::shared_ptr<cb::CommonCalibrationStateMagnetoCalibrationRequiredState>
common_calibrationstate_magnetocalibrationrequiredstate_ptr;
boost::shared_ptr<cb::CommonCalibrationStateMagnetoCalibrationAxisToCalibrateChanged>
common_calibrationstate_magnetocalibrationaxistocalibratechanged_ptr;
boost::shared_ptr<cb::CommonCalibrationStateMagnetoCalibrationStartedChanged>
common_calibrationstate_magnetocalibrationstartedchanged_ptr;
boost::shared_ptr<cb::CommonFlightPlanStateAvailabilityStateChanged>
common_flightplanstate_availabilitystatechanged_ptr;
boost::shared_ptr<cb::CommonFlightPlanStateComponentStateListChanged>
common_flightplanstate_componentstatelistchanged_ptr;
boost::shared_ptr<cb::CommonARLibsVersionsStateControllerLibARCommandsVersion>
common_arlibsversionsstate_controllerlibarcommandsversion_ptr;
boost::shared_ptr<cb::CommonARLibsVersionsStateSkyControllerLibARCommandsVersion>
common_arlibsversionsstate_skycontrollerlibarcommandsversion_ptr;
boost::shared_ptr<cb::CommonARLibsVersionsStateDeviceLibARCommandsVersion>
common_arlibsversionsstate_devicelibarcommandsversion_ptr;
boost::shared_ptr<cb::CommonAudioStateAudioStreamingRunning>
common_audiostate_audiostreamingrunning_ptr;
boost::shared_ptr<cb::CommonHeadlightsStateintensityChanged>
common_headlightsstate_intensitychanged_ptr;
boost::shared_ptr<cb::CommonAnimationsStateList>
common_animationsstate_list_ptr;
boost::shared_ptr<cb::CommonAccessoryStateSupportedAccessoriesListChanged>
common_accessorystate_supportedaccessorieslistchanged_ptr;
boost::shared_ptr<cb::CommonAccessoryStateAccessoryConfigChanged>
common_accessorystate_accessoryconfigchanged_ptr;
boost::shared_ptr<cb::CommonAccessoryStateAccessoryConfigModificationEnabled>
common_accessorystate_accessoryconfigmodificationenabled_ptr;
boost::shared_ptr<cb::CommonChargerStateMaxChargeRateChanged>
common_chargerstate_maxchargeratechanged_ptr;
boost::shared_ptr<cb::CommonChargerStateCurrentChargeStateChanged>
common_chargerstate_currentchargestatechanged_ptr;
boost::shared_ptr<cb::CommonChargerStateLastChargeRateChanged>
common_chargerstate_lastchargeratechanged_ptr;
boost::shared_ptr<cb::CommonChargerStateChargingInfo>
common_chargerstate_charginginfo_ptr;
boost::shared_ptr<cb::CommonRunStateRunIdChanged>
common_runstate_runidchanged_ptr;
#endif // DEFINE_SHARED_PTRS
#ifdef UPDTAE_CALLBACK_MAP
// Instantiate state callback wrappers
common_commonstate_allstateschanged_ptr.reset(
new cb::CommonCommonStateAllStatesChanged(
nh, priv_nh, "states/common/CommonState/AllStatesChanged"));
common_commonstate_batterystatechanged_ptr.reset(
new cb::CommonCommonStateBatteryStateChanged(
nh, priv_nh, "states/common/CommonState/BatteryStateChanged"));
common_commonstate_massstoragestatelistchanged_ptr.reset(
new cb::CommonCommonStateMassStorageStateListChanged(
nh, priv_nh, "states/common/CommonState/MassStorageStateListChanged"));
common_commonstate_massstorageinfostatelistchanged_ptr.reset(
new cb::CommonCommonStateMassStorageInfoStateListChanged(
nh, priv_nh, "states/common/CommonState/MassStorageInfoStateListChanged"));
common_commonstate_currentdatechanged_ptr.reset(
new cb::CommonCommonStateCurrentDateChanged(
nh, priv_nh, "states/common/CommonState/CurrentDateChanged"));
common_commonstate_currenttimechanged_ptr.reset(
new cb::CommonCommonStateCurrentTimeChanged(
nh, priv_nh, "states/common/CommonState/CurrentTimeChanged"));
common_commonstate_massstorageinforemaininglistchanged_ptr.reset(
new cb::CommonCommonStateMassStorageInfoRemainingListChanged(
nh, priv_nh, "states/common/CommonState/MassStorageInfoRemainingListChanged"));
common_commonstate_wifisignalchanged_ptr.reset(
new cb::CommonCommonStateWifiSignalChanged(
nh, priv_nh, "states/common/CommonState/WifiSignalChanged"));
common_commonstate_sensorsstateslistchanged_ptr.reset(
new cb::CommonCommonStateSensorsStatesListChanged(
nh, priv_nh, "states/common/CommonState/SensorsStatesListChanged"));
common_commonstate_productmodel_ptr.reset(
new cb::CommonCommonStateProductModel(
nh, priv_nh, "states/common/CommonState/ProductModel"));
common_commonstate_countrylistknown_ptr.reset(
new cb::CommonCommonStateCountryListKnown(
nh, priv_nh, "states/common/CommonState/CountryListKnown"));
common_overheatstate_overheatchanged_ptr.reset(
new cb::CommonOverHeatStateOverHeatChanged(
nh, priv_nh, "states/common/OverHeatState/OverHeatChanged"));
common_overheatstate_overheatregulationchanged_ptr.reset(
new cb::CommonOverHeatStateOverHeatRegulationChanged(
nh, priv_nh, "states/common/OverHeatState/OverHeatRegulationChanged"));
common_mavlinkstate_mavlinkfileplayingstatechanged_ptr.reset(
new cb::CommonMavlinkStateMavlinkFilePlayingStateChanged(
nh, priv_nh, "states/common/MavlinkState/MavlinkFilePlayingStateChanged"));
common_mavlinkstate_mavlinkplayerrorstatechanged_ptr.reset(
new cb::CommonMavlinkStateMavlinkPlayErrorStateChanged(
nh, priv_nh, "states/common/MavlinkState/MavlinkPlayErrorStateChanged"));
common_calibrationstate_magnetocalibrationstatechanged_ptr.reset(
new cb::CommonCalibrationStateMagnetoCalibrationStateChanged(
nh, priv_nh, "states/common/CalibrationState/MagnetoCalibrationStateChanged"));
common_calibrationstate_magnetocalibrationrequiredstate_ptr.reset(
new cb::CommonCalibrationStateMagnetoCalibrationRequiredState(
nh, priv_nh, "states/common/CalibrationState/MagnetoCalibrationRequiredState"));
common_calibrationstate_magnetocalibrationaxistocalibratechanged_ptr.reset(
new cb::CommonCalibrationStateMagnetoCalibrationAxisToCalibrateChanged(
nh, priv_nh, "states/common/CalibrationState/MagnetoCalibrationAxisToCalibrateChanged"));
common_calibrationstate_magnetocalibrationstartedchanged_ptr.reset(
new cb::CommonCalibrationStateMagnetoCalibrationStartedChanged(
nh, priv_nh, "states/common/CalibrationState/MagnetoCalibrationStartedChanged"));
common_flightplanstate_availabilitystatechanged_ptr.reset(
new cb::CommonFlightPlanStateAvailabilityStateChanged(
nh, priv_nh, "states/common/FlightPlanState/AvailabilityStateChanged"));
common_flightplanstate_componentstatelistchanged_ptr.reset(
new cb::CommonFlightPlanStateComponentStateListChanged(
nh, priv_nh, "states/common/FlightPlanState/ComponentStateListChanged"));
common_arlibsversionsstate_controllerlibarcommandsversion_ptr.reset(
new cb::CommonARLibsVersionsStateControllerLibARCommandsVersion(
nh, priv_nh, "states/common/ARLibsVersionsState/ControllerLibARCommandsVersion"));
common_arlibsversionsstate_skycontrollerlibarcommandsversion_ptr.reset(
new cb::CommonARLibsVersionsStateSkyControllerLibARCommandsVersion(
nh, priv_nh, "states/common/ARLibsVersionsState/SkyControllerLibARCommandsVersion"));
common_arlibsversionsstate_devicelibarcommandsversion_ptr.reset(
new cb::CommonARLibsVersionsStateDeviceLibARCommandsVersion(
nh, priv_nh, "states/common/ARLibsVersionsState/DeviceLibARCommandsVersion"));
common_audiostate_audiostreamingrunning_ptr.reset(
new cb::CommonAudioStateAudioStreamingRunning(
nh, priv_nh, "states/common/AudioState/AudioStreamingRunning"));
common_headlightsstate_intensitychanged_ptr.reset(
new cb::CommonHeadlightsStateintensityChanged(
nh, priv_nh, "states/common/HeadlightsState/intensityChanged"));
common_animationsstate_list_ptr.reset(
new cb::CommonAnimationsStateList(
nh, priv_nh, "states/common/AnimationsState/List"));
common_accessorystate_supportedaccessorieslistchanged_ptr.reset(
new cb::CommonAccessoryStateSupportedAccessoriesListChanged(
nh, priv_nh, "states/common/AccessoryState/SupportedAccessoriesListChanged"));
common_accessorystate_accessoryconfigchanged_ptr.reset(
new cb::CommonAccessoryStateAccessoryConfigChanged(
nh, priv_nh, "states/common/AccessoryState/AccessoryConfigChanged"));
common_accessorystate_accessoryconfigmodificationenabled_ptr.reset(
new cb::CommonAccessoryStateAccessoryConfigModificationEnabled(
nh, priv_nh, "states/common/AccessoryState/AccessoryConfigModificationEnabled"));
common_chargerstate_maxchargeratechanged_ptr.reset(
new cb::CommonChargerStateMaxChargeRateChanged(
nh, priv_nh, "states/common/ChargerState/MaxChargeRateChanged"));
common_chargerstate_currentchargestatechanged_ptr.reset(
new cb::CommonChargerStateCurrentChargeStateChanged(
nh, priv_nh, "states/common/ChargerState/CurrentChargeStateChanged"));
common_chargerstate_lastchargeratechanged_ptr.reset(
new cb::CommonChargerStateLastChargeRateChanged(
nh, priv_nh, "states/common/ChargerState/LastChargeRateChanged"));
common_chargerstate_charginginfo_ptr.reset(
new cb::CommonChargerStateChargingInfo(
nh, priv_nh, "states/common/ChargerState/ChargingInfo"));
common_runstate_runidchanged_ptr.reset(
new cb::CommonRunStateRunIdChanged(
nh, priv_nh, "states/common/RunState/RunIdChanged"));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_allstateschanged_ptr->GetCommandKey(),
common_commonstate_allstateschanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_batterystatechanged_ptr->GetCommandKey(),
common_commonstate_batterystatechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_massstoragestatelistchanged_ptr->GetCommandKey(),
common_commonstate_massstoragestatelistchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_massstorageinfostatelistchanged_ptr->GetCommandKey(),
common_commonstate_massstorageinfostatelistchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_currentdatechanged_ptr->GetCommandKey(),
common_commonstate_currentdatechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_currenttimechanged_ptr->GetCommandKey(),
common_commonstate_currenttimechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_massstorageinforemaininglistchanged_ptr->GetCommandKey(),
common_commonstate_massstorageinforemaininglistchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_wifisignalchanged_ptr->GetCommandKey(),
common_commonstate_wifisignalchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_sensorsstateslistchanged_ptr->GetCommandKey(),
common_commonstate_sensorsstateslistchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_productmodel_ptr->GetCommandKey(),
common_commonstate_productmodel_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_commonstate_countrylistknown_ptr->GetCommandKey(),
common_commonstate_countrylistknown_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_overheatstate_overheatchanged_ptr->GetCommandKey(),
common_overheatstate_overheatchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_overheatstate_overheatregulationchanged_ptr->GetCommandKey(),
common_overheatstate_overheatregulationchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_mavlinkstate_mavlinkfileplayingstatechanged_ptr->GetCommandKey(),
common_mavlinkstate_mavlinkfileplayingstatechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_mavlinkstate_mavlinkplayerrorstatechanged_ptr->GetCommandKey(),
common_mavlinkstate_mavlinkplayerrorstatechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_calibrationstate_magnetocalibrationstatechanged_ptr->GetCommandKey(),
common_calibrationstate_magnetocalibrationstatechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_calibrationstate_magnetocalibrationrequiredstate_ptr->GetCommandKey(),
common_calibrationstate_magnetocalibrationrequiredstate_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_calibrationstate_magnetocalibrationaxistocalibratechanged_ptr->GetCommandKey(),
common_calibrationstate_magnetocalibrationaxistocalibratechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_calibrationstate_magnetocalibrationstartedchanged_ptr->GetCommandKey(),
common_calibrationstate_magnetocalibrationstartedchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_flightplanstate_availabilitystatechanged_ptr->GetCommandKey(),
common_flightplanstate_availabilitystatechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_flightplanstate_componentstatelistchanged_ptr->GetCommandKey(),
common_flightplanstate_componentstatelistchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_arlibsversionsstate_controllerlibarcommandsversion_ptr->GetCommandKey(),
common_arlibsversionsstate_controllerlibarcommandsversion_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_arlibsversionsstate_skycontrollerlibarcommandsversion_ptr->GetCommandKey(),
common_arlibsversionsstate_skycontrollerlibarcommandsversion_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_arlibsversionsstate_devicelibarcommandsversion_ptr->GetCommandKey(),
common_arlibsversionsstate_devicelibarcommandsversion_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_audiostate_audiostreamingrunning_ptr->GetCommandKey(),
common_audiostate_audiostreamingrunning_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_headlightsstate_intensitychanged_ptr->GetCommandKey(),
common_headlightsstate_intensitychanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_animationsstate_list_ptr->GetCommandKey(),
common_animationsstate_list_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_accessorystate_supportedaccessorieslistchanged_ptr->GetCommandKey(),
common_accessorystate_supportedaccessorieslistchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_accessorystate_accessoryconfigchanged_ptr->GetCommandKey(),
common_accessorystate_accessoryconfigchanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_accessorystate_accessoryconfigmodificationenabled_ptr->GetCommandKey(),
common_accessorystate_accessoryconfigmodificationenabled_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_chargerstate_maxchargeratechanged_ptr->GetCommandKey(),
common_chargerstate_maxchargeratechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_chargerstate_currentchargestatechanged_ptr->GetCommandKey(),
common_chargerstate_currentchargestatechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_chargerstate_lastchargeratechanged_ptr->GetCommandKey(),
common_chargerstate_lastchargeratechanged_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_chargerstate_charginginfo_ptr->GetCommandKey(),
common_chargerstate_charginginfo_ptr));
// Add all wrappers to the callback map
callback_map_.insert(std::pair<eARCONTROLLER_DICTIONARY_KEY, boost::shared_ptr<cb::AbstractCommand> >(
common_runstate_runidchanged_ptr->GetCommandKey(),
common_runstate_runidchanged_ptr));
#endif // UPDTAE_CALLBACK_MAP
| 64.64467 | 153 | 0.812721 |
d2ef83b1971b09a8fd98aa3b80807f5812185193 | 14,005 | c | C | contrib/gnu/gcc/dist/gcc/common/config/riscv/riscv-common.c | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | 3 | 2021-05-04T17:09:06.000Z | 2021-10-04T07:19:26.000Z | contrib/gnu/gcc/dist/gcc/common/config/riscv/riscv-common.c | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | contrib/gnu/gcc/dist/gcc/common/config/riscv/riscv-common.c | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | /* Common hooks for RISC-V.
Copyright (C) 2016-2020 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include <sstream>
#define INCLUDE_STRING
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "common/common-target.h"
#include "common/common-target-def.h"
#include "opts.h"
#include "flags.h"
#include "diagnostic-core.h"
#include "config/riscv/riscv-protos.h"
#define RISCV_DONT_CARE_VERSION -1
/* Subset info. */
struct riscv_subset_t
{
riscv_subset_t ();
std::string name;
int major_version;
int minor_version;
struct riscv_subset_t *next;
};
/* Subset list. */
class riscv_subset_list
{
private:
/* Original arch string. */
const char *m_arch;
/* Location of arch string, used for report error. */
location_t m_loc;
/* Head of subset info list. */
riscv_subset_t *m_head;
/* Tail of subset info list. */
riscv_subset_t *m_tail;
/* X-len of m_arch. */
unsigned m_xlen;
riscv_subset_list (const char *, location_t);
const char *parsing_subset_version (const char *, unsigned *, unsigned *,
unsigned, unsigned, bool);
const char *parse_std_ext (const char *);
const char *parse_sv_or_non_std_ext (const char *, const char *,
const char *);
public:
~riscv_subset_list ();
void add (const char *, int, int);
riscv_subset_t *lookup (const char *,
int major_version = RISCV_DONT_CARE_VERSION,
int minor_version = RISCV_DONT_CARE_VERSION) const;
std::string to_string () const;
unsigned xlen() const {return m_xlen;};
static riscv_subset_list *parse (const char *, location_t);
};
static const char *riscv_supported_std_ext (void);
static riscv_subset_list *current_subset_list = NULL;
riscv_subset_t::riscv_subset_t ()
: name (), major_version (0), minor_version (0), next (NULL)
{
}
riscv_subset_list::riscv_subset_list (const char *arch, location_t loc)
: m_arch (arch), m_loc (loc), m_head (NULL), m_tail (NULL), m_xlen (0)
{
}
riscv_subset_list::~riscv_subset_list ()
{
if (!m_head)
return;
riscv_subset_t *item = this->m_head;
while (item != NULL)
{
riscv_subset_t *next = item->next;
delete item;
item = next;
}
}
/* Add new subset to list. */
void
riscv_subset_list::add (const char *subset, int major_version,
int minor_version)
{
riscv_subset_t *s = new riscv_subset_t ();
if (m_head == NULL)
m_head = s;
s->name = subset;
s->major_version = major_version;
s->minor_version = minor_version;
s->next = NULL;
if (m_tail != NULL)
m_tail->next = s;
m_tail = s;
}
/* Convert subset info to string with explicit version info. */
std::string
riscv_subset_list::to_string () const
{
std::ostringstream oss;
oss << "rv" << m_xlen;
bool first = true;
riscv_subset_t *subset = m_head;
while (subset != NULL)
{
if (!first)
oss << '_';
first = false;
oss << subset->name
<< subset->major_version
<< 'p'
<< subset->minor_version;
subset = subset->next;
}
return oss.str ();
}
/* Find subset in list with version checking, return NULL if not found.
major/minor version checking can be ignored if major_version/minor_version
is RISCV_DONT_CARE_VERSION. */
riscv_subset_t *
riscv_subset_list::lookup (const char *subset, int major_version,
int minor_version) const
{
riscv_subset_t *s;
for (s = m_head; s != NULL; s = s->next)
if (strcasecmp (s->name.c_str (), subset) == 0)
{
if ((major_version != RISCV_DONT_CARE_VERSION)
&& (s->major_version != major_version))
return NULL;
if ((minor_version != RISCV_DONT_CARE_VERSION)
&& (s->minor_version != minor_version))
return NULL;
return s;
}
return s;
}
/* Return string which contains all supported standard extensions in
canonical order. */
static const char *
riscv_supported_std_ext (void)
{
return "mafdqlcbjtpvn";
}
/* Parsing subset version.
Return Value:
Points to the end of version
Arguments:
`p`: Current parsing position.
`major_version`: Parsing result of major version, using
default_major_version if version is not present in arch string.
`minor_version`: Parsing result of minor version, set to 0 if version is
not present in arch string, but set to `default_minor_version` if
`major_version` using default_major_version.
`default_major_version`: Default major version.
`default_minor_version`: Default minor version.
`std_ext_p`: True if parsing std extension. */
const char *
riscv_subset_list::parsing_subset_version (const char *p,
unsigned *major_version,
unsigned *minor_version,
unsigned default_major_version,
unsigned default_minor_version,
bool std_ext_p)
{
bool major_p = true;
unsigned version = 0;
unsigned major = 0;
unsigned minor = 0;
char np;
for (; *p; ++p)
{
if (*p == 'p')
{
np = *(p + 1);
if (!ISDIGIT (np))
{
/* Might be beginning of `p` extension. */
if (std_ext_p)
{
*major_version = version;
*minor_version = 0;
return p;
}
else
{
error_at (m_loc, "%<-march=%s%>: Expect number "
"after %<%dp%>.", m_arch, version);
return NULL;
}
}
major = version;
major_p = false;
version = 0;
}
else if (ISDIGIT (*p))
version = (version * 10) + (*p - '0');
else
break;
}
if (major_p)
major = version;
else
minor = version;
if (major == 0 && minor == 0)
{
/* We didn't find any version string, use default version. */
*major_version = default_major_version;
*minor_version = default_minor_version;
}
else
{
*major_version = major;
*minor_version = minor;
}
return p;
}
/* Parsing function for standard extensions.
Return Value:
Points to the end of extensions.
Arguments:
`p`: Current parsing position. */
const char *
riscv_subset_list::parse_std_ext (const char *p)
{
const char *all_std_exts = riscv_supported_std_ext ();
const char *std_exts = all_std_exts;
unsigned major_version = 0;
unsigned minor_version = 0;
char std_ext = '\0';
/* First letter must start with i, e or g. */
switch (*p)
{
case 'i':
p++;
p = parsing_subset_version (p, &major_version, &minor_version,
/* default_major_version= */ 2,
/* default_minor_version= */ 0,
/* std_ext_p= */ true);
add ("i", major_version, minor_version);
break;
case 'e':
p++;
p = parsing_subset_version (p, &major_version, &minor_version,
/* default_major_version= */ 1,
/* default_minor_version= */ 9,
/* std_ext_p= */ true);
add ("e", major_version, minor_version);
if (m_xlen > 32)
{
error_at (m_loc, "%<-march=%s%>: rv%de is not a valid base ISA",
m_arch, m_xlen);
return NULL;
}
break;
case 'g':
p++;
p = parsing_subset_version (p, &major_version, &minor_version,
/* default_major_version= */ 2,
/* default_minor_version= */ 0,
/* std_ext_p= */ true);
add ("i", major_version, minor_version);
for (; *std_exts != 'q'; std_exts++)
{
const char subset[] = {*std_exts, '\0'};
add (subset, major_version, minor_version);
}
break;
default:
error_at (m_loc, "%<-march=%s%>: first ISA subset must be %<e%>, "
"%<i%> or %<g%>", m_arch);
return NULL;
}
while (*p)
{
char subset[2] = {0, 0};
if (*p == 'x' || *p == 's')
break;
if (*p == '_')
{
p++;
continue;
}
std_ext = *p;
/* Checking canonical order. */
while (*std_exts && std_ext != *std_exts)
std_exts++;
if (std_ext != *std_exts)
{
if (strchr (all_std_exts, std_ext) == NULL)
error_at (m_loc, "%<-march=%s%>: unsupported ISA subset %<%c%>",
m_arch, *p);
else
error_at (m_loc,
"%<-march=%s%>: ISA string is not in canonical order. "
"%<%c%>", m_arch, *p);
return NULL;
}
std_exts++;
p++;
p = parsing_subset_version (p, &major_version, &minor_version,
/* default_major_version= */ 2,
/* default_minor_version= */ 0,
/* std_ext_p= */ true);
subset[0] = std_ext;
add (subset, major_version, minor_version);
}
return p;
}
/* Parsing function for non-standard and supervisor extensions.
Return Value:
Points to the end of extensions.
Arguments:
`p`: Current parsing position.
`ext_type`: What kind of extensions, 'x', 's' or 'sx'.
`ext_type_str`: Full name for kind of extension. */
const char *
riscv_subset_list::parse_sv_or_non_std_ext (const char *p,
const char *ext_type,
const char *ext_type_str)
{
unsigned major_version = 0;
unsigned minor_version = 0;
size_t ext_type_len = strlen (ext_type);
while (*p)
{
if (*p == '_')
{
p++;
continue;
}
if (strncmp (p, ext_type, ext_type_len) != 0)
break;
/* It's non-standard supervisor extension if it prefix with sx. */
if ((ext_type[0] == 's') && (ext_type_len == 1)
&& (*(p + 1) == 'x'))
break;
char *subset = xstrdup (p);
char *q = subset;
const char *end_of_version;
while (*++q != '\0' && *q != '_' && !ISDIGIT (*q))
;
end_of_version
= parsing_subset_version (q, &major_version, &minor_version,
/* default_major_version= */ 2,
/* default_minor_version= */ 0,
/* std_ext_p= */ FALSE);
*q = '\0';
add (subset, major_version, minor_version);
free (subset);
p += end_of_version - subset;
if (*p != '\0' && *p != '_')
{
error_at (m_loc, "%<-march=%s%>: %s must separate with _",
m_arch, ext_type_str);
return NULL;
}
}
return p;
}
/* Parsing arch string to subset list, return NULL if parsing failed. */
riscv_subset_list *
riscv_subset_list::parse (const char *arch, location_t loc)
{
riscv_subset_list *subset_list = new riscv_subset_list (arch, loc);
const char *p = arch;
if (strncmp (p, "rv32", 4) == 0)
{
subset_list->m_xlen = 32;
p += 4;
}
else if (strncmp (p, "rv64", 4) == 0)
{
subset_list->m_xlen = 64;
p += 4;
}
else
{
error_at (loc, "%<-march=%s%>: ISA string must begin with rv32 or rv64",
arch);
goto fail;
}
/* Parsing standard extension. */
p = subset_list->parse_std_ext (p);
if (p == NULL)
goto fail;
/* Parsing non-standard extension. */
p = subset_list->parse_sv_or_non_std_ext (p, "x", "non-standard extension");
if (p == NULL)
goto fail;
/* Parsing supervisor extension. */
p = subset_list->parse_sv_or_non_std_ext (p, "s", "supervisor extension");
if (p == NULL)
goto fail;
/* Parsing non-standard supervisor extension. */
p = subset_list->parse_sv_or_non_std_ext
(p, "sx", "non-standard supervisor extension");
if (p == NULL)
goto fail;
if (*p != '\0')
{
error_at (loc, "%<-march=%s%>: unexpected ISA string at end: %qs",
arch, p);
goto fail;
}
return subset_list;
fail:
delete subset_list;
return NULL;
}
/* Return the current arch string. */
std::string
riscv_arch_str ()
{
gcc_assert (current_subset_list);
return current_subset_list->to_string ();
}
/* Parse a RISC-V ISA string into an option mask. Must clear or set all arch
dependent mask bits, in case more than one -march string is passed. */
static void
riscv_parse_arch_string (const char *isa, int *flags, location_t loc)
{
riscv_subset_list *subset_list;
subset_list = riscv_subset_list::parse (isa, loc);
if (!subset_list)
return;
if (subset_list->xlen () == 32)
*flags &= ~MASK_64BIT;
else if (subset_list->xlen () == 64)
*flags |= MASK_64BIT;
*flags &= ~MASK_RVE;
if (subset_list->lookup ("e"))
*flags |= MASK_RVE;
*flags &= ~MASK_MUL;
if (subset_list->lookup ("m"))
*flags |= MASK_MUL;
*flags &= ~MASK_ATOMIC;
if (subset_list->lookup ("a"))
*flags |= MASK_ATOMIC;
*flags &= ~(MASK_HARD_FLOAT | MASK_DOUBLE_FLOAT);
if (subset_list->lookup ("f"))
*flags |= MASK_HARD_FLOAT;
if (subset_list->lookup ("d"))
*flags |= MASK_DOUBLE_FLOAT;
*flags &= ~MASK_RVC;
if (subset_list->lookup ("c"))
*flags |= MASK_RVC;
if (current_subset_list)
delete current_subset_list;
current_subset_list = subset_list;
}
/* Implement TARGET_HANDLE_OPTION. */
static bool
riscv_handle_option (struct gcc_options *opts,
struct gcc_options *opts_set ATTRIBUTE_UNUSED,
const struct cl_decoded_option *decoded,
location_t loc)
{
switch (decoded->opt_index)
{
case OPT_march_:
riscv_parse_arch_string (decoded->arg, &opts->x_target_flags, loc);
return true;
default:
return true;
}
}
/* Implement TARGET_OPTION_OPTIMIZATION_TABLE. */
static const struct default_options riscv_option_optimization_table[] =
{
{ OPT_LEVELS_1_PLUS, OPT_fsection_anchors, NULL, 1 },
{ OPT_LEVELS_2_PLUS, OPT_free, NULL, 1 },
{ OPT_LEVELS_NONE, 0, NULL, 0 }
};
#undef TARGET_OPTION_OPTIMIZATION_TABLE
#define TARGET_OPTION_OPTIMIZATION_TABLE riscv_option_optimization_table
#undef TARGET_HANDLE_OPTION
#define TARGET_HANDLE_OPTION riscv_handle_option
struct gcc_targetm_common targetm_common = TARGETM_COMMON_INITIALIZER;
| 22.661812 | 78 | 0.634416 |
304248ccea1b20b801de28825b18c3376683ebff | 414 | h | C | PES_Project_6/source/util.h | Taylorjtt/PES-Project-6 | 3bf1e1f8737976b6bda8a7184752cb058c1a7e37 | [
"MIT"
] | null | null | null | PES_Project_6/source/util.h | Taylorjtt/PES-Project-6 | 3bf1e1f8737976b6bda8a7184752cb058c1a7e37 | [
"MIT"
] | null | null | null | PES_Project_6/source/util.h | Taylorjtt/PES-Project-6 | 3bf1e1f8737976b6bda8a7184752cb058c1a7e37 | [
"MIT"
] | null | null | null | /*
* util.h
*
* Created on: Nov 1, 2019
* Author: john
*/
#ifndef UTIL_H_
#define UTIL_H_
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define EnableInterrupts asm(" CPSIE i");
#define DisableInterrupts asm(" CPSID i");
#define START_CRITICAL DisableInterrupts
#define END_CRITICAL EnableInterrupts
extern uint32_t usecs;
void delayMilliseconds(uint32_t delay);
#endif /* UTIL_H_ */
| 16.56 | 42 | 0.719807 |
d03a64752e69226f1c8dc662a126f0d38b3b0573 | 367 | h | C | src/TextureManager.h | thamstras/GamesProgramming | b576760cd12c1a13347bc488a2eb3d5a141abac1 | [
"MIT"
] | null | null | null | src/TextureManager.h | thamstras/GamesProgramming | b576760cd12c1a13347bc488a2eb3d5a141abac1 | [
"MIT"
] | null | null | null | src/TextureManager.h | thamstras/GamesProgramming | b576760cd12c1a13347bc488a2eb3d5a141abac1 | [
"MIT"
] | null | null | null | #pragma once
#include "CommonIncludes.h"
#include <map>
#include <exception>
#include "SDL_image.h"
class TextureManager
{
public:
TextureManager();
~TextureManager();
void initTextures();
void loadTextureList(SDL_Renderer * ren);
void cleanup();
SDL_Texture * getTexture(std::string name);
private:
std::map<std::string, SDL_Texture *> textureMap;
};
| 14.115385 | 49 | 0.724796 |
652e9fd8f48ed02e89c292ca15423652df2f525b | 1,028 | h | C | PrivateFrameworks/ClassroomKit/CRKIdentitySharingOperation.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/ClassroomKit/CRKIdentitySharingOperation.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/ClassroomKit/CRKIdentitySharingOperation.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "CATOperation.h"
@class IDSService, NSDictionary, NSObject<CRKIdentitySharingOperationDelegate>, NSSet;
@interface CRKIdentitySharingOperation : CATOperation
{
NSObject<CRKIdentitySharingOperationDelegate> *_delegate;
IDSService *_service;
NSDictionary *_message;
NSSet *_destinations;
}
@property(readonly, nonatomic) NSSet *destinations; // @synthesize destinations=_destinations;
@property(copy, nonatomic) NSDictionary *message; // @synthesize message=_message;
@property(readonly, nonatomic) IDSService *service; // @synthesize service=_service;
@property(nonatomic) __weak NSObject<CRKIdentitySharingOperationDelegate> *delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct;
- (void)main;
- (BOOL)isAsynchronous;
- (void)didSendWithSuccess:(BOOL)arg1 error:(id)arg2;
- (id)initWithService:(id)arg1 message:(id)arg2 recipients:(id)arg3;
@end
| 33.16129 | 119 | 0.761673 |
6570291505986178cad664750f2c1e1c93771b40 | 7,610 | c | C | uni_log.c | junlon2006/wav_pcm_parse_tools | 0bc080057bdff5ddffea1443b052647eac7f943a | [
"Apache-2.0"
] | 2 | 2020-08-31T06:30:51.000Z | 2020-09-07T09:51:40.000Z | logger/src/uni_log.c | junlon2006/wheels | 05232e05b83dbcd44ea477df4ad0666f0e08959c | [
"Apache-2.0"
] | 7 | 2019-11-13T10:02:25.000Z | 2019-12-10T12:43:53.000Z | logger/src/uni_log.c | junlon2006/wheels | 05232e05b83dbcd44ea477df4ad0666f0e08959c | [
"Apache-2.0"
] | 4 | 2019-11-13T02:34:10.000Z | 2021-12-23T06:24:40.000Z | /**************************************************************************
* Copyright (C) 2018-2019 Junlon2006
*
* 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
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**************************************************************************
*
* Description : uni_log.c
* Author : junlon2006@163.com
* Date : 2019.03.17
*
**************************************************************************/
#include "uni_log.h"
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <sys/time.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdlib.h>
#include <inttypes.h>
#include <unistd.h>
#define LOG_BUFFER_LEN (1024)
#define LOG_FILE_NAME "app.log"
#define uni_min(x,y) ({ \
typeof(x) _x = (x); \
typeof(y) _y = (y); \
(void)(&_x == &_y); \
_x < _y ? _x : _y;})
#define uni_max(x,y) ({ \
typeof(x) _x = (x); \
typeof(y) _y = (y); \
(void)(&_x == &_y); \
_x > _y ? _x : _y;})
typedef struct {
int fd;
pthread_mutex_t mutex;
} LogFile;
static LogConfig g_log_config = {1, 1, 1, 1, 0, N_LOG_ALL};
static LogFile g_log_file;
static const char* _level_tostring(LogLevel level) {
switch (level) {
case N_LOG_ERROR: return g_log_config.enable_color ?
"\033[0m\033[41;33m[E]\033[0m" : "[E]";
case N_LOG_DEBUG: return g_log_config.enable_color ?
"\033[0m\033[47;33m[D]\033[0m" : "[D]";
case N_LOG_TRACK: return g_log_config.enable_color ?
"\033[0m\033[42;33m[T]\033[0m" : "[T]";
case N_LOG_WARN: return g_log_config.enable_color ?
"\033[0m\033[41;33m[W]\033[0m" : "[W]";
default: return "[N/A]";
}
}
static void _get_now_str(char *buf, int len) {
struct timeval tv;
time_t s;
struct tm local;
gettimeofday(&tv, NULL);
s = tv.tv_sec;
localtime_r(&s, &local);
snprintf(buf, len, "%02d:%02d:%02d.%06"PRId64" ", local.tm_hour,
local.tm_min, local.tm_sec, (int64_t)tv.tv_usec);
}
static void _get_thread_id_str(char *buf, int len) {
pthread_t thread_id = pthread_self();
snprintf(buf, len, "%x", (unsigned int)thread_id);
}
static int _fill_log_level(LogLevel level, char *buf, int len) {
int write_len = 0;
switch (level) {
case N_LOG_DEBUG:
write_len = snprintf(buf, len, "%s ", _level_tostring(N_LOG_DEBUG));
break;
case N_LOG_TRACK:
write_len = snprintf(buf, len, "%s ", _level_tostring(N_LOG_TRACK));
break;
case N_LOG_WARN:
write_len = snprintf(buf, len, "%s ", _level_tostring(N_LOG_WARN));
break;
case N_LOG_ERROR:
write_len = snprintf(buf, len, "%s ", _level_tostring(N_LOG_ERROR));
break;
default:
break;
}
return uni_max(0, write_len);
}
static int _fill_tag(char *buf, int len, const char *tag) {
return uni_max(0, snprintf(buf, len, "<%s>", tag));
}
static int _fill_time(char *buf, int len) {
char now[64];
if (!g_log_config.enable_time) {
return 0;
}
_get_now_str(now, sizeof(now));
return uni_max(0, snprintf(buf, len, "%s", now));
}
static int _fill_function_line(char *buf, int len, const char *function,
int line) {
return (g_log_config.enable_function_line ?
uni_max(0, snprintf(buf, len, "%s:%d->", function, line)) : 0);
}
static int _fill_thread_id(char *buf, int len) {
char thread_id[32];
if (!g_log_config.enable_thread_id) {
return 0;
}
_get_thread_id_str(thread_id, sizeof(thread_id));
return uni_max(0, snprintf(buf, len, "%s", thread_id));
}
static void _fill_customer_info(char *buf, int len, char *fmt, va_list args,
int append_feed_line) {
int length, remain_len;
length = vsnprintf(buf, len, fmt, args);
length = uni_max(length, 0);
length = uni_min(length, len);
remain_len = len - length;
if (0 == remain_len) {
if (append_feed_line) {
buf[len - 2] = '\n';
}
buf[len - 1] = '\0';
return;
}
if (1 == remain_len) {
if (append_feed_line) {
buf[len - 2] = '\n';
}
return;
}
if (append_feed_line) {
strncat(buf, "\n", remain_len);
}
return;
}
static void _save_log_2_file(char *buf, int len) {
if (0 < g_log_file.fd && 0 < len) {
pthread_mutex_lock(&g_log_file.mutex);
write(g_log_file.fd, buf, len);
pthread_mutex_unlock(&g_log_file.mutex);
}
}
int LogLevelValid(LogLevel level) {
return level <= g_log_config.set_level ? 1 : 0;
}
#define _log_assemble(buf, level, tags, function, line, fmt, args) do { \
int len = 0; \
if (level != N_LOG_RAW) { \
len += _fill_log_level(level, buf + len, LOG_BUFFER_LEN - len); \
len += _fill_time(buf + len, LOG_BUFFER_LEN - len); \
len += _fill_thread_id(buf + len, LOG_BUFFER_LEN - len); \
len += _fill_tag(buf + len, LOG_BUFFER_LEN - len, tags); \
len += _fill_function_line(buf + len, LOG_BUFFER_LEN - len, \
function, line); \
} \
_fill_customer_info(buf + len, LOG_BUFFER_LEN - len, fmt, args, \
level != N_LOG_RAW); \
} while (0)
static int _sync_write_process(LogLevel level, const char *tags,
const char *function, int line,
char *fmt, va_list args) {
char buf[LOG_BUFFER_LEN];
_log_assemble(buf, level, tags, function, line, fmt, args);
printf("%s", buf);
_save_log_2_file(buf, strlen(buf) + 1);
return 0;
}
int LogWrite(LogLevel level, const char *tags, const char *function, int line,
char *fmt, ...) {
va_list args;
va_start(args, fmt);
_sync_write_process(level, tags, function, line, fmt, args);
va_end(args);
return 0;
}
static void _destroy_all() {
if (g_log_config.enable_file) {
pthread_mutex_destroy(&g_log_file.mutex);
}
}
int LogLevelSet(LogLevel level) {
g_log_config.set_level = level;
return 0;
}
static void _open_save_fd() {
g_log_file.fd = open(LOG_FILE_NAME, O_WRONLY | O_CREAT, 0664);
if (g_log_file.fd <= 0) {
printf("%s%d: open save fd[%d] failed.\n", __FUNCTION__, __LINE__,
g_log_file.fd);
}
}
int LogInitialize(LogConfig logConfig) {
g_log_config.enable_time = logConfig.enable_time;
g_log_config.enable_thread_id = logConfig.enable_thread_id;
g_log_config.enable_function_line = logConfig.enable_function_line;
g_log_config.enable_color = logConfig.enable_color;
g_log_config.enable_file = logConfig.enable_file;
g_log_config.set_level = logConfig.set_level;
if (g_log_config.enable_file) {
pthread_mutex_init(&g_log_file.mutex, NULL);
_open_save_fd();
}
return 0;
}
int LogFinalize(void) {
_destroy_all();
return 0;
}
| 31.188525 | 78 | 0.596321 |
a9e63b855d99d0e6d521ae9fbb50c81ac2a3032b | 1,049 | h | C | deps/cinder/include/boost/predef/os/irix.h | multi-os-engine/cinder-natj-binding | 969b66fdd49e4ca63442baf61ce90ae385ab8178 | [
"Apache-2.0"
] | 978 | 2015-03-25T04:30:43.000Z | 2022-03-18T22:47:35.000Z | src/third_party/boost-1.56.0/boost/predef/os/irix.h | wujf/mongo | f2f48b749ded0c5585c798c302f6162f19336670 | [
"Apache-2.0"
] | 194 | 2015-01-10T15:45:46.000Z | 2022-03-20T08:02:27.000Z | src/third_party/boost-1.56.0/boost/predef/os/irix.h | wujf/mongo | f2f48b749ded0c5585c798c302f6162f19336670 | [
"Apache-2.0"
] | 412 | 2015-01-14T07:31:04.000Z | 2022-03-31T08:41:41.000Z | /*
Copyright Rene Rivera 2008-2013
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 BOOST_PREDEF_OS_IRIX_H
#define BOOST_PREDEF_OS_IRIX_H
#include <boost/predef/version_number.h>
#include <boost/predef/make.h>
/*`
[heading `BOOST_OS_IRIX`]
[@http://en.wikipedia.org/wiki/Irix IRIX] operating system.
[table
[[__predef_symbol__] [__predef_version__]]
[[`sgi`] [__predef_detection__]]
[[`__sgi`] [__predef_detection__]]
]
*/
#define BOOST_OS_IRIX BOOST_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BOOST_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(sgi) || defined(__sgi) \
)
# undef BOOST_OS_IRIX
# define BOOST_OS_IRIX BOOST_VERSION_NUMBER_AVAILABLE
#endif
#if BOOST_OS_IRIX
# define BOOST_OS_IRIX_AVAILABLE
# include <boost/predef/detail/os_detected.h>
#endif
#define BOOST_OS_IRIX_NAME "IRIX"
#include <boost/predef/detail/test.h>
BOOST_PREDEF_DECLARE_TEST(BOOST_OS_IRIX,BOOST_OS_IRIX_NAME)
#endif
| 21.854167 | 59 | 0.762631 |
aa1ea77d8820772f9fdd4b506bd6b9a665b47dde | 3,470 | c | C | util/util.c | andrewchambers/mc | 56fbadf5e329f00c9c8058e2dfe2350a8cafa850 | [
"MIT"
] | null | null | null | util/util.c | andrewchambers/mc | 56fbadf5e329f00c9c8058e2dfe2350a8cafa850 | [
"MIT"
] | null | null | null | util/util.c | andrewchambers/mc | 56fbadf5e329f00c9c8058e2dfe2350a8cafa850 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <stdarg.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "util.h"
/* Some systems don't have strndup. */
char *strdupn(char *s, size_t len)
{
char *ret;
ret = xalloc(len + 1);
memcpy(ret, s, len);
ret[len] = '\0';
return ret;
}
char *strjoin(char *u, char *v)
{
size_t n;
char *s;
n = strlen(u) + strlen(v) + 1;
s = xalloc(n);
bprintf(s, n + 1, "%s%s", u, v);
return s;
}
char *swapsuffix(char *buf, size_t sz, char *s, char *suf, char *swap)
{
size_t slen, suflen, swaplen;
slen = strlen(s);
suflen = strlen(suf);
swaplen = strlen(swap);
if (slen < suflen)
return NULL;
if (slen + swaplen >= sz)
die("swapsuffix: buf too small");
buf[0] = '\0';
/* if we have matching suffixes */
if (suflen < slen && !strcmp(suf, &s[slen - suflen])) {
strncat(buf, s, slen - suflen);
strncat(buf, swap, swaplen);
} else {
bprintf(buf, sz, "%s%s", s, swap);
}
return buf;
}
size_t max(size_t a, size_t b)
{
if (a > b)
return a;
else
return b;
}
size_t min(size_t a, size_t b)
{
if (a < b)
return a;
else
return b;
}
size_t align(size_t sz, size_t a)
{
/* align to 0 just returns sz */
if (a == 0)
return sz;
return (sz + a - 1) & ~(a - 1);
}
void indentf(int depth, char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfindentf(stdout, depth, fmt, ap);
va_end(ap);
}
void findentf(FILE *fd, int depth, char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfindentf(fd, depth, fmt, ap);
va_end(ap);
}
void vfindentf(FILE *fd, int depth, char *fmt, va_list ap)
{
ssize_t i;
for (i = 0; i < depth; i++)
fprintf(fd, "\t");
vfprintf(fd, fmt, ap);
}
static int optinfo(Optctx *ctx, char arg, int *take, int *mand)
{
char *s;
for (s = ctx->optstr; *s != '\0'; s++) {
if (*s == arg) {
s++;
if (*s == ':') {
*take = 1;
*mand = 1;
return 1;
} else if (*s == '?') {
*take = 1;
*mand = 0;
return 1;
} else {
*take = 0;
*mand = 0;
return 1;
}
}
}
return 0;
}
static int findnextopt(Optctx *ctx)
{
size_t i;
for (i = ctx->argidx + 1; i < ctx->noptargs; i++) {
if (ctx->optargs[i][0] == '-')
goto foundopt;
else
lappend(&ctx->args, &ctx->nargs, ctx->optargs[i]);
}
ctx->finished = 1;
return 0;
foundopt:
ctx->argidx = i;
ctx->curarg = ctx->optargs[i] + 1; /* skip initial '-' */
return 1;
}
void optinit(Optctx *ctx, char *optstr, char **optargs, size_t noptargs)
{
ctx->args = NULL;
ctx->nargs = 0;
ctx->optstr = optstr;
ctx->optargs = optargs;
ctx->noptargs = noptargs;
ctx->optdone = 0;
ctx->finished = 0;
ctx->argidx = 0;
ctx->curarg = "";
findnextopt(ctx);
}
int optnext(Optctx *ctx)
{
int take, mand;
int c;
c = *ctx->curarg;
ctx->curarg++;
if (!optinfo(ctx, c, &take, &mand)) {
printf("Unexpected argument %c\n", *ctx->curarg);
exit(1);
}
ctx->optarg = NULL;
if (take) {
if (*ctx->curarg) {
ctx->optarg = ctx->curarg;
ctx->curarg += strlen(ctx->optarg);
} else if (ctx->argidx < ctx->noptargs - 1) {
ctx->optarg = ctx->optargs[ctx->argidx + 1];
ctx->argidx++;
} else if (mand) {
fprintf(stderr, "expected argument for %c\n", *ctx->curarg);
}
findnextopt(ctx);
} else {
if (*ctx->curarg == '\0')
findnextopt(ctx);
}
return c;
}
int optdone(Optctx *ctx) { return *ctx->curarg == '\0' && ctx->finished; }
| 17.178218 | 74 | 0.576945 |
4e11b619e3879b63621aaab070b2eb7155346557 | 252 | h | C | Module/ViewController/TestViewController.h | KayDing/Module | 894fa1ff6c7b3e22662d7b9df2c2ab817f04f5c2 | [
"MIT"
] | null | null | null | Module/ViewController/TestViewController.h | KayDing/Module | 894fa1ff6c7b3e22662d7b9df2c2ab817f04f5c2 | [
"MIT"
] | null | null | null | Module/ViewController/TestViewController.h | KayDing/Module | 894fa1ff6c7b3e22662d7b9df2c2ab817f04f5c2 | [
"MIT"
] | null | null | null | //
// TestViewController.h
// MGJRouter
//
// Created by 丁磊 on 2020/7/27.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface TestViewController : UIViewController
@property (nonatomic, copy) NSString *text;
@end
NS_ASSUME_NONNULL_END
| 14.823529 | 48 | 0.746032 |
bd3d609b47421dcf3ac939af857d222a5a8ed4f0 | 12,378 | h | C | dep/include/yse/JuceLibraryCode/extras/Introjucer/Source/ComponentEditor/paintelements/jucer_FillType.h | ChrSacher/MyEngine | 8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8 | [
"Apache-2.0"
] | 2 | 2015-10-27T21:36:59.000Z | 2017-03-17T21:52:19.000Z | dep/include/yse/JuceLibraryCode/extras/Introjucer/Source/ComponentEditor/paintelements/jucer_FillType.h | ChrSacher/MyEngine | 8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8 | [
"Apache-2.0"
] | null | null | null | dep/include/yse/JuceLibraryCode/extras/Introjucer/Source/ComponentEditor/paintelements/jucer_FillType.h | ChrSacher/MyEngine | 8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8 | [
"Apache-2.0"
] | null | null | null | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCER_FILLTYPE_H_INCLUDED
#define JUCER_FILLTYPE_H_INCLUDED
#include "../jucer_JucerDocument.h"
#include "../jucer_UtilityFunctions.h"
#include "../../Project Saving/jucer_ResourceFile.h"
//==============================================================================
class JucerFillType
{
public:
JucerFillType()
{
reset();
}
JucerFillType (const JucerFillType& other)
{
image = Image();
mode = other.mode;
colour = other.colour;
gradCol1 = other.gradCol1;
gradCol2 = other.gradCol2;
gradPos1 = other.gradPos1;
gradPos2 = other.gradPos2;
imageResourceName = other.imageResourceName;
imageOpacity = other.imageOpacity;
imageAnchor = other.imageAnchor;
}
JucerFillType& operator= (const JucerFillType& other)
{
image = Image();
mode = other.mode;
colour = other.colour;
gradCol1 = other.gradCol1;
gradCol2 = other.gradCol2;
gradPos1 = other.gradPos1;
gradPos2 = other.gradPos2;
imageResourceName = other.imageResourceName;
imageOpacity = other.imageOpacity;
imageAnchor = other.imageAnchor;
return *this;
}
bool operator== (const JucerFillType& other) const
{
return mode == other.mode
&& colour == other.colour
&& gradCol1 == other.gradCol1
&& gradCol2 == other.gradCol2
&& gradPos1 == other.gradPos1
&& gradPos2 == other.gradPos2
&& imageResourceName == other.imageResourceName
&& imageOpacity == other.imageOpacity
&& imageAnchor == other.imageAnchor;
}
bool operator!= (const JucerFillType& other) const
{
return ! operator== (other);
}
//==============================================================================
void setFillType (Graphics& g, JucerDocument* const document, const Rectangle<int>& parentArea)
{
if (mode == solidColour)
{
image = Image();
g.setColour (colour);
}
else if (mode == imageBrush)
{
jassert (document != nullptr);
loadImage (document);
Rectangle<int> r (imageAnchor.getRectangle (parentArea, document->getComponentLayout()));
g.setTiledImageFill (image, r.getX(), r.getY(), (float) imageOpacity);
}
else
{
image = Image();
Rectangle<int> r1 (gradPos1.getRectangle (parentArea, document->getComponentLayout()));
Rectangle<int> r2 (gradPos2.getRectangle (parentArea, document->getComponentLayout()));
g.setGradientFill (ColourGradient (gradCol1, (float) r1.getX(), (float) r1.getY(),
gradCol2, (float) r2.getX(), (float) r2.getY(),
mode == radialGradient));
}
}
void fillInGeneratedCode (GeneratedCode& code, String& paintMethodCode) const
{
String s;
switch (mode)
{
case solidColour:
s << "g.setColour (" << CodeHelpers::colourToCode (colour) << ");\n";
break;
case linearGradient:
case radialGradient:
{
String x1, y1, w, h, x2, y2;
positionToCode (gradPos1, code.document->getComponentLayout(), x1, y1, w, h);
positionToCode (gradPos2, code.document->getComponentLayout(), x2, y2, w, h);
s << "g.setGradientFill (ColourGradient (";
const String indent (String::repeatedString (" ", s.length()));
s << CodeHelpers::colourToCode (gradCol1) << ",\n"
<< indent << castToFloat (x1) << ", " << castToFloat (y1) << ",\n"
<< indent << CodeHelpers::colourToCode (gradCol2) << ",\n"
<< indent << castToFloat (x2) << ", " << castToFloat (y2) << ",\n"
<< indent << CodeHelpers::boolLiteral (mode == radialGradient) << "));\n";
break;
}
case imageBrush:
{
const String imageVariable ("cachedImage_" + imageResourceName.replace ("::", "_") + "_" + String (code.getUniqueSuffix()));
code.addImageResourceLoader (imageVariable, imageResourceName);
String x, y, w, h;
positionToCode (imageAnchor, code.document->getComponentLayout(), x, y, w, h);
s << "g.setTiledImageFill (";
const String indent (String::repeatedString (" ", s.length()));
s << imageVariable << ",\n"
<< indent << x << ", " << y << ",\n"
<< indent << CodeHelpers::floatLiteral (imageOpacity, 4) << ");\n";
break;
}
default:
jassertfalse;
break;
}
paintMethodCode += s;
}
String toString() const
{
switch (mode)
{
case solidColour:
return "solid: " + colour.toString();
case linearGradient:
case radialGradient:
return (mode == linearGradient ? "linear: "
: " radial: ")
+ gradPos1.toString()
+ ", "
+ gradPos2.toString()
+ ", 0=" + gradCol1.toString()
+ ", 1=" + gradCol2.toString();
case imageBrush:
return "image: " + imageResourceName.replaceCharacter (':', '#')
+ ", "
+ String (imageOpacity)
+ ", "
+ imageAnchor.toString();
default:
jassertfalse;
break;
}
return String::empty;
}
void restoreFromString (const String& s)
{
reset();
if (s.isNotEmpty())
{
StringArray toks;
toks.addTokens (s, ",:", StringRef());
toks.trim();
if (toks[0] == "solid")
{
mode = solidColour;
colour = Colour::fromString (toks[1]);
}
else if (toks[0] == "linear"
|| toks[0] == "radial")
{
mode = (toks[0] == "linear") ? linearGradient : radialGradient;
gradPos1 = RelativePositionedRectangle();
gradPos1.rect = PositionedRectangle (toks[1]);
gradPos2 = RelativePositionedRectangle();
gradPos2.rect = PositionedRectangle (toks[2]);
gradCol1 = Colour::fromString (toks[3].fromFirstOccurrenceOf ("=", false, false));
gradCol2 = Colour::fromString (toks[4].fromFirstOccurrenceOf ("=", false, false));
}
else if (toks[0] == "image")
{
mode = imageBrush;
imageResourceName = toks[1].replaceCharacter ('#', ':');
imageOpacity = toks[2].getDoubleValue();
imageAnchor= RelativePositionedRectangle();
imageAnchor.rect = PositionedRectangle (toks[3]);
}
else
{
jassertfalse;
}
}
}
bool isOpaque() const
{
switch (mode)
{
case solidColour:
return colour.isOpaque();
case linearGradient:
case radialGradient:
return gradCol1.isOpaque() && gradCol1.isOpaque();
case imageBrush:
return image.isValid()
&& imageOpacity >= 1.0f
&& ! image.hasAlphaChannel();
default:
jassertfalse;
break;
}
return false;
}
bool isInvisible() const
{
switch (mode)
{
case solidColour:
return colour.isTransparent();
case linearGradient:
case radialGradient:
return gradCol1.isTransparent() && gradCol2.isTransparent();
case imageBrush:
return imageOpacity == 0;
default:
jassertfalse;
break;
}
return false;
}
//==============================================================================
enum FillMode
{
solidColour,
linearGradient,
radialGradient,
imageBrush
};
FillMode mode;
Colour colour, gradCol1, gradCol2;
// just the x, y, of these are used
RelativePositionedRectangle gradPos1, gradPos2;
String imageResourceName;
double imageOpacity;
RelativePositionedRectangle imageAnchor;
//==============================================================================
private:
Image image;
void reset()
{
image = Image();
mode = solidColour;
colour = Colours::brown.withHue (Random::getSystemRandom().nextFloat());
gradCol1 = Colours::red;
gradCol2 = Colours::green;
gradPos1 = RelativePositionedRectangle();
gradPos1.rect = PositionedRectangle ("50 50");
gradPos2 = RelativePositionedRectangle();
gradPos2.rect = PositionedRectangle ("100 100");
imageResourceName.clear();
imageOpacity = 1.0;
imageAnchor = RelativePositionedRectangle();
imageAnchor.rect = PositionedRectangle ("0 0");
}
void loadImage (JucerDocument* const document)
{
if (image.isNull())
{
if (document != nullptr)
{
if (imageResourceName.contains ("::"))
{
if (Project* project = document->getCppDocument().getProject())
{
ResourceFile resourceFile (*project);
for (int i = 0; i < resourceFile.getNumFiles(); ++i)
{
const File& file = resourceFile.getFile(i);
if (imageResourceName == resourceFile.getClassName() + "::" + resourceFile.getDataVariableFor (file))
{
image = ImageCache::getFromFile (file);
break;
}
}
}
}
else
{
image = document->getResources().getImageFromCache (imageResourceName);
}
}
if (image.isNull())
{
const int hashCode = 0x3437856f;
image = ImageCache::getFromHashCode (hashCode);
if (image.isNull())
{
image = Image (Image::RGB, 100, 100, true);
Graphics g (image);
g.fillCheckerBoard (image.getBounds(),
image.getWidth() / 2, image.getHeight() / 2,
Colours::white, Colours::lightgrey);
g.setFont (12.0f);
g.setColour (Colours::grey);
g.drawText ("(image missing)", 0, 0, image.getWidth(), image.getHeight() / 2, Justification::centred, true);
ImageCache::addImageToCache (image, hashCode);
}
}
}
}
};
#endif // JUCER_FILLTYPE_H_INCLUDED
| 31.336709 | 140 | 0.485054 |
860e2de9d64184444c540a43485b5b0c82d2538f | 5,640 | h | C | hdi/dimensionality_reduction/knn_utils.h | alxvth/HDILibSlim | ac2c43ba40b5896d9124e07d907a6e9418c0f7f7 | [
"MIT"
] | null | null | null | hdi/dimensionality_reduction/knn_utils.h | alxvth/HDILibSlim | ac2c43ba40b5896d9124e07d907a6e9418c0f7f7 | [
"MIT"
] | null | null | null | hdi/dimensionality_reduction/knn_utils.h | alxvth/HDILibSlim | ac2c43ba40b5896d9124e07d907a6e9418c0f7f7 | [
"MIT"
] | null | null | null | /*
*
* Copyright (c) 2019, BIOVAULT (Leiden University Medical Center, Delft University of Technology)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Delft University of Technology.
* 4. Neither the name of the Delft University of Technology nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY BIOVAULT ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL NICOLA PEZZOTTI BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
*/
#ifndef KNN_H
#define KNN_H
#include <vector>
#include <map>
#include <string>
#include <thread>
#include <mutex>
namespace hdi{
namespace dr{
enum knn_library
{
KNN_HNSW = 0,
KNN_ANNOY = 1
};
enum knn_distance_metric
{
KNN_METRIC_EUCLIDEAN = 0,
KNN_METRIC_COSINE = 1,
KNN_METRIC_INNER_PRODUCT = 2,
KNN_METRIC_MANHATTAN = 3,
KNN_METRIC_HAMMING = 4,
KNN_METRIC_DOT = 5
};
//! Returns the number of supported KNN libraries.
//! This function should be considered deprecated and kept for backward comppatibility. New code should use the supported_knn_libraries function.
int HierarchicalSNE_NrOfKnnAlgorithms();
//! Returns both the name/label and index of the supported KNN libraries since this can depend on compiler support.
//! This function is especially useful for building user-interfaces where the user can select which KNN library to use for a specific task (e.g. t-SNE or HSNE).
//! Alternatively it can be used to offer a look-up table to translate the currently set KNN Library index back to human readable text.
std::map<std::string, int> supported_knn_libraries();
//! Returns the name/label and index of distance metrics supported by a specific KNN library.
//! This function is especially useful for building user-interfaces where the user can select both a KNN library and a distance metric since not every KNN library supports the same distance metric.
//! Alternatively it can be used to offer a look-up table to translate the currently set KNN distance metric index back to human readable text.
std::map<std::string, int> supported_knn_library_distance_metrics(int knn_lib);
}
}
namespace hnswlib {
/*
* replacement for the openmp '#pragma omp parallel for' directive
* only handles a subset of functionality (no reductions etc)
* Process ids from start (inclusive) to end (EXCLUSIVE)
*
* The method is borrowed from nmslib https://github.com/nmslib/nmslib/blob/v2.1.1/similarity_search/include/thread_pool.h#L62
* and used in the hnswlib examples as well https://github.com/nmslib/hnswlib/blob/v0.5.0/examples/updates_test.cpp
*/
template<class Function>
inline void ParallelFor(size_t start, size_t end, size_t numThreads, Function fn) {
if (numThreads <= 0) {
numThreads = std::thread::hardware_concurrency();
}
if (numThreads == 1) {
for (size_t id = start; id < end; id++) {
fn(id, 0);
}
}
else {
std::vector<std::thread> threads;
std::atomic<size_t> current(start);
// keep track of exceptions in threads
// https://stackoverflow.com/a/32428427/1713196
std::exception_ptr lastException = nullptr;
std::mutex lastExceptMutex;
for (size_t threadId = 0; threadId < numThreads; ++threadId) {
threads.push_back(std::thread([&, threadId] {
while (true) {
size_t id = current.fetch_add(1);
if ((id >= end)) {
break;
}
try {
fn(id, threadId);
}
catch (...) {
std::unique_lock<std::mutex> lastExcepLock(lastExceptMutex);
lastException = std::current_exception();
/*
* This will work even when current is the largest value that
* size_t can fit, because fetch_add returns the previous value
* before the increment (what will result in overflow
* and produce 0 instead of current + 1).
*/
current = end;
break;
}
}
}));
}
for (auto &thread : threads) {
thread.join();
}
if (lastException) {
std::rethrow_exception(lastException);
}
}
}
}
#endif // KNN_H
| 39.166667 | 199 | 0.68617 |
26d93b947b9b9679036e23530391ab1a93028968 | 191 | h | C | SOURCE/allProjects/ManagerEmployeeSystem/ManagerEmployeeSystem/Node.h | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | SOURCE/allProjects/ManagerEmployeeSystem/ManagerEmployeeSystem/Node.h | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | SOURCE/allProjects/ManagerEmployeeSystem/ManagerEmployeeSystem/Node.h | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | #pragma once
#include<list>
#include<string>
using namespace std;
class Node
{
public:
string name;
list<Node>* nodeList;
Node(string);
Node(string, list<Node>*);
Node();
~Node();
};
| 11.235294 | 27 | 0.670157 |
9cd9a8d4f6f662e780da3e6a837635e7668bba79 | 1,162 | h | C | ncgen/odom.h | nokutu/netcdf-c | eba281a8d985e24caad97a6badc3369cfa399f77 | [
"BSD-3-Clause"
] | 386 | 2015-01-07T21:22:54.000Z | 2022-03-31T15:12:52.000Z | ncgen/odom.h | nokutu/netcdf-c | eba281a8d985e24caad97a6badc3369cfa399f77 | [
"BSD-3-Clause"
] | 1,748 | 2015-01-08T11:47:48.000Z | 2022-03-30T20:45:13.000Z | ncgen/odom.h | nokutu/netcdf-c | eba281a8d985e24caad97a6badc3369cfa399f77 | [
"BSD-3-Clause"
] | 242 | 2015-01-05T11:09:11.000Z | 2022-03-30T08:07:18.000Z | /*********************************************************************
* Copyright 2018, UCAR/Unidata
* See netcdf/COPYRIGHT file for copying and redistribution conditions.
*********************************************************************/
#ifndef ODOM_H
#define ODOM_H 1
typedef struct Odometer {
int rank;
int offset;
struct Odometer* origin;
size_t start[NC_MAX_VAR_DIMS];
size_t count[NC_MAX_VAR_DIMS];
size_t index[NC_MAX_VAR_DIMS];
size_t declsize[NC_MAX_VAR_DIMS];
} Odometer;
/*Forward*/
struct Dimset;
/* Odometer operators*/
extern Odometer* newodometer(struct Dimset*, size_t* startp, size_t* countp);
extern Odometer* newsubodometer(Odometer*, struct Dimset*, int, int);
extern Odometer* newsubodometer(Odometer*, struct Dimset*,
int start, int stop);
extern void odometerfree(Odometer*);
extern char* odometerprint(Odometer* odom);
extern int odometermore(Odometer* odom);
extern int odometerincr(Odometer* odom);
extern size_t odometeroffset(Odometer* odom);
extern size_t* odometerstartvector(Odometer* odom);
extern size_t* odometercountvector(Odometer* odom);
#endif /*ODOM_H*/
| 29.794872 | 77 | 0.654045 |
6c5b94a504ba76563ed77ed47e63bd225e462ed8 | 808 | c | C | 3rdparty/musl/libc-test/src/api/sys_shm.c | jbdelcuv/openenclave | c2e9cfabd788597f283c8dd39edda5837b1b1339 | [
"MIT"
] | 2 | 2022-03-31T05:46:57.000Z | 2022-03-31T07:13:13.000Z | 3rdparty/musl/libc-test/src/api/sys_shm.c | jbdelcuv/openenclave | c2e9cfabd788597f283c8dd39edda5837b1b1339 | [
"MIT"
] | 21 | 2020-02-05T11:09:56.000Z | 2020-03-26T18:09:09.000Z | 3rdparty/musl/libc-test/src/api/sys_shm.c | jbdelcuv/openenclave | c2e9cfabd788597f283c8dd39edda5837b1b1339 | [
"MIT"
] | 4 | 2019-09-14T07:58:58.000Z | 2020-03-03T15:55:28.000Z | #include <sys/shm.h>
#define T(t) (t*)0;
#define F(t,n) {t *y = &x.n;}
#define C(n) switch(n){case n:;}
static void f()
{
T(shmatt_t)
T(pid_t)
T(size_t)
T(time_t)
C(SHM_RDONLY)
C(SHM_RND)
C(SHMLBA)
{
struct shmid_ds x;
F(struct ipc_perm, shm_perm)
F(size_t,shm_segsz)
F(pid_t, shm_lpid)
F(pid_t, shm_cpid)
F(shmatt_t,shm_nattch)
F(time_t,shm_atime)
F(time_t,shm_dtime)
F(time_t,shm_ctime)
}
{void*(*p)(int,const void*,int) = shmat;}
{int(*p)(int,int,struct shmid_ds*) = shmctl;}
{int(*p)(const void*) = shmdt;}
{int(*p)(key_t,size_t,int) = shmget;}
T(uid_t)
T(gid_t)
T(mode_t)
T(key_t)
{
struct ipc_perm x;
F(uid_t,uid)
F(gid_t,gid)
F(uid_t,cuid)
F(gid_t,cgid)
F(mode_t, mode)
}
C(IPC_CREAT)
C(IPC_EXCL)
C(IPC_NOWAIT)
C(IPC_PRIVATE)
C(IPC_RMID)
C(IPC_SET)
C(IPC_STAT)
{key_t(*p)(const char*,int) = ftok;}
}
| 15.843137 | 45 | 0.678218 |
18ca989a63aac44f699da6eac544a3dd81f74cab | 6,747 | h | C | Microsoft.WindowsAzure.Storage/includes/wascore/xml_wrapper.h | ShippyMSFT/azure-storage-cpp | ee3a3f7db31a39ed5041fe1cb947c784ce64295b | [
"Apache-2.0"
] | 137 | 2015-01-06T09:12:04.000Z | 2022-02-08T06:07:02.000Z | Microsoft.WindowsAzure.Storage/includes/wascore/xml_wrapper.h | ShippyMSFT/azure-storage-cpp | ee3a3f7db31a39ed5041fe1cb947c784ce64295b | [
"Apache-2.0"
] | 313 | 2015-01-07T05:43:27.000Z | 2022-03-23T11:06:21.000Z | Microsoft.WindowsAzure.Storage/includes/wascore/xml_wrapper.h | ShippyMSFT/azure-storage-cpp | ee3a3f7db31a39ed5041fe1cb947c784ce64295b | [
"Apache-2.0"
] | 159 | 2015-01-19T13:37:58.000Z | 2021-12-25T18:03:19.000Z | /***
* ==++==
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ==--==
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* xml_wrapper.h
*
* This file contains wrapper for libxml2
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#pragma once
#ifndef _XML_WRAPPER_H
#define _XML_WRAPPER_H
#ifndef _WIN32
#include <string>
#include <libxml/xmlreader.h>
#include <libxml/xmlwriter.h>
#include "wascore/basic_types.h"
namespace azure { namespace storage { namespace core { namespace xml {
std::string xml_char_to_string(const xmlChar *xml_char);
/// <summary>
/// A class to wrap xmlTextReader of c library libxml2. This class provides abilities to read from xml format texts.
/// </summary>
class xml_text_reader_wrapper {
public:
xml_text_reader_wrapper(const unsigned char* buffer, unsigned int size);
~xml_text_reader_wrapper();
/// <summary>
/// Moves to the next node in the stream.
/// </summary>
/// <returns>true if the node was read successfully and false if there are no more nodes to read</returns>
bool read();
/// <summary>
/// Gets the type of the current node.
/// </summary>
/// <returns>A integer that represent the type of the node</returns>
unsigned get_node_type();
/// <summary>
/// Checks if current node is empty
/// </summary>
/// <returns>True if current node is empty and false if otherwise</returns>
bool is_empty_element();
/// <summary>
/// Gets the local name of the node
/// </summary>
/// <returns>A string indicates the local name of this node</returns>
std::string get_local_name();
/// <summary>
/// Gets the value of the node
/// </summary>
/// <returns>A string value of the node</returns>
std::string get_value();
/// <summary>
/// Moves to the first attribute of the node.
/// </summary>
/// <returns>True if the move is successful, false if empty</returns>
bool move_to_first_attribute();
/// <summary>
/// Moves to the next attribute of the node.
/// </summary>
/// <returns>True if the move is successful, false if empty</returns>
bool move_to_next_attribute();
private:
xmlTextReaderPtr m_reader;
};
/// <summary>
/// A class to wrap xmlNode of c library libxml2. This class provides abilities to create xml nodes.
/// </summary>
class xml_element_wrapper {
public:
xml_element_wrapper();
~xml_element_wrapper();
xml_element_wrapper(xmlNode* node);
/// <summary>
/// Adds a child element to this node.
/// </summary>
/// <param name="name">The name of the child node.</param>
/// <param name="prefix">The namespace prefix of the child node.</param>
/// <returns>The created child node.</returns>
xml_element_wrapper* add_child(const std::string& name, const std::string& prefix);
/// <summary>
/// Adds a namespace declaration to the node.
/// </summary>
/// <param name="uri">The namespace to associate with the prefix.</param>
/// <param name="prefix">The namespace prefix</param>
void set_namespace_declaration(const std::string& uri, const std::string& prefix);
/// <summary>
/// Set the namespace prefix
/// </summary>
/// <param name="prefix">name space prefix to be set</param>
void set_namespace(const std::string& prefix);
/// <summary>
/// Sets the value of the attribute with this name (and prefix).
/// </summary>
/// <param name="name">The name of the attribute</param>
/// <param name="value">The value of the attribute</param>
/// <param name="prefix">The prefix of the attribute, this is optional.</param>
void set_attribute(const std::string& name, const std::string& value, const std::string& prefix);
/// <summary>
/// Sets the text of the first text node. If there isn't a text node, add one and set it.
/// </summary>
/// <param name="text">The text to be set to the child node.</param>
void set_child_text(const std::string& text);
/// <summary>
/// Frees the wrappers set in nod->_private
/// </summary>
/// <param name="node">The node to be freed.</param>
/// <returns>A <see cref="pplx::task" /> object that represents the current operation.</returns>
static void free_wrappers(xmlNode* node);
private:
xmlNode* m_ele;
};
/// <summary>
/// A class to wrap xmlDoc of c library libxml2. This class provides abilities to create xml format texts from nodes.
/// </summary>
class xml_document_wrapper {
public:
xml_document_wrapper();
~xml_document_wrapper();
/// <summary>
/// Converts object to a string object.
/// </summary>
/// <returns>A std::string that contains the result</returns>
std::string write_to_string();
/// <summary>
/// Creates the root node of the document.
/// </summary>
/// <param name="name">The name of the root node.</param>
/// <param name="namespace_name">The namespace of the root node.</param>
/// <param name="prefix">The namespace prefix of the root node.</param>
/// <returns>A wrapper that contains the root node.</returns>
xml_element_wrapper* create_root_node(const std::string& name, const std::string& namespace_name, const std::string& prefix);
/// <summary>
/// Gets the root node of the document.
/// </summary>
/// <returns>The root node of the document.</returns>
xml_element_wrapper* get_root_node() const;
private:
xmlDocPtr m_doc;
};
}}}} // namespace azure::storage::core::xml
#endif //#ifdef _WIN32
#endif //#ifndef _XML_WRAPPER_H
| 35.510526 | 133 | 0.59671 |
17d3b60a6392cb3b2533f55fd8f522778bcd2c67 | 572 | c | C | c/KR/mysql.c | yanrong/book_demo | 20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f | [
"Apache-2.0"
] | null | null | null | c/KR/mysql.c | yanrong/book_demo | 20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f | [
"Apache-2.0"
] | null | null | null | c/KR/mysql.c | yanrong/book_demo | 20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f | [
"Apache-2.0"
] | null | null | null |
#include <stdio.h>
#include "mysql.h"
int main()
{
MYSQL conn;
int res;
mysql_init(&conn);
if(mysql_real_connect(&conn,"localhost","username","password","your's DB",0,NULL,CLIENT_FOUND_ROWS))
{
printf("Linke Mysql success!\n");
res=mysql_query(&conn,"insert into children values('20124400','male',22)");
if(res)
{
printf("语句执行失败\n");
mysql_close(&conn);//记得关闭连接
}
else
{
printf("语句执行成功\n");
mysql_close(&conn);
}
}
return 0;
}
| 19.724138 | 104 | 0.520979 |
025e977f623d7eef69854f89e954e16b6ef309e2 | 342 | h | C | Pods/Target Support Files/Pods-SwiftySnippets_macOS/Pods-SwiftySnippets_macOS-umbrella.h | MarekKojder/SwiftySnippets | 8fbde6d3ea1c55bb837e0c1a4ae7c05fc66754d3 | [
"MIT"
] | 1 | 2021-12-27T02:43:36.000Z | 2021-12-27T02:43:36.000Z | Pods/Target Support Files/Pods-SwiftySnippets_macOS/Pods-SwiftySnippets_macOS-umbrella.h | MarekKojder/SwiftySnippets | 8fbde6d3ea1c55bb837e0c1a4ae7c05fc66754d3 | [
"MIT"
] | null | null | null | Pods/Target Support Files/Pods-SwiftySnippets_macOS/Pods-SwiftySnippets_macOS-umbrella.h | MarekKojder/SwiftySnippets | 8fbde6d3ea1c55bb837e0c1a4ae7c05fc66754d3 | [
"MIT"
] | null | null | null | #ifdef __OBJC__
#import <Cocoa/Cocoa.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
FOUNDATION_EXPORT double Pods_SwiftySnippets_macOSVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_SwiftySnippets_macOSVersionString[];
| 20.117647 | 79 | 0.842105 |
77f63e24186c3ff39cc17f9401834bc4b9a6bc4c | 259 | h | C | Example/PNPullToRefresh/PNPullToRefreshViewController.h | giuseppenucifora/PNPullToRefresh | 76f73f23786ba1f078a57477d0e20dd05bf3c1a5 | [
"MIT"
] | null | null | null | Example/PNPullToRefresh/PNPullToRefreshViewController.h | giuseppenucifora/PNPullToRefresh | 76f73f23786ba1f078a57477d0e20dd05bf3c1a5 | [
"MIT"
] | null | null | null | Example/PNPullToRefresh/PNPullToRefreshViewController.h | giuseppenucifora/PNPullToRefresh | 76f73f23786ba1f078a57477d0e20dd05bf3c1a5 | [
"MIT"
] | null | null | null | //
// PNPullToRefreshViewController.h
// PNPullToRefresh
//
// Created by Giuseppe Nucifora on 04/27/2016.
// Copyright (c) 2016 Giuseppe Nucifora. All rights reserved.
//
@import UIKit;
@interface PNPullToRefreshViewController : UIViewController
@end
| 18.5 | 62 | 0.752896 |
ae2d3840f6fb0eb9dd14fbcd40cd891daf1c472c | 8,485 | h | C | RPCS3_HLE_UYA_physgun/RPCS3/Utilities/bit_set.h | isJuhn/RPCS3_HLE_UYA_physgun | ed71ac1ad60f3fcd4fde186183bf870496271b96 | [
"MIT"
] | null | null | null | RPCS3_HLE_UYA_physgun/RPCS3/Utilities/bit_set.h | isJuhn/RPCS3_HLE_UYA_physgun | ed71ac1ad60f3fcd4fde186183bf870496271b96 | [
"MIT"
] | null | null | null | RPCS3_HLE_UYA_physgun/RPCS3/Utilities/bit_set.h | isJuhn/RPCS3_HLE_UYA_physgun | ed71ac1ad60f3fcd4fde186183bf870496271b96 | [
"MIT"
] | null | null | null | #pragma once
/*
This header implements bs_t<> class for scoped enum types (enum class).
To enable bs_t<>, enum scope must contain `__bitset_enum_max` entry.
enum class flagzz : u32
{
flag1, // Bit indices start from zero
flag2,
__bitset_enum_max // It must be the last value
};
This also enables helper operators for this enum type.
Examples:
`+flagzz::flag1` - unary `+` operator convert flagzz value to bs_t<flagzz>
`flagzz::flag1 + flagzz::flag2` - bitset union
`flagzz::flag1 - flagzz::flag2` - bitset difference
Intersection (&) and symmetric difference (^) is also available.
*/
#include "types.h"
#include "Atomic.h"
template <typename T>
class atomic_bs_t;
// Bitset type for enum class with available bits [0, T::__bitset_enum_max)
template <typename T>
class bs_t final
{
public:
// Underlying type
using under = std::underlying_type_t<T>;
private:
// Underlying value
under m_data;
friend class atomic_bs_t<T>;
// Value constructor
constexpr explicit bs_t(int, under data)
: m_data(data)
{
}
public:
static constexpr std::size_t bitmax = sizeof(T) * 8;
static constexpr std::size_t bitsize = static_cast<under>(T::__bitset_enum_max);
static_assert(std::is_enum<T>::value, "bs_t<> error: invalid type (must be enum)");
static_assert(bitsize <= bitmax, "bs_t<> error: invalid __bitset_enum_max");
static_assert(bitsize != bitmax || std::is_unsigned<under>::value, "bs_t<> error: invalid __bitset_enum_max (sign bit)");
// Helper function
static constexpr under shift(T value)
{
return static_cast<under>(1) << static_cast<under>(value);
}
bs_t() = default;
// Construct from a single bit
constexpr bs_t(T bit)
: m_data(shift(bit))
{
}
// Test for empty bitset
constexpr explicit operator bool() const
{
return m_data != 0;
}
// Extract underlying data
constexpr explicit operator under() const
{
return m_data;
}
// Copy
constexpr bs_t operator +() const
{
return *this;
}
constexpr bs_t& operator +=(bs_t rhs)
{
m_data |= static_cast<under>(rhs);
return *this;
}
constexpr bs_t& operator -=(bs_t rhs)
{
m_data &= ~static_cast<under>(rhs);
return *this;
}
constexpr bs_t& operator &=(bs_t rhs)
{
m_data &= static_cast<under>(rhs);
return *this;
}
constexpr bs_t& operator ^=(bs_t rhs)
{
m_data ^= static_cast<under>(rhs);
return *this;
}
constexpr bs_t operator +(bs_t rhs) const
{
return bs_t(0, m_data | rhs.m_data);
}
constexpr bs_t operator -(bs_t rhs) const
{
return bs_t(0, m_data & ~rhs.m_data);
}
constexpr bs_t operator &(bs_t rhs) const
{
return bs_t(0, m_data & rhs.m_data);
}
constexpr bs_t operator ^(bs_t rhs) const
{
return bs_t(0, m_data ^ rhs.m_data);
}
constexpr bool operator ==(bs_t rhs) const
{
return m_data == rhs.m_data;
}
constexpr bool operator !=(bs_t rhs) const
{
return m_data != rhs.m_data;
}
constexpr bool test(bs_t rhs) const
{
return (m_data & rhs.m_data) != 0;
}
constexpr bool test_and_set(T bit)
{
bool r = (m_data & shift(bit)) != 0;
m_data |= shift(bit);
return r;
}
constexpr bool test_and_reset(T bit)
{
bool r = (m_data & shift(bit)) != 0;
m_data &= ~shift(bit);
return r;
}
constexpr bool test_and_complement(T bit)
{
bool r = (m_data & shift(bit)) != 0;
m_data ^= shift(bit);
return r;
}
};
// Unary '+' operator: promote plain enum value to bitset value
template <typename T, typename = decltype(T::__bitset_enum_max)>
constexpr bs_t<T> operator +(T bit)
{
return bit;
}
// Binary '+' operator: bitset union
template <typename T, typename = decltype(T::__bitset_enum_max)>
constexpr bs_t<T> operator +(T lhs, T rhs)
{
return bs_t<T>(lhs) + bs_t<T>(rhs);
}
// Binary '-' operator: bitset difference
template <typename T, typename = decltype(T::__bitset_enum_max)>
constexpr bs_t<T> operator -(T lhs, T rhs)
{
return bs_t<T>(lhs) - bs_t<T>(rhs);
}
// Binary '&' operator: bitset intersection
template <typename T, typename = decltype(T::__bitset_enum_max)>
constexpr bs_t<T> operator &(T lhs, T rhs)
{
return bs_t<T>(lhs) & bs_t<T>(rhs);
}
// Binary '^' operator: bitset symmetric difference
template <typename T, typename = decltype(T::__bitset_enum_max)>
constexpr bs_t<T> operator ^(T lhs, T rhs)
{
return bs_t<T>(lhs) ^ bs_t<T>(rhs);
}
// Atomic bitset specialization with optimized operations
template <typename T>
class atomic_bs_t : public atomic_t<::bs_t<T>> // TODO: true specialization
{
// Corresponding bitset type
using bs_t = ::bs_t<T>;
// Base class
using base = atomic_t<::bs_t<T>>;
// Use underlying m_data
using base::m_data;
public:
// Underlying type
using under = typename bs_t::under;
atomic_bs_t() = default;
atomic_bs_t(const atomic_bs_t&) = delete;
atomic_bs_t& operator =(const atomic_bs_t&) = delete;
explicit constexpr atomic_bs_t(bs_t value)
: base(value)
{
}
explicit constexpr atomic_bs_t(T bit)
: base(bit)
{
}
explicit operator bool() const
{
return static_cast<bool>(base::load());
}
explicit operator under() const
{
return static_cast<under>(base::load());
}
bs_t operator +() const
{
return base::load();
}
bs_t fetch_add(const bs_t& rhs)
{
return bs_t(0, atomic_storage<under>::fetch_or(m_data.m_data, rhs.m_data));
}
bs_t add_fetch(const bs_t& rhs)
{
return bs_t(0, atomic_storage<under>::or_fetch(m_data.m_data, rhs.m_data));
}
bs_t operator +=(const bs_t& rhs)
{
return add_fetch(rhs);
}
bs_t fetch_sub(const bs_t& rhs)
{
return bs_t(0, atomic_storage<under>::fetch_and(m_data.m_data, ~rhs.m_data));
}
bs_t sub_fetch(const bs_t& rhs)
{
return bs_t(0, atomic_storage<under>::and_fetch(m_data.m_data, ~rhs.m_data));
}
bs_t operator -=(const bs_t& rhs)
{
return sub_fetch(rhs);
}
bs_t fetch_and(const bs_t& rhs)
{
return bs_t(0, atomic_storage<under>::fetch_and(m_data.m_data, rhs.m_data));
}
bs_t and_fetch(const bs_t& rhs)
{
return bs_t(0, atomic_storage<under>::and_fetch(m_data.m_data, rhs.m_data));
}
bs_t operator &=(const bs_t& rhs)
{
return and_fetch(rhs);
}
bs_t fetch_xor(const bs_t& rhs)
{
return bs_t(0, atomic_storage<under>::fetch_xor(m_data.m_data, rhs.m_data));
}
bs_t xor_fetch(const bs_t& rhs)
{
return bs_t(0, atomic_storage<under>::xor_fetch(m_data.m_data, rhs.m_data));
}
bs_t operator ^=(const bs_t& rhs)
{
return xor_fetch(rhs);
}
auto fetch_or(const bs_t&) = delete;
auto or_fetch(const bs_t&) = delete;
auto operator |=(const bs_t&) = delete;
auto operator ++() = delete;
auto operator --() = delete;
auto operator ++(int) = delete;
auto operator --(int) = delete;
bs_t operator +(bs_t rhs) const
{
return bs_t(0, base::load().m_data | rhs.m_data);
}
bs_t operator -(bs_t rhs) const
{
return bs_t(0, base::load().m_data & ~rhs.m_data);
}
bs_t operator &(bs_t rhs) const
{
return bs_t(0, base::load().m_data & rhs.m_data);
}
bs_t operator ^(bs_t rhs) const
{
return bs_t(0, base::load().m_data ^ rhs.m_data);
}
bs_t operator ==(bs_t rhs) const
{
return base::load().m_data == rhs.m_data;
}
bs_t operator !=(bs_t rhs) const
{
return base::load().m_data != rhs.m_data;
}
friend bs_t operator +(bs_t lhs, const atomic_bs_t& rhs)
{
return bs_t(0, lhs.m_data | rhs.load().m_data);
}
friend bs_t operator -(bs_t lhs, const atomic_bs_t& rhs)
{
return bs_t(0, lhs.m_data & ~rhs.load().m_data);
}
friend bs_t operator &(bs_t lhs, const atomic_bs_t& rhs)
{
return bs_t(0, lhs.m_data & rhs.load().m_data);
}
friend bs_t operator ^(bs_t lhs, const atomic_bs_t& rhs)
{
return bs_t(0, lhs.m_data ^ rhs.load().m_data);
}
friend bs_t operator ==(bs_t lhs, const atomic_bs_t& rhs)
{
return lhs.m_data == rhs.load().m_data;
}
friend bs_t operator !=(bs_t lhs, const atomic_bs_t& rhs)
{
return lhs.m_data != rhs.load().m_data;
}
bool test(const bs_t& rhs)
{
return base::load().test(rhs);
}
bool test_and_set(T rhs)
{
return atomic_storage<under>::bts(m_data.m_data, static_cast<uint>(static_cast<under>(rhs)));
}
bool test_and_reset(T rhs)
{
return atomic_storage<under>::btr(m_data.m_data, static_cast<uint>(static_cast<under>(rhs)));
}
bool test_and_complement(T rhs)
{
return atomic_storage<under>::btc(m_data.m_data, static_cast<uint>(static_cast<under>(rhs)));
}
};
template <typename T>
struct fmt_unveil<bs_t<T>, void>
{
// Format as is
using type = bs_t<T>;
static inline u64 get(const bs_t<T>& bitset)
{
return static_cast<std::underlying_type_t<T>>(bitset);
}
};
| 20.495169 | 122 | 0.682616 |
c4442aa3b3538a2a2713b7e772a9f1ae7cbc934a | 89 | c | C | restart.c | vzvca/flash | 61ebd8c1edbd013cfad6366961a764f7c2d8d429 | [
"MIT"
] | 1 | 2021-04-19T13:17:49.000Z | 2021-04-19T13:17:49.000Z | restart.c | vzvca/flash | 61ebd8c1edbd013cfad6366961a764f7c2d8d429 | [
"MIT"
] | null | null | null | restart.c | vzvca/flash | 61ebd8c1edbd013cfad6366961a764f7c2d8d429 | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <sys/reboot.h>
main()
{
sync();
reboot(RB_AUTOBOOT);
}
| 9.888889 | 23 | 0.629213 |
8fbb652f0d0dd61ea546f1bb7c3b5ed730f2575e | 6,289 | c | C | dependencies/agar/tests/network.c | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 5 | 2016-04-18T23:12:51.000Z | 2022-03-06T05:12:07.000Z | dependencies/agar/tests/network.c | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 2 | 2015-10-09T19:13:25.000Z | 2018-12-25T17:16:54.000Z | dependencies/agar/tests/network.c | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 15 | 2015-02-23T16:35:28.000Z | 2022-03-25T13:40:33.000Z | /* Public domain */
/*
* Test the AG_Net(3) network interface.
*/
#include "agartest.h"
#ifdef AG_NETWORK
#include <string.h>
typedef struct {
AG_TestInstance _inherit;
char testHost[128];
char testPort[16];
AG_Console *cons;
} MyTestInstance;
static void
TestConnect(AG_Event *event)
{
MyTestInstance *ti = AG_PTR(1);
AG_NetSocket *ns = NULL;
AG_NetAddrList *nal = NULL;
/* Create a new stream socket, with no defined address family. */
if ((ns = AG_NetSocketNew(0, AG_NET_STREAM, 0)) == NULL)
goto fail;
/* Resolve the hostname and port number (or service name). */
AG_ConsoleMsg(ti->cons, "Resolving %s:%s...", ti->testHost, ti->testPort);
if ((nal = AG_NetResolve(ti->testHost, ti->testPort, 0)) == NULL) {
AG_NetSocketFree(ns);
goto fail;
}
/*
* Establish a connection with one of the resolved addresses.
* The socket will inherit the address family of the NetAddress.
*/
AG_ConsoleMsg(ti->cons, "Connecting...");
if (AG_NetConnect(ns, nal) == -1) {
AG_NetAddrListFree(nal);
AG_NetSocketFree(ns);
goto fail;
}
AG_ConsoleMsg(ti->cons, "Connected to %s [%s]",
AG_NetAddrNumerical(ns->addrRemote),
agNetAddrFamilyNames[ns->addrRemote->family]);
AG_NetClose(ns);
AG_NetAddrListFree(nal);
AG_NetSocketFree(ns);
return;
fail:
AG_ConsoleMsg(ti->cons, "Failed: %s", AG_GetError());
return;
}
static void
TestServer(AG_Event *event)
{
MyTestInstance *ti = AG_PTR(1);
char buf[128];
AG_NetAddrList *ifc;
AG_NetAddr *na;
AG_NetSocket *ns;
AG_NetSocketSet sockSet, rdSet, exceptSet;
AG_NetSocketSetInit(&sockSet);
AG_NetSocketSetInit(&rdSet);
AG_NetSocketSetInit(&exceptSet);
/* Retrieve the locally configured network addresses. */
if ((ifc = AG_NetGetIfConfig()) == NULL) {
goto fail;
}
AG_TAILQ_FOREACH(na, ifc, addrs) {
/* Skip any non-internet address. */
if (na->family != AG_NET_INET4 &&
na->family != AG_NET_INET6)
continue;
/* Create a new stream socket bound to port 3456. */
if ((ns = AG_NetSocketNew(na->family, AG_NET_STREAM, 0))
== NULL) {
goto fail;
}
AG_NetSetOptionInt(ns, AG_NET_REUSEADDR, 1);
na->port = 3456;
if (AG_NetBind(ns, na) == -1) {
AG_ConsoleMsg(ti->cons, "bind(%s): %s; skipping",
AG_NetAddrNumerical(na), AG_GetError());
AG_NetSocketFree(ns);
continue;
}
AG_ConsoleMsg(ti->cons, "Bound to %s:%d",
AG_NetAddrNumerical(na), na->port);
/* Add this socket to the set for polling. */
ns->poll |= AG_NET_POLL_READ;
ns->poll |= AG_NET_POLL_EXCEPTIONS;
AG_TAILQ_INSERT_TAIL(&sockSet, ns, sockets);
}
AG_NetAddrListFree(ifc);
for (;;) {
/* Poll sockSet for read/exception conditions. */
if (AG_NetPoll(&sockSet, &rdSet, NULL, &exceptSet, 0) < 1) {
AG_ConsoleMsg(ti->cons, "Poll: %s", AG_GetError());
break;
}
AG_TAILQ_FOREACH(ns, &rdSet, read) {
/*
* Read condition on a bound socket indicates
* an incoming connection that we must accept.
*/
if (ns->flags & AG_NET_SOCKET_BOUND) {
AG_NetSocket *nsNew;
if ((nsNew = AG_NetAccept(ns)) == NULL) {
goto fail;
}
AG_ConsoleMsg(ti->cons,
"Connection on [%s:%d] from [%s]!",
AG_NetAddrNumerical(ns->addrLocal),
ns->addrLocal->port,
AG_NetAddrNumerical(nsNew->addrRemote));
nsNew->poll |= AG_NET_POLL_READ;
nsNew->poll |= AG_NET_POLL_WRITE;
nsNew->poll |= AG_NET_POLL_EXCEPTIONS;
AG_TAILQ_INSERT_TAIL(&sockSet, nsNew, sockets);
AG_Strlcpy(buf, "Hello\n", sizeof(buf));
if (AG_NetWrite(nsNew, buf, strlen(buf), NULL)
== -1) {
goto fail;
}
} else {
size_t nRead;
if (AG_NetRead(ns, buf, sizeof(buf), &nRead) == -1) {
goto fail;
}
if (nRead == 0) {
AG_ConsoleMsg(ti->cons,
"Closing connection to [%s]",
AG_NetAddrNumerical(ns->addrRemote));
AG_TAILQ_REMOVE(&sockSet, ns, sockets);
AG_NetSocketFree(ns);
} else {
buf[nRead-1] = '\0';
AG_ConsoleMsg(ti->cons,
"Data from [%s]: %s",
AG_NetAddrNumerical(ns->addrRemote),
buf);
}
}
}
AG_TAILQ_FOREACH(ns, &exceptSet, except) {
AG_ConsoleMsg(ti->cons, "Exception on socket [%s]",
ns->addrRemote ? AG_NetAddrNumerical(ns->addrRemote) : "");
}
}
AG_NetSocketSetFree(&sockSet);
return;
fail:
AG_ConsoleMsg(ti->cons, "Failed: %s", AG_GetError());
}
static int
Init(void *obj)
{
MyTestInstance *ti = obj;
AG_Strlcpy(ti->testHost, "libagar.org", sizeof(ti->testHost));
AG_Strlcpy(ti->testPort, "80", sizeof(ti->testPort));
return (0);
}
static int
TestGUI(void *obj, AG_Window *win)
{
MyTestInstance *ti = obj;
AG_Tlist *tl;
AG_NetAddr *na;
AG_NetAddrList *ifc;
AG_Button *btn;
AG_Event *ev;
AG_Textbox *tb;
AG_Box *hBox;
if ((ifc = AG_NetGetIfConfig()) != NULL) {
AG_LabelNewS(win, 0, "Local addresses:");
tl = AG_TlistNew(win, AG_TLIST_HFILL);
AG_TlistSizeHint(tl, "[inet4] XXX.XXX.XXX.XXX", 4);
AG_TAILQ_FOREACH(na, ifc, addrs) {
AG_TlistAdd(tl, NULL, "[%s] %s",
agNetAddrFamilyNames[na->family],
AG_NetAddrNumerical(na));
}
AG_NetAddrListFree(ifc);
} else {
AG_LabelNewS(win, 0, AG_GetError());
}
AG_LabelNewS(win, 0, "Status:");
ti->cons = AG_ConsoleNew(win, AG_CONSOLE_EXPAND);
hBox = AG_BoxNewHoriz(win, AG_BOX_HFILL);
{
tb = AG_TextboxNewS(hBox, AG_TEXTBOX_HFILL, "Test Host: ");
AG_TextboxBindUTF8(tb, ti->testHost, sizeof(ti->testHost));
tb = AG_TextboxNewS(hBox, 0, " Port: ");
AG_TextboxSizeHint(tb, "<1234>");
AG_TextboxBindUTF8(tb, ti->testPort, sizeof(ti->testPort));
}
btn = AG_ButtonNew(win, AG_BUTTON_HFILL, "Connect (in separate thread)");
ev = AG_SetEvent(btn, "button-pushed", TestConnect, "%p", ti);
ev->flags |= AG_EVENT_ASYNC;
AG_ButtonNewFn(win, AG_BUTTON_HFILL, "Connect (in main thread)",
TestConnect, "%p", ti);
btn = AG_ButtonNew(win, AG_BUTTON_HFILL, "Start test server");
ev = AG_SetEvent(btn, "button-pushed", TestServer, "%p", ti);
ev->flags |= AG_EVENT_ASYNC;
AG_WindowSetGeometryAligned(win, AG_WINDOW_MC, 380, 500);
return (0);
}
const AG_TestCase networkTest = {
"network",
N_("Test the AG_Net(3) interface"),
"1.4.2",
0,
sizeof(MyTestInstance),
Init,
NULL, /* destroy */
NULL, /* test */
TestGUI,
NULL /* bench */
};
#endif /* AG_NETWORK */
| 24.956349 | 75 | 0.656066 |
3a8ed35c08bc01e3bbab7c151cbd252709ef437c | 19,382 | h | C | src/utilities.h | leyhline/modern-mutual-information | ca2e5579d0b82979ee9a8a0dee0b4453b96647b2 | [
"Apache-2.0"
] | 2 | 2021-01-12T09:23:38.000Z | 2022-03-03T14:00:30.000Z | src/utilities.h | leyhline/modern-mutual-information | ca2e5579d0b82979ee9a8a0dee0b4453b96647b2 | [
"Apache-2.0"
] | null | null | null | src/utilities.h | leyhline/modern-mutual-information | ca2e5579d0b82979ee9a8a0dee0b4453b96647b2 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2018, University of Freiburg
* Optophysiology Lab.
* Thomas Leyh <thomas.leyh@mailbox.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <vector>
#include <cstddef>
#include <random>
#include <stdexcept>
#include <iterator>
#include <climits>
#include <chrono>
#include "Histogram2d.h"
/**
* Calculates the histogram indices of a certain data container.
* @param bins Number of bins for the imaginary histogram.
* @param min Minimum value in data container.
* @param max Maximum value in data container.
* @param begin Iterator to the beginning of the data.
* @param end Iterator to the end of the data.
* @return A vector with the same size as the data holding the index positions.
* If there is a value outside the [min,max] range UINT_MAX is inserted
* at this position.
*/
template<typename T, typename Iterator>
std::vector<int> calculate_indices_1d(
const int bins,
const T min, const T max,
const Iterator begin, const Iterator end);
/**
* Small struct for simply holding two index values.
*/
struct index_pair
{
int first;
int second;
};
/**
* Calculate indices of a 2d histogram for a certain data container.
* @param binsX Number of bins on imaginary histogram's x-axis.
* @param binsY Number of bins on imaginary histogram's y-axis.
* @param minX Minimum value in first data container.
* @param maxX Maximum value in first data container.
* @param minY Minimum value in second data container.
* @param maxY Maximum value in second data container.
* @param beginX Iterator to the beginning of the first data container.
* @param endX Iterator to the end of the first data container.
* @param beginY Iterator to the beginning of the second data container.
* @param endY Iterator to the end of the second data container.
* Both containers must have the same size.
* @return Vector of index_pair structs. The vector has the same size as the data.
* If there is a value outside the [min,max] range index_pair {UINT_MAX, UINT_MAX}
* is inserted at this position.
*/
template<typename T, typename Iterator>
std::vector<index_pair> calculate_indices_2d(
const int binsX, const int binsY,
const T minX, const T maxX,
const T minY, const T maxY,
const Iterator beginX, const Iterator endX,
const Iterator beginY, const Iterator endY);
/**
* Calculate a certain range of mutual information by shifting the second data container
* in relation to the first one.
* No shift:
* |--------------------| dataX
* |--------------------| dataY
* Negative shift:
* |--------------------| dataX
* |--------------------| dataY
* Positive shift:
* |--------------------| dataX
* |--------------------| dataY
* @param shift_from Negative (or positive) value for specifying the largest shift to the left.
* @param shift_to Positive (of negative) value for specifying the largest shift to the right.
* Has to be greater than shift_from.
* @param minX Minimum value in first data container.
* @param maxX Maximum value in first data container.
* @param minY Minimum value in second data container.
* @param maxY Maximum value in second data container.
* @param beginX Iterator to the beginning of the first data container.
* @param endX Iterator to the end of the first data container.
* @param beginY Iterator to the beginning of the second data container.
* @param endY Iterator to the end of the second data container.
* Both containers must have the same size.
* @param shift_step (Optional) Specifies the steps between shifts. Default = 1.
* @return Vector with size (shift_to - shift_from) holding the mutual information for each shift.
* Might be smaller if shift_step is specified.
*/
template<typename T, typename Iterator>
std::vector<T> shifted_mutual_information(
const int shift_from, const int shift_to,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
const Iterator beginX, const Iterator endX,
const Iterator beginY, const Iterator endY,
const int shift_step = 1);
/**
* Calculates the mutual information of the two given data vectors X and Y
* by using bootstrapping. This is done by first generating nr_samples
* histograms by sampling the data and then again sampling these histograms
* and adding them together.
* Helper function for shifted_mutual_information_with_bootstrap.
*/
template<typename T, typename Iterator>
std::vector<T> bootstrapped_mi(const Iterator beginX, const Iterator endX,
const Iterator beginY, const Iterator endY,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
int nr_samples, int nr_repetitions, std::mt19937& rgen);
/**
* Similar to shifted_mutual_information but additionally uses bootstrapping
* this increasing its runtime. There are two additional parameters:
* @param nr_samples How many temporary histograms to generate by sampling the data.
* @param nr_repetitions How many times to repeat this process to minimize noise.
* @return A vector of size `(shift_to - shift_from) / shift_step + 1`
holding vectors of size `nr_repetitions` with the mutual information.
*/
template<typename T, typename Iterator>
std::vector< std::vector<T> > shifted_mutual_information_with_bootstrap(
const int shift_from, const int shift_to,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
const Iterator beginX, const Iterator endX,
const Iterator beginY, const Iterator endY,
int nr_samples, int nr_repetitions,
const int shift_step = 1);
/**
* This is for the matlab mex interface:
* Instead of returning a vector the result is written to a pointer location.
* The values specified by beginX, endX, beginY, endY are the histogram indices in range [0, nr_bins).
* @param output A pointer to to a vector of size (shift_to - shift_from) / shift_step + 1
*/
template<typename T>
void shifted_mutual_information(
const int shift_from, const int shift_to,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
const int* beginX, const int* endX,
const int* beginY, const int* endY,
const int shift_step,
T* output);
/**
* This is for the matlab mex interface:
* Instead of returning a vector the result is written to a pointer location.
* The values specified by beginX, endX, beginY, endY are the histogram indices in range [0, nr_bins).
* @param output A pointer to to a vector of size ((shift_to - shift_from) / shift_step + 1) * nr_repetitions
*/
template<typename T>
void shifted_mutual_information_with_bootstrap(
const int shift_from, const int shift_to,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
const int* beginX, const int* endX,
const int* beginY, const int* endY,
int nr_samples, int nr_repetitions,
const int shift_step,
T* output);
//////////////////
/// IMPLEMENTATION
//////////////////
template<typename T, typename Iterator>
std::vector<int> calculate_indices_1d(
const int bins,
const T min, const T max,
const Iterator begin, const Iterator end)
{
if (min >= max)
throw std::logic_error("min has to be smaller than max.");
if (bins < 1)
throw std::invalid_argument("There must be at least one bin.");
int size = std::distance(begin, end);
std::vector<int> result(size);
// Most code token from Histogram1d class.
#pragma omp parallel for
for (int i = 0; i < size; ++i)
{
auto value = begin[i];
if (value >= min && value < max)
{
T normalized = (value - min) / (max - min);
#pragma warning(suppress: 4244)
int index = normalized * bins; // Implicit conversion to integer.
result[i] = index;
}
else if (value == max)
{
result[i] = bins - 1;
}
else
{
result[i] = INT_MAX;
}
}
return result;
}
template<typename T, typename Iterator>
std::vector<index_pair> calculate_indices_2d(
const int binsX, const int binsY,
const T minX, const T maxX,
const T minY, const T maxY,
const Iterator beginX, const Iterator endX,
const Iterator beginY, const Iterator endY)
{
if (minX >= maxX)
throw std::logic_error("minX has to be smaller than maxX.");
if (minY >= maxY)
throw std::logic_error("minY has to be smaller than maxY.");
if (binsX < 1)
throw std::invalid_argument("There must be at least one binX.");
if (binsY < 1)
throw std::invalid_argument("There must be at least one binY.");
int sizeX = std::distance(beginX, endX);
int sizeY = std::distance(beginY, endY);
if (sizeX != sizeY)
throw std::logic_error("Containers referenced by iterators must have the same size.");
std::vector<index_pair> result(sizeX);
// Most code token from Histogram2d class.
#pragma omp parallel for
for (int i = 0; i < sizeX; ++i)
{
auto x = beginX[i];
auto y = beginY[i];
if (x >= minX
&& x <= maxX
&& y >= minY
&& y <= maxY)
{
int indexX;
if (x == maxX)
indexX = binsX - 1;
else
#pragma warning(suppress: 4244)
indexX = (x - minX) / (maxX - minX) * binsX;
int indexY;
if (y == maxY)
indexY = binsY - 1;
else
#pragma warning(suppress: 4244)
indexY = (y - minY) / (maxY - minY) * binsY;
result[i] = index_pair{ indexX, indexY }; // I hope this is allowed.
}
else
{
result[i] = index_pair{ INT_MAX, INT_MAX };
}
}
return result;
}
template<typename T>
inline void check_shifted_mutual_information(
const size_t sizeX, const size_t sizeY,
const int shift_from, const int shift_to,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY, const int shift_step)
{
if (sizeX != sizeY)
throw std::logic_error("Containers referenced by iterators must have the same size.");
if (shift_from >= shift_to)
throw std::logic_error("shift_from has to be smaller than shift_to.");
if (minX >= maxX)
throw std::logic_error("minX has to be smaller than maxX.");
if (minY >= maxY)
throw std::logic_error("minY has to be smaller than maxY.");
if (binsX < 1)
throw std::invalid_argument("There must be at least one binX.");
if (binsY < 1)
throw std::invalid_argument("There must be at least one binY.");
if ((size_t)(shift_to < 0 ? -shift_to : shift_to) >= sizeX)
throw std::logic_error("Maximum shift does not fit data size.");
if ((size_t)(shift_from < 0 ? -shift_from : shift_from) >= sizeX)
throw std::logic_error("Minimum shift does not fit data size.");
if (shift_step < 1)
throw std::invalid_argument("shift_step must be greater or equal 1.");
}
template<typename T, typename Iterator>
std::vector<T> shifted_mutual_information(
const int shift_from, const int shift_to,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
const Iterator beginX, const Iterator endX,
const Iterator beginY, const Iterator endY,
const int shift_step /* 1 */)
{
size_t sizeX = std::distance(beginX, endX);
size_t sizeY = std::distance(beginY, endY);
check_shifted_mutual_information(sizeX, sizeY, shift_from, shift_to,
binsX, binsY, minX, maxX, minY, maxY, shift_step);
std::vector<int> indicesX = calculate_indices_1d(binsX, minX, maxX, beginX, endX);
std::vector<int> indicesY = calculate_indices_1d(binsY, minY, maxY, beginY, endY);
auto indX_begin = indicesX.begin();
auto indX_end = indicesX.end();
auto indY_begin = indicesY.begin();
auto indY_end = indicesY.end();
std::vector<T> result((shift_to - shift_from) / shift_step + 1);
#pragma omp parallel for
for (int i = shift_from; i <= shift_to; i += shift_step)
{
Histogram2d<T> hist(binsX, binsY, minX, maxX, minY, maxY);
if (i < 0)
{
hist.increment_cpu(indX_begin, std::prev(indX_end, -i),
std::next(indY_begin, -i), indY_end);
}
else if (i > 0)
{
hist.increment_cpu(std::next(indX_begin, i), indX_end,
indY_begin, std::prev(indY_end, i));
}
else // Should not be necessary but better be explicit.
{
hist.increment_cpu(indX_begin, indX_end,
indY_begin, indY_end);
}
result[(i - shift_from) / shift_step] = *hist.calculate_mutual_information();
}
return result;
}
template<typename T, typename Iterator>
std::vector<T> bootstrapped_mi(const Iterator beginX, const Iterator endX,
const Iterator beginY, const Iterator endY,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
int nr_samples, int nr_repetitions, std::mt19937& rgen)
{
size_t sizeX = std::distance(beginX, endX);
size_t sizeY = std::distance(beginY, endY);
if (sizeX != sizeY)
throw std::logic_error("Containers referenced by iterators must have the same size.");
std::uniform_int_distribution<int> uniform(0, sizeX - 1);
std::vector<Histogram2d<T>*> hist3d(nr_samples); // A vector of raw pointers :(
int nr_samples_per_histogram = sizeX / nr_samples;
// First create some histograms from randomly sampled data pairs.
for (int sample = 0; sample < nr_samples; ++sample)
{
Histogram2d<T>* hist_ptr = new Histogram2d<T>(binsX, binsY, minX, maxX, minY, maxY);
for (int i = 0; i < nr_samples_per_histogram; ++i)
{
int ridx = uniform(rgen);
hist_ptr->increment_at(beginX[ridx], beginY[ridx]);
}
hist3d[sample] = hist_ptr;
}
// Now sample these histograms again and add them together.
std::uniform_int_distribution<int> uniform_from_samples(0, nr_samples - 1);
std::vector<T> results(nr_repetitions);
for (int i = 0; i < nr_repetitions; ++i)
{
Histogram2d<T> final_hist(binsX, binsY, minX, maxX, minY, maxY);
for (int sample = 0; sample < nr_samples; ++sample)
{
int sampleidx = uniform_from_samples(rgen);
final_hist.add(*hist3d[sampleidx]);
}
results[i] = *final_hist.calculate_mutual_information();
}
// Cleanup (even though using raw pointers is not really elegant)
for (int sample = 0; sample < nr_samples; ++sample)
{
delete hist3d[sample];
}
return results;
}
template<typename T, typename Iterator>
std::vector< std::vector<T> > shifted_mutual_information_with_bootstrap(
const int shift_from, const int shift_to,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
const Iterator beginX, const Iterator endX,
const Iterator beginY, const Iterator endY,
int nr_samples, int nr_repetitions,
const int shift_step /* 1 */)
{
size_t sizeX = std::distance(beginX, endX);
size_t sizeY = std::distance(beginY, endY);
check_shifted_mutual_information(sizeX, sizeY, shift_from, shift_to,
binsX, binsY, minX, maxX, minY, maxY, shift_step);
if (nr_samples < 1)
throw std::logic_error("For bootstrapping you need a minimum of one sample.");
if (nr_repetitions < 1)
throw std::logic_error("There needs to be at least one repetition of the bootstrapping process.");
std::vector<int> indicesX = calculate_indices_1d(binsX, minX, maxX, beginX, endX);
std::vector<int> indicesY = calculate_indices_1d(binsY, minY, maxY, beginY, endY);
auto indX_begin = indicesX.begin();
auto indX_end = indicesX.end();
auto indY_begin = indicesY.begin();
auto indY_end = indicesY.end();
std::vector< std::vector<T> > result((shift_to - shift_from) / shift_step + 1);
#pragma omp parallel for
for (int i = shift_from; i <= shift_to; i += shift_step)
{
unsigned int seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::mt19937 rgen(seed);
std::vector<T> mi;
if (i < 0)
{
mi = bootstrapped_mi<T>(indX_begin, std::prev(indX_end, -i),
std::next(indY_begin, -i), indY_end,
binsX, binsY, minX, maxX, minY, maxY, nr_samples, nr_repetitions, rgen);
}
else if (i > 0)
{
mi = bootstrapped_mi<T>(std::next(indX_begin, i), indX_end,
indY_begin, std::prev(indY_end, i),
binsX, binsY, minX, maxX, minY, maxY, nr_samples, nr_repetitions, rgen);
}
else // Should not be necessary but better be explicit.
{
mi = bootstrapped_mi<T>(indX_begin, indX_end,
indY_begin, indY_end,
binsX, binsY, minX, maxX, minY, maxY, nr_samples, nr_repetitions, rgen);
}
result[(i - shift_from) / shift_step] = mi;
}
return result;
}
template<typename T>
void shifted_mutual_information(
const int shift_from, const int shift_to,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
const int* beginX, const int* endX,
const int* beginY, const int* endY,
const int shift_step,
T* output)
{
size_t sizeX = std::distance(beginX, endX);
size_t sizeY = std::distance(beginY, endY);
check_shifted_mutual_information(sizeX, sizeY, shift_from, shift_to,
binsX, binsY, minX, maxX, minY, maxY, shift_step);
#pragma omp parallel for
for (int i = shift_from; i <= shift_to; i += shift_step)
{
Histogram2d<T> hist(binsX, binsY, minX, maxX, minY, maxY);
if (i < 0)
{
hist.increment_cpu(beginX, std::prev(endX, -i),
std::next(beginY, -i), endY);
}
else if (i > 0)
{
hist.increment_cpu(std::next(beginX, i), endX,
beginY, std::prev(endY, i));
}
else // Should not be necessary but better be explicit.
{
hist.increment_cpu(beginX, endX,
beginY, endY);
}
output[(i - shift_from) / shift_step] = *hist.calculate_mutual_information();
}
}
template<typename T>
void shifted_mutual_information_with_bootstrap(
const int shift_from, const int shift_to,
const int binsX, const int binsY,
const T minX, const T maxX, const T minY, const T maxY,
const int* beginX, const int* endX,
const int* beginY, const int* endY,
int nr_samples, int nr_repetitions,
const int shift_step,
T* output)
{
size_t sizeX = std::distance(beginX, endX);
size_t sizeY = std::distance(beginY, endY);
check_shifted_mutual_information(sizeX, sizeY, shift_from, shift_to,
binsX, binsY, minX, maxX, minY, maxY, shift_step);
if (nr_samples < 1)
throw std::logic_error("For bootstrapping you need a minimum of one sample.");
if (nr_repetitions < 1)
throw std::logic_error("There needs to be at least one repetition of the bootstrapping process.");
#pragma omp parallel for
for (int i = shift_from; i <= shift_to; i += shift_step)
{
unsigned int seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::mt19937 rgen(seed);
std::vector<T> mi;
if (i < 0)
{
mi = bootstrapped_mi<T>(beginX, std::prev(endX, -i),
std::next(beginY, -i), endY,
binsX, binsY, minX, maxX, minY, maxY, nr_samples, nr_repetitions, rgen);
}
else if (i > 0)
{
mi = bootstrapped_mi<T>(std::next(beginX, i), endX,
beginY, std::prev(endY, i),
binsX, binsY, minX, maxX, minY, maxY, nr_samples, nr_repetitions, rgen);
}
else // Should not be necessary but better be explicit.
{
mi = bootstrapped_mi<T>(beginX, endX,
beginY, endY,
binsX, binsY, minX, maxX, minY, maxY, nr_samples, nr_repetitions, rgen);
}
for (int j = 0; j < nr_repetitions; ++j) // Copy result to output.
{
output[((i - shift_from) / shift_step) * nr_repetitions + j] = mi[j];
}
}
} | 36.29588 | 109 | 0.704674 |
3a9a3fb86ee1de7a9f52c4036890d47029c8b9d3 | 2,708 | h | C | ios/chrome/browser/ui/payments/credit_card_edit_coordinator.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ios/chrome/browser/ui/payments/credit_card_edit_coordinator.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ios/chrome/browser/ui/payments/credit_card_edit_coordinator.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_PAYMENTS_CREDIT_CARD_EDIT_COORDINATOR_H_
#define IOS_CHROME_BROWSER_UI_PAYMENTS_CREDIT_CARD_EDIT_COORDINATOR_H_
#import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h"
#import "ios/chrome/browser/ui/payments/address_edit_coordinator.h"
#import "ios/chrome/browser/ui/payments/billing_address_selection_coordinator.h"
#import "ios/chrome/browser/ui/payments/payment_request_edit_view_controller.h"
namespace payments {
class AutofillPaymentInstrument;
}
namespace payments {
class PaymentRequest;
} // namespace payments
@class CreditCardEditCoordinator;
// Delegate protocol for CreditCardEditCoordinator.
@protocol CreditCardEditCoordinatorDelegate<NSObject>
// Notifies the delegate that the user has finished editing or creating
// |paymentMethod|. |paymentMethod| will be a new payment method owned by the
// PaymentRequest object if no payment method instance was provided to the
// coordinator. Otherwise, it will be the same edited instance.
- (void)creditCardEditCoordinator:(CreditCardEditCoordinator*)coordinator
didFinishEditingPaymentMethod:
(payments::AutofillPaymentInstrument*)paymentMethod;
// Notifies the delegate that the user has chosen to cancel editing or creating
// a credit card and return to the previous screen.
- (void)creditCardEditCoordinatorDidCancel:
(CreditCardEditCoordinator*)coordinator;
@end
// Coordinator responsible for creating and presenting a credit card editor view
// controller. This view controller will be presented by the view controller
// provided in the initializer.
@interface CreditCardEditCoordinator
: ChromeCoordinator<AddressEditCoordinatorDelegate,
BillingAddressSelectionCoordinatorDelegate,
PaymentRequestEditViewControllerDelegate>
// The payment method to be edited, if any. This pointer is not owned by this
// class and should outlive it.
@property(nonatomic, assign) payments::AutofillPaymentInstrument* paymentMethod;
// The PaymentRequest object owning an instance of payments::WebPaymentRequest
// as provided by the page invoking the Payment Request API. This pointer is not
// owned by this class and should outlive it.
@property(nonatomic, assign) payments::PaymentRequest* paymentRequest;
// The delegate to be notified when the user returns or finishes creating or
// editing a credit card.
@property(nonatomic, weak) id<CreditCardEditCoordinatorDelegate> delegate;
@end
#endif // IOS_CHROME_BROWSER_UI_PAYMENTS_CREDIT_CARD_EDIT_COORDINATOR_H_
| 41.661538 | 80 | 0.80613 |
27188cde716a584612661ba47297f2c0e6b95060 | 1,699 | h | C | base/message_loop.h | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | 1 | 2017-07-27T15:08:19.000Z | 2017-07-27T15:08:19.000Z | base/message_loop.h | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | null | null | null | base/message_loop.h | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | 1 | 2020-10-01T08:46:10.000Z | 2020-10-01T08:46:10.000Z | // Copyright (c) 2014 The Caroline authors. All rights reserved.
// Use of this source file is governed by a MIT license that can be found in the
// LICENSE file.
// @author Aleksandr Derbenev <alex@technoworks.ru>
#ifndef BASE_MESSAGE_LOOP_H_
#define BASE_MESSAGE_LOOP_H_
#include <functional>
#include <string>
#include "base/macro.h"
#include "base/threadsafe_queue.h"
namespace base {
class MessageLoop {
public:
struct CalledFrom {
CalledFrom() = default;
CalledFrom(const std::string& file, unsigned int line)
: file(file),
line(line) {}
std::string file;
unsigned int line;
};
MessageLoop();
virtual ~MessageLoop();
void Run();
void PostTask(const CalledFrom& called_from,
const std::function<void()>& callback);
void PostTask(const CalledFrom& called_from,
std::function<void()>&& callback);
void Quit();
static MessageLoop* GetCurrent();
protected:
virtual void IdleTask();
private:
enum State {
kNotStartedState,
kRunningState,
kStoppingState,
kStoppedState
};
State state_;
struct Task {
Task() = default;
Task(const std::function<void()>& callback,
const CalledFrom& called_from)
: callback(callback),
called_from(called_from) {}
Task(std::function<void()>&& callback,
const CalledFrom& called_from)
: callback(callback),
called_from(called_from) {}
std::function<void()> callback;
CalledFrom called_from;
};
ThreadSafeQueue<Task> task_queue_;
DISALLOW_COPY_AND_ASSIGN(MessageLoop);
};
} // namespace base
#define FROM_HERE base::MessageLoop::CalledFrom(__FILE__, __LINE__)
#endif // BASE_MESSAGE_LOOP_H_
| 20.975309 | 80 | 0.68452 |
5c8b57de0ebf7b92fa6539b3e828b02f19808630 | 1,932 | c | C | src/recipe.c | luciusmagn/c2tc | 96cd70d0e666604fad4f44c2e2f52260465a1fd7 | [
"MIT",
"BSD-2-Clause-FreeBSD",
"0BSD"
] | 1 | 2016-06-26T10:52:49.000Z | 2016-06-26T10:52:49.000Z | src/recipe.c | luciusmagn/c2tc | 96cd70d0e666604fad4f44c2e2f52260465a1fd7 | [
"MIT",
"BSD-2-Clause-FreeBSD",
"0BSD"
] | null | null | null | src/recipe.c | luciusmagn/c2tc | 96cd70d0e666604fad4f44c2e2f52260465a1fd7 | [
"MIT",
"BSD-2-Clause-FreeBSD",
"0BSD"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "util.h"
#include "types.h"
#include "mpc.h"
#include "shared.h"
#include "errors.h"
#include "log.h"
#include "tree_transform.h"
void processrecipe()
{
if(opts->print_info) printf("number of targets:%ld\n", recipe->target_count);
for (int32 i = 0; i < recipe->target_count; i++)
processtarget(vector_get(recipe->targets, i));
}
void processtarget(target_t* trg)
{
trg->trees = malloc(sizeof(vector));
vector_init(trg->trees);
int success = 0;
if(opts->test)
printf(ANSI_YELLOW "target: " ANSI_GREEN "%s " ANSI_RESET "\n", trg->name);
for(int32 i = 0; i < vector_total(trg->files); i++)
{
mpc_ast_t* ast = malloc(sizeof(mpc_ast_t*));
ast = c2parse(vector_get(trg->files, i));
if(ast)
{
vector_add(trg->trees, ast);
if(opts->print_info)
printf("module name: %s\n", MODULE_PRE(ast)->contents);
if(opts->print_ast1)
mpc_ast_print(ast);
if(opts->test)
printf(ANSI_MAGENTA "\tfile:" ANSI_CYAN " %s " ANSI_GREEN "[SUCCESS]" ANSI_RESET "\n",
(char*)vector_get(trg->files, i));
success++;
}
else if(!opts->test)
{
throw(&eparsef, get_file_error(vector_get(trg->files, i)));
log_info("compilation failed, exiting");
exit(-1);
}
else
printf(ANSI_MAGENTA "\tfile:" ANSI_CYAN " %s " ANSI_RED "[FAILURE]" ANSI_RESET "\n",
(char*)vector_get(trg->files, i));
}
if(opts->test)
printf(ANSI_GREEN "TOTAL: " ANSI_YELLOW "%d/%d files parsed successfully" ANSI_RESET "\n",
success, vector_total(trg->files));
cleanup_trg(trg);
for(int32 i = 0; i < vector_total(trg->trees); i++)
analyse(vector_get(trg->trees, i));
}
| 31.16129 | 102 | 0.565735 |
5807cbd4b2e50d08655a59ad822b7a06bd806c68 | 11,154 | c | C | carray/carray.c | zhoujie-jay/sortix | 7348cb0b9ad5931bf73c8b3fa2dd63c99cae6afa | [
"0BSD"
] | 5 | 2018-06-13T14:56:57.000Z | 2021-08-25T01:07:32.000Z | carray/carray.c | zhoujie-jay/sortix | 7348cb0b9ad5931bf73c8b3fa2dd63c99cae6afa | [
"0BSD"
] | null | null | null | carray/carray.c | zhoujie-jay/sortix | 7348cb0b9ad5931bf73c8b3fa2dd63c99cae6afa | [
"0BSD"
] | null | null | null | /*
* Copyright (c) 2014 Jonas 'Sortie' Termansen.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* carray.c
* Convert a binary file to a C array.
*/
#include <errno.h>
#include <error.h>
#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void compact_arguments(int* argc, char*** argv)
{
for ( int i = 0; i < *argc; i++ )
{
while ( i < *argc && !(*argv)[i] )
{
for ( int n = i; n < *argc; n++ )
(*argv)[n] = (*argv)[n+1];
(*argc)--;
}
}
}
bool get_option_variable(const char* option, char** varptr,
const char* arg, int argc, char** argv, int* ip,
const char* argv0)
{
size_t option_len = strlen(option);
if ( strncmp(option, arg, option_len) != 0 )
return false;
if ( arg[option_len] == '=' )
{
*varptr = strdup(arg + option_len + 1);
return true;
}
if ( arg[option_len] != '\0' )
return false;
if ( *ip + 1 == argc )
{
fprintf(stderr, "%s: expected operand after `%s'\n", argv0, option);
exit(1);
}
*varptr = strdup(argv[++*ip]), argv[*ip] = NULL;
return true;
}
#define GET_OPTION_VARIABLE(str, varptr) \
get_option_variable(str, varptr, arg, argc, argv, &i, argv0)
void get_short_option_variable(char c, char** varptr,
const char* arg, int argc, char** argv, int* ip,
const char* argv0)
{
free(*varptr);
if ( *(arg+1) )
{
*varptr = strdup(arg + 1);
}
else
{
if ( *ip + 1 == argc )
{
error(0, 0, "option requires an argument -- '%c'", c);
fprintf(stderr, "Try `%s --help' for more information.\n", argv0);
exit(1);
}
*varptr = strdup(argv[*ip + 1]);
argv[++(*ip)] = NULL;
}
}
#define GET_SHORT_OPTION_VARIABLE(c, varptr) \
get_short_option_variable(c, varptr, arg, argc, argv, &i, argv0)
static void help(FILE* fp, const char* argv0)
{
fprintf(fp, "Usage: %s [OPTION]... [INPUT...] -o OUTPUT\n", argv0);
fprintf(fp, "Convert a binary file to a C array.\n");
fprintf(fp, "\n");
fprintf(fp, "Mandatory arguments to long options are mandatory for short options too.\n");
fprintf(fp, " -c, --const add const keyword\n");
fprintf(fp, " -e, --extern add extern keyword\n");
fprintf(fp, " --extern-c use C linkage\n");
fprintf(fp, " -f, --forward forward declare rather than define\n");
fprintf(fp, " --guard=MACRO use include guard macro MACRO\n");
fprintf(fp, " -g, --use-guard add include guard\n");
fprintf(fp, " -i, --include include prerequisite headers\n");
fprintf(fp, " --identifier=NAME use identifier NAME\n");
fprintf(fp, " --includes=INCLUDES emit raw preprocessor INCLUDES\n");
fprintf(fp, " -o, --output=FILE write result to FILE\n");
fprintf(fp, " -r, --raw emit only raw \n");
fprintf(fp, " -s, --static add static keyword\n");
fprintf(fp, " --type=TYPE use type TYPE [unsigned char]\n");
fprintf(fp, " -v, --volatile add volatile keyword\n");
fprintf(fp, " --char use type char\n");
fprintf(fp, " --signed-char use type signed char\n");
fprintf(fp, " --unsigned-char use type unsigned char\n");
fprintf(fp, " --int8_t use type int8_t\n");
fprintf(fp, " --uint8_t use type uint8_t\n");
fprintf(fp, " --help display this help and exit\n");
fprintf(fp, " --version output version information and exit\n");
}
static void version(FILE* fp, const char* argv0)
{
fprintf(fp, "%s (Sortix) %s\n", argv0, VERSIONSTR);
}
int main(int argc, char* argv[])
{
setlocale(LC_ALL, "");
bool flag_const = false;
bool flag_extern_c = false;
bool flag_extern = false;
bool flag_forward = false;
bool flag_guard = false;
bool flag_include = false;
bool flag_raw = false;
bool flag_static = false;
bool flag_volatile = false;
char* arg_guard = NULL;
char* arg_identifier = NULL;
char* arg_includes = NULL;
char* arg_output = NULL;
char* arg_type = NULL;
const char* argv0 = argv[0];
for ( int i = 1; i < argc; i++ )
{
const char* arg = argv[i];
if ( arg[0] != '-' || !arg[1] )
continue;
argv[i] = NULL;
if ( !strcmp(arg, "--") )
break;
if ( arg[1] != '-' )
{
char c;
while ( (c = *++arg) ) switch ( c )
{
case 'c': flag_const = true; break;
case 'e': flag_extern = true; break;
case 'f': flag_forward = true; break;
case 'g': flag_guard = true; break;
case 'i': flag_include = true; break;
case 'o': GET_SHORT_OPTION_VARIABLE('o', &arg_output); arg = "o"; break;
case 'r': flag_raw = true; break;
case 's': flag_static = true; break;
case 'v': flag_volatile = true; break;
default:
fprintf(stderr, "%s: unknown option -- '%c'\n", argv0, c);
help(stderr, argv0);
exit(1);
}
}
else if ( !strcmp(arg, "--help") )
help(stdout, argv0), exit(0);
else if ( !strcmp(arg, "--version") )
version(stdout, argv0), exit(0);
else if ( !strcmp(arg, "--const") )
flag_const = true;
else if ( !strcmp(arg, "--extern") )
flag_extern = true;
else if ( !strcmp(arg, "--forward") )
flag_forward = true;
else if ( !strcmp(arg, "--use-guard") )
flag_guard = true;
else if ( !strcmp(arg, "--include") )
flag_include = true;
else if ( !strcmp(arg, "--raw") )
flag_raw = true;
else if ( !strcmp(arg, "--static") )
flag_static = true;
else if ( !strcmp(arg, "--volatile") )
flag_volatile = true;
else if ( !strcmp(arg, "--char") )
free(arg_type), arg_type = strdup("char");
else if ( !strcmp(arg, "--signed-char") )
free(arg_type), arg_type = strdup("signed char");
else if ( !strcmp(arg, "--unsigned-char") )
free(arg_type), arg_type = strdup("unsigned char");
else if ( !strcmp(arg, "--int8_t") )
free(arg_type), arg_type = strdup("int8_t");
else if ( !strcmp(arg, "--uint8_t") )
free(arg_type), arg_type = strdup("uint8_t");
else if ( GET_OPTION_VARIABLE("--guard", &arg_guard) )
flag_guard = true;
else if ( GET_OPTION_VARIABLE("--identifier", &arg_identifier) ) { }
else if ( GET_OPTION_VARIABLE("--includes", &arg_includes) )
flag_include = true;
else if ( GET_OPTION_VARIABLE("--output", &arg_output) ) { }
else if ( GET_OPTION_VARIABLE("--type", &arg_type) ) { }
else if ( !strcmp(arg, "--extern-c") )
flag_extern_c = true;
else
{
fprintf(stderr, "%s: unknown option: %s\n", argv0, arg);
help(stderr, argv0);
exit(1);
}
}
compact_arguments(&argc, &argv);
const char* output_path = arg_output;
if ( flag_extern && flag_static )
error(1, 0, "the --extern and --static are mutually incompatible");
if ( flag_forward && flag_raw )
error(1, 0, "the --forward and --raw are mutually incompatible");
if ( !arg_type )
arg_type = strdup("unsigned char");
char* guard = arg_guard;
if ( !guard )
{
if ( output_path )
guard = strdup(output_path);
else if ( 2 <= argc && strcmp(argv[1], "-") != 0 )
asprintf(&guard, "%s_H", argv[1]);
else
guard = strdup("CARRAY_H");
for ( size_t i = 0; guard[i]; i++ )
{
if ( 'A' <= guard[i] && guard[i] <= 'Z' )
continue;
else if ( 'a' <= guard[i] && guard[i] <= 'z' )
guard[i] = 'A' + guard[i] - 'a';
else if ( i != 0 && '0' <= guard[i] && guard[i] <= '9' )
continue;
else if ( guard[i] == '+' )
guard[i] = 'X';
else if ( i == 0 )
guard[i] = 'X';
else
guard[i] = '_';
}
}
if ( flag_include && !arg_includes )
{
if ( !strcmp(arg_type, "int8_t") ||
!strcmp(arg_type, "uint8_t") )
arg_includes = strdup("#include <stdint.h>");
}
char* identifier = arg_identifier;
if ( !identifier )
{
if ( output_path )
identifier = strdup(output_path);
else if ( 2 <= argc && strcmp(argv[1], "-") != 0 )
identifier = strdup(argv[1]);
else
identifier = strdup("carray");
for ( size_t i = 0; identifier[i]; i++ )
{
if ( i && identifier[i] == '.' && !strchr(identifier + i, '/') )
identifier[i] = '\0';
else if ( 'a' <= identifier[i] && identifier[i] <= 'z' )
continue;
else if ( 'A' <= identifier[i] && identifier[i] <= 'Z' )
identifier[i] = 'a' + identifier[i] - 'A';
else if ( i != 0 && '0' <= identifier[i] && identifier[i] <= '9' )
continue;
else if ( guard[i] == '+' )
identifier[i] = 'x';
else if ( i == 0 )
identifier[i] = 'x';
else
identifier[i] = '_';
}
}
if ( output_path && !freopen(output_path, "w", stdout) )
error(1, errno, "%s", output_path);
if ( flag_guard && guard )
{
printf("#ifndef %s\n", guard);
printf("#define %s\n", guard);
printf("\n");
}
if ( flag_include && arg_includes )
{
printf("%s\n", arg_includes);
printf("\n");
}
if ( !flag_raw )
{
if ( flag_extern_c )
{
printf("#if defined(__cplusplus)\n");
printf("extern \"C\" {\n");
printf("#endif\n");
printf("\n");
}
if ( flag_extern )
printf("extern ");
if ( flag_static )
printf("static ");
if ( flag_const )
printf("const ");
if ( flag_volatile )
printf("volatile ");
printf("%s %s[]", arg_type, identifier);
if ( flag_forward )
printf(";\n");
else
printf(" = {\n");
}
if ( !flag_forward )
{
bool begun_row = false;
unsigned int position = 0;
for ( int i = 0; i < argc; i++ )
{
if ( i == 0 && 2 <= argc )
continue;
FILE* fp;
const char* arg;
if ( argc == 1 || !strcmp(argv[i], "-") )
{
arg = "<stdin>";
fp = stdin;
}
else
{
arg = argv[i];
fp = fopen(arg, "r");
}
if ( !fp )
error(1, errno, "%s", arg);
int ic;
while ( (ic = fgetc(fp)) != EOF )
{
printf("%c0x%02X,", position++ ? ' ' : '\t', ic);
begun_row = true;
if ( position == (80 - 8) / 6 )
{
printf("\n");
position = 0;
begun_row = false;
}
}
if ( ferror(fp) )
error(1, errno, "fgetc: %s", arg);
if ( fp != stdin )
fclose(fp);
}
if ( begun_row )
printf("\n");
}
if ( !flag_raw )
{
if ( !flag_forward )
printf("};\n");
if ( flag_extern_c )
{
printf("\n");
printf("#if defined(__cplusplus)\n");
printf("} /* extern \"C\" */\n");
printf("#endif\n");
}
}
if ( flag_guard && guard )
{
printf("\n");
printf("#endif\n");
}
if ( ferror(stdout) || fflush(stdout) == EOF )
error(1, errno, "%s", output_path ? output_path : "stdout");
return 0;
}
| 27.472906 | 91 | 0.570199 |
5be0386eaf6accd6c4efaa94e974f4d2a5e422e8 | 459 | c | C | lib/source/my_malloc.c | kassisdion/Raytracer | ef18d5dc84c838f45e6d2a938dbdcd6acb549d8a | [
"MIT"
] | 1 | 2015-02-17T03:26:16.000Z | 2015-02-17T03:26:16.000Z | lib/source/my_malloc.c | kassisdion/raytracer | ef18d5dc84c838f45e6d2a938dbdcd6acb549d8a | [
"MIT"
] | null | null | null | lib/source/my_malloc.c | kassisdion/raytracer | ef18d5dc84c838f45e6d2a938dbdcd6acb549d8a | [
"MIT"
] | null | null | null | /*
** my_malloc.c for my_malloc in /home/florian/git/rt/lib/source
**
** Made by florian faisant
** Login <faisan_f@epitech.eu>
**
** Started on Tue Apr 9 21:53:35 2013 florian faisant
** Last update Sun Apr 14 14:56:34 2013 florian faisant
*/
#include <stdlib.h>
#include "my.h"
void *xmalloc(int size)
{
void *ptr;
ptr = malloc(size);
if (ptr == NULL)
fatal_error("Sorry, we have to exit (fatal_error[my_malloc])\n");
return (ptr);
}
| 19.956522 | 69 | 0.657952 |
21fcdf0e2334fc4d434005a426255731f197bfda | 3,459 | c | C | d/barriermnts/ruins/obj/circlet.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 9 | 2021-07-05T15:24:54.000Z | 2022-02-25T19:44:15.000Z | d/barriermnts/ruins/obj/circlet.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/barriermnts/ruins/obj/circlet.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 10 | 2021-03-13T00:18:03.000Z | 2022-03-29T15:02:42.000Z | // updated int bonus from the new system. Nienne, 09/07.
#include <std.h>
#include <daemons.h>
#include "../inherit/ruins.h"
inherit ARMOUR;
void create(){
::create();
set_name("silvery circlet");
set_id(({ "circlet","Circlet","coronet","Coronet","silver circlet","silvery circlet","coronet of illumination","Coronet of Illumination" }));
set_short("%^WHITE%^%^BOLD%^C%^RESET%^%^WHITE%^o%^BLACK%^%^BOLD%^r%^RESET%^%^WHITE%^o%^WHITE%^%^BOLD%^n%^RESET%^%^WHITE%^e%^BLACK%^%^BOLD%^t %^RESET%^%^WHITE%^o%^WHITE%^%^BOLD%^f %^CYAN%^I%^WHITE%^l%^CYAN%^lu%^WHITE%^m%^CYAN%^in%^WHITE%^a%^CYAN%^ti%^WHITE%^o%^CYAN%^n%^RESET%^");
set_obvious_short("%^WHITE%^%^BOLD%^s%^RESET%^%^WHITE%^i%^BLACK%^%^BOLD%^l%^RESET%^%^WHITE%^v%^WHITE%^%^BOLD%^e%^RESET%^%^WHITE%^r%^BLACK%^%^BOLD%^y %^RESET%^%^WHITE%^c%^WHITE%^%^BOLD%^i%^RESET%^%^WHITE%^r%^BLACK%^%^BOLD%^c%^RESET%^%^WHITE%^l%^WHITE%^%^BOLD%^e%^RESET%^%^WHITE%^t%^RESET%^");
set_long("%^MAGENTA%^This circlet is nothing more than a delicate band of %^WHITE%^%^BOLD%^s%^RESET%^"
"%^WHITE%^il%^BOLD%^ve%^RESET%^%^WHITE%^r%^MAGENTA%^, which would rest comfortably atop one's head. The only "
"decoration to the item is near the front, where the band dips forward over the wearer's brow, clasping a "
"single perfect %^WHITE%^%^BOLD%^o%^CYAN%^p%^MAGENTA%^a%^WHITE%^l%^RESET%^%^MAGENTA%^. Despite its plain "
"appearance, it is obviously of very high quality crafting.%^RESET%^\n");
set_weight(3);
set_value(4055);
set_lore("%^WHITE%^%^BOLD%^This circlet matches with tales you have heard of a particular magus "
"of note, Lachlan Crenulon. While his strengths were in abjuration, he was also a noted enchanter. "
"This particular circlet was one such enchanted creation, made to assist him in both his spellcraft and "
"his research.%^RESET%^");
set_property("lore difficulty",17);
set_type("clothing");
set_limbs(({ "head" }));
set_size(2);
set_ac(0);
set_property("enchantment",1);
set_item_bonus("intelligence",1);
set_item_bonus("sight bonus",2);
set_wear((:TO,"wear_fun":));
set_remove((:TO,"remove_fun":));
set_property("repairtype",({ "jewel" }));
}
void init() {
::init();
if(!interactive(ETO)) return;
if(interactive(TP) && TP == environment(TO)) set_size(TP->query_size());
}
int wear_fun(){
int modifier;
if((int)ETO->query_level() < 15) {
tell_object(ETO,"%^WHITE%^%^BOLD%^You can't make sense of how to use the circlet!%^RESET%^");
tell_room(EETO,"%^WHITE%^%^BOLD%^"+ETO->QCN+" can't seem to make sense of how to wear the circlet!%^RESET%^",ETO);
return 0;
}
if(member_array(ETO->query_race(),PLAYER_D->night_races()) != -1) modifier = (-2);
else modifier = 2;
tell_room(EETO,"%^WHITE%^%^BOLD%^An almost tangible aura flickers into being around "+ETOQCN+" as "
+ETO->QS+" slips the circlet over "+ETO->QP+" brow.%^RESET%^",ETO);
tell_object(ETO,"%^WHITE%^%^BOLD%^An almost tangible aura flickers into being around you, as your "
"vision becomes startlingly clear.%^RESET%^");
return 1;
}
int remove_fun(){
int modifier;
if(member_array(ETO->query_race(),PLAYER_D->night_races()) != -1) modifier = 2;
else modifier = (-2);
tell_room(EETO,"%^WHITE%^%^BOLD%^The near tangible aura fades from around "+ETOQCN+".%^RESET%^",ETO);
tell_object(ETO,"%^WHITE%^%^BOLD%^The near tangible aura seems to fade from around you, as your "
"vision returns abruptly to normal.%^RESET%^");
return 1;
}
| 50.867647 | 294 | 0.655103 |
1d15625e717b4eb4180cfe01c39e68dd8c3841c9 | 4,885 | c | C | ompi/mca/mtl/base/mtl_base_frame.c | urids/XSCALAMPI | 38624f682211d55c047183637fed8dbcc09f6d74 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2019-02-25T19:56:36.000Z | 2019-02-25T19:56:36.000Z | ompi/mca/mtl/base/mtl_base_frame.c | urids/XSCALAMPI | 38624f682211d55c047183637fed8dbcc09f6d74 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | ompi/mca/mtl/base/mtl_base_frame.c | urids/XSCALAMPI | 38624f682211d55c047183637fed8dbcc09f6d74 | [
"BSD-3-Clause-Open-MPI"
] | 3 | 2015-11-29T06:00:56.000Z | 2021-03-29T07:03:29.000Z | /*
* Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2005 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2006 The Regents of the University of California.
* All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "ompi_config.h"
#include "opal/mca/mca.h"
#include "opal/util/output.h"
#include "opal/mca/base/base.h"
#include "ompi/constants.h"
#include "ompi/mca/mtl/mtl.h"
#include "ompi/mca/mtl/base/base.h"
/*
* The following file was created by configure. It contains extern
* statements and the definition of an array of pointers to each
* component's public mca_base_component_t struct.
*/
#include "ompi/mca/mtl/base/static-components.h"
mca_mtl_base_component_t *ompi_mtl_base_selected_component = NULL;
mca_mtl_base_module_t *ompi_mtl = NULL;
/*
* Function for selecting one component from all those that are
* available.
*
* For now, we take the first component that says it can run. Might
* need to reexamine this at a later time.
*/
int
ompi_mtl_base_select(bool enable_progress_threads,
bool enable_mpi_threads)
{
opal_list_item_t *item = NULL;
mca_base_component_list_item_t *cli = NULL;
mca_mtl_base_component_t *component = NULL;
mca_mtl_base_module_t *module = NULL;
/* Traverse the list of available components; call their init
functions. */
for (item = opal_list_get_first(&ompi_mtl_base_framework.framework_components);
opal_list_get_end(&ompi_mtl_base_framework.framework_components) != item;
item = opal_list_get_next(item) ) {
cli = (mca_base_component_list_item_t *) item;
component = (mca_mtl_base_component_t *) cli->cli_component;
if (NULL == component->mtl_init) {
opal_output_verbose( 10, ompi_mtl_base_framework.framework_output,
"select: no init function; ignoring component %s",
component->mtl_version.mca_component_name );
continue;
}
opal_output_verbose( 10, ompi_mtl_base_framework.framework_output,
"select: initializing %s component %s",
component->mtl_version.mca_type_name,
component->mtl_version.mca_component_name );
module = component->mtl_init(enable_progress_threads,
enable_mpi_threads);
if (NULL == module) {
opal_output_verbose( 10, ompi_mtl_base_framework.framework_output,
"select: init returned failure for component %s",
component->mtl_version.mca_component_name );
continue;
}
opal_output_verbose( 10, ompi_mtl_base_framework.framework_output,
"select: init returned success");
ompi_mtl_base_selected_component = component;
ompi_mtl = module;
}
/* This base function closes, unloads, and removes from the
available list all unselected components. The available list will
contain only the selected component. */
if (ompi_mtl_base_selected_component) {
(void) mca_base_framework_components_close(&ompi_mtl_base_framework,
(mca_base_component_t *) ompi_mtl_base_selected_component);
}
/* All done */
if (NULL == module) {
opal_output_verbose( 10, ompi_mtl_base_framework.framework_output,
"select: no component selected");
return OMPI_ERR_NOT_FOUND;
} else {
opal_output_verbose( 10, ompi_mtl_base_framework.framework_output,
"select: component %s selected",
ompi_mtl_base_selected_component->
mtl_version.mca_component_name );
return OMPI_SUCCESS;
}
}
static int
ompi_mtl_base_close(void)
{
/* NTH: Should we be freeing the mtl module here? */
ompi_mtl = NULL;
/* Close all remaining available modules (may be one if this is a
OMPI RTE program, or [possibly] multiple if this is ompi_info) */
return mca_base_framework_components_close(&ompi_mtl_base_framework, NULL);
}
MCA_BASE_FRAMEWORK_DECLARE(ompi, mtl, NULL, NULL, NULL, ompi_mtl_base_close,
mca_mtl_base_static_components, 0);
| 38.769841 | 110 | 0.636438 |
df461b0b6461893617123de7b6caa8985395e18a | 402 | h | C | content/electronic-safe/SafeState.h | Puneethkumarsn/good-arduino-code | 361115010c030d5514cdc7d9d345968a0f49d728 | [
"MIT"
] | 18 | 2020-06-23T13:50:44.000Z | 2022-03-29T03:30:12.000Z | content/electronic-safe/SafeState.h | LironHazan/good-arduino-code | 3e3c7b374b1039b0890cffafa7f5639c33f60ea5 | [
"MIT"
] | 27 | 2020-07-21T06:33:38.000Z | 2022-03-26T23:20:07.000Z | content/electronic-safe/SafeState.h | LironHazan/good-arduino-code | 3e3c7b374b1039b0890cffafa7f5639c33f60ea5 | [
"MIT"
] | 11 | 2020-06-30T12:18:21.000Z | 2022-01-22T19:16:22.000Z | /**
Arduino Electronic Safe
Copyright (C) 2020, Uri Shaked.
Released under the MIT License.
*/
#ifndef SAFESTATE_H
#define SAFESTATE_H
class SafeState {
public:
SafeState();
void lock();
bool unlock(String code);
bool locked();
bool hasCode();
void setCode(String newCode);
private:
void setLock(bool locked);
bool _locked;
};
#endif /* SAFESTATE_H */
| 15.461538 | 34 | 0.649254 |
0ebaa113d619c123a4a439ebfe4454f85a8d60e5 | 1,198 | h | C | Applications/PineBoard/PBOpenAppDialogsTransaction.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | 2 | 2021-04-15T10:50:21.000Z | 2021-08-19T19:00:09.000Z | usr/sbin/usr/libexec/PineBoard/PBOpenAppDialogsTransaction.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | null | null | null | usr/sbin/usr/libexec/PineBoard/PBOpenAppDialogsTransaction.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | null | null | null | //
// 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 Steve Nygard.
//
#import <BaseBoard/BSTransaction.h>
@class NSNumber, PBOpenApplicationRequest;
@interface PBOpenAppDialogsTransaction : BSTransaction
{
PBOpenApplicationRequest *_request; // 8 = 0x8
NSNumber *_restrictionValue; // 16 = 0x10
NSNumber *_legacyGameValue; // 24 = 0x18
}
- (void).cxx_destruct; // IMP=0x00000001001d08bc
@property(readonly, nonatomic) NSNumber *legacyGameValue; // @synthesize legacyGameValue=_legacyGameValue;
@property(readonly, nonatomic) NSNumber *restrictionValue; // @synthesize restrictionValue=_restrictionValue;
@property(readonly, nonatomic) PBOpenApplicationRequest *request; // @synthesize request=_request;
- (void)_addLegacyGameDialogTransaction; // IMP=0x00000001001d04c4
- (void)_addRestrictionDialogTransaction; // IMP=0x00000001001d0114
@property(readonly, nonatomic) _Bool shouldContinueLaunch;
- (_Bool)_shouldFailForChildTransaction:(id)arg1; // IMP=0x00000001001d0028
- (void)_begin; // IMP=0x00000001001cffc4
- (id)initWithRequest:(id)arg1; // IMP=0x00000001001cfed4
@end
| 38.645161 | 120 | 0.776294 |
1dc741affdc14cdfdf40262bc3978cc1b60af7b8 | 915 | c | C | machine.c | hjparker/mrasm | e2eff738f0f210c9af446f7361fb443426a12f55 | [
"MIT"
] | null | null | null | machine.c | hjparker/mrasm | e2eff738f0f210c9af446f7361fb443426a12f55 | [
"MIT"
] | null | null | null | machine.c | hjparker/mrasm | e2eff738f0f210c9af446f7361fb443426a12f55 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include "machine.h"
// two global variables pointing to start and end of queue
INSTRUCTION *prog_head = NULL;
INSTRUCTION *prog_current = NULL;
int prog_add(int instrCount, char addrMode, unsigned long opcode, int operand, char zReg, char yReg, char xReg, char aSig, char bSig)
{
INSTRUCTION *ptr;
// allocate a new line
ptr = (INSTRUCTION *) malloc(sizeof(INSTRUCTION));
if (ptr == NULL)
{
printf("malloc failed!\n");
return 0;
}
// setup first entry
if (prog_head == NULL)
{
prog_current = prog_head = ptr;
}
else
{
prog_current->next = ptr;
prog_current = ptr;
}
ptr->next = NULL;
// copy in instruction data
ptr->instrCount = instrCount;
ptr->addrMode = addrMode;
ptr->opcode = opcode;
ptr->operand = operand;
ptr->zReg = zReg;
ptr->yReg = yReg;
ptr->xReg = xReg;
ptr->aSig = aSig;
ptr->bSig = bSig;
printf("%08X\n",ptr->opcode);
return 1;
}
| 19.468085 | 133 | 0.66776 |
3d4f94370289b0de57c1e1284932b915ccf9a93e | 358 | h | C | chap01/interp.h | dangerggg/TigerCompiler | 38d6acebc123ef6776fdfad04c1698dedb02b525 | [
"MIT"
] | null | null | null | chap01/interp.h | dangerggg/TigerCompiler | 38d6acebc123ef6776fdfad04c1698dedb02b525 | [
"MIT"
] | null | null | null | chap01/interp.h | dangerggg/TigerCompiler | 38d6acebc123ef6776fdfad04c1698dedb02b525 | [
"MIT"
] | null | null | null | #ifndef INTERP_H
#define INTERP_H
#include "node.h"
typedef struct I_table_ *I_table;
struct I_table_ {
string id;
int value;
I_table tail;
};
/* This function can also be used as update */
I_table I_Table(string, int, I_table);
int Lookup(string, I_table);
I_table InterpStm(A_stm, I_table);
I_table InterpExp(A_exp, I_table, int *);
#endif
| 17.9 | 46 | 0.72067 |
ce38dc853983d94254be61573f44a97a47ff65ca | 140 | h | C | src/exact_cover/dlx.h | JamsRamen/Polycube | e2f4233361e1a87f461fb879e02964dff6a708d6 | [
"MIT"
] | 2 | 2020-09-09T16:36:36.000Z | 2021-11-01T17:59:06.000Z | src/exact_cover/dlx.h | jamesrayman/Polycube | e2f4233361e1a87f461fb879e02964dff6a708d6 | [
"MIT"
] | 9 | 2020-09-15T15:57:51.000Z | 2021-06-07T23:18:13.000Z | src/exact_cover/dlx.h | jamesrayman/Polycube | e2f4233361e1a87f461fb879e02964dff6a708d6 | [
"MIT"
] | null | null | null | #pragma once
#include "exact_cover.h"
namespace exact_cover {
std::vector<Solution> dlx (const Problem& problem, int solutionLimit);
} | 20 | 74 | 0.742857 |
c4072de8a8c80042f9f596822c4ffbe607108b4f | 652 | h | C | ProofTreeInterpreter/ProofTreeVisitor.h | roncato/ProofTreeInterpreter | ef43b5f09e25ccd1a701fef128ae62da7c35ca7d | [
"BSD-2-Clause"
] | null | null | null | ProofTreeInterpreter/ProofTreeVisitor.h | roncato/ProofTreeInterpreter | ef43b5f09e25ccd1a701fef128ae62da7c35ca7d | [
"BSD-2-Clause"
] | null | null | null | ProofTreeInterpreter/ProofTreeVisitor.h | roncato/ProofTreeInterpreter | ef43b5f09e25ccd1a701fef128ae62da7c35ca7d | [
"BSD-2-Clause"
] | null | null | null | #ifndef PROOFTREEVISITOR_H
#define PROOFTREEVISITOR_H
#include "ProofTreeAST\AbstractSyntaxTree.h"
#include "ProofTreeAST\Connective.h"
#include "ProofTreeAST\Sentence.h"
#include "ProofTreeAST\AtomicFormula.h"
#include "ProofTreeAST\BinaryFormula.h"
namespace ProofTreeAST
{
class ProofTreeVisitor
{
public :
virtual void* visitConnective(const ProofTreeAST::Connective object) = 0;
virtual void* visitSentence(const ProofTreeAST::Sentence& object) = 0;
virtual void* visitAtomicFormula(const ProofTreeAST::AtomicFormula& object) = 0;
virtual void* visitBinaryFormula(const ProofTreeAST::BinaryFormula& object) = 0;
};
}
#endif]
| 26.08 | 83 | 0.783742 |
e07bfd25f056adbaf3d0cf6dc14c75b146b14d35 | 486 | h | C | Applications/HeadBoard/TVCarouselViewDataSource-Protocol.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | 2 | 2021-04-15T10:50:21.000Z | 2021-08-19T19:00:09.000Z | Applications/HeadBoard/TVCarouselViewDataSource-Protocol.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | null | null | null | Applications/HeadBoard/TVCarouselViewDataSource-Protocol.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | null | null | null | //
// 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 Steve Nygard.
//
#import "NSObject-Protocol.h"
@class UICollectionViewCell, _TVCarouselView;
@protocol TVCarouselViewDataSource <NSObject>
- (UICollectionViewCell *)carouselView:(_TVCarouselView *)arg1 cellForItemAtIndex:(unsigned long long)arg2;
- (unsigned long long)numberOfItemsInCarouselView:(_TVCarouselView *)arg1;
@end
| 30.375 | 120 | 0.76749 |
ef8e7e74a7100716861d955e34abd5687515e346 | 1,441 | h | C | asix/dyndns/dyndns.h | temcocontrols/Programmable-Controller | a78527b60ccc536a9d8d88759d9b1be1a9eb6cb0 | [
"FTL"
] | 1 | 2015-11-06T01:48:52.000Z | 2015-11-06T01:48:52.000Z | asix/dyndns/dyndns.h | temcocontrols/Programmable-Controller | a78527b60ccc536a9d8d88759d9b1be1a9eb6cb0 | [
"FTL"
] | 1 | 2020-11-03T04:56:30.000Z | 2020-11-03T04:56:30.000Z | asix/dyndns/dyndns.h | temcocontrols/Programmable-Controller | a78527b60ccc536a9d8d88759d9b1be1a9eb6cb0 | [
"FTL"
] | 6 | 2015-11-24T05:57:32.000Z | 2020-11-03T03:16:59.000Z | /*
******************************************************************************
* Copyright (c) 2006 ASIX Electronic Corporation All rights reserved.
*
* This is unpublished proprietary source code of ASIX Electronic Corporation
*
* The copyright notice above does not evidence any actual or intended
* publication of such source code.
******************************************************************************
*/
/*=============================================================================
* Module Name:dyndns.h
* Purpose:
* Author:
* Date:
* Notes:
*=============================================================================
*/
#ifndef __DYNDNS_H__
#define __DYNDNS_H__
/* INCLUDE FILE DECLARATIONS */
#include "types.h"
/* TYPE DECLARATIONS */
/* GLOBAL VARIABLES */
#define DYNDNS_STATE_IDLE 0
#define DYNDNS_STATE_MAKE_CONNECT 1
#define DYNDNS_STATE_WAIT_CONNECT 2
#define DYNDNS_STATE_SEND_COMMAND 3
#define DYNDNS_STATE_WAIT_RESPONSE 4
#define DYNDNS_STATE_UPDATE_OK 5 // added by chelsea
/* EXPORTED SUBPROGRAM SPECIFICATIONS */
void DynDNS_Init(void);
void DynDNS_DoUpdateDynDns(U8_T Type, U32_T HostIp, U8_T *Domain, U8_T *User, U8_T *Passwd);
void DynDNS_EventHandle(U8_T connID, U8_T event);
void DynDNS_ReceiveHandle(U8_T XDATA *pData, U16_T length, U8_T connId);
BOOL DynDNS_GetUpdateState(void);
U8_T DynDNS_GetState(void);
#endif /* End of __DYNDNS_H__ */
| 29.408163 | 92 | 0.582929 |
dcf3734fb68067d10361186357b9c2ee0e66dd41 | 379 | h | C | WWFoundation/Services/OEMonitorService.h | Dean-Z/WWFoundation | 5490809fc628cd94d105735403d764126894fdf7 | [
"MIT"
] | 1 | 2016-04-13T12:49:02.000Z | 2016-04-13T12:49:02.000Z | WWFoundation/Services/OEMonitorService.h | Dean-Z/WWFoundation | 5490809fc628cd94d105735403d764126894fdf7 | [
"MIT"
] | null | null | null | WWFoundation/Services/OEMonitorService.h | Dean-Z/WWFoundation | 5490809fc628cd94d105735403d764126894fdf7 | [
"MIT"
] | null | null | null | //
// OEMonitorService.h
// WWFoundation
//
// Created by William Wu on 2/1/14.
// Copyright (c) 2014 WW. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "OEMonitorInfo.h"
@interface OEMonitorService : NSObject
- (NSMutableDictionary *)loadAllMonitors;
- (OEMonitorInfo *) monitorAction:(NSURL *)actionURL lastUpdateTime:(NSDate *)lastUpdateTime;
@end
| 19.947368 | 93 | 0.730871 |
8177b0ddc087a40d6f365dd3794f195af6cbaedb | 3,507 | c | C | src/kms-message/src/kms_crypto_windows.c | MahdiMaarouf2016/mongo-c-driver-build | 345a1fb0b2b33fa14b19b64f6fe4404ccaeca02e | [
"Apache-2.0"
] | 728 | 2015-01-23T02:18:29.000Z | 2022-03-05T05:32:45.000Z | src/kms-message/src/kms_crypto_windows.c | MahdiMaarouf2016/mongo-c-driver-build | 345a1fb0b2b33fa14b19b64f6fe4404ccaeca02e | [
"Apache-2.0"
] | 397 | 2015-01-06T09:13:57.000Z | 2022-03-30T22:02:40.000Z | src/kms-message/src/kms_crypto_windows.c | MahdiMaarouf2016/mongo-c-driver-build | 345a1fb0b2b33fa14b19b64f6fe4404ccaeca02e | [
"Apache-2.0"
] | 451 | 2015-01-04T13:10:45.000Z | 2022-03-03T03:41:19.000Z | /*
* Copyright 2018-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kms_crypto.h"
#ifdef KMS_MESSAGE_ENABLE_CRYPTO_CNG
// tell windows.h not to include a bunch of headers we don't need:
#define WIN32_LEAN_AND_MEAN
// Tell windows.h not to define any NT status codes, so that we can
// get the definitions from ntstatus.h, which has a more complete list.
#define WIN32_NO_STATUS
#include <windows.h>
#undef WIN32_NO_STATUS
// Obtain a definition for the ntstatus type.
#include <winternl.h>
// Add back in the status definitions so that macro expansions for
// things like STILL_ACTIVE and WAIT_OBJECT_O can be resolved (they
// expand to STATUS_ codes).
#include <ntstatus.h>
#include <bcrypt.h>
static BCRYPT_ALG_HANDLE _algoSHA256 = 0;
static BCRYPT_ALG_HANDLE _algoSHA256Hmac = 0;
int
kms_crypto_init ()
{
if (BCryptOpenAlgorithmProvider (
&_algoSHA256, BCRYPT_SHA256_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0) !=
STATUS_SUCCESS) {
return 1;
}
if (BCryptOpenAlgorithmProvider (&_algoSHA256Hmac,
BCRYPT_SHA256_ALGORITHM,
MS_PRIMITIVE_PROVIDER,
BCRYPT_ALG_HANDLE_HMAC_FLAG) !=
STATUS_SUCCESS) {
return 2;
}
return 0;
}
void
kms_crypto_cleanup ()
{
(void) BCryptCloseAlgorithmProvider (_algoSHA256, 0);
(void) BCryptCloseAlgorithmProvider (_algoSHA256Hmac, 0);
}
bool
kms_sha256 (void *unused_ctx,
const char *input,
size_t len,
unsigned char *hash_out)
{
BCRYPT_HASH_HANDLE hHash;
NTSTATUS status =
BCryptCreateHash (_algoSHA256, &hHash, NULL, 0, NULL, 0, 0);
if (status != STATUS_SUCCESS) {
return 0;
}
status = BCryptHashData (hHash, (PUCHAR) (input), (ULONG) len, 0);
if (status != STATUS_SUCCESS) {
goto cleanup;
}
// Hardcode output length
status = BCryptFinishHash (hHash, hash_out, 256 / 8, 0);
if (status != STATUS_SUCCESS) {
goto cleanup;
}
cleanup:
(void) BCryptDestroyHash (hHash);
return status == STATUS_SUCCESS ? 1 : 0;
}
bool
kms_sha256_hmac (void *unused_ctx,
const char *key_input,
size_t key_len,
const char *input,
size_t len,
unsigned char *hash_out)
{
BCRYPT_HASH_HANDLE hHash;
NTSTATUS status = BCryptCreateHash (
_algoSHA256Hmac, &hHash, NULL, 0, (PUCHAR) key_input, (ULONG) key_len, 0);
if (status != STATUS_SUCCESS) {
return 0;
}
status = BCryptHashData (hHash, (PUCHAR) input, (ULONG) len, 0);
if (status != STATUS_SUCCESS) {
goto cleanup;
}
// Hardcode output length
status = BCryptFinishHash (hHash, hash_out, 256 / 8, 0);
if (status != STATUS_SUCCESS) {
goto cleanup;
}
cleanup:
(void) BCryptDestroyHash (hHash);
return status == STATUS_SUCCESS ? 1 : 0;
}
#endif /* KMS_MESSAGE_ENABLE_CRYPTO_CNG */
| 25.59854 | 80 | 0.660679 |
e66b0f038aa183bd639072e4df97ef3c90cef50f | 4,429 | c | C | Unix Family/Linux.Superkit.a/src/sha1.c | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | 3 | 2021-05-15T15:57:13.000Z | 2022-03-16T09:11:05.000Z | Unix Family/Linux.Superkit.a/src/sha1.c | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | null | null | null | Unix Family/Linux.Superkit.a/src/sha1.c | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | 3 | 2021-05-15T15:57:15.000Z | 2022-01-08T20:51:04.000Z | /*
* $Id: sha1.c, implementation of sha1 in c,
* originally By Steve Reid <steve@edmweb.com>
*/
#include "sk.h"
#include "sha1.h"
#include "strasm.h"
void SHA1Transform(ulong state[5], uchar buffer[64])
{
ulong a, b, c, d, e;
typedef union {
uchar c[64];
ulong l[16];
} CHAR64LONG16;
CHAR64LONG16 *block;
#ifdef SHA1HANDSOFF
static uchar workspace[64];
block = (CHAR64LONG16 *) workspace;
memcpy(block, buffer, 64);
#else
block = (CHAR64LONG16 *) buffer;
#endif
/* Copy context->state[] to working vars */
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
/* 4 rounds of 20 operations each. Loop unrolled. */
R0(a, b, c, d, e, 0);
R0(e, a, b, c, d, 1);
R0(d, e, a, b, c, 2);
R0(c, d, e, a, b, 3);
R0(b, c, d, e, a, 4);
R0(a, b, c, d, e, 5);
R0(e, a, b, c, d, 6);
R0(d, e, a, b, c, 7);
R0(c, d, e, a, b, 8);
R0(b, c, d, e, a, 9);
R0(a, b, c, d, e, 10);
R0(e, a, b, c, d, 11);
R0(d, e, a, b, c, 12);
R0(c, d, e, a, b, 13);
R0(b, c, d, e, a, 14);
R0(a, b, c, d, e, 15);
R1(e, a, b, c, d, 16);
R1(d, e, a, b, c, 17);
R1(c, d, e, a, b, 18);
R1(b, c, d, e, a, 19);
R2(a, b, c, d, e, 20);
R2(e, a, b, c, d, 21);
R2(d, e, a, b, c, 22);
R2(c, d, e, a, b, 23);
R2(b, c, d, e, a, 24);
R2(a, b, c, d, e, 25);
R2(e, a, b, c, d, 26);
R2(d, e, a, b, c, 27);
R2(c, d, e, a, b, 28);
R2(b, c, d, e, a, 29);
R2(a, b, c, d, e, 30);
R2(e, a, b, c, d, 31);
R2(d, e, a, b, c, 32);
R2(c, d, e, a, b, 33);
R2(b, c, d, e, a, 34);
R2(a, b, c, d, e, 35);
R2(e, a, b, c, d, 36);
R2(d, e, a, b, c, 37);
R2(c, d, e, a, b, 38);
R2(b, c, d, e, a, 39);
R3(a, b, c, d, e, 40);
R3(e, a, b, c, d, 41);
R3(d, e, a, b, c, 42);
R3(c, d, e, a, b, 43);
R3(b, c, d, e, a, 44);
R3(a, b, c, d, e, 45);
R3(e, a, b, c, d, 46);
R3(d, e, a, b, c, 47);
R3(c, d, e, a, b, 48);
R3(b, c, d, e, a, 49);
R3(a, b, c, d, e, 50);
R3(e, a, b, c, d, 51);
R3(d, e, a, b, c, 52);
R3(c, d, e, a, b, 53);
R3(b, c, d, e, a, 54);
R3(a, b, c, d, e, 55);
R3(e, a, b, c, d, 56);
R3(d, e, a, b, c, 57);
R3(c, d, e, a, b, 58);
R3(b, c, d, e, a, 59);
R4(a, b, c, d, e, 60);
R4(e, a, b, c, d, 61);
R4(d, e, a, b, c, 62);
R4(c, d, e, a, b, 63);
R4(b, c, d, e, a, 64);
R4(a, b, c, d, e, 65);
R4(e, a, b, c, d, 66);
R4(d, e, a, b, c, 67);
R4(c, d, e, a, b, 68);
R4(b, c, d, e, a, 69);
R4(a, b, c, d, e, 70);
R4(e, a, b, c, d, 71);
R4(d, e, a, b, c, 72);
R4(c, d, e, a, b, 73);
R4(b, c, d, e, a, 74);
R4(a, b, c, d, e, 75);
R4(e, a, b, c, d, 76);
R4(d, e, a, b, c, 77);
R4(c, d, e, a, b, 78);
R4(b, c, d, e, a, 79);
/* Add the working vars back into context.state[] */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
/* Wipe variables */
a = b = c = d = e = 0;
}
/* SHA1Init - Initialize new context */
void SHA1Init(SHA1_CTX * context)
{
/* SHA1 initialization constants */
context->state[0] = 0x67452301;
context->state[1] = 0xEFCDAB89;
context->state[2] = 0x98BADCFE;
context->state[3] = 0x10325476;
context->state[4] = 0xC3D2E1F0;
context->count[0] = context->count[1] = 0;
}
/* Run your data through this. */
void SHA1Update(SHA1_CTX * context, uchar * data, ulong len)
{
ulong i, j;
j = (context->count[0] >> 3) & 63;
if ((context->count[0] += len << 3) < (len << 3))
context->count[1]++;
context->count[1] += (len >> 29);
if ((j + len) > 63) {
memcpy(&context->buffer[j], data, (i = 64 - j));
SHA1Transform(context->state, context->buffer);
for (; i + 63 < len; i += 64) {
SHA1Transform(context->state, &data[i]);
}
j = 0;
} else
i = 0;
memcpy(&context->buffer[j], &data[i], len - i);
}
/* Add padding and return the message digest. */
void SHA1Final(uchar digest[20], SHA1_CTX * context)
{
ulong i, j;
uchar finalcount[8];
for (i = 0; i < 8; i++) {
finalcount[i] = (uchar) ((context->count[(i >= 4 ? 0 : 1)]
>> ((3 - (i & 3)) * 8)) & 255);
}
SHA1Update(context, (uchar *) "\200", 1);
while ((context->count[0] & 504) != 448) {
SHA1Update(context, (uchar *) "\0", 1);
}
SHA1Update(context, finalcount, 8);
for (i = 0; i < 20; i++) {
digest[i] = (uchar)
((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
}
/* Wipe variables */
i = j = 0;
memset(context->buffer, 0, 64);
memset(context->state, 0, 20);
memset(context->count, 0, 8);
memset(&finalcount, 0, 8);
#ifdef SHA1HANDSOFF
SHA1Transform(context->state, context->buffer);
#endif
}
| 23.684492 | 63 | 0.496049 |
fc2366b3f77c88f2453b49ec5570296c537dd7dc | 89 | h | C | netbsd/sys/arch/hp700/include/kcore.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 91 | 2015-01-05T15:18:31.000Z | 2022-03-11T16:43:28.000Z | netbsd/sys/arch/hp700/include/kcore.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 1 | 2016-02-25T15:57:55.000Z | 2016-02-25T16:01:02.000Z | netbsd/sys/arch/hp700/include/kcore.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 21 | 2015-02-07T08:23:07.000Z | 2021-12-14T06:01:49.000Z | /* $NetBSD: kcore.h,v 1.1 2002/06/06 19:48:09 fredette Exp $ */
#include <hppa/kcore.h>
| 22.25 | 63 | 0.640449 |
76d61cea18cd50b456b2005a156fcb12db22f6b9 | 484 | h | C | GameEngineCore/LightmapSet.h | csyonghe/spire-engine | 9c98b277a6643688365f9ce308e8621d90af9c97 | [
"MIT"
] | 42 | 2020-06-06T13:54:11.000Z | 2022-03-21T20:29:48.000Z | GameEngineCore/LightmapSet.h | csyonghe/spire-engine | 9c98b277a6643688365f9ce308e8621d90af9c97 | [
"MIT"
] | 2 | 2020-05-19T21:50:27.000Z | 2020-05-31T15:54:07.000Z | GameEngineCore/LightmapSet.h | csyonghe/spire-engine | 9c98b277a6643688365f9ce308e8621d90af9c97 | [
"MIT"
] | 5 | 2020-06-06T12:57:18.000Z | 2021-11-13T16:35:57.000Z | #ifndef GAME_ENGINE_LIGHTMAP_SET_H
#define GAME_ENGINE_LIGHTMAP_SET_H
#include "CoreLib/Basic.h"
#include "ObjectSpaceMapSet.h"
namespace GameEngine
{
class Actor;
class Level;
struct LightmapSet
{
CoreLib::List<RawObjectSpaceMap> Lightmaps;
CoreLib::Dictionary<Actor*, int> ActorLightmapIds;
void SaveToFile(Level* level, CoreLib::String fileName);
void LoadFromFile(Level* level, CoreLib::String fileName);
};
}
#endif | 22 | 66 | 0.702479 |
748b26a21de8c82834d8da4b30e096c991fea423 | 330 | h | C | src/evol/Rng.h | mpohl100/Blackjack | 73646ff39015784f864ec32aed81dce6c15cf99b | [
"Apache-2.0"
] | null | null | null | src/evol/Rng.h | mpohl100/Blackjack | 73646ff39015784f864ec32aed81dce6c15cf99b | [
"Apache-2.0"
] | null | null | null | src/evol/Rng.h | mpohl100/Blackjack | 73646ff39015784f864ec32aed81dce6c15cf99b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <random>
#include <stack>
namespace evol{
class Rng{
public:
Rng();
std::stack<int> fetchUniform(int from, int to, size_t num) const;
std::stack<double> fetchNormal( double expValue, double stdDev, size_t num) const;
private:
std::random_device rd_;
mutable std::mt19937 gen_;
};
}
| 15.714286 | 86 | 0.684848 |
20cf578703b35b3b599f8be92be68f9fee9c9c16 | 12,143 | c | C | src/cfile.c | jahnf/cranberry-server | 30f50f9ff267b530b6d8e3d85f4a29e81d370538 | [
"MIT"
] | 1 | 2015-10-21T02:52:39.000Z | 2015-10-21T02:52:39.000Z | src/cfile.c | jahnf/cranberry-server | 30f50f9ff267b530b6d8e3d85f4a29e81d370538 | [
"MIT"
] | 4 | 2016-01-22T12:27:25.000Z | 2016-01-22T12:37:47.000Z | src/cfile.c | jahnf/cranberry-server | 30f50f9ff267b530b6d8e3d85f4a29e81d370538 | [
"MIT"
] | null | null | null | /* cranberry-server
* https://github.com/jahnf/cranberry-server
* For licensing see LICENSE file or
* https://github.com/jahnf/cranberry-server/blob/master/LICENSE
*/
/** @addtogroup cfile
* @{
* @file cfile.c
*/
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <dirent.h>
#include <limits.h>
#include <pwd.h>
#endif
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "cfile.h"
const char * cfile_get_tempdir()
{
static const char * tempdir = NULL;
#ifdef _WIN32
static char tmp_fallback[MAX_PATH+1];
#else
static const char tmp_fallback[] = "/tmp";
#endif
if( !tempdir ) {
tempdir = getenv("TEMP");
if(!tempdir )
tempdir = getenv("TMP");
if(!tempdir )
tempdir = getenv("TMPDIR");
#ifdef _WIN32
if(!tempdir) {
DWORD v = GetTempPath( MAX_PATH, tmp_fallback);
if( v && v < sizeof(tmp_fallback) )
tempdir = tmp_fallback;
} else if( strlen(tempdir) < sizeof(tmp_fallback) ) {
strcpy( tmp_fallback, tempdir );
tempdir = tmp_fallback;
}
#else
if(!tempdir)
tempdir = tmp_fallback;
#endif
}
return tempdir;
}
const char * cfile_get_homedir()
{
static const char * homedir = NULL;
#ifdef _WIN32
char *homedrive = 0, *homepath = 0;
static char homedir_win[2048];
#else
struct passwd *pwd;
static const char hd_fallback[] = "/";
#endif
#ifdef _WIN32
if( !homedir ) {
homedrive = getenv("HOMEDRIVE");
if(!homedrive) homedrive = "C:";
homepath = getenv("HOMEPATH");
strcpy(homedir_win, homedrive);
if(homepath) strcpy(&homedir_win[strlen(homedrive)], homepath);
homedir = homedir_win;
}
#else
if( !homedir ) {
homedir = getenv("HOME");
if(!homedir) {
pwd = getpwuid(getuid());
if(pwd && pwd->pw_dir)
homedir = pwd->pw_dir;
}
if(!homedir) homedir = hd_fallback;
}
#endif
return homedir;
}
int cfile_getstat( const char *filename, cfile_stat_t *cst )
{
struct stat st;
if( stat( filename, &st ) != 0 ) {
return CFILE_DOES_NOT_EXIST;
}
cst->size = st.st_size;
if( st.st_mode & S_IFDIR )
cst->type = CFILE_TYPE_DIR;
else if( st.st_mode & S_IFREG )
cst->type = CFILE_TYPE_REGULAR;
else
cst->type = CFILE_TYPE_UNKNOWN;
return CFILE_SUCCESS;
}
void cfile_item_free( cfile_item_t *cf_item )
{
cfile_item_t *tmp;
while( cf_item ) {
if( cf_item != cf_item->children )
cfile_item_free( cf_item->children );
tmp = cf_item;
cf_item = cf_item->next;
free( tmp->name );
free( tmp );
}
}
/** Create a new CFILE item and prepend it to a given item. */
cfile_item_t * cfile_item_prepend( const char *name, cfile_item_t *parent,
cfile_item_t *prependto )
{
cfile_item_t *item;
if( (item = malloc( sizeof(cfile_item_t) )) ) {
memset( item, 0, sizeof(cfile_item_t) );
if( name ) {
item->name = malloc( strlen(name) + 1 );
strcpy( item->name, name );
}
item->next = prependto;
}
return item;
}
/** Create a new CFILE item. */
cfile_item_t * cfile_item_new( const char *name, cfile_item_t *parent )
{
return cfile_item_prepend( name, parent, NULL );
}
static int _stat_to_cfile_attr( struct stat *fattr )
{
unsigned int drwx[4] = {0,0,0,0};
drwx[0] = fattr->st_mode & S_IFDIR;
#ifdef _WIN32
drwx[1] = fattr->st_mode & S_IREAD;
drwx[2] = fattr->st_mode & S_IWRITE;
drwx[3] = fattr->st_mode & S_IEXEC;
#else
drwx[1] = fattr->st_mode & S_IROTH;
drwx[2] = fattr->st_mode & S_IWOTH;
drwx[3] = fattr->st_mode & S_IXOTH;
if( !drwx[0] && drwx[1] && drwx[2] ) return CFILE_ACCESS_RW;
if( drwx[0] && drwx[1] && drwx[2] && drwx[3] ) return CFILE_ACCESS_RW;
if( fattr->st_gid == getegid() ) {
drwx[1] |= fattr->st_mode & S_IRGRP;
drwx[2] |= fattr->st_mode & S_IWGRP;
drwx[3] |= fattr->st_mode & S_IXGRP;
}
if( !drwx[0] && drwx[1] && drwx[2] ) return CFILE_ACCESS_RW;
if( drwx[0] && drwx[1] && drwx[2] && drwx[3] ) return CFILE_ACCESS_RW;
if( fattr->st_uid == geteuid() ) {
drwx[1] |= fattr->st_mode & S_IRUSR;
drwx[2] |= fattr->st_mode & S_IWUSR;
drwx[3] |= fattr->st_mode & S_IXUSR;
}
#endif
if( !drwx[0] ) {
if( drwx[1] ) {
if( drwx[2] ) return CFILE_ACCESS_RW;
return CFILE_ACCESS_RO;
}
if( drwx[2] ) return CFILE_ACCESS_WO;
}
else if( drwx[3] ) {
if( drwx[1] ) {
if( drwx[2] ) return CFILE_ACCESS_RW;
return CFILE_ACCESS_RO;
}
if( drwx[2] ) return CFILE_ACCESS_WO;
}
return CFILE_ACCESS_NA;
}
/* Local string compare function. */
static int ___compare (const char *a, const char *b)
{
/* Don't use the first dot for sorting...: */
if( *a == '.' ) ++a;
if( *b == '.' ) ++b;
#ifdef _WIN32
return _stricmp( a, b );
#else
return strcasecmp( a, b );
#endif
}
/* File & directory listing... */
cfile_item_t * cfile_list_dir( const char *path, cfile_item_t *parent )
{
cfile_item_t *new_list = NULL;
size_t path_len = strlen(path);
int path_has_trailing_slash = path_len?(path[path_len-1] == DIR_SEP):0;
#ifdef _WIN32
char buf[MAX_PATH];
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
strcpy( buf, path );
if( !path_has_trailing_slash ) {
strcpy( &buf[path_len], DIR_SEP_STR );
++path_len;
}
strcpy( &buf[path_len], "*" );
hFind = FindFirstFile( buf, &ffd );
if (INVALID_HANDLE_VALUE != hFind) {
cfile_item_t *prev = NULL;
do
{
cfile_item_t *new_item = cfile_item_new( ffd.cFileName, parent );
#else /* linux, posix ...*/
DIR *dp = opendir( path );
if (dp != NULL)
{
struct dirent *ep;
char buf[PATH_MAX];
strcpy( buf, path );
if( !path_has_trailing_slash ) {
strcpy( &buf[path_len], DIR_SEP_STR );
++path_len;
}
while( (ep = readdir(dp)) ) {
cfile_item_t *new_item = cfile_item_new( ep->d_name, parent );
#endif
if( new_list == NULL ) {
new_list = new_item;
} else {
cfile_item_t *it = new_list, *prev = NULL;
for( ; it; prev=it, it=it->next ) {
if( ___compare( new_item->name, it->name ) < 0 ) {
new_item->next = it;
if( it == new_list ) new_list = new_item;
else prev->next = new_item;
break;
}
}
if( it == NULL ) prev->next = new_item;
}
#ifdef _WIN32
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
new_item->type = CFILE_TYPE_DIR;
}
else
{
/* filesize.LowPart = ffd.nFileSizeLow; */
/* filesize.HighPart = ffd.nFileSizeHigh; */
printf("@ %s xbytes\n", ffd.cFileName/*, filesize.QuadPart*/);
new_item->type = CFILE_TYPE_REGULAR;
}
prev = new_item;
{
struct stat fattr;
strcpy( buf, path );
if( !path_has_trailing_slash ) strcat( buf, DIR_SEP_STR );
strcat( buf, new_item->name );
if( 0 == stat( buf, &fattr ) ) {
new_item->access = _stat_to_cfile_attr(&fattr);
if( new_item->type == CFILE_TYPE_REGULAR || new_item->type == CFILE_TYPE_LNKFILE ) {
new_item->size = fattr.st_size;
}
}
else new_item->access = CFILE_ACCESS_NA;
}
}
while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
} else /* findfirst failure TODO - error handling */ ;
#else /* Linux/_nix */
switch( ep->d_type ){
case DT_DIR: new_item->type = CFILE_TYPE_DIR; break;
case DT_LNK: new_item->type = CFILE_TYPE_LINK; break;
case DT_REG: new_item->type = CFILE_TYPE_REGULAR; break;
default:
/* a file type we dont support */
new_item->type = CFILE_TYPE_UNKNOWN;
break;
}
/* Read in basic file attributes. */
{
struct stat fattr;
strcpy( &buf[path_len], new_item->name );
if( 0 == stat( buf, &fattr ) ) {
new_item->access = _stat_to_cfile_attr(&fattr);
if( new_item->type != CFILE_TYPE_UNKNOWN ) {
if( new_item->type == CFILE_TYPE_LINK ) {
if( fattr.st_mode & S_IFDIR )
new_item->type = CFILE_TYPE_LNKDIR;
else if( fattr.st_mode & S_IFREG )
new_item->type = CFILE_TYPE_LNKFILE;
}
} else {
if( fattr.st_mode & S_IFDIR ) {
if( fattr.st_mode & S_IFLNK )
new_item->type = CFILE_TYPE_LNKDIR;
else
new_item->type = CFILE_TYPE_DIR;
} else if( fattr.st_mode & S_IFREG ) {
if( fattr.st_mode & S_IFLNK )
new_item->type = CFILE_TYPE_LNKFILE;
else
new_item->type = CFILE_TYPE_REGULAR;
}
}
if( new_item->type == CFILE_TYPE_REGULAR
|| new_item->type == CFILE_TYPE_LNKFILE ) {
new_item->size = fattr.st_size;
}
}
else new_item->access = CFILE_ACCESS_NA;
}
}
}
(void) closedir (dp);
#endif
return new_list;
}
cfile_item_t * cfile_get_drives()
{
cfile_item_t *new_list = NULL;
#ifdef _WIN32
#define BUFFERSIZE 4096
char buf[BUFFERSIZE];
struct stat fattr;
size_t i, ret = GetLogicalDriveStrings( BUFFERSIZE, buf );
cfile_item_t *new_item, *prev = NULL;
for( i = 0; i < ret; ++i ) {
if( 0 == stat( &buf[i], &fattr ) ) {
new_item = cfile_item_new( &buf[i], NULL );
if( new_list == NULL ) new_list = new_item;
else prev->next = new_item;
new_item->access = _stat_to_cfile_attr(&fattr);
new_item->type = CFILE_TYPE_DRIVE;
prev = new_item;
}
i+=strlen( &buf[i] );
}
#else /* Linux/Posix ...*/
struct stat fattr;
if( 0 == stat( "/", &fattr ) ) {
new_list = cfile_item_new( "/", NULL );
new_list->access = _stat_to_cfile_attr(&fattr);
new_list->type = CFILE_TYPE_DRIVE;
}
#endif
return new_list;
}
/** @} */ | 30.819797 | 108 | 0.482747 |
dd5281173e3d7ed6ac0c4bec792e59a3ee34aaa1 | 2,090 | h | C | rfc/threads/KTimer.h | hasaranga/RFC-Framework | 9c1881d412db6f9f7670b910a0918a631208cfd1 | [
"MIT"
] | 9 | 2017-10-02T08:15:50.000Z | 2021-08-09T21:29:46.000Z | rfc/threads/KTimer.h | hasaranga/RFC-Framework | 9c1881d412db6f9f7670b910a0918a631208cfd1 | [
"MIT"
] | 1 | 2021-09-18T07:38:53.000Z | 2021-09-26T12:11:48.000Z | rfc/threads/KTimer.h | hasaranga/RFC-Framework | 9c1881d412db6f9f7670b910a0918a631208cfd1 | [
"MIT"
] | 8 | 2017-10-02T13:21:29.000Z | 2021-07-30T09:35:31.000Z |
/*
RFC - KTimer.h
Copyright (C) 2013-2019 CrownSoft
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef _RFC_KTIMER_H_
#define _RFC_KTIMER_H_
#include "KTimerListener.h"
#include "../gui/KWindow.h"
#include <windows.h>
#include "../containers/KLeakDetector.h"
/**
Encapsulates a timer.
The timer can be started with the StartTimer() method
and controlled with various other methods. Before you start timer, you must set
timer window by calling SetTimerWindow method.
*/
class KTimer
{
protected:
UINT timerID;
int resolution;
bool started;
KWindow *window;
KTimerListener *listener;
public:
KTimer();
/**
@param resolution timer interval
*/
virtual void SetInterval(int resolution);
virtual int GetInterval();
/**
Call this method before you start timer
*/
virtual void SetTimerWindow(KWindow *window);
virtual void SetTimerID(UINT timerID);
/**
@returns unique id of this timer
*/
virtual UINT GetTimerID();
/**
Starts timer
*/
virtual void StartTimer();
/**
Stops the timer. You can restart it by calling StartTimer() method.
*/
virtual void StopTimer();
virtual void SetListener(KTimerListener *listener);
virtual bool IsTimerRunning();
virtual void OnTimer();
virtual ~KTimer();
private:
RFC_LEAK_DETECTOR(KTimer)
};
#endif | 22.473118 | 81 | 0.744976 |
dd623e03754c7f3469821da6fb4845d0d4543361 | 3,697 | h | C | release/src/linux/linux/include/asm-arm/sl811-hw.h | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 278 | 2015-11-03T03:01:20.000Z | 2022-01-20T18:21:05.000Z | release/src/linux/linux/include/asm-arm/sl811-hw.h | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 374 | 2015-11-03T12:37:22.000Z | 2021-12-17T14:18:08.000Z | release/src/linux/linux/include/asm-arm/sl811-hw.h | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 96 | 2015-11-22T07:47:26.000Z | 2022-01-20T19:52:19.000Z | /*
File: include/asm-arm/sl811-hw.h
19.09.2003 hne@ist1.de
Use Kernel 2.4.20 and this source from 2.4.22
Splitt hardware depens into file sl811-x86.h and sl811-arm.h.
Functions as inline.
23.09.2003 hne
Move Hardware depend header sl811-arm.h into include/asm-arm/sl811-hw.h.
GPRD as parameter.
24.09.2003 hne
Use Offset from ADDR to DATA instand of direct io.
03.10.2003 hne
Low level only for port io into hardware-include.
*/
#ifndef __LINUX_SL811_HW_H
#define __LINUX_SL811_HW_H
#define MAX_CONTROLERS 1 /* Max number of sl811 controllers */
/* Always 1 for this architecture! */
#define SIZEOF_IO_REGION 1 /* Size for request/release region */
#define OFFSET_DATA_REG data_off /* Offset from ADDR_IO to DATA_IO (future) */
/* Can change by arg */
static int io = 0xf100000e; /* Base addr_io */
static int data_off = 1; /* Offset from addr_io to addr_io */
static int irq = 44; /* also change gprd !!! */
static int gprd = 23; /* also change irq !!! */
MODULE_PARM(io,"i");
MODULE_PARM_DESC(io,"sl811 address io port 0xf100000e");
MODULE_PARM(data_off,"i");
MODULE_PARM_DESC(data_off,"sl811 data io port offset from address port (default 1)");
MODULE_PARM(irq,"i");
MODULE_PARM_DESC(irq,"sl811 irq 44(default)");
MODULE_PARM(gprd,"i");
MODULE_PARM_DESC(gprd,"sl811 GPRD port 23(default)");
/*
* Low level: Read from Data port [arm]
*/
static __u8 inline sl811_read_data (struct sl811_hc *hc)
{
__u8 data;
data = readb(hc->data_io);
rmb();
return data;
}
/*
* Low level: Write to index register [arm]
*/
static void inline sl811_write_index (struct sl811_hc *hc, __u8 index)
{
writeb(index, hc->addr_io);
wmb();
}
/*
* Low level: Write to Data port [arm]
*/
static void inline sl811_write_data (struct sl811_hc *hc, __u8 data)
{
writeb(data, hc->data_io);
wmb();
}
/*
* Low level: Write to index register and data port [arm]
*/
static void inline sl811_write_index_data (struct sl811_hc *hc, __u8 index, __u8 data)
{
writeb(index, hc->addr_io);
writeb(data, hc->data_io);
wmb();
}
/*
* This function is board specific. It sets up the interrupt to
* be an edge trigger and trigger on the rising edge
*/
static void inline sl811_init_irq(void)
{
GPDR &= ~(1<<gprd);
set_GPIO_IRQ_edge(1<<gprd, GPIO_RISING_EDGE);
}
/*****************************************************************
*
* Function Name: release_regions [arm]
*
* This function is board specific. It release all io address
* from memory (if can).
*
* Input: struct sl811_hc * *
*
* Return value : 0 = OK
*
*****************************************************************/
static void inline sl811_release_regions(struct sl811_hc *hc)
{
if (hc->addr_io)
release_region(hc->addr_io, SIZEOF_IO_REGION);
hc->addr_io = 0;
if (hc->data_io)
release_region(hc->data_io, SIZEOF_IO_REGION);
hc->data_io = 0;
}
/*****************************************************************
*
* Function Name: request_regions [arm]
*
* This function is board specific. It request all io address and
* maps into memory (if can).
*
* Input: struct sl811_hc *
*
* Return value : 0 = OK
*
*****************************************************************/
static int inline sl811_request_regions (struct sl811_hc *hc, int addr_io, int data_io, const char *name)
{
if (!request_region(addr_io, SIZEOF_IO_REGION, name)) {
PDEBUG(3, "request address %d failed", addr_io);
return -EBUSY;
}
hc->addr_io = addr_io;
if (!request_region(data_io, SIZEOF_IO_REGION, MODNAME)) {
PDEBUG(3, "request address %d failed", data_io);
/* release_region(hc->addr_io, SIZEOF_IO_REGION); */
return -EBUSY;
}
hc->data_io = data_io;
return 0;
}
#endif // __LINUX_SL811_HW_H
| 24.812081 | 105 | 0.653773 |
1c82b424207d5c37a3886369ae76ddc6ec9daa43 | 912 | h | C | usr/libexec/gamed/GKEntitlements.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | 2 | 2021-04-15T10:50:21.000Z | 2021-08-19T19:00:09.000Z | usr/sbin/usr/libexec/gamed/GKEntitlements.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | null | null | null | usr/sbin/usr/libexec/gamed/GKEntitlements.h | lechium/tvOS144Headers | e22dcf52662ae03002e3a6d57273f54e74013cb0 | [
"MIT"
] | null | null | null | //
// 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 Steve Nygard.
//
#import <objc/NSObject.h>
@interface GKEntitlements : NSObject
{
unsigned long long _entitlements; // 8 = 0x8
}
- (_Bool)_shouldBypasAuthenticationForConnection:(id)arg1; // IMP=0x00000001000cf99c
- (_Bool)hasAnyPrivateEntitlement; // IMP=0x00000001000cf988
- (_Bool)hasAnyEntitlement; // IMP=0x00000001000cf980
- (_Bool)hasEntitlements:(unsigned long long)arg1; // IMP=0x00000001000cf970
- (id)fullEntitlements; // IMP=0x00000001000cf960
- (id)initWithConnection:(id)arg1; // IMP=0x00000001000cf870
- (unsigned long long)_valuesForEntitlement:(id)arg1 forConnection:(id)arg2; // IMP=0x00000001000cf6b0
- (id)description; // IMP=0x00000001000cf4bc
- (unsigned long long)_entitlementForName:(id)arg1; // IMP=0x00000001000cf3b8
@end
| 35.076923 | 120 | 0.758772 |
c1e082060e6dbe01ded0636591b5e1bd624d8189 | 993 | h | C | RockBuster/Player.h | Mateusz1223/RockBuster | 6261391425188059baf79e892272fc19ce50c26d | [
"MIT"
] | 1 | 2021-04-17T09:49:18.000Z | 2021-04-17T09:49:18.000Z | RockBuster/Player.h | Mateusz1223/RockBuster | 6261391425188059baf79e892272fc19ce50c26d | [
"MIT"
] | null | null | null | RockBuster/Player.h | Mateusz1223/RockBuster | 6261391425188059baf79e892272fc19ce50c26d | [
"MIT"
] | null | null | null | #pragma once
#include "common.h"
#include "TexturePack.h"
class Player
{
private:
// Player body
sf::RectangleShape body;
// Logic variables
float maxSpeed; // always positive value
float speed;
float acceleration;
unsigned int points;
unsigned int healthPoints;
// Private funtions
void initVariables(sf::Vector2f size, float maxSpeed);
void initBody(sf::Vector2f size);
public:
Player(sf::Vector2f size, sf::Vector2f position, float maxSpeed);
~Player();
// Accessors
sf::Vector2f getPosition(); // don't needed
sf::FloatRect getBounds();
unsigned int getPoints();
unsigned int getHealthPoints();
float getSpeed();
// Public Funtions
void setPosition(sf::Vector2f position);
void setTexture(sf::Texture& texture);
void useLeftEngine();
void useRightEngine();
void stop();
void addPoints(unsigned int p); // takes amount of points to be added
void takeDamage();
void takeHealthPointsBonus();
void update();
void render(sf::RenderTarget& target);
};
| 19.096154 | 70 | 0.728097 |
e3ecdb7944bb0d42436112c0d2b2f95e005df680 | 2,060 | h | C | include/uml/activityGroup.h | nemears/uml-cpp | d72c8b5506f391f2b6a5696972ff8da7ec10bd21 | [
"MIT"
] | null | null | null | include/uml/activityGroup.h | nemears/uml-cpp | d72c8b5506f391f2b6a5696972ff8da7ec10bd21 | [
"MIT"
] | 1 | 2022-02-25T18:14:21.000Z | 2022-03-10T08:59:55.000Z | include/uml/activityGroup.h | nemears/uml-cpp | d72c8b5506f391f2b6a5696972ff8da7ec10bd21 | [
"MIT"
] | null | null | null | #ifndef _UML_ACTIVITY_GROUP_H_
#define _UML_ACTIVITY_GROUP_H_
#include "activityNode.h"
#include "activityEdge.h"
namespace UML {
class ActivityGroup;
typedef UmlPtr<Activity> ActivityPtr;
typedef UmlPtr<ActivityGroup> ActivityGroupPtr;
class ActivityGroup : public NamedElement {
friend class Activity;
protected:
Singleton<Activity, ActivityGroup> m_inActivity = Singleton<Activity, ActivityGroup>(this);
Singleton<ActivityGroup, ActivityGroup> m_superGroup = Singleton<ActivityGroup, ActivityGroup>(this);
Set<ActivityNode, ActivityGroup> m_containedNodes = Set<ActivityNode, ActivityGroup>(this);
Set<ActivityEdge, ActivityGroup> m_containedEdges = Set<ActivityEdge, ActivityGroup>(this);
Set<ActivityGroup, ActivityGroup> m_subGroups = Set<ActivityGroup, ActivityGroup>(this);
Set<Activity, ActivityGroup>& getInActivitySingleton();
Set<ActivityGroup, ActivityGroup>& getSuperGroupSingleton();
void referencingReleased(ID id) override;
void referenceReindexed(ID oldID, ID newID) override;
void reindexName(ID id, std::string newName) override;
void referenceErased(ID id) override;
void init();
ActivityGroup();
public:
virtual ~ActivityGroup();
ActivityPtr getInActivity() const;
void setInActivity(Activity* inActivity);
void setInActivity(Activity& inActivity);
void setInActivity(ActivityPtr inActivity);
void setInActivity(ID id);
ActivityGroupPtr getSuperGroup() const;
Set<ActivityNode, ActivityGroup>& getContainedNodes();
Set<ActivityEdge, ActivityGroup>& getContainedEdges();
Set<ActivityGroup, ActivityGroup>& getSubGroups();
bool isSubClassOf(ElementType eType) const override;
static ElementType elementType() {
return ElementType::ACTIVITY_GROUP;
};
};
}
#endif | 42.040816 | 113 | 0.669903 |
6e31ed070070d20e743a198cbfa67c3afc870e9a | 911 | h | C | BTE/Tools/HttpTool/YQNetworking/Cache/YQDiskCache.h | sophiemarceau/bte_iOS | 3e44be16be9559709e5dfbe24855f929e68832b1 | [
"MIT"
] | 1 | 2022-02-08T06:42:11.000Z | 2022-02-08T06:42:11.000Z | ISSCloudTools/ISSCloudTools/ISSCloudTool/Tools/YQNetworking/Cache/YQDiskCache.h | zzxdx/ISSCloudTools | 42d2517bc80cb4517aee1970a75059b14e587ead | [
"MIT"
] | 1 | 2021-11-12T02:04:11.000Z | 2021-11-12T02:04:11.000Z | ISSCloudTools/ISSCloudTools/ISSCloudTool/Tools/YQNetworking/Cache/YQDiskCache.h | zzxdx/ISSCloudTools | 42d2517bc80cb4517aee1970a75059b14e587ead | [
"MIT"
] | null | null | null | //
// YQDiskCache.h
// YQNetworking
//
// Created by yingqiu huang on 2017/2/10.
// Copyright © 2017年 yingqiu huang. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface YQDiskCache : NSObject
/**
* 将数据写入磁盘
*
* @param data 数据
* @param directory 目录
* @param filename 文件名
*/
+ (void)writeData:(id)data
toDir:(NSString *)directory
filename:(NSString *)filename;
/**
* 从磁盘读取数据
*
* @param directory 目录
* @param filename 文件名
*
* @return 数据
*/
+ (id)readDataFromDir:(NSString *)directory
filename:(NSString *)filename;
/**
* 获取目录中文件总大小
*
* @param directory 目录名
*
* @return 文件总大小
*/
+ (NSUInteger)dataSizeInDir:(NSString *)directory;
/**
* 清理目录中的文件
*
* @param directory 目录名
*/
+ (void)clearDataIinDir:(NSString *)directory;
/**
* 删除某文件
*
* @param fileUrl 文件路径
*/
+ (void)deleteCache:(NSString *)fileUrl;
@end
| 15.706897 | 57 | 0.620198 |
f56ef37143c61445cee5c294dfc29d2104f66673 | 487 | h | C | src/RakNet/include/RouterInterface.h | tomazas/open-bomber | ddbcbd701f1440acb579f8927dee02701dc44b7c | [
"MIT"
] | 1 | 2016-06-28T18:19:30.000Z | 2016-06-28T18:19:30.000Z | src/RakNet/include/RouterInterface.h | tomazas/open-bomber | ddbcbd701f1440acb579f8927dee02701dc44b7c | [
"MIT"
] | null | null | null | src/RakNet/include/RouterInterface.h | tomazas/open-bomber | ddbcbd701f1440acb579f8927dee02701dc44b7c | [
"MIT"
] | null | null | null | #ifndef __ROUTER_INTERFACE_H
#define __ROUTER_INTERFACE_H
#include "Export.h"
#include "RakNetTypes.h"
/// On failed directed sends, RakNet can call an alternative send function to use.
class RAK_DLL_EXPORT RouterInterface
{
public:
RouterInterface() {}
virtual ~RouterInterface() {}
virtual bool Send( const char *data, BitSize_t bitLength, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress )=0;
};
#endif
| 27.055556 | 170 | 0.765914 |
0ce372318581a173ff28756b0892cf5d63b56061 | 1,117 | h | C | lib/erlang/c_src/src/lib/cat_test.h | woozhijun/cat | 3d523202c38e37b1a2244b26d4336ebbea5db001 | [
"Apache-2.0"
] | 17,318 | 2015-01-03T03:02:07.000Z | 2022-03-31T02:43:28.000Z | lib/erlang/c_src/src/lib/cat_test.h | MrCoderYu/cat | 674bd9ab70267dd6fc74879e4344af77397f4acd | [
"Apache-2.0"
] | 1,162 | 2015-01-04T08:23:49.000Z | 2022-03-31T15:38:04.000Z | lib/erlang/c_src/src/lib/cat_test.h | MrCoderYu/cat | 674bd9ab70267dd6fc74879e4344af77397f4acd | [
"Apache-2.0"
] | 5,520 | 2015-01-03T03:02:07.000Z | 2022-03-31T16:16:56.000Z | //
// Created by Terence on 2018/10/18.
//
#ifndef CCAT_TEST_H
#define CCAT_TEST_H
static int g_assertions = 0;
static void inline _assert_null(void* ptr) {
g_assertions++;
if (NULL != ptr) {
printf("The pointer expected to be null, non-null value given.\n");
}
}
static void inline _assert_not_null(void* ptr) {
g_assertions++;
if (NULL == ptr) {
printf("The pointer expected to be non-null value, null given.\n");
}
}
static void inline _assert_int_eq(int expect, int actual) {
g_assertions++;
if (expect != actual) {
printf ("The given value expected to be %d, %d given.\n", expect, actual);
}
}
static void inline _assert_int_ne(int expect, int actual) {
g_assertions++;
if (expect == actual) {
printf ("The given value expected to be not equal to %d.\n", expect);
}
}
#define ASSERT_NULL(ptr) _assert_null(ptr)
#define ASSERT_NOT_NULL(ptr) _assert_not_null(ptr)
#define ASSERT_INT_EQ(expect, actual) _assert_int_eq(expect, actual)
#define ASSERT_INT_NE(expect, actual) _assert_int_ne(expect, actual)
#endif //CCAT_TEST_H
| 23.765957 | 82 | 0.675022 |
4938e03c308e548951ad0e41bd7960fbd77db4e2 | 3,618 | c | C | components/av/swresample/resample.c | 1847123212/YoC-open | f4e20c67256472d863ea6d118e3ecbaa1e879d4a | [
"Apache-2.0"
] | 9 | 2020-05-12T03:01:55.000Z | 2021-08-12T10:22:31.000Z | components/av/swresample/resample.c | 1847123212/YoC-open | f4e20c67256472d863ea6d118e3ecbaa1e879d4a | [
"Apache-2.0"
] | null | null | null | components/av/swresample/resample.c | 1847123212/YoC-open | f4e20c67256472d863ea6d118e3ecbaa1e879d4a | [
"Apache-2.0"
] | 12 | 2020-04-15T11:37:33.000Z | 2021-09-13T13:19:04.000Z | /*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include "avutil/common.h"
#include "swresample/resample.h"
#define TAG "resample"
static struct resx_ops *_res_ops;
/**
* @brief regist resample ops
* @param [in] ops
* @return 0/-1
*/
int resx_ops_register(const struct resx_ops *ops)
{
CHECK_PARAM(ops, -1);
if (_res_ops) {
LOGE(TAG, "error. ops had regist yet!, name = %s", _res_ops->name);
return -1;
}
_res_ops = (struct resx_ops*)ops;
LOGD(TAG, "regist resampler, name = %s", _res_ops->name);
return 0;
}
/**
* @brief new a resampler
* @param [in] irate : input sample rate
* @param [in] orate : output sample rate
* @param [in] channels : 1/2, mono/stereo
* @param [in] bits : 16 only
* @return NULL on error
*/
resx_t *resx_new(uint32_t irate, uint32_t orate, uint8_t channels, uint8_t bits)
{
int rc;
resx_t *r = NULL;
CHECK_PARAM((irate != orate), NULL);
CHECK_PARAM((bits == 16), NULL);
CHECK_PARAM(((channels == 1) || (channels == 2)), NULL);
if (!((irate == 8000) || (irate == 16000) || (irate == 32000)
|| (irate == 12000) || (irate == 24000) || (irate == 48000)
|| (irate == 11025) || (irate == 22050) || (irate == 44100))) {
LOGE(TAG, "irate is not support, irate = %d", irate);
return NULL;
}
if (!((orate == 8000) || (orate == 16000) || (orate == 32000)
|| (orate == 12000) || (orate == 24000) || (orate == 48000)
|| (orate == 11025) || (orate == 22050) || (orate == 44100))) {
LOGE(TAG, "orate is not support, orate = %d", orate);
return NULL;
}
r = aos_zalloc(sizeof(resx_t));
CHECK_RET_TAG_WITH_RET(r, NULL);
r->irate = irate;
r->orate = orate;
r->bits = bits;
r->channels = channels;
r->ops = _res_ops;
rc = r->ops->init(r);
CHECK_RET_TAG_WITH_GOTO(rc == 0, err);
aos_mutex_new(&r->lock);
return r;
err:
aos_free(r);
return NULL;
}
/**
* @brief get the max out samples number per channel
* @param [in] irate
* @param [in] orate
* @param [in] nb_isamples : number of input samples available in one channel
* @return -1 on error
*/
int resx_get_osamples_max(uint32_t irate, uint32_t orate, size_t nb_isamples)
{
int rc;
//FIXME: guess
CHECK_PARAM(irate && orate && nb_isamples, -1);
rc = (1.2 * orate / irate * nb_isamples);
rc = AV_ALIGN_SIZE(rc + 16, 16);
return irate == orate ? nb_isamples : rc;
}
/**
* @brief convert nb_samples from src to dst sample format
* @param [in] r
* @param [in] out
* @param [in] nb_osamples : amount of space available for output in samples per channels
* @param [in] in
* @param [in] nb_isamples : number of input samples available in one channels
* @return number of samples output per channels, -1 on error
*/
int resx_convert(resx_t *r, void **out, size_t nb_osamples, const void **in, size_t nb_isamples)
{
int rc, i;
CHECK_PARAM(r && out && in && nb_osamples && nb_isamples, -1);
for (i = 0; i < r->channels; i++) {
if (!(in[i] && out[i])) {
LOGE(TAG, "out/in params is err.");
return -1;
}
}
aos_mutex_lock(&r->lock, AOS_WAIT_FOREVER);
rc = r->ops->convert(r, out, nb_osamples, in, nb_isamples);
aos_mutex_unlock(&r->lock);
return rc;
}
/**
* @brief free the resample
* @param [in] r
* @return
*/
void resx_free(resx_t *r)
{
if (r) {
r->ops->uninit(r);
aos_mutex_free(&r->lock);
aos_free(r);
}
}
| 25.478873 | 96 | 0.574627 |
2961330152a4d34e6c6f9df4168e411e341b7bc8 | 5,275 | h | C | include/QtNetwork/qlocalsocket.h | 219-design/build_qt4_binaries_armv5tejl_sbc6000x | 0d33869719a56ce4e9c7009f825c7d3c79869f36 | [
"MIT"
] | null | null | null | include/QtNetwork/qlocalsocket.h | 219-design/build_qt4_binaries_armv5tejl_sbc6000x | 0d33869719a56ce4e9c7009f825c7d3c79869f36 | [
"MIT"
] | null | null | null | include/QtNetwork/qlocalsocket.h | 219-design/build_qt4_binaries_armv5tejl_sbc6000x | 0d33869719a56ce4e9c7009f825c7d3c79869f36 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information
** to ensure GNU General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html. In addition, as a special
** exception, Nokia gives you certain additional rights. These rights
** are described in the Nokia Qt GPL Exception version 1.3, included in
** the file GPL_EXCEPTION.txt in this package.
**
** Qt for Windows(R) Licensees
** As a special exception, Nokia, as the sole copyright holder for Qt
** Designer, grants users of the Qt/Eclipse Integration plug-in the
** right for the Qt/Eclipse Integration to link to functionality
** provided by Qt Designer and its related libraries.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
****************************************************************************/
#ifndef QLOCALSOCKET_H
#define QLOCALSOCKET_H
#include <QtCore/qiodevice.h>
#include <QtNetwork/qabstractsocket.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Network)
#ifndef QT_NO_LOCALSOCKET
class QLocalSocketPrivate;
class Q_NETWORK_EXPORT QLocalSocket : public QIODevice
{
Q_OBJECT
Q_DECLARE_PRIVATE(QLocalSocket)
public:
enum LocalSocketError
{
ConnectionRefusedError = QAbstractSocket::ConnectionRefusedError,
PeerClosedError = QAbstractSocket::RemoteHostClosedError,
ServerNotFoundError = QAbstractSocket::HostNotFoundError,
SocketAccessError = QAbstractSocket::SocketAccessError,
SocketResourceError = QAbstractSocket::SocketResourceError,
SocketTimeoutError = QAbstractSocket::SocketTimeoutError,
DatagramTooLargeError = QAbstractSocket::DatagramTooLargeError,
ConnectionError = QAbstractSocket::NetworkError,
UnsupportedSocketOperationError = QAbstractSocket::UnsupportedSocketOperationError,
UnknownSocketError = QAbstractSocket::UnknownSocketError
};
enum LocalSocketState
{
UnconnectedState = QAbstractSocket::UnconnectedState,
ConnectingState = QAbstractSocket::ConnectingState,
ConnectedState = QAbstractSocket::ConnectedState,
ClosingState = QAbstractSocket::ClosingState
};
QLocalSocket(QObject *parent = 0);
~QLocalSocket();
void connectToServer(const QString &name, OpenMode openMode = ReadWrite);
void disconnectFromServer();
QString serverName() const;
QString fullServerName() const;
void abort();
virtual bool isSequential() const;
virtual qint64 bytesAvailable() const;
virtual qint64 bytesToWrite() const;
virtual bool canReadLine() const;
virtual void close();
LocalSocketError error() const;
bool flush();
bool isValid() const;
qint64 readBufferSize() const;
void setReadBufferSize(qint64 size);
bool setSocketDescriptor(quintptr socketDescriptor,
LocalSocketState socketState = ConnectedState,
OpenMode openMode = ReadWrite);
quintptr socketDescriptor() const;
LocalSocketState state() const;
bool waitForBytesWritten(int msecs = 30000);
bool waitForConnected(int msecs = 30000);
bool waitForDisconnected(int msecs = 30000);
bool waitForReadyRead(int msecs = 30000);
Q_SIGNALS:
void connected();
void disconnected();
void error(QLocalSocket::LocalSocketError socketError);
void stateChanged(QLocalSocket::LocalSocketState socketState);
protected:
virtual qint64 readData(char*, qint64);
virtual qint64 writeData(const char*, qint64);
private:
Q_DISABLE_COPY(QLocalSocket)
#ifdef Q_OS_WIN
Q_PRIVATE_SLOT(d_func(), void _q_notified())
Q_PRIVATE_SLOT(d_func(), void _q_canWrite())
Q_PRIVATE_SLOT(d_func(), void _q_pipeClosed())
#else
Q_PRIVATE_SLOT(d_func(), void _q_stateChanged(QAbstractSocket::SocketState))
Q_PRIVATE_SLOT(d_func(), void _q_error(QAbstractSocket::SocketError))
Q_PRIVATE_SLOT(d_func(), void _q_connectToSocket())
Q_PRIVATE_SLOT(d_func(), void _q_abortConnectionAttempt())
#endif
};
#ifndef QT_NO_DEBUG_STREAM
#include <QtCore/qdebug.h>
Q_NETWORK_EXPORT QDebug operator<<(QDebug, QLocalSocket::LocalSocketError);
Q_NETWORK_EXPORT QDebug operator<<(QDebug, QLocalSocket::LocalSocketState);
#endif
#endif // QT_NO_LOCALSOCKET
QT_END_NAMESPACE
QT_END_HEADER
#endif // QLOCALSOCKET_H
| 34.933775 | 91 | 0.726445 |
51e9463b2fa9fc84419f4b596e75aabdc910b0e8 | 1,500 | h | C | src/include/cm/cm_server/cms_cn.h | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 1 | 2021-11-05T10:14:39.000Z | 2021-11-05T10:14:39.000Z | src/include/cm/cm_server/cms_cn.h | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | null | null | null | src/include/cm/cm_server/cms_cn.h | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* cms_cn.h
*
* IDENTIFICATION
* src/include/cm/cm_server/cms_cn.h
*
* -------------------------------------------------------------------------
*/
#ifndef CMS_CN_H
#define CMS_CN_H
#include "cm_server.h"
#ifdef ENABLE_MULTIPLE_NODES
void process_cm_to_agent_repair_ack(CM_Connection* con, uint32 group_index);
void process_agent_to_cm_coordinate_status_report_msg(
CM_Connection* con, agent_to_cm_coordinate_status_report* agent_to_cm_coordinate_status_ptr);
void process_ctl_to_cm_disable_cn(CM_Connection* con, ctl_to_cm_disable_cn* ctl_to_cm_disable_cn_ptr);
void process_agent_to_central_coordinate_status(
CM_Connection* con, const agent_to_cm_coordinate_status_report* report_msg, int group_index, uint32 count);
#endif
void SetBarrierInfo(agent_to_cm_coordinate_barrier_status_report* barrier_info);
#endif
| 37.5 | 112 | 0.687333 |
55416bc9c39f61d36ca1aff92e5aabce3bb60979 | 888 | h | C | src/hmm_calcerrorlod.h | gatarelib/qtl2 | 4aba67a3a43ca16888c18f913934098bb28895c0 | [
"RSA-MD"
] | null | null | null | src/hmm_calcerrorlod.h | gatarelib/qtl2 | 4aba67a3a43ca16888c18f913934098bb28895c0 | [
"RSA-MD"
] | null | null | null | src/hmm_calcerrorlod.h | gatarelib/qtl2 | 4aba67a3a43ca16888c18f913934098bb28895c0 | [
"RSA-MD"
] | null | null | null | // calculate genotyping error LOD scores
// (assumes constant is_female and cross_info and pre-calcs the step and emit matrices)
#ifndef HMM_CALCERRORLOD_H
#define HMM_CALCERRORLOD_H
#include <Rcpp.h>
Rcpp::NumericMatrix calc_errorlod(const Rcpp::String& crosstype,
const Rcpp::NumericVector& probs, // genotype probs [genotype, ind, marker]
const Rcpp::IntegerMatrix& genotypes, // columns are individuals, rows are markers
const Rcpp::IntegerMatrix& founder_geno, // columns are markers, rows are founder lines
const bool is_X_chr,
const bool is_female, // same for all individuals
const Rcpp::IntegerVector& cross_info); // same for all individuals
#endif // HMM_CALCERRORLOD_H
| 52.235294 | 121 | 0.61036 |
4ef315317855affd216d8ae359d523ff2f8c0b4c | 352 | h | C | Flix Application/Views/MovieCollectionCell.h | randrade13/Flix_Application | 6d0461fd8c48bb770b28207c41d259d3e6779ea1 | [
"Apache-2.0"
] | null | null | null | Flix Application/Views/MovieCollectionCell.h | randrade13/Flix_Application | 6d0461fd8c48bb770b28207c41d259d3e6779ea1 | [
"Apache-2.0"
] | 1 | 2019-07-02T03:01:16.000Z | 2019-07-02T03:01:16.000Z | Flix Application/Views/MovieCollectionCell.h | randrade13/Flix_Application | 6d0461fd8c48bb770b28207c41d259d3e6779ea1 | [
"Apache-2.0"
] | null | null | null | //
// MovieCollectionCell.h
// Flix Application
//
// Created by rodrigoandrade on 6/27/19.
// Copyright © 2019 rodrigoandrade. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface MovieCollectionCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *posterView;
@end
NS_ASSUME_NONNULL_END
| 18.526316 | 61 | 0.769886 |
b6fe5131e90cd168e36a8d3efb9a581a1db2bd44 | 679 | h | C | AmbaDemo/AmbaRemoteCam/wifiViewController.h | BFAlex/BFsTCPCommands | cf5c3bc3b0e3bc2191fc4977e0ef2e4d4730dd10 | [
"MIT"
] | null | null | null | AmbaDemo/AmbaRemoteCam/wifiViewController.h | BFAlex/BFsTCPCommands | cf5c3bc3b0e3bc2191fc4977e0ef2e4d4730dd10 | [
"MIT"
] | null | null | null | AmbaDemo/AmbaRemoteCam/wifiViewController.h | BFAlex/BFsTCPCommands | cf5c3bc3b0e3bc2191fc4977e0ef2e4d4730dd10 | [
"MIT"
] | null | null | null | //
// wifiViewController.h
// AmbaRemoteCam
//
// Created by (Ram Kumar) Ambarella
// Copyright (c) 2014 Ambarella. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ambaStateMachine.h"
@interface wifiViewController : UIViewController
@property (retain, nonatomic) NSMutableArray *defaultIP;
@property (retain, nonatomic) IBOutlet UITextField *cameraIPAddress;
@property (nonatomic) IBOutlet UIButton *tcpConnectButton;
@property (nonatomic) IBOutlet UIButton *cameraControlPanelButton;
@property (nonatomic) IBOutlet UILabel *conStatusLabel;
- (IBAction) connectToCamera:(id)sender;
- (IBAction) dismiss:(id)sender;
- (IBAction) textFieldReturn:(id)sender;
@end
| 27.16 | 68 | 0.771723 |
391612e8bfb574e22c7a04de285b8e6ab66a4058 | 1,450 | c | C | kernel/interrupts.c | puchake/odysseos | f78f43c97e58ea776d2d30bc6ab4fde5081dc536 | [
"MIT"
] | null | null | null | kernel/interrupts.c | puchake/odysseos | f78f43c97e58ea776d2d30bc6ab4fde5081dc536 | [
"MIT"
] | null | null | null | kernel/interrupts.c | puchake/odysseos | f78f43c97e58ea776d2d30bc6ab4fde5081dc536 | [
"MIT"
] | null | null | null | #include "interrupts.h"
#include "pic.h"
#include "keyboard.h"
#include "utilities.h"
volatile int timer_i = 0;
void timer_handler() {
timer_i++;
send_eoi(TIMER_IRQ);
}
void keystroke_handler() {;
if (keyboard_input_state == WAITING_FOR_KEYBOARD_INPUT) {
// Fill in the scancode buffer, if get_char is waiting for input.
char scancode_byte = 0;
char next_scancode_byte = inb(KEYBOARD_IN_PORT);
int buffer_i = 0;
zero_buffer(scancode_buffer, MAX_SCANCODE_LENGTH);
do {
scancode_buffer[buffer_i] = next_scancode_byte;
buffer_i += 1;
scancode_byte = next_scancode_byte;
next_scancode_byte = inb(KEYBOARD_IN_PORT);
}
while (next_scancode_byte != scancode_byte);
// Switch buffer and input states to signal that the keystroke has
// occured.
scancode_buffer_state = SCANCODE_BUFFER_FULL;
keyboard_input_state = IGNORE_KEYBOARD_INPUT;
}
else if (keyboard_input_state == WAITING_FOR_KEYBOARD_RESPONSE) {
// Handle keyboard command response.
scancode_buffer[0] = inb(KEYBOARD_IN_PORT);
keyboard_input_state = IGNORE_KEYBOARD_INPUT;
}
else {
// If nothing is waiting for input, simply read one byte from
// keyboard's port to prevent keyboard's interrupt from locking.
inb(KEYBOARD_IN_PORT);
}
send_eoi(KEYSTROKE_IRQ);
}
| 30.208333 | 74 | 0.66 |
fbe32d0781f142e68aeb088eea3769b9c12fa399 | 498 | h | C | gdm/gdm-2.6.0.5/gui/greeter/greeter_events.h | OneIdentity/rc-legacy | 6e247f55b7df6b1022819810ba3363a2db401f08 | [
"Apache-2.0"
] | null | null | null | gdm/gdm-2.6.0.5/gui/greeter/greeter_events.h | OneIdentity/rc-legacy | 6e247f55b7df6b1022819810ba3363a2db401f08 | [
"Apache-2.0"
] | null | null | null | gdm/gdm-2.6.0.5/gui/greeter/greeter_events.h | OneIdentity/rc-legacy | 6e247f55b7df6b1022819810ba3363a2db401f08 | [
"Apache-2.0"
] | null | null | null | #ifndef GREETER_EVENTS_H
#define GREETER_EVENTS_H
typedef void (*ActionFunc) (GreeterItemInfo *info,
gpointer user_data);
gint greeter_item_event_handler (GnomeCanvasItem *item,
GdkEvent *event,
gpointer data);
void greeter_item_register_action_callback (char *id,
ActionFunc func,
gpointer user_data);
void greeter_item_run_action_callback (const char *id);
#endif /* GREETER_EVENTS_H */
| 27.666667 | 66 | 0.644578 |
2560b43bddd98a15f2aa2355f17e467e6fbb150c | 9,299 | c | C | old codes/Ultimate linked list programe.c | ikaushikpal/C-practice | abab8a186eaf38b434811755833a32306cd47d64 | [
"MIT"
] | null | null | null | old codes/Ultimate linked list programe.c | ikaushikpal/C-practice | abab8a186eaf38b434811755833a32306cd47d64 | [
"MIT"
] | null | null | null | old codes/Ultimate linked list programe.c | ikaushikpal/C-practice | abab8a186eaf38b434811755833a32306cd47d64 | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*first=NULL;
void insert()
{
struct node *p,*q;
p=(struct node*)malloc(sizeof(struct node));
printf("enter value\n");
scanf("%d",&p->data);
p->next=NULL;
if(first==NULL)
{
first=p;
}
else
{
q=first;
while(q->next!=NULL)
{
q=q->next;
}
q->next=p;
}
}
void insert_beg()
{
struct node* p,*q;
p=(struct node*)malloc(sizeof(struct node));
printf("enter value for the node\n");
scanf("%d",&p->data);
q=first;
p->next=first;
first=p;
}
void insert_end()
{
struct node* p,*q;
p=(struct node*)malloc(sizeof(struct node));
printf("enter value for the node\n");
scanf("%d",&p->data);
p->next=NULL;
if(first==NULL)
{
first=p;
}
else
{
q=first;
while(q->next!=NULL)
{
q=q->next;
}
q->next=p;
}
}
void insert_pos()
{
int pos,val,i;
struct node *p,*q,*t;
p=first;
do
{
printf("enter location where you want to insert\n");
scanf("%d",&pos);
}while(pos<0 && pos>count(p));
printf("enter data\n");
scanf("%d",&val);
t=(struct node*)malloc(sizeof(struct node));
t->data=val;
t->next=NULL;
if(pos==1)
{
t->next=first;
first=t;
}
else
{
for(i=0;i<pos-1;i++)
{
q=p;
p=p->next;
}
q->next=t;
t->next=p;
}
}
void insert_sort()
{
int val;
printf("enter value\n");
scanf("%d",&val);
struct node *p,*q,*t;
p=first;
t=(struct node*)malloc(sizeof(struct node));
t->data=val;
t->next=NULL;
if(first==NULL)
{
first=t;
}
else
{
while(p->data<val)
{
q=p;
p=p->next;
}
if(first->data>val)
{
t->next=first;
first=t;
}
else
{
q->next=t;
t->next=p;
}
}
}
int count()
{
struct node *p=first;
int count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
printf("total node = %d\n",count);
}
void del_beg()
{
struct node *q;
q=first;
first=first->next;
free(q);
}
void del_end()
{
struct node *p,*q;
p=first;
while(p!=NULL)
{
q=p;
p=p->next;
}
q->next=NULL;
free(p);
}
void del_pos()
{
int pos,i;
label:
printf("which element do you want to delete? give index\n");
printf("counting from 1\n");
scanf("%d",&pos);
if(pos<=1)
{
printf("give higher index\n");
goto label;
}
struct node *p,*q;
p=first;
q=NULL;
for(i=0;i<pos-1&&p!=NULL;i++)
{
q=p;
p=p->next;
}
q->next=p->next;
free(p);
}
void display()
{
struct node* p=first;
if(p==NULL)
printf("! no nodes in the link list (empty)\n");
while(p!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
}
void chk_sort()
{
struct node* p;
int val=INT_MIN;
p=first;
if(p==NULL)
{
printf("empty list\n");
return;
}
else
while(p!=NULL)
{
if(p->data<val)
{
printf("link list is not sorted\n");
return;
}
else
{
val=p->data;
p=p->next;
}
}
printf("link list is sorted\n");
}
void sum()
{
struct node *p;
p=first;
int sum=0;
while(p!=NULL)
{
sum+=p->data;
p=p->next;
}
printf("sum of all nodes vales = %d\n",sum);
}
int min()
{
struct node *p=first;
int Min=INT_MAX;
if(p==NULL)
printf("link-list is empty\n");
else
{
while(p)
{
if(Min>p->data)
{
Min=p->data;
p=p->next;
}
p=p->next;
}
}
printf("minimum element in the link-list is = %d\n",Min);
}
int max()
{
struct node *p;
p=first;
int Max=INT_MIN;
if(p==NULL)
printf("link-list is empty\n");
else
{
do
{
if(p->data>Max)
{
Max=p->data;
p=p->next;
}
p=p->next;
}while(p->next!=NULL);
}
if(p!=NULL)
{
if(p->data>Max)
Max=p->data;
}
printf("maximum element in the link-list is = %d\n",Max);
}
void swap(struct node *p,struct node *q)
{
int tmp;
tmp=q->data;
q->data=p->data;
p->data=tmp;
}
void search()
{
int key;
printf("which element do you want to search?\n");
scanf("%d",&key);
struct node *p=first;
int count=1;
while(p!=NULL)
{
if(key==p->data)
{
printf("item found !\n");
printf("%d is %dth node\n",key,count);
printf("address of that node is %d\n",p);
return;
}
else
p=p->next;
count++;
}
if(key!=p->data)
{
printf("wrong item entered\n");
}
}
void search_sort()
{
int key;
printf("which element do you want to search?\n");
scanf("%d",&key);
struct node *p=first;
int count=1;
struct node *q=NULL;
while(p!=NULL)
{
if(key==p->data)
{
printf("item found !\n");
printf("%d is %dth node\n",key,count);
printf("address of that node is %d\n",p);
q->next=p->next;
p->next=first;
first=p;
return ;
}
else
{
q=p;
p=p->next;
count++;
}
}
if((key!=p->data))
{
printf("wrong item entered\n");
}
}
void search_cng()
{
int key;
printf("which element do you want to search?\n");
scanf("%d",&key);
struct node *p=first,*q;
int count=1;
while(p!=NULL)
{
if(key==p->data)
{
printf("item found !\n");
printf("%d is %dth node\n",key,count);
printf("address of that node is %d\n",p);
swap(q,p);
return ;
}
else
q=p;
p=p->next;
count++;
}
if(key!=p->data)
{
printf("wrong item entered\n");
}
}
void sort()
{
struct node *p,*q;
p=first;
q=p->next;
while(p!=NULL && q!=NULL)
{
if(p->data>q->data)
{
swap(p,q);
p=first;
q=p->next;
}
else
{
p=q;
q=p->next;
}
}
}
main()
{
int choice,choice1,choice2,choice3;
while(1)
{
printf("\tULTIMATE LINKED LIST PROGRAMME\n");
printf("\t--------------MENU--------------\n");
printf("\t1.Insertion\n");
printf("\t2.Deletion\n");
printf("\t3.Utility\n");
printf("\t4.Display\n");
printf("\t5.Clear screen\n");
printf("\t6.Exit\n");
printf("\t--------------------------------\n");
printf("your choice ?\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("\t--------------------INSERTION--------------------\n");
printf("\t1.Enter values(append)\n");
printf("\t2.Insert an element at begening of the link-list\n");
printf("\t3.Insert an element at end of the link-list\n");
printf("\t4.Insert any element with POS\n");
printf("\t5.Insert any element in sorted link-list\n");
printf("\t6.Back to main menu\n");
printf("\t--------------------------------------------------\n");
printf("your choice ?\n");
scanf("%d",&choice1);
switch(choice1)
{
case 1 :
insert();
break;
case 2 :
insert_beg();
break;
case 3 :
insert_end();
break;
case 4 :
insert_pos();
break;
case 5 :
insert_sort();
break;
case 6 :
break;
default :
printf("wrong choice,enter a valid choice\n");
}
break;
case 2 :
printf("\t---------------------DELETION---------------------\n");
printf("\t1.Delete first element of the link-list\n");
printf("\t2.Delete last element of the link-list\n");
printf("\t3.Delete any element of the link-list with POS\n");
printf("\t4.Back to main menu\n");
printf("\t--------------------------------------------------\n");
printf("your choice ?\n");
scanf("%d",&choice2);
switch(choice2)
{
case 1 :
del_beg();
break;
case 2 :
del_end();
break;
case 3 :
del_pos();
break;
case 4 :
break;
default :
printf("wrong choice,enter a valid choice\n");
}
break;
case 3 :
printf("\t---------------------UTILITY---------------------\n");
printf("\t1.Check if link-list is sorted\n");
printf("\t2.Make link-list sorted\n");
printf("\t3.Check if in link-list there is dublicate element\n");
printf("\t4.Remove deblicate element from link-list\n");
printf("\t5.Reverse link-list\n");
printf("\t6.Maximum element in the link-list\n");
printf("\t7.Minimum element in the link-list\n");
printf("\t8.Total nodes in the link-list except head\n");
printf("\t9.Only search element and find POS\n");
printf("\t10.Search an element and make it first node\n");
printf("\t11.Search an element and make it closer to head\n");
printf("\t12.Sum of all nodes values\n");
printf("\t13.Back to main menu\n");
printf("\t--------------------------------------------------\n");
printf("your choice ?\n");
scanf("%d",&choice1);
switch(choice1)
{
case 1 :
chk_sort();
break;
case 2 :
sort();
break;
case 3 :
break;
case 4 :
break;
case 5 :
break;
case 6 :
max();
break;
case 7 :
min();
break;
case 8 :
count();
break;
case 9 :
search();
break;
case 10 :
search_sort();
break;
case 11 :
search_cng();
break;
case 12 :
sum();
break;
/* case 8 :
break;*/
case 13 :
break;
default :
printf("wrong choice,enter a valid choice\n");
}
break;
case 4 :
display();
break;
case 5 :
system("cls");
break;
case 6 :
_Exit(10);
break;
default :
printf("wrong choice,enter a valid choice\n");
}
}
}
| 17.22037 | 71 | 0.513604 |
f94cd9ccd951ac9d020ed1abf9cc5ccc0f6e1fc9 | 1,608 | h | C | src/php_pq_params.h | trowski/ext-pq | 63fb773601422aa39375d8effb9f37abab981804 | [
"BSD-2-Clause"
] | 33 | 2015-05-29T13:07:24.000Z | 2022-02-07T07:58:41.000Z | src/php_pq_params.h | trowski/ext-pq | 63fb773601422aa39375d8effb9f37abab981804 | [
"BSD-2-Clause"
] | 43 | 2015-06-10T14:35:14.000Z | 2022-02-01T09:46:10.000Z | src/php_pq_params.h | trowski/ext-pq | 63fb773601422aa39375d8effb9f37abab981804 | [
"BSD-2-Clause"
] | 10 | 2015-06-10T15:40:51.000Z | 2021-04-22T08:10:22.000Z | /*
+--------------------------------------------------------------------+
| PECL :: pq |
+--------------------------------------------------------------------+
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the conditions mentioned |
| in the accompanying LICENSE file are met. |
+--------------------------------------------------------------------+
| Copyright (c) 2013, Michael Wallner <mike@php.net> |
+--------------------------------------------------------------------+
*/
#ifndef PHP_PQ_PARAMS_H
#define PHP_PQ_PARAMS_H
typedef struct php_pq_params {
struct {
HashTable conv;
unsigned count;
Oid *oids;
} type;
struct {
HashTable dtor;
unsigned count;
char **strings;
} param;
} php_pq_params_t;
extern php_pq_params_t *php_pq_params_init(HashTable *conv, HashTable *oids, HashTable *params);
extern void php_pq_params_free(php_pq_params_t **p);
extern unsigned php_pq_params_set_params(php_pq_params_t *p, HashTable *params);
extern unsigned php_pq_params_set_type_oids(php_pq_params_t *p, HashTable *oids);
extern unsigned php_pq_params_add_type_oid(php_pq_params_t *p, Oid type);
extern unsigned php_pq_params_add_param(php_pq_params_t *p, zval *param);
extern void php_pq_params_set_type_conv(php_pq_params_t *p, HashTable *conv);
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| 34.212766 | 96 | 0.562189 |
c3561842b6f5c578b967ff00e4247fff4145f892 | 10,938 | h | C | Havtorn/Source/Engine/Input/InputTypes.h | nicolas-risberg/NewEngine | 38441f0713167ca8a469a1c6c0e7a290b5e402de | [
"MIT"
] | null | null | null | Havtorn/Source/Engine/Input/InputTypes.h | nicolas-risberg/NewEngine | 38441f0713167ca8a469a1c6c0e7a290b5e402de | [
"MIT"
] | null | null | null | Havtorn/Source/Engine/Input/InputTypes.h | nicolas-risberg/NewEngine | 38441f0713167ca8a469a1c6c0e7a290b5e402de | [
"MIT"
] | 1 | 2022-01-09T12:01:24.000Z | 2022-01-09T12:01:24.000Z | // Copyright 2022 Team Havtorn. All Rights Reserved.
#pragma once
namespace Havtorn
{
enum class EInputModifier
{
None = 0,
Shift = BIT(0),
Ctrl = BIT(1),
Alt = BIT(2),
};
enum class EInputContext
{
Editor = BIT(0),
InGame = BIT(1),
};
enum class EInputKey
{
None = 0x00,
Mouse1 = 0x01, // Left
Mouse2 = 0x02, // Right
Mouse3 = 0x04, // Middle
Mouse4 = 0x05,
Mouse5 = 0x06,
Backspace = 0x08,
Tab = 0x09,
Return = 0x0D, // Enter
Shift = 0x10,
Ctrl = 0x11,
Alt = 0x12,
Pause = 0x13,
Caps = 0x14, // Caps Lock
Esc = 0x1B, // Escape
Space = 0x20,
PageUp = 0x21,
PageDown = 0x22,
End = 0x23,
Home = 0x24,
Left = 0x25, // Left Arrow
Up = 0x26, // Up Arrow
Right = 0x27, // Right Arrow
Down = 0x28, // Down
PrtSc = 0x2C, // Print Screen
Insert = 0x2D,
Delete = 0x2E,
Key0 = 0x30,
Key1 = 0x31,
Key2 = 0x32,
Key3 = 0x33,
Key4 = 0x34,
Key5 = 0x35,
Key6 = 0x36,
Key7 = 0x37,
Key8 = 0x38,
Key9 = 0x39,
KeyA = 0x41,
KeyB = 0x42,
KeyC = 0x43,
KeyD = 0x44,
KeyE = 0x45,
KeyF = 0x46,
KeyG = 0x47,
KeyH = 0x48,
KeyI = 0x49,
KeyJ = 0x4A,
KeyK = 0x4B,
KeyL = 0x4C,
KeyM = 0x4D,
KeyN = 0x4E,
KeyO = 0x4F,
KeyP = 0x50,
KeyQ = 0x51,
KeyR = 0x52,
KeyS = 0x53,
KeyT = 0x54,
KeyU = 0x55,
KeyV = 0x56,
KeyW = 0x57,
KeyX = 0x58,
KeyY = 0x59,
KeyZ = 0x5A,
LWin = 0x5B, // Left Windows key
RWin = 0x5C, // Right Windows key
KeyNum0 = 0x60, // Numeric keypad 0 key
KeyNum1 = 0x61, // Numeric keypad 1 key
KeyNum2 = 0x62, // Numeric keypad 2 key
KeyNum3 = 0x63, // Numeric keypad 3 key
KeyNum4 = 0x64, // Numeric keypad 4 key
KeyNum5 = 0x65, // Numeric keypad 5 key
KeyNum6 = 0x66, // Numeric keypad 6 key
KeyNum7 = 0x67, // Numeric keypad 7 key
KeyNum8 = 0x68, // Numeric keypad 8 key
KeyNum9 = 0x69, // Numeric keypad 9 key
KeyNumMult = 0x6A, // Numeric keypad Multiply key
KeyNumAdd = 0x6B, // Numeric keypad Add key
Pipe = 0x6C, // Separator key
KeyNumSub = 0x6D, // Numeric keypad Subtract key
KeyNumDec = 0x6E, // Numeric keypad Decimal key
KeyNumDiv = 0x6F, // Numeric keypad Divide key
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
NumLk = 0x90, // Num Lock key
ScrLk = 0x91, // Scroll Lock key
};
enum class EInputAxis
{
Key,
MouseWheel,
MouseHorizontal,
MouseVertical,
AnalogHorizontal,
AnalogVertical
};
enum class EInputActionEvent
{
None,
CenterCamera,
ResetCamera,
TeleportCamera,
Count
};
enum class EInputAxisEvent
{
Right, // X-axis
Up, // Y-axis
Forward, // Z-axis
Pitch, // X-axis
Yaw, // Y-axis
Roll, // Z-axis
MouseHorizontal,
MouseVertical,
Zoom,
Count
};
struct SInputActionPayload
{
EInputKey Key = EInputKey::None;
bool IsPressed = false;
bool IsHeld = false;
bool IsReleased = false;
};
struct SInputAxisPayload
{
EInputAxisEvent Event = EInputAxisEvent::Count;
F32 AxisValue = 0.0f;
};
struct SInputAction
{
SInputAction(EInputKey key, EInputContext context, EInputModifier modifier)
: Key(key)
, Contexts(static_cast<U32>(context))
, Modifiers(static_cast<U32>(modifier))
{}
SInputAction(EInputKey key, std::initializer_list<EInputContext> contexts, std::initializer_list<EInputModifier> modifiers = {})
: Key(key)
, Contexts(static_cast<U32>(EInputContext::Editor))
, Modifiers(0)
{
SetContexts(contexts);
SetModifiers(modifiers);
}
SInputAction(EInputKey key, EInputContext context)
: Key(key)
, Contexts(static_cast<U32>(context))
, Modifiers(0)
{}
// Pass in the number of modifiers the SInputAction should have
// followed by that number of EInputModifier entries, separated by comma
void SetModifiers(U32 numberOfModifiers, ...)
{
Modifiers = 0;
va_list args;
va_start(args, numberOfModifiers);
for (U32 index = 0; index < numberOfModifiers; index++)
{
Modifiers += static_cast<U32>(va_arg(args, EInputModifier));
}
va_end(args);
}
void SetModifiers(std::initializer_list<EInputModifier> modifiers)
{
Modifiers = 0;
for (auto modifier : modifiers)
Modifiers += static_cast<U32>(modifier);
}
void SetContexts(std::initializer_list<EInputContext> contexts)
{
Contexts = 0;
for (auto context : contexts)
Contexts += static_cast<U32>(context);
}
EInputKey Key = EInputKey::None;
U32 Contexts = static_cast<U32>(EInputContext::Editor);
U32 Modifiers = static_cast<U32>(EInputModifier::None);
};
struct SInputActionEvent
{
SInputActionEvent() = default;
explicit SInputActionEvent(SInputAction action)
: Delegate(CMulticastDelegate<const SInputActionPayload>())
{
Actions.push_back(action);
}
[[nodiscard]] bool HasKey(const EInputKey& key) const
{
return std::ranges::any_of(Actions.begin(), Actions.end(),
[key](const SInputAction& action) {return action.Key == key; });
}
[[nodiscard]] bool HasContext(U32 context) const
{
return std::ranges::any_of(Actions.begin(), Actions.end(),
[context](const SInputAction& action) {return (action.Contexts & context) != 0; });
}
[[nodiscard]] bool HasModifiers(U32 modifiers) const
{
return std::ranges::any_of(Actions.begin(), Actions.end(),
[modifiers](const SInputAction& action) {return (action.Modifiers ^ modifiers) == 0; });
}
[[nodiscard]] bool Has(const EInputKey& key, U32 context, U32 modifiers) const
{
return std::ranges::any_of(Actions.begin(), Actions.end(),
[key, context, modifiers](const SInputAction& action)
{
return action.Key == key && (action.Contexts & context) != 0 && (action.Modifiers ^ modifiers) == 0;
});
}
CMulticastDelegate<const SInputActionPayload> Delegate;
std::vector<SInputAction> Actions;
};
struct SInputAxis
{
SInputAxis(EInputAxis axis, EInputContext context)
: Axis(axis)
, AxisPositiveKey(EInputKey::KeyW)
, AxisNegativeKey(EInputKey::KeyS)
, Contexts(static_cast<U32>(context))
, Modifiers(0)
{}
SInputAxis(EInputAxis axis, EInputContext context, EInputModifier modifier)
: Axis(axis)
, AxisPositiveKey(EInputKey::KeyW)
, AxisNegativeKey(EInputKey::KeyS)
, Contexts(static_cast<U32>(context))
, Modifiers(static_cast<U32>(modifier))
{}
SInputAxis(EInputAxis axis, EInputKey axisPositiveKey, EInputKey axisNegativeKey, EInputContext context)
: Axis(axis)
, AxisPositiveKey(axisPositiveKey)
, AxisNegativeKey(axisNegativeKey)
, Contexts(static_cast<U32>(context))
, Modifiers(0)
{}
SInputAxis(EInputAxis axis, std::initializer_list<EInputContext> contexts, std::initializer_list<EInputModifier> modifiers = {})
: Axis(axis)
, AxisPositiveKey(EInputKey::KeyW)
, AxisNegativeKey(EInputKey::KeyS)
, Contexts(static_cast<U32>(EInputContext::Editor))
, Modifiers(0)
{
SetContexts(contexts);
SetModifiers(modifiers);
}
SInputAxis(EInputAxis axis, EInputKey axisPositiveKey, EInputKey axisNegativeKey, std::initializer_list<EInputContext> contexts, std::initializer_list<EInputModifier> modifiers = {})
: Axis(axis)
, AxisPositiveKey(axisPositiveKey)
, AxisNegativeKey(axisNegativeKey)
, Contexts(static_cast<U32>(EInputContext::Editor))
, Modifiers(0)
{
SetContexts(contexts);
SetModifiers(modifiers);
}
// Pass in the number of modifiers the SInputAction should have
// followed by that number of EInputModifier entries, separated by comma
void SetModifiers(U32 numberOfModifiers, ...)
{
Modifiers = 0;
va_list args;
va_start(args, numberOfModifiers);
for (U32 index = 0; index < numberOfModifiers; index++)
{
Modifiers += static_cast<U32>(va_arg(args, EInputModifier));
}
va_end(args);
}
void SetModifiers(std::initializer_list<EInputModifier> modifiers)
{
Modifiers = 0;
for (auto modifier : modifiers)
Modifiers += static_cast<U32>(modifier);
}
void SetContexts(std::initializer_list<EInputContext> contexts)
{
Contexts = 0;
for (auto context : contexts)
Contexts += static_cast<U32>(context);
}
[[nodiscard]] F32 GetAxisValue(const EInputKey& key) const
{
if (AxisPositiveKey == key)
return 1.0;
if (AxisNegativeKey == key)
return -1.0f;
return 0.0f;
}
[[nodiscard]] F32 GetAxisValue(const F32 rawValue) const
{
switch (Axis)
{
// Mouse Wheel scroll threshold is capped at 120
case EInputAxis::MouseWheel:
return rawValue / 120.0f;
// Return raw delta for now
case EInputAxis::MouseHorizontal:
case EInputAxis::MouseVertical:
return rawValue;
case EInputAxis::AnalogHorizontal:
case EInputAxis::AnalogVertical:
// Do not handle this here, call GetAxisValue(const EInputKey&) instead
case EInputAxis::Key:
default:
return 0.0f;
}
}
EInputAxis Axis = EInputAxis::Key;
EInputKey AxisPositiveKey = EInputKey::None; // Optional
EInputKey AxisNegativeKey = EInputKey::None; // Optional
U32 Contexts = static_cast<U32>(EInputContext::Editor);
U32 Modifiers = static_cast<U32>(EInputModifier::None);
};
struct SInputAxisEvent
{
SInputAxisEvent() = default;
explicit SInputAxisEvent(SInputAxis axis)
: Delegate(CMulticastDelegate<const SInputAxisPayload>())
{
Axes.push_back(axis);
}
[[nodiscard]] bool HasKeyAxis() const
{
return std::ranges::any_of(Axes.begin(), Axes.end(),
[](const SInputAxis& axis) {return axis.Axis == EInputAxis::Key; });
}
[[nodiscard]] bool Has(const EInputKey& key, U32 context, U32 modifiers, F32& outAxisValue) const
{
return std::ranges::any_of(Axes.begin(), Axes.end(),
[key, context, modifiers, &outAxisValue](const SInputAxis& axisAction)
{
if ((axisAction.AxisPositiveKey == key || axisAction.AxisNegativeKey == key)
&& (axisAction.Contexts & context) != 0 && (axisAction.Modifiers ^ modifiers) == 0)
{
outAxisValue = axisAction.GetAxisValue(key);
return true;
}
return false;
});
}
[[nodiscard]] bool Has(const EInputAxis& axis, F32& outAxisValue) const
{
return std::ranges::any_of(Axes.begin(), Axes.end(),
[axis, &outAxisValue](const SInputAxis& axisAction)
{
if (axisAction.Axis == axis)
{
outAxisValue = axisAction.GetAxisValue(outAxisValue);
return true;
}
return false;
});
}
CMulticastDelegate<const SInputAxisPayload> Delegate;
std::vector<SInputAxis> Axes;
};
class IInputObserver
{
public:
IInputObserver() = default;
virtual ~IInputObserver() = default;
IInputObserver(const IInputObserver&) = delete;
IInputObserver(const IInputObserver&&) = delete;
virtual void ReceiveEvent(const EInputActionEvent& event) = 0;
};
}
| 24.360802 | 184 | 0.664381 |
c36a79f758a2a84175d23ce643a0e1565781ea06 | 851 | c | C | src/sched_round_robin.c | uLipe/Kalango | b084f651bb786292bfc7b3f2426ead9477dbb29c | [
"MIT"
] | 2 | 2019-12-31T21:20:34.000Z | 2020-01-05T17:47:36.000Z | src/sched_round_robin.c | uLipe/Kalango | b084f651bb786292bfc7b3f2426ead9477dbb29c | [
"MIT"
] | null | null | null | src/sched_round_robin.c | uLipe/Kalango | b084f651bb786292bfc7b3f2426ead9477dbb29c | [
"MIT"
] | 1 | 2019-12-30T03:52:32.000Z | 2019-12-30T03:52:32.000Z | #include <sched.h>
#if CONFIG_ENABLE_ROUND_ROBIN_SCHED
KernelResult SchedulerDoRoundRobin(TaskPriorityList *list) {
ASSERT_PARAM(list);
uint8_t top_priority = (31 - ArchCountLeadZeros(list->ready_task_bitmap));
ArchCriticalSectionEnter();
sys_dnode_t *current_head = sys_dlist_peek_head(&list->task_list[top_priority]);
sys_dnode_t *next = sys_dlist_peek_next(&list->task_list[top_priority], current_head);
//The list has at least one more element, round robin allowed:
if(next) {
//move current head to the tail of the list, dont worry to
//scheduling, the core module is responsible to manage
//ready lists
sys_dlist_remove(current_head);
sys_dlist_append(&list->task_list[top_priority], current_head);
}
ArchCriticalSectionExit();
return kSuccess;
}
#endif | 31.518519 | 90 | 0.719154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.