repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
pengdao/simcc
|
simcc/memmem.h
|
/* Copyright (C) 1991,92,93,94,96,97,98,2000,2004 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
*/
#pragma once
#include <string.h>
#ifdef WIN32
#ifndef _LIBC
# define __builtin_expect(expr, val) (expr)
#endif
#ifndef H_MEMMEM
#define H_MEMMEM
#undef memmem
// @see https://raw.githubusercontent.com/jaysi/jlib/3f7a190e1e80b270c9a07cac46aeab960a802cd1/src/memmem.c
// @see http://sourceware.org/ml/libc-alpha/2007-12/msg00000.html
/* Return the first occurrence of NEEDLE in HAYSTACK. */
inline void*
memmem(const void* haystack,
size_t haystack_len,
const void* needle,
size_t needle_len) {
/* not really Rabin-Karp, just using additive hashing */
char* haystack_ = (char*)haystack;
char* needle_ = (char*)needle;
int hash = 0; /* this is the static hash value of the needle */
int hay_hash = 0; /* rolling hash over the haystack */
char* last;
size_t i;
if (haystack_len < needle_len) {
return NULL;
}
if (!needle_len) {
return haystack_;
}
/* initialize hashes */
for (i = needle_len; i; --i) {
hash += *needle_++;
hay_hash += *haystack_++;
}
/* iterate over the haystack */
haystack_ = (char*)haystack;
needle_ = (char*)needle;
last = haystack_ + (haystack_len - needle_len + 1);
for (; haystack_ < last; ++haystack_) {
if (__builtin_expect(hash == hay_hash, 0) &&
*haystack_ == *needle_ && /* prevent calling memcmp, was a optimization from existing glibc */
!memcmp(haystack_, needle_, needle_len)) {
return haystack_;
}
/* roll the hash */
hay_hash -= *haystack_;
hay_hash += *(haystack_ + needle_len);
}
return NULL;
}
#endif // end of H_MEMMEM
#endif
|
pengdao/simcc
|
simcc/gettimeofday.h
|
<reponame>pengdao/simcc
#pragma once
#include <time.h>
#ifdef WIN32
#define _WINSOCKAPI_
#include <windows.h>
#include <WinSock2.h>
#else
#include <sys/time.h>
#endif
#ifdef WIN32
#ifndef H_GETTIMEOFDAY
#define H_GETTIMEOFDAY
inline int gettimeofday(struct timeval* tp, void* tzp) {
time_t clock;
struct tm tm;
SYSTEMTIME wtm;
GetLocalTime(&wtm);
tm.tm_year = wtm.wYear - 1900;
tm.tm_mon = wtm.wMonth - 1;
tm.tm_mday = wtm.wDay;
tm.tm_hour = wtm.wHour;
tm.tm_min = wtm.wMinute;
tm.tm_sec = wtm.wSecond;
tm.tm_isdst = -1;
clock = mktime(&tm);
tp->tv_sec = (long)clock;
tp->tv_usec = wtm.wMilliseconds * 1000;
return (0);
}
#endif // end of H_GETTIMEOFDAY
#endif //end of WIN32
namespace simcc {
inline double utcsecond() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (double)(tv.tv_sec) + ((double)(tv.tv_usec)) / 1000000.0f;
}
inline uint64_t utcmicrosecond() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64_t)(((uint64_t)(tv.tv_sec)) * 1000000 + tv.tv_usec);
}
inline struct timeval timevalconv(uint64_t time_us) {
struct timeval tv;
tv.tv_sec = (long)time_us / 1000000;
tv.tv_usec = (long)time_us % 1000000;
return tv;
}
}
|
pengdao/simcc
|
simcc/misc/double_buffering.h
|
#pragma once
#include "simcc/inner_pre.h"
#include "simcc/ref_object.h"
#include "simcc/timestamp.h"
#include <mutex>
#include <map>
namespace simcc {
class SIMCC_EXPORT DoubleBuffering {
public:
class SIMCC_EXPORT Target : public RefObject {
public:
virtual bool Initialize(const string& conf) = 0;
virtual string MD5() const { return ""; }
virtual ~Target() {}
};
typedef RefPtr<Target> TargetPtr;
typedef std::function<TargetPtr ()> TargetCreator;
DoubleBuffering(TargetCreator f);
bool Reload(const string& conf);
string MD5() const;
Timestamp reload_time() const {
return reload_time_;
}
TargetPtr Get() const;
private:
mutable std::mutex mutex_;
TargetPtr current_;
TargetCreator creator_;
Timestamp reload_time_;
};
typedef std::shared_ptr<DoubleBuffering> DoubleBufferingPtr;
class SIMCC_EXPORT DoubleBufferingManager {
public:
DoubleBufferingManager();
bool Add(const string& name,
const string& conf,
DoubleBuffering::TargetCreator f);
DoubleBuffering* Get(const string& name) const;
bool Reload(const string& name, const string& conf);
private:
std::map<string/*name*/, DoubleBufferingPtr> dbufs_;
mutable std::mutex mutex_;
};
}
|
pengdao/simcc
|
simcc/base64.h
|
#pragma once
#include "simcc/inner_pre.h"
#include <string.h>
#include <string>
namespace simcc {
class SIMCC_EXPORT Base64 {
public:
// @brief b64 encode a c-style string with len
//
// @param[in] s the input string to encode
// @param[in] len the length of the input string
// @return a newly allocated b64 string. Empty if failed.
static string Encode(const char* s, size_t len);
// @brief b64 encode a c-style string
//
// @param[in] s the input string to encode
// @return a newly allocated b64 string. Empty if failed.
static string Encode(const char* s) {
return Encode(s, static_cast<int>(strlen(s)));
}
// @brief b64 encode a const string
//
// @param[in] s the input string to encode
// @return a newly allocated b64 string. Empty if failed.
static string Encode(const string& s) {
return Encode(s.data(), s.size());
}
static string Decode(const char* src, size_t len);
static string Decode(const char* src) {
return Decode(src, strlen(src));
}
static string Decode(const string& s) {
return Decode(s.data(), s.size());
}
};
}
|
pengdao/simcc
|
simcc/file_util.inl.h
|
#pragma once
#ifdef H_OS_WINDOWS
#include <direct.h>
#include <io.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <limits.h>
#endif
namespace simcc {
inline bool FileUtil::IsValidDirName(const char* szName) {
return !(szName [0] == ('.') ||
(szName [1] != 0 && (szName[1] == '.' && szName[2] == 0)));
}
// Query whether strFileName is a absolute path.
inline bool FileUtil::IsAbsolutePath(const string& path) {
if (path.size() == 0) {
return false;
}
#ifdef H_OS_WINDOWS
if (isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':') {
return true;
} else {
return false;
}
#else
return path[0] == '/';
#endif
}
inline string FileUtil::GetAbsolutePathName(const string& strPathName) {
string strTmp = strPathName;
if (!IsAbsolutePath(strTmp)) {
//
char szDir[_MAX_PATH];
#ifdef H_OS_WINDOWS
if (_getcwd(szDir, _MAX_PATH)) {
strTmp = string(szDir) + ("/") + strTmp;
}
#else
getcwd(szDir, _MAX_PATH);
strTmp = string(szDir) + ("/") + strTmp;
#endif
}
// convert file name here.
NormalizePath(strTmp);
return strTmp;
}
inline string FileUtil::GetFileName(const string& strFileName) {
// since '/' equal to L'/', we can cast to either one.
string::size_type i = strFileName.find_last_of((string::value_type)'/');
if (i == string::npos) {
return strFileName;
}
return strFileName.substr(i + 1);
}
inline string FileUtil::GetFileNameWithoutExt(const string& strFileName) {
// since '/' equal to L'/', we can cast to either one.
string::size_type iStart = strFileName.find_last_of((string::value_type)'/');
if (iStart == string::npos) {
iStart = 0;
} else {
// skip the '/'
++iStart;
}
return strFileName.substr(iStart, strFileName.find_last_of((string::value_type)'.') - iStart);
}
inline string FileUtil::GetFileNameExtension(const string& strFileName) {
string::size_type endPos = strFileName.find_last_of((string::value_type)'.');
if (endPos < strFileName.length() - 1) {
return strFileName.substr(endPos + 1);
}
return string();
}
inline string FileUtil::GetFileDirName(const string& strFileName) {
// since '/' equal to L'/', we can cast to either one.
string::size_type i = strFileName.find_last_of((string::value_type)'/');
if (i == string::npos) {
return string();
}
return strFileName.substr(0, i);
}
inline bool FileUtil::IsDir(const char* szFileName) {
if (!szFileName) {
return false;
}
const string strFileName(szFileName);
return IsDir(strFileName);
}
inline bool FileUtil::IsDir(const string& strFileName) {
//for the 'stat' API, the parameter strFileName SHOULD not contain a trailing backslash
string strStandardisePath = NormalizePath(strFileName, false);
struct stat st;
if (0 != stat(strStandardisePath.c_str(), &st)) {
return false;
}
#ifdef H_OS_WINDOWS
if ((st.st_mode & _S_IFDIR) == _S_IFDIR)
#else
if (S_ISDIR(st.st_mode))
#endif
{
return true;
}
return false;
}
inline bool FileUtil::RemoveDirIfEmpty(const string& strDirName, bool bRecursivelyDeleteEmptyParentDir /*= true*/) {
if (!IsDir(strDirName)) {
return true;
}
bool retval = true;
std::list<string> files;
GetFiles(strDirName, files, true);
if (files.size() == 0) {
if (FileUtil::Rmdir(strDirName.c_str()) != 0) {
retval = false;
}
}
if (bRecursivelyDeleteEmptyParentDir) {
string strParentDir = GetParentDir(strDirName);
if (!RemoveDirIfEmpty(strParentDir, bRecursivelyDeleteEmptyParentDir)) {
retval = false;
}
}
return retval;
}
inline string FileUtil::GetParentDir(const string& strFileName, bool with_trailing_slash /*= true*/) {
string path = NormalizePath(strFileName, false);
if (!IsAbsolutePath(strFileName)) {
path = GetAbsolutePathName(path);
}
size_t pos = path.find_last_of('/');
if (pos == 0 || pos == string::npos) {
if (with_trailing_slash) {
path += "/";
}
return path;
} else {
if (with_trailing_slash) {
string retp = string(path.c_str(), pos) + "/";
return retp;
} else {
return string(path.c_str(), pos);
}
}
}
inline bool FileUtil::Rmdir(const string& strDirName) {
return Rmdir(strDirName.c_str());
}
inline bool FileUtil::Rmdir(const char* strDirName) {
#ifdef H_OS_WINDOWS
if (::_rmdir(strDirName) == 0)
#else
if (::rmdir(strDirName) == 0)
#endif
{
return true;
}
return false;
}
}
|
pengdao/simcc
|
simcc/exp.h
|
#pragma once
#ifdef H_OS_WINDOWS
H_LINK_LIB("libglueasync")
#endif
// #include "glueasync_types.h"
// #include "glueasync_common.h"
// #include "glueasync_context.h"
// #include "glueasync_status.h"
// #include "glueasync_module.h"
// #include "sync_module.h"
// #include "gas_module_manager.h"
// #include "sync_module_manager.h"
|
pengdao/simcc
|
simcc/ini_parser.h
|
#pragma once
#include "simcc/inner_pre.h"
#include "simcc/gcc_list.h"
#include <string>
#include <map>
#include <vector>
namespace simcc {
class DataStream;
// @brief The class for parsing an INI format file or memory data.
// The INI file can contains comments lines which start with '#' or '//' or ';'
class SIMCC_EXPORT INIParser {
public:
typedef std::map<string, string> ssmap;
typedef std::map<string, ssmap> SectionMap;
typedef list<string> StringList;
typedef std::pair<string, StringList> SectionPairEntry;
typedef list<SectionPairEntry> SectionList;
typedef std::function<void(INIParser& parser, const string& section, const string& key, const string& value)> ParseListener;
typedef std::function<void(const INIParser& parser, const string& section, const string& key, const string& value)> Visitor;
enum ErrorCode {
kNoError = 0,
kErrorCannotFindKVSeperator = 1,
kErrorCannotFindLineSeperator = 2,
kErrorCannotFindKVSeperatorAndLineSeperator = 3,
kErrorSectionFormatWrong = 4,
};
public:
// @brief
// @param[in] is_case_sensitive -
// @param[in] is_compatible - If it is true, we will neglect the wrong format line and try to parse the remaining contents
// @param[in] keep_sequence - If it is true, we will record the sequence of the input INI file. This will slow down the parsing speed.
// @return -
INIParser(bool is_case_sensitive = true, bool is_compatible = false, bool keep_sequence = false);
~INIParser();
// @brief Clear the section/key-value map
void Reset();
// @brief Parse the INI file
// @param const string & filename - The INI file name
// @return bool - return true if parse successfully.
// In the compatible mode of parsing, even this function return true,
// there is a chance that the INI file contents is wrong,
// at this time we can use <code>error()</code> function to get the actual error code
bool Parse(const string& filename);
bool Parse(const char* filename);
// @brief Parse the raw data.
// We will parse the data every line.
// Lines are separated by '\n'.
// @param const char * data - The source data
// @param size_t datalen - The length of the data
// @return bool - return true if parse successfully
bool Parse(const char* data, size_t datalen);
// @brief Parse the raw data
// We will parse the data line by line.
// Lines are separated by <code>linesep</code>
// key-value is separated by <code>keyvaluesep</code>
// @param const char * data -
// @param size_t datalen -
// @param const char * linesep - the line separator
// @param const char * keyvaluesep - the key/value separator
// @return bool -
bool Parse(const char* data, size_t datalen, const char* linesep, const char* keyvaluesep);
bool Parse(const char* data, size_t datalen, const string& linesep, const string& keyvaluesep);
// @brief When parsing the INI file, you can call this function to stop the parsing
// @return void -
void StopParsing(bool stop_parsing);
//The error code
ErrorCode error() const {
return error_code_;
}
bool ok() const {
return error_code_ == kNoError;
}
const char* strerror() const;
// @brief
// @param ParseListener * pl -
// @return void -
void SetParseListener(ParseListener pl);
// Query
public:
// @brief Get the value of specified key from the default section
// @param const string & key -
// @param[out] size_t * data_len - If it is provided, the value length will stored here
// @return const char* - If find return the value, or return NULL
// @return const string& - If find return the value, or return an empty string
const string& Get(const string& key, bool* found = NULL) const;
// @brief Get the value of specified key from a certain section
// @param const string & section - The section name
// @param const string & key - The key
// @param[out] size_t * data_len - If it is provided, the value length will stored here
// @return const char* - If find return the value, or return NULL
// @return const string& - If find return the value, or return an empty string
const string& Get(const string& section, const string& key, bool* found = NULL) const;
int64_t GetInteger(const string& key, int64_t default_value = 0) const;
int64_t GetInteger(const string& section, const string& key, int64_t default_value = 0) const;
bool GetBool(const string& key, bool default_value = false) const;
bool GetBool(const string& section, const string& key, bool default_value = false) const;
double GetDouble(const string& key, double default_value = 0.0) const;
double GetDouble(const string& section, const string& key, double default_value = 0.0) const;
// @brief Set the value of specified key into a certain section
// @param const string & section - The section name
// @param const string & key - The key
// @param const string & key - The value
void Set(const string& section, const string& key, const string& value);
void Set(const string& key, const string& value);
// @brief Get the default key/value Map
// which equals to call <code>GetKeyValueMap("")</code>
// @return const StringAStringAMap& -
const ssmap& GetDefaultKeyValueMap();
// @brief Get the key/value Map of a certain section
// @param const string & section - The section name
// @return const ssmap& -
const ssmap& GetKeyValueMap(const string& section) const;
// @brief Get the section full map
// @return - const SectionMap&
const SectionMap& GetSectionMap() const {
return section_map_;
}
public:
bool compatible() const {
return compatible_;
}
void set_compatible(bool val) {
compatible_ = val;
}
// @brief Query whether it is case sensitive
// @return - bool
bool case_sensitive() const {
return case_sensitive_;
}
void set_case_sensitive(bool b) {
case_sensitive_ = b;
}
void set_trim_chars(const string& trim_chars);
void set_keep_sequence(bool b) {
keep_sequence_ = b;
}
// Separator
public:
void SetKVSeparator(const string& separator) {
kv_sep_ = separator;
}
void SetLineSeparator(const string& separator) {
line_sep_ = separator;
}
const string& line_separator() const {
return line_sep_;
}
const string& kv_separator() const {
return kv_sep_;
}
// Visit
public:
// @brief Visit all the section/key/value in this INI.
// If sequential is true, we will visit the section/key/value
// in the order of the input file.
// If sequential is false, we will visit the section/key/value
// in the memory order, it is may be not the same of the input order.
// @param[in] - FastVisitor & visitor
// @return - void
void Visit(const Visitor& visitor, bool sequential = false) const;
void Visit(const string& section, const Visitor& visitor, bool sequential = false) const;
// Serialize
public:
// @brief Serialize the INI to output string
// @param[in] - bool input_order - true if we want to
// serialize this INI object as the order of the input INI file
// @return - string
string Serialize(bool input_order = false) const;
// @brief Serialize the INI to output string
// @param[in] - string & output
// @param[in] - MemoryDataStream & buf
// @param[in] - std::ostream & os
// @return - void
void Serialize(string& output, bool input_order = false) const;
void Serialize(DataStream& buf, bool input_order = false) const;
void Serialize(std::ostream& os, bool input_order = false) const;
private:
void InitTrimCharsTable();
// @brief Skip the lines which start with '#' or '//' or ";"
// @note Lines are separated by '\n' or '\r\n'
// @param const char * szsrc - The source string
// @return const char* - The pointer to the next line
const char* SkipCommits(const char* szsrc, size_t len);
// @brief Skipping whitespace, such as '\n' '\r' ' '
// @param const char * szsrc - The source string
// @return const char* - The pointer to the next character
const char* SkipSpaces(const char* szsrc);
// @brief Skipping the characters within <code>trim_chars_</code>
// @param const char * szsrc - The source string
// @param const char * dataend - The end of the string, not include
// @return const char* - The pointer to the next character
const char* SkipTrimChars(const char* szsrc, const char* dataend);
template<class stream_t>
void serialize(stream_t& os, bool input_order = false) const;
enum Status {
kFinishedError = 0,
kFinishedOK,
kFoundKeyAndValue,
kNeedSkipThisLine,
};
Status CheckStatus(const char* dataend, const char* kv_sep_pos, const char*& line_end/*in,out*/);
private:
bool case_sensitive_;// case sensitive flag
bool stop_parsing_; // stop the parsing
bool keep_sequence_;
SectionMap section_map_; // pair<section string, key/value map>
string kv_sep_;// The key/value separator
string line_sep_;// The key/value separator
SectionList section_list_; // pair<section string, keys list>
ErrorCode error_code_;
bool compatible_;
string trim_chars_; // the trimming characters when parsing
char trim_chars_table_[256];
typedef std::list<ParseListener> ListenerList;
ListenerList listeners_;
class SequenceParseListener;
};
inline void INIParser::Reset() {
section_map_.clear();
}
inline void INIParser::StopParsing(bool stop_parsing) {
stop_parsing_ = stop_parsing;
}
}
|
abhay-agarwal/DueTimer
|
DueTimer.h
|
/*
DueTimer.h - DueTimer header file, definition of methods and attributes...
For instructions, go to https://github.com/ivanseidel/DueTimer
Created by <NAME>, March, 2013.
Modified by <NAME>, June 2013.
Released into the public domain.
*/
#include "Arduino.h"
#if defined(_SAM3XA_)
#ifndef DueTimer_h
#define DueTimer_h
#include <inttypes.h>
#define USING_IR_LIB true
#if defined TC2
#define NUM_TIMERS 9
#else
#define NUM_TIMERS 6
#endif
class DueTimer
{
protected:
// Represents the timer id (index for the array of Timer structs)
const unsigned short timer;
// Stores the object timer frequency
// (allows to access current timer period and frequency):
static double _frequency[NUM_TIMERS];
// Picks the best clock to lower the error
static uint8_t bestClock(double frequency, uint32_t& retRC);
// Make Interrupt handlers friends, so they can use callbacks
friend void TC0_Handler(void);
friend void TC1_Handler(void);
friend void TC2_Handler(void);
#ifndef USING_IR_LIB
friend void TC3_Handler(void);
#endif
friend void TC4_Handler(void);
friend void TC5_Handler(void);
#if NUM_TIMERS > 6
friend void TC6_Handler(void);
friend void TC7_Handler(void);
friend void TC8_Handler(void);
#endif
static void (*callbacks[NUM_TIMERS])();
struct Timer
{
Tc *tc;
uint32_t channel;
IRQn_Type irq;
};
// Store timer configuration (static, as it's fixed for every object)
static const Timer Timers[NUM_TIMERS];
public:
static DueTimer getAvailable(void);
DueTimer(unsigned short _timer);
DueTimer& attachInterrupt(void (*isr)());
DueTimer& detachInterrupt(void);
DueTimer& start(double microseconds = -1);
DueTimer& stop(void);
DueTimer& setFrequency(double frequency);
DueTimer& setPeriod(double microseconds);
double getFrequency(void) const;
double getPeriod(void) const;
inline __attribute__((always_inline)) bool operator== (const DueTimer& rhs) const
{return timer == rhs.timer; };
inline __attribute__((always_inline)) bool operator!= (const DueTimer& rhs) const
{return timer != rhs.timer; };
};
extern DueTimer Timer;
extern DueTimer Timer1;
extern DueTimer Timer0;
extern DueTimer Timer2;
#ifndef USING_IR_LIB
extern DueTimer Timer3;
#endif
extern DueTimer Timer4;
extern DueTimer Timer5;
#if NUM_TIMERS > 6
extern DueTimer Timer6;
extern DueTimer Timer7;
extern DueTimer Timer8;
#endif
#endif
#else
#error Oops! Trying to include DueTimer on another device?
#endif
|
NataliaD/SocketApp---RN
|
client.c
|
/*
* client.c
*
* Created on: 27.12.2014
* Author: <NAME>
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/socket.h>
#include <netdb.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <ctype.h>
#include <wctype.h>
#include <wchar.h>
#include <errno.h>
#define REQUETE 1
#define REPONSE 2
#define TEST_TEXTE 3
#define RESULTAT_TEST 4
#define ERREUR 5
#define TAILLE_TEXTE 684
#define TAILLE_CHILD 171
#define TAILLE_ID_CLIENT 44
#define TAILLE_RESULTAT 8 // Result can be "SUCCES !" or "ECHEC !!"
#define NUMERO_PORT_SERVEUR 42047 // Port number of server
#define SERVER_NAME "vega.info.univ-tours.fr" // "172.16.31.10" // Address of server
// Struct type for the inter-process message queue
typedef struct {
long mType; // always needed for a message queue! Must not be included in a msgsnd / msgrcv size parameter!
int childId;
char line[TAILLE_CHILD];
} message_t;
// Lock a semaphore with given ID
void sem1PO(int id_sem){
struct sembuf op;
op.sem_num=0;
op.sem_op=-1;
op.sem_flg=SEM_UNDO;
semop(id_sem,&op,1);
}
// Release a semaphore with given ID
void sem1VO(int id_sem){
struct sembuf op;
op.sem_num=0;
op.sem_op=1;
op.sem_flg=SEM_UNDO;
semop(id_sem,&op,1);
}
int *globalCounter;
int main()
{
// Initialze a string for the result (filled with zero) and a message struct for the message queue
char* resultString = calloc(TAILLE_TEXTE + 1, sizeof(char));
message_t msg;
msg.mType = 1; // The message queue message struct alyways has to have a long as first member with a value > 0!
// Message types as declared in the specification of the task
struct msg_requete {
char vide[TAILLE_TEXTE];
};
struct msg_reponse {
char lettre;
int position;
char vide[TAILLE_TEXTE];
};
struct msg_test_texte {
char texte[TAILLE_TEXTE];
};
struct msg_resultat {
char resultat[TAILLE_RESULTAT];
char vide[TAILLE_TEXTE - TAILLE_RESULTAT];
};
struct msg_erreur {
char texte[TAILLE_TEXTE];
};
struct msg_generic {
char id_client[TAILLE_ID_CLIENT];
int type_msg;
union corps_msg {
struct msg_requete requete;
struct msg_reponse reponse;
struct msg_test_texte test_texte;
struct msg_resultat resultat_test;
struct msg_erreur erreur;
} corps;
};
// one structure for the sent and one for the received message
struct msg_generic msg_send, msg_recv;
// prepare the request message for the child processes
bzero(msg_send.id_client, TAILLE_ID_CLIENT);
strncpy(msg_send.id_client, "NataliaDuske", 12);
msg_send.type_msg = REQUETE; // Set the message type of the request (REQUETE)
// Prepare a message queue for exchanging the result string elements
int idMsgQueue=msgget(IPC_PRIVATE,0660|IPC_CREAT);
printf("Message Queue %i initialized\n", idMsgQueue);
// Initialize a shared memory segment for the global counter
int idShMem;
struct shmid_ds nb_at;
key_t sync_key=ftok("/sync_key", 2);
nb_at.shm_nattch=10;
idShMem=shmget(sync_key,sizeof(int),IPC_CREAT|0777);
globalCounter = shmat(idShMem,NULL,0);
shmctl(idShMem,IPC_STAT,&nb_at);
// initialize a semaphore for shared memory access
int idSem;
idSem=semget(IPC_PRIVATE,1,0777);
semctl(idSem,0,SETVAL,1);
// Initialize shared memory value for the global counter with 0
sem1PO(idSem);
*globalCounter = 0;
sem1VO(idSem);
// Forking of processes:
// fork child processes only if none of the child process IDs is 0.
// process IDs are only 0 if the executing process itself is already a child process.
// By only forking further if no forked process ID is 0, child processes don't create
// "grand children". This way, there will be exactly one father process with four children.
int p1 = 0;
int p2 = 0;
int p3 = 0;
int p4 = 0;
p1 = fork();
if (p1 != 0) {
p2 = fork();
}
if (p1 != 0 && p2 != 0) {
p3 = fork();
}
if (p1 != 0 && p2 != 0 && p3 != 0) {
p4 = fork();
}
int process = 0; // 0 = father process
// 1 to 4 are the child processes, identified by how many child process have already
// been created before a fork() statement.
if (p1 == 0 && p2 == 0 && p3 == 0 && p4 == 0) {
process = 1; // first child: no process IDs of children known, so the current process
// has to be the first one created by fork().
} else if (p2 == 0 && p3 == 0 && p4 == 0) {
process = 2; // second child: the first child's process ID is already set, the others are not.
// this process must have been created by the seconds fork().
} else if (p3 == 0 && p4 == 0) {
process = 3;
} else if (p4 == 0) {
process = 4;
}
// Make a connection to the server
int client_socket; // client socket ID
struct sockaddr_in socketadr_server; // Socket address structure
socklen_t socket_server_size = sizeof(socketadr_server);
struct hostent *server_adress; // Structure for name resolution of an URL
if ( (server_adress = gethostbyname(SERVER_NAME)) == NULL){
printf("Unable to connect to server %s!\n", SERVER_NAME);
return 1;
}
// copy the resolved server address data to the socket address struct
bzero( (char *)&socketadr_server, sizeof(socketadr_server) );
bcopy( server_adress->h_addr, (char *)&socketadr_server.sin_addr, server_adress->h_length);
socketadr_server.sin_family = server_adress->h_addrtype;
socketadr_server.sin_port = htons(NUMERO_PORT_SERVEUR); // Use the UNSIGNED value!
client_socket = socket( AF_INET, SOCK_DGRAM, 0);
// Set timeout for the socket
struct timeval tv;
tv.tv_sec = 5; /* 30 Secs Timeout */
tv.tv_usec = 0; // Not init'ing this can cause strange errors
setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval));
// Child processes:
if(process != 0){ // only in child processes:
// Each child has to read its own segment of the result string:
int minPos = TAILLE_CHILD * (process -1);
int maxPos = minPos + TAILLE_CHILD - 1;
// Counters for the number of requests and the number of actually relevant reads
// (inside the substring for the current child process and not already known characters)
int counter = 0;
int triesCounter = 0;
// Loop until every needed character is sent from the server at least once.
while (counter < TAILLE_CHILD){
int sentRet = sendto(client_socket, &msg_send, sizeof(msg_send), 0, (struct sockaddr *)&socketadr_server, socket_server_size);
int recvRet = recvfrom(client_socket, &msg_recv, sizeof(msg_recv), 0, (struct sockaddr *)&socketadr_server, &socket_server_size);
if (sentRet < 0 || recvRet < 0) {
printf("Error on sending or receiving from child %i: \nSend returncode = %i, Receive returncode = %i,\n",
process, sentRet, recvRet);
} else if(msg_recv.type_msg == REPONSE) {
triesCounter++;
if(msg_recv.corps.reponse.position >= minPos
&& msg_recv.corps.reponse.position <= maxPos
&& resultString[msg_recv.corps.reponse.position] != msg_recv.corps.reponse.lettre ) {
// Copy the received character to its destination in the result string
resultString[msg_recv.corps.reponse.position]=msg_recv.corps.reponse.lettre;
// Increase the global counter while holding the semaphore for its shared memory
sem1PO(idSem);
(*globalCounter)++; //increment the global counter
sem1VO(idSem);
counter++; // increment the child processes' internal counter
} // if [new character]
// Give some feedback about the process, but not too much spam =)
if (triesCounter%50 == 0) {
printf("Child %d received %d characters from %d requests. Global counter is now %d.\n",
process,
counter,
triesCounter,
(*globalCounter));
}
}
} // end of "while (counter < TAILLE_CHILD)"
// Report end of this child process and put its substring to the
// message queue for the father process to merge it with the others.
printf("Child process %d has finished after %i requests!\n", process, triesCounter);
msg.childId = process;
msg.mType = process;
//sem1PO(idSem);
memcpy(msg.line, resultString + (process-1) * TAILLE_CHILD, TAILLE_CHILD);
int sendResult = msgsnd(idMsgQueue, &msg, TAILLE_CHILD * sizeof(char) + sizeof(int), 0);
//sem1VO(idSem);
printf("Child process %d sent message queue (result %i)!\n", process, sendResult);
}
else { // if process != 0
// This is the father process: It does nothing more than wait for its
// children to finish their work and afterwards combine the four substrings
// to the solution, which is then sent to the server.
// Wait for results...
int received[4] = {0, 0, 0, 0};
while(!received[0] || !received[1] || !received[2] || !received[3]) {
printf("Father waiting for message queue...\n");
int receiveResult = msgrcv(idMsgQueue,&msg,TAILLE_CHILD * sizeof(char) + sizeof(int),0,MSG_NOERROR);
if (msg.childId < 1 || msg.childId > 4) {
printf("Answer from invalid child process %i is ignored.\n", msg.childId);
} else {
printf("Father process received result part #%d:\n%s\n",
msg.childId, msg.line);
memcpy(resultString + (msg.childId - 1) * TAILLE_CHILD, msg.line, TAILLE_CHILD);
received[msg.childId - 1] = 1;
}
}
// Now the result is ready.
/*
int i = 0;
for (i = 0; i < TAILLE_TEXTE; i++) {
if (resultString[i] == 0) {
resultString[i] = ' ';
}
}
*/
printf("Result is ready:\n%s\n", resultString);
msg_send.type_msg = TEST_TEXTE;
memcpy(msg_send.corps.test_texte.texte, resultString, TAILLE_TEXTE);
int sentRet = sendto(client_socket, &msg_send, sizeof(msg_send), 0, (struct sockaddr *)&socketadr_server, socket_server_size);
int recvRet = recvfrom(client_socket, &msg_recv, sizeof(msg_recv), 0, (struct sockaddr *)&socketadr_server, &socket_server_size);
if (msg_recv.type_msg == RESULTAT_TEST) {
printf("Server returned test result \"%s\"!\n", msg_recv.corps.resultat_test.resultat);
} else {
printf("Server did not return test result...\n");
}
}
return 0;
} // main()
|
NataliaD/SocketApp---RN
|
socketApp.c
|
//Autoren: <NAME>
//<NAME>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <time.h>
#define SRV_PORT 7777
void client(int argc, char** argv);
void server(char** argv);
int receiveFile(char* fileName, int socket, int display);
int sendFile(char* fileName, int socket);
int createSocket(const char* dest, const char* type);
/**
* Entry point, here should be chosen how to start an application
* as server or client
*/
int main(int argc, char** argv) {
setbuf(stdout, NULL); // No Buffer for output, every printf is displayed directly
//Making a choice to start an application with:
// -S --> as Server
// -C --> as Client
if (argc != 3 || !(strcmp(argv[1], "-C") == 0 || strcmp(argv[1], "-S") == 0)) {
printf("First argument has to be -C for client or -S for Server! \"%s\"\n", argv[1]);
exit(1);
}
if (strcmp(argv[1], "-C") == 0) {
printf("Starting as client\n\n");
client(argc, argv);
} else {
printf("Starting as server\n\n");
server(argv);
}
return 0;
}
/**
* Create a socket for Target IP oder name dest
*/
int createSocket(const char* dest, const char* type){
int resSocket = -1;
char portStr[10]; // Buffer to hold the port Number as a string
// Address information variables
struct addrinfo *result, *rp, *sockAddr = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof hints); // empty struct memory
hints.ai_socktype = SOCK_STREAM; //TCP socket
hints.ai_family = AF_UNSPEC; //can use IPv4 or IPv6
char ipstr[INET6_ADDRSTRLEN];
printf("Resolving Server %s\n", dest);
// Copy the #define'd integer port number into a string
sprintf(portStr, "%d", SRV_PORT);
//fill the addrinfo structure for the socket connection
int status = getaddrinfo(dest, portStr, &hints, &result);
if (status != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(EXIT_FAILURE);
}//if(status)
// iterate over the addrinfo structs produced by getaddrinfo,
// to find a valid IPv4 address
for (rp = result; rp != NULL; rp = rp->ai_next) {
struct sockaddr* sa = (struct sockaddr*) rp->ai_addr;
// get the pointer to the address itself
if (rp->ai_family == AF_INET) { // IPv4
sockAddr = rp;
//convert IP address from binary to string
inet_ntop( rp->ai_family, (void*)&((struct sockaddr_in*)sa)->sin_addr, ipstr, sizeof(ipstr) );
break;
} else if (rp->ai_family == AF_INET6) {
sockAddr = rp;
//convert IP address from binary to string
inet_ntop( rp->ai_family, (void*)&((struct sockaddr_in6*)sa)->sin6_addr, ipstr, sizeof(ipstr) );
break;
}
printf("Address %s found\n", ipstr);
// Use any identified IPv4 address
}//for()
if (sockAddr == NULL) {
// If no address was found, sockAddr stays NULL => exit.
printf("No valid address found!\n");
exit(1);
} else {
//if address was found, use it and print it
printf("Using address %s\n", ipstr);
}
//create socket
if ((resSocket = socket(sockAddr->ai_family,
sockAddr->ai_socktype,
sockAddr->ai_protocol)) < 0) {
perror("TCP Socket");
exit(1);
}
printf("Socket created.\n");
printf("Inhalt von type: %s\n", type);
if (strcmp(type, "CLIENT") == 0) {
//try to connect with server
printf("Client Socket\n");
if (connect(resSocket, sockAddr->ai_addr, sockAddr->ai_addrlen) < 0) {
printf("\n");
perror("Connect");
exit(1);
}
} else if (strcmp(type, "SERVER") == 0) {
printf("Server Socket!\n");
// Try to setup the server socket
if (bind(resSocket, sockAddr->ai_addr, sockAddr->ai_addrlen) < 0) {
perror("bind");
exit(1);
}
if (listen(resSocket, 5) < 0) {
perror("listen");
close(resSocket);
exit(1);
}
}
// Free ressources of address lookup
freeaddrinfo(result);
return resSocket;
}
/**
* Create the client
*/
void client(int argc, char** argv) {
if (argc < 3) {
printf("Client mode requires an additional parameter! Usage:\n");
printf("%s -C [servername or address]\n", argv[0]);
exit(1);
}
int s_tcp; // socket descriptor
int doLoop = 1; // switch for terminating the command loop
// define and initialize a buffer for all string operations
char* buffer;
int bufferSize = 65535;
buffer = malloc(bufferSize * sizeof (char));
char cmd[256], cmdArg[256]; // Command used (get, put, quit) and argument for command
char* serverAddress = argv[2]; // argv is taken from main method
// create a socket for the connection to server serverAdress
s_tcp = createSocket(serverAddress, "CLIENT");
// PART TWO: Main client loop////
/////////////////////////////////
printf(" OK!\nPlease choose one of the following commands:\n");
printf("get [filename] read file from server\n", argv[3]);
printf("put [filename] write local file to server\n", argv[3]);
printf("quit close client application\n\n", argv[3]);
while (doLoop) {
//parse input from terminal
//there are 3 possibilities:
//GET, PUT and QUIT
memset(buffer, 0, bufferSize);//clear buffer
memset(cmd, 0, sizeof(cmd)); //clear command buffer
memset(cmdArg, 0, sizeof(cmdArg)); //clear command arguments buffer
//read the whole input until linefeed
fgets (buffer, bufferSize, stdin);
//split fgets() result into command and argument
sscanf(buffer, "%s %s", cmd, cmdArg);
//if input is QUIT, then just EXIT
if (strcmp(cmd, "quit") == 0) {
doLoop = 0;
//if input is GET
} else if (strcmp(cmd, "get") == 0) {
//buffer should be cleared again
memset(buffer, 0, bufferSize);
strcpy(buffer, "@SEND ");
strcat(buffer, cmdArg);
send(s_tcp, buffer, strlen(buffer), 0);
memset(buffer, 0, bufferSize);
// read the header info and print received caracters
recv(s_tcp, buffer, bufferSize, 0);
printf("%s", buffer);
// Send a simple "OK"
send(s_tcp, "OK", 4, 0);
// write and display the file
receiveFile(cmdArg, s_tcp, 0);
} else if (strcmp(cmd, "put") == 0) {
// Send an info, that a file is being sent
memset(buffer, 0, bufferSize);
strcpy(buffer, "@RECEIVE ");
strcat(buffer, cmdArg);
//send server information about the file to receive
send(s_tcp, buffer, strlen(buffer), 0);
// Wait for an answer from server
memset(buffer, 0, bufferSize);
recv(s_tcp, buffer, bufferSize, 0);
// Send file lines
sendFile(cmdArg, s_tcp);
// Wait for answer
memset(buffer, 0, bufferSize);
recv(s_tcp, buffer, bufferSize, 0);
printf("Completion Answer from Server: %s\n", buffer);
} else {
//if there were unknown input:
printf("Command %s unknown\n", cmd);
}
printf("\n");
}//while (doLoop)
printf("Closing connection.\n");
close(s_tcp);
}
/**
* Create server socket
*/
void server(char** argv) {
int s_tcp, s_client; // socket descriptors
struct sockaddr_in6 sa_client; // socket address structures
int sa_len = sizeof (struct sockaddr_in), n;
char* serverAddress = argv[2]; // argv is taken from main method
char* buffer; //buffer for all string operations
int bufferSize = 1024;
buffer = malloc(bufferSize * sizeof (char));
char fileName[256], hostName[64];
char ipstr[INET6_ADDRSTRLEN];
struct sockaddr_storage addrInfo;
socklen_t addrInfoLen = sizeof(addrInfo);
// create a socket for the server
s_tcp = createSocket(serverAddress, "SERVER");
///////////Main server loop///////////
//////////////////////////////////////
//main loop can be interrupted only by using "CTRL + C"
while (1) {
printf("> Waiting for TCP connections ... \n");
if ((s_client = accept(s_tcp, (struct sockaddr*) &sa_client, &sa_len)) < 0) {
perror("accept");
close(s_tcp);
exit(1);
}
printf("accepted\n");
n = 1;
getsockname(s_client, (struct sockaddr *)&addrInfo, &addrInfoLen);
//getpeername(sa_client, (struct sockaddr*)&addrInfo, &addrInfoLen);
//as long as client sends data, server receives and evaluates it
//if client sends 0 Bytes, the connection will be closed and the
//server will return to the main loop and wait for new connections
while (n > 0) {
memset(buffer, 0, bufferSize); // Prepare receive buffer with zeros
n = recv(s_client, buffer, bufferSize, 0);
if (n > 0) {
// interpretation of the received command, only two options:
// "@RECEIVE [filename]" means, the client will send a file
// named [filename]
// "@SEND [filename]" means, the client requests the contents
// of file [filename].
if (strncmp(buffer, "@RECEIVE", 8) == 0) {
strcpy(fileName, buffer+9);
// Tell client that the command is accepted
send(s_client, "OK", 3, 0);
// create the file
receiveFile(fileName, s_client, 1);
//convert client address from binary to string
//inet_ntop(sa_client.sin6_family, &(sa_client.sin6_addr), ipstr, sizeof(ipstr));
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addrInfo;
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof(ipstr));
memset(buffer, 0, bufferSize);
//write into buffer the result after receiving and send to client
//after that server is waiting for the next order
sprintf(buffer, "OK <%s>:<%d>", ipstr, ntohs(sa_client.sin6_port));
send(s_client, buffer, bufferSize, 0);
} else if (strncmp(buffer, "@SEND", 5) == 0) {
strcpy(fileName, buffer+6);
// Return message
// <Date + Time>
// <Serverhostname>
// <used Server-IP-Address>
// contents of <filename>
gethostname(hostName, sizeof(hostName)); //get pc name
//convert client address from binary to string
//inet_ntop(sa_client.sin6_family, &(sa_client.sin6_addr), ipstr, sizeof(ipstr));
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addrInfo;
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof(ipstr));
time_t tmpTime;
time(&tmpTime);
struct tm* curLocalTime = localtime(&tmpTime);
memset(buffer, 0, bufferSize);
sprintf(buffer, "<%02d.%02d.%d %02d:%02d:%02d>\n<%s>\n<%s>\n",
curLocalTime->tm_mday,
curLocalTime->tm_mon + 1,
curLocalTime->tm_year + 1900,
curLocalTime->tm_hour,
curLocalTime->tm_min,
curLocalTime->tm_sec,
hostName,
ipstr);
send(s_client, buffer, bufferSize, 0);//send Header
recv(s_client, buffer, bufferSize, 0);
// send the file
sendFile(fileName, s_client);
}//else if (@SEND)
}//if(n>0)
}//while(n>0)
}//while(1)
free(buffer);
close(s_tcp);
}//server ()
/**
* receive file from socket and store it locally
*/
int receiveFile(char* fileName, int socket, int display) {
char* buffer; //buffer for received data chars
int bufferSize = 65535;
buffer = malloc(bufferSize * sizeof (char));
int eof = 0;
FILE* inFile = NULL;
// Ask the other side, if the requested file was found
memset(buffer, 0, bufferSize);
recv(socket, buffer, bufferSize, 0);
if (strncmp(buffer, "@OK", 3) != 0) {
eof = 1; // don't start writing
if(display == 0){
printf("%s\n", buffer);
}
} else {
eof = 0;
// create the file or overwrite if already exists
inFile = fopen(fileName, "w+");
}
// Dummy answer
send(socket, "@OK", 4, 0);
// receive file lines
while(eof == 0) {
memset(buffer, 0, bufferSize);
//fill the buffer with data from socket
recv(socket, buffer, bufferSize, 0);
//write the data from buffer into outfile
fputs (buffer, inFile);
if(display == 0){
printf("%s", buffer);
}
// check if file is complete
//at the end of the filedata there is an appended string "@EOF" after "\0"
if (strcmp((buffer + strlen(buffer) + 1), "@EOF") == 0) {
//printf("File finished\n");
eof=1;
}
}//while(eof == 0)
free(buffer);
if (inFile != NULL) {
fclose(inFile);
}
return 0;
}
/**
* sends requested file
* if such file is absent, an error message is returned instead
*/
int sendFile(char* fileName, int socket) {
char* buffer; // Another local character buffer
int bufferSize = 65535;
buffer = malloc(bufferSize * sizeof (char));
int returnValue = 0;
FILE* outFile = fopen(fileName, "r");
//if the file isn't readable or doesn't exist
//send error-message and return error code
if (outFile == NULL) {
memset(buffer, 0, bufferSize);
//write to socket buffer
sprintf(buffer, "File \"%s\" not found.\n", fileName);
printf("%s", buffer);
// Tell the other side, if the requested file was found
send(socket, "File not Found!", 16, 0);
recv(socket, buffer, bufferSize, 0);
returnValue = 1;
} else {
// Tell the other side, if the requested file was found
send(socket, "@OK", 4, 0);
recv(socket, buffer, bufferSize, 0);
// Send file lines
while (!feof(outFile)) {
memset(buffer, 0, bufferSize);
//read from file line by line and send it
fgets (buffer, bufferSize, outFile);
send(socket, buffer, strlen(buffer), 0);
}
memset(buffer, 0, bufferSize);
//to mark the end of the file append extra "@EOF" after "\0"
strcpy(buffer+1 , "@EOF");
send(socket, buffer, 5, 0);
}
free(buffer);
return returnValue;
}
|
303774813/FFCategoryKit
|
FFCategoryKit/Classes/yuanma.h
|
//
// yuanma.h
// yuanma
//
// Created by yiche on 2019/4/8.
// Copyright © 2019 yiche. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface yuanma : NSObject
- (void)sayhi;
@end
|
303774813/FFCategoryKit
|
Example/FFCategoryKit/FFViewController.h
|
<filename>Example/FFCategoryKit/FFViewController.h<gh_stars>0
//
// FFViewController.h
// FFCategoryKit
//
// Created by 303774813 on 04/09/2019.
// Copyright (c) 2019 303774813. All rights reserved.
//
@import UIKit;
@interface FFViewController : UIViewController
@end
|
noldeni/arduino-spectrum-analyzer
|
RPi_LED_Matrix_code/Dot_test/Dot_test.c
|
<reponame>noldeni/arduino-spectrum-analyzer<filename>RPi_LED_Matrix_code/Dot_test/Dot_test.c
// blink.c
//
// Example program for bcm2835 library
// Blinks a pin on an off every 0.5 secs
//
// After installing bcm2835, you can build this
// with something like:
// make or gcc -o led led.c -lbcm2835
// sudo ./led
/*
define from bcm2835.h define from Board DVK511
3.3V | | 5V -> 3.3V | | 5V
RPI_V2_GPIO_P1_03 | | 5V -> SDA | | 5V
RPI_V2_GPIO_P1_05 | | GND -> SCL | | GND
RPI_GPIO_P1_07 | | RPI_GPIO_P1_08 -> IO7 | | TX
GND | | RPI_GPIO_P1_10 -> GND | | RX
RPI_GPIO_P1_11 | | RPI_GPIO_P1_12 -> IO0 | | IO1
RPI_V2_GPIO_P1_13 | | GND -> IO2 | | GND
RPI_GPIO_P1_15 | | RPI_GPIO_P1_16 -> IO3 | | IO4
VCC | | RPI_GPIO_P1_18 -> VCC | | IO5
RPI_GPIO_P1_19 | | GND -> MOSI | | GND
RPI_GPIO_P1_21 | | RPI_GPIO_P1_22 -> MISO | | IO6
RPI_GPIO_P1_23 | | RPI_GPIO_P1_24 -> SCK | | CE0
GND | | RPI_GPIO_P1_26 -> GND | | CE1
::if your raspberry Pi is version 1 or rev 1 or rev A
RPI_V2_GPIO_P1_03->RPI_GPIO_P1_03
RPI_V2_GPIO_P1_05->RPI_GPIO_P1_05
RPI_V2_GPIO_P1_13->RPI_GPIO_P1_13:
*/
#include <bcm2835.h>
#include <stdio.h>
#define uchar unsigned char
#define uint unsigned int
//#define Max7219_pinCLK RPI_GPIO_P1_11
#define Max7219_pinCS RPI_GPIO_P1_24
//#define Max7219_pinDIN RPI_V2_GPIO_P1_13
uchar disp1[38][8] = {
{0x3C,0x42,0x42,0x42,0x42,0x42,0x42,0x3C},//0
{0x10,0x30,0x50,0x10,0x10,0x10,0x10,0x7C},//1
{0x3E,0x02,0x02,0x3E,0x20,0x20,0x3E,0x00},//2
{0x00,0x7C,0x04,0x04,0x7C,0x04,0x04,0x7C},//3
{0x08,0x18,0x28,0x48,0xFE,0x08,0x08,0x08},//4
{0x3C,0x20,0x20,0x3C,0x04,0x04,0x3C,0x00},//5
{0x3C,0x20,0x20,0x3C,0x24,0x24,0x3C,0x00},//6
{0x3E,0x22,0x04,0x08,0x08,0x08,0x08,0x08},//7
{0x00,0x3E,0x22,0x22,0x3E,0x22,0x22,0x3E},//8
{0x3E,0x22,0x22,0x3E,0x02,0x02,0x02,0x3E},//9
{0x08,0x14,0x22,0x3E,0x22,0x22,0x22,0x22},//A
{0x3C,0x22,0x22,0x3E,0x22,0x22,0x3C,0x00},//B
{0x3C,0x40,0x40,0x40,0x40,0x40,0x3C,0x00},//C
{0x7C,0x42,0x42,0x42,0x42,0x42,0x7C,0x00},//D
{0x7C,0x40,0x40,0x7C,0x40,0x40,0x40,0x7C},//E
{0x7C,0x40,0x40,0x7C,0x40,0x40,0x40,0x40},//F
{0x3C,0x40,0x40,0x40,0x40,0x44,0x44,0x3C},//G
{0x44,0x44,0x44,0x7C,0x44,0x44,0x44,0x44},//H
{0x7C,0x10,0x10,0x10,0x10,0x10,0x10,0x7C},//I
{0x3C,0x08,0x08,0x08,0x08,0x08,0x48,0x30},//J
{0x00,0x24,0x28,0x30,0x20,0x30,0x28,0x24},//K
{0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x7C},//L
{0x81,0xC3,0xA5,0x99,0x81,0x81,0x81,0x81},//M
{0x00,0x42,0x62,0x52,0x4A,0x46,0x42,0x00},//N
{0x3C,0x42,0x42,0x42,0x42,0x42,0x42,0x3C},//O
{0x3C,0x22,0x22,0x22,0x3C,0x20,0x20,0x20},//P
{0x1C,0x22,0x22,0x22,0x22,0x26,0x22,0x1D},//Q
{0x3C,0x22,0x22,0x22,0x3C,0x24,0x22,0x21},//R
{0x00,0x1E,0x20,0x20,0x3E,0x02,0x02,0x3C},//S
{0x00,0x3E,0x08,0x08,0x08,0x08,0x08,0x08},//T
{0x42,0x42,0x42,0x42,0x42,0x42,0x22,0x1C},//U
{0x42,0x42,0x42,0x42,0x42,0x42,0x24,0x18},//V
{0x00,0x49,0x49,0x49,0x49,0x2A,0x1C,0x00},//W
{0x00,0x41,0x22,0x14,0x08,0x14,0x22,0x41},//X
{0x41,0x22,0x14,0x08,0x08,0x08,0x08,0x08},//Y
{0x00,0x7F,0x02,0x04,0x08,0x10,0x20,0x7F},//Z
{0x08,0x7F,0x49,0x49,0x7F,0x08,0x08,0x08},//中
{0xFE,0xBA,0x92,0xBA,0x92,0x9A,0xBA,0xFE},//国
};
void Delay_xms(uint x)
{
bcm2835_delay(x);
}
//------------------------
void Write_Max7219_byte(uchar DATA)
{
uchar i ;
bcm2835_gpio_write(Max7219_pinCS,LOW);
/* for(i = 8; i >= 1; i--)
{
bcm2835_gpio_write(Max7219_pinCLK,LOW);
bcm2835_gpio_write( Max7219_pinDIN, (DATA & 0x80));
DATA = DATA << 1;
bcm2835_gpio_write(Max7219_pinCLK,HIGH);
}
*/
bcm2835_spi_transfer(DATA);
}
void Write_Max7219(uchar address1,uchar dat1,uchar address2,uchar dat2)
//void Write_Max7219(uchar address,uchar dat)
{
bcm2835_gpio_write(Max7219_pinCS,LOW);
Write_Max7219_byte(address1);
Write_Max7219_byte(dat1);
Write_Max7219_byte(address2);
Write_Max7219_byte(dat2);
//_nop_();
//Write_Max7219_byte(address);
//Write_Max7219_byte(dat);
bcm2835_gpio_write(Max7219_pinCS,HIGH);
}
void Init_MAX7219(void)
{
Write_Max7219(0x09,0x00,0x09,0x00);
Write_Max7219(0x0a,0x03,0x0a,0x03);
Write_Max7219(0x0b,0x07,0x0b,0x07);
Write_Max7219(0x0c,0x01,0x0c,0x01);
Write_Max7219(0x0f,0x00,0x0f,0x00);
}
/*void Init_MAX7219(void)
{
Write_Max7219(0x09,0x00);
Write_Max7219(0x0a,0x03);
Write_Max7219(0x0b,0x07);
Write_Max7219(0x0c,0x01);
Write_Max7219(0x0f,0x00);
}
*/
void main(void)
{
uchar i , j;
if (!bcm2835_init())
return 1;
bcm2835_spi_begin();
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST); // The default
bcm2835_spi_setDataMode(BCM2835_SPI_MODE0); // The default
bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_256); // The default
bcm2835_gpio_fsel(Max7219_pinCS, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(disp1[j][i],HIGH);
Delay_xms(50);
Init_MAX7219();
while(1)
{
for(j = 0;j <37; j++)
{
for(i = 1;i < 9;i++)
Write_Max7219(i , disp1[j+1][i-1],i,disp1[j][i-1]);
Delay_xms(1000);
}
}
bcm2835_spi_end();
bcm2835_close();
return 0;
}
|
noldeni/arduino-spectrum-analyzer
|
bcm2835-1.50/examples/spi/spi.c
|
// spi.c
//
// Example program for bcm2835 library
// Shows how to interface with SPI to transfer a byte to and from an SPI device
//
// After installing bcm2835, you can build this
// with something like:
// gcc -o spi spi.c -l bcm2835
// sudo ./spi
//
// Or you can test it before installing with:
// gcc -o spi -I ../../src ../../src/bcm2835.c spi.c
// sudo ./spi
//
// Author: <NAME>
// Copyright (C) 2012 <NAME>
// $Id: RF22.h,v 1.21 2012/05/30 01:51:25 mikem Exp $
#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
// If you call this, it will not actually access the GPIO
// Use for testing
// bcm2835_set_debug(1);
if (!bcm2835_init())
{
printf("bcm2835_init failed. Are you running as root??\n");
return 1;
}
if (!bcm2835_spi_begin())
{
printf("bcm2835_spi_begin failedg. Are you running as root??\n");
return 1;
}
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST); // The default
bcm2835_spi_setDataMode(BCM2835_SPI_MODE0); // The default
bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536); // The default
bcm2835_spi_chipSelect(BCM2835_SPI_CS0); // The default
bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW); // the default
// Send a byte to the slave and simultaneously read a byte back from the slave
// If you tie MISO to MOSI, you should read back what was sent
uint8_t send_data = 0x23;
uint8_t read_data = bcm2835_spi_transfer(send_data);
printf("Sent to SPI: 0x%02X. Read back from SPI: 0x%02X.\n", send_data, read_data);
if (send_data != read_data)
printf("Do you have the loopback from MOSI to MISO connected?\n");
bcm2835_spi_end();
bcm2835_close();
return 0;
}
|
ShenYj/JSProgressHud
|
JSProgressHUD/JSProgressHUD/JSProgressHUD/JSLoadIngView.h
|
//
// JSLoadIngView.h
// JSProgressHUD
//
// Created by ShenYj on 2017/5/27.
// Copyright © 2017年 Auko. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface JSLoadIngView : UIView
/** 文本提示 */
@property (nonatomic,strong) UILabel *contentLabel;
@end
|
ShenYj/JSProgressHud
|
JSProgressHUD/JSProgressHUD/JSProgressHUD/JSProgressHUD.h
|
//
// JSProgressHUD.h
// JSProgressHUD
//
// Created by ShenYj on 2017/5/26.
// Copyright © 2017年 Auko. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
static NSString * const kJSProgressHUDRequest = @"正在请求...";
static NSString * const kJSProgressHUDSuccess = @"请求完成...";
static NSString * const kJSProgressHUDNoMore = @"没有更多数据了...";
static NSString * const kJSProgressHUDFail = @"您的网络不给力!";
@interface JSProgressHUD : MBProgressHUD
/*!
* @metohd sharedProgressHUD:
*
* @discussion 单例
*/
+ (instancetype)sharedProgressHUD;
/*!
* @metohd js_showHUDTo: animated:
*
* @param view 将要添加到的视图
* @param animated 是否有动画效果
*
* @discussion 显示遮罩视图
*/
- (void)js_showHUDTo:(UIView *)view animated:(BOOL)animated;
/*!
* @property noticeString
*
* @discussion 文本提示内容
*/
@property (nonatomic,copy) NSString *noticeString;
@end
|
ShenYj/JSProgressHud
|
JSProgressHUD/JSProgressHUD/ViewController.h
|
//
// ViewController.h
// JSProgressHUD
//
// Created by ShenYj on 2017/5/26.
// Copyright © 2017年 Auko. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
ShenYj/JSProgressHud
|
JSProgressHUD/JSProgressHUD/Extension/UIColor+JSExtension.h
|
<reponame>ShenYj/JSProgressHud
//
// UIColor+JSExtension.h
// TableView联动
//
// Created by ShenYj on 16/8/18.
// Copyright © 2016年 ___ShenYJ___. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIColor (JSExtension)
/**
* 设置RGB颜色
*
* @param red red: 0 ~ 255
* @param green green: 0 ~ 255
* @param blue blue: 0 ~ 255
*
* @return RGB颜色
*/
+ (UIColor *)js_RGBColorWithRed:(CGFloat)red withGreen:(CGFloat)green withBlue:(CGFloat)blue;
/*!
* @metohd grayColor:
*
* @param number 0~255的数值,设置需要的灰度值
*
* @discussion 设置指定灰度颜色
*/
+ (UIColor *)js_GrayColor:(CGFloat)number;
/**
* 生成随机色
*
* @return 返回随机色
*/
+ (UIColor *)js_randomColor;
/**
* 根据无符号的 32 位整数转换成对应的 RGB 颜色
*
* @param hex hex
*
* @return UIColor
*/
+ (instancetype)js_colorWithHex:(u_int32_t)hex;
@end
|
nuin/freebayes
|
src/ResultData.h
|
<reponame>nuin/freebayes
#ifndef __RESULT_DATA_H
#define __RESULT_DATA_H
#include <vector>
#include <ostream>
#include <iomanip>
#include "Genotype.h"
#include "Allele.h"
#include "Utility.h"
#include "AlleleParser.h"
#include "Variant.h"
#include "version_git.h"
#include "Result.h"
using namespace std;
// for sorting data likelihoods
class DataLikelihoodCompare {
public:
bool operator()(const pair<Genotype*, long double>& a,
const pair<Genotype*, long double>& b) {
return a.second > b.second;
}
};
// maps sample names to results
class Results : public map<string, Result> {
public:
void update(SampleDataLikelihoods& likelihoods) {
for (SampleDataLikelihoods::iterator s = likelihoods.begin(); s != likelihoods.end(); ++s) {
vector<SampleDataLikelihood>& sdls = *s;
string& name = sdls.front().name;
Result& result = (*this)[name];
result.clear();
for (vector<SampleDataLikelihood>::iterator s = sdls.begin(); s != sdls.end(); ++s) {
result.push_back(*s);
}
}
}
vcf::Variant& vcf(
vcf::Variant& var, // variant to update
BigFloat pHom,
long double bestComboOddsRatio,
//long double alleleSamplingProb,
Samples& samples,
string refbase,
vector<Allele>& altAlleles,
map<string, int> repeats,
int genotypingIterations,
vector<string>& sampleNames,
int coverage,
GenotypeCombo& genotypeCombo,
map<string, vector<Allele*> >& alleleGroups,
map<string, vector<Allele*> >& partialObservationGroups,
map<Allele*, set<Allele*> >& partialSupport,
map<int, vector<Genotype> >& genotypesByPloidy,
vector<string>& sequencingTechnologies,
AlleleParser* parser);
};
string dateStr(void);
void vcfHeader(ostream& out, string referenceFileName, vector<string>& samples, Parameters& parameters, vector<string>& sequencingTechnologies);
#endif
|
nuin/freebayes
|
src/DataLikelihood.h
|
<filename>src/DataLikelihood.h
#ifndef __DATALIKELIHOOD_H
#define __DATALIKELIHOOD_H
#include <iostream>
#include <vector>
#include <utility> // pair
#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>
#include <cmath>
#include "Allele.h"
#include "Sample.h"
#include "Genotype.h"
#include "Utility.h"
#include "Multinomial.h"
#include "Dirichlet.h"
#include "Bias.h"
#include "Contamination.h"
using namespace std;
long double
probObservedAllelesGivenGenotype(
Sample& sample,
Genotype& genotype,
double dependenceFactor,
bool useMapQ,
Bias& observationBias,
bool standardGLs,
vector<Allele>& genotypeAlleles,
Contamination& contaminations,
map<string, double>& freqs);
vector<pair<Genotype*, long double> >
probObservedAllelesGivenGenotypes(
Sample& sample,
vector<Genotype*>& genotypes,
double dependenceFactor,
bool useMapQ,
Bias& observationBias,
bool standardGLs,
vector<Allele>& genotypeAlleles,
Contamination& contaminations,
map<string, double>& freqs);
#endif
|
wzhhh123/Vk
|
Moss/src/Moss/Moss.h
|
<reponame>wzhhh123/Vk
#pragma once
// for use by moss applications
#include "Application.h"
#include "Log.h"
#include "EntryPoint.h"
|
wzhhh123/Vk
|
Moss/src/Moss/Core.h
|
#pragma once
#ifdef MOSS_PLATFORM_WINDOWS
#ifdef MOSS_BUILD_DLL
#define MOSS_API __declspec(dllexport)
#else
#define MOSS_API __declspec(dllimport)
#endif
#else
#error Moss only support Windows!
#endif
|
wzhhh123/Vk
|
Moss/src/Moss/Log.h
|
<filename>Moss/src/Moss/Log.h<gh_stars>0
#pragma once
#include <memory.h>
#include "Core.h"
#include "spdlog/spdlog.h"
namespace Moss {
class MOSS_API Log
{
public:
static void Init();
inline static std::shared_ptr<spdlog::logger>&GetCoreLogger() { return s_CoreLogger; }
inline static std::shared_ptr<spdlog::logger>&GetClientLogger() { return s_ClientLogger; }
private:
static std::shared_ptr<spdlog::logger> s_ClientLogger;
static std::shared_ptr<spdlog::logger> s_CoreLogger;
};
}
//Core log macros
#define MS_CORE_ERROR(...) ::Moss::Log::GetCoreLogger()->error(__VA_ARGS__)
#define MS_CORE_WARN(...) ::Moss::Log::GetCoreLogger()->warn(__VA_ARGS__)
#define MS_CORE_INFO(...) ::Moss::Log::GetCoreLogger()->info(__VA_ARGS__)
#define MS_CORE_TRACE(...) ::Moss::Log::GetCoreLogger()->trace(__VA_ARGS__)
#define MS_CORE_FATAL(...) ::Moss::Log::GetCoreLogger()->fatal(__VA_ARGS__)
//Client log macros
#define MS_CLIENT_ERROR(...) ::Moss::Log::GetClientLogger()->error(__VA_ARGS__)
#define MS_CLIENT_WARN(...) ::Moss::Log::GetClientLogger()->warn(__VA_ARGS__)
#define MS_CLIENT_INFO(...) ::Moss::Log::GetClientLogger()->info(__VA_ARGS__)
#define MS_CLIENT_TRACE(...) ::Moss::Log::GetClientLogger()->trace(__VA_ARGS__)
#define MS_CLIENT_FATAL(...) ::Moss::Log::GetClientLogger()->fatal(__VA_ARGS__)
|
leticiamp/LPI
|
include/automovel.h
|
#ifndef AUTOMOVEL_H
#define AUTOMOVEL_H
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
class Automovel {
private:
std::string m_marca;
float m_preco;
std::string m_chassi;
long int m_dataFabricacao;
std::string m_modelo;
public:
Automovel(); //Construtor padrão
Automovel(std::string marca_, float preco_, std::string chassi_,
long int dataFabricacao_, std::string modelo_); //Construtor parametrizado
~Automovel(); //Destrutor
//Getters e Setters
std::string getMarca();
void setMarca(std::string marca_);
float getPreco();
void setPreco(float preco_);
std::string getChassi();
void setChassi(std::string chassi_);
long int getDataFabricacao();
void setDataFabricacao(long int dataFabricacao_);
std::string getModelo();
void setModelo(std::string modelo_);
friend std::ostream& operator<< (std::ostream &o, Automovel const a); //Sobrecarga do operador de inserção
};
#endif
|
leticiamp/LPI
|
include/propriedade.h
|
<gh_stars>1-10
#ifndef PROPRIEDADE_H
#define PROPRIEDADE_H
template <class T>
class Propriedade {
private:
T m_primeiroNome;
T m_segundoNome;
public:
Propriedade(T primeiroNome_, T segundoNome_); //Construtor parametrizado
~Propriedade(); //Destrutor
T getPrimeiroNome();
void setPrimeiroNome(T primeiroNome_);
T getSegundoNome();
void setSegundoNome(T segundoNome_);
};
template <class T>
Propriedade<T>::Propriedade(T primeiroNome_, T segundoNome_) {
m_primeiroNome = primeiroNome_;
m_segundoNome = segundoNome_;
}
template <class T>
Propriedade<T>::~Propriedade() {}
template <class T>
T Propriedade<T>::getPrimeiroNome() {
return m_primeiroNome;
}
template <class T>
void Propriedade<T>::setPrimeiroNome(T primeiroNome_) {
m_primeiroNome = primeiroNome_;
}
template <class T>
T Propriedade<T>::getSegundoNome() {
return m_segundoNome;
}
template <class T>
void Propriedade<T>::setSegundoNome(T segundoNome_) {
m_segundoNome = segundoNome_;
}
#endif
|
leticiamp/LPI
|
include/system.h
|
#ifndef SYSTEM_H
#define SYSTEM_H
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <streambuf>
#include "automovel.h"
#include "concessionaria.h"
class System {
private:
std::vector<Concessionaria> v_lojas; //Vetor de concessionarias
public:
System(); //Construtor padrão
~System(); //Destrutor
std::vector<Concessionaria> getV_lojas();
void setV_carros(Concessionaria lojas_);
void newconc(); //criar consessionaria
void newcar(Concessionaria &C); //criar carro
void media(); //Calcula a média dos carros por concessionária
char menuInicial();
char menuConcessionaria();
char menuAutomovel();
void listarConcessionaria(); //Lista o proprietário, a frota total de cada tipo de veículo e o valor total dos veículos
void escreveConcessionaria(std::string nome); //Escreve informações de uma concessionaria em um arquivo .txt
Concessionaria lerConcessionaria(const std::string& arq); //Lê informações de uma concessionaria em um arquivo .txt
};
#endif
|
leticiamp/LPI
|
include/carro.h
|
#ifndef CARRO_H
#define CARRO_H
#include "automovel.h"
enum Tipo_motor {
GASOLINA,
ELETRICO
};
class Carro : public Automovel {
private:
Tipo_motor m_tipo_motor;
public:
Carro();
Carro(Tipo_motor tipo_motor_);
~Carro();
Tipo_motor getTipo_motor();
void setTipo_motor(Tipo_motor tipo_motor_);
};
#endif
|
leticiamp/LPI
|
include/moto.h
|
<filename>include/moto.h
#ifndef MOTO_H
#define MOTO_H
#include "automovel.h"
enum Model {
CLASSICO,
ESPORTIVO
};
class Moto : public Automovel {
private:
Model m_model;
public:
Moto();
Moto(Model model);
~Moto();
Model getModel();
void setModel(Model model);
};
#endif
|
leticiamp/LPI
|
include/concessionaria.h
|
<gh_stars>1-10
#ifndef CONCESSIONARIA_H
#define CONCESSIONARIA_H
#include "automovel.h"
#include "data.h"
#include "propriedade.h"
class Concessionaria {
private:
std::string m_nome;
int m_cnpj;
int m_estoque;
std::string m_proprietario;
//Propriedade<T> m_propriedade;
std::vector<Automovel> v_carros; //Vetor de carros
std::vector<std::string> v_chassis; //Vetor de chassis
public:
Concessionaria(); //Construtor padrão
Concessionaria(std::string nome, int cnpj, int estoque, std::string proprietario_); //Construtor parametrizado
~Concessionaria(); //Destrutor
//Getters e Setters
std::string getNome();
void setNome(std::string nome_);
int getCnpj();
void setCnpj(int cnpj_);
int getEstoque();
void setEstoque(int estoque_);
std::string getProprietario();
void setProprietario(std::string proprietario_);
std::vector<Automovel> getV_carros();
void setV_carros(Automovel carro_);
std::vector<std::string> getV_chassis();
void setV_chassis(std::string chassi_);
void aumentarValor(float porcentagem); //Aumento de x% no preço dos carros
void buscarChassi(std::string chassi_); //Função que encontra veículo pelo chassi
float valorTotal(); //Função que calcula o valor de todos os veículos de uma concessionária
};
#endif
|
leticiamp/LPI
|
include/caminhao.h
|
<filename>include/caminhao.h<gh_stars>1-10
#ifndef CAMINHAO_H
#define CAMINHAO_H
#include "automovel.h"
enum Tipo_carga {
COMUM,
PERIGOSA
};
class Caminhao : public Automovel {
private:
Tipo_carga m_tipo_carga;
public:
Caminhao();
Caminhao(Tipo_carga tipo_carga_);
~Caminhao();
Tipo_carga getTipo_carga();
void setTipo_carga(Tipo_carga tipo_carga_);
};
#endif
|
aidan-clyens/Arduino_Data_Structures
|
Vector/src/Vector.h
|
/***********************************************************/
/* Vector
/*
/* A dynamically resizable vector data structure.
/* To be used with Arduino, so this uses no C++ standard
/* library functions.
/*
/* <NAME>
/* May 29, 2018
/***********************************************************/
#ifndef VECTOR_H
#define VECTOR_H
#ifdef ARDUINO_H
#include "Arduino.h"
#else
#include <iostream>
#endif
template <typename Type>
class vector {
public:
vector( int = 16 );
~vector();
// Size
int size() const;
int capacity() const;
bool empty() const;
// Element Access
Type &at( int ) const;
Type &operator[]( int ) const;
Type &front() const;
Type &back() const;
// Modifiers
void push_back( const Type & );
void pop_back();
// Misc.
void print();
private:
void double_capacity();
void half_capacity();
int vector_size;
int vector_capacity;
Type *array;
};
/***************************************
* Constructors
****************************************/
/*
* Default Vector Constructor
*/
template <typename Type>
vector<Type>::vector(int n):
vector_capacity( n ),
vector_size( 0 ),
array( new Type[n] )
{
// Empty
}
/*
* Vector Destructor
*/
template <typename Type>
vector<Type>::~vector() {
delete[] array;
}
/***************************************
* Public Size Functions
****************************************/
/* size
* Returns the size of the vector.
*/
template <typename Type>
int vector<Type>::size() const {
return vector_size;
}
/* capacity
* Returns the current capacity of the vector.
*/
template <typename Type>
int vector<Type>::capacity() const {
return vector_capacity;
}
/* empty
* Returns whether the vector is empty or not.
*/
template <typename Type>
bool vector<Type>::empty() const {
return (vector_size == 0);
}
/***************************************
* Public Element Access Functions
****************************************/
/* at
* Returns the value at the specified index.
*/
template <typename Type>
Type &vector<Type>::at(int i) const {
if (i >= vector_size) {
// TODO: Throw OutOfRange exception
}
return array[i];
}
/* operator[]
* Returns the value at the specifed index, the same as the at() function.
*/
template <typename Type>
Type &vector<Type>::operator[](int i) const {
if (i >= vector_size) {
// TDOD: Throw OutOfRange exception
}
return array[i];
}
/* front
* Return the element at the back of the vector.
*/
template <typename Type>
Type &vector<Type>::front() const {
return array[0];
}
/* back
* Return the element at the back of the vector.
*/
template <typename Type>
Type &vector<Type>::back() const {
return array[vector_size - 1];
}
/***************************************
* Public Modifier Functions
****************************************/
/* push_back
* Push a new element to the back of the vector.
*/
template <typename Type>
void vector<Type>::push_back(const Type &obj) {
if (vector_size == vector_capacity) double_capacity(); // Resize
array[vector_size] = obj;
++vector_size;
}
/* pop_back
* Remove the back element from the vector.
*/
template <typename Type>
void vector<Type>::pop_back() {
if (empty()) return;
if (vector_size <= vector_capacity / 4 && vector_capacity > 16) half_capacity();
--vector_size;
}
/***************************************
* Misc. Functions
****************************************/
/* print_vector
* Print the vector contents.
*/
template <typename Type>
void vector<Type>::print() {
for (int i = 0; i < size(); ++i) {
#ifdef ARDUINO_H
Serial.print(at(i));
Serial.print(" ");
#else
std::cout << at(i) << " ";
#endif
}
#ifdef ARDUINO_H
Serial.println();
#else
std::cout << std::endl;
#endif
}
/***************************************
* Private Functions
****************************************/
/* double_capacity
* Double the capacity of the array used for the vector.
*/
template <typename Type>
void vector<Type>::double_capacity() {
int new_capacity = 2 * vector_capacity;
Type *temp = array;
array = new Type[new_capacity];
for (int i = 0; i < vector_size; ++i) {
array[i] = temp[i];
}
vector_capacity = new_capacity;
delete[] temp;
}
/* half_capacity
* Half the capacity of the array used for the vector.
*/
template <typename Type>
void vector<Type>::half_capacity() {
int new_capacity = vector_capacity / 2;
Type *temp = array;
array = new Type[new_capacity];
for (int i = 0; i < vector_size; ++i) {
array[i] = temp[i];
}
vector_capacity = new_capacity;
delete[] temp;
}
#endif
|
aidan-clyens/Arduino_Data_Structures
|
SearchTree/src/SearchTree.h
|
<reponame>aidan-clyens/Arduino_Data_Structures
/***********************************************************/
/* Search Tree
/*
/* <NAME>
/* August 20, 2018
/***********************************************************/
#ifndef SEARCH_TREE_H
#define SEARCH_TREE_H
#ifdef ARDUINO_H
#include "Arduino.h"
#else
#include <iostream>
#endif
template <typename Type>
class SearchTree {
public:
class SearchNode {
public:
SearchNode( Type const & );
// Size
int height() const;
// Element Access
SearchNode *find( Type const & );
// Modifers
bool insert( Type const & );
bool erase( Type const &, SearchNode *& );
void clear();
// Misc.
bool is_leaf() const;
int max( int, int ) const;
void print( int = 0 );
bool is_search_tree();
Type node_value;
SearchNode* left_tree;
SearchNode* right_tree;
int tree_height;
};
SearchTree();
~SearchTree();
// Size
bool empty() const;
int size() const;
int height() const;
// Element Access
Type top();
SearchNode *find( Type const & );
// Modifiers
bool insert( Type const & );
bool erase( Type const & );
void clear();
// Misc.
void print();
bool is_search_tree();
private:
SearchNode* root_node;
int tree_size;
};
/***********************************************/
/*************** SearchTree ***************/
/***********************************************/
/***************************************
* Constructors
****************************************/
/*
* Search Tree Constructor
*/
template <typename Type>
SearchTree<Type>::SearchTree():
root_node( nullptr ),
tree_size( 0 )
{
// Empty Constructor
}
/*
* Search Tree Destructor
*/
template <typename Type>
SearchTree<Type>::~SearchTree() {
clear();
}
/***************************************
* Public Size Functions
****************************************/
/*
* empty
*/
template <typename Type>
bool SearchTree<Type>::empty() const {
return (tree_size == 0);
}
/*
* size
*/
template <typename Type>
int SearchTree<Type>::size() const {
return tree_size;
}
/*
* height
*/
template <typename Type>
int SearchTree<Type>::height() const {
if (root_node == nullptr) return -1;
else return root_node->height();
}
/***************************************
* Public Element Access Functions
****************************************/
template <typename Type>
Type SearchTree<Type>::top() {
if (root_node != nullptr) return root_node->node_value;
}
/*
* find
*/
template <typename Type>
typename SearchTree<Type>::SearchNode *SearchTree<Type>::find(Type const &obj) {
if (empty()) return nullptr;
return root_node->find(obj);
}
/***************************************
* Public Modifier Functions
****************************************/
/*
* insert
*/
template <typename Type>
bool SearchTree<Type>::insert(Type const &obj) {
if (empty()) {
root_node = new SearchTree::SearchNode(obj);
tree_size = 1;
return true;
} else if (root_node->insert(obj)) {
++tree_size;
return true;
} else {
return false;
}
}
/*
* erase
*/
template <typename Type>
bool SearchTree<Type>::erase(Type const &obj) {
if (empty()) return false;
if (root_node->erase(obj, root_node)) {
--tree_size;
return true;
}
}
/*
* clear
*/
template <typename Type>
void SearchTree<Type>::clear() {
if (root_node != nullptr) root_node->clear();
}
/***************************************
* Public Misc. Functions
****************************************/
/*
* print
*/
template <typename Type>
void SearchTree<Type>::print() {
root_node->print(6*height());
}
template <typename Type>
bool SearchTree<Type>::is_search_tree() {
if (root_node != nullptr) root_node->is_search_tree();
else return true;
}
/***********************************************/
/*************** SearchNode ***************/
/***********************************************/
/***************************************
* Constructors
****************************************/
/*
* SearchNode Constructor
*/
template <typename Type>
SearchTree<Type>::SearchNode::SearchNode(Type const &obj):
node_value( obj ),
left_tree( nullptr ),
right_tree( nullptr ),
tree_height( 0 )
{
// Empty Constructor
}
/***************************************
* Public Size Functions
****************************************/
/*
* height
*/
template <typename Type>
int SearchTree<Type>::SearchNode::height() const {
return (this == nullptr) ? -1 : tree_height;
}
/***************************************
* Element Access Functions
****************************************/
/*
* find
*/
template <typename Type>
typename SearchTree<Type>::SearchNode *SearchTree<Type>::SearchNode::find(Type const &obj) {
if (obj == node_value) {
return this;
} else if (obj < node_value) {
if (left_tree != nullptr) {
return left_tree->find(obj);
} else {
return nullptr;
}
} else if (obj > node_value) {
if (right_tree != nullptr) {
return right_tree->find(obj);
} else {
return nullptr;
}
}
}
/***************************************
* Public Modifier Functions
****************************************/
/*
* insert
*/
template <typename Type>
bool SearchTree<Type>::SearchNode::insert(Type const &obj) {
// If the new object is less than the current value, attempt to insert into the left tree
if (obj < node_value) {
// If there is no left tree, create a new node
if (left_tree == nullptr) {
left_tree = new SearchTree::SearchNode(obj);
tree_height = max(left_tree->height(), right_tree->height()) + 1;
return true;
// If there is a left tree, attempt to insert into it
} else {
if (left_tree->insert(obj)) {
tree_height = max(left_tree->height(), right_tree->height()) + 1;
return true;
// If the new object could not be inserted into the left tree, return false
} else {
return false;
}
}
// If the new object is greater than the current value, attempt to insert into the right tree
} else if (obj > node_value) {
// If there is no right tree, create a new node
if (right_tree == nullptr) {
right_tree = new SearchTree::SearchNode(obj);
tree_height = max(left_tree->height(), right_tree->height()) + 1;
return true;
// If there is a right tree, attempt to insert into it
} else if (right_tree->insert(obj)) {
tree_height = max(left_tree->height(), right_tree->height()) + 1;
return true;
// If the new object could not be inserted into the right tree, return false
} else {
return false;
}
// If the object is equal to the current value, do nothing and return false
} else {
return false;
}
}
/*
* erase
*/
template <typename Type>
bool SearchTree<Type>::SearchNode::erase(Type const &obj, SearchNode *&to_this) {
if (obj < node_value) {
if (left_tree != nullptr) {
if (left_tree->erase(obj, left_tree)) {
tree_height = max(left_tree->height(), right_tree->height()) + 1;
return true;
} else {
return false;
}
}
} else if (obj > node_value) {
if (right_tree != nullptr) {
if (right_tree->erase(obj, right_tree)) {
tree_height = max(left_tree->height(), right_tree->height()) + 1;
return true;
} else {
return false;
}
}
} else {
if (is_leaf()) {
to_this = nullptr;
delete this;
} else if (left_tree == nullptr) {
to_this = right_tree;
delete this;
} else if (right_tree == nullptr) {
to_this = left_tree;
delete this;
} else {
node_value = right_tree->node_value;
right_tree->erase(node_value, right_tree);
tree_height = max(left_tree->height(), right_tree->height()) + 1;
}
return this;
}
}
/*
* clear
*/
template <typename Type>
void SearchTree<Type>::SearchNode::clear() {
if (left_tree != nullptr) left_tree->clear();
if (right_tree != nullptr) right_tree->clear();
delete this;
}
/***************************************
* Public Misc. Functions
****************************************/
/*
* is_leaf
*/
template <typename Type>
bool SearchTree<Type>::SearchNode::is_leaf() const {
return (left_tree == nullptr && right_tree == nullptr);
}
/*
* print
*/
template <typename Type>
void SearchTree<Type>::SearchNode::print(int indent) {
if (this != nullptr) {
if (indent) {
for (int i = 0; i < indent; ++i) {
#ifdef ARDUINO_H
Serial.print(" ");
#else
std::cout << " ";
#endif
}
}
#ifdef ARDUINO_H
Serial.println(node_value);
#else
std::cout << node_value << std::endl;
#endif
if (left_tree != nullptr) left_tree->print(indent-5);
if (right_tree != nullptr) right_tree->print(indent+5);
}
}
/*
* max
*/
template <typename Type>
int SearchTree<Type>::SearchNode::max(int lhs, int rhs) const {
return (lhs > rhs) ? lhs : rhs;
}
template <typename Type>
bool SearchTree<Type>::SearchNode::is_search_tree() {
if (left_tree != nullptr) {
if (left_tree->node_value > node_value) return false;
}
if (right_tree != nullptr) {
if (right_tree->node_value < node_value) return false;
}
return true;
}
#endif
|
aidan-clyens/Arduino_Data_Structures
|
HashTable/src/HashTable.h
|
<reponame>aidan-clyens/Arduino_Data_Structures<filename>HashTable/src/HashTable.h
/***********************************************************/
/* Hash Table
/*
/* A hash table that uses quadratic probing.
/* To be used with Arduino, so this uses no C++ standard
/* library functions.
/*
/* <NAME>
/* July 18, 2018
/***********************************************************/
#ifndef HASH_TABLE_H
#define HASH_TABLE_H
#ifdef ARDUINO_H
#include "Arduino.h"
#else
#include <iostream>
#endif
enum bin_state_t { UNOCCUPIED, OCCUPIED, ERASED };
template <typename Type>
class HashTable {
public:
HashTable( int = 5 );
~HashTable();
// Size
int size() const;
int capacity() const;
bool empty() const;
// Element Access
Type at( int ) const;
bool member( Type const & ) const;
// Modifiers
void insert( Type const & );
bool erase( Type const &);
void clear();
// Misc.
double load_factor() const;
void print();
private:
int hash( Type const & ) const;
int power;
int table_size;
int erased_count;
int array_capacity;
Type *array;
bin_state_t *occupied;
};
/***************************************
* Constructors
****************************************/
/*
* Default Hash Table Constructor
*/
template <typename Type>
HashTable<Type>::HashTable(int n):
power( n ),
table_size( 0 ),
erased_count( 0 ),
array_capacity( 1 << power ),
array( new Type[array_capacity] ),
occupied( new bin_state_t[array_capacity] )
{
// Initialize all bin of the hash table as UNOCCUPIED
for (int i = 0; i < array_capacity; ++i) {
occupied[i] = UNOCCUPIED;
}
}
/*
* Hash Table Destructor
*/
template <typename Type>
HashTable<Type>::~HashTable() {
delete[] array;
delete[] occupied;
}
/***************************************
* Public Size Functions
****************************************/
/*
* size
*/
template <typename Type>
int HashTable<Type>::size() const {
return table_size;
}
/*
* capacity
*/
template <typename Type>
int HashTable<Type>::capacity() const {
return array_capacity;
}
/*
* empty
*/
template <typename Type>
bool HashTable<Type>::empty() const {
return (table_size == 0);
}
/***************************************
* Public Element Access Functions
****************************************/
/*
* at
*/
template <typename Type>
Type HashTable<Type>::at(int n) const {
return array[n];
}
/*
* member
*/
template <typename Type>
bool HashTable<Type>::member(Type const &obj) const {
// Create the hash value of the object to use as the starting index
int index = hash(obj);
for (int i = 0; i < array_capacity; ++i) {
// Use quadratic probing to search the hash table
index = (index + i) % array_capacity;
// Return true if the object if found
if (occupied[index] == OCCUPIED && array[index] == obj) {
return true;
}
}
return false;
}
/***************************************
* Public Modifier Functions
****************************************/
/*
* insert
*/
template <typename Type>
void HashTable<Type>::insert(Type const &obj) {
// Return if hash table is full
if (table_size == array_capacity) return;
// Return if the object is already in the hash table
if (member(obj)) return;
// Create the hash value of the object to use as the starting index
int index = hash(obj);
int i = 0;
while (occupied[index] == OCCUPIED) {
// Use quadratic probing to search for an UNOCCUPIED or ERASED bin
index = (index + i) % array_capacity;
++i;
}
// Insert the object into the first empty bin and mark it as occupied
array[index] = obj;
occupied[index] = OCCUPIED;
++table_size;
}
/*
* erase
*/
template <typename Type>
bool HashTable<Type>::erase(Type const &obj) {
// Create the hash value of the object to use as the starting index
int index = hash(obj);
// Use quadratic probing to iterate through the hash table
for (int i = 0; i < array_capacity; ++i) {
index = (index + i) % array_capacity;
// If the current bin is OCCUPIED and equals the object, mark it as ERASED
if (occupied[index] == OCCUPIED && array[index] == obj) {
occupied[index] = ERASED;
--table_size;
++erased_count;
return true;
}
}
return false;
}
/*
* clear
*/
template <typename Type>
void HashTable<Type>::clear() {
// Iterate through the table and mark all bins as UNOCCUPIED
for (int i = 0; i < array_capacity; ++i) {
occupied[i] = UNOCCUPIED;
table_size = 0;
erased_count = 0;
}
}
/***************************************
* Misc. Functions
****************************************/
/*
* load_factor
*/
template <typename Type>
double HashTable<Type>::load_factor() const {
return (static_cast<double>(table_size) + static_cast<double>(erased_count)) / static_cast<double>(array_capacity);
}
/*
* print
*/
template <typename Type>
void HashTable<Type>::print() {
for (int i = 0; i < array_capacity; ++i) {
if (occupied[i] == UNOCCUPIED) {
#ifdef ARDUINO_H
Serial.print("U");
#else
std::cout << "U";
#endif
}
else if (occupied[i] == ERASED) {
#ifdef ARDUINO_H
Serial.print("E");
#else
std::cout << "E";
#endif
}
else if (occupied[i] == OCCUPIED) {
#ifdef ARDUINO_H
Serial.print(array[i]);
#else
std::cout << array[i];
#endif
}
#ifdef ARDUINO_H
Serial.print(" ");
#else
std::cout << " ";
#endif
}
#ifdef ARDUINO_H
Serial.println();
#else
std::cout << std::endl;
#endif
}
/***************************************
* Private Functions
****************************************/
/*
* hash
*/
template <typename Type>
int HashTable<Type>::hash(Type const &obj) const {
int n = static_cast<int>(obj);
int hash = n % array_capacity;
return (hash >= 0) ? hash : hash + array_capacity;
}
#endif
|
aidan-clyens/Arduino_Data_Structures
|
MaxHeap/src/MaxHeap.h
|
/***********************************************************/
/* Max Heap
/*
/* To be used with Arduino, so this uses no C++ standard
/* library functions.
/*
/* <NAME>
/* May 31, 2018
/***********************************************************/
#ifndef MAX_HEAP_H
#define MAX_HEAP_H
#ifdef ARDUINO_H
#include "Arduino.h"
#else
#include <iostream>
#endif
#include "../include/Vector.h"
template <typename Type>
class MaxHeap {
public:
MaxHeap( int = 16 );
~MaxHeap();
// Size
int size() const;
bool empty() const;
// Element Access
Type top() const;
// Modifers
void push( const Type & );
void pop();
// Misc.
void print();
bool is_max_heap( int );
private:
void swap( Type &, Type &);
void percolate_up( int );
void percolate_down( int );
vector<Type> heap;
};
/***************************************
* Constructors
****************************************/
/*
* Default Heap Constructor
*/
template <typename Type>
MaxHeap<Type>::MaxHeap(int n) {
vector<Type> heap(n);
}
/*
* Heap Destructor
*/
template <typename Type>
MaxHeap<Type>::~MaxHeap() {
// Empty
}
/***************************************
* Public Size Functions
****************************************/
/* size
* Returns the size of the heap.
*/
template <typename Type>
int MaxHeap<Type>::size() const {
return heap.size();
}
/* empty
* Returns whether the heap is empty or not.
*/
template <typename Type>
bool MaxHeap<Type>::empty() const {
return (size() == 0);
}
/***************************************
* Public Element Access Functions
****************************************/
/* top
* Return the element at the top of the heap.
*/
template <typename Type>
Type MaxHeap<Type>::top() const {
return heap.front();
}
/***************************************
* Public Modifier Functions
****************************************/
/* push
* Push an element to the bottom of the heap and percolate it up.
*/
template <typename Type>
void MaxHeap<Type>::push(const Type &obj) {
heap.push_back(obj);
percolate_up(size() - 1);
}
/* pop
* Pop an element from the top of the heap and percolate new top down
* if necessary.
*/
template <typename Type>
void MaxHeap<Type>::pop() {
heap.front() = heap.back();
heap.pop_back();
percolate_down(0);
}
/***************************************
* Misc. Functions
****************************************/
/* print_heap
* Print the heap contents.
*/
template <typename Type>
void MaxHeap<Type>::print() {
heap.print();
}
/* is_max_heap
* Returns whether or not the container is a correct max heap.
*/
template <typename Type>
bool MaxHeap<Type>::is_max_heap(int n) {
int left = 2*n + 1;
int right = 2*n + 2;
bool is_heap = true;
// If the current node has a right child, check that it is less than the current node
if (right < size()) {
if (heap[right] <= heap[n] && is_max_heap(right)) is_heap = true;
else return false;
}
// If the current node has a left child, check that is is less than the current node
if (left < size()) {
if (heap[left] <= heap[n] && is_max_heap(left)) is_heap = true;
else return false;
}
return is_heap;
}
/***************************************
* Private Functions
****************************************/
/* swap
* Swap two elements.
*/
template <typename Type>
void MaxHeap<Type>::swap(Type &a, Type &b) {
Type temp = a;
a = b;
b = temp;
}
/* percolate_up
* When pushing to the heap, move the new element up if the
* parent is less than the new element.
*/
template <typename Type>
void MaxHeap<Type>::percolate_up(int n) {
int parent = (n - 1) / 2;
// If the parent of the current node is less than the current node,
// swap and check the parent recursively
if (heap[parent] < heap[n]) {
swap(heap[parent], heap[n]);
percolate_up(parent);
}
}
/* percolate_down
* When popping the top element of the heap, check the children of
* the new top to make sure they are less than the new top.
*/
template <typename Type>
void MaxHeap<Type>::percolate_down(int n) {
int left = 2*n + 1;
int right = 2*n + 2;
int max;
// The current node has no children, so return
if (left > size() - 1) return;
// If the current node has two children, compare both
if (right < size()) {
max = (heap[left] > heap[right]) ? left : right;
} else {
max = left;
}
// If the maximum of the node's children is greater than the current node,
// swap and check the subtree recursively
if (heap[n] < heap[max]) {
swap(heap[n], heap[max]);
percolate_down(max);
}
}
#endif
|
aidan-clyens/Arduino_Data_Structures
|
QueueList/include/LinkedList.h
|
/***********************************************************/
/* Doubly Linked List
/*
/* Uses sentinel nodes at the head and tail of the linked
/* list.
/* To be used with Arduino, so this uses no C++ standard
/* library functions.
/*
/* <NAME>
/* May 9, 2018
/***********************************************************/
#ifndef LINKED_LIST_ARDUINO_H
#define LINKED_LIST_ARDUINO_H
#ifdef ARDUINO_H
#include "Arduino.h"
#else
#include <iostream>
#endif
template <typename Type>
class LinkedList {
public:
class Node {
public:
Node( Type const & = Type(), Node * = nullptr, Node * = nullptr );
// Element Access
Type value() const;
Node* next() const;
Node* previous() const;
Type node_value;
Node *next_node;
Node *previous_node;
};
LinkedList();
LinkedList( LinkedList const & );
~LinkedList();
// Size
int size() const;
bool empty() const;
// Element Access
Type front() const;
Type back() const;
Node* begin() const;
Node* end() const;
Node* rbegin() const;
Node* rend() const;
Node* find() const;
// Modifiers
void push_front( Type const & );
void push_back( Type const & );
void pop_front();
void pop_back();
void clear();
// Misc.
void print();
private:
int list_size;
Node *list_head;
Node *list_tail;
};
/***********************************************/
/*************** LinkedList ***************/
/***********************************************/
/***************************************
* Constructors
****************************************/
/*
* Linked List Default Constructor
*/
template <typename Type>
LinkedList<Type>::LinkedList():
list_head( new Node() ),
list_tail( new Node() ),
list_size( 0 )
{
list_head->next_node = list_tail;
list_tail->previous_node = list_head;
}
/*
* Linked List Copy Constructor
*/
template <typename Type>
LinkedList<Type>::LinkedList(LinkedList<Type> const &list):
list_head( new Node() ),
list_tail( new Node() ),
list_size( 0 )
{
list_head->next_node = list_tail;
list_tail->previous_node = list_head;
for (Node *ptr = list.begin(); ptr != list.end(); ptr = ptr->next()) {
push_back(ptr->value());
}
}
/*
* Linked List Destructor
*/
template <typename Type>
LinkedList<Type>::~LinkedList() {
clear();
delete list_head;
delete list_tail;
}
/***************************************
Public Size Functions
****************************************/
/*
* size
* Returns the linked list size
*/
template <typename Type>
int LinkedList<Type>::size() const {
return list_size;
}
/*
* empty
* Returns a boolean value stating if the linked list is empty
*/
template <typename Type>
bool LinkedList<Type>::empty() const {
return (list_size == 0);
}
/***************************************
* Public Element Access Functions
****************************************/
/*
* front
* Returns the element at the front of the linked list
*/
template <typename Type>
Type LinkedList<Type>::front() const {
return (!empty()) ? begin()->value() : Type();
}
/*
* back
* Returns the element at the end of the linked list
*/
template <typename Type>
Type LinkedList<Type>::back() const {
return (!empty()) ? rbegin()->value() : Type();
}
/*
* begin
* Returns the address of the first node in the linked list
*/
template <typename Type>
typename LinkedList<Type>::Node *LinkedList<Type>::begin() const {
return list_head->next();
}
/*
* end
* Returns the address of the tail sentinel node of the linked list_tail
*/
template <typename Type>
typename LinkedList<Type>::Node *LinkedList<Type>::end() const {
return list_tail;
}
/*
* rbegin
* Returns the address of the last node in the linked list
*/
template <typename Type>
typename LinkedList<Type>::Node *LinkedList<Type>::rbegin() const {
return list_tail->previous();
}
/*
* rend
* Returns the address of the head sentinel node of the linked list_tail
*/
template <typename Type>
typename LinkedList<Type>::Node *LinkedList<Type>::rend() const {
return list_head;
}
/***************************************
* Public Modifier Functions
****************************************/
/*
* push_front
* Pushs a new object to the front of the linked list
*/
template <typename Type>
void LinkedList<Type>::push_front(Type const &obj) {
// Store current first node in the list and create a new empty node
Node *temp = begin();
Node *node = new Node(obj, temp, list_head);
// Reassign pointers at the head of the list
list_head->next_node = node;
temp->previous_node = node;
++list_size;
}
/*
* push_back
* Pushs a new object to the back of the linked list
*/
template <typename Type>
void LinkedList<Type>::push_back(Type const &obj) {
// Store the current last node in the list and create a new empty node
Node *temp = rbegin();
Node *node = new Node(obj, list_tail, temp);
// Reassign pointers at the tail of the list
list_tail->previous_node = node;
temp->next_node = node;
++list_size;
}
/*
* pop_front
* Pops the object from the front of the linked list
*/
template <typename Type>
void LinkedList<Type>::pop_front() {
if (empty()) return;
Node *temp = begin();
temp->next()->previous_node = list_head;
list_head->next_node = temp->next();
delete temp;
--list_size;
}
/*
* pop_back
* Pops the object from the back of the linked list
*/
template <typename Type>
void LinkedList<Type>::pop_back() {
if (empty()) return;
Node *temp = rbegin();
temp->previous()->next_node = list_tail;
list_tail->previous_node = temp->previous();
delete temp;
--list_size;
}
/*
* clear
* Deletes all of the elements in the linked list
*/
template <typename Type>
void LinkedList<Type>::clear() {
while (!empty()) pop_front();
}
/***************************************
* Public Misc. Functions
****************************************/
/*
* print
* Prints the list using Arduino serial communication
*/
template <typename Type>
void LinkedList<Type>::print() {
#ifdef ARDUINO_H
Serial.print("head -> ");
#else
std::cout << "head -> ";
#endif
for (typename LinkedList<Type>::Node *ptr = begin(); ptr != end(); ptr = ptr->next()) {
#ifdef ARDUINO_H
Serial.print(ptr->value());
Serial.print(" -> ");
#else
std::cout << ptr->value() << " -> ";
#endif
}
#ifdef ARDUINO_H
Serial.println("tail");
#else
std::cout << "tail" << std::endl;
#endif
}
/***********************************************/
/*************** Node ***************/
/***********************************************/
/***************************************
* Constructors
****************************************/
/*
* Default Node Constructor
*/
template <typename Type>
LinkedList<Type>::Node::Node(Type const &obj, typename LinkedList<Type>::Node *next, typename LinkedList<Type>::Node *previous):
node_value( obj ),
next_node( next ),
previous_node( previous )
{
// Empty
}
/***************************************
* Element Access Functions
****************************************/
/*
* value
* Returns the node value
*/
template <typename Type>
Type LinkedList<Type>::Node::value() const {
return node_value;
}
/*
* next
* Returns the address of the next node to the current node
*/
template <typename Type>
typename LinkedList<Type>::Node *LinkedList<Type>::Node::next() const {
return next_node;
}
/*
* previous
* Returns the address of the previous node to the current node
*/
template <typename Type>
typename LinkedList<Type>::Node *LinkedList<Type>::Node::previous() const {
return previous_node;
}
#endif
|
aidan-clyens/Arduino_Data_Structures
|
QueueList/src/QueueList.h
|
/***********************************************************/
/* QueueList
/*
/* This is an implementation used a custom Linked List
/* class.
/* To be used with Arduino, so this uses no C++ standard
/* library functions.
/*
/* <NAME>
/* May 17, 2018
/***********************************************************/
#ifndef QUEUE_LIST_ARDUINO_H
#define QUEUE_LIST_ARDUINO_H
#ifdef ARDUINO_H
#include "Arduino.h"
#endif
#include "../include/LinkedList.h"
template <typename Type>
class QueueList {
public:
QueueList();
QueueList( QueueList const & );
~QueueList();
// Accessor Functions
int size() const;
bool empty() const;
Type front() const;
Type back() const;
// Mutator Functions
void push( Type const & );
void pop();
void clear();
void print();
private:
LinkedList<Type> queue;
};
/*************************************/
/********** Queue **********/
/*************************************/
// Default QueueList Constructor
template <typename Type>
QueueList<Type>::QueueList() {
// Empty Constructor
}
// QueueList Copy Constructor
template <typename Type>
QueueList<Type>::QueueList(QueueList<Type> const ©) {
queue = copy.queue;
}
// QueueList Destructor
template <typename Type>
QueueList<Type>::~QueueList() {
queue.clear();
}
/****** QueueList Accessor Functions ******/
// Return the size of the queue
template <typename Type>
int QueueList<Type>::size() const {
return queue.size();
}
// Returns a boolean value stating if the queue is empty
template <typename Type>
bool QueueList<Type>::empty() const {
return queue.empty();
}
// Return the element at the front of the queue
template <typename Type>
Type QueueList<Type>::front() const {
return queue.front();
}
// Return the element at the back of the queue
template <typename Type>
Type QueueList<Type>::back() const {
return queue.back();
}
/****** QueueList Mutator Functions ******/
// Push a new element to the back of the queue
template <typename Type>
void QueueList<Type>::push(Type const &obj) {
queue.push_back(obj);
}
// Pop the element at the front of the list
template <typename Type>
void QueueList<Type>::pop() {
queue.pop_front();
}
// Clears all the elements in the queue
template <typename Type>
void QueueList<Type>::clear() {
queue.clear();
}
// Print the queue on the Arduino serial monitor
template <typename Type>
void QueueList<Type>::print() {
queue.print();
}
#endif
|
aidan-clyens/Arduino_Data_Structures
|
QueueArray/src/QueueArray.h
|
/***********************************************************/
/* QueueArray
/*
/* This is an implementation using arrays. Currently, there
/* is no dynamic array resizing.
/* To be used with Arduino, so this uses no C++ standard
/* library functions.
/*
/* <NAME>
/* May 23, 2018
/***********************************************************/
#ifndef QUEUE_ARRAY_H
#define QUEUE_ARRAY_H
#ifdef ARDUINO_H
#include "Arduino.h"
#else
#include <iostream>
#endif
template <typename Type>
class QueueArray {
public:
QueueArray( int = 16 );
~QueueArray();
// Size
int size() const;
bool empty() const;
// Element Access
Type front() const;
Type back() const;
// Modifiers
void push( Type const & );
void pop();
void clear();
// Misc.
void print();
private:
Type* queue;
int queue_size;
int queue_capacity;
int front_index;
int back_index;
};
/***************************************
* Constructors
****************************************/
/*
* Default QueueArray Constructor
*/
template <typename Type>
QueueArray<Type>::QueueArray(int n):
queue_capacity( n ),
queue_size( 0 ),
queue( new Type[n] ),
front_index( 0 ),
back_index( -1 )
{
// Empty Constructor
}
/*
* QueueArray Destructor
*/
template <typename Type>
QueueArray<Type>::~QueueArray() {
delete[] queue;
}
/***************************************
* Public Size Functions
****************************************/
/*
* size
* Return the size of the queue
*/
template <typename Type>
int QueueArray<Type>::size() const {
return queue_size;
}
/*
* empty
* Returns a boolean value stating if the queue is empty
*/
template <typename Type>
bool QueueArray<Type>::empty() const {
return (queue_size == 0);
}
/***************************************
* Public Element Access Functions
****************************************/
/*
* front
* Return the element at the front of the queue
*/
template <typename Type>
Type QueueArray<Type>::front() const {
return queue[front_index];
}
/*
* back
* Return the element at the back of the queue
*/
template <typename Type>
Type QueueArray<Type>::back() const {
return queue[back_index];
}
/***************************************
* Public Modifier Functions
****************************************/
/*
* push
* Push a new element to the back of the queue
*/
template <typename Type>
void QueueArray<Type>::push(Type const &obj) {
if (queue_size == queue_capacity) return;
// Move back index forwards, accounting for array wraparound
back_index = ++back_index % queue_capacity;
queue[back_index] = obj;
++queue_size;
}
/*
* pop
* Pop the element at the front of the list
*/
template <typename Type>
void QueueArray<Type>::pop() {
if (empty()) return;
// Move front index forwards, accounting for array wraparound
front_index = ++front_index % queue_capacity;
--queue_size;
}
/*
* clear
* Clears all the elements in the queue
*/
template <typename Type>
void QueueArray<Type>::clear() {
delete[] queue;
queue = new Type[queue_capacity];
queue_size = 0;
front_index = 0;
back_index = -1;
}
/***************************************
* Public Misc. Functions
****************************************/
/*
* print
* Print the queue on the Arduino serial monitor
*/
template <typename Type>
void QueueArray<Type>::print() {
if (empty()) return;
int i = front_index;
while (i != back_index) {
#ifdef ARDUINO_H
Serial.print(queue[i]);
Serial.print(" ");
#else
std::cout << queue[i] << " ";
#endif
i = ++i % queue_capacity;
}
#ifdef ARDUINO_H
Serial.println(queue[back_index]);
#else
std::cout << queue[back_index] << std::endl;
#endif
}
#endif
|
airbit/ArduinoMQTT
|
src/PubSubClient.h
|
/*
PubSubClient.h - A simple client for MQTT.
<NAME>
http://knolleary.net
*/
#ifndef PubSubClient_h
#define PubSubClient_h
#include <Arduino.h>
#include <Stream.h>
#include <WiFi.h>
#include <IPAddress.h>
#include "MQTT.h"
#define MQTTPROTOCOLVERSION 3
#define MQTTCONNECT 1 << 4 // Client request to connect to Server
#define MQTTCONNACK 2 << 4 // Connect Acknowledgment
#define MQTTPUBLISH 3 << 4 // Publish message
#define MQTTPUBACK 4 << 4 // Publish Acknowledgment
#define MQTTPUBREC 5 << 4 // Publish Received (assured delivery part 1)
#define MQTTPUBREL 6 << 4 // Publish Release (assured delivery part 2)
#define MQTTPUBCOMP 7 << 4 // Publish Complete (assured delivery part 3)
#define MQTTSUBSCRIBE 8 << 4 // Client Subscribe request
#define MQTTSUBACK 9 << 4 // Subscribe Acknowledgment
#define MQTTUNSUBSCRIBE 10 << 4 // Client Unsubscribe request
#define MQTTUNSUBACK 11 << 4 // Unsubscribe Acknowledgment
#define MQTTPINGREQ 12 << 4 // PING Request
#define MQTTPINGRESP 13 << 4 // PING Response
#define MQTTDISCONNECT 14 << 4 // Client is Disconnecting
#define MQTTReserved 15 << 4 // Reserved
#define MQTTQOS0 (0 << 1)
#define MQTTQOS1 (1 << 1)
#define MQTTQOS2 (2 << 1)
struct mqtt_packet_t {
uint8_t header;
uint8_t *data;
size_t length;
size_t total;
};
class PubSubClient {
public:
typedef void(*callback_t)(const MQTT::Publish &, void *);
private:
IPAddress server_ip;
String server_hostname;
uint16_t server_port;
bool _ssl;
String username, password;
callback_t _callback;
void *_callback_data;
Stream *_stream;
WiFiClient _client;
uint8_t buffer[MQTT_MAX_PACKET_SIZE];
uint16_t keepalive = MQTT_KEEPALIVE;
uint8_t _max_retries;
uint16_t nextMsgId;
unsigned long lastOutActivity;
unsigned long lastInActivity;
bool pingOutstanding;
size_t send(uint8_t c);
size_t send(const uint8_t *buf, size_t len);
bool send(MQTT::Message &message);
bool sendReliably(MQTT::Message &message);
mqtt_packet_t readPacket();
MQTT::Message *readMessage();
uint8_t readByte();
bool write(uint8_t header, uint8_t *buf, uint16_t length);
uint16_t writeString(String string, uint8_t *buf, uint16_t pos);
// Wait for a certain type of packet to come back, optionally check its packet id
bool wait_for(uint8_t wait_type, uint16_t wait_pid = 0);
bool processMessage(MQTT::Message *msg, uint8_t match_type = 0, uint16_t match_pid = 0);
public:
PubSubClient();
PubSubClient(IPAddress &ip, uint16_t port = 1883, bool ssl = false);
PubSubClient(String hostname, uint16_t port = 1883, bool ssl = false);
PubSubClient &set_server(IPAddress &ip, uint16_t port = 1883, bool ssl = false);
PubSubClient &set_server(String hostname, uint16_t port = 1883, bool ssl = false);
PubSubClient &unset_server(void);
PubSubClient &set_auth(String u, String p);
PubSubClient &unset_auth(void);
callback_t callback(void) const { return _callback; }
PubSubClient &set_callback(callback_t cb, void *data = NULL);
PubSubClient &unset_callback(void);
// Set the maximum number of retries when waiting for response packets
PubSubClient &set_max_retries(uint8_t mr) {
_max_retries = mr;
return *this;
}
Stream *stream(void) const { return _stream; }
PubSubClient &set_stream(Stream &s);
PubSubClient &unset_stream(void);
bool connect(String id);
bool connect(String id, String willTopic, uint8_t willQos, bool willRetain, String willMessage);
void disconnect(void);
bool publish(String topic, String payload);
bool publish(String topic, const uint8_t *payload, unsigned int plength, bool retained = false);
bool publish_P(String topic, const uint8_t PROGMEM *payload, unsigned int, bool retained = false);
bool subscribe(String topic, uint8_t qos = 0);
bool unsubscribe(String topic);
bool loop();
bool connected();
bool publish(MQTT::Publish &pub);
// Return the next packet id
// Needed for constructing our own publish (with QoS>0) or (un)subscribe messages
uint16_t next_packet_id(void) {
nextMsgId++;
if (nextMsgId == 0) nextMsgId = 1;
return nextMsgId;
}
};
#endif
|
airbit/ArduinoMQTT
|
examples/mqtt_subscriber/.creds.h
|
<gh_stars>0
// creds.h template
#ifndef CREDS_H
#define CREDS_H
const char *ssid = "xxxxxxxx"; // cannot be longer than 32 characters!
const char *pass = "<PASSWORD>"; //
#endif //CREDS_H
|
airbit/ArduinoMQTT
|
ArduinoMQTT.h
|
//
// Created by 陶源 on 15/6/17.
//
#ifndef ARDUINO_MQTT_H
#define ARDUINO_MQTT_H
#include "src/MQTT.h"
#include "src/PubSubClient.h"
#endif //ARDUINO_MQTT_H
|
airbit/ArduinoMQTT
|
src/MQTT.h
|
//
// Created by 陶源 on 15/6/18.
//
#ifndef MQTT_H
#define MQTT_H
#include <Arduino.h>
#include <stdint.h>
#include <stddef.h>
#include <WString.h>
#include <Client.h>
// MQTT_MAX_PACKET_SIZE : Maximum packet size
#ifdef __CC3200R1M1RGC__
#define MQTT_MAX_PACKET_SIZE 1024
#else
#define MQTT_MAX_PACKET_SIZE 128
#endif
#define MQTT_MAX_PAYLOAD_SIZE 896
#define MQTT_SEND_BLOCK_SIZE 64
// MQTT_KEEPALIVE : keepAlive interval in Seconds
#define MQTT_KEEPALIVE 15
#define MQTT_CONNECT 1 // Client request to connect to Server
#define MQTT_CONNACK 2 // Connect Acknowledgment
#define MQTT_PUBLISH 3 // Publish message
#define MQTT_PUBACK 4 // Publish Acknowledgment
#define MQTT_PUBREC 5 // Publish Received (assured delivery part 1)
#define MQTT_PUBREL 6 // Publish Release (assured delivery part 2)
#define MQTT_PUBCOMP 7 // Publish Complete (assured delivery part 3)
#define MQTT_SUBSCRIBE 8 // Client Subscribe request
#define MQTT_SUBACK 9 // Subscribe Acknowledgment
#define MQTT_UNSUBSCRIBE 10 // Client Unsubscribe request
#define MQTT_UNSUBACK 11 // Unsubscribe Acknowledgment
#define MQTT_PINGREQ 12 // PING Request
#define MQTT_PINGRESP 13 // PING Response
#define MQTT_DISCONNECT 14 // Client is Disconnecting
#define MQTT_Reserved 15 // Reserved
namespace MQTT {
class Message {
protected:
uint8_t _type, _flags;
uint16_t _packet_id; // Not all message types use a packet id, but most do
Message(uint8_t t, uint8_t f = 0) :
_type(t), _flags(f),
_packet_id(0) { }
Message(uint8_t t, uint16_t pid) :
_type(t), _flags(0),
_packet_id(pid) { }
// Write the fixed header to a buffer
bool write_fixed_header(uint8_t *buf, size_t &bufpos, size_t rlength);
bool write_packet_id(uint8_t *buf, size_t &bufpos);
// Abstract methods to be implemented by derived classes
virtual bool write_variable_header(uint8_t *buf, size_t &bufpos) = 0;
virtual bool write_payload(uint8_t *buf, size_t &bufpos) { }
public:
virtual uint8_t response_type(void) const { return 0; }
// Send the message out
bool send(Stream &stream, size_t block_size = MQTT_SEND_BLOCK_SIZE);
bool send(Stream &stream, uint8_t *buffer, size_t block_size = MQTT_SEND_BLOCK_SIZE);
// Get the message type
uint8_t type(void) const { return _type; }
// Get the packet id
uint16_t packet_id(void) const { return _packet_id; }
};
class Publish : public Message {
protected:
String _topic;
uint8_t *_payload;
size_t _payload_len;
bool write_variable_header(uint8_t *buf, size_t &bufpos);
bool write_payload(uint8_t *buf, size_t &bufpos);
virtual void init(String topic, uint8_t *payload, size_t len) {
_topic = topic;
_payload = payload;
_payload_len = len;
}
public:
Publish() :
Message(MQTT_PUBLISH),
_payload(NULL) { }
Publish(String topic, uint8_t *payload, size_t len) :
Message(MQTT_PUBLISH) {
init(topic, payload, len);
}
Publish(String topic, const char *payload, size_t len = 0) :
Message(MQTT_PUBLISH) {
if (len == 0) {
len = strlen(payload);
}
init(topic, (uint8_t *) payload, len);
}
uint8_t response_type(void) const;
// Get or set retain flag
bool retain(void) const { return (bool) (_flags & 0x01); }
Publish &set_retain(bool r = true) {
_flags = (uint8_t) ((_flags & ~0x01) | r);
return *this;
}
Publish &unset_retain(void) {
_flags = (uint8_t) (_flags & ~0x01);
return *this;
}
// Get or set QoS value
uint8_t qos(void) const { return (uint8_t) ((_flags >> 1) & 0x03); }
Publish &set_qos(uint8_t q, uint16_t pid = 0) {
if (q > 2)
q = 2;
_flags &= ~0x06;
if (q) {
_flags |= q << 1;
_packet_id = pid;
}
return *this;
}
Publish &unset_qos(void) {
_flags &= ~0x06;
return *this;
}
// Get or set dup flag
bool dup(void) const { return (bool) ((_flags >> 3) & 0x01); }
Publish &set_dup(bool d = true) {
_flags = (uint8_t) ((_flags & ~0x08) | (d ? 0x08 : 0));
return *this;
}
Publish &unset_dup(void) {
_flags = (uint8_t) (_flags & ~0x08);
return *this;
}
virtual char *topic(void) const { return (char *) _topic.c_str(); }
virtual uint8_t *payload(void) const { return _payload; }
virtual size_t payload_len(void) const { return _payload_len; }
virtual char *payload_string(void) const { return (char *) _payload; }
};
class BufferedPublish : public Publish {
protected:
uint8_t _buffer[MQTT_MAX_PAYLOAD_SIZE];
virtual void init(String topic, uint8_t *payload, size_t len) {
_topic = topic;
_payload_len = len;
memcpy(_buffer, payload, len);
memset(_buffer + len, 0, MQTT_MAX_PAYLOAD_SIZE - len);
}
public:
BufferedPublish(String topic, uint8_t *payload, size_t len) {
init(topic, payload, len);
}
BufferedPublish(String topic, String &payload) {
_topic = topic;
_payload_len = 0;
memset(_buffer, 0, MQTT_MAX_PAYLOAD_SIZE);
if (payload.length() > 0) {
memcpy(_buffer, payload.c_str(), payload.length());
_payload_len = payload.length();
}
}
BufferedPublish(String topic, const __FlashStringHelper *payload) {
_topic = topic;
_payload_len = strlen_P((PGM_P) payload);
strncpy((char *) _payload, (PGM_P) payload, _payload_len);
}
BufferedPublish(String topic, PGM_P payload, size_t length) {
_topic = topic;
_payload_len = length;
memset(_buffer, 0, MQTT_MAX_PAYLOAD_SIZE);
memcpy_P(_buffer, payload, length);
}
// Construct from a network buffer
BufferedPublish(uint8_t flags, uint8_t *data, size_t length);
virtual uint8_t *payload(void) const { return (uint8_t *) _buffer; }
virtual char *payload_string(void) const { return (char *) _buffer; }
};
// Response to Publish when qos == 1
class PublishAck : public Message {
private:
bool write_variable_header(uint8_t *buf, size_t &bufpos) { }
public:
// Construct with a packet id
PublishAck(uint16_t pid);
// Construct from a network buffer
PublishAck(uint8_t *data, size_t length);
};
// First response to Publish when qos == 2
class PublishRec : public Message {
private:
bool write_variable_header(uint8_t *buf, size_t &bufpos);
public:
// Construct with a packet id
PublishRec(uint16_t pid);
// Construct from a network buffer
PublishRec(uint8_t *data, size_t length);
uint8_t response_type(void) const { return MQTT_PUBREL; }
};
// Response to PublishRec
class PublishRel : public Message {
private:
bool write_variable_header(uint8_t *buf, size_t &bufpos);
public:
// Construct with a packet id
PublishRel(uint16_t pid);
// Construct from a network buffer
PublishRel(uint8_t *data, size_t length);
uint8_t response_type(void) const { return MQTT_PUBCOMP; }
};
// Response to PublishRel
class PublishComp : public Message {
private:
bool write_variable_header(uint8_t *buf, size_t &bufpos);
public:
// Construct with a packet id
PublishComp(uint16_t pid);
// Construct from a network buffer
PublishComp(uint8_t *data, size_t length);
};
// Ping the broker
class Ping : public Message {
private:
bool write_variable_header(uint8_t *buf, size_t &bufpos) { }
public:
// Constructor
Ping() :
Message(MQTT_PINGREQ) { }
// Construct from a network buffer
Ping(uint8_t *data, size_t length) :
Message(MQTT_PINGREQ) { }
uint8_t response_type(void) const { return MQTT_PINGRESP; }
};
// Response to Ping
class PingResp : public Message {
private:
bool write_variable_header(uint8_t *buf, size_t &bufpos) { }
public:
// Constructor
PingResp() :
Message(MQTT_PINGRESP) { }
// Construct from a network buffer
PingResp(uint8_t *data, size_t length) :
Message(MQTT_PINGRESP) { }
};
}
#endif //MQTT_H
|
airbit/ArduinoMQTT
|
examples/mqtt_basic/creds.h
|
<reponame>airbit/ArduinoMQTT<gh_stars>0
#ifndef CREDS_H
#define CREDS_H
char *ssid = "CCTY"; // cannot be longer than 32 characters!
char *pass = "<PASSWORD>"; //
#endif //CREDS_H
|
vodka-bears/LiteOSD
|
inc/ascii.h
|
#ifndef ascii_h
#define ascii_h
#define _a 0x08
#define _b 0x10
#define _c 0x18
#define _d 0x20
#define _e 0x28
#define _f 0x30
#define _g 0x38
#define _h 0x40
#define _i 0x48
#define _j 0x50
#define _k 0x58
#define _l 0x60
#define _m 0x68
#define _n 0x70
#define _o 0x78
#define _p 0x80
#define _q 0x88
#define _r 0x90
#define _s 0x98
#define _t 0xa0
#define _u 0xa8
#define _v 0xb0
#define _w 0xb8
#define _x 0xc0
#define _y 0xc8
#define _z 0xd0
#define _black 0xe8
#define b00000000 0x00
#define b01111110 0x7E
#define b01000010 0x42
#define b01000000 0x40
#define b01111000 0x78
#define b01000100 0x44
#define b00000010 0x02
#define b00010000 0x10
#define b01100110 0x66
#define b01111100 0x7C
#define b01000110 0x46
#define b01001000 0x48
#define b01010000 0x50
#define b01100000 0x60
#define b01011010 0x5A
#define b01010010 0x52
#define b01001010 0x4A
#define b01011000 0x58
#define b00100100 0x24
#define b00101100 0x2C
#define b00011000 0x18
#define b10000010 0x82
#define b10010010 0x92
#define b11111110 0xFE
#define b00100010 0x22
#define b00010100 0x14
#define b00001000 0x08
#define b11111111 0xFF
#define b10000000 0x80
#define b00111000 0x38
#define b00000100 0x04
#define b00100000 0x20
#define b00110000 0x30
#define b00111110 0x3E
#define b00011100 0x1C
#define b00111111 0x3F
#define b11111100 0xFC
#define b01111111 0x7F
#define b00000011 0x03
#define b11000000 0xC0
#define b00000111 0x07
#define b11100000 0xE0
#define b00000001 0x01
#define b00001111 0x0F
#define b11110000 0xF0
#define b00011111 0x1F
#define b11111000 0xF8
#define b10001110 0x8E
#define b00000110 0x06
#define b01110000 0x70
#define b00001110 0x0E
#define b10011110 0x9E
#define b00111100 0x3C
#define b11000001 0xC1
#define b11100011 0xE3
#define b00011110 0x1E
#define b01110001 0x71
#define b00001001 0x09
#define b10010000 0x90
#define b00001011 0x0B
#define b11010000 0xB0
#define b00110000 0x30
#define b00001100 0x03
#define b01100010 0x62
#define b10001010 0x8A
#define b00101000 0x28
#define b10000100 0x84
#define b01010100 0x54
#define b10101010 0xaa
#define b01001100 0x4c
#define b00110010 0x32
#define b10001100 0x8c
#define b01110010 0x72
#define b11000100 0xc4
#define b10111000 0xb8
#define b10111100 0xbc
#define b11000010 0xc2
#define b11000110 0xc6
#define b10100010 0xa2
#define b10000110 0x86
#define b10111110 0xbe
#define b10100000 0xa0
#define b10001000 0x88
unsigned char code ULetters[] = {
// Blank - 0
b00000000,
b00111110,
b01000000,
b10000000,
b10000000,
b10000000,
b10000000,
b01000000,
b00111000,
b00000100,
b00000010,
b00000010,
b00000010,
b00000010,
b00000100,
b11111000,
b00000000,
b01111100,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b01111100,
b00000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01111110,
b00000000,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b01000100,
b00101000,
b00010000,
b00000000,
b11111110,
b10000000,
b10000000,
b10000000,
b10000000,
b10000000,
b10000000,
b11111110,
b10000000,
b10000000,
b10000000,
b10000000,
b10000000,
b10000000,
b11111110,
b00000000,
b11111110,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b11111110,
b11000000,
b10100000,
b10010000,
b10001000,
b10000100,
b10000010,
};
unsigned char code PLetters[] = {
// Blank - a
b00000000,
b00010000,
b00101000,
b01000100,
b10000010,
b10000010,
b10000010,
b10000010,
b11111110,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b10000010,
b00000000,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b10101010,
b01000100,
b00000000,
b00100000,
b00100000,
b00100000,
b00111110,
b00100010,
b00100010,
b00111110,
b00000000,
b10010000,
b10010000,
b01010000,
b00110000,
b00100000,
b01000000,
b10000000,
};
unsigned char code letters[] = {
// Blank - y
b00000000,
b00000000,
b00000000,
b00000000,
b00000000,
b00000000,
b00000000,
b00000000,
// A - 1
b00000000,
b00011000,
b00100100,
b01000010,
b01111110,
b01000010,
b01000010,
b01000010,
// B - 2
b00000000,
b01111100,
b01000010,
b01000010,
b01111110,
b01000010,
b01000010,
b01111100,
// C - 3
b00000000,
b00011110,
b00100000,
b01000000,
b01000000,
b01000000,
b00100000,
b00011110,
// D - 4
b00000000,
b01111000,
b01000100,
b01000010,
b01000010,
b01000010,
b01000100,
b01111000,
// E - 5
b00000000,
b01111110,
b01000000,
b01000000,
b01111110,
b01000000,
b01000000,
b01111110,
// F - 6
b00000000,
b01111110,
b01000000,
b01000000,
b01111110,
b01000000,
b01000000,
b01000000,
// G - 7
b00000000,
b01111110,
b10000010,
b10000000,
b10000110,
b10000010,
b10000010,
b01111100,
// H - 8
b00000000,
b01000010,
b01000010,
b01000010,
b01111110,
b01000010,
b01000010,
b01000010,
// I - 9
b00000000,
b01111100,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b01111100,
// J - 10
b00000000,
b01111110,
b00000010,
b00000010,
b00000010,
b01000010,
b01100110,
b01111100,
//K - 11
b00000000,
b01000100,
b01001000,
b01010000,
b01100000,
b01010000,
b01001000,
b01000100,
// L - 12
b00000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01000000,
b01111100,
// M - 13
b00000000,
b11000110,
b10101010,
b10010010,
b10000010,
b10000010,
b10000010,
b10000010,
// N - 14
b00000000,
b11000010,
b10100010,
b10010010,
b10001010,
b10001010,
b10000110,
b10000010,
// O - 15
b00000000,
b00111100,
b01000010,
b01000010,
b01000010,
b01000010,
b01000010,
b00111100,
// P - 16
b00000000,
b01111100,
b01000010,
b01000010,
b01111100,
b01000000,
b01000000,
b01000000,
// Q - 17
b00000000,
b01111110,
b01000010,
b01000010,
b01000010,
b01011010,
b01111110,
b00000110,
// R - 18
b00000000,
b01111100,
b01000010,
b01000010,
b01111100,
b01001000,
b01000100,
b01000010,
// S - 19
b00000000,
b00111110,
b01000000,
b01000000,
b00111100,
b00000010,
b00000010,
b01111100,
// T - 20
b00000000,
b01111110,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
b00010000,
// U - 21
b00000000,
b01000010,
b01000010,
b01000010,
b01000010,
b01000010,
b01000010,
b00111100,
// V - 22
b00000000,
b10000010,
b10000010,
b10000010,
b10000010,
b01000100,
b00101000,
b00010000,
// w - 23
b00000000,
b10000010,
b10010010,
b10010010,
b10010010,
b10010010,
b10010010,
b01111100,
// x - 24
b00000000,
b01000010,
b00100010,
b00010100,
b00001000,
b00010100,
b00100010,
b01000010,
// y - 25
b00000000,
b01000010,
b00100010,
b00010100,
b00001000,
b00001000,
b00001000,
b00001000,
//Z
b00000000,
b01111110,
b00000100,
b00001000,
b00010000,
b00100000,
b01000000,
b01111110,
//27
b00000000,
b00000000,
b00000000,
b00000000,
b11110000,
b10000000,
b10000000,
b11110000,
//28
b00000000,
b00000000,
b00000000,
b00000000,
b00011110,
b00000010,
b00000010,
b00011110,
//29
b00000000,//233
b11111110,
b11111110,
b11111110,
b11111110,
b11111110,
b11111110,
b00000000,
//30
b00000000,//233
b00000000,
b00000000,
b00000000,
b10000100,
b10000100,
b01001000,
b00110000,
//31
b00000000,//233
b00000000,
b00000000,
b00000000,
b00110000,
b01001000,
b11111100,
b10000100,
};
// Array with numbers, "-", ".", ":" and blank
char code numbers[] = {
// 0
b00000000,
b01111110,
b01000010,
b01000010,
b01000010,
b01000010,
b01000010,
b01111110,
// 1
b00000000,
b00010000,
b00110000,
b01010000,
b00010000,
b00010000,
b00010000,
b01111110,
// 2
b00000000,
b01111110,
b00000110,
b00000110,
b01111110,
b01000000,
b01000000,
b01111110,
// 3
b00000000,
b01111110,
b00000010,
b00000010,
b00111110,
b00000010,
b00000010,
b01111110,
// 4
b00000000,
b01000010, //0x42
b01000010, //0x42
b01000010, //0x42
b01111110, //0x7E
b00000010, //0x02
b00000010, //0x02
b00000010, //0x02
// 5
b00000000,
b01111110,
b01000000,
b01000000,
b01111110,
b00000010,
b00000010,
b01111110,
// 6
b00000000,
b01111110,
b01000000,
b01000000,
b01111110,
b01000010,
b01000010,
b01111110,
// 7
b00000000,
b01111110,
b01000010,
b00000100,
b00001000,
b00010000,
b00100000,
b00100000,
// 8
b00000000,
b01111110,
b01000010,
b01000010,
b01111110,
b01000010,
b01000010,
b01111110,
// 9
b00000000,
b01111110,
b01000010,
b01000010,
b01111110,
b00000010,
b00000010,
b00000010,
// -
b00000000,
b00000000,
b00000000,
b00000000,
b11111110,
b00000000,
b00000000,
b00000000,
// .
b00000000,
b00000000,
b00000000,
b00000000,
b00000000,
b00000000,
b00111000,
b00111000,
// >
b00000000,
b10000000,
b00100000,
b00001000,
b00000010,
b00001000,
b00100000,
b10000000,
//:
b00000000,
b00000000,
b00011100,
b00011100,
b00000000,
b00011100,
b00011100,
b00000000,
// +
b00000000,
b00010000,
b00010000,
b00010000,
b11111110,
b00010000,
b00010000,
b00010000,
// ^
b00000000,
b00010000,
b00101000,
b01000100,
b10000010,
b00000000,
b00000000,
b00000000,
//<
b00000000,
b11111110,
b10000010,
b10000010,
b10000010,
b10000010,
b11111110,
b00000000,
//
b00000000,
b10000010,
b10000010,
b10000010,
b01000100,
b00101000,
b00010000,
b00000000,
//_
b00000000,
b00000000,
b00000000,
b00000000,
b00000000,
b00000000,
b00000000,
b11111110
};
#endif
|
didaclis/Research_QuadTree
|
Handout/Motor2D/ent_Player.h
|
#ifndef __ENT_PLAYER_H__
#define __ENT_PLAYER_H__
#include "j1Entity.h"
#include "Animation.h"
#include "j1Collision.h"
struct SDL_Texture;
enum PlayerState {
IDLE = 0,
WALKING,
UNKNOWN
};
class Player : public j1Entity
{
public:
Player(int x, int y, std::string name);
~Player();
bool Start();
bool Update(float dt);
bool CleanUp();
void OnCollision(Collider*, Collider*, float dt);
private:
void PushBack();
void AddColliders();
void ChangeState(PlayerState);
void SetCollidersPos();
void IdAnimToEnum();
void LoadProperties(pugi::xml_node&);
void LoadCollider(pugi::xml_node&);
private:
PlayerState state = IDLE;
Animation anim_walking;
Animation anim_default;
};
#endif
|
didaclis/Research_QuadTree
|
Handout/Motor2D/j1QuadTree.h
|
<reponame>didaclis/Research_QuadTree
#ifndef __J1QUADTREE_H__
#define __J1QUADTREE_H__
#include "j1Module.h"
class j1QuadTree
{
public:
j1QuadTree(SDL_Rect area, uint maxCol, uint lvl);
~j1QuadTree();
void DebugDraw();
private:
SDL_Rect area;
uint lvl;
uint maxCol;
};
#endif
|
didaclis/Research_QuadTree
|
Handout/Motor2D/j1Collision.h
|
#ifndef __J1COLLISION_H__
#define __J1COLLISION_H__
#include "j1Module.h"
#include <vector>
class j1Entity;
enum COLLIDER_TYPE
{
COLLIDER_NONE = -1,
COLLIDER_ENTITY,
COLLIDER_MAX
};
struct Collider
{
SDL_Rect rect;
bool to_delete = false;
COLLIDER_TYPE type;
j1Entity* callback = nullptr;
Collider(SDL_Rect rectangle, COLLIDER_TYPE type, j1Entity* callback = nullptr) :
rect(rectangle),
type(type),
callback(callback)
{}
void SetPos(int x, int y)
{
rect.x = x;
rect.y = y;
}
bool CheckCollision(const SDL_Rect& r) const;
};
class j1Colliders : public j1Module
{
public:
j1Colliders();
~j1Colliders();
bool Awake(pugi::xml_node&);
bool PreUpdate() ;
bool Update(float dt);
void OnCollisionCall(Collider * c1, Collider * c2, float dt);
//update_status PostUpdate();
bool CleanUp();
Collider* AddCollider(SDL_Rect rect, COLLIDER_TYPE type, j1Entity * callback = nullptr);
bool EraseAllCollider(Collider* collider);
void DebugDraw();
bool checkColisionList(Collider* enemCollider);
bool Check(Collider* c1, COLLIDER_TYPE type);
bool debug = false;
bool traditionalMetod = false;
private:
std::vector<Collider*> colliders;
bool matrix[COLLIDER_MAX][COLLIDER_MAX];
};
#endif // __J1COLLIDERS_H__
|
didaclis/Research_QuadTree
|
Handout/Motor2D/j1Map.h
|
#ifndef __j1MAP_H__
#define __j1MAP_H__
#include <list>
#include <string>
#include "j1Module.h"
#include "j1Collision.h"
struct SDL_Texture;
// ----------------------------------------------------
struct LayerProperties
{
bool draw = true;
};
struct MapProperties
{
std::string objects_path;
};
struct MapLayer {
std::string name;
uint width = 0;
uint height = 0;
uint* tiles = nullptr;
bool visible = true;
LayerProperties properties;
~MapLayer() { delete[] tiles; tiles = nullptr; }
inline uint Get(int x, int y) const;
};
// ----------------------------------------------------
struct TileSet
{
SDL_Rect GetTileRect(int id) const;
std::string name;
int firstgid;
int margin;
int spacing;
int tile_width;
int tile_height;
SDL_Texture* texture;
int tex_width;
int tex_height;
int num_tiles_width;
int num_tiles_height;
int offset_x;
int offset_y;
};
enum MapTypes
{
MAPTYPE_UNKNOWN = 0,
MAPTYPE_ORTHOGONAL,
MAPTYPE_ISOMETRIC,
MAPTYPE_STAGGERED
};
// ----------------------------------------------------
struct MapData
{
int width;
int height;
int tile_width;
int tile_height;
MapProperties properties;
SDL_Color background_color;
MapTypes type;
std::list<TileSet*> tilesets;
std::list<MapLayer*> layers;
std::list<Collider*> mapColliders;
};
// ----------------------------------------------------
class j1Map : public j1Module
{
public:
j1Map();
// Destructor
virtual ~j1Map();
// Called before render is available
bool Awake(pugi::xml_node& conf);
// Called each loop iteration
void Draw();
// Called before quitting
bool CleanUp();
// Load new map
bool Load(const char* path);
iPoint MapToWorld(int x, int y) const;
iPoint WorldToMap(int x, int y) const;
//void AddCollidersMap();
private:
bool LoadMap();
bool LoadMapProperties(pugi::xml_node& node);
bool LoadTilesetDetails(pugi::xml_node& tileset_node, TileSet* set);
bool LoadTilesetImage(pugi::xml_node& tileset_node, TileSet* set);
bool LoadLayer(pugi::xml_node& layer_node, MapLayer* layer);
bool LoadObjects(pugi::xml_node& layer_node, SDL_Rect &rect);
void LoadLayerProperties(pugi::xml_node & properties_node, MapLayer* layer = nullptr);
TileSet* GetTilesetFromTileId(int id) const;
public:
MapData data;
std::string sceneName;
bool draw_grid = false;
private:
pugi::xml_document map_file;
std::string folder;
bool map_loaded;
SDL_Texture* grid = nullptr;
};
#endif // __j1MAP_H__
|
didaclis/Research_QuadTree
|
Handout/Motor2D/ent_NPC.h
|
#ifndef __ENT_NPC_H__
#define __ENT_NPC_H__
#include "j1Entity.h"
#include "Animation.h"
struct SDL_Texture;
class ent_NPC : public j1Entity
{
public:
ent_NPC(int x, int y, std::string name);
~ent_NPC();
bool Start();
bool Update(float dt);
bool CleanUp();
void OnCollision(Collider*, Collider*, float dt);
private:
};
#endif
|
didaclis/Research_QuadTree
|
Handout/Motor2D/Quadtree.h
|
#ifndef __QUADTREE_H__
#define __QUADTREE_H__
#include "p2Defs.h"
#include "p2Log.h"
#include "SDL/include/SDL.h"
class Quadtree
{
public:
//Constructor
Quadtree(uint max_levels, SDL_Rect area, uint level, uint maxElements);
~Quadtree();
//subdivide the node into 4 subnodes
virtual void Subdivide() {};
void Draw() const {};
bool CheckIn(SDL_Rect rect);
protected:
uint max_levels; //Max number of levels a quadtree will have
uint level; //Position in the tree
SDL_Rect area; //Position and size
bool isDivided; //true when have subnodes
uint maxElements; //max elements to divide;
};
#endif // !__QUADTREE_H__
|
didaclis/Research_QuadTree
|
Handout/Motor2D/CollisionQuadTree.h
|
#ifndef _COLLISIONQUADTREE_H_
#define _COLLISIONQUADTREE_H_
#include "Quadtree.h"
#include "j1Collision.h"
#include <list>
class CollisionQuadTree : public Quadtree
{
public:
CollisionQuadTree(uint max_levels, SDL_Rect area, uint level, uint maxElements, CollisionQuadTree* prev = nullptr);
~CollisionQuadTree();
void Subdivide();
void AddCollider(Collider* col);
void DistrbuteColliders();
void CheckCollisions(float dt);
void PlaceCollider(Collider* col);
void CleanUp();
uint GetSize();
void Draw();
private:
CollisionQuadTree* nodes[4]; //next subdivide
std::list<Collider*> elements;//elements to check collisions
CollisionQuadTree* prev = nullptr; //save the Quadtree that create them
};
#endif
|
didaclis/Research_QuadTree
|
Solution/Motor2D/j1Scene.h
|
<gh_stars>0
#ifndef __j1SCENE_H__
#define __j1SCENE_H__
#include "j1Module.h"
#include "CollisionQuadTree.h"
#include <vector>
class j1Scene : public j1Module
{
public:
j1Scene();
// Destructor
virtual ~j1Scene();
// Called before render is available
bool Awake(pugi::xml_node& map);
// Called before the first frame
bool Start();
// Called each loop iteration
bool Update(float dt);
// Called before quitting
bool CleanUp();
bool entities_box = false;
public:
CollisionQuadTree* quadtree = nullptr;
uint collisionsCheck = 0;
};
#endif // __j1SCENE_H__
|
didaclis/Research_QuadTree
|
Solution/Motor2D/j1Window.h
|
#ifndef __j1WINDOW_H__
#define __j1WINDOW_H__
#include "j1Module.h"
struct SDL_Window;
struct SDL_Surface;
class j1Window : public j1Module
{
public:
j1Window();
// Destructor
virtual ~j1Window();
// Called before render is available
bool Awake(pugi::xml_node&);
// Called before quitting
bool CleanUp();
// Change title
void SetNewTitle(const char* new_title);
void AddStringToTitle(const char* add_title);
void ClearTitle();
// Retrive window size
uint GetWindowWidth() const;
uint GetWindowHeight() const;
// Retrieve window scale
uint GetScale() const;
void SetScale(int scale);
public:
//The window we'll be rendering to
SDL_Window* window;
//The surface contained by the window
SDL_Surface* screen_surface;
bool fullscreen;
private:
std::string title;
uint width;
uint height;
uint scale;
};
#endif // __j1WINDOW_H__
|
didaclis/Research_QuadTree
|
Handout/Motor2D/ent_Static.h
|
<filename>Handout/Motor2D/ent_Static.h
#ifndef __ENT_STATIC_H__
#define __ENT_STATIC_H__
#include "j1Entity.h"
struct SDL_Texture;
class ent_Static : public j1Entity
{
public:
enum class Type {
TREE,
STATUE,
POST,
HOUSE,
CENTER,
PILAR,
CORNER,
WALL_UP_RIGHT,
WALL_UP_LEFT,
WALL_DOWN_RIGHT,
WALL_DOWN_LEFT,
DOOR,
UNKNOWN
};
public:
ent_Static(int x, int y, std::string name);
~ent_Static();
//void OnCollision(Collider*, Collider*, float dt);
private:
void Draw();
void SetRect(int x, int y, int w, int h);
private:
SDL_Rect frame;
Type type;
};
#endif
|
didaclis/Research_QuadTree
|
Handout/Motor2D/j1Entity.h
|
#ifndef __ENTITY_H__
#define __ENTITY_H__
#include "p2Point.h"
#include "Animation.h"
#include <string>
#include "j1Collision.h"
#include "SDL_image/include/SDL_image.h"
struct SDL_Texture;
struct Collider;
struct TileSetEntity {
SDL_Rect GetTileRect(int id) const;
std::string name;
uint tilewidth = 0;
uint tileheight = 0;
uint spacing = 0;
uint margin = 0;
uint tilecount = 0;
uint columns = 0;
std::string imagePath;
SDL_Texture* texture = nullptr;
uint width = 0;
uint height = 0;
};
enum class EntityState {
IDLE = 0,
WALKING,
UNKNOWN
};
class j1Entity
{
public:
j1Entity(int x, int y, std::string name);
virtual ~j1Entity();
const Collider* GetCollider() const;
//-----------------------------------------------------------------------------------------------------------
virtual bool Start() { return true; }
virtual bool Update(float dt);
virtual void Draw();
void OnCollision(Collider* collider1, Collider * collider2, float dt);
virtual bool CleanUp();
public:
uint count = 0;
std::string name;
fPoint position;
iPoint pivot = { 0, 0 };
iPoint size = { 0, 0 };
Animation anim_run;
Animation col_anim;
SDL_Texture* texture;
Collider* collider;
std::string folder = "entities/";
SDL_RendererFlip flip = (SDL_RendererFlip)SDL_FLIP_NONE;
pugi::xml_document entity_file;
Animation* current_animation = nullptr;
protected:
bool goleft;
};
#endif // __ENTITY_H__
|
cydrobolt/compos
|
compos.c
|
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/list.h>
#include <asm/uaccess.h>
// Import proc_fs and netfilter
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/tcp.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
// Import JSON libraries to interface with compos_ctl
#include "lib/jsmn.h"
// Define constants
#define PROCFS_NAME "compos"
#define PROCFS_MAX_SIZE 1024
MODULE_LICENSE("MIT");
MODULE_AUTHOR("cydrobolt");
MODULE_DESCRIPTION("compos self-control module");
static struct nf_hook_ops nfho;
static struct proc_dir_entry *proc_entry;
static char procfs_buffer[PROCFS_MAX_SIZE];
static int procfs_buffer_size = 0;
/* proc file functions */
static int cp_proc_write(struct file *file, char *buffer, size_t count, loff_t *offset) {
procfs_buffer_size = count;
if (procfs_buffer_size > PROCFS_MAX_SIZE) {
procfs_buffer_size = PROCFS_MAX_SIZE;
}
printk(KERN_INFO "received something in write!");
if (!copy_from_user(procfs_buffer, buffer, procfs_buffer_size)) {
printk(KERN_INFO "received information in procfile");
printk(KERN_INFO "%s", procfs_buffer);
return -EFAULT;
}
return procfs_buffer_size;
}
static int cp_proc_show(struct seq_file *m, void *v) {
seq_printf(m, "hello world!\n");
return 0;
}
static int cp_proc_open(struct inode *inode, struct file *file) {
return single_open(file, cp_proc_show, NULL);
}
static const struct file_operations cp_fops = {
owner: THIS_MODULE,
open: cp_proc_open,
read: seq_read,
llseek: seq_lseek,
release: single_release,
write: cp_proc_write
};
/* netfilter hooks */
unsigned int hook_func_out (void *priv,
struct sk_buff *skb,
const struct nf_hook_state *state) {
// Intercept outbound packets
struct iphdr *ip_header = (struct iphdr *) skb_network_header(skb);
// unsigned int src_ip = (unsigned int)ip_header->saddr;
unsigned int dest_ip = (unsigned int) ip_header->daddr;
printk("packet with dest %pI4", &dest_ip);
if (false) {
return NF_DROP;
}
return NF_ACCEPT;
}
/* initialize & cleanup compos */
static int __init compos_init(void) {
printk(KERN_INFO "Loading compos\n");
nfho.hook = hook_func_out;
nfho.hooknum = NF_INET_LOCAL_OUT;
nfho.pf = PF_INET;
nfho.priority = NF_IP_PRI_FIRST;
// Register hook
nf_register_hook(&nfho);
// Initialize proc file
proc_entry = proc_create(PROCFS_NAME, 0, NULL, &cp_fops);
if (proc_entry == NULL) {
remove_proc_entry(PROCFS_NAME, NULL);
printk(KERN_ALERT "Could not initialize /proc/%s\n", PROCFS_NAME);
return -ENOMEM;
}
printk(KERN_INFO "compos proc file created");
return 0;
}
static void __exit compos_cleanup(void) {
printk(KERN_ALERT "Cleaning up compos.\n");
nf_unregister_hook(&nfho);
remove_proc_entry(PROCFS_NAME, NULL);
}
module_init(compos_init);
module_exit(compos_cleanup);
|
eelfroth/orca-bytebeat
|
base36.c
|
#include <stdio.h>
#include <time.h>
#define NS_PER_S 1000000000L
struct timespec ts_subtract(struct timespec time1, struct timespec time2);
int main()
{
int c;
long dt;
struct timespec ts_now, ts_last;
clock_gettime(CLOCK_REALTIME, &ts_last);
for (;;) {
clock_gettime(CLOCK_REALTIME, &ts_now);
dt = ts_subtract(ts_now, ts_last).tv_nsec;
ts_last = ts_now;
c = getc(stdin);
if (c == EOF) break;
else if (c >= '0' && c <= '9') c -= '0';
else if (c >= 'a' && c <= 'z') c -= 'a' - 10;
else if (c >= 'A' && c <= 'Z') c -= 'A' - 10;
else continue;
c = c * 255 / 35;
putc((unsigned char) c, stdout);
fflush(stdout);
fprintf(stderr, "\r%f Hz \t", (float)NS_PER_S/dt);
}
return 0;
}
struct timespec ts_subtract(struct timespec time1, struct timespec time2)
{
struct timespec result;
result.tv_sec = time1.tv_sec - time2.tv_sec;
if (time1.tv_nsec < time2.tv_nsec) {
result.tv_nsec = time1.tv_nsec + NS_PER_S - time2.tv_nsec;
result.tv_sec--;
} else {
result.tv_nsec = time1.tv_nsec - time2.tv_nsec;
}
return (result);
}
|
giordi91/Compressonator
|
Compressonator/Applications/_Plugins/Common/PluginManager.h
|
<filename>Compressonator/Applications/_Plugins/Common/PluginManager.h
//=====================================================================
// Copyright 2016 (c), Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
/// \file PluginManager.h
/// \version 2.20
//
//=====================================================================
#ifndef _PLUGINMANAGER_H
#define _PLUGINMANAGER_H
// C RunTime Header Files
#include <stdlib.h>
#ifndef __APPLE__
#include <malloc.h>
#endif
#include <memory.h>
#ifdef _WIN32
#include <tchar.h>
#include <direct.h>
#endif
#include <vector>
//#include "PluginInterface.h"
#include "PluginBase.h"
using namespace std;
#define MAX_PLUGIN_FILENAME_STR 512
#define MAX_PLUGIN_NAME_STR 256
#define MAX_PLUGIN_UUID_STR 37
#define MAX_PLUGIN_TYPE_STR 64
#define MAX_PLUGIN_CATEGORY_STR 64
#define DEFAULT_PLUGINLIST_DIR "./plugins"
class PluginDetails
{
public:
PluginDetails() { clearMembers(); }
~PluginDetails();
void *makeNewInstance();
void setFileName(char * nm);
char *getFileName() { return filename; }
char *getName() { return pluginName; }
char *getUUID() { return pluginUUID; }
char *getType() { return pluginType; }
char *getCategory() { return pluginCategory; }
void setName(char * nm);
void setUUID(char * nm);
void setType(char * nm);
void setCategory(char * nm);
bool isStatic;
bool isRegistered; // true when all dll interfaces has been registered using LoadLibraryA and GetProcAddress
PLUGIN_FACTORYFUNC funcHandle;
private:
void clearMembers()
{
#ifdef _WIN32
dllHandle = NULL;
#endif
isStatic = false;
isRegistered = false;
filename[0] = 0;
pluginType[0] = 0;
pluginName[0] = 0;
pluginUUID[0] = 0;
pluginCategory[0] = 0;
}
char filename [MAX_PLUGIN_FILENAME_STR];
char pluginType [MAX_PLUGIN_TYPE_STR];
char pluginName [MAX_PLUGIN_NAME_STR];
char pluginUUID [MAX_PLUGIN_UUID_STR];
char pluginCategory[MAX_PLUGIN_CATEGORY_STR];
#ifdef _WIN32
HINSTANCE dllHandle;
#endif
};
class PluginManager
{
public:
PluginManager();
~PluginManager();
void getPluginList(char * dirPath);
void registerStaticPlugin(char *pluginType, char *pluginName, void * makePlugin);
void registerStaticPlugin(char *pluginType, char *pluginName, char *uuid, void * makePlugin);
bool PluginSupported(char *type, char *name);
void getPluginDetails(PluginDetails *curPlugin);
int getNumPlugins();
void *makeNewPluginInstance(int index);
char *getPluginName(int index);
char *getPluginUUID(int index);
char *getPluginCategory(int index);
char *getPluginType(int index);
void *GetPlugin(char *type, char *name);
void *GetPlugin(char *uuid);
private:
bool m_pluginlistset;
char m_pluginfolder [MAX_PLUGIN_FILENAME_STR];
void clearPluginList();
vector<PluginDetails*> pluginRegister;
};
#endif
|
SicklySilverMoon/C-Utils
|
ArrayList/TEST_FOR_ARRAYLIST.c
|
<reponame>SicklySilverMoon/C-Utils
#include "ArrayList.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int compare(const void* a, const void* b);
int main() {
ArrayList* list = createArrayList(1);
srand(time(NULL));
int a = rand();
printf("value of added first element: %d\n", a);
addArrayListElement(list, &a);
int b = rand();
addArrayListElement(list, &b);
int c = rand();
addArrayListElement(list, &c);
int d = rand();
addArrayListElement(list, &d);
int e = rand();
addArrayListElement(list, &e);
int f = rand();
addArrayListElement(list, &f);
printf("\nUNSORTED LIST:\n\n");
for (size_t i = 0; i < getArrayListSize(list); i++) {
printf("%d\n", *(int*)(getArrayListElement(list, i)));
}
sortArrayList(list, compare);
printf("\nSORTED LIST:\n\n");
for (size_t i = 0; i < getArrayListSize(list); i++) {
printf("%d\n", *(int*)(getArrayListElement(list, i)));
}
removeArrayListElement(list);
printf("\nLAST ELEMENT REMOVED\n\n");
for (size_t i = 0; i < getArrayListSize(list); i++) {
printf("%d\n", *(int*)(getArrayListElement(list, i)));
}
printf("\nindex of first added element is: %zu\n", (findInArrayList(list, &a, compare)));
int testSet = 2;
setArrayListElement(list, getArrayListSize(list)/2, &testSet);
printf("\nMID ELEMENT SET TO 2\n\n");
for (size_t i = 0; i < getArrayListSize(list); i++) {
printf("%d\n", *(int*)(getArrayListElement(list, i)));
}
freeArrayList(list);
return 0;
}
int compare(const void* a, const void* b) {
int first = **(int**)a;
int second = **(int**)b;
if (first > second) return 1;
if (first < second) return -1;
return 0;
}
|
SicklySilverMoon/C-Utils
|
ArrayList/ArrayList.c
|
<filename>ArrayList/ArrayList.c
#include "ArrayList.h"
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
struct ArrayList
{
size_t size;
size_t capacity;
void** elements;
};
static void expandArrayList(ArrayList* list);
//size is final index +1, meaning add just does elements[size] = x, whereas remove would do elements[--size] = NULL
/**
* A function that creates and returns a pointer to an ArrayList for usage, returns NULL on error
*/
ArrayList* createArrayList(size_t capacity) {
ArrayList* list = malloc(sizeof(ArrayList));
if (list == NULL)
return NULL;
list->size = 0;
list->capacity = capacity;
list->elements = malloc(sizeof(void*) * capacity);
return list;
}
/**
* Removes the ArrayList struct from memory, does not free the actual pointers themselves, that's up to the programmer to manage, returns -1 on error
*/
int freeArrayList(ArrayList* list) {
if (list == NULL)
return -1;
free(list->elements);
free(list);
return 0;
}
/**
* Returns the size of the list (defined as number of elements currently in the list), returns (size_t) -1 on error
*/
size_t getArrayListSize(const ArrayList* list) {
if (list == NULL)
return (size_t) -1;
return list->size;
}
/**
* Returns the capacity of the list (defined as number of elements that can be added to the list before it must expand), returns (size_t) -1 on error
*/
size_t getArrayListCapacity(const ArrayList* list) {
if (list == NULL)
return (size_t) -1;
return list->capacity;
}
/**
* Returns the element (a void pointer) at the given index, returns NULL on error
*/
void* getArrayListElement(ArrayList* list, size_t index) {
if (list == NULL || index >= list->size || index < 0)
return NULL;
return list->elements[index];
}
/**
* Sets the element at the given index to a void pointer to the given element, returns -1 on error
*/
int setArrayListElement(ArrayList* list, size_t index, void* data) {
if (list == NULL || index >= list->size || index < 0)
return -1;
list->elements[index] = data;
return 0;
}
/**
* Appends an item onto the end of the list, returns -1 on error
*/
int addArrayListElement(ArrayList* list, void* data) {
if (list == NULL)
return -1;
if (list->size == list->capacity)
expandArrayList(list);
list->elements[list->size++] = data;
return 0;
}
/**
* Removes the final element of the list, returns -1 on error
*/
int removeArrayListElement(ArrayList* list) {
if (list == NULL)
return -1;
if (list->size == 0)
return -1;
list->elements[--list->size] = NULL;
return 0;
}
/**
* Sorts the list via the qsort function, the passed function must cast from (void*) to (type**) before dereferencing, example compare function on ints:
*
* int compare(const void* a, const void* b) {
* int first = **(int**)a;
* int second = **(int**)b;
* if (first > second) return 1;
* if (first < second) return -1;
* return 0;
* }
*
* Returns -1 on error;
*/
int sortArrayList(ArrayList* list, int (*compar)(const void*, const void*)) {
if (list == NULL)
return -1;
qsort(list->elements, list->size, sizeof(void*), compar);
return 0;
}
/**
* Finds the given element (passed as a void pointer) when the passed function returns zero, enabling the ability to use the same compare function for both sortArrayList and findInArrayList.
*
* Returns the index of the element if found, (size_t) -1 if no match exists or there was an error
*/
size_t findInArrayList(ArrayList* list, const void* toFind, int (*compar)(const void*, const void*)) {
if (list == NULL)
return -1;
for (size_t i = 0; i < list->size; i++) {
if (compar(&toFind, &(list->elements[i])) == 0)
return i;
}
return (size_t) -1;
}
//internal methods
static void expandArrayList(ArrayList* list) {
if (list->capacity < 1)
list->capacity = 2;
else
list->capacity *= 2;
list->elements = realloc(list->elements, list->capacity * sizeof(void*));
}
|
SicklySilverMoon/C-Utils
|
ArrayList/ArrayList.h
|
#ifndef ARRAYLIST_H
#define ARRAYLIST_H
#include <stddef.h>
typedef struct ArrayList ArrayList;
ArrayList* createArrayList(size_t capacity);
int freeArrayList(ArrayList* list);
size_t getArrayListSize(const ArrayList* list);
size_t getArrayListCapacity(const ArrayList* list);
void* getArrayListElement(ArrayList* list, size_t index);
int setArrayListElement(ArrayList* list, size_t index, void* data);
int addArrayListElement(ArrayList* list, void* data);
int removeArrayListElement(ArrayList* list);
int sortArrayList(ArrayList* list, int (*compar)(const void*, const void*));
size_t findInArrayList(ArrayList* list, const void* toFind, int (*compar)(const void*, const void*));
#endif
|
bguest/Segment16Sign
|
lib/Segment.h
|
<filename>lib/Segment.h
#ifndef SEGMENT_H
#define SEGMENT_H
#include <stdint.h>
#include "Pixel.h"
#define VERTICAL 0
#define DIAGONAL_RIGHT 1
#define HORIZONTAL 2
#define DIAGONAL_LEFT 3
#define ORIENTATION_COUNT 4
class Segment {
public:
Segment();
void init(Pixel pixels[], uint8_t start, uint8_t endPlus1);
Pixel *pixels[4];
bool isOn;
uint16_t pixelCount();
void toArray(CRGB array[], uint16_t &currIdx);
void setColor(CHSV color);
void setColor(uint8_t layer, CHSV color);
void setHsv16(CHSV16 color);
CHSV16 getHsv16();
void setHsv16(uint8_t layer, CHSV16 color);
uint8_t index;
char orientation();
private:
uint8_t length;
};
#endif
|
bguest/Segment16Sign
|
lib/Segment16.h
|
#ifndef SEGMENT_16_H
#define SEGMENT_16_H
#include "Arduino.h"
#include <FastLED.h>
#include "Sign.h"
#include "Effects.h"
#include "Keyboard.h"
#include "Sound.h"
#include "EffectData.h"
#define SAVED_INPUT_COUNT 2
class Segment16 {
public:
Segment16();
void pushChar(uint32_t character);
Sign sign;
CRGB leds[LETTERS_COUNT*(NUM_4_PIXEL*4 + NUM_2_PIXEL*2)];
void init();
void run();
void show();
private:
char input[SAVED_INPUT_COUNT];
bool decideInput(char input);
bool isInsertMode;
EffectData data;
Sound sound;
Keyboard keyboard;
Effects effects;
};
#endif
|
bguest/Segment16Sign
|
lib/effects/RandomScroll.h
|
#ifndef RANDOM_SCROLL_H
#define RANDOM_SCROLL_H
#include "Effect.h"
class RandomScroll : public Effect{
public:
RandomScroll();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
private:
};
#endif
|
bguest/Segment16Sign
|
lib/effects/RandomOn.h
|
<reponame>bguest/Segment16Sign
#ifndef RANDOM_ON_H
#define RANDOM_ON_H
#include "Effect.h"
class RandomOn : public Effect{
public:
RandomOn();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void randomize(uint8_t ci);
private:
uint8_t onCount;
bool shouldReset;
bool turnOn;
};
#endif
|
bguest/Segment16Sign
|
lib/Sound.h
|
#ifndef SOUND_H
#define SOUND_H
#include "EffectData.h"
class Sound {
public:
void init();
void run(EffectData &data);
private:
unsigned long lastCollect;
uint16_t volume;
uint16_t freqAmp[7];
};
#endif
|
bguest/Segment16Sign
|
lib/effects/RainbowLetter.h
|
#ifndef RAINBOW_LETTER_H
#define RAINBOW_LETTER_H
#include "Effect.h"
class RainbowLetter : public Effect{
public:
RainbowLetter();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void signWasUpdated(Sign &sign);
void signWasUpdated(Sign &sign, uint8_t layer);
void randomize(uint8_t ci);
private:
bool isStatic;
bool changeOnBeat;
int8_t hueStep[LAYER_COUNT];
uint16_t cycleTime[LAYER_COUNT];
int16_t hueA[LAYER_COUNT];
};
#endif
|
bguest/Segment16Sign
|
lib/effects/RainbowSegment.h
|
#ifndef RAINBOW_SEGMENT_H
#define RAINBOW_SEGMENT_H
#include "Effect.h"
class RainbowSegment : public Effect{
public:
RainbowSegment();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void signWasUpdated(Sign &sign);
void randomize(uint8_t ci);
private:
bool isStatic;
bool changeOnBeat;
int8_t hueStep[LAYER_COUNT];
int8_t beatStep[LAYER_COUNT];
};
#endif
|
bguest/Segment16Sign
|
lib/effects/BasicTyping.h
|
#ifndef BASIC_TYPING_H
#define BASIC_TYPING_H
#include "Effect.h"
class BasicTyping : public Effect{
public:
BasicTyping();
void run(Sign &sign, EffectData &data, uint8_t layer);
};
#endif
|
bguest/Segment16Sign
|
lib/effects/WordsEnter.h
|
#ifndef WORDS_ENTER_H
#define WORDS_ENTER_H
#include "Effect.h"
const uint8_t WORDS_COUNT = 20;
class WordsEnter : public Effect{
public:
WordsEnter();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushInsert(char character);
bool pushChar(char character, uint8_t layer);
void randomize(uint8_t ci);
private:
void pushBuffer();
void pushToBuffer(char character);
void backspaceBuffer();
void softReset();
uint8_t numBeats;
uint8_t beatIdx;
uint8_t wordIdx;
uint8_t wordsCount;
uint8_t letterIdx;
char buffer[LETTERS_COUNT];
char words[WORDS_COUNT][LETTERS_COUNT];
};
#endif
|
bguest/Segment16Sign
|
lib/effects/Clock.h
|
<reponame>bguest/Segment16Sign
#ifndef CLOCK_H
#define CLOCK_H
#include "Effect.h"
class Clock : public Effect{
public:
Clock();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
private:
bool isClock; //As Apposed to Timer
bool is24Hour;
uint16_t stepTime;
int16_t minutesOffset;
int16_t hoursOffset;
unsigned long lastUpdated;
int16_t timeAmpMinutes;
uint16_t dilationPeriodMinutes;
};
#endif
|
bguest/Segment16Sign
|
lib/Color16.h
|
<gh_stars>0
#ifndef COLOR_16_H
#define COLOR_16_H
// Shamelessly mimiced from fastled.io
struct CHSV16 {
union {
struct {
union {
uint16_t hue;
uint16_t h; };
union {
uint16_t saturation;
uint16_t sat;
uint16_t s; };
union {
uint16_t value;
uint16_t val;
uint16_t v; };
};
uint16_t raw[3];
};
// default values are UNITIALIZED
inline CHSV16() __attribute__((always_inline))
{
}
// allow construction from H, S, V
inline CHSV16( uint16_t ih, uint16_t is, uint16_t iv) __attribute__((always_inline))
: h(ih), s(is), v(iv)
{
}
// allow copy construction
inline CHSV16(const CHSV16& rhs) __attribute__((always_inline))
{
h = rhs.h;
s = rhs.s;
v = rhs.v;
}
inline CHSV16( const CHSV& rhs) __attribute__((always_inline))
{
h = rhs.h << 8;
s = rhs.s << 8;
v = rhs.v << 8;
}
inline CHSV16& operator= (const CHSV16& rhs) __attribute__((always_inline))
{
h = rhs.h;
s = rhs.s;
v = rhs.v;
return *this;
}
inline CHSV16& setHSV(uint16_t ih, uint16_t is, uint16_t iv) __attribute__((always_inline))
{
h = ih;
s = is;
v = iv;
return *this;
}
};
#endif
|
bguest/Segment16Sign
|
lib/Pixel.h
|
<reponame>bguest/Segment16Sign
#ifndef PIXEL_H
#define PIXEL_H
#include "FastLED.h"
#include "Color16.h"
class Pixel {
public:
Pixel();
void setColor(CHSV color);
void setHue16(uint16_t hue);
void addHue16(int16_t deltaHue);
uint16_t getHue16();
CHSV getColor();
CHSV16 getHsv16();
void setHsv16(CHSV16 clr);
uint8_t x();
uint8_t y();
void setXY(uint8_t x, uint8_t y);
private:
CHSV16 hsv16;
uint8_t u[2];
};
#endif
|
bguest/Segment16Sign
|
lib/effects/Seizure.h
|
<reponame>bguest/Segment16Sign
#ifndef SEIZURE_H
#define SEIZURE_H
#include "Effect.h"
#define SEIZURE_COLOR_COUNT 4
class Seizure : public Effect{
public:
Seizure();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void randomize(uint8_t ci);
private:
CHSV colors[SEIZURE_COLOR_COUNT][LAYER_COUNT];
uint8_t editIdx;
uint8_t colorIdx[LAYER_COUNT];
uint8_t flashPerBeat[LAYER_COUNT];
unsigned long lastChange[LAYER_COUNT];
};
#endif
|
bguest/Segment16Sign
|
lib/Letter.h
|
#ifndef LETTER_H
#define LETTER_H
#include <stdint.h>
#include "Converter.h"
#include "Segment.h"
/**Represents a sixteen segment single letter, it looks like this
# 0 1 2 3 4 5 6
#
# --- 0 --- --- 1 --- 0
# |\ | /|
# | \ | / | 1
# | \ | / |
# | \ | / | 2
# 7 8 11 12 2
# | \ | / | 3
# | \ | / |
# | \ | / | 4
# | \|/ |
# -- 14 --- --- 15 -- 5
# | /|\ |
# | / | \ | 6
# | / | \ |
# | / | \ | 7
# 6 13 10 9 3
# | / | \ | 8
# | / | \ |
# | / | \ | 9
# |/ | \|
# --- 5 --- --- 4 --- 10
#
# NOTE: These are the segment numbers
*/
#define NUM_2_PIXEL 10
#define NUM_4_PIXEL 6
#define LETTER_PIXEL_WIDTH 8
class Letter {
public:
Letter();
void init(uint8_t letterIdx, uint8_t lengths[16]);
Segment* segment(uint8_t i);
Pixel* pixel(uint8_t i);
uint16_t pixelCount();
void toArray(CRGB array[], uint16_t &currIdx);
void setChar(char character);
void setLayer(uint8_t layer, bool isOn);
void setColor(uint8_t layer, CHSV color);
CHSV16 getHsv16(uint8_t layer);
void setHsv16(uint8_t layer, CHSV16 color);
char currentChar;
private:
uint8_t letterIdx;
void setPixelLocations();
Pixel pixels[2*NUM_2_PIXEL+4*NUM_4_PIXEL];
Segment segments[16];
};
#endif
|
bguest/Segment16Sign
|
lib/Keyboard.h
|
#ifndef KEYBOARD_H
#define KEYBOARD_H
#include "Arduino.h"
class Keyboard {
public:
Keyboard();
void init();
void run();
uint32_t data;
bool isAvailable;
};
#endif
|
bguest/Segment16Sign
|
lib/effects/RandomLetters.h
|
#ifndef RANDOM_LETTERS_H
#define RANDOM_LETTERS_H
class RandomLetters : public Effect{
public:
RandomLetters();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
private:
};
#endif
|
bguest/Segment16Sign
|
lib/effects/SolidColor.h
|
#ifndef SOLID_COLOR_H
#define SOLID_COLOR_H
#include "Effect.h"
class SolidColor : public Effect{
public:
SolidColor();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void randomize(uint8_t ci);
private:
};
#endif
|
bguest/Segment16Sign
|
lib/effects/WavePixels.h
|
#ifndef WAVE_SEGMENT_H
#define WAVE_SEGMENT_H
#include "Effect.h"
class WavePixels : public Effect{
public:
WavePixels();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void invertColors();
void randomize(uint8_t ci);
private:
uint16_t cycleTime[LAYER_COUNT];
int16_t hueA[LAYER_COUNT];
};
#endif
|
bguest/Segment16Sign
|
lib/effects/WaveXY.h
|
#ifndef WAVE_XY_H
#define WAVE_XY_H
#include "Effect.h"
class WaveXY : public Effect{
public:
WaveXY();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void randomize(uint8_t ci);
void invertColors();
private:
uint8_t freq[2][LAYER_COUNT];
int8_t step[2][LAYER_COUNT];
uint16_t offset[2][LAYER_COUNT];
bool isWaveValue;
void calculate(Pixel &pixel, uint8_t layer);
};
#endif
|
bguest/Segment16Sign
|
lib/effects/Scrolling.h
|
#ifndef SCROLLING_H
#define SCROLLING_H
#include "Effect.h"
const uint8_t SCROLL_LENGTH = 100;
class Scrolling : public Effect {
public:
Scrolling();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushInsert(char character);
bool pushChar(char character, uint8_t layer);
void randomize(uint8_t ci);
private:
void pushToBuffer(char character);
void shiftLeft();
void backspaceBuffer();
void softReset();
void setRandomLetter(char word[4]);
uint8_t numBeats;
uint8_t beatIdx;
uint8_t startIdx;
uint8_t charCount;
char buffer[SCROLL_LENGTH];
int8_t randomLetterIdx;
};
#endif
|
bguest/Segment16Sign
|
lib/EffectData.h
|
<reponame>bguest/Segment16Sign<gh_stars>0
#ifndef EFFECT_DATA_H
#define EFFECT_DATA_H
#define FREQ_COUNT 7
#include "Arduino.h"
const uint8_t UINT8_MAX_2 = UINT8_MAX/2;
struct EffectData{
uint16_t tempo;
uint8_t rolloff;
uint16_t volume;
uint16_t maxVolume;
uint16_t freqAmp[FREQ_COUNT];
uint16_t maxFreqAmp[FREQ_COUNT];
};
#endif
|
bguest/Segment16Sign
|
lib/effects/FadedXY.h
|
#ifndef FADED_XY_H
#define FADED_XY_H
#include "Effect.h"
#define FADED_XY_POINT_COUNT 4
class FadedXY : public Effect{
public:
FadedXY();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void randomize(uint8_t ci);
void invertColors();
private:
uint16_t hueOffset[LAYER_COUNT];
int16_t hueOffsetSpeed[LAYER_COUNT];
uint16_t hue[LAYER_COUNT][FADED_XY_POINT_COUNT];
int16_t hueSpeed[LAYER_COUNT][FADED_XY_POINT_COUNT];
void interpolate(Pixel &pixel, uint8_t layer);
};
#endif
|
bguest/Segment16Sign
|
lib/effects/RandomFade.h
|
<reponame>bguest/Segment16Sign
#ifndef RANDOM_FADE_H
#define RANDOM_FADE_H
#include "Effect.h"
class RandomFade : public Effect{
public:
RandomFade();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void signWasUpdated(Sign &sign);
void randomize(uint8_t ci);
private:
int16_t fadeSpeed[LAYER_COUNT];
uint16_t segHue[16*LETTERS_COUNT];
int16_t segSpeed[16*LETTERS_COUNT];
uint16_t fadeTime;
int16_t incRandomSpeed(bool isPositive, uint8_t layer);
void randomizeSpeeds();
void recalculateSpeeds(Sign &sign);
};
#endif
|
bguest/Segment16Sign
|
lib/effects/FadeTo.h
|
#ifndef FADE_TO_H
#define FADE_TO_H
#include "Effect.h"
class FadeTo : public Effect{
public:
FadeTo();
void reset();
void run(Sign &sign, EffectData &data, uint8_t layer);
bool pushChar(char character, uint8_t layer);
void randomize(uint8_t ci);
private:
uint16_t fadeTime;
uint16_t segHue[16*LETTERS_COUNT];
};
#endif
|
mdzakirhussain/try1
|
verilog/dv/la_test1/la_test1.c
|
/*
* SPDX-FileCopyrightText: 2020 Efabless 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.
* SPDX-License-Identifier: Apache-2.0
*/
// This include is relative to $CARAVEL_PATH (see Makefile)
#include "verilog/dv/caravel/defs.h"
#include "verilog/dv/caravel/stub.c"
// --------------------------------------------------------
/*
MPRJ Logic Analyzer Test:
- Observes counter value through LA probes [31:0]
- Sets counter initial value through LA probes [63:32]
- Flags when counter value exceeds 500 through the management SoC gpio
- Outputs message to the UART when the test concludes successfuly
*/
void main()
{
/* Set up the housekeeping SPI to be connected internally so */
/* that external pin changes don't affect it. */
reg_spimaster_config = 0xa002; // Enable, prescaler = 2,
// connect to housekeeping SPI
// Connect the housekeeping SPI to the SPI master
// so that the CSB line is not left floating. This allows
// all of the GPIO pins to be used for user functions.
// The upper GPIO pins are configured to be output
// and accessble to the management SoC.
// Used to flad the start/end of a test
// The lower GPIO pins are configured to be output
// and accessible to the user project. They show
// the project count value, although this test is
// designed to read the project count through the
// logic analyzer probes.
// I/O 6 is configured for the UART Tx line
reg_mprj_io_31 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_30 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_29 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_28 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_27 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_26 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_25 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_24 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_23 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_22 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_21 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_20 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_19 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_18 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_17 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_16 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_io_15 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_14 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_13 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_12 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_11 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_10 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_9 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_8 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_7 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_5 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_4 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_3 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_2 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_1 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_0 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_6 = GPIO_MODE_MGMT_STD_OUTPUT;
// Set UART clock to 64 kbaud (enable before I/O configuration)
reg_uart_clkdiv = 625;
reg_uart_enable = 1;
/* Apply configuration */
reg_mprj_xfer = 1;
while (reg_mprj_xfer == 1);
// Configure LA probes [31:0], [127:64] as inputs to the cpu
// Configure LA probes [63:32] as outputs from the cpu
reg_la0_oenb = reg_la0_iena = 0xFFFFFFFF; // [31:0]
reg_la1_oenb = reg_la1_iena = 0x00000000; // [63:32]
reg_la2_oenb = reg_la2_iena = 0xFFFFFFFF; // [95:64]
reg_la3_oenb = reg_la3_iena = 0xFFFFFFFF; // [127:96]
// Flag start of the test
reg_mprj_datal = 0xAB400000;
// Set Counter value to zero through LA probes [63:32]
reg_la1_data = 0x00000000;
// Configure LA probes from [63:32] as inputs to disable counter write
reg_la1_oenb = reg_la1_iena = 0xFFFFFFFF;
while (1) {
if (reg_la0_data > 0x1F4) {
reg_mprj_datal = 0xAB410000;
break;
}
}
print("\n");
print("Monitor: Test 2 Passed\n\n"); // Makes simulation very long!
reg_mprj_datal = 0xAB510000;
}
|
szkzn/poc-cve-2021-4034
|
payload/payload.c
|
<reponame>szkzn/poc-cve-2021-4034
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
// build with gcc payload.c -o payload.so -shared -fPIC
void gconv() {}
void gconv_init() {
setuid(0);
setgid(0);
setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
char* argv[] = { "/bin/sh", NULL };
char* envp[] = { "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", NULL };
system("/usr/bin/rm -r gconv");
system("/usr/bin/rm -r \"GCONV_PATH=.\"");
fprintf(stdout, "Spawning root shell!\n");
if (execve("/bin/sh", argv, envp) == -1)
perror("Could not execve :( ");
}
|
Dish1306/reportlab-mirror
|
src/rl_addons/renderPM/gt1/gt1-namecontext.c
|
/* A module for a simple "name context", i.e. lisp-style atoms */
#include "gt1-misc.h"
#include "gt1-namecontext.h"
#if defined(_WIN32) || defined(macintosh) || defined(__APPLE__)
# include <string.h>
#endif
/* btw, I do not know who wrote the following comment. I modified this
file somewhat from gimp's app/procedural_db.c hash function. */
/* I have seen something like that in Perl/TK. --MW */
static unsigned int
gt1_name_context_hash_func (const char *string)
{
unsigned int result;
int c;
int i;
/*
* I tried a zillion different hash functions and asked many other
* people for advice. Many people had their own favorite functions,
* all different, but no-one had much idea why they were good ones.
* I chose the one below (multiply by 9 and add new character)
* because of the following reasons:
*
* 1. Multiplying by 10 is perfect for keys that are decimal strings,
* and multiplying by 9 is just about as good.
* 2. Times-9 is (shift-left-3) plus (old). This means that each
* character's bits hang around in the low-order bits of the
* hash value for ever, plus they spread fairly rapidly up to
* the high-order bits to fill out the hash value. This seems
* works well both for decimal and non-decimal strings.
*
* tclHash.c --
*
* Implementation of in-memory hash tables for Tcl and Tcl-based
* applications.
*
* Copyright (c) 1991-1993 The Regents of the University of California.
* Copyright (c) 1994 Sun Microsystems, Inc.
*/
result = 0;
for (i = 0; (c = ((const unsigned char *)string)[i]) != '\0'; i++)
result += (result << 3) + c;
return result;
}
static unsigned int
gt1_name_context_hash_func_size (const char *string, int size)
{
unsigned int result;
int i;
result = 0;
for (i = 0; i < size; i++)
result += (result << 3) + ((const unsigned char *)string)[i];
return result;
}
Gt1NameContext *
gt1_name_context_new (void)
{
Gt1NameContext *nc;
int i;
nc = gt1_new (Gt1NameContext, 1);
nc->num_entries = 0;
nc->table_size = 16;
nc->table = gt1_new (Gt1NameContextHashEntry, nc->table_size);
for (i = 0; i < nc->table_size; i++)
nc->table[i].name = NULL;
return nc;
}
void
gt1_name_context_free (Gt1NameContext *nc)
{
int i;
for (i = 0; i < nc->table_size; i++)
if (nc->table[i].name != NULL)
gt1_free (nc->table[i].name);
gt1_free (nc->table);
gt1_free (nc);
}
static char *
gt1_name_context_strdup (const char *s)
{
int len;
char *new;
len = strlen (s);
new = gt1_new (char, len + 1);
memcpy (new, s, len);
new[len] = '\0';
return new;
}
static gt1_boolean
gt1_name_context_streq_size (const char *s1, const char *s2, int size2)
{
int i;
/* could rewrite for 32 bits at a time, but I wouldn't worry */
for (i = 0; i < size2; i++)
if (s1[i] != s2[i])
return gt1_false;
return s1[i] == 0;
}
static char *
gt1_name_context_strdup_size (const char *s, int size)
{
char *new;
new = gt1_new (char, size + 1);
memcpy (new, s, size);
new[size] = '\0';
return new;
}
/* double the size of the hash table, rehashing as needed */
static void
gt1_name_context_double (Gt1NameContext *nc)
{
int i, j;
int oldsize, newmask;
Gt1NameContextHashEntry *old_table, *new_table;
oldsize = nc->table_size;
old_table = nc->table;
nc->table_size = oldsize << 1;
newmask = nc->table_size - 1;
new_table = gt1_new (Gt1NameContextHashEntry, nc->table_size);
for (j = 0; j < nc->table_size; j++)
new_table[j].name = NULL;
for (i = 0; i < oldsize; i++)
{
if (old_table[i].name)
{
for (j = gt1_name_context_hash_func(old_table[i].name);
new_table[j & newmask].name;
j++);
new_table[j & newmask] = old_table[i];
}
}
gt1_free (old_table);
nc->table = new_table;
}
/* Return the unique (to this name context) Gt1NameId for the given string,
allocating a new one if necessary. */
Gt1NameId
gt1_name_context_intern (Gt1NameContext *nc, const char *name)
{
int i;
int mask;
mask = nc->table_size - 1;
for (i = gt1_name_context_hash_func (name); nc->table[i & mask].name; i++)
if (!strcmp (nc->table[i & mask].name, name))
return nc->table[i & mask].Gt1NameId;
/* not found, allocate a new one */
if (nc->num_entries >= nc->table_size >> 1)
{
gt1_name_context_double (nc);
mask = nc->table_size - 1;
for (i = gt1_name_context_hash_func (name); nc->table[i & mask].name; i++);
}
i &= mask;
nc->table[i].name = gt1_name_context_strdup (name);
nc->table[i].Gt1NameId = nc->num_entries;
return nc->num_entries++;
}
/* Return the unique (to this name context) Gt1NameId for the given string,
return GT1_UNKNOWN if not found*/
Gt1NameId gt1_name_context_interned (Gt1NameContext *nc, const char *name)
{
int i;
int mask;
mask = nc->table_size - 1;
for (i = gt1_name_context_hash_func (name); nc->table[i & mask].name; i++)
if (!strcmp (nc->table[i & mask].name, name))
return nc->table[i & mask].Gt1NameId;
return GT1_UNKNOWN;
}
/* Return the unique (to this name context) Gt1NameId for the given
string, allocating a new one if necessary. The string is not
necessarily null-terminated; the size is given explicitly. */
Gt1NameId
gt1_name_context_intern_size (Gt1NameContext *nc, const char *name, int size)
{
int i;
int mask;
mask = nc->table_size - 1;
for (i = gt1_name_context_hash_func_size (name, size);
nc->table[i & mask].name;
i++)
if (gt1_name_context_streq_size (nc->table[i & mask].name, name, size))
return nc->table[i & mask].Gt1NameId;
/* not found, allocate a new one */
if (nc->num_entries >= nc->table_size >> 1)
{
gt1_name_context_double (nc);
mask = nc->table_size - 1;
for (i = gt1_name_context_hash_func_size (name, size);
nc->table[i & mask].name;
i++);
}
i &= mask;
nc->table[i].name = gt1_name_context_strdup_size (name, size);
nc->table[i].Gt1NameId = nc->num_entries;
return nc->num_entries++;
}
/* This one is slow - it's intended for debugging only */
char *
gt1_name_context_string (Gt1NameContext *nc, Gt1NameId Gt1NameId)
{
int j;
for (j = 0; j < nc->table_size; j++)
if (nc->table[j].name && nc->table[j].Gt1NameId == Gt1NameId)
return nc->table[j].name;
return NULL;
}
|
Dish1306/reportlab-mirror
|
src/rl_addons/renderPM/gt1/gt1-misc.h
|
/* What allocation functions are we going to use? */
#ifndef __GT1_MISC_H__
#define __GT1_MISC_H__
#include <stdlib.h> /* for malloc, etc. */
#if defined(macintosh) || defined(__APPLE__) || defined (__linux__) || defined(__FreeBSD_kernel__) || defined(__GNU__)
# include <string.h> /* for memcpy() */
#endif
#define gt1_alloc malloc
#define gt1_free free
#define gt1_realloc realloc
/* These aren't, strictly speaking, configuration macros, but they're
damn handy to have around, and may be worth playing with for
debugging. */
#define gt1_new(type, n) ((type *)gt1_alloc ((n) * sizeof(type)))
#define gt1_renew(p, type, n) ((type *)gt1_realloc (p, (n) * sizeof(type)))
/* This one must be used carefully - in particular, p and max should
be variables. They can also be pstruct->el lvalues. */
#define gt1_double(p, type, max) p = gt1_renew (p, type, max <<= 1)
typedef int gt1_boolean;
#define gt1_false 0
#define gt1_true 1
typedef unsigned char uchar;
/* define pi */
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif /* M_PI */
void
gt1_die (const char *fmt, ...);
#endif /* __GT1_MISC_H__ */
|
UnofficialJuliaMirror/SDE.jl-0d6d677f-8475-5ebf-bbf8-769304748c2b
|
deps/sigma.c
|
<reponame>UnofficialJuliaMirror/SDE.jl-0d6d677f-8475-5ebf-bbf8-769304748c2b
#include <math.h>
#include <stdio.h>
int maxi(int x, int y)
{
return (x > y ? x : y);
}
int mini(int x, int y)
{
return (x < y ? x : y);
}
double hat(double x)
{
double z = 1.-fabs(2.*x-1.); /* (1 -|2x-1|)+ */
return z > 0.0 ? z : 0.0;
}
double sq(double x)
{
return x*x;
}
void fe_mu(double *mu, double *y, int N, int L)
{
int n = 1<<(L-1);
int t;
int i;
for (i = 1; i < n - 1; i++)
{
mu[2*i-2] = mu[2*i-1] = 0.;
for (t = 0; t < N-1; t++)
{
mu[2*i-2] += hat(y[t]*n-i + 1)*(y[t+1]-y[t]);
mu[2*i-1] += hat(y[t]*n-i +.5)*(y[t+1]-y[t]);
}
}
mu[2*n-2] = 0.;
for (t = 0; t < N-1; t++) mu[2*n-2] += hat(y[t]*n-n+1)*(y[t+1]-y[t]);
}
void fe_mu_at(double *mu, double *y, int N, int L)
{
int n = 1<<(L-1);
int t;
int i,j ;
double yn;
for (t = 0; t < N-1; t++)
{
/* find both hat functions with y[t] in support */
yn = y[t]*(double) n;
i = maxi(mini(((int) ceil(yn)), n), 1);
j = maxi(mini(((int) ceil(yn-0.5)), n-1), 1);
/* only those components of mu are affected */
mu[2*i-2] += hat(y[t]*n-i + 1)*(y[t+1]-y[t]);
mu[2*j-1] += hat(y[t]*n-j +.5)*(y[t+1]-y[t]);
}
}
void fe_SigmaB2_at(double *S, double *y, int N, double dt, int L)
{
int n = 1<<(L-1);
int K = 1;
int d = 2*n - 1 + K;
int t;
int i, j;
double yn;
printf("L: %i\n", L);
printf("n: %i\n", n);
printf("d: %i\n", d);
printf("N: %i\n", N);
printf("dt: %f\n", dt);
double a, b, c;
for (t = 0; t < N; t++)
{
yn = y[t]*(double) n;
i = maxi(mini(((int) ceil(yn)), n), 1);
j = maxi(mini(((int) ceil(yn-0.5)), n-1), 1);
a = sq(hat(yn-i + 1)) * dt;
b = sq(hat(yn-j + 0.5)) * dt;
c = hat(yn-i + 1) * hat(yn-j + 0.5) * dt;
if (t < 10) printf("%5.3f(%i, %i), %5.6f %5.6f %5.6f \n", yn, i, j, a,b,c);
S[(2*i-2)*d + 2*i-2] += a;
S[(2*j-1)*d + 2*j-1] += b;
S[(2*i-2)*d + 2*j-1] = S[(2*j-1)*d + 2*i-2] += c;
S[(d-1)*d + 2*j-1] = S[(2*j-1)*d + d - 1] += hat(yn-j + 0.5) * dt;
S[(d-1)*d + 2*i-2] = S[(2*i-2)*d + d - 1] += hat(yn-i + 1) * dt;
}
S[d*d - 1] = N * dt;
for (i = 0; i < d*d; i++)
{
printf(" %10.3f", S[i]);
if(i % d == d-1) printf("\n");
}
printf("\n");
}
void fe_SigmaB1_at(double *S, double *y, int N, double dt, int L)
{
int n = 1<<(L-1);
int K = 1;
int d = 2*n - 1 + K;
int t;
int i, j;
double yn;
for (t = 0; t < N; t++)
{
yn = y[t]*(double) n;
i = maxi(mini(((int) ceil(yn)), n), 1);
j = maxi(mini(((int) ceil(yn-0.5)), n-1), 1);
S[(2*i-2)*d + 2*i-2] += sq(hat(yn-i + 1)) * dt;
S[(2*j-1)*d + 2*j-1] += sq(hat(yn-j + 0.5)) * dt;
S[(2*i-2)*d + 2*j-1] = S[(2*j-1)*d + 2*i-2] += hat(yn-i + 1) * hat(yn-j + 0.5) * dt;
S[(d-1)*d + 2*j-1] = S[(2*j-1)*d + d - 1] += hat(yn-j + 0.5) * dt;
S[(d-1)*d + 2*i-2] = S[(2*i-2)*d + d - 1] += hat(yn-i + 1) * dt;
}
S[d*d - 1] = N * dt;
}
void fe_Sigma_at(double *S, double *y, int N, double dt, int L)
{
int n = 1<<(L-1);
int d = 2*n - 1;
int t;
int i, j;
double yn;
double a, b, c;
for (t = 0; t < N; t++)
{
yn = y[t]*(double) n;
i = maxi(mini(((int) ceil(yn)), n), 1);
j = maxi(mini(((int) ceil(yn-0.5)), n-1), 1);
a = sq(hat(yn-i + 1)) * dt;
b = sq(hat(yn-j + 0.5)) * dt;
c = hat(yn-i + 1) * hat(yn-j + 0.5) * dt;
S[(2*i-2)*d + 2*i-2] += a;
S[(2*j-1)*d + 2*j-1] += b;
S[(2*i-2)*d + 2*j-1] = S[(2*j-1)*d + 2*i-2] += c;
}
}
/*
yn = y[t]*n
i = clamp(ceil(yn), 1, n)
j = clamp(ceil(yn-0.5), 1, n-1)
S[2i-1, 2i-1] += ((hat(yn-i + 1).^2))*dt
S[2j, 2j] += ((hat(yn-j + 0.5).^2))*dt
S[2i-1, 2j] = S[2j, 2i-1] += (hat(yn-i + 1).*hat(yn-j + 0.5))*dt
*/
|
mungurk/binlex
|
src/decompiler.h
|
#include <elf.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <capstone/capstone.h>
#ifndef DECOMPILER_H
#define DECOMPILER_H
#define DECOMPILER_TYPE_FUNCS 0
#define DECOMPILER_TYPE_BLCKS 1
#define DECOMPILER_TYPE_UNSET 2
#define DECOMPILER_TYPE_ALL 3
#define DECOMPILER_MAX_SECTIONS 256
class Decompiler{
private:
csh cs_handle;
char *temp = NULL;
struct Section {
char *function_traits;
char *block_traits;
};
char * hexdump_le(const void *data, int size){
int buffer_size = size * 2 + size;
char *buffer0 = (char *)malloc(buffer_size);
memset((void *)buffer0, 0, buffer_size);
const unsigned char * pc = (const unsigned char *)data;
int count = 0;
for (int i = size - 1; i >= 0; i--){
if (count == 0){
sprintf(buffer0, "%s%02x", buffer0, pc[i]);
} else {
sprintf(buffer0, "%s %02x", buffer0, pc[i]);
}
count++;
}
return buffer0;
}
char * hexdump_be(const void *data, int size){
int buffer_size = size * 2 + size;
char *buffer0 = (char *)malloc(buffer_size);
memset((void *)buffer0, 0, buffer_size);
const unsigned char * pc = (const unsigned char *)data;
int count = 0;
for (int i = 0; i < size; i++){
if (count == 0){
sprintf(buffer0, "%s%02x", buffer0, pc[i]);
} else {
sprintf(buffer0, "%s %02x", buffer0, pc[i]);
}
count++;
}
return buffer0;
}
char * wildcard_bytes(char *str, char *wild){
char wildcard[] = "??";
char *offset = strstr(str, wild);
if (offset != 0){
for (int i = 0; i < strlen(wild);){
memcpy(offset + i, &wildcard, 2);
i = i + 3;
}
}
return offset;
}
void wildcard_null(char *bytes){
char wildcard[] = "??";
char *buffer0 = (char *)malloc(3);
memset(buffer0, 0, 3);
for (int i = strlen(bytes) + 1; i >= 0;){
i = i - 3;
if (i < 0){
break;
}
memcpy(buffer0, bytes + i, 2);
if (strcmp(buffer0, (char *)"00") == 0){
memcpy(bytes + i, &wildcard, 2);
} else {
break;
}
}
free(buffer0);
}
char * hexdump_mem_disp(long int disp){
int size = sizeof(disp) * 2 + sizeof(disp);
char *buffer0 = (char *)malloc(size);
memset((void *)buffer0, 0, size);
const unsigned char * pc = (const unsigned char *)&disp;
int count = 0;
for (int i = 0; i < sizeof(disp) -1 ; i++){
if (pc[i] != 0 && pc[i] != 255){
if (count == 0){
sprintf(buffer0, "%s%02x", buffer0, pc[i]);
} else {
sprintf(buffer0, "%s %02x", buffer0, pc[i]);
}
count++;
}
}
return buffer0;
}
char * hexdump_mem_disp_rev(void *disp, int size){
//int size = sizeof(disp) * 2 + sizeof(disp);
char *buffer0 = (char *)malloc(size);
memset((void *)buffer0, 0, size);
const unsigned char * pc = (const unsigned char *)&disp;
int count = 0;
for (int i = 0; i < size -1 ; i++){
if (pc[i] != 0 && pc[i] != 255){
if (count == 0){
sprintf(buffer0, "%s%02x", buffer0, pc[i]);
} else {
sprintf(buffer0, "%s %02x", buffer0, pc[i]);
}
count++;
}
}
return buffer0;
}
void SetSectionsDefault(){
for (int i = 0; i < DECOMPILER_MAX_SECTIONS; i++){
sections[i].function_traits = NULL;
sections[i].block_traits = NULL;
}
}
public:
struct Section sections[DECOMPILER_MAX_SECTIONS];
Decompiler(){
SetSectionsDefault();
}
void Setup(cs_arch arch, cs_mode mode){
assert(cs_open(arch, mode, &cs_handle) == CS_ERR_OK);
cs_option(cs_handle, CS_OPT_DETAIL, CS_OPT_ON);
//cs_option(cs_handle, CS_OPT_SKIPDATA, CS_OPT_ON);
}
int x86_64_0(int decompiler_type, void *data, int data_size, int section_index){
cs_insn *insn;
char *disp = NULL;
char *bytes = NULL;
int offset;
size_t count;
int op_mem_disp_size;
char *buffer0;
int count_rev;
const unsigned char * pc;
void *op_disp = NULL;
temp = (char *)malloc(data_size * 2 + data_size + 1);
memset((void *)temp, 0, data_size * 2 + data_size);
count = cs_disasm(cs_handle, (const uint8_t *)data, data_size, 0x0, 0, &insn);
if (count > 0) {
size_t j;
for (j = 0; j < count; j++) {
bytes = hexdump_be(insn[j].bytes, insn[j].size);
for (int k = 0; k < insn[j].detail->x86.op_count; k++) {
cs_x86_op *op = &(insn[j].detail->x86.operands[k]);
switch((int)op->type) {
case X86_OP_MEM:
if (op->mem.disp != 0)
disp = hexdump_mem_disp(op->mem.disp);
op_mem_disp_size = sizeof(op->mem.disp) * 2 + sizeof(op->mem.disp);
buffer0 = (char *)malloc(op_mem_disp_size);
memset((void *)buffer0, 0, op_mem_disp_size);
pc = (const unsigned char *)&op->mem.disp;
count_rev = 0;
for (int i = 0; i < sizeof(disp) -1 ; i++){
if (pc[i] != 0 && pc[i] != 255){
if (count_rev == 0){
sprintf(buffer0, "%s%02x", buffer0, pc[i]);
} else {
sprintf(buffer0, "%s %02x", buffer0, pc[i]);
}
count_rev++;
}
}
wildcard_bytes(bytes, buffer0);
free(buffer0);
break;
default:
break;
}
}
wildcard_null(bytes);
if (decompiler_type == DECOMPILER_TYPE_FUNCS &&
insn[j].id == X86_INS_RET){
sprintf(temp + strlen(temp), "%s\n", bytes);
//printf("%s\n", bytes);
} else if (decompiler_type == DECOMPILER_TYPE_BLCKS &&
(insn[j].id == X86_INS_JMP ||
insn[j].id == X86_INS_JNE ||
insn[j].id == X86_INS_JNO ||
insn[j].id == X86_INS_JNP ||
insn[j].id == X86_INS_JL ||
insn[j].id == X86_INS_JLE ||
insn[j].id == X86_INS_JG ||
insn[j].id == X86_INS_JGE ||
insn[j].id == X86_INS_JE ||
insn[j].id == X86_INS_JECXZ ||
insn[j].id == X86_INS_JCXZ ||
insn[j].id == X86_INS_JB ||
insn[j].id == X86_INS_JBE ||
insn[j].id == X86_INS_JA ||
insn[j].id == X86_INS_JAE ||
insn[j].id == X86_INS_JNS ||
insn[j].id == X86_INS_JO ||
insn[j].id == X86_INS_JP ||
insn[j].id == X86_INS_JRCXZ ||
insn[j].id == X86_INS_JS)){
sprintf(temp + strlen(temp), "%s\n", bytes);
//printf("%s\n", bytes);
} else {
if (j + 1 >= count){
sprintf(temp + strlen(temp), "%s\n", bytes);
//printf("%s\n", bytes);
} else {
sprintf(temp + strlen(temp), "%s ", bytes);
//printf("%s ", bytes);
}
}
free(bytes);
if (j == count - 1){
offset = insn[j].address + insn[j].size;
}
}
cs_free(insn, count);
}
if (decompiler_type == DECOMPILER_TYPE_FUNCS){
if (sections[section_index].function_traits == NULL){
sections[section_index].function_traits = (char *)malloc(data_size * 2 + data_size + 1);
memset((void *)sections[section_index].function_traits, 0, data_size * 2 + data_size + 1);
}
if (strlen(sections[section_index].function_traits) == 0){
sprintf(sections[section_index].function_traits, "%s", temp);
} else {
sprintf(sections[section_index].function_traits, "%s%s", sections[section_index].function_traits, temp);
}
}
if (decompiler_type == DECOMPILER_TYPE_BLCKS){
if (sections[section_index].block_traits == NULL){
sections[section_index].block_traits = (char *)malloc(data_size * 2 + data_size + 1);
memset((void *)sections[section_index].block_traits, 0, data_size * 2 + data_size + 1);
}
if (strlen(sections[section_index].block_traits) == 0){
sprintf(sections[section_index].block_traits, "%s", temp);
} else {
sprintf(sections[section_index].block_traits, "%s%s", sections[section_index].block_traits, temp);
}
}
free(temp);
return offset;
}
void x86_64(int decompiler_type, void *data, int data_size, int section_index){
// This is a hack should be in the x86_64_0 function as recursion, this fix works for now on emotet sample
int offset = x86_64_0(decompiler_type, data, data_size, section_index);
for(;;) {
if (offset < data_size){
offset = offset + x86_64_0(decompiler_type, data + offset, data_size - offset, section_index);
} else {
break;
}
}
}
void PrintTraits(int type){
for (int i = 0; i < DECOMPILER_MAX_SECTIONS; i++){
switch(type){
case DECOMPILER_TYPE_FUNCS:
if (sections[i].function_traits != NULL){
printf("%s", sections[i].function_traits);
}
break;
case DECOMPILER_TYPE_BLCKS:
if (sections[i].block_traits != NULL){
printf("%s", sections[i].block_traits);
}
break;
case DECOMPILER_TYPE_ALL:
if (sections[i].function_traits != NULL){
printf("%s", sections[i].function_traits);
}
if (sections[i].block_traits != NULL){
printf("%s", sections[i].block_traits);
}
break;
default:
break;
}
}
}
void WriteTraits(char *file_path){
FILE *fd = fopen(file_path, "w");
for (int i = 0; i < DECOMPILER_MAX_SECTIONS; i++){
if (sections[i].function_traits != NULL){
fwrite(sections[i].function_traits, sizeof(char), strlen(sections[i].function_traits), fd);
}
if (sections[i].block_traits != NULL){
fwrite(sections[i].block_traits, sizeof(char), strlen(sections[i].block_traits), fd);
}
}
fclose(fd);
}
~Decompiler(){
cs_close(&cs_handle);
for (int i = 0; i < DECOMPILER_MAX_SECTIONS; i++){
if (sections[i].function_traits != NULL){
free(sections[i].function_traits);
}
if (sections[i].block_traits != NULL){
free(sections[i].block_traits);
}
}
SetSectionsDefault();
}
};
#endif
|
loki-project/loki-storage-server
|
httpserver/omq_server.h
|
<reponame>loki-project/loki-storage-server
#pragma once
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include <oxenmq/oxenmq.h>
#include <nlohmann/json_fwd.hpp>
#include "oxenmq/bt_serialize.h"
#include "sn_record.h"
namespace oxen {
class ServiceNode;
class RequestHandler;
class RateLimiter;
struct Response;
struct OnionRequestMetadata;
void omq_logger(oxenmq::LogLevel level, const char* file, int line,
std::string message);
oxenmq::bt_value json_to_bt(nlohmann::json j);
nlohmann::json bt_to_json(oxenmq::bt_dict_consumer d);
nlohmann::json bt_to_json(oxenmq::bt_list_consumer l);
class OxenmqServer {
oxenmq::OxenMQ omq_;
oxenmq::ConnectionID oxend_conn_;
// Has information about current SNs
ServiceNode* service_node_ = nullptr;
RequestHandler* request_handler_ = nullptr;
RateLimiter* rate_limiter_ = nullptr;
// Get node's address
std::string peer_lookup(std::string_view pubkey_bin) const;
// Handle Session data coming from peer SN
void handle_sn_data(oxenmq::Message& message);
// Called starting at HF18 for SS-to-SS onion requests
void handle_onion_request(oxenmq::Message& message);
// Handles a decoded onion request
void handle_onion_request(
std::string_view payload,
OnionRequestMetadata&& data,
oxenmq::Message::DeferredSend send);
// sn.ping - sent by SNs to ping each other.
void handle_ping(oxenmq::Message& message);
// sn.storage_test
void handle_storage_test(oxenmq::Message& message);
/// storage.(whatever) -- client request handling. These reply with [BODY] on success or [CODE,
/// BODY] on failure (where BODY typically is some sort of error message).
///
/// The return value is either:
/// [VALUE] for a successful response
/// [ERRCODE, VALUE] for a failure.
///
/// Successful responses will generally return VALUE as json, if the request was json (or
/// empty), or a bt-encoded dict if the request was bt-encoded. Note that base64-encoded values
/// for json responses are raw byte values (*not* base64-encoded) when returning a bt-encoded
/// value.
///
/// Failure responses are an HTTP error number and a plain text failure string.
///
/// `forwarded` is set if this request was forwarded from another swarm member rather than being
/// direct from the client; the request is handled identically except that these forwarded
/// requests are not-reforwarded again, and the method name is prepended on the argument list.
void handle_client_request(std::string_view method, oxenmq::Message& message, bool forwarded = false);
void handle_get_logs(oxenmq::Message& message);
void handle_get_stats(oxenmq::Message& message);
// Access pubkeys for the 'service' command category (for access stats & logs), in binary.
std::unordered_set<std::string> stats_access_keys_;
// Connects (and blocks until connected) to oxend. When this returns an oxend connection will
// be available (and oxend_conn_ will be set to the connection id to reach it).
void connect_oxend(const oxenmq::address& oxend_rpc);
public:
OxenmqServer(
const sn_record& me,
const x25519_seckey& privkey,
const std::vector<x25519_pubkey>& stats_access_keys_hex);
// Initialize oxenmq; return a future that completes once we have connected to and initialized
// from oxend.
void init(ServiceNode* sn, RequestHandler* rh, RateLimiter* rl, oxenmq::address oxend_rpc);
/// Dereferencing via * or -> accesses the contained OxenMQ instance.
oxenmq::OxenMQ& operator*() { return omq_; }
oxenmq::OxenMQ* operator->() { return &omq_; }
// Returns the OMQ ConnectionID for the connection to oxend.
const oxenmq::ConnectionID& oxend_conn() const { return oxend_conn_; }
// Invokes a request to the local oxend; given arguments (which must contain at least the
// request name and a callback) are forwarded as `omq.request(connid, ...)`.
template <typename... Args>
void oxend_request(Args&&... args) {
assert(oxend_conn_);
omq_.request(oxend_conn(), std::forward<Args>(args)...);
}
// Sends a one-way message to the local oxend; arguments are forwarded as `omq.send(connid,
// ...)` (and must contain at least a command name).
template <typename... Args>
void oxend_send(Args&&... args) {
assert(oxend_conn_);
omq_.send(oxend_conn(), std::forward<Args>(args)...);
}
// Encodes the onion request data that we send for internal SN-to-SN onion requests starting at
// HF18.
static std::string encode_onion_data(std::string_view payload, const OnionRequestMetadata& data);
// Decodes onion request data; throws if invalid formatted or missing required fields.
static std::pair<std::string_view, OnionRequestMetadata> decode_onion_data(std::string_view data);
using rpc_map = std::unordered_map<
std::string_view,
std::function<void(RequestHandler&, std::string_view params, bool recurse, std::function<void(Response)>)>
>;
static const rpc_map client_rpc_endpoints;
};
} // namespace oxen
|
loki-project/loki-storage-server
|
httpserver/request_handler.h
|
#pragma once
#include "channel_encryption.hpp"
#include "client_rpc_endpoints.h"
#include "http.h"
#include "onion_processing.h"
#include "oxen_common.h"
#include "oxend_key.h"
#include "service_node.h"
#include "string_utils.hpp"
#include <chrono>
#include <forward_list>
#include <future>
#include <string>
#include <string_view>
#include <type_traits>
#include <nlohmann/json_fwd.hpp>
#include <variant>
namespace oxen {
// When a storage test returns a "retry" response, we retry again after this interval:
inline constexpr auto TEST_RETRY_INTERVAL = 50ms;
// If a storage test is still returning "retry" after this long since the initial request then we
// give up and send an error response back to the requestor:
inline constexpr auto TEST_RETRY_PERIOD = 55s;
// Minimum and maximum TTL permitted for a message storage request
inline constexpr auto TTL_MINIMUM = 10s;
inline constexpr auto TTL_MAXIMUM = 14 * 24h;
// Tolerance for store requests: we don't allow stores with a timestamp more than this into the
// future, and don't allow stores with an expiry in the past by more than this amount.
inline constexpr auto STORE_TOLERANCE = 10s;
// Tolerance for timestamp-dependent, signed requests (such as `delete_all`); we accept the initial
// request if within SIGNATURE_TOLERANCE of now, and accept a recursive request if within
// SIGNATURE_TOLERANCE_FORWARDED (generally slightly larger to account for swarm forwarding
// latency).
inline constexpr auto SIGNATURE_TOLERANCE = 60s;
inline constexpr auto SIGNATURE_TOLERANCE_FORWARDED = 70s;
// Simpler wrapper that works for most of our responses
struct Response {
http::response_code status = http::OK;
std::variant<std::string, std::string_view, nlohmann::json> body;
std::vector<std::pair<std::string, std::string>> headers;
};
// Views the string or string_view body inside a Response. Should only be called when the body has
// already been verified to not contain a json object.
inline std::string_view view_body(const Response& r) {
assert(!std::holds_alternative<nlohmann::json>(r.body));
if (auto* sv = std::get_if<std::string_view>(&r.body))
return *sv;
if (auto* s = std::get_if<std::string>(&r.body))
return *s;
return "(internal error)"sv;
}
std::string to_string(const Response& res);
namespace detail {
// detail::to_hashable takes either an integral type, system_clock::time_point, or a string type and
// converts it to a string_view by writing an integer value (using std::to_chars) into the buffer
// space (which should be at least 20 bytes), and returning a string_view into the written buffer
// space. For strings/string_views the string_view is returned directly from the argument.
// system_clock::time_points are converted into integral milliseconds since epoch then treated as an
// integer value.
template <typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>
std::string_view to_hashable(const T& val, char*& buffer) {
auto [p, ec] = std::to_chars(buffer, buffer+20, val);
std::string_view s(buffer, p-buffer);
buffer = p;
return s;
}
inline std::string_view to_hashable(const std::chrono::system_clock::time_point& val, char*& buffer) {
return to_hashable(std::chrono::duration_cast<std::chrono::milliseconds>(val.time_since_epoch()).count(), buffer);
}
template <typename T, std::enable_if_t<std::is_convertible_v<T, std::string_view>, int> = 0>
std::string_view to_hashable(const T& value, char*&) {
return value;
}
}
/// Compute a hash from the given strings, concatenated together.
std::string compute_hash_blake2b_b64(std::vector<std::string_view> parts);
std::string compute_hash_sha512_hex(std::vector<std::string_view> parts);
/// Computes a message hash based on its constituent parts. Takes a function (which accepts a
/// container of string_views) and any number of std::string, std::string_view, system_clock values,
/// or integer values. Strings are concatenated; integers are converted to strings via
/// std::to_chars; clock values are treated as integer milliseconds-since-unix-epoch values.
template <typename Func, typename... T>
std::string compute_hash(Func hasher, const T&... args) {
// Allocate a buffer of 20 bytes per integral value (which is the largest the any integral value
// can be when stringified).
std::array<char, (0 + ... + (std::is_integral_v<T> ||
std::is_same_v<T, std::chrono::system_clock::time_point> ? 20 : 0))> buffer;
auto* b = buffer.data();
return hasher({detail::to_hashable(args, b)...});
}
/// Computes a message hash using either the "new" (post-2.2) or "old" formats, which are blake2b
/// and sha512 of the messages attributes (which differ a little between new/old).
std::string computeMessageHash(
std::chrono::system_clock::time_point timestamp,
std::chrono::system_clock::time_point expiry,
const user_pubkey_t& pubkey,
std::string_view data,
bool old);
struct OnionRequestMetadata {
x25519_pubkey ephem_key;
std::function<void(Response)> cb;
int hop_no = 0;
EncryptType enc_type = EncryptType::aes_gcm;
};
class RequestHandler {
ServiceNode& service_node_;
const ChannelEncryption& channel_cipher_;
const ed25519_seckey ed25519_sk_;
std::forward_list<std::future<void>> pending_proxy_requests_;
// Wrap response `res` to an intermediate node
Response wrap_proxy_response(
Response res,
const x25519_pubkey& client_key,
EncryptType enc_type,
bool json = false,
bool base64 = true) const;
// Return the correct swarm for `pubKey`
Response handle_wrong_swarm(const user_pubkey_t& pubKey);
// ===== Session Client Requests =====
// Similar to `handle_wrong_swarm`; but used when the swarm is requested
// explicitly
Response process_snodes_by_pk(const nlohmann::json& params) const;
// Save the message and relay the swarm
Response process_store(const nlohmann::json& params);
// Query the database and return requested messages
Response process_retrieve(const nlohmann::json& params);
// ===================================
public:
RequestHandler(ServiceNode& sn, const ChannelEncryption& ce, ed25519_seckey ed_sk);
// Handlers for parsed client requests
void process_client_req(rpc::store&& req, std::function<void(Response)> cb);
void process_client_req(rpc::retrieve&& req, std::function<void(Response)> cb);
void process_client_req(rpc::get_swarm&& req, std::function<void(Response)> cb);
void process_client_req(rpc::oxend_request&& req, std::function<void(Response)> cb);
void process_client_req(rpc::info&&, std::function<void(Response)> cb);
void process_client_req(rpc::delete_all&&, std::function<void(Response)> cb);
void process_client_req(rpc::delete_msgs&&, std::function<void(Response)> cb);
void process_client_req(rpc::delete_before&&, std::function<void(Response)> cb);
void process_client_req(rpc::expire_all&&, std::function<void(Response)> cb);
void process_client_req(rpc::expire_msgs&&, std::function<void(Response)> cb);
using rpc_map = std::unordered_map<
std::string_view,
std::function<void(RequestHandler&, const nlohmann::json&, std::function<void(Response)>)>
>;
static const rpc_map client_rpc_endpoints;
// Process a client request taking encoded json to be parsed containing something like
// `{"method": "abc", "params": {"some_arg": 1}}`, dispatching to the appropriate request
// handler.
void process_client_req(std::string_view req_json, std::function<void(Response)> cb);
// Processes a pre-parsed client request taking the method name ("store", "retrieve", etc.) and
// the json params object.
void process_client_req(
std::string_view method,
nlohmann::json params,
std::function<void(Response)> cb);
// Processes a swarm test request; if it succeeds the callback is immediately invoked, otherwise
// the test is scheduled for retries for some time until it succeeds, fails, or times out, at
// which point the callback is invoked to return the result.
void process_storage_test_req(
uint64_t height,
legacy_pubkey tester,
std::string msg_hash_hex,
std::function<void(MessageTestStatus, std::string, std::chrono::steady_clock::duration)> callback);
// Forwards a request to oxend RPC. `params` should contain:
// - endpoint -- the name of the rpc endpoint; currently allowed are `ons_resolve` and
// `get_service_nodes`.
// - params -- optional dict of parameters to pass through to oxend as part of the request
//
// See oxen-core/rpc/core_rpc_server_command_defs.h for parameters to these endpoints.
//
// Returns (via the response callback) the oxend JSON object on success; on failure returns
// a failure response with a body of the error string.
void process_oxend_request(const nlohmann::json& params,
std::function<void(Response)> cb);
// Test only: retrieve all db entires
Response process_retrieve_all();
// The result will arrive asynchronously, so it needs a callback handler
void process_onion_req(std::string_view ciphertext, OnionRequestMetadata data);
private:
void process_onion_req(FinalDestinationInfo&& res, OnionRequestMetadata&& data);
void process_onion_req(RelayToNodeInfo&& res, OnionRequestMetadata&& data);
void process_onion_req(RelayToServerInfo&& res, OnionRequestMetadata&& data);
void process_onion_req(ProcessCiphertextError&& res, OnionRequestMetadata&& data);
};
} // namespace oxen
|
loki-project/loki-storage-server
|
httpserver/reachability_testing.h
|
#pragma once
#include "oxen_common.h"
#include "oxend_key.h"
#include "sn_record.h"
#include <chrono>
#include <queue>
#include <random>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace oxen {
namespace detail {
// Returns std::greater on the std::get<N>(v)th element value.
template <typename T, size_t N>
struct nth_greater {
constexpr bool operator()(const T& lhs, const T& rhs) const {
return std::greater<std::tuple_element_t<N, T>>{}(
std::get<N>(lhs), std::get<N>(rhs));
}
};
struct incoming_test_state {
std::chrono::steady_clock::time_point last_test{};
std::chrono::steady_clock::time_point last_whine{};
bool was_failing = false;
};
} // namespace detail
class Swarm;
enum class ReachType { HTTPS, OMQ };
class reachability_testing {
public:
// How often we tick the timer to check whether we need to do any tests.
inline static constexpr auto TESTING_TIMER_INTERVAL = 200ms;
// Distribution for the seconds between node tests: we throw in some randomness to avoid
// potential clustering of tests. (Note that there is some granularity here as the test timer
// only runs every TESTING_TIMER_INTERVAL).
inline static thread_local std::normal_distribution<float> TESTING_INTERVAL{10.0, 3.0};
// The linear backoff after each consecutive test failure before we re-test. Specifically we
// schedule the next re-test for (TESTING_BACKOFF*previous_failures) + TESTING_INTERVAL(rng).
inline static constexpr auto TESTING_BACKOFF = 10s;
// The upper bound for the re-test interval.
inline static constexpr auto TESTING_BACKOFF_MAX = 2min;
// The maximum number of nodes that we will re-test at once (i.e. per TESTING_TIMING_INTERVAL);
// mainly intended to throttle ourselves if, for instance, our own connectivity loss makes us
// accumulate tons of nodes to test all at once. (Despite the random intervals, this can happen
// if we also get decommissioned during which we can't test at all but still have lots of
// failing nodes we want to test right away when we get recommissioned).
inline static constexpr int MAX_RETESTS_PER_TICK = 4;
// Maximum time without a ping before we start whining about it.
//
// We have a probability of about 0.368* of *not* getting pinged within a ping interval (10s),
// and so the probability of not getting a ping for 2 minutes (i.e. 12 test spans) just because
// we haven't been selected is extremely small (0.0000061). It also coincides nicely with
// blockchain time (i.e. two minutes) and our max testing backoff.
//
// * = approx value of ((n-1)/n)^n for non-tiny values of n
inline static constexpr auto MAX_TIME_WITHOUT_PING = 2min;
// How often we whine in the logs about being unreachable
inline static constexpr auto WHINING_INTERVAL = 2min;
using clock = std::chrono::steady_clock;
private:
// Queue of pubkeys of service nodes to test; we pop off the back of this until the queue
// empties then we refill it with a shuffled list of all pubkeys then pull off of it until it is
// empty again, etc.
std::vector<legacy_pubkey> testing_queue;
// The next time for a general test
clock::time_point next_general_test = clock::time_point::min();
// When we started, so that we know not to hold off on whining about no pings for a while.
const clock::time_point startup = clock::now();
// Pubkeys, next test times, and sequential failure counts of service nodes that are currently
// in "failed" status along with the last time they failed; we retest them first after 10s then
// back off linearly by an additional 10s up to a max testing interval of 2m30s, until we get a
// successful response.
using FailingPK = std::tuple<legacy_pubkey, clock::time_point, int>;
std::priority_queue<FailingPK, std::vector<FailingPK>, detail::nth_greater<FailingPK, 1>> failing_queue;
std::unordered_set<legacy_pubkey> failing;
// Track the last time *this node* was tested by other network nodes; used to detect and warn about
// possible network issues.
detail::incoming_test_state last_https;
detail::incoming_test_state last_omq;
public:
// If it is time to perform another random test, this returns the next node to test from the
// testing queue and returns it, also updating the timer for the next test. If it is not yet
// time, or if the queue is empty and cannot current be replenished, returns std::nullopt. If
// the queue empties then this builds a new one by shuffling current public keys in the swarm's
// "all nodes" then starts using the new queue for this an subsequent calls.
//
// `requeue` is mainly for internal use: if false it avoids rebuilding the queue if we run
// out (and instead just return nullopt).
std::optional<sn_record> next_random(
const Swarm& swarm,
const clock::time_point& now = clock::now(),
bool requeue = true);
// Removes and returns up to MAX_RETESTS_PER_TICK nodes that are due to be tested (i.e.
// next-testing-time <= now). Returns [snrecord, #previous-failures] for each.
std::vector<std::pair<sn_record, int>> get_failing(
const Swarm& swarm,
const clock::time_point& now = clock::now());
// Adds a bad node pubkey to the failing list, to be re-tested soon (with a backoff depending on
// `failures`; see TESTING_BACKOFF). `previous_failures` should be the number of previous
// failures *before* this one, i.e. 0 for a random general test; or the failure count returned
// by `get_failing` for repeated failures.
void add_failing_node(const legacy_pubkey& pk, int previous_failures = 0);
// Removes a node from the set of failing nodes; should be called whenever we stop testing a
// node (e.g. because it is not passing, or because it deregistered).
void remove_node_from_failing(const legacy_pubkey& pk);
// Called when this storage server receives an incoming HTTP or OMQ ping
void incoming_ping(ReachType type, const clock::time_point& now = clock::now());
// Check whether we received incoming pings recently
void check_incoming_tests(const clock::time_point& now = clock::now());
};
} // namespace oxen
|
loki-project/loki-storage-server
|
httpserver/http.h
|
#pragma once
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include "string_utils.hpp"
/// Namespace for http constants/types
namespace oxen::http {
using namespace std::literals;
// HTTP response status code
using response_code = std::pair<int, std::string_view>;
inline constexpr response_code
OK{200, "OK"sv},
BAD_REQUEST{400, "Bad Request"sv},
UNAUTHORIZED{401, "Unauthorized"sv},
FORBIDDEN{403, "Forbidden"sv},
NOT_FOUND{404, "Not Found"sv},
NOT_ACCEPTABLE{406, "Not Acceptable"sv},
GONE{410, "Gone"sv},
PAYLOAD_TOO_LARGE{413, "Payload Too Large"sv},
MISDIRECTED_REQUEST{421, "Misdirected Request"sv},
TOO_MANY_REQUESTS{429, "Too Many Requests"sv},
INTERNAL_SERVER_ERROR{500, "Internal Server Error"sv},
BAD_GATEWAY{502, "Bad Gateway"sv},
SERVICE_UNAVAILABLE{503, "Service Unavailable"sv},
GATEWAY_TIMEOUT{504, "Gateway Timeout"sv};
inline constexpr response_code from_code(int status) {
switch (status) {
case 200: return OK;
case 400: return BAD_REQUEST;
case 401: return UNAUTHORIZED;
case 403: return FORBIDDEN;
case 404: return NOT_FOUND;
case 406: return NOT_ACCEPTABLE;
case 410: return GONE;
case 413: return PAYLOAD_TOO_LARGE;
case 421: return MISDIRECTED_REQUEST;
case 429: return TOO_MANY_REQUESTS;
case 502: return BAD_GATEWAY;
case 503: return SERVICE_UNAVAILABLE;
case 504: return GATEWAY_TIMEOUT;
default: [[fallthrough]];
case 500: return INTERNAL_SERVER_ERROR;
}
}
namespace detail {
struct ascii_lc_hash {
std::size_t operator()(const std::string& val) const {
return std::hash<std::string>{}(util::lowercase_ascii_string(val));
}
};
struct ascii_lc_equal {
bool operator()(const std::string& lhs, const std::string& rhs) const {
return util::lowercase_ascii_string(lhs) == util::lowercase_ascii_string(rhs);
}
};
}
// A case-insensitive (but case-preserving) unordered_map for holding header fields
using headers = std::unordered_map<std::string, std::string, detail::ascii_lc_hash, detail::ascii_lc_equal>;
// Deprecated headers; these can be removed after HF19
constexpr auto SNODE_SENDER_HEADER = "X-Loki-Snode-PubKey";
constexpr auto SNODE_TARGET_HEADER = "X-Target-Snode-Key";
constexpr auto SNODE_SIGNATURE_HEADER = "X-Loki-Snode-Signature";
constexpr auto SENDER_KEY_HEADER = "X-Sender-Public-Key";
// Returned in a HF19+ ping_test to include the remote's pubkey in the response
constexpr auto SNODE_PUBKEY_HEADER = "X-Oxen-Snode-Pubkey";
}
|
dragon-archer/2048
|
Include/Pch.h
|
#ifndef _PCH_H
#define _PCH_H
#include <QApplication>
#include <QHeaderView>
#include <QKeyEvent>
#include <QLabel>
#include <QLocale>
#include <QMainWindow>
#include <QMenuBar>
#include <QMessageBox>
#include <QStatusBar>
#include <QTableWidget>
#include <QTranslator>
#ifndef NDEBUG
#include <QDebug>
#endif
#include <fstream>
#include <random>
#include <algorithm>
constexpr const char* dataFileName = "2048.dat";
#endif /* _PCH_H */
|
dragon-archer/2048
|
Include/Common.h
|
<reponame>dragon-archer/2048
#ifndef _COMMMON_H
#define _COMMMON_H 1
#include <Pch.h>
size_t ReadBestScore(const std::string& filename = std::string());
bool WriteBestScore(const std::string& filename, size_t bestScore = 0);
#endif /* _COMMON_H */
|
dragon-archer/2048
|
Include/MainWindow.h
|
#ifndef MainWindow_H
#define MainWindow_H
#include <Pch.h>
#include <Common.h>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void keyPressEvent(QKeyEvent* event);
void print();
bool moveUp();
bool moveDown();
bool moveLeft();
bool moveRight();
bool generate();
void setupUi();
void retranslateUi();
private:
uint8_t table[4][4];
size_t score;
size_t bestScore;
QColor color[16];
static std::mt19937 engine;
QWidget *CentralWidget;
QTableWidget *TableData;
QLabel *Label1;
QLabel *Label2;
QLabel *LabelScore;
QLabel *LabelBestScore;
QMenuBar *MenuBar;
QMenu *MenuFile;
QMenu *MenuSettings;
QStatusBar *StatusBar;
};
#endif // MainWindow_H
|
serisman/arduboy-hangma
|
Hangman/EEPROM_Utils.h
|
<gh_stars>0
#ifndef EEPROM_UTILS_H
#define EEPROM_UTILS_H
#include <EEPROM.h>
#define EEPROM_START (EEPROM_STORAGE_SPACE_START + 72)
void EEPROM_saveScore(uint8_t w, uint8_t l) {
EEPROM.update(EEPROM_START+2, w);
EEPROM.update(EEPROM_START+3, l);
}
uint8_t EEPROM_getWins() {
return EEPROM.read(EEPROM_START+2);
}
uint8_t EEPROM_getLosses() {
return EEPROM.read(EEPROM_START+3);
}
void EEPROM_init() {
uint8_t h1 = EEPROM.read(EEPROM_START+0);
uint8_t h2 = EEPROM.read(EEPROM_START+1);
if (h1 != 'H' || h2 != 'M') {
EEPROM.update(EEPROM_START+0, 'H');
EEPROM.update(EEPROM_START+1, 'M');
EEPROM_saveScore(0, 0);
}
}
#endif
|
serisman/arduboy-hangma
|
Hangman/sounds.h
|
#ifndef SOUNDS_H
#define SOUNDS_H
const uint16_t soundCorrect[] PROGMEM = {NOTE_F4,100,NOTE_A4,150,TONES_END};
const uint16_t soundWin[] PROGMEM = {NOTE_E4,100,NOTE_F4,100,NOTE_C5,250,TONES_END};
const uint16_t soundIncorrect[] PROGMEM = {NOTE_A4,100,NOTE_F3,150,TONES_END};
const uint16_t soundDead[] PROGMEM = {NOTE_D4,100,NOTE_B3,100,NOTE_E3,100,NOTE_F2,150,TONES_END};
#endif
|
RamsayBoy/Minishell-C
|
include/parser.h
|
#ifndef PARSER_H_INCLUDED
#define PARSER_H_INCLUDED
typedef struct {
char * filename;
int argc;
char ** argv;
} tcommand;
typedef struct {
int ncommands;
tcommand * commands;
char * redirect_input;
char * redirect_output;
char * redirect_error;
int background;
} tline;
extern tline * tokenize(char *str);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.