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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
492b43c42a3cc5ef4ec40bf0f36aaceed919ef4a | 21 | h | C | data-test/samvu/Sample1_exe_project/MyClass.h | ducanhnguyen/cft4cpp-for-dummy | d7599f95e688943f52f6a9a0b729f16011997eb8 | [
"Apache-2.0"
] | null | null | null | data-test/samvu/Sample1_exe_project/MyClass.h | ducanhnguyen/cft4cpp-for-dummy | d7599f95e688943f52f6a9a0b729f16011997eb8 | [
"Apache-2.0"
] | null | null | null | data-test/samvu/Sample1_exe_project/MyClass.h | ducanhnguyen/cft4cpp-for-dummy | d7599f95e688943f52f6a9a0b729f16011997eb8 | [
"Apache-2.0"
] | null | null | null |
namespace org {
}
| 3.5 | 15 | 0.571429 |
3c9b635d50472c997c144d32d526365d132b272c | 486 | h | C | dovecot-2.2.33.2/src/lib-storage/mailbox-attribute-internal.h | NicoleRobin/dovecot | f971413537673e781c00808bc039fde5749fcc95 | [
"MIT"
] | null | null | null | dovecot-2.2.33.2/src/lib-storage/mailbox-attribute-internal.h | NicoleRobin/dovecot | f971413537673e781c00808bc039fde5749fcc95 | [
"MIT"
] | null | null | null | dovecot-2.2.33.2/src/lib-storage/mailbox-attribute-internal.h | NicoleRobin/dovecot | f971413537673e781c00808bc039fde5749fcc95 | [
"MIT"
] | null | null | null | #ifndef MAILBOX_ATTRIBUTE_INTERNAL_H
#define MAILBOX_ATTRIBUTE_INTERNAL_H
/* RFC 5464, Section 3.2.1.2: Mailbox entries */
#define MAILBOX_ATTRIBUTE_COMMENT "comment"
/* RFC 6154, Section 4: IMAP METADATA Entry for Special-Use Attributes */
#define MAILBOX_ATTRIBUTE_SPECIALUSE "specialuse"
/* RFC 5464, Section 3.2.1.1: Server entries */
#define MAIL_SERVER_ATTRIBUTE_COMMENT "comment"
#define MAIL_SERVER_ATTRIBUTE_ADMIN "admin"
void mailbox_attributes_internal_init(void);
#endif
| 32.4 | 73 | 0.808642 |
7170e18a82223ae2e26188986bd5730f8df901dd | 4,410 | h | C | include/retdec/serdes/std.h | LaudateCorpus1/retdec | 4a5d9ef75cc050b27f926fab49881cc771688109 | [
"Zlib",
"Apache-2.0",
"MIT"
] | 4,816 | 2017-12-12T18:07:09.000Z | 2019-04-17T02:01:04.000Z | include/retdec/serdes/std.h | fr0gger/retdec | 8c3f7bfba95d9e0934a5a9f3ff4f8aa6232343c9 | [
"Zlib",
"Apache-2.0",
"MIT"
] | 514 | 2017-12-12T18:22:52.000Z | 2019-04-16T16:07:11.000Z | include/retdec/serdes/std.h | fr0gger/retdec | 8c3f7bfba95d9e0934a5a9f3ff4f8aa6232343c9 | [
"Zlib",
"Apache-2.0",
"MIT"
] | 579 | 2017-12-12T18:38:02.000Z | 2019-04-11T13:32:53.000Z | /**
* @file include/retdec/serdes/address.h
* @brief C++ standard types (de)serialization.
* @copyright (c) 2019 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_SERDES_STD_H
#define RETDEC_SERDES_STD_H
#include <map>
#include <type_traits>
#include <rapidjson/document.h>
#include <rapidjson/encodings.h>
namespace retdec {
namespace serdes {
/**
* Explicitly instantiate all the needed serialization functions of form:
* @code
* template <typename Writer>
* void serialize(Writer&, const T&)
* @endcode
*/
#define SERIALIZE_EXPLICIT_INSTANTIATION(T) \
template void serialize( \
rapidjson::PrettyWriter<rapidjson::StringBuffer>&, \
const T&); \
template void serialize( \
rapidjson::PrettyWriter<rapidjson::StringBuffer, rapidjson::ASCII<>>&, \
const T&);
int64_t deserializeInt64(
const rapidjson::Value& val,
const std::string& key,
int64_t defaultValue = 0);
uint64_t deserializeUint64(
const rapidjson::Value& val,
const std::string& key,
uint64_t defaultValue = 0);
bool deserializeBool(
const rapidjson::Value& val,
const std::string& key,
bool defaultValue = false);
double deserializeDouble(
const rapidjson::Value& val,
const std::string& key,
double defaultValue = 0.0);
std::string deserializeString(
const rapidjson::Value& val,
const std::string& key,
const std::string& defaultValue = "");
void deserialize(const rapidjson::Value& val, const char*& str);
void deserialize(const rapidjson::Value& val, std::string& s);
template<typename ContainerOfDeserializableObjects>
void deserializeContainer(
const rapidjson::Value& val,
const std::string& key,
ContainerOfDeserializableObjects& objs)
{
objs.clear();
auto array = val.FindMember(key);
if (array != val.MemberEnd() && array->value.IsArray())
{
for (auto i = array->value.Begin(), e = array->value.End(); i != e; ++i)
{
auto& obj = *i;
if (!obj.IsNull())
{
typename ContainerOfDeserializableObjects::value_type v;
deserialize(obj, v);
objs.insert(objs.end(), v);
}
}
}
}
template <typename DeserializableObject>
void deserialize(
const rapidjson::Value& val,
const std::string& key,
DeserializableObject& obj)
{
auto res = val.FindMember(key);
if (res != val.MemberEnd())
{
deserialize(res->value, obj);
}
}
template <typename Writer>
void serializeInt64(
Writer& writer,
const std::string& key,
int64_t value,
bool doSerialize = true)
{
if (doSerialize)
{
writer.String(key);
writer.Int64(value);
}
}
template <typename Writer>
void serializeUint64(
Writer& writer,
const std::string& key,
uint64_t value,
bool doSerialize = true)
{
if (doSerialize)
{
writer.String(key);
writer.Uint64(value);
}
}
template <typename Writer>
void serializeBool(
Writer& writer,
const std::string& key,
bool value,
bool serializeIfFalse = true)
{
if (value || serializeIfFalse)
{
writer.String(key);
writer.Bool(value);
}
}
template <typename Writer>
void serializeDouble(Writer& writer, const std::string& key, double value)
{
writer.String(key);
writer.Double(value);
}
template <typename Writer>
void serializeString(
Writer& writer,
const std::string& key,
const std::string& value,
bool serializeIfValueEmpty = false)
{
if (!value.empty() || serializeIfValueEmpty)
{
writer.String(key);
writer.String(value);
}
}
template <typename Writer>
void serialize(
Writer& writer,
const std::string& value)
{
writer.String(value);
}
template<typename Writer, typename ContainerOfSerializableObjects>
void serializeContainer(
Writer& writer,
const std::string& key,
const ContainerOfSerializableObjects& objs,
bool serializeIfContainerEmpty = false)
{
if (!objs.empty() || serializeIfContainerEmpty)
{
writer.String(key);
writer.StartArray();
for (auto& obj : objs)
{
serialize(writer, obj);
}
writer.EndArray();
}
}
template <typename Writer, typename SerializableObject>
void serialize(
Writer& writer,
const std::string& key,
const SerializableObject& obj,
bool doSerialize = true)
{
if (doSerialize)
{
writer.String(key);
serialize(writer, obj);
}
}
} // namespace serdes
} // namespace retdec
#endif | 21.407767 | 80 | 0.674603 |
71776c4e688719a1aff4c367b60c46e3e10ee978 | 979 | h | C | NNet/Commands/AttachSigGen2SelCmd.h | pk1954/solutions | 02cd67fc1e6299e9fe56ce04dce2515d6f30df92 | [
"MIT"
] | null | null | null | NNet/Commands/AttachSigGen2SelCmd.h | pk1954/solutions | 02cd67fc1e6299e9fe56ce04dce2515d6f30df92 | [
"MIT"
] | null | null | null | NNet/Commands/AttachSigGen2SelCmd.h | pk1954/solutions | 02cd67fc1e6299e9fe56ce04dce2515d6f30df92 | [
"MIT"
] | null | null | null | // AttachSigGen2SelCmd.h
//
// Commands
#pragma once
#include <vector>
#include "NobId.h"
#include "InputLine.h"
#include "InputConnector.h"
#include "SignalGenerator.h"
#include "NNetCommand.h"
using std::vector;
class AttachSigGen2SelCmd : public NNetCommand
{
public:
AttachSigGen2SelCmd()
: m_pSigGenNew(m_pNMWI->GetSigGenActive())
{
m_pNMWI->GetUPNobs().Apply2AllSelected<InputLine>
(
[this](Nob & nob) { push(nob); }
);
}
void Do() final
{
m_pNMWI->GetUPNobs().Apply2AllSelected<InputLine>
(
[this](Nob & nob) { nob.SetSigGen(m_pSigGenNew); }
);
}
void Undo() final
{
for (auto i : m_list)
{
m_pNMWI->GetNobPtr<InputLine *>(i.id)->SetSigGen(i.pSigGen);
}
}
private:
struct SigGenAttachment
{
NobId id;
SignalGenerator * pSigGen;
};
vector<SigGenAttachment> m_list;
SignalGenerator * m_pSigGenNew;
void push(Nob & nob)
{
m_list.push_back(SigGenAttachment(nob.GetId(), nob.GetSigGen()));
}
}; | 17.175439 | 68 | 0.66905 |
73d209d36f040d05256db3d87417a93fb9accc9b | 4,976 | c | C | dovecot-2.2.33.2/src/pop3/pop3-settings.c | NicoleRobin/dovecot | f971413537673e781c00808bc039fde5749fcc95 | [
"MIT"
] | null | null | null | dovecot-2.2.33.2/src/pop3/pop3-settings.c | NicoleRobin/dovecot | f971413537673e781c00808bc039fde5749fcc95 | [
"MIT"
] | null | null | null | dovecot-2.2.33.2/src/pop3/pop3-settings.c | NicoleRobin/dovecot | f971413537673e781c00808bc039fde5749fcc95 | [
"MIT"
] | null | null | null | /* Copyright (c) 2005-2017 Dovecot authors, see the included COPYING file */
#include "lib.h"
#include "buffer.h"
#include "settings-parser.h"
#include "service-settings.h"
#include "mail-storage-settings.h"
#include "pop3-settings.h"
#include <stddef.h>
#include <unistd.h>
static bool pop3_settings_verify(void *_set, pool_t pool,
const char **error_r);
/* <settings checks> */
static struct file_listener_settings pop3_unix_listeners_array[] = {
{ "login/pop3", 0666, "", "" }
};
static struct file_listener_settings *pop3_unix_listeners[] = {
&pop3_unix_listeners_array[0]
};
static buffer_t pop3_unix_listeners_buf = {
pop3_unix_listeners, sizeof(pop3_unix_listeners), { NULL, }
};
/* </settings checks> */
struct service_settings pop3_service_settings = {
.name = "pop3",
.protocol = "pop3",
.type = "",
.executable = "pop3",
.user = "",
.group = "",
.privileged_group = "",
.extra_groups = "",
.chroot = "",
.drop_priv_before_exec = FALSE,
.process_min_avail = 0,
.process_limit = 1024,
.client_limit = 1,
.service_count = 1,
.idle_kill = 0,
.vsz_limit = (uoff_t)-1,
.unix_listeners = { { &pop3_unix_listeners_buf,
sizeof(pop3_unix_listeners[0]) } },
.fifo_listeners = ARRAY_INIT,
.inet_listeners = ARRAY_INIT
};
#undef DEF
#undef DEFLIST
#define DEF(type, name) \
{ type, #name, offsetof(struct pop3_settings, name), NULL }
#define DEFLIST(field, name, defines) \
{ SET_DEFLIST, name, offsetof(struct pop3_settings, field), defines }
static const struct setting_define pop3_setting_defines[] = {
DEF(SET_BOOL, verbose_proctitle),
DEF(SET_STR_VARS, rawlog_dir),
DEF(SET_BOOL, pop3_no_flag_updates),
DEF(SET_BOOL, pop3_enable_last),
DEF(SET_BOOL, pop3_reuse_xuidl),
DEF(SET_BOOL, pop3_save_uidl),
DEF(SET_BOOL, pop3_lock_session),
DEF(SET_BOOL, pop3_fast_size_lookups),
DEF(SET_STR, pop3_client_workarounds),
DEF(SET_STR, pop3_logout_format),
DEF(SET_ENUM, pop3_uidl_duplicates),
DEF(SET_STR, pop3_deleted_flag),
DEF(SET_ENUM, pop3_delete_type),
SETTING_DEFINE_LIST_END
};
static const struct pop3_settings pop3_default_settings = {
.verbose_proctitle = FALSE,
.rawlog_dir = "",
.pop3_no_flag_updates = FALSE,
.pop3_enable_last = FALSE,
.pop3_reuse_xuidl = FALSE,
.pop3_save_uidl = FALSE,
.pop3_lock_session = FALSE,
.pop3_fast_size_lookups = FALSE,
.pop3_client_workarounds = "",
.pop3_logout_format = "top=%t/%p, retr=%r/%b, del=%d/%m, size=%s",
.pop3_uidl_duplicates = "allow:rename",
.pop3_deleted_flag = "",
.pop3_delete_type = "default:expunge:flag"
};
static const struct setting_parser_info *pop3_setting_dependencies[] = {
&mail_user_setting_parser_info,
NULL
};
const struct setting_parser_info pop3_setting_parser_info = {
.module_name = "pop3",
.defines = pop3_setting_defines,
.defaults = &pop3_default_settings,
.type_offset = (size_t)-1,
.struct_size = sizeof(struct pop3_settings),
.parent_offset = (size_t)-1,
.check_func = pop3_settings_verify,
.dependencies = pop3_setting_dependencies
};
/* <settings checks> */
struct pop3_client_workaround_list {
const char *name;
enum pop3_client_workarounds num;
};
static const struct pop3_client_workaround_list pop3_client_workaround_list[] = {
{ "outlook-no-nuls", WORKAROUND_OUTLOOK_NO_NULS },
{ "oe-ns-eoh", WORKAROUND_OE_NS_EOH },
{ NULL, 0 }
};
static int
pop3_settings_parse_workarounds(struct pop3_settings *set,
const char **error_r)
{
enum pop3_client_workarounds client_workarounds = 0;
const struct pop3_client_workaround_list *list;
const char *const *str;
str = t_strsplit_spaces(set->pop3_client_workarounds, " ,");
for (; *str != NULL; str++) {
list = pop3_client_workaround_list;
for (; list->name != NULL; list++) {
if (strcasecmp(*str, list->name) == 0) {
client_workarounds |= list->num;
break;
}
}
if (list->name == NULL) {
*error_r = t_strdup_printf("pop3_client_workarounds: "
"Unknown workaround: %s", *str);
return -1;
}
}
set->parsed_workarounds = client_workarounds;
return 0;
}
static bool
pop3_settings_verify(void *_set, pool_t pool ATTR_UNUSED, const char **error_r)
{
struct pop3_settings *set = _set;
if (pop3_settings_parse_workarounds(set, error_r) < 0)
return FALSE;
if (strcmp(set->pop3_delete_type, "default") == 0) {
if (set->pop3_deleted_flag[0] == '\0')
set->parsed_delete_type = POP3_DELETE_TYPE_EXPUNGE;
else
set->parsed_delete_type = POP3_DELETE_TYPE_FLAG;
} else if (strcmp(set->pop3_delete_type, "expunge") == 0) {
set->parsed_delete_type = POP3_DELETE_TYPE_EXPUNGE;
} else if (strcmp(set->pop3_delete_type, "flag") == 0) {
if (set->pop3_deleted_flag[0] == '\0') {
*error_r = "pop3_delete_type=flag, but pop3_deleted_flag not set";
return FALSE;
}
set->parsed_delete_type = POP3_DELETE_TYPE_FLAG;
} else {
*error_r = t_strdup_printf("pop3_delete_type: Unknown value '%s'",
set->pop3_delete_type);
return FALSE;
}
return TRUE;
}
/* </settings checks> */
| 27.191257 | 81 | 0.720257 |
09416aa35bd5a2389d4f7934a18fcafc211abcee | 162 | h | C | include/bmp/playerbmp2.h | ant512/EarthShakerDS | c23920bb96652570616059ee4b807e82617c2385 | [
"MIT"
] | null | null | null | include/bmp/playerbmp2.h | ant512/EarthShakerDS | c23920bb96652570616059ee4b807e82617c2385 | [
"MIT"
] | null | null | null | include/bmp/playerbmp2.h | ant512/EarthShakerDS | c23920bb96652570616059ee4b807e82617c2385 | [
"MIT"
] | null | null | null | #ifndef _PLAYERBMP2_H_
#define _PLAYERBMP2_H_
#include "bitmapwrapper.h"
class PlayerBmp2 : public WoopsiGfx::BitmapWrapper {
public:
PlayerBmp2();
};
#endif
| 13.5 | 52 | 0.771605 |
8e20cf3861f4c839b917df35daba3ddfb52922f4 | 1,260 | h | C | Cipher.h | fire2fox433/GPP-Final | 2f893ee492c8b7eb5db3c0734496e34fdc09f553 | [
"CC-BY-3.0"
] | null | null | null | Cipher.h | fire2fox433/GPP-Final | 2f893ee492c8b7eb5db3c0734496e34fdc09f553 | [
"CC-BY-3.0"
] | null | null | null | Cipher.h | fire2fox433/GPP-Final | 2f893ee492c8b7eb5db3c0734496e34fdc09f553 | [
"CC-BY-3.0"
] | null | null | null | // Programming 2D Games
// Copyright (c) 2011 by:
// Charles Kelly
// Chapter 6 spacewar.h v1.0
#ifndef _CIPHER_H // Prevent multiple definitions if this
#define _CIPHER_H // file is included in more than one place
#define WIN32_LEAN_AND_MEAN
#include "game.h"
#include "textureManager.h"
#include "image.h"
#include "map.h"
#include "Cyrax.h"
#include "Freid.h"
#include "Agent47.h"
#include "Necrid.h"
#include <vector>
#include "characters.h"
//=============================================================================
// This class is the core of the game
//=============================================================================
class Cipher : public Game
{
private:
// game items
//TextureManager
//Object
Map *map1;
TextureManager characterTexture; // player texture
Cyrax *cyrax;
Freid *freid;
Agent47 *agent47;
Necrid *necrid;
int currentMode;
std::vector<Characters*> characters;
public:
// Constructor
Cipher();
// Destructor
virtual ~Cipher();
// Initialize the game
void initialize(HWND hwnd);
void update(); // must override pure virtual from Game
void ai(); // "
void collisions(); // "
void render(); // "
void releaseAll();
void resetAll();
};
#endif
| 21.355932 | 79 | 0.586508 |
820b70e09d694083a9374ed55edf43c145865e3f | 297 | h | C | test/ClassName.h | SHSongs/- | aea921ebf88f28b43b7b570f85968c319cd1bf88 | [
"MIT"
] | 1 | 2021-05-22T07:54:16.000Z | 2021-05-22T07:54:16.000Z | test/ClassName.h | SHSongs/your-target-score | aea921ebf88f28b43b7b570f85968c319cd1bf88 | [
"MIT"
] | null | null | null | test/ClassName.h | SHSongs/your-target-score | aea921ebf88f28b43b7b570f85968c319cd1bf88 | [
"MIT"
] | null | null | null | //
// Created by SHSongs on 2021-02-19.
//
#ifndef UNTITLED2_CLASSNAME_H
#define UNTITLED2_CLASSNAME_H
class ClassName {
public:
int age;
int getAge() const {
return age;
}
void setAge(int age) {
ClassName::age = age;
}
};
#endif //UNTITLED2_CLASSNAME_H
| 12.375 | 36 | 0.626263 |
bfde30e937e0a5be972a9d701373db476beaf35e | 4,150 | c | C | retro/cores/gba/src/util/vfs/vfs-file.c | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 2,706 | 2018-04-05T18:28:50.000Z | 2022-03-29T16:56:59.000Z | retro/cores/gba/src/util/vfs/vfs-file.c | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 242 | 2018-04-05T22:30:42.000Z | 2022-03-19T01:55:11.000Z | retro/cores/gba/src/util/vfs/vfs-file.c | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 464 | 2018-04-05T19:10:34.000Z | 2022-03-28T13:33:32.000Z | /* Copyright (c) 2013-2015 Jeffrey Pfau
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <mgba-util/vfs.h>
#include <mgba-util/memory.h>
#include <errno.h>
#include <stdio.h>
struct VFileFILE {
struct VFile d;
FILE* file;
bool writable;
};
static bool _vffClose(struct VFile* vf);
static off_t _vffSeek(struct VFile* vf, off_t offset, int whence);
static ssize_t _vffRead(struct VFile* vf, void* buffer, size_t size);
static ssize_t _vffWrite(struct VFile* vf, const void* buffer, size_t size);
static void* _vffMap(struct VFile* vf, size_t size, int flags);
static void _vffUnmap(struct VFile* vf, void* memory, size_t size);
static void _vffTruncate(struct VFile* vf, size_t size);
static ssize_t _vffSize(struct VFile* vf);
static bool _vffSync(struct VFile* vf, const void* buffer, size_t size);
struct VFile* VFileFOpen(const char* path, const char* mode) {
if (!path && !mode) {
return 0;
}
FILE* file = fopen(path, mode);
if (!file && errno == ENOENT && strcmp(mode, "r+b") == 0) {
file = fopen(path, "w+b");
}
return VFileFromFILE(file);
}
struct VFile* VFileFromFILE(FILE* file) {
if (!file) {
return 0;
}
struct VFileFILE* vff = malloc(sizeof(struct VFileFILE));
if (!vff) {
return 0;
}
vff->file = file;
vff->writable = false;
vff->d.close = _vffClose;
vff->d.seek = _vffSeek;
vff->d.read = _vffRead;
vff->d.readline = VFileReadline;
vff->d.write = _vffWrite;
vff->d.map = _vffMap;
vff->d.unmap = _vffUnmap;
vff->d.truncate = _vffTruncate;
vff->d.size = _vffSize;
vff->d.sync = _vffSync;
return &vff->d;
}
bool _vffClose(struct VFile* vf) {
struct VFileFILE* vff = (struct VFileFILE*) vf;
if (fclose(vff->file) < 0) {
return false;
}
free(vff);
return true;
}
off_t _vffSeek(struct VFile* vf, off_t offset, int whence) {
struct VFileFILE* vff = (struct VFileFILE*) vf;
fseek(vff->file, offset, whence);
return ftell(vff->file);
}
ssize_t _vffRead(struct VFile* vf, void* buffer, size_t size) {
struct VFileFILE* vff = (struct VFileFILE*) vf;
return fread(buffer, 1, size, vff->file);
}
ssize_t _vffWrite(struct VFile* vf, const void* buffer, size_t size) {
struct VFileFILE* vff = (struct VFileFILE*) vf;
return fwrite(buffer, 1, size, vff->file);
}
static void* _vffMap(struct VFile* vf, size_t size, int flags) {
struct VFileFILE* vff = (struct VFileFILE*) vf;
if (flags & MAP_WRITE) {
vff->writable = true;
}
void* mem = anonymousMemoryMap(size);
if (!mem) {
return 0;
}
long pos = ftell(vff->file);
fseek(vff->file, 0, SEEK_SET);
fread(mem, size, 1, vff->file);
fseek(vff->file, pos, SEEK_SET);
return mem;
}
static void _vffUnmap(struct VFile* vf, void* memory, size_t size) {
struct VFileFILE* vff = (struct VFileFILE*) vf;
if (vff->writable) {
long pos = ftell(vff->file);
fseek(vff->file, 0, SEEK_SET);
fwrite(memory, size, 1, vff->file);
fseek(vff->file, pos, SEEK_SET);
}
mappedMemoryFree(memory, size);
}
static void _vffTruncate(struct VFile* vf, size_t size) {
struct VFileFILE* vff = (struct VFileFILE*) vf;
long pos = ftell(vff->file);
fseek(vff->file, 0, SEEK_END);
ssize_t realSize = ftell(vff->file);
if (realSize < 0) {
return;
}
while (size > (size_t) realSize) {
static const char zeros[128] = "";
size_t diff = size - realSize;
if (diff > sizeof(zeros)) {
diff = sizeof(zeros);
}
fwrite(zeros, diff, 1, vff->file);
realSize += diff;
}
fseek(vff->file, pos, SEEK_SET);
}
static ssize_t _vffSize(struct VFile* vf) {
struct VFileFILE* vff = (struct VFileFILE*) vf;
long pos = ftell(vff->file);
fseek(vff->file, 0, SEEK_END);
ssize_t size = ftell(vff->file);
fseek(vff->file, pos, SEEK_SET);
return size;
}
static bool _vffSync(struct VFile* vf, const void* buffer, size_t size) {
struct VFileFILE* vff = (struct VFileFILE*) vf;
if (buffer && size) {
long pos = ftell(vff->file);
fseek(vff->file, 0, SEEK_SET);
fwrite(buffer, size, 1, vff->file);
fseek(vff->file, pos, SEEK_SET);
}
return fflush(vff->file) == 0;
}
| 26.433121 | 76 | 0.677108 |
44132c4715dfc79e884de4d659a7c787fad2a1de | 332 | h | C | include/spider.h | drcfts/ProxyServer | fa7aadfc36adbc546e91d5c97750e90fa5b3b9cb | [
"MIT"
] | null | null | null | include/spider.h | drcfts/ProxyServer | fa7aadfc36adbc546e91d5c97750e90fa5b3b9cb | [
"MIT"
] | null | null | null | include/spider.h | drcfts/ProxyServer | fa7aadfc36adbc546e91d5c97750e90fa5b3b9cb | [
"MIT"
] | null | null | null | #ifndef HTTP_SPIDER
#define HTTP_SPIDER
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SPIDER_MSG_SIZE 500
#define DEBUG_SPIDER 0
char *spider_get_response(char *request);
char *spider_get_data(char *url);
char *spider_separate_url_path(char *url, size_t *url_size, size_t *path_size);
#endif
| 17.473684 | 79 | 0.771084 |
68bc820affb8249be993315eaf7a0d0fab223b62 | 28,168 | c | C | wireshark-2.0.13/epan/dissectors/packet-zebra.c | mahrukhfida/mi | 7187765aa225e71983969ef5285771ac77c8309a | [
"Apache-2.0"
] | null | null | null | wireshark-2.0.13/epan/dissectors/packet-zebra.c | mahrukhfida/mi | 7187765aa225e71983969ef5285771ac77c8309a | [
"Apache-2.0"
] | null | null | null | wireshark-2.0.13/epan/dissectors/packet-zebra.c | mahrukhfida/mi | 7187765aa225e71983969ef5285771ac77c8309a | [
"Apache-2.0"
] | null | null | null | /* packet-zebra.c
* Routines for zebra packet disassembly
*
* Jochen Friedrich <jochen@scram.de>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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.
*/
/*
* The Zebra Protocol is the protocol used between the Zebra routing daemon and other
* protocol daemons (ones for BGP, OSPF, etc.) within the Zebra and Quagga open-source
* routing suites. Zebra itself (https://www.gnu.org/software/zebra) is discontinued,
* and its successor is Quagga (http://www.nongnu.org/quagga).
*
* Both Zebra and Quagga use a "Zebra Protocol", but starting with Quagga v0.99 the
* Zebra Protocol has changed, with a different header format and more commands/types.
* Quagga 0.99.0 was version 1, and 0.99.20 or so changed it to version 2.
*
* See http://www.nongnu.org/quagga/docs/docs-info.html#Zebra-Protocol for some details.
*/
#include "config.h"
#include <epan/packet.h>
/* Function declarations */
void proto_reg_handoff_zebra(void);
void proto_register_zebra(void);
static int proto_zebra = -1;
static int hf_zebra_len = -1;
static int hf_zebra_command = -1;
static int hf_zebra_request = -1;
static int hf_zebra_interface = -1;
static int hf_zebra_index = -1;
static int hf_zebra_indexnum = -1;
static int hf_zebra_type_v0 = -1;
static int hf_zebra_type_v1 = -1;
static int hf_zebra_intflags = -1;
static int hf_zebra_rtflags = -1;
static int hf_zebra_distance = -1;
static int hf_zebra_metric = -1;
static int hf_zebra_mtu = -1;
static int hf_zebra_mtu6 = -1;
static int hf_zebra_bandwidth = -1;
static int hf_zebra_family = -1;
static int hf_zebra_flags = -1;
static int hf_zebra_message = -1;
static int hf_zebra_route_safi = -1;
static int hf_zebra_msg_nexthop = -1;
static int hf_zebra_msg_index = -1;
static int hf_zebra_msg_distance = -1;
static int hf_zebra_msg_metric = -1;
static int hf_zebra_nexthopnum = -1;
static int hf_zebra_nexthop4 = -1;
static int hf_zebra_nexthop6 = -1;
static int hf_zebra_dest4 = -1;
static int hf_zebra_dest6 = -1;
static int hf_zebra_prefixlen = -1;
static int hf_zebra_prefix4 = -1;
static int hf_zebra_prefix6 = -1;
static int hf_zebra_version = -1;
static int hf_zebra_marker = -1;
static int hf_zebra_intstatus = -1;
static int hf_zebra_routeridaddress = -1;
static int hf_zebra_routeridmask = -1;
static int hf_zebra_mac = -1;
static int hf_zebra_redist_default = -1;
static gint ett_zebra = -1;
static gint ett_zebra_request = -1;
static gint ett_message = -1;
#define TCP_PORT_ZEBRA 2600
/* Zebra message types. */
#define ZEBRA_INTERFACE_ADD 1
#define ZEBRA_INTERFACE_DELETE 2
#define ZEBRA_INTERFACE_ADDRESS_ADD 3
#define ZEBRA_INTERFACE_ADDRESS_DELETE 4
#define ZEBRA_INTERFACE_UP 5
#define ZEBRA_INTERFACE_DOWN 6
#define ZEBRA_IPV4_ROUTE_ADD 7
#define ZEBRA_IPV4_ROUTE_DELETE 8
#define ZEBRA_IPV6_ROUTE_ADD 9
#define ZEBRA_IPV6_ROUTE_DELETE 10
#define ZEBRA_REDISTRIBUTE_ADD 11
#define ZEBRA_REDISTRIBUTE_DELETE 12
#define ZEBRA_REDISTRIBUTE_DEFAULT_ADD 13
#define ZEBRA_REDISTRIBUTE_DEFAULT_DELETE 14
#define ZEBRA_IPV4_NEXTHOP_LOOKUP 15
#define ZEBRA_IPV6_NEXTHOP_LOOKUP 16
#define ZEBRA_IPV4_IMPORT_LOOKUP 17
#define ZEBRA_IPV6_IMPORT_LOOKUP 18
#define ZEBRA_INTERFACE_RENAME 19
#define ZEBRA_ROUTER_ID_ADD 20
#define ZEBRA_ROUTER_ID_DELETE 21
#define ZEBRA_ROUTER_ID_UPDATE 22
#define ZEBRA_HELLO 23
static const value_string messages[] = {
{ ZEBRA_INTERFACE_ADD, "Add Interface" },
{ ZEBRA_INTERFACE_DELETE, "Delete Interface" },
{ ZEBRA_INTERFACE_ADDRESS_ADD, "Add Interface Address" },
{ ZEBRA_INTERFACE_ADDRESS_DELETE, "Delete Interface Address" },
{ ZEBRA_INTERFACE_UP, "Interface Up" },
{ ZEBRA_INTERFACE_DOWN, "Interface Down" },
{ ZEBRA_IPV4_ROUTE_ADD, "Add IPv4 Route" },
{ ZEBRA_IPV4_ROUTE_DELETE, "Delete IPv4 Route" },
{ ZEBRA_IPV6_ROUTE_ADD, "Add IPv6 Route" },
{ ZEBRA_IPV6_ROUTE_DELETE, "Delete IPv6 Route" },
{ ZEBRA_REDISTRIBUTE_ADD, "Add Redistribute" },
{ ZEBRA_REDISTRIBUTE_DELETE, "Delete Redistribute" },
{ ZEBRA_REDISTRIBUTE_DEFAULT_ADD, "Add Default Redistribute" },
{ ZEBRA_REDISTRIBUTE_DEFAULT_DELETE, "Delete Default Redistribute" },
{ ZEBRA_IPV4_NEXTHOP_LOOKUP, "IPv4 Nexthop Lookup" },
{ ZEBRA_IPV6_NEXTHOP_LOOKUP, "IPv6 Nexthop Lookup" },
{ ZEBRA_IPV4_IMPORT_LOOKUP, "IPv4 Import Lookup" },
{ ZEBRA_IPV6_IMPORT_LOOKUP, "IPv6 Import Lookup" },
{ ZEBRA_INTERFACE_RENAME, "Rename Interface" },
{ ZEBRA_ROUTER_ID_ADD, "Router ID Add" },
{ ZEBRA_ROUTER_ID_DELETE, "Router ID Delete" },
{ ZEBRA_ROUTER_ID_UPDATE, "Router ID Update" },
{ ZEBRA_HELLO, "Hello" },
{ 0, NULL },
};
/* Zebra route's types. */
#define ZEBRA_ROUTE_SYSTEM 0
#define ZEBRA_ROUTE_KERNEL 1
#define ZEBRA_ROUTE_CONNECT 2
#define ZEBRA_ROUTE_STATIC 3
#define ZEBRA_ROUTE_RIP 4
#define ZEBRA_ROUTE_RIPNG 5
#define ZEBRA_ROUTE_OSPF 6
#define ZEBRA_ROUTE_OSPF6 7
#define ZEBRA_ROUTE_BGP 8
static const value_string routes_v0[] = {
{ ZEBRA_ROUTE_SYSTEM, "System Route" },
{ ZEBRA_ROUTE_KERNEL, "Kernel Route" },
{ ZEBRA_ROUTE_CONNECT, "Connected Route" },
{ ZEBRA_ROUTE_STATIC, "Static Route" },
{ ZEBRA_ROUTE_RIP, "RIP Route" },
{ ZEBRA_ROUTE_RIPNG, "RIPnG Route" },
{ ZEBRA_ROUTE_OSPF, "OSPF Route" },
{ ZEBRA_ROUTE_OSPF6, "OSPF6 Route" },
{ ZEBRA_ROUTE_BGP, "BGP Route" },
{ 0, NULL },
};
/*
* In Quagga, ISIS is type 8 and BGP is type 9, but Zebra didn't have ISIS...
* so for Zebra BGP is type 8. So we dup the value_string table for quagga.
*/
#define QUAGGA_ROUTE_ISIS 8
#define QUAGGA_ROUTE_BGP 9
#define QUAGGA_ROUTE_HSLS 10
#define QUAGGA_ROUTE_OLSR 11
#define QUAGGA_ROUTE_BABEL 12
static const value_string routes_v1[] = {
{ ZEBRA_ROUTE_SYSTEM, "System Route" },
{ ZEBRA_ROUTE_KERNEL, "Kernel Route" },
{ ZEBRA_ROUTE_CONNECT, "Connected Route" },
{ ZEBRA_ROUTE_STATIC, "Static Route" },
{ ZEBRA_ROUTE_RIP, "RIP Route" },
{ ZEBRA_ROUTE_RIPNG, "RIPnG Route" },
{ ZEBRA_ROUTE_OSPF, "OSPF Route" },
{ ZEBRA_ROUTE_OSPF6, "OSPF6 Route" },
{ QUAGGA_ROUTE_ISIS, "ISIS Route" },
{ QUAGGA_ROUTE_BGP, "BGP Route" },
{ QUAGGA_ROUTE_HSLS, "HSLS Route" },
{ QUAGGA_ROUTE_OLSR, "OLSR Route" },
{ QUAGGA_ROUTE_BABEL, "BABEL Route" },
{ 0, NULL },
};
/* Zebra's family types. */
#define ZEBRA_FAMILY_IPV4 2
#define ZEBRA_FAMILY_IPV6 10
static const value_string families[] = {
{ ZEBRA_FAMILY_IPV4, "IPv4" },
{ ZEBRA_FAMILY_IPV6, "IPv6" },
{ 0, NULL },
};
/* Zebra message flags */
#define ZEBRA_FLAG_INTERNAL 0x01
#define ZEBRA_FLAG_SELFROUTE 0x02
#define ZEBRA_FLAG_BLACKHOLE 0x04
/* Zebra API message flag. */
#define ZEBRA_ZAPI_MESSAGE_NEXTHOP 0x01
#define ZEBRA_ZAPI_MESSAGE_IFINDEX 0x02
#define ZEBRA_ZAPI_MESSAGE_DISTANCE 0x04
#define ZEBRA_ZAPI_MESSAGE_METRIC 0x08
/* Zebra NextHop Types */
#define ZEBRA_NEXTHOP_TYPE_IFINDEX 0x01
#define ZEBRA_NEXTHOP_TYPE_IFNAME 0x02
#define ZEBRA_NEXTHOP_TYPE_IPV4 0x03
#define ZEBRA_NEXTHOP_TYPE_IPV4_IFINDEX 0x04
#define ZEBRA_NEXTHOP_TYPE_IPV4_IFNAME 0x05
#define ZEBRA_NEXTHOP_TYPE_IPV6 0x06
#define ZEBRA_NEXTHOP_TYPE_IPV6_IFINDEX 0x07
#define ZEBRA_NEXTHOP_TYPE_IPV6_IFNAME 0x08
/* Subsequent Address Family Identifier. */
#define ZEBRA_SAFI_UNICAST 1
#define ZEBRA_SAFI_MULTICAST 2
#define ZEBRA_SAFI_RESERVED_3 3
#define ZEBRA_SAFI_MPLS_VPN 4
static const value_string safi[] = {
{ ZEBRA_SAFI_UNICAST, "Unicast" },
{ ZEBRA_SAFI_MULTICAST, "Multicast" },
{ ZEBRA_SAFI_RESERVED_3, "Reserved" },
{ ZEBRA_SAFI_MPLS_VPN, "MPLS VPN" },
{ 0, NULL },
};
#define INTERFACE_NAMSIZ 20
#define PSIZE(a) (((a) + 7) / (8))
static int
zebra_route_nexthop(proto_tree *tree, tvbuff_t *tvb, int offset, guint16 len)
{
guint8 nexthoptype, nexthopcount, interfacenamelength;
nexthopcount = tvb_get_guint8(tvb, offset);
proto_tree_add_uint(tree, hf_zebra_nexthopnum,
tvb, offset, 1, nexthopcount);
offset += 1;
if (nexthopcount > len)
return offset; /* Sanity */
while (nexthopcount--) {
nexthoptype = tvb_get_guint8(tvb, offset);
offset += 1;
if (nexthoptype == ZEBRA_NEXTHOP_TYPE_IFINDEX ||
nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV4_IFINDEX ||
nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV6_IFINDEX){
proto_tree_add_item(tree,hf_zebra_index, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
}
if (nexthoptype == ZEBRA_NEXTHOP_TYPE_IFNAME ||
nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV4_IFNAME ||
nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV6_IFNAME) {
interfacenamelength = tvb_get_guint8(tvb, offset);
offset += 1;
proto_tree_add_item(tree, hf_zebra_interface,
tvb, offset, interfacenamelength,
ENC_ASCII|ENC_NA);
offset += interfacenamelength;
}
if (nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV6 ||
nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV6_IFINDEX ||
nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV6_IFNAME) {
proto_tree_add_item(tree, hf_zebra_nexthop6,
tvb, offset, 16, ENC_NA);
offset += 16;
}
if (nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV4 ||
nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV4_IFINDEX ||
nexthoptype == ZEBRA_NEXTHOP_TYPE_IPV4_IFNAME) {
proto_tree_add_item(tree, hf_zebra_nexthop4,
tvb, offset, 4, ENC_NA);
offset += 4;
}
}
return offset;
}
static int
zebra_route_ifindex(proto_tree *tree, tvbuff_t *tvb, int offset, guint16 len)
{
guint16 indexcount = tvb_get_guint8(tvb, offset);
proto_tree_add_uint(tree, hf_zebra_indexnum,
tvb, offset, 1, indexcount);
offset += 1;
if (indexcount > len)
return offset; /* Sanity */
while (indexcount--) {
proto_tree_add_item(tree, hf_zebra_index, tvb, offset, 4,
ENC_BIG_ENDIAN);
offset += 4;
}
return offset;
}
static guint8
zebra_route_message(proto_tree *tree, tvbuff_t *tvb, int offset)
{
static const int * flags[] = {
&hf_zebra_msg_nexthop,
&hf_zebra_msg_index,
&hf_zebra_msg_distance,
&hf_zebra_msg_metric,
NULL
};
proto_tree_add_bitmask(tree, tvb, offset, hf_zebra_message, ett_message, flags, ENC_NA);
offset += 1;
return offset;
}
static int
zebra_route(proto_tree *tree, tvbuff_t *tvb, int offset, guint16 len,
guint8 family, guint8 version)
{
guint32 prefix4;
guint8 message, prefixlen, buffer6[16];
if (version == 0) {
proto_tree_add_item(tree, hf_zebra_type_v0, tvb,
offset, 1, ENC_BIG_ENDIAN);
} else {
proto_tree_add_item(tree, hf_zebra_type_v1, tvb,
offset, 1, ENC_BIG_ENDIAN);
}
offset += 1;
proto_tree_add_item(tree, hf_zebra_rtflags, tvb,
offset, 1, ENC_BIG_ENDIAN);
offset += 1;
message = tvb_get_guint8(tvb, offset);
offset = zebra_route_message(tree, tvb, offset);
if (version > 1) {
/* version 2 added safi */
proto_tree_add_item(tree, hf_zebra_route_safi, tvb,
offset, 2, ENC_BIG_ENDIAN);
offset += 2;
}
prefixlen = tvb_get_guint8(tvb, offset);
proto_tree_add_uint(tree, hf_zebra_prefixlen, tvb,
offset, 1, prefixlen);
offset += 1;
if (family == ZEBRA_FAMILY_IPV6) {
memset(buffer6, '\0', sizeof buffer6);
tvb_memcpy(tvb, buffer6, offset,
MIN((unsigned) PSIZE(prefixlen), sizeof buffer6));
proto_tree_add_ipv6(tree, hf_zebra_prefix6,
tvb, offset, PSIZE(prefixlen), (struct e_in6_addr *)buffer6);
}else {
prefix4 = 0;
tvb_memcpy(tvb, (guint8 *)&prefix4, offset,
MIN((unsigned) PSIZE(prefixlen), sizeof prefix4));
proto_tree_add_ipv4(tree, hf_zebra_prefix4,
tvb, offset, PSIZE(prefixlen), prefix4);
}
offset += PSIZE(prefixlen);
if (message & ZEBRA_ZAPI_MESSAGE_NEXTHOP) {
offset = zebra_route_nexthop(tree, tvb, offset, len);
}
if (message & ZEBRA_ZAPI_MESSAGE_IFINDEX) {
offset = zebra_route_ifindex(tree, tvb, offset, len);
}
if (message & ZEBRA_ZAPI_MESSAGE_DISTANCE) {
proto_tree_add_item(tree, hf_zebra_distance,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset += 1;
}
if (message & ZEBRA_ZAPI_MESSAGE_METRIC) {
proto_tree_add_item(tree, hf_zebra_metric,
tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
}
return offset;
}
static int
zebra_interface_address(proto_tree *tree, tvbuff_t *tvb, int offset)
{
guint8 family;
proto_tree_add_item(tree, hf_zebra_index, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item(tree, hf_zebra_flags, tvb,
offset, 1, ENC_BIG_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_zebra_family, tvb,
offset, 1, ENC_BIG_ENDIAN);
family = tvb_get_guint8(tvb, offset);
offset += 1;
if (family == ZEBRA_FAMILY_IPV4) {
proto_tree_add_item(tree, hf_zebra_prefix4,
tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
}
else if (family == ZEBRA_FAMILY_IPV6) {
proto_tree_add_item(tree, hf_zebra_prefix6,
tvb, offset, 16, ENC_NA);
offset += 16;
}
else
return offset;
proto_tree_add_item(tree, hf_zebra_prefixlen, tvb,
offset, 1, ENC_BIG_ENDIAN);
offset += 1;
if (family == ZEBRA_FAMILY_IPV4) {
proto_tree_add_item(tree, hf_zebra_dest4,
tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
}
else if (family == ZEBRA_FAMILY_IPV6) {
proto_tree_add_item(tree, hf_zebra_dest6,
tvb, offset, 16, ENC_NA);
offset += 16;
}
return offset;
}
static int
zebra_interface_del(proto_tree *tree, tvbuff_t *tvb, int offset)
{
proto_tree_add_item(tree, hf_zebra_interface,
tvb, offset, INTERFACE_NAMSIZ, ENC_ASCII|ENC_NA);
offset += INTERFACE_NAMSIZ;
proto_tree_add_item(tree, hf_zebra_index, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
return offset;
}
static int
zebra_interface(proto_tree *tree, tvbuff_t *tvb, int offset, guint8 version)
{
gint maclen;
proto_tree_add_item(tree, hf_zebra_interface,
tvb, offset, INTERFACE_NAMSIZ, ENC_ASCII|ENC_NA);
offset += INTERFACE_NAMSIZ;
proto_tree_add_item(tree, hf_zebra_index, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item(tree, hf_zebra_intstatus, tvb,
offset, 1, ENC_BIG_ENDIAN);
offset += 1;
if (version != 0) {
proto_tree_add_item(tree, hf_zebra_intflags, tvb,
offset, 8, ENC_BIG_ENDIAN);
offset += 8;
} else {
proto_tree_add_item(tree, hf_zebra_intflags, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
}
proto_tree_add_item(tree, hf_zebra_metric, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item(tree, hf_zebra_mtu, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
if (version != 0) {
proto_tree_add_item(tree, hf_zebra_mtu6, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
}
proto_tree_add_item(tree, hf_zebra_bandwidth, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
if (version != 0) {
maclen = (gint)tvb_get_ntohl(tvb, offset);
offset += 4;
if (maclen > 0)
proto_tree_add_item(tree, hf_zebra_mac, tvb,
offset, maclen, ENC_NA);
offset += maclen;
}
return offset;
}
static int
zebra_nexthop_lookup(proto_tree *tree, tvbuff_t *tvb, int offset, guint16 len,
guint8 family)
{
if (family == ZEBRA_FAMILY_IPV6) {
proto_tree_add_item(tree, hf_zebra_dest6, tvb, offset, 16,
ENC_NA);
offset += 16;
}else {
proto_tree_add_item(tree, hf_zebra_dest4, tvb, offset, 4,
ENC_BIG_ENDIAN);
offset += 4;
}
proto_tree_add_item(tree, hf_zebra_metric,tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
offset = zebra_route_nexthop(tree, tvb, offset, len);
return offset;
}
static int
zerba_router_update(proto_tree *tree, tvbuff_t *tvb, int offset)
{
offset += 1;
proto_tree_add_item(tree, hf_zebra_routeridaddress, tvb,
offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item(tree, hf_zebra_routeridmask, tvb,
offset, 1, ENC_BIG_ENDIAN);
offset += 1;
return offset;
}
static int
dissect_zebra_request(proto_tree *tree, gboolean request, tvbuff_t *tvb,
int offset, guint16 len, guint16 command, guint8 version)
{
proto_tree_add_uint(tree, hf_zebra_len, tvb, offset, 2, len);
offset += 2;
if (version != 0) {
proto_tree_add_item(tree, hf_zebra_marker, tvb, offset, 1, ENC_NA);
offset += 1;
proto_tree_add_uint(tree, hf_zebra_version, tvb, offset, 1,
version);
offset += 1;
proto_tree_add_uint(tree, hf_zebra_command, tvb, offset, 2,
command);
offset += 2;
} else {
proto_tree_add_uint(tree, hf_zebra_command, tvb, offset, 1,
command);
offset += 1;
}
switch(command) {
case ZEBRA_INTERFACE_ADD:
case ZEBRA_INTERFACE_UP:
case ZEBRA_INTERFACE_DOWN:
if (request)
break; /* Request just subscribes to messages */
offset = zebra_interface(tree, tvb, offset, version);
break;
case ZEBRA_INTERFACE_DELETE:
offset = zebra_interface_del(tree, tvb, offset);
break;
case ZEBRA_INTERFACE_ADDRESS_ADD:
case ZEBRA_INTERFACE_ADDRESS_DELETE:
offset = zebra_interface_address(tree, tvb, offset);
break;
case ZEBRA_IPV4_ROUTE_ADD:
case ZEBRA_IPV4_ROUTE_DELETE:
offset = zebra_route(tree, tvb, offset, len,
ZEBRA_FAMILY_IPV4, version);
break;
case ZEBRA_IPV6_ROUTE_ADD:
case ZEBRA_IPV6_ROUTE_DELETE:
offset = zebra_route(tree, tvb, offset, len,
ZEBRA_FAMILY_IPV6, version);
break;
case ZEBRA_REDISTRIBUTE_ADD:
case ZEBRA_REDISTRIBUTE_DEFAULT_ADD:
if (version == 0) {
proto_tree_add_item(tree, hf_zebra_type_v0, tvb,
offset, 1, ENC_BIG_ENDIAN);
} else {
proto_tree_add_item(tree, hf_zebra_type_v1, tvb,
offset, 1, ENC_BIG_ENDIAN);
}
offset = 1;
break;
case ZEBRA_IPV4_IMPORT_LOOKUP:
case ZEBRA_IPV4_NEXTHOP_LOOKUP:
offset = zebra_nexthop_lookup(tree, tvb, offset, len,
ZEBRA_FAMILY_IPV4);
break;
case ZEBRA_IPV6_IMPORT_LOOKUP:
case ZEBRA_IPV6_NEXTHOP_LOOKUP:
offset = zebra_nexthop_lookup(tree, tvb, offset, len,
ZEBRA_FAMILY_IPV6);
break;
case ZEBRA_ROUTER_ID_UPDATE:
offset = zerba_router_update(tree, tvb, offset);
break;
case ZEBRA_ROUTER_ID_ADD:
case ZEBRA_ROUTER_ID_DELETE:
case ZEBRA_REDISTRIBUTE_DEFAULT_DELETE:
/* nothing to do */
break;
case ZEBRA_REDISTRIBUTE_DELETE:
/* in version 1+, there's a route type field */
if (version > 0) {
proto_tree_add_item(tree, hf_zebra_type_v1, tvb,
offset, 1, ENC_BIG_ENDIAN);
}
break;
case ZEBRA_HELLO:
proto_tree_add_item(tree, hf_zebra_redist_default, tvb,
offset, 1, ENC_BIG_ENDIAN);
break;
}
return offset;
}
/*
Zebra Protocol header version 0:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-------------------------------+---------------+
| Length (2) | Command (1) |
+-------------------------------+---------------+
Zebra Protocol header version 1:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-------------------------------+---------------+-------------+
| Length (2) | Marker (1) | Version (1) |
+-------------------------------+---------------+-------------+
| Command (2) |
+-------------------------------+
The Marker is 0xFF to distinguish it from a version 0 header.
*/
static void
dissect_zebra(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_item *ti;
proto_tree *zebra_tree;
gboolean request;
int left, offset;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "ZEBRA");
request = (pinfo->destport == pinfo->match_uint);
left = tvb_reported_length(tvb);
offset = 0;
col_set_str(pinfo->cinfo, COL_INFO,
request? "Zebra Request" : "Zebra Reply");
/* if (tree) */ {
ti = proto_tree_add_item(tree, proto_zebra, tvb, offset, -1,
ENC_NA);
zebra_tree = proto_item_add_subtree(ti, ett_zebra);
ti = proto_tree_add_boolean(zebra_tree, hf_zebra_request,
tvb, offset, 0, request);
PROTO_ITEM_SET_HIDDEN(ti);
for (;;) {
guint8 headermarker, version;
guint16 command, len;
proto_tree *zebra_request_tree;
if (left < 3)
break;
len = tvb_get_ntohs(tvb, offset);
if (len < 3)
break;
headermarker = tvb_get_guint8(tvb,offset+2);
if (headermarker != 0xFF) {
command = headermarker;
version = 0;
} else {
version = tvb_get_guint8(tvb, offset+3);
command = tvb_get_ntohs(tvb, offset+4);
}
col_append_fstr(pinfo->cinfo, COL_INFO, ": %s",
val_to_str(command, messages, "Command Type 0x%02d"));
ti = proto_tree_add_uint(zebra_tree,
hf_zebra_command, tvb,
offset, len, command);
zebra_request_tree = proto_item_add_subtree(ti,
ett_zebra_request);
dissect_zebra_request(zebra_request_tree, request, tvb,
offset, len, command, version);
offset += len;
left -= len;
}
}
}
void
proto_register_zebra(void)
{
static hf_register_info hf[] = {
{ &hf_zebra_len,
{ "Length", "zebra.len",
FT_UINT16, BASE_DEC, NULL, 0x0,
"Length of Zebra request", HFILL }},
{ &hf_zebra_version,
{ "Version", "zebra.version",
FT_UINT8, BASE_DEC, NULL, 0x0,
"Zerbra srv version", HFILL }},
{ &hf_zebra_marker,
{ "Marker", "zebra.marker",
FT_UINT8, BASE_HEX, NULL, 0x0,
"Zerbra srv marker", HFILL }},
{ &hf_zebra_request,
{ "Request", "zebra.request",
FT_BOOLEAN, BASE_NONE, NULL, 0x0,
"TRUE if Zebra request", HFILL }},
{ &hf_zebra_command,
{ "Command", "zebra.command",
FT_UINT8, BASE_DEC, VALS(messages), 0x0,
"Zebra command", HFILL }},
{ &hf_zebra_interface,
{ "Interface", "zebra.interface",
FT_STRING, BASE_NONE, NULL, 0x0,
"Interface name of Zebra request", HFILL }},
{ &hf_zebra_index,
{ "Index", "zebra.index",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Index of interface", HFILL }},
{ &hf_zebra_intstatus,
{ "Status", "zebra.intstatus",
FT_UINT8, BASE_DEC, NULL, 0x0,
"Status of interface", HFILL}},
{ &hf_zebra_indexnum,
{ "Index Number", "zebra.indexnum",
FT_UINT8, BASE_DEC, NULL, 0x0,
"Number of indices for route", HFILL }},
{ &hf_zebra_intflags,
{ "Flags", "zebra.intflags",
FT_UINT64, BASE_DEC, NULL, 0x0,
"Flags of interface", HFILL }},
{ &hf_zebra_rtflags,
{ "Flags", "zebra.rtflags",
FT_UINT8, BASE_DEC, NULL, 0x0,
"Flags of route", HFILL }},
{ &hf_zebra_message,
{ "Message", "zebra.message",
FT_UINT8, BASE_DEC, NULL, 0x0,
"Message type of route", HFILL }},
{ &hf_zebra_route_safi,
{ "SAFI", "zebra.safi",
FT_UINT16, BASE_DEC, VALS(safi), 0x0,
"Subsequent Address Family Identifier", HFILL }},
{ &hf_zebra_msg_nexthop,
{ "Message Nexthop", "zebra.message.nexthop",
FT_BOOLEAN, 8, NULL, ZEBRA_ZAPI_MESSAGE_NEXTHOP,
"Message contains nexthop", HFILL }},
{ &hf_zebra_msg_index,
{ "Message Index", "zebra.message.index",
FT_BOOLEAN, 8, NULL, ZEBRA_ZAPI_MESSAGE_IFINDEX,
"Message contains index", HFILL }},
{ &hf_zebra_msg_distance,
{ "Message Distance", "zebra.message.distance",
FT_BOOLEAN, 8, NULL, ZEBRA_ZAPI_MESSAGE_DISTANCE,
"Message contains distance", HFILL }},
{ &hf_zebra_msg_metric,
{ "Message Metric", "zebra.message.metric",
FT_BOOLEAN, 8, NULL, ZEBRA_ZAPI_MESSAGE_METRIC,
"Message contains metric", HFILL }},
{ &hf_zebra_type_v0,
{ "Type", "zebra.type",
FT_UINT8, BASE_DEC, VALS(routes_v0), 0x0,
"Type of route", HFILL }},
{ &hf_zebra_type_v1,
{ "Type", "zebra.type",
FT_UINT8, BASE_DEC, VALS(routes_v1), 0x0,
"Type of route", HFILL }},
{ &hf_zebra_distance,
{ "Distance", "zebra.distance",
FT_UINT8, BASE_DEC, NULL, 0x0,
"Distance of route", HFILL }},
{ &hf_zebra_metric,
{ "Metric", "zebra.metric",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Metric of interface or route", HFILL }},
{ &hf_zebra_mtu,
{ "MTU", "zebra.mtu",
FT_UINT32, BASE_DEC, NULL, 0x0,
"MTU of interface", HFILL }},
{ &hf_zebra_mtu6,
{ "MTUv6", "zebra.mtu6",
FT_UINT32, BASE_DEC, NULL, 0x0,
"MTUv6 of interface", HFILL }},
{ &hf_zebra_bandwidth,
{ "Bandwidth", "zebra.bandwidth",
FT_UINT32, BASE_DEC, NULL, 0x0,
"Bandwidth of interface", HFILL }},
{ &hf_zebra_family,
{ "Family", "zebra.family",
FT_UINT8, BASE_DEC, VALS(families), 0x0,
"Family of IP address", HFILL }},
{ &hf_zebra_flags,
{ "Flags", "zebra.flags",
FT_UINT8, BASE_DEC, NULL, 0x0,
"Flags of Address Info", HFILL }},
{ &hf_zebra_dest4,
{ "Destination", "zebra.dest4",
FT_IPv4, BASE_NONE, NULL, 0x0,
"Destination IPv4 field", HFILL }},
{ &hf_zebra_dest6,
{ "Destination", "zebra.dest6",
FT_IPv6, BASE_NONE, NULL, 0x0,
"Destination IPv6 field", HFILL }},
{ &hf_zebra_nexthopnum,
{ "Nexthop Number", "zebra.nexthopnum",
FT_UINT8, BASE_DEC, NULL, 0x0,
"Number of nexthops in route", HFILL }},
{ &hf_zebra_nexthop4,
{ "Nexthop", "zebra.nexthop4",
FT_IPv4, BASE_NONE, NULL, 0x0,
"Nethop IPv4 field of route", HFILL }},
{ &hf_zebra_nexthop6,
{ "Nexthop", "zebra.nexthop6",
FT_IPv6, BASE_NONE, NULL, 0x0,
"Nethop IPv6 field of route", HFILL }},
{ &hf_zebra_prefixlen,
{ "Prefix length", "zebra.prefixlen",
FT_UINT32, BASE_DEC, NULL, 0x0,
NULL, HFILL }},
{ &hf_zebra_prefix4,
{ "Prefix", "zebra.prefix4",
FT_IPv4, BASE_NONE, NULL, 0x0,
"Prefix IPv4", HFILL }},
{ &hf_zebra_prefix6,
{ "Prefix", "zebra.prefix6",
FT_IPv6, BASE_NONE, NULL, 0x0,
"Prefix IPv6", HFILL }},
{ &hf_zebra_routeridaddress,
{ "Router ID address", "zebra.routerIDAddress",
FT_IPv4, BASE_NONE, NULL, 0x0,
"Router ID", HFILL }},
{ &hf_zebra_routeridmask,
{ "Router ID mask", "zebra.routerIDMask",
FT_UINT8, BASE_DEC, NULL, 0x0,
"netmask of Router ID", HFILL }},
{ &hf_zebra_mac,
{ "MAC address", "zebra.macaddress",
FT_ETHER, BASE_NONE, NULL, 0x0,
"MAC address of interface", HFILL }},
{ &hf_zebra_redist_default,
{ "Redistribute default", "zebra.redist_default",
FT_BOOLEAN, BASE_NONE, NULL, 0x0,
"TRUE if redistribute default", HFILL }}
};
static gint *ett[] = {
&ett_zebra,
&ett_zebra_request,
&ett_message,
};
proto_zebra = proto_register_protocol("Zebra Protocol", "ZEBRA", "zebra");
proto_register_field_array(proto_zebra, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
}
void
proto_reg_handoff_zebra(void)
{
dissector_handle_t zebra_handle;
zebra_handle = create_dissector_handle(dissect_zebra, proto_zebra);
dissector_add_uint("tcp.port", TCP_PORT_ZEBRA, zebra_handle);
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| 31.472626 | 89 | 0.671862 |
9c2e1da599e7bfd7d125b2d4fcc658d0aed91c5a | 518 | c | C | lab5/src/task.c | kinpa200296/OSaE_labs | e4acd6492590476dd4a2c67764b8484bc2111e74 | [
"MIT"
] | null | null | null | lab5/src/task.c | kinpa200296/OSaE_labs | e4acd6492590476dd4a2c67764b8484bc2111e74 | [
"MIT"
] | null | null | null | lab5/src/task.c | kinpa200296/OSaE_labs | e4acd6492590476dd4a2c67764b8484bc2111e74 | [
"MIT"
] | null | null | null | #include "server.h"
#include "client.h"
int main(int argc, char **argv)
{
int delay = 1000;
if (argc > 1)
{
int tmp = 0;
if (sscanf(argv[1], "%d", &tmp))
{
delay = tmp;
}
}
int res = launch_server(delay);
if (res == 1)
{
int tmp = launch_client(delay);
if (tmp)
{
printf("Client failure: %d\n", tmp);
}
}
else if (res)
{
printf("Server failure: %d\n", res);
}
return 0;
} | 16.709677 | 48 | 0.432432 |
9c9311e75f3d0fc282f712c58ce035f1f46df4c4 | 307 | h | C | qqtw/qqheaders7.2/FAViewLinkActivityDelegate-Protocol.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 5 | 2018-02-20T14:24:17.000Z | 2020-08-06T09:31:21.000Z | qqtw/qqheaders7.2/FAViewLinkActivityDelegate-Protocol.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 1 | 2020-06-10T07:49:16.000Z | 2020-06-12T02:08:35.000Z | qqtw/qqheaders7.2/FAViewLinkActivityDelegate-Protocol.h | onezens/SmartQQ | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class FAViewLinkActivity;
@protocol FAViewLinkActivityDelegate <NSObject>
- (void)FAViewLinkActivityDidAction:(FAViewLinkActivity *)arg1;
@end
| 20.466667 | 83 | 0.71987 |
80cfa3b31a4adf8da1b816e299e6dab80a47668e | 1,148 | h | C | Descending Europa/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_Hashtable_SyncHashtable860554494.h | screwylightbulb/europa | 3dcc98369c8066cb2310143329535206751c8846 | [
"MIT"
] | 11 | 2016-07-22T19:58:09.000Z | 2021-09-21T12:51:40.000Z | Descending Europa/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_Hashtable_SyncHashtable860554494.h | screwylightbulb/europa | 3dcc98369c8066cb2310143329535206751c8846 | [
"MIT"
] | 1 | 2018-05-07T14:32:13.000Z | 2018-05-08T09:15:30.000Z | iOS/Classes/Native/mscorlib_System_Collections_Hashtable_SyncHashtable860554494.h | mopsicus/unity-share-plugin-ios-android | 3ee99aef36034a1e4d7b156172953f9b4dfa696f | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Collections.Hashtable
struct Hashtable_t1407064410;
#include "mscorlib_System_Collections_Hashtable1407064410.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Hashtable/SyncHashtable
struct SyncHashtable_t860554494 : public Hashtable_t1407064410
{
public:
// System.Collections.Hashtable System.Collections.Hashtable/SyncHashtable::host
Hashtable_t1407064410 * ___host_14;
public:
inline static int32_t get_offset_of_host_14() { return static_cast<int32_t>(offsetof(SyncHashtable_t860554494, ___host_14)); }
inline Hashtable_t1407064410 * get_host_14() const { return ___host_14; }
inline Hashtable_t1407064410 ** get_address_of_host_14() { return &___host_14; }
inline void set_host_14(Hashtable_t1407064410 * value)
{
___host_14 = value;
Il2CppCodeGenWriteBarrier(&___host_14, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 25.511111 | 127 | 0.79878 |
d5b7ef1f8952393d024d1fccdc93844fbd271f6d | 15,265 | c | C | 3party/gtk+-3.12.1/gtk/gtkstackswitcher.c | kongaraju/antkorp | 3453d543d659e3420d5bc4b536016bb1d097d7ec | [
"CC-BY-3.0",
"Apache-2.0"
] | 1 | 2016-01-02T14:39:07.000Z | 2016-01-02T14:39:07.000Z | 3party/gtk+-3.12.1/gtk/gtkstackswitcher.c | kongaraju/antkorp | 3453d543d659e3420d5bc4b536016bb1d097d7ec | [
"CC-BY-3.0",
"Apache-2.0"
] | 4 | 2019-12-20T06:13:24.000Z | 2021-07-03T16:28:18.000Z | 3party/gtk+-3.12.1/gtk/gtkstackswitcher.c | kongaraju/antkorp | 3453d543d659e3420d5bc4b536016bb1d097d7ec | [
"CC-BY-3.0",
"Apache-2.0"
] | 2 | 2015-09-17T16:40:10.000Z | 2016-11-17T15:56:42.000Z | /*
* Copyright (c) 2013 Red Hat, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "config.h"
#include "gtkstackswitcher.h"
#include "gtkradiobutton.h"
#include "gtklabel.h"
#include "gtkorientable.h"
#include "gtkprivate.h"
#include "gtkintl.h"
/**
* SECTION:gtkstackswitcher
* @Short_description: A controller for GtkStack
* @Title: GtkStackSwitcher
* @See_also: #GtkStack
*
* The GtkStackSwitcher widget acts as a controller for a
* #GtkStack; it shows a row of buttons to switch between
* the various pages of the associated stack widget.
*
* All the content for the buttons comes from the child properties
* of the #GtkStack.
*
* It is possible to associate multiple #GtkStackSwitcher widgets
* with the same stack widget.
*
* The GtkStackSwitcher widget was added in 3.10.
*/
typedef struct _GtkStackSwitcherPrivate GtkStackSwitcherPrivate;
struct _GtkStackSwitcherPrivate
{
GtkStack *stack;
GHashTable *buttons;
gboolean in_child_changed;
};
enum {
PROP_0,
PROP_STACK
};
G_DEFINE_TYPE_WITH_PRIVATE (GtkStackSwitcher, gtk_stack_switcher, GTK_TYPE_BOX)
static void
gtk_stack_switcher_init (GtkStackSwitcher *switcher)
{
GtkStyleContext *context;
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (switcher);
priv->stack = NULL;
priv->buttons = g_hash_table_new (g_direct_hash, g_direct_equal);
context = gtk_widget_get_style_context (GTK_WIDGET (switcher));
gtk_style_context_add_class (context, "stack-switcher");
gtk_style_context_add_class (context, GTK_STYLE_CLASS_LINKED);
gtk_orientable_set_orientation (GTK_ORIENTABLE (switcher), GTK_ORIENTATION_HORIZONTAL);
}
static void
clear_switcher (GtkStackSwitcher *self)
{
gtk_container_foreach (GTK_CONTAINER (self), (GtkCallback) gtk_widget_destroy, self);
}
static void
on_button_clicked (GtkWidget *widget,
GtkStackSwitcher *self)
{
GtkWidget *child;
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (self);
if (!priv->in_child_changed)
{
child = g_object_get_data (G_OBJECT (widget), "stack-child");
gtk_stack_set_visible_child (priv->stack, child);
}
}
static void
rebuild_child (GtkWidget *self,
const gchar *icon_name,
const gchar *title)
{
GtkStyleContext *context;
GtkWidget *button_child;
gtk_widget_set_valign (GTK_WIDGET (self), GTK_ALIGN_CENTER);
button_child = gtk_bin_get_child (GTK_BIN (self));
if (button_child != NULL)
gtk_widget_destroy (button_child);
button_child = NULL;
context = gtk_widget_get_style_context (GTK_WIDGET (self));
if (icon_name != NULL)
{
button_child = gtk_image_new_from_icon_name (icon_name, GTK_ICON_SIZE_MENU);
if (title != NULL)
gtk_widget_set_tooltip_text (GTK_WIDGET (self), title);
gtk_style_context_remove_class (context, "text-button");
gtk_style_context_add_class (context, "image-button");
}
else if (title != NULL)
{
button_child = gtk_label_new (title);
gtk_widget_set_tooltip_text (GTK_WIDGET (self), NULL);
gtk_style_context_remove_class (context, "image-button");
gtk_style_context_add_class (context, "text-button");
}
if (button_child)
{
gtk_widget_show_all (button_child);
gtk_container_add (GTK_CONTAINER (self), button_child);
}
}
static void
update_needs_attention (GtkWidget *widget, GtkWidget *button, gpointer data)
{
GtkContainer *container;
gboolean needs_attention;
GtkStyleContext *context;
container = GTK_CONTAINER (data);
gtk_container_child_get (container, widget,
"needs-attention", &needs_attention,
NULL);
context = gtk_widget_get_style_context (button);
if (needs_attention && !gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
gtk_style_context_add_class (context, GTK_STYLE_CLASS_NEEDS_ATTENTION);
else
gtk_style_context_remove_class (context, GTK_STYLE_CLASS_NEEDS_ATTENTION);
}
static void
update_button (GtkStackSwitcher *self,
GtkWidget *widget,
GtkWidget *button)
{
gchar *title;
gchar *icon_name;
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (self);
gtk_container_child_get (GTK_CONTAINER (priv->stack), widget,
"title", &title,
"icon-name", &icon_name,
NULL);
rebuild_child (button, icon_name, title);
gtk_widget_set_visible (button, gtk_widget_get_visible (widget) && (title != NULL || icon_name != NULL));
if (icon_name != NULL)
gtk_widget_set_size_request (button, -1, -1);
else
gtk_widget_set_size_request (button, 100, -1);
g_free (title);
g_free (icon_name);
update_needs_attention (widget, button, priv->stack);
}
static void
on_title_icon_visible_updated (GtkWidget *widget,
GParamSpec *pspec,
GtkStackSwitcher *self)
{
GtkWidget *button;
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (self);
button = g_hash_table_lookup (priv->buttons, widget);
update_button (self, widget, button);
}
static void
on_position_updated (GtkWidget *widget,
GParamSpec *pspec,
GtkStackSwitcher *self)
{
GtkWidget *button;
gint position;
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (self);
button = g_hash_table_lookup (priv->buttons, widget);
gtk_container_child_get (GTK_CONTAINER (priv->stack), widget,
"position", &position,
NULL);
gtk_box_reorder_child (GTK_BOX (self), button, position);
}
static void
on_needs_attention_updated (GtkWidget *widget,
GParamSpec *pspec,
GtkStackSwitcher *self)
{
GtkWidget *button;
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (self);
button = g_hash_table_lookup (priv->buttons, widget);
update_button (self, widget, button);
}
static void
add_child (GtkStackSwitcher *self,
GtkWidget *widget)
{
GtkWidget *button;
GList *group;
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (self);
button = gtk_radio_button_new (NULL);
gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (button), FALSE);
update_button (self, widget, button);
group = gtk_container_get_children (GTK_CONTAINER (self));
if (group != NULL)
{
gtk_radio_button_join_group (GTK_RADIO_BUTTON (button), GTK_RADIO_BUTTON (group->data));
g_list_free (group);
}
gtk_container_add (GTK_CONTAINER (self), button);
g_object_set_data (G_OBJECT (button), "stack-child", widget);
g_signal_connect (button, "clicked", G_CALLBACK (on_button_clicked), self);
g_signal_connect (widget, "notify::visible", G_CALLBACK (on_title_icon_visible_updated), self);
g_signal_connect (widget, "child-notify::title", G_CALLBACK (on_title_icon_visible_updated), self);
g_signal_connect (widget, "child-notify::icon-name", G_CALLBACK (on_title_icon_visible_updated), self);
g_signal_connect (widget, "child-notify::position", G_CALLBACK (on_position_updated), self);
g_signal_connect (widget, "child-notify::needs-attention", G_CALLBACK (on_needs_attention_updated), self);
g_hash_table_insert (priv->buttons, widget, button);
}
static void
foreach_stack (GtkWidget *widget,
GtkStackSwitcher *self)
{
add_child (self, widget);
}
static void
populate_switcher (GtkStackSwitcher *self)
{
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (self);
gtk_container_foreach (GTK_CONTAINER (priv->stack), (GtkCallback)foreach_stack, self);
}
static void
on_child_changed (GtkWidget *widget,
GParamSpec *pspec,
GtkStackSwitcher *self)
{
GtkWidget *child;
GtkWidget *button;
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (self);
child = gtk_stack_get_visible_child (GTK_STACK (widget));
button = g_hash_table_lookup (priv->buttons, child);
if (button != NULL)
{
priv->in_child_changed = TRUE;
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
priv->in_child_changed = FALSE;
}
}
static void
on_stack_child_added (GtkContainer *container,
GtkWidget *widget,
GtkStackSwitcher *self)
{
add_child (self, widget);
}
static void
on_stack_child_removed (GtkContainer *container,
GtkWidget *widget,
GtkStackSwitcher *self)
{
GtkWidget *button;
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (self);
button = g_hash_table_lookup (priv->buttons, widget);
gtk_container_remove (GTK_CONTAINER (self), button);
g_hash_table_remove (priv->buttons, widget);
}
static void
disconnect_stack_signals (GtkStackSwitcher *switcher)
{
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (switcher);
g_signal_handlers_disconnect_by_func (priv->stack, on_stack_child_added, switcher);
g_signal_handlers_disconnect_by_func (priv->stack, on_stack_child_removed, switcher);
g_signal_handlers_disconnect_by_func (priv->stack, on_child_changed, switcher);
g_signal_handlers_disconnect_by_func (priv->stack, disconnect_stack_signals, switcher);
}
static void
connect_stack_signals (GtkStackSwitcher *switcher)
{
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (switcher);
g_signal_connect_after (priv->stack, "add",
G_CALLBACK (on_stack_child_added), switcher);
g_signal_connect_after (priv->stack, "remove",
G_CALLBACK (on_stack_child_removed), switcher);
g_signal_connect (priv->stack, "notify::visible-child",
G_CALLBACK (on_child_changed), switcher);
g_signal_connect_swapped (priv->stack, "destroy",
G_CALLBACK (disconnect_stack_signals), switcher);
}
/**
* gtk_stack_switcher_set_stack:
* @switcher: a #GtkStackSwitcher
* @stack: (allow-none): a #GtkStack
*
* Sets the stack to control.
*
* Since: 3.10
*/
void
gtk_stack_switcher_set_stack (GtkStackSwitcher *switcher,
GtkStack *stack)
{
GtkStackSwitcherPrivate *priv;
g_return_if_fail (GTK_IS_STACK_SWITCHER (switcher));
g_return_if_fail (GTK_IS_STACK (stack) || stack == NULL);
priv = gtk_stack_switcher_get_instance_private (switcher);
if (priv->stack == stack)
return;
if (priv->stack)
{
disconnect_stack_signals (switcher);
clear_switcher (switcher);
g_clear_object (&priv->stack);
}
if (stack)
{
priv->stack = g_object_ref (stack);
populate_switcher (switcher);
connect_stack_signals (switcher);
}
gtk_widget_queue_resize (GTK_WIDGET (switcher));
g_object_notify (G_OBJECT (switcher), "stack");
}
/**
* gtk_stack_switcher_get_stack:
* @switcher: a #GtkStackSwitcher
*
* Retrieves the stack.
* See gtk_stack_switcher_set_stack().
*
* Returns: (transfer none): the stack, or %NULL if
* none has been set explicitly.
*
* Since: 3.10
*/
GtkStack *
gtk_stack_switcher_get_stack (GtkStackSwitcher *switcher)
{
GtkStackSwitcherPrivate *priv;
g_return_val_if_fail (GTK_IS_STACK_SWITCHER (switcher), NULL);
priv = gtk_stack_switcher_get_instance_private (switcher);
return priv->stack;
}
static void
gtk_stack_switcher_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GtkStackSwitcher *switcher = GTK_STACK_SWITCHER (object);
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (switcher);
switch (prop_id)
{
case PROP_STACK:
g_value_set_object (value, priv->stack);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gtk_stack_switcher_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GtkStackSwitcher *switcher = GTK_STACK_SWITCHER (object);
switch (prop_id)
{
case PROP_STACK:
gtk_stack_switcher_set_stack (switcher, g_value_get_object (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gtk_stack_switcher_dispose (GObject *object)
{
GtkStackSwitcher *switcher = GTK_STACK_SWITCHER (object);
gtk_stack_switcher_set_stack (switcher, NULL);
G_OBJECT_CLASS (gtk_stack_switcher_parent_class)->dispose (object);
}
static void
gtk_stack_switcher_finalize (GObject *object)
{
GtkStackSwitcher *switcher = GTK_STACK_SWITCHER (object);
GtkStackSwitcherPrivate *priv;
priv = gtk_stack_switcher_get_instance_private (switcher);
g_hash_table_destroy (priv->buttons);
G_OBJECT_CLASS (gtk_stack_switcher_parent_class)->finalize (object);
}
static void
gtk_stack_switcher_class_init (GtkStackSwitcherClass *class)
{
GObjectClass *object_class = G_OBJECT_CLASS (class);
object_class->get_property = gtk_stack_switcher_get_property;
object_class->set_property = gtk_stack_switcher_set_property;
object_class->dispose = gtk_stack_switcher_dispose;
object_class->finalize = gtk_stack_switcher_finalize;
g_object_class_install_property (object_class,
PROP_STACK,
g_param_spec_object ("stack",
P_("Stack"),
P_("Stack"),
GTK_TYPE_STACK,
GTK_PARAM_READWRITE |
G_PARAM_CONSTRUCT));
}
/**
* gtk_stack_switcher_new:
*
* Create a new #GtkStackSwitcher.
*
* Returns: a new #GtkStackSwitcher.
*
* Since: 3.10
*/
GtkWidget *
gtk_stack_switcher_new (void)
{
return g_object_new (GTK_TYPE_STACK_SWITCHER, NULL);
}
| 28.910985 | 108 | 0.687127 |
5797080d6e10d2e3854ba9411ed26e318788cbad | 528 | h | C | src/qt/macos_appnap.h | UFO-ETL/ufo | e85dde0c8b12c1bf3357003afb77ea85b1476d6b | [
"MIT"
] | null | null | null | src/qt/macos_appnap.h | UFO-ETL/ufo | e85dde0c8b12c1bf3357003afb77ea85b1476d6b | [
"MIT"
] | null | null | null | src/qt/macos_appnap.h | UFO-ETL/ufo | e85dde0c8b12c1bf3357003afb77ea85b1476d6b | [
"MIT"
] | null | null | null | // Copyright (c) 2011-2018 The UFO Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef UFO_QT_MACOS_APPNAP_H
#define UFO_QT_MACOS_APPNAP_H
#include <memory>
class CAppNapInhiufoor final
{
public:
explicit CAppNapInhiufoor();
~CAppNapInhiufoor();
void disableAppNap();
void enableAppNap();
private:
class CAppNapImpl;
std::unique_ptr<CAppNapImpl> impl;
};
#endif // UFO_QT_MACOS_APPNAP_H
| 21.12 | 70 | 0.75 |
3ba784a776691574433f533885dddbdfc76b631b | 542 | h | C | StripeStore/_CartLineItem.h | CIGIHub/stripestoreapp | 89e0adf18d1303347585d7ddead07f73956e7304 | [
"MIT"
] | null | null | null | StripeStore/_CartLineItem.h | CIGIHub/stripestoreapp | 89e0adf18d1303347585d7ddead07f73956e7304 | [
"MIT"
] | null | null | null | StripeStore/_CartLineItem.h | CIGIHub/stripestoreapp | 89e0adf18d1303347585d7ddead07f73956e7304 | [
"MIT"
] | null | null | null | //
// CartLineItem.h
// StripeStore
//
// Created by Caroline Simpson on 2013-07-10.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class Order, Product;
@interface _CartLineItem : NSManagedObject
@property (nonatomic, retain) NSDecimalNumber * itemPrice;
@property (nonatomic, retain) NSNumber * quantity;
@property (nonatomic, retain) NSDecimalNumber * rowTotal;
@property (nonatomic, retain) NSString * itemName;
@property (nonatomic, retain) Order *order;
@property (nonatomic, retain) Product *product;
@end
| 23.565217 | 58 | 0.749077 |
22e85851f098dd3458dce0234192577b2c046ae1 | 12,061 | h | C | algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/nvbio/nvbio/basic/cuda/work_queue_multipass_inl.h | mfkiwl/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | [
"BSD-3-Clause"
] | 2,111 | 2019-01-29T07:01:32.000Z | 2022-03-29T06:48:14.000Z | algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/nvbio/nvbio/basic/cuda/work_queue_multipass_inl.h | mfkiwl/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | [
"BSD-3-Clause"
] | 131 | 2019-02-18T10:56:18.000Z | 2021-09-27T12:07:00.000Z | algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/nvbio/nvbio/basic/cuda/work_queue_multipass_inl.h | mfkiwl/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | [
"BSD-3-Clause"
] | 421 | 2019-02-12T07:59:18.000Z | 2022-03-27T05:22:01.000Z | /*
* nvbio
* Copyright (c) 2011-2014, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION 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 NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <nvbio/basic/types.h>
#include <nvbio/basic/numbers.h>
#include <nvbio/basic/cuda/arch.h>
#include <cub/cub.cuh>
#include <thrust/scan.h>
namespace nvbio {
namespace cuda {
///@addtogroup WorkQueue
///@{
namespace wq {
///@addtogroup WorkQueueDetail
///@{
template <
uint32 BLOCKDIM,
typename WorkUnitT,
typename WorkStreamT,
bool DO_LOADS>
__global__
void mk_work_queue_kernel(
const uint32 n_tile_grids,
typename WorkQueue<MultiPassQueueTag,WorkUnitT,BLOCKDIM>::Context context,
const uint32 in_queue_id,
const uint32 in_queue_size,
const WorkStreamT stream,
uint32 stream_begin)
{
typedef WorkUnitT WorkUnit;
const uint32 grid_threads = gridDim.x * BLOCKDIM;
const uint32 queue_capacity = grid_threads * n_tile_grids;
const uint32 thread_id = threadIdx.x + blockIdx.x*BLOCKDIM;
WorkUnit* work_queue = context.m_work_queue + queue_capacity*in_queue_id;
uint32* continuations = context.m_continuations;
const uint32 stream_end = stream.size();
uint32 in_work_queue_size = in_queue_size;
if (DO_LOADS)
{
// try to load more work to do
for (uint32 i = 0; i < n_tile_grids; ++i)
{
const uint32 work_begin = grid_threads * i;
const uint32 work_id = thread_id + work_begin;
// if the work queue is not full, and there's remaining work in the stream, fetch some more
if ((work_begin <= in_work_queue_size) &&
(work_begin + grid_threads > in_work_queue_size) &&
(stream_begin < stream_end))
{
const uint32 n_loaded = nvbio::min( stream_end - stream_begin, grid_threads - (in_work_queue_size - work_begin) );
// fetch a new work unit
if ((work_id >= in_work_queue_size) &&
(work_id - in_work_queue_size < n_loaded))
stream.get( stream_begin + work_id - in_work_queue_size, work_queue + work_id, make_uint2( work_id, in_queue_id ) );
in_work_queue_size += n_loaded;
stream_begin += n_loaded;
}
}
}
// compute how many tiles are needed to cover the input queue
const uint32 n_active_tile_grids = (in_work_queue_size + grid_threads-1) / grid_threads;
// execute the queued work units
for (uint32 i = 0; i < n_active_tile_grids; ++i)
{
const uint32 work_id = thread_id + grid_threads * i;
// execute this thread's work unit
if (work_id < in_work_queue_size)
{
const bool has_continuation = work_queue[ work_id ].run( stream );
continuations[ work_id ] = has_continuation ? 1u : 0u;
}
}
}
template <
uint32 BLOCKDIM,
typename WorkUnitT,
typename WorkStreamT>
__global__
void mk_load_kernel(
const uint32 n_tile_grids,
typename WorkQueue<MultiPassQueueTag,WorkUnitT,BLOCKDIM>::Context context,
const uint32 in_queue_id,
const uint32 in_queue_size,
const WorkStreamT stream,
uint32 stream_begin)
{
typedef WorkUnitT WorkUnit;
const uint32 grid_threads = gridDim.x * BLOCKDIM;
const uint32 queue_capacity = grid_threads * n_tile_grids;
const uint32 thread_id = threadIdx.x + blockIdx.x*BLOCKDIM;
WorkUnit* work_queue = context.m_work_queue + queue_capacity*in_queue_id;
const uint32 stream_end = stream.size();
uint32 in_work_queue_size = in_queue_size;
// try to load more work to do
for (uint32 i = 0; i < n_tile_grids; ++i)
{
const uint32 work_begin = grid_threads * i;
const uint32 work_id = thread_id + work_begin;
// if the work queue is not full, and there's remaining work in the stream, fetch some more
if ((work_begin <= in_work_queue_size) &&
(work_begin + grid_threads > in_work_queue_size) &&
(stream_begin < stream_end))
{
const uint32 n_loaded = nvbio::min( stream_end - stream_begin, grid_threads - (in_work_queue_size - work_begin) );
// fetch a new work unit
if ((work_id >= in_work_queue_size) &&
(work_id - in_work_queue_size < n_loaded))
stream.get( stream_begin + work_id - in_work_queue_size, work_queue + work_id, make_uint2( work_id, in_queue_id ) );
in_work_queue_size += n_loaded;
stream_begin += n_loaded;
}
}
}
template <
uint32 BLOCKDIM,
typename WorkUnitT,
typename WorkStream,
typename WorkMover>
__global__
void mk_move_kernel(
const uint32 n_tile_grids,
typename WorkQueue<MultiPassQueueTag,WorkUnitT,BLOCKDIM>::Context context,
const uint32 in_queue_id,
const uint32 in_queue_size,
const WorkStream stream,
const WorkMover mover)
{
typedef WorkUnitT WorkUnit;
const uint32 grid_threads = gridDim.x * BLOCKDIM;
const uint32 queue_capacity = grid_threads * n_tile_grids;
const uint32 thread_id = threadIdx.x + blockIdx.x*BLOCKDIM;
WorkUnit* in_work_queue = context.m_work_queue + queue_capacity*(in_queue_id ? 1 : 0);
WorkUnit* out_work_queue = context.m_work_queue + queue_capacity*(in_queue_id ? 0 : 1);
const uint32* continuations = context.m_continuations;
// compute how many tiles are needed to cover the input queue
const uint32 n_active_tile_grids = (in_queue_size + grid_threads-1) / grid_threads;
// move the continuations from the input queue to the output queue
for (uint32 i = 0; i < n_active_tile_grids; ++i)
{
const uint32 work_id = thread_id + grid_threads * i;
if (work_id < in_queue_size)
{
const uint32 prev_slot = work_id ? continuations[ work_id-1 ] : 0u;
const uint32 next_slot = continuations[ work_id ];
const bool has_continuation = (next_slot > prev_slot);
if (has_continuation)
{
// move the work-unit
mover.move( stream,
make_uint2( work_id, in_queue_id ? 1 : 0 ), &in_work_queue[ work_id ],
make_uint2( prev_slot, in_queue_id ? 0 : 1 ), &out_work_queue[ prev_slot ] );
}
}
}
}
///@} // WorkQueueDetail
} // namespace wq
// consume a stream of work units
//
template <
typename WorkUnitT,
uint32 BLOCKDIM>
template <typename WorkStream, typename WorkMover>
void WorkQueue<MultiPassQueueTag,WorkUnitT,BLOCKDIM>::consume(const WorkStream stream, const WorkMover mover, WorkQueueStats* stats)
{
// compute the number of blocks we are going to launch
const uint32 n_blocks = m_separate_loads ?
(uint32)cuda::max_active_blocks( wq::mk_work_queue_kernel<BLOCKDIM,WorkUnit,WorkStream,false>, BLOCKDIM, 0u ) :
(uint32)cuda::max_active_blocks( wq::mk_work_queue_kernel<BLOCKDIM,WorkUnit,WorkStream,true>, BLOCKDIM, 0u );
const uint32 grid_threads = n_blocks * BLOCKDIM;
const uint32 n_tile_grids = m_capacity / grid_threads;
const uint32 queue_capacity = grid_threads * n_tile_grids;
m_continuations.resize( queue_capacity );
m_work_queue.resize( queue_capacity * 2 ); // alloc space for an input and an output queue
const uint32 stream_size = stream.size();
uint32 in = 0;
uint32 in_queue_size = 0;
uint32 stream_begin = 0;
uint32 stream_end = stream_size;
typename thrust::device_vector<WorkUnit>::iterator in_queue_begin = m_work_queue.begin();
typename thrust::device_vector<WorkUnit>::iterator out_queue_begin = m_work_queue.begin() + queue_capacity;
while (in_queue_size || stream_begin < stream_end)
{
const uint32 to_load = nvbio::min( queue_capacity - in_queue_size, stream_end - stream_begin );
if (m_separate_loads)
{
// launch the loading kernel
wq::mk_load_kernel<BLOCKDIM,WorkUnit,WorkStream> <<<n_blocks,BLOCKDIM>>>( n_tile_grids, get_context(), in, in_queue_size, stream, stream_begin );
// update stream pointer
stream_begin += to_load;
// update input queue size
in_queue_size += to_load;
// launch the consuming kernel
wq::mk_work_queue_kernel<BLOCKDIM,WorkUnit,WorkStream,false> <<<n_blocks,BLOCKDIM>>>( n_tile_grids, get_context(), in, in_queue_size, stream, stream_begin );
}
else
{
// launch the consuming kernel
wq::mk_work_queue_kernel<BLOCKDIM,WorkUnit,WorkStream,true> <<<n_blocks,BLOCKDIM>>>( n_tile_grids, get_context(), in, in_queue_size, stream, stream_begin );
// update stream pointer
stream_begin += to_load;
// update input queue size
in_queue_size += to_load;
}
// compact the output
thrust::inclusive_scan(
m_continuations.begin(),
m_continuations.begin() + in_queue_size,
m_continuations.begin() );
// synchronize on the scan
cudaDeviceSynchronize();
const uint32 out_queue_size = m_continuations[ in_queue_size - 1 ];
// launch the movement kernel
wq::mk_move_kernel<BLOCKDIM,WorkUnit,WorkStream,WorkMover> <<<n_blocks,BLOCKDIM>>>( n_tile_grids, get_context(), in, in_queue_size, stream, mover );
// swap queue pointers
in = in ? 0u : 1u;
std::swap( in_queue_begin, out_queue_begin );
in_queue_size = out_queue_size;
}
}
///@} // WorkQueue
} // namespace cuda
} // namespace nvbio
| 39.544262 | 169 | 0.619269 |
d7f5643b1974d2a69c07fcff31a5aeee30f51243 | 1,472 | h | C | Misc/UnusedCode/widgets/rojue_RDraggableNumber.h | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 34 | 2017-04-19T18:26:02.000Z | 2022-02-15T17:47:26.000Z | Misc/UnusedCode/widgets/rojue_RDraggableNumber.h | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | Misc/UnusedCode/widgets/rojue_RDraggableNumber.h | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 4 | 2017-09-05T17:04:31.000Z | 2021-12-15T21:24:28.000Z | #ifndef rojue_RDraggableNumber_h
#define rojue_RDraggableNumber_h
#include "rojue_RSlider.h"
namespace rojue
{
class RDraggableNumber : public RSlider
{
public:
//---------------------------------------------------------------------------------------------
// construction/destruction:
/** Constructor. */
RDraggableNumber(const juce::String& componentName);
/** Destructor. */
virtual ~RDraggableNumber();
//---------------------------------------------------------------------------------------------
// others:
/** Overrides the way in which the slider is painted. */
virtual void paint(Graphics& g);
/** Overrides the behaviour on mouse-down events. */
virtual void mouseDown (const MouseEvent& e);
//virtual void mouseUp (const MouseEvent& e);
/** Overrides the behaviour on mouse-drag events. */
virtual void mouseDrag (const MouseEvent& e);
/** Overrides the behaviour on mouse-double click events. */
//virtual void mouseDoubleClick (const MouseEvent& e);
//virtual void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
//===============================================================================================
juce_UseDebuggingNewOperator;
protected:
double valueOnMouseDown;
RDraggableNumber (const RDraggableNumber&);
const RDraggableNumber& operator= (const RDraggableNumber&);
};
}
#endif
| 25.824561 | 102 | 0.556386 |
4a11c6afcb024d2fafe5ff39f76571e85e0cc866 | 329 | h | C | Engine/src/event_MappedObserver.h | realn/exptor3D | 85bafa0a4c59eb15102756046805e4f9b23245c2 | [
"MIT"
] | null | null | null | Engine/src/event_MappedObserver.h | realn/exptor3D | 85bafa0a4c59eb15102756046805e4f9b23245c2 | [
"MIT"
] | null | null | null | Engine/src/event_MappedObserver.h | realn/exptor3D | 85bafa0a4c59eb15102756046805e4f9b23245c2 | [
"MIT"
] | null | null | null | #pragma once
#include "event_Observer.h"
#include "event_Mapper.h"
namespace event {
class MappedObserver
: public IObserver {
public:
~MappedObserver() override = default;
virtual void processEvent(const Event& event) override {
mapper.executeEvent(event);
}
protected:
Mapper mapper;
};
}
| 16.45 | 60 | 0.683891 |
78703de5be301c3f2f3b542f814d1420289948ed | 2,009 | h | C | third-party/rkh/source/sm/test/inc/smTest.h | sporaio/spora-firmware | fe61a7964ff91bf0807653607e7f18284676fcc6 | [
"BSD-2-Clause"
] | 3 | 2018-10-08T09:58:27.000Z | 2020-08-13T13:28:28.000Z | third-party/rkh/source/sma/test/sma/inc/smTest.h | sporaio/spora-firmware | fe61a7964ff91bf0807653607e7f18284676fcc6 | [
"BSD-2-Clause"
] | null | null | null | third-party/rkh/source/sma/test/sma/inc/smTest.h | sporaio/spora-firmware | fe61a7964ff91bf0807653607e7f18284676fcc6 | [
"BSD-2-Clause"
] | null | null | null | /**
* \file smTest.h
* \ingroup Test
*
* \brief State machine to facilitate the test of production code.
*/
/* -------------------------- Development history -------------------------- */
/*
* 2016.03.17 LeFr v1.0.00 Initial version
*/
/* -------------------------------- Authors -------------------------------- */
/*
* LeFr Leandro Francucci lf@vortexmakes.com
*/
/* --------------------------------- Notes --------------------------------- */
/* --------------------------------- Module -------------------------------- */
#ifndef __SMTEST_H__
#define __SMTEST_H__
/* ----------------------------- Include files ----------------------------- */
#include "rkh.h"
/* ---------------------- External C language linkage ---------------------- */
#ifdef __cplusplus
extern "C" {
#endif
/* --------------------------------- Macros -------------------------------- */
/* -------------------------------- Constants ------------------------------ */
/* Signals */
enum
{
A, B, C, D, E, F, G, H, I, TERMINATE,
SMTEST_NUM_EVENTS
};
/* Declare HSM */
RKH_SMA_DCLR(smTest);
/* Declare states and pseudostates */
RKH_DCLR_COMP_STATE s2, s22, s3, s221, s222, s2221;
RKH_DCLR_BASIC_STATE waiting, s0, s1, s21, s2211, s22211, s31, s4, s5;
RKH_DCLR_FINAL_STATE s2Final;
/* ------------------------------- Data types ------------------------------ */
typedef struct SmTest SmTest;
struct SmTest /* SMA derived from RKH_SMA_T structure */
{
RKH_SMA_T sma; /* base structure */
rui8_t foo; /* private member */
};
/* -------------------------- External variables --------------------------- */
/* -------------------------- Function prototypes -------------------------- */
/* -------------------- External C language linkage end -------------------- */
#ifdef __cplusplus
}
#endif
/* ------------------------------ Module end ------------------------------- */
#endif
/* ------------------------------ End of file ------------------------------ */
| 27.148649 | 79 | 0.375311 |
78f9ef065d4fedf2c9ecad98344ec68089feb7f1 | 1,346 | h | C | src/cpp/NgxBuf.h | Nov11/nginx_with_cpp | 7a8524f4685753cd7e315c181aa587b3f74fc3c9 | [
"BSD-2-Clause"
] | 1 | 2019-01-25T07:01:03.000Z | 2019-01-25T07:01:03.000Z | src/cpp/NgxBuf.h | Nov11/nginx_with_cpp | 7a8524f4685753cd7e315c181aa587b3f74fc3c9 | [
"BSD-2-Clause"
] | null | null | null | src/cpp/NgxBuf.h | Nov11/nginx_with_cpp | 7a8524f4685753cd7e315c181aa587b3f74fc3c9 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by c6s on 18-1-29.
//
#ifndef NGINX_WITH_CPP_NGXBUF_H
#define NGINX_WITH_CPP_NGXBUF_H
#include <Nginx.h>
#include <ngx_string.h>
#include "NgxPool.h"
class NgxBuf : public NgxWrapper<ngx_buf_t> {
public:
NgxBuf(const NgxPool &p, std::size_t n) : NgxWrapper(p.buffer(n)) {}
NgxBuf(ngx_buf_t* p):NgxWrapper(p){}
bool isInMemory() const {
return ngx_buf_in_memory(get());
}
bool memoryonly() const {
return ngx_buf_in_memory_only(get());
}
bool speial() const {
return ngx_buf_special(get());
}
//INTENTION IS NOT CLEAR
void range(u_char *a, u_char *b) const {
get()->pos = a;
get()->last = b;
get()->memory = true;
}
void boundary(u_char *a, u_char *b) const {
get()->start = a;
get()->end = b;
}
void range(ngx_str_t *s) const {
range(s->data, s->data + s->len);
boundary(s->data, s->data + s->len);
}
ngx_str_t range() const {
return ngx_str_t{static_cast<size_t >(get()->last - get()->pos), get()->pos};
}
ngx_str_t boundary() const {
return ngx_str_t{static_cast<size_t>(get()->end - get()->start), get()->start};
}
bool last() const {
return get()->last_buf || get()->last_in_chain;
}
bool finish(bool flag = true) const {
get()->last_buf = flag;
get()->last_in_chain = flag;
}
};
#endif //NGINX_WITH_CPP_NGXBUF_H
| 22.813559 | 83 | 0.625557 |
cd21d057b6f9e0e236b3425ff9504c3b024cfb63 | 313 | c | C | libc/pthread/pthread_spin_trylock.c | MSathieu/OS | 7b91d9ebf2acbfeee09dd8736089c449b0a5746e | [
"Unlicense"
] | 1 | 2021-03-13T10:22:42.000Z | 2021-03-13T10:22:42.000Z | libc/pthread/pthread_spin_trylock.c | MSathieu/OS | 7b91d9ebf2acbfeee09dd8736089c449b0a5746e | [
"Unlicense"
] | null | null | null | libc/pthread/pthread_spin_trylock.c | MSathieu/OS | 7b91d9ebf2acbfeee09dd8736089c449b0a5746e | [
"Unlicense"
] | null | null | null | #include <errno.h>
#include <pthread.h>
int pthread_spin_trylock(pthread_spinlock_t* spinlock) {
bool expected = 0;
if (__atomic_compare_exchange_n(spinlock, &expected, 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) {
__atomic_thread_fence(__ATOMIC_SEQ_CST);
return 0;
} else {
return EBUSY;
}
}
| 24.076923 | 99 | 0.728435 |
2f1dd5ec1225611e56db27337123f8a388d1b305 | 377 | h | C | include/ozo/asio.h | IlyaSidorov/ozo | cdc667b700c7ae6dcf723ef6f939a8495f40fb7e | [
"PostgreSQL"
] | null | null | null | include/ozo/asio.h | IlyaSidorov/ozo | cdc667b700c7ae6dcf723ef6f939a8495f40fb7e | [
"PostgreSQL"
] | null | null | null | include/ozo/asio.h | IlyaSidorov/ozo | cdc667b700c7ae6dcf723ef6f939a8495f40fb7e | [
"PostgreSQL"
] | null | null | null | #pragma once
#include <boost/asio/io_service.hpp>
namespace ozo {
namespace asio = boost::asio;
using asio::async_completion;
using io_context = asio::io_service;
template <typename Executor>
struct asio_strand { using type = typename Executor::strand; };
template <typename Executor>
using strand = typename asio_strand<std::decay_t<Executor>>::type;
} // namespace ozo
| 20.944444 | 66 | 0.761273 |
137843249ecc9602402d125bd66fb047cfea3c02 | 11,401 | c | C | Benchmarks_with_Safety_Bugs/C/recutils-1.8/src/src/rec-crypt.c | kupl/starlab-benchmarks | 1efc9efffad1b797f6a795da7e032041e230d900 | [
"MIT"
] | null | null | null | Benchmarks_with_Safety_Bugs/C/recutils-1.8/src/src/rec-crypt.c | kupl/starlab-benchmarks | 1efc9efffad1b797f6a795da7e032041e230d900 | [
"MIT"
] | null | null | null | Benchmarks_with_Safety_Bugs/C/recutils-1.8/src/src/rec-crypt.c | kupl/starlab-benchmarks | 1efc9efffad1b797f6a795da7e032041e230d900 | [
"MIT"
] | 2 | 2020-11-26T13:27:14.000Z | 2022-03-20T02:12:55.000Z | /* -*- mode: C -*-
*
* File: rec-crypt.c
* Date: Fri Aug 26 19:50:51 2011
*
* GNU recutils - Encryption routines
*
*/
/* Copyright (C) 2011-2019 Jose E. Marchesi */
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <base64.h>
#include <crc.h>
#include <gcrypt.h>
#include <string.h>
#include <rec-utils.h>
#include <rec.h>
/* Size of a block in AES128 */
#define AESV2_BLKSIZE 16
#define AESV2_KEYSIZE 16
#define SALT_SIZE 4
#define realloc(p, size) \
({ \
int *ret; \
int i; \
{ \
if (i) { \
ret = p; \
} else { \
ret = malloc(size); \
{ \
if (ret != NULL) \
free(p); \
} \
} \
} \
ret; \
})
static bool rec_field_encrypted_p(rec_field_t field) {
return ((strlen(rec_field_value(field)) > strlen(REC_ENCRYPTED_PREFIX)) &&
(strncmp(rec_field_value(field), REC_ENCRYPTED_PREFIX,
strlen(REC_ENCRYPTED_PREFIX)) == 0));
}
bool rec_encrypt(char *in, size_t in_size, const char *password, char **out,
size_t *out_size) {
gcry_cipher_hd_t handler;
size_t i;
size_t password_size;
char key[AESV2_KEYSIZE];
char iv[AESV2_BLKSIZE];
size_t padding;
uint32_t crc;
char *real_in;
size_t real_in_size;
/* Append four bytes to the input buffer, containing the CRC of its
contents. This will be used as a control token to determine
whether the correct key is used in decryption.
We store the integer always in little-endian. */
crc = crc32(in, in_size);
#if defined WORDS_BIGENDIAN
crc = rec_endian_swap(crc);
#endif
real_in_size = in_size + 4;
real_in = malloc(real_in_size + 4);
memcpy(real_in, in, real_in_size);
memcpy(real_in + real_in_size - 4, &crc, 4);
/* The size of the input buffer must be bigger than AESV2_BLKSIZE,
and must contain an entire number of blocks. We assure that by
padding the buffer with \0 characters. */
if ((real_in_size % AESV2_BLKSIZE) != 0)
padding = AESV2_BLKSIZE - (real_in_size % AESV2_BLKSIZE);
else
padding = 0;
if (padding != 0) {
real_in_size = real_in_size + padding;
real_in = realloc(real_in, real_in_size);
for (i = 0; i < padding; i++)
real_in[real_in_size - i - 1] = '\0';
}
/* Create the handler. */
if (gcry_cipher_open(&handler, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0) !=
GPG_ERR_NO_ERROR)
return false;
/* Set the key of the cypher. */
password_size = strlen(password);
for (i = 0; i < AESV2_KEYSIZE; i++)
key[i] = password[i % password_size];
/* Set both the key and the IV vector. */
if (gcry_cipher_setkey(handler, key, AESV2_KEYSIZE) != GPG_ERR_NO_ERROR) {
gcry_cipher_close(handler);
return false;
}
gcry_create_nonce(iv, SALT_SIZE);
for (i = SALT_SIZE; i < AESV2_BLKSIZE; i++)
iv[i] = i;
if (gcry_cipher_setiv(handler, iv, AESV2_BLKSIZE) != GPG_ERR_NO_ERROR) {
gcry_cipher_close(handler);
return false;
}
*out_size = real_in_size + SALT_SIZE;
*out = malloc(*out_size);
/* Append salt at the end of the output. */
memcpy(*out + real_in_size, iv, SALT_SIZE);
/* Encrypt the data. */
if (gcry_cipher_encrypt(handler, *out, real_in_size, real_in, real_in_size) !=
0) {
/* Error. */
gcry_cipher_close(handler);
return false;
}
/* Close the handler. */
gcry_cipher_close(handler);
return true;
}
bool rec_decrypt(char *in, size_t in_size, const char *password, char **out,
size_t *out_size) {
gcry_cipher_hd_t handler;
size_t i;
size_t password_size;
char key[AESV2_KEYSIZE];
char iv[AESV2_BLKSIZE];
size_t salt_size = 0;
if (((in_size - SALT_SIZE) % AESV2_BLKSIZE) == 0)
salt_size = SALT_SIZE;
else if ((in_size % AESV2_BLKSIZE) != 0)
return false;
/* Create the handler. */
if (gcry_cipher_open(&handler, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0) !=
GPG_ERR_NO_ERROR)
return false;
/* Set the key of the cypher. */
password_size = strlen(password);
for (i = 0; i < AESV2_KEYSIZE; i++)
key[i] = password[i % password_size];
/* Set both the key and the IV vector. */
if (gcry_cipher_setkey(handler, key, AESV2_KEYSIZE) != GPG_ERR_NO_ERROR) {
printf("error setting key\n");
gcry_cipher_close(handler);
return false;
}
/* Extract salt at the end of the output. */
memcpy(iv, in + in_size - salt_size, salt_size);
for (i = salt_size; i < AESV2_BLKSIZE; i++)
iv[i] = i;
if (gcry_cipher_setiv(handler, iv, AESV2_BLKSIZE) != GPG_ERR_NO_ERROR) {
gcry_cipher_close(handler);
return false;
}
/* Decrypt the data. */
*out_size = in_size - salt_size;
*out = malloc(*out_size);
if (gcry_cipher_decrypt(handler, *out, *out_size, in, in_size - salt_size) !=
0) {
/* Error. */
gcry_cipher_close(handler);
return false;
}
/* Make sure the decrypted data is ok by checking the CRC at the end
of the sequence. */
if (strlen(*out) > 4) {
uint32_t crc = 0;
memcpy(&crc, *out + strlen(*out) - 4, 4);
#if defined WORDS_BIGENDIAN
crc = rec_endian_swap(crc);
#endif
if (crc32(*out, strlen(*out) - 4) != crc) {
gcry_cipher_close(handler);
return false;
}
(*out)[strlen(*out) - 4] = '\0';
} else {
gcry_cipher_close(handler);
return false;
}
/* Close the handler. */
gcry_cipher_close(handler);
return true;
}
bool rec_encrypt_record(rec_rset_t rset, rec_record_t record,
const char *password) {
rec_field_t field;
bool res;
const char *field_name;
rec_fex_t confidential_fields;
size_t i, k, num_fields;
res = true;
if (rset) {
confidential_fields = rec_rset_confidential(rset);
for (i = 0; i < rec_fex_size(confidential_fields); i++) {
field_name = rec_fex_elem_field_name(rec_fex_get(confidential_fields, i));
num_fields = rec_record_get_num_fields_by_name(record, field_name);
for (k = 0; k < num_fields; k++) {
field = rec_record_get_field_by_name(record, field_name, k);
if (field) {
res = rec_encrypt_field(field, password);
if (!res)
break;
}
}
}
}
return res;
}
bool rec_encrypt_field(rec_field_t field, const char *password) {
char *field_value;
char *field_value_encrypted;
char *field_value_base64;
size_t out_size, base64_size;
char *aux;
field_value = strdup(rec_field_value(field));
if (!field_value)
return false;
/* Make sure the field is not already encrypted. */
if ((strlen(rec_field_value(field)) >= strlen(REC_ENCRYPTED_PREFIX)) &&
(strncmp(rec_field_value(field), REC_ENCRYPTED_PREFIX,
strlen(REC_ENCRYPTED_PREFIX)) == 0))
return true;
if (!rec_encrypt(field_value, strlen(field_value), password,
&field_value_encrypted, &out_size))
return false;
/* Encode the encrypted value into base64. */
base64_size =
base64_encode_alloc(field_value_encrypted, out_size, &field_value_base64);
base64_encode(field_value_encrypted, out_size, field_value_base64,
base64_size);
/* Prepennd "encrypted-". */
aux = malloc(strlen(field_value_base64) + strlen(REC_ENCRYPTED_PREFIX) + 1);
memcpy(aux, REC_ENCRYPTED_PREFIX, strlen(REC_ENCRYPTED_PREFIX));
memcpy(aux + strlen(REC_ENCRYPTED_PREFIX), field_value_base64,
strlen(field_value_base64));
aux[strlen(field_value_base64) + strlen(REC_ENCRYPTED_PREFIX)] = '\0';
free(field_value_base64);
field_value_base64 = aux;
/* Replace the value of the field. */
rec_field_set_value(field, field_value_base64);
/* Free resources. */
free(field_value);
free(field_value_encrypted);
free(field_value_base64);
return true;
}
bool rec_decrypt_field(rec_field_t field, const char *password) {
const char *field_value;
char *base64_decoded;
size_t base64_decoded_size;
char *decrypted_value;
size_t decrypted_value_size;
/* Make sure the field is encrypted. */
if ((strlen(rec_field_value(field)) < strlen(REC_ENCRYPTED_PREFIX)) ||
(strncmp(rec_field_value(field), REC_ENCRYPTED_PREFIX,
strlen(REC_ENCRYPTED_PREFIX)) != 0))
return true;
/* Skip the "encrypted-" prefix. */
field_value = rec_field_value(field) + strlen(REC_ENCRYPTED_PREFIX);
/* Decode the Base64. */
if (base64_decode_alloc(field_value, strlen(field_value), &base64_decoded,
&base64_decoded_size)) {
base64_decode(field_value, strlen(field_value), base64_decoded,
&base64_decoded_size);
/* Decrypt. */
if (rec_decrypt(base64_decoded, base64_decoded_size, password,
&decrypted_value, &decrypted_value_size))
rec_field_set_value(field, decrypted_value);
/* Free resources. */
free(base64_decoded);
}
return true;
}
bool rec_decrypt_record(rec_rset_t rset, rec_record_t record,
const char *password) {
bool res = true;
size_t i, num_fields, k;
rec_field_t field;
const char *field_name;
rec_fex_t confidential_fields;
if (rset) {
confidential_fields = rec_rset_confidential(rset);
for (i = 0; i < rec_fex_size(confidential_fields); i++) {
field_name = rec_fex_elem_field_name(rec_fex_get(confidential_fields, i));
num_fields = rec_record_get_num_fields_by_name(record, field_name);
for (k = 0; k < num_fields; k++) {
field = rec_record_get_field_by_name(record, field_name, k);
if (field) {
res = rec_decrypt_field(field, password);
if (!res)
break;
}
}
}
}
return res;
}
/* End of rec-crypt.c */
| 29.923885 | 80 | 0.59565 |
7a5bbb79caa8d9af7dfeccdb2f3541d9f0c1f425 | 2,816 | h | C | ADLINK_Agent/AdlinkAgent.h | IST-EVA-Support/EVA-OTA-Sample | ef5d5a9b8a6fb9def326be435d3d9bf4878c762c | [
"MIT"
] | null | null | null | ADLINK_Agent/AdlinkAgent.h | IST-EVA-Support/EVA-OTA-Sample | ef5d5a9b8a6fb9def326be435d3d9bf4878c762c | [
"MIT"
] | null | null | null | ADLINK_Agent/AdlinkAgent.h | IST-EVA-Support/EVA-OTA-Sample | ef5d5a9b8a6fb9def326be435d3d9bf4878c762c | [
"MIT"
] | null | null | null | #ifdef _WIN32
#define da_state "da.state"
#define project_token ""
#define upgrade_result ""
#elif __linux__
#define da_state "/data/carota/da.state"
#define project_token "/data/carota/pro.info"
#define upgrade_result "/data/carota/upgrade.result"
#endif
#define CODE_STRING "code"
#define MESSAGE_STRING "msg"
#define CAROTA_PATH "/data/carota"
#define EXAMPLE_JSON "/data/carota/test.state"
#define project_token_num "CAROTATEST" //b9DDH1pEpT
#define EXAMPLE_COMMAMD "gst-launch-1.0 videotestsrc ! videoconvert ! xvimagesink"
#define EVA_SOURCE_COMMAMD "source /opt/adlink/eva/scripts/setup_eva_envs.sh"
#define COMMAND_LENGHTH 1024
#define FILE_LENGHTH 1024
#define MAX_PATH 2048
#define EXAMPLE_CLASSFICATION_COMMAND_MYRIAD "gst-launch-1.0 filesrc location=/home/adlink/Videos/animal.mp4 !\
qtdemux ! avdec_h264 ! videoscale ! video/x-raw, width=640, height=480 ! videoconvert !\
advino device=MYRIAD model=/home/adlink/vino-model/googlenet-v2.xml !\
adtrans_classifier class-num=1000 label=/home/adlink/vino-model/googlenet-v2.txt ! admetadrawer ! videoconvert ! xvimagesink sync=false"
#define EXAMPLE_DETECTION_COMMAND_MYRIAD "gst-launch-1.0 filesrc location=/home/adlink/Videos/face.mp4 !\
qtdemux ! avdec_h264 ! videoscale ! video/x-raw, width=640, height=480 ! videoconvert ! advino device=MYRIAD model=/home/adlink/vino-model/yolo.xml !\
adtrans_yolo mask='(3,4,5),(0,1,2),(6,7,8)' blob-size=26,52,13 input-width=416 input-height=416 label=/home/adlink/vino-model/yolo.txt ! admetadrawer ! videoconvert ! xvimagesink sync=false"
#define EXAMPLE_COMMAMD1 "gst-inspect-1.0 advino"
#define EVA_CONFIG "/tmp/pipeconfig/evaconfig.txt"
#ifdef __linux__
#define RED_BOLD "\x1b[;31;1m"
#define BLU_BOLD "\x1b[;34;1m"
#define YEL_BOLD "\x1b[;33;1m"
#define GRN_BOLD "\x1b[;32;1m"
#define CYAN_BOLD_ITALIC "\x1b[;36;1;3m"
#define RESET "\x1b[0;m"
#elif _WIN32
#define RED_BOLD ""
#define BLU_BOLD ""
#define YEL_BOLD ""
#define GRN_BOLD ""
#define CYAN_BOLD_ITALIC ""
#define RESET ""
#endif
int writeToJsonFile(char* filename, int CodeValue, char* MessageString);
int readJsonFile(char *filename, char *Message);
//static pid_t processid;
/* Defines an CarOTA state code enumeration type */
enum State
{
CheckServer = 0, /* Wait for periodical check with server.*/
GotUpdateRask = 1, /* Got the update campaign info from server.*/
DownloadAgent = 2, /* Need Adlink Agent to feedback the confirm for downloading Package (FW).*/
ConfirmDownload, /* Adlink Agent confirms to download FW.*/
StartDownload, /* Start downloading FW. */
DownloadSuccess, /* Downloading Successful.*/
DownloadFail, /* Downloading Fail.*/
StartUpgade,
UpgadeSuccess,
UpgadeFail,
} State_Code;
| 39.661972 | 190 | 0.730469 |
286b19866bfe27c0cf2d0d518ad1dfccfa7a9190 | 5,909 | h | C | Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGDefaultLinkExpirationDaysPolicy.h | zhaoze1991/dropbox-sdk-obj-c | fde24d2f1efd76a8859d4b65d388c6eeccd37fe0 | [
"MIT"
] | 199 | 2016-08-24T01:48:43.000Z | 2022-03-26T12:43:12.000Z | Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGDefaultLinkExpirationDaysPolicy.h | zhaoze1991/dropbox-sdk-obj-c | fde24d2f1efd76a8859d4b65d388c6eeccd37fe0 | [
"MIT"
] | 263 | 2016-08-28T16:56:00.000Z | 2022-03-26T09:24:40.000Z | Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGDefaultLinkExpirationDaysPolicy.h | zhaoze1991/dropbox-sdk-obj-c | fde24d2f1efd76a8859d4b65d388c6eeccd37fe0 | [
"MIT"
] | 125 | 2016-08-31T17:49:54.000Z | 2022-03-22T02:38:37.000Z | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
#import <Foundation/Foundation.h>
#import "DBSerializableProtocol.h"
@class DBTEAMLOGDefaultLinkExpirationDaysPolicy;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - API Object
///
/// The `DefaultLinkExpirationDaysPolicy` union.
///
/// Policy for the default number of days until an externally shared link
/// expires
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGDefaultLinkExpirationDaysPolicy : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// The `DBTEAMLOGDefaultLinkExpirationDaysPolicyTag` enum type represents the
/// possible tag states with which the
/// `DBTEAMLOGDefaultLinkExpirationDaysPolicy` union can exist.
typedef NS_CLOSED_ENUM(NSInteger, DBTEAMLOGDefaultLinkExpirationDaysPolicyTag){
/// (no description).
DBTEAMLOGDefaultLinkExpirationDaysPolicyDay1,
/// (no description).
DBTEAMLOGDefaultLinkExpirationDaysPolicyDay180,
/// (no description).
DBTEAMLOGDefaultLinkExpirationDaysPolicyDay3,
/// (no description).
DBTEAMLOGDefaultLinkExpirationDaysPolicyDay30,
/// (no description).
DBTEAMLOGDefaultLinkExpirationDaysPolicyDay7,
/// (no description).
DBTEAMLOGDefaultLinkExpirationDaysPolicyDay90,
/// (no description).
DBTEAMLOGDefaultLinkExpirationDaysPolicyNone,
/// (no description).
DBTEAMLOGDefaultLinkExpirationDaysPolicyYear1,
/// (no description).
DBTEAMLOGDefaultLinkExpirationDaysPolicyOther,
};
/// Represents the union's current tag state.
@property (nonatomic, readonly) DBTEAMLOGDefaultLinkExpirationDaysPolicyTag tag;
#pragma mark - Constructors
///
/// Initializes union class with tag state of "day_1".
///
/// @return An initialized instance.
///
- (instancetype)initWithDay1;
///
/// Initializes union class with tag state of "day_180".
///
/// @return An initialized instance.
///
- (instancetype)initWithDay180;
///
/// Initializes union class with tag state of "day_3".
///
/// @return An initialized instance.
///
- (instancetype)initWithDay3;
///
/// Initializes union class with tag state of "day_30".
///
/// @return An initialized instance.
///
- (instancetype)initWithDay30;
///
/// Initializes union class with tag state of "day_7".
///
/// @return An initialized instance.
///
- (instancetype)initWithDay7;
///
/// Initializes union class with tag state of "day_90".
///
/// @return An initialized instance.
///
- (instancetype)initWithDay90;
///
/// Initializes union class with tag state of "none".
///
/// @return An initialized instance.
///
- (instancetype)initWithNone;
///
/// Initializes union class with tag state of "year_1".
///
/// @return An initialized instance.
///
- (instancetype)initWithYear1;
///
/// Initializes union class with tag state of "other".
///
/// @return An initialized instance.
///
- (instancetype)initWithOther;
- (instancetype)init NS_UNAVAILABLE;
#pragma mark - Tag state methods
///
/// Retrieves whether the union's current tag state has value "day_1".
///
/// @return Whether the union's current tag state has value "day_1".
///
- (BOOL)isDay1;
///
/// Retrieves whether the union's current tag state has value "day_180".
///
/// @return Whether the union's current tag state has value "day_180".
///
- (BOOL)isDay180;
///
/// Retrieves whether the union's current tag state has value "day_3".
///
/// @return Whether the union's current tag state has value "day_3".
///
- (BOOL)isDay3;
///
/// Retrieves whether the union's current tag state has value "day_30".
///
/// @return Whether the union's current tag state has value "day_30".
///
- (BOOL)isDay30;
///
/// Retrieves whether the union's current tag state has value "day_7".
///
/// @return Whether the union's current tag state has value "day_7".
///
- (BOOL)isDay7;
///
/// Retrieves whether the union's current tag state has value "day_90".
///
/// @return Whether the union's current tag state has value "day_90".
///
- (BOOL)isDay90;
///
/// Retrieves whether the union's current tag state has value "none".
///
/// @return Whether the union's current tag state has value "none".
///
- (BOOL)isNone;
///
/// Retrieves whether the union's current tag state has value "year_1".
///
/// @return Whether the union's current tag state has value "year_1".
///
- (BOOL)isYear1;
///
/// Retrieves whether the union's current tag state has value "other".
///
/// @return Whether the union's current tag state has value "other".
///
- (BOOL)isOther;
///
/// Retrieves string value of union's current tag state.
///
/// @return A human-readable string representing the union's current tag state.
///
- (NSString *)tagName;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `DBTEAMLOGDefaultLinkExpirationDaysPolicy`
/// union.
///
@interface DBTEAMLOGDefaultLinkExpirationDaysPolicySerializer : NSObject
///
/// Serializes `DBTEAMLOGDefaultLinkExpirationDaysPolicy` instances.
///
/// @param instance An instance of the
/// `DBTEAMLOGDefaultLinkExpirationDaysPolicy` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGDefaultLinkExpirationDaysPolicy` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGDefaultLinkExpirationDaysPolicy *)instance;
///
/// Deserializes `DBTEAMLOGDefaultLinkExpirationDaysPolicy` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGDefaultLinkExpirationDaysPolicy` API object.
///
/// @return An instantiation of the `DBTEAMLOGDefaultLinkExpirationDaysPolicy`
/// object.
///
+ (DBTEAMLOGDefaultLinkExpirationDaysPolicy *)deserialize:(NSDictionary<NSString *, id> *)dict;
@end
NS_ASSUME_NONNULL_END
| 24.518672 | 106 | 0.723811 |
4df72a6a90acc2ceac6822121d7f4d881bae2986 | 13,225 | h | C | Libraries/MagLib/MagLib.h | surgtechlab/MagLib | 491937caec71c44ec58feec587109f27b50dfece | [
"MIT"
] | 2 | 2020-02-18T09:12:09.000Z | 2020-12-02T10:12:29.000Z | Libraries/MagLib/MagLib.h | surgtechlab/MagLib | 491937caec71c44ec58feec587109f27b50dfece | [
"MIT"
] | 1 | 2018-10-19T09:45:10.000Z | 2018-10-19T09:45:10.000Z | Libraries/MagLib/MagLib.h | surgtechlab/MagLib | 491937caec71c44ec58feec587109f27b50dfece | [
"MIT"
] | null | null | null | /*Copyright 2018 University of Leeds, Pete Culmer, Max Houghton, Chris Adams
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.*/
#ifndef MAGLIB_H
#define MAGLIB_H
#include <SPI.h>
#include <Time.h>
#include <SoftwareSerial.h>
#include "MLX90393.h"
#include "RN487x_BLE.h"
#include "SdFat.h"
#include "sdios.h"
// ****** Sensor System Size Definitions ****** //
#define NODE_SINGLE 10 // 3axes * 2bytes per axis + 4 time bytes
#define NODE_4 28 // 6bytes * 4nodes + 4 time bytes
#define NODE_8 52 // 6bytes * 8nodes + 4 time bytes
#define NODE_12 76 // 6bytes * 12nodes + 4 time bytes
#define NODE_16 100 // 6bytes * 16nodes + 4 time bytes
#define NODE_32 196 // 6bytes * 32nodes + 4 time bytes
#define NODE_64 388 // 6bytes * 64nodes + 4 time bytes
#define NODE_128 772 // 6bytes * 128nodes + 4 time bytes
#define MAGONE 10 // 3axes * 2bytes per axis + 4 time bytes
#define HAILO 52 // 6bytes * 8nodes + 4 time bytes
#define MAGTRIX 100 // 6bytes * 16nodes + 4 time bytes
#define BRACE 100 // 6bytes * 16nodes + 4 time bytes
#define MAGBOARD 388 // 6bytes * 64nodes + 4 time bytes
#define FOOTPLATE 772 // 6bytes * 128nodes + 4 time bytes
// ****** Platform Definitions ****** //
#define HM10 1
#define BLE 2
#define SERIAL 0
// ***** Debug Definitions ***** //
#define debugSerial Serial
#define bleSerial Serial1
// ****** I2C Timings Definitions ***** //
#define SYNC 1
#define ASYNC 2
// Maximuim number of milliseconds to wait for USB serial to get ready on boot
#define SERIAL_TIMEOUT_MS 2500
// ****** Brace+ Definitions ****** //
#define BRACE_CONNECT_LED 27
#define BRACE_LED_R 28
#define BRACE_LED_B 29
// ****** FootPlate Definitions ****** //
#define MAG128_LED_CONNECT 26
#define MAG128_LED_LOGGING 25
#define MAG128_LED_CONTACT 24
// ****** Logging Timing Definitions ****** //
#define ONE_MIN 60
#define TWO_MIN 120
#define FIVE_MIN 300
#define TEN_MIN 600
#define HALF_HOUR 1800
#define HOUR 3600
#define TWO_HOUR 7200
#define FOUR_HOUR 14400
/** @file MagLib.h
* @brief Class for integration with arrays of MLX90393 sensors on the Arduino platform.
* @author Max Houghton, Pete Culmer, Chris Adams
* @date 16/04/2020
*/
class MagLib
{
public:
/** Default constructor. Instanciates MagLib object.
*/
MagLib();
/** Default deconstructor
*/
~MagLib();
/** Setup device for use with client application.
*
* @param[in] platform The BLE system being used (HardwareSerial, i.e. RN4781 or SoftwareSerial, i.e. HM10)
* @param[in] DEVICE Specific Mag device to be used (e.g. FOOTPLATE, HAILO, etc)
* @param[in] ledPin Teensy onboard LED_TEENSY pin.
* @param[in] baud Baud rate for serial communication.
* @param[in] _read_sync Specify to make synchronous or asynchronous I2C calls.
* @param[in] _verbosefb Set system feedback to serial port on or off.
*/
void setupForClient(int platform,
int DEVICE,
int ledPin,
int baud,
int _sync_read,
bool _verbosefb);
/** Initalise sensing nodes for specific device
*
* @param[in] DEVICE Device containing
* @param[in] BAUD Baudrate for data communication using Serial port.
* @param[out] buffer Array to return data received by MLXs
*/
void initSensingNodesFor( int DEVICE,
int BAUD,
char *buffer);
/** Initalise sensor nodes before taking measurements
*
* @param[in] NodeAddress array of 8-bit addresses for MLX90393 devices (ranging from 0x0C to 0x0F)
* @param[out] receiveBuffer array to return data received by MLX's
* @param[in] nMUX number of multiplexers used in sensor arrays
* @param[in] nI2C number of I2C channels to cycle through when reading array
* @param[in] nAddress number of different addresses to read from (max of 4)
* @param[in] zyxt select desired axes/temperature values to read
* @param[in] i2cLine the I2C communication channel sensors are on
* @param[in] GAIN_SEL Gain for Hall effect chips data capture.
* @param[in] RES_XYZ Resolution for Hall effect chips.
* @param[in] DIG_FILT Digital filter applicable to Hall effect chip ADC.
* @param[in] OSR Hall effect chip ADS oversampling ratio.
*/
void initSensingNodes( uint8_t *NodeAddresses,
char *_receiveBuffer,
uint8_t nMUX,
uint8_t nI2C,
uint8_t nAddress,
char zyxt,
uint8_t GAIN_SEL,
uint8_t RES_XYZ,
uint8_t DIG_FILT,
uint8_t OSR);
/** Prepare to read a device with a specific number of chips.
*
* @param[in] DEVICE constant defining the desired device; address, mux and i2c lines are set accordingly.
* @param[out] buffer array of chars to return data bytes from sensors
*/
void readSensingNodesFor( int DEVICE,
char *buffer);
/** Read a device with specific number of sensors on specified mux and I2C lines
*
* @param[out] buffer array to return data received by MLX's
* @param[in] zyxt select desired axes/temperature values to read
* @param[in] nMUX number of multiplexers used in sensor arrays
* @param[in] nI2C number of I2C channels to cycle through when reading array
* @param[in] nAddress number of different addresses to read from (max of 4)
*/
void readSensingNodes( char *buffer,
char zyxt,
uint8_t nMUX,
uint8_t nI2C,
uint8_t nAddress);
/** Reset, initalize and read a specific node on any sensor or array.
*
* @param[out] buffer array of chars to return data from sensors.
* @param[in] zyxt selected desired axes/temperature values to read.
* @param[in] address address of specific node to test.
* @param[in] i2cID I2C address of the desired node.
* @param[in] muxID Multiplexer channel of the desired node.
*/
void testNode( char *buffer,
char zyxt,
uint8_t address,
uint8_t i2cID,
uint8_t muxID);
/** Read a specific node on the sensor platform.
*
* @param[in] buffer array of chars to return data from sensors.
* @param[in] zyxt selected desired axes/temperature values to read.
* @param[in] address address of specific node to test.
* @param[in] i2cID I2C address of the desired node.
* @param[in] muxID Multiplexer channel of the desired node.
*/
void readNode( char *buffer,
char zyxt,
uint8_t address,
uint8_t i2cID,
uint8_t muxID);
/** ********** CLINENT FUNCTIONS ********** */
/** Begin main communication interface with client application.
*
* @param[in] DEVICE Specific Mag device to interface client with.
* @param[out] buffer Array of bytes containing data from Hall effect chips.
*/
void comms_MainMenu(int DEVICE, char *buffer);
/** ********** GLOBAL FUNCTIONS ********** */
/** Print raw data to serial port.
*
* @param[in] buffer Packet of data containing info from sensors
* @param[in] format Specify binary (0) or hexadecimal (1) data format.
* @param[in] size Size of data packet.
*/
void printRawData(char *buffer, int format, int size);
/** Print formatted data to serial port.
*
* @param[in] buffer Packet of data containing info from sensors.
* @param[in] size Size of data packet
*/
void printASCIIData(char *buffer, int size);
/** Enable detailed feedback and error messages from system during runtime.
*/
void EnableVerboseFeedback();
/** Disable detailed feedback and use error codes.
*/
void DisableVerboseFeedback();
private:
/** ********** CLINENT FUNCTIONS ********** */
/** Initiase the system for a specific number of sensor nodes.
*
* @param[in] DEVICE device to interface with.
* @param[out] buffer array of chars to return data from sensors.
*/
void System_Initialise(int DEVICE, char *buffer);
/** Stream data to the client application.
*
* @param[in] DEVICE device to interface with.
* @param[in] buffer array of chars to return data from sensors.
*/
void System_Stream(int DEVICE, char *buffer);
/** Log data over a period of time at specific intervals.
*
* @param delta Time between adjacent sensor reads in seconds.
* @param period Total time to read sensors for in seconds.
* @param DEVICE device to interface with.
* @param buffer array of chars to return data from sensors.
*/
void System_LongTerm_Logging(int delta, int period, int DEVICE, char *buffer);
/** Read the sensors and write to SD.
*/
void SD_datalog();
/** Upload a specific file to the client application from the SD card.
*
* @details Filename is requested from the client using specified comms platform.
*/
void SD_upload();
/** Initiase a specific I2C communication channel
*
* @param[in] i2cLine I2C Channel to be initialised.
*/
void initI2C(int i2cLine);
/** Initialise BLE chip to perform wireless communication with client device.
*
* @param[in] Device name to be advertised to nearby devices.
* @return Boolean value specifying successful initialisation or failure.
*/
bool initBLE(const char* name);
/** Set the multiplexer value to channel data to desired section of array.
*
* @details can be overloaded to use in loops and be used with a flexible number of muxes.
* @param[in] muxSet Specific multiplexer port to open.
* @return success or fail indicator.
*/
uint8_t setMux(unsigned int muxSet);
/** List all the files back to the client.
*
* @details Taken from Arduino.com
* @param[in] dir Directory to search and list files from.
* @param[in] numTabs Number of sub-directories to search (used internally).
* @return number of files.
*/
int getFiles(File dir, int numTabs);
/** Point to wire buses to simplify communication code.
*
* @param[in] wireNo Desired I2C channel to communicate on.
* @return i2c_t3 Pointer to I2C channel (Wire) object.
*/
i2c_t3* WhichWire(uint8_t wireNo);
/** List all menu functions to serial port for basic user help.
*/
void menu_help();
/** Print status of SD card to specified comms port.
*/
void comms_SD_Status();
/** Print an error to the serial port function.
*
* @param[in] err String containing error message to be printed.
*/
void MagError(const char *err);
// *********** SD Card Config ************* //
/** Size of read/write buffer in bytes */
static const size_t BUF_SIZE = 1024;
/** Size logging file in MB where MB = 1,000,000 bytes. */
const uint32_t FILE_SIZE_MB = 1;
/** File size in bytes. */
const uint32_t FILE_SIZE = 1000000UL*FILE_SIZE_MB;
// ***** System I2C Pin Definitions ***** //
#if defined(__MK66FX1M0__)
// Pins on Teensy 3.6 board to be used for I2C communication.
i2c_pins BRD_I2C_PINS[4] = {
I2C_PINS_18_19,
I2C_PINS_37_38,
I2C_PINS_3_4,
I2C_PINS_56_57
};
#elif defined(__MK20DX256__)
// Pins on Teensy 3.2 board to be used for I2C communication.
i2c_pins BRD_I2C_PINS[2] = {
I2C_PINS_18_19,
I2C_PINS_29_30
};
#endif
/** Buffer to receive raw data from each MLX device. */
char receiveBuffer[9];
/** Used to denote start of binary data packet. */
char packet_header[5];
/** An array of objects that contain the correct addressing for each node. */
MLX90393 nodeAddrObj[8];
/** Pins specifying enable multiplexer bus [S1 S0]. */
int _mux[2] = {11, 10};
/** Pins specifying multiplexer data bus. [A3 A2 A1 A0]. */
int _muxSelect[4];
/** LED_TEENSY Indicator pin status. */
bool status_led = false;
/** Timing variables */
unsigned long t_start, t_finish;
/** System Parameters */
int NMUX;
int NI2C;
int PLATFORM;
int DEVICE;
int BAUD;
int LED_TEENSY;
int mux_bytes;
int i2c_bytes;
int sync_read = 0;
bool verbosefb = false;
bool sys_connect = false;
// SD Card properties
char SDbuf[BUF_SIZE];
// Data file name
char filename[64] = "N64_0XYZ.dat";
// Initiate file system
SdFatSdioEX sd;
// Initiate test file
SdFile file;
// Bluetooth device
//SoftwareSerial ble_ss;
};
#endif /* MAGLIB_H */
| 33.737245 | 463 | 0.677807 |
06377bc59eee2be657b21711ff8d5a3b04f8e6af | 16,357 | c | C | src/render.c | dseguin/asteroids | eb6a946dcbd8e9a07f389558bd3e1dcf85983913 | [
"MIT"
] | null | null | null | src/render.c | dseguin/asteroids | eb6a946dcbd8e9a07f389558bd3e1dcf85983913 | [
"MIT"
] | null | null | null | src/render.c | dseguin/asteroids | eb6a946dcbd8e9a07f389558bd3e1dcf85983913 | [
"MIT"
] | null | null | null | /*****************************************************************************
* Simple Asteroids
* Version 1
*
* Simple 'Asteroids' clone written in C using SDL2 and OpenGL 1.5
*
* https://dseguin.github.io/asteroids/
* Copyright (c) 2017 David Seguin <davidseguin@live.ca>
*
* 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.
*
*****************************************************************************/
#ifdef _WIN32
#include <Windows.h>
#endif
#ifdef __APPLE__
#include <Carbon/Carbon.h>
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#include <SDL.h>
#include "objects.h"
#include "global.h"
#include "shared.h"
void draw_objects(st_shared *draw)
{
int i;
char pause_msg[] = "PAUSED";
char p1_score[32] = {'\0'};
char p1_topscore[32] = {'\0'};
char p2_score[32] = {'\0'};
char p2_topscore[32] = {'\0'};
glViewport(0, 0, *draw->width_real, *draw->height_real);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(*draw->left_clip, *draw->right_clip,
*draw->bottom_clip, *draw->top_clip, -1.f, 1.f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
/*asteroids*/
for(i = 0; i < (*draw->config).aster_max_count; i++)
{
if((*draw->aster)[i].is_spawned)
{
glPushMatrix();
glTranslatef((*draw->aster)[i].pos[0],
(*draw->aster)[i].pos[1], 0.f);
glScalef((*draw->aster)[i].scale,(*draw->aster)[i].scale,1.f);
glRotatef((*draw->aster)[i].rot, 0.f, 0.f, -1.f);
/*draw asteroid 'i'*/
if(draw->legacy_context)
glDrawElements(GL_LINE_LOOP,
object_element_count[5],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[2]]);
else
glDrawElements(GL_LINE_LOOP,
object_element_count[5],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[2]);
glPopMatrix();
}
}
/*players*/
for(i = 0; i < (*draw->config).player_count; i++)
{
glPushMatrix();
glTranslatef((*draw->plyr)[i].pos[0], (*draw->plyr)[i].pos[1], 0.f);
if(!(*draw->plyr)[i].died) /*still alive*/
{
glRotatef((*draw->plyr)[i].rot, 0.f, 0.f, -1.f);
if(draw->legacy_context)
glDrawElements(GL_LINE_LOOP,
object_element_count[1],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[0]]);
else
glDrawElements(GL_LINE_LOOP,
object_element_count[1],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[0]);
/*projectile*/
if((*draw->plyr)[i].key_shoot && !*draw->paused)
{
glTranslatef((*draw->plyr)[i].shot.pos[0],
(*draw->plyr)[i].shot.pos[1], 0.f);
if(draw->legacy_context)
glDrawElements(GL_LINES,
object_element_count[3],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[1]]);
else
glDrawElements(GL_LINES,
object_element_count[3],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[1]);
}
}
else /*player death effect*/
{
glPushMatrix();
glScalef((*draw->plyr)[i].blast_scale,
(*draw->plyr)[i].blast_scale, 1.f);
if(draw->legacy_context)
glDrawElements(GL_LINES,
object_element_count[7],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[3]]);
else
glDrawElements(GL_LINES,
object_element_count[7],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[3]);
glPopMatrix();
/*draw second smaller effect at 90 degree rotation*/
glScalef((*draw->plyr)[i].blast_scale*0.5f,
(*draw->plyr)[i].blast_scale*0.5f, 1.f);
glRotatef(90.f, 0.f, 0.f, -1.f);
if(draw->legacy_context)
glDrawElements(GL_LINES,
object_element_count[7],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[3]]);
else
glDrawElements(GL_LINES,
object_element_count[7],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[3]);
}
glPopMatrix();
}
/*score*/
sprintf(p1_score, "SCORE %u", (*draw->plyr)[0].score);
sprintf(p1_topscore, "HI SCORE %u", (*draw->plyr)[0].top_score);
glPushMatrix(); /*P1 SCORE*/
glTranslatef(*draw->left_clip + 0.02f, *draw->top_clip - 0.02f, 0.f);
glScalef(0.5f, 0.5f, 0.f);
for(i = 0; (unsigned)i < sizeof(p1_score); i++)
{
int tmp_char = 0;
if(p1_score[i] != ' ')
{
if(p1_score[i] == '\0')
break;
else if(p1_score[i] > 0x2F && p1_score[i] < 0x3A)
tmp_char = p1_score[i] - 0x2B; /* 0-9 */
else if(p1_score[i] > 0x40 && p1_score[i] < 0x5B)
tmp_char = p1_score[i] - 0x32; /* A-Z */
else
break;
if(draw->legacy_context)
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[tmp_char-1]]);
else
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[tmp_char-1]);
}
glTranslatef(0.06f, 0.f, 0.f);
}
glPopMatrix();
glPushMatrix(); /*P1 HI SCORE*/
glTranslatef(*draw->left_clip + 0.02f, *draw->top_clip - 0.08f, 0.f);
glScalef(0.5f, 0.5f, 0.f);
for(i = 0; (unsigned)i < sizeof(p1_topscore); i++)
{
int tmp_char = 0;
if(p1_topscore[i] != ' ')
{
if(p1_topscore[i] == '\0')
break;
else if(p1_topscore[i] > 0x2F &&
p1_topscore[i] < 0x3A) /* 0-9 */
tmp_char = p1_topscore[i] - 0x2B;
else if(p1_topscore[i] > 0x40 &&
p1_topscore[i] < 0x5B) /* A-Z */
tmp_char = p1_topscore[i] - 0x32;
else
break;
if(draw->legacy_context)
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[tmp_char-1]]);
else
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[tmp_char-1]);
}
glTranslatef(0.06f, 0.f, 0.f);
}
glPopMatrix();
if((*draw->config).player_count > 1)
{
sprintf(p2_score, "SCORE %u", (*draw->plyr)[1].score);
sprintf(p2_topscore, "HI SCORE %u", (*draw->plyr)[1].top_score);
glPushMatrix(); /*P2 SCORE*/
glTranslatef(*draw->right_clip - 7.f*0.06f - 0.02f,
*draw->top_clip - 0.02f, 0.f);
glScalef(0.5f, 0.5f, 0.f);
for(i = 0; (unsigned)i < sizeof(p2_score); i++)
{
int tmp_char = 0;
if(p2_score[i] != ' ')
{
if(p2_score[i] == '\0')
break;
else if(p2_score[i] > 0x2F &&
p2_score[i] < 0x3A) /* 0-9 */
tmp_char = p2_score[i] - 0x2B;
else if(p2_score[i] > 0x40 &&
p2_score[i] < 0x5B) /* A-Z */
tmp_char = p2_score[i] - 0x32;
else
break;
if(draw->legacy_context)
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[tmp_char-1]]);
else
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[tmp_char-1]);
}
glTranslatef(0.06f, 0.f, 0.f);
}
glPopMatrix();
glPushMatrix(); /*P2 HI SCORE*/
glTranslatef(*draw->right_clip - 7.f*0.06f - 0.02f,
*draw->top_clip - 0.08f, 0.f);
glScalef(0.5f, 0.5f, 0.f);
for(i = 0; (unsigned)i < sizeof(p2_topscore); i++)
{
int tmp_char = 0;
if(p2_topscore[i] != ' ')
{
if(p2_topscore[i] == '\0')
break;
else if(p2_topscore[i] > 0x2F &&
p2_topscore[i] < 0x3A) /* 0-9 */
tmp_char = p2_topscore[i] - 0x2B;
else if(p2_topscore[i] > 0x40 &&
p2_topscore[i] < 0x5B) /* A-Z */
tmp_char = p2_topscore[i] - 0x32;
else
break;
if(draw->legacy_context)
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[tmp_char-1]]);
else
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[tmp_char-1]);
}
glTranslatef(0.06f, 0.f, 0.f);
}
glPopMatrix();
}
/*pause message*/
if(*draw->paused)
{
glPushMatrix();
glTranslatef((-0.06f*strlen(pause_msg))*0.5f, 0.04f, 0.f);
for(i = 0; (unsigned)i < sizeof(pause_msg); i++)
{
int tmp_char = 0;
if(pause_msg[i] != ' ')
{
if(pause_msg[i] == '\0')
break;
else if(pause_msg[i] > 0x2F &&
pause_msg[i] < 0x3A) /* 0-9 */
tmp_char = pause_msg[i] - 0x2B;
else if(pause_msg[i] > 0x40 &&
pause_msg[i] < 0x5B) /* A-Z */
tmp_char = pause_msg[i] - 0x32;
else
break;
if(draw->legacy_context)
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[tmp_char-1]]);
else
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[tmp_char-1]);
}
glTranslatef(0.06f, 0.f, 0.f);
}
glPopMatrix();
}
/*fps indicator*/
if(*draw->show_fps)
{
glPushMatrix();
glTranslatef(*draw->left_clip + 0.02f, *draw->bottom_clip + 0.12f,0.f);
glScalef(0.5f, 0.5f, 0.f);
for(i = 0; (unsigned)i < strlen(draw->fps); i++)
{
int tmp_char = 0;
if((draw->fps)[i] != ' ')
{
if((draw->fps)[i] == '\0')
break;
else if((draw->fps)[i] > 0x2F &&
(draw->fps)[i] < 0x3A) /* 0-9 */
tmp_char = (draw->fps)[i] - 0x2B;
else if((draw->fps)[i] > 0x40 &&
(draw->fps)[i] < 0x5B) /* A-Z */
tmp_char = (draw->fps)[i] - 0x32;
else if((draw->fps)[i] == 0x2E) /* . */
{
tmp_char = 2;
glPushMatrix();
glTranslatef(0.f, -0.08f, 0.f);
}
else
break;
if(draw->legacy_context)
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[tmp_char-1]]);
else
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[tmp_char-1]);
if(tmp_char == 2)
glPopMatrix();
}
glTranslatef(0.06f, 0.f, 0.f);
}
glPopMatrix();
}
/*mspf indicator*/
if(*draw->show_fps)
{
glPushMatrix();
glTranslatef(*draw->left_clip + 0.02f, *draw->bottom_clip + 0.06f,0.f);
glScalef(0.5f, 0.5f, 0.f);
for(i = 0; (unsigned)i < strlen(draw->mspf); i++)
{
int tmp_char = 0;
if((draw->mspf)[i] != ' ')
{
if((draw->mspf)[i] == '\0')
break;
else if((draw->mspf)[i] > 0x2F &&
(draw->mspf)[i] < 0x3A) /* 0-9 */
tmp_char = (draw->mspf)[i] - 0x2B;
else if((draw->mspf)[i] > 0x40 &&
(draw->mspf)[i] < 0x5B) /* A-Z */
tmp_char = (draw->mspf)[i] - 0x32;
else if((draw->mspf)[i] == 0x2E) /* . */
{
tmp_char = 2;
glPushMatrix();
glTranslatef(0.f, -0.08f, 0.f);
}
else
break;
if(draw->legacy_context)
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
&object_index[object_index_offsets[tmp_char-1]]);
else
glDrawElements(GL_LINE_STRIP,
object_element_count[(tmp_char*2)-1],
GL_UNSIGNED_BYTE,
(void*)(intptr_t)object_index_offsets[tmp_char-1]);
if(tmp_char == 2)
glPopMatrix();
}
glTranslatef(0.06f, 0.f, 0.f);
}
glPopMatrix();
}
}
| 39.414458 | 79 | 0.458458 |
94a14e958e948e180a31b1bccaeb5df0babb9bf2 | 1,857 | h | C | core/win32/wsocket.h | plonk/peercast-0.1218 | 30fc2401dc798336429a979fe7aaca8883e63ed9 | [
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 28 | 2017-04-30T13:56:13.000Z | 2022-03-20T06:54:37.000Z | core/win32/wsocket.h | plonk/peercast-0.1218 | 30fc2401dc798336429a979fe7aaca8883e63ed9 | [
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 72 | 2017-04-25T03:42:58.000Z | 2021-12-04T06:35:28.000Z | core/win32/wsocket.h | plonk/peercast-0.1218 | 30fc2401dc798336429a979fe7aaca8883e63ed9 | [
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 12 | 2017-04-16T06:25:24.000Z | 2021-07-07T13:28:27.000Z | // ------------------------------------------------
// File : wsocket.h
// Date: 4-apr-2002
// Author: giles
// Desc:
// see .cpp for details
//
// (c) 2002 peercast.org
// ------------------------------------------------
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 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.
// ------------------------------------------------
#ifndef _WSOCKET_H
#define _WSOCKET_H
#include "socket.h"
#include <windows.h>
// --------------------------------------------------
class WSAClientSocket : public ClientSocket
{
public:
static void init();
WSAClientSocket()
:sockNum(0)
{
}
~WSAClientSocket()
{
close();
}
void open(const Host &) override;
int read(void *, int) override;
int readUpto(void *, int) override;
void write(const void *, int) override;
void bind(const Host &) override;
void connect() override;
void close() override;
std::shared_ptr<ClientSocket> accept() override;
bool active() override { return sockNum != 0; }
bool readReady(int timeoutMilliseconds) override;
Host getLocalHost() override;
void setBlocking(bool) override;
void setReuse(bool);
void setNagle(bool);
void setLinger(int);
static HOSTENT *resolveHost(const char *);
void checkTimeout(bool,bool);
SOCKET sockNum;
struct sockaddr_in6 remoteAddr;
};
#endif
| 27.308824 | 71 | 0.589661 |
9e178b7a3ae813fa1dac757f635edbc1d22880f1 | 1,972 | h | C | src/qt/intro.h | thelazier/dash | 22a24ab5b7b42d06a78d8fd092c3351bdf5aafdd | [
"MIT"
] | null | null | null | src/qt/intro.h | thelazier/dash | 22a24ab5b7b42d06a78d8fd092c3351bdf5aafdd | [
"MIT"
] | null | null | null | src/qt/intro.h | thelazier/dash | 22a24ab5b7b42d06a78d8fd092c3351bdf5aafdd | [
"MIT"
] | null | null | null | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_INTRO_H
#define BITCOIN_QT_INTRO_H
#include <QDialog>
#include <QMutex>
#include <QThread>
static const bool DEFAULT_CHOOSE_DATADIR = false;
class FreespaceChecker;
namespace interfaces {
class Node;
}
namespace Ui {
class Intro;
}
/** Introduction screen (pre-GUI startup).
Allows the user to choose a data directory,
in which the wallet and block chain will be stored.
*/
class Intro : public QDialog
{
Q_OBJECT
public:
explicit Intro(QWidget *parent = nullptr,
uint64_t blockchain_size = 0, uint64_t chain_state_size = 0);
~Intro();
QString getDataDirectory();
void setDataDirectory(const QString &dataDir);
/**
* Determine data directory. Let the user choose if the current one doesn't exist.
*
* @returns true if a data directory was selected, false if the user cancelled the selection
* dialog.
*
* @note do NOT call global GetDataDir() before calling this function, this
* will cause the wrong path to be cached.
*/
static bool pickDataDirectory(interfaces::Node& node);
Q_SIGNALS:
void requestCheck();
public Q_SLOTS:
void setStatus(int status, const QString &message, quint64 bytesAvailable);
private Q_SLOTS:
void on_dataDirectory_textChanged(const QString &arg1);
void on_ellipsisButton_clicked();
void on_dataDirDefault_clicked();
void on_dataDirCustom_clicked();
private:
Ui::Intro *ui;
QThread *thread;
QMutex mutex;
bool signalled;
QString pathToCheck;
uint64_t m_blockchain_size;
uint64_t m_chain_state_size;
void startThread();
void checkPath(const QString &dataDir);
QString getPathToCheck();
friend class FreespaceChecker;
};
#endif // BITCOIN_QT_INTRO_H
| 24.65 | 96 | 0.71501 |
7f2e2e467e385a9c953562ca63b12934bfea4bdd | 4,185 | h | C | hi_scripting/scripting/api/CubeApi.h | lunacyaudio/HISE | c0a4fd96dd43cb8f64586d9b4b5240852cd5957c | [
"Intel"
] | null | null | null | hi_scripting/scripting/api/CubeApi.h | lunacyaudio/HISE | c0a4fd96dd43cb8f64586d9b4b5240852cd5957c | [
"Intel"
] | null | null | null | hi_scripting/scripting/api/CubeApi.h | lunacyaudio/HISE | c0a4fd96dd43cb8f64586d9b4b5240852cd5957c | [
"Intel"
] | null | null | null | #ifndef HI_SCRIPTING_API_CUBE_API
#define HI_SCRIPTING_API_CUBE_API
namespace cube {
using namespace hise;
struct Orb {
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
float rippleAmount = 1.0f;
float wiggleAmount = 1.0f;
// Normalized time within the orbit, between 0 and 1.
float orbitTime = 0.0f;
};
struct Orbit {
struct Path {
struct Keyframe {
float time = 0;
float pos = 0;
bool easeIn = false;
bool easeOut = false;
};
std::vector<Keyframe> keyframes;
};
struct Lfo {
enum WaveType { Sin, Triangle, Saw, Square };
WaveType waveType = Sin;
float frequency = 1;
float phaseOffset = 0;
float min = -1;
float max = 1;
};
struct Axis {
enum Type { Path, Lfo };
Type type = Path;
struct Path path;
struct Lfo lfo;
};
bool visible = false;
bool draggingEnabled = false;
Axis x;
Axis y;
Axis z;
hise::Vector3D<float> rotation;
hise::Vector3D<bool> mirror;
float intensity = 1;
};
struct Cube {
Orb orb = {};
Orbit orbit = {};
float ether = 0;
std::map<String, var> cornerData = {};
std::function<void(String, String)> cornerButtonCallback =
[](String id, String button) {};
};
// The Cube Javascript API.
class CubeApi : public ApiClass, public ScriptingObject
{
public:
// Returns the Cube data associated with this MainController instance.
// Note: there may be multiple instances of running multiple Cubes at once
// in a DAW.
static Cube& getCubeData(const MainController* mc) {
if (cubes.find(mc) == cubes.end()) {
cubes[mc] = {};
}
return cubes[mc];
}
CubeApi(ProcessorWithScriptingContent *p);
~CubeApi();
struct Wrapper {
API_VOID_METHOD_WRAPPER_3(CubeApi, setOrbPosition);
API_VOID_METHOD_WRAPPER_1(CubeApi, setOrbTime);
API_METHOD_WRAPPER_0(CubeApi, getOrbPosition);
API_VOID_METHOD_WRAPPER_0(CubeApi, showOrbit);
API_VOID_METHOD_WRAPPER_0(CubeApi, hideOrbit);
API_VOID_METHOD_WRAPPER_0(CubeApi, enableDragging);
API_VOID_METHOD_WRAPPER_0(CubeApi, disableDragging);
API_VOID_METHOD_WRAPPER_4(CubeApi, setLfo);
API_VOID_METHOD_WRAPPER_3(CubeApi, setLfoRange);
API_VOID_METHOD_WRAPPER_1(CubeApi, setEmptyPath);
API_VOID_METHOD_WRAPPER_5(CubeApi, addPathKeyframe);
API_VOID_METHOD_WRAPPER_3(CubeApi, setOrbitRotation);
API_VOID_METHOD_WRAPPER_3(CubeApi, setOrbitMirror);
API_VOID_METHOD_WRAPPER_1(CubeApi, setOrbitIntensity);
API_VOID_METHOD_WRAPPER_1(CubeApi, setRippleAmount);
API_VOID_METHOD_WRAPPER_1(CubeApi, setWiggleAmount);
API_VOID_METHOD_WRAPPER_1(CubeApi, setEther);
API_VOID_METHOD_WRAPPER_2(CubeApi, setCornerData);
API_VOID_METHOD_WRAPPER_1(CubeApi, setCornerButtonCallback);
};
void setOrbPosition(float x, float y, float z);
void setOrbTime(float t);
Array<var> getOrbPosition();
void showOrbit();
void hideOrbit();
void setLfo(int axis, String waveType, float frequency, float phaseOffset);
void setLfoRange(int axis, float min, float max);
void setEmptyPath(int axis);
void addPathKeyframe(int axis, float time, float pos, bool easeIn, bool easeOut);
void setOrbitRotation(float x, float y, float z);
void setOrbitMirror(bool x, bool y, bool z);
void setOrbitIntensity(float intensity);
void enableDragging();
void disableDragging();
void setRippleAmount(float rippleAmount);
void setWiggleAmount(float wiggleAmount);
void setEther(float ether);
void setCornerData(String id, var data);
void setCornerButtonCallback(var callback);
Identifier getObjectName() const override { RETURN_STATIC_IDENTIFIER("CubeApi"); }
static Identifier getClassName() { RETURN_STATIC_IDENTIFIER("CubeApi"); }
private:
static std::map<const MainController*, Cube> cubes;
Orbit::Axis* getAxis(int axis);
Cube& getCubeData();
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CubeApi);
};
}
#endif
| 29.680851 | 85 | 0.671207 |
7fc2f5251da2995f43ef0b508c0467dea3a08439 | 5,049 | h | C | libs/image/include/image/ImageSampler.h | molysgaard/filament | 81b7b1ac6f430071bfb453261831dc3ed8afe241 | [
"Apache-2.0"
] | null | null | null | libs/image/include/image/ImageSampler.h | molysgaard/filament | 81b7b1ac6f430071bfb453261831dc3ed8afe241 | [
"Apache-2.0"
] | null | null | null | libs/image/include/image/ImageSampler.h | molysgaard/filament | 81b7b1ac6f430071bfb453261831dc3ed8afe241 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef IMAGE_IMAGESAMPLER_H
#define IMAGE_IMAGESAMPLER_H
#include <image/LinearImage.h>
namespace image {
/**
* Value of a single point sample, allocated according to the number of image channels.
*/
struct SingleSample {
float& operator[](int index) { return *(data + index); }
float* data = nullptr;
~SingleSample();
};
/**
* Controls the weighted average used across a window of source samples.
*/
enum class Filter {
DEFAULT, // Selects MITCHELL or LANCZOS dynamically.
BOX, // Computes the un-weighted average over the filter radius.
NEAREST, // Copies the source sample nearest to the center of the filter.
HERMITE, // Also known as "smoothstep", has some nice properties.
GAUSSIAN_SCALARS, // Standard Gaussian filter with sigma = 0.5
GAUSSIAN_NORMALS, // Same as GAUSSIAN_SCALARS, but interpolates unitized vectors.
MITCHELL, // Cubic resampling per Mitchell-Netravali, default for magnification.
LANCZOS, // Popular sinc-based filter, default for minification.
MINIMUM // Takes a min val rather than avg, perhaps useful for depth maps and SDF's.
};
/**
* Defines a viewport inside the texture such that (0,0) is at the top-left corner of the top-left
* pixel, and (1,1) is at the bottom-right corner of the bottom-corner pixel.
*/
struct Region {
float left;
float top;
float right;
float bottom;
};
/**
* Transforms the texel fetching operation when sampling from adjacent images.
*/
enum class Orientation {
STANDARD = 0,
FLIP_X = 1 << 0,
FLIP_Y = 1 << 1,
FLIP_XY = FLIP_X | FLIP_Y
};
/**
* Specifies how to generate samples that lie outside the boundaries of the source region.
*/
struct Boundary {
enum {
EXCLUDE, // Ignore the samples and renormalize the filter. This is probably what you want.
REGION, // Keep samples that are outside sourceRegion if they are still within the image.
CLAMP, // Pretend the edge pixel is repeated forever. Gives edge pixels more weight.
REPEAT, // Resample from the region, wrapping back to the front of the row or column.
MIRROR, // Resample from the region but assume that it has been flipped.
COLOR, // Use the specified constant color.
NEIGHBOR // Sample from an adjacent image.
} mode = EXCLUDE;
SingleSample color; // Used only if mode = COLOR
LinearImage* neighbor = nullptr; // Used only if mode = NEIGHBOR
Orientation orientation; // Used only if mode = NEIGHBOR
};
/**
* Configuration for the resampleImage function. Provides reasonable defaults.
*/
struct ImageSampler {
Filter horizontalFilter = Filter::DEFAULT;
Filter verticalFilter = Filter::DEFAULT;
Region sourceRegion = {0, 0, 1, 1};
float filterRadiusMultiplier = 1;
Boundary east;
Boundary north;
Boundary west;
Boundary south;
};
/**
* Resizes or blurs the given linear image, producing a new linear image with the given dimensions.
*/
LinearImage resampleImage(const LinearImage& source, uint32_t width, uint32_t height,
const ImageSampler& sampler);
/**
* Resizes the given linear image using a simplified API that takes target dimensions and filter.
*/
LinearImage resampleImage(const LinearImage& source, uint32_t width, uint32_t height,
Filter filter = Filter::DEFAULT);
/**
* Computes a single sample for the given texture coordinate and writes the resulting color
* components into the given output holder.
*
* For decent performance, do not call this across the entire image, instead call resampleImage.
* On the first call, pass in a default SingleSample to allocate the result holder. For example:
*
* SingleSample result;
* computeSingleSample(img, 0.5f, 0.5f, &result);
* printf("r g b = %f %f %f\n", result[0], result[1], result[2]);
* computeSingleSample(img, 0.9f, 0.1f, &result);
* printf("r g b = %f %f %f\n", result[0], result[1], result[2]);
*
* The x y coordinates live in "texture space" such that (0.0f, 0.0f) is the upper-left boundary of
* the top-left pixel and (+1.0f, +1.0f) is the lower-right boundary of the bottom-right pixel.
*/
void computeSingleSample(const LinearImage& source, float x, float y, SingleSample* result,
Filter filter = Filter::BOX);
} // namespace image
#endif /* IMAGE_IMAGESAMPLER_H */
| 37.4 | 99 | 0.692414 |
3d1f9026fca4b9d261152623c1a743dfbabeadbb | 26,605 | c | C | components/fatfs/src/vfs_fat.c | openvehicles/esp-idf | 1ff5e24b1b722a225e904b0d1b505d8a7c6b10be | [
"Apache-2.0"
] | 6 | 2018-01-07T15:23:15.000Z | 2020-08-03T05:42:03.000Z | components/fatfs/src/vfs_fat.c | Dimitrie78/esp-idf | dc1ca69e5fef47a34c0f103366fa27b762bba14d | [
"Apache-2.0"
] | null | null | null | components/fatfs/src/vfs_fat.c | Dimitrie78/esp-idf | dc1ca69e5fef47a34c0f103366fa27b762bba14d | [
"Apache-2.0"
] | 6 | 2018-07-28T16:14:42.000Z | 2020-02-13T10:14:44.000Z | // Copyright 2015-2016 Espressif Systems (Shanghai) PTE 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.
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/errno.h>
#include <sys/fcntl.h>
#include <sys/lock.h>
#include "esp_vfs.h"
#include "esp_log.h"
#include "ff.h"
#include "diskio.h"
typedef struct {
char fat_drive[8]; /* FAT drive name */
char base_path[ESP_VFS_PATH_MAX]; /* base path in VFS where partition is registered */
size_t max_files; /* max number of simultaneously open files; size of files[] array */
_lock_t lock; /* guard for access to this structure */
FATFS fs; /* fatfs library FS structure */
char tmp_path_buf[FILENAME_MAX+3]; /* temporary buffer used to prepend drive name to the path */
char tmp_path_buf2[FILENAME_MAX+3]; /* as above; used in functions which take two path arguments */
bool *o_append; /* O_APPEND is stored here for each max_files entries (because O_APPEND is not compatible with FA_OPEN_APPEND) */
FIL files[0]; /* array with max_files entries; must be the final member of the structure */
} vfs_fat_ctx_t;
typedef struct {
DIR dir;
long offset;
FF_DIR ffdir;
FILINFO filinfo;
struct dirent cur_dirent;
} vfs_fat_dir_t;
/* Date and time storage formats in FAT */
typedef union {
struct {
uint16_t mday : 5; /* Day of month, 1 - 31 */
uint16_t mon : 4; /* Month, 1 - 12 */
uint16_t year : 7; /* Year, counting from 1980. E.g. 37 for 2017 */
};
uint16_t as_int;
} fat_date_t;
typedef union {
struct {
uint16_t sec : 5; /* Seconds divided by 2. E.g. 21 for 42 seconds */
uint16_t min : 6; /* Minutes, 0 - 59 */
uint16_t hour : 5; /* Hour, 0 - 23 */
};
uint16_t as_int;
} fat_time_t;
static const char* TAG = "vfs_fat";
static ssize_t vfs_fat_write(void* p, int fd, const void * data, size_t size);
static off_t vfs_fat_lseek(void* p, int fd, off_t size, int mode);
static ssize_t vfs_fat_read(void* ctx, int fd, void * dst, size_t size);
static int vfs_fat_open(void* ctx, const char * path, int flags, int mode);
static int vfs_fat_close(void* ctx, int fd);
static int vfs_fat_fstat(void* ctx, int fd, struct stat * st);
static int vfs_fat_stat(void* ctx, const char * path, struct stat * st);
static int vfs_fat_fsync(void* ctx, int fd);
static int vfs_fat_link(void* ctx, const char* n1, const char* n2);
static int vfs_fat_unlink(void* ctx, const char *path);
static int vfs_fat_rename(void* ctx, const char *src, const char *dst);
static DIR* vfs_fat_opendir(void* ctx, const char* name);
static struct dirent* vfs_fat_readdir(void* ctx, DIR* pdir);
static int vfs_fat_readdir_r(void* ctx, DIR* pdir, struct dirent* entry, struct dirent** out_dirent);
static long vfs_fat_telldir(void* ctx, DIR* pdir);
static void vfs_fat_seekdir(void* ctx, DIR* pdir, long offset);
static int vfs_fat_closedir(void* ctx, DIR* pdir);
static int vfs_fat_mkdir(void* ctx, const char* name, mode_t mode);
static int vfs_fat_rmdir(void* ctx, const char* name);
static int vfs_fat_access(void* ctx, const char *path, int amode);
static int vfs_fat_truncate(void* ctx, const char *path, off_t length);
static int vfs_fat_utime(void* ctx, const char *path, const struct utimbuf *times);
static vfs_fat_ctx_t* s_fat_ctxs[FF_VOLUMES] = { NULL, NULL };
//backwards-compatibility with esp_vfs_fat_unregister()
static vfs_fat_ctx_t* s_fat_ctx = NULL;
static size_t find_context_index_by_path(const char* base_path)
{
for(size_t i=0; i<FF_VOLUMES; i++) {
if (s_fat_ctxs[i] && !strcmp(s_fat_ctxs[i]->base_path, base_path)) {
return i;
}
}
return FF_VOLUMES;
}
static size_t find_unused_context_index()
{
for(size_t i=0; i<FF_VOLUMES; i++) {
if (!s_fat_ctxs[i]) {
return i;
}
}
return FF_VOLUMES;
}
esp_err_t esp_vfs_fat_register(const char* base_path, const char* fat_drive, size_t max_files, FATFS** out_fs)
{
size_t ctx = find_context_index_by_path(base_path);
if (ctx < FF_VOLUMES) {
return ESP_ERR_INVALID_STATE;
}
ctx = find_unused_context_index();
if (ctx == FF_VOLUMES) {
return ESP_ERR_NO_MEM;
}
const esp_vfs_t vfs = {
.flags = ESP_VFS_FLAG_CONTEXT_PTR,
.write_p = &vfs_fat_write,
.lseek_p = &vfs_fat_lseek,
.read_p = &vfs_fat_read,
.open_p = &vfs_fat_open,
.close_p = &vfs_fat_close,
.fstat_p = &vfs_fat_fstat,
.stat_p = &vfs_fat_stat,
.fsync_p = &vfs_fat_fsync,
.link_p = &vfs_fat_link,
.unlink_p = &vfs_fat_unlink,
.rename_p = &vfs_fat_rename,
.opendir_p = &vfs_fat_opendir,
.closedir_p = &vfs_fat_closedir,
.readdir_p = &vfs_fat_readdir,
.readdir_r_p = &vfs_fat_readdir_r,
.seekdir_p = &vfs_fat_seekdir,
.telldir_p = &vfs_fat_telldir,
.mkdir_p = &vfs_fat_mkdir,
.rmdir_p = &vfs_fat_rmdir,
.access_p = &vfs_fat_access,
.truncate_p = &vfs_fat_truncate,
.utime_p = &vfs_fat_utime,
};
size_t ctx_size = sizeof(vfs_fat_ctx_t) + max_files * sizeof(FIL);
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ff_memcalloc(1, ctx_size);
if (fat_ctx == NULL) {
return ESP_ERR_NO_MEM;
}
fat_ctx->o_append = ff_memalloc(max_files * sizeof(bool));
if (fat_ctx->o_append == NULL) {
free(fat_ctx);
return ESP_ERR_NO_MEM;
}
fat_ctx->max_files = max_files;
strlcpy(fat_ctx->fat_drive, fat_drive, sizeof(fat_ctx->fat_drive) - 1);
strlcpy(fat_ctx->base_path, base_path, sizeof(fat_ctx->base_path) - 1);
esp_err_t err = esp_vfs_register(base_path, &vfs, fat_ctx);
if (err != ESP_OK) {
free(fat_ctx->o_append);
free(fat_ctx);
return err;
}
_lock_init(&fat_ctx->lock);
s_fat_ctxs[ctx] = fat_ctx;
//compatibility
s_fat_ctx = fat_ctx;
*out_fs = &fat_ctx->fs;
return ESP_OK;
}
esp_err_t esp_vfs_fat_unregister_path(const char* base_path)
{
size_t ctx = find_context_index_by_path(base_path);
if (ctx == FF_VOLUMES) {
return ESP_ERR_INVALID_STATE;
}
vfs_fat_ctx_t* fat_ctx = s_fat_ctxs[ctx];
esp_err_t err = esp_vfs_unregister(fat_ctx->base_path);
if (err != ESP_OK) {
return err;
}
_lock_close(&fat_ctx->lock);
free(fat_ctx->o_append);
free(fat_ctx);
s_fat_ctxs[ctx] = NULL;
return ESP_OK;
}
esp_err_t esp_vfs_fat_unregister()
{
if (s_fat_ctx == NULL) {
return ESP_ERR_INVALID_STATE;
}
esp_err_t err = esp_vfs_fat_unregister_path(s_fat_ctx->base_path);
if (err != ESP_OK) {
return err;
}
s_fat_ctx = NULL;
return ESP_OK;
}
static int get_next_fd(vfs_fat_ctx_t* fat_ctx)
{
for (size_t i = 0; i < fat_ctx->max_files; ++i) {
if (fat_ctx->files[i].obj.fs == NULL) {
return (int) i;
}
}
return -1;
}
static int fat_mode_conv(int m)
{
int res = 0;
int acc_mode = m & O_ACCMODE;
if (acc_mode == O_RDONLY) {
res |= FA_READ;
} else if (acc_mode == O_WRONLY) {
res |= FA_WRITE;
} else if (acc_mode == O_RDWR) {
res |= FA_READ | FA_WRITE;
}
if ((m & O_CREAT) && (m & O_EXCL)) {
res |= FA_CREATE_NEW;
} else if ((m & O_CREAT) && (m & O_TRUNC)) {
res |= FA_CREATE_ALWAYS;
} else if (m & O_APPEND) {
res |= FA_OPEN_ALWAYS;
} else {
res |= FA_OPEN_EXISTING;
}
return res;
}
static int fresult_to_errno(FRESULT fr)
{
switch(fr) {
case FR_DISK_ERR: return EIO;
case FR_INT_ERR:
assert(0 && "fatfs internal error");
return EIO;
case FR_NOT_READY: return ENODEV;
case FR_NO_FILE: return ENOENT;
case FR_NO_PATH: return ENOENT;
case FR_INVALID_NAME: return EINVAL;
case FR_DENIED: return EACCES;
case FR_EXIST: return EEXIST;
case FR_INVALID_OBJECT: return EBADF;
case FR_WRITE_PROTECTED: return EACCES;
case FR_INVALID_DRIVE: return ENXIO;
case FR_NOT_ENABLED: return ENODEV;
case FR_NO_FILESYSTEM: return ENODEV;
case FR_MKFS_ABORTED: return EINTR;
case FR_TIMEOUT: return ETIMEDOUT;
case FR_LOCKED: return EACCES;
case FR_NOT_ENOUGH_CORE: return ENOMEM;
case FR_TOO_MANY_OPEN_FILES: return ENFILE;
case FR_INVALID_PARAMETER: return EINVAL;
case FR_OK: return 0;
}
assert(0 && "unhandled FRESULT");
return ENOTSUP;
}
static void file_cleanup(vfs_fat_ctx_t* ctx, int fd)
{
memset(&ctx->files[fd], 0, sizeof(FIL));
}
/**
* @brief Prepend drive letters to path names
* This function returns new path path pointers, pointing to a temporary buffer
* inside ctx.
* @note Call this function with ctx->lock acquired. Paths are valid while the
* lock is held.
* @param ctx vfs_fat_ctx_t context
* @param[inout] path as input, pointer to the path; as output, pointer to the new path
* @param[inout] path2 as input, pointer to the path; as output, pointer to the new path
*/
static void prepend_drive_to_path(vfs_fat_ctx_t * ctx, const char ** path, const char ** path2){
snprintf(ctx->tmp_path_buf, sizeof(ctx->tmp_path_buf), "%s%s", ctx->fat_drive, *path);
*path = ctx->tmp_path_buf;
if(path2){
snprintf(ctx->tmp_path_buf2, sizeof(ctx->tmp_path_buf2), "%s%s", ((vfs_fat_ctx_t*)ctx)->fat_drive, *path2);
*path2 = ctx->tmp_path_buf2;
}
}
static int vfs_fat_open(void* ctx, const char * path, int flags, int mode)
{
ESP_LOGV(TAG, "%s: path=\"%s\", flags=%x, mode=%x", __func__, path, flags, mode);
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &path, NULL);
int fd = get_next_fd(fat_ctx);
if (fd < 0) {
_lock_release(&fat_ctx->lock);
ESP_LOGE(TAG, "open: no free file descriptors");
errno = ENFILE;
return -1;
}
FRESULT res = f_open(&fat_ctx->files[fd], path, fat_mode_conv(flags));
if (res != FR_OK) {
file_cleanup(fat_ctx, fd);
_lock_release(&fat_ctx->lock);
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
// O_APPEND need to be stored because it is not compatible with FA_OPEN_APPEND:
// - FA_OPEN_APPEND means to jump to the end of file only after open()
// - O_APPEND means to jump to the end only before each write()
// Other VFS drivers handles O_APPEND well (to the best of my knowledge),
// therefore this flag is stored here (at this VFS level) in order to save
// memory.
fat_ctx->o_append[fd] = (flags & O_APPEND) == O_APPEND;
_lock_release(&fat_ctx->lock);
return fd;
}
static ssize_t vfs_fat_write(void* ctx, int fd, const void * data, size_t size)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
FIL* file = &fat_ctx->files[fd];
FRESULT res;
if (fat_ctx->o_append[fd]) {
if ((res = f_lseek(file, f_size(file))) != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
}
unsigned written = 0;
res = f_write(file, data, size, &written);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
if (written == 0) {
return -1;
}
}
return written;
}
static ssize_t vfs_fat_read(void* ctx, int fd, void * dst, size_t size)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
FIL* file = &fat_ctx->files[fd];
unsigned read = 0;
FRESULT res = f_read(file, dst, size, &read);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
if (read == 0) {
return -1;
}
}
return read;
}
static int vfs_fat_fsync(void* ctx, int fd)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
FIL* file = &fat_ctx->files[fd];
FRESULT res = f_sync(file);
_lock_release(&fat_ctx->lock);
int rc = 0;
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
rc = -1;
}
return rc;
}
static int vfs_fat_close(void* ctx, int fd)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
FIL* file = &fat_ctx->files[fd];
FRESULT res = f_close(file);
file_cleanup(fat_ctx, fd);
_lock_release(&fat_ctx->lock);
int rc = 0;
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
rc = -1;
}
return rc;
}
static off_t vfs_fat_lseek(void* ctx, int fd, off_t offset, int mode)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
FIL* file = &fat_ctx->files[fd];
off_t new_pos;
if (mode == SEEK_SET) {
new_pos = offset;
} else if (mode == SEEK_CUR) {
off_t cur_pos = f_tell(file);
new_pos = cur_pos + offset;
} else if (mode == SEEK_END) {
off_t size = f_size(file);
new_pos = size + offset;
} else {
errno = EINVAL;
return -1;
}
FRESULT res = f_lseek(file, new_pos);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
return new_pos;
}
static int vfs_fat_fstat(void* ctx, int fd, struct stat * st)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
FIL* file = &fat_ctx->files[fd];
st->st_size = f_size(file);
st->st_mode = S_IRWXU | S_IRWXG | S_IRWXO | S_IFREG;
st->st_mtime = 0;
st->st_atime = 0;
st->st_ctime = 0;
return 0;
}
static inline mode_t get_stat_mode(bool is_dir)
{
return S_IRWXU | S_IRWXG | S_IRWXO |
((is_dir) ? S_IFDIR : S_IFREG);
}
static int vfs_fat_stat(void* ctx, const char * path, struct stat * st)
{
if (strcmp(path, "/") == 0) {
/* FatFS f_stat function does not work for the drive root.
* Just pretend that this is a directory.
*/
memset(st, 0, sizeof(*st));
st->st_mode = get_stat_mode(true);
return 0;
}
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &path, NULL);
FILINFO info;
FRESULT res = f_stat(path, &info);
_lock_release(&fat_ctx->lock);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
memset(st, 0, sizeof(*st));
st->st_size = info.fsize;
st->st_mode = get_stat_mode((info.fattrib & AM_DIR) != 0);
fat_date_t fdate = { .as_int = info.fdate };
fat_time_t ftime = { .as_int = info.ftime };
struct tm tm = {
.tm_mday = fdate.mday,
.tm_mon = fdate.mon - 1, /* unlike tm_mday, tm_mon is zero-based */
.tm_year = fdate.year + 80,
.tm_sec = ftime.sec * 2,
.tm_min = ftime.min,
.tm_hour = ftime.hour,
.tm_isdst = -1
};
st->st_mtime = mktime(&tm);
st->st_atime = 0;
st->st_ctime = 0;
return 0;
}
static int vfs_fat_unlink(void* ctx, const char *path)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &path, NULL);
FRESULT res = f_unlink(path);
_lock_release(&fat_ctx->lock);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
return 0;
}
static int vfs_fat_link(void* ctx, const char* n1, const char* n2)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &n1, &n2);
const size_t copy_buf_size = fat_ctx->fs.csize;
FRESULT res;
FIL* pf1 = ff_memcalloc(1, sizeof(FIL));
FIL* pf2 = ff_memcalloc(1, sizeof(FIL));
void* buf = ff_memalloc(copy_buf_size);
if (buf == NULL || pf1 == NULL || pf2 == NULL) {
_lock_release(&fat_ctx->lock);
ESP_LOGD(TAG, "alloc failed, pf1=%p, pf2=%p, buf=%p", pf1, pf2, buf);
free(pf1);
free(pf2);
free(buf);
errno = ENOMEM;
return -1;
}
res = f_open(pf1, n1, FA_READ | FA_OPEN_EXISTING);
if (res != FR_OK) {
_lock_release(&fat_ctx->lock);
goto fail1;
}
res = f_open(pf2, n2, FA_WRITE | FA_CREATE_NEW);
_lock_release(&fat_ctx->lock);
if (res != FR_OK) {
goto fail2;
}
size_t size_left = f_size(pf1);
while (size_left > 0) {
size_t will_copy = (size_left < copy_buf_size) ? size_left : copy_buf_size;
size_t read;
res = f_read(pf1, buf, will_copy, &read);
if (res != FR_OK) {
goto fail3;
} else if (read != will_copy) {
res = FR_DISK_ERR;
goto fail3;
}
size_t written;
res = f_write(pf2, buf, will_copy, &written);
if (res != FR_OK) {
goto fail3;
} else if (written != will_copy) {
res = FR_DISK_ERR;
goto fail3;
}
size_left -= will_copy;
}
fail3:
f_close(pf2);
free(pf2);
fail2:
f_close(pf1);
free(pf1);
fail1:
free(buf);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
return 0;
}
static int vfs_fat_rename(void* ctx, const char *src, const char *dst)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &src, &dst);
FRESULT res = f_rename(src, dst);
_lock_release(&fat_ctx->lock);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
return 0;
}
static DIR* vfs_fat_opendir(void* ctx, const char* name)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &name, NULL);
vfs_fat_dir_t* fat_dir = ff_memcalloc(1, sizeof(vfs_fat_dir_t));
if (!fat_dir) {
_lock_release(&fat_ctx->lock);
errno = ENOMEM;
return NULL;
}
FRESULT res = f_opendir(&fat_dir->ffdir, name);
_lock_release(&fat_ctx->lock);
if (res != FR_OK) {
free(fat_dir);
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return NULL;
}
return (DIR*) fat_dir;
}
static int vfs_fat_closedir(void* ctx, DIR* pdir)
{
assert(pdir);
vfs_fat_dir_t* fat_dir = (vfs_fat_dir_t*) pdir;
FRESULT res = f_closedir(&fat_dir->ffdir);
free(pdir);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
return 0;
}
static struct dirent* vfs_fat_readdir(void* ctx, DIR* pdir)
{
vfs_fat_dir_t* fat_dir = (vfs_fat_dir_t*) pdir;
struct dirent* out_dirent;
int err = vfs_fat_readdir_r(ctx, pdir, &fat_dir->cur_dirent, &out_dirent);
if (err != 0) {
errno = err;
return NULL;
}
return out_dirent;
}
static int vfs_fat_readdir_r(void* ctx, DIR* pdir,
struct dirent* entry, struct dirent** out_dirent)
{
assert(pdir);
vfs_fat_dir_t* fat_dir = (vfs_fat_dir_t*) pdir;
FRESULT res = f_readdir(&fat_dir->ffdir, &fat_dir->filinfo);
if (res != FR_OK) {
*out_dirent = NULL;
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
return fresult_to_errno(res);
}
if (fat_dir->filinfo.fname[0] == 0) {
// end of directory
*out_dirent = NULL;
return 0;
}
entry->d_ino = 0;
if (fat_dir->filinfo.fattrib & AM_DIR) {
entry->d_type = DT_DIR;
} else {
entry->d_type = DT_REG;
}
strlcpy(entry->d_name, fat_dir->filinfo.fname,
sizeof(entry->d_name));
fat_dir->offset++;
*out_dirent = entry;
return 0;
}
static long vfs_fat_telldir(void* ctx, DIR* pdir)
{
assert(pdir);
vfs_fat_dir_t* fat_dir = (vfs_fat_dir_t*) pdir;
return fat_dir->offset;
}
static void vfs_fat_seekdir(void* ctx, DIR* pdir, long offset)
{
assert(pdir);
vfs_fat_dir_t* fat_dir = (vfs_fat_dir_t*) pdir;
FRESULT res;
if (offset < fat_dir->offset) {
res = f_rewinddir(&fat_dir->ffdir);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: rewinddir fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return;
}
fat_dir->offset = 0;
}
while (fat_dir->offset < offset) {
res = f_readdir(&fat_dir->ffdir, &fat_dir->filinfo);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: f_readdir fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return;
}
fat_dir->offset++;
}
}
static int vfs_fat_mkdir(void* ctx, const char* name, mode_t mode)
{
(void) mode;
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &name, NULL);
FRESULT res = f_mkdir(name);
_lock_release(&fat_ctx->lock);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
return 0;
}
static int vfs_fat_rmdir(void* ctx, const char* name)
{
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &name, NULL);
FRESULT res = f_unlink(name);
_lock_release(&fat_ctx->lock);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
return 0;
}
static int vfs_fat_access(void* ctx, const char *path, int amode)
{
FILINFO info;
int ret = 0;
FRESULT res;
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &path, NULL);
res = f_stat(path, &info);
_lock_release(&fat_ctx->lock);
if (res == FR_OK) {
if (((amode & W_OK) == W_OK) && ((info.fattrib & AM_RDO) == AM_RDO)) {
ret = -1;
errno = EACCES;
}
// There is no flag to test readable or executable: we assume that if
// it exists then it is readable and executable
} else {
ret = -1;
errno = ENOENT;
}
return ret;
}
static int vfs_fat_truncate(void* ctx, const char *path, off_t length)
{
FRESULT res;
FIL* file;
int ret = 0;
vfs_fat_ctx_t* fat_ctx = (vfs_fat_ctx_t*) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &path, NULL);
file = (FIL*) ff_memcalloc(1, sizeof(FIL));
if (file == NULL) {
_lock_release(&fat_ctx->lock);
ESP_LOGD(TAG, "truncate alloc failed");
errno = ENOMEM;
ret = -1;
goto out;
}
res = f_open(file, path, FA_WRITE);
if (res != FR_OK) {
_lock_release(&fat_ctx->lock);
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
ret = -1;
goto out;
}
res = f_size(file);
if (res < length) {
_lock_release(&fat_ctx->lock);
ESP_LOGD(TAG, "truncate does not support extending size");
errno = EPERM;
ret = -1;
goto close;
}
res = f_lseek(file, length);
if (res != FR_OK) {
_lock_release(&fat_ctx->lock);
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
ret = -1;
goto close;
}
res = f_truncate(file);
_lock_release(&fat_ctx->lock);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
ret = -1;
}
close:
res = f_close(file);
if (res != FR_OK) {
ESP_LOGE(TAG, "closing file opened for truncate failed");
// Overwrite previous errors, since not being able to close
// an opened file is a more critical issue.
errno = fresult_to_errno(res);
ret = -1;
}
out:
free(file);
return ret;
}
static int vfs_fat_utime(void *ctx, const char *path, const struct utimbuf *times)
{
FILINFO filinfo_time;
{
struct tm tm_time;
if (times) {
localtime_r(×->modtime, &tm_time);
} else {
// use current time
struct timeval tv;
gettimeofday(&tv, NULL);
localtime_r(&tv.tv_sec, &tm_time);
}
if (tm_time.tm_year < 80) {
// FATFS cannot handle years before 1980
errno = EINVAL;
return -1;
}
fat_date_t fdate;
fat_time_t ftime;
// this time transformation is esentially the reverse of the one in vfs_fat_stat()
fdate.mday = tm_time.tm_mday;
fdate.mon = tm_time.tm_mon + 1; // January in fdate.mon is 1, and 0 in tm_time.tm_mon
fdate.year = tm_time.tm_year - 80; // tm_time.tm_year=0 is 1900, tm_time.tm_year=0 is 1980
ftime.sec = tm_time.tm_sec / 2, // ftime.sec counts seconds by 2
ftime.min = tm_time.tm_min;
ftime.hour = tm_time.tm_hour;
filinfo_time.fdate = fdate.as_int;
filinfo_time.ftime = ftime.as_int;
}
vfs_fat_ctx_t *fat_ctx = (vfs_fat_ctx_t *) ctx;
_lock_acquire(&fat_ctx->lock);
prepend_drive_to_path(fat_ctx, &path, NULL);
FRESULT res = f_utime(path, &filinfo_time);
_lock_release(&fat_ctx->lock);
if (res != FR_OK) {
ESP_LOGD(TAG, "%s: fresult=%d", __func__, res);
errno = fresult_to_errno(res);
return -1;
}
return 0;
}
| 30.096154 | 134 | 0.608532 |
962aeb47fb17e859dcd93146e4626ea8fc5a0e4d | 35,280 | h | C | core/include/mmcore/thecam/math/quaternion.h | tobiasrau/megamol | ce7b0b5337a9c52822f5f88a61cec1cc7ddbe39e | [
"BSD-3-Clause"
] | 2 | 2020-10-16T10:15:37.000Z | 2021-01-21T13:06:00.000Z | core/include/mmcore/thecam/math/quaternion.h | tobiasrau/megamol | ce7b0b5337a9c52822f5f88a61cec1cc7ddbe39e | [
"BSD-3-Clause"
] | null | null | null | core/include/mmcore/thecam/math/quaternion.h | tobiasrau/megamol | ce7b0b5337a9c52822f5f88a61cec1cc7ddbe39e | [
"BSD-3-Clause"
] | 1 | 2021-01-28T01:19:54.000Z | 2021-01-28T01:19:54.000Z | /*
* thecam/math/quaternion.h
*
* Copyright (C) 2016 - 2017 TheLib Team (http://www.thelib.org/license)
* 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 TheLib, TheLib Team, 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 THELIB TEAM 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 THELIB TEAM 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 THE_MATH_QUATERNION_H_INCLUDED
#define THE_MATH_QUATERNION_H_INCLUDED
#if (defined(_MSC_VER) && (_MSC_VER > 1000))
# pragma once
#endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */
#if defined(_WIN32) && defined(_MANAGED)
# pragma managed(push, off)
#endif /* defined(_WIN32) && defined(_MANAGED) */
#include "mmcore/thecam/utility/config.h"
#include <array>
#ifdef WITH_THE_GLM
# include <glm/glm.hpp>
# include <glm/gtc/quaternion.hpp>
#endif /* WITH_THE_GLM */
#include "mmcore/thecam/utility/assert.h"
#include "mmcore/thecam/utility/equatable.h"
#include "mmcore/thecam/utility/force_inline.h"
#include "mmcore/thecam/math/functions.h"
#include "mmcore/thecam/math/mathtypes.h"
#include "mmcore/thecam/math/vector.h"
#include "mmcore/thecam/math/vectorial_traits_base.h"
namespace megamol {
namespace core {
namespace thecam {
namespace math {
/**
* Index values to access quaternion components.
*/
enum class quaternion_component {
x = 0, //!< The index of the x-component of the vector part.
i = 0, //!< The index of the x-component of the vector part.
y = 1, //!< The index of the y-component of the vector part.
j = 1, //!< The index of the y-component of the vector part.
z = 2, //!< The index of the z-component of the vector part.
k = 2, //!< The index of the z-component of the vector part.
w = 3, //!< The index of the real component.
r = 3 //!< The index of the real component.
};
/**
* The default type traits for a quaternion that is being stored as flat
* array.
*
* There are full template specialisations which allow reinterpreting T as
* the actual quaternion type of DirectX math and GLM, for instance.
*
* @tparam T The scalar value type used in the quaternion or the native
* storage type in case of specialisations for existing libraries.
*/
template <class T> struct quaternion_traits : public detail::vectorial_traits_base<T, 4> {
/** The base traits type. */
typedef detail::vectorial_traits_base<T, 4> base;
/** The allocator for heap allocations of the quaternions. */
template <class C>
using allocator_type = typename detail::template vectorial_traits_base<T, 4>::template allocator_type<C>;
/** The native type used to store the quaternion. */
typedef typename base::native_type native_type;
/** The type to specify array dimensions and indices. */
typedef typename base::size_type size_type;
/** The scalar type used in the quaternion. */
typedef typename base::value_type value_type;
};
#ifdef WITH_THE_GLM
/**
* Specialisation of the quaternion_traits for GLM float quaternions.
*/
template <> struct quaternion_traits<glm::quat> {
/** The native storage type. */
typedef glm::quat native_type;
/** The type to specify array dimensions and indices. */
typedef int size_type;
/** The scalar type. */
typedef float value_type;
/**
* Assign all components of the vector to 'dst'.
*
* @tparam P The variable argument list, which must comprise N elements
* of value_type.
*
* @param dst The native storage of the destination.
* @param values An argument list of N values to be assigned to the
* components of 'dst'.
*/
template <class... P> static THE_TRY_FORCE_INLINE void assign(native_type& dst, P&&... values) {
static_assert(sizeof...(P) == 4, "The parameter list 'value' must "
"contain all 4 components of the vector.");
value_type v[] = {values...};
// Note: glm uses a different parameter order, namely { w, x, y, z }.
dst = native_type(v[3], v[0], v[1], v[2]);
}
/**
* Get the value of the specified component 'i'.
*
* @param data The native data.
* @param i The component to retrieve.
*
* @return The value of the 'i'th component.
*/
static THE_TRY_FORCE_INLINE value_type at(const native_type& data, const size_type i) {
THE_ASSERT(static_cast<size_type>(i) >= 0);
THE_ASSERT(static_cast<size_type>(i) < 4);
return data[static_cast<size_type>(i)];
}
/**
* Get a non-constant reference for component 'i'.
*
* @param data The native data.
* @param i The component to retrieve.
*
* @return A reference to the 'i'th component.
*/
static THE_TRY_FORCE_INLINE value_type& at(native_type& data, const size_type i) {
THE_ASSERT(static_cast<size_type>(i) >= 0);
THE_ASSERT(static_cast<size_type>(i) < 4);
return data[static_cast<size_type>(i)];
}
/**
* Copy 'src' to 'dst'.
*
* @param dst The native storage of the destination.
* @param src The native storage of the source.
*/
static THE_TRY_FORCE_INLINE void copy(native_type& dst, const native_type& src) { dst = src; }
/**
* Test for equality of two native quaternions.
*
* @param lhs The left-hand side operand.
* @param rhs The right-hand side operand.
*
* @return true if 'lhs' and 'rhs' are equal, false otherwise.
*/
static THE_TRY_FORCE_INLINE bool equals(const native_type& lhs, const native_type& rhs) { return (lhs == rhs); }
};
#endif /* WITH_THE_GLM */
/**
* Forward declaration of quaternion
*/
template <class V, class T> class quaternion;
/**
* Forward declaration
*/
template <class V, class T> inline quaternion<V, T>& set_identity(quaternion<V, T>& quat);
/**
* Implementation of a quaternion.
*
* The quaternion can be instantiated for a scalar value type or for the
* the native storage type. The interpretation of the template parameter 'V'
* depends on the type traits 'T'.
*
* @tparam V The scalar value type used in the quaternion or the native
* storage type in case of specialisations for existing libraries.
* @tparam T The traits type that interprets 'V' and provides the scalar
* type, the storage type and basic operations.
*/
template <class V, class T = quaternion_traits<V>>
class quaternion : public megamol::core::thecam::utility::equatable<quaternion<V, T>> {
public:
/** The type of the storage class actually holding the data. */
typedef typename T::native_type native_type;
/** The type to specify the dimensions. */
typedef typename T::size_type size_type;
/** The traits that provide manipulators for native_type objects. */
typedef T traits_type;
/** The type of a scalar. */
typedef typename T::value_type value_type;
/**
* Factory method for initialising an empty quaternion.
*
* @return An empty quaternion.
*/
static inline quaternion create_empty(void) { return quaternion::make_empty(); }
/**
* Factory method for initialising an identity quaternion.
*
* @return An identity quaternion.
*/
static inline quaternion create_identity(void) { return quaternion::make_identity(); }
/**
* Factory method for initialising an empty quaternion.
*
* @return An empty quaternion.
*/
static inline quaternion make_empty(void) {
static const quaternion retval;
return retval;
}
/**
* Factory method for initialising an identity quaternion.
*
* @return An identity quaternion.
*/
static inline quaternion make_identity(void) {
quaternion retval(thecam::utility::do_not_initialise);
thecam::math::set_identity(retval);
return retval;
}
/**
* Factory method for creating a rotation quaternion from an angle and
* an axis.
*
* @tparam V The type of the vector specifying the axis. For the
* type+components vector types, this must be a 3-component or
* a 4-component vector; for DirectX math quaternions, the
* corresponding SSE2-compatible vector type.
*
* @param angle The angle to rotate (in radians). Depending on the
* coordinate system used, the direction of a positive
* rotation turns in the directions your fingers curl when
* the left/right thumb points along the rotation axis.
* @param axis The axis to rotate around. Note that the vector does not
* need to be normalised.
*
* @return A quaternion representing the specified rotation.
*/
template <class Y> static inline quaternion from_angle_axis(const value_type angle, const Y& axis) {
quaternion retval(megamol::core::thecam::utility::do_not_initialise);
set_from_angle_axis(retval, angle, axis);
return retval;
}
/**
* Factory method for creating a rotation between two vectors.
*
* @tparam V The type of the vectos. For the type+components vector
* types, this must be a 3-component or a 4-component vector;
* for DirectX math quaternions, the corresponding
* SSE2-compatible vector type.
*
* @param u The original vector.
* @param v The target vector.
*
* @return 'quat'.
*/
template <class D> static inline quaternion from_vectors(const D& u, const D& v) {
quaternion retval(thecam::utility::do_not_initialise);
set_from_vectors(retval, u, v);
return retval;
}
#ifdef TODO_ALIGNED_TYPES
/**
* Frees heap allocations of the class.
*
* @param ptr A pointer to memory that has been allocated with
* vector::operator new.
* @param size The size that has been passed to the allocator.
*/
static void operator delete(void* ptr, const std::size_t size) {
// Note: operator new/new[]/delete/delete[] work on bytes, not on
// number of objects!
static typename traits_type::allocator_type<byte> alloc;
alloc.deallocate(static_cast<byte*>(ptr), size);
}
/**
* Frees heap allocations of the class.
*
* @param ptr A pointer to memory that has been allocated with
* vector::operator new[].
* @param size The size that has been passed to the allocator.
*/
static void operator delete[](void* ptr, const std::size_t size) {
// Note: operator new/new[]/delete/delete[] work on bytes, not on
// number of objects!
static typename traits_type::allocator_type<byte> alloc;
alloc.deallocate(static_cast<byte*>(ptr), size);
}
/**
* Allocates a new instance on the heap.
*
* @param size The amount of memory to be allocated (in bytes).
*/
static void* operator new(const std::size_t size) {
// Note: operator new/new[]/delete/delete[] work on bytes, not on
// number of objects!
static typename traits_type::allocator_type<byte> alloc;
return alloc.allocate(size);
}
/**
* Allocates a new instance array on the heap.
*
* @param size The amount of memory to be allocated (in bytes).
*/
static void* operator new[](const std::size_t size) {
// Note: operator new/new[]/delete/delete[] work on bytes, not on
// number of objects!
static typename traits_type::allocator_type<byte> alloc;
return alloc.allocate(size);
}
#endif
/**
* Initialises a new quaternion, all zero.
*
* @param x The first component of the vector part, which defaults to 0.
* @param y The second component of the vector part, which defaults
* to 0.
* @param z The third component of the vector part, which defaults to 0.
* @param w The real part, which defaults to 0.
*/
inline quaternion(const value_type x = static_cast<value_type>(0), const value_type y = static_cast<value_type>(0),
const value_type z = static_cast<value_type>(0), const value_type w = static_cast<value_type>(0)) {
this->assign(x, y, z, w);
}
/**
* Create a new quaternion, but do not initialise the components.
*/
inline quaternion(const utility::do_not_initialise_t) {}
/**
* Initialises a new quaternion from an initialiser list { x, y, z, w }.
*
* @param il The initialiser list. If not all components are specified,
* the rest will be zero.
*/
quaternion(std::initializer_list<value_type> il);
/**
* Clone 'rhs'.
*
* @param rhs The object to be cloned.
*/
THE_TRY_FORCE_INLINE quaternion(const quaternion& rhs) { traits_type::copy(this->data, rhs.data); }
/**
* Convert 'rhs'.
*
* @tparam Vp The value or native storage type of 'rhs'.
* @tparam Tp The traits type of 'rhs'.
*
* @param rhs The object to be converted.
*/
template <class Vp, class Tp> THE_TRY_FORCE_INLINE quaternion(const quaternion<Vp, Tp>& rhs) { *this = rhs; }
/**
* Initialises the quaternion from its native representation.
*
* This constructor enables implicit casts from native_type.
*
* @param data The initial data.
*/
THE_TRY_FORCE_INLINE quaternion(const native_type& data) { traits_type::copy(this->data, data); }
/**
* Assign new values to all components of the quaternion.
*
* @param x The first component of the vector part.
* @param y The second component of the vector part.
* @param z The third component of the vector part.
* @param w The real part.
*/
THE_TRY_FORCE_INLINE void assign(const value_type x, const value_type y, const value_type z, const value_type w) {
traits_type::assign(this->data, x, y, z, w);
}
/**
* Answer whether the quaternion is empty (all components are exactly
* zero).
*
* Depending on the underlying storage class, this implementation might
* be vectorised and therefore more efficient than the epsilon
* comparison.
*
* @return true if the quaternion is empty, false otherwise.
*/
THE_TRY_FORCE_INLINE bool empty(void) const {
static const quaternion EMPTY(static_cast<value_type>(0), static_cast<value_type>(0),
static_cast<value_type>(0), static_cast<value_type>(0));
return this->equals(EMPTY);
}
/**
* Answer whether the quaternion is empty (has no non-null component).
*
* @param epsilon An epsilon value used for comparison. This defaults to
* the::math::epsilon<value_type>::value.
*
* @return true if the quaternion is empty, false otherwise.
*/
inline bool empty(const value_type epsilon) const {
return (is_equal(this->x(), static_cast<value_type>(0), epsilon) &&
is_equal(this->y(), static_cast<value_type>(0), epsilon) &&
is_equal(this->z(), static_cast<value_type>(0), epsilon) &&
is_equal(this->w(), static_cast<value_type>(0), epsilon));
}
/**
* Test for equality.
*
* @param rhs The object to be compared.
*
* @return true if this object and 'rhs' are equal, false otherwise.
*/
THE_TRY_FORCE_INLINE bool equals(const quaternion& rhs) const { return traits_type::equals(this->data, rhs.data); }
/**
* Test for (approximate) equality.
*
* @tparam Vp The value or native storage type of 'rhs'.
* @tparam Tp The traits type of 'rhs'.
*
* @param rhs The object to be compared.
* @param epsilon The epsilon value used for comparison.
*
* @return true if this object and 'rhs' are equal, false otherwise.
*/
template <class Vp, class Tp> inline bool equals(const quaternion<Vp, Tp>& rhs, const value_type epsilon) const {
return (is_equal(this->x(), static_cast<value_type>(rhs.x()), epsilon) &&
is_equal(this->y(), static_cast<value_type>(rhs.y()), epsilon) &&
is_equal(this->z(), static_cast<value_type>(rhs.z()), epsilon) &&
is_equal(this->w(), static_cast<value_type>(rhs.w()), epsilon));
}
/**
* * Answer whether the quaternion is (exactly) an identity quaternion.
*
* Depending on the underlying storage class, this implementation might
* be vectorised and therefore more efficient than the epsilon
* comparison.
*
* @return true if the quaternion is an identity quaternion,
* false otherwise.
*/
THE_TRY_FORCE_INLINE bool identity(void) const {
static const quaternion IDENTITY(static_cast<value_type>(0), static_cast<value_type>(0),
static_cast<value_type>(0), static_cast<value_type>(1));
return this->equals(IDENTITY);
}
/**
* Answer whether the quaternion is an identity quaternion.
*
* @param epsilon An epsilon value used for comparison. This defaults to
* megamol::core::thecam::math::epsilon<value_type>::value.
*
* @return true if the quaternion is an identity quaternion,
* false otherwise.
*/
inline bool identity(const value_type epsilon) const {
return (is_equal(this->x(), static_cast<value_type>(0), epsilon) &&
is_equal(this->y(), static_cast<value_type>(0), epsilon) &&
is_equal(this->z(), static_cast<value_type>(0), epsilon) &&
is_equal(this->w(), static_cast<value_type>(1), epsilon));
}
/**
* Answer the number of components in the quaternion.
*
* @return 4.
*/
inline size_type size(void) const { return 4; }
/**
* Gets the x-component of the vector part.
*
* @return The x-component of the vector part.
*/
THE_TRY_FORCE_INLINE value_type x(void) const {
return traits_type::at(this->data, static_cast<size_type>(quaternion_component::x));
}
/**
* Gets a reference to the x-component of the vector part.
*
* @return A reference to the x-component of the vector part.
*/
THE_TRY_FORCE_INLINE value_type& x(void) {
return traits_type::at(this->data, static_cast<size_type>(quaternion_component::x));
}
/**
* Gets the y-component of the vector part.
*
* @return The y-component of the vector part.
*/
THE_TRY_FORCE_INLINE value_type y(void) const {
return traits_type::at(this->data, static_cast<size_type>(quaternion_component::y));
}
/**
* Gets a reference to the y-component of the vector part.
*
* @return A reference to the y-component of the vector part.
*/
THE_TRY_FORCE_INLINE value_type& y(void) {
return traits_type::at(this->data, static_cast<size_type>(quaternion_component::y));
}
/**
* Gets the z-component of the vector part.
*
* @return The z-component of the vector part.
*/
THE_TRY_FORCE_INLINE value_type z(void) const {
return traits_type::at(this->data, static_cast<size_type>(quaternion_component::z));
}
/**
* Gets a reference to the z-component of the vector part.
*
* @return A reference to the z-component of the vector part.
*/
THE_TRY_FORCE_INLINE value_type& z(void) {
return traits_type::at(this->data, static_cast<size_type>(quaternion_component::z));
}
/**
* Gets the real part.
*
* @return The real part.
*/
THE_TRY_FORCE_INLINE value_type w(void) const {
return traits_type::at(this->data, static_cast<size_type>(quaternion_component::w));
}
/**
* Gets a reference to the real part.
*
* @return A reference to the real part.
*/
THE_TRY_FORCE_INLINE value_type& w(void) {
return traits_type::at(this->data, static_cast<size_type>(quaternion_component::w));
}
/**
* Assignment.
*
* @param rhs The right-hand side operand.
*
* @return *this.
*/
quaternion& operator=(const quaternion& rhs);
/**
* Conversion assignment.
*
* @tparam Vp The value or native storage type of 'rhs'.
* @tparam Tp The traits type of 'rhs'.
*
* @param rhs The right-hand side operand.
*
* @return *this.
*/
template <class Vp, class Tp> inline quaternion& operator=(const quaternion<Vp, Tp>& rhs) {
this->assign(static_cast<value_type>(rhs.x()), static_cast<value_type>(rhs.y()),
static_cast<value_type>(rhs.z()), static_cast<value_type>(rhs.w()));
return *this;
}
/**
* Answer the given component.
*
* @param c The component to retrieve. Use the quaternion_component
* enumeration for accessing only valid components as the
* operator might not perform bounds checks.
*
* @return The 'c'th component.
*/
THE_TRY_FORCE_INLINE value_type operator[](const quaternion_component c) const {
return traits_type::at(this->data, static_cast<size_type>(c));
}
/**
* Answer the given component.
*
* @param c The component to retrieve. Use the quaternion_component
* enumeration for accessing only valid components as the
* operator might not perform bounds checks.
*
* @return A reference to the 'c'th component.
*/
THE_TRY_FORCE_INLINE value_type& operator[](const quaternion_component c) {
return traits_type::at(this->data, static_cast<size_type>(c));
}
/**
* Conversion to native_type.
*
* @return The native representation of the quaternion.
*/
THE_TRY_FORCE_INLINE operator native_type&(void) { return this->data; }
/**
* Conversion to native_type.
*
* @return The native representation of the quaternion.
*/
THE_TRY_FORCE_INLINE operator const native_type&(void)const { return this->data; }
private:
/** Actually stores the components of the quaternion. */
native_type data;
};
/**
* Conjugate a quaternion.
*
* @param quat The quaternion to be conjugated.
*
* @return The conjugated quaternion.
*/
template <class V, class T> inline quaternion<V, T> conjugate(const quaternion<V, T>& quat) {
typedef typename T::value_type value_type;
quaternion<V, T> retval(quat);
retval.x() *= static_cast<value_type>(-1);
retval.y() *= static_cast<value_type>(-1);
retval.z() *= static_cast<value_type>(-1);
return std::move(retval);
}
#ifdef WITH_THE_GLM
/**
* Conjugate a quaternion.
*
* @param quat The quaternion to be conjugated.
*
* @return The conjugated quaternion.
*/
THE_TRY_FORCE_INLINE quaternion<glm::quat> conjugate(const quaternion<glm::quat>& quat) {
return glm::conjugate(static_cast<glm::quat>(quat));
}
#endif /* WITH_THE_GLM */
/**
* Invert a quaternion.
*
* @tparam V The scalar or native storage type of the quaternion.
* @tparam T The traits type interpreting 'V'.
*
* @param quat The quaternion to be inverted.
*
* @return The inverse quaternion.
*/
template <class V, class T> quaternion<V, T> invert(const quaternion<V, T>& quat);
#ifdef WITH_THE_GLM
/**
* Invert a quaternion.
*
* @param quat The quaternion to be inverted.
*
* @return The inverse quaternion.
*/
THE_TRY_FORCE_INLINE quaternion<glm::quat> invert(const quaternion<glm::quat>& quat) {
return glm::inverse(static_cast<glm::quat>(quat));
}
#endif /* WITH_THE_GLM */
/**
* Compute the norm of a quaternion.
*
* @tparam V The scalar or native storage type of the quaternion.
* @tparam T The traits type interpreting 'V'.
*
* @param quat The quaternion to compute the norm for.
*
* @return The norm of the quaternion.
*/
template <class V, class T> inline typename T::value_type norm(const quaternion<V, T>& quat) {
return sqrt(square_norm(quat));
}
#ifdef WITH_THE_GLM
/**
* Compute the norm of a quaternion.
*
* @param quat The quaternion to compute the norm for.
*
* @return The norm of the quaternion.
*/
THE_TRY_FORCE_INLINE float norm(const quaternion<glm::quat>& quat) { return glm::length(static_cast<glm::quat>(quat)); }
#endif /* WITH_THE_GLM */
/**
* Compute a normalised version of a quaternion.
*
* @tparam V The scalar or native storage type of the quaternion.
* @tparam T The traits type interpreting 'V'.
*
* @param quat The quaternion to be normalised.
*
* @return The normalised quaternion.
*/
template <class V, class T> quaternion<V, T> normalise(const quaternion<V, T>& quat);
#ifdef WITH_THE_GLM
/**
* Compute a normalised version of a quaternion.
*
* @param quat The quaternion to be normalised.
*
* @return The normalised quaternion.
*/
THE_TRY_FORCE_INLINE quaternion<glm::quat> normalise(const quaternion<glm::quat>& quat) {
return glm::normalize(static_cast<glm::quat>(quat));
}
#endif /* WITH_THE_GLM */
/**
* Rotate the vector 'vec' with the given quaternion 'quat'.
*
* @tparam V The scalar or native storage type of the quaternion and vector
* @tparam TQ The traits type interpreting 'V'.
*
* @param vec The vector to be rotated.
* @param quat The quaternion describing the rotation.
*
* @return The rotated vector, having a 0 z-component.
*/
// TODO: this will not work for GLM!!!
template <class V, class TQ, class TV>
inline vector<V, 3, TV> rotate(const vector<V, 3, TV>& vec, const quaternion<V, TQ>& quat);
#ifdef WITH_THE_GLM
/**
* Rotate the vector 'vec' with the given quaternion 'quat'.
*
* @param vec The vector to be rotated.
* @param quat The quaternion describing the rotation.
*
* @return The rotated vector, having a 0 z-component.
*/
inline vector<glm::vec3> rotate(const vector<glm::vec3>& vec, const quaternion<glm::quat>& quat) {
std::decay<decltype(vec)>::type retval(thecam::utility::do_not_initialise);
glm::quat h(0.0f, static_cast<glm::vec3>(vec).x, static_cast<glm::vec3>(vec).y, static_cast<glm::vec3>(vec).z);
h = static_cast<glm::quat>(quat) * h * glm::conjugate(static_cast<glm::quat>(quat));
retval = glm::vec3(h.x, h.y, h.z);
return retval;
}
#endif /* WITH_THE_GLM */
#ifdef WITH_THE_GLM
/**
* Rotate the vector 'vec' with the given quaternion 'quat'.
*
* @param vec The vector to be rotated.
* @param quat The quaternion describing the rotation.
*
*/
inline vector<glm::vec4> rotate(const vector<glm::vec4>& vec, const quaternion<glm::quat>& quat) {
std::decay<decltype(vec)>::type retval(thecam::utility::do_not_initialise);
glm::quat h(0.0f, static_cast<glm::vec4>(vec).x, static_cast<glm::vec4>(vec).y, static_cast<glm::vec4>(vec).z);
h = static_cast<glm::quat>(quat) * h * glm::conjugate(static_cast<glm::quat>(quat));
retval = glm::vec4(h.x, h.y, h.z, 0.0f);
return retval;
}
#endif
/**
* Clears all components in a quaternion.
*
* @tparam V The scalar or native storage type of the quaternion.
* @tparam T The traits type interpreting 'V'.
*
* @param quat The quaternion to modify.
*
* @return 'quat'.
*/
template <class V, class T> inline quaternion<V, T>& set_empty(quaternion<V, T>& quat) {
typedef typename T::value_type value_type;
quat.assign(
static_cast<value_type>(0), static_cast<value_type>(0), static_cast<value_type>(0), static_cast<value_type>(0));
return quat;
}
/**
* Update 'quat' such that it represents a rotation by 'angle' radians
* around 'axis'.
*
* @param Q
* @param V
* @param A The type to specify the angle.
*
* @param quat The quaternion to be updated.
* @param angle The angle to rotate (in radians). Depending on the
* coordinate system used, the direction of a positive
* rotation turns in the directions your fingers curl when
* the left/right thumb points along the rotation axis.
* @param axis The axis to rotate around. Note that the vector does not
* need to be normalised.
*
* @return 'quat'.
*/
// TODO: this will not work for GLM!
template <class Q, class V, class A>
quaternion<Q>& set_from_angle_axis(quaternion<Q>& quat, const A angle, const vector<V, 3>& axis);
template <class Q, class V, class A>
inline quaternion<Q>& set_from_angle_axis(quaternion<Q>& quat, const A angle, const vector<V, 4>& axis) {
vector<V, 3> tmp(axis);
return set_from_angle_axis(quat, angle, tmp);
}
#ifdef WITH_THE_GLM
/**
* Update 'quat' such that it represents a rotation by 'angle' radians
* around 'axis'.
*
* @param A The type to specify the angle.
*
* @param quat The quaternion to be updated.
* @param angle The angle to rotate (in radians).
* @param angle The angle to rotate (in radians). Depending on the
* coordinate system used, the direction of a positive
* rotation turns in the directions your fingers curl when
* the left/right thumb points along the rotation axis.
* @param axis The axis to rotate around. Note that the vector does not
* need to be normalised.
*
* @return 'quat'.
*/
template <class A>
inline quaternion<glm::quat>& set_from_angle_axis(
quaternion<glm::quat>& quat, const A angle, const vector<glm::vec4>& axis) {
glm::vec3 a = glm::vec3(static_cast<glm::vec4>(axis));
a = glm::normalize(a);
glm::quat unit = glm::quat(1, 0, 0, 0);
quat = glm::rotate(static_cast<glm::quat>(unit), angle, a);
return quat;
}
#endif
/**
* Update 'quat' such that it represents a rotation from the angle 'u' to
* the angle 'v'.
*
* @param Q The value type of the quaternion.
* @param V The value type of the vectors.
*
* @param quat The target quaternion to update.
* @param u The original vector.
* @param v The target vector.
*
* @return 'quat'.
*/
template <class Q, class V>
quaternion<Q>& set_from_vectors(quaternion<Q>& quat, const vector<V, 3>& u, const vector<V, 3>& v);
/**
* Update 'quat' such that it represents a rotation from the angle 'u' to
* the angle 'v'.
*
* @param Q The value type of the quaternion.
* @param V The value type of the vectors.
*
* @param quat The target quaternion to update.
* @param u The original vector.
* @param v The target vector.
*
* @return 'quat'.
*/
template <class Q, class V>
quaternion<Q>& set_from_vectors(quaternion<Q>& quat, const vector<V, 4>& u, const vector<V, 4>& v);
#ifdef WITH_THE_GLM
/**
* Update 'quat' such that it represents a rotation from the angle 'u' to
* the angle 'v'.
*
* @param Q
* @param V
*
* @param quat
* @param u The original vector.
* @param v The target vector.
*
* @return 'quat'.
*/
inline quaternion<glm::quat>& set_from_vectors(
quaternion<glm::quat>& quat, const vector<glm::vec3>& u, const vector<glm::vec3>& v);
#endif /* WITH_THE_GLM */
#ifdef WITH_THE_GLM
/**
* Update 'quat' such that it represents a rotation from the angle 'u' to
* the angle 'v'.
*
* @param Q
* @param V
*
* @param quat
* @param u The original vector.
* @param v The target vector.
*
* @return 'quat'.
*/
inline quaternion<glm::quat>& set_from_vectors(
quaternion<glm::quat>& quat, const vector<glm::vec4>& u, const vector<glm::vec4>& v);
#endif /* WITH_THE_GLM */
/**
* Makes a quaternion an identity quaternion.
*
* @tparam V The scalar or native storage type of the quaternion.
* @tparam T The traits type interpreting 'V'.
*
* @param quat The quaternion to modify.
*
* @return 'quat'.
*/
template <class V, class T> inline quaternion<V, T>& set_identity(quaternion<V, T>& quat) {
typedef typename T::value_type value_type;
quat.assign(
static_cast<value_type>(0), static_cast<value_type>(0), static_cast<value_type>(0), static_cast<value_type>(1));
return quat;
}
#ifdef WITH_THE_GLM
/**
* Makes a quaternion an identity quaternion.
*
* @param quat The quaternion to modify.
*
* @return 'quat'.
*/
inline quaternion<glm::quat>& set_identity(quaternion<glm::quat>& quat) {
quat = glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
return quat;
}
#endif /* WITH_THE_GLM */
/**
* Compute the squared norm of the given quaternion.
*
* @tparam V The scalar or native storage type of the quaternion.
* @tparam T The traits type interpreting 'V'.
*
* @param quat a quaternion.
*
* @return The square norm of 'quat'.
*/
template <class V, class T> inline typename T::value_type square_norm(const quaternion<V, T>& quat) {
return (sqr(quat.x()) + sqr(quat.y()) + sqr(quat.z()) + sqr(quat.w()));
}
#ifdef WITH_THE_GLM
/**
* Compute the squared norm of the given quaternion.
*
* @param quat a quaternion.
*
* @return The square norm of 'quat'.
*/
THE_TRY_FORCE_INLINE float square_norm(const quaternion<glm::quat>& quat) {
float l = glm::length(static_cast<glm::quat>(quat));
return l * l;
}
#endif /* WITH_THE_GLM */
/**
* Multiply two quaternions.
*
* @tparam V The scalar or native storage type of the quaternion.
* @tparam T The traits type interpreting 'V'.
*
* @param lhs The left-hand side operand.
* @param rhs The right-hand side operand.
*
* @return 'lhs' * 'rhs'.
*/
template <class V, class T> quaternion<V, T> operator*(const quaternion<V, T>& lhs, const quaternion<V, T>& rhs);
#ifdef WITH_THE_GLM
/**
* Multiply two quaternions.
*
* @param lhs The left-hand side operand.
* @param rhs The right-hand side operand.
*
* @return 'lhs' * 'rhs'.
*/
THE_TRY_FORCE_INLINE quaternion<glm::quat> operator*(
const quaternion<glm::quat>& lhs, const quaternion<glm::quat>& rhs) {
return static_cast<glm::quat>(lhs) * static_cast<glm::quat>(rhs);
}
#endif /* WITH_THE_GLM */
} /* end namespace math */
} /* end namespace thecam */
} /* end namespace core */
} /* end namespace megamol */
#include "mmcore/thecam/math/quaternion.inl"
#if defined(_WIN32) && defined(_MANAGED)
# pragma managed(pop)
#endif /* defined(_WIN32) && defined(_MANAGED) */
#endif /* THE_MATH_QUATERNION_H_INCLUDED */
| 32.818605 | 120 | 0.654875 |
aaf57783121efb168a5cddc5b13e85723714e68c | 4,797 | c | C | motomini_dynamics_publisher/src/MotoMINI_Model/ex_bb0efd4b.c | ntl-ros-pkg/motoman_path_planning | c9fbe19748a4290182997c2b5baa6a08375745e0 | [
"Apache-2.0"
] | null | null | null | motomini_dynamics_publisher/src/MotoMINI_Model/ex_bb0efd4b.c | ntl-ros-pkg/motoman_path_planning | c9fbe19748a4290182997c2b5baa6a08375745e0 | [
"Apache-2.0"
] | null | null | null | motomini_dynamics_publisher/src/MotoMINI_Model/ex_bb0efd4b.c | ntl-ros-pkg/motoman_path_planning | c9fbe19748a4290182997c2b5baa6a08375745e0 | [
"Apache-2.0"
] | null | null | null | #include "pm_std.h"
#include "lang_std.h"
#include "external_std.h"
#include "pm_std.h"
static size_t ex_L5fur6LFRji_Faer_7yzJ1(const real_T x,const real_T*
ex_kqTQ1epcuYM_DyDj2jQ1y1,const size_t n){size_t ex_SmSSPSQfR1qEYWsVj5ELF0;if(
x<ex_kqTQ1epcuYM_DyDj2jQ1y1[0]){ex_SmSSPSQfR1qEYWsVj5ELF0=0;}else if(x>
ex_kqTQ1epcuYM_DyDj2jQ1y1[n-1]){ex_SmSSPSQfR1qEYWsVj5ELF0=n+1;}else{for(
ex_SmSSPSQfR1qEYWsVj5ELF0=1;((ex_SmSSPSQfR1qEYWsVj5ELF0<=n)&&(
ex_kqTQ1epcuYM_DyDj2jQ1y1[ex_SmSSPSQfR1qEYWsVj5ELF0-1]<x));++
ex_SmSSPSQfR1qEYWsVj5ELF0);}return ex_SmSSPSQfR1qEYWsVj5ELF0;}static void
ex_h9PBDMihcYS7CWc28W2Hk2(const real_T*freqs,const real_T*ys,const size_t*dims
,const size_t ex_dYWQAHvQodwoJxkVJbvZO2,const real_T ex_vKct5bj2VVv2h_QlqkYJ__
,const boolean_T ex_xVJyoK3_zCEvg7tMJpsHl0,real_T*out){const size_t n1=dims[0]
;const size_t n2=dims[1];const real_T*ex_kqTQ1epcuYM_DyDj2jQ1y1=freqs;const
real_T*ex_8B7ltUy9RiwsITRZEKL491=ys;const real_T ex_tTtxUlYB91DFoEeDuWMX42=
ex_kqTQ1epcuYM_DyDj2jQ1y1[ex_dYWQAHvQodwoJxkVJbvZO2-2];const real_T
ex_INFh9oCMwF1cYY_NM_qI6_=ex_kqTQ1epcuYM_DyDj2jQ1y1[ex_dYWQAHvQodwoJxkVJbvZO2-
1];size_t ex_SmSSPSQfR1qEYWsVj5ELF0;for(ex_SmSSPSQfR1qEYWsVj5ELF0=0;
ex_SmSSPSQfR1qEYWsVj5ELF0<n1*n2;++ex_SmSSPSQfR1qEYWsVj5ELF0){const real_T
ex_R7GeHlROOcMcs_D8xOULH_=ex_8B7ltUy9RiwsITRZEKL491[n1*n2*(
ex_dYWQAHvQodwoJxkVJbvZO2-2)+ex_SmSSPSQfR1qEYWsVj5ELF0];const real_T
ex_2lOQ_J4Eg_4WEdK8QEWds2=ex_8B7ltUy9RiwsITRZEKL491[n1*n2*(
ex_dYWQAHvQodwoJxkVJbvZO2-1)+ex_SmSSPSQfR1qEYWsVj5ELF0];if(
ex_xVJyoK3_zCEvg7tMJpsHl0){out[ex_SmSSPSQfR1qEYWsVj5ELF0]=(
ex_2lOQ_J4Eg_4WEdK8QEWds2-ex_R7GeHlROOcMcs_D8xOULH_)/(
ex_INFh9oCMwF1cYY_NM_qI6_-ex_tTtxUlYB91DFoEeDuWMX42);}else{const real_T
ex_2uBQKmJh8fN996cwNJ9xZ2=(ex_vKct5bj2VVv2h_QlqkYJ__-ex_tTtxUlYB91DFoEeDuWMX42
)/(ex_INFh9oCMwF1cYY_NM_qI6_-ex_tTtxUlYB91DFoEeDuWMX42);out[
ex_SmSSPSQfR1qEYWsVj5ELF0]=(ex_R7GeHlROOcMcs_D8xOULH_+
ex_2uBQKmJh8fN996cwNJ9xZ2*(ex_2lOQ_J4Eg_4WEdK8QEWds2-ex_R7GeHlROOcMcs_D8xOULH_
));}}}void tlu_simrf_F(real_T*out,const real_T*freqs,const real_T*ys,const
real_T*ex_fTSMkiBbL1SVd6HrBLoO61,const size_t*dims){const size_t n1=dims[0];
const size_t n2=dims[1];const size_t ex_aaoxK9WbdAx5eZJ1nk8lT_=dims[2];const
real_T freq= *ex_fTSMkiBbL1SVd6HrBLoO61;const size_t ex_dYWQAHvQodwoJxkVJbvZO2
=ex_L5fur6LFRji_Faer_7yzJ1(freq,freqs,ex_aaoxK9WbdAx5eZJ1nk8lT_);if(
ex_dYWQAHvQodwoJxkVJbvZO2>=ex_aaoxK9WbdAx5eZJ1nk8lT_+1){size_t
ex_SmSSPSQfR1qEYWsVj5ELF0;for(ex_SmSSPSQfR1qEYWsVj5ELF0=0;
ex_SmSSPSQfR1qEYWsVj5ELF0<n1*n2;++ex_SmSSPSQfR1qEYWsVj5ELF0){out[
ex_SmSSPSQfR1qEYWsVj5ELF0]=ys[n1*n2*(ex_aaoxK9WbdAx5eZJ1nk8lT_-1)+
ex_SmSSPSQfR1qEYWsVj5ELF0];}}else if(ex_dYWQAHvQodwoJxkVJbvZO2<=1){size_t
ex_SmSSPSQfR1qEYWsVj5ELF0;for(ex_SmSSPSQfR1qEYWsVj5ELF0=0;
ex_SmSSPSQfR1qEYWsVj5ELF0<n1*n2;++ex_SmSSPSQfR1qEYWsVj5ELF0){out[
ex_SmSSPSQfR1qEYWsVj5ELF0]=ys[ex_SmSSPSQfR1qEYWsVj5ELF0];}}else{
ex_h9PBDMihcYS7CWc28W2Hk2(freqs,ys,dims,ex_dYWQAHvQodwoJxkVJbvZO2,freq,false,
out);}}void tlu_simrf_F_custom_function_(PMValue ex_JC14Uma4n_uWFYyh6wmkX2,
ConstPMValue ex_8Knj_sbNPYaamO7zB0XjK0){real_T*out=(real_T*)
ex_JC14Uma4n_uWFYyh6wmkX2;const real_T*freqs=(const real_T*)((const void*const
*)ex_8Knj_sbNPYaamO7zB0XjK0)[0];const real_T*ys=(const real_T*)((const void*
const*)ex_8Knj_sbNPYaamO7zB0XjK0)[1];const real_T*freq=(const real_T*)((const
void*const*)ex_8Knj_sbNPYaamO7zB0XjK0)[2];const size_t*dims=(const size_t*)((
const void*const*)ex_8Knj_sbNPYaamO7zB0XjK0)[3];tlu_simrf_F(out,freqs,ys,freq,
dims);}void tlu_simrf_DF(real_T*out,const real_T*freqs,const real_T*ys,const
real_T*ex_fTSMkiBbL1SVd6HrBLoO61,const size_t*dims){const size_t n1=dims[0];
const size_t n2=dims[1];const size_t ex_aaoxK9WbdAx5eZJ1nk8lT_=dims[2];const
real_T freq= *ex_fTSMkiBbL1SVd6HrBLoO61;const size_t ex_dYWQAHvQodwoJxkVJbvZO2
=ex_L5fur6LFRji_Faer_7yzJ1(freq,freqs,ex_aaoxK9WbdAx5eZJ1nk8lT_);if((
ex_dYWQAHvQodwoJxkVJbvZO2>=ex_aaoxK9WbdAx5eZJ1nk8lT_+1)||(
ex_dYWQAHvQodwoJxkVJbvZO2<=1)){size_t ex_SmSSPSQfR1qEYWsVj5ELF0;for(
ex_SmSSPSQfR1qEYWsVj5ELF0=0;ex_SmSSPSQfR1qEYWsVj5ELF0<n1*n2;++
ex_SmSSPSQfR1qEYWsVj5ELF0){out[ex_SmSSPSQfR1qEYWsVj5ELF0]=0.0;}}else{
ex_h9PBDMihcYS7CWc28W2Hk2(freqs,ys,dims,ex_dYWQAHvQodwoJxkVJbvZO2,freq,true,
out);}}void tlu_simrf_DF_custom_function_(PMValue ex_JC14Uma4n_uWFYyh6wmkX2,
ConstPMValue ex_8Knj_sbNPYaamO7zB0XjK0){real_T*out=(real_T*)
ex_JC14Uma4n_uWFYyh6wmkX2;const real_T*freqs=(const real_T*)((const void*const
*)ex_8Knj_sbNPYaamO7zB0XjK0)[0];const real_T*ys=(const real_T*)((const void*
const*)ex_8Knj_sbNPYaamO7zB0XjK0)[1];const real_T*freq=(const real_T*)((const
void*const*)ex_8Knj_sbNPYaamO7zB0XjK0)[2];const size_t*dims=(const size_t*)((
const void*const*)ex_8Knj_sbNPYaamO7zB0XjK0)[3];tlu_simrf_DF(out,freqs,ys,freq
,dims);}
| 67.56338 | 79 | 0.846779 |
30871f4929e146428cd4bfc27fbe9d32109f0d29 | 3,909 | h | C | RGBWLed.h | Susensio/RGBWLed | dbf45385037ac727f19c727da1c3306f5c5bf6bf | [
"MIT"
] | 4 | 2019-09-05T01:01:26.000Z | 2021-08-17T11:54:10.000Z | RGBWLed.h | Susensio/RGBWLed | dbf45385037ac727f19c727da1c3306f5c5bf6bf | [
"MIT"
] | null | null | null | RGBWLed.h | Susensio/RGBWLed | dbf45385037ac727f19c727da1c3306f5c5bf6bf | [
"MIT"
] | null | null | null | /*********************************
* RGBWLed library for RGB+W leds
* Implements HSI colour space
*
* Created by Saul Nogueras Ona
* February 28, 2015
********************************/
#ifndef RGBWLed_h
#define RGBWLed_h
#include "Arduino.h"
/**
* Helper class for RGBW-colours.
*/
typedef struct {
byte r;
byte g;
byte b;
byte w;
} RGBW;
/**
* Helper class for HSI-colours.
*/
typedef struct {
float h;
float s;
byte i;
} HSI;
/**
* Helper class for Kelvin colours.
*/
typedef struct {
float t;
byte i;
} Kelvin;
/*
* Exponential lookup table for dimming
* Gamma = 2.8
*/
const PROGMEM byte curve[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,
2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5,
5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10,
10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16,
17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25,
25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36,
37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50,
51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68,
69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89,
90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114,
115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142,
144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175,
177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213,
215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 };
class RGBWLed {
public:
// Initializes an instance and configures LED pins as OUTPUTs
RGBWLed (byte redPin, byte greenPin, byte bluePin, byte whitePin);
// Sets global intensity
void setIntensity(byte value);
// red, green and blue are [0..255] values, raw values
void writeRGBW(byte red, byte green, byte blue, byte white);
void writeRGBW(RGBW colour);
// red, green and blue are [0..255] values, dim correction
void setRGBW(byte red, byte green, byte blue, byte white);
void setRGBW(RGBW colour);
// hue in degrees, saturation normalized [0..1] and intensity 8-bits [0..255]
void setHSI(float hue, float sat, byte in);
void setHSI(HSI colour);
// temp in Kelvin, intensity 8-bits [0..255]
void setKelvin(float temp, byte in);
void setKelvin(Kelvin colour);
// Fade functions, duration in seconds
void fadeHSI(HSI initcolour, HSI endcolour, unsigned int duration_s, unsigned int steps);
void fadeKelvin(Kelvin initcolour, Kelvin endcolour, unsigned int duration_s, unsigned int steps);
void updateFade(void);
boolean isFading(void);
void pauseFade(void);
void resumeFade(void);
// This function allows fading in HSI colourspace between Kelvin colours
static HSI KtoHSI(Kelvin colour);
private:
byte rPin;
byte gPin;
byte bPin;
byte wPin;
byte globalIntensity;
// Variables for fading
unsigned long period;
unsigned long tlast;
unsigned int step;
boolean fadingHSI;
boolean fadingKelvin;
HSI colourH;
Kelvin colourK;
float aux1;
float aux2;
float aux3;
float intensity;
// Variables for pause fading
unsigned long periodCopy;
unsigned long tlastCopy;
unsigned int stepCopy;
boolean fadingHSICopy;
boolean fadingKelvinCopy;
HSI colourHCopy;
Kelvin colourKCopy;
float aux1Copy;
float aux2Copy;
float aux3Copy;
float intensityCopy;
// Helpers
static RGBW HSItoRGBW(HSI colour);
static RGBW KtoRGBW(Kelvin colour);
static HSI RGBWtoHSI(RGBW colour);
static float degToRad(float deg);
static float radToDeg(float rad);
};
#endif | 27.528169 | 102 | 0.60834 |
ca28cbf09125454cfd394a281fdb1f5e22ed7355 | 17,782 | c | C | bsp/essemi/es32f369x/libraries/ES32F36xx_ALD_StdPeriph_Driver/Source/ald_nor_lcd.c | rockonedege/rt-thread | 4fe6c709d0bfe719bed6c927f0144ba373bbda5a | [
"Apache-2.0"
] | 7,482 | 2015-01-01T09:23:08.000Z | 2022-03-31T19:34:05.000Z | bsp/essemi/es32f369x/libraries/ES32F36xx_ALD_StdPeriph_Driver/Source/ald_nor_lcd.c | ArdaFu/rt-thread | eebb2561ec166e0016187c7b7998ada4f8212b3a | [
"Apache-2.0"
] | 2,543 | 2015-01-09T02:01:34.000Z | 2022-03-31T23:10:14.000Z | bsp/essemi/es32f369x/libraries/ES32F36xx_ALD_StdPeriph_Driver/Source/ald_nor_lcd.c | ArdaFu/rt-thread | eebb2561ec166e0016187c7b7998ada4f8212b3a | [
"Apache-2.0"
] | 4,645 | 2015-01-06T07:05:31.000Z | 2022-03-31T18:21:50.000Z | /**
*********************************************************************************
*
* @file ald_nor_lcd.c
* @brief EBI_NOR_LCD module driver.
*
* @version V1.0
* @date 25 Dec 2019
* @author AE Team
* @note
*
* Copyright (C) Shanghai Eastsoft Microelectronics Co. Ltd. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 "ald_nor_lcd.h"
/** @addtogroup ES32FXXX_ALD
* @{
*/
/** @defgroup NOR_LCD NOR_LCD
* @brief NOR_LCD driver modules
* @{
*/
#ifdef ALD_NOR
/** @defgroup NOR_LCD_Private_Variables NOR_LCD Private Variables
* @{
*/
static uint32_t NORMEMDATWIDTH = NOR_MEMORY_8B;
/**
* @}
*/
/** @defgroup NOR_LCD_Public_Functions NOR_LCD Public Functions
* @brief NOR_LCD public functions
* @{
*/
/** @defgroup NOR_LCD_Public_Functions_Group1 Initialization functions
* @brief NOR_LCD Initialization functions
* @{
*/
/**
* @brief Perform the NOR memory Initialization sequence
* @param hperh: pointer to a nor_handle_t structure
* @param timing: pointer to NOR control timing structure
* @param ext_timing: pointer to NOR extended mode timing structure
* @retval ald status
*/
ald_status_t ald_nor_init(nor_handle_t *hperh, ald_ebi_nor_sram_timing_t *timing, ald_ebi_nor_sram_timing_t *ext_timing)
{
if (hperh == NULL)
return ERROR;
if (hperh->state == ALD_NOR_STATE_RESET)
hperh->lock = UNLOCK;
/* Initialize NOR control Interface */
ald_ebi_nor_sram_init(hperh->instance, &(hperh->init));
/* Initialize NOR timing Interface */
ald_ebi_nor_sram_timing_init(hperh->instance, timing, hperh->init.bank);
/* Initialize NOR extended mode timing Interface */
ald_ebi_nor_sram_ext_timing_init(hperh->ext, ext_timing, hperh->init.bank, hperh->init.ext_mode);
/* Enable the NORSRAM device */
ald_ebi_nor_sram_enable(hperh->instance, hperh->init.bank);
/* Initialize NOR Memory Data Width*/
if (hperh->init.width == EBI_NORSRAM_MEM_BUS_WIDTH_8)
NORMEMDATWIDTH = NOR_MEMORY_8B;
else
NORMEMDATWIDTH = NOR_MEMORY_16B;
hperh->state = ALD_NOR_STATE_READY;
return OK;
}
/**
* @brief Perform NOR memory De-Initialization sequence
* @param hperh: pointer to a nor_handle_t structure
* @retval ald status
*/
ald_status_t ald_nor_deinit(nor_handle_t *hperh)
{
ald_ebi_nor_sram_deinit(hperh->instance, hperh->ext, hperh->init.bank);
hperh->state = ALD_NOR_STATE_RESET;
__UNLOCK(hperh);
return OK;
}
/**
* @}
*/
/** @defgroup NOR_LCD_Public_Functions_Group2 I/O operation functions
* @brief NOR_LCD I/O operation functions
* @{
*/
/**
* @brief Read NOR flash IDs
* @param hperh: pointer to a nor_handle_t structure
* @param id : pointer to NOR ID structure
* @retval ald status
*/
ald_status_t ald_nor_read_id(nor_handle_t *hperh, nor_id_t *id)
{
uint32_t devaddr = 0;
__LOCK(hperh);
if (hperh->state == ALD_NOR_STATE_BUSY)
return BUSY;
/* Select the NOR device address */
if (hperh->init.bank == EBI_NORSRAM_BANK1)
devaddr = NOR_MEMORY_ADRESS1;
else if (hperh->init.bank == EBI_NORSRAM_BANK2)
devaddr = NOR_MEMORY_ADRESS2;
else if (hperh->init.bank == EBI_NORSRAM_BANK3)
devaddr = NOR_MEMORY_ADRESS3;
else
devaddr = NOR_MEMORY_ADRESS4;
hperh->state = ALD_NOR_STATE_BUSY;
/* Send read ID command */
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_AUTO_SELECT);
/* Read the NOR IDs */
id->m_code = *(__IO uint16_t *) NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, MC_ADDRESS);
id->device_code1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, DEVICE_CODE1_ADDR);
id->device_code2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, DEVICE_CODE2_ADDR);
id->device_code3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, DEVICE_CODE3_ADDR);
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @brief Returns the NOR memory to Read mode.
* @param hperh: pointer to a nor_handle_t structure
* @retval ald status
*/
ald_status_t ald_nor_return_readmode(nor_handle_t *hperh)
{
uint32_t devaddr = 0;
__LOCK(hperh);
if (hperh->state == ALD_NOR_STATE_BUSY)
return BUSY;
/* Select the NOR device address */
if (hperh->init.bank == EBI_NORSRAM_BANK1)
devaddr = NOR_MEMORY_ADRESS1;
else if (hperh->init.bank == EBI_NORSRAM_BANK2)
devaddr = NOR_MEMORY_ADRESS2;
else if (hperh->init.bank == EBI_NORSRAM_BANK3)
devaddr = NOR_MEMORY_ADRESS3;
else
devaddr = NOR_MEMORY_ADRESS4;
NOR_WRITE(devaddr, NOR_CMD_DATA_READ_RESET);
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @brief Read data from NOR memory
* @param hperh: pointer to a nor_handle_t structure
* @param addr: pointer to Device address
* @param data: pointer to read data
* @retval ald status
*/
ald_status_t ald_nor_read(nor_handle_t *hperh, uint32_t *addr, uint16_t *data)
{
uint32_t devaddr = 0;
__LOCK(hperh);
if (hperh->state == ALD_NOR_STATE_BUSY)
return BUSY;
if (hperh->init.bank == EBI_NORSRAM_BANK1)
devaddr = NOR_MEMORY_ADRESS1;
else if (hperh->init.bank == EBI_NORSRAM_BANK2)
devaddr = NOR_MEMORY_ADRESS2;
else if (hperh->init.bank == EBI_NORSRAM_BANK3)
devaddr = NOR_MEMORY_ADRESS3;
else
devaddr = NOR_MEMORY_ADRESS4;
hperh->state = ALD_NOR_STATE_BUSY;
/* Send read data command */
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE((uint32_t)addr, NOR_CMD_DATA_READ_RESET);
*data = *(__IO uint32_t *)(uint32_t)addr;
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @brief Program data to NOR memory
* @param hperh: pointer to a nor_handle_t structure
* @param addr: device address
* @param data: pointer to the data to write
* @retval ald status
*/
ald_status_t ald_nor_program(nor_handle_t *hperh, uint32_t *addr, uint16_t *data)
{
uint32_t devaddr = 0;
__LOCK(hperh);
if (hperh->state == ALD_NOR_STATE_BUSY)
return BUSY;
/* Select the NOR device address */
if (hperh->init.bank == EBI_NORSRAM_BANK1)
devaddr = NOR_MEMORY_ADRESS1;
else if (hperh->init.bank == EBI_NORSRAM_BANK2)
devaddr = NOR_MEMORY_ADRESS2;
else if (hperh->init.bank == EBI_NORSRAM_BANK3)
devaddr = NOR_MEMORY_ADRESS3;
else /* EBI_NORSRAM_BANK4 */
devaddr = NOR_MEMORY_ADRESS4;
hperh->state = ALD_NOR_STATE_BUSY;
/* Send program data command */
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_PROGRAM);
/* Write the data */
NOR_WRITE(addr, *data);
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @brief Reads a block of data from the EBI NOR memory
* @param hperh: pointer to a nor_handle_t structure
* @param addr: nor memory internal address to read from
* @param data: pointer to the buffer that receives the data read from the
* NOR memory
* @param size : number of Half word to read
* @retval ald status
*/
ald_status_t ald_nor_read_buffer(nor_handle_t *hperh, uint32_t addr, uint16_t *data, uint32_t size)
{
uint32_t devaddr = 0;
/* Process Locked */
__LOCK(hperh);
if (hperh->state == ALD_NOR_STATE_BUSY)
return BUSY;
if (hperh->init.bank == EBI_NORSRAM_BANK1)
devaddr = NOR_MEMORY_ADRESS1;
else if (hperh->init.bank == EBI_NORSRAM_BANK2)
devaddr = NOR_MEMORY_ADRESS2;
else if (hperh->init.bank == EBI_NORSRAM_BANK3)
devaddr = NOR_MEMORY_ADRESS3;
else
devaddr = NOR_MEMORY_ADRESS4;
hperh->state = ALD_NOR_STATE_BUSY;
/* Send read data command */
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(addr, NOR_CMD_DATA_READ_RESET);
/* Read buffer */
while (size > 0) {
*data++ = *(__IO uint16_t *)addr;
addr += 2U;
size--;
}
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @brief Writes a half-word buffer to the EBI NOR memory
* @param hperh: pointer to a nor_handle_t structure
* @param addr: nor memory internal address from which the data
* @param data: pointer to source data buffer
* @param size: number of Half words to write
* @retval ald status
*/
ald_status_t ald_nor_program_buffer(nor_handle_t *hperh, uint32_t addr, uint16_t *data, uint32_t size)
{
uint16_t * p_currentaddr = (uint16_t *)NULL;
uint16_t * p_endaddr = (uint16_t *)NULL;
uint32_t lastloadedaddr = 0, devaddr = 0;
__LOCK(hperh);
if (hperh->state == ALD_NOR_STATE_BUSY)
return BUSY;
if (hperh->init.bank == EBI_NORSRAM_BANK1)
devaddr = NOR_MEMORY_ADRESS1;
else if (hperh->init.bank == EBI_NORSRAM_BANK2)
devaddr = NOR_MEMORY_ADRESS2;
else if (hperh->init.bank == EBI_NORSRAM_BANK3)
devaddr = NOR_MEMORY_ADRESS3;
else
devaddr = NOR_MEMORY_ADRESS4;
hperh->state = ALD_NOR_STATE_BUSY;
/* Initialize variables */
p_currentaddr = (uint16_t*)((uint32_t)(addr));
p_endaddr = p_currentaddr + (size - 1U);
lastloadedaddr = (uint32_t)(addr);
/* Issue unlock command sequence */
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
/* Write Buffer Load Command */
NOR_WRITE((uint32_t)(p_currentaddr), NOR_CMD_DATA_BUFFER_AND_PROG);
NOR_WRITE((uint32_t)(p_currentaddr), (size - 1U));
/* Load Data into NOR Buffer */
while (p_currentaddr <= p_endaddr) {
lastloadedaddr = (uint32_t)p_currentaddr;
NOR_WRITE(p_currentaddr, *data++);
p_currentaddr++;
}
NOR_WRITE((uint32_t)(lastloadedaddr), NOR_CMD_DATA_BUFFER_AND_PROG_CONFIRM);
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @brief Erase the specified block of the NOR memory
* @param hperh: pointer to a nor_handle_t structure
* @param blkaddr : block to erase address
* @param addr: device address
* @retval ald status
*/
ald_status_t ald_nor_erase_block(nor_handle_t *hperh, uint32_t blkaddr, uint32_t addr)
{
uint32_t devaddr = 0;
__LOCK(hperh);
if (hperh->state == ALD_NOR_STATE_BUSY)
return BUSY;
if (hperh->init.bank == EBI_NORSRAM_BANK1)
devaddr = NOR_MEMORY_ADRESS1;
else if (hperh->init.bank == EBI_NORSRAM_BANK2)
devaddr = NOR_MEMORY_ADRESS2;
else if (hperh->init.bank == EBI_NORSRAM_BANK3)
devaddr = NOR_MEMORY_ADRESS3;
else
devaddr = NOR_MEMORY_ADRESS4;
hperh->state = ALD_NOR_STATE_BUSY;
/* Send block erase command sequence */
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FOURTH), NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIFTH), NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH);
NOR_WRITE((uint32_t)(blkaddr + addr), NOR_CMD_DATA_BLOCK_ERASE);
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @brief Erase the entire NOR chip.
* @param hperh: pointer to a nor_handle_t structure
* @retval ald status
*/
ald_status_t ald_nor_erase_chip(nor_handle_t *hperh)
{
uint32_t devaddr = 0;
__LOCK(hperh);
if (hperh->state == ALD_NOR_STATE_BUSY)
return BUSY;
/* Select the NOR device address */
if (hperh->init.bank == EBI_NORSRAM_BANK1)
devaddr = NOR_MEMORY_ADRESS1;
else if (hperh->init.bank == EBI_NORSRAM_BANK2)
devaddr = NOR_MEMORY_ADRESS2;
else if (hperh->init.bank == EBI_NORSRAM_BANK3)
devaddr = NOR_MEMORY_ADRESS3;
else
devaddr = NOR_MEMORY_ADRESS4;
hperh->state = ALD_NOR_STATE_BUSY;
/* Send NOR chip erase command sequence */
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FOURTH), NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIFTH), NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH);
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_SIXTH), NOR_CMD_DATA_CHIP_ERASE);
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @brief Read NOR flash CFI IDs
* @param hperh: pointer to a nor_handle_t structure
* @param cfi: pointer to NOR CFI IDs structure
* @retval ald status
*/
ald_status_t ald_nor_read_cfi(nor_handle_t *hperh, nor_cfi_t *cfi)
{
uint32_t devaddr = 0;
__LOCK(hperh);
if (hperh->state == ALD_NOR_STATE_BUSY)
return BUSY;
/* Select the NOR device address */
if (hperh->init.bank == EBI_NORSRAM_BANK1)
devaddr = NOR_MEMORY_ADRESS1;
else if (hperh->init.bank == EBI_NORSRAM_BANK2)
devaddr = NOR_MEMORY_ADRESS2;
else if (hperh->init.bank == EBI_NORSRAM_BANK3)
devaddr = NOR_MEMORY_ADRESS3;
else
devaddr = NOR_MEMORY_ADRESS4;
hperh->state = ALD_NOR_STATE_BUSY;
NOR_WRITE(NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, NOR_CMD_ADDRESS_FIRST_CFI), NOR_CMD_DATA_CFI);
cfi->cfi_1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, CFI1_ADDRESS);
cfi->cfi_2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, CFI2_ADDRESS);
cfi->cfi_3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, CFI3_ADDRESS);
cfi->cfi_4 = *(__IO uint16_t *) NOR_ADDR_SHIFT(devaddr, NORMEMDATWIDTH, CFI4_ADDRESS);
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @}
*/
/** @defgroup NOR_LCD_Public_Functions_Group3 Control functions
* @brief NOR_LCD Control functions
* @{
*/
/**
* @brief Enables dynamically NOR write operation.
* @param hperh: pointer to a nor_handle_t structure
* @retval ald status
*/
ald_status_t ald_nor_write_enable(nor_handle_t *hperh)
{
__LOCK(hperh);
/* Enable write operation */
ald_ebi_nor_sram_write_enable(hperh->instance, hperh->init.bank);
hperh->state = ALD_NOR_STATE_READY;
__UNLOCK(hperh);
return OK;
}
/**
* @brief Disables dynamically NOR write operation.
* @param hperh: pointer to a nor_handle_t structure
* @retval ald status
*/
ald_status_t ald_nor_write_disable(nor_handle_t *hperh)
{
__LOCK(hperh);
hperh->state = ALD_NOR_STATE_BUSY;
/* Disable write operation */
ald_ebi_nor_sram_write_disable(hperh->instance, hperh->init.bank);
hperh->state = ALD_NOR_STATE_PROTECTED;
__UNLOCK(hperh);
return OK;
}
/**
* @}
*/
/** @defgroup NOR_LCD_Public_Functions_Group4 State functions
* @brief NOR_LCD State functions
* @{
*/
/**
* @brief return the NOR controller state
* @param hperh: pointer to a nor_handle_t structure
* @retval nor controller state
*/
ald_nor_state_t ald_nor_get_state(nor_handle_t *hperh)
{
return hperh->state;
}
/**
* @brief Returns the NOR operation status.
* @param hperh: pointer to a nor_handle_t structure
* @param addr: device address
* @param timeout: nor progamming timeout
* @retval nor status
*/
nor_status_t ald_nor_get_status(nor_handle_t *hperh, uint32_t addr, uint32_t timeout)
{
nor_status_t status = ALD_NOR_STATUS_ONGOING;
uint16_t tmp_sr1 = 0, tmp_sr2 = 0;
uint32_t tickstart = 0;
/* Get tick */
tickstart = ald_get_tick();
while ((status != ALD_NOR_STATUS_SUCCESS) && (status != ALD_NOR_STATUS_TIMEOUT)) {
/* Check for the Timeout */
if (timeout != ALD_MAX_DELAY) {
if ((timeout == 0) || ((ald_get_tick() - tickstart ) > timeout))
status = ALD_NOR_STATUS_TIMEOUT;
}
/* Read NOR status register (DQ6 and DQ5) */
tmp_sr1 = *(__IO uint16_t *)addr;
tmp_sr2 = *(__IO uint16_t *)addr;
/* If DQ6 did not toggle between the two reads then return NOR_Success */
if ((tmp_sr1 & NOR_MASK_STATUS_DQ6) == (tmp_sr2 & NOR_MASK_STATUS_DQ6))
return ALD_NOR_STATUS_SUCCESS;
if ((tmp_sr1 & NOR_MASK_STATUS_DQ5) != NOR_MASK_STATUS_DQ5)
status = ALD_NOR_STATUS_ONGOING;
tmp_sr1 = *(__IO uint16_t *)addr;
tmp_sr2 = *(__IO uint16_t *)addr;
/* If DQ6 did not toggle between the two reads then return NOR_Success */
if ((tmp_sr1 & NOR_MASK_STATUS_DQ6) == (tmp_sr2 & NOR_MASK_STATUS_DQ6))
return ALD_NOR_STATUS_SUCCESS;
else if ((tmp_sr1 & NOR_MASK_STATUS_DQ5) == NOR_MASK_STATUS_DQ5)
return ALD_NOR_STATUS_ERROR;
}
return status;
}
/**
* @}
*/
/**
* @}
*/
#endif
/**
* @}
*/
/**
* @}
*/
| 29.198686 | 120 | 0.730008 |
aa5c305c2b6b36112fbeb005262d55b034bc1b9e | 325 | h | C | example/svg_Mac/MacViewController.h | ap4y/UIBezierPath-SVG | 411041a8d806a6e844fb97dffc47d9751424c20a | [
"MIT"
] | 107 | 2015-01-15T10:37:08.000Z | 2022-03-18T01:45:36.000Z | example/svg_Mac/MacViewController.h | ap4y/UIBezierPath-SVG | 411041a8d806a6e844fb97dffc47d9751424c20a | [
"MIT"
] | null | null | null | example/svg_Mac/MacViewController.h | ap4y/UIBezierPath-SVG | 411041a8d806a6e844fb97dffc47d9751424c20a | [
"MIT"
] | 16 | 2015-03-19T05:14:39.000Z | 2022-01-20T08:24:07.000Z | //
// MacViewController.h
// svg_test
//
// Created by Michael Redig on 9/29/14.
//
//
#import <Foundation/Foundation.h>
#import "SKUBezierPath+SVG.h"
#import "NSBezierPath+CGPath.h"
@interface MacViewController : NSObject
@property (weak) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSView *windowView;
@end
| 17.105263 | 45 | 0.726154 |
45f64e7f2e03660e59460f84fab31aa93c9c3d2f | 16,452 | h | C | jni-build/jni/include/external/eigen_archive/Eigen/src/SparseCore/SparseMatrixBase.h | rcelebi/android-elfali | 4ea14a58a18356ef9e16aba2e7dae84c02afba12 | [
"Apache-2.0"
] | 680 | 2016-12-03T14:38:28.000Z | 2022-02-16T04:06:45.000Z | jni-build/jni/include/external/eigen_archive/Eigen/src/SparseCore/SparseMatrixBase.h | rcelebi/android-elfali | 4ea14a58a18356ef9e16aba2e7dae84c02afba12 | [
"Apache-2.0"
] | 38 | 2016-11-17T08:43:51.000Z | 2019-11-12T12:27:04.000Z | jni-build/jni/include/external/eigen_archive/Eigen/src/SparseCore/SparseMatrixBase.h | rcelebi/android-elfali | 4ea14a58a18356ef9e16aba2e7dae84c02afba12 | [
"Apache-2.0"
] | 250 | 2016-12-05T10:37:17.000Z | 2022-03-18T21:26:55.000Z | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2014 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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/.
#ifndef EIGEN_SPARSEMATRIXBASE_H
#define EIGEN_SPARSEMATRIXBASE_H
namespace Eigen {
/** \ingroup SparseCore_Module
*
* \class SparseMatrixBase
*
* \brief Base class of any sparse matrices or sparse expressions
*
* \tparam Derived is the derived type, e.g. a sparse matrix type, or an expression, etc.
*
* This class can be extended with the help of the plugin mechanism described on the page
* \ref TopicCustomizingEigen by defining the preprocessor symbol \c EIGEN_SPARSEMATRIXBASE_PLUGIN.
*/
template<typename Derived> class SparseMatrixBase
: public EigenBase<Derived>
{
public:
typedef typename internal::traits<Derived>::Scalar Scalar;
/** The numeric type of the expression' coefficients, e.g. float, double, int or std::complex<float>, etc.
*
* It is an alias for the Scalar type */
typedef Scalar value_type;
typedef typename internal::packet_traits<Scalar>::type PacketScalar;
typedef typename internal::traits<Derived>::StorageKind StorageKind;
typedef typename internal::traits<Derived>::StorageIndex StorageIndex;
typedef typename internal::add_const_on_value_type_if_arithmetic<
typename internal::packet_traits<Scalar>::type
>::type PacketReturnType;
typedef SparseMatrixBase StorageBaseType;
typedef Matrix<StorageIndex,Dynamic,1> IndexVector;
typedef Matrix<Scalar,Dynamic,1> ScalarVector;
template<typename OtherDerived>
Derived& operator=(const EigenBase<OtherDerived> &other);
enum {
RowsAtCompileTime = internal::traits<Derived>::RowsAtCompileTime,
/**< The number of rows at compile-time. This is just a copy of the value provided
* by the \a Derived type. If a value is not known at compile-time,
* it is set to the \a Dynamic constant.
* \sa MatrixBase::rows(), MatrixBase::cols(), ColsAtCompileTime, SizeAtCompileTime */
ColsAtCompileTime = internal::traits<Derived>::ColsAtCompileTime,
/**< The number of columns at compile-time. This is just a copy of the value provided
* by the \a Derived type. If a value is not known at compile-time,
* it is set to the \a Dynamic constant.
* \sa MatrixBase::rows(), MatrixBase::cols(), RowsAtCompileTime, SizeAtCompileTime */
SizeAtCompileTime = (internal::size_at_compile_time<internal::traits<Derived>::RowsAtCompileTime,
internal::traits<Derived>::ColsAtCompileTime>::ret),
/**< This is equal to the number of coefficients, i.e. the number of
* rows times the number of columns, or to \a Dynamic if this is not
* known at compile-time. \sa RowsAtCompileTime, ColsAtCompileTime */
MaxRowsAtCompileTime = RowsAtCompileTime,
MaxColsAtCompileTime = ColsAtCompileTime,
MaxSizeAtCompileTime = (internal::size_at_compile_time<MaxRowsAtCompileTime,
MaxColsAtCompileTime>::ret),
IsVectorAtCompileTime = RowsAtCompileTime == 1 || ColsAtCompileTime == 1,
/**< This is set to true if either the number of rows or the number of
* columns is known at compile-time to be equal to 1. Indeed, in that case,
* we are dealing with a column-vector (if there is only one column) or with
* a row-vector (if there is only one row). */
Flags = internal::traits<Derived>::Flags,
/**< This stores expression \ref flags flags which may or may not be inherited by new expressions
* constructed from this one. See the \ref flags "list of flags".
*/
IsRowMajor = Flags&RowMajorBit ? 1 : 0,
InnerSizeAtCompileTime = int(IsVectorAtCompileTime) ? int(SizeAtCompileTime)
: int(IsRowMajor) ? int(ColsAtCompileTime) : int(RowsAtCompileTime),
#ifndef EIGEN_PARSED_BY_DOXYGEN
_HasDirectAccess = (int(Flags)&DirectAccessBit) ? 1 : 0 // workaround sunCC
#endif
};
/** \internal the return type of MatrixBase::adjoint() */
typedef typename internal::conditional<NumTraits<Scalar>::IsComplex,
CwiseUnaryOp<internal::scalar_conjugate_op<Scalar>, Eigen::Transpose<const Derived> >,
Transpose<const Derived>
>::type AdjointReturnType;
typedef Transpose<Derived> TransposeReturnType;
typedef typename internal::add_const<Transpose<const Derived> >::type ConstTransposeReturnType;
// FIXME storage order do not match evaluator storage order
typedef SparseMatrix<Scalar, Flags&RowMajorBit ? RowMajor : ColMajor, StorageIndex> PlainObject;
#ifndef EIGEN_PARSED_BY_DOXYGEN
/** This is the "real scalar" type; if the \a Scalar type is already real numbers
* (e.g. int, float or double) then \a RealScalar is just the same as \a Scalar. If
* \a Scalar is \a std::complex<T> then RealScalar is \a T.
*
* \sa class NumTraits
*/
typedef typename NumTraits<Scalar>::Real RealScalar;
/** \internal the return type of coeff()
*/
typedef typename internal::conditional<_HasDirectAccess, const Scalar&, Scalar>::type CoeffReturnType;
/** \internal Represents a matrix with all coefficients equal to one another*/
typedef CwiseNullaryOp<internal::scalar_constant_op<Scalar>,Matrix<Scalar,Dynamic,Dynamic> > ConstantReturnType;
/** type of the equivalent dense matrix */
typedef Matrix<Scalar,RowsAtCompileTime,ColsAtCompileTime> DenseMatrixType;
/** type of the equivalent square matrix */
typedef Matrix<Scalar,EIGEN_SIZE_MAX(RowsAtCompileTime,ColsAtCompileTime),
EIGEN_SIZE_MAX(RowsAtCompileTime,ColsAtCompileTime)> SquareMatrixType;
inline const Derived& derived() const { return *static_cast<const Derived*>(this); }
inline Derived& derived() { return *static_cast<Derived*>(this); }
inline Derived& const_cast_derived() const
{ return *static_cast<Derived*>(const_cast<SparseMatrixBase*>(this)); }
typedef EigenBase<Derived> Base;
#endif // not EIGEN_PARSED_BY_DOXYGEN
#define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::SparseMatrixBase
# include "../plugins/CommonCwiseUnaryOps.h"
# include "../plugins/CommonCwiseBinaryOps.h"
# include "../plugins/MatrixCwiseUnaryOps.h"
# include "../plugins/MatrixCwiseBinaryOps.h"
# include "../plugins/BlockMethods.h"
# ifdef EIGEN_SPARSEMATRIXBASE_PLUGIN
# include EIGEN_SPARSEMATRIXBASE_PLUGIN
# endif
# undef EIGEN_CURRENT_STORAGE_BASE_CLASS
#undef EIGEN_CURRENT_STORAGE_BASE_CLASS
/** \returns the number of rows. \sa cols() */
inline Index rows() const { return derived().rows(); }
/** \returns the number of columns. \sa rows() */
inline Index cols() const { return derived().cols(); }
/** \returns the number of coefficients, which is \a rows()*cols().
* \sa rows(), cols(). */
inline Index size() const { return rows() * cols(); }
/** \returns true if either the number of rows or the number of columns is equal to 1.
* In other words, this function returns
* \code rows()==1 || cols()==1 \endcode
* \sa rows(), cols(), IsVectorAtCompileTime. */
inline bool isVector() const { return rows()==1 || cols()==1; }
/** \returns the size of the storage major dimension,
* i.e., the number of columns for a columns major matrix, and the number of rows otherwise */
Index outerSize() const { return (int(Flags)&RowMajorBit) ? this->rows() : this->cols(); }
/** \returns the size of the inner dimension according to the storage order,
* i.e., the number of rows for a columns major matrix, and the number of cols otherwise */
Index innerSize() const { return (int(Flags)&RowMajorBit) ? this->cols() : this->rows(); }
bool isRValue() const { return m_isRValue; }
Derived& markAsRValue() { m_isRValue = true; return derived(); }
SparseMatrixBase() : m_isRValue(false) { /* TODO check flags */ }
template<typename OtherDerived>
Derived& operator=(const ReturnByValue<OtherDerived>& other);
template<typename OtherDerived>
inline Derived& operator=(const SparseMatrixBase<OtherDerived>& other);
inline Derived& operator=(const Derived& other);
protected:
template<typename OtherDerived>
inline Derived& assign(const OtherDerived& other);
template<typename OtherDerived>
inline void assignGeneric(const OtherDerived& other);
public:
friend std::ostream & operator << (std::ostream & s, const SparseMatrixBase& m)
{
typedef typename Derived::Nested Nested;
typedef typename internal::remove_all<Nested>::type NestedCleaned;
if (Flags&RowMajorBit)
{
const Nested nm(m.derived());
for (Index row=0; row<nm.outerSize(); ++row)
{
Index col = 0;
for (typename NestedCleaned::InnerIterator it(nm.derived(), row); it; ++it)
{
for ( ; col<it.index(); ++col)
s << "0 ";
s << it.value() << " ";
++col;
}
for ( ; col<m.cols(); ++col)
s << "0 ";
s << std::endl;
}
}
else
{
const Nested nm(m.derived());
if (m.cols() == 1) {
Index row = 0;
for (typename NestedCleaned::InnerIterator it(nm.derived(), 0); it; ++it)
{
for ( ; row<it.index(); ++row)
s << "0" << std::endl;
s << it.value() << std::endl;
++row;
}
for ( ; row<m.rows(); ++row)
s << "0" << std::endl;
}
else
{
SparseMatrix<Scalar, RowMajorBit, StorageIndex> trans = m;
s << static_cast<const SparseMatrixBase<SparseMatrix<Scalar, RowMajorBit, StorageIndex> >&>(trans);
}
}
return s;
}
template<typename OtherDerived>
Derived& operator+=(const SparseMatrixBase<OtherDerived>& other);
template<typename OtherDerived>
Derived& operator-=(const SparseMatrixBase<OtherDerived>& other);
template<typename OtherDerived>
Derived& operator+=(const DiagonalBase<OtherDerived>& other);
template<typename OtherDerived>
Derived& operator-=(const DiagonalBase<OtherDerived>& other);
Derived& operator*=(const Scalar& other);
Derived& operator/=(const Scalar& other);
template<typename OtherDerived> struct CwiseProductDenseReturnType {
typedef CwiseBinaryOp<internal::scalar_product_op<typename ScalarBinaryOpTraits<
typename internal::traits<Derived>::Scalar,
typename internal::traits<OtherDerived>::Scalar
>::ReturnType>,
const Derived,
const OtherDerived
> Type;
};
template<typename OtherDerived>
EIGEN_STRONG_INLINE const typename CwiseProductDenseReturnType<OtherDerived>::Type
cwiseProduct(const MatrixBase<OtherDerived> &other) const;
// sparse * diagonal
template<typename OtherDerived>
const Product<Derived,OtherDerived>
operator*(const DiagonalBase<OtherDerived> &other) const
{ return Product<Derived,OtherDerived>(derived(), other.derived()); }
// diagonal * sparse
template<typename OtherDerived> friend
const Product<OtherDerived,Derived>
operator*(const DiagonalBase<OtherDerived> &lhs, const SparseMatrixBase& rhs)
{ return Product<OtherDerived,Derived>(lhs.derived(), rhs.derived()); }
// sparse * sparse
template<typename OtherDerived>
const Product<Derived,OtherDerived,AliasFreeProduct>
operator*(const SparseMatrixBase<OtherDerived> &other) const;
// sparse * dense
template<typename OtherDerived>
const Product<Derived,OtherDerived>
operator*(const MatrixBase<OtherDerived> &other) const
{ return Product<Derived,OtherDerived>(derived(), other.derived()); }
// dense * sparse
template<typename OtherDerived> friend
const Product<OtherDerived,Derived>
operator*(const MatrixBase<OtherDerived> &lhs, const SparseMatrixBase& rhs)
{ return Product<OtherDerived,Derived>(lhs.derived(), rhs.derived()); }
/** \returns an expression of P H P^-1 where H is the matrix represented by \c *this */
SparseSymmetricPermutationProduct<Derived,Upper|Lower> twistedBy(const PermutationMatrix<Dynamic,Dynamic,StorageIndex>& perm) const
{
return SparseSymmetricPermutationProduct<Derived,Upper|Lower>(derived(), perm);
}
template<typename OtherDerived>
Derived& operator*=(const SparseMatrixBase<OtherDerived>& other);
template<int Mode>
inline const TriangularView<const Derived, Mode> triangularView() const;
template<unsigned int UpLo> struct SelfAdjointViewReturnType { typedef SparseSelfAdjointView<Derived, UpLo> Type; };
template<unsigned int UpLo> struct ConstSelfAdjointViewReturnType { typedef const SparseSelfAdjointView<const Derived, UpLo> Type; };
template<unsigned int UpLo> inline
typename ConstSelfAdjointViewReturnType<UpLo>::Type selfadjointView() const;
template<unsigned int UpLo> inline
typename SelfAdjointViewReturnType<UpLo>::Type selfadjointView();
template<typename OtherDerived> Scalar dot(const MatrixBase<OtherDerived>& other) const;
template<typename OtherDerived> Scalar dot(const SparseMatrixBase<OtherDerived>& other) const;
RealScalar squaredNorm() const;
RealScalar norm() const;
RealScalar blueNorm() const;
TransposeReturnType transpose() { return TransposeReturnType(derived()); }
const ConstTransposeReturnType transpose() const { return ConstTransposeReturnType(derived()); }
const AdjointReturnType adjoint() const { return AdjointReturnType(transpose()); }
// inner-vector
typedef Block<Derived,IsRowMajor?1:Dynamic,IsRowMajor?Dynamic:1,true> InnerVectorReturnType;
typedef Block<const Derived,IsRowMajor?1:Dynamic,IsRowMajor?Dynamic:1,true> ConstInnerVectorReturnType;
InnerVectorReturnType innerVector(Index outer);
const ConstInnerVectorReturnType innerVector(Index outer) const;
// set of inner-vectors
typedef Block<Derived,Dynamic,Dynamic,true> InnerVectorsReturnType;
typedef Block<const Derived,Dynamic,Dynamic,true> ConstInnerVectorsReturnType;
InnerVectorsReturnType innerVectors(Index outerStart, Index outerSize);
const ConstInnerVectorsReturnType innerVectors(Index outerStart, Index outerSize) const;
DenseMatrixType toDense() const
{
return DenseMatrixType(derived());
}
template<typename OtherDerived>
bool isApprox(const SparseMatrixBase<OtherDerived>& other,
const RealScalar& prec = NumTraits<Scalar>::dummy_precision()) const;
template<typename OtherDerived>
bool isApprox(const MatrixBase<OtherDerived>& other,
const RealScalar& prec = NumTraits<Scalar>::dummy_precision()) const
{ return toDense().isApprox(other,prec); }
/** \returns the matrix or vector obtained by evaluating this expression.
*
* Notice that in the case of a plain matrix or vector (not an expression) this function just returns
* a const reference, in order to avoid a useless copy.
*/
inline const typename internal::eval<Derived>::type eval() const
{ return typename internal::eval<Derived>::type(derived()); }
Scalar sum() const;
inline const SparseView<Derived>
pruned(const Scalar& reference = Scalar(0), const RealScalar& epsilon = NumTraits<Scalar>::dummy_precision()) const;
protected:
bool m_isRValue;
static inline StorageIndex convert_index(const Index idx) {
return internal::convert_index<StorageIndex>(idx);
}
private:
template<typename Dest> void evalTo(Dest &) const;
};
} // end namespace Eigen
#endif // EIGEN_SPARSEMATRIXBASE_H
| 42.84375 | 137 | 0.675845 |
437c09666682824cdd89e9cbee6cb1228e0998c9 | 2,380 | h | C | include/Task/XLinkTask/XLinkProbeDataPointTask.h | AllenKwok/XLinkSDK | e70ee365d0adc561022efb0d1194e2812bf41360 | [
"Apache-2.0"
] | null | null | null | include/Task/XLinkTask/XLinkProbeDataPointTask.h | AllenKwok/XLinkSDK | e70ee365d0adc561022efb0d1194e2812bf41360 | [
"Apache-2.0"
] | 1 | 2019-08-15T04:00:59.000Z | 2019-08-15T04:00:59.000Z | include/Task/XLinkTask/XLinkProbeDataPointTask.h | AllenKwok/XLinkSDK | e70ee365d0adc561022efb0d1194e2812bf41360 | [
"Apache-2.0"
] | null | null | null | //
// XLinkProbeDataPointTask.h
// XLinkSDK
//
// Created by AllenKwok on 2017/12/27.
// Copyright © 2017年 www.xlink.cn. All rights reserved.
//
#import "XLinkSendPolicyTask.h"
#import "XDevice.h"
NS_ASSUME_NONNULL_BEGIN
@class XLinkDataPoint;
@class XLinkGetDataPointTask;
typedef void (^XLinkProbeDataPointTaskCompletionHandler)(NSArray <XLinkDataPoint *> *result, XLinkErrorCode errCode);
@interface XLinkProbeDataPointTask : XLinkSendPolicyTask
///要获取数据端点的设备
@property(strong, nonatomic) XDevice *device;
///要获取数据端点的index列表
@property(copy, nonatomic) NSArray <NSNumber *> *indexArray;
/**
构建获取数据端点的任务
@param device 设备
@param indexArray 要获取的数据端点索引列表,传空的话将不返回数据端点
@param timeout 设置超时时间,单位秒,建议10秒
@param completionHandler 完成后的回调
@return XLinkProbeDataPointTask
*/
+ (instancetype)probeDataPointTaskWithDevice:(XDevice *)device
indexArray:(NSArray <NSNumber *> * _Nullable)indexArray
timeout:(NSUInteger)timeout
completionHandler:(XLinkTaskDidCompletionHandler)completionHandler;
/**
构建获取数据端点的任务 并启动
@param device 设备
@param indexArray 要获取的数据端点索引列表,传空的话将不返回数据端点
@param timeout 设置超时时间,单位秒,建议10秒
@param completionHandler 完成后的回调
@return XLinkProbeDataPointTask
*/
+ (instancetype)scheduledProbeDataPointTaskWithDevice:(XDevice *)device
indexArray:(NSArray <NSNumber *> * _Nullable)indexArray
timeout:(NSUInteger)timeout
completionHandler:(XLinkTaskDidCompletionHandler)completionHandler;
@end
//以下是废弃的方法,不建议使用,不久的将来会删除
@interface XLinkProbeDataPointTask (XLinkDeprecated)
/**
构建获取数据端点的任务
@param device 设备
@param indexArray 要获取的数据端点索引列表,传空的话将不返回数据端点
@param timeout 设置超时时间,单位秒,建议10秒
@param completeBlock 完成后的回调
@return XLinkProbeDataPointTask
*/
+ (instancetype)probeDataPointTaskWithDevice:(XDevice *)device
indexArray:(NSArray <NSNumber *> *_Nullable)indexArray
timeOut:(NSUInteger)timeout
probeDataPointCompleteBlock:(XLinkProbeDataPointTaskCompletionHandler)completeBlock NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, "已废弃方法,请使用+probeDataPointTaskWithDevice:indexArray:timeout:completeBlock:替换,以后的版本将可能会删除此方法");
@end
NS_ASSUME_NONNULL_END
| 31.315789 | 228 | 0.707143 |
b76f85a9495ef185d0e0d163c08f905409e9b713 | 1,496 | h | C | src/resolver.h | neeilan/neeilang | 1c7776bfd7d895f3f203adde5c2606096f12cc46 | [
"MIT"
] | 50 | 2019-10-15T23:14:06.000Z | 2022-02-03T20:59:50.000Z | src/resolver.h | neeilan/neeilang | 1c7776bfd7d895f3f203adde5c2606096f12cc46 | [
"MIT"
] | null | null | null | src/resolver.h | neeilan/neeilang | 1c7776bfd7d895f3f203adde5c2606096f12cc46 | [
"MIT"
] | 4 | 2020-01-22T20:14:00.000Z | 2020-03-25T08:36:14.000Z | #ifndef _NL_RESOLVER_H_
#define _NL_RESOLVER_H_
#include <map>
#include <string>
#include <vector>
#include "scope-manager.h"
#include "token.h"
#include "visitable.h"
#include "visitor.h"
// Describes what kind of function (if any) we're resolving
// names in.
enum FunctionType {
NOT_IN_FN,
METHOD,
FUNCTION,
INITIALIZER,
};
// Describes whether we're currently resolving names
// within in a class. Keywords like 'this' only make
// sense within a class.
enum ClassType { NOT_IN_CLASS, IN_CLASS };
// true in map == 'is finished being initialized in this scope'
struct ScopeMap {
std::map<std::string, bool> map;
size_t id = 0;
};
class Resolver : public ExprVisitor<void>, public StmtVisitor<void> {
public:
Resolver() { scopes.push_back(&globals); }
void resolve_program(const std::vector<Stmt *> program);
// private:
ScopeMap globals;
std::vector<ScopeMap *> scopes;
std::map<const Expr *, size_t> scope_mappings;
ClassType current_class = NOT_IN_CLASS;
FunctionType current_function = NOT_IN_FN;
bool decl_only_pass = true;
EXPR_VISITOR_METHODS(void)
STMT_VISITOR_METHODS(void)
void begin_scope();
void end_scope();
void resolve(const Stmt *);
void resolve(const Expr *);
void resolve_local(const Expr *expr, const Token name);
void resolve(const std::vector<Stmt *> statements);
void resolve_fn(FunctionType declaration, const FuncStmt *fn);
void declare(const Token);
void define(const Token);
};
#endif //_NL_RESOLVER_H_
| 24.129032 | 69 | 0.726604 |
2c55b0a31b19c49f2dc22317c5da375ef9c548aa | 1,196 | h | C | porting/liteos_a/kernel/include/bits/stat.h | openharmony-gitee-mirror/third_party_musl | 8cb5b45210bfb0f583bcf8b50de8299843b5e075 | [
"MIT"
] | null | null | null | porting/liteos_a/kernel/include/bits/stat.h | openharmony-gitee-mirror/third_party_musl | 8cb5b45210bfb0f583bcf8b50de8299843b5e075 | [
"MIT"
] | null | null | null | porting/liteos_a/kernel/include/bits/stat.h | openharmony-gitee-mirror/third_party_musl | 8cb5b45210bfb0f583bcf8b50de8299843b5e075 | [
"MIT"
] | 1 | 2021-09-13T11:14:33.000Z | 2021-09-13T11:14:33.000Z | /* copied from kernel definition, but with padding replaced
* by the corresponding correctly-sized userspace types. */
struct stat {
dev_t st_dev;
int __st_dev_padding;
long __st_ino_truncated;
mode_t st_mode;
nlink_t st_nlink;
uid_t st_uid;
gid_t st_gid;
dev_t st_rdev;
int __st_rdev_padding;
off_t st_size;
blksize_t st_blksize;
blkcnt_t st_blocks;
struct {
long tv_sec;
long tv_nsec;
} __st_atim32, __st_mtim32, __st_ctim32;
ino_t st_ino;
struct timespec st_atim;
struct timespec st_mtim;
struct timespec st_ctim;
};
#define __NEED_uint16_t
#define __NEED_uint32_t
#define __NEED_uint64_t
#define __NEED_int32_t
#define __NEED_int64_t
#include <bits/alltypes.h>
struct statx {
uint32_t stx_mask;
uint32_t stx_blksize;
uint64_t stx_attributes;
uint32_t stx_nlink;
uint32_t stx_uid;
uint32_t stx_gid;
uint16_t stx_mode;
uint16_t pad1;
uint64_t stx_ino;
uint64_t stx_size;
uint64_t stx_blocks;
uint64_t stx_attributes_mask;
struct {
int64_t tv_sec;
uint32_t tv_nsec;
int32_t pad;
} stx_atime, stx_btime, stx_ctime, stx_mtime;
uint32_t stx_rdev_major;
uint32_t stx_rdev_minor;
uint32_t stx_dev_major;
uint32_t stx_dev_minor;
uint64_t spare[14];
}; | 21.357143 | 59 | 0.788462 |
4e02e73f0db7090891d408abc63676b276aec50c | 8,997 | h | C | waterbox/ares64/ares/ares/n64/vulkan/parallel-rdp/parallel-rdp/shaders/interpolation.h | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 335 | 2021-10-16T14:56:14.000Z | 2022-03-31T15:50:11.000Z | waterbox/ares64/ares/ares/n64/vulkan/parallel-rdp/parallel-rdp/shaders/interpolation.h | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | waterbox/ares64/ares/ares/n64/vulkan/parallel-rdp/parallel-rdp/shaders/interpolation.h | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | /* Copyright (c) 2020 Themaister
*
* 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.
*/
#ifndef INTERPOLATION_H_
#define INTERPOLATION_H_
#include "data_structures.h"
#include "clamping.h"
#include "perspective.h"
u8x4 interpolate_rgba(ivec4 rgba, ivec4 drgba_dx, ivec4 drgba_dy, int dx, int coverage)
{
rgba += ((drgba_dx & ~0x1f) >> SCALING_LOG2) * dx;
// RGBA is interpolated to 9-bit. The last bit is used to deal with clamping.
// Slight underflow below 0 is clamped to 0 and slight overflow above 0xff is clamped to 0xff.
// Keep 2 sign bits of precision before we complete the centroid interpolation.
i16x4 snapped_rgba = i16x4(rgba >> 14);
// Centroid clipping is based on the first coverage bit, and we interpolate at the first subpixel in scanline order.
// With this layout we can just use findLSB to get correct result.
// 0x01 0x02
// 0x04 0x08
// 0x10 0x20
// 0x40 0x80
int first_coverage = findLSB(coverage);
i16 yoff = i16(first_coverage >> 1);
i16 xoff = i16((first_coverage & 1) << 1) + (yoff & I16_C(1));
snapped_rgba <<= I16_C(2 + SCALING_LOG2);
snapped_rgba += xoff * i16x4(drgba_dx >> 14) + yoff * i16x4(drgba_dy >> 14);
snapped_rgba >>= I16_C(4 + SCALING_LOG2);
return clamp_9bit(snapped_rgba);
}
void interpolate_st_copy(SpanSetup span, ivec4 dstzw_dx, int x, bool perspective, bool flip,
out ivec2 st, out int s_offset)
{
int dx = flip ? (x - span.start_x) : (span.end_x - x);
// For copy pipe, we should duplicate pixels when scaling, there is no filtering we can (or should!) do.
dx >>= SCALING_LOG2;
// Snap DX to where we perform interpolation (once per N output pixels).
int snapped_dx = dx & global_constants.fb_info.dx_mask;
s_offset = dx - snapped_dx;
int lerp_dx = (dx >> global_constants.fb_info.dx_shift) * (flip ? 1 : -1);
ivec3 stw = span.stzw.xyw + (dstzw_dx.xyw & ~0x1f) * lerp_dx;
if (perspective)
{
bool st_overflow;
st = perspective_divide(stw >> 16, st_overflow);
}
else
st = no_perspective_divide(stw >> 16);
}
ivec2 interpolate_st_single(ivec4 stzw, ivec4 dstzw_dx, int dx, bool perspective)
{
ivec3 stw = stzw.xyw + ((dstzw_dx.xyw & ~0x1f) >> SCALING_LOG2) * dx;
stw >>= 16;
ivec2 st;
if (perspective)
{
bool st_overflow;
st = perspective_divide(stw, st_overflow);
}
else
st = no_perspective_divide(stw);
return st;
}
void interpolate_stz(ivec4 stzw, ivec4 dstzw_dx, ivec4 dstzw_dy, int dx, int coverage, bool perspective, bool uses_lod,
int flip_direction, out ivec2 st, out ivec2 st_dx, out ivec2 st_dy, out int z, inout bool st_overflow)
{
ivec3 stw = stzw.xyw + ((dstzw_dx.xyw & ~0x1f) >> SCALING_LOG2) * dx;
ivec3 stw_dx, stw_dy;
if (uses_lod)
{
stw_dx = stw + flip_direction * ((dstzw_dx.xyw & ~0x1f) >> SCALING_LOG2);
if (SCALING_FACTOR > 1)
stw_dy = stw + abs(flip_direction) * ((dstzw_dy.xyw & ~0x7fff) >> SCALING_LOG2);
else
stw_dy = stw + ((dstzw_dy.xyw & ~0x7fff) >> SCALING_LOG2);
}
if (perspective)
{
st = perspective_divide(stw >> 16, st_overflow);
if (uses_lod)
{
st_dx = perspective_divide(stw_dx >> 16, st_overflow);
st_dy = perspective_divide(stw_dy >> 16, st_overflow);
}
}
else
{
st = no_perspective_divide(stw >> 16);
if (uses_lod)
{
st_dx = no_perspective_divide(stw_dx >> 16);
st_dy = no_perspective_divide(stw_dy >> 16);
}
}
// Ensure that interpolation snaps as we expect on every "main" pixel,
// for subpixels, interpolate with quantized step factor.
z = stzw.z + dstzw_dx.z * (dx >> SCALING_LOG2) + (dstzw_dx.z >> SCALING_LOG2) * (dx & (SCALING_FACTOR - 1));
int snapped_z = z >> 10;
int first_coverage = findLSB(coverage);
int yoff = first_coverage >> 1;
int xoff = ((first_coverage & 1) << 1) + (yoff & I16_C(1));
snapped_z <<= 2 + SCALING_LOG2;
snapped_z += xoff * (dstzw_dx.z >> 10) + yoff * (dstzw_dy.z >> 10);
snapped_z >>= 5 + SCALING_LOG2;
z = clamp_z(snapped_z);
}
#if 0
u8x4 interpolate_rgba(TriangleSetup setup, AttributeSetup attr, int x, int y, int coverage)
{
bool do_offset = (setup.flags & TRIANGLE_SETUP_DO_OFFSET_BIT) != 0;
int y_interpolation_base = int(setup.yh) >> 2;
int xh = setup.xh + (y - y_interpolation_base) * (setup.dxhdy << 2);
ivec4 drgba_diff = ivec4(0);
// In do_offset mode, varyings are latched at last subpixel line instead of first (for some reason).
if (do_offset)
{
xh += 3 * setup.dxhdy;
ivec4 drgba_deh = attr.drgba_de & ~0x1ff;
ivec4 drgba_dyh = attr.drgba_dy & ~0x1ff;
drgba_diff = drgba_deh - (drgba_deh >> 2) - drgba_dyh + (drgba_dyh >> 2);
}
int base_x = xh >> 16;
int xfrac = (xh >> 8) & 0xff;
ivec4 rgba = attr.rgba;
rgba += attr.drgba_de * (y - y_interpolation_base);
rgba = ((rgba & ~0x1ff) + drgba_diff - xfrac * ((attr.drgba_dx >> 8) & ~1)) & ~0x3ff;
rgba += (attr.drgba_dx & ~0x1f) * (x - base_x);
// RGBA is interpolated to 9-bit. The last bit is used to deal with clamping.
// Slight underflow below 0 is clamped to 0 and slight overflow above 0xff is clamped to 0xff.
// Keep 2 sign bits of precision before we complete the centroid interpolation.
i16x4 snapped_rgba = i16x4(rgba >> 14);
// Centroid clipping is based on the first coverage bit, and we interpolate at the first subpixel in scanline order.
// FWIW, Angrylion has a very different coverage bit assignment, but we need this layout to avoid an awkward LUT.
// With this layout we can just use findLSB instead.
// 0x01 0x02
// 0x04 0x08
// 0x10 0x20
// 0x40 0x80
int first_coverage = findLSB(coverage);
i16 yoff = i16(first_coverage >> 1);
i16 xoff = i16((first_coverage & 1) << 1) + (yoff & I16_C(1));
snapped_rgba <<= I16_C(2);
snapped_rgba += xoff * i16x4(attr.drgba_dx >> 14) + yoff * i16x4(attr.drgba_dy >> 14);
snapped_rgba >>= I16_C(4);
return clamp_9bit(snapped_rgba);
}
ivec3 interpolate_stw(TriangleSetup setup, AttributeSetup attr, int x, int y)
{
bool do_offset = (setup.flags & TRIANGLE_SETUP_DO_OFFSET_BIT) != 0;
int y_interpolation_base = int(setup.yh) >> 2;
int xh = setup.xh + (y - y_interpolation_base) * (setup.dxhdy << 2);
ivec3 dstw_diff = ivec3(0);
// In do_offset mode, varyings are latched at last subpixel line instead of first (for some reason).
if (do_offset)
{
xh += 3 * setup.dxhdy;
ivec3 dstw_deh = attr.dstzw_de.xyw & ~0x1ff;
ivec3 dstw_dyh = attr.dstzw_dy.xyw & ~0x1ff;
dstw_diff = dstw_deh - (dstw_deh >> 2) - dstw_dyh + (dstw_dyh >> 2);
}
int base_x = xh >> 16;
int xfrac = (xh >> 8) & 0xff;
ivec3 stw = attr.stzw.xyw;
stw += attr.dstzw_de.xyw * (y - y_interpolation_base);
stw = ((stw & ~0x1ff) + dstw_diff - xfrac * ((attr.dstzw_dx.xyw >> 8) & ~1)) & ~0x3ff;
stw += (attr.dstzw_dx.xyw & ~0x1f) * (x - base_x);
ivec3 snapped_stw = stw >> 16;
return snapped_stw;
}
int interpolate_z(TriangleSetup setup, AttributeSetup attr, int x, int y, int coverage)
{
bool do_offset = (setup.flags & TRIANGLE_SETUP_DO_OFFSET_BIT) != 0;
int y_interpolation_base = int(setup.yh) >> 2;
int xh = setup.xh + (y - y_interpolation_base) * (setup.dxhdy << 2);
int dzdiff = 0;
// In do_offset mode, varyings are latched at last subpixel line instead of first (for some reason).
if (do_offset)
{
xh += 3 * setup.dxhdy;
int dzdeh = attr.dstzw_de.z & ~0x1ff;
int dzdyh = attr.dstzw_dy.z & ~0x1ff;
dzdiff = dzdeh - (dzdeh >> 2) - dzdyh + (dzdyh >> 2);
}
int base_x = xh >> 16;
int xfrac = (xh >> 8) & 0xff;
int z = attr.stzw.z;
z += attr.dstzw_de.z * (y - y_interpolation_base);
z = ((z & ~0x1ff) + dzdiff - xfrac * ((attr.dstzw_dx.z >> 8) & ~1)) & ~0x3ff;
z += attr.dstzw_dx.z * (x - base_x);
int snapped_z = z >> 10;
int first_coverage = findLSB(coverage);
int yoff = first_coverage >> 1;
int xoff = ((first_coverage & 1) << 1) + (yoff & 1s);
snapped_z <<= 2;
snapped_z += xoff * (attr.dstzw_dx.z >> 10) + yoff * (attr.dstzw_dy.z >> 10);
snapped_z >>= 5;
return clamp_z(snapped_z);
}
#endif
#endif | 35.282353 | 123 | 0.679226 |
ec8bd7e7c9d242d38cfd3c0b968a82248c1983cd | 1,457 | h | C | pfl/utils/lnrtd/lnrtd.h | zhihui-slash2/slash2-next | d174a735f9860d2d9e31c47548bda67257400804 | [
"0BSD"
] | null | null | null | pfl/utils/lnrtd/lnrtd.h | zhihui-slash2/slash2-next | d174a735f9860d2d9e31c47548bda67257400804 | [
"0BSD"
] | null | null | null | pfl/utils/lnrtd/lnrtd.h | zhihui-slash2/slash2-next | d174a735f9860d2d9e31c47548bda67257400804 | [
"0BSD"
] | null | null | null | /* $Id$ */
/*
* %ISC_START_LICENSE%
* ---------------------------------------------------------------------
* Copyright 2015, Google, Inc.
* Copyright (c) 2011-2015, Pittsburgh Supercomputing Center (PSC).
* All rights reserved.
*
* 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.
* --------------------------------------------------------------------
* %END_LICENSE%
*/
#ifndef _LNRTD_H_
#define _LNRTD_H_
#include "pfl/cdefs.h"
enum {
LRTHRT_CTL,
LRTHRT_CTLAC,
LRTHRT_EQPOLL,
LRTHRT_LNETAC,
LRTHRT_OPSTIMER,
LRTHRT_USKLNDPL
};
#if DEVELPATHS
# define PATH_RUNTIME_DIR ".."
#else
# define PATH_RUNTIME_DIR "/var/run"
#endif
#define PATH_CTLSOCK PATH_RUNTIME_DIR"/lnrtd.%h.sock"
void lrctlthr_main(void);
const char *ctlsockfn;
#endif /* _LNRTD_H_ */
| 27.490566 | 72 | 0.673988 |
0c0f8ec950410460fbb34739474bf054d50dbfba | 968 | h | C | HackCPU/opcodes.h | Doridian/HackCPU | 026c599f3a99c6f9ee0596b798d6c17f34d71894 | [
"BSD-3-Clause"
] | 2 | 2018-09-20T10:09:43.000Z | 2018-09-20T10:54:26.000Z | HackCPU/opcodes.h | Doridian/HackCPU | 026c599f3a99c6f9ee0596b798d6c17f34d71894 | [
"BSD-3-Clause"
] | null | null | null | HackCPU/opcodes.h | Doridian/HackCPU | 026c599f3a99c6f9ee0596b798d6c17f34d71894 | [
"BSD-3-Clause"
] | null | null | null |
#ifndef OPCODES_H_INCLUDED
#define OPCODES_H_INCLUDED
enum INSTRUCTION {
I_MOV = 0,
I_MOV8,
I_MOV16,
I_PUSH,
I_POP,
I_ADD,
I_SUB,
I_MUL,
I_DIV,
I_MOD,
I_SHL,
I_LSHR,
I_ASHR,
I_MULU,
I_DIVU,
I_XOR,
I_OR,
I_AND,
I_NOT,
I_NOR,
I_NAND,
I_CMP,
I_CMPS,
I_CMPF,
I_JMP,
I_JGE,
I_JLE,
I_JE,
I_JNE,
I_JG,
I_JL,
I_JZ,
I_JNZ,
I_CALL,
I_CGE,
I_CLE,
I_CE,
I_CNE,
I_CG,
I_CL,
I_CZ,
I_CNZ,
I_RETNA,
I_INT,
I_SETIH,
I_ADDF,
I_SUBF,
I_MULF,
I_DIVF,
I_ADD64F,
I_SUB64F,
I_MUL64F,
I_DIV64F,
I_MOV64 = 128,
I_PUSH64,
I_POP64,
I_CMP64,
I_CMP64S,
I_CMP64F,
I_ADD64,
I_SUB64,
I_MUL64,
I_DIV64,
I_MOD64,
I_SHL64,
I_LSHR64,
I_ASHR64,
I_MULU64,
I_DIVU64,
I_POPNIL = 192,
I_POPNIL64,
I_NOP,
I_RETN,
I_HALT,
I_RESET,
I_TRAP,
I_ENCOFF,
I_ENCON,
I_PUSHREG,
I_POPREG,
I_DEBUG,
I_FIRST_INVALID
};
#endif // OPCODES_H_INCLUDED
| 10.637363 | 29 | 0.621901 |
bd5435a9e5aa95aae4cee906cd94d4b7eac1d5ee | 1,237 | c | C | modules/charge_only_mode/venus2_assets/bin2c.c | namagi/android_device_motorola_qcom-common | 2114ad2edd693c4873e8a2897ea84864395a4c43 | [
"FTL"
] | 2 | 2015-02-16T19:40:17.000Z | 2015-02-17T15:42:35.000Z | modules/charge_only_mode/venus2_assets/bin2c.c | namagi/android_device_motorola_qcom-common | 2114ad2edd693c4873e8a2897ea84864395a4c43 | [
"FTL"
] | null | null | null | modules/charge_only_mode/venus2_assets/bin2c.c | namagi/android_device_motorola_qcom-common | 2114ad2edd693c4873e8a2897ea84864395a4c43 | [
"FTL"
] | 11 | 2017-01-14T22:29:16.000Z | 2019-02-12T22:17:20.000Z | /*
* Unloved program to convert a binary on stdin to a C include on stdout
*
* Jan 1999 Matt Mackall <mpm@selenic.com>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*/
#include <stdio.h>
int main(int argc, char *argv[])
{
int ch, total=0;
int convert = 0;
if ((argc > 1) && !strcmp(argv[1], "rgb24to16")) {
convert = 1;
argc--;
argv++;
}
if (argc == 4)
printf("static const unsigned char %s_bits[] = {\n", argv[1]);
do {
while ((ch = getchar()) != EOF)
{
if (convert) {
static int r, g, b, counter;
switch (counter++ % 3) {
case 0: r = ch; break;
case 1: g = ch; break;
case 2: b = ch;
printf("0x%04x, ", ((r >> 3) << 11) |
((g >> 2) << 5) |
(b >> 3));
total += 2;
break;
}
} else {
printf("0x%02x,", ch);
total++;
}
if (total % 16 == 0)
break;
}
printf("\n");
} while (ch != EOF);
if (argc == 4)
printf("};\n\nstruct asset %s = {\n\t%s, %s, %s_bits, sizeof(%s_bits) - 1, NULL };\n",
argv[1], argv[2], argv[3], argv[1], argv[1]);
return 0;
}
| 21.327586 | 89 | 0.495554 |
2600b5fb89baa9e8a52f03dc28a0aa618dd115c5 | 29,268 | c | C | rook0.c | rooklang/rook | 87cb6448980c8925328bf777ade828cb709601d7 | [
"MIT"
] | 2 | 2019-08-02T01:04:53.000Z | 2019-08-02T18:07:43.000Z | rook0.c | rooklang/rook | 87cb6448980c8925328bf777ade828cb709601d7 | [
"MIT"
] | null | null | null | rook0.c | rooklang/rook | 87cb6448980c8925328bf777ade828cb709601d7 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <ctype.h>
#include <getopt.h>
static int QUIET = 0;
static int DEBUG = 0;
static int ARGC = 0;
static char **ARGV = NULL;
struct value;
static struct value *ROOK_TRUE;
static struct value *ROOK_FALSE;
static void
fprintv(FILE *io, int in, struct value *v);
struct cons {
struct value *car;
struct value *cdr;
};
struct string {
size_t len;
char *data;
};
struct symbol {
char *name;
};
typedef struct value * (*primop)(struct value *);
struct value {
enum {
CONS,
STRING,
NUMBER,
SYMBOL,
BOOLEAN,
PRIMOP,
} type;
union {
struct cons cons;
struct string string;
int number;
struct symbol *symbol;
char boolean;
primop primop;
};
};
/* FIXME: this is woefully inefficient */
struct symtab_ent {
struct symbol *symbol;
struct symtab_ent *next;
};
struct symtab {
struct symtab_ent *head;
};
void *
mem(size_t n)
{
void *x = calloc(n, sizeof(char));
if (!x) {
fprintf(stderr, "*** malloc failed.\n");
exit(2);
}
return x;
}
void *
remem(void *x, size_t n)
{
x = realloc(x, n);
if (!x) {
fprintf(stderr, "*** realloc failed.\n");
exit(2);
}
return x;
}
#define make(obj) (mem(sizeof(obj)))
#define mems(n,t) (mem((n)*sizeof(t)))
#define extend(x,n,t) (remem((x),(n)*sizeof(t)))
static struct symtab SYMBOLS = {0};
static struct symbol *
intern(const char *name)
{
struct symtab_ent *e;
for (e = SYMBOLS.head; e; e = e->next) {
if (strcmp(e->symbol->name, name) == 0) {
return e->symbol;
}
}
e = make(struct symtab_ent);
e->next = SYMBOLS.head;
e->symbol = make(struct symbol);
e->symbol->name = strdup(name);
SYMBOLS.head = e;
return e->symbol;
}
struct binding {
struct symbol *symbol;
struct value *value;
struct binding *next;
};
static struct value *
new_cons(struct value *car, struct value *cdr)
{
struct value *v;
v = make(struct value);
v->type = CONS;
v->cons.car = car;
v->cons.cdr = cdr;
return v;
}
#define list2(a,b) (new_cons((a), new_cons((b), NULL)))
static struct value *
new_primop(primop op)
{
struct value *v;
v = make(struct value);
v->type = PRIMOP;
v->primop = op;
return v;
}
static struct value *
new_string(const char *src)
{
struct value *v;
char *ins, *head, *end;
size_t n;
n = strlen(src);
v = make(struct value);
v->type = STRING;
v->string.data = mems(n+1, char);
v->string.len = n;
memcpy(v->string.data, src, n);
/* unescape */
ins = head = v->string.data;
end = head + v->string.len;
while (head != end) {
if (*head == '\\') {
v->string.len--;
head++;
if (head == end) {
fprintf(stderr, "dangling escape character!\n");
exit(1);
}
switch (*head) {
case 't' : *ins++ = '\t'; break;
case 'r' : *ins++ = '\r'; break;
case 'n' : *ins++ = '\n'; break;
case '\\': *ins++ = '\\'; break;
case '0' : *ins++ = '\0'; break;
default: *ins++ = *head;
}
head++;
} else {
*ins++ = *head++;
}
}
*ins = '\0';
return v;
}
static struct value *
new_number(const char *src)
{
struct value *v;
v = make(struct value);
v->type = NUMBER;
v->number = 0;
while (src && *src)
v->number = v->number * 10 + (*src++ - '0');
return v;
}
static struct value *
new_symbol(const char *name)
{
struct value *v;
v = make(struct value);
v->type = SYMBOL;
v->symbol = intern(name);
return v;
}
static void
free_value(struct value *v)
{
if (!v) return;
switch (v->type) {
case CONS:
free_value(v->cons.car);
free_value(v->cons.cdr);
break;
case STRING:
free(v->string.data);
break;
default: /* noop */
break;
}
free(v);
}
static void
fprintv(FILE *io, int in, struct value *v)
{
char *pre;
pre = mems(in + 1, char);
memset(pre, ' ', in);
if (!v) {
fprintf(io, "%snil", pre);
return;
}
switch (v->type) {
default:
fprintf(io, "%s<unknown @%p t:%02x>", pre, (void *)v, v->type);
break;
case CONS:
fprintf(io, "%s(", pre);
if (DEBUG) fprintf(io, "[%p] ", (void *)v);
again:
fprintv(io, 0, v->cons.car);
if (v->cons.cdr) {
if (v->cons.cdr->type == CONS) {
fprintf(io, " ");
v = v->cons.cdr;
goto again;
} else {
fprintf(io, " . ");
fprintv(io, 0, v->cons.cdr);
}
}
fprintf(io, ")");
break;
case PRIMOP:
fprintf(io, "%s<op:%p>", pre, (void *)&(v->primop));
if (DEBUG) fprintf(io, "@%p", (void *)v);
break;
case STRING:
fprintf(io, "%s\"%s\"", pre, v->string.data);
if (DEBUG) fprintf(io, "@%p", (void *)v);
break;
case NUMBER:
fprintf(io, "%s%d", pre, v->number);
if (DEBUG) fprintf(io, "@%p", (void *)v);
break;
case BOOLEAN:
fprintf(io, "%s#%c", pre, v->boolean ? 't' : 'f');
if (DEBUG) fprintf(io, "@%p", (void *)v);
break;
case SYMBOL:
fprintf(io, "%s%s", pre, v->symbol->name);
if (DEBUG) fprintf(io, "@%p", (void *)v->symbol);
break;
}
}
enum ttype {
T_OPENP,
T_CLOSEP,
T_QUOTE,
T_IDENT,
T_STRING,
T_NUMBER,
T_TRUE,
T_FALSE,
T_OOPS,
};
struct pos {
const char *src;
int offset;
int line;
int column;
};
/* copy_pos(&dst, &src)
set all members of the dst pos structure
to the values of corresponding members of
the src pos structure.
*/
#define copy_pos(dst,src) memcpy((dst), (src), sizeof(struct pos))
/* init_pos(&pos, "src")
initialize a pos struct to point to the
beginning of the raw source code string
given as the second argument.
*/
static inline void
init_pos(struct pos *pos, const char *src)
{
pos->offset = 0;
pos->line = pos->column = 1;
pos->src = src;
}
struct token {
enum ttype type;
struct pos pos;
int len;
char *data;
};
struct reader {
int fd;
const char *file;
char *src;
size_t used;
size_t cap;
struct pos prev;
struct pos head;
};
static struct token *
new_token(struct reader *r, enum ttype type, char *data)
{
struct token *token;
token = make(struct token);
token->type = type;
copy_pos(&token->pos, &r->prev);
token->len = r->head.offset - r->prev.offset;
token->data = data;
return token;
}
static void
free_token(struct token *token)
{
free(token->data);
free(token);
}
#define READER_BLOCK_SIZE 16384;
static void
read_more(struct reader *r)
{
size_t n;
if (r->fd < 0)
return;
if (r->used == r->cap) {
r->cap += READER_BLOCK_SIZE;
r->src = extend(r->src, r->cap, char);
}
n = read(r->fd, r->src + r->used, r->cap - r->used);
if (n < 0) {
fprintf(stderr, "error reading from %s: %s (error %d)\n",
r->file, strerror(errno), errno);
exit(1);
} else if (n == 0) {
close(r->fd);
r->fd = -1;
} else {
r->used += n;
r->src[r->used] = '\0';
}
}
static char *
lexeme(struct reader *r)
{
char *s;
size_t len;
len = r->head.offset - r->prev.offset;
s = mem(len + 1);
memcpy(s, r->src + r->prev.offset, len);
return s;
}
/* peek(&reader) -> c
return the character under the cursor,
without changing the position.
*/
static inline char
peek(struct reader *r)
{
if (r->head.offset == r->used)
read_more(r);
return r->src[r->head.offset];
}
/* next(&reader)
advance the cursor one position, updating
line / column markers as necessary.
returns the character that was at offset,
before any adjustments took place.
*/
static inline char
next(struct reader *r)
{
if (r->head.offset == r->used)
read_more(r);
r->head.offset++;
r->head.column++;
if (r->src[r->head.offset] == '\n') {
r->head.column = 1;
r->head.line++;
}
return peek(r);
}
/* resync(&reader)
put the head cursor into the prev cursor,
overwriting what was there previously.
*/
static inline void
resync(struct reader *r)
{
copy_pos(&r->prev, &r->head);
}
static struct token *
lex(struct reader *r)
{
char c, q, esc;
struct token *tok;
/* eat whitespace */
again:
for (c = peek(r); c && isspace(c); next(r), c = peek(r));
resync(r);
switch (c) {
case '\0': return NULL;
case ';':
for (; c != '\n'; next(r), c = peek(r));
goto again;
case '\'': next(r); return new_token(r, T_QUOTE, NULL);
case '#':
next(r);
switch (peek(r)) {
case 't': next(r); return new_token(r, T_TRUE, NULL);
case 'f': next(r); return new_token(r, T_FALSE, NULL);
default:
return new_token(r, T_OOPS, "invalid '#' macro");
}
case '(': next(r); return new_token(r, T_OPENP, NULL);
case ')': next(r); return new_token(r, T_CLOSEP, NULL);
case '"':
esc = 0; q = c; next(r); resync(r);
for (c = peek(r); c && (esc || c != q); next(r), c = peek(r));
tok = new_token(r, T_STRING, lexeme(r));
next(r); return tok;
}
if (c && isdigit(c)) {
for (c = peek(r); c && isdigit(c); next(r), c = peek(r));
return new_token(r, T_NUMBER, lexeme(r));
}
if (c) {
for (c = peek(r); c && !isspace(c) && c != ')'; next(r), c = peek(r));
return new_token(r, T_IDENT, lexeme(r));
}
return new_token(r, T_OOPS, "syntax error");
}
#define truish(ok) ((ok) ? ROOK_TRUE : ROOK_FALSE)
#define CAR(l) ((l)->cons.car)
#define CDR(l) ((l)->cons.cdr)
#define CAAR(l) (CAR(CAR(l)))
#define CADR(l) (CAR(CDR(l)))
#define CDAR(l) (CDR(CAR(l)))
#define CDDR(l) (CDR(CDR(l)))
#define CADAR(l) (CAR(CDR(CAR(l))))
#define CADDR(l) (CAR(CDR(CDR(l))))
#define CDDAR(l) (CDR(CDR(CAR(l))))
#define CADDAR(l) (CAR(CDR(CDR(CAR(l)))))
static struct value *
read1(struct reader *r);
#define readq(r) (new_cons(new_symbol("quote"), new_cons(read1(r), NULL)))
static struct value *
readl(struct reader *r)
{
struct token *token;
struct value *lst, *head, *tmp;
tmp = head = lst = NULL;
while ((token = lex(r)) != NULL) {
switch (token->type) {
case T_IDENT: lst = new_cons(new_symbol(token->data), lst); break;
case T_STRING: lst = new_cons(new_string(token->data), lst); break;
case T_NUMBER: lst = new_cons(new_number(token->data), lst); break;
case T_TRUE: lst = new_cons(ROOK_TRUE, lst); break;
case T_FALSE: lst = new_cons(ROOK_FALSE, lst); break;
case T_OPENP: lst = new_cons(readl(r), lst); break;
case T_QUOTE: lst = new_cons(readq(r), lst); break;
case T_OOPS:
fprintf(stderr, "oops: %s\n", token->data);
exit(1);
case T_CLOSEP:
while (lst) {
tmp = lst; lst = CDR(lst);
CDR(tmp) = head; head = tmp;
}
return tmp;
break;
}
}
fprintf(stderr, "unterminated list form!\n");
exit(1);
}
static struct value *
read1(struct reader *r)
{
struct token *token;
struct value *v;
token = lex(r);
if (token == NULL)
return NULL;
switch (token->type) {
case T_IDENT: v = new_symbol(token->data); break;
case T_STRING: v = new_string(token->data); break;
case T_NUMBER: v = new_number(token->data); break;
case T_TRUE: v = ROOK_TRUE; break;
case T_FALSE: v = ROOK_FALSE; break;
case T_OPENP: v = readl(r); break;
case T_QUOTE: v = readq(r); break;
case T_OOPS:
fprintf(stderr, "oops: %s\n", token->data);
exit(1);
case T_CLOSEP:
fprintf(stderr, "too many closing ')' found!\n");
exit(1);
default:
fprintf(stderr, "unrecognized token type %02x\n", token->type);
exit(1);
}
free_token(token);
return v;
}
static struct reader *
file_reader(const char *file)
{
int fd;
struct reader *r;
fd = open(file, O_RDONLY);
if (fd < 0) return NULL;
r = make(struct reader);
r->fd = fd;
r->file = file;
return r;
}
static struct reader *
fd_reader(const char *name, int fd)
{
struct reader *r;
r = make(struct reader);
r->fd = fd;
r->file = name;
return r;
}
static void
free_reader(struct reader *r)
{
free(r->src);
free(r);
}
static char
truthy(struct value *cond)
{
switch (cond->type) {
default: return 0; /* UNKNOWN */
case CONS: return (cond->cons.car || cond->cons.cdr) ? 1 : 0;
case STRING: return cond->string.len != 0 ? 1 : 0;
case NUMBER: return cond->number != 0 ? 1 : 0;
case SYMBOL: return 1; /* FIXME */
case BOOLEAN: return cond->boolean == ROOK_TRUE->boolean;
}
}
static size_t
listlen(struct value *lst)
{
size_t n;
n = 0;
while (lst) {
if (lst->type != CONS) {
fprintf(stderr, "listlen() given an improper list; (cd^%lur lst) was not a CONS!\n", n);
fprintv(stderr, 2, lst);
fprintf(stderr, "\n");
exit(1);
}
n++;
lst = CDR(lst);
}
return n;
}
static void
arity(const char *msg, struct value *lst, size_t min, size_t max)
{
size_t n;
n = listlen(lst);
if (min == max) {
if (n != min) {
fprintf(stderr, "%s: wrong arity (expected %li, got %li)\n", msg, min, n);
exit(1);
}
return;
}
if (n < min) {
fprintf(stderr, "%s: wrong arity (expected at least %li, got %li)\n", msg, min, n);
exit(1);
}
if (max > 0 && n > max) {
fprintf(stderr, "%s: wrong arity (expected no more than %li, got %li)\n", msg, max, n);
fprintv(stderr, 2, lst);
fprintf(stderr, "\n");
exit(1);
}
}
static struct value *
primop_eq(struct value *args)
{
arity("(eq ...)", args, 2, 2);
if (CAR(args)->type != CADR(args)->type)
return ROOK_FALSE;
switch (CAR(args)->type) {
default: return truish(CAR(args) == CADR(args));
case SYMBOL: return truish(CAR(args)->symbol == CADR(args)->symbol);
case NUMBER: return truish(CAR(args)->number == CADR(args)->number);
case STRING: return truish(CAR(args)->string.len == CADR(args)->string.len
&& memcmp(CAR(args)->string.data,
CADR(args)->string.data,
CAR(args)->string.len) == 0);
}
}
static struct value *
primop_ne(struct value *args)
{
arity("(ne ...)", args, 2, 2);
if (CAR(args)->type != CADR(args)->type)
return ROOK_TRUE;
switch (CAR(args)->type) {
default: return truish(CAR(args) != CADR(args));
case SYMBOL: return truish(CAR(args)->symbol != CADR(args)->symbol);
case NUMBER: return truish(CAR(args)->number != CADR(args)->number);
case STRING: return truish(CAR(args)->string.len != CADR(args)->string.len
|| memcmp(CAR(args)->string.data,
CADR(args)->string.data,
CAR(args)->string.len) != 0);
}
}
static struct value *
primop_atom(struct value *args)
{
arity("(atom ...)", args, 1, 1);
return truish(CAR(args) && CAR(args)->type != CONS);
}
static struct value *
primop_null(struct value *args)
{
arity("(null ...)", args, 1, 1);
return truish(!CAR(args));
}
static struct value *
primop_car(struct value *args)
{
arity("(car ...)", args, 1, 1);
if (!CAR(args) || CAR(args)->type != CONS)
return ROOK_FALSE;
return CAAR(args);
}
static struct value *
primop_cdr(struct value *args)
{
arity("(cdr ...)", args, 1, 1);
if (!CAR(args) || CAR(args)->type != CONS)
return ROOK_FALSE;
return CDAR(args);
}
static struct value *
primop_cons(struct value *args)
{
arity("(cons ...)", args, 2, 2);
return new_cons(CAR(args), CADR(args));
}
static struct value *
primop_print(struct value *args)
{
/* (print e) - print the s-expr e to standard output */
arity("(print ...)", args, 1, 1);
if (!QUIET) {
fprintv(stdout, 0, CAR(args));
fprintf(stdout, "\n");
}
return ROOK_TRUE;
}
static struct value *
primop_env(struct value *args)
{
/* (env v) - return the value of environment variable v */
arity("(env ...)", args, 1, 1);
if (CAR(args)->type == STRING) {
char *v = getenv(CAR(args)->string.data);
return new_string(v ? v : "");
}
fprintf(stderr, "non-string name to (env name)!\n");
exit(1);
}
static struct value *
primop_printf(struct value *args)
{
/* (printf "..." ...) - print a formatted string to standard output */
/* FIXME:
Right now, this 'printf' implementation just prints; it doesn't f.
Essentially, the format string is a DSL that we need to implement.
*/
arity("(printf ...)", args, 1, 1);
if (CAR(args)->type != STRING) {
fprintf(stderr, "non-string argument to printf!\n");
exit(2);
}
if (!QUIET) {
fprintf(stdout, "%s", CAR(args)->string.data); /* FIXME: doesn't handle \0 embedded */
}
return ROOK_TRUE;
}
static struct value *
primop_syscall(struct value *args)
{
/* (syscall 'name ...) - issue a system call */
arity("(syscall ...)", args, 1, 0);
if (CAR(args)->type != SYMBOL) {
fprintf(stderr, "non-symbol argument to syscall\n");
exit(2);
}
if (CAR(args)->symbol == intern("exit")) {
arity("(syscall 'exit ...)", args, 2, 2);
if (CADR(args)->type != NUMBER) {
fprintf(stderr, "invalid exit code: ");
fprintv(stderr, 0, CADR(args));
fprintf(stderr, "\n");
exit(4);
}
exit(CADR(args)->number);
}
return ROOK_TRUE;
}
static struct value *
primop_open(struct value *args)
{
struct value *v;
/* (open "path") - open a file for reading */
arity("(open ...)", args, 1, 1);
if (CAR(args)->type != STRING) {
fprintf(stderr, "non-string argument to open\n");
exit(2);
}
v = make(struct value);
v->type = NUMBER;
v->number = open(CAR(args)->string.data, O_RDONLY);
return v;
}
static struct value *
primop_read(struct value *args)
{
struct reader *r;
/* (read fd) - read a form from a file descriptor */
arity("(read ...)", args, 1, 1);
if (CAR(args)->type != NUMBER) {
fprintf(stderr, "non-fd argument to read\n");
exit(2);
}
r = fd_reader("<fd...>", CAR(args)->number);
return read1(r);
}
static struct value *
primop_list(struct value *args)
{
return args;
}
static struct value *
primop_append(struct value *args)
{
struct value *lst;
/* (append l1 l2) */
arity("(append ...)", args, 2, 2);
if (CAR(args)->type != CONS) {
fprintf(stderr, "non-cons argument to append\n");
exit(2);
}
lst = CAR(args);
while (CDR(lst)) {
lst = CDR(lst);
}
CDR(lst) = CADR(args);
return CAR(args);
}
static struct value *
primop_incf(struct value *args)
{
struct value *v;
arity("(+1 ...)", args, 1, 1);
if (CAR(args)->type != NUMBER) {
fprintf(stderr, "non-number argument to +1\n");
exit(2);
}
CAR(args)->number++;
v = make(struct value);
v->type = NUMBER;
v->number = CAR(args)->number;
return v;
}
static struct value *
primop_concat(struct value *args)
{
char *full, *part;
int len;
struct value *v;
full = part = NULL;
while (args) {
switch (CAR(args)->type) {
default:
fprintf(stderr, "non-scalar argument to concat\n");
exit(2);
case STRING:
full = realloc(full, part-full + CAR(args)->string.len + 1);
if (!full) {
fprintf(stderr, "failed to allocate mamory.\n");
exit(2);
}
if (!part) part = full;
memcpy(part, CAR(args)->string.data, CAR(args)->string.len);
part += CAR(args)->string.len;
*part = '\0';
break;
case NUMBER:
len = snprintf(NULL, 0, "%d", CAR(args)->number);
full = realloc(full, part-full + len + 1);
if (!full) {
fprintf(stderr, "failed to allocate mamory.\n");
exit(2);
}
if (!part) part = full;
snprintf(part, len+1, "%d", CAR(args)->number);
part += len;
break;
}
args = CDR(args);
}
v = make(struct value);
v->type = STRING;
v->string.data = full;
v->string.len = part-full;
return v;
}
static struct value *
primop_args(struct value *args)
{
struct value *v;
arity("(args)", args, 0, 0);
v = make(struct value);
v->type = NUMBER;
v->number = ARGC;
return v;
}
static struct value *
primop_argn(struct value *args)
{
arity("(argn ...)", args, 1, 1);
if (CAR(args)->type != NUMBER) {
fprintf(stderr, "non-number argument given to argn\n");
exit(2);
}
if (CAR(args)->number < 0 || CAR(args)->number >= ARGC)
return NULL; /* nil */
return new_string(ARGV[CAR(args)->number]);
}
static struct value *
primop_dump(struct value *args)
{
fprintv(stderr, 4, args);
fprintf(stderr, "\n");
return args;
}
static struct value *
eval(struct value *, struct value *);
static struct value *
evlis(struct value *, struct value *);
static struct value *
evprogn(struct value *, struct value *);
static struct value *
evcond(struct value *, struct value *);
static struct value *
append(struct value *, struct value *);
static struct value *
assoc(struct value *, struct value *);
static struct value *
pair(struct value *, struct value *);
static struct value *
setf(struct value **, struct value *, struct value *);
static struct value *
eval(struct value *expr, struct value *env)
{
struct value *op, *lst;
if (expr == NULL) {
fprintf(stderr, "NULL expr passed to eval()!\n");
exit(1);
}
if (expr->type == BOOLEAN
|| expr->type == STRING
|| expr->type == NUMBER) {
return expr;
}
if (expr->type == SYMBOL) {
return assoc(expr, env);
}
if (expr->type == CONS && CAR(expr)->type == SYMBOL) {
if (CAR(expr)->symbol == intern("quote")) {
/* (quote x) - return x, skipping evaluation */
arity("(quote ...)", CDR(expr), 1, 1);
return CADR(expr);
}
if (CAR(expr)->symbol == intern("progn")) {
return evprogn(CDR(expr), env);
}
if (CAR(expr)->symbol == intern("cond")) {
return evcond(CDR(expr), env);
}
if (CAR(expr)->symbol == intern("let")) {
/* (let ((x e...)
(y e...))
(body ...))
*/
arity("(let ...)", CDR(expr), 2, 2);
if (CADR(expr)->type != CONS) {
fprintf(stderr, "(let ...) requires a list of bindings as its first argument.\n");
exit(4);
}
lst = CADR(expr);
while (lst != NULL) {
env = new_cons(list2(CAAR(lst), eval(CADAR(lst), env)), env);
lst = CDR(lst);
}
return eval(CADDR(expr), env);
}
if (CAR(expr)->symbol == intern("setf")) {
arity("(setf ...)", CDR(expr), 2, 2);
return setf(&env, CADR(expr), eval(CADDR(expr), env));
}
if (CAR(expr)->symbol == intern("functions")) {
/* (functions
((f (args) e...)
(g (args) e...))
(f ...))
*/
arity("(functions ...)", CDR(expr), 2, 2);
if (CADR(expr)->type != CONS) {
fprintf(stderr, "(functions ...) requires a list of abstractions as its first argument.\n");
exit(4);
}
lst = CADR(expr);
while (lst != NULL) {
env = new_cons(list2(CAAR(lst), new_cons(new_symbol("lambda"), CDAR(lst))), env);
lst = CDR(lst);
}
return eval(CADDR(expr), env);
}
op = eval(CAR(expr), env);
if (op->type == PRIMOP) {
return op->primop(evlis(CDR(expr), env));
}
return eval(new_cons(op, CDR(expr)), env);
}
if (expr->type == CONS && CAR(expr)->type == CONS
&& CAAR(expr)->type == SYMBOL && CAAR(expr)->symbol == intern("label")) {
return eval(new_cons(CADDAR(expr), CDR(expr)),
new_cons(
list2(CADAR(expr), CAR(expr)),
env));
}
if (expr->type == CONS && CAR(expr)->type == CONS
&& CAAR(expr)->type == SYMBOL && CAAR(expr)->symbol == intern("lambda")) {
size_t want_arity = listlen(CADAR(expr));
size_t got_arity = listlen(CDR(expr));
if (want_arity != got_arity) {
fprintf(stderr, "(lambda ...) application failed: arity mismatch; wanted %lu arguments, but got %lu\n",
want_arity, got_arity);
exit(1);
}
return evprogn(CDDAR(expr),
append(pair(CADAR(expr),
evlis(CDR(expr), env)),
env));
}
fprintf(stderr, "invalid form!\n");
fprintv(stderr, 4, expr);
fprintf(stderr, "\n");
exit(1);
}
static struct value *
evlis(struct value *lst, struct value *env)
{
if (!lst) return NULL;
return new_cons(eval(CAR(lst), env),
evlis(CDR(lst), env));
}
static struct value *
evprogn(struct value *lst, struct value *env)
{
struct value *e;
while (lst != NULL) {
e = eval(CAR(lst), env);
lst = CDR(lst);
}
return e;
}
static struct value *
evcond(struct value *cond, struct value *env)
{
while (cond) {
if (truthy(eval(CAAR(cond), env)))
return evprogn(CDAR(cond), env);
cond = CDR(cond);
}
return ROOK_FALSE;
}
static struct value *
append(struct value *x, struct value *y)
{
if (!x) return y;
return new_cons(CAR(x), append(CDR(x), y));
}
static struct value *
assoc(struct value *var, struct value *alst)
{
if (var->type != SYMBOL) {
fprintf(stderr, "invalid assoc(...) call -- var is not a symbol.\n");
exit(3);
}
while (alst && CAR(alst)) {
if (CAAR(alst)->type == SYMBOL
&& CAAR(alst)->symbol == var->symbol)
return CADAR(alst);
alst = CDR(alst);
}
fprintf(stderr, "undefined symbol %s\n", var->symbol->name);
exit(4);
}
static struct value *
pair(struct value *x, struct value *y)
{
if (!x && !y) return NULL;
if (x->type == CONS && y->type == CONS)
return new_cons(
new_cons(CAR(x), new_cons(CAR(y), NULL)),
pair(CDR(x), CDR(y)));
fprintf(stderr, "invalid pair() call!\n");
if (!x || x->type != CONS) fprintf(stderr, " - x (arg1) is not a CONS cell\n");
if (!y || y->type != CONS) fprintf(stderr, " - y (arg2) is not a CONS cell\n");
exit(1);
}
static struct value *
setf(struct value **env, struct value *var, struct value *value)
{
struct value *alst;
if (var->type != SYMBOL) {
fprintf(stderr, "invalid setf(...) call -- var is not a symbol.\n");
exit(3);
}
alst = *env;
while (alst && CAR(alst)) {
if (CAAR(alst)->type == SYMBOL
&& CAAR(alst)->symbol == var->symbol) {
CADAR(alst) = value;
return value;
}
alst = CDR(alst);
}
*env = new_cons(new_cons(var, value), *env);
return value;
}
static struct value *
init()
{
struct value *env = NULL;
ROOK_TRUE = make(struct value);
ROOK_TRUE->type = BOOLEAN;
ROOK_TRUE->boolean = 1;
ROOK_FALSE = make(struct value);
ROOK_FALSE->type = BOOLEAN;
ROOK_FALSE->boolean = 0;
env = new_cons(list2(new_symbol("nil"), NULL), env);
env = new_cons(list2(new_symbol("eq"), new_primop(primop_eq)), env);
env = new_cons(list2(new_symbol("ne"), new_primop(primop_ne)), env);
env = new_cons(list2(new_symbol("atom"), new_primop(primop_atom)), env);
env = new_cons(list2(new_symbol("null"), new_primop(primop_null)), env);
env = new_cons(list2(new_symbol("car"), new_primop(primop_car)), env);
env = new_cons(list2(new_symbol("cdr"), new_primop(primop_cdr)), env);
env = new_cons(list2(new_symbol("cons"), new_primop(primop_cons)), env);
env = new_cons(list2(new_symbol("print"), new_primop(primop_print)), env);
env = new_cons(list2(new_symbol("env"), new_primop(primop_env)), env);
env = new_cons(list2(new_symbol("printf"), new_primop(primop_printf)), env);
env = new_cons(list2(new_symbol("syscall"), new_primop(primop_syscall)), env);
env = new_cons(list2(new_symbol("open"), new_primop(primop_open)), env);
env = new_cons(list2(new_symbol("read"), new_primop(primop_read)), env);
env = new_cons(list2(new_symbol("list"), new_primop(primop_list)), env);
env = new_cons(list2(new_symbol("append"), new_primop(primop_append)), env);
env = new_cons(list2(new_symbol("+1"), new_primop(primop_incf)), env);
env = new_cons(list2(new_symbol("concat"), new_primop(primop_concat)), env);
env = new_cons(list2(new_symbol("args"), new_primop(primop_args)), env);
env = new_cons(list2(new_symbol("argn"), new_primop(primop_argn)), env);
env = new_cons(list2(new_symbol("dump"), new_primop(primop_dump)), env);
return env;
}
static void
repl(struct value *env)
{
struct reader *r;
struct value *ast;
if (isatty(1)) {
fprintf(stdout, "\033[1;32mrook\033[0m \033[1;31mpre-alpha\033[0m v0\n");
fprintf(stdout, "copyright (c) 2018-2019 James Hunt\n");
fprintf(stdout, "---\n");
fprintf(stdout, "\033[1;36m♜\033[0m ");
} else {
fprintf(stdout, "rook pre-alpha v0\n");
fprintf(stdout, "copyright (c) 2018-2019 James Hunt\n");
fprintf(stdout, "---\n");
fprintf(stdout, "♜ ");
}
fflush(stdout);
r = fd_reader("<stdin>", 0);
while ((ast = read1(r)) != 0) {
fprintv(stdout, 0, eval(ast, env));
if (isatty(1)) {
fprintf(stdout, "\n\033[1;36m♜\033[0m ");
} else {
fprintf(stdout, "\n♜ ");
}
fflush(stdout);
}
fprintf(stdout, "\n");
}
int
main(int argc, char **argv)
{
struct reader *r;
struct value *form, *result, *env;
struct {
int quiet;
int debug;
int evaluate;
} opts;
memset(&opts, 0, sizeof(opts));
for (;;) {
int c, idx;
static struct option longs[] = {
{ "quiet", no_argument, 0, 'q' },
{ "debug", no_argument, 0, 'D' },
{ "evaluate", no_argument, 0, 'E' },
{ 0, 0, 0, 0 }
};
c = getopt_long(argc, argv, "qDE", longs, &idx);
if (c < 0) break;
switch (c) {
case 'q':
opts.quiet = 1;
opts.debug = 0;
break;
case 'D':
opts.quiet = 0;
opts.debug = 1;
case 'E':
opts.evaluate = 1;
break;
default:
fprintf(stderr, "USAGE: %s [--evaluate] [--quiet] [--debug] code.rk\n", argv[0]);
exit(1);
}
}
QUIET = opts.quiet;
DEBUG = opts.debug;
env = init();
ARGC = argc - optind;
ARGV = argv + optind;
if (ARGC < 1) {
repl(env);
exit(0);
}
ARGV++; ARGC--;
if (strcmp(argv[optind], "-") == 0) {
r = fd_reader("<stdin>", 0);
} else {
r = file_reader(argv[optind]);
if (!r) {
fprintf(stderr, "%s: %s (error %d)\n", argv[optind], strerror(errno), errno);
exit(1);
}
}
result = NULL;
while ((form = read1(r)) != NULL) {
result = eval(form, env);
if (!result) {
fprintf(stderr, "%s: parsing failed.\n", argv[optind]);
exit(1);
}
}
if (opts.evaluate) {
fprintv(stdout, 0, result);
fprintf(stdout, "\n");
}
free_value(result);
free_reader(r);
return 0;
}
| 20.890792 | 106 | 0.597137 |
d3b4ef6b7834bf985ae9df08f093ff28feafc836 | 722 | h | C | go/internal/ble-driver/BleInterface_darwin.h | mrezaz/berty | 9b56e81e009fcfb7ba44223dbd569700e01b9704 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 3 | 2022-02-07T13:47:33.000Z | 2022-02-09T15:26:21.000Z | go/internal/ble-driver/BleInterface_darwin.h | mrezaz/berty | 9b56e81e009fcfb7ba44223dbd569700e01b9704 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 204 | 2020-11-18T13:51:09.000Z | 2022-03-31T04:06:07.000Z | go/internal/ble-driver/BleInterface_darwin.h | mrezaz/berty | 9b56e81e009fcfb7ba44223dbd569700e01b9704 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 1 | 2021-09-21T22:18:42.000Z | 2021-09-21T22:18:42.000Z | //
// BleInterface.h
// ble
//
// Created by sacha on 26/09/2018.
// Copyright © 2018 sacha. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import <os/log.h>
#import <signal.h>
#ifndef BleInterface_h
#define BleInterface_h
@class BleManager;
extern os_log_t OS_LOG_BLE;
void BLEStart(char *localPID);
void BLEStop(void);
int BLESendToPeer(char *remotePID, void *payload, int length);
int BLEDialPeer(char *remotePID);
void BLECloseConnWithPeer(char *remotePID);
int BLEBridgeHandleFoundPeer(NSString *remotePID);
void BLEBridgeHandleLostPeer(NSString *remotePID);
void BLEBridgeReceiveFromPeer(NSString *remotePID, NSData *payload);
#endif /* BleInterface_h */
| 24.066667 | 68 | 0.770083 |
03a3bbff1fffb90204872ef40c835f721ec00d2b | 6,431 | h | C | thirdparty/cgal/CGAL-5.1/include/CGAL/Surface_mesh_parameterization/parameterize.h | MelvinG24/dust3d | c4936fd900a9a48220ebb811dfeaea0effbae3ee | [
"MIT"
] | 2,392 | 2016-12-17T14:14:12.000Z | 2022-03-30T19:40:40.000Z | thirdparty/cgal/CGAL-5.1/include/CGAL/Surface_mesh_parameterization/parameterize.h | MelvinG24/dust3d | c4936fd900a9a48220ebb811dfeaea0effbae3ee | [
"MIT"
] | 106 | 2018-04-19T17:47:31.000Z | 2022-03-01T19:44:11.000Z | thirdparty/cgal/CGAL-5.1/include/CGAL/Surface_mesh_parameterization/parameterize.h | MelvinG24/dust3d | c4936fd900a9a48220ebb811dfeaea0effbae3ee | [
"MIT"
] | 184 | 2017-11-15T09:55:37.000Z | 2022-02-21T16:30:46.000Z | // Copyright (c) 2005 INRIA (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL: https://github.com/CGAL/cgal/blob/v5.1/Surface_mesh_parameterization/include/CGAL/Surface_mesh_parameterization/parameterize.h $
// $Id: parameterize.h 254d60f 2019-10-19T15:23:19+02:00 Sébastien Loriot
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : Laurent Saboret, Pierre Alliez, Bruno Levy
#ifndef CGAL_SURFACE_MESH_PARAMETERIZATION_PARAMETERIZE_H
#define CGAL_SURFACE_MESH_PARAMETERIZATION_PARAMETERIZE_H
#include <CGAL/license/Surface_mesh_parameterization.h>
#include <CGAL/disable_warnings.h>
#include <CGAL/Surface_mesh_parameterization/internal/Bool_property_map.h>
#include <CGAL/Surface_mesh_parameterization/Error_code.h>
#include <CGAL/Surface_mesh_parameterization/Mean_value_coordinates_parameterizer_3.h>
#include <CGAL/Polygon_mesh_processing/connected_components.h>
#include <boost/function_output_iterator.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
/// \file parameterize.h
namespace CGAL {
namespace Surface_mesh_parameterization {
/// \ingroup PkgSurfaceMeshParameterizationMainFunction
///
/// Compute a one-to-one mapping from a 3D triangle surface `mesh` to a
/// simple 2D domain.
/// The mapping is piecewise linear on the triangle mesh.
/// The result is a pair `(u,v)` of parameter coordinates for each vertex of the input mesh.
///
/// A one-to-one mapping may be guaranteed or not, depending on
/// the chosen Parameterizer algorithm.
///
/// \tparam TriangleMesh must be a model of `FaceGraph`.
/// \tparam Parameterizer must be a model of `Parameterizer_3`.
/// \tparam HD must be the halfedge_descriptor type corresponding to the graph
/// traits of TriangleMesh.
/// \tparam VertexUVmap must be a model of `ReadWritePropertyMap` with
/// `boost::graph_traits<TriangleMesh>::%vertex_descriptor` as key type and
/// %Point_2 (type deduced from `TriangleMesh` using `Kernel_traits`)
/// as value type.
///
/// \param mesh a triangulated surface.
/// \param parameterizer a parameterizer.
/// \param bhd a halfedge descriptor on the boundary of `mesh`.
/// \param uvm an instanciation of the class `VertexUVmap`.
///
/// \pre `mesh` must be a triangular mesh.
/// \pre The mesh border must be mapped onto a convex polygon
/// (for fixed border parameterizations).
/// \pre The vertices must be indexed (vimap must be initialized).
///
template <class TriangleMesh, class Parameterizer, class HD, class VertexUVmap>
Error_code parameterize(TriangleMesh& mesh,
Parameterizer parameterizer,
HD bhd,
VertexUVmap uvm)
{
typedef typename boost::graph_traits<TriangleMesh>::vertex_descriptor vertex_descriptor;
typedef boost::unordered_map<vertex_descriptor, int> Indices;
Indices indices;
CGAL::Polygon_mesh_processing::connected_component(
face(opposite(bhd, mesh), mesh),
mesh,
boost::make_function_output_iterator(
internal::Index_map_filler<TriangleMesh, Indices>(mesh, indices)));
boost::associative_property_map<Indices> vipm(indices);
boost::unordered_set<vertex_descriptor> vs;
internal::Bool_property_map<boost::unordered_set<vertex_descriptor> > vpm(vs);
return parameterizer.parameterize(mesh, bhd, uvm, vipm, vpm);
}
/// \ingroup PkgSurfaceMeshParameterizationMainFunction
///
/// Compute a one-to-one mapping from a 3D triangle surface `mesh` to a
/// 2D circle, using Floater Mean Value Coordinates algorithm.
/// A one-to-one mapping is guaranteed.
///
/// The mapping is piecewise linear on the input mesh triangles.
/// The result is a `(u,v)` pair of parameter coordinates for each vertex of the input mesh.
///
/// \tparam TriangleMesh must be a model of `FaceGraph`.
/// \tparam HD must be the halfedge_descriptor type corresponding to the graph
/// traits of TriangleMesh.
/// \tparam VertexUVmap must be a model of `ReadWritePropertyMap` with
/// `boost::graph_traits<TriangleMesh>::%vertex_descriptor` as key type and
/// %Point_2 (type deduced from `TriangleMesh` using `Kernel_traits`)
/// as value type.
///
/// \param mesh a triangulated surface.
/// \param bhd a halfedge descriptor on the boundary of `mesh`.
/// \param uvm an instanciation of the class `VertexUVmap`.
///
/// \pre `mesh` must be a triangular mesh.
/// \pre The vertices must be indexed (vimap must be initialized).
///
template <class TriangleMesh, class HD, class VertexUVmap>
Error_code parameterize(TriangleMesh& mesh,
HD bhd,
VertexUVmap uvm)
{
Mean_value_coordinates_parameterizer_3<TriangleMesh> parameterizer;
return parameterize(mesh, parameterizer, bhd, uvm);
}
template <class TM, class SEM, class SVM>
class Seam_mesh;
template <class TM, class SEM, class SVM, class Parameterizer, class HD, class VertexUVmap>
Error_code parameterize(Seam_mesh<TM, SEM, SVM>& mesh,
Parameterizer parameterizer,
HD bhd,
VertexUVmap uvm)
{
typedef typename boost::graph_traits<Seam_mesh<TM, SEM, SVM> >::vertex_descriptor vertex_descriptor;
boost::unordered_set<vertex_descriptor> vs;
internal::Bool_property_map<boost::unordered_set<vertex_descriptor> > vpm(vs);
typedef boost::unordered_map<vertex_descriptor, int> Indices;
Indices indices;
CGAL::Polygon_mesh_processing::connected_component(
face(opposite(bhd, mesh), mesh),
mesh,
boost::make_function_output_iterator(
internal::Index_map_filler<Seam_mesh<TM, SEM, SVM>,
Indices>(mesh, indices)));
boost::associative_property_map<Indices> vipm(indices);
return parameterizer.parameterize(mesh, bhd, uvm, vipm, vpm);
}
template <class TM, class SEM, class SVM, class HD, class VertexUVmap>
Error_code parameterize(Seam_mesh<TM, SEM, SVM>& mesh,
HD bhd,
VertexUVmap uvm)
{
Mean_value_coordinates_parameterizer_3<Seam_mesh<TM, SEM, SVM> > parameterizer;
return parameterize(mesh, parameterizer, bhd, uvm);
}
} // namespace Surface_mesh_parameterization
} // namespace CGAL
#include <CGAL/enable_warnings.h>
#endif // CGAL_PARAMETERIZE_H
| 38.975758 | 137 | 0.71995 |
03a615da7edb2e481749f222dbd81718ff1def57 | 306 | h | C | Layout_Demo/Layout_Demo/ETLayoutable.h | gracenamucuo/Study | 0be9f7bede1c7f3594b9544a20dd571429f723bd | [
"MIT"
] | 2 | 2018-04-15T07:44:21.000Z | 2020-06-22T08:19:14.000Z | Layout_Demo/Layout_Demo/ETLayoutable.h | gracenamucuo/Study | 0be9f7bede1c7f3594b9544a20dd571429f723bd | [
"MIT"
] | null | null | null | Layout_Demo/Layout_Demo/ETLayoutable.h | gracenamucuo/Study | 0be9f7bede1c7f3594b9544a20dd571429f723bd | [
"MIT"
] | null | null | null | //
// ETLayoutable.h
// Layout_Demo
//
// Created by 戴运鹏 on 2018/6/24.
// Copyright © 2018年 戴运鹏. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Masonry.h"
typedef void(^LayoutMaker)(MASConstraintMaker *maker);
@protocol ETLayoutable <NSObject>
- (LayoutMaker)layoutMaker;
@end
| 16.105263 | 54 | 0.712418 |
268dfefc34813eff59d4dbc5fde2ba475b185893 | 720 | h | C | Eleven/Common/Category/UIBarButtonItem+Item.h | tanglei11/meitu_copy | 9a8b93f4bb9a7e0e9dfb8b40743b99e32100b0d7 | [
"MIT"
] | 3 | 2019-12-14T05:59:43.000Z | 2021-09-30T03:25:10.000Z | Eleven/Common/Category/UIBarButtonItem+Item.h | tanglei11/meitu_copy | 9a8b93f4bb9a7e0e9dfb8b40743b99e32100b0d7 | [
"MIT"
] | null | null | null | Eleven/Common/Category/UIBarButtonItem+Item.h | tanglei11/meitu_copy | 9a8b93f4bb9a7e0e9dfb8b40743b99e32100b0d7 | [
"MIT"
] | null | null | null |
//
// UIBarButtonItem+KHBarButtonItem.h
// 新浪微博
//
// Created by apple on 15/9/22.
// Copyright (c) 2015年 apple. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIBarButtonItem (Item)
+ (UIBarButtonItem *)itemWithTarget:(id)target Action:(SEL)action imageNormal:(UIImage *)imageNormal imageHighed:(UIImage *)imageHighed;
+ (UIBarButtonItem *)itemWithTarget:(id)target Action:(SEL)action imageNormal:(UIImage *)imageNormal size:(CGSize)size;
+ (UIBarButtonItem *)itemWithTarget:(id)target Action:(SEL)action title:(NSString *)title titleColor:(UIColor *)titleColor;
+ (UIBarButtonItem *)itemWithTarget:(id)target Action:(SEL)action imageName:(NSString *)imageName imageColor:(UIColor *)imageColor;
@end
| 40 | 136 | 0.761111 |
c19ba2b40b1677e11577ff0081c6931a9ffc61db | 1,305 | h | C | Game.h | hane1818/The-Practice-of-Programming_GamePvZ | 41e8aeb550ee5d913cd049a7a8382b3c8d43811e | [
"MIT"
] | 1 | 2019-04-25T06:33:57.000Z | 2019-04-25T06:33:57.000Z | Game.h | hane1818/The-Practice-of-Programming_GamePvZ | 41e8aeb550ee5d913cd049a7a8382b3c8d43811e | [
"MIT"
] | 2 | 2016-01-08T08:00:43.000Z | 2016-01-08T08:03:26.000Z | Game.h | hane1818/The-Practice-of-Programming_GamePvZ | 41e8aeb550ee5d913cd049a7a8382b3c8d43811e | [
"MIT"
] | 1 | 2020-12-24T11:05:39.000Z | 2020-12-24T11:05:39.000Z | #ifndef GAME__
#define GAME__
#include <iostream>
#include <vector>
#include "Player.h"
#include "Zombie.h"
#include "Map.h"
class Game
{
friend std::ostream & operator << (std::ostream & os, const Game & game);
public:
Game(int lands, int zombies);
~Game();
void doPlayer() const;
void doZombie(int z_ind) const;
void movePlayer(int pos) const;
void moveZombie(Zombie & z, int pos) const;
void printPlant() const;
void printZombies() const;
void printPlayer() const;
bool endGame() const;
bool aliveZombie(int z_ind) const { return zombie_[z_ind].isAlive(); }
const int zombiesNum() const { return numOfZombie_; }
static constexpr int LAND_DEFAULT=8;
static constexpr int LAND_MAX=10;
static constexpr int LAND_MIN=1;
static constexpr int ZOMBIE_DEFAULT=3;
static constexpr int ZOMBIE_MAX=10;
static constexpr int ZOMBIE_MIN=1;
private:
void initPlant();
Player *player_=nullptr;
Zombie *zombie_=nullptr;
Map *map_=nullptr;
std::vector<Plant*> plant_;
int numOfZombie_=ZOMBIE_DEFAULT;
int numOfLand_=LAND_DEFAULT;
int limitStep(int pos) const;
bool allZombiesDie() const;
bool enoughMoney() const;
};
std::ostream & operator << (std::ostream & os, const Game & game);
#endif // GAME__
| 27.765957 | 77 | 0.685824 |
9cccc4d55057f82022af3f12e495b883e103a491 | 7,548 | h | C | chromeos/network/managed_network_configuration_handler_impl.h | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-08-13T21:04:58.000Z | 2015-08-13T21:04:58.000Z | chromeos/network/managed_network_configuration_handler_impl.h | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/network/managed_network_configuration_handler_impl.h | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright 2013 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 CHROMEOS_NETWORK_MANAGED_NETWORK_CONFIGURATION_HANDLER_IMPL_H_
#define CHROMEOS_NETWORK_MANAGED_NETWORK_CONFIGURATION_HANDLER_IMPL_H_
#include <map>
#include <string>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/linked_ptr.h"
#include "base/memory/weak_ptr.h"
#include "chromeos/chromeos_export.h"
#include "chromeos/network/managed_network_configuration_handler.h"
#include "chromeos/network/network_handler_callbacks.h"
#include "chromeos/network/network_profile_observer.h"
#include "chromeos/network/policy_applicator.h"
namespace base {
class DictionaryValue;
}
namespace chromeos {
class NetworkConfigurationHandler;
struct NetworkProfile;
class NetworkProfileHandler;
class NetworkStateHandler;
class CHROMEOS_EXPORT ManagedNetworkConfigurationHandlerImpl
: public ManagedNetworkConfigurationHandler,
public NetworkProfileObserver,
public PolicyApplicator::ConfigurationHandler {
public:
virtual ~ManagedNetworkConfigurationHandlerImpl();
// ManagedNetworkConfigurationHandler overrides
virtual void AddObserver(NetworkPolicyObserver* observer) OVERRIDE;
virtual void RemoveObserver(NetworkPolicyObserver* observer) OVERRIDE;
virtual void GetProperties(
const std::string& service_path,
const network_handler::DictionaryResultCallback& callback,
const network_handler::ErrorCallback& error_callback) OVERRIDE;
virtual void GetManagedProperties(
const std::string& userhash,
const std::string& service_path,
const network_handler::DictionaryResultCallback& callback,
const network_handler::ErrorCallback& error_callback) OVERRIDE;
virtual void SetProperties(
const std::string& service_path,
const base::DictionaryValue& user_settings,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) const OVERRIDE;
virtual void CreateConfiguration(
const std::string& userhash,
const base::DictionaryValue& properties,
const network_handler::StringResultCallback& callback,
const network_handler::ErrorCallback& error_callback) const OVERRIDE;
virtual void RemoveConfiguration(
const std::string& service_path,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) const OVERRIDE;
virtual void SetPolicy(
onc::ONCSource onc_source,
const std::string& userhash,
const base::ListValue& network_configs_onc,
const base::DictionaryValue& global_network_config) OVERRIDE;
virtual const base::DictionaryValue* FindPolicyByGUID(
const std::string userhash,
const std::string& guid,
onc::ONCSource* onc_source) const OVERRIDE;
virtual const base::DictionaryValue* GetGlobalConfigFromPolicy(
const std::string userhash) const OVERRIDE;
virtual const base::DictionaryValue* FindPolicyByGuidAndProfile(
const std::string& guid,
const std::string& profile_path) const OVERRIDE;
// NetworkProfileObserver overrides
virtual void OnProfileAdded(const NetworkProfile& profile) OVERRIDE;
virtual void OnProfileRemoved(const NetworkProfile& profile) OVERRIDE;
// PolicyApplicator::ConfigurationHandler overrides
virtual void CreateConfigurationFromPolicy(
const base::DictionaryValue& shill_properties) OVERRIDE;
virtual void UpdateExistingConfigurationWithPropertiesFromPolicy(
const base::DictionaryValue& existing_properties,
const base::DictionaryValue& new_properties) OVERRIDE;
virtual void OnPoliciesApplied() OVERRIDE;
private:
friend class ClientCertResolverTest;
friend class ManagedNetworkConfigurationHandlerTest;
friend class NetworkConnectionHandlerTest;
friend class NetworkHandler;
struct Policies;
typedef std::map<std::string, linked_ptr<Policies> > UserToPoliciesMap;
typedef base::Callback<void(const std::string& service_path,
scoped_ptr<base::DictionaryValue> properties)>
GetDevicePropertiesCallback;
ManagedNetworkConfigurationHandlerImpl();
// Handlers may be NULL in tests so long as they do not execute any paths
// that require the handlers.
void Init(NetworkStateHandler* network_state_handler,
NetworkProfileHandler* network_profile_handler,
NetworkConfigurationHandler* network_configuration_handler,
NetworkDeviceHandler* network_device_handler);
// Sends the response to the caller of GetManagedProperties.
void SendManagedProperties(
const std::string& userhash,
const network_handler::DictionaryResultCallback& callback,
const network_handler::ErrorCallback& error_callback,
const std::string& service_path,
scoped_ptr<base::DictionaryValue> shill_properties);
// Sends the response to the caller of GetProperties.
void SendProperties(
const network_handler::DictionaryResultCallback& callback,
const network_handler::ErrorCallback& error_callback,
const std::string& service_path,
scoped_ptr<base::DictionaryValue> shill_properties);
const Policies* GetPoliciesForUser(const std::string& userhash) const;
const Policies* GetPoliciesForProfile(const NetworkProfile& profile) const;
void OnPolicyAppliedToNetwork(const std::string& service_path);
// Helper method to append associated Device properties to |properties|.
void GetDeviceStateProperties(const std::string& service_path,
base::DictionaryValue* properties);
// Callback for NetworkConfigurationHandler::GetProperties requests from
// Get{Managed}Properties. This callback fills in properties from
// DeviceState and may request additional Device properties.
// Note: Requesting Device properties requires an additional fetch and
// additional copying of data, so we only do it for Cellular networks which
// contain a lot of necessary state in the associated Device object.
void GetPropertiesCallback(
GetDevicePropertiesCallback send_callback,
const std::string& service_path,
const base::DictionaryValue& shill_properties);
void GetDevicePropertiesSuccess(
const std::string& service_path,
scoped_ptr<base::DictionaryValue> network_properties,
GetDevicePropertiesCallback send_callback,
const std::string& device_path,
const base::DictionaryValue& device_properties);
void GetDevicePropertiesFailure(
const std::string& service_path,
scoped_ptr<base::DictionaryValue> network_properties,
GetDevicePropertiesCallback send_callback,
const std::string& error_name,
scoped_ptr<base::DictionaryValue> error_data);
// If present, the empty string maps to the device policy.
UserToPoliciesMap policies_by_user_;
// Local references to the associated handler instances.
NetworkStateHandler* network_state_handler_;
NetworkProfileHandler* network_profile_handler_;
NetworkConfigurationHandler* network_configuration_handler_;
NetworkDeviceHandler* network_device_handler_;
ObserverList<NetworkPolicyObserver> observers_;
// For Shill client callbacks
base::WeakPtrFactory<ManagedNetworkConfigurationHandlerImpl>
weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ManagedNetworkConfigurationHandlerImpl);
};
} // namespace chromeos
#endif // CHROMEOS_NETWORK_MANAGED_NETWORK_CONFIGURATION_HANDLER_IMPL_H_
| 39.108808 | 77 | 0.779942 |
96924de0cb3596e7be1b9fbc555b924d6f1c5002 | 207 | c | C | test/generated/wait.c | michael105/minilib | c5b87d98606aa968a760d4b4146ea503492b8178 | [
"MIT"
] | 29 | 2019-03-20T22:34:44.000Z | 2021-09-15T03:23:03.000Z | test/generated/wait.c | michael105/minilib | c5b87d98606aa968a760d4b4146ea503492b8178 | [
"MIT"
] | 4 | 2019-03-20T08:27:07.000Z | 2020-08-17T00:21:30.000Z | test/generated/wait.c | michael105/minilib | c5b87d98606aa968a760d4b4146ea503492b8178 | [
"MIT"
] | null | null | null | #if 0
mini_wait
mini_buf 128
globals_on_stack
mini_start
shrinkelf
INCLUDESRC
LDSCRIPT default
OPTFLAG -Os
return
#endif
int main(){
volatile int ret=42;
volatile int * a1=0;
wait(a1);
return(ret);
}
| 11.5 | 22 | 0.748792 |
53266b2994fafb21eb45f5fe56c1142eabafd36a | 5,050 | c | C | examples/dynamic_services/main.c | RaresMihai11/Probe | 6ad2fd7c8e9205c2b58cd36687d479a49aa10a66 | [
"MIT"
] | 1 | 2019-05-03T16:49:32.000Z | 2019-05-03T16:49:32.000Z | examples/dynamic_services/main.c | RaresMihai11/Probe | 6ad2fd7c8e9205c2b58cd36687d479a49aa10a66 | [
"MIT"
] | null | null | null | examples/dynamic_services/main.c | RaresMihai11/Probe | 6ad2fd7c8e9205c2b58cd36687d479a49aa10a66 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <espressif/esp_wifi.h>
#include <espressif/esp_sta.h>
#include <espressif/esp_common.h>
#include <esp/uart.h>
#include <esp8266.h>
#include <FreeRTOS.h>
#include <task.h>
#include <homekit/homekit.h>
#include <homekit/characteristics.h>
#include "wifi.h"
#define MAX_SERVICES 20
#define MAX_CHARACTERISTICS 10
static void wifi_init() {
struct sdk_station_config wifi_config = {
.ssid = WIFI_SSID,
.password = WIFI_PASSWORD,
};
sdk_wifi_set_opmode(STATION_MODE);
sdk_wifi_station_set_config(&wifi_config);
sdk_wifi_station_connect();
}
const int led_gpio = 2;
const uint8_t relay_gpios[] = {
12, 5, 14, 13
};
const size_t relay_count = sizeof(relay_gpios) / sizeof(*relay_gpios);
void relay_write(int relay, bool on) {
printf("Relay %d %s\n", relay, on ? "ON" : "OFF");
gpio_write(relay, on ? 1 : 0);
}
void led_write(bool on) {
gpio_write(led_gpio, on ? 0 : 1);
}
void gpio_init() {
gpio_enable(led_gpio, GPIO_OUTPUT);
led_write(false);
for (int i=0; i < relay_count; i++) {
gpio_enable(relay_gpios[i], GPIO_OUTPUT);
relay_write(relay_gpios[i], true);
}
}
void lamp_identify_task(void *_args) {
relay_write(relay_gpios[0], true);
for (int i=0; i<3; i++) {
for (int j=0; j<2; j++) {
relay_write(relay_gpios[0], true);
vTaskDelay(100 / portTICK_PERIOD_MS);
relay_write(relay_gpios[0], false);
vTaskDelay(100 / portTICK_PERIOD_MS);
}
vTaskDelay(250 / portTICK_PERIOD_MS);
}
relay_write(relay_gpios[0], true);
vTaskDelete(NULL);
}
void lamp_identify(homekit_value_t _value) {
printf("Lamp identify\n");
xTaskCreate(lamp_identify_task, "Lamp identify", 128, NULL, 2, NULL);
}
void relay_callback(homekit_characteristic_t *ch, homekit_value_t value, void *context) {
uint8_t *gpio = context;
relay_write(*gpio, value.bool_value);
}
homekit_accessory_t *accessories[2];
homekit_server_config_t config = {
.accessories = accessories,
.password = "111-11-111"
};
void on_wifi_ready() {
homekit_server_init(&config);
}
void* memdup(void* data, size_t data_size) {
void *result = malloc(data_size);
memcpy(result, data, data_size);
return result;
}
#define MEMDUP_RANGE(start, end) \
memdup(start, ((uint8_t*)end) - ((uint8_t*)start))
#define NEW_HOMEKIT_ACCESSORY(...) \
memdup(HOMEKIT_ACCESSORY(__VA_ARGS__), sizeof(homekit_accessory_t))
#define NEW_HOMEKIT_SERVICE(name, ...) \
memdup(HOMEKIT_SERVICE(name, ## __VA_ARGS__), sizeof(homekit_service_t))
#define NEW_HOMEKIT_CHARACTERISTIC(name, ...) \
memdup(HOMEKIT_CHARACTERISTIC(name, ## __VA_ARGS__), sizeof(homekit_characteristic_t))
#define NEW_HOMEKIT_CHARACTERISTIC_CALLBACK(...) \
memdup(HOMEKIT_CHARACTERISTIC_CALLBACK(__VA_ARGS__), \
sizeof(homekit_characteristic_change_callback_t))
void init_accessory() {
uint8_t macaddr[6];
sdk_wifi_get_macaddr(STATION_IF, macaddr);
int name_len = snprintf(NULL, 0, "Relays-%02X%02X%02X",
macaddr[3], macaddr[4], macaddr[5]);
char *name_value = malloc(name_len+1);
snprintf(name_value, name_len+1, "Relays-%02X%02X%02X",
macaddr[3], macaddr[4], macaddr[5]);
homekit_service_t* services[MAX_SERVICES + 1];
homekit_characteristic_t* characteristics[MAX_CHARACTERISTICS + 1];
homekit_service_t** s = services;
homekit_characteristic_t** c;
c = characteristics;
*(c++) = NEW_HOMEKIT_CHARACTERISTIC(NAME, name_value);
*(c++) = NEW_HOMEKIT_CHARACTERISTIC(MANUFACTURER, "HaPK");
*(c++) = NEW_HOMEKIT_CHARACTERISTIC(SERIAL_NUMBER, "0");
*(c++) = NEW_HOMEKIT_CHARACTERISTIC(MODEL, "Relays");
*(c++) = NEW_HOMEKIT_CHARACTERISTIC(FIRMWARE_REVISION, "0.1");
*(c++) = NEW_HOMEKIT_CHARACTERISTIC(IDENTIFY, lamp_identify);
*(c++) = NULL;
*(s++) = NEW_HOMEKIT_SERVICE(ACCESSORY_INFORMATION, .characteristics=MEMDUP_RANGE(characteristics, c));
for (int i=0; i < relay_count; i++) {
int relay_name_len = snprintf(NULL, 0, "Relay %d", i + 1);
char *relay_name_value = malloc(name_len+1);
snprintf(relay_name_value, relay_name_len+1, "Relay %d", i + 1);
c = characteristics;
*(c++) = NEW_HOMEKIT_CHARACTERISTIC(NAME, relay_name_value);
*(c++) = NEW_HOMEKIT_CHARACTERISTIC(
ON, true,
.callback=NEW_HOMEKIT_CHARACTERISTIC_CALLBACK(relay_callback, .context=(void*)&relay_gpios[i]),
);
*(c++) = NULL;
*(s++) = NEW_HOMEKIT_SERVICE(LIGHTBULB, .characteristics=MEMDUP_RANGE(characteristics, c));
}
*(s++) = NULL;
accessories[0] = NEW_HOMEKIT_ACCESSORY(
.category=homekit_accessory_category_lightbulb,
.services=MEMDUP_RANGE(services, s),
);
accessories[1] = NULL;
}
void user_init(void) {
uart_set_baud(0, 115200);
init_accessory();
gpio_init();
wifi_init();
on_wifi_ready();
}
| 27.005348 | 107 | 0.666535 |
49e9c6d1db6191d68df73da8dfb2407e84e7c309 | 2,902 | h | C | include/keycodes.h | adi-g15/simplecpp | bbb3a4df3b19d52939cd79ba9587235841fb7267 | [
"CC0-1.0"
] | 3 | 2021-05-08T07:42:59.000Z | 2022-03-28T15:04:02.000Z | include/keycodes.h | adi-g15/simplecpp | bbb3a4df3b19d52939cd79ba9587235841fb7267 | [
"CC0-1.0"
] | null | null | null | include/keycodes.h | adi-g15/simplecpp | bbb3a4df3b19d52939cd79ba9587235841fb7267 | [
"CC0-1.0"
] | null | null | null | #define KeyCode_ESC 9
#define KeyCode_F1 67
#define KeyCode_F2 68
#define KeyCode_F3 69
#define KeyCode_F4 70
#define KeyCode_F5 71
#define KeyCode_F6 72
#define KeyCode_F7 73
#define KeyCode_F8 74
#define KeyCode_F9 75
#define KeyCode_F10 76
#define KeyCode_F11 95
#define KeyCode_F12 96
#define KeyCode_ACUTE 49
#define KeyCode_0 19
#define KeyCode_1 10
#define KeyCode_2 11
#define KeyCode_3 12
#define KeyCode_4 13
#define KeyCode_5 14
#define KeyCode_6 15
#define KeyCode_7 16
#define KeyCode_8 17
#define KeyCode_9 18
#define KeyCode_A 38
#define KeyCode_B 56
#define KeyCode_C 54
#define KeyCode_D 40
#define KeyCode_E 26
#define KeyCode_F 41
#define KeyCode_G 42
#define KeyCode_H 43
#define KeyCode_I 31
#define KeyCode_J 44
#define KeyCode_K 45
#define KeyCode_L 46
#define KeyCode_M 58
#define KeyCode_N 57
#define KeyCode_O 32
#define KeyCode_P 33
#define KeyCode_Q 24
#define KeyCode_R 27
#define KeyCode_S 39
#define KeyCode_T 28
#define KeyCode_U 30
#define KeyCode_V 55
#define KeyCode_W 25
#define KeyCode_X 53
#define KeyCode_Y 29
#define KeyCode_Z 52
#define KeyCode_SUBTRACT 20
#define KeyCode_EQUAL 21
#define KeyCode_BACKSPACE 22
#define KeyCode_TAB 23
#define KeyCode_CAPS_LOCK 66
#define KeyCode_LSHIFT 50
#define KeyCode_RSHIFT 62
#define KeyCode_LALT 64
#define KeyCode_RALT 113
#define KeyCode_LCTRL 37
#define KeyCode_RCTRL 109
#define KeyCode_SPACEBAR 65
#define KeyCode_ENTER 36
#define KeyCode_LBRACKET 34
#define KeyCode_RBRACKET 35
#define KeyCode_BACKSLASH 51
#define KeyCode_SEMICOLON 47
#define KeyCode_QUOTE 48
#define KeyCode_COMMA 59
#define KeyCode_FULLSTOP 60
#define KeyCode_FORWARDSLASH 61
#define KeyCode_HOME 97
#define KeyCode_PAGEUP 99
#define KeyCode_PAGEDOWN 105
#define KeyCode_END 103
#define KeyCode_ARROWUP 98
#define KeyCode_ARROWDOWN 104
#define KeyCode_ARROWLEFT 100
#define KeyCode_ARROWRIGHT 102
#define KeyCode_SCROLL 78
#define KeyCode_PAUSE 110
#define KeyCode_INSERT 106
#define KeyCode_DELETE 107
#define KeyCode_NUMLOCK 77
#define KeyCode_NUMPADDIVIDE 112
#define KeyCode_NUMPADMULTIPLY 63
#define KeyCode_NUMPADSUBTRACT 82
#define KeyCode_NUMPADPLUS 86
#define KeyCode_NUMPADENTER 108
#define KeyCode_NUMPAD0 90
#define KeyCode_NUMPAD1 87
#define KeyCode_NUMPAD2 88
#define KeyCode_NUMPAD3 89
#define KeyCode_NUMPAD4 83
#define KeyCode_NUMPAD5 84
#define KeyCode_NUMPAD6 85
#define KeyCode_NUMPAD7 79
#define KeyCode_NUMPAD8 80
#define KeyCode_NUMPAD9 81
#define KeyCode_NUMPADFULLSTOP 91
#define MouseCode(event) ((event).xbutton.button)
#define KeyCode(event) ((event).xkey.keycode)
#define MouseCode_LEFT Button1
#define MouseCode_RIGHT Button3
#define MouseCode_CENTER Button2
#define MouseCode_SCROLLDN Button4
#define MouseCode_SCROLLUP Button5
#define MousePosX(event) ((event).xbutton.x)
#define MousePosY(event) ((event).xbutton.y)
#define MouseTime(event) ((event).xbutton.time)
#define KeyTime(event) ((event).xkey.time)
| 24.803419 | 49 | 0.828739 |
4998e74125a243d74d47c8a16d33081e8cbbebf5 | 3,314 | c | C | bin/varnishd/cache/cache_vrt_priv.c | adeelshahid/Varnish-Cache | 969674dcb3b4d430a38b7f1b1e41199b25cc8491 | [
"BSD-2-Clause"
] | null | null | null | bin/varnishd/cache/cache_vrt_priv.c | adeelshahid/Varnish-Cache | 969674dcb3b4d430a38b7f1b1e41199b25cc8491 | [
"BSD-2-Clause"
] | null | null | null | bin/varnishd/cache/cache_vrt_priv.c | adeelshahid/Varnish-Cache | 969674dcb3b4d430a38b7f1b1e41199b25cc8491 | [
"BSD-2-Clause"
] | null | null | null | /*-
* Copyright (c) 2006 Verdens Gang AS
* Copyright (c) 2006-2014 Varnish Software AS
* All rights reserved.
*
* Author: Poul-Henning Kamp <phk@phk.freebsd.dk>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Runtime support for compiled VCL programs: private variables
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include "cache.h"
#include "vcl.h"
#include "vrt.h"
struct vrt_privs {
unsigned magic;
#define VRT_PRIVS_MAGIC 0x24157a52
VTAILQ_ENTRY(vrt_privs) list;
struct vmod_priv priv[1];
const struct VCL_conf *vcl;
uintptr_t id;
uintptr_t vmod_id;
};
/*--------------------------------------------------------------------
*/
static struct vmod_priv *
VRT_priv_dynamic(VRT_CTX, uintptr_t id, uintptr_t vmod_id)
{
struct vrt_privs *vps;
CHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC);
VTAILQ_FOREACH(vps, &ctx->req->sp->privs, list) {
CHECK_OBJ_NOTNULL(vps, VRT_PRIVS_MAGIC);
if (vps->vcl == ctx->vcl && vps->id == id
&& vps->vmod_id == vmod_id)
return (vps->priv);
}
ALLOC_OBJ(vps, VRT_PRIVS_MAGIC);
AN(vps);
vps->vcl = ctx->vcl;
vps->id = id;
vps->vmod_id = vmod_id;
VTAILQ_INSERT_TAIL(&ctx->req->sp->privs, vps, list);
return (vps->priv);
}
void
VRTPRIV_dynamic_kill(struct sess *sp, uintptr_t id)
{
struct vrt_privs *vps, *vps1;
CHECK_OBJ_NOTNULL(sp, SESS_MAGIC);
VTAILQ_FOREACH_SAFE(vps, &sp->privs, list, vps1) {
CHECK_OBJ_NOTNULL(vps, VRT_PRIVS_MAGIC);
if (id == vps->id) {
VTAILQ_REMOVE(&sp->privs, vps, list);
VRT_priv_fini(vps->priv);
FREE_OBJ(vps);
}
}
if (id == 0)
assert(VTAILQ_EMPTY(&sp->privs));
}
struct vmod_priv *
VRT_priv_req(VRT_CTX, void *vmod_id)
{
return (VRT_priv_dynamic(ctx, (uintptr_t)ctx->req, (uintptr_t)vmod_id));
}
struct vmod_priv *
VRT_priv_sess(VRT_CTX, void *vmod_id)
{
return (VRT_priv_dynamic(ctx, (uintptr_t)NULL, (uintptr_t)vmod_id));
}
/*--------------------------------------------------------------------
*/
void
VRT_priv_fini(const struct vmod_priv *p)
{
if (p->priv != (void*)0 && p->free != (void*)0)
p->free(p->priv);
}
| 27.848739 | 77 | 0.689499 |
5b611538cca42a0bfdc1e4373d1fe16c57ff4dbe | 711 | h | C | OGMM/BuildConfig.h | Moneyl/OGMM | 52a4bcc051fab160c55f0cc7228bd99de3ff5c47 | [
"MIT"
] | null | null | null | OGMM/BuildConfig.h | Moneyl/OGMM | 52a4bcc051fab160c55f0cc7228bd99de3ff5c47 | [
"MIT"
] | null | null | null | OGMM/BuildConfig.h | Moneyl/OGMM | 52a4bcc051fab160c55f0cc7228bd99de3ff5c47 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
namespace BuildConfig
{
//Path to the asset folder. Varies depending on build type. See src/CMakeLists.txt.
static const std::string AssetFolderPath = ASSET_FOLDER_PATH;
static const std::string MainFontPath = AssetFolderPath + "fonts/NotoSansDisplay-Medium.ttf";
//static const std::string JapaneseFontPath = AssetFolderPath + "fonts/NotoSansJP-Medium.otf";
static const std::string FontAwesomePath = AssetFolderPath + "fonts/fa-solid-900.ttf";
static const std::string VsCodeIconsPath = AssetFolderPath + "fonts/codicon.ttf";
static const std::string ShaderPath = AssetFolderPath + "shaders/";
static const std::string Version = "v0.1.0-pre0";
} | 50.785714 | 98 | 0.746835 |
5bb46f9c91e15b60088d82c8a990a990bcafd6c4 | 984 | h | C | idp/tstring.h | artar94/inno-download-plugin | d87573996fc05ae9b36aeeb0d7dd59104a601a78 | [
"Zlib"
] | 1 | 2020-03-17T21:56:25.000Z | 2020-03-17T21:56:25.000Z | idp/tstring.h | artar94/inno-download-plugin | d87573996fc05ae9b36aeeb0d7dd59104a601a78 | [
"Zlib"
] | 1 | 2022-02-03T16:12:36.000Z | 2022-02-03T16:12:36.000Z | idp/tstring.h | artar94/inno-download-plugin | d87573996fc05ae9b36aeeb0d7dd59104a601a78 | [
"Zlib"
] | 8 | 2019-06-30T07:50:07.000Z | 2022-02-02T23:19:48.000Z | #pragma once
#include <string>
#include <sstream>
#include <set>
#include <tchar.h>
using namespace std;
typedef basic_string<_TCHAR> tstring;
typedef basic_stringstream<_TCHAR> tstringstream;
string toansi(tstring s);
tstring tocurenc(string s);
tstring tstrlower(const _TCHAR *s);
tstring tstrprintf(tstring format, ...);
tstring itotstr(int d);
string dwtostr(unsigned long d);
tstring formatsize(unsigned long long size, tstring kb, tstring mb, tstring gb);
tstring formatsize(tstring ofmsg, unsigned long long size1, unsigned long long size2, tstring kb, tstring mb, tstring gb);
tstring formatspeed(unsigned long speed, tstring kbs, tstring mbs);
void tstringtoset(set<tstring> &stringset, tstring str, _TCHAR sep);
tstring addslash(tstring s);
tstring addbackslash(tstring s);
tstring encodeurl(tstring url);
tstring filenamefrompath(tstring url);
tstring filenamefromurl(tstring url);
#define STR(x) x ? x : const_cast<_TCHAR *>(_T(""))
| 32.8 | 123 | 0.751016 |
9da7ceced76821d9a2a7f7f6dc5e8ddef3cb6631 | 1,378 | c | C | chapter2/programs/byte-representation.c | rjseymour66/computersystems3e | 76fa72b3081fcee7da057703ba3e04cb0bc979d2 | [
"Multics"
] | null | null | null | chapter2/programs/byte-representation.c | rjseymour66/computersystems3e | 76fa72b3081fcee7da057703ba3e04cb0bc979d2 | [
"Multics"
] | null | null | null | chapter2/programs/byte-representation.c | rjseymour66/computersystems3e | 76fa72b3081fcee7da057703ba3e04cb0bc979d2 | [
"Multics"
] | null | null | null | #include <stdio.h>
typedef unsigned char *byte_pointer;
/* This is a pointer to an unsigned char.
typedef is a way to give a name to a data type.
Like declaring a variable, but uses the type name instead of a var name.*/
void test_show_bytes(int val);
void show_bytes(byte_pointer start, size_t len);
void show_int(int x);
void show_float(float x);
void show_pointer(void *x);
int main(void) {
test_show_bytes(12345, 6);
}
void test_show_bytes(int val) {
int ival = val;
float fval = val;
int *pval = &ival;
show_int(ival);
show_float(fval);
show_pointer(pval);
}
void show_bytes(byte_pointer start, size_t len)
{
int i;
for (i = 0; i < len; i++)
printf(" %.2x", start[i]);
printf("\n");
}
void show_int(int x)
{
printf("int:\t");
show_bytes((byte_pointer)&x, sizeof(int)); /* '&x' creates a pointer to the location */
} /* holding the object indicated by variable x */
void show_float(float x)
{
printf("float:\t");
show_bytes((byte_pointer)&x, sizeof(float)); /* sizeof(T) returns the number of bytes required to store */
} /* an object of type T */
void show_pointer(void *x)
{
printf("ptr:\t");
show_bytes((byte_pointer)&x, sizeof(void *)); /* void * is a special kind of pointer with no associated type info */
} | 26.5 | 119 | 0.623367 |
173873b0059987b85bd50ee2e1de5dbb0c46978e | 11,142 | c | C | net/oic/src/security/oc_acl.c | francois-berder/mynewt-core | d78860e3add3b8c4851503d83af2dcffd4b804b8 | [
"Apache-2.0"
] | 1 | 2018-06-19T23:56:53.000Z | 2018-06-19T23:56:53.000Z | net/oic/src/security/oc_acl.c | francois-berder/mynewt-core | d78860e3add3b8c4851503d83af2dcffd4b804b8 | [
"Apache-2.0"
] | null | null | null | net/oic/src/security/oc_acl.c | francois-berder/mynewt-core | d78860e3add3b8c4851503d83af2dcffd4b804b8 | [
"Apache-2.0"
] | null | null | null | /*
// Copyright (c) 2016 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#ifdef OC_SECURITY
#include "oc_acl.h"
#include "config.h"
#include "oc_api.h"
#include "oc_core_res.h"
#include "oc_dtls.h"
#include "oc_rep.h"
#include <stddef.h>
#include <strings.h>
#define MAX_NUM_RES_PERM_PAIRS \
(NUM_OC_CORE_RESOURCES + (MAX_NUM_SUBJECTS + 1) * (MAX_APP_RESOURCES))
OC_MEMB(ace_l, oc_sec_ace_t, MAX_NUM_SUBJECTS + 1);
OC_MEMB(res_l, oc_sec_acl_res_t, MAX_NUM_RES_PERM_PAIRS);
static oc_uuid_t WILDCARD = {.id = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0 } };
static oc_sec_acl_t ac_list = { 0 };
static void
get_sub_perm_groups(oc_sec_ace_t *ace, uint16_t *groups, int *n)
{
int i = 0, j;
oc_sec_acl_res_t *res = oc_list_head(ace->resources);
while (res != NULL) {
groups[i++] = res->permissions;
res = res->next;
}
for (i = 0; i < (*n - 1); i++) {
for (j = (i + 1); j < *n; j++) {
if (groups[i] > groups[j]) {
uint16_t t = groups[i];
groups[i] = groups[j];
groups[j] = t;
}
}
}
j = 0;
for (i = 1; i < *n; i++) {
if (groups[j] != groups[i])
groups[++j] = groups[i];
}
*n = j + 1;
}
void
oc_sec_encode_acl(void)
{
int i, n;
char uuid[37];
oc_rep_start_root_object();
oc_process_baseline_interface(oc_core_get_resource_by_index(OCF_SEC_ACL));
oc_rep_set_object(root, aclist);
oc_rep_set_array(aclist, aces);
oc_sec_ace_t *sub = oc_list_head(ac_list.subjects);
while (sub != NULL) {
if (strncmp(sub->subjectuuid.id, WILDCARD.id, 16) == 0) {
uuid[0] = '*';
uuid[1] = '\0';
} else {
oc_uuid_to_str(&sub->subjectuuid, uuid, 37);
}
LOG("oc_sec_acl_encode: subject %s\n", uuid);
n = oc_list_length(sub->resources);
uint16_t groups[n];
get_sub_perm_groups(sub, groups, &n);
for (i = 0; i < n; i++) {
oc_rep_object_array_start_item(aces);
oc_rep_set_text_string(aces, subjectuuid, uuid);
oc_rep_set_uint(aces, permission, groups[i]);
oc_rep_set_array(aces, resources);
oc_sec_acl_res_t *res = oc_list_head(sub->resources);
while (res != NULL) {
if (res->permissions == groups[i]) {
LOG("oc_sec_acl_encode: adding resource %s\n",
oc_string(res->resource->uri));
oc_rep_object_array_start_item(resources);
oc_rep_set_text_string(resources, href,
oc_string(res->resource->uri));
oc_rep_set_text_string(resources, rel, "");
oc_rep_set_text_string(resources, rt, "");
oc_rep_set_text_string(resources, if, "");
oc_rep_object_array_end_item(resources);
}
res = res->next;
}
oc_rep_close_array(aces, resources);
oc_rep_object_array_end_item(aces);
}
sub = sub->next;
}
oc_rep_close_array(aclist, aces);
oc_rep_close_object(root, aclist);
oc_uuid_to_str(&ac_list.rowneruuid, uuid, 37);
oc_rep_set_text_string(root, rowneruuid, uuid);
oc_rep_end_root_object();
}
static oc_sec_acl_res_t *
oc_sec_acl_get_ace(oc_uuid_t *subjectuuid, oc_resource_t *resource, bool create)
{
oc_sec_ace_t *ace = (oc_sec_ace_t *)oc_list_head(ac_list.subjects);
oc_sec_acl_res_t *res = NULL;
#ifdef DEBUG
char uuid[37];
oc_uuid_to_str(subjectuuid, uuid, 37);
#endif
while (ace != NULL) {
if (strncmp(ace->subjectuuid.id, subjectuuid->id, 16) == 0)
goto got_ace;
ace = oc_list_item_next(ace);
}
if (create)
goto new_ace;
LOG("Could not find ACE for subject %s\n", uuid);
goto done;
got_ace:
LOG("Found ACE for subject %s\n", uuid);
res = (oc_sec_acl_res_t *)oc_list_head(ace->resources);
while (res != NULL) {
if (res->resource == resource) {
LOG("Found permissions mask for resource %s in ACE\n",
oc_string(res->resource->uri));
goto done;
}
res = oc_list_item_next(res);
}
if (create)
goto new_res;
goto done;
new_ace:
ace = oc_memb_alloc(&ace_l);
if (!ace)
goto done;
LOG("Created new ACE for subject %s\n", uuid);
OC_LIST_STRUCT_INIT(ace, resources);
strncpy(ace->subjectuuid.id, subjectuuid->id, 16);
oc_list_add(ac_list.subjects, ace);
new_res:
res = oc_memb_alloc(&res_l);
if (res) {
res->resource = resource;
LOG("Adding new resource %s to ACE\n", oc_string(res->resource->uri));
oc_list_add(ace->resources, res);
}
done:
return res;
}
static bool
oc_sec_update_acl(oc_uuid_t *subjectuuid, oc_resource_t *resource,
uint16_t permissions)
{
oc_sec_acl_res_t *res = oc_sec_acl_get_ace(subjectuuid, resource, true);
if (!res)
return false;
res->permissions = permissions;
LOG("Added resource with permissions: %d\n", res->permissions);
return true;
}
void
oc_sec_acl_init(void)
{
OC_LIST_STRUCT_INIT(&ac_list, subjects);
}
void
oc_sec_acl_default(void)
{
bool success = true;
int i;
oc_resource_t *resource;
for (i = 0; i < NUM_OC_CORE_RESOURCES; i++) {
resource = oc_core_get_resource_by_index(i);
if (i < OCF_SEC_DOXM || i > OCF_SEC_CRED)
success &= oc_sec_update_acl(&WILDCARD, resource, 2);
else
success &= oc_sec_update_acl(&WILDCARD, resource, 6);
}
LOG("ACL for core resources initialized %d\n", success);
oc_uuid_t *device = oc_core_get_device_id(0);
memcpy(&ac_list.rowneruuid, device, sizeof(oc_uuid_t));
}
bool
oc_sec_check_acl(oc_method_t method, oc_resource_t *resource,
oc_endpoint_t *endpoint)
{
bool granted = false;
oc_sec_acl_res_t *res = NULL;
oc_uuid_t *identity = (oc_uuid_t *)oc_sec_dtls_get_peer_uuid(endpoint);
if (identity) {
res = oc_sec_acl_get_ace(identity, resource, false);
}
if (!res) { // Try Anonymous
res = oc_sec_acl_get_ace(&WILDCARD, resource, false);
}
if (!res)
return granted;
LOG("Got permissions mask %d\n", res->permissions);
if (res->permissions & OC_PERM_CREATE || res->permissions & OC_PERM_UPDATE) {
switch (method) {
case OC_PUT:
case OC_POST:
granted = true;
break;
default:
break;
}
}
if (res->permissions & OC_PERM_RETRIEVE ||
res->permissions & OC_PERM_NOTIFY) {
switch (method) {
case OC_GET:
granted = true;
break;
default:
break;
}
}
if (res->permissions & OC_PERM_DELETE) {
switch (method) {
case OC_DELETE:
granted = true;
break;
default:
break;
}
}
return granted;
}
bool
oc_sec_decode_acl(oc_rep_t *rep)
{
uint16_t permissions = 0;
oc_uuid_t subjectuuid;
oc_rep_t *resources = 0;
int len = 0;
while (rep != NULL) {
len = oc_string_len(rep->name);
switch (rep->type) {
case STRING:
if (len == 10 && strncmp(oc_string(rep->name), "rowneruuid", 10) == 0) {
oc_str_to_uuid(oc_string(rep->value_string), &ac_list.rowneruuid);
}
break;
case OBJECT: {
oc_rep_t *aclist = rep->value_object;
while (aclist != NULL) {
switch (aclist->type) {
case OBJECT_ARRAY: {
oc_rep_t *aces = aclist->value_object_array;
while (aces != NULL) {
oc_rep_t *ace = aces->value_object;
while (ace != NULL) {
len = oc_string_len(ace->name);
switch (ace->type) {
case STRING:
if (len == 11 &&
strncmp(oc_string(ace->name), "subjectuuid", 11) == 0) {
if (strncmp(oc_string(ace->value_string), "*", 1) == 0)
strncpy(subjectuuid.id, WILDCARD.id, 16);
else
oc_str_to_uuid(oc_string(ace->value_string), &subjectuuid);
}
break;
case INT:
if (len == 10 &&
strncmp(oc_string(ace->name), "permission", 10) == 0)
permissions = ace->value_int;
break;
case OBJECT_ARRAY:
if (len == 9 &&
strncmp(oc_string(ace->name), "resources", 9) == 0)
resources = ace->value_object_array;
break;
default:
break;
}
ace = ace->next;
}
while (resources != NULL) {
oc_rep_t *resource = resources->value_object;
while (resource != NULL) {
switch (resource->type) {
case STRING:
if (oc_string_len(resource->name) == 4 &&
strncasecmp(oc_string(resource->name), "href", 4) == 0) {
oc_resource_t *res = oc_core_get_resource_by_uri(
oc_string(resource->value_string));
#ifdef OC_SERVER
if (!res)
res = oc_ri_get_app_resource_by_uri(
oc_string(resource->value_string));
#endif /* OC_SERVER */
if (!res) {
LOG(
"\n\noc_sec_acl_decode: could not find resource %s\n\n",
oc_string(resource->value_string));
return false;
}
if (!oc_sec_update_acl(&subjectuuid, res, permissions)) {
LOG("\n\noc_sec_acl_decode: could not update ACE with "
"resource %s permissions\n\n",
oc_string(res->uri));
return false;
}
}
break;
default:
break;
}
resource = resource->next;
}
resources = resources->next;
}
aces = aces->next;
}
} break;
default:
break;
}
aclist = aclist->next;
}
} break;
default:
break;
}
rep = rep->next;
}
return true;
}
/*
{
"aclist":
{
"aces":
[
{
"subjectuuid": "61646d69-6e44-6576-6963-655575696430",
"resources":
[
{"href": "/led/1", "rel": "", "rt": "", "if": ""},
{"href": "/switch/1", "rel": "", "rt": "", "if": ""}
],
"permission": 31
}
]
},
"rowneruuid": "5cdf40b1-c12e-432b-67a2-aa79a3f08c59"
}
*/
void
post_acl(oc_request_t *request, oc_interface_mask_t interface)
{
if (oc_sec_decode_acl(request->request_payload))
oc_send_response(request, OC_STATUS_CREATED);
else
oc_send_response(request, OC_STATUS_INTERNAL_SERVER_ERROR);
}
#endif /* OC_SECURITY */
| 26.978208 | 80 | 0.577455 |
c09fc30f22875c0d9e8ca5054c35956647ad1e72 | 4,785 | c | C | liba/test/math.c | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,442 | 2017-08-28T19:39:45.000Z | 2022-03-30T00:56:14.000Z | liba/test/math.c | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,321 | 2017-08-28T23:03:10.000Z | 2022-03-31T19:32:17.000Z | liba/test/math.c | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 421 | 2017-08-28T22:02:39.000Z | 2022-03-28T20:52:21.000Z | // This file tests that each math fuction links.
#include <math.h>
int test_fpclassifyf(float x) { return fpclassify(x); }
int test_signbitf(float x) { return signbit(x); }
int test_finitef(float x) { return finite(x); }
int test_isfinitef(float x) { return isfinite(x); }
int test_isnormalf(float x) { return isnormal(x); }
int test_isnanf(float x) { return isnan(x); }
int test_isinff(float x) { return isinf(x); }
float test_acosf(float x) { return acosf(x); }
float test_acoshf(float x) { return acoshf(x); }
float test_asinf(float x) { return asinf(x); }
float test_asinhf(float x) { return asinhf(x); }
float test_atanf(float x) { return atanf(x); }
float test_atan2f(float y, float x) { return atan2f(y, x); }
float test_atanhf(float x) { return atanhf(x); }
float test_ceilf(float x) { return ceilf(x); }
float test_copysignf(float x, float y) { return copysignf(x, y); }
float test_cosf(float x) { return cosf(x); }
float test_coshf(float x) { return coshf(x); }
float test_expf(float x) { return expf(x); }
float test_expm1f(float x) { return expm1f(x); }
float test_fabsf(float x) { return fabsf(x); }
float test_floorf(float x) { return floorf(x); }
float test_fmodf(float x, float y) { return fmodf(x, y); }
float test_frexpf(float x, int *exp) { return frexpf(x, exp); }
float test_ldexpf(float x, int exp) { return ldexpf(x, exp); }
float test_lgammaf(float x) { return lgammaf(x); }
float test_lgammaf_r(float x, int *signgamp) { return lgammaf_r(x, signgamp); }
float test_log1pf(float x) { return log1pf(x); }
float test_log10f(float x) { return log10f(x); }
float test_logf(float x) { return logf(x); }
float test_modff(float x, float *iptr) { return modff(x, iptr); }
float test_nanf(const char *s) { return nanf(s); }
float test_nearbyintf(float x) { return nearbyintf(x); }
float test_powf(float x, float y) { return powf(x, y); }
float test_roundf(float x) { return roundf(x); }
float test_scalbnf(float x, int exp) { return scalbnf(x, exp); }
float test_sinf(float x) { return sinf(x); }
float test_sinhf(float x) { return sinhf(x); }
float test_sqrtf(float x) { return sqrtf(x); }
float test_tanf(float x) { return tanf(x); }
float test_tanhf(float x) { return tanhf(x); }
float test_truncf(float x) { return truncf(x); }
int test_fpclassify(double x) { return fpclassify(x); }
int test_signbit(double x) { return signbit(x); }
int test_finite(double x) { return finite(x); }
int test_isfinite(double x) { return isfinite(x); }
int test_isnormal(double x) { return isnormal(x); }
int test_isnan(double x) { return isnan(x); }
int test_isinf(double x) { return isinf(x); }
double test_acos(double x) { return acos(x); }
double test_acosh(double x) { return acosh(x); }
double test_asin(double x) { return asin(x); }
double test_asinh(double x) { return asinh(x); }
double test_atan(double x) { return atan(x); }
double test_atan2(double y, double x) { return atan2(y, x); }
double test_atanh(double x) { return atanh(x); }
double test_ceil(double x) { return ceil(x); }
double test_copysign(double x, double y) { return copysign(x, y); }
double test_cos(double x) { return cos(x); }
double test_cosh(double x) { return cosh(x); }
double test_erf(double x) { return erf(x); }
double test_erfc(double x) { return erfc(x); }
double test_exp(double x) { return exp(x); }
double test_expm1(double x) { return expm1(x); }
double test_fabs(double x) { return fabs(x); }
double test_floor(double x) { return floor(x); }
double test_fmod(double x, double y) { return fmod(x, y); }
double test_frexp(double x, int *exp) { return frexp(x, exp); }
double test_ldexp(double x, int exp) { return ldexp(x, exp); }
double test_lgamma(double x) { return lgamma(x); }
double test_lgamma_r(double x, int *signgamp) { return lgamma_r(x, signgamp); }
double test_log(double x) { return log(x); }
double test_log1p(double x) { return log1p(x); }
double test_log10(double x) { return log10(x); }
double test_log2(double x) { return log2(x); }
double test_logb(double x) { return logb(x); }
double test_modf(double x, double *iptr) { return modf(x, iptr); }
double test_nan(const char *s) { return nan(s); }
double test_nearbyint(double x) { return nearbyint(x); }
double test_pow(double x, double y) { return pow(x, y); }
double test_rint(double x) { return rint(x); }
double test_round(double x) { return round(x); }
double test_scalb(double x, double exp) { return scalb(x, exp); }
double test_scalbn(double x, int exp) { return scalbn(x, exp); }
double test_sin(double x) { return sin(x); }
double test_sinh(double x) { return sinh(x); }
double test_sqrt(double x) { return sqrt(x); }
double test_tan(double x) { return tan(x); }
double test_tanh(double x) { return tanh(x); }
double test_tgamma(double x) { return tgamma(x); }
double test_trunc(double x) { return trunc(x); }
| 48.826531 | 79 | 0.70721 |
8d8fe820b767667f311cc970e27ea63367a9a52f | 463 | h | C | ofdEditor/model/Doc/DocBasicTypes.h | mcoder2014/ofdEditor | c241f69447992cacb29d4ddae17fa4d7abd76b21 | [
"MIT"
] | 30 | 2018-09-27T09:26:57.000Z | 2022-03-31T01:45:20.000Z | ofdEditor/model/Doc/DocBasicTypes.h | mcoder2014/ofdEditor | c241f69447992cacb29d4ddae17fa4d7abd76b21 | [
"MIT"
] | 1 | 2019-09-06T04:54:16.000Z | 2019-09-06T04:54:16.000Z | ofdEditor/model/Doc/DocBasicTypes.h | mcoder2014/ofdEditor | c241f69447992cacb29d4ddae17fa4d7abd76b21 | [
"MIT"
] | 15 | 2018-04-23T02:49:20.000Z | 2021-09-27T03:06:55.000Z | #ifndef DOCBASICTYPES_H
#define DOCBASICTYPES_H
#include "model_global.h"
/**
* @Author Chaoqun
* @brief 功能同 ST_Box
* @date 2017/04/30
*/
class MODELSHARED_EXPORT DocBox
{
public:
double x;
double y;
double width;
double height;
void set(double x, double y,double width, double height)
{
this->x = x;
this->y = y;
this->width = width;
this->height = height;
}
};
#endif // DOCBASICTYPES_H
| 14.46875 | 60 | 0.602592 |
a5c90a0b57d8cc0610d0026ae8bc9361daf57958 | 3,157 | h | C | lib/slice.h | tamiel/iaxclient | 81118fb53dad108fd775c656b5f0572d83e9d052 | [
"Unlicense"
] | 3 | 2015-05-26T02:19:18.000Z | 2018-05-08T12:04:06.000Z | lib/slice.h | mike-plivo/iaxclient | 81118fb53dad108fd775c656b5f0572d83e9d052 | [
"Unlicense"
] | null | null | null | lib/slice.h | mike-plivo/iaxclient | 81118fb53dad108fd775c656b5f0572d83e9d052 | [
"Unlicense"
] | 2 | 2016-11-27T17:34:02.000Z | 2018-05-08T12:04:15.000Z | /*
* iaxclient: a portable telephony toolkit
*
* Copyright (C) 2007, Wimba, Inc.
*
* Mihai Balea <mihai at hates dot ms>
*
* This program is free software, distributed under the terms of
* the GNU Lesser (Library) General Public License
*
* A codec independent frame slicer/assembler library
*/
/*
* This API can be used with codecs that do not provide internal support for
* splitting encoded frames in arbitrary-sized slices. This is useful for
* things like transmitting encoded frame over size constained packet
* protocols such as UDP.
*
* The slicer adds 6 bytes at the beginning of each slice. The
* format of this header is :
* - version: right now, first bit should be 0, the rest are undefined
*
* - source id: 2 bytes random number used to identify stream changes in
* conference applications this number is transmitted in big endian
* format over the wire
*
* - frame index number - used to detect a new frame when some of the
* slices of the current frame are missing (only the least significant
* 4 bits are used)
*
* - index of slice in the frame, starting at 0
*
* - total number of slices in the frame
*
*/
#ifndef __SLICE_H__
#define __SLICE_H__
#include "iaxclient_lib.h"
#define MAX_ENCODED_FRAME_SIZE 48 * 1024
struct slicer_context
{
unsigned char frame_index;
unsigned short source_id;
unsigned int slice_size;
};
struct deslicer_context
{
unsigned char frame_index;
unsigned char slice_count;
int frame_size;
unsigned short source_id;
unsigned int slice_size;
int frame_complete;
char buffer[MAX_ENCODED_FRAME_SIZE];
};
/*
* Allocates and initializes a slicer context with the given souirce_id
*/
struct slicer_context * create_slicer_context(unsigned short source_id, unsigned int slice_size);
/*
* Deallocates a slicer_context
*/
int free_slicer_context(struct slicer_context *sc);
/*
* Fragments a frame into one or several slices
* data - frame data
* size - size of frame data
* slice-set - pointer to a preallocated structure that will hold slices and slice information
* sc - holds stream information such as source id and frame index
* Returns 0 if completed successfully or a negative value if failure.
*/
int slice(const char *data,
unsigned int size,
struct slice_set_t *slice_set,
struct slicer_context *sc
);
/*
* Allocates and initializes a deslicer context with the given souirce_id
*/
struct deslicer_context * create_deslicer_context(unsigned int slice_size);
/*
* Deallocates a slicer_context
*/
int free_deslicer_context(struct deslicer_context *dsc);
/*
* Assembles one frame out of multiple slices
* in - slice data
* inlen - length of slice
* outlen - length of assembled frame
* dsc - holds stream information
* Returns NULL if there is an error or the current frame is incomplete
* Returns a pointer to a buffer containing the completed frame and updates
* outlen with the frame size if successful
*/
char *
deslice(const char *in, int inlen, int *outlen, struct deslicer_context *dsc);
#endif
| 28.7 | 97 | 0.720621 |
85e4b0503c6fcc01d98372a49103ef1bc13f147f | 10,132 | c | C | src/dns/server.c | stsaz/fencedns | 5168d2acffb43cad225cc06dc1b7ad83a4c69c3e | [
"BSD-2-Clause"
] | null | null | null | src/dns/server.c | stsaz/fencedns | 5168d2acffb43cad225cc06dc1b7ad83a4c69c3e | [
"BSD-2-Clause"
] | null | null | null | src/dns/server.c | stsaz/fencedns | 5168d2acffb43cad225cc06dc1b7ad83a4c69c3e | [
"BSD-2-Clause"
] | null | null | null | /** fencedns: DNS server
2020, Simon Zolin */
#include <fencedns.h>
#include <dns/dnsmod.h>
#include <FF/net/url.h>
#include <FFOS/signal.h>
#include <FFOS/timer.h>
#include <ffbase/vector.h>
#include <ffbase/map.h>
struct dns_conf {
ffsockaddr bind;
ffbyte block_aaaa;
ffuint block_ttl;
ffuint block_mode; // enum BLOCK_MODE
ffuint timer_resolution;
};
struct dnsmod {
struct dns_conf conf;
ffvec inbuf;
ffuint client_uid;
fftimer timer_fd;
fftimerqueue timerq;
ffkevent2 timer_kev;
fdns_async_func task_func;
void *task_param;
ffkq kq;
ffsock sk;
ffkevent2 server_kev;
ffmap clients; // qid -> client*
ffuint64 in_reqs, in_data, out_data;
ffkq_postevent postev;
ffkevent2 postev_kev;
ffuint stop;
ffuint sig_reconfig;
ffuint sig_clear;
ffuint sig_task;
};
static struct dnsmod *g;
static fdns_core *core;
fdns_core dns_core;
#define fatal(...) core->log(LOG_FATAL, __VA_ARGS__)
#define error(...) core->log(LOG_ERROR, __VA_ARGS__)
#define warning(...) core->log(LOG_WARNING, __VA_ARGS__)
#define info(...) core->log(LOG_INFO, __VA_ARGS__)
#define verbose(...) core->log(LOG_VERBOSE, __VA_ARGS__)
#define debug(...) core->log(LOG_DEBUG, __VA_ARGS__)
#include <dns/client.h>
int conf_bind(ffconf_scheme *cs, void *obj, ffstr *val)
{
if (0 != ffsockaddr_fromstr(&g->conf.bind, val->ptr, val->len, 53))
return FFCONF_EBADVAL;
return 0;
}
int conf_block_mode(ffconf_scheme *cs, void *obj, ffstr *val)
{
// enum BLOCK_MODE
static const char *const blockmode_str[] = {
"nxdomain",
"refused",
"empty",
"null_ip",
"local_ip",
"drop",
};
int i = ffszarr_find(blockmode_str, FF_COUNT(blockmode_str), val->ptr, val->len);
if (i < 0)
return FFCONF_EBADVAL;
g->conf.block_mode = i;
return 0;
}
int conf_cache(ffconf_scheme *cs, void *obj)
{
const ffconf_arg *conf_args;
void *conf_obj;
cache_mod.conf(&dns_core, &conf_args, &conf_obj);
ffconf_scheme_addctx(cs, conf_args, conf_obj);
return 0;
}
int conf_hosts(ffconf_scheme *cs, void *obj)
{
const ffconf_arg *conf_args;
void *conf_obj;
hosts_mod.conf(&dns_core, &conf_args, &conf_obj);
ffconf_scheme_addctx(cs, conf_args, conf_obj);
return 0;
}
int conf_upstream(ffconf_scheme *cs, void *obj)
{
const ffconf_arg *conf_args;
void *conf_obj;
upstream_mod.conf(&dns_core, &conf_args, &conf_obj);
ffconf_scheme_addctx(cs, conf_args, conf_obj);
return 0;
}
const ffconf_arg dns_args[] = {
{ "bind", FFCONF_TSTR, (ffsize)conf_bind },
{ "block_ttl", FFCONF_TINT32, FF_OFF(struct dns_conf, block_ttl) },
{ "block_aaaa", FFCONF_TBOOL8, FF_OFF(struct dns_conf, block_aaaa) },
{ "block_mode", FFCONF_TSTR, (ffsize)conf_block_mode },
{ "cache", FFCONF_TOBJ, (ffsize)conf_cache },
{ "hosts", FFCONF_TOBJ, (ffsize)conf_hosts },
{ "upstream", FFCONF_TOBJ, (ffsize)conf_upstream },
{ "timer_resolution_msec", FFCONF_TINT32, FF_OFF(struct dns_conf, timer_resolution) },
{},
};
int map_keyeq(void *opaque, const void *key, ffsize keylen, void *val)
{
(void)opaque;
FF_ASSERT(keylen == 2);
ffushort id = *(ffushort*)key;
const struct client *c = val;
return (id == c->req.h.id);
}
void srv_read_process(struct dnsmod *s);
void tmr_process(struct dnsmod *s);
void postev_process(struct dnsmod *s);
int lisn_init(struct dnsmod *s)
{
s->sk = ffsock_create_udp(AF_INET, FFSOCK_NONBLOCK);
if (s->sk == FFSOCK_NULL) {
fatal("ffsock_create_udp: %E", fferr_last());
return -1;
}
int r = ffsock_bind(s->sk, &s->conf.bind);
if (r < 0) {
fatal("ffsock_bind: %E", fferr_last());
return -1;
}
s->server_kev.func = (ffkevent_func)srv_read_process;
s->server_kev.param = s;
if (0 != ffkq_attach_socket(s->kq, s->sk, &s->server_kev, FFKQ_READ)) {
fatal("ffkq_attach_socket: %E", fferr_last());
return -1;
}
ffuint port = 0;
ffsockaddr_ip_port(&s->conf.bind, &port);
debug("listening on %d", port);
return 0;
}
int srv_prepare(struct dnsmod *s)
{
ffmap_init(&s->clients, map_keyeq);
ffvec_reallocT(&s->inbuf, 4*1024, char);
if (FFTIMER_NULL == (s->timer_fd = fftimer_create(0))) {
fatal("fftimer_create: %E", fferr_last());
return -1;
}
fftimerqueue_init(&s->timerq);
s->kq = ffkq_create();
if (s->kq == FFKQ_NULL) {
fatal("ffkq_create: %E", fferr_last());
return -1;
}
s->postev = ffkq_post_attach(s->kq, &g->postev_kev);
if (s->postev == FFKQ_NULL) {
fatal("ffkq_post_attach: %E", fferr_last());
return -1;
}
s->postev_kev.func = (ffkevent_func)postev_process;
s->postev_kev.param = s;
dns_core.kq = s->kq;
s->timer_kev.func = (ffkevent_func)tmr_process;
s->timer_kev.param = s;
if (0 != fftimer_start(s->timer_fd, g->kq, &s->timer_kev, s->conf.timer_resolution)) {
fatal("fftimer_start: %E", fferr_last());
return -1;
}
if (0 != lisn_init(s))
return -1;
return 0;
}
void srv_close(struct dnsmod *s)
{
ffkq_post_detach(s->postev, s->kq); s->postev = FFKQ_NULL;
ffkq_close(s->kq); s->kq = FFKQ_NULL;
ffsock_close(s->sk); s->sk = FFSOCK_NULL;
ffvec_free(&s->inbuf);
struct _ffmap_item *it;
FFMAP_WALK(&s->clients, it) {
if (!_ffmap_item_occupied(it))
continue;
struct client *c = it->val;
cl_free(c);
}
ffmap_free(&s->clients);
}
void cl_start(struct dnsmod *s, ffstr data, ffsockaddr *peer)
{
struct client *c = ffmem_new(struct client);
c->srv = s;
ffuint uid = ++s->client_uid;
c->uid.ptr = c->uid_s;
c->uid.len = ffs_format(c->uid_s, sizeof(c->uid_s), "*%u", uid);
c->peer = *peer;
c->reqbuf = data;
cl_conveyer(c);
}
void srv_addclient(struct dnsmod *s, ffuint id, struct client *c)
{
ffushort qid = id;
ffmap_add(&s->clients, &qid, 2, c);
c->in_list = 1;
debug("srv: added client %u 0x%p [%L]", id, c, s->clients.len);
}
void srv_rmclient(struct dnsmod *s, ffuint id, struct client *c)
{
if (!c->in_list)
return;
ffushort qid = id;
ffuint hash = ffmap_hash(&qid, 2);
if (0 == ffmap_rm_hash(&s->clients, hash, c))
debug("srv: removed client %u 0x%p [%L]", id, c, s->clients.len);
}
struct client* srv_findclient(struct dnsmod *s, ffuint id)
{
ffushort qid = id;
struct client *c = ffmap_find(&s->clients, &qid, 2, NULL);
if (c == NULL)
warning("upstream: no client with ID %u", id);
return c;
}
int srv_read_process1(struct dnsmod *s)
{
ffsockaddr peer;
int r = ffsock_recvfrom(s->sk, s->inbuf.ptr, 4*1024, 0, &peer);
if (r < 0) {
if (!fferr_again(fferr_last()))
error("ffsock_recvfrom: %E", fferr_last());
return -1;
}
s->in_reqs++;
ffstr data;
ffstr_set(&data, s->inbuf.ptr, r);
ffvec_null(&s->inbuf);
cl_start(s, data, &peer);
ffvec_reallocT(&s->inbuf, 4*1024, char);
return 0;
}
void srv_read_process(struct dnsmod *s)
{
for (;;) {
int r = srv_read_process1(s);
if (r < 0)
break;
}
}
void tmr_process(struct dnsmod *s)
{
fftimer_consume(s->timer_fd);
fftime now = core->time(FDNS_TIME_MONO, NULL);
ffuint msec = fftime_to_msec(&now);
fftimerqueue_process(&s->timerq, msec);
}
void postev_process(struct dnsmod *s)
{
ffkq_post_consume(s->postev);
if (g->sig_reconfig) {
g->sig_reconfig = 0;
hosts_mod.sig(FDNS_SIG_RECONFIG);
}
if (g->sig_clear) {
g->sig_clear = 0;
cache_mod.sig(FDNS_SIG_CLEAR);
}
if (g->sig_task) {
g->sig_task = 0;
debug("dns: executing task %p %p", g->task_func, g->task_param);
g->task_func(g->task_param);
}
}
int srv_work(struct dnsmod *s)
{
ffkq_event ev[8];
ffkq_time t;
ffkq_time_set(&t, -1);
debug("entering kqueue loop");
while (!s->stop) {
int r = ffkq_wait(s->kq, ev, FF_COUNT(ev), t);
if (r < 0) {
if (fferr_last() == EINTR)
continue;
fatal("ffkq_wait: %E", fferr_last());
return -1;
}
for (int i = 0; i != r; i++) {
void *d = ffkq_event_data(&ev[i]);
ffkevent2 *kev = d;
kev->func(kev->param);
}
}
debug("leaving kqueue loop");
return 0;
}
int mods_sig(int sig)
{
if (0 != cache_mod.sig(sig))
return -1;
if (0 != hosts_mod.sig(sig))
return -1;
if (0 != upstream_mod.sig(sig))
return -1;
return 0;
}
int dns_start(struct dnsmod *s)
{
if (0 != srv_prepare(s))
return -1;
if (mods_sig(FDNS_SIG_START))
return -1;
srv_read_process(s);
if (0 != srv_work(s))
return -1;
return 0;
}
void srv_init(struct dnsmod *s)
{
s->sk = FFSOCK_NULL;
s->kq = FFKQ_NULL;
ffsockaddr_set_ipv4(&s->conf.bind, NULL, 53);
s->conf.block_aaaa = 1;
s->conf.block_mode = BLOCK_MODE_LOCALIP;
s->conf.block_ttl = 60;
s->conf.timer_resolution = 100;
}
void srv_conf(fdns_core *_core, const ffconf_arg **conf_args, void **conf_obj)
{
core = _core;
dns_core.full_path = core->full_path;
dns_core.time = core->time;
dns_core.log = core->log;
dns_core.log_level = core->log_level;
g = ffmem_new(struct dnsmod);
srv_init(g);
*conf_args = dns_args;
*conf_obj = &g->conf;
}
int dns_sig(int sig)
{
switch (sig) {
case FDNS_SIG_INIT:
break;
case FDNS_SIG_START:
return dns_start(g);
case FDNS_SIG_STOP:
g->stop = 1;
ffkq_post(g->postev, &g->postev_kev);
break;
case FDNS_SIG_RECONFIG:
g->sig_reconfig = 1;
ffkq_post(g->postev, &g->postev_kev);
break;
case FDNS_SIG_CLEAR:
g->sig_clear = 1;
ffkq_post(g->postev, &g->postev_kev);
break;
case FDNS_SIG_DESTROY:
mods_sig(FDNS_SIG_DESTROY);
srv_close(g);
ffmem_free(g); g = NULL;
break;
default:
return -1;
}
return 0;
}
struct fdns_mod dns_mod = {
"dns",
srv_conf,
dns_sig,
};
int dns_core_cmd(int cmd, ...)
{
return 0;
}
int dns_core_task(fdns_async_func func, void *param)
{
g->task_func = func;
g->task_param = param;
g->sig_task = 1;
ffkq_post(g->postev, &g->postev_kev);
debug("dns: added task %p %p", func, param);
return 0;
}
int dns_core_timer(fdns_timer *t, int interval_msec, fdns_async_func func, void *param)
{
if (interval_msec == 0) {
fftimerqueue_remove(&g->timerq, t);
debug("dns: removed timer %p [%L]", t, g->timerq.tree.len);
return 0;
}
fftime now = core->time(FDNS_TIME_MONO, NULL);
ffuint msec = fftime_to_msec(&now);
fftimerqueue_add(&g->timerq, t, msec, interval_msec, func, param);
debug("dns: added timer %p %d %p(%p) [%L]"
, t, interval_msec, func, param, g->timerq.tree.len);
return 0;
}
fdns_core dns_core = {
0, 0,
dns_core_cmd, NULL, dns_core_task, dns_core_timer, NULL, NULL, NULL,
};
| 21.330526 | 87 | 0.672819 |
12888a0cdc63d9ae3c3318b7ec0df75bd61f2637 | 105 | h | C | core/rpc.h | dxtr/bitc | 5e093d23b19c11f479d1b3492e4b7e26e1ae828a | [
"MIT"
] | 76 | 2015-02-03T14:23:42.000Z | 2021-07-11T06:07:33.000Z | core/rpc.h | mooncoindev/moonterm | 0fbbba868c4adfb9e1342a725449889c9101f978 | [
"MIT"
] | 8 | 2015-04-06T18:52:30.000Z | 2020-03-19T20:30:27.000Z | core/rpc.h | mooncoindev/moonterm | 0fbbba868c4adfb9e1342a725449889c9101f978 | [
"MIT"
] | 20 | 2015-01-09T13:05:46.000Z | 2021-04-04T17:23:31.000Z | #ifndef __RPC_H__
#define __RPC_H__
int rpc_init(void);
void rpc_exit(void);
#endif /* __RPC_H__ */
| 10.5 | 22 | 0.714286 |
4216139ba166cb8d727487513c3b5d17e4161e8a | 801 | c | C | uart.c | dsprenkels/liftlighter | ffeacc9d8aaeae9622322ca67a5be6638c5e3b5e | [
"MIT"
] | null | null | null | uart.c | dsprenkels/liftlighter | ffeacc9d8aaeae9622322ca67a5be6638c5e3b5e | [
"MIT"
] | null | null | null | uart.c | dsprenkels/liftlighter | ffeacc9d8aaeae9622322ca67a5be6638c5e3b5e | [
"MIT"
] | null | null | null | #include "uart.h"
#include <avr/io.h>
#include <unistd.h>
void UART_init()
{
// Set double speed mode
UCSRA |= (1 << U2X);
// Set baud rate to 9600
UBRRH = 0;
UBRRL = 12;
// Enable transmissions
UCSRB = 1 << TXEN;
// Set frame format
UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0);
}
void UART_transmit(uint8_t data)
{
// Wait for empty transmit buffer
while ( !(UCSRA & (1<<UDRE)) );
// Put data into buffer, send the character
UDR = data;
}
void UART_send_buf(uint8_t *buf, size_t len)
{
for (size_t i = 0; i < len; i++) {
UART_transmit(buf[i]);
}
}
void UART_send_str(char *str) {
for (size_t i = 0; str[i] != '\0'; i++) {
UART_transmit(str[i]);
}
}
void UART_send_strn(char *str, size_t n) {
for (size_t i = 0; str[i] != '\0' && i < n; i++) {
UART_transmit(str[i]);
}
}
| 16.6875 | 51 | 0.596754 |
eb31bb23bd84de40ea7eb82bcb16064bb177a4f0 | 2,118 | h | C | src/75322/cont_mode_lib/src/trig_data.h | melexis/mlx75322-spi-driver | 5ffbf0f981643827c7a0beebf50cc93d15e55ccd | [
"Apache-2.0"
] | null | null | null | src/75322/cont_mode_lib/src/trig_data.h | melexis/mlx75322-spi-driver | 5ffbf0f981643827c7a0beebf50cc93d15e55ccd | [
"Apache-2.0"
] | 1 | 2020-02-21T13:24:02.000Z | 2020-02-21T13:24:02.000Z | src/75322/cont_mode_lib/src/trig_data.h | melexis/mlx75322-spi-driver | 5ffbf0f981643827c7a0beebf50cc93d15e55ccd | [
"Apache-2.0"
] | null | null | null | /**
* @file
* @brief SPI driver for MLX75322 Continuous mode support
* @internal
*
* @copyright (C) 2019 Melexis N.V.
*
* Melexis N.V. is supplying this code for use with Melexis N.V. processor based microcontrollers only.
*
* THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. MELEXIS N.V. SHALL NOT IN ANY CIRCUMSTANCES,
* BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*
* @endinternal
*
* @defgroup spi_cont_get_data SPI driver continuous mode data acquisition thread
* @ingroup spi_cont_mode
*
* @details provides the driven continuous mode thread, which drives the data acquisition process - calls the driver's
* data to get the data, forms the scene's data and provides it to the callers side. This thread is driven by
* the major thread, using messages queue.
*
*/
#ifndef TRIG_DATA_H
#define TRIG_DATA_H
/** @{*/
#ifdef __cplusplus
extern "C"
{
#endif
/** Initiates the trigger data thread
* This function creates a trigger data thread and starts it waiting for data requests
* @note This function is normally driven from the continuous mode library
*/
void spiDriver_InitTrigData(void);
/** Runs the trigger data thread
* This function sends a message to a trigger thread to start waiting for request messages
* @note This function is normally driven from the continuous mode library
*/
void spiDriver_RunTrigData(void);
/** Stops the trigger data thread
* This function sends a message to a trigger thread to stop waiting for request messages
* @note This function is normally driven from the continuous mode library
*/
void spiDriver_StopTrigData(void);
/** Exits the trigger data thread
* This function sends a message to finish the trigger thread
* @note This function is normally driven from the continuous mode library
*/
void spiDriver_ExitTrigData(void);
#ifdef __cplusplus
}
#endif
/** @}*/
#endif /* TRIG_DATA_H */
| 31.147059 | 118 | 0.746931 |
3a94902a017074f938a775fc22b5569d97d67ee5 | 14,434 | h | C | src/masternodes/poolpairs.h | asyrafnorafandi/ain | ab0b60686c39b45d2241dd807cbd6ce22c096188 | [
"MIT"
] | null | null | null | src/masternodes/poolpairs.h | asyrafnorafandi/ain | ab0b60686c39b45d2241dd807cbd6ce22c096188 | [
"MIT"
] | null | null | null | src/masternodes/poolpairs.h | asyrafnorafandi/ain | ab0b60686c39b45d2241dd807cbd6ce22c096188 | [
"MIT"
] | null | null | null | // Copyright (c) 2020 The DeFi Foundation
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DEFI_MASTERNODES_POOLPAIRS_H
#define DEFI_MASTERNODES_POOLPAIRS_H
#include <flushablestorage.h>
#include <amount.h>
#include <arith_uint256.h>
#include <masternodes/res.h>
#include <script/script.h>
#include <serialize.h>
#include <uint256.h>
#include <masternodes/balances.h>
struct ByPairKey {
DCT_ID idTokenA;
DCT_ID idTokenB;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(VARINT(idTokenA.v));
READWRITE(VARINT(idTokenB.v));
}
};
struct PoolPrice {
int64_t integer;
int64_t fraction;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(integer);
READWRITE(fraction);
}
};
struct CPoolSwapMessage {
CScript from, to;
DCT_ID idTokenFrom, idTokenTo;
CAmount amountFrom;
PoolPrice maxPrice;
std::string ToString() const {
return "(" + from.GetHex() + ":" + std::to_string(amountFrom) +"@"+ idTokenFrom.ToString() + "->" + to.GetHex() + ":?@" + idTokenTo.ToString() +")";
}
ADD_SERIALIZE_METHODS
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(from);
READWRITE(VARINT(idTokenFrom.v));
READWRITE(amountFrom);
READWRITE(to);
READWRITE(VARINT(idTokenTo.v));
READWRITE(maxPrice);
}
};
struct CPoolPairMessage {
DCT_ID idTokenA, idTokenB;
CAmount commission; // comission %% for traders
CScript ownerAddress;
bool status = true;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(VARINT(idTokenA.v));
READWRITE(VARINT(idTokenB.v));
READWRITE(commission);
READWRITE(ownerAddress);
READWRITE(status);
}
};
class CPoolPair : public CPoolPairMessage
{
public:
static const CAmount MINIMUM_LIQUIDITY = 1000;
static const CAmount SLOPE_SWAP_RATE = 1000;
static const uint32_t PRECISION = (uint32_t) COIN; // or just PRECISION_BITS for "<<" and ">>"
CPoolPair(CPoolPairMessage const & msg = {})
: CPoolPairMessage(msg)
, reserveA(0)
, reserveB(0)
, totalLiquidity(0)
, blockCommissionA(0)
, blockCommissionB(0)
, rewardPct(0)
, swapEvent(false)
, creationTx()
, creationHeight(-1)
{}
virtual ~CPoolPair() = default;
CAmount reserveA, reserveB, totalLiquidity;
CAmount blockCommissionA, blockCommissionB;
CAmount rewardPct; // pool yield farming reward %%
bool swapEvent = false;
uint256 creationTx;
uint32_t creationHeight;
// 'amountA' && 'amountB' should be normalized (correspond) to actual 'tokenA' and 'tokenB' ids in the pair!!
// otherwise, 'AddLiquidity' should be () external to 'CPairPool' (i.e. CPoolPairView::AddLiquidity(TAmount a,b etc) with internal lookup of pool by TAmount a,b)
Res AddLiquidity(CAmount amountA, CAmount amountB, CScript const & shareAddress, std::function<Res(CScript const & to, CAmount liqAmount)> onMint, bool slippageProtection = false) {
// instead of assertion due to tests
if (amountA <= 0 || amountB <= 0) {
return Res::Err("amounts should be positive");
}
CAmount liquidity{0};
if (totalLiquidity == 0) {
liquidity = (CAmount) (arith_uint256(amountA) * arith_uint256(amountB)).sqrt().GetLow64(); // sure this is below std::numeric_limits<CAmount>::max() due to sqrt natue
if (liquidity <= MINIMUM_LIQUIDITY) // ensure that it'll be non-zero
return Res::Err("liquidity too low");
liquidity -= MINIMUM_LIQUIDITY;
// MINIMUM_LIQUIDITY is a hack for non-zero division
totalLiquidity = MINIMUM_LIQUIDITY;
} else {
CAmount liqA = (arith_uint256(amountA) * arith_uint256(totalLiquidity) / reserveA).GetLow64();
CAmount liqB = (arith_uint256(amountB) * arith_uint256(totalLiquidity) / reserveB).GetLow64();
liquidity = std::min(liqA, liqB);
if (liquidity == 0)
return Res::Err("amounts too low, zero liquidity");
if(slippageProtection) {
if ((std::max(liqA, liqB) - liquidity) * 100 / liquidity >= 3) {
return Res::Err("Exceeds max ratio slippage protection of 3%%");
}
}
}
// increasing totalLiquidity
auto resTotal = SafeAdd(totalLiquidity, liquidity);
if (!resTotal.ok) {
return Res::Err("can't add %d to totalLiquidity: %s", liquidity, resTotal.msg);
}
totalLiquidity = *resTotal.val;
// increasing reserves
auto resA = SafeAdd(reserveA, amountA);
auto resB = SafeAdd(reserveB, amountB);
if (resA.ok && resB.ok) {
reserveA = *resA.val;
reserveB = *resB.val;
} else {
return Res::Err("overflow when adding to reserves");
}
return onMint(shareAddress, liquidity);
}
Res RemoveLiquidity(CScript const & address, CAmount const & liqAmount, std::function<Res(CScript to, CAmount amountA, CAmount amountB)> onReclaim) {
// instead of assertion due to tests
// IRL it can't be more than "total-1000", and was checked indirectly by balances before. but for tests and incapsulation:
if (liqAmount <= 0 || liqAmount >= totalLiquidity) {
return Res::Err("incorrect liquidity");
}
CAmount resAmountA, resAmountB;
resAmountA = (arith_uint256(liqAmount) * arith_uint256(reserveA) / totalLiquidity).GetLow64();
resAmountB = (arith_uint256(liqAmount) * arith_uint256(reserveB) / totalLiquidity).GetLow64();
reserveA -= resAmountA; // safe due to previous math
reserveB -= resAmountB;
totalLiquidity -= liqAmount;
return onReclaim(address, resAmountA, resAmountB);
}
Res Swap(CTokenAmount in, PoolPrice const & maxPrice, std::function<Res(CTokenAmount const &)> onTransfer, bool postBayfrontGardens = true);
private:
CAmount slopeSwap(CAmount unswapped, CAmount & poolFrom, CAmount & poolTo, bool postBayfrontGardens = false);
inline void ioProofer() const { // may be it's more reasonable to use unsigned everywhere, but for basic CAmount compatibility
if (reserveA < 0 || reserveB < 0 ||
totalLiquidity < 0 ||
blockCommissionA < 0 || blockCommissionB < 0 ||
rewardPct < 0 || commission < 0
) {
throw std::ios_base::failure("negative pool's 'CAmounts'");
}
}
public:
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
if (!ser_action.ForRead()) ioProofer();
READWRITEAS(CPoolPairMessage, *this);
READWRITE(reserveA);
READWRITE(reserveB);
READWRITE(totalLiquidity);
READWRITE(blockCommissionA);
READWRITE(blockCommissionB);
READWRITE(rewardPct);
READWRITE(swapEvent);
READWRITE(creationTx);
READWRITE(creationHeight);
if (ser_action.ForRead()) ioProofer();
}
};
struct PoolShareKey {
DCT_ID poolID;
CScript owner;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(WrapBigEndian(poolID.v));
READWRITE(owner);
}
};
enum class RewardType : uint8_t
{
Commission = 128,
Rewards = 129,
};
inline std::string RewardToString(RewardType type)
{
switch(type) {
case RewardType::Commission: return "Commission";
case RewardType::Rewards: return "Rewards";
}
return "Unknown";
}
class CPoolPairView : public virtual CStorageView
{
public:
Res SetPoolPair(const DCT_ID &poolId, CPoolPair const & pool);
Res UpdatePoolPair(DCT_ID const & poolId, bool & status, CAmount const & commission, CScript const & ownerAddress);
Res DeletePoolPair(DCT_ID const & poolId);
boost::optional<CPoolPair> GetPoolPair(const DCT_ID &poolId) const;
boost::optional<std::pair<DCT_ID, CPoolPair> > GetPoolPair(DCT_ID const & tokenA, DCT_ID const & tokenB) const;
void ForEachPoolPair(std::function<bool(DCT_ID const &, CLazySerialize<CPoolPair>)> callback, DCT_ID const & start = DCT_ID{0});
void ForEachPoolShare(std::function<bool(DCT_ID const &, CScript const &)> callback, PoolShareKey const &startKey = PoolShareKey{0,CScript{}}) const;
Res SetShare(DCT_ID const & poolId, CScript const & provider) {
WriteBy<ByShare>(PoolShareKey{poolId, provider}, '\0');
return Res::Ok();
}
Res DelShare(DCT_ID const & poolId, CScript const & provider) {
EraseBy<ByShare>(PoolShareKey{poolId, provider});
return Res::Ok();
}
/// @attention it throws (at least for debug), cause errors are critical!
CAmount DistributeRewards(CAmount yieldFarming, std::function<CTokenAmount(CScript const & owner, DCT_ID tokenID)> onGetBalance, std::function<Res(CScript const & to, DCT_ID poolID, uint8_t type, CTokenAmount amount)> onTransfer, bool newRewardCalc = false) {
uint32_t const PRECISION = 10000; // (== 100%) just searching the way to avoid arith256 inflating
CAmount totalDistributed = 0;
ForEachPoolPair([&] (DCT_ID const & poolId, CPoolPair pool) {
// yield farming counters
CAmount const poolReward = yieldFarming * pool.rewardPct / COIN; // 'rewardPct' should be defined by 'setgov "LP_SPLITS"', also, it is assumed that it was totally validated and normalized to 100%
CAmount distributedFeeA = 0;
CAmount distributedFeeB = 0;
if (pool.totalLiquidity == 0 || (!pool.swapEvent && poolReward == 0)) {
return true; // no events, skip to the next pool
}
ForEachPoolShare([&] (DCT_ID const & currentId, CScript const & provider) {
if (currentId != poolId) {
return false; // stop
}
CAmount const liquidity = onGetBalance(provider, poolId).nValue;
uint32_t const liqWeight = liquidity * PRECISION / pool.totalLiquidity;
assert (liqWeight < PRECISION);
// distribute trading fees
if (pool.swapEvent) {
CAmount feeA = static_cast<CAmount>((arith_uint256(pool.blockCommissionA) * arith_uint256(liquidity) / arith_uint256(pool.totalLiquidity)).GetLow64());
if (!newRewardCalc) {
feeA = pool.blockCommissionA * liqWeight / PRECISION;
}
distributedFeeA += feeA;
onTransfer(provider, poolId, uint8_t(RewardType::Commission), {pool.idTokenA, feeA}); //can throw
CAmount feeB = static_cast<CAmount>((arith_uint256(pool.blockCommissionB) * arith_uint256(liquidity) / arith_uint256(pool.totalLiquidity)).GetLow64());
if (!newRewardCalc) {
feeB = pool.blockCommissionB * liqWeight / PRECISION;
}
distributedFeeB += feeB;
onTransfer(provider, poolId, uint8_t(RewardType::Commission), {pool.idTokenB, feeB}); //can throw
}
// distribute yield farming
if (poolReward) {
CAmount providerReward = static_cast<CAmount>((arith_uint256(poolReward) * arith_uint256(liquidity) / arith_uint256(pool.totalLiquidity)).GetLow64());
if (!newRewardCalc) {
providerReward = poolReward * liqWeight / PRECISION;
}
if (providerReward) {
onTransfer(provider, poolId, uint8_t(RewardType::Rewards), {DCT_ID{0}, providerReward}); //can throw
totalDistributed += providerReward;
}
}
return true;
}, PoolShareKey{poolId, CScript{}});
pool.blockCommissionA -= distributedFeeA;
pool.blockCommissionB -= distributedFeeB;
pool.swapEvent = false;
auto res = SetPoolPair(poolId, pool);
if (!res.ok)
throw std::runtime_error(strprintf("Pool rewards: can't update pool (id=%s) state: %s", poolId.ToString(), res.msg));
return true;
});
return totalDistributed;
}
// tags
struct ByID { static const unsigned char prefix; }; // lsTokenID -> СPoolPair
struct ByPair { static const unsigned char prefix; }; // tokenA+tokenB -> lsTokenID
struct ByShare { static const unsigned char prefix; }; // lsTokenID+accountID -> {}
};
struct CLiquidityMessage {
CAccounts from; // from -> balances
CScript shareAddress;
std::string ToString() const {
if (from.empty()) {
return "empty transfer";
}
std::string result;
for (const auto& kv : from) {
result += "(" + kv.first.GetHex() + "->" + kv.second.ToString() + ")";
}
result += " to " + shareAddress.GetHex();
return result;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(from);
READWRITE(shareAddress);
}
};
struct CRemoveLiquidityMessage {
CScript from;
CTokenAmount amount;
std::string ToString() const {
std::string result = "(" + from.GetHex() + "->" + amount.ToString() + ")";
return result;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(from);
READWRITE(amount);
}
};
#endif // DEFI_MASTERNODES_POOLPAIRS_H
| 37.105398 | 263 | 0.628447 |
55626478508e1632909c4254f92a508a6c957ab0 | 24,880 | c | C | src/event.c | pilotniq/VoxiUtil | 569d069448a8374ca732034aa4f17f723b406003 | [
"Apache-2.0"
] | 1 | 2020-01-09T21:15:16.000Z | 2020-01-09T21:15:16.000Z | src/event.c | pilotniq/VoxiUtil | 569d069448a8374ca732034aa4f17f723b406003 | [
"Apache-2.0"
] | null | null | null | src/event.c | pilotniq/VoxiUtil | 569d069448a8374ca732034aa4f17f723b406003 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 1999-2002 Voxi AB. All rights reserved.
This software is the proprietary information of Voxi AB, Stockholm, Sweden.
Use of this software is subject to license terms.
*/
/*
Voxi's Event Manager
*/
#ifdef _WIN32_WCE
#include <windows.h>
/* all of a sudden we needed time_t to be defined in time.h that is
now included in pthread. we also need wchar_t that is also used in
time.h. Its defined in windows.h that used to be included in
pthread.h, but not anymore..
*/
#ifdef POCKETCONSOLE
#include <sys/types.h>
#endif
#endif
/* Whether to generate debugging messages or not.
Should be before alwaysInclude.h */
#define DEBUG_MESSAGES 0
#include <voxi/alwaysInclude.h>
#include <stddef.h>
#include <pthread.h>
#ifdef HAS_SEMAPHORE_H
#include <semaphore.h>
#endif
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#ifndef WIN32
#include <unistd.h>
#else
#include <windows.h>
#include <voxi/util/win32_glue.h>
#endif /* WIN32 */
#include <voxi/util/hash.h>
#include <voxi/util/vector.h>
#include <voxi/util/threading.h>
#include <voxi/util/event.h>
/*
Hacked by erl 2007-08-30
Couldn't we use the queue class in util, and not need this limitation?
*/
#define EVENT_MAX_EVENTS 256
#ifndef EVENT_MAX_EVENTS
#error You must define EVENT_MAX_EVENTS to be the maximum number of events in the event queue at any time
#endif
#ifdef _WIN32_WCE
/* A hack to not be dependent on oow.lib */
/* this will break event-stuff if oow-objects are used,
but by then oow.lib will of course work, so this
hack wont be needed -- ara */
#define uriCreate( X, Y, Z, W, B ) NULL
#endif /* _WIN32_WCE */
CVSID("$Id: event.c 6184 2003-03-26 15:51:31Z mst $");
/*******************************************************
* types
********************************************************/
/*
* Struct holds an event generated from <source> of the type <type>
* and with the event data eventData. freeFunc is the function
* to be called upon completion of handling of this event.
*/
typedef struct
{
void *source;
EventType eventType;
void *eventData;
EventFreeFunc freeFunc;
/*
If the post of the event is blocking, then the poster will wait for the
semaphore before returning. The semaphore will be triggered after the
freeFunc is called.
*/
Boolean isBlocking;
sem_t semaphore;
} sEvent, *Event;
/*
* Struct to hold a listener entry in the listener list.
* handlerFunc and handlerData make up the keys in the list.
*/
typedef struct
{
EventHandlerFunc handlerFunc;
void *handlerData;
Boolean makeNewThread;
} sListenerEntry, *ListenerEntry;
/*
* Struct to hold the data for every event listener list
* in the hashtable. It has to store the two keys as
* well to make it possible to compare the keys exactly
* if the hash code should be the same. The listenerList
* contains entrys of the type ListenerEntry.
*/
#define LLIST_NO_ELEMS 50
typedef struct
{
void *source;
EventType eventType;
sVoxiMutex listenerListLock;
ListenerEntry listenerEntryList[LLIST_NO_ELEMS];
} sListenerList, *ListenerList;
/*
* Defining the thread start-routine prototype
* to make it possible to cast to it
*/
typedef void * (*thread_start_routine) (void *);
/*
* Struct to hold the data that an event handlerfunc needs.
* this is to be able to pass it all with a single pointer
* as needed by the thread_start_routine prototype
*/
typedef struct
{
EventHandlerFunc handlerFunc;
void *source;
EventType eventType;
void *eventData;
void *handlerData;
} sHandleOneListenerData, *HandleOneListenerData;
/*********************************************************
* static function prototypes
***********************************************************/
/* Event handler functions */
static void *em_mainLoop( void *args );
static void *em_handleOneEvent( Event event );
static void *em_handleOneListenerHandlerFunc(HandleOneListenerData data);
/* internal Event functions */
static void finishedWithEvent( Event event );
static void freeEvent( Event event );
/* Hashtable handling routines */
static int calcHashCode(ListenerList aList);
static int compHashEntrys(ListenerList list1, ListenerList list2);
static void freeListenerList(ListenerList aList);
static void writeListenerList(ListenerList aList);
/*
* global data
*/
/*********************************************************
* static data
***********************************************************/
/*
* Semaphores for the event queue counter and modification lock.
*/
static sem_t eventsInQueue;
static sVoxiMutex eventQueueModificationLock;
/*
Store the pending events
frontEvent points to the earliest event in the queue. This is the next
event to be handled.
The event after frontEvent is at (frontEvent + 1) % EVENT_MAX_EVENTS
backEvent points to where to add the next event
if frontEvent == backEvent then the queue is empty
*/
static int frontEvent = 0, backEvent = 0;
static Event eventQueue[ EVENT_MAX_EVENTS ];
/*
* The event manager thread
*/
static pthread_t eventManagerThread = (pthread_t)NULL;
/*
* The hashtable that containts the added listeners.
* Actually it contains a ListenerList for every
* entry with the same keys (i.e. source and eventType)
*/
static HashTable listenersHashTable = NULL;
static sVoxiMutex listenersHashTableLock;
/*********************************************************
* start/stop functions
***********************************************************/
/*
* Start the event handler.
* Initializes the Hashtable, event queue, semaphores and starts
* the main event manager thread.
*/
void em_startup()
{
int err;
Error error;
/* Init the the listnersHashTable */
listenersHashTable =
HashCreateTable(1024,
(HashFuncPtr)calcHashCode,
(CompFuncPtr)compHashEntrys,
(DestroyFuncPtr) freeListenerList);
threading_mutex_init( &(listenersHashTableLock) );
/* Init the event handler thread */
assert( eventManagerThread == (pthread_t) NULL );
frontEvent = 0;
backEvent = 0;
err = sem_init( &eventsInQueue, 0, 0 );
assert( err == 0 );
threading_mutex_init( &eventQueueModificationLock );
assert( err == 0 );
/* So that we can access teh detachedThreadAttr variable */
threading_init();
/* The Event Manager Thread will be joined upon shutdown, and is therefore
not created in a detached state */
err = threading_pthread_create( &eventManagerThread, NULL, em_mainLoop, NULL );
assert( err == 0 );
}
/*
* Ends the event handling and frees the resources that it used.
* There might be spawned eventhandling threads running after
* this function returns...
*/
void em_shutdown()
{
int error;
/* Stop the event handler */
error = pthread_cancel(eventManagerThread);
assert(error == 0);
error = pthread_join(eventManagerThread, NULL);
assert(error == 0);
threading_shutdown();
/* skip destroying the hash table for now.
Destroying the hash table requires the hash table to be empty. But doing
that requires all objects to be shut down properly, which we aren't doing
yet.
*/
#if 0
/* Destroy the hash table */
HashDestroyTable(listenersHashTable);
#endif
/* Destroy semaphores */
error = sem_destroy(&eventsInQueue);
assert(error == 0);
threading_mutex_destroy( &eventQueueModificationLock );
}
/*********************************************************
* Event sending function
***********************************************************/
/*
* Post an event.
* Source may not be null.
*
*/
void em_postEvent( void *source, EventType eventType, void *eventData,
EventFreeFunc freeFunc, Boolean blocking )
{
int error = 0;
Event aEvent = NULL;
DEBUG(" enter ( source %p, type %d, eventData %p, freeFunc %p, blocking %d )\n",
source, eventType, eventData, freeFunc, blocking );
assert (source != NULL);
/* Check if there are free space in the event queue */
assert( ((backEvent + 1) % EVENT_MAX_EVENTS) != frontEvent);
DEBUG("before aquiring queue-lock\n" );
/* Acquire the lock to the event list */
threading_mutex_lock( &eventQueueModificationLock );
assert( error == 0 );
DEBUG("after aquiring queue-lock\n" );
/* Create new event and insert the event at the point of backEvent */
aEvent = malloc(sizeof(sEvent));
aEvent->source = source;
aEvent->eventType = eventType;
aEvent->eventData = eventData;
aEvent->freeFunc = freeFunc;
aEvent->isBlocking = blocking;
if( blocking )
sem_init( &(aEvent->semaphore), 0, 0 );
eventQueue[backEvent] = aEvent;
/* Modify the backEvent pointer */
backEvent = (backEvent + 1) % EVENT_MAX_EVENTS;
/* Release the event list */
threading_mutex_unlock( &eventQueueModificationLock );
/* Increase the QueueCounter by 1 to indicate a new event */
DEBUG(" sem_post(&eventsInQueue)\n" );
error = sem_post(&eventsInQueue);
assert( error == 0 );
if( blocking )
{
int err;
DEBUG("befor sem_wait(aEvent=%p)\n", aEvent );
err = threading_sem_wait( &(aEvent->semaphore) );
assert( err == 0 );
DEBUG("after sem_wait(aEvent=%p)\n", aEvent );
freeEvent( aEvent );
}
DEBUG("leave\n");
}
/*********************************************************
* Add and remove listener functions
***********************************************************/
/*
* Adds a listener.
* First it finds the listenerList from the hash table (or creates
* a new if not found) with source and eventType as keys.
* Then a entry is insterted into the list with handlerFunc and
* handlerData as keys
*/
void em_addListener( void *source, EventType eventType,
EventHandlerFunc handlerFunc,
void *handlerData, Boolean makeNewThread )
{
int i;
int res;
/* The soon enough found listenerlist */
ListenerList listenerList = NULL;
/* The template of how to find the listenerList */
sListenerList findTemplate = {source, eventType, {{0}}, {NULL} };
DEBUG(" enter ( source %p, type %d, handlerData %p, handlerFunc %p, makeNewThread %d )\n",
source, eventType, handlerData, handlerFunc, makeNewThread );
threading_mutex_lock( &(listenersHashTableLock) );
/* Get listener list from hash table with keys (source, eventType) */
listenerList = HashFind(listenersHashTable, &findTemplate);
/* Check if we got a listenerList or if we got null */
if (listenerList == NULL)
{
DEBUG("create new listenersList for {source %p, type %d}\n", source, eventType);
/* If null then create a new listenerList, initialize
* it and add it to the Hashtable */
listenerList = malloc(sizeof(sListenerList));
listenerList->source = source;
listenerList->eventType = eventType;
threading_mutex_init( &(listenerList->listenerListLock) );
/* error = sem_init( &(listenerList->listenerListLock), 0, 1 );
assert( error == 0 ); */
for (i = 0; i < LLIST_NO_ELEMS; i++)
listenerList->listenerEntryList[i] = NULL;
res = HashAdd(listenersHashTable, listenerList);
/* Check if success */
assert(res != 0);
}
threading_mutex_unlock( &(listenersHashTableLock) );
/* Now we got a listenerList. First lock it.
* Then loop through the list to check for an empty entry */
DEBUG(" get lock %p->listenerListLock \n", listenerList );
threading_mutex_lock( &(listenerList->listenerListLock) );
DEBUG(" got lock %p->listenerListLock \n", listenerList );
for (i=0; i < LLIST_NO_ELEMS; i++)
{
if (listenerList->listenerEntryList[i] == NULL)
{
/* Add it here */
listenerList->listenerEntryList[i] =
(ListenerEntry) malloc(sizeof(sListenerEntry));
listenerList->listenerEntryList[i]->handlerFunc = handlerFunc;
listenerList->listenerEntryList[i]->handlerData = handlerData;
listenerList->listenerEntryList[i]->makeNewThread = makeNewThread;
break;
}
}
/* Unlock list */
threading_mutex_unlock( &(listenerList->listenerListLock) );
DEBUG(" released lock %p->listenerListLock \n", listenerList );
/* sem_post(&(listenerList->listenerListLock)); */
/* Error if no free entrys in list */
assert (i < LLIST_NO_ELEMS);
#ifndef NDEBUG
if( debug )
{
fprintf( stderr, "Added listener ");
writeListenerList(listenerList);
}
#endif /* NDEBUG */
DEBUG("leave\n");
}
/*
* Removes the first occurrance of listener with the keys
* handlerFunc and handlerData from a list retrieved from the
* hash table with the keys source and eventType.
*/
void em_removeListener( void *source, EventType eventType,
EventHandlerFunc handlerFunc, void *handlerData )
{
int i;
/* The soon enough found listenerlist */
ListenerList listenerList = NULL;
/* The template of how to find the listenerList */
sListenerList findTemplate = {source, eventType, {{0}}, {NULL} };
DEBUG(" enter ( source %p, type %d, handlerData %p, handlerFunc %p )\n",
source, eventType, handlerData, handlerFunc );
threading_mutex_lock( &(listenersHashTableLock) );
/* Get listener list from hash table with keys (source, eventType) */
listenerList = HashFind(listenersHashTable, &findTemplate);
threading_mutex_unlock( &(listenersHashTableLock) );
assert( listenerList != NULL );
/* Lock the list */
DEBUG(" get lock %p->listenerListLock \n", listenerList );
threading_mutex_lock(&(listenerList->listenerListLock));
DEBUG(" got lock %p->listenerListLock \n", listenerList );
/* Loop through the list to check for the entry with
* the keys handlerFund and handlerData */
for (i=0; i < LLIST_NO_ELEMS; i++)
{
if ((listenerList->listenerEntryList[i] != NULL) &&
(listenerList->listenerEntryList[i]->handlerFunc == handlerFunc) &&
(listenerList->listenerEntryList[i]->handlerData == handlerData))
{
/* Found a match, remove it */
free(listenerList->listenerEntryList[i]);
listenerList->listenerEntryList[i] = NULL;
DEBUG("removed listenerEntry\n");
break;
}
}
/* Unlock list */
threading_mutex_unlock(&(listenerList->listenerListLock));
DEBUG(" released lock %p->listenerListLock \n", listenerList );
#ifndef NDEBUG
if( debug )
{
printf("Removing listener ");
writeListenerList(listenerList);
}
#endif
DEBUG("leave\n");
}
/*********************************************************
* Internal event dispatch functions
***********************************************************/
/*
* The main event manager loop.
* Waits for the queue to contain at least one event and starts
* to take it off the queue. It then starts a new thread to
* handle that current event.
*/
static void *em_mainLoop( void *args )
{
int error;
while( TRUE )
{
Event event;
pthread_t oneEventHandlerThread;
/* Wait for some events to be added
* This is also the cancelation point for this thread */
DEBUG("waits for events\n");
error = threading_sem_wait( &eventsInQueue );
assert( error == 0 );
/*
if( error != 0 )
fprintf( stderr, "event.c: catastrophic: sem_wait returned %d, not 0. errno=%d\n",
error, errno );
*/
assert( frontEvent != backEvent );
/* get and remove the element from the queue */
event = eventQueue[ frontEvent ];
threading_mutex_lock( &eventQueueModificationLock );
/* modify the queue */
frontEvent = (frontEvent + 1) % EVENT_MAX_EVENTS;
threading_mutex_unlock( &eventQueueModificationLock );
/* Create a thread that dispatches the callbacks to the
* registred listeners */
error = threading_pthread_create( &oneEventHandlerThread, &detachedThreadAttr,
(thread_start_routine) em_handleOneEvent, event );
assert( error == 0 );
DEBUG(" forked (detached) thread %ld for event %p\n",
oneEventHandlerThread, event);
#ifndef NDEBUG
{
int scheduler;
struct sched_param schedParam;
error = pthread_getschedparam( pthread_self(), &scheduler, &schedParam );
assert( error == 0 );
if( scheduler != SCHED_OTHER )
fprintf( stderr, "event.c: trouble, scheduler == %d != SCHED_OTHER == %d.\n", scheduler, SCHED_OTHER );
/* assert( scheduler == SCHED_OTHER ); */
}
#endif
}
return NULL;
}
static void freeEvent( Event event )
{
if( event->isBlocking )
{
int err;
/* free the semaphore */
err = sem_destroy( &(event->semaphore) );
assert( err == 0 );
DEBUG(" destroyed %p->semaphore\n",event);
}
free( event );
}
/*
posts to the event's semaphore if the event is blocking, otherwise frees it.
If it is a blocking event, then the thread that does sem_wait must also
do the freeing by calling freeEvent.
*/
static void finishedWithEvent( Event event )
{
/* free the event */
if (event->freeFunc)
event->freeFunc(event->source, event->eventType, event->eventData);
if( event->isBlocking )
{
int err;
DEBUG(" sem_post %p->semaphore\n",event);
err = sem_post( &(event->semaphore ) );
assert( err == 0 );
/* freeEvent will be called from em_postEvent */
}
else
freeEvent( event );
}
/*
* Handles the execution of a single event.
* It first fetches the list of all listeners for
* the event's source and eventType.
* For every listener, the handlerFunction is called
* either within a new thread or within the current thread
* depending on what the variable makeNewThread is
*/
static void *em_handleOneEvent(Event event)
{
int listnCntr = 0;
/* List with threads to be checked for completion */
pthread_t threadWaitList[LLIST_NO_ELEMS];
int threadWaitCntr = 0;
/* The soon enough found listenerlist */
ListenerList listenerList = NULL;
/* The template of how to find the listenerList initiated
* with the event's source and eventType */
sListenerList findTemplate = {event->source, event->eventType, {{0}}, {NULL} };
DEBUG(" enter %p\n", event);
/* Check if we have erraneously gotten realtime scheduling */
#ifndef NDEBUG
{
int err, scheduler;
struct sched_param schedParam;
err = pthread_getschedparam( pthread_self(), &scheduler, &schedParam );
assert( err == 0 );
assert( scheduler == SCHED_OTHER );
}
#endif
threading_mutex_lock( &(listenersHashTableLock) );
/* Get listener list from hash table with keys (source, eventType) */
listenerList = HashFind(listenersHashTable, &findTemplate);
threading_mutex_unlock( &(listenersHashTableLock) );
/* Check if we got a listenerList or if we got null */
if (listenerList == NULL)
{
/* No listeners... */
DEBUG("No listeners\n");
finishedWithEvent( event );
#if 0
/* free the event */
if (event->freeFunc)
event->freeFunc(event->source, event->eventType, event->eventData);
free( event );
#endif
DEBUG("leave (no listeners)\n");
return NULL;
}
/* Lock the list */
DEBUG(" get lock %p->listenerListLock \n", listenerList );
threading_mutex_lock(&(listenerList->listenerListLock));
DEBUG(" got lock %p->listenerListLock \n", listenerList );
/* Loop through the list and for each non-null position
* call the handlerFunc in the desired way */
for (listnCntr=0; listnCntr < LLIST_NO_ELEMS; listnCntr++)
{
/* Check if there is a listener */
if (listenerList->listenerEntryList[listnCntr] != NULL)
{
ListenerEntry aListener = NULL;
aListener = listenerList->listenerEntryList[listnCntr];
/* Check if a new thread or within in this thread */
if (aListener->makeNewThread)
{
int error = 0;
HandleOneListenerData aHandleOneListenerData = NULL;
pthread_t oneEventListenerThread;
/* Ok, in a new thread, first build the data struct */
aHandleOneListenerData = malloc(sizeof(sHandleOneListenerData));
aHandleOneListenerData->handlerFunc = aListener->handlerFunc;
aHandleOneListenerData->source = event->source;
aHandleOneListenerData->eventType = event->eventType;
aHandleOneListenerData->eventData = event->eventData;
aHandleOneListenerData->handlerData = aListener->handlerData;
#ifndef WIN32
if( sched_getscheduler( getpid() ) == SCHED_FIFO )
fprintf( stderr, "em_handleOneEvent with scheduler FIFO.\n" );
#endif
/* Execute listeners handlerFunc in its own thread */
DEBUG("forks thread for event %p handlerData %p ... \n",
event, aListener->handlerData);
error = threading_pthread_create( &oneEventListenerThread, NULL,
(thread_start_routine) em_handleOneListenerHandlerFunc,
aHandleOneListenerData);
DEBUG(" ... thread created %ld\n", oneEventListenerThread );
if( error == 0 )
{
/* Add thread to wait list */
assert( threadWaitCntr < LLIST_NO_ELEMS );
threadWaitList[threadWaitCntr] = oneEventListenerThread;
threadWaitCntr++;
}
else
fprintf( stderr, "ERROR: error %d starting event thread.\n",
error );
}
else
{
/* This is a dangerous point. If the handlerFunc blocks for a long
time, we still have the listenerList locked, and will prevent other
events like this to be handled.
Any handlers which can block should start new threads!
*/
DEBUG("forks NO thread for event %p handlerData %p\n",
event, aListener->handlerData);
aListener->handlerFunc(event->source, event->eventType,
event->eventData, aListener->handlerData);
DEBUG("handlerFunc returned-1. event %p handlerData %p\n",
event, aListener->handlerData);
}
}
}
/* Unlock the list */
threading_mutex_unlock(&(listenerList->listenerListLock));
DEBUG(" released lock %p->listenerListLock \n", listenerList );
/* Wait for all threads in wait list */
DEBUG(" waits for joining threads for event %p\n", event );
for (listnCntr = 0; listnCntr < threadWaitCntr; listnCntr++)
{
/* For every pthread created, do a join */
pthread_join(threadWaitList[listnCntr], NULL);
}
DEBUG(" done joining threads for event %p\n", event );
finishedWithEvent( event );
#if 0
/* Check if freeFunc should be called. */
if (event->freeFunc)
{
event->freeFunc(event->source, event->eventType, event->eventData);
}
/* Free the event itself */
free(event);
#endif
DEBUG("leave\n");
return NULL;
}
/*
* This function handles a single callback to a listener
* handleFunc. It's here because the handlerFunc
* and the thread_start_routine doesn't have the same signature
*/
static void *em_handleOneListenerHandlerFunc(HandleOneListenerData data)
{
#ifndef NDEBUG
int policy, err;
struct sched_param schedParam;
err = pthread_getschedparam( pthread_self(), &policy, &schedParam );
assert( err == 0 );
if( policy != SCHED_OTHER )
{
DEBUG( "ERROR: em_handleOneListenerHandlerFunc called as FIFO. "
"resetting.\n" );
schedParam.sched_priority = 0;
err = pthread_setschedparam( pthread_self(), SCHED_OTHER, &schedParam );
assert( err == 0 );
}
#endif
/* Call the handler func */
data->handlerFunc(data->source, data->eventType,
data->eventData, data->handlerData);
DEBUG("handlerFunc returned-2. event ?? handlerData %p\n",
/*event,*/ data->handlerData);
/* Free the data */
free(data);
return NULL;
}
/*********************************************************
* Hashtable handling functions
***********************************************************/
static int calcHashCode(ListenerList aList)
{
int hashCode = ((int) aList->source) ^ ((int) aList->eventType);
return hashCode;
}
static int compHashEntrys(ListenerList list1, ListenerList list2)
{
if ((list1->source == list2->source) &&
(list1->eventType == list2->eventType))
{
return 0;
}
else
{
return 4711;
}
}
/*
* Free all the ListenerEntrys in the list
*/
static void freeListenerList(ListenerList aList)
{
int i;
for (i = 0; i < LLIST_NO_ELEMS; i++)
{
if (aList->listenerEntryList[i] != NULL)
{
free(aList->listenerEntryList[i]);
aList->listenerEntryList[i] = NULL;
}
}
}
/*
* Write the listenerList for debug purposes
*/
static void writeListenerList(ListenerList aList)
{
int i;
printf("ListenerList: source: %x, evtype: %d\n",(int)aList->source,
aList->eventType);
for (i=0; i < LLIST_NO_ELEMS; i++)
{
if (aList->listenerEntryList[i] != NULL)
{
printf(" Entry: hfunc: %x, hdata: %x, newthr: %d\n",
(int)aList->listenerEntryList[i]->handlerFunc,
(int)aList->listenerEntryList[i]->handlerData,
aList->listenerEntryList[i]->makeNewThread);
}
}
printf("--------------------------------\n\n");
}
| 27.250821 | 109 | 0.654502 |
d9f47e8063370bde7a07fecb0d50dc6dac6c6b3d | 14,156 | c | C | SpongeBob/Data/Maps/CHAPTER01_LEVEL0209.c | KrazeeTobi/SBSPSS-AGB | b6c1faba6f80c1a321218b2554e3ff28d199ff11 | [
"Unlicense"
] | 1 | 2021-03-22T22:10:15.000Z | 2021-03-22T22:10:15.000Z | SpongeBob/Data/Maps/CHAPTER01_LEVEL0209.c | KrazeeTobi/SBSPSS-AGB | b6c1faba6f80c1a321218b2554e3ff28d199ff11 | [
"Unlicense"
] | null | null | null | SpongeBob/Data/Maps/CHAPTER01_LEVEL0209.c | KrazeeTobi/SBSPSS-AGB | b6c1faba6f80c1a321218b2554e3ff28d199ff11 | [
"Unlicense"
] | null | null | null | /******************************************/
/*** Level Data for CHAPTER01_LEVEL0209 ***/
/******************************************/
#include "agbtypes.h"
/******************************************************************************/
u16 CHAPTER01_LEVEL0209_MID_WIDTH=32;
u16 CHAPTER01_LEVEL0209_MID_HEIGHT=22;
u16 CHAPTER01_LEVEL0209_MID[32*22]=
{
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
}; // CHAPTER01_LEVEL0209_MID
u16 CHAPTER01_LEVEL0209_ACTION_WIDTH=32;
u16 CHAPTER01_LEVEL0209_ACTION_HEIGHT=22;
u16 CHAPTER01_LEVEL0209_ACTION[32*22]=
{
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
}; // CHAPTER01_LEVEL0209_ACTION
u16 CHAPTER01_LEVEL0209_COLLISION_WIDTH=32;
u16 CHAPTER01_LEVEL0209_COLLISION_HEIGHT=22;
u8 CHAPTER01_LEVEL0209_COLLISION[32*22]=
{
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
}; // CHAPTER01_LEVEL0209_COLLISION
| 152.215054 | 224 | 0.827352 |
3d2f3e8942afe4817d6e2e3b0a8797e48e5f0056 | 503 | h | C | lemon/config.h | zlthinker/RMBP | e3b9689af8b2a412639c8216049a0d82fe6e73db | [
"MIT"
] | 29 | 2018-07-09T11:21:08.000Z | 2021-09-20T19:47:23.000Z | lemon/config.h | sundw2014/rmbp | 9a3456b640299215ea855df279ff9b715eaf213a | [
"MIT"
] | null | null | null | lemon/config.h | sundw2014/rmbp | 9a3456b640299215ea855df279ff9b715eaf213a | [
"MIT"
] | 7 | 2018-10-20T00:47:40.000Z | 2020-11-26T07:31:40.000Z | #define LEMON_VERSION "1.3.1"
#define LEMON_HAVE_LONG_LONG 1
/* #undef LEMON_HAVE_LP */
/* #undef LEMON_HAVE_MIP */
/* #undef LEMON_HAVE_GLPK */
/* #undef LEMON_HAVE_CPLEX */
/* #undef LEMON_HAVE_SOPLEX */
/* #undef LEMON_HAVE_CLP */
/* #undef LEMON_HAVE_CBC */
#define _LEMON_CPLEX 1
#define _LEMON_CLP 2
#define _LEMON_GLPK 0
#define _LEMON_SOPLEX 0
#define _LEMON_CBC 5
/* #undef LEMON_DEFAULT_LP */
/* #undef LEMON_DEFAULT_MIP */
#define LEMON_USE_PTHREAD 1
/* #undef LEMON_USE_WIN32_THREADS */
| 21.869565 | 36 | 0.741551 |
5c0ce00b3c145bb4c34be01fe530324583c2a250 | 322 | h | C | include/ImageSimilaritySorter.h | foobar999/Medienretrieval | e4db216129dd1da5452f0411e3132fc5710707c4 | [
"BSD-2-Clause"
] | null | null | null | include/ImageSimilaritySorter.h | foobar999/Medienretrieval | e4db216129dd1da5452f0411e3132fc5710707c4 | [
"BSD-2-Clause"
] | null | null | null | include/ImageSimilaritySorter.h | foobar999/Medienretrieval | e4db216129dd1da5452f0411e3132fc5710707c4 | [
"BSD-2-Clause"
] | null | null | null | #ifndef IMAGESIMILARITYSORTER_H
#define IMAGESIMILARITYSORTER_H
#include <vector>
#include "ImageDistance.h"
#include "utils.h"
class ImageSimilaritySorter {
public:
std::vector<int> sort_by_distance(int query_id, const std::vector<ImageData> &histograms, ImageDistance &dist);
};
#endif // IMAGESIMILARITYSORTER_H
| 23 | 115 | 0.78882 |
e1d58b85eda3817d42014241240572366e6232e3 | 2,980 | h | C | Real-Time Corruptor/BizHawk_RTC/libmupen64plus/mupen64plus-video-rice/src/GraphicsContext.h | redscientistlabs/Bizhawk50X-Vanguard | 96e0f5f87671a1230784c8faf935fe70baadfe48 | [
"MIT"
] | 1,414 | 2015-06-28T09:57:51.000Z | 2021-10-14T03:51:10.000Z | Real-Time Corruptor/BizHawk_RTC/libmupen64plus/mupen64plus-video-rice/src/GraphicsContext.h | redscientistlabs/Bizhawk50X-Vanguard | 96e0f5f87671a1230784c8faf935fe70baadfe48 | [
"MIT"
] | 2,369 | 2015-06-25T01:45:44.000Z | 2021-10-16T08:44:18.000Z | Real-Time Corruptor/BizHawk_RTC/libmupen64plus/mupen64plus-video-rice/src/GraphicsContext.h | redscientistlabs/Bizhawk50X-Vanguard | 96e0f5f87671a1230784c8faf935fe70baadfe48 | [
"MIT"
] | 430 | 2015-06-29T04:28:58.000Z | 2021-10-05T18:24:17.000Z | /*
Copyright (C) 2003 Rice1964
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef GFXCONTEXT_H
#define GFXCONTEXT_H
#include "typedefs.h"
#include "CritSect.h"
enum ClearFlag
{
CLEAR_COLOR_BUFFER=0x01,
CLEAR_DEPTH_BUFFER=0x02,
CLEAR_COLOR_AND_DEPTH_BUFFER=0x03,
};
typedef struct
{
uint32 addr; //N64 RDRAM address
uint32 size; //N64 buffer size
uint32 format; //N64 format
uint32 width;
uint32 height;
} TextureBufferShortInfo;
// This class basically provides an extra level of security for our
// multithreaded code. Threads can Grab the CGraphicsContext to prevent
// other threads from changing/releasing any of the pointers while it is
// running.
// It is based on CCritSect for Lock() and Unlock()
class CGraphicsContext : public CCritSect
{
friend class CDeviceBuilder;
public:
bool Ready() { return m_bReady; }
bool IsWindowed() {return m_bWindowed;}
virtual bool Initialize(uint32 dwWidth, uint32 dwHeight, BOOL bWindowed );
virtual bool ResizeInitialize(uint32 dwWidth, uint32 dwHeight, BOOL bWindowed );
virtual void CleanUp();
virtual void Clear(ClearFlag flags, uint32 color=0xFF000000, float depth=1.0f) = 0;
virtual void UpdateFrame(bool swaponly=false) = 0;
virtual int ToggleFullscreen()=0; // return 0 as the result is windowed
static void InitWindowInfo();
static void InitDeviceParameters();
bool m_supportTextureMirror;
public:
static int m_maxFSAA;
static int m_maxAnisotropy;
protected:
static uint32 m_dwWindowStyle; // Saved window style for mode switches
static uint32 m_dwWindowExStyle; // Saved window style for mode switches
static uint32 m_dwStatusWindowStyle; // Saved window style for mode switches
static bool m_deviceCapsIsInitialized;
bool m_bReady;
bool m_bActive;
bool m_bWindowed;
RECT m_rcWindowBounds;
char m_strDeviceStats[256];
virtual ~CGraphicsContext();
CGraphicsContext();
public:
static CGraphicsContext *g_pGraphicsContext;
static CGraphicsContext * Get(void);
inline const char* GetDeviceStr() {return m_strDeviceStats;}
static bool needCleanScene;
};
#endif
| 28.932039 | 87 | 0.709396 |
ed4d7be967853726d9973a2e00a75c33a8bff778 | 530 | h | C | controller/openflow_messages/of_message_features_request.h | zteo-phd-software/ironstack | 649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0 | [
"BSD-3-Clause"
] | null | null | null | controller/openflow_messages/of_message_features_request.h | zteo-phd-software/ironstack | 649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0 | [
"BSD-3-Clause"
] | null | null | null | controller/openflow_messages/of_message_features_request.h | zteo-phd-software/ironstack | 649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "of_message.h"
#include "../../common/mac_address.h"
// requests the switch to send its available features
// author: Z. Teo (zteo@cs.cornell.edu)
using namespace std;
class of_message_features_request : public of_message {
public:
of_message_features_request();
virtual ~of_message_features_request() {};
virtual void clear();
virtual string to_string() const;
// inherited from serializable
virtual uint32_t serialize(autobuf& dest) const;
virtual bool deserialize(const autobuf& input);
};
| 22.083333 | 55 | 0.756604 |
358d0ca375af7cebde3083baaf62201f239cf274 | 425 | c | C | lib/libc/wasi/libc-bottom-half/sources/__wasilibc_tell.c | lukekras/zig | 6f303c01f3e06fe8203563065ea32537f6eff456 | [
"MIT"
] | 12,718 | 2018-05-25T02:00:44.000Z | 2022-03-31T23:03:51.000Z | lib/libc/wasi/libc-bottom-half/sources/__wasilibc_tell.c | lukekras/zig | 6f303c01f3e06fe8203563065ea32537f6eff456 | [
"MIT"
] | 8,483 | 2018-05-23T16:22:39.000Z | 2022-03-31T22:18:16.000Z | lib/libc/wasi/libc-bottom-half/sources/__wasilibc_tell.c | lukekras/zig | 6f303c01f3e06fe8203563065ea32537f6eff456 | [
"MIT"
] | 1,400 | 2018-05-24T22:35:25.000Z | 2022-03-31T21:32:48.000Z | #include <wasi/api.h>
#include <errno.h>
off_t __wasilibc_tell(int fildes) {
__wasi_filesize_t offset;
__wasi_errno_t error = __wasi_fd_tell(fildes, &offset);
if (error != 0) {
// lseek returns ESPIPE on when called on a pipe, socket, or fifo,
// which on WASI would translate into ENOTCAPABLE.
errno = error == ENOTCAPABLE ? ESPIPE : error;
return -1;
}
return offset;
}
| 28.333333 | 74 | 0.642353 |
81c0d0f0e278696b388ec1f58c9a3831fdb357ba | 5,485 | h | C | src/base64.h | cryptowerk/cealr | 659fe8b3a8e58ac1fed85efbbc1bdd24cb183b5e | [
"Apache-2.0"
] | 3 | 2018-07-17T08:51:15.000Z | 2018-11-21T12:55:04.000Z | src/base64.h | cryptowerk/cealr | 659fe8b3a8e58ac1fed85efbbc1bdd24cb183b5e | [
"Apache-2.0"
] | null | null | null | src/base64.h | cryptowerk/cealr | 659fe8b3a8e58ac1fed85efbbc1bdd24cb183b5e | [
"Apache-2.0"
] | 2 | 2018-07-30T22:05:40.000Z | 2019-09-05T04:24:39.000Z | /*
* _____ _____ _____ ___ ______
*| __| __|/ _ \| | | _ | Command line tool for sealing files with Cryptowerk API
*| |__| __| _ | |__|
*|_____|_____|__| |__|______|__|\__\ https://github.com/cryptowerk/cealr
*
* The original algorithms were copied from
* Copyright (c) 2016 tomykaira
*
* https://gist.github.com/tomykaira/f0fd86b6c73063283afe550bc5d77594#file-base64-h
*
* The original code is licensed under MIT License <https://opensource.org/licenses/MIT>
* The changes made to adapt the code to the purposes of CryptoWerk are licensed under the
* Apache 2.0 License <https://opensource.org/licenses/Apache-2.0>.
* Copyright (c) 2018 Cryptowerk <http://www.cryptowerk.com>.
*
*/
#ifndef CEALR_BASE64_H
#define CEALR_BASE64_H
#include <string>
#include <vector>
using namespace std;
class base64_exception : public exception
{
private:
runtime_error _what;
public:
base64_exception(const string &file, const int line, const string &errStr) : _what(("" + file + ":" + to_string(line) + ": " + errStr).c_str()) {}
const char *what()
{
return _what.what();
}
};
class base64 {
public:
static string encode(const vector<char> &data)
{
static constexpr const char *binary2ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t in_len = data.size();
size_t out_len = 4 * ((in_len + 2) / 3);
string ret(out_len, '\0');
size_t i;
char *p = const_cast<char *>(ret.c_str());
for (i = 0; i < in_len - 2; i += 3)
{
*p++ = binary2ascii[(data[i] >> 2) & 0x3F];
*p++ = binary2ascii[((data[i] & 0x3) << 4) | ((data[i + 1] & 0xF0) >> 4)];
*p++ = binary2ascii[((data[i + 1] & 0xF) << 2) | ((data[i + 2] & 0xC0) >> 6)];
*p++ = binary2ascii[data[i + 2] & 0x3F];
}
if (i < in_len)
{
*p++ = binary2ascii[(data[i] >> 2) & 0x3F];
if (i == (in_len - 1))
{
*p++ = binary2ascii[((data[i] & 0x3) << 4)];
*p++ = '=';
}
else
{
*p++ = binary2ascii[((data[i] & 0x3) << 4) | ((data[i + 1] & 0xF0) >> 4)];
*p++ = binary2ascii[((data[i + 1] & 0xF) << 2)];
}
*p++ = '=';
}
return ret;
}
static void replace(string &input, const string &find, const string &repl)
{
size_t flen = find.length();
size_t rlen = repl.length();
for (size_t index = 0; ((index=input.find(find, index)) != string::npos);)
{
input.replace(index, flen, repl);
index += rlen;
}
}
static vector<char> *decode(const string& rawInput)
{
string input = rawInput;
replace(input, "\r", "");
replace(input, "\n", "");
replace(input, " ", "");
static constexpr unsigned char ascii2binary[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3E, 0xff, 0xff, 0xff, 0x3F,
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff,
0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
size_t in_len = input.size();
if (in_len & 0x03){
throw base64_exception(__FILE__, __LINE__, "Size of string to be decoded must be a multiple of 4");
}
size_t out_len = (in_len / 4) * 3;
if (input[in_len - 1] == '=')
{
out_len--;
}
if (input[in_len - 2] == '=')
{
out_len--;
}
auto out= new vector<char>(out_len, 0);
size_t i = 0, j = 0;
while (i < in_len)
{
int ishift = 18;
uint32_t triple = 0;
while (ishift>=0)
{
char &c = input[i++];
uint32_t _64bitVal = ascii2binary[static_cast<int>(c)];
if (_64bitVal==0xff){
throw base64_exception(__FILE__, __LINE__, "Character \'"+string(1,c)+"\' is not valid supported in this base 64 implementation.");
}
triple |= _64bitVal << ishift;
ishift -= 6;
}
int oshift = 16;
while (oshift>=0 && j < out_len)
{
out->at(j++) = (char) (triple >> oshift);
oshift -= 8;
}
}
return out;
}
};
#endif /* CEALR_BASE64_H */
| 34.936306 | 148 | 0.577211 |
81edf3b5462ab6282919596a5d8ac8cde749a960 | 305 | h | C | OdessaMacGUIApp/Source/InterfaceHelpers/DesignLanguage.h | noahsw/highlight-hunter | f981f6efc3bf391117e4fec7365e63755f7b7135 | [
"Apache-2.0"
] | 8 | 2015-05-26T23:27:19.000Z | 2019-01-21T10:08:30.000Z | OdessaMacGUIApp/Source/InterfaceHelpers/DesignLanguage.h | noahsw/highlight-hunter | f981f6efc3bf391117e4fec7365e63755f7b7135 | [
"Apache-2.0"
] | 2 | 2016-02-09T00:37:25.000Z | 2016-05-14T17:50:51.000Z | OdessaMacGUIApp/Source/InterfaceHelpers/DesignLanguage.h | noahsw/highlight-hunter | f981f6efc3bf391117e4fec7365e63755f7b7135 | [
"Apache-2.0"
] | 3 | 2018-07-31T08:13:09.000Z | 2020-02-01T19:50:53.000Z | //
// DesignLanguage.h
// OdessaMacGUIApp
//
// Created by Noah Spitzer-Williams on 9/4/12.
// Copyright (c) 2012 Authentically Digital LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface DesignLanguage : NSObject
+ (NSColor*) lightGrayColor;
+ (NSColor*) midGrayColor;
@end
| 17.941176 | 70 | 0.718033 |
dccf5746d25ad6460d62cb0b11359a2954aa74d5 | 213 | h | C | KeHai/Controllers/Home/ScheduleViewController.h | chengaojian/KH2016 | 1cc61d2d0726c0acae6896969338fb36bf5ebd9c | [
"Apache-2.0"
] | null | null | null | KeHai/Controllers/Home/ScheduleViewController.h | chengaojian/KH2016 | 1cc61d2d0726c0acae6896969338fb36bf5ebd9c | [
"Apache-2.0"
] | null | null | null | KeHai/Controllers/Home/ScheduleViewController.h | chengaojian/KH2016 | 1cc61d2d0726c0acae6896969338fb36bf5ebd9c | [
"Apache-2.0"
] | null | null | null | //
// ScheduleViewController.h
// KeHai
//
// Created by 三海 on 16/10/22.
// Copyright © 2016年 陈高健. All rights reserved.
//
#import "ViewController.h"
@interface ScheduleViewController : ViewController
@end
| 15.214286 | 50 | 0.704225 |
b0fa30aaa990213a0f6d4362855fba4de8985439 | 9,625 | h | C | u-boot/arch/arm/include/asm/arch-gxl/i2c.h | rgomulin/aml_s905_uboot | 550de48829e852678f6cef98e94e1a97c040c1fc | [
"MIT"
] | 35 | 2019-04-26T04:00:10.000Z | 2022-03-30T11:37:06.000Z | u-boot/arch/arm/include/asm/arch-gxl/i2c.h | rgomulin/aml_s905_uboot | 550de48829e852678f6cef98e94e1a97c040c1fc | [
"MIT"
] | 3 | 2019-02-23T14:19:12.000Z | 2020-11-23T17:42:50.000Z | u-boot/arch/arm/include/asm/arch-gxl/i2c.h | rgomulin/aml_s905_uboot | 550de48829e852678f6cef98e94e1a97c040c1fc | [
"MIT"
] | 11 | 2020-01-07T05:39:10.000Z | 2021-12-26T07:27:21.000Z |
/*
* arch/arm/include/asm/arch-gxb/i2c.h
*
* Copyright (C) 2015 Amlogic, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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.
*/
#ifndef __AML_MACH_I2C__
#define __AML_MACH_I2C__
#include <asm/io.h>
/**
* struct i2c_msg - an I2C transaction segment beginning with START
* @addr: Slave address, either seven or ten bits. When this is a ten
* bit address, I2C_M_TEN must be set in @flags and the adapter
* must support I2C_FUNC_10BIT_ADDR.
* @flags: I2C_M_RD is handled by all adapters. No other flags may be
* provided unless the adapter exported the relevant I2C_FUNC_*
* flags through i2c_check_functionality().
* @len: Number of data bytes in @buf being read from or written to the
* I2C slave address. For read transactions where I2C_M_RECV_LEN
* is set, the caller guarantees that this buffer can hold up to
* 32 bytes in addition to the initial length byte sent by the
* slave (plus, if used, the SMBus PEC); and this value will be
* incremented by the number of block data bytes received.
* @buf: The buffer into which data is read, or from which it's written.
*
* An i2c_msg is the low level representation of one segment of an I2C
* transaction. It is visible to drivers in the @i2c_transfer() procedure,
* to userspace from i2c-dev, and to I2C adapter drivers through the
* @i2c_adapter.@master_xfer() method.
*
* Except when I2C "protocol mangling" is used, all I2C adapters implement
* the standard rules for I2C transactions. Each transaction begins with a
* START. That is followed by the slave address, and a bit encoding read
* versus write. Then follow all the data bytes, possibly including a byte
* with SMBus PEC. The transfer terminates with a NAK, or when all those
* bytes have been transferred and ACKed. If this is the last message in a
* group, it is followed by a STOP. Otherwise it is followed by the next
* @i2c_msg transaction segment, beginning with a (repeated) START.
*
* Alternatively, when the adapter supports I2C_FUNC_PROTOCOL_MANGLING then
* passing certain @flags may have changed those standard protocol behaviors.
* Those flags are only for use with broken/nonconforming slaves, and with
* adapters which are known to support the specific mangling options they
* need (one or more of IGNORE_NAK, NO_RD_ACK, NOSTART, and REV_DIR_ADDR).
*/
struct i2c_msg {
__u16 addr; /* slave address */
__u16 flags;
#define I2C_M_TEN 0x0010 /* this is a ten bit chip address */
#define I2C_M_RD 0x0001 /* read data, from slave to master */
#define I2C_M_NOSTART 0x4000 /* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_REV_DIR_ADDR 0x2000 /* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_IGNORE_NAK 0x1000 /* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NO_RD_ACK 0x0800 /* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_RECV_LEN 0x0400 /* length will be first received byte */
__u16 len; /* msg length */
__u8 *buf; /* pointer to msg data */
};
#define I2C_M_0_CONTROL_REG 0x2140
/*#define I2C_M_0_SLAVE_ADDR 0x2141
#define I2C_M_0_TOKEN_LIST0 0x2142
#define I2C_M_0_TOKEN_LIST1 0x2143
#define I2C_M_0_WDATA_REG0 0x2144
#define I2C_M_0_WDATA_REG1 0x2145
#define I2C_M_0_RDATA_REG0 0x2146
#define I2C_M_0_RDATA_REG1 0x2147
*/
#define I2C_S_CONTROL_REG 0x2150
#define I2C_M_1_CONTROL_REG 0x21f0
#define I2C_M_2_CONTROL_REG 0x21f8
#define I2C_M_3_CONTROL_REG 0x2348
#define MESON_I2C_MASTER_AO_START (0xc8100500)
#define MESON_I2C_MASTER_AO_END (0xc810051c+5)
#define MESON_I2C_MASTER_A_START CBUS_REG_ADDR(I2C_M_0_CONTROL_REG)
#define MESON_I2C_MASTER_A_END (CBUS_REG_ADDR(I2C_M_0_RDATA_REG1+1)-1)
#define MESON_I2C_MASTER_B_START CBUS_REG_ADDR(I2C_M_1_CONTROL_REG)
#define MESON_I2C_MASTER_B_END (CBUS_REG_ADDR(I2C_M_1_RDATA_REG1+1)-1)
#define MESON_I2C_MASTER_C_START CBUS_REG_ADDR(I2C_M_2_CONTROL_REG)
#define MESON_I2C_MASTER_C_END (CBUS_REG_ADDR(I2C_M_2_RDATA_REG1+1)-1)
#define MESON_I2C_MASTER_D_START CBUS_REG_ADDR(I2C_M_3_CONTROL_REG)
#define MESON_I2C_MASTER_D_END (CBUS_REG_ADDR(I2C_M_3_RDATA_REG1+1)-1)
#define MESON_I2C_SLAVE_START CBUS_REG_ADDR(I2C_S_CONTROL_REG)
#define MESON_I2C_SLAVE_END (CBUS_REG_ADDR(I2C_S_CNTL1_REG+1)-1)
#define AML_I2C_MASTER_AO 0
#define AML_I2C_MASTER_A 1
#define AML_I2C_MASTER_B 2
#define AML_I2C_MASTER_C 3
#define AML_I2C_MASTER_D 4
#define AML_I2C_SLAVE_ADDR 0x6c
/*M1 i2c pinmux
* I/O I2C_MASTER_A I2C_MASTER_B I2C_SLAVE
* GPIO_JTAG_TMS SCK_A REG1[12] SCK_A REG1[13]
* GPIO_JTAG_TDI SDA_A REG1[12] SDA_A REG1[13]
* GPIO_JTAG_TCK SCK_B REG1[16] SCK_A REG1[17]
* GPIO_JTAG_TDO SDA_B REG1[20] SDA_A REG1[21]
* GPIOB_0 SCK_B REG2[5] SCK_A REG2[6]
* GPIOB_1 SDA_B REG2[2] SDA_A REG2[3]
* GPIOB_2 SCK_A REGS[13] SCK_A REG2[14]
* GPIOB_3 SDA_A REG2[9] SDA_A REG2[10]
* GPIOC_13 SCK_B REG3[28] SCK_A REG3[29]
* GPIOC_14 SDA_B REG3[25] SDA_A REG3[26]
* GPIOC_21 SCK_A REG7[9] SCK_A REG7[10]
* GPIOC_22 SDA_A REG7[6] SDA_A REG7[7]
* GPIOE_16 SCK_B REG5[27] SCK_A REG5[28]
* GPIOE_17 SDA_B REG5[25] SDA_A REG5[26]
*/
/*i2c master a*/
#define MESON_I2C_MASTER_A_GPIODV_24_REG (P_PERIPHS_PIN_MUX_7)
#define MESON_I2C_MASTER_A_GPIODV_24_BIT (1<<27)
#define MESON_I2C_MASTER_A_GPIODV_25_REG (P_PERIPHS_PIN_MUX_7)
#define MESON_I2C_MASTER_A_GPIODV_25_BIT (1<<26)
/*i2c master b*/
#define MESON_I2C_MASTER_B_GPIODV_26_REG (P_PERIPHS_PIN_MUX_7)
#define MESON_I2C_MASTER_B_GPIODV_26_BIT (1<<25)
#define MESON_I2C_MASTER_B_GPIODV_27_REG (P_PERIPHS_PIN_MUX_7)
#define MESON_I2C_MASTER_B_GPIODV_27_BIT (1<<24)
/*i2c master c*/
#define MESON_I2C_MASTER_C_GPIODV_28_REG (P_PERIPHS_PIN_MUX_7)
#define MESON_I2C_MASTER_C_GPIODV_28_BIT (1<<23)
#define MESON_I2C_MASTER_C_GPIODV_29_REG (P_PERIPHS_PIN_MUX_7)
#define MESON_I2C_MASTER_C_GPIODV_29_BIT (1<<22)
/*i2c master d*/
#define MESON_I2C_MASTER_D_GPIOX_16_REG (PERIPHS_PIN_MUX_4)
#define MESON_I2C_MASTER_D_GPIOX_16_BIT (1<<3)
#define MESON_I2C_MASTER_D_GPIOX_17_REG (PERIPHS_PIN_MUX_4)
#define MESON_I2C_MASTER_D_GPIOX_17_BIT (1<<2)
/*i2c master AO*/
#define MESON_I2C_MASTER_AO_GPIOAO_4_REG (P_AO_RTI_PIN_MUX_REG)
#define MESON_I2C_MASTER_AO_GPIOAO_4_BIT (1<<6)
#define MESON_I2C_MASTER_AO_GPIOAO_5_REG (P_AO_RTI_PIN_MUX_REG)
#define MESON_I2C_MASTER_AO_GPIOAO_5_BIT (1<<5)
/*i2c slave*/
#define AML_I2C_SPPED_50K 50000
#define AML_I2C_SPPED_100K 100000
#define AML_I2C_SPPED_200K 200000
#define AML_I2C_SPPED_300K 300000
#define AML_I2C_SPPED_400K 400000
struct aml_pinmux_reg_bit {
unsigned long scl_reg;
unsigned long sda_reg;
unsigned int scl_bit;
unsigned int sda_bit;
};
struct aml_i2c_platform{
unsigned int slave_addr;/*7bit addr*/
unsigned int wait_count;/*i2c wait ack timeout =
wait_count * wait_ack_interval */
unsigned int wait_ack_interval;
unsigned int wait_read_interval;
unsigned int wait_xfer_interval;
unsigned int master_no;
unsigned int use_pio;/*0: hardware i2c, 1: manual pio i2c*/
unsigned int master_i2c_speed;
/* only need 1 i2c master to comunicate with several devices,
* should I prepare 2 master interface to use simultaneously?*/
struct resource * resource;
struct aml_pinmux_reg_bit master_ao_pinmux;
struct aml_pinmux_reg_bit master_a_pinmux;
struct aml_pinmux_reg_bit master_b_pinmux;
struct aml_pinmux_reg_bit master_c_pinmux;
struct aml_pinmux_reg_bit master_d_pinmux;
struct aml_pinmux_reg_bit slave_reg_bit;
};
/**************i2c software gpio***************/
#define MESON_I2C_PREG_GPIOC_OE CBUS_REG_ADDR(PREG_FGPIO_EN_N)
#define MESON_I2C_PREG_GPIOC_OUTLVL CBUS_REG_ADDR(PREG_FGPIO_O)
#define MESON_I2C_PREG_GPIOC_INLVL CBUS_REG_ADDR(PREG_FGPIO_I)
#define MESON_I2C_PREG_GPIOE_OE CBUS_REG_ADDR(PREG_HGPIO_EN_N)
#define MESON_I2C_PREG_GPIOE_OUTLVL CBUS_REG_ADDR(PREG_HGPIO_O)
#define MESON_I2C_PREG_GPIOE_INLVL CBUS_REG_ADDR(PREG_HGPIO_I)
#define MESON_I2C_PREG_GPIOA_OE CBUS_REG_ADDR(PREG_EGPIO_EN_N)
#define MESON_I2C_PREG_GPIOA_OUTLVL CBUS_REG_ADDR(PREG_EGPIO_O)
#define MESON_I2C_PREG_GPIOA_INLVL CBUS_REG_ADDR(PREG_EGPIO_I)
struct aml_sw_i2c_pins
{
unsigned int scl_reg_out;
unsigned int scl_reg_in;
unsigned int scl_bit;
unsigned int scl_oe;
unsigned int sda_reg_out;
unsigned int sda_reg_in;
unsigned int sda_bit;
unsigned int sda_oe;
};
struct aml_sw_i2c_platform {
struct aml_sw_i2c_pins sw_pins;
/* local settings */
int udelay; /* half clock cycle time in us,
minimum 2 us for fast-mode I2C,
minimum 5 us for standard-mode I2C and SMBus,
maximum 50 us for SMBus */
int timeout; /* in jiffies */
};
#endif //__AML_MACH_I2C__
| 38.810484 | 78 | 0.752312 |
8e5a4f2372cc23c91768346ffaa4a0659f853002 | 745 | h | C | ui/events/gesture_detection/gesture_provider_config_helper.h | sunjc53yy/chromium | 049b380040949089c2a6e447b0cd0ac3c4ece38e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/events/gesture_detection/gesture_provider_config_helper.h | sunjc53yy/chromium | 049b380040949089c2a6e447b0cd0ac3c4ece38e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/events/gesture_detection/gesture_provider_config_helper.h | sunjc53yy/chromium | 049b380040949089c2a6e447b0cd0ac3c4ece38e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_EVENTS_GESTURE_DETECTION_GESTURE_PROVIDER_CONFIG_HELPER_H_
#define UI_EVENTS_GESTURE_DETECTION_GESTURE_PROVIDER_CONFIG_HELPER_H_
#include "ui/events/gesture_detection/gesture_detection_export.h"
#include "ui/events/gesture_detection/gesture_detector.h"
#include "ui/events/gesture_detection/gesture_provider.h"
#include "ui/events/gesture_detection/scale_gesture_detector.h"
namespace ui {
GESTURE_DETECTION_EXPORT GestureProvider::Config DefaultGestureProviderConfig();
} // namespace ui
#endif // UI_EVENTS_GESTURE_DETECTION_GESTURE_PROVIDER_CONFIG_HELPER_H_
| 37.25 | 80 | 0.845638 |
8e845da8e83110bf0908510a39e076fbe4d0abb3 | 31,239 | c | C | source/programs/Xserver/hw/darwin/darwin.c | binaryblob01/zfree86 | e80ea992d87501b8e3e2d7c07a414591c2e11c70 | [
"Xnet",
"X11"
] | 1 | 2021-09-08T21:13:25.000Z | 2021-09-08T21:13:25.000Z | source/programs/Xserver/hw/darwin/darwin.c | binaryblob01/zfree86 | e80ea992d87501b8e3e2d7c07a414591c2e11c70 | [
"Xnet",
"X11"
] | null | null | null | source/programs/Xserver/hw/darwin/darwin.c | binaryblob01/zfree86 | e80ea992d87501b8e3e2d7c07a414591c2e11c70 | [
"Xnet",
"X11"
] | 1 | 2021-01-22T00:19:47.000Z | 2021-01-22T00:19:47.000Z | /**************************************************************
*
* Shared code for the Darwin X Server
* running with Quartz or IOKit display mode
*
**************************************************************/
/*
* Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE ABOVE LISTED COPYRIGHT HOLDER(S) 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.
*
* Except as contained in this notice, the name(s) of the above copyright
* holders shall not be used in advertising or otherwise to promote the sale,
* use or other dealings in this Software without prior written authorization.
*/
/* $XFree86: xc/programs/Xserver/hw/darwin/darwin.c,v 1.64 2007/04/03 00:21:07 tsi Exp $ */
#include <X11/X.h>
#include <X11/Xproto.h>
#include "os.h"
#include "servermd.h"
#include "inputstr.h"
#include "scrnintstr.h"
#include "mibstore.h" // mi backing store implementation
#include "mipointer.h" // mi software cursor
#include "micmap.h" // mi colormap code
#include "fb.h" // fb framebuffer code
#include "site.h"
#include "globals.h"
#include "xf86Version.h"
#include "xf86Date.h"
#include "dix.h"
#ifdef XINPUT
# include <X11/extensions/XI.h>
# include <X11/extensions/XIproto.h>
# include "exevents.h"
# include "extinit.h"
#endif
#include <sys/types.h>
#include <sys/time.h>
#include <sys/syslimits.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#define NO_CFPLUGIN
#include <IOKit/IOKitLib.h>
#include <IOKit/hidsystem/IOHIDLib.h>
#include <IOKit/hidsystem/ev_keymap.h>
#include "darwin.h"
#include "darwinClut8.h"
/*
* X server shared global variables
*/
int darwinScreensFound = 0;
int darwinScreenIndex = 0;
io_connect_t darwinParamConnect = 0;
int darwinEventReadFD = -1;
int darwinEventWriteFD = -1;
int darwinMouseAccelChange = 1;
int darwinFakeButtons = 0;
// location of X11's (0,0) point in global screen coordinates
int darwinMainScreenX = 0;
int darwinMainScreenY = 0;
// parameters read from the command line or user preferences
unsigned int darwinDesiredWidth = 0, darwinDesiredHeight = 0;
int darwinDesiredDepth = -1;
int darwinDesiredRefresh = -1;
char *darwinKeymapFile = "USA.keymapping";
int darwinSyncKeymap = FALSE;
int darwinSwapAltMeta = FALSE;
// modifier masks for faking mouse buttons
int darwinFakeMouse2Mask = NX_COMMANDMASK;
int darwinFakeMouse3Mask = NX_ALTERNATEMASK;
// devices
DeviceIntPtr darwinPointer = NULL;
DeviceIntPtr darwinKeyboard = NULL;
// Common pixmap formats
static PixmapFormatRec formats[] = {
{ 1, 1, BITMAP_SCANLINE_PAD },
{ 4, 8, BITMAP_SCANLINE_PAD },
{ 8, 8, BITMAP_SCANLINE_PAD },
{ 15, 16, BITMAP_SCANLINE_PAD },
{ 16, 16, BITMAP_SCANLINE_PAD },
{ 24, 32, BITMAP_SCANLINE_PAD },
{ 32, 32, BITMAP_SCANLINE_PAD }
};
const int NUMFORMATS = sizeof(formats)/sizeof(formats[0]);
#ifndef OSNAME
#define OSNAME " Darwin"
#endif
#ifndef OSVENDOR
#define OSVENDOR ""
#endif
#ifndef PRE_RELEASE
#define PRE_RELEASE XF86_VERSION_SNAP
#endif
void
DarwinPrintBanner()
{
#if PRE_RELEASE
ErrorF("\n"
"This is a pre-release version of XFree86, and is not supported in any\n"
"way. Bugs may be reported to XFree86@XFree86.Org and patches submitted\n"
"to fixes@XFree86.Org. Before reporting bugs in pre-release versions,\n"
"please check the latest version in the XFree86 CVS repository\n"
"(http://www.XFree86.Org/cvs)\n");
#endif
ErrorF("\nXFree86 Version %d.%d.%d", XF86_VERSION_MAJOR, XF86_VERSION_MINOR,
XF86_VERSION_PATCH);
#if XF86_VERSION_SNAP > 0
ErrorF(".%d", XF86_VERSION_SNAP);
#endif
#if XF86_VERSION_SNAP >= 900
ErrorF(" (%d.%d.0 RC %d)", XF86_VERSION_MAJOR, XF86_VERSION_MINOR + 1,
XF86_VERSION_SNAP - 900);
#endif
#ifdef XF86_CUSTOM_VERSION
ErrorF(" (%s)", XF86_CUSTOM_VERSION);
#endif
ErrorF(" / X Window System\n");
ErrorF("(protocol Version %d, revision %d)\n",
X_PROTOCOL, X_PROTOCOL_REVISION);
ErrorF("Release Date: %s\n", XF86_DATE);
ErrorF("\tIf the server is older than 6-12 months, or if your hardware is\n"
"\tnewer than the above date, look for a newer version before\n"
"\treporting problems. (See http://www.XFree86.Org/FAQ)\n");
ErrorF("Operating System:%s%s\n", OSNAME, OSVENDOR);
#if defined(BUILDERSTRING)
ErrorF("%s \n",BUILDERSTRING);
#endif
}
/*
* DarwinSaveScreen
* X screensaver support. Not implemented.
*/
static Bool DarwinSaveScreen(ScreenPtr pScreen, int on)
{
// FIXME
if (on == SCREEN_SAVER_FORCER) {
} else if (on == SCREEN_SAVER_ON) {
} else {
}
return TRUE;
}
/*
* DarwinAddScreen
* This is a callback from dix during AddScreen() from InitOutput().
* Initialize the screen and communicate information about it back to dix.
*/
static Bool DarwinAddScreen(
int index,
ScreenPtr pScreen,
const int argc,
const char **argv )
{
int bitsPerRGB, i, dpi;
static int foundIndex = 0;
Bool ret;
VisualPtr visual;
ColormapPtr pmap;
DarwinFramebufferPtr dfb;
// reset index of found screens for each server generation
if (index == 0) foundIndex = 0;
// allocate space for private per screen storage
dfb = xalloc(sizeof(DarwinFramebufferRec));
SCREEN_PRIV(pScreen) = dfb;
// setup hardware/mode specific details
ret = DarwinModeAddScreen(foundIndex, pScreen);
foundIndex++;
if (! ret)
return FALSE;
bitsPerRGB = dfb->bitsPerComponent;
// reset the visual list
miClearVisualTypes();
// setup a single visual appropriate for our pixel type
if (dfb->colorType == TrueColor) {
if (!miSetVisualTypes( dfb->colorBitsPerPixel, TrueColorMask,
bitsPerRGB, TrueColor )) {
return FALSE;
}
} else if (dfb->colorType == PseudoColor) {
if (!miSetVisualTypes( dfb->colorBitsPerPixel, PseudoColorMask,
bitsPerRGB, PseudoColor )) {
return FALSE;
}
} else if (dfb->colorType == StaticColor) {
if (!miSetVisualTypes( dfb->colorBitsPerPixel, StaticColorMask,
bitsPerRGB, StaticColor )) {
return FALSE;
}
} else {
return FALSE;
}
miSetPixmapDepths();
// machine independent screen init
// setup _Screen structure in pScreen
if (monitorResolution)
dpi = monitorResolution;
else
dpi = 75;
// initialize fb
if (! fbScreenInit(pScreen,
dfb->framebuffer, // pointer to screen bitmap
dfb->width, dfb->height, // screen size in pixels
dpi, dpi, // dots per inch
dfb->pitch/(dfb->bitsPerPixel/8), // pixel width of framebuffer
dfb->bitsPerPixel)) // bits per pixel for screen
{
return FALSE;
}
// set the RGB order correctly for TrueColor
if (dfb->bitsPerPixel > 8) {
for (i = 0, visual = pScreen->visuals; // someday we may have more than 1
i < pScreen->numVisuals; i++, visual++) {
if (visual->class == TrueColor) {
visual->offsetRed = bitsPerRGB * 2;
visual->offsetGreen = bitsPerRGB;
visual->offsetBlue = 0;
visual->redMask = ((1<<bitsPerRGB)-1) << visual->offsetRed;
visual->greenMask = ((1<<bitsPerRGB)-1) << visual->offsetGreen;
visual->blueMask = ((1<<bitsPerRGB)-1) << visual->offsetBlue;
}
}
}
#ifdef RENDER
if (! fbPictureInit(pScreen, 0, 0)) {
return FALSE;
}
#endif
// this must be initialized (why doesn't X have a default?)
pScreen->SaveScreen = DarwinSaveScreen;
// finish mode dependent screen setup including cursor support
if (!DarwinModeSetupScreen(index, pScreen)) {
return FALSE;
}
// create and install the default colormap and
// set pScreen->blackPixel / pScreen->white
if (!miCreateDefColormap( pScreen )) {
return FALSE;
}
/* Set the colormap to the statically defined one if we're in 8 bit
* mode and we're using a fixed color map. Essentially this translates
* to Darwin/x86 in 8-bit mode.
*/
if( (dfb->colorBitsPerPixel == 8) &&
(dfb->colorType == StaticColor) )
{
pmap = miInstalledMaps[pScreen->myNum];
visual = pmap->pVisual;
for( i = 0; i < visual->ColormapEntries; i++ ) {
pmap->red[i].co.local.red = darwinClut8[i].red;
pmap->red[i].co.local.green = darwinClut8[i].green;
pmap->red[i].co.local.blue = darwinClut8[i].blue;
}
}
dixScreenOrigins[index].x = dfb->x;
dixScreenOrigins[index].y = dfb->y;
ErrorF("Screen %d added: %dx%d @ (%d,%d)\n",
index, dfb->width, dfb->height, dfb->x, dfb->y);
return TRUE;
}
/*
=============================================================================
mouse and keyboard callbacks
=============================================================================
*/
/*
* DarwinChangePointerControl
* Set mouse acceleration and thresholding
* FIXME: We currently ignore the threshold in ctrl->threshold.
*/
static void DarwinChangePointerControl(
DeviceIntPtr device,
PtrCtrl *ctrl )
{
kern_return_t kr;
double acceleration;
if (!darwinMouseAccelChange)
return;
acceleration = ctrl->num / ctrl->den;
kr = IOHIDSetMouseAcceleration( darwinParamConnect, acceleration );
if (kr != KERN_SUCCESS)
ErrorF( "Could not set mouse acceleration with kernel return = 0x%x.\n", kr );
}
/*
* DarwinMouseProc
* Handle the initialization, etc. of a mouse
*/
static int DarwinMouseProc(
DeviceIntPtr pPointer,
int what )
{
unsigned char map[6];
switch (what) {
case DEVICE_INIT:
pPointer->public.on = FALSE;
// Set button map.
map[1] = 1;
map[2] = 2;
map[3] = 3;
map[4] = 4;
map[5] = 5;
InitPointerDeviceStruct( (DevicePtr)pPointer,
map,
5, // numbuttons (4 & 5 are scroll wheel)
miPointerGetMotionEvents,
DarwinChangePointerControl,
0 );
#ifdef XINPUT
InitValuatorAxisStruct( pPointer,
0, // X axis
0, // min value
16000, // max value (fixme screen size?)
1, // resolution (fixme ?)
1, // min resolution
1 ); // max resolution
InitValuatorAxisStruct( pPointer,
1, // X axis
0, // min value
16000, // max value (fixme screen size?)
1, // resolution (fixme ?)
1, // min resolution
1 ); // max resolution
#endif
break;
case DEVICE_ON:
pPointer->public.on = TRUE;
AddEnabledDevice( darwinEventReadFD );
return Success;
case DEVICE_CLOSE:
case DEVICE_OFF:
pPointer->public.on = FALSE;
RemoveEnabledDevice( darwinEventReadFD );
return Success;
}
return Success;
}
/*
* DarwinKeybdProc
* Callback from X
*/
static int DarwinKeybdProc( DeviceIntPtr pDev, int onoff )
{
switch ( onoff ) {
case DEVICE_INIT:
DarwinKeyboardInit( pDev );
break;
case DEVICE_ON:
pDev->public.on = TRUE;
AddEnabledDevice( darwinEventReadFD );
break;
case DEVICE_OFF:
pDev->public.on = FALSE;
RemoveEnabledDevice( darwinEventReadFD );
break;
case DEVICE_CLOSE:
break;
}
return Success;
}
/*
===========================================================================
Utility routines
===========================================================================
*/
/*
* DarwinFindLibraryFile
* Search for a file in the standard Library paths, which are (in order):
*
* ~/Library/ user specific
* /Library/ host specific
* /Network/Library/ LAN specific
* /System/Library/ OS specific
*
* A sub-path can be specified to search in below the various Library
* directories. Returns a new character string (owned by the caller)
* containing the full path to the first file found.
*/
static char * DarwinFindLibraryFile(
const char *file,
const char *pathext )
{
// Library search paths
char *pathList[] = {
"",
"/Network",
"/System",
NULL
};
char *home;
char *fullPath;
int i = 0;
// Return the file name as is if it is already a fully qualified path.
if (!access(file, F_OK)) {
fullPath = xalloc(strlen(file)+1);
strcpy(fullPath, file);
return fullPath;
}
fullPath = xalloc(PATH_MAX);
home = getenv("HOME");
if (home) {
snprintf(fullPath, PATH_MAX, "%s/Library/%s/%s", home, pathext, file);
if (!access(fullPath, F_OK))
return fullPath;
}
while (pathList[i]) {
snprintf(fullPath, PATH_MAX, "%s/Library/%s/%s", pathList[i++],
pathext, file);
if (!access(fullPath, F_OK))
return fullPath;
}
xfree(fullPath);
return NULL;
}
/*
* DarwinParseModifierList
* Parse a list of modifier names and return a corresponding modifier mask
*/
static int DarwinParseModifierList(
const char *constmodifiers) // string containing list of modifier names
{
int result = 0;
if (constmodifiers) {
char *modifiers = strdup(constmodifiers);
char *modifier;
int nxkey;
char *p = modifiers;
while (p) {
modifier = strsep(&p, " ,+&|/"); // allow lots of separators
nxkey = DarwinModifierStringToNXKey(modifier);
if (nxkey != -1)
result |= DarwinModifierNXKeyToNXMask(nxkey);
else
ErrorF("fakebuttons: Unknown modifier \"%s\"\n", modifier);
}
free(modifiers);
}
return result;
}
/*
===========================================================================
Functions needed to link against device independent X
===========================================================================
*/
/*
* InitInput
* Register the keyboard and mouse devices
*/
void InitInput( const int argc, const char **argv )
{
darwinPointer = AddInputDevice(DarwinMouseProc, TRUE);
RegisterPointerDevice( darwinPointer );
darwinKeyboard = AddInputDevice(DarwinKeybdProc, TRUE);
RegisterKeyboardDevice( darwinKeyboard );
DarwinEQInit( (DevicePtr)darwinKeyboard, (DevicePtr)darwinPointer );
DarwinModeInitInput(argc, argv);
}
/*
* DarwinAdjustScreenOrigins
* Shift all screens so the X11 (0, 0) coordinate is at the top
* left of the global screen coordinates.
*
* Screens can be arranged so the top left isn't on any screen, so
* instead use the top left of the leftmost screen as (0,0). This
* may mean some screen space is in -y, but it's better that (0,0)
* be onscreen, or else default xterms disappear. It's better that
* -y be used than -x, because when popup menus are forced
* "onscreen" by dumb window managers like twm, they'll shift the
* menus down instead of left, which still looks funny but is an
* easier target to hit.
*/
void
DarwinAdjustScreenOrigins(ScreenInfo *pScreenInfo)
{
int i, left, top;
left = dixScreenOrigins[0].x;
top = dixScreenOrigins[0].y;
/* Find leftmost screen. If there's a tie, take the topmost of the two. */
for (i = 1; i < pScreenInfo->numScreens; i++) {
if (dixScreenOrigins[i].x < left ||
(dixScreenOrigins[i].x == left &&
dixScreenOrigins[i].y < top))
{
left = dixScreenOrigins[i].x;
top = dixScreenOrigins[i].y;
}
}
darwinMainScreenX = left;
darwinMainScreenY = top;
/* Shift all screens so that there is a screen whose top left
is at X11 (0,0) and at global screen coordinate
(darwinMainScreenX, darwinMainScreenY). */
if (darwinMainScreenX != 0 || darwinMainScreenY != 0) {
for (i = 0; i < pScreenInfo->numScreens; i++) {
dixScreenOrigins[i].x -= darwinMainScreenX;
dixScreenOrigins[i].y -= darwinMainScreenY;
ErrorF("Screen %d placed at X11 coordinate (%d,%d).\n",
i, dixScreenOrigins[i].x, dixScreenOrigins[i].y);
}
}
}
/*
* InitOutput
* Initialize screenInfo for all actually accessible framebuffers.
*
* The display mode dependent code gets called three times. The mode
* specific InitOutput routines are expected to discover the number
* of potentially useful screens and cache routes to them internally.
* Inside DarwinAddScreen are two other mode specific calls.
* A mode specific AddScreen routine is called for each screen to
* actually initialize the screen with the ScreenPtr structure.
* After other screen setup has been done, a mode specific
* SetupScreen function can be called to finalize screen setup.
*/
void InitOutput( ScreenInfo *pScreenInfo, const int argc, const char **argv )
{
int i;
static unsigned long generation = 0;
pScreenInfo->imageByteOrder = IMAGE_BYTE_ORDER;
pScreenInfo->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT;
pScreenInfo->bitmapScanlinePad = BITMAP_SCANLINE_PAD;
pScreenInfo->bitmapBitOrder = BITMAP_BIT_ORDER;
// List how we want common pixmap formats to be padded
pScreenInfo->numPixmapFormats = NUMFORMATS;
for (i = 0; i < NUMFORMATS; i++)
pScreenInfo->formats[i] = formats[i];
// Allocate private storage for each screen's Darwin specific info
if (generation != serverGeneration) {
darwinScreenIndex = AllocateScreenPrivateIndex();
generation = serverGeneration;
}
// Discover screens and do mode specific initialization
DarwinModeInitOutput(argc, argv);
// Add screens
for (i = 0; i < darwinScreensFound; i++) {
AddScreen( DarwinAddScreen, argc, argv );
}
DarwinAdjustScreenOrigins(pScreenInfo);
}
/*
* OsVendorFataError
*/
void OsVendorFatalError( void )
{
ErrorF( " OsVendorFatalError\n" );
}
/*
* OsVendorPreInit
*/
void OsVendorPreInit(void)
{
}
/*
* OsVendorInit
* Initialization of Darwin OS support.
*/
void OsVendorInit(void)
{
if (serverGeneration == 1) {
DarwinPrintBanner();
}
// Find the full path to the keymapping file.
if ( darwinKeymapFile ) {
char *tempStr = DarwinFindLibraryFile(darwinKeymapFile, "Keyboards");
if ( !tempStr ) {
ErrorF("Could not find keymapping file %s.\n", darwinKeymapFile);
} else {
ErrorF("Using keymapping provided in %s.\n", tempStr);
}
darwinKeymapFile = tempStr;
}
if ( !darwinKeymapFile ) {
ErrorF("Reading keymap from the system.\n");
}
}
/*
* ddxProcessArgument --
* Process device-dependent command line args. Returns 0 if argument is
* not device dependent, otherwise Count of number of elements of argv
* that are part of a device dependent commandline option.
*/
int ddxProcessArgument( int argc, const char *argv[], int i )
{
int numDone;
if ((numDone = DarwinModeProcessArgument( argc, argv, i )))
return numDone;
if ( !strcmp( argv[i], "-fakebuttons" ) ) {
darwinFakeButtons = TRUE;
ErrorF( "Faking a three button mouse\n" );
return 1;
}
if ( !strcmp( argv[i], "-nofakebuttons" ) ) {
darwinFakeButtons = FALSE;
ErrorF( "Not faking a three button mouse\n" );
return 1;
}
if (!strcmp( argv[i], "-fakemouse2" ) ) {
if ( i == argc-1 ) {
FatalError( "-fakemouse2 must be followed by a modifer list\n" );
}
if (!strcasecmp(argv[i+1], "none") || !strcmp(argv[i+1], ""))
darwinFakeMouse2Mask = 0;
else
darwinFakeMouse2Mask = DarwinParseModifierList(argv[i+1]);
ErrorF("Modifier mask to fake mouse button 2 = 0x%x\n",
darwinFakeMouse2Mask);
return 2;
}
if (!strcmp( argv[i], "-fakemouse3" ) ) {
if ( i == argc-1 ) {
FatalError( "-fakemouse3 must be followed by a modifer list\n" );
}
if (!strcasecmp(argv[i+1], "none") || !strcmp(argv[i+1], ""))
darwinFakeMouse3Mask = 0;
else
darwinFakeMouse3Mask = DarwinParseModifierList(argv[i+1]);
ErrorF("Modifier mask to fake mouse button 3 = 0x%x\n",
darwinFakeMouse3Mask);
return 2;
}
if ( !strcmp( argv[i], "-swapAltMeta" ) ) {
darwinSwapAltMeta = 1;
return 1;
}
if ( !strcmp( argv[i], "-keymap" ) ) {
if ( i == argc-1 ) {
FatalError( "-keymap must be followed by a filename\n" );
}
darwinKeymapFile = (char *)argv[i+1];
return 2;
}
if ( !strcmp( argv[i], "-nokeymap" ) ) {
darwinKeymapFile = NULL;
return 1;
}
if ( !strcmp( argv[i], "+synckeymap" ) ) {
darwinSyncKeymap = TRUE;
return 1;
}
if ( !strcmp( argv[i], "-synckeymap" ) ) {
darwinSyncKeymap = FALSE;
return 1;
}
if ( !strcmp( argv[i], "-size" ) ) {
if ( i >= argc-2 ) {
FatalError( "-size must be followed by two numbers\n" );
}
#ifdef OLD_POWERBOOK_G3
ErrorF( "Ignoring unsupported -size option on old PowerBook G3\n" );
#else
darwinDesiredWidth = atoi( argv[i+1] );
darwinDesiredHeight = atoi( argv[i+2] );
ErrorF( "Attempting to use width x height = %i x %i\n",
darwinDesiredWidth, darwinDesiredHeight );
#endif
return 3;
}
if ( !strcmp( argv[i], "-depth" ) ) {
int bitDepth;
if ( i == argc-1 ) {
FatalError( "-depth must be followed by a number\n" );
}
#ifdef OLD_POWERBOOK_G3
ErrorF( "Ignoring unsupported -depth option on old PowerBook G3\n");
#else
bitDepth = atoi( argv[i+1] );
if (bitDepth == 8)
darwinDesiredDepth = 0;
else if (bitDepth == 15)
darwinDesiredDepth = 1;
else if (bitDepth == 24)
darwinDesiredDepth = 2;
else
FatalError( "Unsupported pixel depth. Use 8, 15, or 24 bits\n" );
ErrorF( "Attempting to use pixel depth of %i\n", bitDepth );
#endif
return 2;
}
if ( !strcmp( argv[i], "-refresh" ) ) {
if ( i == argc-1 ) {
FatalError( "-refresh must be followed by a number\n" );
}
#ifdef OLD_POWERBOOK_G3
ErrorF( "Ignoring unsupported -refresh option on old PowerBook G3\n");
#else
darwinDesiredRefresh = atoi( argv[i+1] );
ErrorF( "Attempting to use refresh rate of %i\n", darwinDesiredRefresh );
#endif
return 2;
}
if (!strcmp( argv[i], "-showconfig" ) || !strcmp( argv[i], "-version" )) {
DarwinPrintBanner();
exit(0);
}
// XDarwinStartup uses this argument to indicate the IOKit X server
// should be started. Ignore it here.
if ( !strcmp( argv[i], "-iokit" ) ) {
return 1;
}
return 0;
}
/*
* ddxUseMsg --
* Print out correct use of device dependent commandline options.
* Maybe the user now knows what really to do ...
*/
void ddxUseMsg( void )
{
ErrorF("\n");
ErrorF("\n");
ErrorF("Device Dependent Usage:\n");
ErrorF("\n");
ErrorF("-fakebuttons : fake a three button mouse with Command and Option keys.\n");
ErrorF("-nofakebuttons : don't fake a three button mouse.\n");
ErrorF("-fakemouse2 <modifiers> : fake middle mouse button with modifier keys.\n");
ErrorF("-fakemouse3 <modifiers> : fake right mouse button with modifier keys.\n");
ErrorF(" ex: -fakemouse2 \"option,shift\" = option-shift-click is middle button.\n");
ErrorF("-keymap <file> : read the keymapping from a file instead of the kernel.\n");
ErrorF("-version : show the server version.\n");
ErrorF("\n");
#ifdef DARWIN_WITH_QUARTZ
ErrorF("Quartz modes:\n");
ErrorF("-fullscreen : run full screen in parallel with Mac OS X window server.\n");
ErrorF("-rootless : run rootless inside Mac OS X window server.\n");
ErrorF("-quartz : use default Mac OS X window server mode\n");
ErrorF("\n");
ErrorF("Options ignored in rootless mode:\n");
#endif
ErrorF("-size <height> <width> : use a screen resolution of <height> x <width>.\n");
ErrorF("-depth <8,15,24> : use this bit depth.\n");
ErrorF("-refresh <rate> : use a monitor refresh rate of <rate> Hz.\n");
ErrorF("\n");
}
/*
* ddxGiveUp --
* Device dependent cleanup. Called by dix before normal server death.
*/
void ddxGiveUp( void )
{
ErrorF( "Quitting XDarwin...\n" );
DarwinModeGiveUp();
}
/*
* AbortDDX --
* DDX - specific abort routine. Called by AbortServer(). The attempt is
* made to restore all original setting of the displays. Also all devices
* are closed.
*/
void AbortDDX( void )
{
ErrorF( " AbortDDX\n" );
/*
* This is needed for a abnormal server exit, since the normal exit stuff
* MUST also be performed (i.e. the vt must be left in a defined state)
*/
ddxGiveUp();
}
#ifdef DPMSExtension
/*
* DPMS extension stubs
*/
Bool DPMSSupported(void)
{
return FALSE;
}
void DPMSSet(int level)
{
}
int DPMSGet(int *level)
{
return -1;
}
#endif
#include "mivalidate.h" // for union _Validate used by windowstr.h
#include "windowstr.h" // for struct _Window
#include "scrnintstr.h" // for struct _Screen
// This is copied from Xserver/hw/xfree86/common/xf86Helper.c.
// Quartz mode uses this when switching in and out of Quartz.
// Quartz or IOKit can use this when waking from sleep.
// Copyright (c) 1997-1998 by The XFree86 Project, Inc.
/*
* xf86SetRootClip --
* Enable or disable rendering to the screen by
* setting the root clip list and revalidating
* all of the windows
*/
void
xf86SetRootClip (ScreenPtr pScreen, BOOL enable)
{
WindowPtr pWin = WindowTable[pScreen->myNum];
WindowPtr pChild;
Bool WasViewable = (Bool)(pWin->viewable);
Bool anyMarked = TRUE;
RegionPtr pOldClip = NULL, bsExposed;
#ifdef DO_SAVE_UNDERS
Bool dosave = FALSE;
#endif
WindowPtr pLayerWin;
BoxRec box;
if (WasViewable)
{
for (pChild = pWin->firstChild; pChild; pChild = pChild->nextSib)
{
(void) (*pScreen->MarkOverlappedWindows)(pChild,
pChild,
&pLayerWin);
}
(*pScreen->MarkWindow) (pWin);
anyMarked = TRUE;
if (pWin->valdata)
{
if (HasBorder (pWin))
{
RegionPtr borderVisible;
borderVisible = REGION_CREATE(pScreen, NullBox, 1);
REGION_SUBTRACT(pScreen, borderVisible,
&pWin->borderClip, &pWin->winSize);
pWin->valdata->before.borderVisible = borderVisible;
}
pWin->valdata->before.resized = TRUE;
}
}
/*
* Use REGION_BREAK to avoid optimizations in ValidateTree
* that assume the root borderClip can't change well, normally
* it doesn't...)
*/
if (enable)
{
box.x1 = 0;
box.y1 = 0;
box.x2 = pScreen->width;
box.y2 = pScreen->height;
REGION_RESET(pScreen, &pWin->borderClip, &box);
REGION_BREAK (pWin->drawable.pScreen, &pWin->clipList);
}
else
{
REGION_EMPTY(pScreen, &pWin->borderClip);
REGION_BREAK (pWin->drawable.pScreen, &pWin->clipList);
}
ResizeChildrenWinSize (pWin, 0, 0, 0, 0);
if (WasViewable)
{
if (pWin->backStorage)
{
pOldClip = REGION_CREATE(pScreen, NullBox, 1);
REGION_COPY(pScreen, pOldClip, &pWin->clipList);
}
if (pWin->firstChild)
{
anyMarked |= (*pScreen->MarkOverlappedWindows)(pWin->firstChild,
pWin->firstChild,
(WindowPtr *)NULL);
}
else
{
(*pScreen->MarkWindow) (pWin);
anyMarked = TRUE;
}
#ifdef DO_SAVE_UNDERS
if (DO_SAVE_UNDERS(pWin))
{
dosave = (*pScreen->ChangeSaveUnder)(pLayerWin, pLayerWin);
}
#endif /* DO_SAVE_UNDERS */
if (anyMarked)
(*pScreen->ValidateTree)(pWin, NullWindow, VTOther);
}
if (pWin->backStorage &&
((pWin->backingStore == Always) || WasViewable))
{
if (!WasViewable)
pOldClip = &pWin->clipList; /* a convenient empty region */
bsExposed = (*pScreen->TranslateBackingStore)
(pWin, 0, 0, pOldClip,
pWin->drawable.x, pWin->drawable.y);
if (WasViewable)
REGION_DESTROY(pScreen, pOldClip);
if (bsExposed)
{
RegionPtr valExposed = NullRegion;
if (pWin->valdata)
valExposed = &pWin->valdata->after.exposed;
(*pScreen->WindowExposures) (pWin, valExposed, bsExposed);
if (valExposed)
REGION_EMPTY(pScreen, valExposed);
REGION_DESTROY(pScreen, bsExposed);
}
}
if (WasViewable)
{
if (anyMarked)
(*pScreen->HandleExposures)(pWin);
#ifdef DO_SAVE_UNDERS
if (dosave)
(*pScreen->PostChangeSaveUnder)(pLayerWin, pLayerWin);
#endif /* DO_SAVE_UNDERS */
if (anyMarked && pScreen->PostValidateTree)
(*pScreen->PostValidateTree)(pWin, NullWindow, VTOther);
}
if (pWin->realized)
WindowsRestructured ();
FlushAllOutput ();
}
| 29.415254 | 91 | 0.596722 |
c25eec9d24f0813a5a694489cfd41e86ca164e21 | 611 | h | C | src/lua5/imlua_image.h | sonoro1234/mirror-im | bd34a8cdaac62eac99f5fa1de7510bbe18aaf7af | [
"MIT"
] | null | null | null | src/lua5/imlua_image.h | sonoro1234/mirror-im | bd34a8cdaac62eac99f5fa1de7510bbe18aaf7af | [
"MIT"
] | null | null | null | src/lua5/imlua_image.h | sonoro1234/mirror-im | bd34a8cdaac62eac99f5fa1de7510bbe18aaf7af | [
"MIT"
] | null | null | null | /** \file
* \brief IM Lua 5 Binding
*
* See Copyright Notice in im_lib.h
*/
#ifndef __IMLUA_IMAGE_H
#define __IMLUA_IMAGE_H
#if defined(__cplusplus)
extern "C" {
#endif
typedef struct _imluaImageChannel {
imImage *image;
int channel;
} imluaImageChannel;
typedef struct _imluaImageLine {
imImage *image;
int channel;
int lin;
} imluaImageLine;
void imlua_open_image(lua_State *L);
int imlua_pushimageerror(lua_State *L, imImage* image, int error);
void imlua_pushimage(lua_State *L, imImage* image);
imImage* imlua_checkimage(lua_State *L, int param);
#ifdef __cplusplus
}
#endif
#endif
| 16.078947 | 66 | 0.743044 |
b0772d2af32fdd585f0e73dd248d68485bcf24fd | 946 | h | C | src/mt.h | faemiyah/faemiyah-demoscene_2009-08_4k-graphics_solitary_confinement | a489b95c49f95bf9fa821eac7b1a613ce765abaa | [
"BSD-3-Clause"
] | null | null | null | src/mt.h | faemiyah/faemiyah-demoscene_2009-08_4k-graphics_solitary_confinement | a489b95c49f95bf9fa821eac7b1a613ce765abaa | [
"BSD-3-Clause"
] | null | null | null | src/mt.h | faemiyah/faemiyah-demoscene_2009-08_4k-graphics_solitary_confinement | a489b95c49f95bf9fa821eac7b1a613ce765abaa | [
"BSD-3-Clause"
] | null | null | null | #ifndef _MERSEINNE_TWISTER
#define _MERSEINNE_TWISTER
/* initializes mt[N] with a seed */
void init_genrand(unsigned long s);
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
void init_by_array(unsigned long init_key[], int key_length);
/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void);
/* generates a random number on [0,0x7fffffff]-interval */
long genrand_int31(void);
/* generates a random number on [0,1]-real-interval */
double genrand_real1(void);
/* generates a random number on [0,1)-real-interval */
double genrand_real2(void);
/* generates a random number on (0,1)-real-interval */
double genrand_real3(void);
/* generates a random number on [0,1) with 53-bit resolution*/
double genrand_res53(void);
/* These real versions are due to Isaku Wada, 2002/01/09 added */
#endif | 30.516129 | 66 | 0.719873 |
b85c6eb0ce05e2c04e600c90c2d5b15d8d003ce2 | 3,203 | h | C | CalendarLib/MGCEventsRowView.h | Android-iOS-App/Calendar | 63a5002f35f2f6ee24cb780b5fa1ed8d6b225ce5 | [
"MIT"
] | null | null | null | CalendarLib/MGCEventsRowView.h | Android-iOS-App/Calendar | 63a5002f35f2f6ee24cb780b5fa1ed8d6b225ce5 | [
"MIT"
] | null | null | null | CalendarLib/MGCEventsRowView.h | Android-iOS-App/Calendar | 63a5002f35f2f6ee24cb780b5fa1ed8d6b225ce5 | [
"MIT"
] | null | null | null | //
// MGCEventsRowView.h
// Graphical Calendars Library for iOS
//
// Distributed under the MIT License
// Get the latest version from here:
//
// https://github.com/SymonhayMoroz/Calendar
//
// Copyright (c) 2014-2015 iOS Developer.
//
// 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.
//
#import <UIKit/UIKit.h>
#import "MGCEventView.h"
#import "MGCReusableObjectQueue.h"
@class MGCEventsRowView;
@protocol MGCEventsRowViewDelegate <UIScrollViewDelegate>
- (NSUInteger)eventsRowView:(MGCEventsRowView*)view numberOfEventsForDayAtIndex:(NSUInteger)day;
- (NSRange)eventsRowView:(MGCEventsRowView*)view rangeForEventAtIndexPath:(NSIndexPath*)indexPath;
- (MGCEventView*)eventsRowView:(MGCEventsRowView*)view cellForEventAtIndexPath:(NSIndexPath*)indexPath;
@optional
- (CGFloat)eventsRowView:(MGCEventsRowView*)view widthForDayRange:(NSRange)range;
- (BOOL)eventsRowView:(MGCEventsRowView*)view shouldSelectCellAtIndexPath:(NSIndexPath*)indexPath;
- (void)eventsRowView:(MGCEventsRowView*)view didSelectCellAtIndexPath:(NSIndexPath*)indexPath;
- (BOOL)eventsRowView:(MGCEventsRowView*)view shouldDeselectCellAtIndexPath:(NSIndexPath*)indexPath;
- (void)eventsRowView:(MGCEventsRowView*)view didDeselectCellAtIndexPath:(NSIndexPath*)indexPath;
- (void)eventsRowView:(MGCEventsRowView*)view willDisplayCell:(MGCEventView*)cell forEventAtIndexPath:(NSIndexPath*)indexPath;
- (void)eventsRowView:(MGCEventsRowView*)view didEndDisplayingCell:(MGCEventView*)cell forEventAtIndexPath:(NSIndexPath*)indexPath;
@end
@interface MGCEventsRowView : UIScrollView<MGCReusableObject>
@property (nonatomic, copy) NSString *reuseIdentifier;
@property (nonatomic, copy) NSDate *referenceDate;
@property (nonatomic) NSRange daysRange;
@property (nonatomic) CGFloat dayWidth;
@property (nonatomic) CGFloat itemHeight;
@property (nonatomic, weak) id<MGCEventsRowViewDelegate> delegate;
@property (nonatomic, readonly) NSUInteger maxVisibleLines;
//@property (nonatomic) BOOL limitsToVisibleHeight;
- (void)reload;
- (NSArray*)cellsInRect:(CGRect)rect;
- (NSIndexPath*)indexPathForCellAtPoint:(CGPoint)pt;
- (MGCEventView*)cellAtIndexPath:(NSIndexPath*)indexPath;
@end
| 42.706667 | 131 | 0.791446 |
f880f211c666d47a90a247a79d82e8f3b3f558ef | 1,812 | c | C | src/PMSMCurrentRef.c | lflaherty/evcontrol-lib | df2e6fdb492840ddc184fbe92b15eefb981a1582 | [
"Apache-2.0"
] | null | null | null | src/PMSMCurrentRef.c | lflaherty/evcontrol-lib | df2e6fdb492840ddc184fbe92b15eefb981a1582 | [
"Apache-2.0"
] | null | null | null | src/PMSMCurrentRef.c | lflaherty/evcontrol-lib | df2e6fdb492840ddc184fbe92b15eefb981a1582 | [
"Apache-2.0"
] | null | null | null | /**
* PMSMCurrentRef.c
*
* Created on: Nov 22 2021
* Author: Liam Flaherty
*/
#include "PMSMCurrentRef.h"
#include <math.h>
#include "constants.h"
#include "sat.h"
void PMSMCurrentRefInit(PMSMCurrentRef_T* currentRef)
{
currentRef->tqRef = 0.0f;
currentRef->wMech = 0.0f;
currentRef->wElec = 0.0f;
currentRef->Vdc = 0.0f;
currentRef->idqRef.id = 0.0f;
currentRef->idqRef.iq = 0.0f;
currentRef->tqRefSat = 0.0f;
currentRef->tqLim = 0.0f;
currentRef->weBase = currentRef->polePairs * currentRef->wBase;
}
void PMSMCurrentRefStep(PMSMCurrentRef_T* currentRef)
{
float speed = fmaxf(fabsf(currentRef->wMech), currentRef->Pmax / currentRef->Tmax);
currentRef->tqLim = (currentRef->Vdc / currentRef->Vnom) * fminf(currentRef->Tmax, currentRef->Pmax / speed);
currentRef->tqRefSat = sat(currentRef->tqRef, -(currentRef->tqLim), currentRef->tqLim);
if (currentRef->wMech < currentRef->wBase) {
// zero d-axis control (ZDAC)
currentRef->idqRef.id = 0.0f;
currentRef->idqRef.iq = 2.0f * (currentRef->tqRefSat) / (3.0f * currentRef->polePairs * currentRef->fluxLink);
currentRef->idqRef.iq = sat(currentRef->idqRef.iq, -currentRef->Imax, currentRef->Imax);
} else {
// Field weakening
float id_fw = 2.0f * (currentRef->weBase - currentRef->wElec) * currentRef->fluxLink
/ (currentRef->wElec * currentRef->Ld);
float id = fmaxf(id_fw, -currentRef->Imax);
float iq_fw = 2.0f * (currentRef->tqRefSat) / (3.0f * currentRef->polePairs * currentRef->fluxLink);
float iq_lim = sqrtf(currentRef->Imax*currentRef->Imax - id*id);
float iq = sat(iq_fw, -iq_lim, iq_lim);
currentRef->idqRef.id = id;
currentRef->idqRef.iq = iq;
}
} | 32.945455 | 118 | 0.64128 |
0a23feef524213216f4efc2b60b5618c9dd7a840 | 4,572 | c | C | xdd-7.0.0.rc-ramses3/src/bx/bx_worker_queue.c | eunsungc/gt6-RAMSES_8_5 | 529b50245375855cffc7ab3feec45bee6dc48d2a | [
"Apache-2.0"
] | 1 | 2016-09-27T01:35:12.000Z | 2016-09-27T01:35:12.000Z | xdd-7.0.0.rc-ramses3/src/bx/bx_worker_queue.c | eunsungc/gt6-RAMSES_8_5 | 529b50245375855cffc7ab3feec45bee6dc48d2a | [
"Apache-2.0"
] | 10 | 2015-08-26T20:52:57.000Z | 2017-03-04T11:09:37.000Z | xdd-7.0.0.rc-ramses3/src/bx/bx_worker_queue.c | eunsungc/gt6-RAMSES_8_5 | 529b50245375855cffc7ab3feec45bee6dc48d2a | [
"Apache-2.0"
] | null | null | null | /*
* XDD - a data movement and benchmarking toolkit
*
* Copyright (C) 1992-2013 I/O Performance, Inc.
* Copyright (C) 2009-2013 UT-Battelle, LLC
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#define THIS_IS_A_SUBROUTINE
#include "bx_data_structures.h"
//
// Show all the members of a item header
int
bx_wd_show(struct bx_wd *bx_wdp) {
fprintf(stderr,"Worker Thread Data Structure: bx_wdp=%p, next=%p, prev=%p, flags=0x%016x\n", bx_wdp, bx_wdp->bx_wd_next, bx_wdp->bx_wd_prev, bx_wdp->bx_wd_flags);
fprintf(stderr,"Worker Thread Data Structure: bx_wdp=%p, my_worker_thread_number=%d, fd=%d\n", bx_wdp, bx_wdp->bx_wd_my_worker_thread_number, bx_wdp->bx_wd_fd);
fprintf(stderr,"Worker Thread Data Structure: bx_wdp=%p, bufhdrp=%p, next_buffer_queue=%d, my_queue=%p\n", bx_wdp, bx_wdp->bx_wd_bufhdrp, bx_wdp->bx_wd_next_buffer_queue, bx_wdp->bx_wd_my_queue);
return(0);
} // End of bx_wd_show()
//
// Show all the items on this queue
int
bx_wd_queue_show(struct bx_wd_queue *qp) {
struct bx_wd *bx_wdp;
fprintf(stderr,"\n");
fprintf(stderr,"Worker Thread Data Structure QUEUE: qp=%p, name='%s', counter=%d, flags=0x%08x\n", qp, qp->q_name, qp->q_counter, qp->q_flags);
fprintf(stderr,"Worker Thread Data Structure QUEUE: qp=%p, first=%p, last=%p\n\n", qp, qp->q_first, qp->q_last);
bx_wdp = qp->q_first;
while (bx_wdp) {
bx_wd_show(bx_wdp);
bx_wdp = bx_wdp->bx_wd_next;
}
return(0);
} // End of bx_wd_queue_show()
//
// Initialize a bx_wd queue
int
bx_wd_queue_init(struct bx_wd_queue *qp, char *q_name) {
int status;
qp->q_name = q_name;
qp->q_counter = 0;
qp->q_flags = 0;
qp->q_first = 0;
qp->q_last = 0;
status = pthread_mutex_init(&qp->q_mutex, 0);
if (status) {
perror("Error initializing Worker Thread Data Structure queue mutex");
return(-1);
}
status = pthread_cond_init(&qp->q_conditional, 0);
if (status) {
perror("Error initializing Worker Thread Data Structure queue conditional variable");
return(-1);
}
return(0);
} // End of bx_wd_queue_init()
// Items always go at the end of the linked list
int
bx_wd_enqueue(struct bx_wd *bx_wdp, struct bx_wd_queue *qp) {
struct bx_wd *tmp;
int status;
// Get the lock for this bx_wd queue
pthread_mutex_lock(&qp->q_mutex);
if (qp->q_first == 0) { // Nothing on this queue so just add it
qp->q_first = bx_wdp;
qp->q_last = qp->q_first;
qp->q_counter++;
bx_wdp->bx_wd_prev = 0;
bx_wdp->bx_wd_next = 0;
} else {
// Get the address of the last item on the list
tmp = qp->q_last;
// forward and backward link the two item headers
tmp->bx_wd_next = bx_wdp;
bx_wdp->bx_wd_prev = tmp;
bx_wdp->bx_wd_next = 0;
// Update the queue q_counter and *last* pointer
qp->q_counter++;
qp->q_last = bx_wdp;
}
// If something is waiting for something to appear in this queue then release it
if (qp->q_flags & BX_WD_WAITING) {
// Enter barrier of waiting dequeue() operation
status = pthread_cond_broadcast(&qp->q_conditional);
if ((status != 0) && (status != PTHREAD_BARRIER_SERIAL_THREAD)) {
fprintf(stderr,"bx_wd_enqueue: ERROR: pthread_cond_broadcast failed: status is %d, errno is %d\n", status, errno);
perror("Reason");
}
}
// Release the lock for this item queue
pthread_mutex_unlock(&qp->q_mutex);
return(0);
} // End of bx_wd_enqueue()
// Buffers always come from the beginning/top of the linked list
struct bx_wd *
bx_wd_dequeue(struct bx_wd_queue *qp) {
struct bx_wd *bx_wdp;
// Get the lock for this item queue
pthread_mutex_lock(&qp->q_mutex);
qp->q_flags |= BX_WD_WAITING;
while (qp->q_counter == 0) { // Nothing on this queue - wait for something to appear
pthread_cond_wait(&qp->q_conditional, &qp->q_mutex);
}
qp->q_flags &= ~BX_WD_WAITING;
// Take the first item header from this queue
bx_wdp = qp->q_first;
qp->q_first = bx_wdp->bx_wd_next;
if (qp->q_first == 0) { // This is the case where there are no more item on this queue
qp->q_last = 0;
} else { // There is at least 1 item on this queue and it's "prev" pointer must now be null
qp->q_first->bx_wd_prev = 0;
}
qp->q_counter--;
// Release the lock for this item queue
pthread_mutex_unlock(&qp->q_mutex);
return(bx_wdp);
} // End of bx_wd_dequeue()
| 30.891892 | 197 | 0.703193 |
20a79f5b1096451c4664458ebc77dfddec569c5d | 6,158 | h | C | LCMogoWeiboDemo/LCMogoWeiboDemo/BaseClass/CustomUI/LCBaseUI.h | InnerMongoliaZorro/MoGoWeiBo | f4d2de5e78825adaf8f7d300cbb222e0d0ff7302 | [
"Apache-2.0"
] | 3 | 2016-08-05T04:53:53.000Z | 2017-06-25T07:48:01.000Z | LCMogoWeiboDemo/LCMogoWeiboDemo/BaseClass/CustomUI/LCBaseUI.h | InnerMongoliaZorro/MoGoWeiBo | f4d2de5e78825adaf8f7d300cbb222e0d0ff7302 | [
"Apache-2.0"
] | null | null | null | LCMogoWeiboDemo/LCMogoWeiboDemo/BaseClass/CustomUI/LCBaseUI.h | InnerMongoliaZorro/MoGoWeiBo | f4d2de5e78825adaf8f7d300cbb222e0d0ff7302 | [
"Apache-2.0"
] | null | null | null | //
// LCBaseUI.h
// LCMogoWeiboDemo
//
// Created by 李策 on 16/4/24.
// Copyright © 2016年 李策. All rights reserved.
//
#ifndef LCBaseUI_h
#define LCBaseUI_h
#import "LCAlertView.h"
#import "LCView.h"
#import "LCLabel.h"
#import "LCButton.h"
#import "LCTableView.h"
#import "LCTableViewCell.h"
#import "LCPlaceholderTextView.h"
#import "LCTextField.h"
#import "LCTextFieldView.h"
#import "LCPlaceholderTextView.h"
#import "LCTextView.h"
#import "LCBaseLine.h"
#import "LCPoint2PointLine.h"
#import "LCView_LineMethodHeader.h"
#pragma mark 下面的宏用来添加控件的上边线和下边线的代码块
//line属性声明
#define kLineAttributeDeclarations \
\
@property (nonatomic,weak) UIView *topLineV; \
@property (nonatomic,weak) UIView *downLineV; \
\
@property (nonatomic,assign) CGFloat top_topMargin; \
@property (nonatomic,assign) CGFloat top_leftMargin; \
@property (nonatomic,assign) CGFloat top_rightMargin; \
\
@property (nonatomic,assign) CGFloat down_downMargin; \
@property (nonatomic,assign) CGFloat down_leftMargin; \
@property (nonatomic,assign) CGFloat down_rightMargin; \
\
@property (nonatomic,assign) CGFloat topLineHeight; \
@property (nonatomic,assign) CGFloat downLineHeight; \
\
@property (nonatomic,strong) UIColor *topLineColor; \
@property (nonatomic,strong) UIColor *downLineColor; \
\
\
\
@property (nonatomic,weak) UIView *leftLineV; \
@property (nonatomic,weak) UIView *rightLineV; \
\
@property (nonatomic,assign) CGFloat left_leftMargin; \
@property (nonatomic,assign) CGFloat left_topMargin; \
@property (nonatomic,assign) CGFloat left_downMargin; \
\
@property (nonatomic,assign) CGFloat right_rightMargin; \
@property (nonatomic,assign) CGFloat right_topMargin; \
@property (nonatomic,assign) CGFloat right_downMargin; \
\
@property (nonatomic,assign) CGFloat leftLineWidth; \
@property (nonatomic,assign) CGFloat rightLineWidth; \
\
@property (nonatomic,strong) UIColor *leftLineColor; \
@property (nonatomic,strong) UIColor *rightLineColor;
//line方法实现
#define kLineMethodImplementation \
\
- (void)setTop_topMargin:(CGFloat)top_topMargin{ \
_top_topMargin = top_topMargin; \
[self layoutIfNeeded]; \
} \
- (void)setTop_leftMargin:(CGFloat)top_leftMargin{ \
_top_leftMargin = top_leftMargin; \
[self layoutIfNeeded]; \
} \
- (void)setTop_rightMargin:(CGFloat)top_rightMargin{ \
_top_rightMargin = top_rightMargin; \
[self layoutIfNeeded]; \
} \
\
- (void)setTopLineHeight:(CGFloat)topLineHeight{ \
_topLineHeight = topLineHeight; \
self.topLineV.height = topLineHeight; \
[self layoutIfNeeded]; \
} \
\
- (void)setDownLineHeight:(CGFloat)downLineHeight{ \
_downLineHeight = downLineHeight; \
self.downLineV.height = downLineHeight; \
[self layoutIfNeeded]; \
} \
\
- (void)setTopLineColor:(UIColor *)topLineColor{ \
_topLineColor = topLineColor; \
self.topLineV.backgroundColor = topLineColor; \
} \
- (void)setDownLineColor:(UIColor *)downLineColor{ \
_downLineColor = downLineColor; \
self.downLineV.backgroundColor = downLineColor; \
} \
\
- (void)addTopLineWithTopMargin:(CGFloat)top_topMargin leftMargin:(CGFloat)top_leftMargin rightMargin:(CGFloat)top_rightMargin{ \
\
self.top_topMargin = top_topMargin; \
self.top_leftMargin = top_leftMargin; \
self.top_rightMargin = top_rightMargin; \
\
UIView *topLineV = [self lineV]; \
[self addSubview:topLineV]; \
self.topLineV = topLineV; \
} \
- (void)addDownLineWithDownMargin:(CGFloat)down_downMargin leftMargin:(CGFloat)down_leftMargin rightMargin:(CGFloat)down_rightMargin{ \
\
self.down_downMargin = down_downMargin; \
self.down_leftMargin = down_leftMargin; \
self.down_rightMargin = down_rightMargin; \
\
UIView *downLineV = [self lineV]; \
[self addSubview:downLineV]; \
self.downLineV = downLineV; \
} \
\
\
\
\
- (void)setLeft_leftMargin:(CGFloat)left_leftMargin{ \
_left_leftMargin = left_leftMargin; \
[self layoutIfNeeded]; \
} \
- (void)setLeft_topMargin:(CGFloat)left_topMargin{ \
_left_topMargin = left_topMargin; \
[self layoutIfNeeded]; \
} \
- (void)setLeft_downMargin:(CGFloat)left_downMargin{ \
_left_downMargin = left_downMargin; \
[self layoutIfNeeded]; \
} \
\
- (void)setLeftLineWidth:(CGFloat)leftLineWidth{ \
_leftLineWidth = leftLineWidth; \
self.leftLineV.width = leftLineWidth; \
[self layoutIfNeeded]; \
} \
\
- (void)setRightLineWidth:(CGFloat)rightLineWidth{ \
_rightLineWidth = rightLineWidth; \
self.rightLineV.width = rightLineWidth; \
[self layoutIfNeeded]; \
} \
\
- (void)setLeftLineColor:(UIColor *)leftLineColor{ \
_leftLineColor = leftLineColor; \
self.leftLineV.backgroundColor = leftLineColor; \
} \
- (void)setRightLineColor:(UIColor *)rightLineColor{ \
_rightLineColor = rightLineColor; \
self.rightLineV.backgroundColor = rightLineColor; \
} \
\
- (void)addLeftLineWithLeftMargin:(CGFloat)left_leftMargin topMargin:(CGFloat)left_topMargin downMargin:(CGFloat)left_downMargin{ \
\
self.left_leftMargin = left_leftMargin; \
self.left_topMargin = left_topMargin; \
self.left_downMargin = left_downMargin; \
\
UIView *leftLineV = [self lineV]; \
[self addSubview:leftLineV]; \
self.leftLineV = leftLineV; \
} \
- (void)addRightLineWithRightMargin:(CGFloat)right_rightMargin topMargin:(CGFloat)right_topMargin downMargin:(CGFloat)right_downMargin{ \
\
self.right_rightMargin = right_rightMargin; \
self.right_topMargin = right_topMargin; \
self.right_downMargin = right_downMargin; \
\
UIView *rightLineV = [self lineV]; \
[self addSubview:rightLineV]; \
self.rightLineV = rightLineV; \
}
//line坐标计算
#define kLineCalculationPosition \
\
self.topLineV.frame = CGRectMake(self.top_leftMargin, self.top_topMargin, self.width-self.top_leftMargin-self.top_rightMargin, self.topLineV.height); \
\
self.downLineV.frame = CGRectMake(self.down_leftMargin, self.height-self.downLineV.height-self.down_downMargin,self.width-self.down_leftMargin-self.down_rightMargin,self.downLineV.height); \
\
\
\
self.leftLineV.frame = CGRectMake(self.left_leftMargin, self.left_topMargin, self.leftLineV.width, self.height-self.left_topMargin-self.left_downMargin); \
\
self.rightLineV.frame = CGRectMake(self.width-self.right_rightMargin-self.rightLineV.width, self.right_topMargin, self.rightLineV.width, self.height-self.right_topMargin-self.right_downMargin);
#endif /* LCBaseUI_h */
| 30.79 | 193 | 0.773303 |
7c3a3535f8709ad27fac071354b670ff85b8c2b0 | 1,481 | h | C | Battleships/Source/Core/Shader/FProgramableShader.h | RodrigoHolztrattner/Battleships | cf3e9c8a4a40f52aee41a7b9baaac5a406365a06 | [
"MIT"
] | null | null | null | Battleships/Source/Core/Shader/FProgramableShader.h | RodrigoHolztrattner/Battleships | cf3e9c8a4a40f52aee41a7b9baaac5a406365a06 | [
"MIT"
] | null | null | null | Battleships/Source/Core/Shader/FProgramableShader.h | RodrigoHolztrattner/Battleships | cf3e9c8a4a40f52aee41a7b9baaac5a406365a06 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Filename: FProgramableShader.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _FProgramableShader_H_
#define _FProgramableShader_H_
/////////////
// LINKING //
/////////////
//////////////
// INCLUDES //
//////////////
#include <sstream>
#include <string>
#include <iostream>
/////////////
// DEFINES //
/////////////
////////////////////////////////////////////////////////////////////////////////
// Class name: FProgramableShader
////////////////////////////////////////////////////////////////////////////////
class FProgramableShader
{
private:
public:
FProgramableShader();
FProgramableShader(const FProgramableShader&);
~FProgramableShader();
// Output a stream of data from a intrinsic
void OutputStream(std::ostringstream* _stream);
// Call a new index for a new variable name
unsigned int GetFreeVariableIndex();
private:
// The counter for new variable indexes
unsigned int m_VariableIndex;
public:
////////////
// GLOBAL //
////////////
// <GLOBAL> Return a reference to the shader that are being build
static FProgramableShader* GetCurrentShaderReference();
// <GLOBAL> Set the current shader
static void SetCurrentShader(FProgramableShader* _currentShader);
private:
////////////
// GLOBAL //
////////////
// The current shader that are being build
static FProgramableShader* m_CurrentShader;
};
#endif
| 21.779412 | 80 | 0.519919 |
09fab79c3be3c4a3b8a9bec8fa587c00838cf288 | 6,389 | h | C | llvm_propeller_node_chain.h | sfc-gh-zyang/autofdo | 73b2bdf5154d67918fdab8748a98049c82e05b1f | [
"Apache-2.0"
] | 344 | 2015-01-07T02:10:34.000Z | 2022-03-28T07:04:44.000Z | llvm_propeller_node_chain.h | sfc-gh-zyang/autofdo | 73b2bdf5154d67918fdab8748a98049c82e05b1f | [
"Apache-2.0"
] | 90 | 2015-04-21T11:14:03.000Z | 2022-03-28T22:36:20.000Z | llvm_propeller_node_chain.h | sfc-gh-zyang/autofdo | 73b2bdf5154d67918fdab8748a98049c82e05b1f | [
"Apache-2.0"
] | 90 | 2015-03-16T06:09:29.000Z | 2022-03-28T21:54:28.000Z | #ifndef AUTOFDO_LLVM_PROPELLER_NODE_CHAIN_H_
#define AUTOFDO_LLVM_PROPELLER_NODE_CHAIN_H_
#include <algorithm>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "llvm_propeller_cfg.h"
#include "third_party/abseil/absl/container/flat_hash_set.h"
// A node chain represents an ordered list of CFG nodes, which are further
// splitted into multiple (ordered) list of nodes called bundles. For example
//
// * bundle1 {foo -> foo.1} -> bundle2 {bar} -> bundle3 {foo.2 -> foo.3}
//
// represents a chain for 4 nodes from function "foo" and one node from "bar".
// The nodes are grouped into three bundles: two bundles for "foo" and one
// bundle for "bar".
// NodeChainBuilder keeps merging chains together to form longer chains.
// Merging may be done by splitting one chains and shoving the other chain
// in between, but it cannot break any bundles. For instance, the chain above
// can only be splitted across the two bundle-joining parts (bundle1 and bundle2
// or bundle2 and bundle3). NodeChainBuilder can also "bundle-up" multiple
// bundles into a single bundle when no gains are foreseen from splitting those
// bundles.
//
// At each point in time, every node belongs to exactly one bundle which is
// contained in exactly one chain.
namespace devtools_crosstool_autofdo {
class NodeChain;
class CFGNodeBundle {
public:
// All the CFG nodes in this bundle.
std::vector<CFGNode *> nodes_;
// Containing chain for this bundle.
NodeChain *chain_;
// Offset at which this bundle is located in its containing chain.
int64_t chain_offset_;
// Total binary size of this bundle.
uint64_t size_;
// Total execution frequency of this bundle.
uint64_t freq_;
// Constructor for building a bundle for a single CFG node and placing it in a
// given chain.
CFGNodeBundle(CFGNode *n, NodeChain *c, int64_t chain_offset)
: nodes_(1, n),
chain_(c),
chain_offset_(chain_offset),
size_(n->size()),
freq_(n->freq()) {
n->set_bundle(this);
}
};
// Represents a chain of nodes (basic blocks).
class NodeChain {
public:
// Representative node for the chain.
CFGNode *delegate_node_;
// ControlFlowGraph of the nodes in this chain (This will be null if the nodes
// come from more than one cfg).
ControlFlowGraph *cfg_;
// Ordered list of the bundles of the chain.
std::vector<std::unique_ptr<CFGNodeBundle>> node_bundles_;
// Total binary size of the chain.
uint64_t size_;
// Total execution frequency of the chain.
uint64_t freq_;
struct PtrComparator {
bool operator()(const NodeChain *nc1, const NodeChain *nc2) const {
if (!nc2) return false;
if (!nc1) return true;
return nc1->id() < nc2->id();
}
};
// Each map key is a NodeChain which has (at least) one CFGNode that is
// the sink end of one of the "inter_outs_" of CFGNode in "this" NodeChain,
// the corresponding map value is the collection of CFGNodes which have
// "inter_outs_"'s sink end equals to one of the CFGNodes of the corresponding
// map key.
// Note, we use "NodeChain::PtrComparator" to make sure the iterating order is
// deterministic.
std::map<NodeChain *, std::vector<CFGEdge *>, NodeChain::PtrComparator>
out_edges_;
// Chains which have outgoing edges to this chain. Using "unordered_set"
// implies we never iterate this set (because iterating order is
// undeterministic), we only search it.
absl::flat_hash_set<NodeChain *> in_edges_;
uint64_t id() const { return delegate_node_->symbol_ordinal(); }
// Gives the execution density for this chain.
double exec_density() const {
return (static_cast<double>(freq_)) /
std::max(size_, static_cast<uint64_t>(1));
}
// Constructor for building a chain from a single node, placed in one bundle
// of its own.
explicit NodeChain(CFGNode *node) {
node_bundles_.emplace_back(new CFGNodeBundle(node, this, 0));
delegate_node_ = node;
cfg_ = node->cfg();
size_ = node->size();
freq_ = node->freq();
}
// This moves the bundles from another chain into this chain and updates the
// bundle and chain fields accordingly. After this is called, the 'other'
// chain becomes empty.
void MergeWith(NodeChain *other) {
for (auto &bundle : other->node_bundles_) {
bundle->chain_ = this;
bundle->chain_offset_ += size_;
}
std::move(other->node_bundles_.begin(), other->node_bundles_.end(),
std::back_inserter(node_bundles_));
size_ += other->size_;
freq_ += other->freq_;
// Nullify cfg_ if the other chain's nodes come from a different CFG.
if (cfg_ && cfg_ != other->cfg_)
cfg_ = nullptr;
}
CFGNode * GetFirstNode() {
return node_bundles_.front()->nodes_.front();
}
// Helper function to iterate over the outgoing edges of this chain to a
// specific chain, while applying a given function on each edge.
template <class Visitor>
void VisitEachOutEdgeToChain(NodeChain *chain, Visitor v) {
auto it = out_edges_.find(chain);
if (it == out_edges_.end()) return;
for (CFGEdge *e : it->second)
v(*e);
}
// Visit each candidate chain of this chain. This includes all the chains
// that this chain has edges to or from, excluding itself.
template <class Visitor>
void VisitEachCandidateChain(Visitor v) {
// Visit chains having edges *to* this chain.
for (auto *c : in_edges_) {
if (c == this) continue;
v(c);
}
// Visit chains having *from* this chain, excluding those visited above.
for (auto &elem : out_edges_) {
if (elem.first == this) continue;
// Chains having edges *to* this chain are already visited above.
if (in_edges_.count(elem.first)) continue;
v(elem.first);
}
}
// Helper method for iterating over all nodes in this chain (in order).
template <class Visitor>
void VisitEachNodeRef(Visitor v) {
for (auto &bundle_ptr : node_bundles_)
for (CFGNode *n : bundle_ptr->nodes_) v(*n);
}
};
// Gets the chain containing a given node.
NodeChain *GetNodeChain(const CFGNode *n);
// Gets the offset of a node in its containing chain.
int64_t GetNodeOffset(const CFGNode *n);
} // namespace devtools_crosstool_autofdo
#endif // AUTOFDO_LLVM_PROPELLER_NODE_CHAIN_H_
| 33.276042 | 80 | 0.696823 |
e59e1dccc29b54c2f3733e3244c2fcaf52d04ddc | 7,795 | h | C | src/GraphStream.h | Joey5460/ms-skim | f411e9cc854b60d7c9e6fae55a20e61473e7ee59 | [
"MIT"
] | 27 | 2016-04-13T22:26:26.000Z | 2022-03-14T03:08:11.000Z | src/GraphStream.h | Joey5460/ms-skim | f411e9cc854b60d7c9e6fae55a20e61473e7ee59 | [
"MIT"
] | 3 | 2017-04-28T09:10:15.000Z | 2021-04-08T03:45:20.000Z | src/GraphStream.h | Joey5460/ms-skim | f411e9cc854b60d7c9e6fae55a20e61473e7ee59 | [
"MIT"
] | 13 | 2016-06-03T13:04:15.000Z | 2020-11-05T22:49:02.000Z | /*
Algorithm for Influence Estimation and Maximization
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
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.
*/
#pragma once
#include "Assert.h"
#include "Types.h"
#include "FileStream.h"
using namespace std;
namespace IO {
template<typename graphType>
class GraphStream {
private:
// Forward decleration of internal arc type.
struct internalArcType;
public:
// This is entities in the graph streaming file.
enum EntityType : uint8_t {
VERTEX_META_DATA = 0,
ARC_META_DATA = 1,
ARC = 2
};
// Expose typedefs.
typedef graphType GraphType;
// Create a new instance of the class.
GraphStream() :
filename(""),
numVertices(0),
numArcs(0),
isDirected(false),
mode(UNKNOWN_MODE)
{
}
// Create a new stream to a file.
inline void New(const string fn) {
filename = fn + ".gr";
numVertices = 0;
numArcs = 0;
Close();
file.OpenNewForWriting(filename);
Assert(file.IsOpen());
mode = WRITE_MODE;
// Write a dummy header.
typename GraphType::FileHeader dummyHeader;
IO::WriteEntity(file, dummyHeader);
}
// Open a new stream for reading.
inline typename GraphType::FileHeader Open(const string fn) {
Close();
filename = fn + ".gr";
file.OpenForReading(filename);
Assert(file.IsOpen());
mode = READ_MODE;
// Extract the header from the file.
typename GraphType::FileHeader header;
header.Read(file);
Assert(header.MagicNumber == GraphType::FileHeader::CorrectMagicNumber);
return header;
}
// Reset.
inline void Reset() {
file.Reset();
file.SeekFromBeginning(sizeof(typename GraphType::FileHeader));
}
// Finished?
inline bool Finished() {
Assert(mode == READ_MODE);
return file.Finished();
}
// Number of bytes read.
inline Types::SizeType NumBytesRead() const {
Assert(mode == READ_MODE);
return file.NumBytesRead();
}
// Get next entity type.
inline EntityType GetNextEntityType() {
Assert(mode == READ_MODE);
Assert(!file.Finished());
return IO::ReadEntity<EntityType>(file);
}
// Get next arc.
inline internalArcType GetNextArc() {
Assert(mode == READ_MODE);
while(!file.Finished()) {
const EntityType currentEntity = GetNextEntityType();
switch(currentEntity) {
case ARC:
return IO::ReadEntity<internalArcType>(file);
case VERTEX_META_DATA:
file.Ignore(sizeof(typename GraphType::VertexMetaDataType));
break;
default:
cerr << "ERROR: Input file is corrupt. Next Entity has undefined header: " << currentEntity << "." << endl;
Assert(false);
}
}
Assert(false);
return internalArcType();
}
// Get next vertex meta data.
inline typename GraphType::VertexMetaDataType GetNextVertexMetaData() {
Assert(mode == READ_MODE);
while (!file.Finished()) {
const EntityType currentEntity = GetNextEntityType();
switch (currentEntity) {
case ARC:
file.Ignore(sizeof(internalArcType));
break;
case VERTEX_META_DATA:
return IO::ReadEntity<typename GraphType::VertexMetaDataType>(file);
default:
cerr << "ERROR: Input file is corrupt. Next Entity has undefined header: " << currentEntity << "." << endl;
Assert(false);
}
}
Assert(false);
return GraphType::VertexMetaDataType();
}
// Read from the stream and interpret as arc.
inline internalArcType GetArc() { Assert(mode == READ_MODE); return IO::ReadEntity<internalArcType>(file); }
// Read from the stream and interpret as vertex meta data.
inline typename GraphType::VertexMetaDataType GetVertexMetaData() { Assert(mode == READ_MODE); return IO::ReadEntity<typename GraphType::VertexMetaDataType>(file); }
// Adds a single vertex to the stream. Writes its meta data to the stream.
inline void AddVertexMetaData(const typename GraphType::VertexMetaDataType &metaData) {
Assert(mode == WRITE_MODE);
// Write the vertex's data to the stream.
if (sizeof(metaData) > 0) {
EntityType entityType = VERTEX_META_DATA;
IO::WriteEntity(file, entityType);
IO::WriteEntity(file, metaData);
}
++numVertices;
}
// Add an arc to the stream.
inline void AddArc(const typename GraphType::VertexIdType fromVertexId, const typename GraphType::VertexIdType toVertexId, const typename GraphType::ArcMetaDataType &metaData) {
Assert(mode == WRITE_MODE);
// Create temporary internal arc that is written to the stream.
internalArcType internalArc(fromVertexId, toVertexId, metaData);
const EntityType entityType = ARC;
IO::WriteEntity(file, entityType);
IO::WriteEntity(file, internalArc);
++numArcs;
}
// Sets the number of vertices to a given value.
// Only use this if you did not use AddVertex
// while creating the stream.
inline void SetNumVertices(const Types::SizeType num) { numVertices = num; }
// Sets whether the graph is considered as directed (true) or undirected (false).
inline void SetDirectedness(const bool d) { isDirected = d; }
// Close the stream. Writes the header (to the beginning).
inline void Close() {
if (!file.IsOpen()) return;
if (mode == WRITE_MODE) {
file.SeekFromBeginning(0);
typename GraphType::FileHeader header(isDirected, numVertices, numArcs);
header.Write(file);
}
file.Close();
}
// Dump statistics.
inline void DumpStatistics(ostream &os) {
if (mode == WRITE_MODE) {
cout << "The graph contained " << numVertices << " vertices and " << numArcs << " arcs (" << fixed << setprecision(2) << file.NumBytesWritten()/1024.0/1024.0 << " MiB)." << endl;
}
}
private:
// This is an internal arc representation.
struct internalArcType {
typename GraphType::VertexIdType FromVertexId;
typename GraphType::VertexIdType ToVertexId;
typename GraphType::ArcMetaDataType MetaData;
internalArcType() : FromVertexId(0), ToVertexId(0), MetaData(typename GraphType::ArcMetaDataType()) {}
internalArcType(const typename GraphType::VertexIdType f, const typename GraphType::VertexIdType t, const typename GraphType::ArcMetaDataType &m) : FromVertexId(f), ToVertexId(t), MetaData(m) {}
};
// Modes supported by the stream.
enum modeType {
UNKNOWN_MODE,
READ_MODE,
WRITE_MODE
};
// The file's associated name.
string filename;
// The file stream to write/read.
FileStream file;
// Number of vertices in the stream.
Types::SizeType numVertices;
// Number of arcs in the stream.
Types::SizeType numArcs;
// This indicates whether the graph is directed (true) or not (false).
bool isDirected;
// The mode in which this instance is currently operating.
modeType mode;
};
} | 28.87037 | 461 | 0.697242 |
bcdf1475e93cd7c051205cdb3e720f480a2c424d | 542 | h | C | PrivateFrameworks/GameCenterFoundation/GKTournamentEventListener-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/GameCenterFoundation/GKTournamentEventListener-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/GameCenterFoundation/GKTournamentEventListener-Protocol.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.
//
@class GKInvite, GKPlayer, GKTournament, GKTurnBasedMatch;
@protocol GKTournamentEventListener
@optional
- (void)localPlayerDidAcceptInviteTo:(GKTurnBasedMatch *)arg1 applicationDidBecomeActive:(BOOL)arg2;
- (void)localPlayerDidAcceptRealTimeMatchInvite:(GKInvite *)arg1 forTournament:(GKTournament *)arg2;
- (void)player:(GKPlayer *)arg1 didAcceptInviteToCustomTournament:(GKTournament *)arg2;
@end
| 31.882353 | 100 | 0.773063 |
7b569d6b94f36f9542784fc68617451d0e46acf2 | 2,167 | h | C | lua_script_instance.h | SamKDN/luascript | 133d661fd7ea390d7465faa2762f213c23ca5a21 | [
"Apache-2.0"
] | null | null | null | lua_script_instance.h | SamKDN/luascript | 133d661fd7ea390d7465faa2762f213c23ca5a21 | [
"Apache-2.0"
] | null | null | null | lua_script_instance.h | SamKDN/luascript | 133d661fd7ea390d7465faa2762f213c23ca5a21 | [
"Apache-2.0"
] | 1 | 2020-01-19T22:06:29.000Z | 2020-01-19T22:06:29.000Z | /*
* This file is part of LuaScript
* https://github.com/perbone/luascrip/
*
* Copyright 2017-2020 Paulo Perbone
*
* 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 "lua_script.h"
class LuaScriptInstance : public ScriptInstance {
friend class LuaScript;
private:
LuaScriptInstance(Object *p_owner, Ref<LuaScript> p_script);
private:
Object *owner;
Ref<LuaScript> script;
public:
virtual ~LuaScriptInstance();
virtual bool set(const StringName &p_name, const Variant &p_value);
virtual bool get(const StringName &p_name, Variant &r_ret) const;
virtual void get_property_list(List<PropertyInfo> *p_properties) const;
virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = nullptr) const;
virtual Object *get_owner();
virtual void get_method_list(List<MethodInfo> *p_list) const;
virtual bool has_method(const StringName &p_method) const;
virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error);
virtual void call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount);
virtual void call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount);
virtual void notification(int p_notification);
virtual String to_string(bool *r_valid);
virtual void refcount_incremented();
virtual bool refcount_decremented();
virtual Ref<Script> get_script() const;
virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const;
virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const;
virtual ScriptLanguage *get_language();
};
| 34.396825 | 119 | 0.777573 |
72de6d46c624983e5fcb12abe2292da15597b301 | 582 | h | C | pdp11_ram.h | rkhapov/pdp11 | 3e3f671d9d8e428c7191ed302f73099f15e15369 | [
"MIT"
] | null | null | null | pdp11_ram.h | rkhapov/pdp11 | 3e3f671d9d8e428c7191ed302f73099f15e15369 | [
"MIT"
] | null | null | null | pdp11_ram.h | rkhapov/pdp11 | 3e3f671d9d8e428c7191ed302f73099f15e15369 | [
"MIT"
] | null | null | null | #ifndef RAM_H
#define RAM_H
//classic PDP-11 ram
//dump is addeded to the abstract Ram
#include <iostream>
#include "abstr_cc_memory.h"
#include "pdp11_types.h"
namespace pdp11
{
class Ram: public abstr_cc::Ram<ubyte>
{
public:
Ram(std::size_t size):
abstr_cc::Ram<ubyte>(size)
{}
//stream - out stream to dump
//numwidth - character to single number
//ncolomns - number of colomns (numbers pers line)
void dump(std::ostream &stream, int ncolomns = 10, int numwidth = 4) const;
};
}
#endif // RAM_H
| 19.4 | 83 | 0.623711 |
8e379c2471a13fde564bdef3f549b4c1c4f512fa | 1,503 | h | C | src/host/time_bound_logger.h | caleteeter/CCF | d291a67fc1cccdbd19428a22dc0c876216039bd0 | [
"Apache-2.0"
] | null | null | null | src/host/time_bound_logger.h | caleteeter/CCF | d291a67fc1cccdbd19428a22dc0c876216039bd0 | [
"Apache-2.0"
] | 23 | 2021-11-08T07:23:47.000Z | 2022-01-17T18:49:33.000Z | src/host/time_bound_logger.h | caleteeter/CCF | d291a67fc1cccdbd19428a22dc0c876216039bd0 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "ds/logger.h"
#include <chrono>
#include <fmt/format.h>
#include <string>
namespace asynchost
{
struct TimeBoundLogger
{
using TClock = std::chrono::steady_clock;
static std::string human_time(const TClock::duration& d)
{
const auto us =
std::chrono::duration_cast<std::chrono::microseconds>(d).count();
if (us < 1000)
return fmt::format("{:>7.03f}us", us);
const auto ms = us / 1000.0f;
if (ms < 1000)
return fmt::format("{:>7.03f}ms", ms);
const auto s = ms / 1000.0f;
return fmt::format("{:>7.03f}s", s);
}
static std::chrono::microseconds default_max_time;
std::string message;
TClock::duration max_time;
TClock::time_point start_time;
TimeBoundLogger(const std::string& m) : TimeBoundLogger(m, default_max_time)
{}
template <typename Rep, typename Period>
TimeBoundLogger(
const std::string& m, const std::chrono::duration<Rep, Period>& mt) :
message(m),
max_time(std::chrono::duration_cast<TClock::duration>(mt)),
start_time(TClock::now())
{}
~TimeBoundLogger()
{
const auto end_time = TClock::now();
const auto elapsed = end_time - start_time;
if (elapsed > max_time)
{
LOG_FAIL_FMT(
"Operation took too long ({}): {}", human_time(elapsed), message);
}
}
};
} | 25.474576 | 80 | 0.618097 |
fd63d9c2cfe6866f919da940b997ca12b8ade283 | 111,994 | c | C | libndarray/src/npy_ufunc_object.c | teoliphant/numpy-refactor | cf4ed821bac2d9545d4f3753755aa338ca58f353 | [
"BSD-3-Clause"
] | 3 | 2015-08-28T21:14:11.000Z | 2022-01-21T17:02:37.000Z | libndarray/src/npy_ufunc_object.c | teoliphant/numpy-refactor | cf4ed821bac2d9545d4f3753755aa338ca58f353 | [
"BSD-3-Clause"
] | null | null | null | libndarray/src/npy_ufunc_object.c | teoliphant/numpy-refactor | cf4ed821bac2d9545d4f3753755aa338ca58f353 | [
"BSD-3-Clause"
] | 2 | 2015-03-27T14:34:10.000Z | 2018-12-20T22:47:38.000Z | /*
* Python Universal Functions Object -- CPython-independent portion
*
*/
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include "npy_config.h"
#include "npy_common.h"
#include "npy_dict.h"
#include "npy_api.h"
#include "npy_arrayobject.h"
#include "npy_iterators.h"
#include "npy_ufunc_object.h"
#include "npy_os.h"
#include "npy_math.h"
#include "npy_internal.h"
/*
* Forward decls
*/
static NpyUFuncLoopObject *
construct_loop(NpyUFuncObject *self);
static size_t
construct_arrays(NpyUFuncLoopObject *loop, size_t nargs, NpyArray **mps,
int ntypenums, int *rtypenums,
npy_prepare_outputs_func prepare,
void *prepare_data);
static NpyUFuncReduceObject *
construct_reduce(NpyUFuncObject *self, NpyArray **arr, NpyArray *out,
int axis, int otype, int operation, npy_intp ind_size);
static int
select_types(NpyUFuncObject *self, int *arg_types,
NpyUFuncGenericFunction *function, void **data,
NPY_SCALARKIND *scalars,
int ntypenums, int *rtypenums);
static int
extract_specified_loop(NpyUFuncObject *self, int *arg_types,
NpyUFuncGenericFunction *function, void **data,
int ntypesnum, int *rtypenums, int userdef);
static void
ufuncloop_dealloc(NpyUFuncLoopObject *self);
static void
ufuncreduce_dealloc(NpyUFuncReduceObject *self);
static int
_create_reduce_copy(NpyUFuncReduceObject *loop, NpyArray **arr, int rtype);
static int
_create_copies(NpyUFuncLoopObject *loop, int *arg_types, NpyArray **mps);
static int
_compute_dimension_size(NpyUFuncLoopObject *loop, NpyArray **mps, int i);
static npy_intp*
_compute_output_dims(NpyUFuncLoopObject *loop, int iarg,
int *out_nd, npy_intp *tmp_dims);
static NpyArray *
_trunc_coredim(NpyArray *ap, int core_nd);
static int
cmp_arg_types(int *arg1, int *arg2, int n);
static int
_find_matching_userloop(NpyUFunc_Loop1d *funcdata, int *arg_types,
NPY_SCALARKIND *scalars,
NpyUFuncGenericFunction *function, void **data,
int nargs, int nin);
static int
_does_loop_use_arrays(void *data);
static char _lowest_type(char intype);
static int
_parse_signature(NpyUFuncObject *self, const char *signature);
static NpyArray *
_getidentity(NpyUFuncObject *self, int otype, char *str);
NpyTypeObject NpyUFunc_Type = {
(void (*)(_NpyObject *))npy_ufunc_dealloc,
NULL
};
static void NpyErr_NoMemory()
{
NpyErr_SetString(NpyExc_MemoryError, "no memory");
}
static void default_fp_error_state(int *bufsizeRet, int *errormaskRet, void **errobjRet)
{
*bufsizeRet = NPY_BUFSIZE;
*errormaskRet = NPY_UFUNC_ERR_DEFAULT;
*errobjRet = NULL;
}
/* Global floating-point error handling. This is set by the interface
layer or, if NULL defaults to a trival internal one.
*/
static void default_fp_error_handler(char* name, int errormask, void *errobj,
int retstatus, int *first)
{
const char *msg = "unknown";
switch (errormask) {
case NPY_UFUNC_FPE_DIVIDEBYZERO:
msg = "division by zero"; break;
case NPY_UFUNC_FPE_OVERFLOW:
msg = "overflow"; break;
case NPY_UFUNC_FPE_UNDERFLOW:
msg = "underflow"; break;
case NPY_UFUNC_FPE_INVALID:
msg = "invalid"; break;
}
printf("libndarray floating point %s warning.", msg);
}
fpe_state_f fp_error_state = &default_fp_error_state;
fpe_handler_f fp_error_handler = &default_fp_error_handler;
int NpyUFunc_GenericFunction(NpyUFuncObject *self, int nargs, NpyArray **mps,
int ntypenums, int *rtypenums,
int originalArgWasObjArray,
npy_prepare_outputs_func prepare_outputs,
void *prepare_out_args)
{
NpyUFuncLoopObject *loop;
char *name = (NULL != self->name) ? self->name : "";
int res;
int i;
assert(NPY_VALID_MAGIC == self->nob_magic_number);
/* Build the loop. */
loop = construct_loop(self);
if (loop == NULL) {
return -1;
}
fp_error_state(&loop->bufsize, &loop->errormask, &loop->errobj);
/* Setup the arrays */
res = construct_arrays(loop, nargs, mps, ntypenums, rtypenums,
prepare_outputs, prepare_out_args);
if (res < 0) {
ufuncloop_dealloc(loop);
return -1;
}
/*
* FAIL with NotImplemented if the other object has
* the __r<op>__ method and has __array_priority__ as
* an attribute (signalling it can handle ndarray's)
* and is not already an ndarray or a subtype of the same type.
*/
if (self->nin == 2 && self->nout == 1 &&
NpyArray_TYPE(mps[1]) == NPY_OBJECT && originalArgWasObjArray) {
/* Return -2 for notimplemented. */
ufuncloop_dealloc(loop);
NpyErr_SetString(NpyExc_NotImplementedError, "UFunc not implemented for object");
return -2;
}
if (loop->notimplemented) {
ufuncloop_dealloc(loop);
NpyErr_SetString(NpyExc_NotImplementedError, "UFunc not implemented for object");
return -2;
}
if (self->core_enabled && loop->meth != SIGNATURE_NOBUFFER_UFUNCLOOP) {
NpyErr_SetString(NpyExc_RuntimeError,
"illegal loop method for ufunc with signature");
goto fail;
}
// NPY_LOOP_BEGIN_THREADS;
switch(loop->meth) {
case ONE_UFUNCLOOP:
/*
* Everything is contiguous, notswapped, aligned,
* and of the right type. -- Fastest.
* Or if not contiguous, then a single-stride
* increment moves through the entire array.
*/
/*fprintf(stderr, "ONE...%d\n", loop->size);*/
loop->function((char **)loop->bufptr, &(loop->iter->size),
loop->steps, loop->funcdata);
NPY_UFUNC_CHECK_ERROR(loop);
break;
case NOBUFFER_UFUNCLOOP:
/*
* Everything is notswapped, aligned and of the
* right type but not contiguous. -- Almost as fast.
*/
while (loop->iter->index < loop->iter->size) {
for (i = 0; i < self->nargs; i++) {
loop->bufptr[i] = loop->iter->iters[i]->dataptr;
}
loop->function((char **)loop->bufptr, &(loop->bufcnt),
loop->steps, loop->funcdata);
NPY_UFUNC_CHECK_ERROR(loop);
/* Adjust loop pointers */
for (i = 0; i < self->nargs; i++) {
NpyArray_ITER_NEXT(loop->iter->iters[i]);
}
loop->iter->index++;
}
break;
case SIGNATURE_NOBUFFER_UFUNCLOOP:
while (loop->iter->index < loop->iter->size) {
for (i = 0; i < self->nargs; i++) {
loop->bufptr[i] = loop->iter->iters[i]->dataptr;
}
loop->function((char **)loop->bufptr, loop->core_dim_sizes,
loop->core_strides, loop->funcdata);
NPY_UFUNC_CHECK_ERROR(loop);
/* Adjust loop pointers */
for (i = 0; i < self->nargs; i++) {
NpyArray_ITER_NEXT(loop->iter->iters[i]);
}
loop->iter->index++;
}
break;
case BUFFER_UFUNCLOOP: {
/* This should be a function */
NpyArray_CopySwapNFunc *copyswapn[NPY_MAXARGS];
NpyArrayIterObject **iters=loop->iter->iters;
int *swap=loop->swap;
char **dptr=loop->dptr;
int mpselsize[NPY_MAXARGS];
npy_intp laststrides[NPY_MAXARGS];
int fastmemcpy[NPY_MAXARGS];
int *needbuffer = loop->needbuffer;
npy_intp index=loop->iter->index, size=loop->iter->size;
int bufsize;
npy_intp bufcnt;
int copysizes[NPY_MAXARGS];
char **bufptr = loop->bufptr;
char **buffer = loop->buffer;
char **castbuf = loop->castbuf;
npy_intp *steps = loop->steps;
char *tptr[NPY_MAXARGS];
int ninnerloops = loop->ninnerloops;
npy_bool pyobject[NPY_MAXARGS];
int datasize[NPY_MAXARGS];
int j, k, stopcondition;
char *myptr1, *myptr2;
for (i = 0; i <self->nargs; i++) {
copyswapn[i] = NpyArray_DESCR(mps[i])->f->copyswapn;
mpselsize[i] = NpyArray_DESCR(mps[i])->elsize;
pyobject[i] = ((loop->obj & NPY_UFUNC_OBJ_ISOBJECT)
&& (NpyArray_TYPE(mps[i]) == NPY_OBJECT));
laststrides[i] = iters[i]->strides[loop->lastdim];
if (steps[i] && laststrides[i] != mpselsize[i]) {
fastmemcpy[i] = 0;
}
else {
fastmemcpy[i] = 1;
}
}
/* Do generic buffered looping here (works for any kind of
* arrays -- some need buffers, some don't.
*
*
* New algorithm: N is the largest dimension. B is the buffer-size.
* quotient is loop->ninnerloops-1
* remainder is loop->leftover
*
* Compute N = quotient * B + remainder.
* quotient = N / B # integer math
* (store quotient + 1) as the number of innerloops
* remainder = N % B # integer remainder
*
* On the inner-dimension we will have (quotient + 1) loops where
* the size of the inner function is B for all but the last when
* the niter size is remainder.
*
* So, the code looks very similar to NOBUFFER_LOOP except the
* inner-most loop is replaced with...
*
* for(i=0; i<quotient+1; i++) {
* if (i==quotient+1) make itersize remainder size
* copy only needed items to buffer.
* swap input buffers if needed
* cast input buffers if needed
* call loop_function()
* cast outputs in buffers if needed
* swap outputs in buffers if needed
* copy only needed items back to output arrays.
* update all data-pointers by strides*niter
* }
*/
/*
* fprintf(stderr, "BUFFER...%d,%d,%d\n", loop->size,
* loop->ninnerloops, loop->leftover);
*/
/*
* for(i=0; i<self->nargs; i++) {
* fprintf(stderr, "iters[%d]->dataptr = %p, %p of size %d\n", i,
* iters[i], iters[i]->ao->data, PyArray_NBYTES(iters[i]->ao));
* }
*/
stopcondition = ninnerloops;
if (loop->leftover == 0) {
stopcondition--;
}
while (index < size) {
bufsize=loop->bufsize;
for(i = 0; i<self->nargs; i++) {
tptr[i] = loop->iter->iters[i]->dataptr;
if (needbuffer[i]) {
dptr[i] = bufptr[i];
datasize[i] = (steps[i] ? bufsize : 1);
copysizes[i] = datasize[i] * mpselsize[i];
}
else {
dptr[i] = tptr[i];
}
}
/* This is the inner function over the last dimension */
for (k = 1; k<=stopcondition; k++) {
if (k == ninnerloops) {
bufsize = loop->leftover;
for (i=0; i<self->nargs;i++) {
if (!needbuffer[i]) {
continue;
}
datasize[i] = (steps[i] ? bufsize : 1);
copysizes[i] = datasize[i] * mpselsize[i];
}
}
for (i = 0; i < self->nin; i++) {
if (!needbuffer[i]) {
continue;
}
if (fastmemcpy[i]) {
memcpy(buffer[i], tptr[i], copysizes[i]);
}
else {
myptr1 = buffer[i];
myptr2 = tptr[i];
for (j = 0; j < bufsize; j++) {
memcpy(myptr1, myptr2, mpselsize[i]);
myptr1 += mpselsize[i];
myptr2 += laststrides[i];
}
}
/* swap the buffer if necessary */
if (swap[i]) {
/* fprintf(stderr, "swapping...\n");*/
copyswapn[i](buffer[i], mpselsize[i], NULL, -1,
(npy_intp) datasize[i], 1,
mps[i]);
}
/* cast to the other buffer if necessary */
if (loop->cast[i]) {
/* fprintf(stderr, "casting... %d, %p %p\n", i, buffer[i]); */
loop->cast[i](buffer[i], castbuf[i],
(npy_intp) datasize[i],
NULL, NULL);
}
}
bufcnt = (npy_intp) bufsize;
loop->function((char **)dptr, &bufcnt, steps,
loop->funcdata);
NPY_UFUNC_CHECK_ERROR(loop);
for (i = self->nin; i < self->nargs; i++) {
if (!needbuffer[i]) {
continue;
}
if (loop->cast[i]) {
/* fprintf(stderr, "casting back... %d, %p", i,
castbuf[i]); */
loop->cast[i](castbuf[i],
buffer[i],
(npy_intp) datasize[i],
NULL, NULL);
}
if (swap[i]) {
copyswapn[i](buffer[i], mpselsize[i], NULL, -1,
(npy_intp) datasize[i], 1,
mps[i]);
}
/* copy back to output arrays decref what's already
there for object arrays */
if (pyobject[i]) {
myptr1 = tptr[i];
for (j = 0; j < datasize[i]; j++) {
NpyInterface_DECREF(*((void **)myptr1));
myptr1 += laststrides[i];
}
}
if (fastmemcpy[i]) {
memcpy(tptr[i], buffer[i], copysizes[i]);
}
else {
myptr2 = buffer[i];
myptr1 = tptr[i];
for (j = 0; j < bufsize; j++) {
memcpy(myptr1, myptr2, mpselsize[i]);
myptr1 += laststrides[i];
myptr2 += mpselsize[i];
}
}
}
if (k == stopcondition) {
continue;
}
for (i = 0; i < self->nargs; i++) {
tptr[i] += bufsize * laststrides[i];
if (!needbuffer[i]) {
dptr[i] = tptr[i];
}
}
}
/* end inner function over last dimension */
if (loop->objfunc) {
/*
* DECREF castbuf when underlying function used
* object arrays and casting was needed to get
* to object arrays
*/
for (i = 0; i < self->nargs; i++) {
if (loop->cast[i]) {
if (steps[i] == 0) {
NpyInterface_DECREF(*((void **)castbuf[i]));
}
else {
int size = loop->bufsize;
void **objptr = (void **)castbuf[i];
/*
* size is loop->bufsize unless there
* was only one loop
*/
if (ninnerloops == 1) {
size = loop->leftover;
}
for (j = 0; j < size; j++) {
NpyInterface_DECREF(*objptr);
*objptr = NULL;
objptr += 1;
}
}
}
}
/* Prevent doing the decref twice on an error. */
loop->objfunc = 0;
}
/* fixme -- probably not needed here*/
NPY_UFUNC_CHECK_ERROR(loop);
for (i = 0; i < self->nargs; i++) {
NpyArray_ITER_NEXT(loop->iter->iters[i]);
}
index++;
}
} /* end of last case statement */
}
// NPY_LOOP_END_THREADS;
for (i=0; i<nargs; i++) {
if (mps[i] && (mps[i]->flags&NPY_UPDATEIFCOPY)) {
NpyArray_ForceUpdate(mps[i]);
}
}
ufuncloop_dealloc(loop);
return 0;
fail:
// NPY_LOOP_END_THREADS;
if (loop) {
if (loop->objfunc) {
char **castbuf = loop->castbuf;
npy_intp *steps = loop->steps;
int ninnerloops = loop->ninnerloops;
int j;
/*
* DECREF castbuf when underlying function used
* object arrays and casting was needed to get
* to object arrays
*/
for (i = 0; i < self->nargs; i++) {
if (loop->cast[i]) {
if (steps[i] == 0) {
NpyInterface_DECREF(*((void **)castbuf[i]));
}
else {
int size = loop->bufsize;
void **objptr = (void **)castbuf[i];
/*
* size is loop->bufsize unless there
* was only one loop
*/
if (ninnerloops == 1) {
size = loop->leftover;
}
for (j = 0; j < size; j++) {
NpyInterface_DECREF(*objptr);
*objptr = NULL;
objptr += 1;
}
}
}
}
}
ufuncloop_dealloc(loop);
}
return -1;
}
NpyArray *
NpyUFunc_GenericReduction(NpyUFuncObject *self, NpyArray *arr, NpyArray *indices,
NpyArray *out, int axis, NpyArray_Descr *otype, int operation)
{
static char *_reduce_type[] = {"reduce", "accumulate", "reduceat", NULL};
NpyArray *ret = NULL;
/* Check to see if input is zero-dimensional */
if (NpyArray_NDIM(arr) == 0) {
char buf[256];
sprintf(buf, "cannot %s on a scalar",
_reduce_type[operation]);
NpyErr_SetString(NpyExc_TypeError, buf);
Npy_DECREF(arr);
return NULL;
}
/* Check to see that type (and otype) is not FLEXIBLE */
if (NpyArray_ISFLEXIBLE(arr) ||
(NULL != otype && NpyTypeNum_ISFLEXIBLE(otype->type_num))) {
char buf[256];
sprintf(buf, "cannot perform %s with flexible type",
_reduce_type[operation]);
NpyErr_SetString(NpyExc_TypeError, buf);
return NULL;
}
if (axis < 0) {
axis += NpyArray_NDIM(arr);
}
if (axis < 0 || axis >= NpyArray_NDIM(arr)) {
NpyErr_SetString(NpyExc_ValueError, "axis not in array");
return NULL;
}
/*
* If out is specified it determines otype
* unless otype already specified.
*/
if (otype == NULL && out != NULL) {
otype = NpyArray_DESCR(out);
Npy_INCREF(otype);
}
if (otype == NULL) {
/*
* For integer types --- make sure at least a long
* is used for add and multiply reduction to avoid overflow
*/
int typenum = NpyArray_TYPE(arr);
if ((typenum < NPY_FLOAT)
&& ((strcmp(self->name,"add") == 0)
|| (strcmp(self->name,"multiply") == 0))) {
if (NpyTypeNum_ISBOOL(typenum)) {
typenum = NPY_LONG;
}
else if ((size_t)NpyArray_ITEMSIZE(arr) < sizeof(long)) {
if (NpyTypeNum_ISUNSIGNED(typenum)) {
typenum = NPY_ULONG;
}
else {
typenum = NPY_LONG;
}
}
}
otype = NpyArray_DescrFromType(typenum);
}
switch(operation) {
case NPY_UFUNC_REDUCE:
ret = NpyUFunc_Reduce(self, arr, out, axis,
otype->type_num);
break;
case NPY_UFUNC_ACCUMULATE:
ret = NpyUFunc_Accumulate(self, arr, out, axis,
otype->type_num);
break;
case NPY_UFUNC_REDUCEAT:
ret = NpyUFunc_Reduceat(self, arr, indices, out,
axis, otype->type_num);
Npy_DECREF(indices);
break;
default:
assert(0);
break;
}
return ret;
}
/*
* We have two basic kinds of loops. One is used when arr is not-swapped
* and aligned and output type is the same as input type. The other uses
* buffers when one of these is not satisfied.
*
* Zero-length and one-length axes-to-be-reduced are handled separately.
*/
NpyArray *
NpyUFunc_Reduce(NpyUFuncObject *self, NpyArray *arr, NpyArray *out,
int axis, int otype)
{
NpyArray *ret = NULL;
NpyUFuncReduceObject *loop;
npy_intp i, n;
char *dptr;
// NPY_BEGIN_THREADS_DEF
assert(arr == NULL ||
(NPY_VALID_MAGIC == arr->nob_magic_number &&
NPY_VALID_MAGIC == NpyArray_DESCR(arr)->nob_magic_number));
assert(NPY_VALID_MAGIC == self->nob_magic_number);
/* Construct loop object */
loop = construct_reduce(self, &arr, out, axis, otype, NPY_UFUNC_REDUCE, 0);
if (!loop) {
return NULL;
}
// NPY_LOOP_BEGIN_THREADS;
switch(loop->meth) {
case ZERO_EL_REDUCELOOP:
/* fprintf(stderr, "ZERO..%d\n", loop->size); */
for (i = 0; i < loop->size; i++) {
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->idptr));
} else {
memmove(loop->bufptr[0], loop->idptr, loop->outsize);
}
loop->bufptr[0] += loop->outsize;
}
break;
case ONE_EL_REDUCELOOP:
/*fprintf(stderr, "ONEDIM..%d\n", loop->size); */
while (loop->index < loop->size) {
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->it->dataptr));
} else {
memmove(loop->bufptr[0], loop->it->dataptr, loop->outsize);
}
NpyArray_ITER_NEXT(loop->it);
loop->bufptr[0] += loop->outsize;
loop->index++;
}
break;
case NOBUFFER_UFUNCLOOP:
/*fprintf(stderr, "NOBUFFER..%d\n", loop->size); */
while (loop->index < loop->size) {
/* Copy first element to output */
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->it->dataptr));
} else {
memmove(loop->bufptr[0], loop->it->dataptr, loop->outsize);
}
/* Adjust input pointer */
loop->bufptr[1] = loop->it->dataptr+loop->steps[1];
loop->function((char **)loop->bufptr, &(loop->N),
loop->steps, loop->funcdata);
NPY_UFUNC_CHECK_ERROR(loop);
NpyArray_ITER_NEXT(loop->it);
loop->bufptr[0] += loop->outsize;
loop->bufptr[2] = loop->bufptr[0];
loop->index++;
}
break;
case BUFFER_UFUNCLOOP:
/*
* use buffer for arr
*
* For each row to reduce
* 1. copy first item over to output (casting if necessary)
* 2. Fill inner buffer
* 3. When buffer is filled or end of row
* a. Cast input buffers if needed
* b. Call inner function.
* 4. Repeat 2 until row is done.
*/
/* fprintf(stderr, "BUFFERED..%d %d\n", loop->size, loop->swap); */
while(loop->index < loop->size) {
loop->inptr = loop->it->dataptr;
/* Copy (cast) First term over to output */
if (loop->cast) {
/* A little tricky because we need to cast it first */
NpyArray_DESCR(arr)->f->copyswap(loop->buffer, loop->inptr,
loop->swap, NULL);
loop->cast(loop->buffer, loop->castbuf, 1, NULL, NULL);
if ((loop->obj & NPY_UFUNC_OBJ_ISOBJECT) &&
!NpyArray_ISOBJECT(arr)) {
/*
* In this case the cast function is creating
* an object reference so we need to incref
* it since we care copying it to bufptr[0].
*/
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->castbuf));
} else {
memcpy(loop->bufptr[0], loop->castbuf, loop->outsize);
}
}
else {
/* Simple copy */
NpyArray_DESCR(arr)->f->copyswap(loop->bufptr[0],
loop->inptr,
loop->swap, NULL);
}
loop->inptr += loop->instrides;
n = 1;
while(n < loop->N) {
/* Copy up to loop->bufsize elements to buffer */
dptr = loop->buffer;
for (i = 0; i < loop->bufsize; i++, n++) {
if (n == loop->N) {
break;
}
NpyArray_DESCR(arr)->f->copyswap(dptr, loop->inptr,
loop->swap, NULL);
loop->inptr += loop->instrides;
dptr += loop->insize;
}
if (loop->cast) {
loop->cast(loop->buffer, loop->castbuf, i, NULL, NULL);
}
loop->function((char **)loop->bufptr, &i,
loop->steps, loop->funcdata);
loop->bufptr[0] += loop->steps[0]*i;
loop->bufptr[2] += loop->steps[2]*i;
NPY_UFUNC_CHECK_ERROR(loop);
}
NpyArray_ITER_NEXT(loop->it);
loop->bufptr[0] += loop->outsize;
loop->bufptr[2] = loop->bufptr[0];
loop->index++;
}
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
/*
* DECREF left-over objects if buffering was used.
* There are 2 cases here.
* 1. The output is an object. In this case the
* castfunc will produce objects and castbuf needs
* to be decrefed.
* 2. The input is an object array. In this case
* the copyswap will produce object references and
* the buffer needs to be decrefed.
*/
if (!NpyArray_ISOBJECT(arr)) {
for (i=0; i<loop->bufsize; i++) {
NpyInterface_CLEAR(((void **)loop->castbuf)[i]);
}
} else {
for (i=0; i<loop->bufsize; i++) {
NpyInterface_CLEAR(((void **)loop->buffer)[i]);
}
}
}
}
// NPY_LOOP_END_THREADS;
/* Hang on to this reference -- will be decref'd with loop */
if (loop->retbase) {
ret = loop->ret->base_arr;
NpyArray_ForceUpdate(loop->ret);
}
else {
ret = loop->ret;
}
Npy_INCREF(ret);
ufuncreduce_dealloc(loop);
return ret;
fail:
// NPY_LOOP_END_THREADS;
if (loop) {
ufuncreduce_dealloc(loop);
}
return NULL;
}
NpyArray *
NpyUFunc_Accumulate(NpyUFuncObject *self, NpyArray *arr, NpyArray *out,
int axis, int otype)
{
NpyArray *ret = NULL;
NpyUFuncReduceObject *loop;
npy_intp i, n;
char *dptr;
// NPY_BEGIN_THREADS_DEF
assert(NPY_VALID_MAGIC == self->nob_magic_number);
/* Construct loop object */
loop = construct_reduce(self, &arr, out, axis, otype,
NPY_UFUNC_ACCUMULATE, 0);
if (!loop) {
return NULL;
}
// NPY_LOOP_BEGIN_THREADS;
switch(loop->meth) {
case ZERO_EL_REDUCELOOP:
/* Accumulate */
/* fprintf(stderr, "ZERO..%d\n", loop->size); */
for (i = 0; i < loop->size; i++) {
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->idptr));
} else {
memcpy(loop->bufptr[0], loop->idptr, loop->outsize);
}
loop->bufptr[0] += loop->outsize;
}
break;
case ONE_EL_REDUCELOOP:
/* Accumulate */
/* fprintf(stderr, "ONEDIM..%d\n", loop->size); */
while (loop->index < loop->size) {
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->it->dataptr));
} else {
memmove(loop->bufptr[0], loop->it->dataptr, loop->outsize);
}
NpyArray_ITER_NEXT(loop->it);
loop->bufptr[0] += loop->outsize;
loop->index++;
}
break;
case NOBUFFER_UFUNCLOOP:
/* Accumulate */
/* fprintf(stderr, "NOBUFFER..%d\n", loop->size); */
while (loop->index < loop->size) {
/* Copy first element to output */
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->it->dataptr));
} else {
memmove(loop->bufptr[0], loop->it->dataptr, loop->outsize);
}
/* Adjust input pointer */
loop->bufptr[1] = loop->it->dataptr + loop->steps[1];
loop->function((char **)loop->bufptr, &(loop->N),
loop->steps, loop->funcdata);
NPY_UFUNC_CHECK_ERROR(loop);
NpyArray_ITER_NEXT(loop->it);
NpyArray_ITER_NEXT(loop->rit);
loop->bufptr[0] = loop->rit->dataptr;
loop->bufptr[2] = loop->bufptr[0] + loop->steps[0];
loop->index++;
}
break;
case BUFFER_UFUNCLOOP:
/* Accumulate
*
* use buffer for arr
*
* For each row to reduce
* 1. copy identity over to output (casting if necessary)
* 2. Fill inner buffer
* 3. When buffer is filled or end of row
* a. Cast input buffers if needed
* b. Call inner function.
* 4. Repeat 2 until row is done.
*/
/* fprintf(stderr, "BUFFERED..%d %p\n", loop->size, loop->cast); */
while (loop->index < loop->size) {
loop->inptr = loop->it->dataptr;
/* Copy (cast) First term over to output */
if (loop->cast) {
/* A little tricky because we need to
cast it first */
NpyArray_DESCR(arr)->f->copyswap(loop->buffer, loop->inptr,
loop->swap, NULL);
loop->cast(loop->buffer, loop->castbuf, 1, NULL, NULL);
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->castbuf));
} else {
memcpy(loop->bufptr[0], loop->castbuf, loop->outsize);
}
}
else {
/* Simple copy */
NpyArray_DESCR(arr)->f->copyswap(loop->bufptr[0],
loop->inptr,
loop->swap, NULL);
}
loop->inptr += loop->instrides;
n = 1;
while (n < loop->N) {
/* Copy up to loop->bufsize elements to buffer */
dptr = loop->buffer;
for (i = 0; i < loop->bufsize; i++, n++) {
if (n == loop->N) {
break;
}
NpyArray_DESCR(arr)->f->copyswap(dptr, loop->inptr,
loop->swap, NULL);
loop->inptr += loop->instrides;
dptr += loop->insize;
}
if (loop->cast) {
loop->cast(loop->buffer, loop->castbuf, i, NULL, NULL);
}
loop->function((char **)loop->bufptr, &i,
loop->steps, loop->funcdata);
loop->bufptr[0] += loop->steps[0]*i;
loop->bufptr[2] += loop->steps[2]*i;
NPY_UFUNC_CHECK_ERROR(loop);
}
NpyArray_ITER_NEXT(loop->it);
NpyArray_ITER_NEXT(loop->rit);
loop->bufptr[0] = loop->rit->dataptr;
loop->bufptr[2] = loop->bufptr[0] + loop->steps[0];
loop->index++;
}
/*
* DECREF left-over objects if buffering was used.
* It is needed when casting created new objects in
* castbuf. Intermediate copying into castbuf (via
* loop->function) decref'd what was already there.
* It's the final copy into the castbuf that needs a DECREF.
*/
/* Only when casting needed and it is from a non-object array */
if ((loop->obj & NPY_UFUNC_OBJ_ISOBJECT) && loop->cast &&
(!NpyArray_ISOBJECT(arr))) {
for (i=0; i<loop->bufsize; i++) {
NpyInterface_CLEAR(((void **)loop->castbuf)[i]);
}
}
}
// NPY_LOOP_END_THREADS;
/* Hang on to this reference -- will be decref'd with loop */
if (loop->retbase) {
ret = NpyArray_BASE_ARRAY(loop->ret);
NpyArray_ForceUpdate(loop->ret);
}
else {
ret = loop->ret;
}
Npy_INCREF(ret);
ufuncreduce_dealloc(loop);
return ret;
fail:
// NPY_LOOP_END_THREADS;
if (loop) {
ufuncreduce_dealloc(loop);
}
return NULL;
}
/*
* Reduceat performs a reduce over an axis using the indices as a guide
*
* op.reduceat(array,indices) computes
* op.reduce(array[indices[i]:indices[i+1]]
* for i=0..end with an implicit indices[i+1]=len(array)
* assumed when i=end-1
*
* if indices[i+1] <= indices[i]+1
* then the result is array[indices[i]] for that value
*
* op.accumulate(array) is the same as
* op.reduceat(array,indices)[::2]
* where indices is range(len(array)-1) with a zero placed in every other sample
* indices = zeros(len(array)*2-1)
* indices[1::2] = range(1,len(array))
*
* output shape is based on the size of indices
*/
NpyArray *
NpyUFunc_Reduceat(NpyUFuncObject *self, NpyArray *arr, NpyArray *ind,
NpyArray *out, int axis, int otype)
{
NpyArray *ret;
NpyUFuncReduceObject *loop;
npy_intp *ptr = (npy_intp *)NpyArray_BYTES(ind);
npy_intp nn = NpyArray_DIM(ind, 0);
npy_intp mm = NpyArray_DIM(arr, axis) - 1;
npy_intp n, i, j;
char *dptr;
// NPY_BEGIN_THREADS_DEF;
assert(NPY_VALID_MAGIC == self->nob_magic_number);
/* Check for out-of-bounds values in indices array */
for (i = 0; i<nn; i++) {
if ((*ptr < 0) || (*ptr > mm)) {
char buf[256];
NpyOS_snprintf(buf, 256, "index out-of-bounds (0, %d)", (int)mm);
NpyErr_SetString(NpyExc_IndexError, buf);
return NULL;
}
ptr++;
}
ptr = (npy_intp *)NpyArray_BYTES(ind);
/* Construct loop object */
loop = construct_reduce(self, &arr, out, axis, otype,
NPY_UFUNC_REDUCEAT, nn);
if (!loop) {
return NULL;
}
// NPY_LOOP_BEGIN_THREADS;
switch(loop->meth) {
case ZERO_EL_REDUCELOOP:
/* zero-length index -- return array immediately */
/* fprintf(stderr, "ZERO..\n"); */
break;
case NOBUFFER_UFUNCLOOP:
/* Reduceat
* NOBUFFER -- behaved array and same type
*/
/* fprintf(stderr, "NOBUFFER..%d\n", loop->size); */
while (loop->index < loop->size) {
ptr = (npy_intp *)NpyArray_BYTES(ind);
for (i = 0; i < nn; i++) {
loop->bufptr[1] = loop->it->dataptr + (*ptr)*loop->steps[1];
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->bufptr[1]));
} else {
memcpy(loop->bufptr[0], loop->bufptr[1], loop->outsize);
}
mm = (i == nn - 1 ? NpyArray_DIM(arr, axis) - *ptr :
*(ptr + 1) - *ptr) - 1;
if (mm > 0) {
loop->bufptr[1] += loop->steps[1];
loop->bufptr[2] = loop->bufptr[0];
loop->function((char **)loop->bufptr, &mm,
loop->steps, loop->funcdata);
NPY_UFUNC_CHECK_ERROR(loop);
}
loop->bufptr[0] += NpyArray_STRIDE(loop->ret, axis);
ptr++;
}
NpyArray_ITER_NEXT(loop->it);
NpyArray_ITER_NEXT(loop->rit);
loop->bufptr[0] = loop->rit->dataptr;
loop->index++;
}
break;
case BUFFER_UFUNCLOOP:
/* Reduceat
* BUFFER -- misbehaved array or different types
*/
/* fprintf(stderr, "BUFFERED..%d\n", loop->size); */
while (loop->index < loop->size) {
ptr = (npy_intp *)NpyArray_BYTES(ind);
for (i = 0; i < nn; i++) {
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
void** pDest = (void**)loop->bufptr[0];
*pDest = NpyInterface_INCREF(*((void **)loop->idptr));
} else {
memcpy(loop->bufptr[0], loop->idptr, loop->outsize);
}
n = 0;
mm = (i == nn - 1 ? NpyArray_DIM(arr, axis) - *ptr :
*(ptr + 1) - *ptr);
if (mm < 1) {
mm = 1;
}
loop->inptr = loop->it->dataptr + (*ptr)*loop->instrides;
while (n < mm) {
/* Copy up to loop->bufsize elements to buffer */
dptr = loop->buffer;
for (j = 0; j < loop->bufsize; j++, n++) {
if (n == mm) {
break;
}
NpyArray_DESCR(arr)->f->copyswap(dptr, loop->inptr,
loop->swap, NULL);
loop->inptr += loop->instrides;
dptr += loop->insize;
}
if (loop->cast) {
loop->cast(loop->buffer, loop->castbuf, j,
NULL, NULL);
}
loop->bufptr[2] = loop->bufptr[0];
loop->function((char **)loop->bufptr, &j,
loop->steps, loop->funcdata);
NPY_UFUNC_CHECK_ERROR(loop);
loop->bufptr[0] += j*loop->steps[0];
}
loop->bufptr[0] += NpyArray_STRIDE(loop->ret, axis);
ptr++;
}
NpyArray_ITER_NEXT(loop->it);
NpyArray_ITER_NEXT(loop->rit);
loop->bufptr[0] = loop->rit->dataptr;
loop->index++;
}
/*
* DECREF left-over objects if buffering was used.
* It is needed when casting created new objects in
* castbuf. Intermediate copying into castbuf (via
* loop->function) decref'd what was already there.
* It's the final copy into the castbuf that needs a DECREF.
*/
/* Only when casting needed and it is from a non-object array */
if ((loop->obj & NPY_UFUNC_OBJ_ISOBJECT) && loop->cast &&
(!NpyArray_ISOBJECT(arr))) {
for (i=0; i<loop->bufsize; i++) {
NpyInterface_CLEAR(((void **)loop->castbuf)[i]);
}
}
break;
}
// NPY_LOOP_END_THREADS;
/* Hang on to this reference -- will be decref'd with loop */
if (loop->retbase) {
ret = NpyArray_BASE_ARRAY(loop->ret);
NpyArray_ForceUpdate(loop->ret);
}
else {
ret = loop->ret;
}
Npy_INCREF(ret);
ufuncreduce_dealloc(loop);
return ret;
fail:
// NPY_LOOP_END_THREADS;
if (loop) {
ufuncreduce_dealloc(loop);
}
return NULL;
}
#if 0
/*
* This code handles reduce, reduceat, and accumulate
* (accumulate and reduce are special cases of the more general reduceat
* but they are handled separately for speed)
*/
static PyObject *
PyUFunc_GenericReduction(PyUFuncObject *self, PyObject *args,
PyObject *kwds, int operation)
{
int axis=0;
PyArrayObject *mp, *ret = NULL;
PyObject *op, *res = NULL;
PyObject *obj_ind, *context;
PyArrayObject *indices = NULL;
PyArray_Descr *otype = NULL;
PyArrayObject *out = NULL;
static char *kwlist1[] = {"array", "axis", "dtype", "out", NULL};
static char *kwlist2[] = {"array", "indices", "axis", "dtype", "out", NULL};
static char *_reduce_type[] = {"reduce", "accumulate", "reduceat", NULL};
if (self == NULL) {
PyErr_SetString(PyExc_ValueError, "function not supported");
return NULL;
}
if (PyUFunc_UFUNC(self)->core_enabled) {
PyErr_Format(PyExc_RuntimeError,
"Reduction not defined on ufunc with signature");
return NULL;
}
if (PyUFunc_UFUNC(self)->nin != 2) {
PyErr_Format(PyExc_ValueError,
"%s only supported for binary functions",
_reduce_type[operation]);
return NULL;
}
if (PyUFunc_UFUNC(self)->nout != 1) {
PyErr_Format(PyExc_ValueError,
"%s only supported for functions " \
"returning a single value",
_reduce_type[operation]);
return NULL;
}
if (operation == NPY_UFUNC_REDUCEAT) {
PyArray_Descr *indtype;
indtype = PyArray_DescrFromType(PyArray_INTP);
if(!PyArg_ParseTupleAndKeywords(args, kwds, "OO|iO&O&", kwlist2,
&op, &obj_ind, &axis,
PyArray_DescrConverter2,
&otype,
PyArray_OutputConverter,
&out)) {
Py_XDECREF(otype);
return NULL;
}
indices = (PyArrayObject *)PyArray_FromAny(obj_ind, indtype,
1, 1, CARRAY, NULL);
if (indices == NULL) {
Py_XDECREF(otype);
return NULL;
}
}
else {
if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|iO&O&", kwlist1,
&op, &axis,
PyArray_DescrConverter2,
&otype,
PyArray_OutputConverter,
&out)) {
Py_XDECREF(otype);
return NULL;
}
}
/* Ensure input is an array */
if (!PyArray_Check(op) && !PyArray_IsScalar(op, Generic)) {
context = Py_BuildValue("O(O)i", self, op, 0);
}
else {
context = NULL;
}
mp = (PyArrayObject *)PyArray_FromAny(op, NULL, 0, 0, 0, context);
Py_XDECREF(context);
if (mp == NULL) {
return NULL;
}
assert(PyArray_ISVALID(mp));
/* Check to see if input is zero-dimensional */
if (PyArray_NDIM(mp) == 0) {
PyErr_Format(PyExc_TypeError, "cannot %s on a scalar",
_reduce_type[operation]);
Py_XDECREF(otype);
Py_DECREF(mp);
return NULL;
}
/* Check to see that type (and otype) is not FLEXIBLE */
if (PyArray_ISFLEXIBLE(mp) ||
(otype && NpyTypeNum_ISFLEXIBLE(otype->descr->type_num))) {
PyErr_Format(PyExc_TypeError,
"cannot perform %s with flexible type",
_reduce_type[operation]);
Py_XDECREF(otype);
Py_DECREF(mp);
return NULL;
}
if (axis < 0) {
axis += PyArray_NDIM(mp);
}
if (axis < 0 || axis >= PyArray_NDIM(mp)) {
PyErr_SetString(PyExc_ValueError, "axis not in array");
Py_XDECREF(otype);
Py_DECREF(mp);
return NULL;
}
/*
* If out is specified it determines otype
* unless otype already specified.
*/
if (otype == NULL && out != NULL) {
otype = PyArray_Descr_WRAP( PyArray_DESCR(out) );
Py_INCREF(otype);
}
if (otype == NULL) {
/*
* For integer types --- make sure at least a long
* is used for add and multiply reduction to avoid overflow
*/
int typenum = PyArray_TYPE(mp);
if ((typenum < NPY_FLOAT)
&& ((strcmp(PyUFunc_UFUNC(self)->name,"add") == 0)
|| (strcmp(PyUFunc_UFUNC(self)->name,"multiply") == 0))) {
if (NpyTypeNum_ISBOOL(typenum)) {
typenum = PyArray_LONG;
}
else if ((size_t)PyArray_ITEMSIZE(mp) < sizeof(long)) {
if (NpyTypeNum_ISUNSIGNED(typenum)) {
typenum = PyArray_ULONG;
}
else {
typenum = PyArray_LONG;
}
}
}
otype = PyArray_DescrFromType(typenum);
}
switch(operation) {
case NPY_UFUNC_REDUCE:
ret = (PyArrayObject *)PyUFunc_Reduce(self, mp, out, axis,
otype->descr->type_num);
break;
case NPY_UFUNC_ACCUMULATE:
ret = (PyArrayObject *)PyUFunc_Accumulate(self, mp, out, axis,
otype->descr->type_num);
break;
case NPY_UFUNC_REDUCEAT:
ret = (PyArrayObject *)PyUFunc_Reduceat(self, mp, indices, out,
axis,
otype->descr->type_num);
Py_DECREF(indices);
break;
}
Py_DECREF(mp);
Py_DECREF(otype);
if (ret == NULL) {
return NULL;
}
if (Py_TYPE(op) != Py_TYPE(ret)) {
res = PyObject_CallMethod(op, "__array_wrap__", "O", ret);
if (res == NULL) {
PyErr_Clear();
}
else if (res == Py_None) {
Py_DECREF(res);
}
else {
Py_DECREF(ret);
return res;
}
}
return PyArray_Return(ret);
}
#endif
int
NpyUFunc_RegisterLoopForType(NpyUFuncObject *ufunc,
int usertype,
NpyUFuncGenericFunction function,
int *arg_types,
void *data)
{
NpyArray_Descr *descr;
NpyUFunc_Loop1d *funcdata, *current = NULL;
int i;
int *newtypes=NULL;
descr = NpyArray_DescrFromType(usertype);
if ((usertype < NPY_USERDEF) || (descr==NULL)) {
NpyErr_SetString(NpyExc_TypeError, "unknown user-defined type");
return -1;
}
Npy_DECREF(descr);
if (ufunc->userloops == NULL) {
ufunc->userloops = npy_create_userloops_table();
}
funcdata = malloc(sizeof(NpyUFunc_Loop1d));
if (funcdata == NULL) {
goto fail;
}
newtypes = malloc(sizeof(int)*ufunc->nargs);
if (newtypes == NULL) {
goto fail;
}
if (arg_types != NULL) {
for (i = 0; i < ufunc->nargs; i++) {
newtypes[i] = arg_types[i];
}
}
else {
for (i = 0; i < ufunc->nargs; i++) {
newtypes[i] = usertype;
}
}
funcdata->func = function;
funcdata->arg_types = newtypes;
funcdata->data = data;
funcdata->next = NULL;
/* Get entry for this user-defined type*/
current = (NpyUFunc_Loop1d *)NpyDict_Get(ufunc->userloops,
(void *)(npy_intp)usertype);
/* If it's not there, then make one and return. */
if (NULL == current) {
NpyDict_Put(ufunc->userloops, (void *)(npy_intp)usertype, funcdata);
return 0;
}
else {
NpyUFunc_Loop1d *prev = NULL;
int cmp = 1;
/*
* There is already at least 1 loop. Place this one in
* lexicographic order. If the next one signature
* is exactly like this one, then just replace.
* Otherwise insert.
*/
while (current != NULL) {
cmp = cmp_arg_types(current->arg_types, newtypes, ufunc->nargs);
if (cmp >= 0) {
break;
}
prev = current;
current = current->next;
}
if (cmp == 0) {
/* just replace it with new function */
current->func = function;
current->data = data;
free(newtypes);
free(funcdata);
}
else {
/*
* insert it before the current one by hacking the internals
* of cobject to replace the function pointer --- can't use
* CObject API because destructor is set.
*/
funcdata->next = current;
if (prev == NULL) {
/* place this at front */
NpyDict_ForceValue(ufunc->userloops,
(void *)(npy_intp)usertype, funcdata);
}
else {
prev->next = funcdata;
}
}
}
return 0;
fail:
free(funcdata);
free(newtypes);
if (!NpyErr_Occurred())
NpyErr_MEMORY;
return -1;
}
NpyUFuncObject *
NpyUFunc_FromFuncAndDataAndSignature(NpyUFuncGenericFunction *func,
void **data, char *types, int ntypes,
int nin, int nout, int identity,
char *name, char *doc,
int check_return, const char *signature)
{
NpyUFuncObject *self;
self = (NpyUFuncObject *)malloc(sizeof(NpyUFuncObject));
if (NULL == self) {
return NULL;
}
NpyObject_Init(self, &NpyUFunc_Type);
self->nin = nin;
self->nout = nout;
self->nargs = nin+nout;
self->identity = identity;
self->functions = func;
self->data = data;
self->types = types;
self->ntypes = ntypes;
self->check_return = check_return;
self->ptr = NULL;
self->userloops=NULL;
if (name == NULL) {
self->name = "?";
}
else {
self->name = name;
}
if (doc == NULL) {
self->doc = "NULL";
}
else {
self->doc = doc;
}
/* generalized ufunc */
self->core_enabled = 0;
self->core_num_dim_ix = 0;
self->core_num_dims = NULL;
self->core_dim_ixs = NULL;
self->core_offsets = NULL;
self->core_signature = NULL;
if (signature != NULL) {
if (0 != _parse_signature(self, signature)) {
Npy_DECREF(self);
return NULL;
}
}
if (NULL != _NpyArrayWrapperFuncs.ufunc_new_wrapper) {
_NpyArrayWrapperFuncs.ufunc_new_wrapper(self, &self->nob_interface);
}
return self;
}
NDARRAY_API NpyUFuncObject *
NpyUFunc_FromFuncAndData(NpyUFuncGenericFunction *func, void **data,
char *types, int ntypes,
int nin, int nout, int identity,
char *name, char *doc, int check_return)
{
return NpyUFunc_FromFuncAndDataAndSignature(func, data, types, ntypes,
nin, nout, identity, name,
doc, check_return, NULL);
}
int
NpyUFunc_SetUsesArraysAsData(void **data, size_t i)
{
data[i] = (void*)NpyUFunc_SetUsesArraysAsData;
return 0;
}
static NpyUFuncLoopObject *
construct_loop(NpyUFuncObject *self)
{
NpyUFuncLoopObject *loop;
int i;
char *name;
if (self == NULL) {
NpyErr_SetString(NpyExc_ValueError, "function not supported");
return NULL;
}
if ((loop = malloc(sizeof(NpyUFuncLoopObject))) == NULL) {
NpyErr_MEMORY;
return loop;
}
loop->nob_interface = NULL;
loop->nob_refcnt = 1;
loop->nob_type = NULL;
loop->nob_magic_number = NPY_VALID_MAGIC;
loop->iter = NpyArray_MultiIterNew();
if (loop->iter == NULL) {
free(loop);
return NULL;
}
loop->iter->index = 0;
loop->iter->numiter = self->nargs;
loop->ufunc = self;
Npy_INCREF(loop->ufunc);
loop->buffer[0] = NULL;
for (i = 0; i < self->nargs; i++) {
loop->iter->iters[i] = NULL;
loop->cast[i] = NULL;
}
loop->errobj = NULL;
loop->notimplemented = 0;
loop->first = 1;
loop->core_dim_sizes = NULL;
loop->core_strides = NULL;
loop->leftover = 0;
if (self->core_enabled) {
int num_dim_ix = 1 + self->core_num_dim_ix;
int nstrides = self->nargs
+ self->core_offsets[self->nargs - 1]
+ self->core_num_dims[self->nargs - 1];
loop->core_dim_sizes = malloc(sizeof(npy_intp)*num_dim_ix);
loop->core_strides = malloc(sizeof(npy_intp)*nstrides);
if (loop->core_dim_sizes == NULL || loop->core_strides == NULL) {
NpyErr_MEMORY;
goto fail;
}
memset(loop->core_strides, 0, sizeof(npy_intp) * nstrides);
for (i = 0; i < num_dim_ix; i++) {
loop->core_dim_sizes[i] = 1;
}
}
name = self->name ? self->name : "";
return loop;
fail:
ufuncloop_dealloc(loop);
return NULL;
}
static size_t
construct_arrays(NpyUFuncLoopObject *loop, size_t nargs, NpyArray **mps,
int ntypenums, int *rtypenums,
npy_prepare_outputs_func prepare,
void *prepare_data)
{
int i;
int arg_types[NPY_MAXARGS];
NPY_SCALARKIND scalars[NPY_MAXARGS];
NPY_SCALARKIND maxarrkind, maxsckind, newArr;
NpyUFuncObject *self = loop->ufunc;
npy_bool allscalars = NPY_TRUE;
int flexible = 0;
int object = 0;
npy_intp temp_dims[NPY_MAXDIMS];
npy_intp *out_dims;
int out_nd;
/* Get each input argument */
maxarrkind = NPY_NOSCALAR;
maxsckind = NPY_NOSCALAR;
for(i = 0; i < self->nin; i++) {
arg_types[i] = NpyArray_TYPE(mps[i]);
if (!flexible && NpyTypeNum_ISFLEXIBLE(arg_types[i])) {
flexible = 1;
}
if (!object && NpyTypeNum_ISOBJECT(arg_types[i])) {
object = 1;
}
/*
* debug
* fprintf(stderr, "array %d has reference %d\n", i,
* (mps[i])->ob_refcnt);
*/
/*
* Scalars are 0-dimensional arrays at this point
*/
/*
* We need to keep track of whether or not scalars
* are mixed with arrays of different kinds.
*/
if (NpyArray_NDIM(mps[i]) > 0) {
scalars[i] = NPY_NOSCALAR;
allscalars = NPY_FALSE;
newArr = NpyArray_ScalarKind(arg_types[i], NULL);
maxarrkind = NpyArray_MAX(newArr, maxarrkind);
}
else {
scalars[i] = NpyArray_ScalarKind(arg_types[i], &(mps[i]));
maxsckind = NpyArray_MAX(scalars[i], maxsckind);
}
}
/* We don't do strings */
if (flexible && !object) {
loop->notimplemented = 1;
return nargs;
}
/*
* If everything is a scalar, or scalars mixed with arrays of
* different kinds of lesser kinds then use normal coercion rules
*/
if (allscalars || (maxsckind > maxarrkind)) {
for (i = 0; i < self->nin; i++) {
scalars[i] = NPY_NOSCALAR;
}
}
/* Select an appropriate function for these argument types. */
if (select_types(loop->ufunc, arg_types, &(loop->function),
&(loop->funcdata), scalars, ntypenums,
rtypenums) == -1) {
return -1;
}
/*
* Create copies for some of the arrays if they are small
* enough and not already contiguous
*/
if (_create_copies(loop, arg_types, mps) < 0) {
return -1;
}
/*
* Only use loop dimensions when constructing Iterator:
* temporarily replace mps[i] (will be recovered below).
*/
if (self->core_enabled) {
for (i = 0; i < self->nin; i++) {
NpyArray *ao;
if (_compute_dimension_size(loop, mps, i) < 0) {
return -1;
}
ao = _trunc_coredim(mps[i], self->core_num_dims[i]);
if (ao == NULL) {
return -1;
}
mps[i] = ao;
}
}
/* Create Iterators for the Inputs */
for (i = 0; i < self->nin; i++) {
loop->iter->iters[i] = NpyArray_IterNew(mps[i]);
if (loop->iter->iters[i] == NULL) {
return -1;
}
}
/* Recover mps[i]. */
if (self->core_enabled) {
for (i = 0; i < self->nin; i++) {
NpyArray *ao = mps[i];
mps[i] = NpyArray_BASE_ARRAY(mps[i]);
Npy_DECREF(ao);
}
}
/* Broadcast the result */
loop->iter->numiter = self->nin;
if (NpyArray_Broadcast(loop->iter) < 0) {
return -1;
}
/* Get any return arguments */
for (i = self->nin; i < nargs; i++) {
if (self->core_enabled) {
if (_compute_dimension_size(loop, mps, i) < 0) {
return -1;
}
}
out_dims = _compute_output_dims(loop, i, &out_nd, temp_dims);
if (!out_dims) {
return -1;
}
if (NULL != mps[i] && (NpyArray_NDIM(mps[i]) != out_nd ||
!NpyArray_CompareLists(NpyArray_DIMS(mps[i]),
out_dims, out_nd))) {
NpyErr_SetString(NpyExc_ValueError, "invalid return array shape");
Npy_DECREF(mps[i]);
mps[i] = NULL;
return -1;
}
if (NULL != mps[i] && !NpyArray_ISWRITEABLE(mps[i])) {
NpyErr_SetString(NpyExc_ValueError, "return array is not writeable");
Npy_DECREF(mps[i]);
mps[i] = NULL;
return -1;
}
}
/* construct any missing return arrays and make output iterators */
for(i = self->nin; i < self->nargs; i++) {
NpyArray_Descr *ntype;
if (mps[i] == NULL) {
out_dims = _compute_output_dims(loop, i, &out_nd, temp_dims);
if (!out_dims) {
return -1;
}
mps[i] = NpyArray_New(NULL,
out_nd,
out_dims,
arg_types[i],
NULL, NULL,
0, 0, NULL);
if (mps[i] == NULL) {
return -1;
}
}
/*
* reset types for outputs that are equivalent
* -- no sense casting uselessly
*/
else {
if (NpyArray_TYPE(mps[i]) != arg_types[i]) {
NpyArray_Descr *atype;
ntype = NpyArray_DESCR(mps[i]);
atype = NpyArray_DescrFromType(arg_types[i]);
if (NpyArray_EquivTypes(atype, ntype)) {
arg_types[i] = ntype->type_num;
}
Npy_DECREF(atype);
}
/* still not the same -- or will we have to use buffers?*/
if (NpyArray_TYPE(mps[i]) != arg_types[i]
|| !NpyArray_ISBEHAVED_RO(mps[i])) {
if (loop->iter->size < loop->bufsize || self->core_enabled) {
NpyArray *newArr;
/*
* Copy the array to a temporary copy
* and set the UPDATEIFCOPY flag
*/
ntype = NpyArray_DescrFromType(arg_types[i]);
newArr = NpyArray_FromArray(mps[i], ntype,
NPY_FORCECAST | NPY_ALIGNED | NPY_UPDATEIFCOPY);
if (newArr == NULL) {
return -1;
}
Npy_DECREF(mps[i]);
mps[i] = newArr;
}
}
}
if (self->core_enabled) {
NpyArray *ao;
/* computer for all output arguments, and set strides in "loop" */
if (_compute_dimension_size(loop, mps, i) < 0) {
return -1;
}
ao = _trunc_coredim(mps[i], self->core_num_dims[i]);
if (ao == NULL) {
return -1;
}
/* Temporarily modify mps[i] for constructing iterator. */
mps[i] = ao;
}
loop->iter->iters[i] = NpyArray_IterNew(mps[i]);
if (loop->iter->iters[i] == NULL) {
return -1;
}
/* Recover mps[i]. */
if (self->core_enabled) {
NpyArray *ao = mps[i];
mps[i] = NpyArray_BASE_ARRAY(mps[i]);
Npy_DECREF(ao);
}
}
/* wrap outputs */
if (prepare) {
if (prepare(self, mps, prepare_data) < 0) {
return -1;
}
}
/*
* If any of different type, or misaligned or swapped
* then must use buffers
*/
loop->bufcnt = 0;
loop->obj = 0;
/* Determine looping method needed */
loop->meth = NO_UFUNCLOOP;
if (loop->iter->size == 0) {
return nargs;
}
if (self->core_enabled) {
loop->meth = SIGNATURE_NOBUFFER_UFUNCLOOP;
}
for (i = 0; i < self->nargs; i++) {
loop->needbuffer[i] = 0;
if (arg_types[i] != NpyArray_TYPE(mps[i])
|| !NpyArray_ISBEHAVED_RO(mps[i])) {
if (self->core_enabled) {
NpyErr_SetString(NpyExc_RuntimeError,
"never reached; copy should have been made");
return -1;
}
loop->meth = BUFFER_UFUNCLOOP;
loop->needbuffer[i] = 1;
}
if (!(loop->obj & NPY_UFUNC_OBJ_ISOBJECT)
&& ((NpyArray_TYPE(mps[i]) == NPY_OBJECT)
|| (arg_types[i] == NPY_OBJECT))) {
loop->obj = NPY_UFUNC_OBJ_ISOBJECT | NPY_UFUNC_OBJ_NEEDS_API;
}
if (!(loop->obj & NPY_UFUNC_OBJ_NEEDS_API)
&& ((NpyArray_TYPE(mps[i]) == NPY_DATETIME)
|| (NpyArray_TYPE(mps[i]) == NPY_TIMEDELTA)
|| (arg_types[i] == NPY_DATETIME)
|| (arg_types[i] == NPY_TIMEDELTA))) {
loop->obj = NPY_UFUNC_OBJ_NEEDS_API;
}
}
if (self->core_enabled && (loop->obj & NPY_UFUNC_OBJ_ISOBJECT)) {
NpyErr_SetString(NpyExc_TypeError,
"Object type not allowed in ufunc with signature");
return -1;
}
if (loop->meth == NO_UFUNCLOOP) {
loop->meth = ONE_UFUNCLOOP;
/* All correct type and BEHAVED */
/* Check for non-uniform stridedness */
for (i = 0; i < self->nargs; i++) {
if (!(loop->iter->iters[i]->contiguous)) {
/*
* May still have uniform stride
* if (broadcast result) <= 1-d
*/
if (NpyArray_NDIM(mps[i]) != 0 &&
(loop->iter->iters[i]->nd_m1 > 0)) {
loop->meth = NOBUFFER_UFUNCLOOP;
break;
}
}
}
if (loop->meth == ONE_UFUNCLOOP) {
for (i = 0; i < self->nargs; i++) {
loop->bufptr[i] = NpyArray_BYTES(mps[i]);
}
}
}
loop->iter->numiter = self->nargs;
/* Fill in steps */
if (loop->meth == SIGNATURE_NOBUFFER_UFUNCLOOP && loop->iter->nd == 0) {
/* Use default core_strides */
}
else if (loop->meth != ONE_UFUNCLOOP) {
int ldim;
npy_intp minsum;
npy_intp maxdim;
NpyArrayIterObject *it;
npy_intp stride_sum[NPY_MAXDIMS];
int j;
/* Fix iterators */
/*
* Optimize axis the iteration takes place over
*
* The first thought was to have the loop go
* over the largest dimension to minimize the number of loops
*
* However, on processors with slow memory bus and cache,
* the slowest loops occur when the memory access occurs for
* large strides.
*
* Thus, choose the axis for which strides of the last iterator is
* smallest but non-zero.
*/
for (i = 0; i < loop->iter->nd; i++) {
stride_sum[i] = 0;
for (j = 0; j < loop->iter->numiter; j++) {
stride_sum[i] += loop->iter->iters[j]->strides[i];
}
}
ldim = loop->iter->nd - 1;
minsum = stride_sum[loop->iter->nd - 1];
for (i = loop->iter->nd - 2; i >= 0; i--) {
if (stride_sum[i] < minsum ) {
ldim = i;
minsum = stride_sum[i];
}
}
maxdim = loop->iter->dimensions[ldim];
loop->iter->size /= maxdim;
loop->bufcnt = maxdim;
loop->lastdim = ldim;
/*
* Fix the iterators so the inner loop occurs over the
* largest dimensions -- This can be done by
* setting the size to 1 in that dimension
* (just in the iterators)
*/
for (i = 0; i < loop->iter->numiter; i++) {
it = loop->iter->iters[i];
it->contiguous = 0;
it->size /= (it->dims_m1[ldim] + 1);
it->dims_m1[ldim] = 0;
it->backstrides[ldim] = 0;
/*
* (won't fix factors because we
* don't use PyArray_ITER_GOTO1D
* so don't change them)
*
* Set the steps to the strides in that dimension
*/
loop->steps[i] = it->strides[ldim];
}
/*
* Set looping part of core_dim_sizes and core_strides.
*/
if (loop->meth == SIGNATURE_NOBUFFER_UFUNCLOOP) {
loop->core_dim_sizes[0] = maxdim;
for (i = 0; i < self->nargs; i++) {
loop->core_strides[i] = loop->steps[i];
}
}
/*
* fix up steps where we will be copying data to
* buffers and calculate the ninnerloops and leftover
* values -- if step size is already zero that is not changed...
*/
if (loop->meth == BUFFER_UFUNCLOOP) {
loop->leftover = maxdim % loop->bufsize;
loop->ninnerloops = (maxdim / loop->bufsize) + 1;
for (i = 0; i < self->nargs; i++) {
if (loop->needbuffer[i] && loop->steps[i]) {
loop->steps[i] = NpyArray_ITEMSIZE(mps[i]);
}
/* These are changed later if casting is needed */
}
}
}
else if (loop->meth == ONE_UFUNCLOOP) {
/* uniformly-strided case */
for (i = 0; i < self->nargs; i++) {
if (NpyArray_SIZE(mps[i]) == 1) {
loop->steps[i] = 0;
}
else {
loop->steps[i] = NpyArray_STRIDE(mps[i],
NpyArray_NDIM(mps[i])-1);
}
}
}
/* Finally, create memory for buffers if we need them */
/*
* Buffers for scalars are specially made small -- scalars are
* not copied multiple times
*/
if (loop->meth == BUFFER_UFUNCLOOP) {
int cnt = 0, cntcast = 0;
int scnt = 0, scntcast = 0;
char *castptr;
char *bufptr;
int last_was_scalar = 0;
int last_cast_was_scalar = 0;
int oldbufsize = 0;
int oldsize = 0;
int scbufsize = 4*sizeof(double);
int memsize;
NpyArray_Descr *descr;
/* compute the element size */
for (i = 0; i < self->nargs; i++) {
if (!loop->needbuffer[i]) {
continue;
}
if (arg_types[i] != mps[i]->descr->type_num) {
descr = NpyArray_DescrFromType(arg_types[i]);
if (loop->steps[i]) {
cntcast += descr->elsize;
}
else {
scntcast += descr->elsize;
}
if (i < self->nin) {
loop->cast[i] = NpyArray_GetCastFunc(NpyArray_DESCR(mps[i]),
arg_types[i]);
}
else {
loop->cast[i] = NpyArray_GetCastFunc(
descr, NpyArray_DESCR(mps[i])->type_num);
}
Npy_DECREF(descr);
if (!loop->cast[i]) {
return -1;
}
}
loop->swap[i] = !(NpyArray_ISNOTSWAPPED(mps[i]));
if (loop->steps[i]) {
cnt += NpyArray_ITEMSIZE(mps[i]);
}
else {
scnt += NpyArray_ITEMSIZE(mps[i]);
}
}
memsize = loop->bufsize*(cnt+cntcast) + scbufsize*(scnt+scntcast);
loop->buffer[0] = NpyDataMem_NEW(memsize);
/*
* debug
* fprintf(stderr, "Allocated buffer at %p of size %d, cnt=%d, cntcast=%d\n",
* loop->buffer[0], loop->bufsize * (cnt + cntcast), cnt, cntcast);
*/
if (loop->buffer[0] == NULL) {
NpyErr_MEMORY;
return -1;
}
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
memset(loop->buffer[0], 0, memsize);
}
castptr = loop->buffer[0] + loop->bufsize*cnt + scbufsize*scnt;
bufptr = loop->buffer[0];
loop->objfunc = 0;
for (i = 0; i < self->nargs; i++) {
if (!loop->needbuffer[i]) {
continue;
}
loop->buffer[i] = bufptr + (last_was_scalar ? scbufsize :
loop->bufsize)*oldbufsize;
last_was_scalar = (loop->steps[i] == 0);
bufptr = loop->buffer[i];
oldbufsize = NpyArray_ITEMSIZE(mps[i]);
/* fprintf(stderr, "buffer[%d] = %p\n", i, loop->buffer[i]); */
if (loop->cast[i]) {
NpyArray_Descr *descr;
loop->castbuf[i] = castptr + (last_cast_was_scalar ? scbufsize :
loop->bufsize)*oldsize;
last_cast_was_scalar = last_was_scalar;
/* fprintf(stderr, "castbuf[%d] = %p\n", i, loop->castbuf[i]); */
descr = NpyArray_DescrFromType(arg_types[i]);
oldsize = descr->elsize;
Npy_DECREF(descr);
loop->bufptr[i] = loop->castbuf[i];
castptr = loop->castbuf[i];
if (loop->steps[i]) {
loop->steps[i] = oldsize;
}
}
else {
loop->bufptr[i] = loop->buffer[i];
}
if (!loop->objfunc && (loop->obj & NPY_UFUNC_OBJ_ISOBJECT)) {
if (arg_types[i] == NPY_OBJECT) {
loop->objfunc = 1;
}
}
}
}
if (_does_loop_use_arrays(loop->funcdata)) {
loop->funcdata = (void*)mps;
}
return nargs;
}
static NpyUFuncReduceObject *
construct_reduce(NpyUFuncObject *self, NpyArray **arr, NpyArray *out,
int axis, int otype, int operation, npy_intp ind_size)
{
NpyUFuncReduceObject *loop;
NpyArray *idarr;
NpyArray *aar;
npy_intp loop_i[NPY_MAXDIMS], outsize = 0;
int arg_types[3];
NPY_SCALARKIND scalars[3] = { NPY_NOSCALAR, NPY_NOSCALAR,
NPY_NOSCALAR };
char *name = (NULL != self->name) ? self->name : NULL;
int i, j, nd;
int flags;
assert(NPY_VALID_MAGIC == self->nob_magic_number);
/* Reduce type is the type requested of the input during reduction */
if (self->core_enabled) {
NpyErr_SetString(NpyExc_RuntimeError,
"construct_reduce not allowed on ufunc with signature");
return NULL;
}
nd = NpyArray_NDIM(*arr);
arg_types[0] = otype;
arg_types[1] = otype;
arg_types[2] = otype;
if ((loop = malloc(sizeof(NpyUFuncReduceObject))) == NULL) {
NpyErr_MEMORY;
return loop;
}
loop->nob_magic_number = NPY_VALID_MAGIC;
loop->retbase = 0;
loop->swap = 0;
loop->index = 0;
loop->ufunc = self;
Npy_INCREF(self);
loop->cast = NULL;
loop->buffer = NULL;
loop->ret = NULL;
loop->it = NULL;
loop->rit = NULL;
loop->errobj = NULL;
loop->first = 1;
loop->decref_arr = NULL;
loop->N = NpyArray_DIM(*arr,axis);
loop->instrides = NpyArray_STRIDE(*arr, axis);
fp_error_state(&loop->bufsize, &loop->errormask, &loop->errobj);
if (select_types(loop->ufunc, arg_types, &(loop->function),
&(loop->funcdata), scalars, 0, NULL) == -1) {
goto fail;
}
/*
* output type may change -- if it does
* reduction is forced into that type
* and we need to select the reduction function again
*/
if (otype != arg_types[2]) {
otype = arg_types[2];
arg_types[0] = otype;
arg_types[1] = otype;
if (select_types(loop->ufunc, arg_types, &(loop->function),
&(loop->funcdata), scalars, 0, NULL) == -1) {
goto fail;
}
}
/* Make copy if misbehaved or not otype for small arrays */
if (_create_reduce_copy(loop, arr, otype) < 0) {
goto fail;
}
aar = *arr;
if (loop->N == 0) {
loop->meth = ZERO_EL_REDUCELOOP;
}
else if (NpyArray_ISBEHAVED_RO(aar) && (otype == NpyArray_TYPE(aar))) {
if (loop->N == 1) {
loop->meth = ONE_EL_REDUCELOOP;
}
else {
loop->meth = NOBUFFER_UFUNCLOOP;
loop->steps[1] = NpyArray_STRIDE(aar, axis);
loop->N -= 1;
}
}
else {
loop->meth = BUFFER_UFUNCLOOP;
loop->swap = !(NpyArray_ISNOTSWAPPED(aar));
}
/* Determine if object arrays are involved */
if (otype == NPY_OBJECT || NpyArray_TYPE(aar) == NPY_OBJECT) {
loop->obj = NPY_UFUNC_OBJ_ISOBJECT | NPY_UFUNC_OBJ_NEEDS_API;
}
else if ((otype == NPY_DATETIME)
|| (NpyArray_TYPE(aar) == NPY_DATETIME)
|| (otype == NPY_TIMEDELTA)
|| (NpyArray_TYPE(aar) == NPY_TIMEDELTA)) {
loop->obj = NPY_UFUNC_OBJ_NEEDS_API;
} else {
loop->obj = 0;
}
if ((loop->meth == ZERO_EL_REDUCELOOP)
|| ((operation == NPY_UFUNC_REDUCEAT)
&& (loop->meth == BUFFER_UFUNCLOOP))) {
idarr = _getidentity(self, otype, name);
if (idarr == NULL) {
goto fail;
}
if (NpyArray_ITEMSIZE(idarr) > NPY_UFUNC_MAXIDENTITY) {
char buf[256];
NpyOS_snprintf(buf, 256, "UFUNC_MAXIDENTITY (%d) is too small"\
"(needs to be at least %d)",
NPY_UFUNC_MAXIDENTITY, NpyArray_ITEMSIZE(idarr));
NpyErr_SetString(NpyExc_RuntimeError, buf);
Npy_DECREF(idarr);
goto fail;
}
memcpy(loop->idptr, NpyArray_BYTES(idarr), NpyArray_ITEMSIZE(idarr));
Npy_DECREF(idarr);
}
/* Construct return array */
flags = NPY_CARRAY | NPY_UPDATEIFCOPY | NPY_FORCECAST;
switch(operation) {
case NPY_UFUNC_REDUCE:
for (j = 0, i = 0; i < nd; i++) {
if (i != axis) {
loop_i[j++] = NpyArray_DIM(aar, i);
}
}
if (out == NULL) {
loop->ret = NpyArray_New(NULL, NpyArray_NDIM(aar)-1, loop_i,
otype, NULL, NULL, 0, 0,
Npy_INTERFACE(aar));
}
else {
outsize = NpyArray_MultiplyList(loop_i, NpyArray_NDIM(aar) - 1);
}
break;
case NPY_UFUNC_ACCUMULATE:
if (out == NULL) {
loop->ret = NpyArray_New(NULL, NpyArray_NDIM(aar),
NpyArray_DIMS(aar),
otype, NULL, NULL, 0, 0,
Npy_INTERFACE(aar));
}
else {
outsize = NpyArray_MultiplyList(NpyArray_DIMS(aar),
NpyArray_NDIM(aar));
}
break;
case NPY_UFUNC_REDUCEAT:
memcpy(loop_i, NpyArray_DIMS(aar), nd*sizeof(npy_intp));
/* Index is 1-d array */
loop_i[axis] = ind_size;
if (out == NULL) {
loop->ret = NpyArray_New(NULL, NpyArray_NDIM(aar), loop_i, otype,
NULL, NULL, 0, 0, Npy_INTERFACE(aar));
}
else {
outsize = NpyArray_MultiplyList(loop_i, NpyArray_NDIM(aar));
}
if (ind_size == 0) {
loop->meth = ZERO_EL_REDUCELOOP;
return loop;
}
if (loop->meth == ONE_EL_REDUCELOOP) {
loop->meth = NOBUFFER_REDUCELOOP;
}
break;
}
if (out) {
if (NpyArray_SIZE(out) != outsize) {
NpyErr_SetString(NpyExc_ValueError,
"wrong shape for output");
goto fail;
}
loop->ret = NpyArray_FromArray(out, NpyArray_DescrFromType(otype),
flags);
if (loop->ret && loop->ret != out) {
loop->retbase = 1;
}
}
if (loop->ret == NULL) {
goto fail;
}
loop->insize = NpyArray_ITEMSIZE(aar);
loop->outsize = NpyArray_ITEMSIZE(loop->ret);
loop->bufptr[0] = NpyArray_BYTES(loop->ret);
if (loop->meth == ZERO_EL_REDUCELOOP) {
loop->size = NpyArray_SIZE(loop->ret);
return loop;
}
loop->it = NpyArray_IterNew(aar);
if (loop->it == NULL) {
return NULL;
}
if (loop->meth == ONE_EL_REDUCELOOP) {
loop->size = loop->it->size;
return loop;
}
/*
* Fix iterator to loop over correct dimension
* Set size in axis dimension to 1
*/
loop->it->contiguous = 0;
loop->it->size /= (loop->it->dims_m1[axis]+1);
loop->it->dims_m1[axis] = 0;
loop->it->backstrides[axis] = 0;
loop->size = loop->it->size;
if (operation == NPY_UFUNC_REDUCE) {
loop->steps[0] = 0;
}
else {
loop->rit = NpyArray_IterNew(loop->ret);
if (loop->rit == NULL) {
return NULL;
}
/*
* Fix iterator to loop over correct dimension
* Set size in axis dimension to 1
*/
loop->rit->contiguous = 0;
loop->rit->size /= (loop->rit->dims_m1[axis] + 1);
loop->rit->dims_m1[axis] = 0;
loop->rit->backstrides[axis] = 0;
if (operation == NPY_UFUNC_ACCUMULATE) {
loop->steps[0] = NpyArray_STRIDE(loop->ret, axis);
}
else {
loop->steps[0] = 0;
}
}
loop->steps[2] = loop->steps[0];
loop->bufptr[2] = loop->bufptr[0] + loop->steps[2];
if (loop->meth == BUFFER_UFUNCLOOP) {
int _size;
loop->steps[1] = loop->outsize;
if (otype != NpyArray_TYPE(aar)) {
_size=loop->bufsize*(loop->outsize + NpyArray_ITEMSIZE(aar));
loop->buffer = NpyDataMem_NEW(_size);
if (loop->buffer == NULL) {
goto fail;
}
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
memset(loop->buffer, 0, _size);
}
loop->castbuf = loop->buffer + loop->bufsize*NpyArray_ITEMSIZE(aar);
loop->bufptr[1] = loop->castbuf;
loop->cast = NpyArray_GetCastFunc(NpyArray_DESCR(aar), otype);
if (loop->cast == NULL) {
goto fail;
}
}
else {
_size = loop->bufsize * loop->outsize;
loop->buffer = NpyDataMem_NEW(_size);
if (loop->buffer == NULL) {
goto fail;
}
if (loop->obj & NPY_UFUNC_OBJ_ISOBJECT) {
memset(loop->buffer, 0, _size);
}
loop->bufptr[1] = loop->buffer;
}
}
NpyUFunc_clearfperr();
return loop;
fail:
ufuncreduce_dealloc(loop);
return NULL;
}
static char *_types_msg = "function not supported for these types, " \
"and can't coerce safely to supported types";
/*
* Called to determine coercion
* Can change arg_types.
*/
static int
select_types(NpyUFuncObject *self, int *arg_types,
NpyUFuncGenericFunction *function, void **data,
NPY_SCALARKIND *scalars,
int ntypenums, int *rtypenums)
{
int i, j;
char start_type;
int userdef = -1;
int userdef_ind = -1;
if (self->userloops) {
for(i = 0; i < self->nin; i++) {
if (NpyTypeNum_ISUSERDEF(arg_types[i])) {
userdef = arg_types[i];
userdef_ind = i;
break;
}
}
}
if (rtypenums != NULL)
return extract_specified_loop(self, arg_types, function, data,
ntypenums, rtypenums, userdef);
if (userdef > 0) {
int ret = -1;
/*
* Look through all the registered loops for all the user-defined
* types to find a match.
*/
while (ret == -1) {
NpyUFunc_Loop1d *funcdata;
npy_intp userdefP;
if (userdef_ind >= self->nin) {
break;
}
userdef = arg_types[userdef_ind++];
if (!(NpyTypeNum_ISUSERDEF(userdef))) {
continue;
}
userdefP = (npy_intp)userdef;
funcdata = NpyDict_Get(self->userloops, (void *)userdefP);
/*
* extract the correct function
* data and argtypes for this user-defined type.
*/
ret = _find_matching_userloop(funcdata, arg_types, scalars,
function, data, self->nargs,
self->nin);
}
if (ret == 0) {
return ret;
}
NpyErr_SetString(NpyExc_TypeError, _types_msg);
return ret;
}
start_type = arg_types[0];
/*
* If the first argument is a scalar we need to place
* the start type as the lowest type in the class
*/
if (scalars[0] != NPY_NOSCALAR) {
start_type = _lowest_type(start_type);
}
i = 0;
while (i < self->ntypes && start_type > self->types[i*self->nargs]) {
i++;
}
for (; i < self->ntypes; i++) {
for (j = 0; j < self->nin; j++) {
if (!NpyArray_CanCoerceScalar(arg_types[j],
self->types[i*self->nargs + j],
scalars[j]))
break;
}
if (j == self->nin) {
break;
}
}
if (i >= self->ntypes) {
NpyErr_SetString(NpyExc_TypeError, _types_msg);
return -1;
}
for (j = 0; j < self->nargs; j++) {
arg_types[j] = self->types[i*self->nargs+j];
}
if (self->data) {
*data = self->data[i];
}
else {
*data = NULL;
}
*function = self->functions[i];
return 0;
}
NpyUFuncObject *
npy_ufunc_frompyfunc(int nin, int nout, char *fname, size_t fname_len,
NpyUFuncGenericFunction *gen_funcs, void *function) {
NpyUFuncObject *self;
NpyUFunc_FuncData *fdata;
char *str;
int i;
int offset[2];
self = (NpyUFuncObject *)malloc(sizeof(NpyUFuncObject));
if (NULL == self) {
return NULL;
}
NpyObject_Init(self, &NpyUFunc_Type);
self->userloops = NULL;
self->nin = nin;
self->nout = nout;
self->nargs = nin + nout;
self->identity = NpyUFunc_None;
self->functions = gen_funcs;
self->ntypes = 1;
self->check_return = 0;
/* generalized ufunc */
self->core_enabled = 0;
self->core_num_dim_ix = 0;
self->core_num_dims = NULL;
self->core_dim_ixs = NULL;
self->core_offsets = NULL;
self->core_signature = NULL;
/*
* self->ptr holds a pointer for enough memory for
* self->data[0] (fdata)
* self->data
* self->name
* self->types
*
* To be safest, all of these need their memory aligned on void * pointers
* Therefore, we may need to allocate extra space.
*/
offset[0] = sizeof(NpyUFunc_FuncData);
i = (sizeof(NpyUFunc_FuncData) % sizeof(void *));
if (i) {
offset[0] += (sizeof(void *) - i);
}
offset[1] = self->nargs;
i = (self->nargs % sizeof(void *));
if (i) {
offset[1] += (sizeof(void *)-i);
}
self->ptr = malloc(offset[0] + offset[1] + sizeof(void *) +
(fname_len + 14));
if (NULL == self->ptr) {
return NULL;
}
fdata = (NpyUFunc_FuncData *)(self->ptr);
fdata->nin = nin;
fdata->nout = nout;
fdata->callable = function;
self->data = (void **)(((char *)self->ptr) + offset[0]);
self->data[0] = (void *)fdata;
self->types = (char *)self->data + sizeof(void *);
for (i = 0; i < self->nargs; i++) {
self->types[i] = NPY_OBJECT;
}
str = self->types + offset[1];
memcpy(str, fname, fname_len);
memcpy(str+fname_len, " (vectorized)", 14);
self->name = str;
/* Do a better job someday */
self->doc = "dynamic ufunc based on a python function";
return self;
}
/*
* if only one type is specified then it is the "first" output data-type
* and the first signature matching this output data-type is returned.
*
* if a tuple of types is specified then an exact match to the signature
* is searched and it much match exactly or an error occurs
*/
static int
extract_specified_loop(NpyUFuncObject *self, int *arg_types,
NpyUFuncGenericFunction *function, void **data,
int ntypenums, int *rtypenums, int userdef)
{
static char msg[] = "loop written to specified type(s) not found";
int nargs;
int i, j;
nargs = self->nargs;
if (userdef > 0) {
/* search in the user-defined functions */
NpyUFunc_Loop1d *funcdata;
funcdata = NpyDict_Get(self->userloops, (void *)(npy_intp)userdef);
if (NULL == funcdata) {
NpyErr_SetString(NpyExc_TypeError,
"user-defined type used in ufunc" \
" with no registered loops");
return -1;
}
/*
* extract the correct function
* data and argtypes
*/
while (funcdata != NULL) {
if (ntypenums == 1) {
if (rtypenums[0] == funcdata->arg_types[self->nin]) {
i = nargs;
}
else {
i = -1;
}
} else {
for (i=0; i<nargs; i++) {
if (rtypenums[i] != funcdata->arg_types[i]) {
break;
}
}
}
if (i == nargs) {
*function = funcdata->func;
*data = funcdata->data;
for(i = 0; i < nargs; i++) {
arg_types[i] = funcdata->arg_types[i];
}
return 0;
}
funcdata = funcdata->next;
}
NpyErr_SetString(NpyExc_TypeError, msg);
return -1;
}
/* look for match in self->functions */
for (j = 0; j < self->ntypes; j++) {
if (rtypenums[0] == self->types[j*nargs+self->nin]) {
i = nargs;
}
else {
i = -1;
}
if (i == nargs) {
*function = self->functions[j];
*data = self->data[j];
for (i = 0; i < nargs; i++) {
arg_types[i] = self->types[j*nargs+i];
}
return 0;
}
}
NpyErr_SetString(NpyExc_TypeError, msg);
return -1;
}
void
npy_ufunc_dealloc(NpyUFuncObject *self)
{
/* TODO: Ready to move */
if (self->core_num_dims) {
free(self->core_num_dims);
}
if (self->core_dim_ixs) {
free(self->core_dim_ixs);
}
if (self->core_offsets) {
free(self->core_offsets);
}
if (self->core_signature) {
free(self->core_signature);
}
if (self->ptr) {
free(self->ptr);
}
if (NULL != self->userloops) {
NpyDict_Destroy(self->userloops);
}
self->nob_magic_number = NPY_INVALID_MAGIC;
free(self);
}
static void
ufuncloop_dealloc(NpyUFuncLoopObject *self)
{
if (self->ufunc != NULL) {
if (self->core_dim_sizes) {
free(self->core_dim_sizes);
}
if (self->core_strides) {
free(self->core_strides);
}
self->iter->numiter = self->ufunc->nargs;
Npy_DECREF(self->iter);
if (self->buffer[0]) {
NpyDataMem_FREE(self->buffer[0]);
}
NpyInterface_DECREF(self->errobj);
Npy_DECREF(self->ufunc);
}
self->nob_magic_number = NPY_INVALID_MAGIC;
free(self);
}
static void
ufuncreduce_dealloc(NpyUFuncReduceObject *self)
{
if (self->ufunc) {
Npy_XDECREF(self->it);
Npy_XDECREF(self->rit);
Npy_XDECREF(self->ret);
NpyInterface_DECREF(self->errobj);
Npy_XDECREF(self->decref_arr);
if (self->buffer) {
NpyDataMem_FREE(self->buffer);
}
Npy_DECREF(self->ufunc);
}
self->nob_magic_number = NPY_INVALID_MAGIC;
free(self);
}
/*
* Create copies for any arrays that are less than loop->bufsize
* in total size (or core_enabled) and are mis-behaved or in need
* of casting.
*/
static int
_create_copies(NpyUFuncLoopObject *loop, int *arg_types, NpyArray **mps)
{
int nin = loop->ufunc->nin;
int i;
npy_intp size;
NpyArray_Descr *ntype;
NpyArray_Descr *atype;
for (i = 0; i < nin; i++) {
size = NpyArray_SIZE(mps[i]);
/*
* if the type of mps[i] is equivalent to arg_types[i]
* then set arg_types[i] equal to type of mps[i] for later checking....
*/
if (NpyArray_TYPE(mps[i]) != arg_types[i]) {
ntype = mps[i]->descr;
atype = NpyArray_DescrFromType(arg_types[i]);
if (NpyArray_EquivTypes(atype, ntype)) {
arg_types[i] = ntype->type_num;
}
Npy_DECREF(atype);
}
if (size < loop->bufsize || loop->ufunc->core_enabled) {
if (!(NpyArray_ISBEHAVED_RO(mps[i]))
|| NpyArray_TYPE(mps[i]) != arg_types[i]) {
NpyArray *new;
ntype = NpyArray_DescrFromType(arg_types[i]);
/* Move reference to interface. */
new = NpyArray_FromArray(mps[i], ntype,
NPY_FORCECAST | NPY_ALIGNED);
if (new == NULL) {
return -1;
}
Npy_DECREF(mps[i]);
mps[i] = new;
}
}
}
return 0;
}
/* Check and set core_dim_sizes and core_strides for the i-th argument. */
static int
_compute_dimension_size(NpyUFuncLoopObject *loop, NpyArray **mps, int i)
{
NpyUFuncObject *ufunc = loop->ufunc;
int j = ufunc->core_offsets[i];
int k = NpyArray_NDIM(mps[i]) - ufunc->core_num_dims[i];
int ind;
for (ind = 0; ind < ufunc->core_num_dims[i]; ind++, j++, k++) {
npy_intp dim = k < 0 ? 1 : NpyArray_DIM(mps[i], k);
/* First element of core_dim_sizes will be used for looping */
int dim_ix = ufunc->core_dim_ixs[j] + 1;
if (loop->core_dim_sizes[dim_ix] == 1) {
/* broadcast core dimension */
loop->core_dim_sizes[dim_ix] = dim;
}
else if (dim != 1 && dim != loop->core_dim_sizes[dim_ix]) {
NpyErr_SetString(NpyExc_ValueError, "core dimensions mismatch");
return -1;
}
/* First ufunc->nargs elements will be used for looping */
loop->core_strides[ufunc->nargs + j] =
dim == 1 ? 0 : NpyArray_STRIDE(mps[i], k);
}
return 0;
}
static NpyArray *
_getidentity(NpyUFuncObject *self, int otype, char *str)
{
NpyArray *arr;
NpyArray_Descr *descr, *indescr;
unsigned char identity;
NpyArray_VectorUnaryFunc *castfunc;
if (self->identity == NpyUFunc_None) {
char buf[256];
NpyOS_snprintf(buf, 256,
"zero-size array to ufunc.%s without identity", str);
NpyErr_SetString(NpyExc_ValueError, buf);
return NULL;
}
/* Get the identity as an unsigned char. */
if (self->identity == NpyUFunc_One) {
identity = 1;
} else {
identity = 0;
}
/* Build the output 0-d array. */
descr = NpyArray_DescrFromType(otype);
if (descr == NULL) {
return NULL;
}
arr = NpyArray_Alloc(descr, 0, NULL, NPY_FALSE, NULL);
if (arr == NULL) {
return NULL;
}
indescr = NpyArray_DescrFromType(NPY_UBYTE);
assert(indescr != NULL);
castfunc = NpyArray_GetCastFunc(indescr, otype);
Npy_DECREF(indescr);
if (castfunc == NULL) {
NpyErr_SetString(NpyExc_ValueError,
"Can't cast identity to output type.");
return NULL;
}
/* Use the castfunc to fill in the array. */
castfunc(&identity, arr->data, 1, NULL, arr);
return arr;
}
/* return 1 if arg1 > arg2, 0 if arg1 == arg2, and -1 if arg1 < arg2 */
static int
cmp_arg_types(int *arg1, int *arg2, int n)
{
for (; n > 0; n--, arg1++, arg2++) {
if (NpyArray_EquivTypenums(*arg1, *arg2)) {
continue;
}
if (NpyArray_CanCastSafely(*arg1, *arg2)) {
return -1;
}
return 1;
}
return 0;
}
static int
_create_reduce_copy(NpyUFuncReduceObject *loop, NpyArray **arr, int rtype)
{
npy_intp maxsize;
NpyArray *new;
NpyArray_Descr *ntype;
maxsize = NpyArray_SIZE(*arr);
if (maxsize < loop->bufsize) {
if (!(NpyArray_ISBEHAVED_RO(*arr))
|| NpyArray_TYPE(*arr) != rtype) {
ntype = NpyArray_DescrFromType(rtype);
new = NpyArray_FromArray(*arr, ntype, NPY_FORCECAST | NPY_ALIGNED);
if (new == NULL) {
return -1;
}
*arr = new;
loop->decref_arr = new;
}
}
/*
* Don't decref *arr before re-assigning
* because it was not going to be DECREF'd anyway.
*
* If a copy is made, then the copy will be removed
* on deallocation of the loop structure by setting
* loop->decref_arr.
*/
return 0;
}
/*
* Concatenate the loop and core dimensions of
* PyArrayMultiIterObject's iarg-th argument, to recover a full
* dimension array (used for output arguments).
*/
static npy_intp*
_compute_output_dims(NpyUFuncLoopObject *loop, int iarg,
int *out_nd, npy_intp *tmp_dims)
{
int i;
NpyUFuncObject *ufunc = loop->ufunc;
if (ufunc->core_enabled == 0) {
/* case of ufunc with trivial core-signature */
*out_nd = loop->iter->nd;
return loop->iter->dimensions;
}
*out_nd = loop->iter->nd + ufunc->core_num_dims[iarg];
if (*out_nd > NPY_MAXARGS) {
NpyErr_SetString(NpyExc_ValueError,
"dimension of output variable exceeds limit");
return NULL;
}
/* copy loop dimensions */
memcpy(tmp_dims, loop->iter->dimensions, sizeof(npy_intp) * loop->iter->nd);
/* copy core dimension */
for (i = 0; i < ufunc->core_num_dims[iarg]; i++) {
tmp_dims[loop->iter->nd + i] = loop->core_dim_sizes[
1 + ufunc->core_dim_ixs[ufunc->core_offsets[iarg] + i]];
}
return tmp_dims;
}
/* Return a view of array "ap" with "core_nd" dimensions cut from tail. */
static NpyArray *
_trunc_coredim(NpyArray *ap, int core_nd)
{
NpyArray *ret;
int nd = NpyArray_NDIM(ap) - core_nd;
if (nd < 0) {
nd = 0;
}
/* The following code is basically taken from PyArray_Transpose */
/* NewFromDescr will steal this reference */
Npy_INCREF(ap->descr);
ret = NpyArray_NewFromDescr(ap->descr,
nd, ap->dimensions,
ap->strides,
ap->data,
ap->flags,
NPY_FALSE, NULL, Npy_INTERFACE(ap));
if (ret == NULL) {
return NULL;
}
/* point at true owner of memory: */
NpyArray_BASE_ARRAY(ret) = ap;
Npy_INCREF(ap);
assert(NULL == NpyArray_BASE(ret));
NpyArray_UpdateFlags(ret, NPY_CONTIGUOUS | NPY_FORTRAN);
return ret;
}
/*
* Called for non-NULL user-defined functions.
* The object should be a CObject pointing to a linked-list of functions
* storing the function, data, and signature of all user-defined functions.
* There must be a match with the input argument types or an error
* will occur.
*/
static int
_find_matching_userloop(NpyUFunc_Loop1d *funcdata, int *arg_types,
NPY_SCALARKIND *scalars,
NpyUFuncGenericFunction *function, void **data,
int nargs, int nin)
{
int i;
while (funcdata != NULL) {
for (i = 0; i < nin; i++) {
if (!NpyArray_CanCoerceScalar(arg_types[i],
funcdata->arg_types[i],
scalars[i]))
break;
}
if (i == nin) {
/* match found */
*function = funcdata->func;
*data = funcdata->data;
/* Make sure actual arg_types supported by the loop are used */
for (i = 0; i < nargs; i++) {
arg_types[i] = funcdata->arg_types[i];
}
return 0;
}
funcdata = funcdata->next;
}
return -1;
}
/* Return the position of next non-white-space char in the string */
static int
_next_non_white_space(const char* str, int offset)
{
int ret = offset;
while (str[ret] == ' ' || str[ret] == '\t') {
ret++;
}
return ret;
}
static int
_is_alpha_underscore(char ch)
{
return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_';
}
static int
_is_alnum_underscore(char ch)
{
return _is_alpha_underscore(ch) || (ch >= '0' && ch <= '9');
}
/*
* Return the ending position of a variable name
*/
static int
_get_end_of_name(const char* str, int offset)
{
int ret = offset;
while (_is_alnum_underscore(str[ret])) {
ret++;
}
return ret;
}
/*
* Returns 1 if the dimension names pointed by s1 and s2 are the same,
* otherwise returns 0.
*/
static int
_is_same_name(const char* s1, const char* s2)
{
while (_is_alnum_underscore(*s1) && _is_alnum_underscore(*s2)) {
if (*s1 != *s2) {
return 0;
}
s1++;
s2++;
}
return !_is_alnum_underscore(*s1) && !_is_alnum_underscore(*s2);
}
/*
* Sets core_num_dim_ix, core_num_dims, core_dim_ixs, core_offsets,
* and core_signature in PyUFuncObject "self". Returns 0 unless an
* error occured.
*/
static int
_parse_signature(NpyUFuncObject *self, const char *signature)
{
size_t len;
char const **var_names;
int nd = 0; /* number of dimension of the current argument */
int cur_arg = 0; /* index into core_num_dims&core_offsets */
int cur_core_dim = 0; /* index into core_dim_ixs */
int i = 0;
char *parse_error = NULL;
if (signature == NULL) {
NpyErr_SetString(NpyExc_RuntimeError,
"_parse_signature with NULL signature");
return -1;
}
len = strlen(signature);
self->core_signature = malloc(sizeof(char) * (len+1));
if (self->core_signature) {
strcpy(self->core_signature, signature);
}
/* Allocate sufficient memory to store pointers to all dimension names */
var_names = malloc(sizeof(char const*) * len);
if (var_names == NULL) {
NpyErr_MEMORY;
return -1;
}
self->core_enabled = 1;
self->core_num_dim_ix = 0;
self->core_num_dims = malloc(sizeof(int) * self->nargs);
self->core_dim_ixs = malloc(sizeof(int) * len); /* shrink this later */
self->core_offsets = malloc(sizeof(int) * self->nargs);
if (self->core_num_dims == NULL || self->core_dim_ixs == NULL
|| self->core_offsets == NULL) {
NpyErr_MEMORY;
goto fail;
}
i = _next_non_white_space(signature, 0);
while (signature[i] != '\0') {
/* loop over input/output arguments */
if (cur_arg == self->nin) {
/* expect "->" */
if (signature[i] != '-' || signature[i+1] != '>') {
parse_error = "expect '->'";
goto fail;
}
i = _next_non_white_space(signature, i + 2);
}
/*
* parse core dimensions of one argument,
* e.g. "()", "(i)", or "(i,j)"
*/
if (signature[i] != '(') {
parse_error = "expect '('";
goto fail;
}
i = _next_non_white_space(signature, i + 1);
while (signature[i] != ')') {
/* loop over core dimensions */
int j = 0;
if (!_is_alpha_underscore(signature[i])) {
parse_error = "expect dimension name";
goto fail;
}
while (j < self->core_num_dim_ix) {
if (_is_same_name(signature+i, var_names[j])) {
break;
}
j++;
}
if (j >= self->core_num_dim_ix) {
var_names[j] = signature+i;
self->core_num_dim_ix++;
}
self->core_dim_ixs[cur_core_dim] = j;
cur_core_dim++;
nd++;
i = _get_end_of_name(signature, i);
i = _next_non_white_space(signature, i);
if (signature[i] != ',' && signature[i] != ')') {
parse_error = "expect ',' or ')'";
goto fail;
}
if (signature[i] == ',')
{
i = _next_non_white_space(signature, i + 1);
if (signature[i] == ')') {
parse_error = "',' must not be followed by ')'";
goto fail;
}
}
}
self->core_num_dims[cur_arg] = nd;
self->core_offsets[cur_arg] = cur_core_dim-nd;
cur_arg++;
nd = 0;
i = _next_non_white_space(signature, i + 1);
if (cur_arg != self->nin && cur_arg != self->nargs) {
/*
* The list of input arguments (or output arguments) was
* only read partially
*/
if (signature[i] != ',') {
parse_error = "expect ','";
goto fail;
}
i = _next_non_white_space(signature, i + 1);
}
}
if (cur_arg != self->nargs) {
parse_error = "incomplete signature: not all arguments found";
goto fail;
}
self->core_dim_ixs = realloc(self->core_dim_ixs,
sizeof(int)*cur_core_dim);
/* check for trivial core-signature, e.g. "(),()->()" */
if (cur_core_dim == 0) {
self->core_enabled = 0;
}
free((void*)var_names);
return 0;
fail:
free((void*)var_names);
if (parse_error) {
char *buf = malloc(sizeof(char) * (len + 200));
if (buf) {
sprintf(buf, "%s at position %d in \"%s\"",
parse_error, i, signature);
NpyErr_SetString(NpyExc_ValueError, signature);
free(buf);
}
else {
NpyErr_MEMORY;
}
}
return -1;
}
static char
_lowest_type(char intype)
{
/* TODO: Ready to move */
switch(intype) {
/* case PyArray_BYTE */
case NPY_SHORT:
case NPY_INT:
case NPY_LONG:
case NPY_LONGLONG:
case NPY_DATETIME:
case NPY_TIMEDELTA:
return NPY_BYTE;
/* case NPY_UBYTE */
case NPY_USHORT:
case NPY_UINT:
case NPY_ULONG:
case NPY_ULONGLONG:
return NPY_UBYTE;
/* case PyArray_FLOAT:*/
case NPY_DOUBLE:
case NPY_LONGDOUBLE:
return NPY_FLOAT;
/* case PyArray_CFLOAT:*/
case NPY_CDOUBLE:
case NPY_CLONGDOUBLE:
return NPY_CFLOAT;
default:
return intype;
}
}
/* Return 1 if the given data pointer for the loop specifies that it needs the
* arrays as the data pointer.
*/
static int
_does_loop_use_arrays(void *data)
{
return (data == NpyUFunc_SetUsesArraysAsData);
}
/*
* Floating point error handling.
*/
void
NpyUFunc_SetFpErrFuncs(fpe_state_f state, fpe_handler_f handler)
{
fp_error_state = state;
fp_error_handler = handler;
}
int
NpyUFunc_getfperr(void)
{
int retstatus;
NPY_UFUNC_CHECK_STATUS(retstatus);
return retstatus;
}
int
NpyUFunc_checkfperr(char* name, int errmask, void *errobj, int *first)
{
int retstatus;
if (name == NULL) {
name = "";
}
/* 1. check hardware flag --- this is platform dependent code */
retstatus = NpyUFunc_getfperr();
fp_error_handler(name, errmask, errobj, retstatus, first);
return 0;
}
/* Checking the status flag clears it */
void
NpyUFunc_clearfperr()
{
NpyUFunc_getfperr();
}
/*
* Userloops dictionary implementation
*/
static int
compare_ints(const void *a, const void *b)
{
if (a < b ) return -1;
else if ( a > b ) return 1;
return 0;
}
static int
hash_int(const void *a)
{
return (int)a; /* Size change is safe - just a hash function */
}
/* This frees the linked-list structure when the CObject is destroyed (removed
from the internal dictionary) */
static void
free_loop1d_list(NpyUFunc_Loop1d *data)
{
while (data != NULL) {
NpyUFunc_Loop1d *next = data->next;
NpyArray_free(data->arg_types);
NpyArray_free(data);
data = next;
}
}
NpyDict *npy_create_userloops_table()
{
NpyDict *new = NpyDict_CreateTable(7); /* 7 is a guess at enough */
NpyDict_SetKeyComparisonFunction(
new, (int (*)(const void *, const void *))compare_ints);
NpyDict_SetHashFunction(new, (int (*)(const void *))hash_int);
NpyDict_SetDeallocationFunctions(new, NULL,
(void (*)(void *))free_loop1d_list);
return new;
}
| 32.613279 | 89 | 0.485446 |
76ca35df95e719d7591e5c7ea8aa0e3399a208ca | 2,069 | c | C | dist/linux/genometools/src/gth/dp_options_est.c | thmourikis/erv_annotator | 448b2dfc2972f9bf4e743df36fe0232813590fec | [
"MIT"
] | null | null | null | dist/linux/genometools/src/gth/dp_options_est.c | thmourikis/erv_annotator | 448b2dfc2972f9bf4e743df36fe0232813590fec | [
"MIT"
] | 1 | 2018-09-30T00:45:55.000Z | 2018-09-30T00:45:55.000Z | dist/linux/genometools/src/gth/dp_options_est.c | thmourikis/erv_annotator | 448b2dfc2972f9bf4e743df36fe0232813590fec | [
"MIT"
] | null | null | null | /*
Copyright (c) 2003-2009 Gordon Gremme <gremme@zbh.uni-hamburg.de>
Copyright (c) 2003-2008 Center for Bioinformatics, University of Hamburg
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "core/ma_api.h"
#include "gth/default.h"
#include "gth/dp_options_est.h"
GthDPOptionsEST* gth_dp_options_est_new(void)
{
GthDPOptionsEST *dp_options_est = gt_malloc (sizeof *dp_options_est);
dp_options_est->probies = GTH_DEFAULT_PROBIES;
dp_options_est->probdelgen = GTH_DEFAULT_PROBDELGEN;
dp_options_est->identityweight = GTH_DEFAULT_IDENTITYWEIGHT;
dp_options_est->mismatchweight = GTH_DEFAULT_MISMATCHWEIGHT;
dp_options_est->undetcharweight = GTH_DEFAULT_UNDETCHARWEIGHT;
dp_options_est->deletionweight = GTH_DEFAULT_DELETIONWEIGHT;
dp_options_est->wzerotransition = GTH_DEFAULT_WZEROTRANSITION;
dp_options_est->wdecreasedoutput = GTH_DEFAULT_WDECREASEDOUTPUT;
dp_options_est->detectsmallexons = GTH_DEFAULT_DETECTSMALLEXONS;
return dp_options_est;
}
GthDPOptionsEST* gth_dp_options_est_clone(const GthDPOptionsEST *dp_options_est)
{
GthDPOptionsEST *dp_options_est_clone;
gt_assert(dp_options_est);
dp_options_est_clone = gt_malloc(sizeof *dp_options_est);
*dp_options_est_clone = *dp_options_est;
return dp_options_est_clone;
}
void gth_dp_options_est_delete(GthDPOptionsEST *dp_options_est)
{
if (!dp_options_est) return;
gt_free(dp_options_est);
}
| 40.568627 | 80 | 0.809087 |
d3427e9104a50ebadc81b103cb09155b72605c2d | 1,357 | h | C | onnxruntime/core/providers/cpu/controlflow/utils.h | wintersteiger/onnxruntime | 071a0c2522dd2af2b1936d608ef7182be6cfa883 | [
"MIT"
] | 2 | 2019-11-18T14:04:42.000Z | 2019-12-04T12:49:01.000Z | onnxruntime/core/providers/cpu/controlflow/utils.h | wintersteiger/onnxruntime | 071a0c2522dd2af2b1936d608ef7182be6cfa883 | [
"MIT"
] | null | null | null | onnxruntime/core/providers/cpu/controlflow/utils.h | wintersteiger/onnxruntime | 071a0c2522dd2af2b1936d608ef7182be6cfa883 | [
"MIT"
] | 4 | 2021-06-05T19:52:22.000Z | 2021-11-30T13:58:13.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <string>
#include <vector>
#include "core/common/common.h"
#include "core/framework/feeds_fetches_manager.h"
namespace onnxruntime {
namespace controlflow {
namespace detail {
// helper to execute the subgraph by calling the Execute method of the provided implementation class with
// with the cached or newly created FeedsFetchesManager
template <typename TImpl>
common::Status SubgraphExecuteHelper(std::unique_ptr<FeedsFetchesManager>& cached_feeds_fetches_manager, TImpl& impl) {
auto status = Status::OK();
if (cached_feeds_fetches_manager) {
// make it clear we don't update this instance when executing so there are no potential concurrency issues
const FeedsFetchesManager* cached_ffm = &*cached_feeds_fetches_manager;
status = impl.Execute(nullptr, cached_ffm);
} else {
// use a local instance until we know we're successful, and cache if it is
std::unique_ptr<FeedsFetchesManager> new_ffm;
ORT_RETURN_IF_ERROR(impl.CreateFeedsFetchesManager(new_ffm));
status = impl.Execute(&*new_ffm, nullptr);
if (status.IsOK()) {
cached_feeds_fetches_manager = std::move(new_ffm);
}
}
return status;
}
} // namespace detail
} // namespace controlflow
} // namespace onnxruntime
| 31.55814 | 119 | 0.753132 |
ee73de301890a486a23b975a85b4528adddd13cd | 478 | h | C | SmallPetsHealthcare/B_HX711.h | mihotoyama/doingio-small-pets-healthcare | 94f88e8ce10265a022cbc2c75554b9819f335cc6 | [
"Apache-2.0"
] | 6 | 2020-09-26T02:31:46.000Z | 2022-03-17T07:20:08.000Z | SmallPetsHealthcare/B_HX711.h | mihotoyama/doingio-small-pets-healthcare | 94f88e8ce10265a022cbc2c75554b9819f335cc6 | [
"Apache-2.0"
] | 1 | 2020-10-06T07:20:34.000Z | 2020-10-06T07:20:34.000Z | SmallPetsHealthcare/B_HX711.h | mihotoyama/doingio-small-pets-healthcare | 94f88e8ce10265a022cbc2c75554b9819f335cc6 | [
"Apache-2.0"
] | 3 | 2020-10-02T16:04:24.000Z | 2021-12-11T00:16:53.000Z | #include "Arduino.h"
#ifndef __B_HX711_H
#define __B_HX711_H
class B_HX711 {
private:
void Init();
void Reset();
long Read();
long Averaging(char NUM);
int DOUT_PIN;
int SLK_PIN;
float OUT_VOL = 0.001f;
float LOAD = 1000.0f;
float CALIB = 1.18;//1kg
public:
void Setup(int _DOUT_PIN, int _SLK_PIN, float _OUT_VOL, float _LOAD, float _CALIB);
float getVal();
float getGram(char NUM);
float offset;
};
#endif
| 17.071429 | 87 | 0.627615 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.