hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588 values | lang stringclasses 305 values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b4773680e5cadda8de00834e3a17edaae930ad4f | 110 | h | C | Source/Storm-Helper/include/Storm-HelperPCH.h | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | 3 | 2021-11-27T04:56:12.000Z | 2022-02-14T04:02:10.000Z | Source/Storm-Helper/include/Storm-HelperPCH.h | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | Source/Storm-Helper/include/Storm-HelperPCH.h | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | #pragma once
#include "StormHelperPrerequisite.h"
#include "Logging.h"
#define STORM_MODULE_NAME "Helpers"
| 13.75 | 36 | 0.781818 |
7e28d0ad0dc402e0ec89b6f8992888a66d58fc67 | 738 | h | C | modules/http_streamer/src/HttpStreamSession.h | nicledomaS/VideoStream | e695e0b544a61bb4e74149005c69723dbbecb952 | [
"Apache-2.0"
] | null | null | null | modules/http_streamer/src/HttpStreamSession.h | nicledomaS/VideoStream | e695e0b544a61bb4e74149005c69723dbbecb952 | [
"Apache-2.0"
] | 1 | 2022-03-16T07:16:25.000Z | 2022-03-16T07:16:25.000Z | modules/http_streamer/src/HttpStreamSession.h | nicledomaS/VideoStream | e695e0b544a61bb4e74149005c69723dbbecb952 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "StreamSession.h"
struct AVIOContext;
namespace video_streamer
{
class HttpStreamSession: public StreamSession
{
public:
explicit HttpStreamSession(AVIOContext* clientContext) noexcept;
~HttpStreamSession() noexcept;
HttpStreamSession(HttpStreamSession&& rhs) noexcept;
HttpStreamSession& operator=(HttpStreamSession&& rhs) noexcept;
void connect() override;
void send(const std::vector<unsigned char>& img) override;
bool isConnected() const noexcept override;
private:
HttpStreamSession(const HttpStreamSession&) = delete;
HttpStreamSession& operator=(const HttpStreamSession&) = delete;
AVIOContext* m_clientContext;
bool m_isConnect = false;
};
} // video_streamer | 24.6 | 66 | 0.762873 |
cc5f59bc57770d2563d5aa2701eacd4111dd57ef | 7,223 | c | C | third_party/python/Modules/_decimal/libmpdec/context.c | appotry/cosmopolitan | af4687cc3f2331a23dc336183ab58fe001cda082 | [
"ISC"
] | null | null | null | third_party/python/Modules/_decimal/libmpdec/context.c | appotry/cosmopolitan | af4687cc3f2331a23dc336183ab58fe001cda082 | [
"ISC"
] | null | null | null | third_party/python/Modules/_decimal/libmpdec/context.c | appotry/cosmopolitan | af4687cc3f2331a23dc336183ab58fe001cda082 | [
"ISC"
] | null | null | null | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright (c) 2008-2016 Stefan Krah. All rights reserved. │
│ │
│ Redistribution and use in source and binary forms, with or without │
│ modification, are permitted provided that the following conditions │
│ are met: │
│ │
│ 1. Redistributions of source code must retain the above copyright │
│ notice, this list of conditions and the following disclaimer. │
│ │
│ 2. Redistributions in binary form must reproduce the above copyright │
│ notice, this list of conditions and the following disclaimer in │
│ the documentation and/or other materials provided with the │
│ distribution. │
│ │
│ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND │
│ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE │
│ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR │
│ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS │
│ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, │
│ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT │
│ OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR │
│ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, │
│ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE │
│ OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, │
│ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/sysv/consts/sig.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
void
mpd_dflt_traphandler(mpd_context_t *ctx)
{
(void)ctx;
raise(SIGFPE);
}
void (* mpd_traphandler)(mpd_context_t *) = mpd_dflt_traphandler;
/* Set guaranteed minimum number of coefficient words. The function may
be used once at program start. Setting MPD_MINALLOC to out-of-bounds
values is a catastrophic error, so in that case the function exits rather
than relying on the user to check a return value. */
void
mpd_setminalloc(mpd_ssize_t n)
{
static int minalloc_is_set = 0;
if (minalloc_is_set) {
mpd_err_warn("mpd_setminalloc: ignoring request to set "
"MPD_MINALLOC a second time\n");
return;
}
if (n < MPD_MINALLOC_MIN || n > MPD_MINALLOC_MAX) {
mpd_err_fatal("illegal value for MPD_MINALLOC"); /* GCOV_NOT_REACHED */
}
MPD_MINALLOC = n;
minalloc_is_set = 1;
}
void
mpd_init(mpd_context_t *ctx, mpd_ssize_t prec)
{
mpd_ssize_t ideal_minalloc;
mpd_defaultcontext(ctx);
if (!mpd_qsetprec(ctx, prec)) {
mpd_addstatus_raise(ctx, MPD_Invalid_context);
return;
}
ideal_minalloc = 2 * ((prec+MPD_RDIGITS-1) / MPD_RDIGITS);
if (ideal_minalloc < MPD_MINALLOC_MIN) ideal_minalloc = MPD_MINALLOC_MIN;
if (ideal_minalloc > MPD_MINALLOC_MAX) ideal_minalloc = MPD_MINALLOC_MAX;
mpd_setminalloc(ideal_minalloc);
}
void
mpd_maxcontext(mpd_context_t *ctx)
{
ctx->prec=MPD_MAX_PREC;
ctx->emax=MPD_MAX_EMAX;
ctx->emin=MPD_MIN_EMIN;
ctx->round=MPD_ROUND_HALF_EVEN;
ctx->traps=MPD_Traps;
ctx->status=0;
ctx->newtrap=0;
ctx->clamp=0;
ctx->allcr=1;
}
void
mpd_defaultcontext(mpd_context_t *ctx)
{
ctx->prec=2*MPD_RDIGITS;
ctx->emax=MPD_MAX_EMAX;
ctx->emin=MPD_MIN_EMIN;
ctx->round=MPD_ROUND_HALF_UP;
ctx->traps=MPD_Traps;
ctx->status=0;
ctx->newtrap=0;
ctx->clamp=0;
ctx->allcr=1;
}
void
mpd_basiccontext(mpd_context_t *ctx)
{
ctx->prec=9;
ctx->emax=MPD_MAX_EMAX;
ctx->emin=MPD_MIN_EMIN;
ctx->round=MPD_ROUND_HALF_UP;
ctx->traps=MPD_Traps|MPD_Clamped;
ctx->status=0;
ctx->newtrap=0;
ctx->clamp=0;
ctx->allcr=1;
}
int
mpd_ieee_context(mpd_context_t *ctx, int bits)
{
if (bits <= 0 || bits > MPD_IEEE_CONTEXT_MAX_BITS || bits % 32) {
return -1;
}
ctx->prec = 9 * (bits/32) - 2;
ctx->emax = 3 * ((mpd_ssize_t)1<<(bits/16+3));
ctx->emin = 1 - ctx->emax;
ctx->round=MPD_ROUND_HALF_EVEN;
ctx->traps=0;
ctx->status=0;
ctx->newtrap=0;
ctx->clamp=1;
ctx->allcr=1;
return 0;
}
mpd_ssize_t
mpd_getprec(const mpd_context_t *ctx)
{
return ctx->prec;
}
mpd_ssize_t
mpd_getemax(const mpd_context_t *ctx)
{
return ctx->emax;
}
mpd_ssize_t
mpd_getemin(const mpd_context_t *ctx)
{
return ctx->emin;
}
int
mpd_getround(const mpd_context_t *ctx)
{
return ctx->round;
}
uint32_t
mpd_gettraps(const mpd_context_t *ctx)
{
return ctx->traps;
}
uint32_t
mpd_getstatus(const mpd_context_t *ctx)
{
return ctx->status;
}
int
mpd_getclamp(const mpd_context_t *ctx)
{
return ctx->clamp;
}
int
mpd_getcr(const mpd_context_t *ctx)
{
return ctx->allcr;
}
int
mpd_qsetprec(mpd_context_t *ctx, mpd_ssize_t prec)
{
if (prec <= 0 || prec > MPD_MAX_PREC) {
return 0;
}
ctx->prec = prec;
return 1;
}
int
mpd_qsetemax(mpd_context_t *ctx, mpd_ssize_t emax)
{
if (emax < 0 || emax > MPD_MAX_EMAX) {
return 0;
}
ctx->emax = emax;
return 1;
}
int
mpd_qsetemin(mpd_context_t *ctx, mpd_ssize_t emin)
{
if (emin > 0 || emin < MPD_MIN_EMIN) {
return 0;
}
ctx->emin = emin;
return 1;
}
int
mpd_qsetround(mpd_context_t *ctx, int round)
{
if (!(0 <= round && round < MPD_ROUND_GUARD)) {
return 0;
}
ctx->round = round;
return 1;
}
int
mpd_qsettraps(mpd_context_t *ctx, uint32_t traps)
{
if (traps > MPD_Max_status) {
return 0;
}
ctx->traps = traps;
return 1;
}
int
mpd_qsetstatus(mpd_context_t *ctx, uint32_t flags)
{
if (flags > MPD_Max_status) {
return 0;
}
ctx->status = flags;
return 1;
}
int
mpd_qsetclamp(mpd_context_t *ctx, int c)
{
if (c != 0 && c != 1) {
return 0;
}
ctx->clamp = c;
return 1;
}
int
mpd_qsetcr(mpd_context_t *ctx, int c)
{
if (c != 0 && c != 1) {
return 0;
}
ctx->allcr = c;
return 1;
}
void
mpd_addstatus_raise(mpd_context_t *ctx, uint32_t flags)
{
ctx->status |= flags;
if (flags&ctx->traps) {
ctx->newtrap = (flags&ctx->traps);
mpd_traphandler(ctx);
}
}
| 25.704626 | 80 | 0.589783 |
2b7f6d40a4d1c27b71e02c639ed0cfd9302036ea | 7,955 | h | C | src/docdblib/db.h | ondra-novak/docdb | 4916c3cce284b4fa6d299bd4f8b299dbfe5b56f8 | [
"MIT"
] | null | null | null | src/docdblib/db.h | ondra-novak/docdb | 4916c3cce284b4fa6d299bd4f8b299dbfe5b56f8 | [
"MIT"
] | null | null | null | src/docdblib/db.h | ondra-novak/docdb | 4916c3cce284b4fa6d299bd4f8b299dbfe5b56f8 | [
"MIT"
] | null | null | null | /*
* db.h
*
* Created on: 16. 12. 2020
* Author: ondra
*/
#ifndef SRC_DOCDB_SRC_DOCDBLIB_DB_H_
#define SRC_DOCDB_SRC_DOCDBLIB_DB_H_
#include <memory>
#include <string>
#include "dbconfig.h"
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <mutex>
#include <imtjson/value.h>
#include "classes.h"
#include "shared/refcnt.h"
#include "iterator.h"
#include "keyspace.h"
namespace docdb {
class KeySpaceIterator;
class Batch : public ::leveldb::WriteBatch {
public:
using ::leveldb::WriteBatch::WriteBatch;
};
enum SnapshotMode {
///write to the snapshot causes an exception
writeError,
///write to the snapshot is silently ignored - no exception, written data are lost
writeIgnore,
///all writes are forwarded to live database (but will not appear in snapshot)
writeForward
};
class DBCore;
using PDBCore = ondra_shared::RefCntPtr<DBCore>;
///Abstract interface defines minimal set of function defined at core level
class DBCore: public ondra_shared:: RefCntObj {
public:
virtual ~DBCore() {}
///Commits a batch (and clears its content)
/** The all writes all done through the batches. There are no other ways to write new keys.
*
* @param b batch to commit
*/
virtual void commitBatch(Batch &b) = 0;
///Creates iterator over keys
/**
* @param from start key
* @param to end key
* @param exclude_begin exclude starting key if matches
* @param exclude_end exclude ending key if matches
* @return iterator
*/
virtual Iterator createIterator(const Iterator::RangeDef &rangeDef) const = 0;
///Retrieve value from the database
/**
* @param key key to retrieve
* @param val the variable is filled with the value. To reduce reallocations, it is good idea to
* reuse single buffer to retrieve multiple values
* @retval true key found
* @retval false key not found
*/
virtual bool get(const Key &key, std::string &val) const = 0;
///Creates a snapshot.
/**
* Function creates a snapshot of current db. Returns new instance of this interface which
* represents the snapshot.
*
* @param mode defines how writes are handled in the snapshot
* @return snapshot
*/
virtual PDBCore getSnapshot(SnapshotMode mode = writeError) const = 0;
///Compacts database
virtual void compact() = 0;
///Retrieves database statistics
virtual json::Value getStats() const = 0;
///Allocates keyspace
/**
* @param class_id specified ID which identifies format of data stored in the keyspace. IDs
* are defined by each class which manipulates with the keyspace. This prevents to change
* purpose of the keyspace.
* @param name name of the keyspace specified by the user
* @return If the keyspace is already allocated, it returns its identifier. If the keyspace is
* not allocated, it is allocated now and new identifier is returned. Note that allocation
* is persistently stored in database. To release keyspace, you need to call freeKeyspace
*/
virtual KeySpaceID allocKeyspace(ClassID class_id, const std::string_view &name) = 0;
///Releases keyspace
/**
* Releases keyspace and deletes all data in it
*
* @param class_id class of the keyspace
* @param name name of the keyspace
* @retval true success
* @retval false keyspace not exists
*/
virtual bool freeKeyspace(ClassID class_id, const std::string_view &name) = 0;
virtual void getApproximateSizes(const std::pair<Key,Key> *ranges, int nranges, std::uint64_t *sizes) = 0;
};
///Core Database
/**
* Main feature of the database object is to manage keyspaces, batches, and
* iterators. To access documents, views, maps, etc, you need also create instance
* of appropriate classes.
*/
class DB {
public:
DB(const PDBCore &core):core(core) {}
///Open database on path with leveldb options
/**
* @param path path to the database
*/
DB(const std::string &path, const Config &opt = Config());
///Commits batch (and also clears its content)
void commitBatch(Batch &b);
///Allocate a keyspace. It is identified by its class_id and the name
/**
* @param class_id class id - each database class knows its class_id
* @param name any arbitrary name of the key space
* @return id of allocated keyspace - you need to use this result to create a Key
* object
*
* @note if the keyspace already exists, its identifier is returned. Note that
* there is limited count of keyspaces (255). When there is no available keyspace,
* the function throws an exception. If you no longer need a keyspace, you
* need to free it (freeKeyspace).
*
* @exception TooManyKeyspaces No more keyspaces can be allocated
*/
KeySpaceID allocKeyspace(ClassID class_id, const std::string_view &name);
KeySpaceID allocKeyspace(KeySpaceClass class_id, const std::string_view &name);
///Releases a keyspace
/** Function also removes content of the keyspace, which can cause a lot
* of processing before the function returns. Ensure, that nobody is using
* keyspace which is being released
*
* @param id id of keyspace to free
*/
bool freeKeyspace(ClassID class_id, const std::string_view &name);
///Stores any arbitrary metadata along with keyspace definition
/**
* @param id id of keyspace
* @param data metadata to store
*/
void keyspace_putMetadata(KeySpaceID id, const json::Value &data) ;
///clear whole keyspace (can take a time)
void clearKeyspace(KeySpaceID id);
///Stores any arbitrary metadata along with keyspace definition
/** Data are stored in batch, which can be commited later
* @param b batch
* @param id id of keyspace
* @param data metadata to store
*/
static void keyspace_putMetadata(Batch &b, KeySpaceID id, const json::Value &data);
///Retrieve any arbitrary metadata stored along with keyspace definition
/**
* @param id keyspace identifier
* @return returns associated data as JSON. Returns undefined, when metadata was not yet stored
*/
json::Value keyspace_getMetadata(KeySpaceID id) const;
///Create cache (to config)
static PCache createCache(std::size_t size);
///Creates iterator over keys
/**
* @param from start key
* @param to end key
* @param exclude_begin exclude starting key if matches
* @param exclude_end exclude ending key if matches
* @return iterator
*/
Iterator createIterator(const Iterator::RangeDef &rangeDef) const;
///Retrieve value from the database
/**
* @param key key to retrieve
* @param val the variable is filled with the value. To reduce reallocations, it is good idea to
* reuse single buffer to retrieve multiple values
* @retval true key found
* @retval false key not found
*/
bool get(const Key &key, std::string &val) const;
///Creates a snapshot.
/**
* Function creates a snapshot of current db. Returns new instance of this interface which
* represents the snapshot.
*
* @param mode defines how writes are handled in the snapshot
* @return snapshot
*/
DB getSnapshot(SnapshotMode mode = writeError) const;
///Retrieves database statistics
json::Value getStats() const;
///Enumerates all allocated keyspaces
KeySpaceIterator listKeyspaces() const;
///Retrieves a single buffer for reading data;
/**
* There is one buffer for thread. Returned buffer is always cleared.
* Function is MT safe. You should not pass returned reference to different thread
* @return reference to local buffer
*/
static std::string &getBuffer();
std::uint64_t getKeyspaceSize(KeySpaceID kod) const;
void compact() {core->compact();}
protected:
PDBCore core;
};
class KeySpaceIterator: public Iterator {
public:
KeySpaceIterator(Iterator &&iter);
using Iterator::next;
///Retrieves ID of keyspace
KeySpaceID getID() const;
///Retrieves class ID of the keyspace
ClassID getClass() const;
///Retrieves name of the keyspace
std::string_view getName() const;
};
inline leveldb::Slice string2slice(json::StrViewA data) {
return leveldb::Slice(data.data, data.length);
}
}
#endif /* SRC_DOCDB_SRC_DOCDBLIB_DB_H_ */
| 29.682836 | 107 | 0.729604 |
93a92e24f6a1336ea5420d0764aded57167bb2f8 | 375 | c | C | sources/entity/stats_skills/stats.c | nwmqpa/MyRPG | 50ef2909475c9ae3e9bf382f4f8b270ef064eb0a | [
"WTFPL"
] | 2 | 2018-12-23T11:43:08.000Z | 2019-02-14T12:32:21.000Z | sources/entity/stats_skills/stats.c | nwmqpa/MyRPG | 50ef2909475c9ae3e9bf382f4f8b270ef064eb0a | [
"WTFPL"
] | null | null | null | sources/entity/stats_skills/stats.c | nwmqpa/MyRPG | 50ef2909475c9ae3e9bf382f4f8b270ef064eb0a | [
"WTFPL"
] | null | null | null | /*
** EPITECH PROJECT, 2017
** sources/entity/stats_skills/stats.c
** File description:
** Stats file.
*/
#include "entities.h"
#include "utils.h"
void stats_init(struct player *player)
{
player->nb_stats = LAST_STAT;
player->stats = my_calloc(sizeof(struct stat) * player->nb_stats);
for (int i = 0; i < LAST_STAT; i++) {
player->stats[i] = (struct stat) {i, 0};
}
} | 20.833333 | 67 | 0.666667 |
2b1c0cd9b01fbba809dfec9cb72a06ace9f17afd | 1,525 | h | C | server/timelog.h | ICT-Infer/timelog | de83ab13801ad3c8ff2822b969e58ed81c143bc9 | [
"0BSD"
] | 1 | 2015-05-03T22:17:13.000Z | 2015-05-03T22:17:13.000Z | server/timelog.h | erikano/django-timelog | de83ab13801ad3c8ff2822b969e58ed81c143bc9 | [
"0BSD"
] | 66 | 2015-03-23T00:57:20.000Z | 2015-07-08T16:01:25.000Z | server/timelog.h | erikano/django-atl | de83ab13801ad3c8ff2822b969e58ed81c143bc9 | [
"0BSD"
] | null | null | null | /*
* Copyright (c) 2015, 2016 Erik Nordstrøm <erikn@ict-infer.no>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef TIMELOG_H
#define TIMELOG_H
#include <sys/types.h>
/*
* XXX: Integer values used in the tz enum
* are _NOT_ related to time zone offset.
*
* XXX: Might need to rethink internal representation of time zones.
*/
typedef enum
{
TZ_UTC = 0,
TZ_EUROPE_OSLO = 1,
} tz;
typedef struct
{
// XXX: parent_catid = 0 means that the category has no parent.
unsigned int parent_catid;
unsigned int id;
char[255] name;
char[255] comment;
char[32] slug;
} category;
typedef struct
{
uid_t pw_uid;
unsigned int catid;
unsigned int id;
time_t t_begin;
tz tz_begin;
time_t t_end;
tz tz_end;
char[255] comment;
} entry;
#endif
| 25.847458 | 75 | 0.699672 |
9eb6df322ed842cb3a4769d34aabaa1b63b45867 | 1,783 | h | C | core/include/prometheus/time_window_quantiles.h | biaks/prometheus-cpp-light | 8f252c36e55d8a82cae16df9eeed9ed64199643c | [
"MIT"
] | null | null | null | core/include/prometheus/time_window_quantiles.h | biaks/prometheus-cpp-light | 8f252c36e55d8a82cae16df9eeed9ed64199643c | [
"MIT"
] | null | null | null | core/include/prometheus/time_window_quantiles.h | biaks/prometheus-cpp-light | 8f252c36e55d8a82cae16df9eeed9ed64199643c | [
"MIT"
] | 2 | 2021-08-31T18:05:16.000Z | 2022-03-10T18:47:33.000Z | #pragma once
#include <chrono>
#include <cstddef>
#include <vector>
#include "prometheus/detail/ckms_quantiles.h"
namespace prometheus {
namespace detail {
class TimeWindowQuantiles {
using Clock = std::chrono::steady_clock;
public:
TimeWindowQuantiles(const std::vector<CKMSQuantiles::Quantile>& quantiles,
const Clock::duration max_age, const int age_buckets)
: quantiles_(quantiles),
ckms_quantiles_(age_buckets, CKMSQuantiles(quantiles_)),
current_bucket_(0),
last_rotation_(Clock::now()),
rotation_interval_(max_age / age_buckets) {}
double get(double q) const {
CKMSQuantiles& current_bucket = rotate();
return current_bucket.get(q);
}
void insert(double value) {
rotate();
for (auto& bucket : ckms_quantiles_) {
bucket.insert(value);
}
}
private:
CKMSQuantiles& rotate() const {
auto delta = Clock::now() - last_rotation_;
while (delta > rotation_interval_) {
ckms_quantiles_[current_bucket_].reset();
if (++current_bucket_ >= ckms_quantiles_.size()) {
current_bucket_ = 0;
}
delta -= rotation_interval_;
last_rotation_ += rotation_interval_;
}
return ckms_quantiles_[current_bucket_];
}
const std::vector<CKMSQuantiles::Quantile>& quantiles_;
mutable std::vector<CKMSQuantiles> ckms_quantiles_;
mutable std::size_t current_bucket_;
mutable Clock::time_point last_rotation_;
const Clock::duration rotation_interval_;
};
} // namespace detail
} // namespace prometheus
| 28.301587 | 82 | 0.603477 |
b10c3e532f6140fa5c572b32a5c6e2286514a99e | 26,618 | c | C | platform/vendor_bsp/gd/GD32E50x_Firmware_Library/GD32E50x_standard_peripheral/Source/gd32e50x_dac.c | rceet/TencentOS-tiny | 1830420984f21e7dfced30dcb6e8f9ef146f0226 | [
"Apache-2.0"
] | 5,547 | 2019-09-18T02:20:53.000Z | 2021-08-25T10:29:54.000Z | platform/vendor_bsp/gd/GD32E50x_Firmware_Library/GD32E50x_standard_peripheral/Source/gd32e50x_dac.c | rceet/TencentOS-tiny | 1830420984f21e7dfced30dcb6e8f9ef146f0226 | [
"Apache-2.0"
] | 103 | 2019-09-19T13:16:09.000Z | 2021-08-04T03:51:19.000Z | platform/vendor_bsp/gd/GD32E50x_Firmware_Library/GD32E50x_standard_peripheral/Source/gd32e50x_dac.c | rceet/TencentOS-tiny | 1830420984f21e7dfced30dcb6e8f9ef146f0226 | [
"Apache-2.0"
] | 1,445 | 2019-09-18T04:38:19.000Z | 2021-08-25T09:17:30.000Z | /*!
\file gd32e50x_dac.c
\brief DAC driver
\version 2020-03-10, V1.0.0, firmware for GD32E50x
\version 2020-08-26, V1.1.0, firmware for GD32E50x
*/
/*
Copyright (c) 2020, GigaDevice Semiconductor Inc.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
#include "gd32e50x_dac.h"
/* DAC register bit offset */
#define OUT1_REG_OFFSET ((uint32_t)0x00000010U)
#define DH_12BIT_OFFSET ((uint32_t)0x00000010U)
#define DH_8BIT_OFFSET ((uint32_t)0x00000008U)
/*!
\brief deinitialize DAC
\param[in] none
\param[out] none
\retval none
*/
void dac_deinit(void)
{
rcu_periph_reset_enable(RCU_DACRST);
rcu_periph_reset_disable(RCU_DACRST);
}
/*!
\brief enable DAC
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_enable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL0 |= DAC_CTL0_DEN0;
}else{
DAC_CTL0 |= DAC_CTL0_DEN1;
}
}
/*!
\brief disable DAC
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_disable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL0 &= ~DAC_CTL0_DEN0;
}else{
DAC_CTL0 &= ~DAC_CTL0_DEN1;
}
}
/*!
\brief enable DAC DMA function
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_dma_enable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL0 |= DAC_CTL0_DDMAEN0;
}else{
DAC_CTL0 |= DAC_CTL0_DDMAEN1;
}
}
/*!
\brief disable DAC DMA function
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_dma_disable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL0 &= ~DAC_CTL0_DDMAEN0;
}else{
DAC_CTL0 &= ~DAC_CTL0_DDMAEN1;
}
}
/*!
\brief enable DAC output buffer
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_output_buffer_enable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL0 &= ~DAC_CTL0_DBOFF0;
}else{
DAC_CTL0 &= ~DAC_CTL0_DBOFF1;
}
}
/*!
\brief disable DAC output buffer
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_output_buffer_disable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL0 |= DAC_CTL0_DBOFF0;
}else{
DAC_CTL0 |= DAC_CTL0_DBOFF1;
}
}
/*!
\brief get DAC output value
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval DAC output data: 0~4095
*/
uint16_t dac_output_value_get(uint8_t dac_out)
{
uint16_t data = 0U;
if(DAC_OUT_0 == dac_out){
/* store the DAC_OUT0 output value */
data = (uint16_t)OUT0_DO;
}else{
/* store the DAC_OUT1 output value */
data = (uint16_t)OUT1_DO;
}
return data;
}
/*!
\brief set DAC data holding register value
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] dac_align: DAC data alignment mode
only one parameter can be selected which is shown as below:
\arg DAC_ALIGN_12B_R: 12-bit right-aligned data
\arg DAC_ALIGN_12B_L: 12-bit left-aligned data
\arg DAC_ALIGN_8B_R: 8-bit right-aligned data
\param[in] data: data to be loaded, 0~4095
\param[out] none
\retval none
*/
void dac_data_set(uint8_t dac_out, uint32_t dac_align, uint16_t data)
{
/* DAC_OUT0 data alignment */
if(DAC_OUT_0 == dac_out){
switch(dac_align){
/* 12-bit right-aligned data */
case DAC_ALIGN_12B_R:
OUT0_R12DH = data;
break;
/* 12-bit left-aligned data */
case DAC_ALIGN_12B_L:
OUT0_L12DH = data;
break;
/* 8-bit right-aligned data */
case DAC_ALIGN_8B_R:
OUT0_R8DH = data;
break;
default:
break;
}
}else{
/* DAC_OUT1 data alignment */
switch(dac_align){
/* 12-bit right-aligned data */
case DAC_ALIGN_12B_R:
OUT1_R12DH = data;
break;
/* 12-bit left-aligned data */
case DAC_ALIGN_12B_L:
OUT1_L12DH = data;
break;
/* 8-bit right-aligned data */
case DAC_ALIGN_8B_R:
OUT1_R8DH = data;
break;
default:
break;
}
}
}
/*!
\brief enable DAC output FIFO
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_output_fifo_enable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL1 |= DAC_CTL1_FIFOEN0;
}else{
DAC_CTL1 |= DAC_CTL1_FIFOEN1;
}
}
/*!
\brief disable DAC output FIFO
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_output_fifo_disable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL1 &= ~DAC_CTL1_FIFOEN0;
}else{
DAC_CTL1 &= ~DAC_CTL1_FIFOEN1;
}
}
/*!
\brief get DAC output FIFO number
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval DAC output FIFO number: 0~4
*/
uint16_t dac_output_fifo_number_get(uint8_t dac_out)
{
uint16_t number = 0U;
if(DAC_OUT_0 == dac_out){
/* get the DAC_OUT0 output FIFO number */
number = (uint16_t)((uint16_t)DAC_STAT1 >> 4U);
}else{
/* get the DAC_OUT1 output FIFO number */
number = (uint16_t)(DAC_STAT1 >> 20U);
}
return number;
}
/*!
\brief enable DAC trigger
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_trigger_enable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL0 |= DAC_CTL0_DTEN0;
}else{
DAC_CTL0 |= DAC_CTL0_DTEN1;
}
}
/*!
\brief disable DAC trigger
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_trigger_disable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_CTL0 &= ~DAC_CTL0_DTEN0;
}else{
DAC_CTL0 &= ~DAC_CTL0_DTEN1;
}
}
/*!
\brief configure DAC trigger source
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] triggersource: external triggers of DAC
only one parameter can be selected which is shown as below:
\arg DAC_TRIGGER_T5_TRGO: TIMER5 TRGO
\arg DAC_TRIGGER_T7_TRGO: TIMER7 TRGO (for GD32E50X_HD and GD32E50X_XD devices)
\arg DAC_TRIGGER_T2_TRGO: TIMER2 TRGO (for GD32E50X_CL devices)
\arg DAC_TRIGGER_T6_TRGO: TIMER6 TRGO
\arg DAC_TRIGGER_T4_TRGO: TIMER4 TRGO
\arg DAC_TRIGGER_T1_TRGO: TIMER1 TRGO
\arg DAC_TRIGGER_T3_TRGO: TIMER3 TRGO
\arg DAC_TRIGGER_EXTI_9: EXTI interrupt line9 event
\arg DAC_TRIGGER_SOFTWARE: software trigger
\arg DAC_TRIGGER_SHRTIMER_DACTRIG0: SHRTIMER_DACTRIG0 trigger(for GD32E50X_HD, GD32E50X_XD and GD32E50X_CL devices)
\arg DAC_TRIGGER_SHRTIMER_DACTRIG1: SHRTIMER_DACTRIG1 trigger(for GD32E50X_HD, GD32E50X_XD and GD32E50X_CL devices)
\arg DAC_TRIGGER_SHRTIMER_DACTRIG2: SHRTIMER_DACTRIG2 trigger(for GD32E50X_HD, GD32E50X_XD and GD32E50X_CL devices)
\param[out] none
\retval none
*/
void dac_trigger_source_config(uint8_t dac_out,uint32_t triggersource)
{
if(DAC_OUT_0 == dac_out){
/* configure DAC_OUT0 trigger source */
DAC_CTL0 &= (uint32_t)(~(DAC_CTL0_DTSEL0 | DAC_CTL0_DTSEL0_3));
DAC_CTL0 |= triggersource;
}else{
/* configure DAC_OUT1 trigger source */
DAC_CTL0 &= (uint32_t)(~(DAC_CTL0_DTSEL1 | DAC_CTL0_DTSEL1_3));
DAC_CTL0 |= (triggersource << OUT1_REG_OFFSET);
}
}
/*!
\brief enable DAC software trigger
\param[in] dac_out: DAC_OUT_x(x=0,1)
\retval none
*/
void dac_software_trigger_enable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_SWT |= DAC_SWT_SWTR0;
}else{
DAC_SWT |= DAC_SWT_SWTR1;
}
}
/*!
\brief disable DAC software trigger
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[out] none
\retval none
*/
void dac_software_trigger_disable(uint8_t dac_out)
{
if(DAC_OUT_0 == dac_out){
DAC_SWT &= ~DAC_SWT_SWTR0;
}else{
DAC_SWT &= ~DAC_SWT_SWTR1;
}
}
/*!
\brief configure DAC wave mode
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] wave_mode: DAC wave mode
only one parameter can be selected which is shown as below:
\arg DAC_WAVE_DISABLE: wave mode disable
\arg DAC_WAVE_MODE_LFSR: LFSR noise mode
\arg DAC_WAVE_MODE_TRIANGLE: triangle noise mode
\param[out] none
\retval none
*/
void dac_wave_mode_config(uint8_t dac_out, uint32_t wave_mode)
{
if(DAC_OUT_0 == dac_out){
/* configure DAC_OUT0 wave mode */
DAC_CTL0 &= ~DAC_CTL0_DWM0;
DAC_CTL0 |= wave_mode;
}else{
/* configure DAC_OUT1 wave mode */
DAC_CTL0 &= ~DAC_CTL0_DWM1;
DAC_CTL0 |= (wave_mode << OUT1_REG_OFFSET);
}
}
/*!
\brief configure DAC wave bit width
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] bit_width: DAC noise wave bit width
only one parameter can be selected which is shown as below:
\arg DAC_WAVE_BIT_WIDTH_1: bit width of the wave signal is 1
\arg DAC_WAVE_BIT_WIDTH_2: bit width of the wave signal is 2
\arg DAC_WAVE_BIT_WIDTH_3: bit width of the wave signal is 3
\arg DAC_WAVE_BIT_WIDTH_4: bit width of the wave signal is 4
\arg DAC_WAVE_BIT_WIDTH_5: bit width of the wave signal is 5
\arg DAC_WAVE_BIT_WIDTH_6: bit width of the wave signal is 6
\arg DAC_WAVE_BIT_WIDTH_7: bit width of the wave signal is 7
\arg DAC_WAVE_BIT_WIDTH_8: bit width of the wave signal is 8
\arg DAC_WAVE_BIT_WIDTH_9: bit width of the wave signal is 9
\arg DAC_WAVE_BIT_WIDTH_10: bit width of the wave signal is 10
\arg DAC_WAVE_BIT_WIDTH_11: bit width of the wave signal is 11
\arg DAC_WAVE_BIT_WIDTH_12: bit width of the wave signal is 12
\param[out] none
\retval none
*/
void dac_wave_bit_width_config(uint8_t dac_out, uint32_t bit_width)
{
if(DAC_OUT_0 == dac_out){
/* configure DAC_OUT0 wave bit width */
DAC_CTL0 &= ~DAC_CTL0_DWBW0;
DAC_CTL0 |= bit_width;
}else{
/* configure DAC_OUT1 wave bit width */
DAC_CTL0 &= ~DAC_CTL0_DWBW1;
DAC_CTL0 |= (bit_width << OUT1_REG_OFFSET);
}
}
/*!
\brief configure DAC LFSR noise mode
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] unmask_bits: LFSR noise unmask bits
only one parameter can be selected which is shown as below:
\arg DAC_LFSR_BIT0: unmask the LFSR bit0
\arg DAC_LFSR_BITS1_0: unmask the LFSR bits[1:0]
\arg DAC_LFSR_BITS2_0: unmask the LFSR bits[2:0]
\arg DAC_LFSR_BITS3_0: unmask the LFSR bits[3:0]
\arg DAC_LFSR_BITS4_0: unmask the LFSR bits[4:0]
\arg DAC_LFSR_BITS5_0: unmask the LFSR bits[5:0]
\arg DAC_LFSR_BITS6_0: unmask the LFSR bits[6:0]
\arg DAC_LFSR_BITS7_0: unmask the LFSR bits[7:0]
\arg DAC_LFSR_BITS8_0: unmask the LFSR bits[8:0]
\arg DAC_LFSR_BITS9_0: unmask the LFSR bits[9:0]
\arg DAC_LFSR_BITS10_0: unmask the LFSR bits[10:0]
\arg DAC_LFSR_BITS11_0: unmask the LFSR bits[11:0]
\param[out] none
\retval none
*/
void dac_lfsr_noise_config(uint8_t dac_out, uint32_t unmask_bits)
{
if(DAC_OUT_0 == dac_out){
/* configure DAC_OUT0 LFSR noise mode */
DAC_CTL0 &= ~DAC_CTL0_DWBW0;
DAC_CTL0 |= unmask_bits;
}else{
/* configure DAC_OUT1 LFSR noise mode */
DAC_CTL0 &= ~DAC_CTL0_DWBW1;
DAC_CTL0 |= (unmask_bits << OUT1_REG_OFFSET);
}
}
/*!
\brief configure DAC triangle noise mode
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] amplitude: the amplitude of the triangle
only one parameter can be selected which is shown as below:
\arg DAC_TRIANGLE_AMPLITUDE_1: triangle amplitude is 1
\arg DAC_TRIANGLE_AMPLITUDE_3: triangle amplitude is 3
\arg DAC_TRIANGLE_AMPLITUDE_7: triangle amplitude is 7
\arg DAC_TRIANGLE_AMPLITUDE_15: triangle amplitude is 15
\arg DAC_TRIANGLE_AMPLITUDE_31: triangle amplitude is 31
\arg DAC_TRIANGLE_AMPLITUDE_63: triangle amplitude is 63
\arg DAC_TRIANGLE_AMPLITUDE_127: triangle amplitude is 127
\arg DAC_TRIANGLE_AMPLITUDE_255: triangle amplitude is 255
\arg DAC_TRIANGLE_AMPLITUDE_511: triangle amplitude is 511
\arg DAC_TRIANGLE_AMPLITUDE_1023: triangle amplitude is 1023
\arg DAC_TRIANGLE_AMPLITUDE_2047: triangle amplitude is 2047
\arg DAC_TRIANGLE_AMPLITUDE_4095: triangle amplitude is 4095
\param[out] none
\retval none
*/
void dac_triangle_noise_config(uint8_t dac_out, uint32_t amplitude)
{
if(DAC_OUT_0 == dac_out){
/* configure DAC_OUT0 triangle noise mode */
DAC_CTL0 &= ~DAC_CTL0_DWBW0;
DAC_CTL0 |= amplitude;
}else{
/* configure DAC_OUT1 triangle noise mode */
DAC_CTL0 &= ~DAC_CTL0_DWBW1;
DAC_CTL0 |= (amplitude << OUT1_REG_OFFSET);
}
}
/*!
\brief enable DAC concurrent mode
\param[in] none
\param[out] none
\retval none
*/
void dac_concurrent_enable(void)
{
uint32_t ctl = 0U;
ctl = (uint32_t)(DAC_CTL0_DEN0 | DAC_CTL0_DEN1);
DAC_CTL0 |= (uint32_t)(ctl);
}
/*!
\brief disable DAC concurrent mode
\param[in] none
\param[out] none
\retval none
*/
void dac_concurrent_disable(void)
{
uint32_t ctl = 0U;
ctl = (uint32_t)(DAC_CTL0_DEN0 | DAC_CTL0_DEN1);
DAC_CTL0 &= (uint32_t)(~ctl);
}
/*!
\brief enable DAC concurrent software trigger
\param[in] none
\param[out] none
\retval none
*/
void dac_concurrent_software_trigger_enable(void)
{
uint32_t swt = 0U;
swt = (uint32_t)(DAC_SWT_SWTR0 | DAC_SWT_SWTR1);
DAC_SWT |= (uint32_t)(swt);
}
/*!
\brief disable DAC concurrent software trigger
\param[in] none
\param[out] none
\retval none
*/
void dac_concurrent_software_trigger_disable(void)
{
uint32_t swt = 0U;
swt = (uint32_t)(DAC_SWT_SWTR0 | DAC_SWT_SWTR1);
DAC_SWT &= (uint32_t)(~swt);
}
/*!
\brief enable DAC concurrent buffer
\param[in] none
\param[out] none
\retval none
*/
void dac_concurrent_output_buffer_enable(void)
{
uint32_t ctl = 0U;
ctl = (uint32_t)(DAC_CTL0_DBOFF0 | DAC_CTL0_DBOFF1);
DAC_CTL0 &= (uint32_t)(~ctl);
}
/*!
\brief disable DAC concurrent buffer
\param[in] none
\param[out] none
\retval none
*/
void dac_concurrent_output_buffer_disable(void)
{
uint32_t ctl = 0U;
ctl = (uint32_t)(DAC_CTL0_DBOFF0 | DAC_CTL0_DBOFF1);
DAC_CTL0 |= (uint32_t)(ctl);
}
/*!
\brief set DAC concurrent mode data holding register value
\param[in] dac_align: DAC data alignment mode
only one parameter can be selected which is shown as below:
\arg DAC_ALIGN_12B_R: 12-bit right-aligned data
\arg DAC_ALIGN_12B_L: 12-bit left-aligned data
\arg DAC_ALIGN_8B_R: 8-bit right-aligned data
\param[in] data0: data to be loaded, 0~4095
\param[in] data1: data to be loaded, 0~4095
\param[out] none
\retval none
*/
void dac_concurrent_data_set(uint32_t dac_align, uint16_t data0, uint16_t data1)
{
uint32_t data = 0U;
switch(dac_align){
/* 12-bit right-aligned data */
case DAC_ALIGN_12B_R:
data = (uint32_t)(((uint32_t)data1 << DH_12BIT_OFFSET) | data0);
DACC_R12DH = (uint32_t)data;
break;
/* 12-bit left-aligned data */
case DAC_ALIGN_12B_L:
data = (uint32_t)(((uint32_t)data1 << DH_12BIT_OFFSET) | data0);
DACC_L12DH = (uint32_t)data;
break;
/* 8-bit right-aligned data */
case DAC_ALIGN_8B_R:
data = (uint32_t)(((uint32_t)data1 << DH_8BIT_OFFSET) | data0);
DACC_R8DH = (uint32_t)data;
break;
default:
break;
}
}
/*!
\brief get DAC flag
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] dac_flag: DAC flag
only one parameter can be selected which is shown as below:
\arg DAC_FLAG_DDUDR0: DAC_OUT0 DMA underrun flag
\arg DAC_FLAG_FF0: DAC_OUT0 FIFO full flag
\arg DAC_FLAG_FE0: DAC_OUT0 FIFO empty flag
\arg DAC_FLAG_FIFOOVR0: DAC_OUT0 FIFO overflow flag
\arg DAC_FLAG_FIFOUDR0: DAC_OUT0 FIFO underflow flag
\arg DAC_FLAG_DDUDR1: DAC_OUT1 DMA underrun flag
\arg DAC_FLAG_FF1: DAC_OUT1 FIFO full flag
\arg DAC_FLAG_FE1: DAC_OUT1 FIFO empty flag
\arg DAC_FLAG_FIFOOVR1: DAC_OUT1 FIFO overflow flag
\arg DAC_FLAG_FIFOUDR1: DAC_OUT1 FIFO underflow flag
\param[out] none
\retval FlagStatus: SET or RESET
*/
FlagStatus dac_flag_get(uint8_t dac_out, uint32_t flag)
{
if(DAC_OUT_0 == dac_out){
/* check DAC_OUT0 flag */
if(DAC_FLAG_DDUDR0 == flag){
if(RESET != (DAC_STAT0 & DAC_STAT0_DDUDR0)){
return SET;
}else{
return RESET;
}
}else{
if(RESET != (DAC_STAT1 & flag)){
return SET;
}else{
return RESET;
}
}
}else{
/* check DAC_OUT1 flag */
if(DAC_FLAG_DDUDR1 == flag){
if(RESET != (DAC_STAT0 & DAC_STAT0_DDUDR1)){
return SET;
}else{
return RESET;
}
}else{
if(RESET != (DAC_STAT1 & flag)){
return SET;
}else{
return RESET;
}
}
}
}
/*!
\brief clear DAC flag
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] flag: DAC flag
only one parameter can be selected which is shown as below:
\arg DAC_FLAG_DDUDR0: DAC_OUT0 DMA underrun flag
\arg DAC_FLAG_FIFOOVR0: DAC_OUT0 FIFO overflow flag
\arg DAC_FLAG_FIFOUDR0: DAC_OUT0 FIFO underflow flag
\arg DAC_FLAG_DDUDR1: DAC_OUT1 DMA underrun flag
\arg DAC_FLAG_FIFOOVR1: DAC_OUT1 FIFO overflow flag
\arg DAC_FLAG_FIFOUDR1: DAC_OUT1 FIFO underflow flag
\param[out] none
\retval none
*/
void dac_flag_clear(uint8_t dac_out, uint32_t flag)
{
if(DAC_OUT_0 == dac_out){
/* clear DAC_OUT0 flag */
if(DAC_FLAG_DDUDR0 == flag){
DAC_STAT0 |= (uint32_t)DAC_STAT0_DDUDR0;
}else{
DAC_STAT1 |= (uint32_t)flag;
}
}else{
/* clear DAC_OUT1 flag */
if(DAC_FLAG_DDUDR1 == flag){
DAC_STAT0 |= (uint32_t)DAC_STAT0_DDUDR1;
}else{
DAC_STAT1 |= (uint32_t)flag;
}
}
}
/*!
\brief enable DAC interrupt
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] interrupt: the DAC interrupt
only one parameter can be selected which is shown as below:
\arg DAC_INT_DDUDRIE0: DAC_OUT0 DMA underrun interrupt enable
\arg DAC_INT_FIFOOVRIE0: DAC_OUT0 FIFO overflow interrupt enable
\arg DAC_INT_FIFOUDRIE0: DAC_OUT0 FIFO underflow interrupt enable
\arg DAC_INT_DDUDRIE1: DAC_OUT1 DMA underrun interrupt enable
\arg DAC_INT_FIFOOVRIE1: DAC_OUT1 FIFO overflow interrupt enable
\arg DAC_INT_FIFOUDRIE1: DAC_OUT1 FIFO underflow interrupt enable
\param[out] none
\retval none
*/
void dac_interrupt_enable(uint8_t dac_out, uint32_t interrupt)
{
if(DAC_OUT_0 == dac_out){
/* enable DAC_OUT0 interrupt */
if(DAC_INT_DDUDRIE0 == interrupt){
DAC_CTL0 |= (uint32_t)DAC_CTL0_DDUDRIE0;
}else{
DAC_CTL1 |= (uint32_t)interrupt;
}
}else{
/* enable DAC_OUT1 interrupt */
if(DAC_INT_DDUDRIE1 == interrupt){
DAC_CTL0 |= (uint32_t)DAC_CTL0_DDUDRIE1;
}else{
DAC_CTL1 |= (uint32_t)interrupt;
}
}
}
/*!
\brief disable DAC interrupt
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] interrupt: the DAC interrupt
only one parameter can be selected which is shown as below:
\arg DAC_INT_DDUDRIE0: DAC_OUT0 DMA underrun interrupt disable
\arg DAC_INT_FIFOOVRIE0: DAC_OUT0 FIFO overflow interrupt disable
\arg DAC_INT_FIFOUDRIE0: DAC_OUT0 FIFO underflow interrupt disable
\arg DAC_INT_DDUDRIE1: DAC_OUT1 DMA underrun interrupt disable
\arg DAC_INT_FIFOOVRIE1: DAC_OUT1 FIFO overflow interrupt disable
\arg DAC_INT_FIFOUDRIE1: DAC_OUT1 FIFO underflow interrupt disable
\param[out] none
\retval none
*/
void dac_interrupt_disable(uint8_t dac_out, uint32_t interrupt)
{
if(DAC_OUT_0 == dac_out){
/* disable DAC_OUT0 interrupt */
if(DAC_INT_DDUDRIE0 == interrupt){
DAC_CTL0 &= (uint32_t)(~DAC_CTL0_DDUDRIE0);
}else{
DAC_CTL1 &= (uint32_t)(~interrupt);
}
}else{
/* disable DAC_OUT1 interrupt */
if(DAC_INT_DDUDRIE1 == interrupt){
DAC_CTL0 &= (uint32_t)(~DAC_CTL0_DDUDRIE1);
}else{
DAC_CTL1 &= (uint32_t)(~interrupt);
}
}
}
/*!
\brief get DAC interrupt flag
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] int_flag: DAC interrupt flag
only one parameter can be selected which is shown as below:
\arg DAC_INT_FLAG_DDUDR0: DAC_OUT0 DMA underrun interrupt flag
\arg DAC_INT_FLAG_FIFOOVR0: DAC_OUT0 FIFO overflow interrupt flag
\arg DAC_INT_FLAG_FIFOUDR0: DAC_OUT0 FIFO underflow interrupt flag
\arg DAC_INT_FLAG_DDUDR1: DAC_OUT1 DMA underrun interrupt flag
\arg DAC_INT_FLAG_FIFOOVR1: DAC_OUT1 FIFO overflow interrupt flag
\arg DAC_INT_FLAG_FIFOUDR1: DAC_OUT1 FIFO underflow interrupt flag
\param[out] none
\retval the state of DAC interrupt flag(SET or RESET)
*/
FlagStatus dac_interrupt_flag_get(uint8_t dac_out, uint32_t int_flag)
{
uint32_t reg1 = 0U, reg2 = 0U;
/* check DAC_OUT0 flag */
if(DAC_OUT_0 == dac_out){
/* check DAC_OUT0 interrupt flag */
if(DAC_INT_FLAG_DDUDR0 == int_flag){
reg1 = DAC_STAT0 & DAC_STAT0_DDUDR0;
reg2 = DAC_CTL0 & DAC_CTL0_DDUDRIE0;
}else if(DAC_INT_FLAG_FIFOOVR0 == int_flag){
reg1 = DAC_STAT1 & DAC_STAT1_FIFOOVR0;
reg2 = DAC_CTL1 & DAC_CTL1_FIFOOVRIE0;
}else{
reg1 = DAC_STAT1 & DAC_FLAG_FIFOUDR0;
reg2 = DAC_CTL1 & DAC_INT_FIFOUDRIE0;
}
}else{
/* check DAC_OUT1 interrupt flag */
if(DAC_INT_FLAG_DDUDR1 == int_flag){
reg1 = DAC_STAT0 & DAC_STAT0_DDUDR1;
reg2 = DAC_CTL0 & DAC_CTL0_DDUDRIE1;
}else if(DAC_INT_FLAG_FIFOOVR1 == int_flag){
reg1 = DAC_STAT1 & DAC_STAT1_FIFOOVR1;
reg2 = DAC_CTL1 & DAC_CTL1_FIFOOVRIE1;
}else{
reg1 = DAC_STAT1 & DAC_FLAG_FIFOUDR1;
reg2 = DAC_CTL1 & DAC_INT_FIFOUDRIE1;
}
}
/*get DAC interrupt flag status */
if((RESET != reg1) && (RESET != reg2)){
return SET;
}else{
return RESET;
}
}
/*!
\brief clear DAC interrupt flag
\param[in] dac_out: DAC_OUT_x(x=0,1)
\param[in] int_flag: DAC interrupt flag
only one parameter can be selected which is shown as below:
\arg DAC_INT_FLAG_DDUDR0: DAC_OUT0 DMA underrun interrupt flag
\arg DAC_INT_FLAG_FIFOOVR0: DAC_OUT0 FIFO overflow interrupt flag
\arg DAC_INT_FLAG_FIFOUDR0: DAC_OUT0 FIFO underflow interrupt flag
\arg DAC_INT_FLAG_DDUDR1: DAC_OUT1 DMA underrun interrupt flag
\arg DAC_INT_FLAG_FIFOOVR1: DAC_OUT1 FIFO overflow interrupt flag
\arg DAC_INT_FLAG_FIFOUDR1: DAC_OUT1 FIFO underflow interrupt flag
\param[out] none
\retval none
*/
void dac_interrupt_flag_clear(uint8_t dac_out, uint32_t int_flag)
{
if(DAC_OUT_0 == dac_out){
/* clear DAC_OUT0 interrupt flag */
if(DAC_INT_FLAG_DDUDR0 == int_flag){
DAC_STAT0 |= (uint32_t)DAC_STAT0_DDUDR0;
}else{
DAC_STAT1 |= (uint32_t)int_flag;
}
}else{
/* clear DAC_OUT1 interrupt flag */
if(DAC_INT_FLAG_DDUDR1 == int_flag){
DAC_STAT0 |= (uint32_t)DAC_STAT0_DDUDR1;
}else{
DAC_STAT1 |= (uint32_t)int_flag;
}
}
}
| 31.916067 | 128 | 0.623976 |
3671187aca532ea5805eda9b6489beb0f82a178b | 2,686 | h | C | external/source/meterpreter/source/bionic/libc/kernel/common/linux/raid/md_u.h | truekonrads/mirv-metasploit | 36bcc1f7f57d67636f4479afc75c2832f12ea466 | [
"BSD-3-Clause"
] | 264 | 2015-01-02T10:15:42.000Z | 2022-03-31T06:59:13.000Z | external/source/meterpreter/source/bionic/libc/kernel/common/linux/raid/md_u.h | truekonrads/mirv-metasploit | 36bcc1f7f57d67636f4479afc75c2832f12ea466 | [
"BSD-3-Clause"
] | 112 | 2015-01-02T01:26:38.000Z | 2021-11-21T02:07:21.000Z | external/source/meterpreter/source/bionic/libc/kernel/common/linux/raid/md_u.h | truekonrads/mirv-metasploit | 36bcc1f7f57d67636f4479afc75c2832f12ea466 | [
"BSD-3-Clause"
] | 130 | 2015-01-02T05:29:46.000Z | 2022-03-18T19:50:39.000Z | /****************************************************************************
****************************************************************************
***
*** This header was automatically generated from a Linux kernel header
*** of the same name, to make information necessary for userspace to
*** call into the kernel available to libc. It contains only constants,
*** structures, and macros generated from the original header, and thus,
*** contains no copyrightable information.
***
****************************************************************************
****************************************************************************/
#ifndef _MD_U_H
#define _MD_U_H
#define RAID_VERSION _IOR (MD_MAJOR, 0x10, mdu_version_t)
#define GET_ARRAY_INFO _IOR (MD_MAJOR, 0x11, mdu_array_info_t)
#define GET_DISK_INFO _IOR (MD_MAJOR, 0x12, mdu_disk_info_t)
#define PRINT_RAID_DEBUG _IO (MD_MAJOR, 0x13)
#define RAID_AUTORUN _IO (MD_MAJOR, 0x14)
#define GET_BITMAP_FILE _IOR (MD_MAJOR, 0x15, mdu_bitmap_file_t)
#define CLEAR_ARRAY _IO (MD_MAJOR, 0x20)
#define ADD_NEW_DISK _IOW (MD_MAJOR, 0x21, mdu_disk_info_t)
#define HOT_REMOVE_DISK _IO (MD_MAJOR, 0x22)
#define SET_ARRAY_INFO _IOW (MD_MAJOR, 0x23, mdu_array_info_t)
#define SET_DISK_INFO _IO (MD_MAJOR, 0x24)
#define WRITE_RAID_INFO _IO (MD_MAJOR, 0x25)
#define UNPROTECT_ARRAY _IO (MD_MAJOR, 0x26)
#define PROTECT_ARRAY _IO (MD_MAJOR, 0x27)
#define HOT_ADD_DISK _IO (MD_MAJOR, 0x28)
#define SET_DISK_FAULTY _IO (MD_MAJOR, 0x29)
#define HOT_GENERATE_ERROR _IO (MD_MAJOR, 0x2a)
#define SET_BITMAP_FILE _IOW (MD_MAJOR, 0x2b, int)
#define RUN_ARRAY _IOW (MD_MAJOR, 0x30, mdu_param_t)
#define START_ARRAY _IO (MD_MAJOR, 0x31)
#define STOP_ARRAY _IO (MD_MAJOR, 0x32)
#define STOP_ARRAY_RO _IO (MD_MAJOR, 0x33)
#define RESTART_ARRAY_RW _IO (MD_MAJOR, 0x34)
typedef struct mdu_version_s {
int major;
int minor;
int patchlevel;
} mdu_version_t;
typedef struct mdu_array_info_s {
int major_version;
int minor_version;
int patch_version;
int ctime;
int level;
int size;
int nr_disks;
int raid_disks;
int md_minor;
int not_persistent;
int utime;
int state;
int active_disks;
int working_disks;
int failed_disks;
int spare_disks;
int layout;
int chunk_size;
} mdu_array_info_t;
typedef struct mdu_disk_info_s {
int number;
int major;
int minor;
int raid_disk;
int state;
} mdu_disk_info_t;
typedef struct mdu_start_info_s {
int major;
int minor;
int raid_disk;
int state;
} mdu_start_info_t;
typedef struct mdu_bitmap_file_s
{
char pathname[4096];
} mdu_bitmap_file_t;
typedef struct mdu_param_s
{
int personality;
int chunk_size;
int max_fault;
} mdu_param_t;
#endif
| 25.580952 | 78 | 0.682055 |
36b0b61f5393ac15fc7d15a62b8cd724bf7acecf | 647 | h | C | C/erfinv.h | CharleySchaefer/erfinv | b38f46fd4a6dc103afe66fbab571fadf5a51fe52 | [
"MIT"
] | null | null | null | C/erfinv.h | CharleySchaefer/erfinv | b38f46fd4a6dc103afe66fbab571fadf5a51fe52 | [
"MIT"
] | null | null | null | C/erfinv.h | CharleySchaefer/erfinv | b38f46fd4a6dc103afe66fbab571fadf5a51fe52 | [
"MIT"
] | 1 | 2018-06-20T22:23:39.000Z | 2018-06-20T22:23:39.000Z | #ifndef LAKSHAYG_ERFINV_H
#define LAKSHAYG_ERFINV_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <stdarg.h>
// Returns a floating point number y such that std::erf(y)
// is close to x. The current implementation is quite accurate
// when x is away from +1.0 and -1.0. As x approaches closer
// to those values, the error in the result increases.
long double erfinv(long double );
// Refine the result of erfinv by performing Newton-Raphson
// iteration nr_iter number of times. This method works well
// when the value of x is away from 1.0 and -1.0
long double erfinv_iter(long double , int);
#endif
| 29.409091 | 62 | 0.741886 |
9ad2851c7afeb8ecd3ab155cce52c1d8d97ad79f | 1,700 | h | C | src/objects/js-regexp-string-iterator.h | xtuc/v8 | 86894d98bfe79f46c51e27b0699f7bfcc07fe0b2 | [
"BSD-3-Clause"
] | 4 | 2019-04-20T15:56:13.000Z | 2019-12-23T07:14:01.000Z | src/objects/js-regexp-string-iterator.h | xtuc/v8 | 86894d98bfe79f46c51e27b0699f7bfcc07fe0b2 | [
"BSD-3-Clause"
] | 1 | 2019-02-13T09:53:48.000Z | 2019-02-13T09:53:48.000Z | src/objects/js-regexp-string-iterator.h | xtuc/v8 | 86894d98bfe79f46c51e27b0699f7bfcc07fe0b2 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_JS_REGEXP_STRING_ITERATOR_H_
#define V8_OBJECTS_JS_REGEXP_STRING_ITERATOR_H_
#include "src/objects/js-objects.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
class JSRegExpStringIterator : public JSObject {
public:
// [regexp]: the [[IteratingRegExp]] internal property.
DECL_ACCESSORS(iterating_regexp, Object)
// [string]: The [[IteratedString]] internal property.
DECL_ACCESSORS(iterating_string, String)
DECL_INT_ACCESSORS(flags)
// [boolean]: The [[Done]] internal property.
DECL_BOOLEAN_ACCESSORS(done)
// [boolean]: The [[Global]] internal property.
DECL_BOOLEAN_ACCESSORS(global)
// [boolean]: The [[Unicode]] internal property.
DECL_BOOLEAN_ACCESSORS(unicode)
DECL_CAST(JSRegExpStringIterator)
DECL_PRINTER(JSRegExpStringIterator)
DECL_VERIFIER(JSRegExpStringIterator)
static const int kIteratingRegExpOffset = JSObject::kHeaderSize;
static const int kIteratedStringOffset =
kIteratingRegExpOffset + kPointerSize;
static const int kFlagsOffset = kIteratedStringOffset + kPointerSize;
static const int kSize = kFlagsOffset + kPointerSize;
static const int kDoneBit = 0;
static const int kGlobalBit = 1;
static const int kUnicodeBit = 2;
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpStringIterator);
};
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_JS_REGEXP_STRING_ITERATOR_H_
| 28.333333 | 73 | 0.770588 |
82fc5e70009d0eb735ad3d7050ca6c8dbc7b537a | 340 | h | C | cpp/semaphore.h | DevinCarr/utils | ec88369b09139e72ee4288c4bc10f0e3144f3e8c | [
"MIT"
] | null | null | null | cpp/semaphore.h | DevinCarr/utils | ec88369b09139e72ee4288c4bc10f0e3144f3e8c | [
"MIT"
] | null | null | null | cpp/semaphore.h | DevinCarr/utils | ec88369b09139e72ee4288c4bc10f0e3144f3e8c | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2016 Devin Carr
* Licensed under MIT (https://github.com/devincarr/utils/blob/master/LICENSE)
*/
#pragma once
#include <condition_variable>
#include <mutex>
class Semaphore {
private:
int value;
std::mutex m;
std::condition_variable c;
public:
Semaphore(int _val);
~Semaphore();
int P();
int V();
};
| 14.782609 | 78 | 0.676471 |
aab89eaebf4be8a3eb3f76ecb3c0577f1e2b3425 | 3,085 | h | C | src/redis_index.h | ashtul/RediSearch | 8aac2bc22fba75bd45ab3c3a12b4ce04fadd33c7 | [
"Ruby",
"MIT"
] | null | null | null | src/redis_index.h | ashtul/RediSearch | 8aac2bc22fba75bd45ab3c3a12b4ce04fadd33c7 | [
"Ruby",
"MIT"
] | null | null | null | src/redis_index.h | ashtul/RediSearch | 8aac2bc22fba75bd45ab3c3a12b4ce04fadd33c7 | [
"Ruby",
"MIT"
] | 1 | 2019-02-04T11:54:56.000Z | 2019-02-04T11:54:56.000Z | #ifndef __REDIS_INDEX__
#define __REDIS_INDEX__
#include "document.h"
#include "index.h"
#include "inverted_index.h"
#include "search_ctx.h"
#include "concurrent_ctx.h"
#include "spec.h"
/* Open an inverted index reader on a redis DMA string, for a specific term.
* If singleWordMode is set to 1, we do not load the skip index, only the score index
*/
IndexReader *Redis_OpenReader(RedisSearchCtx *ctx, RSQueryTerm *term, DocTable *dt,
int singleWordMode, t_fieldMask fieldMask, ConcurrentSearchCtx *csx,
double weight);
InvertedIndex *Redis_OpenInvertedIndexEx(RedisSearchCtx *ctx, const char *term, size_t len,
int write, RedisModuleKey **keyp);
#define Redis_OpenInvertedIndex(ctx, term, len, isWrite) \
Redis_OpenInvertedIndexEx(ctx, term, len, isWrite, NULL)
void Redis_CloseReader(IndexReader *r);
/*
* Select a random term from the index that matches the index prefix and inveted key format.
* It tries RANDOMKEY 10 times and returns NULL if it can't find anything.
*/
const char *Redis_SelectRandomTerm(RedisSearchCtx *ctx, size_t *tlen);
#define TERM_KEY_FORMAT "ft:%s/%.*s"
#define TERM_KEY_PREFIX "ft:"
#define SKIPINDEX_KEY_FORMAT "si:%s/%.*s"
#define SCOREINDEX_KEY_FORMAT "ss:%s/%.*s"
#define INVERTED_INDEX_ENCVER 1
#define INVERTED_INDEX_NOFREQFLAG_VER 0
typedef int (*ScanFunc)(RedisModuleCtx *ctx, RedisModuleString *keyName, void *opaque);
/* Scan the keyspace with MATCH for a prefix, and call ScanFunc for each key found */
int Redis_ScanKeys(RedisModuleCtx *ctx, const char *prefix, ScanFunc f, void *opaque);
/* Optimize the buffers of a speicif term hit */
int Redis_OptimizeScanHandler(RedisModuleCtx *ctx, RedisModuleString *kn, void *opaque);
/* Drop the index and all the associated keys.
*
* If deleteDocuments is non zero, we will delete the saved documents (if they exist).
* Only set this if there are no other indexes in the same redis instance.
*/
int Redis_DropIndex(RedisSearchCtx *ctx, int deleteDocuments, int deleteSpecKey);
/* Drop all the index's internal keys using this scan handler */
int Redis_DropScanHandler(RedisModuleCtx *ctx, RedisModuleString *kn, void *opaque);
/* Collect memory stas on the index */
int Redis_StatsScanHandler(RedisModuleCtx *ctx, RedisModuleString *kn, void *opaque);
/**
* Format redis key for a term.
* TODO: Add index name to it
*/
RedisModuleString *fmtRedisTermKey(RedisSearchCtx *ctx, const char *term, size_t len);
RedisModuleString *fmtRedisSkipIndexKey(RedisSearchCtx *ctx, const char *term, size_t len);
RedisModuleString *fmtRedisNumericIndexKey(RedisSearchCtx *ctx, const char *field);
extern RedisModuleType *InvertedIndexType;
void InvertedIndex_Free(void *idx);
void *InvertedIndex_RdbLoad(RedisModuleIO *rdb, int encver);
void InvertedIndex_RdbSave(RedisModuleIO *rdb, void *value);
void InvertedIndex_Digest(RedisModuleDigest *digest, void *value);
int InvertedIndex_RegisterType(RedisModuleCtx *ctx);
unsigned long InvertedIndex_MemUsage(const void *value);
#endif | 41.133333 | 98 | 0.755592 |
c5679a883038499defebef1915948d8093667a97 | 1,944 | h | C | pw_checksum/public/pw_checksum/ccitt_crc16.h | LastRitter/pigweed | 7cf23ab0d7b70bd468baa6f7454486f373c95cf7 | [
"Apache-2.0"
] | 43 | 2020-03-20T21:07:13.000Z | 2021-11-23T17:34:02.000Z | pw_checksum/public/pw_checksum/ccitt_crc16.h | LastRitter/pigweed | 7cf23ab0d7b70bd468baa6f7454486f373c95cf7 | [
"Apache-2.0"
] | 2 | 2021-06-08T21:43:09.000Z | 2021-09-08T02:06:57.000Z | pw_checksum/public/pw_checksum/ccitt_crc16.h | LastRitter/pigweed | 7cf23ab0d7b70bd468baa6f7454486f373c95cf7 | [
"Apache-2.0"
] | 12 | 2020-03-21T01:02:26.000Z | 2022-01-04T01:35:14.000Z | // Copyright 2020 The Pigweed Authors
//
// 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
//
// https://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.
// Provides an implementation of the CCITT CRC16 for the polynomial
//
// x^16 + x^12 + x^5 + 1
//
// Polynomial 0x1021, initial value 0xFFFF. See https://www.zlib.net/crc_v3.txt.
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// C API for calculating the CCITT CRC16 of an array of data.
uint16_t pw_ChecksumCcittCrc16(const void* data,
size_t size_bytes,
uint16_t initial_value);
#ifdef __cplusplus
} // extern "C"
#include "pw_span/span.h"
namespace pw::checksum {
inline constexpr uint16_t kCcittCrc16DefaultInitialValue = 0xFFFF;
// Calculates the CCITT CRC16 for the provided data. To update an existing CRC,
// pass the previous value as the initial_value argument.
inline uint16_t CcittCrc16(
span<const std::byte> data,
uint16_t initial_value = kCcittCrc16DefaultInitialValue) {
return pw_ChecksumCcittCrc16(data.data(), data.size_bytes(), initial_value);
}
// Calculates the CCITT CRC16 for a single byte. This is useful for updating a
// CRC byte-by-byte.
inline uint16_t CcittCrc16(
std::byte value, uint16_t initial_value = kCcittCrc16DefaultInitialValue) {
return pw_ChecksumCcittCrc16(&value, sizeof(value), initial_value);
}
} // namespace pw::checksum
#endif // __cplusplus
| 31.868852 | 80 | 0.725823 |
cf5e8f4e718a1946eb8fd7510ae1860183ca9cea | 2,247 | h | C | os/include/tinyara/sercomm/sercomm.h | shan-hu/SamsungTizenRT_Sept_2017 | 67f06c94e56f89193e42b96691aed8ee196622ac | [
"Apache-2.0"
] | 2 | 2019-01-27T14:50:42.000Z | 2019-01-27T14:51:25.000Z | os/include/tinyara/sercomm/sercomm.h | shan-hu/SamsungTizenRT_Sept_2017 | 67f06c94e56f89193e42b96691aed8ee196622ac | [
"Apache-2.0"
] | 1 | 2017-10-19T18:20:33.000Z | 2017-10-19T18:20:33.000Z | os/include/tinyara/sercomm/sercomm.h | shan-hu/SamsungTizenRT_Sept_2017 | 67f06c94e56f89193e42b96691aed8ee196622ac | [
"Apache-2.0"
] | 1 | 2020-02-27T09:33:42.000Z | 2020-02-27T09:33:42.000Z | /****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#ifndef _SERCOMM_H
#define _SERCOMM_H
/* SERCOMM layer on UART1 (modem UART) */
#include <osmocom/core/msgb.h>
#define SERCOMM_UART_NR 1
#define HDLC_FLAG 0x7E
#define HDLC_ESCAPE 0x7D
#define HDLC_C_UI 0x03
#define HDLC_C_P_BIT (1 << 4)
#define HDLC_C_F_BIT (1 << 4)
/* a low sercomm_dlci means high priority. A high DLCI means low priority */
enum sercomm_dlci {
SC_DLCI_HIGHEST = 0,
SC_DLCI_DEBUG = 4,
SC_DLCI_L1A_L23 = 5,
SC_DLCI_LOADER = 9,
SC_DLCI_CONSOLE = 10,
SC_DLCI_ECHO = 128,
_SC_DLCI_MAX
};
void sercomm_init(void);
int sercomm_initialized(void);
/* User Interface: Tx */
/* user interface for transmitting messages for a given DLCI */
void sercomm_sendmsg(uint8_t dlci, struct msgb *msg);
/* how deep is the Tx queue for a given DLCI */
unsigned int sercomm_tx_queue_depth(uint8_t dlci);
/* User Interface: Rx */
/* receiving messages for a given DLCI */
typedef void (*dlci_cb_t)(uint8_t dlci, struct msgb *msg);
int sercomm_register_rx_cb(uint8_t dlci, dlci_cb_t cb);
/* Driver Interface */
/* fetch one octet of to-be-transmitted serial data. returns 0 if no more data */
int sercomm_drv_pull(uint8_t *ch);
/* the driver has received one byte, pass it into sercomm layer.
returns 1 in case of success, 0 in case of unrecognized char */
int sercomm_drv_rx_char(uint8_t ch);
static inline struct msgb *sercomm_alloc_msgb(unsigned int len)
{
return msgb_alloc_headroom(len + 4, 4, "sercomm_tx");
}
#endif /* _SERCOMM_H */
| 29.96 | 81 | 0.690699 |
a961bd968b9959cea7e3b02f4868bf7af60d470d | 2,299 | h | C | gsoap/VisualStudio2005/wsdl2h/wsdl2h/sp.h | JinpengLI/gsoap | 58ba1cfaee90f6f018ef81e9cb63fbd8e1af4566 | [
"Zlib",
"OpenSSL",
"Unlicense"
] | null | null | null | gsoap/VisualStudio2005/wsdl2h/wsdl2h/sp.h | JinpengLI/gsoap | 58ba1cfaee90f6f018ef81e9cb63fbd8e1af4566 | [
"Zlib",
"OpenSSL",
"Unlicense"
] | 1 | 2017-07-17T17:30:47.000Z | 2017-07-24T21:20:44.000Z | gsoap/wsdl/sp.h | JinpengLI/gsoap | 58ba1cfaee90f6f018ef81e9cb63fbd8e1af4566 | [
"Zlib",
"OpenSSL",
"Unlicense"
] | null | null | null | /*
sp.h
WS-SecurityPolicy 1.2 binding schemas
--------------------------------------------------------------------------------
gSOAP XML Web services tools
Copyright (C) 2001-2010, Robert van Engelen, Genivia Inc. All Rights Reserved.
This software is released under one of the following two licenses:
GPL or Genivia's license for commercial use.
--------------------------------------------------------------------------------
GPL license.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
Author contact information:
engelen@genivia.com / engelen@acm.org
--------------------------------------------------------------------------------
A commercial use license is available from Genivia, Inc., contact@genivia.com
--------------------------------------------------------------------------------
*/
//gsoap sp schema documentation: WS-SecurityPolicy binding
//gsoap sp schema namespace: http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702
// 1.1 //gsoap sp schema namespace: http://schemas.xmlsoap.org/ws/2005/07/securitypolicy
//gsoap sp schema elementForm: qualified
//gsoap sp schema attributeForm: unqualified
#import "imports.h"
#import "wsam.h"
#import "wst.h"
class sp__Header
{ public:
@xsd__NCName Name;
@xsd__anyURI Namespace;
};
class sp__Parts
{ public:
xsd__string Body;
std::vector<sp__Header> Header;
xsd__string Attachments;
};
class sp__Elements
{ public:
@xsd__anyURI XPathVersion;
std::vector<xsd__string> XPath;
};
class sp__Token : public wsp__Assertion
{ public:
@xsd__anyURI IncludeToken;
wsa__EndpointReferenceType *Issuer;
xsd__anyURI IssuerName;
wst__Claims *wst__Claims_;
};
| 32.380282 | 88 | 0.658112 |
ca088de1fc51dce8530c34d70e472c32aa7de8a4 | 1,479 | h | C | fahes_service/OD.h | daqcri/Fahes_GUI | a37f0d3dfdbcd3162bae30ae284aab1197ce9f8b | [
"MIT"
] | 6 | 2019-05-09T04:24:06.000Z | 2021-04-17T16:01:02.000Z | fahes_service/OD.h | daqcri/Fahes_GUI | a37f0d3dfdbcd3162bae30ae284aab1197ce9f8b | [
"MIT"
] | 1 | 2020-10-08T11:19:03.000Z | 2020-10-08T11:19:03.000Z | fahes_service/OD.h | daqcri/Fahes_GUI | a37f0d3dfdbcd3162bae30ae284aab1197ce9f8b | [
"MIT"
] | 3 | 2019-07-09T17:18:44.000Z | 2021-05-26T13:52:16.000Z | /**************************************
**** 2017-6-5 ******************
**** Abdulhakim Qahtan ****************
**** aqahtan@hbku.edu.qa ****************
***************************************/
/****************************************************************************
-- num_non_ignorable_strings: if the column contains more than num_non_ignorable_strings
then outlier detection is applicable
-- num_od_tools: the number of outlier detection tools that will be used
-- sq: the exponent that will be used in the pow() function
-- least_num_values: is the least number of distinct values to be able to run
outlier detection
****************************************************************************/
#ifndef _Outlier_Detector_
#define _Outlier_Detector_
#include "Table.h"
#include "common.h"
class OD {
int num_non_ignorable_strings = 3;
int num_od_tools = 1;
int EX = 2;
int least_num_values = 10;
public:
OD(){ }
// double z_score(double val, const double & mean, const double & std){
// double z_sc = (fabs(val - mean)) / std;
// return z_sc;
// }
void compute_statistical_quantities(map<double, long> & col_profile, double & mean,
double & std);
void detect_outliers(TableProfile & TP, vector<sus_disguised> & sus_dis_values);
// vector<sus_disguised> z_score_od(const string Attribute, map<double, long> & col_profile,
// const double & mean, const double & std);
};
#endif | 36.073171 | 97 | 0.555781 |
aa4c8b7833e495e358be5d5b31ec1c1d94895e9f | 5,549 | c | C | tests/gamma.c | 730404956/glfw | 7f02898264d6077738f0e8032f027eb7e252c90e | [
"Zlib"
] | 1,066 | 2015-01-23T23:07:29.000Z | 2022-03-29T06:25:40.000Z | libs/GLFW3/glfw-3.3.6/tests/gamma.c | CraftingInC/OpenGL_Text | b794df424de6bddb89d649f83e7c5a2158d25c83 | [
"MIT"
] | 110 | 2015-01-24T22:01:14.000Z | 2021-12-31T22:27:00.000Z | libs/GLFW3/glfw-3.3.6/tests/gamma.c | CraftingInC/OpenGL_Text | b794df424de6bddb89d649f83e7c5a2158d25c83 | [
"MIT"
] | 127 | 2017-07-04T00:41:25.000Z | 2022-03-21T09:38:41.000Z | //========================================================================
// Gamma correction test program
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//
// This program is used to test the gamma correction functionality for
// both full screen and windowed mode windows
//
//========================================================================
#include <glad/gl.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#define NK_IMPLEMENTATION
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_BUTTON_TRIGGER_ON_RELEASE
#include <nuklear.h>
#define NK_GLFW_GL2_IMPLEMENTATION
#include <nuklear_glfw_gl2.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action == GLFW_PRESS && key == GLFW_KEY_ESCAPE)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
static void chart_ramp_array(struct nk_context* nk,
struct nk_color color,
int count, unsigned short int* values)
{
if (nk_chart_begin_colored(nk, NK_CHART_LINES,
color, nk_rgb(255, 255, 255),
count, 0, 65535))
{
int i;
for (i = 0; i < count; i++)
{
char buffer[1024];
if (nk_chart_push(nk, values[i]))
{
snprintf(buffer, sizeof(buffer), "#%u: %u (%0.5f) ",
i, values[i], values[i] / 65535.f);
nk_tooltip(nk, buffer);
}
}
nk_chart_end(nk);
}
}
int main(int argc, char** argv)
{
GLFWmonitor* monitor = NULL;
GLFWwindow* window;
GLFWgammaramp orig_ramp;
struct nk_context* nk;
struct nk_font_atlas* atlas;
float gamma_value = 1.f;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
monitor = glfwGetPrimaryMonitor();
glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE);
window = glfwCreateWindow(800, 400, "Gamma Test", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
{
const GLFWgammaramp* ramp = glfwGetGammaRamp(monitor);
const size_t array_size = ramp->size * sizeof(short);
orig_ramp.size = ramp->size;
orig_ramp.red = malloc(array_size);
orig_ramp.green = malloc(array_size);
orig_ramp.blue = malloc(array_size);
memcpy(orig_ramp.red, ramp->red, array_size);
memcpy(orig_ramp.green, ramp->green, array_size);
memcpy(orig_ramp.blue, ramp->blue, array_size);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
nk = nk_glfw3_init(window, NK_GLFW3_INSTALL_CALLBACKS);
nk_glfw3_font_stash_begin(&atlas);
nk_glfw3_font_stash_end();
glfwSetKeyCallback(window, key_callback);
while (!glfwWindowShouldClose(window))
{
int width, height;
struct nk_rect area;
glfwGetWindowSize(window, &width, &height);
area = nk_rect(0.f, 0.f, (float) width, (float) height);
nk_window_set_bounds(nk, "", area);
glClear(GL_COLOR_BUFFER_BIT);
nk_glfw3_new_frame();
if (nk_begin(nk, "", area, 0))
{
const GLFWgammaramp* ramp;
nk_layout_row_dynamic(nk, 30, 3);
if (nk_slider_float(nk, 0.1f, &gamma_value, 5.f, 0.1f))
glfwSetGamma(monitor, gamma_value);
nk_labelf(nk, NK_TEXT_LEFT, "%0.1f", gamma_value);
if (nk_button_label(nk, "Revert"))
glfwSetGammaRamp(monitor, &orig_ramp);
ramp = glfwGetGammaRamp(monitor);
nk_layout_row_dynamic(nk, height - 60.f, 3);
chart_ramp_array(nk, nk_rgb(255, 0, 0), ramp->size, ramp->red);
chart_ramp_array(nk, nk_rgb(0, 255, 0), ramp->size, ramp->green);
chart_ramp_array(nk, nk_rgb(0, 0, 255), ramp->size, ramp->blue);
}
nk_end(nk);
nk_glfw3_render(NK_ANTI_ALIASING_ON);
glfwSwapBuffers(window);
glfwWaitEventsTimeout(1.0);
}
free(orig_ramp.red);
free(orig_ramp.green);
free(orig_ramp.blue);
nk_glfw3_shutdown();
glfwTerminate();
exit(EXIT_SUCCESS);
}
| 30.827778 | 89 | 0.617949 |
43f01d5f6bc129c95b0c794f699bfb07d2b97aee | 1,507 | h | C | ext/yices/src/utils/ptr_stack.h | maelvls/ocamlyices2 | 554893d467a4bf3e9b0b630833b417348b15e771 | [
"0BSD"
] | 2 | 2017-04-05T13:53:54.000Z | 2018-11-23T00:16:01.000Z | ext/yices/src/utils/ptr_stack.h | maelvls/ocamlyices2 | 554893d467a4bf3e9b0b630833b417348b15e771 | [
"0BSD"
] | 5 | 2017-04-07T14:29:10.000Z | 2021-01-08T18:01:46.000Z | ext/yices/src/utils/ptr_stack.h | maelvls/ocamlyices2 | 554893d467a4bf3e9b0b630833b417348b15e771 | [
"0BSD"
] | 1 | 2017-04-05T16:58:14.000Z | 2017-04-05T16:58:14.000Z | /*
* The Yices SMT Solver. Copyright 2014 SRI International.
*
* This program may only be used subject to the noncommercial end user
* license agreement which is downloadable along with this program.
*/
/*
* STACK FOR ALLOCATION OF POINTER ARRAYS IN FIFO ORDER
*
* This is similar to int_stack but for arrays of (void*) pointers.
*/
#ifndef __PTR_STACK_H
#define __PTR_STACK_H
#include <stdint.h>
/*
* Memory blocks:
* - array of pointers + header
* - header include: previous block on the stack (or NULL)
* - size of the block
* - index for allocation in that block
*/
typedef struct pblock_s pblock_t;
struct pblock_s {
pblock_t *next;
uint32_t size;
uint32_t ptr;
void *data[0]; // real size = size
};
#define DEFAULT_PBLOCK_SIZE 1024
#define MAX_PBLOCK_SIZE ((UINT32_MAX/8)-sizeof(pblock_t))
/*
* Stack
* 1) list of blocks
* - current = head of the list = top block
* 2) list of free blocks
*/
typedef struct {
pblock_t *current;
pblock_t *free;
} ptr_stack_t;
/*
* Initialize
*/
extern void init_pstack(ptr_stack_t *stack);
/*
* Delete the full stack
*/
extern void delete_pstack(ptr_stack_t *stack);
/*
* Allocate an array of n pointers
*/
extern void **alloc_pstack_array(ptr_stack_t *stack, uint32_t n);
/*
* Free allocated array a
* - a must be the last array allocated.
*/
extern void free_pstack_array(ptr_stack_t *stack, void **a);
/*
* Reset: empty the stack
*/
extern void reset_pstack(ptr_stack_t *stack);
#endif /* __PTR_STACK_H */
| 19.075949 | 70 | 0.704048 |
b762a1752ebd61fa04372bef598e8c8906d66ddf | 856 | h | C | pcu/pcu_order.h | Thomas-Ulrich/core | 1c7bc7ff994c3570ab22b96d37be0c4c993e5940 | [
"BSD-3-Clause"
] | 138 | 2015-01-05T15:50:20.000Z | 2022-02-25T01:09:58.000Z | pcu/pcu_order.h | Thomas-Ulrich/core | 1c7bc7ff994c3570ab22b96d37be0c4c993e5940 | [
"BSD-3-Clause"
] | 337 | 2015-08-07T18:24:58.000Z | 2022-03-31T14:39:03.000Z | pcu/pcu_order.h | Thomas-Ulrich/core | 1c7bc7ff994c3570ab22b96d37be0c4c993e5940 | [
"BSD-3-Clause"
] | 70 | 2015-01-17T00:58:41.000Z | 2022-02-13T04:58:20.000Z | /******************************************************************************
Copyright 2014 Scientific Computation Research Center,
Rensselaer Polytechnic Institute. All rights reserved.
This work is open source software, licensed under the terms of the
BSD license as described in the LICENSE file in the top-level directory.
*******************************************************************************/
#ifndef PCU_ORDER_H
#define PCU_ORDER_H
#include <stdbool.h>
#include "pcu_msg.h"
typedef struct pcu_order_struct* pcu_order;
pcu_order pcu_order_new(void);
void pcu_order_free(pcu_order o);
bool pcu_order_receive(pcu_order o, pcu_msg* m);
void* pcu_order_unpack(pcu_order o, size_t size);
bool pcu_order_unpacked(pcu_order o);
int pcu_order_received_from(pcu_order o);
size_t pcu_order_received_size(pcu_order o);
#endif
| 31.703704 | 80 | 0.648364 |
2e92dd74fbd604fef05e2e25c588d2ab4d919a69 | 2,035 | h | C | platform/linux-generic/include/odp_debug_internal.h | ecwolf/odp | 6adce4648bf228b60fc65312964a21c84771f58d | [
"BSD-3-Clause"
] | null | null | null | platform/linux-generic/include/odp_debug_internal.h | ecwolf/odp | 6adce4648bf228b60fc65312964a21c84771f58d | [
"BSD-3-Clause"
] | null | null | null | platform/linux-generic/include/odp_debug_internal.h | ecwolf/odp | 6adce4648bf228b60fc65312964a21c84771f58d | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2014-2018, Linaro Limited
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/**
* @file
*
* ODP Debug internal
* This file contains implementer support functions for Debug capabilities.
*
* @warning These definitions are not part of ODP API, they are for
* internal use by implementers and should not be called from any other scope.
*/
#ifndef ODP_DEBUG_INTERNAL_H_
#define ODP_DEBUG_INTERNAL_H_
#include <stdio.h>
#include <stdlib.h>
#include <odp/api/debug.h>
#include <odp_global_data.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup odp_ver_abt_log_dbg
* @{
*/
/**
* Runtime assertion-macro - aborts if 'cond' is false.
*/
#define ODP_ASSERT(cond) \
do { if ((ODP_DEBUG == 1) && (!(cond))) { \
ODP_ERR("%s\n", #cond); \
odp_global_data.abort_fn(); } \
} while (0)
/**
* This macro is used to indicate when a given function is not implemented
*/
#define ODP_UNIMPLEMENTED() \
odp_global_data.log_fn(ODP_LOG_UNIMPLEMENTED, \
"%s:%d:The function %s() is not implemented\n", \
__FILE__, __LINE__, __func__)
/**
* Log debug message if ODP_DEBUG_PRINT flag is set.
*/
#define ODP_DBG(fmt, ...) \
do { \
if (ODP_DEBUG_PRINT == 1) \
ODP_LOG(ODP_LOG_DBG, fmt, ##__VA_ARGS__);\
} while (0)
/**
* Log error message.
*/
#define ODP_ERR(fmt, ...) \
ODP_LOG(ODP_LOG_ERR, fmt, ##__VA_ARGS__)
/**
* Log abort message and then stop execution (by default call abort()).
* This function should not return.
*/
#define ODP_ABORT(fmt, ...) \
do { \
ODP_LOG(ODP_LOG_ABORT, fmt, ##__VA_ARGS__); \
odp_global_data.abort_fn(); \
} while (0)
/**
* ODP LOG macro.
*/
#define ODP_LOG(level, fmt, ...) \
odp_global_data.log_fn(level, "%s:%d:%s():" fmt, __FILE__, \
__LINE__, __func__, ##__VA_ARGS__)
/**
* Log print message when the application calls one of the ODP APIs
* specifically for dumping internal data.
*/
#define ODP_PRINT(fmt, ...) \
odp_global_data.log_fn(ODP_LOG_PRINT, fmt, ##__VA_ARGS__)
#ifdef __cplusplus
}
#endif
#endif
| 22.362637 | 78 | 0.674693 |
bde645eb03435ea0bdc0ca786525e8031f8fd233 | 414 | c | C | src/write_listener.c | benjyup/my_irc | ecc2d96b7489edc015f229bc7793420a0f9635ac | [
"MIT"
] | null | null | null | src/write_listener.c | benjyup/my_irc | ecc2d96b7489edc015f229bc7793420a0f9635ac | [
"MIT"
] | null | null | null | src/write_listener.c | benjyup/my_irc | ecc2d96b7489edc015f229bc7793420a0f9635ac | [
"MIT"
] | null | null | null | /*
** write_listener.c for myirc in /home/jeanadrien/rendu/PROJECT/PSU_2016_myirc/src
**
** Made by Jean-Adrien Domage
** Login <jeanadrien.domage@epitech.eu>
**
** Started on Sat Jun 3 22:17:23 2017 Jean-Adrien Domage
** Last update Sun Jun 11 18:34:32 2017 Jean-Adrien Domage
*/
#include <stdio.h>
#include <unistd.h>
#include "myirc.h"
int write_listener(t_server *serv, t_peer *peer)
{
return (0);
}
| 21.789474 | 82 | 0.705314 |
aec10deca5ce20be0f960e65b3292111056af62e | 448 | h | C | src/Maze.h | jlcrodrigues/Robots_Game_2.0 | 4200136b2e8ebadbd1dd90427161ea61dc434a96 | [
"MIT"
] | null | null | null | src/Maze.h | jlcrodrigues/Robots_Game_2.0 | 4200136b2e8ebadbd1dd90427161ea61dc434a96 | [
"MIT"
] | null | null | null | src/Maze.h | jlcrodrigues/Robots_Game_2.0 | 4200136b2e8ebadbd1dd90427161ea61dc434a96 | [
"MIT"
] | null | null | null | // T01_G12
#ifndef MAZE_H
#define MAZE_H
#include <iostream>
#include "Post.h"
#include <vector>
class Maze
{
public:
Maze();
Maze(int numRows, int numCols);
void addPost(int row, int col, char type);
char charPost(int row, int col) const;
int getnumCols() const;
int getnumRows() const;
void setnumCols(int numCols);
void setnumRows(int numRows);
private:
int numRows, numCols;
std::vector<Post> posts;
};
#endif | 16.592593 | 45 | 0.680804 |
9cdc4cb7e8698f7a1e698f59d96c4ab69e284e7a | 14,909 | h | C | SQLBridge/include/sb_ref_context.h | GVNG/SQLCPPBridgeFramework | 9aac56ad81aaa6384b650dd4c1184e66bbddd89e | [
"BSD-3-Clause"
] | 1 | 2019-12-20T15:17:50.000Z | 2019-12-20T15:17:50.000Z | SQLBridge/include/sb_ref_context.h | GVNG/SQLCPPBridgeFramework | 9aac56ad81aaa6384b650dd4c1184e66bbddd89e | [
"BSD-3-Clause"
] | 1 | 2020-01-09T02:20:27.000Z | 2020-01-09T08:20:10.000Z | SQLBridge/include/sb_ref_context.h | GVNG/SQLCPPBridgeFramework | 9aac56ad81aaa6384b650dd4c1184e66bbddd89e | [
"BSD-3-Clause"
] | 1 | 2020-01-08T19:04:52.000Z | 2020-01-08T19:04:52.000Z | //
// sb_ref_context.h
// SQLCPPBridgeFramework
//
// Created by Roman Makhnenko on 09/05/2020.
// Copyright © 2020, DataArt.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the DataArt nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DataArt BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#ifndef sb_ref_context_h
#define sb_ref_context_h
#include "sb_context_engine.h"
namespace sql_bridge
{
class ref_context : public context_engine
{
private:
template<typename T> class save_task : public db_task
{
typedef typename std::decay<T>::type _t_base;
public:
save_task(_t_base const* src,
data_sections_ptr section,
range pg,
sql_context_references_container const& ref,
void const* rd)
: db_task(section)
, page_size_(pg)
, data_(src)
, references_(ref)
, root_data_(rd)
{};
inline void run_task() override {if (!page_size_.empty()) section_->save_page(page_size_,data_,references_,root_data_); else section_->save(data_,references_,root_data_);}
void error(base_sql_error const& err) override {throw err;}
private:
range page_size_;
_t_base const* data_;
void const* root_data_;
sql_context_references_container const& references_;
};
template<typename T> class replace_task : public db_task
{
typedef typename std::decay<T>::type _t_base;
public:
replace_task(_t_base const* src,
data_sections_ptr section,
sql_context_references_container const& ref,
void const* rd)
: db_task(section)
, data_(src)
, references_(ref)
, root_data_(rd)
{};
inline void run_task() override {section_->replace(data_,references_,root_data_);}
void error(base_sql_error const& err) override {throw err;}
private:
_t_base const* data_;
void const* root_data_;
sql_context_references_container const& references_;
};
template<typename T> class load_page_task : public db_task
{
typedef typename std::decay<T>::type _t_base;
public:
load_page_task(_t_base* src,
data_sections_ptr section,
std::string const& fl,
range pg,
sql_context_references_container const& ref,
void* rd)
: db_task(section)
, filter_(fl)
, page_size_(pg)
, data_(src)
, references_(ref)
, root_data_(rd)
, items_load_(0)
{};
inline void run_task() override {section_->load_page(page_size_,data_,filter_,items_load_,references_,root_data_);}
void error(base_sql_error const& err) override {throw err;}
size_t items_load() const {return items_load_;}
private:
std::string filter_;
range page_size_;
_t_base* data_;
void* root_data_;
sql_context_references_container const& references_;
size_t items_load_;
};
template<typename T> class load_task : public db_task
{
typedef typename std::decay<T>::type _t_base;
public:
load_task(_t_base* src,
data_sections_ptr section,
std::string const& fl,
sql_context_references_container const& ref,
void* rd)
: db_task(section)
, filter_(fl)
, data_(src)
, references_(ref)
, root_data_(rd)
, items_load_(0)
{};
inline void run_task() override {section_->load(data_,filter_,items_load_,references_,root_data_);}
void error(base_sql_error const& err) override {throw err;}
size_t items_load() const {return items_load_;}
private:
std::string filter_;
_t_base* data_;
void* root_data_;
sql_context_references_container const& references_;
size_t items_load_;
};
sql_context_references_container references_;
void* root_data_;
protected:
ref_context(db_tasks_queue_interface_ptr q,
data_sections_ptr ds,
sql_context_references_container const& ref,
void const* rd)
: context_engine(q,ds)
, references_(ref)
, root_data_(const_cast<void*>(rd))
{}
ref_context() = delete;
ref_context(ref_context const&) = delete;
public:
ref_context(ref_context&& src)
: context_engine(std::move(src))
, root_data_(nullptr)
{
std::swap(references_,src.references_);
std::swap(root_data_,src.root_data_);
}
#pragma mark - public methods
template<typename T> inline ref_context& save() {_replace<T>(nullptr);return *this;}
template<typename T> inline ref_context& save(T const& src) {_save<T>(range(),&src);return *this;}
template<typename T> inline ref_context& save(T const* src) {_save<T>(range(),src);return *this;}
template<typename T> inline ref_context& save(T* src) {_save<T>(range(),src);return *this;}
template<typename T> inline ref_context& save(T& src) {_save<T>(range(),&src);return *this;}
template<typename T> inline ref_context& save(size_t pgsz, T const& src) {_save<T>(range(0,pgsz),&src);return *this;}
template<typename T> inline ref_context& save(size_t pgsz, T const* src) {_save<T>(range(0,pgsz),src);return *this;}
template<typename T> inline ref_context& save(size_t pgsz, T& src) {_save<T>(range(0,pgsz),&src);return *this;}
template<typename T> inline ref_context& save(size_t pgsz, T* src) {_save<T>(range(0,pgsz),src);return *this;}
template<typename T> inline ref_context& load() {_load<T>(nullptr,"",nullptr);return *this;}
template<typename T> inline ref_context& load(T& dst, std::string const& flt = "", size_t* num = nullptr) {_load<T>(&dst,build_suffix(flt,true),num);return *this;}
template<typename T> inline ref_context& load(T* dst, std::string const& flt = "", size_t* num = nullptr) {_load<T>(dst,build_suffix(flt,true),num);return *this;}
template<typename T> inline ref_context& load(size_t pgsz, T& dst, std::string const& flt = "", size_t* num = nullptr) {_load_page<T>(range(0,pgsz),&dst,build_suffix(flt,true),num);return *this;}
template<typename T> inline ref_context& load(size_t pgsz, T* dst, std::string const& flt = "", size_t* num = nullptr) {_load_page<T>(range(0,pgsz),dst,build_suffix(flt,true),num);return *this;}
template<typename T> inline ref_context& replace() {_replace<T>(nullptr);return *this;}
template<typename T> inline ref_context& replace(T const& src) {_replace<T>(&src);return *this;}
template<typename T> inline ref_context& replace(T const* src) {_replace<T>(src);return *this;}
template<typename T> inline ref_context& replace(T* src) {_replace<T>(src);return *this;}
template<typename T> inline ref_context& replace(T& src) {_replace<T>(&src);return *this;}
inline ref_context& limit(size_t count, size_t offset = 0) {context_engine::limit(count,offset);return *this;}
inline ref_context& sql_or() {context_engine::sql_or();return *this;}
inline ref_context& sql_and() {context_engine::sql_and();return *this;}
template<typename T, typename TFn> inline ref_context& order(TFn const T::*mem_ptr) {context_engine::order<T,TFn>(mem_ptr);return *this;}
template<typename T, typename TFn> inline ref_context& order_desc(TFn const T::*mem_ptr) {context_engine::order_desc<T,TFn>(mem_ptr);return *this;}
template<typename T, typename TFn> inline ref_context& where(TFn const T::*mem_ptr, std::string const& op, TFn const& val) {context_engine::where<T,TFn>(mem_ptr,op,val);return *this;}
template<typename T, typename TFn> inline ref_context& where_between(TFn const T::*mem_ptr, TFn const& from, TFn const& to) {context_engine::where_between<T,TFn>(mem_ptr,from,to);return *this;}
template<typename T, typename TFn> inline ref_context& where_between(TFn const& val, TFn const T::*mem_ptr_from, TFn const T::*mem_ptr_to) {context_engine::where_between<T,TFn>(val,mem_ptr_from,mem_ptr_to);return *this;}
template<typename T, typename TFn> inline ref_context& where_not_between(TFn const T::*mem_ptr, TFn const& from, TFn const& to) {context_engine::where_not_between<T,TFn>(mem_ptr,from,to);return *this;}
template<typename T, typename TFn> inline ref_context& where_not_between(TFn const& val, TFn const T::*mem_ptr_from, TFn const T::*mem_ptr_to) {context_engine::where_not_between<T,TFn>(val,mem_ptr_from,mem_ptr_to);return *this;}
template<typename T, typename TFn, typename TCont> inline ref_context& where_in(TFn const T::*mem_ptr, TCont const& cnt) {context_engine::where_in<T,TFn,TCont>(mem_ptr,cnt); return *this;}
template<typename T, typename TFn, typename TCont> inline ref_context& where_not_in(TFn const T::*mem_ptr, TCont const& cnt) {context_engine::where_not_in<T,TFn,TCont>(mem_ptr,cnt); return *this;}
template<typename T> inline ref_context& where_like(std::string const T::*mem_ptr, std::string const& val) {context_engine::where_like<T>(mem_ptr,val);return *this;}
template<typename T> inline ref_context& where_not_like(std::string const T::*mem_ptr, std::string const& val) {context_engine::where_not_like<T>(mem_ptr,val);return *this;}
private:
#pragma mark - load
template<typename T> inline typename std::enable_if<is_sql_acceptable<T>::value>::type _load(T*, std::string const& flt, size_t* num) const
{
throw sql_bridge_error(g_internal_error_text, g_incorrect_operation_err_text);
}
template<typename T> inline typename std::enable_if<!is_sql_acceptable<T>::value>::type _load(T* dst, std::string const& flt, size_t* num) const
{
db_task_ptr task(std::make_shared< load_task<T> >(dst,data_,flt,references_,root_data_));
std::future<void> ret(task->get_future());
db_tasks_queue_interface_ptr qp = queue_.lock();
if (qp!=nullptr)
{
qp->add( task );
ret.get();
if (num)
*num = static_cast<load_task<T>*>(task.get())->items_load();
}
}
#pragma mark - load page
template<typename T> inline typename std::enable_if<is_sql_acceptable<T>::value>::type _load_page(range, T*, std::string const& flt, size_t* num) const
{
throw sql_bridge_error(g_internal_error_text, g_incorrect_operation_err_text);
}
template<typename T> inline typename std::enable_if<!is_sql_acceptable<T>::value>::type _load_page(range pg, T* dst, std::string const& flt, size_t* num) const
{
db_task_ptr task(std::make_shared< load_page_task<T> >(dst,data_,flt,pg,references_,root_data_));
std::future<void> ret(task->get_future());
db_tasks_queue_interface_ptr qp = queue_.lock();
if (qp!=nullptr)
{
qp->add( task );
ret.get();
if (num)
*num = static_cast<load_page_task<T>*>(task.get())->items_load();
}
}
#pragma mark - save
template<typename T> inline typename std::enable_if<is_sql_acceptable<T>::value>::type _save(range, T const*) const
{
throw sql_bridge_error(g_internal_error_text, g_incorrect_operation_err_text);
}
template<typename T> inline typename std::enable_if<!is_sql_acceptable<T>::value>::type _save(range pg, T const* src) const
{
db_task_ptr task(std::make_shared< save_task<T> >(src,data_,pg,references_,root_data_));
std::future<void> ret(task->get_future());
db_tasks_queue_interface_ptr qp = queue_.lock();
if (qp!=nullptr)
{
qp->add( task );
ret.get();
}
}
#pragma mark - replace
template<typename T> inline typename std::enable_if<is_sql_acceptable<T>::value>::type _replace(T const*) const
{
throw sql_bridge_error(g_internal_error_text, g_incorrect_operation_err_text);
}
template<typename T> inline typename std::enable_if<!is_sql_acceptable<T>::value>::type _replace(T const* src) const
{
db_task_ptr task(std::make_shared< replace_task<T> >(src,data_,references_,root_data_));
std::future<void> ret(task->get_future());
db_tasks_queue_interface_ptr qp = queue_.lock();
if (qp!=nullptr)
{
qp->add( task );
ret.get();
}
}
};
};
#endif /* sb_ref_context_h */
| 51.767361 | 236 | 0.623918 |
6c385e116eb4f95a11e88182b178c816f4c1ab8e | 1,624 | h | C | Frameworks/MediaPlayer.framework/Headers/MPPlaceholderAVItem.h | CarlAmbroselli/barcelona | 9bd087575935485a4c26674c2414d7ef20d7e168 | [
"Apache-2.0"
] | 13 | 2021-08-12T22:57:13.000Z | 2022-03-09T16:45:52.000Z | Frameworks/MediaPlayer.framework/Headers/MPPlaceholderAVItem.h | CarlAmbroselli/barcelona | 9bd087575935485a4c26674c2414d7ef20d7e168 | [
"Apache-2.0"
] | 20 | 2021-09-03T13:38:34.000Z | 2022-03-17T13:24:39.000Z | Frameworks/MediaPlayer.framework/Headers/MPPlaceholderAVItem.h | CarlAmbroselli/barcelona | 9bd087575935485a4c26674c2414d7ef20d7e168 | [
"Apache-2.0"
] | 2 | 2022-02-13T08:35:11.000Z | 2022-03-17T01:56:47.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <MediaPlayer/MPAVItem.h>
@class NSString;
@interface MPPlaceholderAVItem : MPAVItem
{
_Bool _explicitTrack;
_Bool _likeStateEnabled;
_Bool _supportsLikedState;
_Bool _tailPlaceholder;
NSString *_album;
NSString *_artist;
double _durationFromExternalMetadata;
NSString *_mainTitle;
id _artworkCatalogBlock;
}
+ (_Bool)isPlaceholder;
@property(copy, nonatomic) id artworkCatalogBlock; // @synthesize artworkCatalogBlock=_artworkCatalogBlock;
@property(nonatomic, getter=isTailPlaceholder) _Bool tailPlaceholder; // @synthesize tailPlaceholder=_tailPlaceholder;
@property(nonatomic) _Bool supportsLikedState; // @synthesize supportsLikedState=_supportsLikedState;
@property(retain, nonatomic) NSString *mainTitle; // @synthesize mainTitle=_mainTitle;
@property(nonatomic, getter=isLikedStateEnabled) _Bool likedStateEnabled; // @synthesize likedStateEnabled=_likeStateEnabled;
@property(nonatomic, getter=isExplicitTrack) _Bool explicitTrack; // @synthesize explicitTrack=_explicitTrack;
@property(nonatomic) double durationFromExternalMetadata; // @synthesize durationFromExternalMetadata=_durationFromExternalMetadata;
@property(retain, nonatomic) NSString *artist; // @synthesize artist=_artist;
@property(retain, nonatomic) NSString *album; // @synthesize album=_album;
- (void)loadAssetAndPlayerItem;
- (_Bool)isValidPlayerSubstituteForItem:(id)arg1;
- (id)description;
- (id)init;
@end
| 38.666667 | 132 | 0.785714 |
caa4503974c12d7ccc6741170ae44cd607436eed | 996 | h | C | app/EQPModule/ViewController/EFileViewController.h | zhang651651/ipad | cf3ebc2854bd5f28d7828498ba63936d21aa43ee | [
"MIT"
] | 1 | 2019-04-06T15:21:53.000Z | 2019-04-06T15:21:53.000Z | app/EQPModule/ViewController/EFileViewController.h | zhang651651/ipad | cf3ebc2854bd5f28d7828498ba63936d21aa43ee | [
"MIT"
] | null | null | null | app/EQPModule/ViewController/EFileViewController.h | zhang651651/ipad | cf3ebc2854bd5f28d7828498ba63936d21aa43ee | [
"MIT"
] | null | null | null | //
// EFileViewController.h
// ipad
//
// Created by Zhang Xinrong on 2018/11/13.
// Copyright © 2018 nil. All rights reserved.
//
#import "BaseViewController.h"
#import "YSEQPThemeOneModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface EFileViewController : BaseViewController
- (instancetype)initWithModel:(YSEQPThemeOneModel *)model;
@property(nonatomic,assign)NSInteger imageIndex;
@property(nonatomic,strong)NSArray *array;
@property(nonatomic,strong)UIView *rightView;
@property(nonatomic,strong)UIView *leftView;
@property(nonatomic,assign)NSInteger defalutIndex;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UIButton *titleBtn;
@property(nonatomic,strong)UIButton *rightbtn;
@property(nonatomic,strong)UIButton *leftbtn;
@property(nonatomic,strong)NSMutableArray *tagsArray;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *cellArray;
@property(nonatomic,strong)UIImageView *imageView;
@end
NS_ASSUME_NONNULL_END
| 30.181818 | 58 | 0.812249 |
6cd35c56265b082f0aef94b417cace29fc097e92 | 3,938 | h | C | c_mcai_worker_sdk/media_worker.h | media-io/rs_amqp_worker | 04251431df3a952250d48cdac56706a5e2a94c23 | [
"MIT"
] | 1 | 2019-02-13T22:25:12.000Z | 2019-02-13T22:25:12.000Z | c_mcai_worker_sdk/media_worker.h | media-io/rs_amqp_worker | 04251431df3a952250d48cdac56706a5e2a94c23 | [
"MIT"
] | 2 | 2019-08-21T07:20:40.000Z | 2019-08-21T07:20:59.000Z | c_mcai_worker_sdk/media_worker.h | media-io/rs_amqp_worker | 04251431df3a952250d48cdac56706a5e2a94c23 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Worker parameter type
*/
typedef struct Parameter {
char* identifier;
char* label;
unsigned int kind_size;
char** kind;
int required;
} Parameter;
/**
* Audio / Video streams descriptors type
*/
enum StreamType {
VIDEO,
AUDIO,
DATA
};
/**
* Job & channel handler
*/
typedef void* Handler;
/**
* Get job parameter value callback
* @param _handler the job & channel handler
* @param _parameter_key the name of the parameter to get
* @return the parameter value
* @note the returned pointer must be freed by user.
*/
typedef char* (*GetParameterValueCallback)(Handler _handler, const char* _parameter_key);
/**
* Rust Logger
* @param _level the log level: 'trace', 'debug', 'info', 'warn' or 'error'
* @param _message the message to log
*/
typedef void* (*Logger)(const char* _level, const char* _message);
typedef const void* StreamDescriptor;
typedef const void* Filter;
typedef void* (*NewStreamDescriptorCallback)(unsigned int _index, StreamType _stream_type);
typedef void* (*NewFilterCallback)(const char* _filter_name, const char* _filter_label);
typedef void* (*AddDescriptorFilterCallback)(StreamDescriptor _stream_descriptor, Filter _filter);
typedef void* (*AddFilterParameterCallback)(Filter _filter, const char* _parameter_key, const char* _parameter_value);
/**
* Get worker name
*/
char* get_name();
/**
* Get worker short description
*/
char* get_short_description();
/**
* Get worker long description
*/
char* get_description();
/**
* Get worker version
*/
char* get_version();
/**
* Get number of worker parameters
*/
unsigned int get_parameters_size();
/**
* Retrieve worker parameters
* @param parameters Output parameters array pointer
*/
void get_parameters(Parameter* parameters);
/**
* Initialize worker
* (This fonction is optional)
* @param logger Rust Logger
*/
void init(Logger logger);
/**
* Initialize worker media process
* (the "media" feature must be enabled)
* @param handler Handler
* @param parameters_value_getter Get job parameter value callback
* @param logger Rust Logger
* @param format_context Format context pointer
* @param output_stream_descriptors Pointer of descriptors of the output streams
*/
int init_process(
Handler handler,
NewStreamDescriptorCallback new_stream_descriptor_callback,
NewFilterCallback new_filter_callback,
AddDescriptorFilterCallback add_descriptor_filter_callback,
AddFilterParameterCallback add_filter_parameter_callback,
Logger logger,
void* format_context,
void** output_stream_descriptors,
unsigned int* output_stream_descriptors_size
);
/**
* Process the media frame
* (the "media" feature must be enabled)
* @param handler Handler
* @param parameters_value_getter Get job parameter value callback
* @param logger Rust Logger
* @param stream_index Frame stream index
* @param frame Frame pointer
* @param message Output message pointer
*/
int process_frame(
Handler handler,
GetParameterValueCallback parameters_value_getter,
Logger logger,
const unsigned int job_id,
const unsigned int stream_index,
void* frame,
const char** message
);
/**
* End the media process
* (the "media" feature must be enabled)
* @param logger Rust Logger
*/
void ending_process(Logger logger);
/**
* Set the C string to the pointer
* @param message Pointer on the const char*
* @param value c string with 0 ending
*/
void set_str_on_ptr(const char** message, const char* value) {
size_t length = strlen(value) + 1;
*message = (const char *)malloc(length);
memcpy((void*)*message, value, length);
}
#ifdef __cplusplus
}
#endif
| 24.767296 | 118 | 0.697562 |
37bed0e19e71c77c80291581e1d56d554c599e4c | 268 | h | C | third_party/virtualbox/src/VBox/Devices/PC/ipxe/src/include/ipxe/segment.h | Fimbure/icebox-1 | 0b81992a53e1b410955ca89bdb6f8169d6f2da86 | [
"MIT"
] | 521 | 2019-03-29T15:44:08.000Z | 2022-03-22T09:46:19.000Z | third_party/virtualbox/src/VBox/Devices/PC/ipxe/src/include/ipxe/segment.h | Fimbure/icebox-1 | 0b81992a53e1b410955ca89bdb6f8169d6f2da86 | [
"MIT"
] | 30 | 2019-06-04T17:00:49.000Z | 2021-09-08T20:44:19.000Z | third_party/virtualbox/src/VBox/Devices/PC/ipxe/src/include/ipxe/segment.h | Fimbure/icebox-1 | 0b81992a53e1b410955ca89bdb6f8169d6f2da86 | [
"MIT"
] | 99 | 2019-03-29T16:04:13.000Z | 2022-03-28T16:59:34.000Z | #ifndef _IPXE_SEGMENT_H
#define _IPXE_SEGMENT_H
/**
* @file
*
* Executable image segments
*
*/
FILE_LICENCE ( GPL2_OR_LATER );
#include <ipxe/uaccess.h>
extern int prep_segment ( userptr_t segment, size_t filesz, size_t memsz );
#endif /* _IPXE_SEGMENT_H */
| 14.888889 | 75 | 0.720149 |
18760f3253ada20df918403a61d12a1f0eed53b7 | 6,154 | h | C | components/autofill/core/browser/data_model/form_group.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill/core/browser/data_model/form_group.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill/core/browser/data_model/form_group.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_FORM_GROUP_H_
#define COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_FORM_GROUP_H_
#include <string>
#include "base/strings/string16.h"
#include "components/autofill/core/browser/field_types.h"
namespace autofill {
namespace structured_address {
enum class VerificationStatus;
}
class AutofillType;
// This class is an interface for collections of form fields, grouped by type.
class FormGroup {
public:
virtual ~FormGroup() = default;
// Used to determine the type of a field based on the |text| that a user
// enters into the field, interpreted in the given |app_locale| if
// appropriate. The field types can then be reported back to the server. This
// method is additive on |matching_types|.
virtual void GetMatchingTypes(const base::string16& text,
const std::string& app_locale,
ServerFieldTypeSet* matching_types) const;
// Returns a set of server field types for which this FormGroup has non-empty
// data. This method is additive on |non_empty_types|.
virtual void GetNonEmptyTypes(const std::string& app_locale,
ServerFieldTypeSet* non_empty_types) const;
// Returns the string associated with |type|, without canonicalizing the
// returned value. For user-visible strings, use GetInfo() instead.
virtual base::string16 GetRawInfo(ServerFieldType type) const = 0;
// Finalization routine that should be called after importing a FormGroup.
// Returns true if the finalization was successful.
bool FinalizeAfterImport();
// Sets this FormGroup object's data for |type| to |value|, without
// canonicalizing the |value|. For data that has not already been
// canonicalized, use SetInfo() instead.
// Accepts a verification status.
virtual void SetRawInfoWithVerificationStatus(
ServerFieldType type,
const base::string16& value,
structured_address::VerificationStatus status) = 0;
// Convenience wrapper to allow passing the status as an integer.
void SetRawInfoWithVerificationStatusInt(ServerFieldType type,
const base::string16& value,
int status);
// Convenience wrapper to add
// |structured_address::VerificationStatus::kNoStatus| to
// |SetRawInfoWithVerificationStatus|.
void SetRawInfo(ServerFieldType type, const base::string16& value);
// Returns true iff the string associated with |type| is nonempty (without
// canonicalizing its value).
bool HasRawInfo(ServerFieldType type) const;
// Returns the string that should be auto-filled into a text field given the
// type of that field, localized to the given |app_locale| if appropriate.
base::string16 GetInfo(ServerFieldType type,
const std::string& app_locale) const;
base::string16 GetInfo(const AutofillType& type,
const std::string& app_locale) const;
// Returns the verification status associated with the type.
// Returns kNoStatus if the type does not support a verification status.
virtual structured_address::VerificationStatus GetVerificationStatus(
ServerFieldType type) const;
structured_address::VerificationStatus GetVerificationStatus(
const AutofillType& type) const;
// Convenience wrappers to retrieve the Verification status in integer
// representation.
int GetVerificationStatusInt(ServerFieldType type) const;
int GetVerificationStatusInt(const AutofillType& type) const;
// Used to populate this FormGroup object with data. Canonicalizes the data
// according to the specified |app_locale| prior to storing, if appropriate.
bool SetInfo(ServerFieldType type,
const base::string16& value,
const std::string& app_locale);
bool SetInfo(const AutofillType& type,
const base::string16& value,
const std::string& app_locale);
// Same as |SetInfo| but supports a verification status.
bool SetInfoWithVerificationStatus(
ServerFieldType type,
const base::string16& value,
const std::string& app_locale,
const structured_address::VerificationStatus status);
bool SetInfoWithVerificationStatus(
const AutofillType& type,
const base::string16& value,
const std::string& app_locale,
const structured_address::VerificationStatus status);
// Returns true iff the string associated with |type| is nonempty.
bool HasInfo(ServerFieldType type) const;
bool HasInfo(const AutofillType& type) const;
protected:
// AutofillProfile needs to call into GetSupportedTypes() for objects of
// non-AutofillProfile type, for which mere inheritance is insufficient.
friend class AutofillProfile;
// Returns a set of server field types for which this FormGroup can store
// data. This method is additive on |supported_types|.
virtual void GetSupportedTypes(ServerFieldTypeSet* supported_types) const = 0;
// Returns the string that should be auto-filled into a text field given the
// type of that field, localized to the given |app_locale| if appropriate.
virtual base::string16 GetInfoImpl(const AutofillType& type,
const std::string& app_locale) const;
// Used to populate this FormGroup object with data. Canonicalizes the data
// according to the specified |app_locale| prior to storing, if appropriate.
virtual bool SetInfoWithVerificationStatusImpl(
const AutofillType& type,
const base::string16& value,
const std::string& app_locale,
const structured_address::VerificationStatus status);
// Used to retrieve the verification status of a value associated with |type|.
virtual structured_address::VerificationStatus GetVerificationStatusImpl(
ServerFieldType type) const;
};
} // namespace autofill
#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_FORM_GROUP_H_
| 42.441379 | 80 | 0.728144 |
afcb010960e90671bae2b50a6e725c06bc9e6a45 | 10,963 | h | C | tnp_test_camera_orientation/UtilCvPclRs.h | warehouse-picking-automation-challenges/team_naist_panasonic | 999b8d20c5528f5510e43bf4a483215011f9871d | [
"Apache-2.0"
] | 10 | 2017-12-22T07:45:09.000Z | 2022-03-25T21:42:22.000Z | tnp_recognition_space_calibration/UtilCvPclRs.h | warehouse-picking-automation-challenges/team_naist_panasonic | 999b8d20c5528f5510e43bf4a483215011f9871d | [
"Apache-2.0"
] | null | null | null | tnp_recognition_space_calibration/UtilCvPclRs.h | warehouse-picking-automation-challenges/team_naist_panasonic | 999b8d20c5528f5510e43bf4a483215011f9871d | [
"Apache-2.0"
] | 6 | 2017-12-24T16:03:22.000Z | 2020-06-14T11:01:18.000Z | /*
* Version: 2017.07.31
* Authors: Members of the Team NAIST-Panasonic at the Amazon Robotics Challenge 2017:
* Gustavo A. Garcia R. <garcia-g at is.naist.jp> (Captain),
* Lotfi El Hafi, Felix von Drigalski, Wataru Yamazaki, Viktor Hoerig, Arnaud Delmotte,
* Akishige Yuguchi, Marcus Gall, Chika Shiogama, Kenta Toyoshima, Pedro Uriguen,
* Rodrigo Elizalde, Masaki Yamamoto, Yasunao Okazaki, Kazuo Inoue, Katsuhiko Asai,
* Ryutaro Futakuchi, Seigo Okada, Yusuke Kato, and Pin-Chu Yang
*********************
* Copyright 2017 Team NAIST-Panasonic
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*********************
*/
#ifndef UTILCVPCLRS_H
#define UTILCVPCLRS_H
#include <opencv2/opencv.hpp>
#include <opencv2/aruco.hpp>
#include <opencv2/aruco/charuco.hpp>
#include <librealsense/rs.hpp>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <string>
#include "RGBDFrame.h"
std::string matType2str(cv::Mat mat);
std::string mat2str(cv::Mat mat, bool printMatContent = true);
bool isR200(rs::device *rsCamera);
bool isSR300(rs::device *rsCamera);
int printRSContextInfo( rs::context *c );
int configureRSStreams( rs::device *rsCamera, bool useDepth = true, bool useIR = false, bool useIR2 = false );
template<typename MatT, int MatRows, int MatCols>
cv::Point3f multMatVecT(cv::Mat mat, cv::Point3f p)
{
cv::Point3f result;
if(MatCols == 3)
{
MatT *line = mat.ptr<MatT>(0);
result.x = line[0]*p.x+line[1]*p.y+line[2]*p.z;
line = mat.ptr<MatT>(1);
result.y = line[0]*p.x+line[1]*p.y+line[2]*p.z;
line = mat.ptr<MatT>(2);
result.z = line[0]*p.x+line[1]*p.y+line[2]*p.z;
}
else
{
MatT *line = mat.ptr<MatT>(0);
result.x = line[0]*p.x+line[1]*p.y+line[2]*p.z+line[3];
line = mat.ptr<MatT>(1);
result.y = line[0]*p.x+line[1]*p.y+line[2]*p.z+line[3];
line = mat.ptr<MatT>(2);
result.z = line[0]*p.x+line[1]*p.y+line[2]*p.z+line[3];
}
if(MatRows == 3)
return result;
else
{
MatT *line = mat.ptr<MatT>(3);
return result / (line[0]*p.x+line[1]*p.y+line[2]*p.z+line[3]);
}
}
cv::Point3f multMatVec(cv::Mat mat, cv::Point3f p);
cv::Point2f multMatVec(cv::Mat mat, cv::Point2f p);
cv::Point2f min(cv::Point2f p1, cv::Point2f p2);
cv::Point2f max(cv::Point2f p1, cv::Point2f p2);
void BarycentricPrecompute(cv::Point2f a, cv::Point2f b, cv::Point2f c, cv::Point2f& v0, cv::Point2f& v1, float& d00, float& d01, float& d11, float& invDenom);
inline void BarycentricWithPrecomputedVal(cv::Point2f p, cv::Point2f a, cv::Point2f v0, cv::Point2f v1, float d00, float d01, float d11, float invDenom, float &u, float &v, float &w)
{
cv::Point2f v2 = p - a;
float d20 = v2.dot(v0);
float d21 = v2.dot(v1);
v = (d11 * d20 - d01 * d21) * invDenom;
w = (d00 * d21 - d01 * d20) * invDenom;
u = 1.0f - v - w;
}
void Barycentric(cv::Point2f p, cv::Point2f a, cv::Point2f b, cv::Point2f c, float &u, float &v, float &w);
cv::Mat RTVec2Mat(cv::Mat rvec, cv::Mat tvec);
cv::Mat getRVecFromMat(cv::Mat M);
cv::Mat getTVecFromMat(cv::Mat M);
cv::Mat point2Mat(cv::Point3d p);
cv::Point3f getMinBoard(cv::Ptr<cv::aruco::CharucoBoard> board);
cv::Point3f getMaxBoard(cv::Ptr<cv::aruco::CharucoBoard> board);
void detectMarker(cv::Mat img, cv::Ptr<cv::aruco::Dictionary> dictionary, std::vector<int>& markerIds, std::vector<std::vector<cv::Point2f> >& markerCorners, cv::Mat result);
bool detectCornersAndPose(const std::vector<int>& markerIds, const std::vector<std::vector<cv::Point2f> >& markerCorners, cv::Mat img, cv::Ptr<cv::aruco::CharucoBoard> board, cv::Mat K, cv::Mat dist, std::vector<cv::Point2f>& charucoCorners, std::vector<int>& charucoIds, cv::Mat& rvec, cv::Mat& tvec, cv::Mat result);
bool detectMarker(cv::Mat img, cv::Ptr<cv::aruco::Dictionary> dictionary, cv::Ptr<cv::aruco::CharucoBoard> board, cv::Mat K, cv::Mat dist, std::vector<int>& markerIds, std::vector<std::vector<cv::Point2f> >& markerCorners, std::vector<cv::Point2f>& charucoCorners, std::vector<int>& charucoIds, cv::Mat& rvec, cv::Mat& tvec, cv::Mat result = cv::Mat());
bool loadCalib(const char *filename, std::vector<std::string>& serialId, std::vector<cv::Mat>& cameraK, std::vector<cv::Mat>& cameraDist, std::vector<cv::Mat>& poses);
bool loadCalib(const char *filename, std::vector<std::string>& serialId, std::vector<cv::Mat>& cameraK, std::vector<cv::Mat>& cameraDist, std::vector<cv::Mat>& poses, std::vector<cv::Mat>& planeRt);
void saveCalib(const char *filename, const std::vector<std::string>& serialId, const std::vector<cv::Mat>& cameraK, const std::vector<cv::Mat>& cameraDist, const std::vector<cv::Mat>& cameraPose, const std::vector<cv::Mat>& planeRt = std::vector<cv::Mat>());
bool loadRecoSpaceConfig(const char *filename, cv::Point3f& recognitionCenter, cv::Point3f& recognitionSize, cv::Point3f& suctionCylinderCenter, cv::Point3f& suctionCylinderMainAxis, float& suctionCylinderHeight, float& suctionCylinderRadius);
void saveRecoSpaceConfig(const char *filename, cv::Point3f recognitionCenter, cv::Point3f recognitionSize, cv::Point3f suctionCylinderCenter, cv::Point3f suctionCylinderMainAxis, float suctionCylinderHeight, float suctionCylinderRadius);
std::vector<std::string> loadFramesIdSerial(const char *seq_folder, int nbCameras, int frameId, const char *prefix = "capture");
std::vector<RgbdFrame> loadFramesId(const char *seq_folder, int nbCameras, int frameId, const char *prefix = "capture");
std::vector<std::vector<RgbdFrame> > loadFrames(const char *seq_folder, int nbCameras, int nbFrames, int firstFrameId = 0, const char *prefix = "capture");
int getIdBySerial(const std::vector<std::string>& listSerial, std::string serial);
std::vector<cv::Point2f> project2d(cv::Mat KRGB, cv::Mat pose, const std::vector<cv::Point3f>& data);
void drawCylinder(cv::Mat result, cv::Mat KRGB, cv::Mat pose, cv::Point3f baseCenter, cv::Point3f top, float radius, cv::Scalar color, int nbHeightSegment = 10, int nbRadiusSegment = 20);
void drawBox(cv::Mat result, cv::Mat KRGB, cv::Mat pose, const std::vector<cv::Point3f>& box, cv::Scalar color);
void drawFilledBox(cv::Mat result, cv::Mat KRGB, cv::Mat pose, const std::vector<cv::Point3f>& box, cv::Scalar color);
bool pointInBox(cv::Point3f p, cv::Point3f center, cv::Point3f size);
bool pointInCylinder(cv::Point3f p, cv::Point3f cylinderCenter, cv::Point3f cylinderMainAxis, float height, float radius);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr filterStatisticalOutlier(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud, int meanK = 50, float stddevMulThresh = 1.0);
std::vector<cv::Point3f> getBoxPoints(cv::Point3f center, cv::Point3f size);
inline cv::Point2f rs2cv(rs::float2 a)
{
return cv::Point2f(a.x, a.y);
}
inline cv::Point3f rs2cv(rs::float3 a)
{
return cv::Point3f(a.x, a.y, a.z);
}
inline rs::float2 cv2rs(cv::Point2f a)
{
return {a.x, a.y};
}
inline rs::float3 cv2rs(cv::Point3f a)
{
return {a.x, a.y, a.z};
}
inline cv::Point3f pcl2cv(pcl::Normal n)
{
return cv::Point3f(n.normal_x, n.normal_y, n.normal_z);
}
inline cv::Point3f pcl2cv(pcl::PointXYZ p)
{
return cv::Point3f(p.x, p.y, p.z);
}
inline cv::Point3f pcl2cv(pcl::PointXYZRGB p)
{
return cv::Point3f(p.x, p.y, p.z);
}
template<int nbDistVal, typename T>
void applyDistortion(const T* p, const T* const cameraDist, T* res, bool modified = false)
{
if(nbDistVal == 0)
{
res[0] = p[0];
res[1] = p[1];
}
else
{
T r2 = p[0]*p[0] + p[1]*p[1];
T rad = T(1) + cameraDist[0] * r2;
if(nbDistVal >= 2)
rad += cameraDist[1] * r2 * r2;
if(nbDistVal >= 5)
rad += cameraDist[4] * r2 * r2 * r2;
res[0] = p[0] * rad;
res[1] = p[1] * rad;
T x,y;
if(modified)
{
x = res[0];
y = res[1];
}
else
{
x = p[0];
y = p[1];
}
if(nbDistVal >= 3)
{
res[0] += T(2)*cameraDist[2]*x*y;
res[1] += cameraDist[2]*(r2+T(2)*y*y);
}
if(nbDistVal >= 4)
{
res[0] += cameraDist[3]*(r2+T(2)*x*x);
res[1] += T(2)*cameraDist[3]*x*y;
}
}
}
template<int nbDistVal>
cv::Point2d applyDistortion(cv::Point2d p, cv::Mat cameraDist, bool modified = false)
{
double vec[2] = {p.x, p.y};
double res[2];
applyDistortion<nbDistVal, double>(&vec[0], cameraDist.ptr<double>(0), &res[0], modified);
return cv::Point2d(res[0], res[1]);
}
template<typename T>
std::vector<T> mat2vec(cv::Mat mat)
{
std::vector<T> vec(mat.cols*mat.rows);
for(int i = 0; i < mat.rows; i++)
{
T *ptr = mat.ptr<T>(i);
T *dst = &vec[i*mat.cols];
for(int j = 0; j < mat.cols; j++)
dst[j] = ptr[j];
}
return vec;
}
template<typename T>
cv::Mat vec2mat(const std::vector<T>& vec, int cols, int rows, int type)
{
cv::Mat mat(rows, cols, type);
for(int i = 0; i < mat.rows; i++)
{
const T *ptr = &vec[i*mat.cols];
T *dst = mat.ptr<T>(i);
for(int j = 0; j < mat.cols; j++)
dst[j] = ptr[j];
}
return mat;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr computeConvexHull(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud);
std::vector<cv::Point3f> computeAABB(pcl::PointCloud<pcl::PointXYZ>::Ptr cloudSegmented);
std::vector<cv::Point3f> computeAABB(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudSegmented);
std::vector<cv::Point3f> computeOBB(pcl::PointCloud<pcl::PointXYZ>::Ptr cloudSegmented, bool useConvexHull = true, float samplingDistance = CV_PI/180, float minTheta = 0.0, float maxTheta = CV_PI/2, float minPhi = 0, float maxPhi = 2*CV_PI);
std::vector<cv::Point3f> computeOBB(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudSegmented, bool useConvexHull = true, float samplingDistance = CV_PI/180, float minTheta = 0.0, float maxTheta = CV_PI/2, float minPhi = 0, float maxPhi = 2*CV_PI);
std::vector<cv::Point3f> estimateOBB(pcl::PointCloud<pcl::PointXYZ>::Ptr cloudSegmented);
std::vector<cv::Point3f> estimateBB(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudSegmented);
cv::Point3f extractCenterFromOBB(const std::vector<cv::Point3f>& OBB);
cv::Point3f extractSizeFromOBB(const std::vector<cv::Point3f>& OBB);
cv::Mat extractRotationFromOBB(const std::vector<cv::Point3f>& OBB);
#endif // CVPCLRSUTIL_H
| 42.992157 | 353 | 0.656572 |
bbaa0d06b78e6523545e74e5018b85feb42d5f7b | 2,685 | h | C | Basalt/src/Basalt/Events/WindowEvent.h | jakenbake97/Half-WayEngine | e09e09ec0b7b3191b0c4e178c3f3a209c50f66d3 | [
"Apache-2.0"
] | null | null | null | Basalt/src/Basalt/Events/WindowEvent.h | jakenbake97/Half-WayEngine | e09e09ec0b7b3191b0c4e178c3f3a209c50f66d3 | [
"Apache-2.0"
] | null | null | null | Basalt/src/Basalt/Events/WindowEvent.h | jakenbake97/Half-WayEngine | e09e09ec0b7b3191b0c4e178c3f3a209c50f66d3 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Event.h"
#include "Basalt/Window.h"
namespace Basalt
{
class WindowCloseEvent : public Event
{
public:
WindowCloseEvent(const int exitCode) : code(exitCode){}
int GetExitCode() const { return code; }
static EventType GetStaticType() { return EventType::WindowClose; }
EventType GetEventType() const override { return GetStaticType(); }
String GetName() const override { return "Window Close Event"; }
int GetCategories() const override { return static_cast<int>(EventCategory::Window); }
String ToString() const override { return GetName(); }
private:
int code;
};
class WindowResizeEvent : public Event
{
public:
WindowResizeEvent(unsigned int width, unsigned int height)
: width(width), height(height){}
unsigned int GetWidth() const { return width; }
unsigned int GetHeight() const { return height; }
String ToString() const override{return GetName() + ": Size(" + width + ", " + height + ")";}
static EventType GetStaticType() { return EventType::WindowResize; }
EventType GetEventType() const override { return GetStaticType(); }
String GetName() const override { return "Window Resize Event"; }
int GetCategories() const override { return static_cast<int>(EventCategory::Window); }
private:
unsigned int width, height;
};
class WindowFocusEvent : public Event
{
public:
static EventType GetStaticType() { return EventType::WindowFocus; }
EventType GetEventType() const override { return GetStaticType(); }
String GetName() const override { return "Window Focus Event"; }
int GetCategories() const override { return static_cast<int>(EventCategory::Window); }
String ToString() const override { return GetName(); }
};
class WindowLostFocusEvent : public Event
{
public:
static EventType GetStaticType() { return EventType::WindowLostFocus; }
EventType GetEventType() const override { return GetStaticType(); }
String GetName() const override { return "Window Lost Focus Event"; }
int GetCategories() const override { return static_cast<int>(EventCategory::Window); }
String ToString() const override { return GetName(); }
};
class WindowMovedEvent : public Event
{
public:
WindowMovedEvent(const int xPos, const int yPos) : x(xPos), y(yPos)
{
}
static EventType GetStaticType() { return EventType::WindowMoved; }
EventType GetEventType() const override { return GetStaticType(); }
String GetName() const override { return "Window Moved Event"; }
int GetCategories() const override { return static_cast<int>(EventCategory::Window); }
String ToString() const override { return GetName() + ": Position(" + x + ", " + y + ")"; }
private:
int x, y;
};
}
| 34.423077 | 95 | 0.716946 |
9dda1d6e577730da6c3a1d8c0354670d75279cd3 | 31,706 | h | C | server/Server/Script/LuaFnTbl_Scene.h | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 3 | 2018-06-19T21:37:38.000Z | 2021-07-31T21:51:40.000Z | server/Server/Script/LuaFnTbl_Scene.h | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | null | null | null | server/Server/Script/LuaFnTbl_Scene.h | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 13 | 2015-01-30T17:45:06.000Z | 2022-01-06T02:29:34.000Z |
//-----------------------------------------------------------------------------
// 文件名 : LuaFnTbl_Scene.h
// 模块 : Script
// 功能 : 场景相关倒出函数
// 修改历史:
//-----------------------------------------------------------------------------
#ifndef __LUAFNTBL_SCENE_H__
#define __LUAFNTBL_SCENE_H__
#include "LuaFnMacro.h"
#include "Scene.h"
#include "SceneManager.h"
#include "CopySceneManager.h"
#include "GWSystemMsg.h"
namespace LuaFnTbl
{
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnGetSceneType
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* 功能说明 :
* 返回当前场景的类型,详见:Config/SceneInfo.ini 里Type字段描述
*/
INT LuaFnGetSceneType(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
{
Scene* pScene = (Scene*)(g_pSceneManager->GetScene(sceneId));
AssertEx(pScene,"场景ID出错 LuaFnGetSceneType");
if(pScene)
{
//Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;
INT nType = pScene->GetSceneType() ;
Lua_PushNumber(L,nType);
return 1;
}
}
LUA_LEAVE_FUNCTION
Lua_PushNumber(L,SCENE_TYPE_INVALID);
return 1 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnCreateCopyScene
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* 功能说明 :
* 返回值:如果返回-1,表示创建失败,否则返回创建成功的场景号
* 根据已经设置好的数据创建副本, 可以选择的设置参数:
* 见“*SetSceneLoad_*”或“*SetCopySceneData_*”类型的函数
*/
INT LuaFnCreateCopyScene(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
BEGINSCENEDEFINE("LuaFnCreateCopyScene")
COPYSCENE_SELECT SelectScene ;
SelectScene.m_Load = pScene->m_SceneLoad ;
SelectScene.m_SceneDataType = 0 ;
SelectScene.m_CopyData = pScene->m_CopyData ;
SelectScene.m_CopyData.m_SourSceneID = sceneId ;//不需要设置,自动填充
INT nRet = g_pCopySceneManager->SelectScene( &SelectScene ) ;
Lua_PushNumber(L,nRet);
return 1 ;
ENDSCENEDEFINE
RETURNFALSE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetSceneLoad_Map
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* mapName
* 导航图文件名,字符串类型
* 功能说明 :
* 设置副本创建选项里的导航图文件,类似"*.nav", 不需要带路径
* 注意:在创建副本时候,必须设置地图文件名,而且,此地图已经
* 配置的SceneInfo.ini里
*/
INT LuaFnSetSceneLoad_Map(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
const CHAR*mapName = Lua_ValueToString(L,2);
BEGINSCENEDEFINE("LuaFnSetSceneLoad_Map")
pScene->SetSceneLoad_Map( mapName ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetSceneLoad_Monster
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* monsterName
* 怪物分布文件名,字符串类型
* 功能说明 :
* 设置副本创建选项里的怪物分布文件,类似"*_monster.ini",
* 不需要带路径
*/
INT LuaFnSetSceneLoad_Monster(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
const CHAR*monsterName = Lua_ValueToString(L,2);
BEGINSCENEDEFINE("LuaFnSetSceneLoad_Monster")
pScene->SetSceneLoad_Monster( monsterName ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetSceneLoad_Platform
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* platformName
* 操作台分布文件名,字符串类型
* 功能说明 :
* 设置副本创建选项里的操作台分布文件,类似"*_platform.ini",
* 不需要带路径
*/
INT LuaFnSetSceneLoad_Platform(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
const CHAR*platformName = Lua_ValueToString(L,2);
BEGINSCENEDEFINE("LuaFnSetSceneLoad_Platform")
pScene->SetSceneLoad_Platform( platformName ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetSceneLoad_GrowPointData
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* growpointdataName
* 生长点分布文件名,字符串类型
* 功能说明 :
* 设置副本创建选项里的生长点分布文件,类似"*_growpoint.ini",
* 不需要带路径
*/
INT LuaFnSetSceneLoad_GrowPointData(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
const CHAR*growpointdataName = Lua_ValueToString(L,2);
BEGINSCENEDEFINE("LuaFnSetSceneLoad_GrowPointData")
pScene->SetSceneLoad_GrowPointData( growpointdataName ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetSceneLoad_GrowPointSetup
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* growpointsetupName
* 从生长点里能生成的物品分布文件名,字符串类型
* 功能说明 :
* 设置副本创建选项里的从生长点里能生成的物品分布文件,类似"*_growpointsetup.ini",
* 不需要带路径
*/
INT LuaFnSetSceneLoad_GrowPointSetup(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
const CHAR*growpointsetupName = Lua_ValueToString(L,2);
BEGINSCENEDEFINE("LuaFnSetSceneLoad_GrowPointSetup")
pScene->SetSceneLoad_GrowPointData( growpointsetupName ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetSceneLoad_Area
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* areaName
* 事件区分布文件名,字符串类型
* 功能说明 :
* 设置副本创建选项里的事件区分布文件,类似"*_area.ini",
* 不需要带路径
*/
INT LuaFnSetSceneLoad_Area(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
const CHAR*areaName = Lua_ValueToString(L,2);
BEGINSCENEDEFINE("LuaFnSetSceneLoad_Area")
pScene->SetSceneLoad_GrowPointData( areaName ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetSceneLoad_Pet
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* petName
* 宠物分布文件名,字符串类型
* 功能说明 :
* 设置副本创建选项里的宠物分布文件,类似"*_pet.ini",
* 不需要带路径
*/
INT LuaFnSetSceneLoad_Pet(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
const CHAR*petName = Lua_ValueToString(L,2);
BEGINSCENEDEFINE("LuaFnSetSceneLoad_Pet")
pScene->SetSceneLoad_GrowPointData( petName ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetSceneLoad_PatrolPointData
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* patrolpointdataName
* 巡逻路径分布文件名,字符串类型
* 功能说明 :
* 设置副本创建选项里的巡逻路径分布文件,类似"*_patrolpoint.ini",
* 不需要带路径
*/
INT LuaFnSetSceneLoad_PatrolPointData(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
const CHAR*patrolpointdataName = Lua_ValueToString(L,2);
BEGINSCENEDEFINE("LuaFnSetSceneLoad_PatrolPointData")
pScene->SetSceneLoad_GrowPointData( patrolpointdataName ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetCopySceneData_TeamLeader
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* guidLeader
* 队长的GUID,UINT
* 功能说明 :
* 设置副本创建数据里的队长GUID
*/
INT LuaFnSetCopySceneData_TeamLeader(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
GUID_t guidLeader = Lua_ValueToNumber(L,2);
BEGINSCENEDEFINE("LuaFnSetCopySceneData_TeamLeader")
pScene->SetCopySceneData_TeamLeader( guidLeader ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetCopySceneData_NoUserCloseTime
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* closeTime
* 时间(毫秒),UINT
* 功能说明 :
* 设置副本创建数据里的:没有人后副本场景自动关闭清除的时间。
*/
INT LuaFnSetCopySceneData_NoUserCloseTime(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
UINT closeTime = Lua_ValueToNumber(L,2);
BEGINSCENEDEFINE("LuaFnSetCopySceneData_NoUserCloseTime")
pScene->SetCopySceneData_NoUserCloseTime( closeTime ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetCopySceneData_Timer
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* uTime
* 时间(毫秒),UINT
* 功能说明 :
* 设置副本创建数据里的:场景定时器的时间间隔,如果为0表示没有设置。
*/
INT LuaFnSetCopySceneData_Timer(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
UINT uTime = Lua_ValueToNumber(L,2);
BEGINSCENEDEFINE("LuaFnSetCopySceneData_Timer")
pScene->SetCopySceneData_Timer( uTime ) ;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnSetCopySceneData_Param
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* uIndex
* 索引,UINT 最大可以到32
* nValue
* 值,UINT
* 功能说明 :
* 设置副本创建数据里的:场景参数信息
*/
INT LuaFnSetCopySceneData_Param(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
UINT uIndex = Lua_ValueToNumber(L,2);
INT nValue = Lua_ValueToNumber(L,3);
Scene* pScene = (Scene*)(g_pSceneManager->GetScene(sceneId));
AssertEx(pScene,"场景ID出错 LuaFnSetCopySceneData_Param");
if(pScene)
{
//Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;
pScene->SetCopySceneData_Param( uIndex, nValue ) ;
}
LUA_LEAVE_FUNCTION
return 0 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnGetCopySceneData_TeamLeader
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* 功能说明 :
* 返回副本创建数据里的队长GUID,失败-1
*/
INT LuaFnGetCopySceneData_TeamLeader(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
Scene* pScene = (Scene*)(g_pSceneManager->GetScene(sceneId));
AssertEx(pScene,"场景ID出错 LuaFnGetCopySceneData_TeamLeader");
if(pScene)
{
//Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;
GUID_t guidLeader = pScene->GetCopySceneData_TeamLeader( ) ;
Lua_PushNumber(L,guidLeader);
return 1;
}
LUA_LEAVE_FUNCTION
Lua_PushNumber(L,INVALID_ID);
return 1 ;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnGetCopySceneData_NoUserCloseTime
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* 功能说明 :
* 返回没有人后副本场景自动关闭清除的时间(毫秒)。
*/
INT LuaFnGetCopySceneData_NoUserCloseTime(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
BEGINSCENEDEFINE("LuaFnGetCopySceneData_NoUserCloseTime")
UINT closeTime = pScene->GetCopySceneData_NoUserCloseTime( ) ;
Lua_PushNumber(L,closeTime);
return 1;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnGetCopySceneData_Timer
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* 功能说明 :
* 读取场景定时器的时间间隔,如果为0表示没有设置。
*/
INT LuaFnGetCopySceneData_Timer(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
BEGINSCENEDEFINE("LuaFnGetCopySceneData_Timer")
UINT uTime = pScene->GetCopySceneData_Timer( ) ;
Lua_PushNumber(L,uTime);
return 1;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-10-16
* 函数名称 : LuaFnGetCopySceneData_Param
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* uIndex
* 索引,UINT 最大可以到32
* 功能说明 :
* 读取场景参数信息
*/
INT LuaFnGetCopySceneData_Param(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
UINT uIndex = Lua_ValueToNumber(L,2);
{
Scene* pScene = (Scene*)(g_pSceneManager->GetScene(sceneId));
AssertEx(pScene,"场景ID出错 LuaFnGetCopySceneData_Param");
if(pScene)
{
//Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;
INT nValue = pScene->GetCopySceneData_Param( uIndex ) ;
Lua_PushNumber(L,nValue);
return 1;
}
}
LUA_LEAVE_FUNCTION
Lua_PushNumber(L,0);
return 1;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-11-18
* 函数名称 : LuaFnGetCopyScene_HumanCount
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* 功能说明 :
* 返回当前场景里面的玩家数量
*/
INT LuaFnGetCopyScene_HumanCount(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
BEGINSCENEDEFINE("LuaFnGetCopyScene_HumanCount")
INT nHumanCount = pScene->GetCopyScene_HumanCount() ;
Lua_PushNumber(L,nHumanCount);
return 1;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
Lua_PushNumber(L,0);
return 1;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-11-18
* 函数名称 : LuaFnGetCopyScene_HumanObjId
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* uIndex
* 索引,UINT 最大可以到32
* 功能说明 :
* 读取场景参数信息
*/
INT LuaFnGetCopyScene_HumanObjId(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
UINT uIndex = Lua_ValueToNumber(L,2);
BEGINSCENEDEFINE("LuaFnGetCopyScene_HumanObjId")
ObjID_t HumanObjId = pScene->GetCopyScene_HumanObjID( uIndex ) ;
Lua_PushNumber(L,HumanObjId);
return 1;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-11-24
* 函数名称 : LuaFnIsObjValid
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* objId
* objId 号
* 功能说明 :
* 判断是否拥有objId号的Obj
*/
INT LuaFnIsObjValid(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
ObjID_t objId = Lua_ValueToNumber(L,2);
BEGINSCENEDEFINE("LuaFnIsObjValid")
Obj* pObj = pScene->GetObjManager()->GetObj(objId) ;
if( pObj==NULL )
{
Lua_PushNumber(L,FALSE);
}
else
{
Lua_PushNumber(L,TRUE);
}
return 1;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2005-11-24
* 函数名称 : LuaFnIsCharacterLiving
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* objId
* objId 号
* 功能说明 :
* 判断objId号的Obj是否是活的
*/
INT LuaFnIsCharacterLiving(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
ObjID_t objId = Lua_ValueToNumber(L,2);
BEGINSCENEDEFINE("LuaFnIsCharacterLiving")
Obj* pObj = pScene->GetObjManager()->GetObj(objId) ;
if( pObj && IsCharacterObj(pObj->GetObjType()) )
{
Obj_Character* pCharacter = (Obj_Character*)pObj ;
if( pCharacter->IsActiveObj() && pCharacter->IsAlive() )
{
Lua_PushNumber(L,TRUE);
}
else
{
Lua_PushNumber(L,FALSE);
}
}
else
{
Lua_PushNumber(L,FALSE);
}
return 1;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
/****************************************************************************
* 开发人员:
* 编写时间: 2006-2-28 10:28
* 函数名称: LuaFnSendNormalMail
* 参数说明:
* sceneId
* 场景编号
* objId
* 调用者 ID,无符号整型
* szName
* 收件人姓名
* szMail
* 邮件内容
*
* 功能说明: 发送普通邮件
* 修改记录:
*****************************************************************************/
INT LuaFnSendNormalMail(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L, 1);
ObjID_t objId = Lua_ValueToNumber(L, 2);
const CHAR*szName = Lua_ValueToString(L, 3);
const CHAR*szMail = Lua_ValueToString(L, 4);
BEGINSCENEDEFINE("LuaFnSendNormalMail")
Assert( szName );
Assert( szMail );
Obj_Human* pHuman = pScene->GetHumanManager()->GetHuman( objId );
if( pHuman == NULL )
{
Assert( pHuman );
return 0;
}
pScene->SendNormalMail( pHuman, szName, szMail );
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0;
}
/****************************************************************************
* 开发人员:
* 编写时间:
* 函数名称: LuaFnSendSystemMail
* 参数说明:
* sceneId
* 场景编号
* szName
* 收件人姓名
* szMail
* 邮件内容
*
* 功能说明: 发送系统邮件
* 修改记录:
*****************************************************************************/
INT LuaFnSendSystemMail( Lua_State* L )
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L, 1);
const CHAR* szName = Lua_ValueToString(L, 2);
const CHAR* szMail = Lua_ValueToString(L, 3);
BEGINSCENEDEFINE("LuaFnSendSystemMail")
Assert( szName );
Assert( szMail );
pScene->SendSystemMail( szName, szMail );
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0;
}
/****************************************************************************
* 开发人员:
* 编写时间: 2006-2-28 13:30
* 函数名称: LuaFnSendScriptMail
* 参数说明:
* sceneId
* 场景编号
* szName
* 收件人姓名
* uParam0 ~ uParam3
* 可执行邮件自带的 4 个参数
*
* 功能说明: 发送可执行邮件
* 修改记录:
*****************************************************************************/
INT LuaFnSendScriptMail(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L, 1);
const CHAR*szName = Lua_ValueToString(L, 2);
UINT uParam0 = Lua_ValueToNumber(L, 3);
UINT uParam1 = Lua_ValueToNumber(L, 4);
UINT uParam2 = Lua_ValueToNumber(L, 5);
UINT uParam3 = Lua_ValueToNumber(L, 6);
BEGINSCENEDEFINE("LuaFnSendScriptMail")
Assert( szName );
pScene->SendScriptMail( szName, uParam0, uParam1, uParam2, uParam3 );
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0;
}
/****************************************************************************
* 开发人员:
* 编写时间: 2006-3-4 17:46
* 函数名称: LuaFnSendMailToAllFriend
* 参数说明:
* sceneId
* 场景编号
* selfId
* 调用者 ID,无符号整型
* szMail
* 邮件内容
*
* 功能说明: 给所有好友发送普通邮件
* 修改记录:
*****************************************************************************/
INT LuaFnSendMailToAllFriend(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L, 1);
ObjID_t objId = Lua_ValueToNumber(L, 2);
const CHAR*szMail = Lua_ValueToString(L, 3);
BEGINSCENEDEFINE("LuaFnSendMailToAllFriend")
Assert( szMail );
Obj_Human* pHuman = pScene->GetHumanManager()->GetHuman( objId );
if( pHuman == NULL )
{
Assert( pHuman );
return 0;
}
pHuman->GetHumanRelation()->SendMailToAllFriend(szMail);
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
return 0;
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2006-3-23
* 函数名称 : LuaFnGetMonsterCount
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* 功能说明 :
* 取得此场景中的怪物数量
*/
INT LuaFnGetMonsterCount(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
BEGINSCENEDEFINE("LuaFnGetMonsterCount")
UINT uRet = pScene->GetMonsterManager()->GetCount() ;
pScene->m_ObjIDList.m_nCount = uRet ;
for( UINT i=0; i<uRet; i++ )
{
pScene->m_ObjIDList.m_aIDs[i] = pScene->GetMonsterManager()->GetObjByIndex(i)->GetID() ;
}
Lua_PushNumber(L,uRet);
return 1;
ENDSCENEDEFINE
RETURNFALSE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2006-3-23
* 函数名称 : LuaFnGetMonsterObjID
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* nIndex
* 怪物索引号
* 功能说明 :
* 根据索引号取得怪物的ObjID
*/
INT LuaFnGetMonsterObjID(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
INT nIndex = Lua_ValueToNumber(L,2);
BEGINSCENEDEFINE("LuaFnGetMonsterObjID")
if( nIndex>=pScene->m_ObjIDList.m_nCount )
{
Assert(FALSE) ;
RETURNFALSE
}
Obj* pObj = (Obj*)(pScene->GetObjManager()->GetObj(pScene->m_ObjIDList.m_aIDs[nIndex])) ;
if( pObj && pObj->GetObjType()==Obj::OBJ_TYPE_MONSTER)
{
UINT uRet = (UINT)pObj->GetID() ;
Lua_PushNumber(L,uRet);
return 1;
}
ENDSCENEDEFINE
RETURNFALSE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2006-05-15
* 函数名称 : LuaFnIsCanEnterCopyScene
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* guid
* 玩家GUID
* 功能说明 :
* 判断玩家是否可以进入场景sceneId,
* 返回1 表示能够进,返回0表示不能进, -1表示出错
*/
INT LuaFnIsCanEnterCopyScene(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
GUID_t guid = Lua_ValueToNumber(L,2);
Scene* pScene = (Scene*)(g_pSceneManager->GetScene(sceneId));
AssertEx(pScene,"场景ID出错 LuaFnGetSceneType");
if(pScene)
{
BOOL bRet = pScene->m_CopyData.IsHaveMember(guid) ;
Lua_PushNumber(L,bRet);
return 1;
}
Lua_PushNumber(L,-1);
return 1;
LUA_LEAVE_FUNCTION
RETURNFALSE
}
INT LuaFnGetNpcShopIndexNM(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
ObjID_t objId = Lua_ValueToNumber(L, 2);
INT ShopIndex = Lua_ValueToNumber(L,3);
BEGINSCENEDEFINE("LuaFnGetNpcShopIndexNM")
INT Index = pScene->GetMonsterManager()->GetMonster(objId)->GetShopManager()->GetShopByIndex(ShopIndex)->m_ShopId;
Assert(Index);
Lua_PushNumber(L,Index);
return 1;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
INT LuaFnGetNpcShopNameNM(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
ObjID_t objId = Lua_ValueToNumber(L, 2);
INT ShopIndex = Lua_ValueToNumber(L,3);
BEGINSCENEDEFINE("LuaFnGetNpcShopNameNM")
Lua_PushString(L,pScene->GetMonsterManager()->GetMonster(objId)->GetShopManager()->GetShopByIndex(ShopIndex)->m_szShopName);
return 1;
ENDSCENEDEFINE
LUA_LEAVE_FUNCTION
RETURNFALSE
}
/** -----------------------------------------------------------------------
* 开发人员 :
* 编写时间 : 2008-01-4
* 函数名称 : LuaSendSysMsg
* 参数说明 :
* L
* LuaState执行环境指针
* sceneId
* 调用该函数场景ID,short
* strSysMsg
* 系统广播消息
* 功能说明 :发送系统广播消息
*
*/
INT LuaSendSysMsg(Lua_State* L)
{
LUA_ENTER_FUNCTION
SceneID_t sceneId = Lua_ValueToNumber(L,1);
ObjID_t selfId = Lua_ValueToNumber(L,2);
const CHAR *strMsg=Lua_ValueToString(L,3);
BEGINHUMANDEFINE("LuaSendSysMsg")
BYTE nMsgSize = (BYTE)strlen(strMsg);
if( nMsgSize >= MAX_SYSTEM_MSG_SIZE ) nMsgSize = MAX_SYSTEM_MSG_SIZE-1;
GWSystemMsg *pPacket = (GWSystemMsg*)(pScene->m_pPacket_SysMsg);
if( nMsgSize > 0 && pPacket )
{
pPacket->SetGUID(pHuman->GetGUID());
pPacket->SetMessageType(GWSystemMsg::SYSTEMMSG_TYPE_SCRIPT);
pPacket->SetContexSize(nMsgSize);
pPacket->SetContex(strMsg);
g_pServerManager->SendPacket(pPacket,INVALID_ID);
}
return 0;
ENDHUMANDEFINE
LUA_LEAVE_FUNCTION
return 0;
}
}
#endif
| 29.303142 | 132 | 0.451397 |
6fb9aca84f1c287f04d11fbe9009da41564be643 | 3,346 | c | C | Unix Family/Linux.lrk.e/sh-utils-1.16/src/printenv.c | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | 3 | 2021-05-15T15:57:13.000Z | 2022-03-16T09:11:05.000Z | Unix Family/Linux.lrk.e/sh-utils-1.16/src/printenv.c | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | null | null | null | Unix Family/Linux.lrk.e/sh-utils-1.16/src/printenv.c | fengjixuchui/Family | 2abe167082817d70ff2fd6567104ce4bcf0fe304 | [
"MIT"
] | 3 | 2021-05-15T15:57:15.000Z | 2022-01-08T20:51:04.000Z | /* printenv -- print all or part of environment
Copyright (C) 89, 90, 91, 92, 93, 94, 95, 1996 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
/* Usage: printenv [variable...]
If no arguments are given, print the entire environment.
If one or more variable names are given, print the value of
each one that is set, and nothing for ones that are not set.
Exit status:
0 if all variables specified were found
1 if not
David MacKenzie and Richard Mlynarik */
#include <config.h>
#include <stdio.h>
#include <sys/types.h>
#include <getopt.h>
#include "system.h"
#include "error.h"
/* The name this program was run with. */
char *program_name;
/* If nonzero, display usage information and exit. */
static int show_help;
/* If nonzero, print the version on standard output and exit. */
static int show_version;
static struct option const long_options[] =
{
{"help", no_argument, &show_help, 1},
{"version", no_argument, &show_version, 1},
{0, 0, 0, 0}
};
extern char **environ;
static void
usage (int status)
{
if (status != 0)
fprintf (stderr, _("Try `%s --help' for more information.\n"),
program_name);
else
{
printf (_("Usage: %s [OPTION]... [VARIABLE]...\n"), program_name);
printf (_("\
If no environment VARIABLE specified, print them all.\n\
\n\
--help display this help and exit\n\
--version output version information and exit\n"));
puts (_("\nReport bugs to sh-utils-bugs@gnu.ai.mit.edu"));
}
exit (status);
}
int
main (int argc, char **argv)
{
char **env;
char *ep, *ap;
int i;
int matches = 0;
int c;
int exit_status;
program_name = argv[0];
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
while ((c = getopt_long (argc, argv, "", long_options, (int *) 0)) != EOF)
{
switch (c)
{
case 0:
break;
default:
usage (1);
}
}
if (show_version)
{
printf ("printenv (%s) %s\n", GNU_PACKAGE, VERSION);
exit (0);
}
if (show_help)
usage (0);
if (optind == argc)
{
for (env = environ; *env != NULL; ++env)
puts (*env);
exit_status = 0;
}
else
{
for (i = optind; i < argc; ++i)
{
for (env = environ; *env; ++env)
{
ep = *env;
ap = argv[i];
while (*ep != '\0' && *ap != '\0' && *ep++ == *ap++)
{
if (*ep == '=' && *ap == '\0')
{
puts (ep + 1);
++matches;
break;
}
}
}
}
exit_status = (matches != argc - optind);
}
if (ferror (stdout) || fclose (stdout) == EOF)
error (2, errno, _("standard output"));
exit (exit_status);
}
| 23.236111 | 80 | 0.614764 |
a57efc3ae057d7c2d50b618c624645d3f88423fb | 5,153 | c | C | CM_GDP_CU/src/ExtraModels/MyHydBrakeCU_20220305_2353.c | CU-2021AM-GDP-T1/rollstiffnesscontrol-enhancehandling-matlabsimulink | 64162ebb0e0dc51f23e545f886bbcfce1e9e5ab6 | [
"MIT"
] | null | null | null | CM_GDP_CU/src/ExtraModels/MyHydBrakeCU_20220305_2353.c | CU-2021AM-GDP-T1/rollstiffnesscontrol-enhancehandling-matlabsimulink | 64162ebb0e0dc51f23e545f886bbcfce1e9e5ab6 | [
"MIT"
] | null | null | null | CM_GDP_CU/src/ExtraModels/MyHydBrakeCU_20220305_2353.c | CU-2021AM-GDP-T1/rollstiffnesscontrol-enhancehandling-matlabsimulink | 64162ebb0e0dc51f23e545f886bbcfce1e9e5ab6 | [
"MIT"
] | null | null | null | /*
******************************************************************************
** CarMaker - Version 9.0.1
** Vehicle Dynamics Simulation Toolkit
**
** Copyright (C) IPG Automotive GmbH
** Bannwaldallee 60 Phone +49.721.98520.0
** 76185 Karlsruhe Fax +49.721.98520.99
** Germany WWW www.ipg-automotive.com
******************************************************************************
**
** Simple Hydraulic Brake Controller Model for a four wheel vehicle
**
** Add the declaration of the register function to one of your header files,
** for example to User.h and call it in User_Register()
**
** HydBrakeCU_Register_MyModel ();
**
******************************************************************************
*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "CarMaker.h"
#include "Car/Vehicle_Car.h"
#include "MyModels.h"
#define NWHEEL 4
static const char ThisModelClass[] = "Brake.Control";
static const char ThisModelKind[] = "MyModel";
static const int ThisVersionId = 1;
struct tMyModel {
double TrqDistrib[NWHEEL]; /* Model Parameter */
double dTrqSum[NWHEEL]; /* Brake torque [Nm] */
};
/*
** MyModel_New ()
**
** Initialising the model
**
** Call:
** - one times at the beginning of every TestRun
*/
static void *
MyModel_New (tInfos *Inf, tHydBrakeCU_CfgIF *CfgIF, const char *KindKey)
{
struct tMyModel *mp = NULL;
const char *ModelKind, *key;
char MsgPre[64];
double dvec[NWHEEL];
int i, VersionId = 0;
sprintf (MsgPre, "%s %s", ThisModelClass, ThisModelKind);
if (CfgIF->nWheels != NWHEEL) {
LogErrF (EC_Init, "%s: wheel number mismatch (brake %d, vehicle %d)", MsgPre,
NWHEEL,CfgIF->nWheels);
return NULL;
}
if ((ModelKind = SimCore_GetKindInfo(Inf, ModelClass_HydBrakeControl, KindKey,
0, ThisVersionId, &VersionId)) == NULL)
return NULL;
mp = (struct tMyModel*)calloc(1, sizeof(struct tMyModel));
/*** Get parameters of MyModel */
key = "Brake.Pedal2Trq";
iGetTable(Inf, key, dvec, NWHEEL, 1, &i);
if (i != NWHEEL) {
LogErrF (EC_Init, "%s: Unsupported argument for '%s'", MsgPre, key);
goto ErrorReturn;
}
for (i=0; i<NWHEEL; i++)
mp->TrqDistrib[i] = dvec[i];
return mp;
ErrorReturn:
free (mp);
return NULL;
}
static void
MyModel_DeclQuants_dyn (struct tMyModel *mp, int park)
{
static struct tMyModel MyModel_Dummy = {{0}};
if (park)
mp = &MyModel_Dummy;
/* Define here dict entries for dynamically allocated variables. */
}
/*
** MyModel_DeclQuants ()
**
** Defining DataDictionary Quantities
**
** Call:
** - at the beginning of every TestRun, after the call for the _New function
*/
static void
MyModel_DeclQuants (void *MP)
{
struct tMyModel *mp = (struct tMyModel *)MP;
if (mp == NULL) {
/* Define here dict entries for non-dynamically allocated (static) variables. */
} else {
MyModel_DeclQuants_dyn (mp, 0);
}
}
/*
** MyModel_Calc ()
**
** Calculation of the model
**
** Call:
** - every cycle
*/
static int
MyModel_Calc (
void *MP, /* model parameter handle */
struct tHydBrakeCU_IF *IF, /* brake interface structure */
double dt) /* time step */
{
int i;
double desiredTrq[NWHEEL], dTrq[NWHEEL];
struct tMyModel *mp = (struct tMyModel *)MP;
for (i=0; i < NWHEEL; i++) {
double u;
desiredTrq[i] = mp->TrqDistrib[i] * IF->Pedal;
dTrq[i] = desiredTrq[i] - IF->Trq_WB[i];
if (IF->Pedal<=1e-6 && IF->Trq_WB[i]<1e-6) {
IF->V[i] = 0.0;
IF->V[4+i] = 0.0;
IF->Pedal = 0;
continue;
}
mp->dTrqSum[i] += dTrq[i];
/* controller P-value 1e-2; controller I-value 1e-2 */
u = 1e-2 * dTrq[i] + 1e-2 * mp->dTrqSum[i] * dt;
if (u>0) { //pressure buildup
if (u>1) {
IF->V[i] = 0.0;
} else {
IF->V[i] = 1.0 - u;
}
IF->V[4+i] = 0.0;
} else { // pressure reduction
IF->V[i] = 1.0;
if (-u>1) {
IF->V[4+i] = 1.0;
} else {
IF->V[4+i] = -u;
}
}
if (IF->V[4+i]>0)
IF->PumpCtrl = 1;
else
IF->PumpCtrl = 0;
}
return 0;
}
/*
** MyModel_Delete ()
**
** Uninitialising the model
**
** Call:
** - at the end of every TestRun
*/
static void
MyModel_Delete (void *MP)
{
struct tMyModel *mp = (struct tMyModel *)MP;
/* Park the dict entries for dynamically allocated variables before deleting */
MyModel_DeclQuants_dyn (mp, 1);
free (mp);
}
/*
** HydBrakeCU_Register_MyModel
**
*/
int
HydBrakeCU_Register_MyModel (void)
{
tModelClassDescr mp;
memset (&mp, 0, sizeof(mp));
mp.HydBrakeControl.New = MyModel_New;
mp.HydBrakeControl.Calc = MyModel_Calc;
mp.HydBrakeControl.Delete = MyModel_Delete;
mp.HydBrakeControl.DeclQuants = MyModel_DeclQuants;
mp.HydBrakeControl.VersionId = ThisVersionId;
/* Should only be used if the model doesn't read params from extra files */
mp.HydBrakeControl.ParamsChanged = ParamsChanged_IgnoreCheck;
return Model_Register(ModelClass_HydBrakeControl, ThisModelKind, &mp);
}
| 22.211207 | 83 | 0.588783 |
48d6055d6e4635bcbd11fecbd52d48c1b4db6160 | 799 | c | C | src/chap18/ccos_ex.c | niklasengvall/cinanutshell2e | d849eb552901591232917a197d2ac017ef96a5fa | [
"MIT"
] | null | null | null | src/chap18/ccos_ex.c | niklasengvall/cinanutshell2e | d849eb552901591232917a197d2ac017ef96a5fa | [
"MIT"
] | null | null | null | src/chap18/ccos_ex.c | niklasengvall/cinanutshell2e | d849eb552901591232917a197d2ac017ef96a5fa | [
"MIT"
] | null | null | null | // ccos_ex.c : ccos() example
// -------------------------------------------------------------
#include <complex.h> // double complex ccos( double complex z );
// float complex ccosf( float complex z );
// long double complex ccosl( long double complex z );
#include <stdio.h>
/* Demonstrate the exponential definition
* of the complex cosine function.
*/
int main()
{
double complex z = 2.2 + 3.3 * I;
double complex c, d;
c = ccos( z );
d = 0.5 * ( cexp( z * I ) + cexp( -z * I ));
printf("The ccos() function returns %.2f %+.2f × I.\n",
creal(c), cimag(c) );
printf("Using the cexp() function, the result is %.2f %+.2f × I.\n",
creal(d), cimag(d) );
return 0;
}
| 29.592593 | 78 | 0.474343 |
5b48ebd616e8d18345b5131cef356fbcfe7a6d8c | 16,414 | h | C | clicks/bluetooth2/lib/include/bluetooth2.h | StrahinjaJacimovic/mikrosdk_click_v2 | f8002047c96605f340957a0d3fdbde33706d02ac | [
"MIT"
] | 31 | 2020-10-02T14:15:14.000Z | 2022-03-24T08:33:21.000Z | clicks/bluetooth2/lib/include/bluetooth2.h | greghol/mikrosdk_click_v2 | 76e5dec265dce5fca72c4b93f77afd668dde5dfa | [
"MIT"
] | 4 | 2020-10-27T14:05:00.000Z | 2022-03-10T09:38:57.000Z | clicks/bluetooth2/lib/include/bluetooth2.h | greghol/mikrosdk_click_v2 | 76e5dec265dce5fca72c4b93f77afd668dde5dfa | [
"MIT"
] | 32 | 2020-11-28T07:56:42.000Z | 2022-03-14T19:42:29.000Z | /****************************************************************************
** Copyright (C) 2020 MikroElektronika d.o.o.
** Contact: https://www.mikroe.com/contact
**
** 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 bluetooth2.h
* @brief This file contains API for Bluetooth 2 Click Driver.
*/
#ifndef BLUETOOTH2_H
#define BLUETOOTH2_H
#ifdef __cplusplus
extern "C"{
#endif
#include "drv_digital_out.h"
#include "drv_digital_in.h"
#include "drv_analog_in.h"
#include "drv_uart.h"
/*!
* @addtogroup bluetooth2 Bluetooth 2 Click Driver
* @brief API for configuring and manipulating Bluetooth 2 Click driver.
* @{
*/
/**
* @defgroup bluetooth2_set Bluetooth 2 Registers Settings
* @brief Settings for registers of Bluetooth 2 Click driver.
*/
/**
* @addtogroup bluetooth2_set
* @{
*/
/**
* @brief Bluetooth 2 list of AT commands.
* @brief AT commands list of Bluetooth 2 Click driver.
*/
#define BLUETOOTH2_ESCAPE_SEQUENCE "+++"
#define BLUETOOTH2_FACTORY_RESET "SET RESET"
#define BLUETOOTH2_LIST_PAIRINGS "SET BT PAIR"
#define BLUETOOTH2_REMOVE_PAIRINGS "SET BT PAIR *"
#define BLUETOOTH2_SW_RESET "RESET"
#define BLUETOOTH2_SET_DEVICE_NAME "SET BT NAME "
#define BLUETOOTH2_FIND_OTHER_DEVICES "INQUIRY "
#define BLUETOOTH2_PAIR "PAIR "
#define BLUETOOTH2_SET_CONTROL_CONFIG "SET CONTROL CONFIG "
#define BLUETOOTH2_ENABLE_OK_WITH_DEFAULT_VALUES "0040 1100"
#define BLUETOOTH2_DEV_ADDRESS_FORMAT "xx:xx:xx:xx:xx:xx"
/**
* @brief Bluetooth 2 driver buffer size.
* @details Specified size of driver ring buffer.
* @note Increase buffer size if needed.
*/
#define DRV_BUFFER_SIZE 200
/*! @} */ // bluetooth2_set
/**
* @defgroup bluetooth2_map Bluetooth 2 MikroBUS Map
* @brief MikroBUS pin mapping of Bluetooth 2 Click driver.
*/
/**
* @addtogroup bluetooth2_map
* @{
*/
/**
* @brief MikroBUS pin mapping.
* @details Mapping pins of Bluetooth 2 Click to the selected MikroBUS.
*/
#define BLUETOOTH2_MAP_MIKROBUS( cfg, mikrobus ) \
cfg.tx_pin = MIKROBUS( mikrobus, MIKROBUS_TX ); \
cfg.rx_pin = MIKROBUS( mikrobus, MIKROBUS_RX ); \
cfg.cts = MIKROBUS( mikrobus, MIKROBUS_CS ); \
cfg.aio = MIKROBUS( mikrobus, MIKROBUS_AN ); \
cfg.rst = MIKROBUS( mikrobus, MIKROBUS_RST ); \
cfg.io7 = MIKROBUS( mikrobus, MIKROBUS_PWM ); \
cfg.rts = MIKROBUS( mikrobus, MIKROBUS_INT )
/*! @} */ // bluetooth2_map
/*! @} */ // bluetooth2
/**
* @brief Bluetooth 2 Click context object.
* @details Context object definition of Bluetooth 2 Click driver.
*/
typedef struct bluetooth2_s
{
digital_out_t rst; /**< Reset. */
digital_out_t io7; /**< Programmable GPIO. */
digital_out_t cts; /**< Clear to Send. */
digital_in_t rts; /**< Request to Send. */
uart_t uart; /**< UART driver object. */
analog_in_t adc; /**< ADC module object. */
char uart_rx_buffer[ DRV_BUFFER_SIZE ]; /**< Buffer size. */
char uart_tx_buffer[ DRV_BUFFER_SIZE ]; /**< Buffer size. */
} bluetooth2_t;
/**
* @brief Bluetooth 2 Click configuration object.
* @details Configuration object definition of Bluetooth 2 Click driver.
*/
typedef struct
{
pin_name_t rx_pin; /**< RX pin. */
pin_name_t tx_pin; /**< TX pin. */
pin_name_t cts; /**< Clear to Send. */
pin_name_t aio; /**< Analog input. */
pin_name_t rst; /**< Reset. */
pin_name_t io7; /**< Programmable GPIO. */
pin_name_t rts; /**< Request to Send. */
analog_in_resolution_t resolution; /**< ADC resolution. */
float vref; /**< ADC reference voltage. */
uint32_t baud_rate; /**< Clock speed. */
bool uart_blocking; /**< Wait for interrupt or not. */
uart_data_bits_t data_bit; /**< Data bits. */
uart_parity_t parity_bit; /**< Parity bit. */
uart_stop_bits_t stop_bit; /**< Stop bits. */
} bluetooth2_cfg_t;
/**
* @brief Bluetooth 2 Click return value data.
* @details Predefined enum values for driver return values.
*/
typedef enum
{
BLUETOOTH2_OK = 0,
BLUETOOTH2_ERROR = -1
} bluetooth2_return_value_t;
/*!
* @addtogroup bluetooth2 Bluetooth 2 Click Driver
* @brief API for configuring and manipulating Bluetooth 2 Click driver.
* @{
*/
/**
* @brief Bluetooth 2 configuration object setup function.
* @details This function initializes click configuration structure to initial
* values.
* @param[out] cfg : Click configuration structure.
* See #bluetooth2_cfg_t object definition for detailed explanation.
* @return Nothing.
* @note The all used pins will be set to unconnected state.
*/
void bluetooth2_cfg_setup ( bluetooth2_cfg_t *cfg );
/**
* @brief Bluetooth 2 initialization function.
* @details This function initializes all necessary pins and peripherals used
* for this click board.
* @param[out] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[in] cfg : Click configuration structure.
* See #bluetooth2_cfg_t object definition for detailed explanation.
* @return @li @c 0 - Success,
* @li @c -1 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_init ( bluetooth2_t *ctx, bluetooth2_cfg_t *cfg );
/**
* @brief Bluetooth 2 default configuration function.
* @details This function executes a default configuration of Bluetooth 2
* click board.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @return None.
* @note This function can consist any necessary configuration or setting to put
* device into operating mode.
*/
void bluetooth2_default_cfg ( bluetooth2_t *ctx );
/**
* @brief Bluetooth 2 data writing function.
* @details This function writes a desired number of data bytes by using UART serial interface.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[in] data_buf : Data buffer for sending.
* @param[in] len : Number of bytes for sending.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_generic_write ( bluetooth2_t *ctx, char *data_buf, uint16_t len );
/**
* @brief Bluetooth 2 data reading function.
* @details This function reads a desired number of data bytes by using UART serial interface.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[out] data_buf : Output read data.
* @param[in] max_len : Number of bytes to be read.
* @return @li @c >0 - Number of data bytes read,
* @li @c <=0 - Error/Empty Ring buffer.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_generic_read ( bluetooth2_t *ctx, char *data_buf, uint16_t max_len );
/**
* @brief Bluetooth 2 read AN pin value function.
* @details This function reads results of AD conversion of the AN pin.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[out] data_out : Output ADC result.
* @return @li @c 0 - Success,
* @li @c -1 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_read_an_pin_value ( bluetooth2_t *ctx, uint16_t *data_out );
/**
* @brief Bluetooth 2 read AN pin voltage level function.
* @details This function reads results of AD conversion of the AN pin and
* converts them to proportional voltage level.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[out] data_out : Output voltage level of the analog pin [V].
* @return @li @c 0 - Success,
* @li @c -1 - Error.
*
* See #err_t definition for detailed explanation.
* @note The conversion to voltage depends on the entered configuration of the
* ADC (resolution, reference voltage).
*/
err_t bluetooth2_read_an_pin_voltage ( bluetooth2_t *ctx, float *data_out );
/**
* @brief Bluetooth 2 set clear to send pin function.
* @details This function sets the CTS pin to a desired state.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[in] state : Pin logic state.
* @return None.
* @note None.
*/
void bluetooth2_set_cts_pin ( bluetooth2_t *ctx, uint8_t state );
/**
* @brief Bluetooth 2 set reset pin function.
* @details This function sets the RST pin to a desired state.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[in] state : Pin logic state.
* @return None.
* @note None.
*/
void bluetooth2_set_rst_pin ( bluetooth2_t *ctx, uint8_t state );
/**
* @brief Bluetooth 2 set PIO7 pin function.
* @details This function sets the PIO7 pin to a desired state.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[in] state : Pin logic state.
* @return None.
* @note None.
*/
void bluetooth2_set_io7_pin ( bluetooth2_t *ctx, uint8_t state );
/**
* @brief Bluetooth 2 get request to send pin function.
* @details This function returns the RTS pin logic state.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @return Pin logic state.
* @note None.
*/
uint8_t bluetooth2_get_rts_pin ( bluetooth2_t *ctx );
/**
* @brief Bluetooth 2 write command function.
* @details This function sends a desired command with the CR byte appended to.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[in] data_buf : Command string.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_write_command ( bluetooth2_t *ctx, char *data_buf );
/**
* @brief Bluetooth 2 hw reset function.
* @details This function resets the module by toggling the RST pin.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @return None.
* @note None.
*/
void bluetooth2_hw_reset ( bluetooth2_t *ctx );
/**
* @brief Bluetooth 2 toggle mode function.
* @details This function is used to toggle between command mode and data mode
* by issuing the escape sequence.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_toggle_mode ( bluetooth2_t *ctx );
/**
* @brief Bluetooth 2 factory reset function.
* @details This function factory resets the device.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note Factory reset does not clear the pairings.
*/
err_t bluetooth2_factory_reset ( bluetooth2_t *ctx );
/**
* @brief Bluetooth 2 sw reset function.
* @details This function sw resets the device.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_sw_reset ( bluetooth2_t *ctx );
/**
* @brief Bluetooth 2 remove pairings function.
* @details This function removes all the device pairings.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_remove_pairings ( bluetooth2_t *ctx );
/**
* @brief Bluetooth 2 list current pairings function.
* @details This function lists all current pairings.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_list_pairings ( bluetooth2_t *ctx );
/**
* @brief Bluetooth 2 set local device name function.
* @details This function sets the local device name.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[in] dev_name : Device name ( up to 140 characters ).
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_set_device_name ( bluetooth2_t *ctx, char *dev_name );
/**
* @brief Bluetooth 2 find other devices function.
* @details This function is used to find other Bluetooth devices in the area i.e.
* to make a device discovery.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[in] timeout : The maximum amount of time (in units of 1.28 seconds) before the
* inquiry process is halted. Range: 1-48.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_find_other_devices ( bluetooth2_t *ctx, uint8_t timeout );
/**
* @brief Bluetooth 2 set local device name function.
* @details This function sets the local device name.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @param[in] dev_addr : Bluetooth device address of the remote device in format xx:xx:xx:xx:xx:xx
* where x is a hexadecimal digit.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t bluetooth2_pair ( bluetooth2_t *ctx, uint8_t *dev_addr );
/**
* @brief Bluetooth 2 enable OK response function.
* @details This function enables OK response.
* The module will display "OK." after each successful command.
* @param[in] ctx : Click context object.
* See #bluetooth2_t object definition for detailed explanation.
* @return @li @c >=0 - Success,
* @li @c <0 - Error.
*
* See #err_t definition for detailed explanation.
* @note This will set optional_block_1 and config_block of CONTROL CONFIG reg to 0040 1100 (default).
*/
err_t bluetooth2_enable_ok_response ( bluetooth2_t *ctx );
#ifdef __cplusplus
}
#endif
#endif // BLUETOOTH2_H
/*! @} */ // bluetooth2
// ------------------------------------------------------------------------ END
| 35.223176 | 102 | 0.668758 |
85bb0c6cbbf990b19e54e5f7068de28404b78174 | 996 | c | C | C&CPP/00-Code/c-program-basic/09-FileOperation/ErrorHandle.c | hiloWang/notes | 64a637a86f734e4e80975f4aa93ab47e8d7e8b64 | [
"Apache-2.0"
] | 2 | 2020-10-08T13:22:08.000Z | 2021-07-28T14:45:41.000Z | C&C++/c-program/FileOperation/ErrorHandle.c | flyfire/Programming-Notes-Code | 4b1bdd74c1ba0c007c504834e4508ec39f01cd94 | [
"Apache-2.0"
] | null | null | null | C&C++/c-program/FileOperation/ErrorHandle.c | flyfire/Programming-Notes-Code | 4b1bdd74c1ba0c007c504834e4508ec39f01cd94 | [
"Apache-2.0"
] | 6 | 2020-08-20T07:19:17.000Z | 2022-03-02T08:16:21.000Z | /*
============================================================================
Author : Ztiany
Description : 错误处理
============================================================================
*/
/*
C语言不提供对错误处理的直接支持,但是作为一种系统编程语言,它以返回值的形式允许您访问底层数据。在发生错误时,大多数的 C 或 UNIX 函数调用返回 1 或 NULL,
同时会设置一个错误代码 errno,该错误代码是全局变量,表示在函数调用期间发生了错误。可以在 <error.h> 头文件中找到各种各样的错误代码。
errno 错误码
perror() 函数显示您传给它的字符串,后跟一个冒号、一个空格和当前 errno 值的文本表示形式。
strerror() 返回一个指针,指针指向当前 errno 值的文本表示形式。
*/
#include <stdio.h>
#include <mem.h>
#include <errno.h>
int main() {
FILE *pf;
pf = fopen("un_exist.txt", "rb");
if (pf == NULL) {
//输出错误码,errno是全局的
fprintf(stderr, "Value of errno: %d\n", errno);
//标准错误输出,出错结果是Error printed by perror: No such file or directory,这是系统根据全局errno加上的
perror("Error printed by perror");
//strerror用于根据错误码获取信息
fprintf(stderr, "Error opening file: %s\n", strerror(errno));
} else {
fclose(pf);
}
return 0;
}
| 25.538462 | 89 | 0.551205 |
e30ba0364ba9bcdfcd769b1f94a82a8010d9879f | 4,846 | c | C | kernel-3.10/drivers/misc/mediatek/lcm/it6151_edp_dsi_video_sharp/it6151_i2c.c | zhengdejin/SC1_Code | dccccf55f2875fb64ec621f4356c625cd48bef7e | [
"Apache-2.0"
] | null | null | null | kernel-3.10/drivers/misc/mediatek/lcm/it6151_edp_dsi_video_sharp/it6151_i2c.c | zhengdejin/SC1_Code | dccccf55f2875fb64ec621f4356c625cd48bef7e | [
"Apache-2.0"
] | null | null | null | kernel-3.10/drivers/misc/mediatek/lcm/it6151_edp_dsi_video_sharp/it6151_i2c.c | zhengdejin/SC1_Code | dccccf55f2875fb64ec621f4356c625cd48bef7e | [
"Apache-2.0"
] | null | null | null | #ifndef BUILD_LK
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/miscdevice.h>
#include <asm/uaccess.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/workqueue.h>
#include <linux/kobject.h>
#include <linux/earlysuspend.h>
#include <linux/platform_device.h>
#include <asm/atomic.h>
#include <cust_acc.h>
#include <linux/hwmsensor.h>
#include <linux/hwmsen_dev.h>
#include <linux/sensors_io.h>
#include <linux/hwmsen_helper.h>
#include <mach/mt_typedefs.h>
#include <mach/mt_gpio.h>
#include <mach/mt_pm_ldo.h>
//#include "it6151_i2c.h"
//#include "cust_charging.h"
//#include <mach/charging.h>
/**********************************************************
*
* [I2C Slave Setting]
*
*********************************************************/
static DEFINE_MUTEX(it6151_i2c_access);
#define it6151_BUSNUM 2
#define DEVICE_NAME "it6151"
#define it6151_DEVICE_ID 0x5c
struct i2c_client *it6151_0;
struct i2c_client *it6151_1;
static const struct i2c_device_id it6151_id[] = {
{ "it6151_0", 0 },
{ "it6151_1", 0 }
};
static struct i2c_board_info it6151_i2c[] = {
{
.type = "it6151_0",
.addr = 0x5C,
},
{
.type = "it6151_1",
.addr = 0x6C,
}
};
// i2c_smbus_read_byte_data(sii902xA,RegOffset);
UINT8 it6151_reg_i2c_read (struct i2c_client *client,UINT8 RegOffset)
{
UINT8 Readnum;
Readnum = i2c_smbus_read_byte_data(client,RegOffset);
printk("[6151]client:%s , read RegOffset=0x%x,Readnum=0x%x \n", client->name, RegOffset, Readnum);
return Readnum;
}
UINT8 it6151_reg_i2c_read_byte(U8 dev_addr,U8 *cmdBuffer, U8 *dataBuffer)
{
UINT8 RetVal = 0xFF;
if(dev_addr == it6151_0->addr)
RetVal = it6151_reg_i2c_read(it6151_0, *cmdBuffer);
else if(dev_addr == it6151_1->addr)
RetVal = it6151_reg_i2c_read(it6151_1, *cmdBuffer);
else
printk("[it6151_reg_i2c_read_byte]error: no this dev_addr \n");
return RetVal;
}
void it6151_reg_i2c_write (struct i2c_client *client,UINT8 RegOffset, UINT8 Data)
{
i2c_smbus_write_byte_data(client, RegOffset, Data);
printk("[6151]client:%s , write RegOffset=0x%x,Data=0x%x \n", client->name, RegOffset, Data);
}
void it6151_reg_i2c_write_byte(U8 dev_addr,U8 cmd, U8 data)
{
U8 write_data[8];
write_data[0] = cmd;
write_data[1] = data;
if(dev_addr == 0x5C)
{
it6151_0->addr = 0x5C;
it6151_0->ext_flag = 0;
i2c_master_send(it6151_0, write_data, 2);
}
else if(dev_addr == 0x6C)
{
it6151_1->addr = 0x6C;
it6151_1->ext_flag = 0;
i2c_master_send(it6151_1, write_data, 2);
}
else
printk("[it6151_reg_i2c_read_byte]error: no this dev_addr \n");
}
static int match_id(const struct i2c_device_id *id, const struct i2c_client *client)
{
if (strcmp(client->name, id->name) == 0)
return true;
return false;
}
static int it6151_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret = 0;
int err=0;
if(match_id(&it6151_id[0], client))
{
if (!(it6151_0 = kmalloc(sizeof(struct i2c_client), GFP_KERNEL))) {
err = -ENOMEM;
goto exit;
}
memset(it6151_0, 0, sizeof(struct i2c_client));
it6151_0 = client;
dev_info(&client->adapter->dev, "attached it6151_0: %s "
"into i2c adapter successfully \n", id->name);
}
else if(match_id(&it6151_id[1], client))
{
if (!(it6151_1 = kmalloc(sizeof(struct i2c_client), GFP_KERNEL))) {
err = -ENOMEM;
goto exit;
}
memset(it6151_1, 0, sizeof(struct i2c_client));
it6151_1 = client;
dev_info(&client->adapter->dev, "attached it6151_1: %s "
"into i2c adapter successfully \n", id->name);
}
else
{
dev_err(&client->adapter->dev, "invalid i2c adapter: can not found dev_id matched\n");
return -EIO;
}
printk("[it6151_i2c_probe] Suss \n");
return ret;
exit:
return err;
}
static struct i2c_driver it6151_i2c_driver = {
.driver = {
.name = DEVICE_NAME,
},
.probe = it6151_i2c_probe,
.id_table = it6151_id,
};
static int __init it6151_i2c_init(void)
{
// int ret=0; //fixed for build warning
printk("[it6151_i2c_init] init start\n");
i2c_register_board_info(it6151_BUSNUM, it6151_i2c, 2);
if(i2c_add_driver(&it6151_i2c_driver)!=0)
{
printk("[it6151_i2c_init] failed to register it6151 i2c driver.\n");
}
else
{
printk("[it6151_i2c_init] Success to register it6151 i2c driver.\n");
}
return 0;
}
static void __exit it6151_i2c_exit(void)
{
i2c_del_driver(&it6151_i2c_driver);
}
module_init(it6151_i2c_init);
module_exit(it6151_i2c_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("I2C it6151 Driver");
MODULE_AUTHOR("jitao.shi<jitao.shi@mediatek.com>");
#endif
| 22.435185 | 99 | 0.65683 |
e341a460ee79cf87cf6a6123f053ae3d83e165bf | 2,447 | h | C | qqtw/qqheaders7.2/QQVipPicEditCanvasView.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 5 | 2018-02-20T14:24:17.000Z | 2020-08-06T09:31:21.000Z | qqtw/qqheaders7.2/QQVipPicEditCanvasView.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 1 | 2020-06-10T07:49:16.000Z | 2020-06-12T02:08:35.000Z | qqtw/qqheaders7.2/QQVipPicEditCanvasView.h | onezens/SmartQQ | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "UIView.h"
#import "CropViewDelegate.h"
@class CropView, NSMutableArray, NSString, QQVipPicEditTextBubbleLayer, UIImageView;
@interface QQVipPicEditCanvasView : UIView <CropViewDelegate>
{
NSMutableArray *_drawLayers;
_Bool _isCroping;
UIImageView *_sourceImageView;
QQVipPicEditTextBubbleLayer *_textBubbleLayer;
CropView *_cropView;
CDStruct_fc86e66d _operationRecorder;
struct CGRect _cropRect;
struct CGRect _scaleCropRect;
struct CGAffineTransform _originalTransform;
}
- (void).cxx_destruct;
- (void)addBubbleByKey:(id)arg1;
- (void)addDrawLayer:(id)arg1;
- (id)cropImage;
@property(nonatomic) struct CGRect cropRect; // @synthesize cropRect=_cropRect;
@property(retain, nonatomic) CropView *cropView; // @synthesize cropView=_cropView;
- (void)executeCropFrameCmdForState:(long long)arg1;
- (void)hideCropView:(_Bool)arg1;
- (id)initWithSourceImage:(id)arg1;
- (void)initializeDrawLayers;
@property(nonatomic) _Bool isCroping; // @synthesize isCroping=_isCroping;
- (void)layoutSubviews;
@property(nonatomic) CDStruct_fc86e66d operationRecorder; // @synthesize operationRecorder=_operationRecorder;
@property(nonatomic) struct CGAffineTransform originalTransform; // @synthesize originalTransform=_originalTransform;
- (_Bool)pointInside:(struct CGPoint)arg1 withEvent:(id)arg2;
- (void)recordForCropViewTouchBegan:(unsigned long long)arg1;
@property(nonatomic) struct CGRect scaleCropRect; // @synthesize scaleCropRect=_scaleCropRect;
- (void)setBubbleLayerActive:(_Bool)arg1;
- (void)setIsCropingByTempCmd:(_Bool)arg1;
@property(retain, nonatomic) UIImageView *sourceImageView; // @synthesize sourceImageView=_sourceImageView;
@property(retain, nonatomic) QQVipPicEditTextBubbleLayer *textBubbleLayer; // @synthesize textBubbleLayer=_textBubbleLayer;
- (id)sourceImage;
- (void)touchesBegan:(id)arg1 withEvent:(id)arg2;
- (void)touchesCancelled:(id)arg1 withEvent:(id)arg2;
- (void)touchesEnded:(id)arg1 withEvent:(id)arg2;
- (void)touchesMoved:(id)arg1 withEvent:(id)arg2;
- (struct CGAffineTransform)transformForCropRectFitCenter;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 39.467742 | 123 | 0.786678 |
3f865e8c36de0f7ef985bdcc3abb8f17d495e2d8 | 2,525 | h | C | third_party/blink/renderer/platform/wtf/scoped_logger.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | third_party/blink/renderer/platform/wtf/scoped_logger.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | third_party/blink/renderer/platform/wtf/scoped_logger.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_SCOPED_LOGGER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_SCOPED_LOGGER_H_
#include "base/dcheck_is_on.h"
#include "base/gtest_prod_util.h"
#include "base/logging.h"
#include "base/macros.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/wtf_export.h"
namespace WTF {
#if !DCHECK_IS_ON()
#define WTF_CREATE_SCOPED_LOGGER(...) ((void)0)
#define WTF_CREATE_SCOPED_LOGGER_IF(...) ((void)0)
#define WTF_APPEND_SCOPED_LOGGER(...) ((void)0)
#else
// ScopedLogger wraps log messages in parentheses, with indentation proportional
// to the number of instances. This makes it easy to see the flow of control in
// the output, particularly when instrumenting recursive functions.
//
// NOTE: This class is a debugging tool, not intended for use by checked-in
// code. Please do not remove it.
//
class WTF_EXPORT ScopedLogger {
DISALLOW_NEW();
public:
// The first message is passed to the constructor. Additional messages for
// the same scope can be added with log(). If condition is false, produce no
// output and do not create a scope.
PRINTF_FORMAT(3, 4) ScopedLogger(bool condition, const char* format, ...);
~ScopedLogger();
PRINTF_FORMAT(2, 3) void Log(const char* format, ...);
private:
FRIEND_TEST_ALL_PREFIXES(ScopedLoggerTest, ScopedLogger);
using PrintFunctionPtr = void (*)(const char* format, va_list args);
// Note: not thread safe.
static void SetPrintFuncForTests(PrintFunctionPtr);
void Init(const char* format, va_list args);
void WriteNewlineIfNeeded();
void Indent();
void Print(const char* format, ...);
void PrintIndent();
static ScopedLogger*& Current();
ScopedLogger* const parent_;
bool multiline_; // The ')' will go on the same line if there is only one
// entry.
static PrintFunctionPtr print_func_;
DISALLOW_COPY_AND_ASSIGN(ScopedLogger);
};
#define WTF_CREATE_SCOPED_LOGGER(name, ...) \
WTF::ScopedLogger name(true, __VA_ARGS__)
#define WTF_CREATE_SCOPED_LOGGER_IF(name, condition, ...) \
WTF::ScopedLogger name(condition, __VA_ARGS__)
#define WTF_APPEND_SCOPED_LOGGER(name, ...) (name.Log(__VA_ARGS__))
#endif // !DCHECK_IS_ON()
} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_SCOPED_LOGGER_H_
| 33.223684 | 80 | 0.750099 |
6a16d8943c9fa1565e4b58a297b7c81e6e405a6d | 2,284 | h | C | include/chartwork/Design.h | nazhor/chartwork | 20cb8df257bec39153ea408305640274c9e09d4c | [
"MIT"
] | 20 | 2018-08-29T07:33:21.000Z | 2022-03-12T05:05:54.000Z | include/chartwork/Design.h | nazhor/chartwork | 20cb8df257bec39153ea408305640274c9e09d4c | [
"MIT"
] | 1 | 2020-10-27T15:04:46.000Z | 2020-10-27T15:04:46.000Z | include/chartwork/Design.h | nazhor/chartwork | 20cb8df257bec39153ea408305640274c9e09d4c | [
"MIT"
] | 7 | 2015-07-09T20:38:28.000Z | 2021-09-27T06:38:11.000Z | #ifndef __DESIGN_H
#define __DESIGN_H
#include <QColor>
#include <QFont>
namespace chartwork
{
namespace design
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Design
//
////////////////////////////////////////////////////////////////////////////////////////////////////
const int keySpacing = 8;
const int keyItemSize = 16;
const int spacing = 16;
const int titleHeight = 24;
const int markWidth = 6;
const int axisSpacing = 8;
// Colors
const QColor darkergrey, darkergray = QColor(46, 52, 54);
const QColor darkgrey, darkgray = QColor(85, 87, 83);
const QColor grey, gray = QColor(136, 138, 133);
const QColor lightgrey, lightgray = QColor(186, 189, 182);
const QColor lightergrey, lightergray = QColor(211, 215, 207);
const QColor superlightgrey, superlightgray = QColor(238, 238, 236);
const QColor darkred = QColor(146, 0, 0);
const QColor red = QColor(204, 0, 0);
const QColor lightred = QColor(239, 41, 41);
const QColor darkbrown = QColor(143, 89, 2);
const QColor brown = QColor(193, 125, 17);
const QColor lightbrown = QColor(233, 185, 110);
const QColor darkpurple = QColor(92, 53, 102);
const QColor purple = QColor(117, 80, 123);
const QColor lightpurple = QColor(173, 127, 168);
const QColor darkblue = QColor(32, 74, 135);
const QColor blue = QColor(52, 101, 164);
const QColor lightblue = QColor(114, 159, 207);
const QColor darkorange = QColor(206, 92, 0);
const QColor orange = QColor(245, 121, 0);
const QColor lightorange = QColor(252, 175, 62);
const QColor darkgreen = QColor(78, 154, 6);
const QColor green = QColor(115, 210, 22);
const QColor lightgreen = QColor(138, 226, 52);
const QColor darkyellow = QColor(169, 160, 0);
const QColor yellow = QColor(237, 212, 0);
const QColor lightyellow = QColor(252, 233, 79);
inline QColor colorPalette(int index)
{
switch (index % 6)
{
default:
return blue;
case 1:
return orange;
case 2:
return green;
case 3:
return purple;
case 4:
return red;
case 5:
return yellow;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
#endif
| 26.55814 | 100 | 0.571366 |
ac170a61c7ebead8898d9f0ac556f54d6d0e6e6b | 664 | h | C | util.h | psforever/FLATool | 6db087cbfe78cc7368f94078ac82bbe0b603604b | [
"BSD-3-Clause"
] | 4 | 2016-07-02T00:12:36.000Z | 2020-08-02T01:42:20.000Z | util.h | psforever/FLATool | 6db087cbfe78cc7368f94078ac82bbe0b603604b | [
"BSD-3-Clause"
] | 1 | 2016-07-20T02:02:44.000Z | 2019-12-03T21:08:20.000Z | util.h | psforever/FLATool | 6db087cbfe78cc7368f94078ac82bbe0b603604b | [
"BSD-3-Clause"
] | 1 | 2019-09-20T23:18:21.000Z | 2019-09-20T23:18:21.000Z | #ifndef UTIL_H
#define UTIL_H
#include <stdbool.h>
#include <inttypes.h>
#include "compat.h"
void fatal(char * msg, ...);
char * basename(const char * path, bool extension);
char * string_cat(const char * l, const char * r);
char * get_extension(char * path);
int planetside_strcmp(const char * l, const char * r);
#define min(x, y) (((x) < (y)) ? (x) : (y))
#ifdef PLATFORM_WINDOWS
#ifdef PLATFORM_BITS_64
#define PRIuSZT "%lu"
#define PRIxSZT "%lx"
#else
#define PRIuSZT "%u"
#define PRIxSZT "%x"
#endif // PLATFORM_BITS_64
#elif defined(PLATFORM_UNIX)
#define PRIuSZT "%zu"
#define PRIxSZT "%zx"
#endif // PLATFORM_BITS_64
#endif // PLATFORM_WINDOWS
| 18.444444 | 54 | 0.689759 |
cdfc20960ecf1e92fd1050b5077a9fb194f91d09 | 32,223 | c | C | ext/allocation_tracer/allocation_tracer.c | ko1/allocation_tracer | f4ac1e8c15f827c293dc885cb0d52b89b3df7fe8 | [
"MIT"
] | 324 | 2015-01-05T17:55:55.000Z | 2022-02-22T07:41:03.000Z | ext/allocation_tracer/allocation_tracer.c | ko1/allocation_tracer | f4ac1e8c15f827c293dc885cb0d52b89b3df7fe8 | [
"MIT"
] | 9 | 2015-03-05T08:37:58.000Z | 2019-10-01T04:21:09.000Z | ext/allocation_tracer/allocation_tracer.c | ko1/allocation_tracer | f4ac1e8c15f827c293dc885cb0d52b89b3df7fe8 | [
"MIT"
] | 17 | 2015-03-04T21:59:17.000Z | 2020-07-20T10:11:51.000Z | /*
* allocation tracer: adds GC::Tracer::start_allocation_tracing
*
* By Koichi Sasada
* created at Thu Apr 17 03:50:38 2014.
*/
#include "ruby/ruby.h"
#include "ruby/debug.h"
#include <assert.h>
size_t rb_obj_memsize_of(VALUE obj); /* in gc.c */
static VALUE rb_mAllocationTracer;
struct traceobj_arg {
int running;
int keys, vals;
st_table *object_table; /* obj (VALUE) -> allocation_info */
st_table *str_table; /* cstr -> refcount */
st_table *aggregate_table; /* user defined key -> [count, total_age, max_age, min_age] */
struct allocation_info *freed_allocation_info;
/* */
size_t **lifetime_table;
size_t allocated_count_table[T_MASK];
size_t freed_count_table[T_MASK];
};
struct allocation_info {
struct allocation_info *next;
/* all of information don't need marking. */
int living;
VALUE flags;
VALUE klass;
size_t generation;
size_t memsize;
/* allocator info */
const char *path;
unsigned long line;
};
#define MAX_KEY_DATA 4
#define KEY_PATH (1<<1)
#define KEY_LINE (1<<2)
#define KEY_TYPE (1<<3)
#define KEY_CLASS (1<<4)
#define MAX_VAL_DATA 6
#define VAL_COUNT (1<<1)
#define VAL_OLDCOUNT (1<<2)
#define VAL_TOTAL_AGE (1<<3)
#define VAL_MIN_AGE (1<<4)
#define VAL_MAX_AGE (1<<5)
#define VAL_MEMSIZE (1<<6)
static char *
keep_unique_str(st_table *tbl, const char *str)
{
st_data_t n;
if (str && st_lookup(tbl, (st_data_t)str, &n)) {
char *result;
st_insert(tbl, (st_data_t)str, n+1);
st_get_key(tbl, (st_data_t)str, (st_data_t *)&result);
return result;
}
else {
return NULL;
}
}
static const char *
make_unique_str(st_table *tbl, const char *str, long len)
{
if (!str) {
return NULL;
}
else {
char *result;
if ((result = keep_unique_str(tbl, str)) == NULL) {
result = (char *)ruby_xmalloc(len+1);
strncpy(result, str, len);
result[len] = 0;
st_add_direct(tbl, (st_data_t)result, 1);
}
return result;
}
}
static void
delete_unique_str(st_table *tbl, const char *str)
{
if (str) {
st_data_t n;
if (st_lookup(tbl, (st_data_t)str, &n) == 0) rb_bug("delete_unique_str: unreachable");
if (n == 1) {
st_delete(tbl, (st_data_t *)&str, NULL);
ruby_xfree((char *)str);
}
else {
st_insert(tbl, (st_data_t)str, n-1);
}
}
}
struct memcmp_key_data {
int n;
st_data_t data[MAX_KEY_DATA];
};
static int
memcmp_hash_compare(st_data_t a, st_data_t b)
{
struct memcmp_key_data *k1 = (struct memcmp_key_data *)a;
struct memcmp_key_data *k2 = (struct memcmp_key_data *)b;
return memcmp(&k1->data[0], &k2->data[0], k1->n * sizeof(st_data_t));
}
static st_index_t
memcmp_hash_hash(st_data_t a)
{
struct memcmp_key_data *k = (struct memcmp_key_data *)a;
return rb_memhash(k->data, sizeof(st_data_t) * k->n);
}
static const struct st_hash_type memcmp_hash_type = {
memcmp_hash_compare, memcmp_hash_hash
};
static struct traceobj_arg *tmp_trace_arg; /* TODO: Do not use global variables */
static struct traceobj_arg *
get_traceobj_arg(void)
{
if (tmp_trace_arg == 0) {
tmp_trace_arg = ALLOC_N(struct traceobj_arg, 1);
MEMZERO(tmp_trace_arg, struct traceobj_arg, 1);
tmp_trace_arg->running = 0;
tmp_trace_arg->keys = 0;
tmp_trace_arg->vals = VAL_COUNT | VAL_OLDCOUNT | VAL_TOTAL_AGE | VAL_MAX_AGE | VAL_MIN_AGE | VAL_MEMSIZE;
tmp_trace_arg->aggregate_table = st_init_table(&memcmp_hash_type);
tmp_trace_arg->object_table = st_init_numtable();
tmp_trace_arg->str_table = st_init_strtable();
tmp_trace_arg->freed_allocation_info = NULL;
tmp_trace_arg->lifetime_table = NULL;
}
return tmp_trace_arg;
}
static int
free_keys_i(st_data_t key, st_data_t value, void *data)
{
ruby_xfree((void *)key);
return ST_CONTINUE;
}
static int
free_values_i(st_data_t key, st_data_t value, void *data)
{
ruby_xfree((void *)value);
return ST_CONTINUE;
}
static int
free_key_values_i(st_data_t key, st_data_t value, void *data)
{
ruby_xfree((void *)key);
ruby_xfree((void *)value);
return ST_CONTINUE;
}
static void
delete_lifetime_table(struct traceobj_arg *arg)
{
int i;
if (arg->lifetime_table) {
for (i=0; i<T_MASK; i++) {
free(arg->lifetime_table[i]);
}
free(arg->lifetime_table);
arg->lifetime_table = NULL;
}
}
static void
clear_traceobj_arg(void)
{
struct traceobj_arg * arg = get_traceobj_arg();
st_foreach(arg->aggregate_table, free_key_values_i, 0);
st_clear(arg->aggregate_table);
st_foreach(arg->object_table, free_values_i, 0);
st_clear(arg->object_table);
st_foreach(arg->str_table, free_keys_i, 0);
st_clear(arg->str_table);
arg->freed_allocation_info = NULL;
delete_lifetime_table(arg);
}
static struct allocation_info *
create_allocation_info(void)
{
return (struct allocation_info *)ruby_xmalloc(sizeof(struct allocation_info));
}
static void
free_allocation_info(struct traceobj_arg *arg, struct allocation_info *info)
{
delete_unique_str(arg->str_table, info->path);
ruby_xfree(info);
}
static void
newobj_i(VALUE tpval, void *data)
{
struct traceobj_arg *arg = (struct traceobj_arg *)data;
struct allocation_info *info;
rb_trace_arg_t *tparg = rb_tracearg_from_tracepoint(tpval);
VALUE obj = rb_tracearg_object(tparg);
VALUE path = rb_tracearg_path(tparg);
VALUE line = rb_tracearg_lineno(tparg);
VALUE klass = Qnil;
switch(BUILTIN_TYPE(obj)) {
case T_NODE:
case T_IMEMO:
break;
default:
klass = RBASIC_CLASS(obj);
}
const char *path_cstr = RTEST(path) ? make_unique_str(arg->str_table, RSTRING_PTR(path), RSTRING_LEN(path)) : NULL;
if (st_lookup(arg->object_table, (st_data_t)obj, (st_data_t *)&info)) {
if (info->living) {
/* do nothing. there is possibility to keep living if FREEOBJ events while suppressing tracing */
}
/* reuse info */
delete_unique_str(arg->str_table, info->path);
}
else {
info = create_allocation_info();
}
info->next = NULL;
info->flags = RBASIC(obj)->flags;
info->living = 1;
info->memsize = 0;
info->klass = (RTEST(klass) && !RB_TYPE_P(obj, T_NODE)) ? rb_class_real(klass) : Qnil;
info->generation = rb_gc_count();
info->path = path_cstr;
info->line = NUM2INT(line);
st_insert(arg->object_table, (st_data_t)obj, (st_data_t)info);
arg->allocated_count_table[BUILTIN_TYPE(obj)]++;
}
/* file, line, type, klass */
#define MAX_KEY_SIZE 4
static void
aggregate_each_info(struct traceobj_arg *arg, struct allocation_info *info, size_t gc_count)
{
st_data_t key, val;
struct memcmp_key_data key_data;
size_t *val_buff;
size_t age = (int)(gc_count - info->generation);
int i = 0;
if (arg->keys & KEY_PATH) {
key_data.data[i++] = (st_data_t)info->path;
}
if (arg->keys & KEY_LINE) {
key_data.data[i++] = (st_data_t)info->line;
}
if (arg->keys & KEY_TYPE) {
key_data.data[i++] = (st_data_t)(info->flags & T_MASK);
}
if (arg->keys & KEY_CLASS) {
key_data.data[i++] = info->klass;
}
key_data.n = i;
key = (st_data_t)&key_data;
if (st_lookup(arg->aggregate_table, key, &val) == 0) {
struct memcmp_key_data *key_buff = ruby_xmalloc(sizeof(struct memcmp_key_data));
key_buff->n = key_data.n;
for (i=0; i<key_data.n; i++) {
key_buff->data[i] = key_data.data[i];
}
key = (st_data_t)key_buff;
/* count, old count, total age, max age, min age */
val_buff = ALLOC_N(size_t, 6);
val_buff[0] = val_buff[1] = val_buff[2] = 0;
val_buff[3] = val_buff[4] = age;
val_buff[5] = 0;
if (arg->keys & KEY_PATH) keep_unique_str(arg->str_table, info->path);
st_insert(arg->aggregate_table, (st_data_t)key_buff, (st_data_t)val_buff);
}
else {
val_buff = (size_t *)val;
}
val_buff[0] += 1;
#ifdef FL_PROMOTED
if (info->flags & FL_PROMOTED) val_buff[1] += 1;
#elif defined(FL_PROMOTED0) && defined(FL_PROMOTED1)
if (info->flags & FL_PROMOTED0 &&
info->flags & FL_PROMOTED1) val_buff[1] += 1;
#endif
val_buff[2] += age;
if (val_buff[3] > age) val_buff[3] = age; /* min */
if (val_buff[4] < age) val_buff[4] = age; /* max */
val_buff[5] += info->memsize;
}
static void
aggregate_freed_info(void *data)
{
size_t gc_count = rb_gc_count();
struct traceobj_arg *arg = (struct traceobj_arg *)data;
struct allocation_info *info = arg->freed_allocation_info;
arg->freed_allocation_info = NULL;
if (arg->running) {
while (info) {
struct allocation_info *next_info = info->next;
aggregate_each_info(arg, info, gc_count);
free_allocation_info(arg, info);
info = next_info;
}
}
}
static void
move_to_freed_list(struct traceobj_arg *arg, VALUE obj, struct allocation_info *info)
{
if (arg->freed_allocation_info == NULL) {
rb_postponed_job_register_one(0, aggregate_freed_info, arg);
}
info->next = arg->freed_allocation_info;
arg->freed_allocation_info = info;
st_delete(arg->object_table, (st_data_t *)&obj, (st_data_t *)&info);
}
static void
add_lifetime_table(size_t **lines, int type, struct allocation_info *info)
{
size_t age = rb_gc_count() - info->generation;
size_t *line = lines[type];
size_t len, i;
if (line == NULL) {
len = age + 1;
line = lines[type] = calloc(1 + len, sizeof(size_t));
assert(line != NULL);
line[0] = len;
}
else {
len = line[0];
if (len < age + 1) {
size_t old_len = len;
len = age + 1;
line = lines[type] = realloc(line, sizeof(size_t) * (1 + len));
assert(line != NULL);
for (i=old_len; i<len; i++) {
line[i+1] = 0;
}
line[0] = len;
}
}
line[1 + age]++;
}
static void
freeobj_i(VALUE tpval, void *data)
{
struct traceobj_arg *arg = (struct traceobj_arg *)data;
rb_trace_arg_t *tparg = rb_tracearg_from_tracepoint(tpval);
VALUE obj = rb_tracearg_object(tparg);
struct allocation_info *info;
if (st_lookup(arg->object_table, (st_data_t)obj, (st_data_t *)&info)) {
info->flags = RBASIC(obj)->flags;
info->memsize = rb_obj_memsize_of(obj);
move_to_freed_list(arg, obj, info);
if (arg->lifetime_table) {
add_lifetime_table(arg->lifetime_table, BUILTIN_TYPE(obj), info);
}
}
arg->freed_count_table[BUILTIN_TYPE(obj)]++;
}
static void
check_tracer_running(void)
{
struct traceobj_arg * arg = get_traceobj_arg();
if (!arg->running) {
rb_raise(rb_eRuntimeError, "not started yet");
}
}
static void
enable_newobj_hook(void)
{
VALUE newobj_hook;
check_tracer_running();
if (!rb_ivar_defined(rb_mAllocationTracer, rb_intern("newobj_hook"))) {
rb_raise(rb_eRuntimeError, "not started.");
}
newobj_hook = rb_ivar_get(rb_mAllocationTracer, rb_intern("newobj_hook"));
if (rb_tracepoint_enabled_p(newobj_hook)) {
rb_raise(rb_eRuntimeError, "newobj hooks is already enabled.");
}
rb_tracepoint_enable(newobj_hook);
}
static void
disable_newobj_hook(void)
{
VALUE newobj_hook;
check_tracer_running();
if ((!rb_ivar_defined(rb_mAllocationTracer, rb_intern("newobj_hook"))) || ((newobj_hook = rb_ivar_get(rb_mAllocationTracer, rb_intern("newobj_hook"))) == Qnil)) {
rb_raise(rb_eRuntimeError, "not started.");
}
if (rb_tracepoint_enabled_p(newobj_hook) == Qfalse) {
rb_raise(rb_eRuntimeError, "newobj hooks is already disabled.");
}
rb_tracepoint_disable(newobj_hook);
}
static void
start_alloc_hooks(VALUE mod)
{
VALUE newobj_hook, freeobj_hook;
struct traceobj_arg *arg = get_traceobj_arg();
if (!rb_ivar_defined(rb_mAllocationTracer, rb_intern("newobj_hook"))) {
rb_ivar_set(rb_mAllocationTracer, rb_intern("newobj_hook"), newobj_hook = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_NEWOBJ, newobj_i, arg));
rb_ivar_set(rb_mAllocationTracer, rb_intern("freeobj_hook"), freeobj_hook = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_FREEOBJ, freeobj_i, arg));
}
else {
newobj_hook = rb_ivar_get(rb_mAllocationTracer, rb_intern("newobj_hook"));
freeobj_hook = rb_ivar_get(rb_mAllocationTracer, rb_intern("freeobj_hook"));
}
rb_tracepoint_enable(newobj_hook);
rb_tracepoint_enable(freeobj_hook);
}
static VALUE
stop_alloc_hooks(VALUE self)
{
struct traceobj_arg * arg = get_traceobj_arg();
check_tracer_running();
{
VALUE newobj_hook = rb_ivar_get(rb_mAllocationTracer, rb_intern("newobj_hook"));
VALUE freeobj_hook = rb_ivar_get(rb_mAllocationTracer, rb_intern("freeobj_hook"));
rb_tracepoint_disable(newobj_hook);
rb_tracepoint_disable(freeobj_hook);
clear_traceobj_arg();
arg->running = 0;
}
return Qnil;
}
static VALUE
type_sym(int type)
{
static VALUE syms[T_MASK] = {0};
if (syms[0] == 0) {
int i;
for (i=0; i<T_MASK; i++) {
switch (i) {
#define TYPE_NAME(t) case (t): syms[i] = ID2SYM(rb_intern(#t)); break;
TYPE_NAME(T_NONE);
TYPE_NAME(T_OBJECT);
TYPE_NAME(T_CLASS);
TYPE_NAME(T_MODULE);
TYPE_NAME(T_FLOAT);
TYPE_NAME(T_STRING);
TYPE_NAME(T_REGEXP);
TYPE_NAME(T_ARRAY);
TYPE_NAME(T_HASH);
TYPE_NAME(T_STRUCT);
TYPE_NAME(T_BIGNUM);
TYPE_NAME(T_FILE);
TYPE_NAME(T_MATCH);
TYPE_NAME(T_COMPLEX);
TYPE_NAME(T_RATIONAL);
TYPE_NAME(T_NIL);
TYPE_NAME(T_TRUE);
TYPE_NAME(T_FALSE);
TYPE_NAME(T_SYMBOL);
TYPE_NAME(T_FIXNUM);
TYPE_NAME(T_UNDEF);
#ifdef T_IMEMO /* introduced from Rub 2.3 */
TYPE_NAME(T_IMEMO);
#endif
TYPE_NAME(T_NODE);
TYPE_NAME(T_ICLASS);
TYPE_NAME(T_ZOMBIE);
TYPE_NAME(T_DATA);
default:
syms[i] = ID2SYM(rb_intern("unknown"));
break;
#undef TYPE_NAME
}
}
}
return syms[type];
}
struct arg_and_result {
int update;
struct traceobj_arg *arg;
VALUE result;
};
static int
aggregate_result_i(st_data_t key, st_data_t val, void *data)
{
struct arg_and_result *aar = (struct arg_and_result *)data;
struct traceobj_arg *arg = aar->arg;
VALUE result = aar->result;
size_t *val_buff = (size_t *)val;
struct memcmp_key_data *key_buff = (struct memcmp_key_data *)key;
VALUE v, oldv, k = rb_ary_new();
int i = 0;
i = 0;
if (arg->keys & KEY_PATH) {
const char *path = (const char *)key_buff->data[i++];
if (path) {
rb_ary_push(k, rb_str_new2(path));
}
else {
rb_ary_push(k, Qnil);
}
}
if (arg->keys & KEY_LINE) {
rb_ary_push(k, INT2FIX((int)key_buff->data[i++]));
}
if (arg->keys & KEY_TYPE) {
int sym_index = key_buff->data[i++];
rb_ary_push(k, type_sym(sym_index));
}
if (arg->keys & KEY_CLASS) {
VALUE klass = key_buff->data[i++];
if (RTEST(klass) && BUILTIN_TYPE(klass) == T_CLASS) {
klass = rb_class_real(klass);
rb_ary_push(k, klass);
/* TODO: actually, it is dangerous code because klass can be sweeped */
/* So that class specifier is hidden feature */
}
else {
rb_ary_push(k, Qnil);
}
}
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
if (aar->update && (oldv = rb_hash_aref(result, k)) != Qnil) {
v = rb_ary_new3(6,
INT2FIX(val_buff[0] + (size_t)FIX2INT(RARRAY_AREF(oldv, 0))), /* count */
INT2FIX(val_buff[1] + (size_t)FIX2INT(RARRAY_AREF(oldv, 1))), /* old count */
INT2FIX(val_buff[2] + (size_t)FIX2INT(RARRAY_AREF(oldv, 2))), /* total_age */
INT2FIX(MIN(val_buff[3], (size_t)FIX2INT(RARRAY_AREF(oldv, 3)))), /* min age */
INT2FIX(MAX(val_buff[4], (size_t)FIX2INT(RARRAY_AREF(oldv, 4)))), /* max age */
INT2FIX(val_buff[5] + (size_t)FIX2INT(RARRAY_AREF(oldv, 5)))); /* memsize_of */
}
else {
v = rb_ary_new3(6,
INT2FIX(val_buff[0]), INT2FIX(val_buff[1]),
INT2FIX(val_buff[2]), INT2FIX(val_buff[3]),
INT2FIX(val_buff[4]), INT2FIX(val_buff[5]));
}
rb_hash_aset(result, k, v);
return ST_CONTINUE;
}
static int
aggregate_live_object_i(st_data_t key, st_data_t val, void *data)
{
VALUE obj = (VALUE)key;
struct allocation_info *info = (struct allocation_info *)val;
size_t gc_count = rb_gc_count();
struct traceobj_arg *arg = (struct traceobj_arg *)data;
if (BUILTIN_TYPE(obj) == (info->flags & T_MASK)) {
VALUE klass = RBASIC_CLASS(obj);
info->flags = RBASIC(obj)->flags;
info->klass = (RTEST(klass) && !RB_TYPE_P(obj, T_NODE)) ? rb_class_real(klass) : Qnil;
}
aggregate_each_info(arg, info, gc_count);
return ST_CONTINUE;
}
static int
lifetime_table_for_live_objects_i(st_data_t key, st_data_t val, st_data_t data)
{
struct allocation_info *info = (struct allocation_info *)val;
VALUE h = (VALUE)data;
int type = info->flags & T_MASK;
VALUE sym = type_sym(type);
size_t age = rb_gc_count() - info->generation;
VALUE line;
size_t count, i;
if ((line = rb_hash_aref(h, sym)) == Qnil) {
line = rb_ary_new();
rb_hash_aset(h, sym, line);
}
for (i=RARRAY_LEN(line); i<age+1; i++) {
rb_ary_push(line, INT2FIX(0));
}
count = NUM2SIZET(RARRAY_AREF(line, age));
RARRAY_ASET(line, age, SIZET2NUM(count + 1));
return ST_CONTINUE;
}
static VALUE
aggregate_result(struct traceobj_arg *arg)
{
struct arg_and_result aar;
aar.result = rb_hash_new();
aar.arg = arg;
while (arg->freed_allocation_info) {
aggregate_freed_info(arg);
}
/* collect from recent-freed objects */
aar.update = 0;
st_foreach(arg->aggregate_table, aggregate_result_i, (st_data_t)&aar);
{
st_table *dead_object_aggregate_table = arg->aggregate_table;
/* make live object aggregate table */
arg->aggregate_table = st_init_table(&memcmp_hash_type);
st_foreach(arg->object_table, aggregate_live_object_i, (st_data_t)arg);
/* aggregate table -> Ruby hash */
aar.update = 1;
st_foreach(arg->aggregate_table, aggregate_result_i, (st_data_t)&aar);
/* remove live object aggregate table */
st_foreach(arg->aggregate_table, free_key_values_i, 0);
st_free_table(arg->aggregate_table);
arg->aggregate_table = dead_object_aggregate_table;
}
/* lifetime table */
if (arg->lifetime_table) {
VALUE h = rb_hash_new();
int i;
rb_ivar_set(rb_mAllocationTracer, rb_intern("lifetime_table"), h);
for (i=0; i<T_MASK; i++) {
size_t *line = arg->lifetime_table[i];
if (line) {
size_t len = line[0], j;
VALUE ary = rb_ary_new();
VALUE sym = type_sym(i);
rb_hash_aset(h, sym, ary);
for (j=0; j<len; j++) {
rb_ary_push(ary, SIZET2NUM(line[j+1]));
}
}
}
st_foreach(arg->object_table, lifetime_table_for_live_objects_i, (st_data_t)h);
}
return aar.result;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.result -> hash
*
* Returns the current allocated results
*
* If you need to know the results of allocation tracing
* without pausing or stopping tracing you can use this method.
*
* Example:
*
* require 'allocation_tracer'
*
* ObjectSpace::AllocationTracer.trace do
* 3.times do |i|
* a = "#{i}"
* puts ObjectSpace::AllocationTracer.result
* end
* end
*
* # => {["scratch.rb", 5]=>[2, 0, 0, 0, 0, 0]}
* # => {["scratch.rb", 5]=>[4, 0, 0, 0, 0, 0], ["scratch.rb", 6]=>[16, 0, 0, 0, 0, 0]}
* # => {["scratch.rb", 5]=>[6, 0, 0, 0, 0, 0], ["scratch.rb", 6]=>[38, 0, 0, 0, 0, 0]}
*
*/
static VALUE
allocation_tracer_result(VALUE self)
{
VALUE result;
struct traceobj_arg *arg = get_traceobj_arg();
disable_newobj_hook();
result = aggregate_result(arg);
enable_newobj_hook();
return result;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.clear -> NilClass
*
* Clears the current allocated results
*
* If you need to clear the results of allocation tracing
* without stopping tracing you can use this method.
*
*/
static VALUE
allocation_tracer_clear(VALUE self)
{
clear_traceobj_arg();
return Qnil;
}
/*! Used in allocation_tracer_trace
* to ensure that a result is returned.
*/
static VALUE
allocation_tracer_trace_i(VALUE self)
{
rb_yield(Qnil);
return allocation_tracer_result(self);
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.trace { |a, b| block } -> array
* ObjectSpace::AllocationTracer.start -> NilClass
*
* Traces object allocations inside of the block
*
* Objects created inside of the block will be tracked by the tracer.
* If the method is called without a block, the tracer will start
* and continue until ObjectSpace::AllocationTracer.stop is called.
*
* Output can be customized with ObjectSpace::AllocationTracer.setup.
*
* Example:
*
* pp ObjectSpace::AllocationTracer.trace{
* 50_000.times{|i|
* i.to_s
* i.to_s
* i.to_s
* }
* }
*
* # => {["test.rb", 6]=>[50000, 0, 47440, 0, 1, 0],
* ["test.rb", 7]=>[50000, 4, 47452, 0, 6, 0],
* ["test.rb", 8]=>[50000, 7, 47456, 0, 6, 0]}
*
*/
static VALUE
allocation_tracer_trace(VALUE self)
{
struct traceobj_arg * arg = get_traceobj_arg();
if (arg->running) {
rb_raise(rb_eRuntimeError, "can't run recursivly");
}
else {
arg->running = 1;
if (arg->keys == 0) arg->keys = KEY_PATH | KEY_LINE;
start_alloc_hooks(rb_mAllocationTracer);
if (rb_block_given_p()) {
return rb_ensure(allocation_tracer_trace_i, self, stop_alloc_hooks, Qnil);
}
}
return Qnil;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.stop -> array
*
* Stops allocation tracing if currently running
*
* When allocation tracing is started via ObjectSpace::AllocationTracer.start
* it will continue until this method is called.
*
* Example:
* pp ObjectSpace::AllocationTracer.stop
*
* # => {["test.rb", 6]=>[50000, 0, 47440, 0, 1, 0],
* ["test.rb", 7]=>[50000, 4, 47452, 0, 6, 0],
* ["test.rb", 8]=>[50000, 7, 47456, 0, 6, 0]}
*
*/
static VALUE
allocation_tracer_stop(VALUE self)
{
VALUE result;
disable_newobj_hook();
result = aggregate_result(get_traceobj_arg());
stop_alloc_hooks(self);
return result;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.pause -> NilClass
*
* Pauses allocation tracing
*
* Use in conjunction with ObjectSpace::AllocationTracer.start and
* ObjectSpace::AllocationTracer.stop.
*
*/
static VALUE
allocation_tracer_pause(VALUE self)
{
disable_newobj_hook();
return Qnil;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.resume -> NilClass
*
* Resumes allocation tracing if previously paused
*
* See ObjectSpace::AllocationTracer.pause to pause allocation tracing.
*
*/
static VALUE
allocation_tracer_resume(VALUE self)
{
enable_newobj_hook();
return Qnil;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.setup([symbol]) -> NilClass
*
* Change the format that results will be returned.
*
* Takes an array of symbols containing the order you would like the output
* to be returned. Valid options:
*
* - :path
* - :line
* - :type
* - :class
*
* Example:
*
* ObjectSpace::AllocationTracer.setup(%i{path line type})
*
* result = ObjectSpace::AllocationTracer.trace do
* 50_000.times{|i|
* a = [i.to_s]
* b = {i.to_s => nil}
* c = (i.to_s .. i.to_s)
* }
* end
*
* pp result
*
* # => {["test.rb", 8, :T_STRING]=>[50000, 15, 49165, 0, 16, 0],
* ["test.rb", 8, :T_ARRAY]=>[50000, 12, 49134, 0, 16, 0],
* ["test.rb", 9, :T_STRING]=>[100000, 27, 98263, 0, 16, 0],
* ["test.rb", 9, :T_HASH]=>[50000, 16, 49147, 0, 16, 8998848],
* ["test.rb", 10, :T_STRING]=>[100000, 36, 98322, 0, 16, 0],
* ["test.rb", 10, :T_STRUCT]=>[50000, 16, 49147, 0, 16, 0]}
*
*/
static VALUE
allocation_tracer_setup(int argc, VALUE *argv, VALUE self)
{
struct traceobj_arg * arg = get_traceobj_arg();
if (arg->running) {
rb_raise(rb_eRuntimeError, "can't change configuration during running");
}
else {
if (argc >= 1) {
int i;
VALUE ary = rb_check_array_type(argv[0]);
arg->keys = 0;
for (i=0; i<(int)RARRAY_LEN(ary); i++) {
if (RARRAY_AREF(ary, i) == ID2SYM(rb_intern("path"))) arg->keys |= KEY_PATH;
else if (RARRAY_AREF(ary, i) == ID2SYM(rb_intern("line"))) arg->keys |= KEY_LINE;
else if (RARRAY_AREF(ary, i) == ID2SYM(rb_intern("type"))) arg->keys |= KEY_TYPE;
else if (RARRAY_AREF(ary, i) == ID2SYM(rb_intern("class"))) arg->keys |= KEY_CLASS;
else {
rb_raise(rb_eArgError, "not supported key type");
}
}
}
}
if (argc == 0) {
arg->keys = KEY_PATH | KEY_LINE;
}
return Qnil;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.header -> array
*
* Return headers
*
* Example:
*
* puts ObjectSpace::AllocationTracer.header
* => [:path, :line, :count, :old_count, :total_age, :min_age, :max_age, :total_memsize]
*
*/
VALUE
allocation_tracer_header(VALUE self)
{
VALUE ary = rb_ary_new();
struct traceobj_arg * arg = get_traceobj_arg();
if (arg->keys & KEY_PATH) rb_ary_push(ary, ID2SYM(rb_intern("path")));
if (arg->keys & KEY_LINE) rb_ary_push(ary, ID2SYM(rb_intern("line")));
if (arg->keys & KEY_TYPE) rb_ary_push(ary, ID2SYM(rb_intern("type")));
if (arg->keys & KEY_CLASS) rb_ary_push(ary, ID2SYM(rb_intern("class")));
if (arg->vals & VAL_COUNT) rb_ary_push(ary, ID2SYM(rb_intern("count")));
if (arg->vals & VAL_OLDCOUNT) rb_ary_push(ary, ID2SYM(rb_intern("old_count")));
if (arg->vals & VAL_TOTAL_AGE) rb_ary_push(ary, ID2SYM(rb_intern("total_age")));
if (arg->vals & VAL_MIN_AGE) rb_ary_push(ary, ID2SYM(rb_intern("min_age")));
if (arg->vals & VAL_MAX_AGE) rb_ary_push(ary, ID2SYM(rb_intern("max_age")));
if (arg->vals & VAL_MEMSIZE) rb_ary_push(ary, ID2SYM(rb_intern("total_memsize")));
return ary;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.lifetime_table_setup(true) -> NilClass
*
* Enables tracing for the generation of objects
*
* See ObjectSpace::AllocationTracer.lifetime_table for an example.
*/
static VALUE
allocation_tracer_lifetime_table_setup(VALUE self, VALUE set)
{
struct traceobj_arg * arg = get_traceobj_arg();
if (arg->running) {
rb_raise(rb_eRuntimeError, "can't change configuration during running");
}
if (RTEST(set)) {
if (arg->lifetime_table == NULL) {
arg->lifetime_table = (size_t **)calloc(T_MASK, sizeof(size_t **));
}
}
else {
delete_lifetime_table(arg);
}
return Qnil;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.lifetime_table -> hash
*
* Returns generations for objects
*
* Count is for both living (retained) and dead (freed) objects.
*
* The key is the type of objects, for example `T_OBJECT` for Ruby objects
* or `T_STRING` for Ruby strings.
*
* The value is an array containing a count of the objects, the index is
* the generation.
*
* Example:
*
* require 'pp'
* require 'allocation_tracer'
*
* ObjectSpace::AllocationTracer.lifetime_table_setup true
* result = ObjectSpace::AllocationTracer.trace do
* 100000.times{
* Object.new
* ''
* }
* end
* pp ObjectSpace::AllocationTracer.lifetime_table
* # => {:T_OBJECT=>[3434, 96563, 0, 0, 1, 0, 0, 2],
* :T_STRING=>[3435, 96556, 2, 1, 1, 1, 1, 1, 2]}
*/
static VALUE
allocation_tracer_lifetime_table(VALUE self)
{
VALUE result = rb_ivar_get(rb_mAllocationTracer, rb_intern("lifetime_table"));
rb_ivar_set(rb_mAllocationTracer, rb_intern("lifetime_table"), Qnil);
return result;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.allocated_count_table -> hash
*
* Returns allocation count totals for Ruby object types
*
* Returns a hash showing the number of each type of object that has been allocated.
*
* Example:
*
* require 'allocation_tracer'
*
* ObjectSpace::AllocationTracer.trace do
* 1000.times {
* ["foo", {}]
* }
* end
* p allocated: ObjectSpace::AllocationTracer.allocated_count_table
* {:allocated=>{:T_NONE=>0, :T_OBJECT=>0, :T_CLASS=>0, :T_MODULE=>0, :T_FLOAT=>0, :T_STRING=>1000, :T_REGEXP=>0, :T_ARRAY=>1000, :T_HASH=>1000, :T_STRUCT=>0, :T_BIGNUM=>0, :T_FILE=>0, :T_DATA=>0, :T_MATCH=>0, :T_COMPLEX=>0, :T_RATIONAL=>0, :unknown=>0, :T_NIL=>0, :T_TRUE=>0, :T_FALSE=>0, :T_SYMBOL=>0, :T_FIXNUM=>0, :T_UNDEF=>0, :T_NODE=>0, :T_ICLASS=>0, :T_ZOMBIE=>0}}
*
* p freed: ObjectSpace::AllocationTracer.freed_count_table
* {:freed=>{:T_NONE=>0, :T_OBJECT=>0, :T_CLASS=>0, :T_MODULE=>0, :T_FLOAT=>0, :T_STRING=>1871, :T_REGEXP=>41, :T_ARRAY=>226, :T_HASH=>7, :T_STRUCT=>41, :T_BIGNUM=>0, :T_FILE=>50, :T_DATA=>25, :T_MATCH=>47, :T_COMPLEX=>0, :T_RATIONAL=>0, :unknown=>0, :T_NIL=>0, :T_TRUE=>0, :T_FALSE=>0, :T_SYMBOL=>0, :T_FIXNUM=>0, :T_UNDEF=>0, :T_NODE=>932, :T_ICLASS=>0, :T_ZOMBIE=>0}}
*/
static VALUE
allocation_tracer_allocated_count_table(VALUE self)
{
struct traceobj_arg * arg = get_traceobj_arg();
VALUE h = rb_hash_new();
int i;
for (i=0; i<T_MASK; i++) {
rb_hash_aset(h, type_sym(i), SIZET2NUM(arg->allocated_count_table[i]));
}
return h;
}
/*
*
* call-seq:
* ObjectSpace::AllocationTracer.freed_count_table -> hash
*
* Returns freed count totals for Ruby object types
*
* Returns a hash showing the number of each type of object that has been freed.
*
* See ObjectSpace::AllocationTracer.allocated_count_table for example usage
*
*/
static VALUE
allocation_tracer_freed_count_table(VALUE self)
{
struct traceobj_arg * arg = get_traceobj_arg();
VALUE h = rb_hash_new();
int i;
for (i=0; i<T_MASK; i++) {
rb_hash_aset(h, type_sym(i), SIZET2NUM(arg->freed_count_table[i]));
}
return h;
}
void
Init_allocation_tracer(void)
{
VALUE rb_mObjSpace = rb_const_get(rb_cObject, rb_intern("ObjectSpace"));
VALUE mod = rb_mAllocationTracer = rb_define_module_under(rb_mObjSpace, "AllocationTracer");
/* allocation tracer methods */
rb_define_module_function(mod, "trace", allocation_tracer_trace, 0);
rb_define_module_function(mod, "start", allocation_tracer_trace, 0);
rb_define_module_function(mod, "stop", allocation_tracer_stop, 0);
rb_define_module_function(mod, "pause", allocation_tracer_pause, 0);
rb_define_module_function(mod, "resume", allocation_tracer_resume, 0);
rb_define_module_function(mod, "result", allocation_tracer_result, 0);
rb_define_module_function(mod, "clear", allocation_tracer_clear, 0);
rb_define_module_function(mod, "setup", allocation_tracer_setup, -1);
rb_define_module_function(mod, "header", allocation_tracer_header, 0);
rb_define_module_function(mod, "lifetime_table_setup", allocation_tracer_lifetime_table_setup, 1);
rb_define_module_function(mod, "lifetime_table", allocation_tracer_lifetime_table, 0);
rb_define_module_function(mod, "allocated_count_table", allocation_tracer_allocated_count_table, 0);
rb_define_module_function(mod, "freed_count_table", allocation_tracer_freed_count_table, 0);
}
| 27.494027 | 376 | 0.637433 |
6db9e600f9b7bef7d20de06ae221f3b09756f7ee | 66 | c | C | benchmarks/Angha_small/extr_sign_xmain/extr_sign_xmain.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | 2 | 2021-03-11T00:46:25.000Z | 2021-07-08T16:44:58.000Z | benchmarks/Angha_small/extr_sign_xmain/extr_sign_xmain.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | null | null | null | benchmarks/Angha_small/extr_sign_xmain/extr_sign_xmain.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | null | null | null | a;
b() {
char c[a];
for (;;) {
c[3] ^= 5;
d(c);
}
}
| 7.333333 | 14 | 0.242424 |
ed2123b356855797761fd0a2bb64d59fe4b9926e | 1,114 | h | C | lib/Secrets/healthcheckrequest_p.h | inzanity/sailfish-secrets | aecaf06f6766029b97d47c1c74bdf7e2ccba5bfe | [
"BSD-3-Clause"
] | 27 | 2017-11-02T11:18:47.000Z | 2021-06-29T10:40:34.000Z | lib/Secrets/healthcheckrequest_p.h | inzanity/sailfish-secrets | aecaf06f6766029b97d47c1c74bdf7e2ccba5bfe | [
"BSD-3-Clause"
] | 149 | 2017-11-09T09:31:52.000Z | 2021-12-24T09:27:19.000Z | lib/Secrets/healthcheckrequest_p.h | inzanity/sailfish-secrets | aecaf06f6766029b97d47c1c74bdf7e2ccba5bfe | [
"BSD-3-Clause"
] | 16 | 2017-11-09T08:23:22.000Z | 2021-06-18T06:15:48.000Z | /*
* Copyright (C) 2018 Jolla Ltd.
* Contact: Timur Kristóf <timur.kristof@jollamobile.com>
* All rights reserved.
* BSD 3-Clause License, see LICENSE.
*/
#ifndef LIBSAILFISHSECRETS_HEALTHCHECKREQUEST_P_H
#define LIBSAILFISHSECRETS_HEALTHCHECKREQUEST_P_H
#include "Secrets/secretsglobal.h"
#include "Secrets/secretmanager.h"
#include "Secrets/secret.h"
#include "Secrets/healthcheckrequest.h"
#include <QtCore/QPointer>
#include <QtCore/QScopedPointer>
#include <QtCore/QString>
#include <QtDBus/QDBusPendingCallWatcher>
namespace Sailfish {
namespace Secrets {
class HealthCheckRequestPrivate
{
Q_DISABLE_COPY(HealthCheckRequestPrivate)
public:
explicit HealthCheckRequestPrivate();
QScopedPointer<QDBusPendingCallWatcher> m_watcher;
Sailfish::Secrets::Request::Status m_status;
Sailfish::Secrets::Result m_result;
QPointer<Sailfish::Secrets::SecretManager> m_manager;
HealthCheckRequest::Health m_saltDataHealth;
HealthCheckRequest::Health m_masterlockHealth;
};
} // namespace Secrets
} // namespace Sailfish
#endif // LIBSAILFISHSECRETS_HEALTHCHECKREQUEST_P_H
| 23.702128 | 57 | 0.787253 |
4bcee625744c5dfd0b049da729e7f28422698c3b | 1,266 | h | C | Kusbegi_Inc/Kusbegi_FC_Main/kusbegi_fc_main.h | canpinaremre/Kusbegi_FC_Firmware | 755877f006168e73b618a22daa0ba3954d74ff86 | [
"MIT"
] | null | null | null | Kusbegi_Inc/Kusbegi_FC_Main/kusbegi_fc_main.h | canpinaremre/Kusbegi_FC_Firmware | 755877f006168e73b618a22daa0ba3954d74ff86 | [
"MIT"
] | null | null | null | Kusbegi_Inc/Kusbegi_FC_Main/kusbegi_fc_main.h | canpinaremre/Kusbegi_FC_Firmware | 755877f006168e73b618a22daa0ba3954d74ff86 | [
"MIT"
] | null | null | null | /*
* Kusbegi Flight Controller Main
*
* Yazar: İsmail Emre CANPINAR
* @canpinaremre
*
* Açıklama: Uçuş kontrol kartının üzerinde çalışan fonksiyonların
* FreeRTOS üzerinde çağırılmasını ve zamanlamalarını kontrol eder.
*
*
*/
#include <Kusbegi_Inc/kusbegi.h>
#include <Kusbegi_Inc/kusbegi_fc_parameters.h>
#include <Kusbegi_Inc/Kusbegi_Filter_And_Fusion/kusbegi_filter_and_fusion.h>
#include <Kusbegi_Inc/Kusbegi_IMU/nxp_imu.h>
#include <Kusbegi_Inc/Kusbegi_RC/kusbegi_rc.h>
#include <Kusbegi_Inc/Kusbegi_SBUS/kusbegi_sbus.h>
#include <Kusbegi_Inc/Kusbegi_PID/kusbegi_pid.h>
#include "stm32f4xx_hal.h"
#ifndef __KUSBEGI_FC_MAIN_H__
#define __KUSBEGI_FC_MAIN_H__
void KUSBEGI_FC_InitKUSBEGI(UART_HandleTypeDef *Telemetry, I2C_HandleTypeDef *IMU,
UART_HandleTypeDef *SBUS, UART_HandleTypeDef *GPS);
void KUSBEGI_FC_UpdateIMU();
void KUSBEGI_FC_UpdateBarometer();
void KUSBEGI_FC_UpdatePID();
void KUSBEGI_FC_UpdateReceiver();
void KUSBEGI_FC_UpdateTelemetry();
void KUSBEGI_FC_UpdateLogger();
void KUSBEGI_FC_UpdateMotorPWM();
void KUSBEGI_FC_UpdateOffBoard();
void KUSBEGI_FC_UpdateFlightMode();
void KUSBEGI_FC_UpdateFlightTask();
void KUSBEGI_FC_UpdateLEDs();
void KUSBEGI_FC_UpdatePositionEstimation();
#endif /* __KUSBEGI_FC_MAIN_H__ */
| 24.823529 | 82 | 0.817536 |
4bf27bb9f4c48f458461f8b99c758f5cbeff0c74 | 777 | h | C | Applications/Podcasts/UIView-MTRTL.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | 4 | 2019-08-27T18:03:47.000Z | 2021-09-18T06:29:00.000Z | Applications/Podcasts/UIView-MTRTL.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | Applications/Podcasts/UIView-MTRTL.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "UIView.h"
@interface UIView (MTRTL)
- (id)mt_shouldRTLMirrorStackDepth; // IMP=0x0000000100184dec
- (void)mt_setShouldRTLMirrorStackDepth:(id)arg1; // IMP=0x0000000100184ddc
@property(nonatomic, getter=mt_enableAutomaticRTLMirroringForSubviews, setter=mt_setEnableAutomaticRTLMirroringForSubviews:) _Bool mt_enableAutomaticRTLMirroringForSubviews;
@property(nonatomic, getter=mt_isExcludedFromAutomaticRTLMirroring, setter=mt_setExcludedFromAutomaticRTLMirroring:) _Bool mt_excludedFromAutomaticRTLMirroring;
- (void)mt_RTLMirrorIfNeeded; // IMP=0x0000000100184914
- (void)mt_setShouldRTLMirror; // IMP=0x0000000100184860
@end
| 43.166667 | 173 | 0.813385 |
8fca6fe9dee02db8d6187c06280cdb8700bc1eb1 | 2,858 | h | C | 3rdparty/fake_boost/type/typetools.h | chencang1980/mockcpp | 45660e7bcf0a6cf8edce3c6a736e4b168acc016e | [
"Apache-2.0"
] | 30 | 2015-04-16T02:42:36.000Z | 2022-03-19T02:53:43.000Z | 3rdparty/fake_boost/type/typetools.h | chencang1980/mockcpp | 45660e7bcf0a6cf8edce3c6a736e4b168acc016e | [
"Apache-2.0"
] | 21 | 2021-03-17T06:41:56.000Z | 2022-02-01T12:27:28.000Z | 3rdparty/fake_boost/type/typetools.h | chencang1980/mockcpp | 45660e7bcf0a6cf8edce3c6a736e4b168acc016e | [
"Apache-2.0"
] | 23 | 2015-04-16T02:44:30.000Z | 2021-12-21T09:50:24.000Z | /*
The NeonX Library
Copyright (c) 2013 darkcat
Code covered by the MIT License
*/
#pragma once
// nx...
#include "config/general.h"
//////////////////////////////////////////////////////////////////////////
NX_BEG namespace type {
//////////////////////////////////////////////////////////////////////////
/*
define null & empty type
*/
struct null_t;
struct empty_t {};
/*
define none type and none
*/
typedef int empty_t::*none_t;
none_t const none = (static_cast<none_t>(0));
/*
for type to another type
*/
template <typename T>
struct Type
{
typedef T ret;
};
template <typename R, typename T>
struct Proxy : R
{};
/*
yes_t and not_t
*/
typedef char not_t;
typedef class { not_t dummy_[2]; } yes_t;
#define nx_is_yes(...) (sizeof(__VA_ARGS__) == sizeof(nx::type::yes_t))
/*
true_t and false_t
*/
#define NX_PROPERTY(T, name, ...) \
static const T name = (__VA_ARGS__)
#define NX_VALUE(T, ...) \
NX_PROPERTY(T, val, __VA_ARGS__)
template <typename T, T Val_>
struct Def
{
NX_VALUE(T, Val_);
};
typedef Def<bool, true> true_t;
typedef Def<bool, false> false_t;
#define nx_value(...) (__VA_ARGS__::val)
#define nx_bool(...) (bool)nx_value(__VA_ARGS__)
/*
int to type
*/
template <int Val_>
struct Int : Def<int, Val_>
{};
/*
Base class for judge
*/
template <bool>
struct Judge;
template <>
struct Judge<true> : true_t
{};
template <>
struct Judge<false> : false_t
{};
/*
type logical operators
*/
template <typename T>
struct NOT : Judge<!nx_bool(T)>
{};
#define nx_not(...) nx::type::NOT<__VA_ARGS__>::ret
template <typename T, typename U>
struct AND : Judge<nx_bool(T) && nx_bool(U)>
{};
#define nx_and(...) nx::type::AND<__VA_ARGS__>::ret
template <typename T, typename U>
struct OR : Judge<nx_bool(T) || nx_bool(U)>
{};
#define nx_or(...) nx::type::OR<__VA_ARGS__>::ret
template <typename T, typename U>
struct XOR : Judge<nx_bool(T) ^ nx_bool(U)>
{};
#define nx_xor(...) nx::type::XOR<__VA_ARGS__>::ret
/*
type select
*/
template <bool flag, typename T, typename U>
struct Select
{
typedef T ret;
};
template <typename T, typename U>
struct Select<false, T, U>
{
typedef U ret;
};
#define nx_select(...) nx::type::Select<__VA_ARGS__>::ret
/*
Shield to protect the parameters are not destroyed by macro expansion
*/
template <typename T> struct Strip { typedef T ret; };
template <typename T> struct Strip<void(T)> { typedef T ret; };
#define NX_SHIELD(...) nx::type::Strip<void(__VA_ARGS__)>::ret
//////////////////////////////////////////////////////////////////////////
} NX_END
//////////////////////////////////////////////////////////////////////////
| 18.088608 | 75 | 0.547586 |
7231b62a08b6c4dd9a9188b13b8a491cf209ed1c | 31,593 | c | C | usr/src/lib/pkcs11/pkcs11_kernel/common/kernelUtil.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/lib/pkcs11/pkcs11_kernel/common/kernelUtil.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/lib/pkcs11/pkcs11_kernel/common/kernelUtil.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018, Joyent, Inc.
*/
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <cryptoutil.h>
#include <errno.h>
#include <security/cryptoki.h>
#include <sys/crypto/common.h>
#include <sys/crypto/ioctl.h>
#include "kernelGlobal.h"
#include "kernelObject.h"
#include "kernelSlot.h"
#define ENCODE_ATTR(type, value, len) { \
cur_attr->oa_type = type; \
(void) memcpy(ptr, value, len); \
cur_attr->oa_value = ptr; \
cur_attr->oa_value_len = len; \
cur_attr++; \
}
#define MECH_HASH(type) (((uintptr_t)type) % KMECH_HASHTABLE_SIZE)
/*
* Serialize writes to the hash table. We don't need a per bucket lock as
* there are only a few writes and we don't need the lock for reads.
*/
pthread_mutex_t mechhash_mutex = PTHREAD_MUTEX_INITIALIZER;
static CK_RV
kmech_hash_insert(CK_MECHANISM_TYPE type, crypto_mech_type_t kmech)
{
uint_t h;
kmh_elem_t *elem, *cur;
elem = malloc(sizeof (kmh_elem_t));
if (elem == NULL)
return (CKR_HOST_MEMORY);
h = MECH_HASH(type);
elem->type = type;
elem->kmech = kmech;
(void) pthread_mutex_lock(&mechhash_mutex);
for (cur = kernel_mechhash[h]; cur != NULL; cur = cur->knext) {
if (type == cur->type) {
/* Some other thread beat us to it. */
(void) pthread_mutex_unlock(&mechhash_mutex);
free(elem);
return (CKR_OK);
}
}
elem->knext = kernel_mechhash[h];
kernel_mechhash[h] = elem;
(void) pthread_mutex_unlock(&mechhash_mutex);
return (CKR_OK);
}
CK_RV
kernel_mech(CK_MECHANISM_TYPE type, crypto_mech_type_t *k_number)
{
crypto_get_mechanism_number_t get_number;
const char *string;
CK_RV rv;
int r;
kmh_elem_t *elem;
uint_t h;
char buf[11]; /* Num chars for representing ulong in ASCII */
/*
* Search for an existing entry. No need to lock since we are
* just a reader and we never free the entries in the hash table.
*/
h = MECH_HASH(type);
for (elem = kernel_mechhash[h]; elem != NULL; elem = elem->knext) {
if (type == elem->type) {
*k_number = elem->kmech;
return (CKR_OK);
}
}
if (type >= CKM_VENDOR_DEFINED) {
(void) snprintf(buf, sizeof (buf), "%#lx", type);
string = buf;
} else {
string = pkcs11_mech2str(type);
}
if (string == NULL)
return (CKR_MECHANISM_INVALID);
get_number.pn_mechanism_string = (char *)string;
get_number.pn_mechanism_len = strlen(string) + 1;
while ((r = ioctl(kernel_fd, CRYPTO_GET_MECHANISM_NUMBER,
&get_number)) < 0) {
if (errno != EINTR)
break;
}
if (r < 0) {
rv = CKR_MECHANISM_INVALID;
} else {
if (get_number.pn_return_value != CRYPTO_SUCCESS) {
rv = crypto2pkcs11_error_number(
get_number.pn_return_value);
} else {
rv = CKR_OK;
}
}
if (rv == CKR_OK) {
*k_number = get_number.pn_internal_number;
/* Add this to the hash table */
(void) kmech_hash_insert(type, *k_number);
}
return (rv);
}
/*
* Return the value of a secret key object.
* This routine allocates memory for the value.
* A null pointer is returned on error.
*/
unsigned char *
get_symmetric_key_value(kernel_object_t *key_p)
{
uint8_t *cipherKey;
switch (key_p->class) {
case CKO_SECRET_KEY:
cipherKey = malloc(OBJ_SEC(key_p)->sk_value_len);
if (cipherKey == NULL)
return (NULL);
(void) memcpy(cipherKey, OBJ_SEC(key_p)->sk_value,
OBJ_SEC(key_p)->sk_value_len);
return (cipherKey);
default:
return (NULL);
}
}
/*
* Convert a RSA private key object into a crypto_key structure.
* Memory is allocated for each attribute stored in the crypto_key
* structure. Memory for the crypto_key structure is not
* allocated. Attributes can be freed by free_key_attributes().
*/
CK_RV
get_rsa_private_key(kernel_object_t *object_p, crypto_key_t *key)
{
biginteger_t *big;
crypto_object_attribute_t *attrs, *cur_attr;
char *ptr;
CK_RV rv;
(void) pthread_mutex_lock(&object_p->object_mutex);
if (object_p->key_type != CKK_RSA ||
object_p->class != CKO_PRIVATE_KEY) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_ATTRIBUTE_TYPE_INVALID);
}
attrs = calloc(1,
RSA_PRI_ATTR_COUNT * sizeof (crypto_object_attribute_t));
if (attrs == NULL) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_HOST_MEMORY);
}
key->ck_format = CRYPTO_KEY_ATTR_LIST;
key->ck_attrs = attrs;
cur_attr = attrs;
/*
* Allocate memory for each key attribute and set up the value
* value length.
*/
key->ck_count = 0;
/* CKA_MODULUS is required. */
big = OBJ_PRI_RSA_MOD(object_p);
if (big->big_value == NULL) {
rv = CKR_ATTRIBUTE_TYPE_INVALID;
goto fail_cleanup;
} else {
if ((ptr = malloc(big->big_value_len)) == NULL) {
rv = CKR_HOST_MEMORY;
goto fail_cleanup;
}
ENCODE_ATTR(CKA_MODULUS, big->big_value, big->big_value_len);
key->ck_count++;
}
/* CKA_PRIVATE_EXPONENT is required. */
big = OBJ_PRI_RSA_PRIEXPO(object_p);
if (big->big_value == NULL) {
rv = CKR_ATTRIBUTE_TYPE_INVALID;
goto fail_cleanup;
} else {
if ((ptr = malloc(big->big_value_len)) == NULL) {
rv = CKR_HOST_MEMORY;
goto fail_cleanup;
}
ENCODE_ATTR(CKA_PRIVATE_EXPONENT, big->big_value,
big->big_value_len);
key->ck_count++;
}
/* CKA_PRIME_1 is optional. */
big = OBJ_PRI_RSA_PRIME1(object_p);
if (big->big_value != NULL) {
if ((ptr = malloc(big->big_value_len)) == NULL) {
rv = CKR_HOST_MEMORY;
goto fail_cleanup;
}
ENCODE_ATTR(CKA_PRIME_1, big->big_value, big->big_value_len);
key->ck_count++;
}
/* CKA_PRIME_2 is optional. */
big = OBJ_PRI_RSA_PRIME2(object_p);
if (big->big_value != NULL) {
if ((ptr = malloc(big->big_value_len)) == NULL) {
rv = CKR_HOST_MEMORY;
goto fail_cleanup;
}
ENCODE_ATTR(CKA_PRIME_2, big->big_value, big->big_value_len);
key->ck_count++;
}
/* CKA_EXPONENT_1 is optional. */
big = OBJ_PRI_RSA_EXPO1(object_p);
if (big->big_value != NULL) {
if ((ptr = malloc(big->big_value_len)) == NULL) {
rv = CKR_HOST_MEMORY;
goto fail_cleanup;
}
ENCODE_ATTR(CKA_EXPONENT_1, big->big_value,
big->big_value_len);
key->ck_count++;
}
/* CKA_EXPONENT_2 is optional. */
big = OBJ_PRI_RSA_EXPO2(object_p);
if (big->big_value != NULL) {
if ((ptr = malloc(big->big_value_len)) == NULL) {
rv = CKR_HOST_MEMORY;
goto fail_cleanup;
}
ENCODE_ATTR(CKA_EXPONENT_2, big->big_value,
big->big_value_len);
key->ck_count++;
}
/* CKA_COEFFICIENT is optional. */
big = OBJ_PRI_RSA_COEF(object_p);
if (big->big_value != NULL) {
if ((ptr = malloc(big->big_value_len)) == NULL) {
rv = CKR_HOST_MEMORY;
goto fail_cleanup;
}
ENCODE_ATTR(CKA_COEFFICIENT, big->big_value,
big->big_value_len);
key->ck_count++;
}
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_OK);
fail_cleanup:
(void) pthread_mutex_unlock(&object_p->object_mutex);
free_key_attributes(key);
return (rv);
}
/*
* Convert a RSA public key object into a crypto_key structure.
* Memory is allocated for each attribute stored in the crypto_key
* structure. Memory for the crypto_key structure is not
* allocated. Attributes can be freed by free_key_attributes().
*/
CK_RV
get_rsa_public_key(kernel_object_t *object_p, crypto_key_t *key)
{
biginteger_t *big;
crypto_object_attribute_t *attrs, *cur_attr;
char *ptr;
(void) pthread_mutex_lock(&object_p->object_mutex);
if (object_p->key_type != CKK_RSA ||
object_p->class != CKO_PUBLIC_KEY) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_ATTRIBUTE_TYPE_INVALID);
}
attrs = calloc(1,
RSA_PUB_ATTR_COUNT * sizeof (crypto_object_attribute_t));
if (attrs == NULL) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_HOST_MEMORY);
}
key->ck_format = CRYPTO_KEY_ATTR_LIST;
key->ck_count = RSA_PUB_ATTR_COUNT;
key->ck_attrs = attrs;
cur_attr = attrs;
big = OBJ_PUB_RSA_PUBEXPO(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_PUBLIC_EXPONENT, big->big_value, big->big_value_len);
big = OBJ_PUB_RSA_MOD(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_MODULUS, big->big_value, big->big_value_len);
if ((ptr = malloc(sizeof (CK_ULONG))) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_MODULUS_BITS, &OBJ_PUB_RSA_MOD_BITS(object_p),
sizeof (CK_ULONG));
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_OK);
mem_failure:
(void) pthread_mutex_unlock(&object_p->object_mutex);
free_key_attributes(key);
return (CKR_HOST_MEMORY);
}
/*
* Free attribute storage in a crypto_key structure.
*/
void
free_key_attributes(crypto_key_t *key)
{
int i;
if (key->ck_format == CRYPTO_KEY_ATTR_LIST &&
(key->ck_count > 0) && key->ck_attrs != NULL) {
for (i = 0; i < key->ck_count; i++) {
freezero(key->ck_attrs[i].oa_value,
key->ck_attrs[i].oa_value_len);
}
free(key->ck_attrs);
}
}
/*
* Convert a DSA private key object into a crypto_key structure.
* Memory is allocated for each attribute stored in the crypto_key
* structure. Memory for the crypto_key structure is not
* allocated. Attributes can be freed by free_dsa_key_attributes().
*/
CK_RV
get_dsa_private_key(kernel_object_t *object_p, crypto_key_t *key)
{
biginteger_t *big;
crypto_object_attribute_t *attrs, *cur_attr;
char *ptr;
(void) pthread_mutex_lock(&object_p->object_mutex);
if (object_p->key_type != CKK_DSA ||
object_p->class != CKO_PRIVATE_KEY) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_ATTRIBUTE_TYPE_INVALID);
}
attrs = calloc(1,
DSA_ATTR_COUNT * sizeof (crypto_object_attribute_t));
if (attrs == NULL) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_HOST_MEMORY);
}
key->ck_format = CRYPTO_KEY_ATTR_LIST;
key->ck_count = DSA_ATTR_COUNT;
key->ck_attrs = attrs;
cur_attr = attrs;
big = OBJ_PRI_DSA_PRIME(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_PRIME, big->big_value, big->big_value_len);
big = OBJ_PRI_DSA_SUBPRIME(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_SUBPRIME, big->big_value, big->big_value_len);
big = OBJ_PRI_DSA_BASE(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_BASE, big->big_value, big->big_value_len);
big = OBJ_PRI_DSA_VALUE(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_VALUE, big->big_value, big->big_value_len);
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_OK);
mem_failure:
(void) pthread_mutex_unlock(&object_p->object_mutex);
free_key_attributes(key);
return (CKR_HOST_MEMORY);
}
/*
* Convert a DSA public key object into a crypto_key structure.
* Memory is allocated for each attribute stored in the crypto_key
* structure. Memory for the crypto_key structure is not
* allocated. Attributes can be freed by free_dsa_key_attributes().
*/
CK_RV
get_dsa_public_key(kernel_object_t *object_p, crypto_key_t *key)
{
biginteger_t *big;
crypto_object_attribute_t *attrs, *cur_attr;
char *ptr;
(void) pthread_mutex_lock(&object_p->object_mutex);
if (object_p->key_type != CKK_DSA ||
object_p->class != CKO_PUBLIC_KEY) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_ATTRIBUTE_TYPE_INVALID);
}
attrs = calloc(1,
DSA_ATTR_COUNT * sizeof (crypto_object_attribute_t));
if (attrs == NULL) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_HOST_MEMORY);
}
key->ck_format = CRYPTO_KEY_ATTR_LIST;
key->ck_count = DSA_ATTR_COUNT;
key->ck_attrs = attrs;
cur_attr = attrs;
big = OBJ_PUB_DSA_PRIME(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_PRIME, big->big_value, big->big_value_len);
big = OBJ_PUB_DSA_SUBPRIME(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_SUBPRIME, big->big_value, big->big_value_len);
big = OBJ_PUB_DSA_BASE(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_BASE, big->big_value, big->big_value_len);
big = OBJ_PUB_DSA_VALUE(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL)
goto mem_failure;
ENCODE_ATTR(CKA_VALUE, big->big_value, big->big_value_len);
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_OK);
mem_failure:
(void) pthread_mutex_unlock(&object_p->object_mutex);
free_key_attributes(key);
return (CKR_HOST_MEMORY);
}
/*
* Convert a EC private key object into a crypto_key structure.
* Memory is allocated for each attribute stored in the crypto_key
* structure. Memory for the crypto_key structure is not
* allocated. Attributes can be freed by free_ec_key_attributes().
*/
CK_RV
get_ec_private_key(kernel_object_t *object_p, crypto_key_t *key)
{
biginteger_t *big;
crypto_object_attribute_t *attrs, *cur_attr;
CK_ATTRIBUTE tmp;
char *ptr;
int rv;
(void) pthread_mutex_lock(&object_p->object_mutex);
if (object_p->key_type != CKK_EC ||
object_p->class != CKO_PRIVATE_KEY) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_ATTRIBUTE_TYPE_INVALID);
}
attrs = calloc(EC_ATTR_COUNT, sizeof (crypto_object_attribute_t));
if (attrs == NULL) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_HOST_MEMORY);
}
key->ck_format = CRYPTO_KEY_ATTR_LIST;
key->ck_count = EC_ATTR_COUNT;
key->ck_attrs = attrs;
cur_attr = attrs;
big = OBJ_PRI_EC_VALUE(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL) {
rv = CKR_HOST_MEMORY;
goto fail;
}
ENCODE_ATTR(CKA_VALUE, big->big_value, big->big_value_len);
tmp.type = CKA_EC_PARAMS;
tmp.pValue = NULL;
rv = kernel_get_attribute(object_p, &tmp);
if (rv != CKR_OK) {
goto fail;
}
tmp.pValue = malloc(tmp.ulValueLen);
if (tmp.pValue == NULL) {
rv = CKR_HOST_MEMORY;
goto fail;
}
rv = kernel_get_attribute(object_p, &tmp);
if (rv != CKR_OK) {
free(tmp.pValue);
goto fail;
}
cur_attr->oa_type = tmp.type;
cur_attr->oa_value = tmp.pValue;
cur_attr->oa_value_len = tmp.ulValueLen;
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_OK);
fail:
(void) pthread_mutex_unlock(&object_p->object_mutex);
free_key_attributes(key);
return (rv);
}
/*
* Convert an EC public key object into a crypto_key structure.
* Memory is allocated for each attribute stored in the crypto_key
* structure. Memory for the crypto_key structure is not
* allocated. Attributes can be freed by free_ec_key_attributes().
*/
CK_RV
get_ec_public_key(kernel_object_t *object_p, crypto_key_t *key)
{
biginteger_t *big;
crypto_object_attribute_t *attrs, *cur_attr;
CK_ATTRIBUTE tmp;
char *ptr;
int rv;
(void) pthread_mutex_lock(&object_p->object_mutex);
if (object_p->key_type != CKK_EC ||
object_p->class != CKO_PUBLIC_KEY) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_ATTRIBUTE_TYPE_INVALID);
}
attrs = calloc(EC_ATTR_COUNT, sizeof (crypto_object_attribute_t));
if (attrs == NULL) {
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_HOST_MEMORY);
}
key->ck_format = CRYPTO_KEY_ATTR_LIST;
key->ck_count = EC_ATTR_COUNT;
key->ck_attrs = attrs;
cur_attr = attrs;
big = OBJ_PUB_EC_POINT(object_p);
if ((ptr = malloc(big->big_value_len)) == NULL) {
rv = CKR_HOST_MEMORY;
goto fail;
}
ENCODE_ATTR(CKA_EC_POINT, big->big_value, big->big_value_len);
tmp.type = CKA_EC_PARAMS;
tmp.pValue = NULL;
rv = kernel_get_attribute(object_p, &tmp);
if (rv != CKR_OK) {
goto fail;
}
tmp.pValue = malloc(tmp.ulValueLen);
if (tmp.pValue == NULL) {
rv = CKR_HOST_MEMORY;
goto fail;
}
rv = kernel_get_attribute(object_p, &tmp);
if (rv != CKR_OK) {
free(tmp.pValue);
goto fail;
}
cur_attr->oa_type = tmp.type;
cur_attr->oa_value = tmp.pValue;
cur_attr->oa_value_len = tmp.ulValueLen;
(void) pthread_mutex_unlock(&object_p->object_mutex);
return (CKR_OK);
fail:
(void) pthread_mutex_unlock(&object_p->object_mutex);
free_key_attributes(key);
return (rv);
}
/*
* Convert an attribute template into an obj_attrs array.
* Memory is allocated for each attribute stored in the obj_attrs.
* The memory can be freed by free_object_attributes().
*
* If the boolean pointer is_token_obj is not NULL, the caller wants to
* retrieve the value of the CKA_TOKEN attribute if it is specified in the
* template.
* - When this routine is called thru C_CreateObject(), C_CopyObject(), or
* any key management function, is_token_obj should NOT be NULL.
* - When this routine is called thru C_GetAttributeValue() or
* C_SetAttributeValue(), "is_token_obj" should be NULL.
*/
CK_RV
process_object_attributes(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
caddr_t *obj_attrs, CK_BBOOL *is_token_obj)
{
crypto_object_attribute_t *attrs, *cur_attr;
int i, cur_i;
char *ptr;
CK_RV rv;
ssize_t value_len;
if (ulCount == 0) {
obj_attrs = NULL;
return (CKR_OK);
}
attrs = calloc(1, ulCount * sizeof (crypto_object_attribute_t));
if (attrs == NULL) {
return (CKR_HOST_MEMORY);
}
cur_attr = attrs;
for (i = 0; i < ulCount; i++) {
/*
* The length of long attributes must be set correctly
* so providers can determine whether they came from 32
* or 64-bit applications.
*/
switch (pTemplate[i].type) {
case CKA_CLASS:
case CKA_CERTIFICATE_TYPE:
case CKA_KEY_TYPE:
case CKA_MODULUS_BITS:
case CKA_HW_FEATURE_TYPE:
value_len = sizeof (ulong_t);
if (pTemplate[i].pValue != NULL &&
(pTemplate[i].ulValueLen < value_len)) {
rv = CKR_ATTRIBUTE_VALUE_INVALID;
cur_i = i;
goto fail_cleanup;
}
break;
default:
value_len = pTemplate[i].ulValueLen;
}
cur_attr->oa_type = pTemplate[i].type;
cur_attr->oa_value_len = value_len;
cur_attr->oa_value = NULL;
if ((pTemplate[i].pValue != NULL) &&
(pTemplate[i].ulValueLen > 0)) {
ptr = malloc(pTemplate[i].ulValueLen);
if (ptr == NULL) {
rv = CKR_HOST_MEMORY;
cur_i = i;
goto fail_cleanup;
} else {
(void) memcpy(ptr, pTemplate[i].pValue,
pTemplate[i].ulValueLen);
cur_attr->oa_value = ptr;
}
}
if ((is_token_obj != NULL) &&
(pTemplate[i].type == CKA_TOKEN)) {
/* Get the CKA_TOKEN attribute value. */
if (pTemplate[i].pValue == NULL) {
rv = CKR_ATTRIBUTE_VALUE_INVALID;
cur_i = i;
goto fail_cleanup;
} else {
*is_token_obj =
*(CK_BBOOL *)pTemplate[i].pValue;
}
}
cur_attr++;
}
*obj_attrs = (char *)attrs;
return (CKR_OK);
fail_cleanup:
cur_attr = attrs;
for (i = 0; i < cur_i; i++) {
if (cur_attr->oa_value != NULL) {
(void) free(cur_attr->oa_value);
}
cur_attr++;
}
(void) free(attrs);
return (rv);
}
/*
* Copy the attribute values from obj_attrs to pTemplate.
* The obj_attrs is an image of the Template and is expected to have the
* same attributes in the same order and each one of the attribute pValue
* in obj_attr has enough space allocated for the corresponding valueLen
* in pTemplate.
*/
CK_RV
get_object_attributes(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
caddr_t obj_attrs)
{
crypto_object_attribute_t *cur_attr;
CK_RV rv = CKR_OK;
int i;
/* LINTED */
cur_attr = (crypto_object_attribute_t *)obj_attrs;
for (i = 0; i < ulCount; i++) {
if (pTemplate[i].type != cur_attr->oa_type) {
/* The attribute type doesn't match, this is bad. */
rv = CKR_FUNCTION_FAILED;
return (rv);
}
pTemplate[i].ulValueLen = cur_attr->oa_value_len;
if ((pTemplate[i].pValue != NULL) &&
((CK_LONG)pTemplate[i].ulValueLen != -1)) {
(void) memcpy(pTemplate[i].pValue, cur_attr->oa_value,
pTemplate[i].ulValueLen);
}
cur_attr++;
}
return (rv);
}
/*
* Free the attribute storage in a crypto_object_attribute_t structure.
*/
void
free_object_attributes(caddr_t obj_attrs, CK_ULONG ulCount)
{
crypto_object_attribute_t *cur_attr;
int i;
if ((ulCount == 0) || (obj_attrs == NULL)) {
return;
}
/* LINTED */
cur_attr = (crypto_object_attribute_t *)obj_attrs;
for (i = 0; i < ulCount; i++) {
/* XXX check that oa_value > 0 */
if (cur_attr->oa_value != NULL) {
free(cur_attr->oa_value);
}
cur_attr++;
}
free(obj_attrs);
}
/*
* This function is called by process_found_objects(). It will check the
* CKA_PRIVATE and CKA_TOKEN attributes for the kernel object "oid", then
* initialize all the necessary fields in the object wrapper "objp".
*/
static CK_RV
create_new_tobj_in_lib(kernel_slot_t *pslot, kernel_session_t *sp,
kernel_object_t *objp, crypto_object_id_t oid)
{
CK_RV rv = CKR_OK;
crypto_object_get_attribute_value_t obj_ga;
boolean_t is_pri_obj;
boolean_t is_token_obj;
CK_BBOOL pri_value, token_value;
CK_ATTRIBUTE pTemplate[2];
int r;
/*
* Make a CRYPTO_OBJECT_GET_ATTRIBUTE_VALUE ioctl call to get this
* kernel object's attribute values for CKA_PRIVATE and CKA_TOKEN.
*/
obj_ga.og_session = sp->k_session;
obj_ga.og_handle = oid;
obj_ga.og_count = 2;
pTemplate[0].type = CKA_PRIVATE;
pTemplate[0].pValue = &pri_value;
pTemplate[0].ulValueLen = sizeof (pri_value);
pTemplate[1].type = CKA_TOKEN;
pTemplate[1].pValue = &token_value;
pTemplate[1].ulValueLen = sizeof (token_value);
rv = process_object_attributes(pTemplate, 2, &obj_ga.og_attributes,
NULL);
if (rv != CKR_OK) {
return (rv);
}
while ((r = ioctl(kernel_fd, CRYPTO_OBJECT_GET_ATTRIBUTE_VALUE,
&obj_ga)) < 0) {
if (errno != EINTR)
break;
}
if (r < 0) {
rv = CKR_FUNCTION_FAILED;
} else {
rv = crypto2pkcs11_error_number(obj_ga.og_return_value);
}
if (rv == CKR_OK) {
rv = get_object_attributes(pTemplate, 2, obj_ga.og_attributes);
if (rv == CKR_OK) {
is_pri_obj = *(CK_BBOOL *)pTemplate[0].pValue;
is_token_obj = *(CK_BBOOL *)pTemplate[1].pValue;
}
}
free_object_attributes(obj_ga.og_attributes, 2);
if (rv != CKR_OK) {
return (rv);
}
/* Make sure it is a token object. */
if (!is_token_obj) {
rv = CKR_ATTRIBUTE_VALUE_INVALID;
return (rv);
}
/* If it is a private object, make sure the user has logged in. */
if (is_pri_obj && (pslot->sl_state != CKU_USER)) {
rv = CKR_ATTRIBUTE_VALUE_INVALID;
return (rv);
}
objp->is_lib_obj = B_FALSE;
objp->k_handle = oid;
objp->bool_attr_mask |= TOKEN_BOOL_ON;
if (is_pri_obj) {
objp->bool_attr_mask |= PRIVATE_BOOL_ON;
} else {
objp->bool_attr_mask &= ~PRIVATE_BOOL_ON;
}
(void) pthread_mutex_init(&objp->object_mutex, NULL);
objp->magic_marker = KERNELTOKEN_OBJECT_MAGIC;
objp->session_handle = (CK_SESSION_HANDLE) sp;
return (CKR_OK);
}
/*
* This function processes the kernel object handles returned from the
* CRYPTO_OBJECT_FIND_UPDATE ioctl and returns an object handle list
* and the number of object handles to the caller - C_FindObjects().
* The caller acquires the slot lock and the session lock.
*/
CK_RV
process_found_objects(kernel_session_t *cur_sp, CK_OBJECT_HANDLE *obj_found,
CK_ULONG *found_obj_count, crypto_object_find_update_t obj_fu)
{
CK_RV rv = CKR_OK;
crypto_object_id_t *oid_p;
kernel_slot_t *pslot;
kernel_object_t *objp;
kernel_object_t *objp1;
kernel_object_t *new_tobj_list = NULL;
kernel_session_t *sp;
CK_ULONG num_obj_found = 0;
boolean_t is_in_lib;
int i;
if (obj_fu.fu_count == 0) {
*found_obj_count = 0;
return (CKR_OK);
}
pslot = slot_table[cur_sp->ses_slotid];
/* LINTED */
oid_p = (crypto_object_id_t *)obj_fu.fu_handles;
for (i = 0; i < obj_fu.fu_count; i++) {
is_in_lib = B_FALSE;
/*
* Check if this oid has an object wrapper in the library
* already. First, search the slot's token object list.
*/
objp = pslot->sl_tobj_list;
while (!is_in_lib && objp) {
if (objp->k_handle == *oid_p) {
is_in_lib = B_TRUE;
} else {
objp = objp->next;
}
}
/*
* If it is not in the slot's token object list,
* search it in all the sessions.
*/
if (!is_in_lib) {
sp = pslot->sl_sess_list;
while (!is_in_lib && sp) {
objp = sp->object_list;
while (!is_in_lib && objp) {
if (objp->k_handle == *oid_p) {
is_in_lib = B_TRUE;
} else {
objp = objp->next;
}
}
sp = sp->next;
}
}
/*
* If this object is in the library already, add its object
* wrapper to the returned find object list.
*/
if (is_in_lib) {
obj_found[num_obj_found++] = (CK_OBJECT_HANDLE)objp;
}
/*
* If we still do not find it in the library. This object
* must be a token object pre-existed in the HW provider.
* We need to create an object wrapper for it in the library.
*/
if (!is_in_lib) {
objp1 = calloc(1, sizeof (kernel_object_t));
if (objp1 == NULL) {
rv = CKR_HOST_MEMORY;
goto failed_exit;
}
rv = create_new_tobj_in_lib(pslot, cur_sp, objp1,
*oid_p);
if (rv == CKR_OK) {
/* Save the new object to the new_tobj_list. */
if (new_tobj_list == NULL) {
new_tobj_list = objp1;
objp1->next = NULL;
objp1->prev = NULL;
} else {
new_tobj_list->prev = objp1;
objp1->next = new_tobj_list;
objp1->prev = NULL;
new_tobj_list = objp1;
}
} else {
/*
* If create_new_tobj_in_lib() doesn't fail
* with CKR_HOST_MEMORY, the failure should be
* caused by the attributes' checking. We will
* just ignore this object and continue on.
*/
free(objp1);
if (rv == CKR_HOST_MEMORY) {
goto failed_exit;
}
}
}
/* Process next one */
oid_p++;
}
/*
* Add the newly created token object wrappers to the found object
* list and to the slot's token object list.
*/
if (new_tobj_list != NULL) {
/* Add to the obj_found array. */
objp = new_tobj_list;
while (objp) {
obj_found[num_obj_found++] = (CK_OBJECT_HANDLE)objp;
if (objp->next == NULL) {
break;
}
objp = objp->next;
}
/* Add to the beginning of the slot's token object list. */
if (pslot->sl_tobj_list != NULL) {
objp->next = pslot->sl_tobj_list;
pslot->sl_tobj_list->prev = objp;
}
pslot->sl_tobj_list = new_tobj_list;
}
*found_obj_count = num_obj_found;
return (CKR_OK);
failed_exit:
/* Free the newly created token object wrappers. */
objp = new_tobj_list;
while (objp) {
objp1 = objp->next;
(void) pthread_mutex_destroy(&objp->object_mutex);
free(objp);
objp = objp1;
}
return (rv);
}
/*
* Get the value of the CKA_PRIVATE attribute for the object just returned
* from the HW provider. This function will be called by any function
* that creates a new object, because the CKA_PRIVATE value of an object is
* token specific. The CKA_PRIVATE attribute value of the new object will be
* stored in the object structure in the library, which will be used later at
* C_Logout to clean up all private objects.
*/
CK_RV
get_cka_private_value(kernel_session_t *sp, crypto_object_id_t oid,
CK_BBOOL *is_pri_obj)
{
CK_RV rv = CKR_OK;
crypto_object_get_attribute_value_t obj_ga;
crypto_object_attribute_t obj_attr;
CK_BBOOL pri_value;
int r;
obj_ga.og_session = sp->k_session;
obj_ga.og_handle = oid;
obj_ga.og_count = 1;
obj_attr.oa_type = CKA_PRIVATE;
obj_attr.oa_value = (char *)&pri_value;
obj_attr.oa_value_len = sizeof (CK_BBOOL);
obj_ga.og_attributes = (char *)&obj_attr;
while ((r = ioctl(kernel_fd, CRYPTO_OBJECT_GET_ATTRIBUTE_VALUE,
&obj_ga)) < 0) {
if (errno != EINTR)
break;
}
if (r < 0) {
rv = CKR_FUNCTION_FAILED;
} else {
rv = crypto2pkcs11_error_number(obj_ga.og_return_value);
}
if (rv == CKR_OK) {
*is_pri_obj = *(CK_BBOOL *)obj_attr.oa_value;
}
return (rv);
}
CK_RV
get_mechanism_info(kernel_slot_t *pslot, CK_MECHANISM_TYPE type,
CK_MECHANISM_INFO_PTR pInfo, uint32_t *k_mi_flags)
{
crypto_get_provider_mechanism_info_t mechanism_info;
const char *string;
CK_FLAGS flags, mi_flags;
CK_RV rv;
int r;
char buf[11]; /* Num chars for representing ulong in ASCII */
if (type >= CKM_VENDOR_DEFINED) {
/* allocate/build a string containing the mechanism number */
(void) snprintf(buf, sizeof (buf), "%#lx", type);
string = buf;
} else {
string = pkcs11_mech2str(type);
}
if (string == NULL)
return (CKR_MECHANISM_INVALID);
(void) strcpy(mechanism_info.mi_mechanism_name, string);
mechanism_info.mi_provider_id = pslot->sl_provider_id;
while ((r = ioctl(kernel_fd, CRYPTO_GET_PROVIDER_MECHANISM_INFO,
&mechanism_info)) < 0) {
if (errno != EINTR)
break;
}
if (r < 0) {
rv = CKR_FUNCTION_FAILED;
} else {
rv = crypto2pkcs11_error_number(
mechanism_info.mi_return_value);
}
if (rv != CKR_OK) {
return (rv);
}
/*
* Atomic flags are not part of PKCS#11 so we filter
* them out here.
*/
mi_flags = mechanism_info.mi_flags;
mi_flags &= ~(CRYPTO_FG_DIGEST_ATOMIC | CRYPTO_FG_ENCRYPT_ATOMIC |
CRYPTO_FG_DECRYPT_ATOMIC | CRYPTO_FG_MAC_ATOMIC |
CRYPTO_FG_SIGN_ATOMIC | CRYPTO_FG_VERIFY_ATOMIC |
CRYPTO_FG_SIGN_RECOVER_ATOMIC |
CRYPTO_FG_VERIFY_RECOVER_ATOMIC |
CRYPTO_FG_ENCRYPT_MAC_ATOMIC |
CRYPTO_FG_MAC_DECRYPT_ATOMIC);
if (mi_flags == 0) {
return (CKR_MECHANISM_INVALID);
}
if (rv == CKR_OK) {
/* set the value of k_mi_flags first */
*k_mi_flags = mi_flags;
/* convert KEF flags into pkcs11 flags */
flags = CKF_HW;
if (mi_flags & CRYPTO_FG_ENCRYPT)
flags |= CKF_ENCRYPT;
if (mi_flags & CRYPTO_FG_DECRYPT) {
flags |= CKF_DECRYPT;
/*
* Since we'll be emulating C_UnwrapKey() for some
* cases, we can go ahead and claim CKF_UNWRAP
*/
flags |= CKF_UNWRAP;
}
if (mi_flags & CRYPTO_FG_DIGEST)
flags |= CKF_DIGEST;
if (mi_flags & CRYPTO_FG_SIGN)
flags |= CKF_SIGN;
if (mi_flags & CRYPTO_FG_SIGN_RECOVER)
flags |= CKF_SIGN_RECOVER;
if (mi_flags & CRYPTO_FG_VERIFY)
flags |= CKF_VERIFY;
if (mi_flags & CRYPTO_FG_VERIFY_RECOVER)
flags |= CKF_VERIFY_RECOVER;
if (mi_flags & CRYPTO_FG_GENERATE)
flags |= CKF_GENERATE;
if (mi_flags & CRYPTO_FG_GENERATE_KEY_PAIR)
flags |= CKF_GENERATE_KEY_PAIR;
if (mi_flags & CRYPTO_FG_WRAP)
flags |= CKF_WRAP;
if (mi_flags & CRYPTO_FG_UNWRAP)
flags |= CKF_UNWRAP;
if (mi_flags & CRYPTO_FG_DERIVE)
flags |= CKF_DERIVE;
pInfo->ulMinKeySize = mechanism_info.mi_min_key_size;
pInfo->ulMaxKeySize = mechanism_info.mi_max_key_size;
pInfo->flags = flags;
}
return (rv);
}
/*
* Unfortunately the kernel and PKCS#11 use a slightly different struct to
* specify CCM parameters.
*/
void
p11_to_kernel_ccm_params(const CK_CCM_PARAMS *in, CK_AES_CCM_PARAMS *out)
{
out->ulMACSize = in->ulMACLen;
out->ulNonceSize = in->ulNonceLen;
out->ulAuthDataSize = in->ulAADLen;
out->ulDataSize = in->ulDataLen;
out->nonce = in->pNonce;
out->authData = in->pAAD;
}
| 25.622871 | 79 | 0.70063 |
f80b4a3714a834c34de4f43b8007f23d50fe306d | 659 | h | C | strings/strings.h | boldenth/tbcutil | 6092ba39d82ebcf6d446d0c9bbd5e3de8344c7c4 | [
"MIT"
] | null | null | null | strings/strings.h | boldenth/tbcutil | 6092ba39d82ebcf6d446d0c9bbd5e3de8344c7c4 | [
"MIT"
] | null | null | null | strings/strings.h | boldenth/tbcutil | 6092ba39d82ebcf6d446d0c9bbd5e3de8344c7c4 | [
"MIT"
] | null | null | null | #ifndef ___GUARD_STRINGS_H
#define ___GUARD_STRINGS_H
#include "global.h"
#include <stdarg.h>
typedef char *string;
string string_dup(const string);
string string_copy(const string);
string string_trim(string);
string string_replace(string, const string, const string);// this'll be annoying
string *string_split(string, const char *);
size_t string_arrsize(string *);
string string_concat(size_t, ...);// extend to concat strings in array
void string_toupper(string);
void string_tolower(string);
void string_free(string);
void string_freearr(string *);
int string_compare(const string, const string);
#endif // ___GUARD_STRINGS_H
| 27.458333 | 81 | 0.76176 |
50b6d6a11b4734ab23fb9f75a5c71d3ef1ad3df3 | 1,324 | h | C | src/region.h | Shao-Group/altai | 27c21affe076849e6edb3957f2a77ece5726f3a1 | [
"BSD-3-Clause"
] | 2 | 2021-11-07T23:25:16.000Z | 2021-12-11T02:21:36.000Z | src/region.h | Shao-Group/altai | 27c21affe076849e6edb3957f2a77ece5726f3a1 | [
"BSD-3-Clause"
] | null | null | null | src/region.h | Shao-Group/altai | 27c21affe076849e6edb3957f2a77ece5726f3a1 | [
"BSD-3-Clause"
] | null | null | null | /*
Part of Scallop Transcript Assembler
(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
Part of Altai
(c) 2021 by Xiaofei Carl Zang, Mingfu Shao, and The Pennsylvania State University.
See LICENSE for licensing.
*/
#ifndef __REGION_H__
#define __REGION_H__
#include <stdint.h>
#include <vector>
#include "interval_map.h"
#include "partial_exon.h"
#include "as_pos32.hpp"
using namespace std;
typedef pair<int, int> PI;
class region
{
public:
region(as_pos32 _lpos, as_pos32 _rpos, int _ltype, int _rtype, const split_interval_map *_mmap, const split_interval_map *_imap);
~region();
public:
as_pos32 lpos; // the leftmost boundary on reference
as_pos32 rpos; // the rightmost boundary on reference
int ltype; // type of the left boundary
int rtype; // type of the right boundary
const split_interval_map *mmap; // pointer to match interval map
const split_interval_map *imap; // pointer to indel interval map
join_interval_map jmap; // subregion intervals
vector<partial_exon> pexons; // generated partial exons
public:
int print(int index) const;
bool left_inclusive();
bool right_inclusive();
private:
int build_join_interval_map();
int smooth_join_interval_map();
bool empty_subregion(as_pos32 p1, as_pos32 p2);
int build_partial_exons();
};
#endif
| 25.461538 | 130 | 0.756042 |
1f5a8b16a1d949cda11fb2906c23d014622fa11e | 18,575 | c | C | src/robotmodel.c | liyanan24/robot-sim | c4123e881f5791ce2be344c89b0bd516d13c6e45 | [
"MIT"
] | null | null | null | src/robotmodel.c | liyanan24/robot-sim | c4123e881f5791ce2be344c89b0bd516d13c6e45 | [
"MIT"
] | null | null | null | src/robotmodel.c | liyanan24/robot-sim | c4123e881f5791ce2be344c89b0bd516d13c6e45 | [
"MIT"
] | null | null | null | //MIT License
//Copyright (c) 2018 Eotvos Lorand University, Budapest
/* vim:set ts=4 sw=4 sts=4 et: */
/* Tools for handling the robot model
*/
#include "robotmodel.h"
double **PreferredVelocities;
phase_t LocalActualPhase;
phase_t LocalActualDelayedPhase;
phase_t SteppedPhase;
phase_t TempPhase;
double *ChangedInnerStateOfActualAgent;
static int NumberOfNeighbours = 0; /* Number of units observed by the actual agent */
/* For passing debug information to CalculatePreferredVelocity function */
agent_debug_info_t DebugInfo;
/* Caulculating the phase space observed by the "WhichAgent"th unit. */
void CreatePhase(phase_t * LocalActualPhaseToCreate,
phase_t * GPSPhase,
phase_t * GPSDelayedPhase,
phase_t * Phase,
phase_t * DelayedPhase,
const int WhichAgent,
const double R_C,
const double packet_loss_ratio,
const double packet_loss_distance, const bool OrderByDistance) {
int i, j;
LocalActualPhaseToCreate->NumberOfAgents = Phase->NumberOfAgents; // ???
LocalActualPhaseToCreate->NumberOfInnerStates = Phase->NumberOfInnerStates; // ???
/* Setting up order by distance from actual unit */
for (i = 0; i < Phase->NumberOfAgents; i++) {
LocalActualPhaseToCreate->RealIDs[i] = Phase->RealIDs[i];
for (j = 0; j < 3; j++) {
LocalActualPhaseToCreate->Coordinates[i][j] =
Phase->Coordinates[i][j];
LocalActualPhaseToCreate->Velocities[i][j] =
Phase->Velocities[i][j];
}
for (j = 0; j < Phase->NumberOfInnerStates; j++) {
LocalActualPhaseToCreate->InnerStates[i][j] =
Phase->InnerStates[i][j];
}
}
static double ActualAgentsPosition[3];
GetAgentsCoordinates(ActualAgentsPosition, Phase, WhichAgent);
if (OrderByDistance) {
/* OrderByDistance selects the nearby agents, and places their phase to the beginning of the full phase array. */
NumberOfNeighbours =
SelectNearbyVisibleAgents(LocalActualPhaseToCreate,
ActualAgentsPosition, R_C,
packet_loss_distance >
0 ? packet_loss_ratio / packet_loss_distance /
packet_loss_distance : 0);
} else {
SwapAgents(LocalActualPhaseToCreate, WhichAgent, 0);
NumberOfNeighbours = 1;
}
/* Setting up delay and GPS inaccuracy for positions and velocities */
/* Velocities */
static double RealVelocity[3];
NullVect(RealVelocity, 3);
static double GPSVelocityToAdd[3];
NullVect(GPSVelocityToAdd, 3);
/* Positions */
static double RealPosition[3];
NullVect(RealPosition, 3);
static double GPSPositionToAdd[3];
NullVect(GPSPositionToAdd, 3);
for (i = 1; i < NumberOfNeighbours; i++) {
GetAgentsCoordinates(RealPosition, DelayedPhase,
LocalActualPhaseToCreate->RealIDs[i]);
GetAgentsVelocity(RealVelocity, DelayedPhase,
LocalActualPhaseToCreate->RealIDs[i]);
InsertAgentsCoordinates(LocalActualPhaseToCreate, RealPosition, i);
InsertAgentsVelocity(LocalActualPhaseToCreate, RealVelocity, i);
}
GetAgentsCoordinates(RealPosition, Phase, WhichAgent);
/* Adding term of GPS errors (XY) */
GetAgentsCoordinates(GPSPositionToAdd, GPSPhase, WhichAgent); // WhichAgent = RealIDs[0] = 0
GetAgentsVelocity(GPSVelocityToAdd, GPSPhase, WhichAgent);
GetAgentsVelocity(RealVelocity, LocalActualPhaseToCreate, 0);
GetAgentsCoordinates(RealPosition, LocalActualPhaseToCreate, 0);
VectSum(RealVelocity, RealVelocity, GPSVelocityToAdd);
VectSum(RealPosition, RealPosition, GPSPositionToAdd);
InsertAgentsCoordinates(LocalActualPhaseToCreate, RealPosition, 0);
InsertAgentsVelocity(LocalActualPhaseToCreate, RealVelocity, 0);
for (i = 1; i < NumberOfNeighbours; i++) {
GetAgentsVelocity(RealVelocity, LocalActualPhaseToCreate, i);
GetAgentsCoordinates(RealPosition, LocalActualPhaseToCreate, i);
GetAgentsCoordinates(GPSPositionToAdd, GPSDelayedPhase,
LocalActualPhaseToCreate->RealIDs[i]);
GetAgentsVelocity(GPSVelocityToAdd, GPSDelayedPhase,
LocalActualPhaseToCreate->RealIDs[i]);
VectSum(RealVelocity, RealVelocity, GPSVelocityToAdd);
VectSum(RealPosition, RealPosition, GPSPositionToAdd);
InsertAgentsCoordinates(LocalActualPhaseToCreate, RealPosition, i);
InsertAgentsVelocity(LocalActualPhaseToCreate, RealVelocity, i);
}
LocalActualPhaseToCreate->NumberOfAgents = NumberOfNeighbours;
}
/* Adding outer noise to final velocity vector */
/* Diffusive noise is a more-or-less effective model of the unknown properties of the control algorithm on the robots. */
void AddNoiseToVector(double *NoisedVector, double *NoiselessVector,
double *RealVelocity, unit_model_params_t * UnitParams,
const double DeltaT, double *WindVelocityVector) {
int i;
static double NoiseToAdd[3];
NullVect(NoiseToAdd, 3);
/* Random noise with Gaussian distribution */
NoiseToAdd[0] = randomizeGaussDouble(0, 1);
NoiseToAdd[1] = randomizeGaussDouble(0, 1);
NoiseToAdd[2] = randomizeGaussDouble(0, 1);
MultiplicateWithScalar(NoiseToAdd, NoiseToAdd,
sqrt(2 * UnitParams->Sigma_Outer_XY.Value) * sqrt(DeltaT), 2);
NoiseToAdd[2] *= sqrt(2 * UnitParams->Sigma_Outer_Z.Value) * sqrt(DeltaT);
/* Noise is an additive term to the final output velocity */
VectSum(NoiseToAdd, NoiselessVector, NoiseToAdd);
for (i = 0; i < 2; i++) {
NoisedVector[i] = NoiseToAdd[i];
}
NoisedVector[2] = NoiseToAdd[2];
}
/* Calculating wind effect to add to final output acceleration */
/* It is based on a simple Stokes-like force-law. */
void StepWind(unit_model_params_t * UnitParams, const double DeltaT,
double *WindVelocityVector) {
static double NoiseToAdd[2];
NoiseToAdd[0] = randomizeGaussDouble(0.0, 1.0);
NoiseToAdd[1] = randomizeGaussDouble(0.0, 1.0);
WindVelocityVector[0] =
WindVelocityVector[0] +
NoiseToAdd[0] * sqrt(2 * UnitParams->Wind_StDev.Value * DeltaT);
WindVelocityVector[1] =
WindVelocityVector[1] +
NoiseToAdd[1] * sqrt(2 * UnitParams->Wind_StDev.Value * DeltaT);
//TODO: Potential for Wind speed...
}
/* Force law contains specific features of a real robot
*/
void RealCoptForceLaw(double *OutputVelocity, double *OutputInnerState,
phase_t * Phase, double *RealVelocity, unit_model_params_t * UnitParams,
flocking_model_params_t * FlockingParams, vizmode_params_t * VizParams,
const double DeltaT, const int TimeStepReal, const int TimeStepLooped,
const int WhichAgent, double *WindVelocityVector) {
int i;
/*
* The units in the array "Phase" ara ordered by the distance from "WhichAgent"th unit.
* Therefore, Position and velocity of "WhichAgent"th unit is stored in Phase[0] - Phase[5].
*/
static double PreviousVelocity[3];
GetAgentsVelocity(PreviousVelocity, Phase, 0);
static double TempTarget[3];
for (i = 0; i < Phase->NumberOfInnerStates; i++) {
OutputInnerState[i] = Phase->InnerStates[0][i];
}
if (TimeStepLooped % ((int) (UnitParams->t_GPS.Value / DeltaT)) == 0) {
/*for (i=0; i<FlockingParams->NumberOfInnerStates; i++) {
OutputInnerState[i] = Phase->InnerStates[0][i];
} */
/* Calculating target velocity */
NullVect(TempTarget, 3);
CalculatePreferredVelocity(TempTarget, OutputInnerState, Phase, 0,
FlockingParams, VizParams, UnitParams->t_del.Value,
TimeStepReal * DeltaT, &DebugInfo);
for (i = 0; i < 3; i++) {
PreferredVelocities[WhichAgent][i] = TempTarget[i];
}
}
for (i = 0; i < 2; i++) {
OutputVelocity[i] =
RealVelocity[i] +
(DeltaT / UnitParams->Tau_PID_XY.Value) *
(PreferredVelocities[WhichAgent][i] - PreviousVelocity[i]);
}
OutputVelocity[2] =
RealVelocity[2] +
(DeltaT / UnitParams->Tau_PID_Z.Value) *
(PreferredVelocities[WhichAgent][2] - PreviousVelocity[2]);
}
/* Step positions and velocities and copy real IDs */
void Step(phase_t * OutputPhase, phase_t * GPSPhase, phase_t * GPSDelayedPhase,
phase_t * PhaseData, unit_model_params_t * UnitParams,
flocking_model_params_t * FlockingParams, sit_parameters_t * SitParams,
vizmode_params_t * VizParams, int TimeStepLooped, int TimeStepReal,
bool CountCollisions, bool * ConditionsReset, int *Collisions,
bool * AgentsInDanger, double *WindVelocityVector,
double *Accelerations) {
int i, j, k;
static double CheckVelocityCache[3];
NullVect(CheckVelocityCache, 3);
static double CheckAccelerationCache[3];
NullVect(CheckAccelerationCache, 3);
static double CheckDifferenceCache[3];
NullVect(CheckDifferenceCache, 3);
static double UnitVectDifference[3];
NullVect(UnitVectDifference, 3);
static double DelayStep;
DelayStep = (UnitParams->t_del.Value / SitParams->DeltaT);
/* Getting phase of actual TimeStepfrom PhaseData */
LocalActualPhase = PhaseData[TimeStepLooped];
LocalActualDelayedPhase = PhaseData[TimeStepLooped - (int) DelayStep];
/* Counting Collisions */
static int PreviousColl = 0;
if (CountCollisions == true) {
*Collisions +=
HowManyCollisions(&LocalActualPhase, AgentsInDanger,
CountCollisions, SitParams->Radius);
PreviousColl = *Collisions;
}
/* Step coordinates (with velocity of previous TimeStepLooped) */
static double Velocity[3];
static double CoordinatesToStep[3];
for (j = 0; j < SitParams->NumberOfAgents; j++) {
GetAgentsVelocity(Velocity, &LocalActualPhase, j);
GetAgentsCoordinates(CoordinatesToStep, &LocalActualPhase, j);
for (i = 0; i < 3; i++) {
CoordinatesToStep[i] += Velocity[i] * SitParams->DeltaT;
}
InsertAgentsCoordinates(&SteppedPhase, CoordinatesToStep, j);
}
/* Step GPS coordinates and velocities (in every "t_gps"th second) */
if ((TimeStepLooped) % ((int) (UnitParams->t_GPS.Value /
SitParams->DeltaT)) == 0) {
StepGPSNoises(GPSPhase, UnitParams);
StepGPSNoises(GPSDelayedPhase, UnitParams);
}
/* Step Wind vector */
//StepWind (UnitParams, SitParams->DeltaT, WindVelocityVector);
/* "Realcopt" force law */
static double RealCoptForceVector[3];
NullVect(RealCoptForceVector, 3);
static double ActualRealVelocity[3];
NullVect(ActualRealVelocity, 3);
for (j = 0; j < SitParams->NumberOfAgents; j++) {
/* Constructing debug information about the actual agent */
DebugInfo.AgentsSeqNumber = j;
GetAgentsCoordinates(DebugInfo.AgentsRealPosition, &LocalActualPhase,
j);
GetAgentsVelocity(DebugInfo.AgentsRealVelocity, &LocalActualPhase, j);
DebugInfo.RealPhase = &LocalActualPhase;
/* Creating phase from the viewpoint of the actual agent */
CreatePhase(&TempPhase, GPSPhase, GPSDelayedPhase, &LocalActualPhase,
&LocalActualDelayedPhase, j, UnitParams->R_C.Value,
UnitParams->packet_loss_ratio.Value,
UnitParams->packet_loss_distance.Value,
(TimeStepLooped % ((int) (UnitParams->t_GPS.Value /
SitParams->DeltaT)) == 0));
GetAgentsVelocity(ActualRealVelocity, &LocalActualPhase, j);
/* Solving Newtonian with Euler-Naruyama method */
NullVect(RealCoptForceVector, 3);
RealCoptForceLaw(RealCoptForceVector, ChangedInnerStateOfActualAgent,
&TempPhase, ActualRealVelocity, UnitParams, FlockingParams,
VizParams, SitParams->DeltaT, TimeStepReal, TimeStepLooped, j,
WindVelocityVector);
NullVect(CheckVelocityCache, 3);
VectSum(CheckVelocityCache, CheckVelocityCache, RealCoptForceVector);
/* Updating inner states */
InsertAgentsVelocity(&SteppedPhase, CheckVelocityCache, j);
for (k = 0; k < PhaseData[0].NumberOfInnerStates; k++) {
SteppedPhase.InnerStates[j][k] = ChangedInnerStateOfActualAgent[k];
}
}
double OnePerDeltaT = 1. / SitParams->DeltaT;
/* The acceleration saturates at a_max. We save out the acceleration magnitude values before we add OuterNoise to the velocities and lose the possibility to derivate numerically */
for (i = 0; i < SitParams->NumberOfAgents; i++) {
GetAgentsVelocity(CheckAccelerationCache, &LocalActualPhase, i);
GetAgentsVelocity(CheckVelocityCache, &SteppedPhase, i);
VectDifference(CheckDifferenceCache, CheckVelocityCache,
CheckAccelerationCache);
UnitVect(UnitVectDifference, CheckDifferenceCache);
Accelerations[i] = VectAbs(CheckDifferenceCache) * OnePerDeltaT;
if (Accelerations[i] > UnitParams->a_max.Value) {
for (k = 0; k < 3; k++) {
CheckVelocityCache[k] =
CheckAccelerationCache[k] +
UnitParams->a_max.Value * SitParams->DeltaT *
UnitVectDifference[k];
}
InsertAgentsVelocity(&SteppedPhase, CheckVelocityCache, i);
Accelerations[i] = UnitParams->a_max.Value;
}
}
/* Outer Noise Term - Gaussian white noise */
for (j = 0; j < SitParams->NumberOfAgents; j++) {
if (true == Noises[j]) {
GetAgentsVelocity(CheckAccelerationCache, &LocalActualPhase, j);
GetAgentsVelocity(CheckVelocityCache, &SteppedPhase, j);
AddNoiseToVector(CheckVelocityCache, CheckVelocityCache,
CheckAccelerationCache, UnitParams, SitParams->DeltaT,
WindVelocityVector);
InsertAgentsVelocity(&SteppedPhase, CheckVelocityCache, j);
}
}
/* Redistribution of agents when pressing F12 */
if (ConditionsReset[0] == true) {
DestroyPhase(&SteppedPhase, FlockingParams, SitParams);
RandomizePhase(&SteppedPhase, SitParams->InitialX, SitParams->InitialY,
SitParams->InitialZ, VizParams->CenterX, VizParams->CenterY,
VizParams->CenterZ, 0, SitParams->NumberOfAgents,
SitParams->Radius);
InitializePhase(&SteppedPhase, FlockingParams, SitParams);
ModelSpecificReset(&SteppedPhase, SitParams->InitialX,
SitParams->InitialY, SitParams->InitialZ, VizParams,
FlockingParams, SitParams->Radius);
ConditionsReset[0] = false;
} else if (ConditionsReset[1] == true) {
if (VizParams->MapSizeXY < SitParams->InitialX
|| VizParams->MapSizeXY < SitParams->InitialY) {
DestroyPhase(&SteppedPhase, FlockingParams, SitParams);
RandomizePhase(&SteppedPhase, SitParams->InitialX,
SitParams->InitialY, SitParams->InitialZ,
VizParams->CenterX, VizParams->CenterY, VizParams->CenterZ,
0, SitParams->NumberOfAgents, SitParams->Radius);
InitializePhase(&SteppedPhase, FlockingParams, SitParams);
ModelSpecificReset(&SteppedPhase,
SitParams->InitialX, SitParams->InitialY,
SitParams->InitialZ, VizParams, FlockingParams,
SitParams->Radius);
} else {
DestroyPhase(&SteppedPhase, FlockingParams, SitParams);
RandomizePhase(&SteppedPhase, VizParams->MapSizeXY,
VizParams->MapSizeXY, VizParams->MapSizeZ,
VizParams->CenterX, VizParams->CenterY, VizParams->CenterZ,
0, SitParams->NumberOfAgents, SitParams->Radius);
InitializePhase(&SteppedPhase, FlockingParams, SitParams);
ModelSpecificReset(&SteppedPhase, VizParams->MapSizeXY,
VizParams->MapSizeXY, VizParams->MapSizeZ, VizParams,
FlockingParams, SitParams->Radius);
}
ConditionsReset[1] = false;
}
/* Insert Phase into PhaseData... */
for (j = 0; j < SitParams->NumberOfAgents; j++) {
for (i = 0; i < 3; i++) {
OutputPhase->Coordinates[j][i] = SteppedPhase.Coordinates[j][i];
OutputPhase->Velocities[j][i] = SteppedPhase.Velocities[j][i];
}
for (i = 0; i < SteppedPhase.NumberOfInnerStates; i++) {
OutputPhase->InnerStates[j][i] = SteppedPhase.InnerStates[j][i];
}
}
}
/* Some global variables are allocated and initialized in this function */
void InitializePreferredVelocities(phase_t * Phase,
flocking_model_params_t * FlockingParams, sit_parameters_t * SitParams,
unit_model_params_t * UnitParams, double *WindVelocityVector) {
/* Preferred Velocities */
PreferredVelocities = doubleMatrix(SitParams->NumberOfAgents, 3);
Noises = BooleanData(SitParams->NumberOfAgents);
int i, j;
for (i = 0; i < SitParams->NumberOfAgents; i++) {
for (j = 0; j < 3; j++) {
PreferredVelocities[i][j] = 0.0;
}
Noises[i] = true;
}
/* Some helper dynamic arrays should be allocated here */
AllocatePhase(&SteppedPhase, SitParams->NumberOfAgents,
Phase->NumberOfInnerStates);
AllocatePhase(&TempPhase, SitParams->NumberOfAgents,
Phase->NumberOfInnerStates);
ChangedInnerStateOfActualAgent =
(double *) calloc(Phase->NumberOfInnerStates, sizeof(double));
/* Setting up wind velocity vector */
WindVelocityVector[0] = cos(UnitParams->Wind_Angle.Value);
WindVelocityVector[1] = sin(UnitParams->Wind_Angle.Value);
}
/* Free every variable allocated in InitializePreferredVelocities function */
void freePreferredVelocities(phase_t * Phase,
flocking_model_params_t * FlockingParams,
sit_parameters_t * SitParams) {
freeMatrix(PreferredVelocities, SitParams->NumberOfAgents, 3);
free(Noises);
/* Freeing memory owned by helper arrays */
freePhase(&SteppedPhase);
freePhase(&TempPhase);
if (Phase->NumberOfInnerStates != 0) {
free(ChangedInnerStateOfActualAgent);
}
}
| 38.063525 | 184 | 0.657012 |
ea6c962a3932f3bc7a28276a93e2bc9c45f2a2cf | 340 | h | C | uboot/include/i2c_eeprom.h | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 35 | 2019-04-26T04:00:10.000Z | 2022-03-30T11:37:06.000Z | uboot/include/i2c_eeprom.h | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 4 | 2016-08-30T11:30:25.000Z | 2020-12-27T09:58:07.000Z | uboot/include/i2c_eeprom.h | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 11 | 2020-01-07T05:39:10.000Z | 2021-12-26T07:27:21.000Z | /*
* Copyright (c) 2014 Google, Inc
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef __I2C_EEPROM
#define __I2C_EEPROM
struct i2c_eeprom_ops {
int (*read)(struct udevice *dev, int offset, uint8_t *buf, int size);
int (*write)(struct udevice *dev, int offset, const uint8_t *buf,
int size);
};
struct i2c_eeprom {
};
#endif
| 17 | 70 | 0.676471 |
6ee1eadd3739eb1ccaa4357104f93cbe1ae0e34f | 429 | h | C | rh_engine_lib/Engine/VulkanImpl/VulkanDebugUtils.h | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 232 | 2016-08-29T00:33:32.000Z | 2022-03-29T22:39:51.000Z | rh_engine_lib/Engine/VulkanImpl/VulkanDebugUtils.h | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 10 | 2021-01-02T12:40:49.000Z | 2021-08-31T06:31:04.000Z | rh_engine_lib/Engine/VulkanImpl/VulkanDebugUtils.h | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 40 | 2017-12-18T06:14:39.000Z | 2022-01-29T16:35:23.000Z | //
// Created by peter on 03.06.2020.
//
#pragma once
#include <string>
namespace rh::engine
{
class IBuffer;
class ICommandBuffer;
class ISyncPrimitive;
class VulkanDebugUtils
{
public:
static void SetDebugName( IBuffer *buffer, std::string name );
static void SetDebugName( ICommandBuffer *buffer, std::string name );
static void SetDebugName( ISyncPrimitive *sp, std::string name );
};
} // namespace rh::engine | 22.578947 | 73 | 0.727273 |
6ef145b24575bb83891a9a4b4095a7bbcffad750 | 7,299 | c | C | lab.c | Scriptor/spotlab | 754dbd3e5d8cbc700a58c11616029ecdfb267b88 | [
"Unlicense"
] | null | null | null | lab.c | Scriptor/spotlab | 754dbd3e5d8cbc700a58c11616029ecdfb267b88 | [
"Unlicense"
] | null | null | null | lab.c | Scriptor/spotlab | 754dbd3e5d8cbc700a58c11616029ecdfb267b88 | [
"Unlicense"
] | null | null | null | #include "lab.h"
#include <pthread.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
sp_session *g_session;
static int notify_events;
static pthread_mutex_t notify_mut;
static pthread_cond_t notify_cond;
int can_prompt = 0;
static pthread_cond_t prompt_cond;
command_t *current_cmd;
void notify_main_thread(sp_session *session){
pthread_mutex_lock(¬ify_mut);
notify_events = 1;
pthread_cond_signal(¬ify_cond);
pthread_mutex_unlock(¬ify_mut);
}
static void connection_error(sp_session *session, sp_error error)
{
}
static void logged_in(sp_session *session, sp_error error)
{
}
static void logged_out(sp_session *session)
{
//exit(0);
}
/**
* This callback is called for log messages.
*
* @sa sp_session_callbacks#log_message
*/
static void log_message(sp_session *session, const char *data)
{
//printf("%s\n", data);
}
static sp_session_callbacks callbacks = {
.logged_in = &logged_in,
.logged_out = &logged_out,
.connection_error = &connection_error,
.notify_main_thread = ¬ify_main_thread,
.log_message = &log_message,
};
static void artistbrowse_complete(sp_artistbrowse *result, void *name){
int i, num_tracks, display_num;
char *ar_name = (char *)name;
sp_track *t;
num_tracks = sp_artistbrowse_num_tracks(result);
display_num = num_tracks < 5 ? num_tracks : 5;
printf("%d tracks found for %s\n", num_tracks, ar_name);
printf("Listing first %d\n", display_num);
for(i=0; i<display_num; i++){
t = sp_artistbrowse_track(result, i);
printf("%d: %s\n", i, sp_track_name(t));
}
sp_artistbrowse_release(result);
finish_cmd();
}
static void search_complete(sp_search *result, void *userdata){
int num_artists;
const char *name;
sp_artist *ar;
num_artists = sp_search_num_artists(result);
printf("%d search artists found\n", num_artists);
ar = sp_search_artist(result, 0);
name = sp_artist_name(ar);
printf("Initiating browse of artist: \"%s\"...\n", name);
sp_artistbrowse_create(g_session, ar, SP_ARTISTBROWSE_FULL,
&artistbrowse_complete, (void *)name);
sp_search_release(result);
sp_artist_release(ar);
// Don't finish_cmd here because we need to wait
// for the artistbrowse callback to finish
}
void parse_toks(char *cmd_str, tok_t **toks){
char cur_tok[256];
char c;
int i=0, j=0;
// Loop indefinitely with (|| 1)
// break on null-terminator inside loop
while((c = *cmd_str++) || 1){
if(isspace(c) || c == '\0'){
cur_tok[j] = '\0';
strcpy(toks[i]->val, cur_tok);
if(i == 3 || c == '\0'){
break;
}else{
j=0;
i++;
}
}else{
cur_tok[j] = c;
j++;
}
}
}
command_t *prompt(char *prompt_str){
char *cmd_str;
cmd_kind kind;
command_t *cmd;
tok_t *cmd_toks[4];
int i;
for(i=0; i<4; i++){
cmd_toks[i] = (tok_t *)malloc(sizeof(tok_t));
}
cmd_str = readline(prompt_str);
parse_toks(cmd_str, cmd_toks);
free(cmd_str);
if(strcmp(cmd_toks[0]->val, "search") == 0){
kind = SEARCH;
}else{
kind = -1;
}
free(cmd_toks[0]);
cmd = (command_t *)malloc(sizeof(command_t));
for(i=0; i<3; i++){
strcpy(cmd->args[i], cmd_toks[i+1]->val);
free(cmd_toks[i+1]);
}
cmd->kind = kind;
return cmd;
}
void *promptloop(void *_){
pthread_mutex_lock(¬ify_mut);
while(1){
while(!can_prompt)
pthread_cond_wait(&prompt_cond, ¬ify_mut);
current_cmd = prompt("spotlab> ");
can_prompt = 0;
pthread_cond_signal(¬ify_cond);
pthread_mutex_unlock(¬ify_mut);
}
}
void finish_cmd(){
pthread_mutex_lock(¬ify_mut);
can_prompt = 1;
pthread_cond_signal(&prompt_cond);
pthread_mutex_unlock(¬ify_mut);
}
void run_cmd(command_t *cmd){
switch(cmd->kind){
case SEARCH:
sp_search_create(g_session, cmd->args[0], 0, 5, 0, 5, 0, 5, 0, 10,
SP_SEARCH_STANDARD, &search_complete, NULL);
break;
case PLAY:
default:
finish_cmd();
break;
}
}
// Contains static configuration data
static sp_session_config config = {
.api_version = SPOTIFY_API_VERSION,
.cache_location = "tmp",
.settings_location = "tmp",
.application_key = g_appkey,
.application_key_size = 0, // Set in main()
.user_agent = "Scriptor's Lab",
.callbacks = &callbacks,
// Rest of config MUST be null or otherwise Spotify gets junk data
// This causes proxy errors and more
NULL,
};
int spotify_init(const char *username, const char *password){
sp_error err;
sp_session *sess;
extern const uint8_t g_appkey[];
extern const size_t g_appkey_size;
config.api_version = SPOTIFY_API_VERSION;
config.application_key_size = g_appkey_size;
err = sp_session_create(&config, &sess);
if(SP_ERROR_OK != err){
fprintf(stderr, "failed to create session: %s\n",
sp_error_message(err));
return 2;
}
err = sp_session_login(sess, username, password, 0, NULL);
if (SP_ERROR_OK != err) {
fprintf(stderr, "failed to login: %s\n",
sp_error_message(err));
return 3;
}
g_session = sess;
return 0;
}
int main(){
int next_timeout = 0;
char *username = "Scriptorius";
char *pw;
size_t len = 0;
FILE *fp;
fp = fopen("pass.txt", "r");
if(fp == NULL)
exit(1);
// Password is first line
getline(&pw, &len, fp);
fclose(fp);
// Strip newline
pw[strlen(pw)-1] = '\0';
pthread_mutex_init(¬ify_mut, NULL);
pthread_cond_init(¬ify_cond, NULL);
pthread_cond_init(&prompt_cond, NULL);
if(spotify_init(username, pw) != 0){
fprintf(stderr,"Spotify failed to initialize\n");
exit(-1);
}else{
pthread_t id;
can_prompt = 1;
pthread_create(&id, NULL, promptloop, NULL);
}
pthread_mutex_lock(¬ify_mut);
for(;;){
if(next_timeout == 0){
while(!notify_events && !current_cmd)
pthread_cond_wait(¬ify_cond, ¬ify_mut);
}else{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
// Specify how much time to wait for
ts.tv_sec += next_timeout / 1000;
ts.tv_nsec += (next_timeout % 1000) * 1000000;
while(!notify_events && !current_cmd){
if(pthread_cond_timedwait(¬ify_cond, ¬ify_mut, &ts))
break;
}
}
if(current_cmd){
command_t *cmd = current_cmd;
current_cmd = NULL;
pthread_mutex_unlock(¬ify_mut);
run_cmd(cmd);
free(cmd);
pthread_mutex_lock(¬ify_mut);
}
notify_events = 0;
pthread_mutex_unlock(¬ify_mut);
do{
sp_session_process_events(g_session, &next_timeout);
}while(next_timeout == 0);
pthread_mutex_lock(¬ify_mut);
}
return 0;
}
| 23.469453 | 74 | 0.611865 |
eecc565fd06f77b65b9fec2fcd0fec8f9bd8b100 | 1,278 | c | C | Sorting Algorithms/quickpivode3.c | whoiswelliton/Algorithms_and_Data_Structures | 8aded4a427c68f6c89135fd8c0094dc361bd1538 | [
"MIT"
] | null | null | null | Sorting Algorithms/quickpivode3.c | whoiswelliton/Algorithms_and_Data_Structures | 8aded4a427c68f6c89135fd8c0094dc361bd1538 | [
"MIT"
] | null | null | null | Sorting Algorithms/quickpivode3.c | whoiswelliton/Algorithms_and_Data_Structures | 8aded4a427c68f6c89135fd8c0094dc361bd1538 | [
"MIT"
] | null | null | null | #include<stdio.h>
int Pivode3 (int v[],int ini,int fim)
{
int meio;
meio=(ini+fim)/2;
if (v[ini]<v[fim] && v[ini]>v[meio] || v[ini]>v[fim] && v[ini]<v[meio])
return ini;
if (v[meio]<v[fim] && v[meio]>v[ini] || v[meio]>v[fim] && v[meio]<v[ini])
return meio;
return fim;
}
void quicksort (int v[],int ini,int fim)
{
int esq,dir,pivo,aux;
esq=ini;
dir=fim-1;
if ((fim-ini)<1)
return;
if ((fim-ini)==1)
{
if(v[ini]>v[fim])
{
aux=v[fim];
v[fim]=v[ini];
v[ini]=aux;
}
return;
}
else
{
pivo=Pivode3(v,ini,fim);
if(v[fim]!=v[pivo])
{
aux=v[fim];
v[fim]=v[pivo];
v[pivo]=aux;}
while(esq<dir)
{
if(v[esq]>v[fim])
{
if(v[dir]<v[fim])
{
aux=v[esq];
v[esq]=v[dir];
v[dir]=aux;
esq++;dir--;
}
else
{
dir--;
}
}
else
{
esq++;
}
}
quicksort(v,ini,esq);
quicksort(v,esq,fim);
}
}
int main (void)
{
int v[10]={9,0,8,1,7,2,6,3,5,4},i;
quicksort(v,0,9);
for(i=0;i<10;i++){
printf("%d\t",v[i]);}
return 0;
}
| 17.506849 | 81 | 0.396714 |
eee015888398cd30521985065e9ac978586dee5e | 3,819 | h | C | torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h | xiaohanhuang/pytorch | a31aea8eaa99a5ff72b5d002c206cd68d5467a5e | [
"Intel"
] | 183 | 2018-04-06T21:10:36.000Z | 2022-03-30T15:05:24.000Z | torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h | xiaohanhuang/pytorch | a31aea8eaa99a5ff72b5d002c206cd68d5467a5e | [
"Intel"
] | 818 | 2020-02-07T02:36:44.000Z | 2022-03-31T23:49:44.000Z | torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h | xiaohanhuang/pytorch | a31aea8eaa99a5ff72b5d002c206cd68d5467a5e | [
"Intel"
] | 58 | 2018-06-05T16:40:18.000Z | 2022-03-16T15:37:29.000Z | #pragma once
#ifdef USE_TENSORPIPE
#include <torch/csrc/distributed/rpc/message.h>
#include <torch/csrc/distributed/rpc/tensorpipe_agent.h>
namespace torch {
namespace distributed {
namespace rpc {
struct TORCH_API FaultyTensorPipeRpcBackendOptions
: public TensorPipeRpcBackendOptions {
FaultyTensorPipeRpcBackendOptions(
int num_worker_threads,
float rpc_timeout,
std::string init_method,
std::vector<std::string> messages_to_fail,
std::unordered_map<std::string, float> messages_to_delay,
int num_fail_sends = 0)
: TensorPipeRpcBackendOptions(
num_worker_threads,
optional<std::vector<std::string>>(),
optional<std::vector<std::string>>(),
rpc_timeout,
std::move(init_method)),
messagesToFail(std::move(messages_to_fail)),
messagesToDelay(std::move(messages_to_delay)),
numFailSends(num_fail_sends) {
TORCH_CHECK(numFailSends >= 0, "numFailSends should be non-negative");
}
std::vector<std::string> messagesToFail;
std::unordered_map<std::string, float> messagesToDelay;
int numFailSends;
};
class TORCH_API FaultyTensorPipeAgent : public TensorPipeAgent {
public:
FaultyTensorPipeAgent(
const c10::intrusive_ptr<::c10d::Store>& store,
std::string selfName,
worker_id_t selfId,
int worldSize,
FaultyTensorPipeRpcBackendOptions opts,
std::unordered_map<std::string, DeviceMap> reverseDeviceMaps,
std::vector<c10::Device> devices,
std::unique_ptr<RequestCallback> callback);
// Faulty send function for this class.
c10::intrusive_ptr<JitFuture> send(
const WorkerInfo& to,
c10::intrusive_ptr<Message> message,
const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout,
const DeviceMap& deviceMap = {}) override;
// Add delay to writes
void pipeWrite(
const std::shared_ptr<tensorpipe::Pipe>& pipe,
c10::intrusive_ptr<Message> rpcMessage,
std::vector<c10::Device>&& devices,
std::vector<c10::Stream> streams,
std::function<void(const tensorpipe::Error&)> fn) noexcept override;
protected:
// This function checks the messageTypesToFail_ to determine whether to use
// the faulty send or not.
bool shouldFailMessage(MessageType type) const;
private:
// This function parses the list of strings passed in by the python tests and
// resolves the Message Types that must use the faulty send.
std::vector<MessageType> parseMessagesToFailInput(
const std::vector<std::string>& messagesToFail) const;
// Returns amount of time in seconds to delay sending of the given message
// type.
float getDelayForMessage(MessageType type) const;
// Parse message types that we should inject arbitrary delays for.
std::unordered_map<MessageType, float, std::hash<int>> parseMessagesToDelay(
const std::unordered_map<std::string, float>& messageTypesToDelay) const;
// Number of sends to intentionally fail before allowing one to succeed.
const int numFailSends_;
// Vector of the MessageTypes that we must use the faulty send for. This is
// parsed based on a list of strings passed in by the python tests.
const std::vector<MessageType> messageTypesToFail_;
// Mapping of message types to amount we should delay send for in the ::send()
// function.
std::unordered_map<MessageType, float, std::hash<int>> messageTypesToDelay_;
// Map to track the number of sends we've failed for each RPC.
std::unordered_map<std::string, int> failMessageCountMap_;
// Mutex to guard failMessageCountMap_
std::mutex failMapMutex_;
MessageType messageStringToType(const std::string& messageString) const;
};
} // namespace rpc
} // namespace distributed
} // namespace torch
#endif // USE_TENSORPIPE
| 35.036697 | 80 | 0.72375 |
8ca4fabb1ccea2b359bdf1e3438746ba4533a22c | 1,053 | c | C | brainfuck/lib/my/my_printf.c | matteovol/utils | 364110acfb88142a30ce8a03253c02c590c5b851 | [
"MIT"
] | 1 | 2018-10-25T12:18:05.000Z | 2018-10-25T12:18:05.000Z | brainfuck/lib/my/my_printf.c | matteovol/utils | 364110acfb88142a30ce8a03253c02c590c5b851 | [
"MIT"
] | null | null | null | brainfuck/lib/my/my_printf.c | matteovol/utils | 364110acfb88142a30ce8a03253c02c590c5b851 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2017
** my_printf.c
** File description:
** main funtions for my_printf
*/
#include <stdio.h>
#include <stdarg.h>
#include "my.h"
int call_functions(va_list va, char c)
{
int pass = 1;
int i = 0;
char li[17] = "csiduoxXbpS345679";
void (*disp[17])(va_list) = {disp_char, disp_str, disp_int, disp_int,
disp_uint, disp_oint, disp_xint, disp_xxint,
disp_bint, disp_ptr, disp_sstr, disp_3int,
disp_4int, disp_5int, disp_6int, disp_7int,
disp_9int};
for (i = 0; li[i] != 0; i++) {
if (li[i] == c) {
(*disp[i])(va);
pass = 0;
}
}
if (pass == 1) {
my_putchar('%');
my_putchar(c);
}
}
int check_percentage(int i, char const *str, va_list va)
{
i++;
if (str[i] == '%')
my_putchar('%');
else
call_functions(va, str[i]);
return (i);
}
int my_printf(const char *str, ...)
{
va_list va;
int i = 0;
va_start(va, str);
for (i = 0; str[i] != 0; i++) {
if (str[i] != '%')
my_putchar(str[i]);
else if (str[i] == '%')
i = check_percentage(i, str, va);
}
va_end(va);
return (0);
}
| 17.55 | 70 | 0.586895 |
efc1b889370ccd57d9bd383b569031c059661d95 | 477 | h | C | IMProgressHUD/IMProgressHUD.h | immortal-it/IMProgressHUD | 0c10ee0ee457e0ca95107eac8ce31cb8518c53d0 | [
"MIT"
] | 5 | 2021-03-25T02:38:51.000Z | 2021-11-28T11:10:33.000Z | IMProgressHUD/IMProgressHUD.h | immortal-it/IMProgressHUD | 0c10ee0ee457e0ca95107eac8ce31cb8518c53d0 | [
"MIT"
] | 1 | 2021-12-08T09:52:29.000Z | 2021-12-08T09:52:29.000Z | IMProgressHUD/IMProgressHUD.h | immortal-it/IMProgressHUD | 0c10ee0ee457e0ca95107eac8ce31cb8518c53d0 | [
"MIT"
] | null | null | null | //
// IMProgressHUD.h
// IMProgressHUD
//
// Created by immortal on 2021/3/18.
//
#import <Foundation/Foundation.h>
//! Project version number for IMProgressHUD.
FOUNDATION_EXPORT double IMProgressHUDVersionNumber;
//! Project version string for IMProgressHUD.
FOUNDATION_EXPORT const unsigned char IMProgressHUDVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <IMProgressHUD/PublicHeader.h>
| 25.105263 | 138 | 0.781971 |
483e03526082431cc9b82145d1c4833d4846e033 | 98,837 | c | C | platform/mcu/moc108/mx108/mx378/ip/lmac/src/chan/chan.c | ghsecuritylab/Alios_SDK | edd416e7d2961db42c2100ac2d6237ee527d1aee | [
"Apache-2.0"
] | 2 | 2021-05-28T08:25:33.000Z | 2021-11-17T02:58:50.000Z | platform/mcu/moc108/mx108/mx378/ip/lmac/src/chan/chan.c | ghsecuritylab/Alios_SDK | edd416e7d2961db42c2100ac2d6237ee527d1aee | [
"Apache-2.0"
] | null | null | null | platform/mcu/moc108/mx108/mx378/ip/lmac/src/chan/chan.c | ghsecuritylab/Alios_SDK | edd416e7d2961db42c2100ac2d6237ee527d1aee | [
"Apache-2.0"
] | 5 | 2018-05-23T02:56:10.000Z | 2021-01-02T16:44:09.000Z | /**
****************************************************************************************
*
* @file chan.c
*
* @brief MAC Management channel management implementation.
*
* Copyright (C) RivieraWaves 2011-2016
*
****************************************************************************************
*/
/**
****************************************************************************************
* @addtogroup CHAN
* @{
****************************************************************************************
*/
/**
* INCLUDE FILES
****************************************************************************************
*/
#include "chan.h"
#include "mac_defs.h"
#include "mac_frame.h"
#include "mm.h"
#include "mm_timer.h"
#include "co_endian.h"
#include "sta_mgmt.h"
#include "vif_mgmt.h"
#include "phy.h"
#include "rd.h"
#include "ps.h"
#include "txl_cntrl.h"
#include "txl_frame.h"
#include "rxl_cntrl.h"
#include "hal_machw.h"
#include "td.h"
#include "scan.h"
#include "tpc.h"
#include "me.h"
#if (NX_MDM_VER >= 20)
#include "karst/reg_riu.h"
#endif //(NX_MDM_VER >= 20)
#include "tdls.h"
#include "include.h"
#include "uart_pub.h"
#if (NX_CHNL_CTXT)
/**
* DEBUG (DEFINES, MACROS, ...)
****************************************************************************************
*/
/// Enable or disable TBTT Switch scheduling debug
#define CHAN_DEBUG_TBTT_EN (0)
/**
* Debug Configuration for CHAN Module
* 0 - Traces are disabled
* 1:3 - Level of verbosity
*/
#define CHAN_DEBUG_TRACES_EN (0)
#if (CHAN_DEBUG_TRACES_EN)
/// Function used to print module information
#define CHAN_DEBUG_PRINT(lvl, format, ...) \
do { \
if (lvl <= CHAN_DEBUG_TRACES_EN) \
{ \
} \
} while (0);
#else
#define CHAN_DEBUG_PRINT(lvl, format, ...)
#endif //(CHAN_DEBUG_TRACES_EN)
/**
* DEFINES
****************************************************************************************
*/
#define CHAN_ROC_SCAN_PENDING_MASK (CO_BIT(CHAN_ENV_ROC_BIT) | CO_BIT(CHAN_ENV_SCAN_BIT))
/**
* GLOBAL VARIABLES
****************************************************************************************
*/
/// MM Channel module context variable
struct chan_env_tag chan_env;
/// Pool of channel contexts
struct chan_ctxt_tag chan_ctxt_pool[CHAN_CHAN_CTXT_CNT];
/**
* PRIVATE FUNCTIONS DECLARATION
****************************************************************************************
*/
static void chan_switch_start(struct chan_ctxt_tag *p_chan_entry);
static void chan_switch_channel(void);
/**
* PRIVATE FUNCTIONS DEFINITION
****************************************************************************************
*/
/**
****************************************************************************************
* @brief Compute number of slots elapsed between time1 and time2. If time1 > time2,
* returned value will be a positive value.
*
* @param[in] time1 Time value in us
* @param[in] time2 Time value in us
*
* @return Computed number of slots (@see CHAN_SLOT_DURATION_US value)
****************************************************************************************
*/
static int16_t chan_get_nb_slots(uint32_t time1, uint32_t time2)
{
// Get time difference in us
int32_t diff = time1 - time2;
// Return time difference in slots
return (int16_t)(diff / CHAN_SLOT_DURATION_US);
}
#if (NX_P2P)
/**
****************************************************************************************
* @brief Loop over the traffic channels in order to find a channel linked with a P2P VIF,
* on which we have to switch with priority.
* It takes care of the number of slots remaining for this channel and it
* also prevent from switching on a channel on which the GO device is not present.
*
* @return P2P channel on which we have to switch.
****************************************************************************************
*/
static struct chan_ctxt_tag *chan_get_next_p2p_chan(void)
{
// Next P2P channel context entry, none by default
struct chan_ctxt_tag *p_p2p_chan_entry = NULL;
// Highest found number of remaining slots
uint8_t high_rem_slots = 0;
// Check if at least one P2P VIF has been created
if (vif_mgmt_env.nb_p2p_vifs)
{
// Get first scheduled channel
struct chan_ctxt_tag *p_chan_entry = (struct chan_ctxt_tag *)co_list_pick(&chan_env.list_sched_ctxt);
// Loop on scheduled traffic channels
while (p_chan_entry)
{
// Number of available slots
uint8_t ava_slots;
do
{
// Check if there is a P2P presence on the channel
if (!p_chan_entry->nb_p2p_presence)
{
break;
}
if (p_chan_entry->nb_rem_slots > p_chan_entry->nb_res_slots)
{
ava_slots = p_chan_entry->nb_rem_slots - p_chan_entry->nb_res_slots;
}
else
{
ava_slots = 0;
}
// Check if channel has enough available slots, if not do not switch on it
if (ava_slots < CHAN_MIN_PRES_DUR)
{
break;
}
// Try to jump on channel with higher number of available slots
if (ava_slots > high_rem_slots)
{
high_rem_slots = ava_slots;
p_p2p_chan_entry = p_chan_entry;
}
} while (0);
// Get next scheduled channel
p_chan_entry = (struct chan_ctxt_tag *)p_chan_entry->list_hdr.next;
}
}
CHAN_DEBUG_PRINT(3, "chan_get_next_p2p_chan -> %d\n",
(p_p2p_chan_entry != NULL) ? p_p2p_chan_entry->idx : 0xFF);
return (p_p2p_chan_entry);
}
#endif //(NX_P2P)
/**
****************************************************************************************
* @brief Select the next traffic channel after following events:
* - Start of new Channel Distribution Event
* - End of TBTT Presence due to end of Beacon/UC/MC/BC reception/transmission
* - End of Channel Duration
* - P2P Go Start/End of Absence (if P2P features are supported)
* Try to jump first on P2P channels on which a GO device is present in order to be
* sure to use available slots outside NOA periods.
*
* @return Channel context entry of next traffic channel
****************************************************************************************
*/
static struct chan_ctxt_tag *chan_get_next_chan(void)
{
// By default, stay on current channel
struct chan_ctxt_tag *p_next_chan_entry = chan_env.current_channel;
// Get first element of the TBTT switch list
struct chan_tbtt_tag *p_tbtt_entry = (struct chan_tbtt_tag *)co_list_pick(&chan_env.list_tbtt);
// Get current time
uint32_t current_time = ke_time();
// Counter
uint8_t counter;
// Number of remaining slots
uint8_t nb_rem_slots;
#if (NX_P2P)
struct chan_ctxt_tag *p_p2p_chan_entry;
#endif //(NX_P2P)
do
{
if (chan_env.current_channel)
{
// Check if a TBTT presence is in progress
if (p_tbtt_entry && (p_tbtt_entry->status == CHAN_TBTT_PRESENCE))
{
// Stay on current channel
break;
}
// Check that enough slots are remaining in the current CDE
if (!hal_machw_time_cmp(current_time + (CHAN_MIN_PRES_DUR * CHAN_SLOT_DURATION_US), chan_env.tmr_cde.time))
{
// Stay on current channel
break;
}
#if (NX_P2P)
// Check if there is a channel used for P2P on which we could switch with priority
p_p2p_chan_entry = chan_get_next_p2p_chan();
/*
* If we have found a P2P channel, we switch on it with priority whatever the status of current channel
*/
if (p_next_chan_entry->nb_linked_p2p_vif || !p_p2p_chan_entry)
#endif //(NX_P2P)
{
// Check if end of channel timer is running
if (p_next_chan_entry->status == CHAN_WAITING_END)
{
// Wait for end of current channel
break;
}
}
}
#if (NX_P2P)
else
{
p_p2p_chan_entry = chan_get_next_p2p_chan();
}
#endif //(NX_P2P)
// Check if next TBTT will occur during current CDE
if (p_tbtt_entry && hal_machw_time_cmp(p_tbtt_entry->time, chan_env.tmr_cde.time))
{
// Number of slots that can be used by the channel
uint8_t ava_slots;
// Get Channel Context for the TBTT
p_next_chan_entry = vif_info_tab[p_tbtt_entry->vif_index].chan_ctxt;
// Sanity Check
ASSERT_ERR(p_next_chan_entry);
// Check if TBTT will occur in less than minimal presence duration
if (!hal_machw_time_cmp(current_time + (CHAN_MIN_PRES_DUR * CHAN_SLOT_DURATION_US), p_tbtt_entry->time))
{
// Jump on TBTT channel
break;
}
#if (NX_P2P)
if (p_p2p_chan_entry)
{
p_next_chan_entry = p_p2p_chan_entry;
break;
}
// If TBTT channel is used for P2P, do not jump (p_p2p_chan_entry would not have been NULL)
if (!p_next_chan_entry->nb_linked_p2p_vif)
#endif //(NX_P2P)
{
if (p_next_chan_entry->nb_rem_slots >= p_next_chan_entry->nb_res_slots)
{
ava_slots = p_next_chan_entry->nb_rem_slots - p_next_chan_entry->nb_res_slots;
}
else
{
ava_slots = 0;
}
// Check if channel context has enough slots to reach the TBTT
if (ava_slots >= chan_get_nb_slots(p_tbtt_entry->time, current_time))
{
// Jump on TBTT channel
break;
}
}
}
#if (NX_P2P)
else
{
if (p_p2p_chan_entry)
{
// Switch on P2P channel
p_next_chan_entry = p_p2p_chan_entry;
break;
}
}
#endif //(NX_P2P)
// No need to switch for a special operation, get channels with higher remaining number of slots
nb_rem_slots = 0;
for (counter = 0; counter < CHAN_TRAF_CTXT_CNT; counter++)
{
// Get channel context
struct chan_ctxt_tag *p_chan_entry = &chan_ctxt_pool[counter];
if ((p_chan_entry->status != CHAN_NOT_SCHEDULED) &&
(p_chan_entry->nb_rem_slots >= nb_rem_slots))
{
#if (NX_P2P)
if (p_p2p_chan_entry == NULL)
{
// Do not consider P2P channels here
if (p_chan_entry->nb_linked_p2p_vif)
{
continue;
}
}
#endif //(NX_P2P)
p_next_chan_entry = p_chan_entry;
nb_rem_slots = p_chan_entry->nb_rem_slots;
}
}
} while (0);
CHAN_DEBUG_PRINT(3, "chan_get_next_chan -> %d\n", p_next_chan_entry->idx);
// Sanity check
ASSERT_ERR(p_next_chan_entry);
return (p_next_chan_entry);
}
/**
****************************************************************************************
* @brief Update the number of remaining slots for provided channel context.
* This function compute duration elapsed since last CDE event.
*
* @param[in] p_chan_entry Channel context entry
* @param[in] current_time Current Time, allowing to compute number of used slots
****************************************************************************************
*/
static void chan_upd_nb_rem_slots(struct chan_ctxt_tag *p_chan_entry, uint32_t current_time)
{
// Get number of slots since last CDE event
uint8_t nb_slots = chan_get_nb_slots(current_time, chan_env.cde_time);
// Update remaining number of slots
p_chan_entry->nb_rem_slots -= co_min(nb_slots, p_chan_entry->nb_rem_slots);
}
/**
****************************************************************************************
* @brief Update the status of a provided channel context and program the Channel Context
* Operation timer (Switch or End of Channel) accordingly with the new state.
*
* Few rules applies:
* - When next state is CHAN_GOTO_IDLE, timer duration is set to CHAN_SWITCH_TO_DUR
* only for traffic channel (no switch timeout for RoC/Scan channels)
* - Timer expiration time is not updated is next state is CHAN_WAIT_NOA_CFM
* - If next state is CHAN_WAITING_END, end of channel timer is always
* programmed for RoC/Scan channels using the channel duration.
* - If next state is CHAN_WAITING_END, end of channel timer is programmed for
* traffic channel is following condition are true:
* -> CDE is used
* -> Enough slots are remaining in order to compute end of channel expiration
* time
* If timer is not programmed, next state is updated to CHAN_PRESENT.
*
* @param[in] p_chan_entry Channel Context entry
* @param[in] next_status New status of the provided channel context
****************************************************************************************
*/
static void chan_upd_ctxt_status(struct chan_ctxt_tag *p_chan_entry, uint8_t next_status)
{
uint32_t tmr_exp_time = 0;
uint32_t current_time = ke_time();
CHAN_DEBUG_PRINT(2, "chan_upd_ctxt_status i=%d, s=%d\n", p_chan_entry->idx, next_status);
if (next_status == CHAN_GOTO_IDLE)
{
// Do not start timer for timeout if RoC or Scan channel
if (p_chan_entry->idx < CHAN_TRAF_CTXT_CNT)
{
tmr_exp_time = current_time + CHAN_SWITCH_TO_DUR;
}
}
else if (next_status == CHAN_WAITING_END)
{
do
{
CHAN_DEBUG_PRINT(3, " -> rem=%d, res=%d\n",
p_chan_entry->nb_rem_slots, p_chan_entry->nb_res_slots);
if (p_chan_entry->idx < CHAN_TRAF_CTXT_CNT)
{
// Number of slots to be used for End of Channel Timer programming
uint8_t ava_slots;
// Program end of channel timer only if CDE is running
if (chan_env.nb_sched_ctxt < 2)
{
next_status = CHAN_PRESENT;
break;
}
// Number of slots available for the channel
ava_slots = (p_chan_entry->nb_rem_slots >= p_chan_entry->nb_res_slots)
? (p_chan_entry->nb_rem_slots - p_chan_entry->nb_res_slots) : 0;
/*
* Do not program end of channel timer, if remaining number of slots is too low
* and wait for next TBTT switch or CDE event
*/
if (ava_slots < CHAN_MIN_PRES_DUR)
{
next_status = CHAN_PRESENT;
break;
}
// Update CDE time in order to be sure to not program in the past
chan_env.cde_time = current_time;
tmr_exp_time = chan_env.cde_time + (ava_slots * CHAN_SLOT_DURATION_US);
}
else
{
tmr_exp_time = current_time + (p_chan_entry->nb_rem_slots * CHAN_SLOT_DURATION_US);
}
} while (0);
}
else if (next_status == CHAN_NOT_PROG)
{
}
// Update the status
p_chan_entry->status = next_status;
if (tmr_exp_time == 0)
{
// Do not clear timer if switch channel operation is not over
if (next_status != CHAN_WAIT_NOA_CFM)
{
mm_timer_clear(&chan_env.tmr_ctxt_op);
}
}
else
{
// Program operation timer
chan_env.tmr_ctxt_op.env = p_chan_entry;
// Program the timer
//os_printf("tmr_ctxt_op:%x\r\n", &chan_env.tmr_ctxt_op.list_hdr);
mm_timer_set(&chan_env.tmr_ctxt_op, tmr_exp_time);
}
}
/**
****************************************************************************************
* @brief Compute number of slots that have to be reserved for TBTT presence periods during
* the next CDE.
*
* @param[in] p_vif_entry VIF entry
* @param[in] p_chan_entry Channel Context entry
****************************************************************************************
*/
static void chan_update_reserved_slots(struct vif_info_tag *p_vif_entry,
struct chan_ctxt_tag *p_chan_entry)
{
uint32_t bcn_int;
uint8_t nb_tbtt;
#if NX_BEACONING
if (p_vif_entry->type == VIF_STA)
#endif
{
// Get peer AP informations
struct sta_info_tag *p_sta_entry = &sta_info_tab[p_vif_entry->u.sta.ap_id];
bcn_int = p_sta_entry->bcn_int;
}
#if NX_BEACONING
else
{
bcn_int = (uint32_t)p_vif_entry->u.ap.bcn_int << 10;
}
#endif
// Deduce the number of TBTTs
nb_tbtt = co_max(1, (chan_env.cde_dur_us / bcn_int));
// Increase number of slots reserved for TBTT
p_chan_entry->nb_res_slots += nb_tbtt * CHAN_MAX_TBTT_PRES_DUR;
}
/**
****************************************************************************************
* @brief Distribute slots available during a Channel Distribution Event between all the
* scheduled channel contexts. This distribution is based on last status generated
* by the Traffic Detection module.
*
* Current version of the algorithm is a very basic one.
* - A VIF on which no traffic has been detected over the last Traffic
* Detection interval will receive only CHAN_MAX_TBTT_PRES_DUR slots for its
* linked channel.
* - Else CHAN_VIF_NB_SLOTS will be allocated for its channel.
* Number of slots not distributed to VIFs with no traffic are then equally distributed
* between VIFs on which Traffic has been detected.
*
* This algorithm can be replaced by a smarter one based on several statistics.
*
* The number of slots allocated for a channel is stored in the nb_slots value of
* each scheduled Channel Context Entry.
****************************************************************************************
*/
static void chan_distribute_slots(void)
{
// Number of VIFs with a scheduled channel context
uint8_t nb_vifs = 0;
// Number of VIFs om which traffic has been detected
uint8_t nb_vifs_traffic = 0;
// Number of slots for VIFs on which no traffic was detected
uint16_t nb_slots_nt;
// Number of slots that can be shared between slots with detected traffic
uint16_t nb_slots_ava = 0;
// VIF Entry
struct vif_info_tag *p_vif_entry = vif_mgmt_first_used();
CHAN_DEBUG_PRINT(4, "chan_distribute_slots\n");
/*
* ---------------------------------------------------------
* Check Traffic Status
* ---------------------------------------------------------
*/
while (p_vif_entry)
{
// Channel Context linked with the VIF
struct chan_ctxt_tag *p_chan_entry = p_vif_entry->chan_ctxt;
if (p_chan_entry)
{
nb_vifs++;
if (td_get_status(p_vif_entry->index) || !p_vif_entry->active)
{
nb_vifs_traffic++;
}
// Reset number of slots
p_chan_entry->nb_slots = 0;
p_chan_entry->nb_res_slots = 0;
}
// Get next VIF
p_vif_entry = (struct vif_info_tag *)(p_vif_entry->list_hdr.next);
}
// Sanity check
ASSERT_WARN(nb_vifs == (chan_env.cde_dur_us / (CHAN_VIF_NB_SLOTS * CHAN_SLOT_DURATION_US)));
/*
* ---------------------------------------------------------
* Distribute slots accordingly with the traffic status
* ---------------------------------------------------------
*/
// Check if all VIFs have the same traffic status
if ((nb_vifs_traffic == 0) || (nb_vifs == nb_vifs_traffic))
{
nb_slots_nt = CHAN_VIF_NB_SLOTS;
}
else
{
nb_slots_nt = CHAN_MAX_TBTT_PRES_DUR;
// Deduce number of total additional slots available for VIFs with traffic
nb_slots_ava = (nb_vifs - nb_vifs_traffic) * (CHAN_VIF_NB_SLOTS - CHAN_MAX_TBTT_PRES_DUR);
// Get number of additional slots per VIF
nb_slots_ava /= nb_vifs_traffic;
}
p_vif_entry = vif_mgmt_first_used();
while (p_vif_entry)
{
// Channel Context linked with the VIF
struct chan_ctxt_tag *p_chan_entry = p_vif_entry->chan_ctxt;
if (p_chan_entry)
{
if (td_get_status(p_vif_entry->index) || !p_vif_entry->active)
{
p_chan_entry->nb_slots += (CHAN_VIF_NB_SLOTS + nb_slots_ava);
}
else
{
p_chan_entry->nb_slots += nb_slots_nt;
}
p_chan_entry->nb_rem_slots = p_chan_entry->nb_slots;
// Update the number of reserved slots
chan_update_reserved_slots(p_vif_entry, p_chan_entry);
CHAN_DEBUG_PRINT(4, " -> i=%d, s=%d r=%d\n", p_chan_entry->idx, p_chan_entry->nb_slots, p_chan_entry->nb_res_slots);
}
// Get next VIF
p_vif_entry = (struct vif_info_tag *)(p_vif_entry->list_hdr.next);
}
}
/**
****************************************************************************************
* @brief Program the timer used for delaying Scan/RoC operations.
* chan_conn_less_delay_evt is called upon timer expiration
****************************************************************************************
*/
static void chan_conn_less_delay_prog(void)
{
// Set status bit
chan_env.status |= CO_BIT(CHAN_ENV_DELAY_PROG_BIT);
// Set timer
mm_timer_set(&chan_env.tmr_conn_less, ke_time() + CHAN_CONN_LESS_DELAY);
}
/**
****************************************************************************************
* @brief Callback called upon Connection Less Delay timer expiration.
* If both Scan and RoC are scheduled, start RoC.
*
* @param[in] env Should be a NULL pointer, do not use it
****************************************************************************************
*/
static void chan_conn_less_delay_evt(void *env)
{
struct chan_ctxt_tag *p_conn_less_chan = NULL;
// In waiting, start RoC in priority
if (chan_env.status & CO_BIT(CHAN_ENV_ROC_WAIT_BIT))
{
// Sanity check, no RoC should be in progress here
ASSERT_ERR((chan_env.status & CO_BIT(CHAN_ENV_ROC_BIT)) == 0);
// Clear status
chan_env.status &= ~CO_BIT(CHAN_ENV_ROC_WAIT_BIT);
// Set RoC bit status
chan_env.status |= CO_BIT(CHAN_ENV_ROC_BIT);
// Modify channel on which we will switch
p_conn_less_chan = &chan_ctxt_pool[CHAN_ROC_CTXT_IDX];
}
// else start Scan
else if (chan_env.status & CO_BIT(CHAN_ENV_SCAN_WAIT_BIT))
{
// Sanity check, no Scan should be in progress here
ASSERT_ERR((chan_env.status & CO_BIT(CHAN_ENV_SCAN_BIT)) == 0);
// Clear status
chan_env.status &= ~CO_BIT(CHAN_ENV_SCAN_WAIT_BIT);
// Set Scan bit status
chan_env.status |= CO_BIT(CHAN_ENV_SCAN_BIT);
// Modify channel on which we will switch
p_conn_less_chan = &chan_ctxt_pool[CHAN_SCAN_CTXT_IDX];
}
if (p_conn_less_chan)
{
if (!chan_env.chan_switch)
{
// Trigger switch procedure
chan_switch_start(p_conn_less_chan);
}
}
}
/**
****************************************************************************************
* @brief Callback called upon Channel Distribution Event timer expiration or when a new
* CDE has to be started.
* Its purpose is to update the bandwidth allocation status for each scheduled
* channel context based on last traffic detection information.
* Then it starts a new CDE.
*
* Note: Start of new CDE is skipped in following conditions,
* - CDE is not needed anymore (less than two scheduled channels)
* - RoC or Scan is in progress
* - A timeout has been detected during current channel switch.
* In the last two situations, CDE will be restarted once pending procedures will be
* over.
*
* @param[in] env If env pointer is not NULL, it means that CDE has been restarted
* at the end of switch procedure, can directly switch on first
* CDE channel
****************************************************************************************
*/
static void chan_cde_evt(void *env)
{
// Get Current Time
uint32_t current_time = ke_time();
// Next channel
struct chan_ctxt_tag *p_chan_entry = NULL;
CHAN_DEBUG_PRINT(2, "chan_cde_evt n=%d s=%d\n", chan_env.nb_sched_ctxt, chan_env.status);
do
{
// Check that CDE is still needed
if (chan_env.nb_sched_ctxt < 2)
{
break;
}
// Check if a RoC or a Scan procedure is in progress
if (chan_env.status & (CO_BIT(CHAN_ENV_ROC_BIT) | CO_BIT(CHAN_ENV_SCAN_BIT)))
{
// CDE will be restart at the end of the scan/roc procedure
break;
}
// Check if a switch timeout has occurred
if (chan_env.status & CO_BIT(CHAN_ENV_TIMEOUT_BIT))
{
// CDE will be restarted once switch procedure will be over
break;
}
// Program end of CDE - Has to be done before next operations
os_printf("t3:%d\r\n", current_time + chan_env.cde_dur_us);
mm_timer_set(&chan_env.tmr_cde, current_time + chan_env.cde_dur_us);
// Update CDE time
chan_env.cde_time = current_time;
// Distribute bandwidth between the channel contexts
chan_distribute_slots();
if (chan_env.current_channel)
{
// Update current channel context status
chan_upd_ctxt_status(chan_env.current_channel, CHAN_NOT_PROG);
}
// Get first channel context of the CDE
p_chan_entry = chan_get_next_chan();
if (env == NULL)
{
// Jump on channel
chan_switch_start(p_chan_entry);
}
else
{
// Update chan_switch value
chan_env.chan_switch = p_chan_entry;
}
} while (0);
}
#if (NX_HW_SCAN)
/**
****************************************************************************************
* @brief Send a channel survey to the host by using the MM_CHANNEL_SURVEY_IND message.
*
****************************************************************************************
*/
static void chan_send_survey_ind(void)
{
// Get latest scanned channel
struct scan_chan_tag const *p_scan_chan = scan_get_chan();
// Allocate a MM_CHANNEL_SURVEY_IND message
struct mm_channel_survey_ind *p_ind = KE_MSG_ALLOC(MM_CHANNEL_SURVEY_IND,
TASK_API, TASK_MM,
mm_channel_survey_ind);
#if (NX_MDM_VER >= 20)
uint8_t read_counter = 10;
#endif //(NX_MDM_VER >= 20)
// Fill the parameters
p_ind->freq = p_scan_chan->freq;
p_ind->chan_time_ms = ((p_scan_chan->flags & SCAN_PASSIVE_BIT) ? SCAN_PASSIVE_DURATION : SCAN_ACTIVE_DURATION) / 1000;
// Fill the parameters - Time values read in register are in units of us (-> /1000)
p_ind->chan_time_busy_ms = nxmac_edca_cca_busy_get() / 1000;
p_ind->noise_dbm = 0;
#if (NX_MDM_VER >= 20)
/*
* If read noise value is 0, value is not valid because of re-sync between AGC clock and
* AHB clock. Register value is updated once AGC is in listen state.
*/
while (read_counter--)
{
// During scan, config used is 1x1, noise has to be read to antenna 0
int8_t reg_noise = (int8_t)riu_inbdpow20pnoisedbm0_getf();
if (reg_noise != 0)
{
p_ind->noise_dbm = reg_noise;
break;
}
}
#endif //(NX_MDM_VER >= 20)
// Send the indication
ke_msg_send(p_ind);
}
#endif //(NX_HW_SCAN)
/**
****************************************************************************************
* @brief Send MM_REMAIN_ON_CHANNEL_EXP_IND message to the upper layers.
*
* @param[in] Pointer to the RoC Channel Context
****************************************************************************************
*/
static void chan_send_roc_exp_ind(struct chan_ctxt_tag *roc_chan_ctxt)
{
// Inform the host that the remain on channel has expired
struct mm_remain_on_channel_exp_ind *ind = KE_MSG_ALLOC(MM_REMAIN_ON_CHANNEL_EXP_IND,
roc_chan_ctxt->taskid, TASK_MM,
mm_remain_on_channel_exp_ind);
ind->chan_ctxt_index = roc_chan_ctxt->idx;
ind->vif_index = roc_chan_ctxt->vif_index;
ke_msg_send(ind);
}
/**
****************************************************************************************
* @brief Callback called upon Channel Operation Timer expiration.
* This timer is used for two main purposes:
* - Detect a timeout during a channel switch (too much time can be taken by HW when
* going to IDLE depending for instance of rate/length of current TXed packet)
* If timer expires while channel context state is CHAN_GOTO_IDLE or
* CHAN_WAIT_NOA_CFM, we keep in mind that the TO has happened.
* Will be processed once switch procedure is over.
* - Detect that the number of remaining slots for a channel has been drained.
*
* @param[in] env Channel for which timer was programmed
****************************************************************************************
*/
static void chan_ctxt_op_evt(void *env)
{
struct chan_ctxt_tag *p_chan_entry = (struct chan_ctxt_tag *)env;
GLOBAL_INT_DECLARATION();
CHAN_DEBUG_PRINT(2, "chan_ctxt_op_evt i=%d, s=%d nb=%d\n",
p_chan_entry->idx, p_chan_entry->status, chan_env.nb_sched_ctxt);
switch (p_chan_entry->status)
{
case (CHAN_GOTO_IDLE):
case (CHAN_WAIT_NOA_CFM):
{
// Set timeout bit
chan_env.status |= CO_BIT(CHAN_ENV_TIMEOUT_BIT);
} break;
case (CHAN_WAITING_END):
{
if (p_chan_entry->idx < CHAN_TRAF_CTXT_CNT)
{
// Reset Channel Context status
p_chan_entry->status = CHAN_NOT_PROG;
if (chan_env.nb_sched_ctxt == 1)
{
// Switch to default channel
p_chan_entry = (struct chan_ctxt_tag *)co_list_pick(&chan_env.list_sched_ctxt);
}
else if (chan_env.nb_sched_ctxt > 1)
{
// Current time
uint32_t current_time = ke_time();
// Update number of remaining slots for current channel
chan_upd_nb_rem_slots(p_chan_entry, current_time);
// Update CDE Time
chan_env.cde_time = current_time;
// Get next channel context of the CDE
p_chan_entry = chan_get_next_chan();
}
// Jump on channel
chan_switch_start(p_chan_entry);
}
else
{
#if (NX_POWERSAVE)
// Power Save can be used
GLOBAL_INT_DISABLE();
ps_env.prevent_sleep &= ~PS_SCAN_ONGOING;
GLOBAL_INT_RESTORE();
nxmac_pwr_mgt_setf(chan_env.pm);
#endif //(NX_POWERSAVE)
chan_env.current_channel = NULL;
if (p_chan_entry->idx == CHAN_SCAN_CTXT_IDX)
{
#if (NX_HW_SCAN)
// Send a channel occupation report to the host
chan_send_survey_ind();
#endif //(NX_HW_SCAN)
// Clear Scan in progress status
chan_env.status &= ~CO_BIT(CHAN_ENV_SCAN_BIT);
// Indicate the end of scanning
ke_msg_send_basic(MM_SCAN_CHANNEL_END_IND, TASK_SCAN, TASK_NONE);
}
else if (p_chan_entry->idx == CHAN_ROC_CTXT_IDX)
{
if (p_chan_entry->taskid != TASK_MM)
{
#if TDLS_ENABLE
if (p_chan_entry->taskid == TASK_TDLS)
{
tdls_send_chan_switch_base_ind(p_chan_entry);
}
else
#endif
{
chan_send_roc_exp_ind(p_chan_entry);
}
}
else
{
// Clear beacon detection status bit
chan_env.status &= ~CO_BIT(CHAN_ENV_BCN_DETECT_BIT);
}
// Clear ROC in progress status
chan_env.status &= ~CO_BIT(CHAN_ENV_ROC_BIT);
}
// Update the index
p_chan_entry->idx = CHAN_CTXT_UNUSED;
// Check if Delay timer has to be restarted
if (chan_env.status & (CO_BIT(CHAN_ENV_ROC_WAIT_BIT) | CO_BIT(CHAN_ENV_SCAN_WAIT_BIT)))
{
chan_conn_less_delay_prog();
}
else
{
// Clear Delay timer status bit
chan_env.status &= ~CO_BIT(CHAN_ENV_DELAY_PROG_BIT);
}
if (chan_env.nb_sched_ctxt == 1)
{
// Switch to default channel
p_chan_entry = (struct chan_ctxt_tag *)co_list_pick(&chan_env.list_sched_ctxt);
chan_switch_start(p_chan_entry);
}
else if (chan_env.nb_sched_ctxt > 1)
{
// Restart CDE
chan_cde_evt(NULL);
}
else
{
// Request to go to IDLE again
mm_force_idle_req();
// Host can now modify the IDLE state
mm_back_to_host_idle();
}
}
} break;
default:
{
// Nothing to do
} break;
}
}
/**
****************************************************************************************
* @brief Function called once SW and HW are ready for a channel switch.
* It checks if a timeout has been detected during the procedure:
* - If yes and if CDE is used, we restart a CDE and we directly jump on the
* indicated next channel.
****************************************************************************************
*/
static void chan_pre_switch_channel(void)
{
// Check if we have to change the next channel
struct chan_ctxt_tag *p_new_chan_switch = NULL;
// Stop switch timeout timer
mm_timer_clear(&chan_env.tmr_ctxt_op);
//os_printf("chan_pre_switch_channel\r\n");
// Check if a Timeout has occurred during switch
if (chan_env.status & CO_BIT(CHAN_ENV_TIMEOUT_BIT))
{
// Check if CDE is used
if (chan_env.nb_sched_ctxt >= 2)
{
if (chan_env.chan_switch)
{
// Clear status of the current switch channel
chan_env.chan_switch->status = CHAN_NOT_PROG;
// CDE will be restarted soon, cancel switch
chan_env.chan_switch = NULL;
}
}
// Clear timeout bit
chan_env.status &= ~CO_BIT(CHAN_ENV_TIMEOUT_BIT);
}
// If a Scan Request is pending, jump on Scan channel
if (chan_env.status & CO_BIT(CHAN_ENV_SCAN_BIT))
{
// Modify channel on which we will switch
p_new_chan_switch = &chan_ctxt_pool[CHAN_SCAN_CTXT_IDX];
}
// If a RoC Request is pending, jump on RoC Channel
else if (chan_env.status & CO_BIT(CHAN_ENV_ROC_BIT))
{
// Modify channel on which we will switch
p_new_chan_switch = &chan_ctxt_pool[CHAN_ROC_CTXT_IDX];
}
if (p_new_chan_switch)
{
if (chan_env.chan_switch)
{
// Clear status of the current switch channel
chan_env.chan_switch->status = CHAN_NOT_PROG;
}
chan_env.chan_switch = p_new_chan_switch;
}
if (chan_env.chan_switch == NULL)
{
// Check if CDE is used
if (chan_env.nb_sched_ctxt >= 2)
{
// Restart CDE and get first channel - Do not start switch on first CDE channel
chan_cde_evt((void *)1);
}
else if (chan_env.nb_sched_ctxt == 1)
{
chan_env.chan_switch = (struct chan_ctxt_tag *)co_list_pick(&chan_env.list_sched_ctxt);
}
}
if (chan_env.chan_switch != NULL)
{
// Finally go on new channel
chan_switch_channel();
}
}
/**
****************************************************************************************
* @brief Function called during the Channel Switch procedure each time a NULL packet used
* for Absence indication is confirmed.
* The cfm_cnt counter value in the chan environment is decremented. When its value
* comes to 0, we can switch on a new channel.
****************************************************************************************
*/
static void chan_tx_cfm(void *dummy, uint32_t status)
{
CHAN_DEBUG_PRINT(3, "chan_tx_cfm s=%d cnt=%d\n", (chan_env.chan_switch != NULL), chan_env.cfm_cnt);
// Sanity check - We shall be waiting for at least 1 TX confirmation
ASSERT_ERR(chan_env.cfm_cnt);
// Decrease the number of confirmations still awaited
chan_env.cfm_cnt--;
// Check if all confirmations have been received
if (chan_env.cfm_cnt == 0)
{
// Request to go to IDLE again, so that we can perform the channel switch
mm_force_idle_req();
// Switch on new channel
chan_pre_switch_channel();
}
}
/**
****************************************************************************************
* @brief For each VIF linked with the channel context we are switching on, we send a NULL
* frame with the PM bit set to 0 in order to indicate our presence.
****************************************************************************************
*/
static void chan_notify_presence(void)
{
struct vif_info_tag *p_vif_entry = vif_mgmt_first_used();
struct chan_ctxt_tag *p_cur_ctxt = chan_env.current_channel;
#if (NX_POWERSAVE)
// First check if STA VIFs on this channel are active or not
if ((ps_env.ps_on) && !(ps_env.prevent_sleep & PS_PSM_PAUSED))
{
// STA VIFs are not active, so no need to indicate our presence
return;
}
#endif //(NX_POWERSAVE)
// Reset the PwrMgt bit in all frames
nxmac_pwr_mgt_setf(0);
// Go through all the active VIFs
while (p_vif_entry != NULL)
{
// Check if VIF is attached to this channel context
if (p_vif_entry->chan_ctxt == p_cur_ctxt)
{
// Check if the VIF is of STA type, and associated
if ((p_vif_entry->type == VIF_STA) && p_vif_entry->active)
{
#if (NX_P2P)
bool send = true;
// If VIF is for P2P, check that GO is present
if (p_vif_entry->p2p)
{
send = p2p_info_tab[p_vif_entry->p2p_index].is_go_present;
}
if (send)
#endif //(NX_P2P)
{
// Send a NULL frame to indicate to the AP that we are leaving the channel
txl_frame_send_null_frame(p_vif_entry->u.sta.ap_id, NULL, NULL);
}
}
}
// Go to next VIF
p_vif_entry = vif_mgmt_next(p_vif_entry);
}
}
/**
****************************************************************************************
* @brief For each VIF linked with the channel context we are leaving, we send a NULL
* frame with the PM bit set to 1 in order to indicate our absence until next TBTT.
****************************************************************************************
*/
static int chan_notify_absence(void)
{
int cfm_cnt = 0;
struct vif_info_tag *p_vif_entry = vif_mgmt_first_used();
struct chan_ctxt_tag *cur;
uint8_t prev_status;
// First check if we are on a channel
if (chan_env.current_channel == NULL)
{
return 0;
}
cur = chan_env.current_channel;
#if (NX_POWERSAVE)
// First check if STA VIFs on this channel are active or not
if ((ps_env.ps_on) && !(ps_env.prevent_sleep & PS_PSM_PAUSED))
{
// STA VIFs are already in PS-mode, so no need to indicate our absence
return 0;
}
#endif //(NX_POWERSAVE)
// Set the PwrMgt bit in all frames
nxmac_pwr_mgt_setf(1);
// Go through all the active VIFs
while (p_vif_entry != NULL)
{
// Check if VIF is attached to this channel context
if (p_vif_entry->chan_ctxt == cur)
{
// Check if the VIF is of STA type, and associated
if ((p_vif_entry->type == VIF_STA) && p_vif_entry->active &&
(p_vif_entry->u.sta.ap_id != INVALID_STA_IDX))
{
#if (NX_P2P)
bool send = true;
// If VIF is for P2P, check that GO is present
if (p_vif_entry->p2p)
{
send = p2p_info_tab[p_vif_entry->p2p_index].is_go_present;
}
if (send)
#endif //(NX_P2P)
{
// Send a NULL frame to indicate to the AP that we are leaving the channel
// update status to allow frame transmission
prev_status = cur->status;
cur->status = CHAN_SENDING_NOA;
if (txl_frame_send_null_frame(p_vif_entry->u.sta.ap_id, chan_tx_cfm, NULL) == CO_OK)
{
// We expect one more confirmation
cfm_cnt++;
}
cur->status = prev_status;
}
}
}
// Go to next VIF
p_vif_entry = vif_mgmt_next(p_vif_entry);
}
// Save the number of TX confirmation expected
chan_env.cfm_cnt = cfm_cnt;
// Check if packets have been programmed
if (cfm_cnt)
{
// Update next_channel state
chan_upd_ctxt_status(chan_env.chan_switch, CHAN_WAIT_NOA_CFM);
// NULL frames programmed, we need to reactivate the HW
mm_active();
}
return (cfm_cnt);
}
/**
****************************************************************************************
* @brief This callback is called once HW has gone to the IDLE state during a channel
* switch procedure.
****************************************************************************************
*/
static void chan_goto_idle_cb(void)
{
//os_printf("chan_goto_idle_cb s=%d\r\n", (chan_env.chan_switch != NULL));
do
{
// Flush all the TX and RX queues
mm_force_idle_req();
/*
* Check if a timeout has been raised during go to idle operation and if current channel
* still exists.
*/
if (chan_env.current_channel &&
!(chan_env.status & CO_BIT(CHAN_ENV_TIMEOUT_BIT)))
{
// Check if we need to notify the absence of the local VIFs to the peers
if (chan_notify_absence())
{
break;
}
}
// Switch on a new channel
chan_pre_switch_channel();
} while (0);
}
/**
****************************************************************************************
* @brief Send CHANNEL_PRE_SWITCH_IND message to the upper layers.
* No more packets should be pushed for transmission after reception of this message.
*
* @param[in] old_chan_ctxt Channel context we are about to leave
****************************************************************************************
*/
static void chan_send_pre_switch_ind(struct chan_ctxt_tag *old_chan_ctxt)
{
if (old_chan_ctxt->idx != CHAN_SCAN_CTXT_IDX)
{
// Allocate the indication structure
struct mm_channel_pre_switch_ind *ind = KE_MSG_ALLOC(MM_CHANNEL_PRE_SWITCH_IND, TASK_API,
TASK_MM, mm_channel_pre_switch_ind);
// Fill-in the parameters
ind->chan_index = old_chan_ctxt->idx;
// Send the message
ke_msg_send(ind);
}
}
/**
****************************************************************************************
* @brief Send CHANNEL_SWITCH_IND message to the upper layers.
* * Packets can be pushed for transmission after reception of this message.
*
* @param[in] new_chan_ctxt Channel context on which we have switched
****************************************************************************************
*/
static void chan_send_switch_ind(struct chan_ctxt_tag *new_chan_ctxt)
{
if (new_chan_ctxt->idx != CHAN_SCAN_CTXT_IDX)
{
// Allocate the indication structure
struct mm_channel_switch_ind *ind = KE_MSG_ALLOC(MM_CHANNEL_SWITCH_IND, TASK_API,
TASK_MM, mm_channel_switch_ind);
// Fill-in the parameters
ind->chan_index = new_chan_ctxt->idx;
// If ROC triggered internally, do not notify driver
#if TDLS_ENABLE
ind->roc = ((new_chan_ctxt->idx == CHAN_ROC_CTXT_IDX) && (new_chan_ctxt->taskid != TASK_MM) && (new_chan_ctxt->taskid != TASK_TDLS));
ind->roc_tdls = new_chan_ctxt->roc_tdls;
#else
ind->roc = ((new_chan_ctxt->idx == CHAN_ROC_CTXT_IDX) && (new_chan_ctxt->taskid != TASK_MM));
ind->roc_tdls = 0;
#endif
ind->vif_index = new_chan_ctxt->vif_index;
// Send the message
ke_msg_send(ind);
}
}
#if (NX_P2P_GO)
/**
****************************************************************************************
* @brief Check if NOA has to be started/updated in following configuration:
* - A GO VIF is active in parallel with a STA VIF
* -> NOA start time will be the next TBTT time for the STA connection
* TODO [LT] - Start Time should move if TBTT moves
* -> NOA duration will depends on the bandwidth allocated for the STA link.
*
* @param[in] p_tbtt_entry TBTT Information structure for the P2P GO VIF
****************************************************************************************
*/
static void chan_p2p_noa_manage(struct chan_tbtt_tag *p_tbtt_entry)
{
// Get VIF interface
struct vif_info_tag *p_vif_entry = &vif_info_tab[p_tbtt_entry->vif_index];
// Get P2P information
struct p2p_info_tag *p_p2p_entry = &p2p_info_tab[p_vif_entry->p2p_index];
// Get next STA TBTT entry
struct chan_tbtt_tag *p_sta_tbtt_entry = (struct chan_tbtt_tag *)p_tbtt_entry->list_hdr.next;
if (p_sta_tbtt_entry)
{
// Get next STA VIF entry
struct vif_info_tag *p_sta_vif_entry = &vif_info_tab[p_sta_tbtt_entry->vif_index];
// Check if at least one beacon has been received (would indicate that tbtt time is correct)
if (p_sta_vif_entry->u.sta.bcn_rcved)
{
// Get STA Channel
struct chan_ctxt_tag *p_sta_chan_entry = p_sta_vif_entry->chan_ctxt;
// Absence Duration
uint32_t duration_us = p_sta_chan_entry->nb_slots * CHAN_SLOT_DURATION_US;
// Get beacon interval
uint32_t go_bcn_int = (uint32_t)p_vif_entry->u.ap.bcn_int << 10;
if (chan_get_nb_slots(p_tbtt_entry->time + go_bcn_int, p_sta_tbtt_entry->time) < p_sta_chan_entry->nb_slots)
{
/*
* GO TBBT presence will occurs during the absence period. Due to NOA priority rules, we will have to
* be present for it. Increase absence duration in order to well to absent during the STA channel duration.
*/
duration_us += CHAN_MAX_TBTT_PRES_DUR * CHAN_SLOT_DURATION_US;
}
if (!p_p2p_entry->is_noa_bcn)
{
// Get channel context used by GO connection
struct chan_ctxt_tag *p_chan_entry = p_vif_entry->chan_ctxt;
// Get beacon interval used by peer AP
uint32_t sta_bcn_int = sta_info_tab[p_sta_vif_entry->u.sta.ap_id].bcn_int;
// Start NOA (Concurrent Mode)
p_chan_entry->p2p_noa_idx = p2p_go_noa_start(p_vif_entry, true, P2P_NOA_CONTINUOUS_COUNTER, false,
sta_bcn_int, duration_us,
p_sta_tbtt_entry->time);
// Sanity check
ASSERT_ERR(p_chan_entry->p2p_noa_idx < P2P_NOA_NB_MAX);
}
else
{
// Check if duration has been updated
if (duration_us != p_p2p_entry->noa[0].noa_dur_us)
{
p2p_go_noa_update_duration(p_vif_entry, 0, duration_us);
}
}
}
}
}
#endif //(NX_P2P_GO)
/**
****************************************************************************************
* @brief Manually increase the next TBTT time after a collision with another TBTT has
* been detected. The priority of the TBTT is increased in order to avoid being
* delayed once again in the next collision check.
*
* @param[in] p_tbtt_entry TBBT Entry that has to be delayed
****************************************************************************************
*/
static void chan_tbtt_delay(struct chan_tbtt_tag *p_tbtt_entry)
{
// Get associated VIF entry
struct vif_info_tag *p_vif_entry = &vif_info_tab[p_tbtt_entry->vif_index];
// Beacon Interval in us
uint32_t bcn_int_us;
CHAN_DEBUG_PRINT(2, "chan_tbtt_delay i=%d\n", p_tbtt_entry->vif_index);
#if NX_BEACONING
if (p_vif_entry->type == VIF_STA)
#endif
{
// Get peer AP information
struct sta_info_tag *p_sta_entry = &sta_info_tab[p_vif_entry->u.sta.ap_id];
bcn_int_us = p_sta_entry->bcn_int;
}
#if NX_BEACONING
else
{
bcn_int_us = (uint32_t)p_vif_entry->u.ap.bcn_int << 10;
}
#endif
// Update TBTT switch time
p_tbtt_entry->time += bcn_int_us;
if (p_tbtt_entry->priority < CHAN_TBTT_PRIORITY_MAX)
{
// Increase priority
p_tbtt_entry->priority++;
}
}
/**
****************************************************************************************
* @brief Detect time conflict between two provided TBTT presence.
* It is considered that the TBTT presence duration is CHAN_MAX_TBTT_PRES_DUR.
*
* @param[in] p_tbtt_entry1 First TBTT entry to be checked
* @param[in] p_tbtt_entry2 Second TBTT entry to be checked
*
* @return true if a collision has been detected, else false
****************************************************************************************
*/
static bool chan_tbtt_detect_conflict(struct chan_tbtt_tag *p_tbtt_entry1,
struct chan_tbtt_tag *p_tbtt_entry2)
{
// Indicate if a there is a conflict between the two contexts
bool conflict;
// Start/End times
uint32_t start1, start2, end1, end2;
start1 = p_tbtt_entry1->time;
start2 = p_tbtt_entry2->time;
end1 = (start1 + CHAN_MAX_TBTT_PRES_DUR * CHAN_SLOT_DURATION_US);
end2 = (start2 + CHAN_MAX_TBTT_PRES_DUR * CHAN_SLOT_DURATION_US);
/**
* Conflict is detected in following cases:
* (1) -----------------------
* | TBTT Presence 1 |
* ----------------------------------
* | TBTT Presence 2 |
* -----------------------
*
* (2) -----------------------
* | TBTT Presence 1 |
* -----------------------------------
* | TBTT Presence 2 |
* -----------------------
*
* (3) -----------------------
* | TBTT Presence 1 |
* -----------------------------------
* | TBTT Presence 2 |
* -----------------------------------
*
* (4) -----------------------------------
* | TBTT Presence 1 |
* -----------------------------------
* | TBTT Presence 2 |
* -----------------------
*
* => if (((start1 >= start2) && (start1 <= end2)) ||
* ((start2 >= start1) && (start2 <= end1)))
*/
if ((!hal_machw_time_cmp(start1, start2) && !hal_machw_time_cmp(end2, start1)) ||
(!hal_machw_time_cmp(start2, start1) && !hal_machw_time_cmp(end1, start2)))
{
conflict = true;
}
else
{
conflict = false;
}
return (conflict);
}
/**
****************************************************************************************
* @brief Try to insert the provided TBTT entry in the list of TBTTs. TBTT are sorted
* by chronological order. The function takes care of possible collisions between
* the different TBTT presence.
*
* @param[in] p_tbtt_entry TBTT entry to be inserted
****************************************************************************************
*/
static void chan_tbtt_insert(struct chan_tbtt_tag *p_tbtt_entry)
{
// Indicate if the element can be inserted
bool insert = true;
// Number of elements to delay
uint8_t nb_delayed = 0;
// Get the list of TBTT
struct co_list *list_tbtt = &chan_env.list_tbtt;
// First element to delay
struct chan_tbtt_tag *p_delay_elem = NULL;
// Element used to insert the TBTT structure at the good position in list_tbtt
struct chan_tbtt_tag *p_prev_elem = NULL;
// Element extracted from the list
struct chan_tbtt_tag *p_elem = (struct chan_tbtt_tag *)co_list_pick(list_tbtt);
/*---------------------------------------------------------------------
* FIND TBTT POSITION
*---------------------------------------------------------------------*/
while (p_elem)
{
// Sanity checks, TBTT entry should not be already present in the list
ASSERT_ERR(p_elem != p_tbtt_entry);
// Check if the element is already in progress
if (p_elem->status != CHAN_TBTT_PRESENCE)
{
if (chan_tbtt_detect_conflict(p_tbtt_entry, p_elem))
{
if (p_tbtt_entry->priority > p_elem->priority)
{
if (!p_delay_elem)
{
p_delay_elem = p_elem;
}
// list_elem will be delayed
nb_delayed++;
}
else
{
// Element cannot be inserted...
insert = false;
// ... And will be delayed
p_delay_elem = p_tbtt_entry;
nb_delayed = 1;
break;
}
}
else
{
// If both value were the same, a conflict would have been detected
if (p_tbtt_entry->time < p_elem->time)
{
// p_tbtt_entry can be inserted before p_elem, so after p_prev_elem
break;
}
else
{
// Loop again in order to check conflict with next element
p_prev_elem = p_elem;
}
}
}
else
{
if ((p_tbtt_entry->time < p_elem->time) ||
chan_tbtt_detect_conflict(p_tbtt_entry, p_elem))
{
// Element cannot be inserted...
insert = false;
// ... And will be delayed
p_delay_elem = p_tbtt_entry;
nb_delayed = 1;
break;
}
else
{
p_prev_elem = p_elem;
}
}
p_elem = (struct chan_tbtt_tag *)p_elem->list_hdr.next;
}
/*-----------------------------------------------------------------
* PROCESS TBTT STRUCTURES THAT HAVE TO BE DELAYED
*-----------------------------------------------------------------*/
// Insert all delayed events
while (nb_delayed--)
{
// Sanity checks
ASSERT_ERR(p_delay_elem);
if (p_delay_elem != p_tbtt_entry)
{
if (p_delay_elem->status == CHAN_TBTT_PROG)
{
// Stop TBTT Switch Timer
mm_timer_clear(&chan_env.tmr_tbtt_switch);
// Reset the status
p_delay_elem->status = CHAN_TBTT_NOT_PROG;
}
// Try to extract element from the list of contexts
co_list_extract(list_tbtt, &p_delay_elem->list_hdr);
}
// Add it in the list of delayed contexts
co_list_push_back(&chan_env.list_tbtt_delay, &p_delay_elem->list_hdr);
p_delay_elem = (struct chan_tbtt_tag *)p_delay_elem->list_hdr.next;
}
if (insert)
{
/*-----------------------------------------------------------------
* INSERT THE TBTT STRUCTURE AT FOUND POSITION
*-----------------------------------------------------------------*/
co_list_insert_after(list_tbtt, &p_prev_elem->list_hdr, &p_tbtt_entry->list_hdr);
}
}
/**
****************************************************************************************
* @brief Callback called upon expiration of the TBTT switch timer.
* Jump on the appropriate channel.
*
* @param[in] env TBTT entry linked with the channel on which we have to jump
****************************************************************************************
*/
static void chan_tbtt_switch_evt(void *env)
{
// TBTT Switch Information structure
struct chan_tbtt_tag *p_tbtt_entry = (struct chan_tbtt_tag *)env;
// Get associated VIF Information Entry
struct vif_info_tag *p_vif_entry = &vif_info_tab[p_tbtt_entry->vif_index];
// Get associated channel context
struct chan_ctxt_tag *p_chan_entry = p_vif_entry->chan_ctxt;
// Get current time
uint32_t current_time = ke_time();
CHAN_DEBUG_PRINT(3, "chan_tbtt_switch_evt i=%d t=%d s=%d n=%d\n",
p_tbtt_entry->vif_index, p_tbtt_entry->time, chan_env.status, chan_env.nb_sched_ctxt);
do
{
// Check if CDE is used
if (chan_env.nb_sched_ctxt < 2)
{
break;
}
// Check if a RoC or a Scan procedure is in progress
if (chan_env.status & (CO_BIT(CHAN_ENV_ROC_BIT) | CO_BIT(CHAN_ENV_SCAN_BIT)))
{
break;
}
// Check if a Channel Switch on another channel is already in progress
if (chan_env.chan_switch && (chan_env.chan_switch != p_chan_entry))
{
break;
}
#if (NX_P2P_GO)
// Check if VIF is a P2P GO one
if (p_vif_entry->p2p && (p_vif_entry->type == VIF_AP))
{
// Check if NOA has to be inserted/updated in the beacon
chan_p2p_noa_manage(p_tbtt_entry);
}
#endif //(NX_P2P_GO)
// Reset priority
p_tbtt_entry->priority = 0;
// Update number of remaining slots for current channel
chan_upd_nb_rem_slots(chan_env.current_channel, current_time);
// Update number of reserved slots
p_chan_entry->nb_res_slots -= co_min(p_chan_entry->nb_res_slots, CHAN_MAX_TBTT_PRES_DUR);
// Update CDE time
chan_env.cde_time = current_time;
// Update TBTT Switch status
p_tbtt_entry->status = CHAN_TBTT_PRESENCE;
// We are already switching on the channel
if (!chan_env.chan_switch)
{
// Switch on TBTT channel
chan_switch_start(p_chan_entry);
}
} while (0);
}
/**
****************************************************************************************
* @brief Insert the provided TBTT entry in the list of TBTTs. TBTT are sorted
* by chronological order. The function takes care of possible collisions between
* the different TBTT presence.
*
* @param[in] p_tbtt_entry TBTT entry to be inserted
****************************************************************************************
*/
static void chan_tbtt_schedule(struct chan_tbtt_tag *p_tbtt_entry)
{
// First element of list_tbtt once the context has been inserted
struct chan_tbtt_tag *first_elem;
if (p_tbtt_entry)
{
#if (CHAN_DEBUG_TBTT_EN)
first_elem = (struct chan_tbtt_tag *)co_list_pick(&chan_env.list_tbtt);
while (first_elem)
{
first_elem = (struct chan_tbtt_tag *)(first_elem->list_hdr.next);
}
#endif //(CHAN_DEBUG_TBTT_EN)
// Try to insert the element in the list of scheduled TBTTs
chan_tbtt_insert(p_tbtt_entry);
// Process delayed TBTT
while (!co_list_is_empty(&chan_env.list_tbtt_delay))
{
struct chan_tbtt_tag *p_delay_elem
= (struct chan_tbtt_tag *)co_list_pop_front(&chan_env.list_tbtt_delay);
// Delay the TBTT
chan_tbtt_delay(p_delay_elem);
// Try to insert it back
chan_tbtt_insert(p_delay_elem);
}
#if (CHAN_DEBUG_TBTT_EN)
first_elem = (struct chan_tbtt_tag *)co_list_pick(&chan_env.list_tbtt);
while (first_elem)
{
first_elem = (struct chan_tbtt_tag *)(first_elem->list_hdr.next);
}
#endif //(CHAN_DEBUG_TBTT_EN)
}
// Get first element of list of scheduled TBTTs
first_elem = (struct chan_tbtt_tag *)co_list_pick(&chan_env.list_tbtt);
// Check if a timer has/needs to be run
if (first_elem && (first_elem->status == CHAN_TBTT_NOT_PROG))
{
// If switch is close enough in the future, start pre-switch
if (hal_machw_time_cmp(first_elem->time, ke_time() + CHAN_MIN_TIMER_VALUE))
{
chan_tbtt_switch_evt(first_elem);
}
else
{
chan_env.tmr_tbtt_switch.env = first_elem;
// Update status
first_elem->status = CHAN_TBTT_PROG;
os_printf("t4:%d\r\n", first_elem->time);
mm_timer_set(&chan_env.tmr_tbtt_switch, first_elem->time);
}
}
}
/**
*****************************************************************************************
* @brief Send a MM_FORCE_IDLE_REQ message to TASK_MM in order to require the HW to enter in
* IDLE mode
****************************************************************************************
*/
static void chan_send_force_idle(void)
{
struct mm_force_idle_req *req = KE_MSG_ALLOC(MM_FORCE_IDLE_REQ,
TASK_MM, TASK_NONE,
mm_force_idle_req);
// Set the request parameters
req->cb = chan_goto_idle_cb;
// Send the request
ke_msg_send(req);
}
/**
****************************************************************************************
* @brief Switch from chan_env.current_channel to chan_env.chan_switch.
* HW is supposed to be in IDLE mode when entering in this function.
* current_channel value is replaced by chan_switch value and chan_switch is set to
* NULL.
****************************************************************************************
*/
static void chan_switch_channel(void)
{
struct chan_ctxt_tag *p_chan_entry = chan_env.chan_switch;
struct mm_chan_ctxt_add_req *param = &p_chan_entry->channel;
//os_printf("chan_switch_channel i=%d\n", p_chan_entry->idx);
// Program the RF with the new channel
phy_set_channel(param->band, param->type, param->prim20_freq, param->center1_freq,
param->center2_freq, PHY_PRIM);
tpc_update_tx_power(param->tx_power);
// Set the basic rates in the HW according to the band
nxmac_rates_set(mm_env.basic_rates[param->band]);
// Indicate to the upper layers that a channel switch has occurred
chan_send_switch_ind(p_chan_entry);
// Store the current channel to the environment
chan_env.current_channel = p_chan_entry;
// Channel switch is now complete
chan_env.chan_switch = NULL;
// Update channel status
chan_upd_ctxt_status(p_chan_entry, CHAN_WAITING_END);
// Check if we switch to an operating channel (Traffic or RoC), or a scanning one
if (p_chan_entry->idx != CHAN_SCAN_CTXT_IDX)
{
if (p_chan_entry->idx != CHAN_ROC_CTXT_IDX)
{
// Notify to the peer devices that we are back
chan_notify_presence();
}
if (p_chan_entry->idx < CHAN_TRAF_CTXT_CNT)
{
// Go through list of used VIFs
struct vif_info_tag *p_vif_entry = vif_mgmt_first_used();
while (p_vif_entry)
{
// Check if VIF is on new channel
if (p_vif_entry->chan_ctxt == p_chan_entry)
{
#if (NX_TD)
// Keep in mind that we have been present on the traffic channel
td_env[p_vif_entry->index].has_active_chan = true;
#endif //(NX_TD)
// Try to send pending frames
vif_mgmt_send_postponed_frame(p_vif_entry);
}
// Get next VIF
p_vif_entry = (struct vif_info_tag *)co_list_next(&p_vif_entry->list_hdr);
}
}
}
else
{
// Clear CCA busy register (see MM_CHANNEL_SURVEY_IND use)
nxmac_edca_cca_busy_set(0);
//os_printf("MM_SCAN_CHANNEL_START_IND\r\n");
// Confirm the channel switch to the scanning module
ke_msg_send_basic(MM_SCAN_CHANNEL_START_IND, TASK_SCAN, TASK_NONE);
}
#if (NX_POWERSAVE)
if (p_chan_entry->idx >= CHAN_SCAN_CTXT_IDX)
{
GLOBAL_INT_DECLARATION();
// Disable PS while we are scanning
GLOBAL_INT_DISABLE();
ps_env.prevent_sleep |= PS_SCAN_ONGOING;
GLOBAL_INT_RESTORE();
// No PM bit set in ProbeReq
chan_env.pm = nxmac_pwr_mgt_getf();
nxmac_pwr_mgt_setf(0);
}
#endif //(NX_POWERSAVE)
// Go to active state
mm_active();
}
/**
****************************************************************************************
* @brief Initiate channel switch procedure in order to jump to indicated channel.
* If we already are present on provided channel or if a switch procedure is
* already in progress, nothing is done.
* Else requests the HW to go in IDLE state.
*
* @param[in] p_chan_entry Channel on which switch is required
****************************************************************************************
*/
static void chan_switch_start(struct chan_ctxt_tag *p_chan_entry)
{
//os_printf("chan_switch_start%d\r\n", p_chan_entry->idx);
do
{
// Check if we already are on the specified channel
if (chan_env.current_channel == p_chan_entry)
{
if ((chan_env.nb_sched_ctxt > 1) && (p_chan_entry->idx < CHAN_TRAF_CTXT_CNT))
{
// If CDE is used, update channel status
chan_upd_ctxt_status(p_chan_entry, CHAN_WAITING_END);
}
break;
}
// Check if we are currently switching
if (chan_env.chan_switch)
{
break;
}
if (chan_env.current_channel)
{
// Indicate to the upper layers that a channel switch will occur soon
chan_send_pre_switch_ind(chan_env.current_channel);
}
// Save the pointer to the ongoing channel switch
chan_env.chan_switch = p_chan_entry;
// Set Channel Context status
chan_upd_ctxt_status(p_chan_entry, CHAN_GOTO_IDLE);
// Send force_idle_req message
chan_send_force_idle();
} while(0);
}
/**
****************************************************************************************
* @brief Go through the list of channel contexts in order to check if a channel contexts
* using exactly the same parameters than those provided by the host is
* currently used.
*
* @param[in] p_add_req Parameters of the channel to be added
* @param[in|out] idx Pointer to the found channel context index
*
* @return true if a channel context with the same parameters has been found, else false
****************************************************************************************
*/
static bool chan_check_chan(struct mm_chan_ctxt_add_req const *p_add_req, uint8_t *p_idx)
{
int chan_idx;
bool found = false;
// Go through the list of channel contexts
for (chan_idx = 0; chan_idx < CHAN_TRAF_CTXT_CNT; chan_idx++)
{
struct chan_ctxt_tag *p_chan_entry = &chan_ctxt_pool[chan_idx];
// Only consider added channel contexts
if (p_chan_entry->idx != CHAN_CTXT_UNUSED)
{
// Compare received parameters with channel ones (exclude tx_power)
if (!memcmp(p_add_req, &p_chan_entry->channel,
offsetof(struct mm_chan_ctxt_add_req, tx_power)))
{
// Return the found channel index
*p_idx = chan_idx;
// And escape the loop
found = true;
break;
}
}
}
return (found);
}
/**
****************************************************************************************
* @brief Initialize all parameters stored in a channel context entry.
*
* @param[in] p_chan_entry Channel context entry to be initialazed
****************************************************************************************
*/
static void chan_ctxt_init(struct chan_ctxt_tag *p_chan_entry)
{
// Reset the channel information
memset(p_chan_entry, 0, sizeof(struct chan_ctxt_tag));
p_chan_entry->taskid = TASK_NONE;
p_chan_entry->idx = CHAN_CTXT_UNUSED;
}
/**
* PUBLIC FUNCTIONS DEFINITION
****************************************************************************************
*/
void chan_init(void)
{
int i;
CHAN_DEBUG_PRINT(1, "chan_init\n");
// Initialize the CHAN environment
memset(&chan_env, 0, sizeof(chan_env));
// Initialize the free channel context list
for (i = 0; i < CHAN_CHAN_CTXT_CNT; i++)
{
struct chan_ctxt_tag *p_chan_entry = &chan_ctxt_pool[i];
chan_ctxt_init(p_chan_entry);
if (i < NX_CHAN_CTXT_CNT)
{
// Add it to the free channel context list
co_list_push_back(&chan_env.list_free_ctxt, &p_chan_entry->list_hdr);
}
else if (i == CHAN_SCAN_CTXT_IDX)
{
p_chan_entry->channel.center2_freq = 0;
p_chan_entry->channel.type = PHY_CHNL_BW_20;
}
}
// Set TBTT Switch Timer callback
chan_env.tmr_tbtt_switch.cb = chan_tbtt_switch_evt;
// Set Channel Distribution Event Timer callback and environment
chan_env.tmr_cde.cb = chan_cde_evt;
chan_env.tmr_cde.env = NULL;
// Set Channel Switch Timer callback
chan_env.tmr_ctxt_op.cb = chan_ctxt_op_evt;
// Set Connection Less Delay Time callback
chan_env.tmr_conn_less.cb = chan_conn_less_delay_evt;
}
#if (NX_HW_SCAN)
void chan_scan_req(uint8_t band, uint16_t freq, int8_t pwr, uint32_t duration_us,
uint8_t vif_index)
{
// Get channel context used for Scan
struct chan_ctxt_tag *p_scan_chan = &chan_ctxt_pool[CHAN_SCAN_CTXT_IDX];
ASSERT_ERR(p_scan_chan->idx == CHAN_CTXT_UNUSED);
p_scan_chan->idx = CHAN_SCAN_CTXT_IDX;
p_scan_chan->taskid = TASK_NONE;
p_scan_chan->channel.band = band;
p_scan_chan->channel.center1_freq = freq;
p_scan_chan->channel.prim20_freq = freq;
p_scan_chan->channel.tx_power = pwr;
p_scan_chan->vif_index = vif_index;
p_scan_chan->status = CHAN_NOT_PROG;
p_scan_chan->nb_rem_slots = duration_us / CHAN_SLOT_DURATION_US;
// Update status
chan_env.status |= CO_BIT(CHAN_ENV_SCAN_WAIT_BIT);
// Check if we can start the Connection Less Delay Timer
if (!(chan_env.status & CO_BIT(CHAN_ENV_DELAY_PROG_BIT)))
{
chan_conn_less_delay_prog();
}
}
#endif //(NX_HW_SCAN)
uint8_t chan_roc_req(struct mm_remain_on_channel_req const *req, ke_task_id_t taskid)
{
// Returned status
uint8_t status = CO_FAIL;
// Get context allocated for the remain of channel operation
struct chan_ctxt_tag *p_roc_chan = &chan_ctxt_pool[CHAN_ROC_CTXT_IDX];
CHAN_DEBUG_PRINT(1, "chan_roc_req o=%d f=%d d=%d\n",
req->op_code, req->prim20_freq, req->duration_ms);
// Check the operation code
switch (req->op_code)
{
case (MM_ROC_OP_START):
{
// Check if a remain on channel is in progress
if (p_roc_chan->idx != CHAN_CTXT_UNUSED)
{
break;
}
p_roc_chan->idx = CHAN_ROC_CTXT_IDX;
p_roc_chan->channel.band = req->band;
p_roc_chan->channel.type = req->type;
p_roc_chan->channel.prim20_freq = req->prim20_freq;
p_roc_chan->channel.center1_freq = req->center1_freq;
p_roc_chan->channel.center2_freq = req->center2_freq;
p_roc_chan->taskid = taskid;
p_roc_chan->status = CHAN_NOT_PROG;
p_roc_chan->nb_rem_slots = (req->duration_ms * 1000) / CHAN_SLOT_DURATION_US;
p_roc_chan->vif_index = req->vif_index;
p_roc_chan->channel.tx_power = req->tx_power;
// If internal RoC (use for beacon detection), do not delay
#if TDLS_ENABLE
if ((taskid == TASK_MM) || (taskid == TASK_TDLS))
#else
if (taskid == TASK_MM)
#endif
{
chan_env.status |= CO_BIT(CHAN_ENV_ROC_BIT);
#if TDLS_ENABLE
if (taskid == TASK_TDLS)
{
p_roc_chan->roc_tdls = true;
}
#endif
if (!chan_env.chan_switch)
{
// Trigger switch procedure
chan_switch_start(p_roc_chan);
}
}
else
{
// Update status
chan_env.status |= CO_BIT(CHAN_ENV_ROC_WAIT_BIT);
// Check if we can start the Connection Less Delay Timer
if (!(chan_env.status & CO_BIT(CHAN_ENV_DELAY_PROG_BIT)))
{
chan_conn_less_delay_prog();
}
}
status = CO_OK;
} break;
case (MM_ROC_OP_CANCEL):
{
// Check if a remain on channel context is used
if (p_roc_chan->idx == CHAN_CTXT_UNUSED)
{
break;
}
#if TDLS_ENABLE
if (taskid == TASK_TDLS)
{
p_roc_chan->roc_tdls = false;
}
#endif
// React depending on the current context state
switch (p_roc_chan->status)
{
case (CHAN_NOT_PROG):
{
// Clear wait RoC status bit
chan_env.status &= ~CO_BIT(CHAN_ENV_ROC_WAIT_BIT);
#if TDLS_ENABLE
if (taskid == TASK_TDLS)
{
tdls_send_chan_switch_base_ind(p_roc_chan);
}
else
#endif
{
// Send RoC Expiration Indication
chan_send_roc_exp_ind(p_roc_chan);
}
} break;
case (CHAN_GOTO_IDLE):
case (CHAN_WAIT_NOA_CFM):
{
// Clear RoC in progress status bit
chan_env.status &= ~CO_BIT(CHAN_ENV_ROC_BIT);
chan_env.chan_switch = NULL;
} break;
case (CHAN_WAITING_END):
{
// Clear channel context operation timer and...
mm_timer_clear(&chan_env.tmr_ctxt_op);
// ...Act as if the End of Operation timer had expired
chan_ctxt_op_evt((void *)p_roc_chan);
} break;
default:
{
} break;
}
// Reset the index
p_roc_chan->idx = CHAN_CTXT_UNUSED;
// Check if we have to stop the delay timer
if (((chan_env.status & CO_BIT(CHAN_ENV_DELAY_PROG_BIT)) != 0) &&
((chan_env.status & CO_BIT(CHAN_ENV_SCAN_WAIT_BIT)) == 0))
{
chan_env.status &= ~CO_BIT(CHAN_ENV_DELAY_PROG_BIT);
mm_timer_clear(&chan_env.tmr_conn_less);
// Clear Delay timer status bit
chan_env.status &= ~CO_BIT(CHAN_ENV_DELAY_PROG_BIT);
}
status = CO_OK;
} break;
default:
break;
}
return (status);
}
uint8_t chan_ctxt_add(struct mm_chan_ctxt_add_req const *p_add_req, uint8_t *idx)
{
// Returned status
uint8_t status = CO_FAIL;
CHAN_DEBUG_PRINT(1, "chan_ctxt_add\n");
do
{
// Check if a channel with the provided parameters as already been added
if (chan_check_chan(p_add_req, idx))
{
// Channel already exists, allocation is successful
status = CO_OK;
break;
}
else
{
// Allocate a channel context from the list
struct chan_ctxt_tag *p_chan_entry
= (struct chan_ctxt_tag *)co_list_pop_front(&chan_env.list_free_ctxt);
if (p_chan_entry == NULL)
{
break;
}
// Compute the index
*idx = p_chan_entry->idx = CO_GET_INDEX(p_chan_entry, chan_ctxt_pool);
// Initialize the operating channel context structure
p_chan_entry->channel.band = p_add_req->band;
p_chan_entry->channel.type = p_add_req->type;
p_chan_entry->channel.center1_freq = p_add_req->center1_freq;
p_chan_entry->channel.center2_freq = p_add_req->center2_freq;
p_chan_entry->channel.prim20_freq = p_add_req->prim20_freq;
p_chan_entry->channel.tx_power = p_add_req->tx_power;
// Allocation is successful
status = CO_OK;
}
} while (0);
return (status);
}
void chan_ctxt_del(uint8_t chan_idx)
{
// Retrieve the channel context
struct chan_ctxt_tag *p_chan_entry = &chan_ctxt_pool[chan_idx];
CHAN_DEBUG_PRINT(1, "chan_ctxt_del chan_idx=%d\n", chan_idx);
// Sanity checks - An unused channel should not be freed
ASSERT_ERR(p_chan_entry->idx != CHAN_CTXT_UNUSED);
// Sanity checks - No more VIFs should be linked with the channel
ASSERT_ERR(p_chan_entry->nb_linked_vif == 0);
// Push back the channel context in the free list
co_list_push_back(&chan_env.list_free_ctxt, &p_chan_entry->list_hdr);
// Reset channel context information
chan_ctxt_init(p_chan_entry);
}
void chan_ctxt_link(uint8_t vif_idx, uint8_t chan_idx)
{
struct chan_ctxt_tag *p_chan_entry = &chan_ctxt_pool[chan_idx];
struct vif_info_tag *p_vif_entry = &vif_info_tab[vif_idx];
CHAN_DEBUG_PRINT(1, "chan_ctxt_link vif_idx=%d, chan_idx=%d\n", vif_idx, chan_idx);
// Sanity checks
ASSERT_ERR(p_vif_entry->chan_ctxt == NULL);
ASSERT_ERR(p_chan_entry->idx != CHAN_CTXT_UNUSED);
// Channel context will now be linked to VIF
p_vif_entry->chan_ctxt = p_chan_entry;
// Increase number of VIFs linked with the channel context
p_chan_entry->nb_linked_vif++;
// Update the CDE duration
chan_env.cde_dur_us += (CHAN_VIF_NB_SLOTS * CHAN_SLOT_DURATION_US);
// Schedule the channel if first link
if (p_chan_entry->nb_linked_vif == 1)
{
// Update channel status
p_chan_entry->status = CHAN_NOT_PROG;
// Increase number of scheduled contexts
chan_env.nb_sched_ctxt++;
// Insert the context in the list of scheduled contexts
co_list_push_back(&chan_env.list_sched_ctxt, &p_chan_entry->list_hdr);
// Check that no switch is pending
if (!chan_env.chan_switch)
{
// Check that a RoC or a Scan is not in progress
if ((chan_env.status & CHAN_ROC_SCAN_PENDING_MASK) == 0)
{
if (chan_env.nb_sched_ctxt == 1)
{
// Start switching on channel
chan_switch_start(p_chan_entry);
}
else
{
// Start a new Channel Distribution Event
chan_cde_evt(NULL);
}
}
}
else
{
// Cancel switch, a new channel will be chosen once pre-switch will be over
chan_env.chan_switch->status = CHAN_NOT_PROG;
// CDE will be restarted soon, cancel switch
chan_env.chan_switch = NULL;
}
}
#if (NX_P2P)
// If VIF is a P2P VIF, schedule the channel
if (p_vif_entry->p2p)
{
// Increase number of P2P VIF and number of P2P presences
p_chan_entry->nb_p2p_presence++;
p_chan_entry->nb_linked_p2p_vif++;
}
#endif //(NX_P2P)
chan_update_tx_power(p_chan_entry);
}
void chan_ctxt_unlink(uint8_t vif_idx)
{
struct vif_info_tag *p_vif_entry = &vif_info_tab[vif_idx];
struct chan_ctxt_tag *p_chan_entry = p_vif_entry->chan_ctxt;
CHAN_DEBUG_PRINT(1, "chan_ctxt_unlink i=%d ci=%d s=%d nb=%d\n", vif_idx, p_chan_entry->idx,
p_chan_entry->status, p_chan_entry->nb_linked_vif);
// Sanity checks
ASSERT_ERR(p_chan_entry != NULL);
// Remove TBTT Switch element
co_list_extract(&chan_env.list_tbtt, &p_vif_entry->tbtt_switch.list_hdr);
// ... and reset status
p_vif_entry->tbtt_switch.status = CHAN_TBTT_NOT_PROG;
// Channel context will now be linked to VIF
p_vif_entry->chan_ctxt = NULL;
// Decrease number of VIFs linked with the channel context
p_chan_entry->nb_linked_vif--;
if (p_chan_entry->status != CHAN_NOT_SCHEDULED)
{
#if (NX_P2P)
if (p_vif_entry->p2p)
{
// Get associated P2P entry
struct p2p_info_tag *p_p2p_entry = &p2p_info_tab[p_vif_entry->p2p_index];
if (p_p2p_entry->is_go_present)
{
// Decrease number of presence
p_chan_entry->nb_p2p_presence--;
}
// Decrease number of P2P VIFs linked with the channel context
p_chan_entry->nb_linked_p2p_vif--;
}
#endif //(NX_P2P)
chan_env.cde_dur_us -= (CHAN_VIF_NB_SLOTS * CHAN_SLOT_DURATION_US);
// If no more VIFs are linked with the channel, unschedule it
if (!p_chan_entry->nb_linked_vif)
{
// Indicate if a switch is in progress
bool switch_in_prog = (chan_env.chan_switch != NULL);
// Indicate if we are switch on the channel to be unscheduled
bool switch_unlk = (chan_env.chan_switch == p_chan_entry);
// Remove the context from the list of channel contexts
co_list_extract(&chan_env.list_sched_ctxt, &p_chan_entry->list_hdr);
// Reset the status
p_chan_entry->status = CHAN_NOT_SCHEDULED;
// Decrease number of scheduled channels
chan_env.nb_sched_ctxt--;
#if (NX_P2P_GO)
if (chan_env.nb_sched_ctxt == 1)
{
// CDE will be disabled stop all used NOA
struct vif_info_tag *p_vif_noa_entry = vif_mgmt_first_used();
while (p_vif_noa_entry)
{
if (p_vif_noa_entry->p2p && (p_vif_noa_entry->type == VIF_AP))
{
p2p_go_noa_stop(p_vif_noa_entry, p_chan_entry->p2p_noa_idx, false);
}
p_vif_noa_entry = (struct vif_info_tag *)p_vif_noa_entry->list_hdr.next;
}
}
#endif //(NX_P2P_GO)
// Check if we are on the channel
if (chan_env.current_channel == p_chan_entry)
{
chan_env.current_channel = NULL;
}
// Check if we are switching on the channel to be unscheduled
else if (switch_unlk)
{
chan_env.chan_switch = NULL;
}
if (switch_in_prog)
{
/*
* If a switch procedure is in progress, act as if a switch timeout has occurred.
* Upon end of switch procedure, we will jump on another channel either through beginning of
* a new CDE or simply because only one channel will be available
*/
chan_env.status |= CO_BIT(CHAN_ENV_TIMEOUT_BIT);
}
else
{
// If CDE is used, restart CDE
if (chan_env.nb_sched_ctxt >= 2)
{
// Start a new channel distribution event
chan_cde_evt(NULL);
}
else if (chan_env.nb_sched_ctxt == 1)
{
chan_switch_start((struct chan_ctxt_tag *)co_list_pick(&chan_env.list_sched_ctxt));
}
}
}
}
// If no more VIF linked with the channel, delete the channel
if (p_chan_entry->nb_linked_vif == 0)
{
chan_ctxt_del(p_chan_entry->idx);
}
// Schedule next TBTT Switch element
chan_tbtt_schedule(NULL);
chan_update_tx_power(p_chan_entry);
}
void chan_ctxt_update(struct mm_chan_ctxt_update_req const *p_upd_req)
{
// Get channel context
struct chan_ctxt_tag *p_chan_entry = &chan_ctxt_pool[p_upd_req->chan_index];
GLOBAL_INT_DECLARATION();
CHAN_DEBUG_PRINT(1, "chan_ctxt_update chan_idx=%d\n", p_upd_req->chan_index);
// Update the channel context
p_chan_entry->channel.band = p_upd_req->band;
p_chan_entry->channel.type = p_upd_req->type;
p_chan_entry->channel.center1_freq = p_upd_req->center1_freq;
p_chan_entry->channel.center2_freq = p_upd_req->center2_freq;
p_chan_entry->channel.prim20_freq = p_upd_req->prim20_freq;
p_chan_entry->channel.tx_power = p_upd_req->tx_power;
// Check if we are currently on this channel
if (chan_env.current_channel == p_chan_entry)
{
// Handle the packets already in the RX queue to ensure that the
// channel information indicated to the upper MAC is correct. This has to be done with
// interrupts disabled, as the normal handling of the packets is done under interrupt
GLOBAL_INT_DISABLE();
rxl_timer_int_handler();
rxl_cntrl_evt(0);
GLOBAL_INT_RESTORE();
// Program the RF with the new channel
phy_set_channel(p_upd_req->band, p_upd_req->type, p_upd_req->prim20_freq,
p_upd_req->center1_freq, p_upd_req->center2_freq, PHY_PRIM);
tpc_update_tx_power(p_chan_entry->channel.tx_power);
}
}
void chan_tbtt_switch_update(struct vif_info_tag *p_vif_entry, uint32_t tbtt_time)
{
// Get VIF's channel context
struct chan_ctxt_tag *p_chan_entry = p_vif_entry->chan_ctxt;
// TBTT Switch element
struct chan_tbtt_tag *p_tbtt_entry = &p_vif_entry->tbtt_switch;
do
{
// Verify that the Channel Context has been scheduled
if (!p_chan_entry || (p_chan_entry->status == CHAN_NOT_SCHEDULED))
{
break;
}
// Verify that tbtt time has been modified
if (p_tbtt_entry->time == (tbtt_time - CHAN_SWITCH_DELAY))
{
break;
}
// Update TBTT switch time based on new TBTT time
p_tbtt_entry->time = tbtt_time - CHAN_SWITCH_DELAY;
// Check that more than 1 channel contexts are currently used
if (chan_env.nb_sched_ctxt < 2)
{
break;
}
CHAN_DEBUG_PRINT(3, "chan_tbtt_switch_update i=%d, s=%d, tbtt=%d, ct=%d\n",
p_vif_entry->index, p_tbtt_entry->status, tbtt_time, ke_time());
// If TBTT Presence is in progress, TBTT Switch will be rescheduled at end of presence
if (p_tbtt_entry->status != CHAN_TBTT_PRESENCE)
{
// Reset the status
p_tbtt_entry->status = CHAN_TBTT_NOT_PROG;
// Remove TBTT information from list of TBTTs
co_list_extract(&chan_env.list_tbtt, &p_vif_entry->tbtt_switch.list_hdr);
// Schedule the TBTT
chan_tbtt_schedule(p_tbtt_entry);
}
} while (0);
}
void chan_bcn_to_evt(struct vif_info_tag *p_vif_entry)
{
// TBTT Switch Information structure
struct chan_tbtt_tag *p_tbtt_entry = &p_vif_entry->tbtt_switch;
// Get current channel context
struct chan_ctxt_tag *p_chan_entry = chan_env.current_channel;
// Current time
uint32_t current_time = ke_time();
CHAN_DEBUG_PRINT(3, "chan_bcn_to_evt idx=%d s=%d\n", p_tbtt_entry->vif_index, chan_env.status);
do
{
if (p_tbtt_entry->status != CHAN_TBTT_PRESENCE)
{
break;
}
// Update status
p_tbtt_entry->status = CHAN_TBTT_NOT_PROG;
// Remove TBTT information from list of TBTTs
co_list_extract(&chan_env.list_tbtt, &p_tbtt_entry->list_hdr);
// Check if CDE is used
if (chan_env.nb_sched_ctxt < 2)
{
break;
}
// Reschedule the TBTT Switch event
chan_tbtt_schedule(p_tbtt_entry);
// Check if a RoC or a Scan procedure is in progress
if (chan_env.status & (CO_BIT(CHAN_ENV_ROC_BIT) | CO_BIT(CHAN_ENV_SCAN_BIT)))
{
break;
}
// Check if a Channel Switch is still in progress
if (chan_env.chan_switch)
{
break;
}
// Update number of remaining slots for current channel
chan_upd_nb_rem_slots(p_chan_entry, current_time);
// If number of reserved slots is not zero, it means than TBTT presence has started in previous NOA
if (p_chan_entry->nb_res_slots)
{
p_chan_entry->nb_res_slots -= co_min(chan_get_nb_slots(current_time, chan_env.cde_time), p_chan_entry->nb_res_slots);
}
// Update CDE time
chan_env.cde_time = current_time;
// Get first channel context of the CDE
p_chan_entry = chan_get_next_chan();
if (chan_env.current_channel != p_chan_entry)
{
// Jump on channel if different than current chan
chan_switch_start(p_chan_entry);
}
} while (0);
}
void chan_bcn_detect_start(struct vif_info_tag *p_vif_entry)
{
// Get linked channel context
struct chan_ctxt_tag *p_chan_entry = p_vif_entry->chan_ctxt;
// Sanity check
ASSERT_ERR(p_chan_entry);
CHAN_DEBUG_PRINT(1, "chan_bcn_detect_start idx=%d\n", p_chan_entry->idx);
// TODO [LT] - Beacon Detection status should be kept by VIF
// TODO [LT] - Once beacon is received we could use Cancel Remain on Channel
if (!(chan_env.status & CO_BIT(CHAN_ENV_BCN_DETECT_BIT)) &&
(chan_env.nb_sched_ctxt > 1))
{
// Get peer AP information
struct sta_info_tag *p_sta_entry = &sta_info_tab[p_vif_entry->u.sta.ap_id];
// Start a remain on channel procedure in order to received all the beacons
struct mm_remain_on_channel_req *p_req = KE_MSG_ALLOC(MM_REMAIN_ON_CHANNEL_REQ,
TASK_MM, TASK_MM,
mm_remain_on_channel_req);
// Fill request parameters
p_req->op_code = MM_ROC_OP_START;
p_req->vif_index = p_vif_entry->index;
p_req->band = p_chan_entry->channel.band;
p_req->type = p_chan_entry->channel.type;
p_req->prim20_freq = p_chan_entry->channel.prim20_freq;
p_req->center1_freq = p_chan_entry->channel.center1_freq;
p_req->center2_freq = p_chan_entry->channel.center2_freq;
p_req->duration_ms = (p_sta_entry->bcn_int - 5000) / 1000;
p_req->tx_power = p_chan_entry->channel.tx_power;
ke_msg_send(p_req);
// Set Beacon Detection bit in environment status
chan_env.status |= CO_BIT(CHAN_ENV_BCN_DETECT_BIT);
}
}
#if (NX_P2P)
void chan_p2p_absence_update(struct chan_ctxt_tag *p_chan_entry, bool absence)
{
// Next channel context to be used
struct chan_ctxt_tag *p_next_chan_entry;
// Get current time
uint32_t current_time = ke_time();
CHAN_DEBUG_PRINT(3, "chan_p2p_absence_update i=%d a=%d\n", p_chan_entry->idx, absence);
// Update number of presences on P2P channel
if (absence)
{
p_chan_entry->nb_p2p_presence--;
}
else
{
p_chan_entry->nb_p2p_presence++;
}
do
{
// Check if CDE is used
if (chan_env.nb_sched_ctxt < 2)
{
break;
}
// Check if a RoC or a Scan procedure is in progress
if (chan_env.status & (CO_BIT(CHAN_ENV_ROC_BIT) | CO_BIT(CHAN_ENV_SCAN_BIT)))
{
break;
}
// Check if a Channel Switch is still in progress
if (chan_env.chan_switch)
{
break;
}
// Check if current channel has P2P presences
if (chan_env.current_channel->nb_p2p_presence)
{
// We can stay on the current channel
break;
}
if (absence)
{
if (chan_env.current_channel != p_chan_entry)
{
// No need to leave the current channel
break;
}
else
{
p_chan_entry->status = CHAN_PRESENT;
}
}
// Get a new channel
p_next_chan_entry = chan_get_next_chan();
if (p_next_chan_entry != chan_env.current_channel)
{
// Update number of remaining slots for current channel
chan_upd_nb_rem_slots(chan_env.current_channel, current_time);
// Update CDE time
chan_env.cde_time = current_time;
// Jump on channel
chan_switch_start(p_next_chan_entry);
}
} while (0);
}
#endif //(NX_P2P)
bool chan_is_on_channel(struct vif_info_tag *p_vif_entry)
{
bool is_on_channel = false;
if (chan_env.current_channel)
{
if (chan_env.current_channel->idx < CHAN_SCAN_CTXT_IDX)
{
is_on_channel = (p_vif_entry->chan_ctxt == chan_env.current_channel);
}
else
{
is_on_channel = (chan_env.current_channel->vif_index == p_vif_entry->index);
}
}
return (is_on_channel);
}
bool chan_is_tx_allowed(struct vif_info_tag *p_vif_entry)
{
if ((!chan_is_on_channel(p_vif_entry)) ||
(chan_env.chan_switch &&
(chan_env.current_channel->status != CHAN_SENDING_NOA)))
{
return false;
}
return true;
}
void chan_update_tx_power(struct chan_ctxt_tag *p_chan_entry)
{
int8_t i, min_pwr = VIF_UNDEF_POWER;
if (p_chan_entry->nb_linked_vif == 0)
return;
for (i = 0 ; i < NX_VIRT_DEV_MAX; i++) {
struct vif_info_tag *p_vif_entry = &vif_info_tab[i];
if (p_vif_entry->chan_ctxt == p_chan_entry)
{
if (p_vif_entry->user_tx_power < min_pwr)
min_pwr = p_vif_entry->user_tx_power;
if (p_vif_entry->tx_power < min_pwr)
min_pwr = p_vif_entry->tx_power;
}
}
if (min_pwr != VIF_UNDEF_POWER)
{
p_chan_entry->channel.tx_power = min_pwr;
}
}
#endif //(NX_CHNL_CTXT)
/// @} end of group
| 34.058236 | 148 | 0.539302 |
14fedca5d1fb059001da3209c8e165acf93e4844 | 717 | h | C | SimpleHttpServer/socket.h | hx1997/SimpleHttpServer | 0dbf2b64e313554b508272da1ca2ffaf84e0c13f | [
"MIT"
] | 15 | 2018-07-02T15:44:43.000Z | 2020-12-21T11:39:44.000Z | SimpleHttpServer/socket.h | hx1997/SimpleHttpServer | 0dbf2b64e313554b508272da1ca2ffaf84e0c13f | [
"MIT"
] | null | null | null | SimpleHttpServer/socket.h | hx1997/SimpleHttpServer | 0dbf2b64e313554b508272da1ca2ffaf84e0c13f | [
"MIT"
] | null | null | null | #pragma once
#ifdef _WIN32
#include <WinSock2.h>
#include <Ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
extern int InitWinSock();
extern unsigned int ListenForHttpConnection(unsigned int port);
extern unsigned int AcceptConnection(unsigned int sock, struct sockaddr_in *clientSockaddrIn, int sizeSockaddrIn);
extern int ReceiveData(unsigned int clientSock, char *buf, int bufsize);
extern int SendData(unsigned int clientSock, const char *buf, int bufsize);
extern int CloseSocket(unsigned int sock);
extern int ShutdownSocket(unsigned int sock);
extern unsigned int OpenCGIClientSock(); | 34.142857 | 114 | 0.788006 |
34d87cda21e3038840d0d5566882d685766c8688 | 3,666 | c | C | src/sources/FilterNode.private_custom_definitions.c | Acidburn0zzz/oyranos | b87dcf0e7a88e9b2f5f6c2e3314ddbd3af045575 | [
"BSD-3-Clause"
] | null | null | null | src/sources/FilterNode.private_custom_definitions.c | Acidburn0zzz/oyranos | b87dcf0e7a88e9b2f5f6c2e3314ddbd3af045575 | [
"BSD-3-Clause"
] | null | null | null | src/sources/FilterNode.private_custom_definitions.c | Acidburn0zzz/oyranos | b87dcf0e7a88e9b2f5f6c2e3314ddbd3af045575 | [
"BSD-3-Clause"
] | null | null | null | /** Function oyFilterNode_Release__Members
* @memberof oyFilterNode_s
* @brief Custom FilterNode destructor
* @internal
*
* This function will free up all memmory allocated by the
* input object. First all object members witch have their
* own release method are deallocated. Then the deallocateFunc_
* of the oy_ object is used to release the rest of the members
* that were allocated with oy_->allocateFunc_.
*
* @param[in] filternode the FilterNode object
*
* @version Oyranos: x.x.x
* @since YYYY/MM/DD (Oyranos: x.x.x)
* @date YYYY/MM/DD
*/
void oyFilterNode_Release__Members( oyFilterNode_s_ * filternode )
{
/* Deallocate members here
* E.g: oyXXX_Release( &filternode->member );
*/
int i,n;
oyOptions_Release( &filternode->tags );
if(filternode->sockets)
{
n = oyFilterNode_EdgeCount( (oyFilterNode_s*)filternode, 0, 0 );
for(i = 0; i < n; ++i)
oyFilterSocket_Release( (oyFilterSocket_s **)&filternode->sockets[i] );
}
if(filternode->plugs)
{
n = oyFilterNode_EdgeCount( (oyFilterNode_s*)filternode, 1, 0 );
for(i = 0; i < n; ++i)
oyFilterPlug_Release( (oyFilterPlug_s**)&filternode->plugs[i] );
}
if(filternode->oy_->deallocateFunc_)
{
oyDeAlloc_f deallocateFunc = filternode->oy_->deallocateFunc_;
/* Deallocate members of basic type here
* E.g.: deallocateFunc( filternode->member );
*/
if(filternode->relatives_)
deallocateFunc( filternode->relatives_ );
filternode->relatives_ = 0;
}
}
/** Function oyFilterNode_Init__Members
* @memberof oyFilterNode_s
* @brief Custom FilterNode constructor
* @internal
*
* This function will allocate all memmory for the input object.
* For the basic member types this is done using the allocateFunc_
* of the attatced (oyObject_s)oy_ object.
*
* @param[in] filternode the FilterNode object
*
* @version Oyranos: x.x.x
* @since YYYY/MM/DD (Oyranos: x.x.x)
* @date YYYY/MM/DD
*/
int oyFilterNode_Init__Members( oyFilterNode_s_ * filternode OY_UNUSED )
{
/** Is this necessary??
* filternode->relatives_ = 0;
*
* if( filternode->backend_data && filternode->backend_data->release )
* filternode->backend_data->release( (oyStruct_s**) & filternode->backend_data );
* filternode->backend_data = 0;
*/
return 0;
}
/** Function oyFilterNode_Copy__Members
* @memberof oyFilterNode_s
* @brief Custom FilterNode copy constructor
* @internal
*
* This function makes a copy of all values from the input
* to the output object. The destination object and all of its
* members should already be allocated.
*
* @param[in] src the oyFilterNode_s_ input object
* @param[out] dst the output oyFilterNode_s_ object
*
* @version Oyranos: x.x.x
* @since YYYY/MM/DD (Oyranos: x.x.x)
* @date YYYY/MM/DD
*/
int oyFilterNode_Copy__Members( oyFilterNode_s_ * dst, oyFilterNode_s_ * src)
{
int error = 0;
#if 0
oyAlloc_f allocateFunc_ = 0;
oyDeAlloc_f deallocateFunc_ = 0;
#endif
if(!dst || !src)
return 1;
#if 0
allocateFunc_ = dst->oy_->allocateFunc_;
deallocateFunc_ = dst->oy_->deallocateFunc_;
#endif
/* Copy each value of src to dst here */
if(src->backend_data && src->backend_data->copy)
dst->backend_data = (oyPointer_s*) src->backend_data->copy( (oyStruct_s*)
src->backend_data , dst->oy_ );
if(oy_debug_objects >= 0 && dst->backend_data)
oyObjectDebugMessage_( dst->backend_data->oy_, __func__,
oyStructTypeToText(dst->backend_data->type_) );
return error;
}
| 29.564516 | 88 | 0.668849 |
f603827640dbda64d34626885ef97ff4695916a0 | 20,585 | c | C | src/io.c | tsccsj/TerraReproject | 78e32e4e6d5728ae3bcd03f77aaf09daddb0b527 | [
"Apache-2.0"
] | null | null | null | src/io.c | tsccsj/TerraReproject | 78e32e4e6d5728ae3bcd03f77aaf09daddb0b527 | [
"Apache-2.0"
] | null | null | null | src/io.c | tsccsj/TerraReproject | 78e32e4e6d5728ae3bcd03f77aaf09daddb0b527 | [
"Apache-2.0"
] | null | null | null | /*
AUTHOR:
Yat Long Lo
EMAIL:
yllo2@illinois.edu
*/
#include <hdf5.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include "io.h"
#define FALSE 0
double* get_misr_rad(hid_t file, char* camera_angle, char* resolution, char* radiance, int* size){
//Path to dataset proccessing
int down_sampling = 0;
char* instrument = "MISR";
char* d_fields = "Data_Fields";
const char* arr[] = {instrument, camera_angle, d_fields, radiance};
//Dataset name parsing
char* rad_dataset_name;
concat_by_sep(&rad_dataset_name, arr, "/", strlen(instrument) + strlen(camera_angle) + strlen(d_fields) + strlen(radiance) + 4, 4);
//Check for correct specification
if(strcmp(camera_angle, "AN") != 0 && strcmp(radiance, "Red_Radiance") != 0 && strcmp(resolution, "H") == 0){
printf("Error: Your specification does not support high resolution.\n");
return NULL;
}
else if((strcmp(camera_angle, "AN") == 0 || strcmp(radiance, "Red_Radiance") == 0) && strcmp(resolution, "L") == 0){
//Downsampling has to be done
down_sampling = 1;
}
printf("Reading MISR\n");
/*Dimensions - 180 blocks, 512 x 2048 ordered in 1D Array*/
//Retrieve radiance dataset and dataspace
double* data = af_read(file, rad_dataset_name);
*size = dim_sum(af_read_size(file, rad_dataset_name), 3);
if(data == NULL){
return NULL;
}
printf("Reading successful\n");
//Variable containing down sampled data
double* down_data;
if(down_sampling == 1){
printf("Undergoing downsampling\n");
hsize_t* dims = af_read_size(file, rad_dataset_name);
*size = dims[0] * (dims[1]/4) * (dims[2]/4);
down_data = malloc(dims[0] * (dims[1]/4) * (dims[2]/4) * sizeof(double));
int i, j, k;
for(i = 0; i < dims[0]; i++){
for(j = 0; j < dims[1]; j = j + 4){
for(k = 0; k < dims[2]; k = k + 4){
//Retrieving 4x4 window for averaging
//Formula for converting i, j and k to index in data array
//int index = i*dims[1]*dims[2] + j*dims[2] + k;
int a,b;
int max_x = j + 4;
int max_z = k + 4;
int* index_array = malloc(16*sizeof(int));
int index_iter = 0;
for(a = j; a < max_x; a++){
for(b = k; b < max_z; b++){
index_array[index_iter] = i*dims[1]*dims[2] + a*dims[2] + b;
index_iter += 1;
}
}
double* window = malloc(16*sizeof(double));
int c;
for(c = 0; c < 16; c++){
window[c] = data[index_array[c]];
}
//Window Retrieved, get average and assign to new data grid
double average = misr_averaging(window);
int new_index = i*dims[1]/4*dims[2]/4 + (j/4)*dims[2]/4 + k/4;
down_data[new_index] = average;
free(index_array);
free(window);
}
}
}
free(data);
printf("Downsampling done\n");
}
if(down_sampling == 1){
printf("rad_data: %f\n", down_data[0]);
return down_data;
}
else{
printf("rad_data: %f\n", data[0]);
return data;
}
}
double* get_misr_lat(hid_t file, char* resolution, int* size){
//Path to dataset proccessing
char* instrument = "MISR";
char* location;
if(strcmp(resolution, "H") == 0){
location = "HRGeolocation";
}
else{
location = "Geolocation";
}
char* lat = "GeoLatitude";
const char* arr2[] = {instrument, location, lat};
//Dataset names parsing
char* lat_dataset_name;
concat_by_sep(&lat_dataset_name, arr2, "/", strlen(instrument) + strlen(location) + strlen(lat) + 4, 3);
printf("Retrieveing latitude data for MISR\n");
//Retrieve latitude dataset and dataspace
double* lat_data = af_read(file, lat_dataset_name);
*size = dim_sum(af_read_size(file, lat_dataset_name), 3);
if(lat_data == NULL){
return NULL;
}
printf("lat_data: %f\n", lat_data[0]);
return lat_data;
}
double* get_misr_long(hid_t file, char* resolution, int* size){
//Path to dataset proccessing
char* instrument = "MISR";
char* location;
if(strcmp(resolution, "H") == 0){
location = "HRGeolocation";
}
else{
location = "Geolocation";
}
char* longitude = "GeoLongitude";
const char* arr3[] = {instrument, location, longitude};
//Dataset names parsing
char* long_dataset_name;
concat_by_sep(&long_dataset_name, arr3, "/", strlen(instrument) + strlen(location) + strlen(longitude) + 4, 3);
printf("Retrieveing longitude data for MISR\n");
//Retrieve longitude dataset and dataspace
double* long_data = af_read(file, long_dataset_name);
*size = dim_sum(af_read_size(file, long_dataset_name), 3);
if(long_data == NULL){
return NULL;
}
printf("long_data: %f\n", long_data[0]);
return long_data;
}
double* get_modis_rad(hid_t file, char* resolution, char* d_name, int* size){
printf("Reading MODIS rad\n");
char* instrument = "MODIS";
char* d_fields = "Data_Fields";
//Get all granule file names
printf("Retrieving granule group names\n");
hid_t group = H5Gopen(file, instrument, H5P_DEFAULT);
if(group < 0){
printf("Group not found\n");
return NULL;
}
hsize_t num_groups;
herr_t err = H5Gget_num_objs(group, &num_groups);
char* names[(int)num_groups][20];
int i;
for(i = 0; i < num_groups; i++){
char* name = malloc(20*sizeof(char));
H5Gget_objname_by_idx(group, (hsize_t)i, name, 20);
strcpy(&names[i], name);
free(name);
}
int h;
double* data;
double curr_size;
int read_first = -1;
for(h = 0; h < num_groups; h++){
//Path formation
char* name = names[h];
const char* d_arr[] = {instrument, name, resolution, d_fields, d_name};
char* dataset_name;
concat_by_sep(&dataset_name, d_arr, "/", strlen(instrument) + strlen(name) + strlen(resolution) + strlen(d_fields) + strlen(d_name), 5);
printf("granule_name: %s\n", name);
if(read_first < 0){
data = af_read(file, dataset_name);
if(data == NULL){
continue;
}
curr_size = dim_sum(af_read_size(file, dataset_name), 3);
read_first = 1;
}
else{
//retrieve next set of data and it's dimention
double* adding_data = af_read(file, dataset_name);
if(adding_data == NULL){
continue;
}
double new_d_size = dim_sum(af_read_size(file, dataset_name), 3);
//Reallocating arrays of data
data = realloc(data, sizeof(double)*(curr_size + new_d_size));
memcpy(&data[(int)curr_size], adding_data, sizeof(double)*new_d_size);
curr_size += new_d_size;
free(adding_data);
}
}
*size = curr_size;
//Print statements to verify data's existence
printf("test data: %f\n", data[0]);
printf("test_data (next_page): %f\n", data[2748620]);
printf("test data (next_granule): %f\n", data[41229300]);
return data;
}
double* get_modis_lat(hid_t file, char* resolution, char* d_name, int* size){
printf("Reading MODIS lat\n");
//Path variables
char* instrument = "MODIS";
char* d_fields = "Data_Fields";
char* location = "Geolocation";
char* lat = "Latitude";
//Get all granule file names
printf("Retrieving granule group names\n");
hid_t group = H5Gopen(file, instrument, H5P_DEFAULT);
if(group < 0){
printf("Group not found\n");
return NULL;
}
hsize_t num_groups;
herr_t err = H5Gget_num_objs(group, &num_groups);
char* names[(int)num_groups][20];
int i;
for(i = 0; i < num_groups; i++){
char* name = malloc(20*sizeof(char));
H5Gget_objname_by_idx(group, (hsize_t)i, name, 20);
strcpy(&names[i], name);
free(name);
}
int h;
double* lat_data;
double curr_lat_size;
int read_first = -1;
for(h = 0; h < num_groups; h++){
//Path formation
char* name = names[h];
const char* d_arr[] = {name, resolution, d_fields, d_name};
char* dataset_name;
concat_by_sep(&dataset_name, d_arr, "/", strlen(name) + strlen(resolution) + strlen(d_fields) + strlen(d_name), 4);
memmove(&dataset_name[0], &dataset_name[1], strlen(dataset_name));
//Check if dataset exists first
printf("granule_name: %s\n", name);
htri_t status = H5Lexists(group, dataset_name, H5P_DEFAULT);
if(status <= 0){
printf("Dataset does not exist\n");
continue;
}
const char* lat_arr[] = {instrument, name, resolution, location, lat};
char* lat_dataset_name;
concat_by_sep(&lat_dataset_name, lat_arr, "/", strlen(instrument) + strlen(name) + strlen(resolution) + strlen(location) + strlen(lat), 5);
if(read_first < 0){
curr_lat_size = dim_sum(af_read_size(file, lat_dataset_name), 2);
lat_data = af_read(file, lat_dataset_name);
read_first = 1;
}
else{
//retrieve next set of data and it's dimention
double* adding_lat = af_read(file, lat_dataset_name);
double new_lat_size = dim_sum(af_read_size(file, lat_dataset_name), 2);
//Reallocating arrays of data
lat_data = realloc(lat_data, sizeof(double)*(curr_lat_size + new_lat_size));
memcpy(&lat_data[(int)curr_lat_size], adding_lat, sizeof(double)*new_lat_size);
curr_lat_size += new_lat_size;
free(adding_lat);
}
}
*size = curr_lat_size;
printf("test_lat_data (next_granule): %f\n", lat_data[0]);
printf("test_lat_data (next_granule): %f\n", lat_data[2748620]);
printf("test_lat_data (next_granule): %f\n", lat_data[5510780]);
return lat_data;
}
double* get_modis_long(hid_t file, char* resolution, char* d_name, int* size){
printf("Reading MODIS long\n");
//Path variables
char* instrument = "MODIS";
char* d_fields = "Data_Fields";
char* location = "Geolocation";
char* longitude = "Longitude";
//Get all granule file names
printf("Retrieving granule group names\n");
hid_t group = H5Gopen(file, instrument, H5P_DEFAULT);
if(group < 0){
printf("Group not found\n");
return NULL;
}
hsize_t num_groups;
herr_t err = H5Gget_num_objs(group, &num_groups);
char* names[(int)num_groups][20];
int i;
for(i = 0; i < num_groups; i++){
char* name = malloc(20*sizeof(char));
H5Gget_objname_by_idx(group, (hsize_t)i, name, 20);
strcpy(&names[i], name);
free(name);
}
int h;
double* long_data;
double curr_long_size;
int read_first = -1;
for(h = 0; h < num_groups; h++){
//Path formation
char* name = names[h];
const char* d_arr[] = {name, resolution, d_fields, d_name};
char* dataset_name;
concat_by_sep(&dataset_name, d_arr, "/", strlen(name) + strlen(resolution) + strlen(d_fields) + strlen(d_name), 4);
memmove(&dataset_name[0], &dataset_name[1], strlen(dataset_name));
//Check if dataset exists first
printf("granule_name: %s\n", name);
htri_t status = H5Lexists(group, dataset_name, H5P_DEFAULT);
if(status <= 0){
printf("Dataset does not exist\n");
continue;
}
const char* long_arr[] = {instrument, name, resolution, location, longitude};
char* long_dataset_name;
concat_by_sep(&long_dataset_name, long_arr, "/", strlen(instrument) + strlen(name) + strlen(resolution) + strlen(location) + strlen(longitude), 5);
if(read_first < 0){
curr_long_size = dim_sum(af_read_size(file, long_dataset_name), 2);
long_data = af_read(file, long_dataset_name);
read_first = 1;
}
else{
//retrieve next set of data and it's dimention
double* adding_long = af_read(file, long_dataset_name);
double new_long_size = dim_sum(af_read_size(file, long_dataset_name), 2);
//Reallocating arrays of data
long_data = realloc(long_data, sizeof(double)*(curr_long_size + new_long_size));
memcpy(&long_data[(int)curr_long_size], adding_long, sizeof(double)*new_long_size);
curr_long_size += new_long_size;
free(adding_long);
}
}
*size = curr_long_size;
printf("test_long_data (next_granule): %f\n", long_data[0]);
printf("test_long_data (next_granule): %f\n", long_data[2748620]);
printf("test_long_data (next_granule): %f\n", long_data[5510780]);
return long_data;
}
double* get_ceres_rad(hid_t file, char* camera, char* d_name, int* size){
printf("Reading CERES radiance\n");
//Path variables
char* instrument = "CERES";
char* rad = "Radiances";
//Get all granule file names
printf("Retrieving granule group names\n");
hid_t group = H5Gopen(file, instrument, H5P_DEFAULT);
if(group < 0){
printf("Group not found\n");
return NULL;
}
hsize_t num_groups;
herr_t err = H5Gget_num_objs(group, &num_groups);
char* names[(int)num_groups][20];
int i;
for(i = 0; i < num_groups; i++){
char* name = malloc(20*sizeof(char));
H5Gget_objname_by_idx(group, (hsize_t)i, name, 20);
strcpy(&names[i], name);
free(name);
}
int h;
double* data;
double curr_size;
int read_first = -1;
for(h = 0; h < num_groups; h++){
//Path formation
char* name = names[h];
const char* d_arr[] = {instrument, name, camera, rad, d_name};
char* dataset_name;
concat_by_sep(&dataset_name, d_arr, "/", strlen(instrument) + strlen(name) + strlen(camera) + strlen(rad) + strlen(d_name), 5);
printf("granule_name: %s\n", name);
printf("ds_name: %s\n", dataset_name);
if(read_first < 0){
data = af_read(file, dataset_name);
if(data == NULL){
continue;
}
curr_size = dim_sum(af_read_size(file, dataset_name), 3);
read_first = 1;
}
else{
//retrieve next set of data and it's dimention
double* adding_data = af_read(file, dataset_name);
if(adding_data == NULL){
continue;
}
double new_d_size = dim_sum(af_read_size(file, dataset_name), 3);
//Reallocating arrays of data
data = realloc(data, sizeof(double)*(curr_size + new_d_size));
memcpy(&data[(int)curr_size], adding_data, sizeof(double)*new_d_size);
curr_size += new_d_size;
free(adding_data);
}
}
//Print statements to verify data's existence
printf("test data: %f\n", data[0]);
printf("test_data: %f\n", data[1]);
printf("test data: %f\n", data[2]);
return data;
}
hsize_t* af_read_size(hid_t file, char* dataset_name){
hid_t dataset = H5Dopen2(file, dataset_name, H5P_DEFAULT);
if(dataset < 0){
printf("Dataset open error\n");
return NULL;
}
hid_t dataspace = H5Dget_space(dataset);
if(dataspace < 0){
printf("Dataspace open error\n");
return NULL;
}
const int ndims = H5Sget_simple_extent_ndims(dataspace);
//printf("ndims: %d\n", ndims);
hsize_t* dims = malloc(sizeof(hsize_t) * ndims);
//printf("dims: %d\n", dims[0]);
H5Sget_simple_extent_dims(dataspace, dims, NULL);
H5Dclose(dataset);
H5Sclose(dataspace);
return dims;
}
double* af_read(hid_t file, char* dataset_name){
hid_t dataset = H5Dopen2(file, dataset_name, H5P_DEFAULT);
if(dataset < 0){
printf("Dataset open error\n");
return NULL;
}
hid_t dataspace = H5Dget_space(dataset);
if(dataspace < 0){
printf("Dataspace open error\n");
return NULL;
}
const int ndims = H5Sget_simple_extent_ndims(dataspace);
hsize_t dims[ndims];
H5Sget_simple_extent_dims(dataspace, dims, NULL);
hid_t memspace = H5Screate_simple(ndims,dims,NULL);
hid_t dtype = H5Dget_type(dataset);
hid_t ndtype = H5Tget_native_type(dtype, H5T_DIR_DESCEND);
float * data = calloc ( dim_sum(dims, sizeof(dims)/sizeof(hsize_t)) , sizeof(ndtype) );
double* converted_data = calloc ( dim_sum(dims, sizeof(dims)/sizeof(hsize_t)) , sizeof(double) );
herr_t status = H5Dread(dataset, ndtype, memspace, memspace, H5P_DEFAULT, data);
int i;
for(i=0;i < dim_sum(dims, sizeof(dims)/sizeof(hsize_t)); i++){
converted_data[i] = float_to_double(data[i]);
}
free(data);
H5Dclose(dataset);
H5Sclose(dataspace);
H5Tclose(dtype);
H5Tclose(ndtype);
if(status < 0){
printf("read error: %d\n", status);
}
return converted_data;
}
hid_t af_open(char* file_path){
hid_t f = H5Fopen(file_path, H5F_ACC_RDONLY, H5P_DEFAULT);
return f;
}
herr_t af_close(hid_t file){
herr_t ret = H5Fclose(file);
return ret;
}
/*
int main (int argc, char *argv[]){
//Preset filename here for easy testing
char* file_path = "/projects/TDataFus/kent/temp/40-orbit-file/Jun15.2/TERRA_BF_L1B_O69365_F000_V000.h5";
hid_t file;
argv[1] = file_path;
if(argc < 3){
printf("Usage: %s filename instrument_name extra_arguments\n", argv[0]);
return 0;
}
else if(strcmp(argv[2], "MISR") == 0){
if(argc < 6){
printf("MISR Usage: %s filename MISR camera_angle resolution(H/L) radiance\n", argv[0]);
return 0;
}
else{
//MISR input requirements fulfilled
//Open file
file = af_open(file_path);
if(file < 0){
printf("File not found\n");
return -1;
}
double d_size = 0;
double* data_pt = &d_size;
double* data = get_misr_rad(file, argv[3], argv[4], argv[5], data_pt);
printf("Data size: %f\n", *data_pt);
double lat_size = 0;
double* lat_pt = &lat_size;
double* lat_data = get_misr_lat(file, argv[4], lat_pt);
printf("Lat size: %f\n", *lat_pt);
double long_size = 0;
double* long_pt = &long_size;
double* long_data = get_misr_long(file, argv[4], long_pt);
printf("Long size: %f\n", *long_pt);
if(data != NULL && lat_data != NULL, long_data != NULL){
printf("MISR retrieval successful\n");
}
else{
printf("MISR retrieval failed\n");
}
herr_t ret = af_close(file);
}
}
else if(strcmp(argv[2], "MODIS") == 0){
if(argc < 4){
printf("MODIS Usage: %s filename MODIS resolution(1KM/500m/250m)\n", argv[0]);
}
else{
file = af_open(file_path);
if(file < 0){
printf("File not found\n");
return -1;
}
char* resolution = argv[3];
char* d_name = "";
if(strcmp(resolution, "1KM") == 0){
resolution = "_1KM";
d_name = "EV_1KM_RefSB";
}
else if(strcmp(resolution, "250M") == 0){
resolution = "_250m";
d_name = "EV_250_RefSB";
}
else if(strcmp(resolution, "500M") == 0){
resolution = "_500m";
d_name = "EV_500_RefSB";
}
else{
printf("Wrong resolution, choose from 1KM, 500M or 250M\n");
}
double data_size = 0;
double* data_pt = &data_size;
double* data = get_modis_rad(file, resolution, d_name, data_pt);
printf("Data size: %f\n", *data_pt);
double lat_size = 0;
double* lat_pt = &lat_size;
double* lat_data = get_modis_lat(file, resolution, d_name, lat_pt);
printf("Lat size: %f\n", *lat_pt);
double long_size = 0;
double* long_pt = &long_size;
double* long_data = get_modis_long(file, resolution, d_name, long_pt);
printf("Long size: %f\n", *long_pt);
if(data != NULL && lat_data != NULL, long_data != NULL){
printf("MODIS retrieval successful\n");
}
else{
printf("MODIS retrieval failed\n");
}
herr_t ret = af_close(file);
}
}
else if(strcmp(argv[2], "CERES") == 0){
if(argc < 6){
printf("CERES Usage: %s filename CERES camera radiance(LW/SW/WN/TOT) filtered/unfiltered(F/U)");
}
else{
file = af_open(file_path);
if(file < 0){
printf("File not found\n");
return -1;
}
char* d_name = calloc(30, sizeof(char));
if(strcmp(argv[5], "F") == 0){
char* f = "_Filtered";
char* r = "_Radiance";
strcpy(d_name, argv[4]);
strncat(d_name, f, strlen(f));
strncat(d_name, r, strlen(r));
}
else{
char* r = "_Radiance";
strcpy(d_name, argv[4]);
strncat(d_name, r, strlen(r));
}
double data_size = 0;
double* data_pt = &data_size;
double* data = get_ceres_rad(file, argv[3], d_name, data_pt);
printf("Data size: %f\n", data_pt);
}
}
return 0;
}
*/
//Helper Functions
//String helper
void concat_by_sep(char** source, const char** w, char* sep, size_t length, int arr_size){
int i;
*source = calloc(length+20, sizeof(char));
for(i = 0; i < arr_size; i++){
if(i == 0){
strncpy(*source, sep, strlen(sep));
strncat(*source, w[i], strlen(w[i]));
}
else{
strncat(*source, sep, strlen(sep));
strncat(*source, w[i], strlen(w[i]));
}
}
}
//Summing up dimensions
double dim_sum(hsize_t* dims, int arr_len){
double sum = 0.0;
int i;
for(i = 0; i < arr_len; i++){
if(i == 0){
sum = (double)dims[i];
}
else{
sum *= (double)dims[i];
}
}
return sum;
}
//Turning float to double
double float_to_double(float f){
char buf[50];
sprintf(buf, "%.7g", f);
return atof(buf);
}
double misr_averaging(double window[16]){
double sum = 0.0;
double count = 0.0;
int i;
for(i = 0; i < 16; i++){
if(window[i] < 0){
return -999.0;
}
else{
sum += window[i];
count += 1;
}
}
return sum/count;
}
| 29.876633 | 150 | 0.638135 |
aba5db2821101c44857478fab684c7c01c034922 | 4,237 | c | C | physicalrobots/player/examples/libplayerc/service_discovery.c | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/examples/libplayerc/service_discovery.c | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/examples/libplayerc/service_discovery.c | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2007, Brian Gerkey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Player Project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <libplayersd/playersd.h>
#include <libplayercore/error.h>
#include <libplayercore/addr_util.h>
#include <libplayercore/interface_util.h>
#include <libplayerc/playerc.h>
#define MAX_DEVS 16
playerc_mclient_t* mclient;
playerc_client_t* clients[MAX_DEVS];
playerc_laser_t* lasers[MAX_DEVS];
int num_laserdevs;
void
device_cb(void* data)
{
playerc_laser_t* laser = (playerc_laser_t*)data;
printf("received data from %u:%u:%u:%u",
laser->info.addr.host,
laser->info.addr.robot,
laser->info.addr.interf,
laser->info.addr.index);
printf(" (%d scans)\n", laser->scan_count);
}
void
browse_cb(player_sd_t* sd, player_sd_dev_t* dev)
{
if(dev->interf == PLAYER_LASER_CODE)
{
clients[num_laserdevs] = playerc_client_create(mclient,
dev->hostname,
dev->robot);
if(0 != playerc_client_connect(clients[num_laserdevs]))
exit(-1);
playerc_client_datamode(clients[num_laserdevs], PLAYERC_DATAMODE_PUSH);
// Create and subscribe to a laser device.
lasers[num_laserdevs] = playerc_laser_create(clients[num_laserdevs],
dev->index);
if(playerc_laser_subscribe(lasers[num_laserdevs], PLAYER_OPEN_MODE))
exit(-1);
// Add a callback to be invoked whenever we receive new data from this
// laser
playerc_client_addcallback(clients[num_laserdevs],
&(lasers[num_laserdevs]->info),
device_cb, lasers[num_laserdevs]);
num_laserdevs++;
printf("subscribed to: %s:%u:%s:%u\n",
dev->hostname,
dev->robot,
interf_to_str(dev->interf),
dev->index);
printf("Now receiving %d lasers\n", num_laserdevs);
}
}
int
main(int argc, const char **argv)
{
int i;
// A service discovery object
player_sd_t* sd;
// Initialize multiclient
mclient = playerc_mclient_create();
// Initialize service discovery
sd = player_sd_init();
// Look for Player devices
if(player_sd_browse(sd, 0.0, 1, browse_cb) != 0)
{
puts("player_sd_browse error");
exit(-1);
}
for(;;)
{
// Update name service
player_sd_update(sd,0.0);
// Wait for new data from server
playerc_mclient_read(mclient,10);
}
// Shutdown
for(i=0;i<num_laserdevs;i++)
{
playerc_laser_unsubscribe(lasers[i]);
playerc_laser_destroy(lasers[i]);
playerc_client_disconnect(clients[i]);
playerc_client_destroy(clients[i]);
}
playerc_mclient_destroy(mclient);
return(0);
}
| 31.154412 | 80 | 0.687987 |
8670e7fa9bab23bf7c375f4c51c90951e490f489 | 18,415 | c | C | kernel/drivers/input/misc/gp2a.c | LoongPenguin/Linux_210 | d941ed620798fb9c96b5d06764fb1dcb68057513 | [
"Apache-2.0"
] | null | null | null | kernel/drivers/input/misc/gp2a.c | LoongPenguin/Linux_210 | d941ed620798fb9c96b5d06764fb1dcb68057513 | [
"Apache-2.0"
] | null | null | null | kernel/drivers/input/misc/gp2a.c | LoongPenguin/Linux_210 | d941ed620798fb9c96b5d06764fb1dcb68057513 | [
"Apache-2.0"
] | null | null | null | /* linux/driver/input/misc/gp2a.c
* Copyright (C) 2010 Samsung Electronics. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/i2c.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/miscdevice.h>
#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/gpio.h>
#include <linux/wakelock.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/workqueue.h>
#include <linux/uaccess.h>
#include <linux/gp2a.h>
/* Note about power vs enable/disable:
* The chip has two functions, proximity and ambient light sensing.
* There is no separate power enablement to the two functions (unlike
* the Capella CM3602/3623).
* This module implements two drivers: /dev/proximity and /dev/light.
* When either driver is enabled (via sysfs attributes), we give power
* to the chip. When both are disabled, we remove power from the chip.
* In suspend, we remove power if light is disabled but not if proximity is
* enabled (proximity is allowed to wakeup from suspend).
*
* There are no ioctls for either driver interfaces. Output is via
* input device framework and control via sysfs attributes.
*/
#define gp2a_dbgmsg(str, args...) pr_debug("%s: " str, __func__, ##args)
#define ADC_BUFFER_NUM 6
/* ADDSEL is LOW */
#define REGS_PROX 0x0 /* Read Only */
#define REGS_GAIN 0x1 /* Write Only */
#define REGS_HYS 0x2 /* Write Only */
#define REGS_CYCLE 0x3 /* Write Only */
#define REGS_OPMOD 0x4 /* Write Only */
/* sensor type */
#define LIGHT 0
#define PROXIMITY 1
#define ALL 2
static u8 reg_defaults[5] = {
0x00, /* PROX: read only register */
0x08, /* GAIN: large LED drive level */
0xC2, /* HYS: receiver sensitivity */
0x04, /* CYCLE: */
0x01, /* OPMOD: normal operating mode */
};
struct gp2a_data;
enum {
LIGHT_ENABLED = BIT(0),
PROXIMITY_ENABLED = BIT(1),
};
/* driver data */
struct gp2a_data {
struct input_dev *proximity_input_dev;
struct input_dev *light_input_dev;
struct gp2a_platform_data *pdata;
struct i2c_client *i2c_client;
int irq;
struct work_struct work_light;
struct hrtimer timer;
ktime_t light_poll_delay;
int adc_value_buf[ADC_BUFFER_NUM];
int adc_index_count;
bool adc_buf_initialized;
bool on;
u8 power_state;
struct mutex power_lock;
struct wake_lock prx_wake_lock;
struct workqueue_struct *wq;
};
int gp2a_i2c_write(struct gp2a_data *gp2a, u8 reg, u8 *val)
{
int err = 0;
struct i2c_msg msg[1];
unsigned char data[2];
int retry = 10;
struct i2c_client *client = gp2a->i2c_client;
if ((client == NULL) || (!client->adapter))
return -ENODEV;
while (retry--) {
data[0] = reg;
data[1] = *val;
msg->addr = client->addr;
msg->flags = 0; /* write */
msg->len = 2;
msg->buf = data;
err = i2c_transfer(client->adapter, msg, 1);
if (err >= 0)
return 0;
}
return err;
}
static void gp2a_light_enable(struct gp2a_data *gp2a)
{
gp2a_dbgmsg("starting poll timer, delay %lldns\n",
ktime_to_ns(gp2a->light_poll_delay));
hrtimer_start(&gp2a->timer, gp2a->light_poll_delay, HRTIMER_MODE_REL);
}
static void gp2a_light_disable(struct gp2a_data *gp2a)
{
gp2a_dbgmsg("cancelling poll timer\n");
hrtimer_cancel(&gp2a->timer);
cancel_work_sync(&gp2a->work_light);
}
static ssize_t poll_delay_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gp2a_data *gp2a = dev_get_drvdata(dev);
return sprintf(buf, "%lld\n", ktime_to_ns(gp2a->light_poll_delay));
}
static ssize_t poll_delay_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct gp2a_data *gp2a = dev_get_drvdata(dev);
int64_t new_delay;
int err;
err = strict_strtoll(buf, 10, &new_delay);
if (err < 0)
return err;
gp2a_dbgmsg("new delay = %lldns, old delay = %lldns\n",
new_delay, ktime_to_ns(gp2a->light_poll_delay));
mutex_lock(&gp2a->power_lock);
if (new_delay != ktime_to_ns(gp2a->light_poll_delay)) {
gp2a->light_poll_delay = ns_to_ktime(new_delay);
if (gp2a->power_state & LIGHT_ENABLED) {
gp2a_light_disable(gp2a);
gp2a_light_enable(gp2a);
}
}
mutex_unlock(&gp2a->power_lock);
return size;
}
static ssize_t light_enable_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gp2a_data *gp2a = dev_get_drvdata(dev);
return sprintf(buf, "%d\n",
(gp2a->power_state & LIGHT_ENABLED) ? 1 : 0);
}
static ssize_t proximity_enable_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gp2a_data *gp2a = dev_get_drvdata(dev);
return sprintf(buf, "%d\n",
(gp2a->power_state & PROXIMITY_ENABLED) ? 1 : 0);
}
static ssize_t light_enable_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct gp2a_data *gp2a = dev_get_drvdata(dev);
bool new_value;
if (sysfs_streq(buf, "1"))
new_value = true;
else if (sysfs_streq(buf, "0"))
new_value = false;
else {
pr_err("%s: invalid value %d\n", __func__, *buf);
return -EINVAL;
}
mutex_lock(&gp2a->power_lock);
gp2a_dbgmsg("new_value = %d, old state = %d\n",
new_value, (gp2a->power_state & LIGHT_ENABLED) ? 1 : 0);
if (new_value && !(gp2a->power_state & LIGHT_ENABLED)) {
if (!gp2a->power_state)
gp2a->pdata->power(true);
gp2a->power_state |= LIGHT_ENABLED;
gp2a_light_enable(gp2a);
} else if (!new_value && (gp2a->power_state & LIGHT_ENABLED)) {
gp2a_light_disable(gp2a);
gp2a->power_state &= ~LIGHT_ENABLED;
if (!gp2a->power_state)
gp2a->pdata->power(false);
}
mutex_unlock(&gp2a->power_lock);
return size;
}
static ssize_t proximity_enable_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct gp2a_data *gp2a = dev_get_drvdata(dev);
bool new_value;
if (sysfs_streq(buf, "1"))
new_value = true;
else if (sysfs_streq(buf, "0"))
new_value = false;
else {
pr_err("%s: invalid value %d\n", __func__, *buf);
return -EINVAL;
}
mutex_lock(&gp2a->power_lock);
gp2a_dbgmsg("new_value = %d, old state = %d\n",
new_value, (gp2a->power_state & PROXIMITY_ENABLED) ? 1 : 0);
if (new_value && !(gp2a->power_state & PROXIMITY_ENABLED)) {
if (!gp2a->power_state)
gp2a->pdata->power(true);
gp2a->power_state |= PROXIMITY_ENABLED;
enable_irq(gp2a->irq);
enable_irq_wake(gp2a->irq);
gp2a_i2c_write(gp2a, REGS_GAIN, ®_defaults[1]);
gp2a_i2c_write(gp2a, REGS_HYS, ®_defaults[2]);
gp2a_i2c_write(gp2a, REGS_CYCLE, ®_defaults[3]);
gp2a_i2c_write(gp2a, REGS_OPMOD, ®_defaults[4]);
} else if (!new_value && (gp2a->power_state & PROXIMITY_ENABLED)) {
disable_irq_wake(gp2a->irq);
disable_irq(gp2a->irq);
gp2a_i2c_write(gp2a, REGS_OPMOD, ®_defaults[0]);
gp2a->power_state &= ~PROXIMITY_ENABLED;
if (!gp2a->power_state)
gp2a->pdata->power(false);
}
mutex_unlock(&gp2a->power_lock);
return size;
}
static DEVICE_ATTR(poll_delay, S_IRUGO | S_IWUSR | S_IWGRP,
poll_delay_show, poll_delay_store);
static struct device_attribute dev_attr_light_enable =
__ATTR(enable, S_IRUGO | S_IWUSR | S_IWGRP,
light_enable_show, light_enable_store);
static struct device_attribute dev_attr_proximity_enable =
__ATTR(enable, S_IRUGO | S_IWUSR | S_IWGRP,
proximity_enable_show, proximity_enable_store);
static struct attribute *light_sysfs_attrs[] = {
&dev_attr_light_enable.attr,
&dev_attr_poll_delay.attr,
NULL
};
static struct attribute_group light_attribute_group = {
.attrs = light_sysfs_attrs,
};
static struct attribute *proximity_sysfs_attrs[] = {
&dev_attr_proximity_enable.attr,
NULL
};
static struct attribute_group proximity_attribute_group = {
.attrs = proximity_sysfs_attrs,
};
static int lightsensor_get_adcvalue(struct gp2a_data *gp2a)
{
int i = 0;
int j = 0;
unsigned int adc_total = 0;
int adc_avr_value;
unsigned int adc_index = 0;
unsigned int adc_max = 0;
unsigned int adc_min = 0;
int value = 0;
/* get ADC */
value = gp2a->pdata->light_adc_value();
adc_index = (gp2a->adc_index_count++) % ADC_BUFFER_NUM;
/*ADC buffer initialize (light sensor off ---> light sensor on) */
if (!gp2a->adc_buf_initialized) {
gp2a->adc_buf_initialized = true;
for (j = 0; j < ADC_BUFFER_NUM; j++)
gp2a->adc_value_buf[j] = value;
} else
gp2a->adc_value_buf[adc_index] = value;
adc_max = gp2a->adc_value_buf[0];
adc_min = gp2a->adc_value_buf[0];
for (i = 0; i < ADC_BUFFER_NUM; i++) {
adc_total += gp2a->adc_value_buf[i];
if (adc_max < gp2a->adc_value_buf[i])
adc_max = gp2a->adc_value_buf[i];
if (adc_min > gp2a->adc_value_buf[i])
adc_min = gp2a->adc_value_buf[i];
}
adc_avr_value = (adc_total-(adc_max+adc_min))/(ADC_BUFFER_NUM-2);
if (gp2a->adc_index_count == ADC_BUFFER_NUM-1)
gp2a->adc_index_count = 0;
return adc_avr_value;
}
static void gp2a_work_func_light(struct work_struct *work)
{
struct gp2a_data *gp2a = container_of(work, struct gp2a_data,
work_light);
int adc = lightsensor_get_adcvalue(gp2a);
input_report_abs(gp2a->light_input_dev, ABS_MISC, adc);
input_sync(gp2a->light_input_dev);
}
/* This function is for light sensor. It operates every a few seconds.
* It asks for work to be done on a thread because i2c needs a thread
* context (slow and blocking) and then reschedules the timer to run again.
*/
static enum hrtimer_restart gp2a_timer_func(struct hrtimer *timer)
{
struct gp2a_data *gp2a = container_of(timer, struct gp2a_data, timer);
queue_work(gp2a->wq, &gp2a->work_light);
hrtimer_forward_now(&gp2a->timer, gp2a->light_poll_delay);
return HRTIMER_RESTART;
}
/* interrupt happened due to transition/change of near/far proximity state */
irqreturn_t gp2a_irq_handler(int irq, void *data)
{
struct gp2a_data *ip = data;
int val = gpio_get_value(ip->pdata->p_out);
if (val < 0) {
pr_err("%s: gpio_get_value error %d\n", __func__, val);
return IRQ_HANDLED;
}
gp2a_dbgmsg("gp2a: proximity val=%d\n", val);
/* 0 is close, 1 is far */
input_report_abs(ip->proximity_input_dev, ABS_DISTANCE, val);
input_sync(ip->proximity_input_dev);
wake_lock_timeout(&ip->prx_wake_lock, 3*HZ);
return IRQ_HANDLED;
}
static int gp2a_setup_irq(struct gp2a_data *gp2a)
{
int rc = -EIO;
struct gp2a_platform_data *pdata = gp2a->pdata;
int irq;
gp2a_dbgmsg("start\n");
rc = gpio_request(pdata->p_out, "gpio_proximity_out");
if (rc < 0) {
pr_err("%s: gpio %d request failed (%d)\n",
__func__, pdata->p_out, rc);
return rc;
}
rc = gpio_direction_input(pdata->p_out);
if (rc < 0) {
pr_err("%s: failed to set gpio %d as input (%d)\n",
__func__, pdata->p_out, rc);
goto err_gpio_direction_input;
}
irq = gpio_to_irq(pdata->p_out);
rc = request_irq(irq,
gp2a_irq_handler,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
"proximity_int",
gp2a);
if (rc < 0) {
pr_err("%s: request_irq(%d) failed for gpio %d (%d)\n",
__func__, irq,
pdata->p_out, rc);
goto err_request_irq;
}
/* start with interrupts disabled */
disable_irq(irq);
gp2a->irq = irq;
gp2a_dbgmsg("success\n");
goto done;
err_request_irq:
err_gpio_direction_input:
gpio_free(pdata->p_out);
done:
return rc;
}
static int gp2a_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret = -ENODEV;
struct input_dev *input_dev;
struct gp2a_data *gp2a;
struct gp2a_platform_data *pdata = client->dev.platform_data;
if (!pdata) {
pr_err("%s: missing pdata!\n", __func__);
return ret;
}
if (!pdata->power || !pdata->light_adc_value) {
pr_err("%s: incomplete pdata!\n", __func__);
return ret;
}
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
pr_err("%s: i2c functionality check failed!\n", __func__);
return ret;
}
gp2a = kzalloc(sizeof(struct gp2a_data), GFP_KERNEL);
if (!gp2a) {
pr_err("%s: failed to alloc memory for module data\n",
__func__);
return -ENOMEM;
}
gp2a->pdata = pdata;
gp2a->i2c_client = client;
i2c_set_clientdata(client, gp2a);
/* wake lock init */
wake_lock_init(&gp2a->prx_wake_lock, WAKE_LOCK_SUSPEND,
"prx_wake_lock");
mutex_init(&gp2a->power_lock);
ret = gp2a_setup_irq(gp2a);
if (ret) {
pr_err("%s: could not setup irq\n", __func__);
goto err_setup_irq;
}
/* allocate proximity input_device */
input_dev = input_allocate_device();
if (!input_dev) {
pr_err("%s: could not allocate input device\n", __func__);
goto err_input_allocate_device_proximity;
}
gp2a->proximity_input_dev = input_dev;
input_set_drvdata(input_dev, gp2a);
input_dev->name = "proximity";
input_set_capability(input_dev, EV_ABS, ABS_DISTANCE);
input_set_abs_params(input_dev, ABS_DISTANCE, 0, 1, 0, 0);
gp2a_dbgmsg("registering proximity input device\n");
ret = input_register_device(input_dev);
if (ret < 0) {
pr_err("%s: could not register input device\n", __func__);
input_free_device(input_dev);
goto err_input_register_device_proximity;
}
ret = sysfs_create_group(&input_dev->dev.kobj,
&proximity_attribute_group);
if (ret) {
pr_err("%s: could not create sysfs group\n", __func__);
goto err_sysfs_create_group_proximity;
}
/* hrtimer settings. we poll for light values using a timer. */
hrtimer_init(&gp2a->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
gp2a->light_poll_delay = ns_to_ktime(200 * NSEC_PER_MSEC);
gp2a->timer.function = gp2a_timer_func;
/* the timer just fires off a work queue request. we need a thread
to read the i2c (can be slow and blocking). */
gp2a->wq = create_singlethread_workqueue("gp2a_wq");
if (!gp2a->wq) {
ret = -ENOMEM;
pr_err("%s: could not create workqueue\n", __func__);
goto err_create_workqueue;
}
/* this is the thread function we run on the work queue */
INIT_WORK(&gp2a->work_light, gp2a_work_func_light);
/* allocate lightsensor-level input_device */
input_dev = input_allocate_device();
if (!input_dev) {
pr_err("%s: could not allocate input device\n", __func__);
ret = -ENOMEM;
goto err_input_allocate_device_light;
}
input_set_drvdata(input_dev, gp2a);
input_dev->name = "lightsensor-level";
input_set_capability(input_dev, EV_ABS, ABS_MISC);
input_set_abs_params(input_dev, ABS_MISC, 0, 1, 0, 0);
gp2a_dbgmsg("registering lightsensor-level input device\n");
ret = input_register_device(input_dev);
if (ret < 0) {
pr_err("%s: could not register input device\n", __func__);
input_free_device(input_dev);
goto err_input_register_device_light;
}
gp2a->light_input_dev = input_dev;
ret = sysfs_create_group(&input_dev->dev.kobj,
&light_attribute_group);
if (ret) {
pr_err("%s: could not create sysfs group\n", __func__);
goto err_sysfs_create_group_light;
}
goto done;
/* error, unwind it all */
err_sysfs_create_group_light:
input_unregister_device(gp2a->light_input_dev);
err_input_register_device_light:
err_input_allocate_device_light:
destroy_workqueue(gp2a->wq);
err_create_workqueue:
sysfs_remove_group(&gp2a->proximity_input_dev->dev.kobj,
&proximity_attribute_group);
err_sysfs_create_group_proximity:
input_unregister_device(gp2a->proximity_input_dev);
err_input_register_device_proximity:
err_input_allocate_device_proximity:
free_irq(gp2a->irq, 0);
gpio_free(gp2a->pdata->p_out);
err_setup_irq:
mutex_destroy(&gp2a->power_lock);
wake_lock_destroy(&gp2a->prx_wake_lock);
kfree(gp2a);
done:
return ret;
}
static int gp2a_suspend(struct device *dev)
{
/* We disable power only if proximity is disabled. If proximity
is enabled, we leave power on because proximity is allowed
to wake up device. We remove power without changing
gp2a->power_state because we use that state in resume.
*/
struct i2c_client *client = to_i2c_client(dev);
struct gp2a_data *gp2a = i2c_get_clientdata(client);
if (gp2a->power_state & LIGHT_ENABLED)
gp2a_light_disable(gp2a);
if (gp2a->power_state == LIGHT_ENABLED)
gp2a->pdata->power(false);
return 0;
}
static int gp2a_resume(struct device *dev)
{
/* Turn power back on if we were before suspend. */
struct i2c_client *client = to_i2c_client(dev);
struct gp2a_data *gp2a = i2c_get_clientdata(client);
if (gp2a->power_state == LIGHT_ENABLED)
gp2a->pdata->power(true);
if (gp2a->power_state & LIGHT_ENABLED)
gp2a_light_enable(gp2a);
return 0;
}
static int gp2a_i2c_remove(struct i2c_client *client)
{
struct gp2a_data *gp2a = i2c_get_clientdata(client);
sysfs_remove_group(&gp2a->light_input_dev->dev.kobj,
&light_attribute_group);
input_unregister_device(gp2a->light_input_dev);
sysfs_remove_group(&gp2a->proximity_input_dev->dev.kobj,
&proximity_attribute_group);
input_unregister_device(gp2a->proximity_input_dev);
free_irq(gp2a->irq, NULL);
gpio_free(gp2a->pdata->p_out);
if (gp2a->power_state) {
gp2a->power_state = 0;
if (gp2a->power_state & LIGHT_ENABLED)
gp2a_light_disable(gp2a);
gp2a->pdata->power(false);
}
destroy_workqueue(gp2a->wq);
mutex_destroy(&gp2a->power_lock);
wake_lock_destroy(&gp2a->prx_wake_lock);
kfree(gp2a);
return 0;
}
static const struct i2c_device_id gp2a_device_id[] = {
{"gp2a", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, gp2a_device_id);
static const struct dev_pm_ops gp2a_pm_ops = {
.suspend = gp2a_suspend,
.resume = gp2a_resume
};
static struct i2c_driver gp2a_i2c_driver = {
.driver = {
.name = "gp2a",
.owner = THIS_MODULE,
.pm = &gp2a_pm_ops
},
.probe = gp2a_i2c_probe,
.remove = gp2a_i2c_remove,
.id_table = gp2a_device_id,
};
static int __init gp2a_init(void)
{
return i2c_add_driver(&gp2a_i2c_driver);
}
static void __exit gp2a_exit(void)
{
i2c_del_driver(&gp2a_i2c_driver);
}
module_init(gp2a_init);
module_exit(gp2a_exit);
MODULE_AUTHOR("mjchen@sta.samsung.com");
MODULE_DESCRIPTION("Optical Sensor driver for gp2ap002a00f");
MODULE_LICENSE("GPL");
| 27.691729 | 77 | 0.722346 |
5e67d4290c56fb9591fa3f9fa46595ef96d7dd4b | 4,934 | h | C | exegesis/util/index_type.h | the-eager-ghosts/EXEgesis | ca6ab91c0e1f617881a34c8e794ea37466229590 | [
"Apache-2.0"
] | 201 | 2017-05-12T05:04:55.000Z | 2022-03-14T15:49:37.000Z | exegesis/util/index_type.h | the-eager-ghosts/EXEgesis | ca6ab91c0e1f617881a34c8e794ea37466229590 | [
"Apache-2.0"
] | 7 | 2017-05-22T11:52:06.000Z | 2022-02-26T16:30:46.000Z | exegesis/util/index_type.h | the-eager-ghosts/EXEgesis | ca6ab91c0e1f617881a34c8e794ea37466229590 | [
"Apache-2.0"
] | 35 | 2017-05-16T04:00:06.000Z | 2022-02-27T03:37:16.000Z | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef EXEGESIS_UTIL_INDEX_TYPE_H_
#define EXEGESIS_UTIL_INDEX_TYPE_H_
#include <functional>
#include <ostream>
#include <type_traits>
namespace exegesis {
// Defines an index type with strong type checks based on an underlying integral
// type, to be used as a handle to other objects. The class is designed so that
// two different index types are incompatible, and any attempts to pass one as
// the other leads to a compilation error.
//
// The index types support comparison, increment/decrement, but they do not
// support arithmetic, as these operations are ill-defined for a handle.
//
// Typical usage:
// DEFINE_INDEX_TYPE(RegisterIndex, int);
// DEFINE_INDEX_TYPE(InstructionIndex, int);
//
// RegisterIndex reg = GetRegisterIndex();
// DoSomethingWithRegister(reg);
// InstructionIndex inst = GetInstructionIndex();
// reg = inst; // Does not compile.
// DoSomethingWithInstruction(reg); // Does not compile.
#define DEFINE_INDEX_TYPE(Index, ValueType) \
struct Index##_index_tag {}; \
using Index = ::exegesis::IndexType<Index##_index_tag, ValueType>;
template <typename TagType, typename ValueT>
class IndexType {
public:
static_assert(std::is_integral<ValueT>::value,
"ValueType must be an integral type.");
// The type of the underlying value of the index.
using ValueType = ValueT;
// A hasher that allows using the index in std::unordered_map and
// std::unordered_set.
//
// Example usage:
// DEFINE_INDEX_TYPE(RegisterIndex, int);
// using RegisterSet = std::unordered_set<RegisterIndex,
// RegisterIndex::Hasher>
struct Hasher {
size_t operator()(const IndexType& index) const {
std::hash<ValueType> hasher;
return hasher(index.value());
}
};
constexpr IndexType() : value_(0) {}
explicit constexpr IndexType(ValueType value) : value_(value) {}
constexpr IndexType(const IndexType&) = default;
constexpr IndexType(IndexType&&) = default;
// The assignment operations on the index work the natural way: only another
// index of the same type may be assigned to the variable.
IndexType& operator=(const IndexType&) = default;
IndexType& operator=(IndexType&&) = default;
// Comparison between two indices.
constexpr inline bool operator==(const IndexType& other) const {
return value_ == other.value_;
}
constexpr inline bool operator!=(const IndexType& other) const {
return value_ != other.value_;
}
constexpr inline bool operator<(const IndexType& other) const {
return value_ < other.value_;
}
constexpr inline bool operator<=(const IndexType& other) const {
return value_ <= other.value_;
}
constexpr inline bool operator>(const IndexType& other) const {
return value_ > other.value_;
}
constexpr inline bool operator>=(const IndexType& other) const {
return value_ >= other.value_;
}
// Convenience operators for comparison between an index and the base type.
constexpr inline bool operator==(const ValueType& other) const {
return value_ == other;
}
constexpr inline bool operator!=(const ValueType& other) const {
return value_ != other;
}
constexpr inline bool operator<(const ValueType& other) const {
return value_ < other;
}
constexpr inline bool operator<=(const ValueType& other) const {
return value_ <= other;
}
constexpr inline bool operator>(const ValueType& other) const {
return value_ > other;
}
constexpr inline bool operator>=(const ValueType& other) const {
return value_ >= other;
}
// Increments and decrements to support for loops.
inline IndexType& operator++() {
++value_;
return *this;
}
inline IndexType operator++(int) {
const IndexType old = *this;
++value_;
return old;
}
inline IndexType& operator--() {
--value_;
return *this;
}
inline IndexType operator--(int) {
const IndexType old = *this;
--value_;
return old;
}
// Returns the raw value of the index.
constexpr ValueType value() const { return value_; }
private:
ValueType value_;
};
template <typename TagType, typename ValueType>
std::ostream& operator<<(std::ostream& os,
const IndexType<TagType, ValueType>& index) {
return os << index.value();
}
} // namespace exegesis
#endif // EXEGESIS_UTIL_INDEX_TYPE_H_
| 31.628205 | 80 | 0.704499 |
228dc9ee25065f8780c63141aa6b38b64dcf9eee | 3,254 | c | C | ATmega328 version/ledstripclock/lib.c | atoomnetmarc/LED-Strip-clock | 4cd4d176e73c46fc9e223714a248d21f263bacaa | [
"Apache-2.0"
] | null | null | null | ATmega328 version/ledstripclock/lib.c | atoomnetmarc/LED-Strip-clock | 4cd4d176e73c46fc9e223714a248d21f263bacaa | [
"Apache-2.0"
] | null | null | null | ATmega328 version/ledstripclock/lib.c | atoomnetmarc/LED-Strip-clock | 4cd4d176e73c46fc9e223714a248d21f263bacaa | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2012 Marc Ketel
SPDX-License-Identifier: Apache-2.0
*/
#include "lib.h"
#include "Ben Buxton/rotary.h"
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/wdt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/cpufunc.h>
#include <util/delay.h>
#include "rtc.h"
//1000Hz
uint16_t timer0counter = 0;
ISR(TIMER0_COMPA_vect)
{
if (timer0counter==0)
{
timer0counter = 100;
event |= EV_10Hz;
}
timer0counter--;
}
void shiftOut(uint8_t * buffer, uint8_t len)
{
uint8_t i;
SPDR = buffer[0];
for (i=1;i<len;i++)
{
loop_until_bit_is_set(SPSR, SPIF);
SPDR = buffer[i];
}
loop_until_bit_is_set(SPSR, SPIF);
PORTB |= _BV(PB0);
_delay_loop_1(20);
PORTB &= ~_BV(PB0);
}
void init(void)
{
clock_prescale_set(clock_div_1); //sysclk = 16MHz
power_all_disable();
//SPI
power_spi_enable();
DDRB |= _BV(PB0) | _BV(PB2) | _BV(PB3) | _BV(PB5);
SPCR |= _BV(SPE) | _BV(MSTR) | _BV(SPI2X);
//ADC
power_adc_enable();
DIDR0 |= _BV(ADC0D);
ADMUX |= _BV(REFS0); //AVCC with external capacitor at AREF pin
//Division Factor 64: 250KHz
ADCSRA |= _BV(ADPS1) | _BV(ADPS2) | _BV(ADEN);
PORTC |= _BV(PC0);
//Timer0
power_timer0_enable();
TCCR0A |= _BV(WGM01); //CTC mode
TCCR0B |= _BV(CS00) | _BV(CS01); //clk/64
TIMSK0 |= _BV(OCIE0A); //Timer/Counter0 Output Compare Match A Interrupt Enable
OCR0A = 0xF9; //1KHz
//Timer1
power_timer1_enable();
DDRB |= _BV(PB1);
//10-bit PWM
//TCCR1A |= _BV(WGM10) | _BV(WGM11);
//TCCR1B |= _BV(WGM12);
TCCR1B |= _BV(WGM13);
TCCR1A |= _BV(COM1A0) | _BV(COM1A1); //Set OC1A on Compare Match when upcounting. Clear OC1A on Compare Match when downcounting.
TCCR1B |= _BV(CS10); //clk/0
//OCR1A = 0x03FF; //max on
OCR1A = 0x0001; //min on
ICR1 = 0x1F3F; //1KHz
//PIR sensor
PORTC |= _BV(PC5);
//Rotary encoder
initRotaryEncoder();
//Enable pull-up on unused ports.
PORTB |= _BV(PB4) | _BV(PB6) | _BV(PB7);
PORTC |= _BV(PC1) | _BV(PC2) | _BV(PC3) | _BV(PC4);
PORTD |= _BV(PD2) | _BV(PD3) | _BV(PD4);
event = 0;
//Setup RTC
initRTC();
// Activate interrupts
sei();
memset(shiftbuffer, 0x00, SHIFTSIZE);
shiftOut(shiftbuffer, SHIFTSIZE);
}
void addMinute(DS3231RegDateTime_t *dateTime)
{
int8_t minutes = dateTime->minutes1 + dateTime->minutes10*10;
int8_t hours = dateTime->hours1 + dateTime->hours10*10;
minutes++;
if (minutes >= 60)
{
minutes=0;
hours++;
}
if (hours>=24)
{
hours=0;
}
dateTime->minutes10 = minutes/10;
dateTime->minutes1 = minutes%10;
dateTime->hours10 = hours/10;
dateTime->hours1 = hours%10;
dateTime->seconds1 = 0;
dateTime->seconds10 = 0;
}
void substractMinute(DS3231RegDateTime_t *dateTime)
{
int8_t minutes = dateTime->minutes1 + dateTime->minutes10*10;
int8_t hours = dateTime->hours1 + dateTime->hours10*10;
minutes--;
if (minutes <= -1)
{
minutes=59;
hours--;
}
if (hours<=-1)
{
hours=23;
}
dateTime->minutes10 = minutes/10;
dateTime->minutes1 = minutes%10;
dateTime->hours10 = hours/10;
dateTime->hours1 = hours%10;
dateTime->seconds1 = 0;
dateTime->seconds10 = 0;
}
| 18.280899 | 129 | 0.642594 |
fbdd6e592f6683d9662851784bf34328a19a98df | 12,409 | h | C | plugin_III/game_III/meta/meta.CCheat.h | Aleksandr-Belousov/plugin-sdk | 5ca5f7d5575ae4138a4f165410a1acf0ae922260 | [
"Zlib"
] | 1 | 2020-10-06T21:10:27.000Z | 2020-10-06T21:10:27.000Z | plugin_III/game_III/meta/meta.CCheat.h | Aleksandr-Belousov/plugin-sdk | 5ca5f7d5575ae4138a4f165410a1acf0ae922260 | [
"Zlib"
] | null | null | null | plugin_III/game_III/meta/meta.CCheat.h | Aleksandr-Belousov/plugin-sdk | 5ca5f7d5575ae4138a4f165410a1acf0ae922260 | [
"Zlib"
] | 3 | 2020-10-03T21:34:05.000Z | 2020-12-19T01:52:38.000Z | /*
Plugin-SDK (Grand Theft Auto 3) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "PluginBase.h"
namespace plugin {
META_BEGIN(WeaponCheat)
static int address;
static int global_address;
static const int id = 0x490D90;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x490D90, 0x490E50, 0x490DE0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x492492,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(HealthCheat)
static int address;
static int global_address;
static const int id = 0x490E70;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x490E70, 0x490F30, 0x490EC0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x4924CC,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(TankCheat)
static int address;
static int global_address;
static const int id = 0x490EE0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x490EE0, 0x490FA0, 0x490F30>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x492523,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(BlowUpCarsCheat)
static int address;
static int global_address;
static const int id = 0x491040;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491040, 0x491100, 0x491090>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x492540,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(ChangePlayerCheat)
static int address;
static int global_address;
static const int id = 0x4910B0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4910B0, 0x491170, 0x491100>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x49255D,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(MayhemCheat)
static int address;
static int global_address;
static const int id = 0x4911C0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4911C0, 0x491280, 0x491210>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x49257A,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(EverybodyAttacksPlayerCheat)
static int address;
static int global_address;
static const int id = 0x491270;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491270, 0x491330, 0x4912C0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x492597,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(WeaponsForAllCheat)
static int address;
static int global_address;
static const int id = 0x491370;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491370, 0x491430, 0x4913C0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x4925B4,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(FastTimeCheat)
static int address;
static int global_address;
static const int id = 0x4913A0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4913A0, 0x491460, 0x4913F0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x4925D1,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(SlowTimeCheat)
static int address;
static int global_address;
static const int id = 0x4913F0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4913F0, 0x4914B0, 0x491440>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x4925EE,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(MoneyCheat)
static int address;
static int global_address;
static const int id = 0x491430;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491430, 0x4914F0, 0x491480>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x4924AF,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(ArmourCheat)
static int address;
static int global_address;
static const int id = 0x491460;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491460, 0x491520, 0x4914B0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x49260B,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(WantedLevelUpCheat)
static int address;
static int global_address;
static const int id = 0x491490;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491490, 0x491550, 0x4914E0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x4924E9,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(WantedLevelDownCheat)
static int address;
static int global_address;
static const int id = 0x4914F0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4914F0, 0x4915B0, 0x491540>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x492506,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(SunnyWeatherCheat)
static int address;
static int global_address;
static const int id = 0x491520;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491520, 0x4915E0, 0x491570>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x492628,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CloudyWeatherCheat)
static int address;
static int global_address;
static const int id = 0x491550;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491550, 0x491610, 0x4915A0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x492645,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(RainyWeatherCheat)
static int address;
static int global_address;
static const int id = 0x491580;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491580, 0x491640, 0x4915D0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x492662,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(FoggyWeatherCheat)
static int address;
static int global_address;
static const int id = 0x4915B0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4915B0, 0x491670, 0x491600>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x49267F,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(FastWeatherCheat)
static int address;
static int global_address;
static const int id = 0x4915E0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4915E0, 0x4916A0, 0x491630>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x49269C,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(OnlyRenderWheelsCheat)
static int address;
static int global_address;
static const int id = 0x491610;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491610, 0x4916D0, 0x491660>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x4926B9,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(ChittyChittyBangBangCheat)
static int address;
static int global_address;
static const int id = 0x491640;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491640, 0x491700, 0x491690>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x4926D6,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(StrongGripCheat)
static int address;
static int global_address;
static const int id = 0x491670;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x491670, 0x491730, 0x4916C0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x4926F3,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(NastyLimbsCheat)
static int address;
static int global_address;
static const int id = 0x4916A0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4916A0, 0x491760, 0x4916F0>;
// total references count: 10en (1), 11en (0), steam (0)
using refs_t = RefList<0x492710,100,0,0x492450,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
}
| 34.759104 | 65 | 0.775324 |
6605c654b41f5bb9a727d44bf86f06cc9863e565 | 2,241 | h | C | alljoyn/services/about/ios/inc/alljoyn/about/AJNAnnounceHandlerAdapter.h | WigWagCo/alljoyn | 1b148edd934882ca32fd319af86a5a927f9d35a7 | [
"0BSD"
] | 37 | 2015-01-18T21:27:23.000Z | 2018-01-12T00:33:43.000Z | alljoyn/services/about/ios/inc/alljoyn/about/AJNAnnounceHandlerAdapter.h | WigWagCo/alljoyn | 1b148edd934882ca32fd319af86a5a927f9d35a7 | [
"0BSD"
] | 14 | 2015-02-24T11:44:01.000Z | 2020-07-20T18:48:44.000Z | alljoyn/services/about/ios/inc/alljoyn/about/AJNAnnounceHandlerAdapter.h | WigWagCo/alljoyn | 1b148edd934882ca32fd319af86a5a927f9d35a7 | [
"0BSD"
] | 29 | 2015-01-23T16:40:52.000Z | 2019-10-21T12:22:30.000Z | /******************************************************************************
* Copyright (c) 2013-2014, AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#ifndef AJNAnnounceHandlerAdapter_H
#define AJNAnnounceHandlerAdapter_H
#import "AnnounceHandler.h"
#import "AJNAnnouncementListener.h"
/**
AnnounceHandlerAdapter enable bind the C++ AnnounceHandler API with an objective-c announcement listener
*/
class AJNAnnounceHandlerAdapter : public ajn::services::AnnounceHandler {
public:
// Handle to the objective-c announcement listener
id<AJNAnnouncementListener> AJNAnnouncementListener;
/**
Constructor
*/
AJNAnnounceHandlerAdapter(id<AJNAnnouncementListener> announcementListener);
/**
Destructor
*/
~AJNAnnounceHandlerAdapter();
/**
Called when a new announcement is received.
@param version The version of the AboutService.
@param port The port used by the AboutService.
@param busName Unique or well-known name of AllJoyn bus.
@param objectDescs Map of ObjectDescriptions using qcc::String as key std::vector<qcc::String> as value, describing interfaces
@param aboutData Map of AboutData using qcc::String as key and ajn::MsgArg as value
*/
void Announce(uint16_t version, uint16_t port, const char* busName, const ObjectDescriptions& objectDescs, const AboutData& aboutData);
};
#endif | 43.096154 | 139 | 0.688086 |
055fb420338ff221e9c81c7e0aba89da9c4afaa8 | 1,099 | c | C | interfaces/innerkits/huks_lite/hks_tmp_client.c | openharmony-sig-ci/security_huks | c53655cb393df290fc0a534d428c0e2fdfc1c83b | [
"Apache-2.0"
] | null | null | null | interfaces/innerkits/huks_lite/hks_tmp_client.c | openharmony-sig-ci/security_huks | c53655cb393df290fc0a534d428c0e2fdfc1c83b | [
"Apache-2.0"
] | null | null | null | interfaces/innerkits/huks_lite/hks_tmp_client.c | openharmony-sig-ci/security_huks | c53655cb393df290fc0a534d428c0e2fdfc1c83b | [
"Apache-2.0"
] | 2 | 2021-09-13T11:13:36.000Z | 2021-12-15T15:10:55.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hks_api.h"
struct hks_blob {
uint8_t type;
uint8_t *data;
uint32_t size;
};
HKS_API_EXPORT int32_t hks_generate_random(struct hks_blob *random)
{
if ((random == NULL) || (random->data == NULL)) {
return HKS_ERROR_NULL_POINTER;
}
if ((random->size == 0) || (random->size > HKS_MAX_RANDOM_LEN)) {
return HKS_ERROR_INVALID_ARGUMENT;
}
struct HksBlob temp = { random->size, random->data };
return HksGenerateRandom(NULL, &temp);
} | 31.4 | 75 | 0.696087 |
05d28c4714e89d53429d2738c9a7a8a7e3a953bd | 279 | h | C | Sources/AdBannerContainerView.h | CropNetwork/ad-support.ios | 1b9c8dc18defd1e3be7e287111eb2a74629a174b | [
"MIT"
] | null | null | null | Sources/AdBannerContainerView.h | CropNetwork/ad-support.ios | 1b9c8dc18defd1e3be7e287111eb2a74629a174b | [
"MIT"
] | null | null | null | Sources/AdBannerContainerView.h | CropNetwork/ad-support.ios | 1b9c8dc18defd1e3be7e287111eb2a74629a174b | [
"MIT"
] | null | null | null | //
// AdBannerContainerView.h
//
// Copyright © 2019 CROP.network. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AdBannerContainerView : UIView
- (void)placeContentView:(UIView *)view;
- (void)placeBannerView:(UIView *)view;
- (void)bannerViewWasRemoved;
@end
| 17.4375 | 55 | 0.724014 |
e8288ee20908c024d104a82a35d9e6f48e6b9755 | 1,853 | h | C | BJShipping/Classes/Other/Category/Utils/ActionSheetHelper.h | UEdge/BJ | bfe3c24f2e24f476996b049a303c7701d86eef8f | [
"Apache-2.0"
] | null | null | null | BJShipping/Classes/Other/Category/Utils/ActionSheetHelper.h | UEdge/BJ | bfe3c24f2e24f476996b049a303c7701d86eef8f | [
"Apache-2.0"
] | null | null | null | BJShipping/Classes/Other/Category/Utils/ActionSheetHelper.h | UEdge/BJ | bfe3c24f2e24f476996b049a303c7701d86eef8f | [
"Apache-2.0"
] | null | null | null | //
// ActionSheetHelper.h
// iPhoto
//
// Created by RockeyCai on 16/4/27.
// Copyright © 2016年 RockeyCai. All rights reserved.
//
#import <Foundation/Foundation.h>
@import UIKit;
typedef void (^CancelBlock)();
typedef void (^OKBlock)();
typedef void (^OtherBlock)(NSInteger);
@interface ActionSheetHelper : NSObject
/**
* ActionSheetHelper单例方法
*
* @return ActionSheetHelper
*/
+ (ActionSheetHelper *)getInstance;
/**
* 显示 UIActionSheet 默认显示确定,取消按钮
*
* @param title 标题
* @param okBlock 确定回调
* @param view 承载父页面
*/
-(void)showTitle:(NSString *)title
okBlock:(OKBlock)okBlock
view : (UIView*)view;
/**
* 显示 UIActionSheet
*
* @param title 标题
* @param cancleTitle 取消标题
* @param cancelBlock 取消回调
* @param okTitle 确定标题
* @param okBlock 确定回调
* @param view 承载父页面
*/
-(void)showTitle:(NSString *)title
cancelButtonTitle:(NSString *)cancleTitle
cancelBlock:(CancelBlock)cancelBlock
okButtonTitle:(NSString *)okTitle
okBlock:(OKBlock)okBlock
view:(UIView*)view;
/**
* 显示 UIActionSheet
*
* @param title 标题
* @param otherButtonTitles 其他标题集合
* @param otherBlock 其他回调
* @param view 承载父页面
*/
-(void)showTitle:(NSString *)title
otherButtonTitles:(NSArray *)otherButtonTitles
otherBlock:(OtherBlock)otherBlock
view:(UIView *)view;
/**
* 显示 UIActionSheet
*
* @param title 标题
* @param cTitle 取消标题
* @param cancelBlock 取消回调
* @param otherButtonTitles 其他标题集合
* @param otherBlock 其他回调
* @param view 承载父页面
*/
-(void)showTitle:(NSString *)title
cancelButtonTitle:(NSString *)cancelTitle
cancelBlock:(CancelBlock)cancelBlock
otherButtonTitles:(NSArray *)otherButtonTitles
otherBlock:(OtherBlock)otherBlock
view:(UIView *)view;
@end
| 20.820225 | 53 | 0.651376 |
d34c3d8f69fff51cdd53479466e87e4573686fa8 | 5,565 | c | C | src/gst-plugins/commons/kmsdectreebin.c | mconf/kms-core | 4e8e066f25084455519d9e671a2bc5ec89066fa1 | [
"Apache-2.0"
] | null | null | null | src/gst-plugins/commons/kmsdectreebin.c | mconf/kms-core | 4e8e066f25084455519d9e671a2bc5ec89066fa1 | [
"Apache-2.0"
] | 2 | 2019-08-19T15:09:41.000Z | 2019-08-19T18:10:12.000Z | src/gst-plugins/commons/kmsdectreebin.c | mconf/kms-core | 4e8e066f25084455519d9e671a2bc5ec89066fa1 | [
"Apache-2.0"
] | null | null | null | /*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "kmsdectreebin.h"
#include "kmsutils.h"
#define GST_DEFAULT_NAME "dectreebin"
#define GST_CAT_DEFAULT kms_dec_tree_bin_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define kms_dec_tree_bin_parent_class parent_class
G_DEFINE_TYPE (KmsDecTreeBin, kms_dec_tree_bin, KMS_TYPE_TREE_BIN);
static GstElement *
create_decoder_for_caps (const GstCaps * caps, const GstCaps * raw_caps)
{
GList *decoder_list, *filtered_list, *aux_list, *l;
GstElementFactory *decoder_factory = NULL;
GstElement *decoder = NULL;
gboolean contains_openh264 = FALSE;
decoder_list =
gst_element_factory_list_get_elements (GST_ELEMENT_FACTORY_TYPE_DECODER,
GST_RANK_NONE);
/* HACK: Augment the openh264 rank */
for (l = decoder_list; l != NULL; l = l->next) {
decoder_factory = GST_ELEMENT_FACTORY (l->data);
if (g_str_has_prefix (GST_OBJECT_NAME (decoder_factory), "libx264")) {
decoder_list = g_list_remove (decoder_list, l->data);
decoder_list = g_list_prepend (decoder_list, decoder_factory);
contains_openh264 = TRUE;
break;
}
}
decoder_factory = NULL;
/* Remove stream-format from raw_caps to allow select openh264dec */
if (contains_openh264 &&
g_str_has_suffix (gst_structure_get_name (gst_caps_get_structure (caps,
0)), "h264")) {
GstCaps *caps_copy;
GstStructure *structure;
structure = gst_structure_copy (gst_caps_get_structure (caps, 0));
gst_structure_remove_field (structure, "stream-format");
caps_copy = gst_caps_new_full (structure, NULL);
aux_list =
gst_element_factory_list_filter (decoder_list, caps_copy, GST_PAD_SINK,
FALSE);
gst_caps_unref (caps_copy);
} else {
aux_list =
gst_element_factory_list_filter (decoder_list, caps, GST_PAD_SINK,
FALSE);
}
filtered_list =
gst_element_factory_list_filter (aux_list, raw_caps, GST_PAD_SRC, FALSE);
for (l = filtered_list; l != NULL && decoder_factory == NULL; l = l->next) {
decoder_factory = GST_ELEMENT_FACTORY (l->data);
if (gst_element_factory_get_num_pad_templates (decoder_factory) != 2)
decoder_factory = NULL;
}
if (decoder_factory != NULL) {
decoder = gst_element_factory_create (decoder_factory, NULL);
}
gst_plugin_feature_list_free (filtered_list);
gst_plugin_feature_list_free (decoder_list);
gst_plugin_feature_list_free (aux_list);
return decoder;
}
static gboolean
kms_dec_tree_bin_configure (KmsDecTreeBin * self, const GstCaps * caps,
const GstCaps * raw_caps)
{
KmsTreeBin *tree_bin = KMS_TREE_BIN (self);
GstElement *dec, *output_tee;
GstPad *pad;
gchar *name;
dec = create_decoder_for_caps (caps, raw_caps);
if (dec == NULL) {
GST_WARNING_OBJECT (self, "Invalid decoder for caps %" GST_PTR_FORMAT,
caps);
return FALSE;
}
GST_DEBUG_OBJECT (self, "Decoder found: %" GST_PTR_FORMAT, dec);
name = gst_element_get_name (dec);
if (g_str_has_prefix (name, "opusdec")) {
g_object_set (dec, "plc", TRUE, "use-inband-fec", TRUE, NULL);
}
if (g_str_has_prefix (name, "openh264dec")) {
GstElement *parse = gst_element_factory_make ("h264parse", NULL);
pad = gst_element_get_static_pad (parse, "sink");
kms_utils_drop_until_keyframe (pad, TRUE);
gst_object_unref (pad);
gst_bin_add_many (GST_BIN (self), parse, dec, NULL);
gst_element_link (parse, dec);
gst_element_sync_state_with_parent (parse);
gst_element_sync_state_with_parent (dec);
kms_tree_bin_set_input_element (tree_bin, parse);
output_tee = kms_tree_bin_get_output_tee (tree_bin);
gst_element_link (dec, output_tee);
} else {
pad = gst_element_get_static_pad (dec, "sink");
kms_utils_drop_until_keyframe (pad, TRUE);
gst_object_unref (pad);
gst_bin_add (GST_BIN (self), dec);
gst_element_sync_state_with_parent (dec);
kms_tree_bin_set_input_element (tree_bin, dec);
output_tee = kms_tree_bin_get_output_tee (tree_bin);
gst_element_link (dec, output_tee);
}
g_free (name);
return TRUE;
}
KmsDecTreeBin *
kms_dec_tree_bin_new (const GstCaps * caps, const GstCaps * raw_caps)
{
GObject *dec;
dec = g_object_new (KMS_TYPE_DEC_TREE_BIN, NULL);
if (!kms_dec_tree_bin_configure (KMS_DEC_TREE_BIN (dec), caps, raw_caps)) {
g_object_unref (dec);
return NULL;
}
return KMS_DEC_TREE_BIN (dec);
}
static void
kms_dec_tree_bin_init (KmsDecTreeBin * self)
{
/* Nothing to do */
}
static void
kms_dec_tree_bin_class_init (KmsDecTreeBinClass * klass)
{
GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
gst_element_class_set_details_simple (gstelement_class,
"DecTreeBin",
"Generic",
"Bin to decode and distribute RAW media.",
"Miguel París Díaz <mparisdiaz@gmail.com>");
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
| 29.919355 | 79 | 0.724708 |
dd20f3a95c4e713ea78ef027aadab78986df2b7f | 3,163 | c | C | ch11/ifttt_ex/src/main.c | PacktPublishing/Internet-of-Things-with-ESP32 | 0eb0763b52ecf56ba3a3b1ab62fd4e41b7462018 | [
"MIT"
] | 45 | 2021-02-05T05:53:28.000Z | 2022-03-24T15:56:33.000Z | ch11/ifttt_ex/src/main.c | PacktPublishing/Internet-of-Things-with-ESP32 | 0eb0763b52ecf56ba3a3b1ab62fd4e41b7462018 | [
"MIT"
] | 1 | 2022-01-05T06:02:47.000Z | 2022-01-27T21:02:21.000Z | ch11/ifttt_ex/src/main.c | PacktPublishing/Internet-of-Things-with-ESP32 | 0eb0763b52ecf56ba3a3b1ab62fd4e41b7462018 | [
"MIT"
] | 8 | 2021-03-01T07:03:45.000Z | 2022-01-16T05:22:51.000Z | // openssl s_client -showcerts -connect maker.ifttt.com:443 last cert
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "private_include/esp_tls_mbedtls.h"
#include "app_temp.h"
#include "app_wifi.h"
#define TAG "app"
#define IFTTT_MAKER_URL "https://maker.ifttt.com"
#define QUEUE_SIZE 10
static QueueHandle_t temp_queue;
static const char REQUEST[] = "POST /trigger/temperature_received/with/key/" IFTTT_KEY " HTTP/1.1\r\n"
"Host: maker.ifttt.com\r\n"
"Content-Type: application/json\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s";
static const char JSON_DATA[] = "{\"value1\":\"%d\"}";
extern const uint8_t server_root_cert_pem_start[] asm("_binary_server_cert_pem_start");
extern const uint8_t server_root_cert_pem_end[] asm("_binary_server_cert_pem_end");
static void do_post(void *arg)
{
esp_tls_cfg_t cfg = {
.cacert_buf = server_root_cert_pem_start,
.cacert_bytes = server_root_cert_pem_end - server_root_cert_pem_start,
};
int16_t temp;
char json_data[32];
char request[256];
char reply[512];
while (1)
{
if (xQueueReceive(temp_queue, &(temp), (TickType_t)10) == pdFALSE)
{
ESP_LOGI(TAG, "nothing in the queue");
vTaskDelay(1000);
continue;
}
struct esp_tls *tls = esp_tls_conn_http_new(IFTTT_MAKER_URL, &cfg);
if (tls == NULL)
{
ESP_LOGE(TAG, "tls connection failed");
continue;
}
memset(json_data, 0, sizeof(json_data));
sprintf(json_data, JSON_DATA, temp);
memset(request, 0, sizeof(request));
sprintf(request, REQUEST, strlen(json_data), json_data);
int ret = esp_mbedtls_write(tls, request, strlen(request));
if (ret > 0)
{
while (1)
{
ret = esp_mbedtls_read(tls, (char *)reply, sizeof(reply) - 1);
if (ret > 0)
{
reply[ret] = 0;
ESP_LOGI(TAG, "%s", reply);
}
else
{
break;
}
}
}
esp_tls_conn_delete(tls);
}
vTaskDelete(NULL);
}
static void publish_reading(int temp, int hum)
{
if (xQueueSendToBack(temp_queue, (void *)&temp, (TickType_t)0) != pdPASS)
{
ESP_LOGW(TAG, "queue is full");
xQueueReset(temp_queue);
}
}
static void handle_wifi_connect(void)
{
xTaskCreate(do_post, "post_task", 15 * configMINIMAL_STACK_SIZE, NULL, 5, NULL);
apptemp_init(publish_reading);
}
static void handle_wifi_failed(void)
{
ESP_LOGE(TAG, "wifi failed");
}
void app_main()
{
temp_queue = xQueueCreate(QUEUE_SIZE, sizeof(int16_t));
connect_wifi_params_t cbs = {
.on_connected = handle_wifi_connect,
.on_failed = handle_wifi_failed};
appwifi_connect(cbs);
}
| 27.034188 | 102 | 0.582042 |
544f5a15cd3280aafae9db525300e6c23fdefb2c | 2,402 | h | C | typeprimitivemath.h | vasil-sd/cpp-row-types | c790e4e719e0e36565abc6cb7448812fed414cef | [
"MIT"
] | null | null | null | typeprimitivemath.h | vasil-sd/cpp-row-types | c790e4e719e0e36565abc6cb7448812fed414cef | [
"MIT"
] | null | null | null | typeprimitivemath.h | vasil-sd/cpp-row-types | c790e4e719e0e36565abc6cb7448812fed414cef | [
"MIT"
] | null | null | null | #ifndef __TYPEPRIMITIVEMATH__
#define __TYPEPRIMITIVEMATH__
#include "typeuniverse.h"
#include "typeprop.h"
#include "typeprint.h"
#include "typerelation.h"
#include "typeprimitive.h"
#include "stdio.h"
namespace typeprimitive
{
using namespace typeuniverse;
using namespace typeprop;
using namespace typerelation;
using namespace typeprint;
// TODO: add overflow/underflow checks
typedef MakeReflexive<Rel<ToList<
TPair<Char, Short>,
TPair<UChar, Short>,
TPair<UChar, UShort>,
TPair<Short, Int>,
TPair<UShort, Int>,
TPair<UShort, UInt>
>>> PrimitiveTypesSubtyping;
typedef Rel<Map<RelPathGetClosure, CloseRelation<PrimitiveTypesSubtyping>>> AllPrimitiveTypesSubtypings;
typedef Rel<ToList<
TPair<Char, cChar<0>>,
TPair<UChar, cUChar<0>>,
TPair<Short, cShort<0>>,
TPair<UShort, cUShort<0>>,
TPair<Int, cInt<0>>,
TPair<UInt, cUInt<0>>
>> PrimitiveTypesToConstantTypes;
template<typename T1, typename T2, typename R = TPair<AllPrimitiveTypesSubtypings::template R<T1, T2>, AllPrimitiveTypesSubtypings::template R<T2, T1>>>
struct GetBiggestTypeAux : False {};
template<typename T1, typename T2>
struct GetBiggestTypeAux<T1, T2, TPair<False, True>> : T1 {};
template<typename T1, typename T2>
struct GetBiggestTypeAux<T1, T2, TPair<True, False>> : T2 {};
template<typename T1, typename T2>
struct GetBiggestTypeAux<T1, T2, TPair<True, True>> : T1 {};
template<typename T1, typename T2>
using GetBiggestType = Essence<GetBiggestTypeAux<T1, T2>>;
template <typename V1, typename V2, typename R = PrimitiveTypesToConstantTypes::template F<GetBiggestType<TypeOf<V1>, TypeOf<V2>>> >
struct AddAux : R::template type_template<V1::cvalue + V2::cvalue> {};
template <typename V1, typename V2>
using Add = Essence<AddAux<V1, V2>>;
template <typename V1, typename V2, typename R = PrimitiveTypesToConstantTypes::template F<GetBiggestType<TypeOf<V1>, TypeOf<V2>>> >
struct MulAux : R::template type_template<V1::cvalue * V2::cvalue> {};
template <typename V1, typename V2>
using Mul = Essence<MulAux<V1, V2>>;
} // end of namespace typeprimitive
#endif // __TYPEPRIMITIVEMATH__
| 34.811594 | 152 | 0.661532 |
e1783a889451139e988bdcd3e100d87f047fcabd | 1,487 | c | C | 10-entrance/g/src/main.c | serjzimmerman/mipt-vladimirov-contest | bc0383654bbcdc780c75b24a7fc0d72380576f91 | [
"MIT"
] | null | null | null | 10-entrance/g/src/main.c | serjzimmerman/mipt-vladimirov-contest | bc0383654bbcdc780c75b24a7fc0d72380576f91 | [
"MIT"
] | null | null | null | 10-entrance/g/src/main.c | serjzimmerman/mipt-vladimirov-contest | bc0383654bbcdc780c75b24a7fc0d72380576f91 | [
"MIT"
] | null | null | null | #include <malloc.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
struct Window {
int min_x, max_x, min_y, max_y;
};
struct Facade {
int n, m, window_count;
struct Window *window_array;
};
int windows_overlap(struct Window *w1, struct Window *w2) {
if (w1->max_x <= w2->min_x || w2->max_x <= w1->min_x) {
return 0;
}
if (w1->max_y <= w1->min_y || w1->max_y <= w1->min_y) {
return 0;
}
return 1;
}
int window_inside(struct Window *w1, struct Facade *f1) {
if (w1->max_y > f1->m || w1->min_y < 0) {
return 0;
}
if (w1->max_x > f1->n || w1->min_x < 0) {
return 0;
}
return 1;
}
int main() {
int temp_count = 0, correct = 1, i, j;
struct Facade facade = {0};
struct Window *array;
scanf("%d %d", &facade.n, &facade.m);
scanf("%d", &temp_count);
array = (struct Window *)calloc(sizeof(struct Window) * temp_count, 1);
for (i = 0; i < temp_count; i++) {
scanf("%d %d %d %d", &array[i].min_x, &array[i].max_x, &array[i].min_y, &array[i].max_y);
}
facade.window_array = array;
facade.window_count = temp_count;
for (i = 0; i < temp_count; i++) {
if (window_inside(&array[i], &facade) == 0) {
correct = 0;
}
for (j = 0; j < temp_count; j++) {
if (j == i) {
continue;
}
if (windows_overlap(&array[i], &array[j])) {
correct = 0;
}
}
}
free(array);
printf("%s", (correct ? "correct\n" : "broken\n"));
return 0;
}
| 20.369863 | 93 | 0.547411 |
7c356c1b1cc5a301bc02765a9f4e8b3decf8e101 | 7,879 | c | C | src/ParMetis-4.0.3/libparmetis/debug.c | rustychris/schism | 3754530ef57b3a058906432b4a9fca4a670f395e | [
"Apache-2.0"
] | 42 | 2019-08-12T21:48:24.000Z | 2022-03-03T03:08:10.000Z | src/ParMetis-4.0.3/libparmetis/debug.c | rustychris/schism | 3754530ef57b3a058906432b4a9fca4a670f395e | [
"Apache-2.0"
] | 42 | 2019-08-19T21:57:12.000Z | 2022-03-03T17:42:01.000Z | src/ParMetis-4.0.3/libparmetis/debug.c | rustychris/schism | 3754530ef57b3a058906432b4a9fca4a670f395e | [
"Apache-2.0"
] | 51 | 2019-08-09T20:59:07.000Z | 2022-03-29T15:48:43.000Z | /*
* Copyright 1997, Regents of the University of Minnesota
*
* debug.c
*
* This file contains various functions that are used to display debuging
* information
*
* Started 10/20/96
* George
*
* $Id: debug.c 10391 2011-06-23 19:00:08Z karypis $
*
*/
#include <parmetislib.h>
/*************************************************************************
* This function prints a vector stored in each processor
**************************************************************************/
void PrintVector(ctrl_t *ctrl, idx_t n, idx_t first, idx_t *vec, char *title)
{
idx_t i, penum;
for (penum=0; penum<ctrl->npes; penum++) {
if (ctrl->mype == penum) {
if (ctrl->mype == 0)
fprintf(stdout, "%s\n", title);
fprintf(stdout, "\t%3"PRIDX". ", ctrl->mype);
for (i=0; i<n; i++)
fprintf(stdout, "[%"PRIDX" %"PRIDX"] ", first+i, vec[i]);
fprintf(stdout, "\n");
fflush(stdout);
}
gkMPI_Barrier(ctrl->comm);
}
}
/*************************************************************************
* This function prints a vector stored in each processor
**************************************************************************/
void PrintVector2(ctrl_t *ctrl, idx_t n, idx_t first, idx_t *vec, char *title)
{
idx_t i, penum;
for (penum=0; penum<ctrl->npes; penum++) {
if (ctrl->mype == penum) {
if (ctrl->mype == 0)
printf("%s\n", title);
printf("\t%3"PRIDX". ", ctrl->mype);
for (i=0; i<n; i++)
printf("[%"PRIDX" %"PRIDX".%"PRIDX"] ", first+i,
(idx_t)(vec[i]>=KEEP_BIT ? 1 : 0),
(idx_t)(vec[i]>=KEEP_BIT ? vec[i]-KEEP_BIT : vec[i]));
printf("\n");
fflush(stdout);
}
gkMPI_Barrier(ctrl->comm);
}
}
/*************************************************************************
* This function prints a vector stored in each processor
**************************************************************************/
void PrintPairs(ctrl_t *ctrl, idx_t n, ikv_t *pairs, char *title)
{
idx_t i, penum;
for (penum=0; penum<ctrl->npes; penum++) {
if (ctrl->mype == penum) {
if (ctrl->mype == 0)
printf("%s\n", title);
printf("\t%3"PRIDX". ", ctrl->mype);
for (i=0; i<n; i++)
printf("[%"PRIDX" %"PRIDX", %"PRIDX"] ", i, pairs[i].key, pairs[i].val);
printf("\n");
fflush(stdout);
}
gkMPI_Barrier(ctrl->comm);
}
}
/*************************************************************************
* This function prints the local portion of the graph stored at each
* processor
**************************************************************************/
void PrintGraph(ctrl_t *ctrl, graph_t *graph)
{
idx_t i, j, penum;
idx_t firstvtx;
gkMPI_Barrier(ctrl->comm);
firstvtx = graph->vtxdist[ctrl->mype];
for (penum=0; penum<ctrl->npes; penum++) {
if (ctrl->mype == penum) {
printf("\t%"PRIDX"", penum);
for (i=0; i<graph->nvtxs; i++) {
if (i==0)
printf("\t%2"PRIDX" %2"PRIDX"\t", firstvtx+i, graph->vwgt[i]);
else
printf("\t\t%2"PRIDX" %2"PRIDX"\t", firstvtx+i, graph->vwgt[i]);
for (j=graph->xadj[i]; j<graph->xadj[i+1]; j++)
printf("[%"PRIDX" %"PRIDX"] ", graph->adjncy[j], graph->adjwgt[j]);
printf("\n");
}
fflush(stdout);
}
gkMPI_Barrier(ctrl->comm);
}
}
/*************************************************************************
* This function prints the local portion of the graph stored at each
* processor along with degree information during refinement
**************************************************************************/
void PrintGraph2(ctrl_t *ctrl, graph_t *graph)
{
idx_t i, j, penum;
idx_t firstvtx;
gkMPI_Barrier(ctrl->comm);
firstvtx = graph->vtxdist[ctrl->mype];
for (penum=0; penum<ctrl->npes; penum++) {
if (ctrl->mype == penum) {
printf("\t%"PRIDX"", penum);
for (i=0; i<graph->nvtxs; i++) {
if (i==0)
printf("\t%2"PRIDX" %2"PRIDX" [%"PRIDX" %"PRIDX" %"PRIDX"]\t", firstvtx+i, graph->vwgt[i], graph->where[i], graph->ckrinfo[i].id, graph->ckrinfo[i].ed);
else
printf("\t\t%2"PRIDX" %2"PRIDX" [%"PRIDX" %"PRIDX" %"PRIDX"]\t", firstvtx+i, graph->vwgt[i], graph->where[i], graph->ckrinfo[i].id, graph->ckrinfo[i].ed);
for (j=graph->xadj[i]; j<graph->xadj[i+1]; j++)
printf("[%"PRIDX" %"PRIDX"] ", graph->adjncy[j], graph->adjwgt[j]);
printf("\n");
}
fflush(stdout);
}
gkMPI_Barrier(ctrl->comm);
}
}
/*************************************************************************
* This function prints the information computed during setup
**************************************************************************/
void PrintSetUpInfo(ctrl_t *ctrl, graph_t *graph)
{
idx_t i, j, penum;
gkMPI_Barrier(ctrl->comm);
for (penum=0; penum<ctrl->npes; penum++) {
if (ctrl->mype == penum) {
printf("PE: %"PRIDX", nnbrs: %"PRIDX"\n", ctrl->mype, graph->nnbrs);
printf("\tSending...\n");
for (i=0; i<graph->nnbrs; i++) {
printf("\t\tTo: %"PRIDX": ", graph->peind[i]);
for (j=graph->sendptr[i]; j<graph->sendptr[i+1]; j++)
printf("%"PRIDX" ", graph->sendind[j]);
printf("\n");
}
printf("\tReceiving...\n");
for (i=0; i<graph->nnbrs; i++) {
printf("\t\tFrom: %"PRIDX": ", graph->peind[i]);
for (j=graph->recvptr[i]; j<graph->recvptr[i+1]; j++)
printf("%"PRIDX" ", graph->recvind[j]);
printf("\n");
}
printf("\n");
}
gkMPI_Barrier(ctrl->comm);
}
}
/*************************************************************************
* This function prints information about the graphs that were sent/received
**************************************************************************/
void PrintTransferedGraphs(ctrl_t *ctrl, idx_t nnbrs, idx_t *peind,
idx_t *slens, idx_t *rlens, idx_t *sgraph, idx_t *rgraph)
{
idx_t i, ii, jj, ll, penum;
gkMPI_Barrier(ctrl->comm);
for (penum=0; penum<ctrl->npes; penum++) {
if (ctrl->mype == penum) {
printf("PE: %"PRIDX", nnbrs: %"PRIDX"", ctrl->mype, nnbrs);
for (ll=i=0; i<nnbrs; i++) {
if (slens[i+1]-slens[i] > 0) {
printf("\n\tTo %"PRIDX"\t", peind[i]);
for (ii=slens[i]; ii<slens[i+1]; ii++) {
printf("%"PRIDX" %"PRIDX" %"PRIDX", ", sgraph[ll], sgraph[ll+1], sgraph[ll+2]);
for (jj=0; jj<sgraph[ll+1]; jj++)
printf("[%"PRIDX" %"PRIDX"] ", sgraph[ll+3+2*jj], sgraph[ll+3+2*jj+1]);
printf("\n\t\t");
ll += 3+2*sgraph[ll+1];
}
}
}
for (ll=i=0; i<nnbrs; i++) {
if (rlens[i+1]-rlens[i] > 0) {
printf("\n\tFrom %"PRIDX"\t", peind[i]);
for (ii=rlens[i]; ii<rlens[i+1]; ii++) {
printf("%"PRIDX" %"PRIDX" %"PRIDX", ", rgraph[ll], rgraph[ll+1], rgraph[ll+2]);
for (jj=0; jj<rgraph[ll+1]; jj++)
printf("[%"PRIDX" %"PRIDX"] ", rgraph[ll+3+2*jj], rgraph[ll+3+2*jj+1]);
printf("\n\t\t");
ll += 3+2*rgraph[ll+1];
}
}
}
printf("\n");
}
gkMPI_Barrier(ctrl->comm);
}
}
/*************************************************************************
* This function writes a graph in the format used by serial METIS
**************************************************************************/
void WriteMetisGraph(idx_t nvtxs, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt)
{
idx_t i, j;
FILE *fp;
fp = fopen("test.graph", "w");
fprintf(fp, "%"PRIDX" %"PRIDX" 11", nvtxs, xadj[nvtxs]/2);
for (i=0; i<nvtxs; i++) {
fprintf(fp, "\n%"PRIDX" ", vwgt[i]);
for (j=xadj[i]; j<xadj[i+1]; j++)
fprintf(fp, " %"PRIDX" %"PRIDX"", adjncy[j]+1, adjwgt[j]);
}
fclose(fp);
}
| 31.516 | 164 | 0.460465 |
09e8d020ba11057c3c0cdc3e53490371e9844d36 | 3,111 | h | C | Payload_Type/Apollo/agent_code/mimikatz/mimikatz/modules/dpapi/kuhl_m_dpapi_oe.h | reznok/Apollo | 9ca995fd0a9b7ba155bd58ce5668007443ea28a5 | [
"BSD-3-Clause"
] | null | null | null | Payload_Type/Apollo/agent_code/mimikatz/mimikatz/modules/dpapi/kuhl_m_dpapi_oe.h | reznok/Apollo | 9ca995fd0a9b7ba155bd58ce5668007443ea28a5 | [
"BSD-3-Clause"
] | null | null | null | Payload_Type/Apollo/agent_code/mimikatz/mimikatz/modules/dpapi/kuhl_m_dpapi_oe.h | reznok/Apollo | 9ca995fd0a9b7ba155bd58ce5668007443ea28a5 | [
"BSD-3-Clause"
] | 2 | 2021-01-12T18:42:06.000Z | 2021-11-06T09:25:40.000Z | /* Benjamin DELPY `gentilkiwi`
http://blog.gentilkiwi.com
benjamin@gentilkiwi.com
Licence : https://creativecommons.org/licenses/by/4.0/
*/
#pragma once
#include "globals.h"
#include "kuhl_m_dpapi.h"
#include "../modules/rpc/kull_m_rpc_dpapi-entries.h"
typedef struct _KUHL_M_DPAPI_OE_MASTERKEY_ENTRY {
LIST_ENTRY navigator;
KUHL_M_DPAPI_MASTERKEY_ENTRY data;
} KUHL_M_DPAPI_OE_MASTERKEY_ENTRY, *PKUHL_M_DPAPI_OE_MASTERKEY_ENTRY;
#define KUHL_M_DPAPI_OE_CREDENTIAL_FLAG_MD4 0x00000001
#define KUHL_M_DPAPI_OE_CREDENTIAL_FLAG_SHA1 0x00000002
#define KUHL_M_DPAPI_OE_CREDENTIAL_FLAG_MD4p 0x00000004
#define KUHL_M_DPAPI_OE_CREDENTIAL_FLAG_GUID 0x80000000
typedef struct _KUHL_M_DPAPI_OE_CREDENTIAL_ENTRY {
LIST_ENTRY navigator;
KUHL_M_DPAPI_CREDENTIAL_ENTRY data;
/*
PVOID DPAPI_SYSTEM_machine;
PVOID DPAPI_SYSTEM_user;
*/
} KUHL_M_DPAPI_OE_CREDENTIAL_ENTRY, *PKUHL_M_DPAPI_OE_CREDENTIAL_ENTRY;
typedef struct _KUHL_M_DPAPI_OE_DOMAINKEY_ENTRY {
LIST_ENTRY navigator;
KUHL_M_DPAPI_DOMAINKEY_ENTRY data;
} KUHL_M_DPAPI_OE_DOMAINKEY_ENTRY, *PKUHL_M_DPAPI_OE_DOMAINKEY_ENTRY;
NTSTATUS kuhl_m_dpapi_oe_clean();
NTSTATUS kuhl_m_dpapi_oe_cache(int argc, wchar_t * argv[]);
BOOL kuhl_m_dpapi_oe_is_sid_valid_ForCacheOrAuto(PSID sid, LPCWSTR szSid, BOOL AutoOrCache);
BOOL kuhl_m_dpapi_oe_autosid(LPCWSTR filename, LPWSTR * pSid);
LIST_ENTRY gDPAPI_Masterkeys;
LIST_ENTRY gDPAPI_Credentials;
LIST_ENTRY gDPAPI_Domainkeys;
PKUHL_M_DPAPI_OE_MASTERKEY_ENTRY kuhl_m_dpapi_oe_masterkey_get(LPCGUID guid);
BOOL kuhl_m_dpapi_oe_masterkey_add(LPCGUID guid, LPCVOID key, DWORD keyLen);
void kuhl_m_dpapi_oe_masterkey_delete(PKUHL_M_DPAPI_OE_MASTERKEY_ENTRY entry);
void kuhl_m_dpapi_oe_masterkey_descr(PKUHL_M_DPAPI_OE_MASTERKEY_ENTRY entry);
void kuhl_m_dpapi_oe_masterkeys_delete();
void kuhl_m_dpapi_oe_masterkeys_descr();
PKUHL_M_DPAPI_OE_CREDENTIAL_ENTRY kuhl_m_dpapi_oe_credential_get(LPCWSTR sid, LPCGUID guid);
BOOL kuhl_m_dpapi_oe_credential_add(LPCWSTR sid, LPCGUID guid, LPCVOID md4hash, LPCVOID sha1hash, LPCVOID md4protectedhash, LPCWSTR password);
void kuhl_m_dpapi_oe_credential_delete(PKUHL_M_DPAPI_OE_CREDENTIAL_ENTRY entry);
void kuhl_m_dpapi_oe_credential_descr(PKUHL_M_DPAPI_OE_CREDENTIAL_ENTRY entry);
void kuhl_m_dpapi_oe_credentials_delete();
void kuhl_m_dpapi_oe_credentials_descr();
PKUHL_M_DPAPI_OE_DOMAINKEY_ENTRY kuhl_m_dpapi_oe_domainkey_get(LPCGUID guid);
BOOL kuhl_m_dpapi_oe_domainkey_add(LPCGUID guid, LPCVOID key, DWORD keyLen, BOOL isNewKey);
void kuhl_m_dpapi_oe_domainkey_delete(PKUHL_M_DPAPI_OE_DOMAINKEY_ENTRY entry);
void kuhl_m_dpapi_oe_domainkey_descr(PKUHL_M_DPAPI_OE_DOMAINKEY_ENTRY entry);
void kuhl_m_dpapi_oe_domainkeys_delete();
void kuhl_m_dpapi_oe_domainkeys_descr();
BOOL kuhl_m_dpapi_oe_credential_addtoEntry(PKUHL_M_DPAPI_OE_CREDENTIAL_ENTRY entry, LPCGUID guid, LPCVOID md4hash, LPCVOID sha1hash, LPCVOID md4protectedhash, LPCWSTR password);
BOOL kuhl_m_dpapi_oe_credential_copyEntryWithNewGuid(PKUHL_M_DPAPI_OE_CREDENTIAL_ENTRY entry, LPCGUID guid);
BOOL kuhl_m_dpapi_oe_SaveToFile(LPCWSTR filename);
BOOL kuhl_m_dpapi_oe_LoadFromFile(LPCWSTR filename); | 45.75 | 177 | 0.874317 |
6750eb7f6464d816c4ca46bcc06c9e93d2e13de0 | 1,697 | h | C | src/lib/common/include/common/profiler.h | moshik1/mcas | a6af06bc278993fb3ffe780f230d2396b2287c26 | [
"Apache-2.0"
] | 60 | 2020-04-28T08:15:07.000Z | 2022-03-08T10:35:15.000Z | src/lib/common/include/common/profiler.h | moshik1/mcas | a6af06bc278993fb3ffe780f230d2396b2287c26 | [
"Apache-2.0"
] | 66 | 2020-09-03T23:40:48.000Z | 2022-03-07T20:34:52.000Z | src/lib/common/include/common/profiler.h | moshik1/mcas | a6af06bc278993fb3ffe780f230d2396b2287c26 | [
"Apache-2.0"
] | 13 | 2019-11-02T06:30:36.000Z | 2022-01-26T01:56:42.000Z | /*
Copyright [2017-2020] [IBM 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.
*/
#ifndef _mcas_COMMON_PROFILER_H_
#define _mcas_COMMON_PROFILER_H_
#if defined HAS_PROFILER
#include <gperftools/profiler.h> /* No __has_include until C++17 */
#else
namespace
{
int ProfilerStart(const char *) { return -1; }
void ProfilerStop() {}
void ProfilerFlush() {}
}
#endif
#include <common/logging.h>
#include <common/moveable_value.h>
#include <cstdlib> /* getenv */
#include <string>
namespace common
{
struct profiler
{
private:
std::string _file;
common::moveable_value<bool> _running;
public:
explicit profiler(const std::string &file_, bool start_ = true)
: _file(file_)
, _running(false)
{
if ( start_ || bool(std::getenv("PROFILE")) )
{
start();
}
}
explicit profiler(const char *file_, bool start_ = true)
: profiler(std::string(file_ ? file_ : ""), start_)
{}
~profiler()
{
if ( _running )
{
ProfilerStop();
ProfilerFlush();
}
}
void start()
{
if ( ! _running && _file.size() )
{
_running = bool(ProfilerStart(_file.c_str()));
PLOG("Profile begins %s", _file.c_str());
}
}
};
}
#endif
| 22.626667 | 75 | 0.678256 |
e5a8cbba6dd872a8b196e08039a0e8483a1f4f71 | 678 | h | C | AVConference.framework/VCVideoRuleCollectionsCameraMac.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 4 | 2021-10-06T12:15:26.000Z | 2022-02-21T02:26:00.000Z | AVConference.framework/VCVideoRuleCollectionsCameraMac.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | null | null | null | AVConference.framework/VCVideoRuleCollectionsCameraMac.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 1 | 2021-10-08T07:40:53.000Z | 2021-10-08T07:40:53.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/AVConference.framework/AVConference
*/
@interface VCVideoRuleCollectionsCameraMac : VCVideoRuleCollectionsCamera {
unsigned int _decodeScore;
unsigned int _encodeScore;
<VCHardwareSettingsMacProtocol> * _hardwareSettings;
}
+ (id)sharedInstance;
- (void)computeDecodingScore;
- (void)computeEncodingScore;
- (void)initSupportedPayloads;
- (id)initWithHardwareSettings:(id)arg1;
- (void)resetEncodingRulesForCameraIsHD:(bool)arg1 isWVGA:(bool)arg2;
- (bool)setupH264Rules;
- (bool)setupH264WifiRules;
- (bool)setupHEVCRules;
- (bool)setupRules;
- (bool)useSoftFramerateSwitching;
@end
| 27.12 | 79 | 0.789086 |
c6512dcae52b172013987ed8590abc242a56adc9 | 10,278 | h | C | apps/wolfmqtt_demo/firmware/src/app_mqtt_task.h | carlosearm/net_apps_pic32mz | f6f36ead86f7a41f59dc52a4aec5a4108718f63f | [
"0BSD"
] | 2 | 2021-10-31T18:33:01.000Z | 2022-03-25T17:17:58.000Z | apps/wolfmqtt_demo/firmware/src/app_mqtt_task.h | carlosearm/net_apps_pic32mz | f6f36ead86f7a41f59dc52a4aec5a4108718f63f | [
"0BSD"
] | 1 | 2020-12-28T22:31:30.000Z | 2020-12-28T22:31:30.000Z | apps/wolfmqtt_demo/firmware/src/app_mqtt_task.h | carlosearm/net_apps_pic32mz | f6f36ead86f7a41f59dc52a4aec5a4108718f63f | [
"0BSD"
] | 6 | 2021-02-02T13:51:49.000Z | 2021-08-31T18:35:37.000Z | /*******************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
/*******************************************************************************
MPLAB Harmony Application Header File
Company:
Microchip Technology Inc.
File Name:
app_mqtt_task.h
Summary:
This header file provides prototypes and definitions for the application.
Description:
This header file provides function prototypes and data type definitions for
the application. Some of these are required by the system (such as the
"APP_Initialize" and "APP_Tasks" prototypes) and some of them are only used
internally by the application (such as the "APP_STATES" definition). Both
are defined here for convenience.
*******************************************************************************/
#ifndef _APP_MQTT_TASK_H_
#define _APP_MQTT_TASK_H_
// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include "configuration.h"
#include "definitions.h"
#include "tcpip/tcpip.h"
#include "wolfmqtt/mqtt_client.h"
// *****************************************************************************
// *****************************************************************************
// Section: Type Definitions
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
/* APP MQTT Client Data
Summary:
Holds MQTT client data
Description:
This structure holds the application's data.
Remarks:
Application strings and buffers are be defined outside this structure.
*/
/* MQTT client application state */
typedef enum
{
APP_MQTT_STATE_IDLE = 0,
APP_MQTT_STATE_BEGIN,
APP_MQTT_STATE_NET_INIT,
APP_MQTT_STATE_BEGIN_SN,
APP_MQTT_STATE_NET_SN_INIT,
APP_MQTT_STATE_INIT,
APP_MQTT_STATE_NET_CONNECT,
APP_MQTT_STATE_CLIENT_CONNECT,
APP_MQTT_STATE_SUBSCRIBE,
APP_MQTT_STATE_PUBLISH,
APP_MQTT_STATE_START_WAIT,
APP_MQTT_STATE_WAIT_MSG,
APP_MQTT_STATE_START_SUB_PING,
APP_MQTT_STATE_SUB_PING,
APP_MQTT_STATE_START_UNSUBSCRIBE,
APP_MQTT_STATE_UNSUBSCRIBE,
APP_MQTT_STATE_CLIENT_DISCONNECT,
APP_MQTT_STATE_INIT_PING,
APP_MQTT_STATE_WAIT_TO_PING,
APP_MQTT_STATE_PING,
APP_MQTT_STATE_NET_DISCONNECT,
APP_MQTT_STATE_DONE,
APP_MQTT_STATE_ERROR,
} APP_MQTT_CONTEXT_STATE;
// *****************************************************************************
/* APP MQTT Command
Summary:
Describes the MQTT command
Description:
This enumerated type describes the current MQTT command
Remarks:
None
*/
/* MQTT client command */
typedef enum
{
APP_MQTT_COMMAND_NONE = 0, // no command, invalid
APP_MQTT_COMMAND_SUBSCRIBE, // subscribe/publish
APP_MQTT_COMMAND_PING, // ping broker
} APP_MQTT_COMMAND;
// demo app configuration
// adjust to your needs
#define APP_MQTT_MAX_APP_NAME_SIZE 32
#define APP_MQTT_DEFAULT_APP_NAME "MQTT_NET_Client App"
// Default MQTT broker to use
#define APP_MQTT_MAX_BROKER_SIZE 32
#define APP_MQTT_DEFAULT_BROKER "mqtt.eclipseprojects.io"
#define APP_MQTT_DEFAULT_BROKER_PORT 1883
#define APP_MQTT_MAX_CLIENT_SIZE 32
#define APP_MQTT_DEFAULT_CLIENT_ID "MQTT_NET_Client"
#define APP_MQTT_MAX_SUBSCRIBE_TOPIC_SIZE 32
#define APP_MQTT_DEFAULT_SUBSCRIBE_TOPIC "MQTT_NET_Client topic"
#define APP_MQTT_MAX_PUBLISH_TOPIC_SIZE 32
#define APP_MQTT_DEFAULT_PUBLISH_TOPIC "MQTT_NET_Client topic"
#define APP_MQTT_MAX_LWT_SIZE 32
#define APP_MQTT_DEFAULT_LWT_TOPIC_NAME "MQTT_NET_Client LWT topic"
#define APP_MQTT_MAX_PUBLISH_MESSAGE_SIZE 64
#define APP_MQTT_DEFAULT_PUBLISH_MESSAGE "MQTT NET Demo Test Message"
#define APP_MQTT_MAX_USER_SIZE 64
#define APP_MQTT_DEFAULT_USER "MQTT_NET_User"
#define APP_MQTT_MAX_PASS_SIZE 16
#define APP_MQTT_DEFAULT_PASS "MQTT_NET_Pass"
#define APP_MQTT_TX_BUFF_SIZE 1024
#define APP_MQTT_RX_BUFF_SIZE 1024
#define APP_MQTT_MAX_KALIVE_TIMEOUT 1000
#define APP_MQTT_DEFAULT_KEEP_ALIVE 60
#define APP_MQTT_DEFAULT_CON_TIMEOUT 5000 // ms
#define APP_MQTT_DEFAULT_QOS MQTT_QOS_0
#define APP_MQTT_DEFAULT_AUTH false
#define APP_MQTT_DEFAULT_CMD_TIMEOUT_MS 30000
#define APP_MQTT_MAX_WAIT_TIMEOUT 120000
#define APP_MQTT_DEFAULT_PING_WAIT_MS 5000 // time between 2 pings, ms
#define APP_MQTT_CB_MESSAGE_BUFFER_SIZE 120
#define APP_MQTT_WAIT_MESSAGE_RETRIES 3
// WOLFMQTT_V5: max size of the MQTT control packet
#define APP_MQTT_MAX_CTRL_PKT_SIZE 768
// WOLFMQTT_V5: Enhanced authentication method
#define APP_MQTT_DEFAULT_EAUTH_METHOD "EXTERNAL"
// WOLFMQTT_V5: Default property content type
#define APP_MQTT_DEFAULT_CONTENT_TYPE "wolf_type"
// WOLFMQTT_V5: Max client ID length
#define APP_MQTT_MAX_PROP_CLIENT_ID_LEN 32
/* MQTT Client application context */
typedef struct
{
// current state
uint16_t currState; // APP_MQTT_CONTEXT_STATE value
uint16_t errorState; // APP_MQTT_CONTEXT_STATE value
int errorCode;
uint32_t currPacketId;
// wolfMQTT containers
MqttClient mqttClient;
MqttNet mqttNet;
MqttConnect mqttConnect;
MqttMessage mqttLwtMsg;
MqttSubscribe mqttSubscribe;
MqttUnsubscribe mqttUnsubscribe;
MqttTopic mqttTopic;
MqttPublish mqttPublish;
MqttDisconnect mqttDisconnect;
// app configuration
uint8_t* txBuff;
uint8_t* rxBuff;
uint16_t txBuffSize;
uint16_t rxBuffSize;
uint8_t qos; // MqttQoS value
uint8_t forceTls; // currently not used as NET_PRES handles it using the port number
uint8_t enableAuth;
uint8_t enableLwt;
uint8_t cleanSession;
uint8_t requestStop;
uint8_t msgReceived;
uint8_t mqttCommand; // current APP_MQTT_COMMAND
uint16_t brokerPort;
uint16_t waitMsgRetries;
uint32_t connTimeout; // connection timeout, ms
uint32_t cmdTimeout; // command timeout, ms
uint32_t tmoTick; // tick when the wait expires
char* pClientId;
uint16_t keepAliveSec;
uint16_t pingCount;
#ifdef WOLFMQTT_V5
uint16_t maxPktSize; // max packet accepted
uint16_t topicAlias;
uint16_t topicAliasMax;
uint8_t subIdAvailable; // Subscription ID available
uint8_t enableEAuth; // Enhanced authentication
MqttProp* propList; // list of added properties
#ifdef WOLFMQTT_PROPERTY_CB
char mqttPropClientId[APP_MQTT_MAX_PROP_CLIENT_ID_LEN + 1];
#endif // WOLFMQTT_PROPERTY_CB
#endif
char appName[APP_MQTT_MAX_APP_NAME_SIZE + 1] ;
char broker[APP_MQTT_MAX_BROKER_SIZE + 1];
char userName[APP_MQTT_MAX_USER_SIZE + 1];
char password[APP_MQTT_MAX_PASS_SIZE + 1];
char subscribeTopicName[APP_MQTT_MAX_SUBSCRIBE_TOPIC_SIZE + 1];
char publishTopicName[APP_MQTT_MAX_PUBLISH_TOPIC_SIZE + 1];
char clientId[APP_MQTT_MAX_CLIENT_SIZE + 1];
char lastWill[APP_MQTT_MAX_LWT_SIZE + 1];
char publishMessage[APP_MQTT_MAX_PUBLISH_MESSAGE_SIZE + 1];
} APP_MQTT_CONTEXT;
// *****************************************************************************
// *****************************************************************************
// Section: External Declarations
// *****************************************************************************
// *****************************************************************************
bool APP_MQTT_Init(void);
bool APP_MQTT_CommandsInit(void);
void APP_MQTT_Task(void);
APP_MQTT_CONTEXT* APP_MQTT_GetContext(void);
const char* APP_MQTT_GetStateString(void);
#endif /* _APP_MQTT_TASK_H_ */
//DOM-IGNORE-BEGIN
#ifdef __cplusplus
}
#endif
//DOM-IGNORE-END
/*******************************************************************************
End of File
*/
| 35.078498 | 103 | 0.593598 |
3c6200b38a784bada6b8192a27a6cc248a6918d2 | 9,733 | h | C | components/cast_certificate/cast_root_ca_cert_der-inc.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/cast_certificate/cast_root_ca_cert_der-inc.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/cast_certificate/cast_root_ca_cert_der-inc.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Certificate:
// Data:
// Version: 3 (0x2)
// Serial Number: 2 (0x2)
// Signature Algorithm: sha1WithRSAEncryption
// Issuer: C=US, ST=California, L=Mountain View, O=Google Inc,
// OU=Cast, CN=Cast Root CA
// Validity
// Not Before: Apr 2 17:34:26 2014 GMT
// Not After : Mar 28 17:34:26 2034 GMT
// Subject: C=US, ST=California, L=Mountain View, O=Google Inc, OU=Cast,
// CN=Cast Root CA
// Subject Public Key Info:
// Public Key Algorithm: rsaEncryption
// Public-Key: (2048 bit)
// Modulus:
// 00:ba:d9:65:9d:da:39:d3:c1:77:f6:d4:d0:ae:8f:
// 58:08:68:39:4a:95:ed:70:cf:fd:79:08:a9:aa:e5:
// e9:b8:a7:2d:a0:67:47:8a:9e:c9:cf:70:b3:05:87:
// 69:11:ec:70:98:97:c3:e6:c3:c3:eb:bd:c6:b0:3d:
// fc:4f:c1:5e:38:9f:da:cf:73:30:06:5b:79:37:c1:
// 5e:8c:87:47:94:9a:41:92:2a:d6:95:c4:71:5c:27:
// 5d:08:b1:80:c6:92:bd:1b:e3:41:97:a1:ec:75:9f:
// 55:9e:3e:9f:8f:1c:c7:65:64:07:d3:b3:96:a1:04:
// 9f:91:c4:de:0a:7b:6c:d9:c8:c0:78:31:a0:19:42:
// a9:e8:83:e3:ce:fc:f1:ce:c2:2e:24:46:95:09:19:
// ca:c0:46:b2:e5:01:ba:d7:4f:f3:bf:f6:69:ad:99:
// 04:fa:a0:07:39:0e:e6:df:51:47:07:c0:e4:a9:5c:
// 4b:94:c5:2f:b3:a0:30:7f:e7:95:6b:b2:af:32:0d:
// f1:8c:d5:6d:cb:7b:47:a7:08:ab:cb:27:a3:4d:cf:
// 4a:5a:f1:05:d1:f8:62:c5:10:2a:74:69:aa:e6:4b:
// 96:fb:9b:d8:63:e4:58:66:d3:ad:8a:6e:ff:7b:5e:
// f9:a5:56:1e:2d:82:31:5b:f0:e2:24:e6:41:4a:1f:
// ae:13
// Exponent: 65537 (0x10001)
// X509v3 extensions:
// X509v3 Basic Constraints:
// CA:TRUE, pathlen:2
// X509v3 Subject Key Identifier:
// 7C:9A:1E:7D:DF:79:54:BC:D7:CC:5E:CA:99:86:45:79:65:74:28:19
// X509v3 Authority Key Identifier:
// keyid:7C:9A:1E:7D:DF:79:54:BC:D7:CC:5E:CA:99:86:45:79:65:74
// :28:19
//
// X509v3 Key Usage:
// Certificate Sign, CRL Sign
// Signature Algorithm: sha1WithRSAEncryption
// 80:f4:5a:fb:3d:28:19:51:20:d7:d4:fb:12:97:4a:65:f2:58:
// 35:92:77:30:6a:f1:d7:b6:51:1a:7f:9a:cd:c7:7b:03:42:ad:
// 55:6a:00:af:f0:e1:06:c2:bd:6b:78:75:db:fe:41:11:53:4a:
// 39:bb:9a:3a:c6:59:34:2f:2c:33:e3:b2:d6:5c:7f:dd:78:eb:
// 71:5b:39:da:83:90:c5:31:e2:3f:23:ef:da:eb:2b:2d:77:5e:
// de:c3:43:d2:c9:6b:59:82:ca:d5:ed:fa:a1:64:5b:cb:f1:0d:
// 1a:62:e1:9c:e8:a7:18:70:f0:5f:17:96:f8:ed:86:db:ae:1d:
// e0:cf:3e:5d:2e:ee:16:6d:95:2b:3c:fd:97:f3:05:5a:24:68:
// 4d:39:b6:f8:e4:58:ba:f5:e0:26:78:51:c5:5b:5d:4e:09:e5:
// 6c:47:8b:7a:5a:2e:89:53:e6:cc:36:5b:26:3c:f8:72:43:02:
// 82:d2:2b:cd:f0:d3:a3:ec:13:3e:52:d5:83:3d:07:dc:1d:43:
// 65:7a:33:02:01:a3:ce:b7:d6:60:51:3b:09:c2:23:8a:32:fe:
// 98:19:60:62:93:85:cd:34:46:db:d5:23:0f:79:da:77:00:2a:
// 02:6d:83:58:ce:03:77:35:e1:a3:20:93:c2:4a:a2:a4:46:1c:
// 75:2c:1f:4d
const unsigned char kCastRootCaDer[] = {
0x30, 0x82, 0x03, 0xc5, 0x30, 0x82, 0x02, 0xad, 0xa0, 0x03, 0x02, 0x01,
0x02, 0x02, 0x01, 0x02, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x75, 0x31, 0x0b, 0x30,
0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13,
0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x43, 0x61, 0x6c,
0x69, 0x66, 0x6f, 0x72, 0x6e, 0x69, 0x61, 0x31, 0x16, 0x30, 0x14, 0x06,
0x03, 0x55, 0x04, 0x07, 0x0c, 0x0d, 0x4d, 0x6f, 0x75, 0x6e, 0x74, 0x61,
0x69, 0x6e, 0x20, 0x56, 0x69, 0x65, 0x77, 0x31, 0x13, 0x30, 0x11, 0x06,
0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x20, 0x49, 0x6e, 0x63, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04,
0x0b, 0x0c, 0x04, 0x43, 0x61, 0x73, 0x74, 0x31, 0x15, 0x30, 0x13, 0x06,
0x03, 0x55, 0x04, 0x03, 0x0c, 0x0c, 0x43, 0x61, 0x73, 0x74, 0x20, 0x52,
0x6f, 0x6f, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x34,
0x30, 0x34, 0x30, 0x32, 0x31, 0x37, 0x33, 0x34, 0x32, 0x36, 0x5a, 0x17,
0x0d, 0x33, 0x34, 0x30, 0x33, 0x32, 0x38, 0x31, 0x37, 0x33, 0x34, 0x32,
0x36, 0x5a, 0x30, 0x75, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04,
0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55,
0x04, 0x08, 0x0c, 0x0a, 0x43, 0x61, 0x6c, 0x69, 0x66, 0x6f, 0x72, 0x6e,
0x69, 0x61, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c,
0x0d, 0x4d, 0x6f, 0x75, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x20, 0x56, 0x69,
0x65, 0x77, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c,
0x0a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x20, 0x49, 0x6e, 0x63, 0x31,
0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x04, 0x43, 0x61,
0x73, 0x74, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c,
0x0c, 0x43, 0x61, 0x73, 0x74, 0x20, 0x52, 0x6f, 0x6f, 0x74, 0x20, 0x43,
0x41, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48,
0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f,
0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xba, 0xd9,
0x65, 0x9d, 0xda, 0x39, 0xd3, 0xc1, 0x77, 0xf6, 0xd4, 0xd0, 0xae, 0x8f,
0x58, 0x08, 0x68, 0x39, 0x4a, 0x95, 0xed, 0x70, 0xcf, 0xfd, 0x79, 0x08,
0xa9, 0xaa, 0xe5, 0xe9, 0xb8, 0xa7, 0x2d, 0xa0, 0x67, 0x47, 0x8a, 0x9e,
0xc9, 0xcf, 0x70, 0xb3, 0x05, 0x87, 0x69, 0x11, 0xec, 0x70, 0x98, 0x97,
0xc3, 0xe6, 0xc3, 0xc3, 0xeb, 0xbd, 0xc6, 0xb0, 0x3d, 0xfc, 0x4f, 0xc1,
0x5e, 0x38, 0x9f, 0xda, 0xcf, 0x73, 0x30, 0x06, 0x5b, 0x79, 0x37, 0xc1,
0x5e, 0x8c, 0x87, 0x47, 0x94, 0x9a, 0x41, 0x92, 0x2a, 0xd6, 0x95, 0xc4,
0x71, 0x5c, 0x27, 0x5d, 0x08, 0xb1, 0x80, 0xc6, 0x92, 0xbd, 0x1b, 0xe3,
0x41, 0x97, 0xa1, 0xec, 0x75, 0x9f, 0x55, 0x9e, 0x3e, 0x9f, 0x8f, 0x1c,
0xc7, 0x65, 0x64, 0x07, 0xd3, 0xb3, 0x96, 0xa1, 0x04, 0x9f, 0x91, 0xc4,
0xde, 0x0a, 0x7b, 0x6c, 0xd9, 0xc8, 0xc0, 0x78, 0x31, 0xa0, 0x19, 0x42,
0xa9, 0xe8, 0x83, 0xe3, 0xce, 0xfc, 0xf1, 0xce, 0xc2, 0x2e, 0x24, 0x46,
0x95, 0x09, 0x19, 0xca, 0xc0, 0x46, 0xb2, 0xe5, 0x01, 0xba, 0xd7, 0x4f,
0xf3, 0xbf, 0xf6, 0x69, 0xad, 0x99, 0x04, 0xfa, 0xa0, 0x07, 0x39, 0x0e,
0xe6, 0xdf, 0x51, 0x47, 0x07, 0xc0, 0xe4, 0xa9, 0x5c, 0x4b, 0x94, 0xc5,
0x2f, 0xb3, 0xa0, 0x30, 0x7f, 0xe7, 0x95, 0x6b, 0xb2, 0xaf, 0x32, 0x0d,
0xf1, 0x8c, 0xd5, 0x6d, 0xcb, 0x7b, 0x47, 0xa7, 0x08, 0xab, 0xcb, 0x27,
0xa3, 0x4d, 0xcf, 0x4a, 0x5a, 0xf1, 0x05, 0xd1, 0xf8, 0x62, 0xc5, 0x10,
0x2a, 0x74, 0x69, 0xaa, 0xe6, 0x4b, 0x96, 0xfb, 0x9b, 0xd8, 0x63, 0xe4,
0x58, 0x66, 0xd3, 0xad, 0x8a, 0x6e, 0xff, 0x7b, 0x5e, 0xf9, 0xa5, 0x56,
0x1e, 0x2d, 0x82, 0x31, 0x5b, 0xf0, 0xe2, 0x24, 0xe6, 0x41, 0x4a, 0x1f,
0xae, 0x13, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x60, 0x30, 0x5e, 0x30,
0x0f, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x08, 0x30, 0x06, 0x01, 0x01,
0xff, 0x02, 0x01, 0x02, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04,
0x16, 0x04, 0x14, 0x7c, 0x9a, 0x1e, 0x7d, 0xdf, 0x79, 0x54, 0xbc, 0xd7,
0xcc, 0x5e, 0xca, 0x99, 0x86, 0x45, 0x79, 0x65, 0x74, 0x28, 0x19, 0x30,
0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14,
0x7c, 0x9a, 0x1e, 0x7d, 0xdf, 0x79, 0x54, 0xbc, 0xd7, 0xcc, 0x5e, 0xca,
0x99, 0x86, 0x45, 0x79, 0x65, 0x74, 0x28, 0x19, 0x30, 0x0b, 0x06, 0x03,
0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, 0x30, 0x0d, 0x06,
0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00,
0x03, 0x82, 0x01, 0x01, 0x00, 0x80, 0xf4, 0x5a, 0xfb, 0x3d, 0x28, 0x19,
0x51, 0x20, 0xd7, 0xd4, 0xfb, 0x12, 0x97, 0x4a, 0x65, 0xf2, 0x58, 0x35,
0x92, 0x77, 0x30, 0x6a, 0xf1, 0xd7, 0xb6, 0x51, 0x1a, 0x7f, 0x9a, 0xcd,
0xc7, 0x7b, 0x03, 0x42, 0xad, 0x55, 0x6a, 0x00, 0xaf, 0xf0, 0xe1, 0x06,
0xc2, 0xbd, 0x6b, 0x78, 0x75, 0xdb, 0xfe, 0x41, 0x11, 0x53, 0x4a, 0x39,
0xbb, 0x9a, 0x3a, 0xc6, 0x59, 0x34, 0x2f, 0x2c, 0x33, 0xe3, 0xb2, 0xd6,
0x5c, 0x7f, 0xdd, 0x78, 0xeb, 0x71, 0x5b, 0x39, 0xda, 0x83, 0x90, 0xc5,
0x31, 0xe2, 0x3f, 0x23, 0xef, 0xda, 0xeb, 0x2b, 0x2d, 0x77, 0x5e, 0xde,
0xc3, 0x43, 0xd2, 0xc9, 0x6b, 0x59, 0x82, 0xca, 0xd5, 0xed, 0xfa, 0xa1,
0x64, 0x5b, 0xcb, 0xf1, 0x0d, 0x1a, 0x62, 0xe1, 0x9c, 0xe8, 0xa7, 0x18,
0x70, 0xf0, 0x5f, 0x17, 0x96, 0xf8, 0xed, 0x86, 0xdb, 0xae, 0x1d, 0xe0,
0xcf, 0x3e, 0x5d, 0x2e, 0xee, 0x16, 0x6d, 0x95, 0x2b, 0x3c, 0xfd, 0x97,
0xf3, 0x05, 0x5a, 0x24, 0x68, 0x4d, 0x39, 0xb6, 0xf8, 0xe4, 0x58, 0xba,
0xf5, 0xe0, 0x26, 0x78, 0x51, 0xc5, 0x5b, 0x5d, 0x4e, 0x09, 0xe5, 0x6c,
0x47, 0x8b, 0x7a, 0x5a, 0x2e, 0x89, 0x53, 0xe6, 0xcc, 0x36, 0x5b, 0x26,
0x3c, 0xf8, 0x72, 0x43, 0x02, 0x82, 0xd2, 0x2b, 0xcd, 0xf0, 0xd3, 0xa3,
0xec, 0x13, 0x3e, 0x52, 0xd5, 0x83, 0x3d, 0x07, 0xdc, 0x1d, 0x43, 0x65,
0x7a, 0x33, 0x02, 0x01, 0xa3, 0xce, 0xb7, 0xd6, 0x60, 0x51, 0x3b, 0x09,
0xc2, 0x23, 0x8a, 0x32, 0xfe, 0x98, 0x19, 0x60, 0x62, 0x93, 0x85, 0xcd,
0x34, 0x46, 0xdb, 0xd5, 0x23, 0x0f, 0x79, 0xda, 0x77, 0x00, 0x2a, 0x02,
0x6d, 0x83, 0x58, 0xce, 0x03, 0x77, 0x35, 0xe1, 0xa3, 0x20, 0x93, 0xc2,
0x4a, 0xa2, 0xa4, 0x46, 0x1c, 0x75, 0x2c, 0x1f, 0x4d};
| 65.322148 | 80 | 0.583993 |
48b22c0142b435b467a557deb8040403a01a7c67 | 296 | c | C | snapgear_linux/user/fnord/str_copy.c | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/user/fnord/str_copy.c | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/user/fnord/str_copy.c | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | 3 | 2016-06-13T13:20:56.000Z | 2019-12-05T02:31:23.000Z | #include "str.h"
unsigned int str_copy(char *out,const char *in) {
register char* s=out;
register const char* t=in;
for (;;) {
if (!(*s=*t)) break; ++s; ++t;
if (!(*s=*t)) break; ++s; ++t;
if (!(*s=*t)) break; ++s; ++t;
if (!(*s=*t)) break; ++s; ++t;
}
return s-out;
}
| 21.142857 | 49 | 0.476351 |
71866e3f2a0faddc7b658bec3d05c9dab40e419f | 25,902 | h | C | Audio_SpectrumAnalyser/SpectrumAnalyzer_NeoPixel/SpectrumAnalyzer_NeoPixel.cydsn/Generated_Source/PSoC4/PWM_6250Hz.h | Vanrykel/Microcontrollers | 385799d17578aec736e4a0dc550102b87fb5bade | [
"MIT"
] | 1 | 2020-11-24T15:24:44.000Z | 2020-11-24T15:24:44.000Z | Audio_SpectrumAnalyser/SpectrumAnalyzer_NeoPixel/SpectrumAnalyzer_NeoPixel.cydsn/Generated_Source/PSoC4/PWM_6250Hz.h | Vanrykel/Microcontrollers | 385799d17578aec736e4a0dc550102b87fb5bade | [
"MIT"
] | null | null | null | Audio_SpectrumAnalyser/SpectrumAnalyzer_NeoPixel/SpectrumAnalyzer_NeoPixel.cydsn/Generated_Source/PSoC4/PWM_6250Hz.h | Vanrykel/Microcontrollers | 385799d17578aec736e4a0dc550102b87fb5bade | [
"MIT"
] | null | null | null | /*******************************************************************************
* File Name: PWM_6250Hz.h
* Version 3.0
*
* Description:
* Contains the prototypes and constants for the functions available to the
* PWM user module.
*
* Note:
*
********************************************************************************
* Copyright 2008-2012, Cypress Semiconductor Corporation. All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
********************************************************************************/
#if !defined(CY_PWM_PWM_6250Hz_H)
#define CY_PWM_PWM_6250Hz_H
#include "cytypes.h"
#include "cyfitter.h"
#include "CyLib.h" /* For CyEnterCriticalSection() and CyExitCriticalSection() functions */
extern uint8 PWM_6250Hz_initVar;
/***************************************
* Conditional Compilation Parameters
***************************************/
#define PWM_6250Hz_Resolution 8u
#define PWM_6250Hz_UsingFixedFunction 0u
#define PWM_6250Hz_DeadBandMode 0u
#define PWM_6250Hz_KillModeMinTime 0u
#define PWM_6250Hz_KillMode 0u
#define PWM_6250Hz_PWMMode 0u
#define PWM_6250Hz_PWMModeIsCenterAligned 0u
#define PWM_6250Hz_DeadBandUsed 0u
#define PWM_6250Hz_DeadBand2_4 0u
#if !defined(PWM_6250Hz_PWMUDB_genblk8_stsreg__REMOVED)
#define PWM_6250Hz_UseStatus 1u
#else
#define PWM_6250Hz_UseStatus 0u
#endif /* !defined(PWM_6250Hz_PWMUDB_genblk8_stsreg__REMOVED) */
#if !defined(PWM_6250Hz_PWMUDB_genblk1_ctrlreg__REMOVED)
#define PWM_6250Hz_UseControl 1u
#else
#define PWM_6250Hz_UseControl 0u
#endif /* !defined(PWM_6250Hz_PWMUDB_genblk1_ctrlreg__REMOVED) */
#define PWM_6250Hz_UseOneCompareMode 1u
#define PWM_6250Hz_MinimumKillTime 1u
#define PWM_6250Hz_EnableMode 0u
#define PWM_6250Hz_CompareMode1SW 0u
#define PWM_6250Hz_CompareMode2SW 0u
/* Check to see if required defines such as CY_PSOC5LP are available */
/* They are defined starting with cy_boot v3.0 */
#if !defined (CY_PSOC5LP)
#error Component PWM_v3_0 requires cy_boot v3.0 or later
#endif /* (CY_ PSOC5LP) */
/* Use Kill Mode Enumerated Types */
#define PWM_6250Hz__B_PWM__DISABLED 0
#define PWM_6250Hz__B_PWM__ASYNCHRONOUS 1
#define PWM_6250Hz__B_PWM__SINGLECYCLE 2
#define PWM_6250Hz__B_PWM__LATCHED 3
#define PWM_6250Hz__B_PWM__MINTIME 4
/* Use Dead Band Mode Enumerated Types */
#define PWM_6250Hz__B_PWM__DBMDISABLED 0
#define PWM_6250Hz__B_PWM__DBM_2_4_CLOCKS 1
#define PWM_6250Hz__B_PWM__DBM_256_CLOCKS 2
/* Used PWM Mode Enumerated Types */
#define PWM_6250Hz__B_PWM__ONE_OUTPUT 0
#define PWM_6250Hz__B_PWM__TWO_OUTPUTS 1
#define PWM_6250Hz__B_PWM__DUAL_EDGE 2
#define PWM_6250Hz__B_PWM__CENTER_ALIGN 3
#define PWM_6250Hz__B_PWM__DITHER 5
#define PWM_6250Hz__B_PWM__HARDWARESELECT 4
/* Used PWM Compare Mode Enumerated Types */
#define PWM_6250Hz__B_PWM__LESS_THAN 1
#define PWM_6250Hz__B_PWM__LESS_THAN_OR_EQUAL 2
#define PWM_6250Hz__B_PWM__GREATER_THAN 3
#define PWM_6250Hz__B_PWM__GREATER_THAN_OR_EQUAL_TO 4
#define PWM_6250Hz__B_PWM__EQUAL 0
#define PWM_6250Hz__B_PWM__FIRMWARE 5
/***************************************
* Data Struct Definition
***************************************/
/**************************************************************************
* Sleep Wakeup Backup structure for PWM Component
*************************************************************************/
typedef struct
{
uint8 PWMEnableState;
#if(!PWM_6250Hz_UsingFixedFunction)
uint8 PWMUdb; /* PWM Current Counter value */
#if(!PWM_6250Hz_PWMModeIsCenterAligned)
uint8 PWMPeriod;
#endif /* (!PWM_6250Hz_PWMModeIsCenterAligned) */
#if (PWM_6250Hz_UseStatus)
uint8 InterruptMaskValue; /* PWM Current Interrupt Mask */
#endif /* (PWM_6250Hz_UseStatus) */
/* Backup for Deadband parameters */
#if(PWM_6250Hz_DeadBandMode == PWM_6250Hz__B_PWM__DBM_256_CLOCKS || \
PWM_6250Hz_DeadBandMode == PWM_6250Hz__B_PWM__DBM_2_4_CLOCKS)
uint8 PWMdeadBandValue; /* Dead Band Counter Current Value */
#endif /* deadband count is either 2-4 clocks or 256 clocks */
/* Backup Kill Mode Counter*/
#if(PWM_6250Hz_KillModeMinTime)
uint8 PWMKillCounterPeriod; /* Kill Mode period value */
#endif /* (PWM_6250Hz_KillModeMinTime) */
/* Backup control register */
#if(PWM_6250Hz_UseControl)
uint8 PWMControlRegister; /* PWM Control Register value */
#endif /* (PWM_6250Hz_UseControl) */
#endif /* (!PWM_6250Hz_UsingFixedFunction) */
}PWM_6250Hz_backupStruct;
/***************************************
* Function Prototypes
**************************************/
void PWM_6250Hz_Start(void) ;
void PWM_6250Hz_Stop(void) ;
#if (PWM_6250Hz_UseStatus || PWM_6250Hz_UsingFixedFunction)
void PWM_6250Hz_SetInterruptMode(uint8 interruptMode) ;
uint8 PWM_6250Hz_ReadStatusRegister(void) ;
#endif /* (PWM_6250Hz_UseStatus || PWM_6250Hz_UsingFixedFunction) */
#define PWM_6250Hz_GetInterruptSource() PWM_6250Hz_ReadStatusRegister()
#if (PWM_6250Hz_UseControl)
uint8 PWM_6250Hz_ReadControlRegister(void) ;
void PWM_6250Hz_WriteControlRegister(uint8 control) ;
#endif /* (PWM_6250Hz_UseControl) */
#if (PWM_6250Hz_UseOneCompareMode)
#if (PWM_6250Hz_CompareMode1SW)
void PWM_6250Hz_SetCompareMode(uint8 comparemode) ;
#endif /* (PWM_6250Hz_CompareMode1SW) */
#else
#if (PWM_6250Hz_CompareMode1SW)
void PWM_6250Hz_SetCompareMode1(uint8 comparemode) ;
#endif /* (PWM_6250Hz_CompareMode1SW) */
#if (PWM_6250Hz_CompareMode2SW)
void PWM_6250Hz_SetCompareMode2(uint8 comparemode) ;
#endif /* (PWM_6250Hz_CompareMode2SW) */
#endif /* (PWM_6250Hz_UseOneCompareMode) */
#if (!PWM_6250Hz_UsingFixedFunction)
uint8 PWM_6250Hz_ReadCounter(void) ;
uint8 PWM_6250Hz_ReadCapture(void) ;
#if (PWM_6250Hz_UseStatus)
void PWM_6250Hz_ClearFIFO(void) ;
#endif /* (PWM_6250Hz_UseStatus) */
void PWM_6250Hz_WriteCounter(uint8 counter) ;
#endif /* (!PWM_6250Hz_UsingFixedFunction) */
void PWM_6250Hz_WritePeriod(uint8 period) ;
uint8 PWM_6250Hz_ReadPeriod(void) ;
#if (PWM_6250Hz_UseOneCompareMode)
void PWM_6250Hz_WriteCompare(uint8 compare) ;
uint8 PWM_6250Hz_ReadCompare(void) ;
#else
void PWM_6250Hz_WriteCompare1(uint8 compare) ;
uint8 PWM_6250Hz_ReadCompare1(void) ;
void PWM_6250Hz_WriteCompare2(uint8 compare) ;
uint8 PWM_6250Hz_ReadCompare2(void) ;
#endif /* (PWM_6250Hz_UseOneCompareMode) */
#if (PWM_6250Hz_DeadBandUsed)
void PWM_6250Hz_WriteDeadTime(uint8 deadtime) ;
uint8 PWM_6250Hz_ReadDeadTime(void) ;
#endif /* (PWM_6250Hz_DeadBandUsed) */
#if ( PWM_6250Hz_KillModeMinTime)
void PWM_6250Hz_WriteKillTime(uint8 killtime) ;
uint8 PWM_6250Hz_ReadKillTime(void) ;
#endif /* ( PWM_6250Hz_KillModeMinTime) */
void PWM_6250Hz_Init(void) ;
void PWM_6250Hz_Enable(void) ;
void PWM_6250Hz_Sleep(void) ;
void PWM_6250Hz_Wakeup(void) ;
void PWM_6250Hz_SaveConfig(void) ;
void PWM_6250Hz_RestoreConfig(void) ;
/***************************************
* Initialization Values
**************************************/
#define PWM_6250Hz_INIT_PERIOD_VALUE 255u
#define PWM_6250Hz_INIT_COMPARE_VALUE1 127u
#define PWM_6250Hz_INIT_COMPARE_VALUE2 63u
#define PWM_6250Hz_INIT_INTERRUPTS_MODE (uint8)(((uint8)(0u << PWM_6250Hz_STATUS_TC_INT_EN_MASK_SHIFT)) | \
(uint8)((uint8)(0u << PWM_6250Hz_STATUS_CMP2_INT_EN_MASK_SHIFT)) | \
(uint8)((uint8)(0u << PWM_6250Hz_STATUS_CMP1_INT_EN_MASK_SHIFT )) | \
(uint8)((uint8)(0u << PWM_6250Hz_STATUS_KILL_INT_EN_MASK_SHIFT )))
#define PWM_6250Hz_DEFAULT_COMPARE2_MODE (uint8)((uint8)1u << PWM_6250Hz_CTRL_CMPMODE2_SHIFT)
#define PWM_6250Hz_DEFAULT_COMPARE1_MODE (uint8)((uint8)1u << PWM_6250Hz_CTRL_CMPMODE1_SHIFT)
#define PWM_6250Hz_INIT_DEAD_TIME 1u
/********************************
* Registers
******************************** */
#if (PWM_6250Hz_UsingFixedFunction)
#define PWM_6250Hz_PERIOD_LSB (*(reg16 *) PWM_6250Hz_PWMHW__PER0)
#define PWM_6250Hz_PERIOD_LSB_PTR ( (reg16 *) PWM_6250Hz_PWMHW__PER0)
#define PWM_6250Hz_COMPARE1_LSB (*(reg16 *) PWM_6250Hz_PWMHW__CNT_CMP0)
#define PWM_6250Hz_COMPARE1_LSB_PTR ( (reg16 *) PWM_6250Hz_PWMHW__CNT_CMP0)
#define PWM_6250Hz_COMPARE2_LSB 0x00u
#define PWM_6250Hz_COMPARE2_LSB_PTR 0x00u
#define PWM_6250Hz_COUNTER_LSB (*(reg16 *) PWM_6250Hz_PWMHW__CNT_CMP0)
#define PWM_6250Hz_COUNTER_LSB_PTR ( (reg16 *) PWM_6250Hz_PWMHW__CNT_CMP0)
#define PWM_6250Hz_CAPTURE_LSB (*(reg16 *) PWM_6250Hz_PWMHW__CAP0)
#define PWM_6250Hz_CAPTURE_LSB_PTR ( (reg16 *) PWM_6250Hz_PWMHW__CAP0)
#define PWM_6250Hz_RT1 (*(reg8 *) PWM_6250Hz_PWMHW__RT1)
#define PWM_6250Hz_RT1_PTR ( (reg8 *) PWM_6250Hz_PWMHW__RT1)
#else
#if (PWM_6250Hz_Resolution == 8u) /* 8bit - PWM */
#if(PWM_6250Hz_PWMModeIsCenterAligned)
#define PWM_6250Hz_PERIOD_LSB (*(reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D1_REG)
#define PWM_6250Hz_PERIOD_LSB_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D1_REG)
#else
#define PWM_6250Hz_PERIOD_LSB (*(reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__F0_REG)
#define PWM_6250Hz_PERIOD_LSB_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__F0_REG)
#endif /* (PWM_6250Hz_PWMModeIsCenterAligned) */
#define PWM_6250Hz_COMPARE1_LSB (*(reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D0_REG)
#define PWM_6250Hz_COMPARE1_LSB_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D0_REG)
#define PWM_6250Hz_COMPARE2_LSB (*(reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D1_REG)
#define PWM_6250Hz_COMPARE2_LSB_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D1_REG)
#define PWM_6250Hz_COUNTERCAP_LSB (*(reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__A1_REG)
#define PWM_6250Hz_COUNTERCAP_LSB_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__A1_REG)
#define PWM_6250Hz_COUNTER_LSB (*(reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__A0_REG)
#define PWM_6250Hz_COUNTER_LSB_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__A0_REG)
#define PWM_6250Hz_CAPTURE_LSB (*(reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__F1_REG)
#define PWM_6250Hz_CAPTURE_LSB_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__F1_REG)
#else
#if(CY_PSOC3) /* 8-bit address space */
#if(PWM_6250Hz_PWMModeIsCenterAligned)
#define PWM_6250Hz_PERIOD_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D1_REG)
#define PWM_6250Hz_PERIOD_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D1_REG)
#else
#define PWM_6250Hz_PERIOD_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__F0_REG)
#define PWM_6250Hz_PERIOD_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__F0_REG)
#endif /* (PWM_6250Hz_PWMModeIsCenterAligned) */
#define PWM_6250Hz_COMPARE1_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D0_REG)
#define PWM_6250Hz_COMPARE1_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D0_REG)
#define PWM_6250Hz_COMPARE2_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D1_REG)
#define PWM_6250Hz_COMPARE2_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__D1_REG)
#define PWM_6250Hz_COUNTERCAP_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__A1_REG)
#define PWM_6250Hz_COUNTERCAP_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__A1_REG)
#define PWM_6250Hz_COUNTER_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__A0_REG)
#define PWM_6250Hz_COUNTER_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__A0_REG)
#define PWM_6250Hz_CAPTURE_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__F1_REG)
#define PWM_6250Hz_CAPTURE_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__F1_REG)
#else
#if(PWM_6250Hz_PWMModeIsCenterAligned)
#define PWM_6250Hz_PERIOD_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_D1_REG)
#define PWM_6250Hz_PERIOD_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_D1_REG)
#else
#define PWM_6250Hz_PERIOD_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_F0_REG)
#define PWM_6250Hz_PERIOD_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_F0_REG)
#endif /* (PWM_6250Hz_PWMModeIsCenterAligned) */
#define PWM_6250Hz_COMPARE1_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_D0_REG)
#define PWM_6250Hz_COMPARE1_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_D0_REG)
#define PWM_6250Hz_COMPARE2_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_D1_REG)
#define PWM_6250Hz_COMPARE2_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_D1_REG)
#define PWM_6250Hz_COUNTERCAP_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_A1_REG)
#define PWM_6250Hz_COUNTERCAP_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_A1_REG)
#define PWM_6250Hz_COUNTER_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_A0_REG)
#define PWM_6250Hz_COUNTER_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_A0_REG)
#define PWM_6250Hz_CAPTURE_LSB (*(reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_F1_REG)
#define PWM_6250Hz_CAPTURE_LSB_PTR ((reg16 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__16BIT_F1_REG)
#endif
#define PWM_6250Hz_AUX_CONTROLDP1 (*(reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u1__DP_AUX_CTL_REG)
#define PWM_6250Hz_AUX_CONTROLDP1_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u1__DP_AUX_CTL_REG)
#endif /* (PWM_6250Hz_Resolution == 8) */
#define PWM_6250Hz_AUX_CONTROLDP0 (*(reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__DP_AUX_CTL_REG)
#define PWM_6250Hz_AUX_CONTROLDP0_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sP8_pwmdp_u0__DP_AUX_CTL_REG)
#endif /* (PWM_6250Hz_UsingFixedFunction) */
#if(PWM_6250Hz_KillModeMinTime )
#define PWM_6250Hz_KILLMODEMINTIME (*(reg8 *) PWM_6250Hz_PWMUDB_sKM_killmodecounterdp_u0__D0_REG)
#define PWM_6250Hz_KILLMODEMINTIME_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sKM_killmodecounterdp_u0__D0_REG)
/* Fixed Function Block has no Kill Mode parameters because it is Asynchronous only */
#endif /* (PWM_6250Hz_KillModeMinTime ) */
#if(PWM_6250Hz_DeadBandMode == PWM_6250Hz__B_PWM__DBM_256_CLOCKS)
#define PWM_6250Hz_DEADBAND_COUNT (*(reg8 *) PWM_6250Hz_PWMUDB_sDB255_deadbandcounterdp_u0__D0_REG)
#define PWM_6250Hz_DEADBAND_COUNT_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sDB255_deadbandcounterdp_u0__D0_REG)
#define PWM_6250Hz_DEADBAND_LSB_PTR ((reg8 *) PWM_6250Hz_PWMUDB_sDB255_deadbandcounterdp_u0__A0_REG)
#define PWM_6250Hz_DEADBAND_LSB (*(reg8 *) PWM_6250Hz_PWMUDB_sDB255_deadbandcounterdp_u0__A0_REG)
#elif(PWM_6250Hz_DeadBandMode == PWM_6250Hz__B_PWM__DBM_2_4_CLOCKS)
/* In Fixed Function Block these bits are in the control blocks control register */
#if (PWM_6250Hz_UsingFixedFunction)
#define PWM_6250Hz_DEADBAND_COUNT (*(reg8 *) PWM_6250Hz_PWMHW__CFG0)
#define PWM_6250Hz_DEADBAND_COUNT_PTR ((reg8 *) PWM_6250Hz_PWMHW__CFG0)
#define PWM_6250Hz_DEADBAND_COUNT_MASK (uint8)((uint8)0x03u << PWM_6250Hz_DEADBAND_COUNT_SHIFT)
/* As defined by the Register Map as DEADBAND_PERIOD[1:0] in CFG0 */
#define PWM_6250Hz_DEADBAND_COUNT_SHIFT 0x06u
#else
/* Lower two bits of the added control register define the count 1-3 */
#define PWM_6250Hz_DEADBAND_COUNT (*(reg8 *) PWM_6250Hz_PWMUDB_genblk7_dbctrlreg__CONTROL_REG)
#define PWM_6250Hz_DEADBAND_COUNT_PTR ((reg8 *) PWM_6250Hz_PWMUDB_genblk7_dbctrlreg__CONTROL_REG)
#define PWM_6250Hz_DEADBAND_COUNT_MASK (uint8)((uint8)0x03u << PWM_6250Hz_DEADBAND_COUNT_SHIFT)
/* As defined by the verilog implementation of the Control Register */
#define PWM_6250Hz_DEADBAND_COUNT_SHIFT 0x00u
#endif /* (PWM_6250Hz_UsingFixedFunction) */
#endif /* (PWM_6250Hz_DeadBandMode == PWM_6250Hz__B_PWM__DBM_256_CLOCKS) */
#if (PWM_6250Hz_UsingFixedFunction)
#define PWM_6250Hz_STATUS (*(reg8 *) PWM_6250Hz_PWMHW__SR0)
#define PWM_6250Hz_STATUS_PTR ((reg8 *) PWM_6250Hz_PWMHW__SR0)
#define PWM_6250Hz_STATUS_MASK (*(reg8 *) PWM_6250Hz_PWMHW__SR0)
#define PWM_6250Hz_STATUS_MASK_PTR ((reg8 *) PWM_6250Hz_PWMHW__SR0)
#define PWM_6250Hz_CONTROL (*(reg8 *) PWM_6250Hz_PWMHW__CFG0)
#define PWM_6250Hz_CONTROL_PTR ((reg8 *) PWM_6250Hz_PWMHW__CFG0)
#define PWM_6250Hz_CONTROL2 (*(reg8 *) PWM_6250Hz_PWMHW__CFG1)
#define PWM_6250Hz_CONTROL3 (*(reg8 *) PWM_6250Hz_PWMHW__CFG2)
#define PWM_6250Hz_GLOBAL_ENABLE (*(reg8 *) PWM_6250Hz_PWMHW__PM_ACT_CFG)
#define PWM_6250Hz_GLOBAL_ENABLE_PTR ( (reg8 *) PWM_6250Hz_PWMHW__PM_ACT_CFG)
#define PWM_6250Hz_GLOBAL_STBY_ENABLE (*(reg8 *) PWM_6250Hz_PWMHW__PM_STBY_CFG)
#define PWM_6250Hz_GLOBAL_STBY_ENABLE_PTR ( (reg8 *) PWM_6250Hz_PWMHW__PM_STBY_CFG)
/***********************************
* Constants
***********************************/
/* Fixed Function Block Chosen */
#define PWM_6250Hz_BLOCK_EN_MASK PWM_6250Hz_PWMHW__PM_ACT_MSK
#define PWM_6250Hz_BLOCK_STBY_EN_MASK PWM_6250Hz_PWMHW__PM_STBY_MSK
/* Control Register definitions */
#define PWM_6250Hz_CTRL_ENABLE_SHIFT 0x00u
#define PWM_6250Hz_CTRL_CMPMODE1_SHIFT 0x04u /* As defined by Register map as MODE_CFG bits in CFG2*/
#define PWM_6250Hz_CTRL_DEAD_TIME_SHIFT 0x06u /* As defined by Register map */
/* Fixed Function Block Only CFG register bit definitions */
#define PWM_6250Hz_CFG0_MODE 0x02u /* Set to compare mode */
/* #define PWM_6250Hz_CFG0_ENABLE 0x01u */ /* Enable the block to run */
#define PWM_6250Hz_CFG0_DB 0x20u /* As defined by Register map as DB bit in CFG0 */
/* Control Register Bit Masks */
#define PWM_6250Hz_CTRL_ENABLE (uint8)((uint8)0x01u << PWM_6250Hz_CTRL_ENABLE_SHIFT)
#define PWM_6250Hz_CTRL_RESET (uint8)((uint8)0x01u << PWM_6250Hz_CTRL_RESET_SHIFT)
#define PWM_6250Hz_CTRL_CMPMODE2_MASK (uint8)((uint8)0x07u << PWM_6250Hz_CTRL_CMPMODE2_SHIFT)
#define PWM_6250Hz_CTRL_CMPMODE1_MASK (uint8)((uint8)0x07u << PWM_6250Hz_CTRL_CMPMODE1_SHIFT)
/* Control2 Register Bit Masks */
/* As defined in Register Map, Part of the TMRX_CFG1 register */
#define PWM_6250Hz_CTRL2_IRQ_SEL_SHIFT 0x00u
#define PWM_6250Hz_CTRL2_IRQ_SEL (uint8)((uint8)0x01u << PWM_6250Hz_CTRL2_IRQ_SEL_SHIFT)
/* Status Register Bit Locations */
#define PWM_6250Hz_STATUS_TC_SHIFT 0x07u /* As defined by Register map as TC in SR0 */
#define PWM_6250Hz_STATUS_CMP1_SHIFT 0x06u /* As defined by the Register map as CAP_CMP in SR0 */
/* Status Register Interrupt Enable Bit Locations */
#define PWM_6250Hz_STATUS_KILL_INT_EN_MASK_SHIFT (0x00u)
#define PWM_6250Hz_STATUS_TC_INT_EN_MASK_SHIFT (PWM_6250Hz_STATUS_TC_SHIFT - 4u)
#define PWM_6250Hz_STATUS_CMP2_INT_EN_MASK_SHIFT (0x00u)
#define PWM_6250Hz_STATUS_CMP1_INT_EN_MASK_SHIFT (PWM_6250Hz_STATUS_CMP1_SHIFT - 4u)
/* Status Register Bit Masks */
#define PWM_6250Hz_STATUS_TC (uint8)((uint8)0x01u << PWM_6250Hz_STATUS_TC_SHIFT)
#define PWM_6250Hz_STATUS_CMP1 (uint8)((uint8)0x01u << PWM_6250Hz_STATUS_CMP1_SHIFT)
/* Status Register Interrupt Bit Masks */
#define PWM_6250Hz_STATUS_TC_INT_EN_MASK (uint8)((uint8)PWM_6250Hz_STATUS_TC >> 4u)
#define PWM_6250Hz_STATUS_CMP1_INT_EN_MASK (uint8)((uint8)PWM_6250Hz_STATUS_CMP1 >> 4u)
/*RT1 Synch Constants */
#define PWM_6250Hz_RT1_SHIFT 0x04u
#define PWM_6250Hz_RT1_MASK (uint8)((uint8)0x03u << PWM_6250Hz_RT1_SHIFT)/* Sync TC and CMP bit masks */
#define PWM_6250Hz_SYNC (uint8)((uint8)0x03u << PWM_6250Hz_RT1_SHIFT)
#define PWM_6250Hz_SYNCDSI_SHIFT 0x00u
#define PWM_6250Hz_SYNCDSI_MASK (uint8)((uint8)0x0Fu << PWM_6250Hz_SYNCDSI_SHIFT) /* Sync all DSI inputs */
#define PWM_6250Hz_SYNCDSI_EN (uint8)((uint8)0x0Fu << PWM_6250Hz_SYNCDSI_SHIFT) /* Sync all DSI inputs */
#else
#define PWM_6250Hz_STATUS (*(reg8 *) PWM_6250Hz_PWMUDB_genblk8_stsreg__STATUS_REG )
#define PWM_6250Hz_STATUS_PTR ((reg8 *) PWM_6250Hz_PWMUDB_genblk8_stsreg__STATUS_REG )
#define PWM_6250Hz_STATUS_MASK (*(reg8 *) PWM_6250Hz_PWMUDB_genblk8_stsreg__MASK_REG)
#define PWM_6250Hz_STATUS_MASK_PTR ((reg8 *) PWM_6250Hz_PWMUDB_genblk8_stsreg__MASK_REG)
#define PWM_6250Hz_STATUS_AUX_CTRL (*(reg8 *) PWM_6250Hz_PWMUDB_genblk8_stsreg__STATUS_AUX_CTL_REG)
#define PWM_6250Hz_CONTROL (*(reg8 *) PWM_6250Hz_PWMUDB_genblk1_ctrlreg__CONTROL_REG)
#define PWM_6250Hz_CONTROL_PTR ((reg8 *) PWM_6250Hz_PWMUDB_genblk1_ctrlreg__CONTROL_REG)
/***********************************
* Constants
***********************************/
/* Control Register definitions */
#define PWM_6250Hz_CTRL_ENABLE_SHIFT 0x07u
#define PWM_6250Hz_CTRL_RESET_SHIFT 0x06u
#define PWM_6250Hz_CTRL_CMPMODE2_SHIFT 0x03u
#define PWM_6250Hz_CTRL_CMPMODE1_SHIFT 0x00u
#define PWM_6250Hz_CTRL_DEAD_TIME_SHIFT 0x00u /* No Shift Needed for UDB block */
/* Control Register Bit Masks */
#define PWM_6250Hz_CTRL_ENABLE (uint8)((uint8)0x01u << PWM_6250Hz_CTRL_ENABLE_SHIFT)
#define PWM_6250Hz_CTRL_RESET (uint8)((uint8)0x01u << PWM_6250Hz_CTRL_RESET_SHIFT)
#define PWM_6250Hz_CTRL_CMPMODE2_MASK (uint8)((uint8)0x07u << PWM_6250Hz_CTRL_CMPMODE2_SHIFT)
#define PWM_6250Hz_CTRL_CMPMODE1_MASK (uint8)((uint8)0x07u << PWM_6250Hz_CTRL_CMPMODE1_SHIFT)
/* Status Register Bit Locations */
#define PWM_6250Hz_STATUS_KILL_SHIFT 0x05u
#define PWM_6250Hz_STATUS_FIFONEMPTY_SHIFT 0x04u
#define PWM_6250Hz_STATUS_FIFOFULL_SHIFT 0x03u
#define PWM_6250Hz_STATUS_TC_SHIFT 0x02u
#define PWM_6250Hz_STATUS_CMP2_SHIFT 0x01u
#define PWM_6250Hz_STATUS_CMP1_SHIFT 0x00u
/* Status Register Interrupt Enable Bit Locations - UDB Status Interrupt Mask match Status Bit Locations*/
#define PWM_6250Hz_STATUS_KILL_INT_EN_MASK_SHIFT PWM_6250Hz_STATUS_KILL_SHIFT
#define PWM_6250Hz_STATUS_FIFONEMPTY_INT_EN_MASK_SHIFT PWM_6250Hz_STATUS_FIFONEMPTY_SHIFT
#define PWM_6250Hz_STATUS_FIFOFULL_INT_EN_MASK_SHIFT PWM_6250Hz_STATUS_FIFOFULL_SHIFT
#define PWM_6250Hz_STATUS_TC_INT_EN_MASK_SHIFT PWM_6250Hz_STATUS_TC_SHIFT
#define PWM_6250Hz_STATUS_CMP2_INT_EN_MASK_SHIFT PWM_6250Hz_STATUS_CMP2_SHIFT
#define PWM_6250Hz_STATUS_CMP1_INT_EN_MASK_SHIFT PWM_6250Hz_STATUS_CMP1_SHIFT
/* Status Register Bit Masks */
#define PWM_6250Hz_STATUS_KILL (uint8)((uint8)0x00u << PWM_6250Hz_STATUS_KILL_SHIFT )
#define PWM_6250Hz_STATUS_FIFOFULL (uint8)((uint8)0x01u << PWM_6250Hz_STATUS_FIFOFULL_SHIFT)
#define PWM_6250Hz_STATUS_FIFONEMPTY (uint8)((uint8)0x01u << PWM_6250Hz_STATUS_FIFONEMPTY_SHIFT)
#define PWM_6250Hz_STATUS_TC (uint8)((uint8)0x01u << PWM_6250Hz_STATUS_TC_SHIFT)
#define PWM_6250Hz_STATUS_CMP2 (uint8)((uint8)0x01u << PWM_6250Hz_STATUS_CMP2_SHIFT)
#define PWM_6250Hz_STATUS_CMP1 (uint8)((uint8)0x01u << PWM_6250Hz_STATUS_CMP1_SHIFT)
/* Status Register Interrupt Bit Masks - UDB Status Interrupt Mask match Status Bit Locations */
#define PWM_6250Hz_STATUS_KILL_INT_EN_MASK PWM_6250Hz_STATUS_KILL
#define PWM_6250Hz_STATUS_FIFOFULL_INT_EN_MASK PWM_6250Hz_STATUS_FIFOFULL
#define PWM_6250Hz_STATUS_FIFONEMPTY_INT_EN_MASK PWM_6250Hz_STATUS_FIFONEMPTY
#define PWM_6250Hz_STATUS_TC_INT_EN_MASK PWM_6250Hz_STATUS_TC
#define PWM_6250Hz_STATUS_CMP2_INT_EN_MASK PWM_6250Hz_STATUS_CMP2
#define PWM_6250Hz_STATUS_CMP1_INT_EN_MASK PWM_6250Hz_STATUS_CMP1
/* Datapath Auxillary Control Register definitions */
#define PWM_6250Hz_AUX_CTRL_FIFO0_CLR 0x01u
#define PWM_6250Hz_AUX_CTRL_FIFO1_CLR 0x02u
#define PWM_6250Hz_AUX_CTRL_FIFO0_LVL 0x04u
#define PWM_6250Hz_AUX_CTRL_FIFO1_LVL 0x08u
#define PWM_6250Hz_STATUS_ACTL_INT_EN_MASK 0x10u /* As defined for the ACTL Register */
#endif /* PWM_6250Hz_UsingFixedFunction */
#endif /* CY_PWM_PWM_6250Hz_H */
/* [] END OF FILE */
| 52.539554 | 122 | 0.696896 |
291173b096f272e63463d49b3c191de5692e9d7c | 5,440 | c | C | thirdparty/sdlcl/yuv.c | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | thirdparty/sdlcl/yuv.c | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | thirdparty/sdlcl/yuv.c | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | /*
* SDLCL - SDL Compatibility Library
* Copyright (C) 2017 Alan Williams <mralert@gmail.com>
*
* Portions taken from SDL 1.2.15
* Copyright (C) 1997-2012 Sam Latinga <slouken@libsdl.org>
*
* This 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.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "SDL2.h"
#include "video.h"
typedef struct SDL1_Overlay {
Uint32 format;
int w, h;
int planes;
Uint16 *pitches;
Uint8 **pixels;
/* Originally struct private_yuvhwfuncs *hwfuncs; */
void *pad;
/* Originally struct private_yuvhwdata *hwdata; */
SDL_Texture *texture;
Uint32 hw_overlay :1;
Uint32 UnusedBits :31;
} SDL1_Overlay;
#define SDL1_YV12_OVERLAY 0x32315659
#define SDL1_IYUV_OVERLAY 0x56555949
#define SDL1_YUY2_OVERLAY 0x32595559
#define SDL1_UYVY_OVERLAY 0x59565955
#define SDL1_YVYU_OVERLAY 0x55595659
static int align_num (int x, int a) {
return ((x + a - 1) / a) * a;
}
DECLSPEC SDL1_Overlay *SDLCALL SDL_CreateYUVOverlay (int width, int height, Uint32 format, SDL1_Surface *display) {
SDL1_Overlay *overlay;
Uint16 pitches[3];
int sizes[3];
int planes, size, i;
Uint32 texfmt;
SDL_Texture *texture;
int whalf = (width + 1) / 2;
int hhalf = (height + 1) / 2;
Uint8 *pixels;
if (!SDLCL_renderer) return NULL;
/* TODO: Support software overlays for other surfaces */
if (display != SDLCL_surface) return NULL;
switch (format) {
case SDL1_YV12_OVERLAY:
case SDL1_IYUV_OVERLAY:
planes = 3;
pitches[0] = align_num(width, 8);
pitches[1] = align_num(whalf, 8);
pitches[2] = align_num(whalf, 8);
sizes[0] = pitches[0] * height;
sizes[1] = pitches[1] * hhalf;
sizes[2] = pitches[2] * hhalf;
break;
case SDL1_YUY2_OVERLAY:
case SDL1_UYVY_OVERLAY:
case SDL1_YVYU_OVERLAY:
planes = 1;
pitches[0] = align_num(width * 2, 8);
sizes[0] = pitches[0] * height;
break;
default:
return NULL;
}
for (i = 0, size = 0; i < planes; i++) size += sizes[i];
switch (format) {
case SDL1_YV12_OVERLAY: texfmt = SDL_PIXELFORMAT_YV12; break;
case SDL1_IYUV_OVERLAY: texfmt = SDL_PIXELFORMAT_IYUV; break;
case SDL1_YUY2_OVERLAY: texfmt = SDL_PIXELFORMAT_YUY2; break;
case SDL1_UYVY_OVERLAY: texfmt = SDL_PIXELFORMAT_UYVY; break;
case SDL1_YVYU_OVERLAY: texfmt = SDL_PIXELFORMAT_YVYU; break;
default: return NULL;
}
overlay = malloc(sizeof(SDL1_Overlay) + sizeof(Uint8 *) * planes + sizeof(Uint16) * planes);
if (!overlay) return NULL;
pixels = malloc(size);
if (!pixels) {
free(overlay);
return NULL;
}
texture = rSDL_CreateTexture(SDLCL_renderer, texfmt, SDL_TEXTUREACCESS_STREAMING, width, height);
if (!texture) {
free(pixels);
free(overlay);
return NULL;
}
overlay->format = format;
overlay->w = width;
overlay->h = height;
overlay->planes = planes;
overlay->pixels = (Uint8 **)(overlay + 1);
overlay->pitches = (Uint16 *)(overlay->pixels + planes);
overlay->pixels[0] = pixels;
for (i = 1; i < planes; i++) overlay->pixels[i] = overlay->pixels[i - 1] + sizes[i - 1];
memcpy(overlay->pitches, pitches, sizeof(Uint16) * planes);
overlay->texture = texture;
overlay->hw_overlay = 1;
return overlay;
}
DECLSPEC int SDLCALL SDL_LockYUVOverlay (SDL1_Overlay *overlay) {
(void)overlay;
return 0;
}
DECLSPEC void SDLCALL SDL_UnlockYUVOverlay (SDL1_Overlay *overlay) {
(void)overlay;
}
static int scale_x (int x) {
return x * SDLCL_scale_rect.w / SDLCL_virtual_width + SDLCL_scale_rect.x;
}
static int scale_y (int y) {
return y * SDLCL_scale_rect.h / SDLCL_virtual_height + SDLCL_scale_rect.y;
}
DECLSPEC int SDLCALL SDL_DisplayYUVOverlay (SDL1_Overlay *overlay, SDL1_Rect *dstrect) {
SDL_Rect dest;
if (overlay->planes == 3) {
if (overlay->format == SDL1_YV12_OVERLAY)
rSDL_UpdateYUVTexture(overlay->texture, NULL,
overlay->pixels[0], overlay->pitches[0],
overlay->pixels[2], overlay->pitches[2],
overlay->pixels[1], overlay->pitches[1]);
else
rSDL_UpdateYUVTexture(overlay->texture, NULL,
overlay->pixels[0], overlay->pitches[0],
overlay->pixels[1], overlay->pitches[1],
overlay->pixels[2], overlay->pitches[2]);
} else
rSDL_UpdateTexture(overlay->texture, NULL, overlay->pixels[0], overlay->pitches[0]);
rSDL_RenderClear(SDLCL_renderer);
if (SDLCL_scaling) {
dest.x = scale_x(dstrect->x);
dest.y = scale_y(dstrect->y);
dest.w = scale_x(dstrect->x + dstrect->w) - dest.x;
dest.h = scale_y(dstrect->y + dstrect->h) - dest.y;
} else {
dest.x = dstrect->x;
dest.y = dstrect->y;
dest.w = dstrect->w;
dest.h = dstrect->h;
}
rSDL_RenderCopy(SDLCL_renderer, overlay->texture, NULL, &dest);
rSDL_RenderPresent(SDLCL_renderer);
return 0;
}
DECLSPEC void SDLCALL SDL_FreeYUVOverlay (SDL1_Overlay *overlay) {
if (overlay) {
free(overlay->pixels[0]);
rSDL_DestroyTexture(overlay->texture);
free(overlay);
}
}
| 30.561798 | 115 | 0.708456 |
34b8a169ee46500724b79615d734438c524266e3 | 50,163 | c | C | gst-plugins-base-1.2.4/gst-libs/gst/app/gstappsrc.c | Malk123/Robby | 1af36a34b40f6a0f2ba80067e0b364d83d5b4630 | [
"MIT"
] | null | null | null | gst-plugins-base-1.2.4/gst-libs/gst/app/gstappsrc.c | Malk123/Robby | 1af36a34b40f6a0f2ba80067e0b364d83d5b4630 | [
"MIT"
] | null | null | null | gst-plugins-base-1.2.4/gst-libs/gst/app/gstappsrc.c | Malk123/Robby | 1af36a34b40f6a0f2ba80067e0b364d83d5b4630 | [
"MIT"
] | null | null | null | /* GStreamer
* Copyright (C) 2007 David Schleef <ds@schleef.org>
* (C) 2008 Wim Taymans <wim.taymans@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/**
* SECTION:gstappsrc
* @short_description: Easy way for applications to inject buffers into a
* pipeline
* @see_also: #GstBaseSrc, appsink
*
* The appsrc element can be used by applications to insert data into a
* GStreamer pipeline. Unlike most GStreamer elements, Appsrc provides
* external API functions.
*
* appsrc can be used by linking with the libgstapp library to access the
* methods directly or by using the appsrc action signals.
*
* Before operating appsrc, the caps property must be set to a fixed caps
* describing the format of the data that will be pushed with appsrc. An
* exception to this is when pushing buffers with unknown caps, in which case no
* caps should be set. This is typically true of file-like sources that push raw
* byte buffers.
*
* The main way of handing data to the appsrc element is by calling the
* gst_app_src_push_buffer() method or by emitting the push-buffer action signal.
* This will put the buffer onto a queue from which appsrc will read from in its
* streaming thread. It is important to note that data transport will not happen
* from the thread that performed the push-buffer call.
*
* The "max-bytes" property controls how much data can be queued in appsrc
* before appsrc considers the queue full. A filled internal queue will always
* signal the "enough-data" signal, which signals the application that it should
* stop pushing data into appsrc. The "block" property will cause appsrc to
* block the push-buffer method until free data becomes available again.
*
* When the internal queue is running out of data, the "need-data" signal is
* emitted, which signals the application that it should start pushing more data
* into appsrc.
*
* In addition to the "need-data" and "enough-data" signals, appsrc can emit the
* "seek-data" signal when the "stream-mode" property is set to "seekable" or
* "random-access". The signal argument will contain the new desired position in
* the stream expressed in the unit set with the "format" property. After
* receiving the seek-data signal, the application should push-buffers from the
* new position.
*
* These signals allow the application to operate the appsrc in two different
* ways:
*
* The push model, in which the application repeatedly calls the push-buffer method
* with a new buffer. Optionally, the queue size in the appsrc can be controlled
* with the enough-data and need-data signals by respectively stopping/starting
* the push-buffer calls. This is a typical mode of operation for the
* stream-type "stream" and "seekable". Use this model when implementing various
* network protocols or hardware devices.
*
* The pull model where the need-data signal triggers the next push-buffer call.
* This mode is typically used in the "random-access" stream-type. Use this
* model for file access or other randomly accessable sources. In this mode, a
* buffer of exactly the amount of bytes given by the need-data signal should be
* pushed into appsrc.
*
* In all modes, the size property on appsrc should contain the total stream
* size in bytes. Setting this property is mandatory in the random-access mode.
* For the stream and seekable modes, setting this property is optional but
* recommended.
*
* When the application is finished pushing data into appsrc, it should call
* gst_app_src_end_of_stream() or emit the end-of-stream action signal. After
* this call, no more buffers can be pushed into appsrc until a flushing seek
* happened or the state of the appsrc has gone through READY.
*
* Last reviewed on 2008-12-17 (0.10.10)
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gst.h>
#include <gst/base/gstbasesrc.h>
#include <string.h>
#include "gstapp-marshal.h"
#include "gstappsrc.h"
struct _GstAppSrcPrivate
{
GCond cond;
GMutex mutex;
GQueue *queue;
GstCaps *caps;
gint64 size;
GstAppStreamType stream_type;
guint64 max_bytes;
GstFormat format;
gboolean block;
gchar *uri;
gboolean new_caps;
gboolean flushing;
gboolean started;
gboolean is_eos;
guint64 queued_bytes;
guint64 offset;
GstAppStreamType current_type;
guint64 min_latency;
guint64 max_latency;
gboolean emit_signals;
guint min_percent;
GstAppSrcCallbacks callbacks;
gpointer user_data;
GDestroyNotify notify;
};
GST_DEBUG_CATEGORY_STATIC (app_src_debug);
#define GST_CAT_DEFAULT app_src_debug
enum
{
/* signals */
SIGNAL_NEED_DATA,
SIGNAL_ENOUGH_DATA,
SIGNAL_SEEK_DATA,
/* actions */
SIGNAL_PUSH_BUFFER,
SIGNAL_END_OF_STREAM,
LAST_SIGNAL
};
#define DEFAULT_PROP_SIZE -1
#define DEFAULT_PROP_STREAM_TYPE GST_APP_STREAM_TYPE_STREAM
#define DEFAULT_PROP_MAX_BYTES 200000
#define DEFAULT_PROP_FORMAT GST_FORMAT_BYTES
#define DEFAULT_PROP_BLOCK FALSE
#define DEFAULT_PROP_IS_LIVE FALSE
#define DEFAULT_PROP_MIN_LATENCY -1
#define DEFAULT_PROP_MAX_LATENCY -1
#define DEFAULT_PROP_EMIT_SIGNALS TRUE
#define DEFAULT_PROP_MIN_PERCENT 0
#define DEFAULT_PROP_CURRENT_LEVEL_BYTES 0
enum
{
PROP_0,
PROP_CAPS,
PROP_SIZE,
PROP_STREAM_TYPE,
PROP_MAX_BYTES,
PROP_FORMAT,
PROP_BLOCK,
PROP_IS_LIVE,
PROP_MIN_LATENCY,
PROP_MAX_LATENCY,
PROP_EMIT_SIGNALS,
PROP_MIN_PERCENT,
PROP_CURRENT_LEVEL_BYTES,
PROP_LAST
};
static GstStaticPadTemplate gst_app_src_template =
GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS_ANY);
GType
gst_app_stream_type_get_type (void)
{
static volatile gsize stream_type_type = 0;
static const GEnumValue stream_type[] = {
{GST_APP_STREAM_TYPE_STREAM, "GST_APP_STREAM_TYPE_STREAM", "stream"},
{GST_APP_STREAM_TYPE_SEEKABLE, "GST_APP_STREAM_TYPE_SEEKABLE", "seekable"},
{GST_APP_STREAM_TYPE_RANDOM_ACCESS, "GST_APP_STREAM_TYPE_RANDOM_ACCESS",
"random-access"},
{0, NULL, NULL}
};
if (g_once_init_enter (&stream_type_type)) {
GType tmp = g_enum_register_static ("GstAppStreamType", stream_type);
g_once_init_leave (&stream_type_type, tmp);
}
return (GType) stream_type_type;
}
static void gst_app_src_uri_handler_init (gpointer g_iface,
gpointer iface_data);
static void gst_app_src_dispose (GObject * object);
static void gst_app_src_finalize (GObject * object);
static void gst_app_src_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_app_src_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static void gst_app_src_set_latencies (GstAppSrc * appsrc,
gboolean do_min, guint64 min, gboolean do_max, guint64 max);
static gboolean gst_app_src_negotiate (GstBaseSrc * basesrc);
static GstCaps *gst_app_src_internal_get_caps (GstBaseSrc * bsrc,
GstCaps * filter);
static GstFlowReturn gst_app_src_create (GstBaseSrc * bsrc, guint64 offset,
guint size, GstBuffer ** buf);
static gboolean gst_app_src_start (GstBaseSrc * bsrc);
static gboolean gst_app_src_stop (GstBaseSrc * bsrc);
static gboolean gst_app_src_unlock (GstBaseSrc * bsrc);
static gboolean gst_app_src_unlock_stop (GstBaseSrc * bsrc);
static gboolean gst_app_src_do_seek (GstBaseSrc * src, GstSegment * segment);
static gboolean gst_app_src_is_seekable (GstBaseSrc * src);
static gboolean gst_app_src_do_get_size (GstBaseSrc * src, guint64 * size);
static gboolean gst_app_src_query (GstBaseSrc * src, GstQuery * query);
static GstFlowReturn gst_app_src_push_buffer_action (GstAppSrc * appsrc,
GstBuffer * buffer);
static guint gst_app_src_signals[LAST_SIGNAL] = { 0 };
#define gst_app_src_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstAppSrc, gst_app_src, GST_TYPE_BASE_SRC,
G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_app_src_uri_handler_init));
static void
gst_app_src_class_init (GstAppSrcClass * klass)
{
GObjectClass *gobject_class = (GObjectClass *) klass;
GstElementClass *element_class = (GstElementClass *) klass;
GstBaseSrcClass *basesrc_class = (GstBaseSrcClass *) klass;
GST_DEBUG_CATEGORY_INIT (app_src_debug, "appsrc", 0, "appsrc element");
gobject_class->dispose = gst_app_src_dispose;
gobject_class->finalize = gst_app_src_finalize;
gobject_class->set_property = gst_app_src_set_property;
gobject_class->get_property = gst_app_src_get_property;
/**
* GstAppSrc::caps:
*
* The GstCaps that will negotiated downstream and will be put
* on outgoing buffers.
*/
g_object_class_install_property (gobject_class, PROP_CAPS,
g_param_spec_boxed ("caps", "Caps",
"The allowed caps for the src pad", GST_TYPE_CAPS,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::format:
*
* The format to use for segment events. When the source is producing
* timestamped buffers this property should be set to GST_FORMAT_TIME.
*/
g_object_class_install_property (gobject_class, PROP_FORMAT,
g_param_spec_enum ("format", "Format",
"The format of the segment events and seek", GST_TYPE_FORMAT,
DEFAULT_PROP_FORMAT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::size:
*
* The total size in bytes of the data stream. If the total size is known, it
* is recommended to configure it with this property.
*/
g_object_class_install_property (gobject_class, PROP_SIZE,
g_param_spec_int64 ("size", "Size",
"The size of the data stream in bytes (-1 if unknown)",
-1, G_MAXINT64, DEFAULT_PROP_SIZE,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::stream-type:
*
* The type of stream that this source is producing. For seekable streams the
* application should connect to the seek-data signal.
*/
g_object_class_install_property (gobject_class, PROP_STREAM_TYPE,
g_param_spec_enum ("stream-type", "Stream Type",
"the type of the stream", GST_TYPE_APP_STREAM_TYPE,
DEFAULT_PROP_STREAM_TYPE,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::max-bytes:
*
* The maximum amount of bytes that can be queued internally.
* After the maximum amount of bytes are queued, appsrc will emit the
* "enough-data" signal.
*/
g_object_class_install_property (gobject_class, PROP_MAX_BYTES,
g_param_spec_uint64 ("max-bytes", "Max bytes",
"The maximum number of bytes to queue internally (0 = unlimited)",
0, G_MAXUINT64, DEFAULT_PROP_MAX_BYTES,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::block:
*
* When max-bytes are queued and after the enough-data signal has been emitted,
* block any further push-buffer calls until the amount of queued bytes drops
* below the max-bytes limit.
*/
g_object_class_install_property (gobject_class, PROP_BLOCK,
g_param_spec_boolean ("block", "Block",
"Block push-buffer when max-bytes are queued",
DEFAULT_PROP_BLOCK, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::is-live:
*
* Instruct the source to behave like a live source. This includes that it
* will only push out buffers in the PLAYING state.
*/
g_object_class_install_property (gobject_class, PROP_IS_LIVE,
g_param_spec_boolean ("is-live", "Is Live",
"Whether to act as a live source",
DEFAULT_PROP_IS_LIVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::min-latency:
*
* The minimum latency of the source. A value of -1 will use the default
* latency calculations of #GstBaseSrc.
*/
g_object_class_install_property (gobject_class, PROP_MIN_LATENCY,
g_param_spec_int64 ("min-latency", "Min Latency",
"The minimum latency (-1 = default)",
-1, G_MAXINT64, DEFAULT_PROP_MIN_LATENCY,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::max-latency:
*
* The maximum latency of the source. A value of -1 means an unlimited amout
* of latency.
*/
g_object_class_install_property (gobject_class, PROP_MAX_LATENCY,
g_param_spec_int64 ("max-latency", "Max Latency",
"The maximum latency (-1 = unlimited)",
-1, G_MAXINT64, DEFAULT_PROP_MAX_LATENCY,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::emit-signals:
*
* Make appsrc emit the "need-data", "enough-data" and "seek-data" signals.
* This option is by default enabled for backwards compatibility reasons but
* can disabled when needed because signal emission is expensive.
*/
g_object_class_install_property (gobject_class, PROP_EMIT_SIGNALS,
g_param_spec_boolean ("emit-signals", "Emit signals",
"Emit need-data, enough-data and seek-data signals",
DEFAULT_PROP_EMIT_SIGNALS,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::empty-percent:
*
* Make appsrc emit the "need-data" signal when the amount of bytes in the
* queue drops below this percentage of max-bytes.
*/
g_object_class_install_property (gobject_class, PROP_MIN_PERCENT,
g_param_spec_uint ("min-percent", "Min Percent",
"Emit need-data when queued bytes drops below this percent of max-bytes",
0, 100, DEFAULT_PROP_MIN_PERCENT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::current-level-bytes:
*
* The number of currently queued bytes inside appsrc.
*
* Since: 1.2
*/
g_object_class_install_property (gobject_class, PROP_CURRENT_LEVEL_BYTES,
g_param_spec_uint64 ("current-level-bytes", "Current Level Bytes",
"The number of currently queued bytes",
0, G_MAXUINT64, DEFAULT_PROP_CURRENT_LEVEL_BYTES,
G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
/**
* GstAppSrc::need-data:
* @appsrc: the appsrc element that emitted the signal
* @length: the amount of bytes needed.
*
* Signal that the source needs more data. In the callback or from another
* thread you should call push-buffer or end-of-stream.
*
* @length is just a hint and when it is set to -1, any number of bytes can be
* pushed into @appsrc.
*
* You can call push-buffer multiple times until the enough-data signal is
* fired.
*/
gst_app_src_signals[SIGNAL_NEED_DATA] =
g_signal_new ("need-data", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GstAppSrcClass, need_data),
NULL, NULL, __gst_app_marshal_VOID__UINT, G_TYPE_NONE, 1, G_TYPE_UINT);
/**
* GstAppSrc::enough-data:
* @appsrc: the appsrc element that emitted the signal
*
* Signal that the source has enough data. It is recommended that the
* application stops calling push-buffer until the need-data signal is
* emitted again to avoid excessive buffer queueing.
*/
gst_app_src_signals[SIGNAL_ENOUGH_DATA] =
g_signal_new ("enough-data", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GstAppSrcClass, enough_data),
NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
/**
* GstAppSrc::seek-data:
* @appsrc: the appsrc element that emitted the signal
* @offset: the offset to seek to
*
* Seek to the given offset. The next push-buffer should produce buffers from
* the new @offset.
* This callback is only called for seekable stream types.
*
* Returns: %TRUE if the seek succeeded.
*/
gst_app_src_signals[SIGNAL_SEEK_DATA] =
g_signal_new ("seek-data", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GstAppSrcClass, seek_data),
NULL, NULL, __gst_app_marshal_BOOLEAN__UINT64, G_TYPE_BOOLEAN, 1,
G_TYPE_UINT64);
/**
* GstAppSrc::push-buffer:
* @appsrc: the appsrc
* @buffer: a buffer to push
*
* Adds a buffer to the queue of buffers that the appsrc element will
* push to its source pad. This function does not take ownership of the
* buffer so the buffer needs to be unreffed after calling this function.
*
* When the block property is TRUE, this function can block until free space
* becomes available in the queue.
*/
gst_app_src_signals[SIGNAL_PUSH_BUFFER] =
g_signal_new ("push-buffer", G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstAppSrcClass,
push_buffer), NULL, NULL, __gst_app_marshal_ENUM__BOXED,
GST_TYPE_FLOW_RETURN, 1, GST_TYPE_BUFFER);
/**
* GstAppSrc::end-of-stream:
* @appsrc: the appsrc
*
* Notify @appsrc that no more buffer are available.
*/
gst_app_src_signals[SIGNAL_END_OF_STREAM] =
g_signal_new ("end-of-stream", G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstAppSrcClass,
end_of_stream), NULL, NULL, __gst_app_marshal_ENUM__VOID,
GST_TYPE_FLOW_RETURN, 0, G_TYPE_NONE);
gst_element_class_set_static_metadata (element_class, "AppSrc",
"Generic/Source", "Allow the application to feed buffers to a pipeline",
"David Schleef <ds@schleef.org>, Wim Taymans <wim.taymans@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&gst_app_src_template));
basesrc_class->negotiate = gst_app_src_negotiate;
basesrc_class->get_caps = gst_app_src_internal_get_caps;
basesrc_class->create = gst_app_src_create;
basesrc_class->start = gst_app_src_start;
basesrc_class->stop = gst_app_src_stop;
basesrc_class->unlock = gst_app_src_unlock;
basesrc_class->unlock_stop = gst_app_src_unlock_stop;
basesrc_class->do_seek = gst_app_src_do_seek;
basesrc_class->is_seekable = gst_app_src_is_seekable;
basesrc_class->get_size = gst_app_src_do_get_size;
basesrc_class->get_size = gst_app_src_do_get_size;
basesrc_class->query = gst_app_src_query;
klass->push_buffer = gst_app_src_push_buffer_action;
klass->end_of_stream = gst_app_src_end_of_stream;
g_type_class_add_private (klass, sizeof (GstAppSrcPrivate));
}
static void
gst_app_src_init (GstAppSrc * appsrc)
{
GstAppSrcPrivate *priv;
priv = appsrc->priv = G_TYPE_INSTANCE_GET_PRIVATE (appsrc, GST_TYPE_APP_SRC,
GstAppSrcPrivate);
g_mutex_init (&priv->mutex);
g_cond_init (&priv->cond);
priv->queue = g_queue_new ();
priv->size = DEFAULT_PROP_SIZE;
priv->stream_type = DEFAULT_PROP_STREAM_TYPE;
priv->max_bytes = DEFAULT_PROP_MAX_BYTES;
priv->format = DEFAULT_PROP_FORMAT;
priv->block = DEFAULT_PROP_BLOCK;
priv->min_latency = DEFAULT_PROP_MIN_LATENCY;
priv->max_latency = DEFAULT_PROP_MAX_LATENCY;
priv->emit_signals = DEFAULT_PROP_EMIT_SIGNALS;
priv->min_percent = DEFAULT_PROP_MIN_PERCENT;
gst_base_src_set_live (GST_BASE_SRC (appsrc), DEFAULT_PROP_IS_LIVE);
}
static void
gst_app_src_flush_queued (GstAppSrc * src)
{
GstBuffer *buf;
GstAppSrcPrivate *priv = src->priv;
while ((buf = g_queue_pop_head (priv->queue)))
gst_buffer_unref (buf);
priv->queued_bytes = 0;
}
static void
gst_app_src_dispose (GObject * obj)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (obj);
GstAppSrcPrivate *priv = appsrc->priv;
if (priv->caps) {
gst_caps_unref (priv->caps);
priv->caps = NULL;
}
gst_app_src_flush_queued (appsrc);
G_OBJECT_CLASS (parent_class)->dispose (obj);
}
static void
gst_app_src_finalize (GObject * obj)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (obj);
GstAppSrcPrivate *priv = appsrc->priv;
g_mutex_clear (&priv->mutex);
g_cond_clear (&priv->cond);
g_queue_free (priv->queue);
g_free (priv->uri);
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
static GstCaps *
gst_app_src_internal_get_caps (GstBaseSrc * bsrc, GstCaps * filter)
{
GstAppSrc *appsrc = GST_APP_SRC (bsrc);
GstCaps *caps;
GST_OBJECT_LOCK (appsrc);
if ((caps = appsrc->priv->caps))
gst_caps_ref (caps);
GST_OBJECT_UNLOCK (appsrc);
if (filter) {
if (caps) {
GstCaps *intersection =
gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
gst_caps_unref (caps);
caps = intersection;
} else {
caps = gst_caps_ref (filter);
}
}
GST_DEBUG_OBJECT (appsrc, "caps: %" GST_PTR_FORMAT, caps);
return caps;
}
static void
gst_app_src_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (object);
GstAppSrcPrivate *priv = appsrc->priv;
switch (prop_id) {
case PROP_CAPS:
gst_app_src_set_caps (appsrc, gst_value_get_caps (value));
break;
case PROP_SIZE:
gst_app_src_set_size (appsrc, g_value_get_int64 (value));
break;
case PROP_STREAM_TYPE:
gst_app_src_set_stream_type (appsrc, g_value_get_enum (value));
break;
case PROP_MAX_BYTES:
gst_app_src_set_max_bytes (appsrc, g_value_get_uint64 (value));
break;
case PROP_FORMAT:
priv->format = g_value_get_enum (value);
break;
case PROP_BLOCK:
priv->block = g_value_get_boolean (value);
break;
case PROP_IS_LIVE:
gst_base_src_set_live (GST_BASE_SRC (appsrc),
g_value_get_boolean (value));
break;
case PROP_MIN_LATENCY:
gst_app_src_set_latencies (appsrc, TRUE, g_value_get_int64 (value),
FALSE, -1);
break;
case PROP_MAX_LATENCY:
gst_app_src_set_latencies (appsrc, FALSE, -1, TRUE,
g_value_get_int64 (value));
break;
case PROP_EMIT_SIGNALS:
gst_app_src_set_emit_signals (appsrc, g_value_get_boolean (value));
break;
case PROP_MIN_PERCENT:
priv->min_percent = g_value_get_uint (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_app_src_get_property (GObject * object, guint prop_id, GValue * value,
GParamSpec * pspec)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (object);
GstAppSrcPrivate *priv = appsrc->priv;
switch (prop_id) {
case PROP_CAPS:
g_value_take_boxed (value, gst_app_src_get_caps (appsrc));
break;
case PROP_SIZE:
g_value_set_int64 (value, gst_app_src_get_size (appsrc));
break;
case PROP_STREAM_TYPE:
g_value_set_enum (value, gst_app_src_get_stream_type (appsrc));
break;
case PROP_MAX_BYTES:
g_value_set_uint64 (value, gst_app_src_get_max_bytes (appsrc));
break;
case PROP_FORMAT:
g_value_set_enum (value, priv->format);
break;
case PROP_BLOCK:
g_value_set_boolean (value, priv->block);
break;
case PROP_IS_LIVE:
g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (appsrc)));
break;
case PROP_MIN_LATENCY:
{
guint64 min;
gst_app_src_get_latency (appsrc, &min, NULL);
g_value_set_int64 (value, min);
break;
}
case PROP_MAX_LATENCY:
{
guint64 max;
gst_app_src_get_latency (appsrc, NULL, &max);
g_value_set_int64 (value, max);
break;
}
case PROP_EMIT_SIGNALS:
g_value_set_boolean (value, gst_app_src_get_emit_signals (appsrc));
break;
case PROP_MIN_PERCENT:
g_value_set_uint (value, priv->min_percent);
break;
case PROP_CURRENT_LEVEL_BYTES:
g_value_set_uint64 (value, gst_app_src_get_current_level_bytes (appsrc));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static gboolean
gst_app_src_unlock (GstBaseSrc * bsrc)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (bsrc);
GstAppSrcPrivate *priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
GST_DEBUG_OBJECT (appsrc, "unlock start");
priv->flushing = TRUE;
g_cond_broadcast (&priv->cond);
g_mutex_unlock (&priv->mutex);
return TRUE;
}
static gboolean
gst_app_src_unlock_stop (GstBaseSrc * bsrc)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (bsrc);
GstAppSrcPrivate *priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
GST_DEBUG_OBJECT (appsrc, "unlock stop");
priv->flushing = FALSE;
g_cond_broadcast (&priv->cond);
g_mutex_unlock (&priv->mutex);
return TRUE;
}
static gboolean
gst_app_src_start (GstBaseSrc * bsrc)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (bsrc);
GstAppSrcPrivate *priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
GST_DEBUG_OBJECT (appsrc, "starting");
priv->new_caps = FALSE;
priv->started = TRUE;
/* set the offset to -1 so that we always do a first seek. This is only used
* in random-access mode. */
priv->offset = -1;
priv->flushing = FALSE;
g_mutex_unlock (&priv->mutex);
gst_base_src_set_format (bsrc, priv->format);
return TRUE;
}
static gboolean
gst_app_src_stop (GstBaseSrc * bsrc)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (bsrc);
GstAppSrcPrivate *priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
GST_DEBUG_OBJECT (appsrc, "stopping");
priv->is_eos = FALSE;
priv->flushing = TRUE;
priv->started = FALSE;
gst_app_src_flush_queued (appsrc);
g_cond_broadcast (&priv->cond);
g_mutex_unlock (&priv->mutex);
return TRUE;
}
static gboolean
gst_app_src_is_seekable (GstBaseSrc * src)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (src);
GstAppSrcPrivate *priv = appsrc->priv;
gboolean res = FALSE;
switch (priv->stream_type) {
case GST_APP_STREAM_TYPE_STREAM:
break;
case GST_APP_STREAM_TYPE_SEEKABLE:
case GST_APP_STREAM_TYPE_RANDOM_ACCESS:
res = TRUE;
break;
}
return res;
}
static gboolean
gst_app_src_do_get_size (GstBaseSrc * src, guint64 * size)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (src);
*size = gst_app_src_get_size (appsrc);
return TRUE;
}
static gboolean
gst_app_src_query (GstBaseSrc * src, GstQuery * query)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (src);
GstAppSrcPrivate *priv = appsrc->priv;
gboolean res;
switch (GST_QUERY_TYPE (query)) {
case GST_QUERY_LATENCY:
{
GstClockTime min, max;
gboolean live;
/* Query the parent class for the defaults */
res = gst_base_src_query_latency (src, &live, &min, &max);
/* overwrite with our values when we need to */
g_mutex_lock (&priv->mutex);
if (priv->min_latency != -1)
min = priv->min_latency;
if (priv->max_latency != -1)
max = priv->max_latency;
g_mutex_unlock (&priv->mutex);
gst_query_set_latency (query, live, min, max);
break;
}
case GST_QUERY_SCHEDULING:
{
gst_query_set_scheduling (query, GST_SCHEDULING_FLAG_SEEKABLE, 1, -1, 0);
gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
switch (priv->stream_type) {
case GST_APP_STREAM_TYPE_STREAM:
case GST_APP_STREAM_TYPE_SEEKABLE:
break;
case GST_APP_STREAM_TYPE_RANDOM_ACCESS:
gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
break;
}
res = TRUE;
break;
}
default:
res = GST_BASE_SRC_CLASS (parent_class)->query (src, query);
break;
}
return res;
}
/* will be called in push mode */
static gboolean
gst_app_src_do_seek (GstBaseSrc * src, GstSegment * segment)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (src);
GstAppSrcPrivate *priv = appsrc->priv;
gint64 desired_position;
gboolean res = FALSE;
desired_position = segment->position;
GST_DEBUG_OBJECT (appsrc, "seeking to %" G_GINT64_FORMAT ", format %s",
desired_position, gst_format_get_name (segment->format));
/* no need to try to seek in streaming mode */
if (priv->stream_type == GST_APP_STREAM_TYPE_STREAM)
return TRUE;
if (priv->callbacks.seek_data)
res = priv->callbacks.seek_data (appsrc, desired_position, priv->user_data);
else {
gboolean emit;
g_mutex_lock (&priv->mutex);
emit = priv->emit_signals;
g_mutex_unlock (&priv->mutex);
if (emit)
g_signal_emit (appsrc, gst_app_src_signals[SIGNAL_SEEK_DATA], 0,
desired_position, &res);
}
if (res) {
GST_DEBUG_OBJECT (appsrc, "flushing queue");
gst_app_src_flush_queued (appsrc);
priv->is_eos = FALSE;
} else {
GST_WARNING_OBJECT (appsrc, "seek failed");
}
return res;
}
/* must be called with the appsrc mutex */
static gboolean
gst_app_src_emit_seek (GstAppSrc * appsrc, guint64 offset)
{
gboolean res = FALSE;
gboolean emit;
GstAppSrcPrivate *priv = appsrc->priv;
emit = priv->emit_signals;
g_mutex_unlock (&priv->mutex);
GST_DEBUG_OBJECT (appsrc,
"we are at %" G_GINT64_FORMAT ", seek to %" G_GINT64_FORMAT,
priv->offset, offset);
if (priv->callbacks.seek_data)
res = priv->callbacks.seek_data (appsrc, offset, priv->user_data);
else if (emit)
g_signal_emit (appsrc, gst_app_src_signals[SIGNAL_SEEK_DATA], 0,
offset, &res);
g_mutex_lock (&priv->mutex);
return res;
}
/* must be called with the appsrc mutex. After this call things can be
* flushing */
static void
gst_app_src_emit_need_data (GstAppSrc * appsrc, guint size)
{
gboolean emit;
GstAppSrcPrivate *priv = appsrc->priv;
emit = priv->emit_signals;
g_mutex_unlock (&priv->mutex);
/* we have no data, we need some. We fire the signal with the size hint. */
if (priv->callbacks.need_data)
priv->callbacks.need_data (appsrc, size, priv->user_data);
else if (emit)
g_signal_emit (appsrc, gst_app_src_signals[SIGNAL_NEED_DATA], 0, size,
NULL);
g_mutex_lock (&priv->mutex);
/* we can be flushing now because we released the lock */
}
/* must be called with the appsrc mutex */
static gboolean
gst_app_src_do_negotiate (GstBaseSrc * basesrc)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (basesrc);
GstAppSrcPrivate *priv = appsrc->priv;
gboolean result;
GstCaps *caps;
GST_OBJECT_LOCK (basesrc);
caps = priv->caps ? gst_caps_ref (priv->caps) : NULL;
GST_OBJECT_UNLOCK (basesrc);
/* Avoid deadlock by unlocking mutex
* otherwise we get deadlock between this and stream lock */
g_mutex_unlock (&priv->mutex);
if (caps) {
result = gst_base_src_set_caps (basesrc, caps);
gst_caps_unref (caps);
} else {
result = GST_BASE_SRC_CLASS (parent_class)->negotiate (basesrc);
}
g_mutex_lock (&priv->mutex);
return result;
}
static gboolean
gst_app_src_negotiate (GstBaseSrc * basesrc)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (basesrc);
GstAppSrcPrivate *priv = appsrc->priv;
gboolean result;
g_mutex_lock (&priv->mutex);
priv->new_caps = FALSE;
result = gst_app_src_do_negotiate (basesrc);
g_mutex_unlock (&priv->mutex);
return result;
}
static GstFlowReturn
gst_app_src_create (GstBaseSrc * bsrc, guint64 offset, guint size,
GstBuffer ** buf)
{
GstAppSrc *appsrc = GST_APP_SRC_CAST (bsrc);
GstAppSrcPrivate *priv = appsrc->priv;
GstFlowReturn ret;
GST_OBJECT_LOCK (appsrc);
if (G_UNLIKELY (priv->size != bsrc->segment.duration &&
bsrc->segment.format == GST_FORMAT_BYTES)) {
GST_DEBUG_OBJECT (appsrc,
"Size changed from %" G_GINT64_FORMAT " to %" G_GINT64_FORMAT,
bsrc->segment.duration, priv->size);
bsrc->segment.duration = priv->size;
GST_OBJECT_UNLOCK (appsrc);
gst_element_post_message (GST_ELEMENT (appsrc),
gst_message_new_duration_changed (GST_OBJECT (appsrc)));
} else {
GST_OBJECT_UNLOCK (appsrc);
}
g_mutex_lock (&priv->mutex);
/* check flushing first */
if (G_UNLIKELY (priv->flushing))
goto flushing;
if (priv->stream_type == GST_APP_STREAM_TYPE_RANDOM_ACCESS) {
/* if we are dealing with a random-access stream, issue a seek if the offset
* changed. */
if (G_UNLIKELY (priv->offset != offset)) {
gboolean res;
/* do the seek */
res = gst_app_src_emit_seek (appsrc, offset);
if (G_UNLIKELY (!res))
/* failing to seek is fatal */
goto seek_error;
priv->offset = offset;
priv->is_eos = FALSE;
}
}
while (TRUE) {
/* return data as long as we have some */
if (!g_queue_is_empty (priv->queue)) {
guint buf_size;
if (priv->new_caps) {
priv->new_caps = FALSE;
gst_app_src_do_negotiate (bsrc);
/* Lock has released so now may need
*- flushing
*- new caps change
*- check queue has data */
if (G_UNLIKELY (priv->flushing))
goto flushing;
/* Contiue checks caps and queue */
continue;
}
*buf = g_queue_pop_head (priv->queue);
buf_size = gst_buffer_get_size (*buf);
GST_DEBUG_OBJECT (appsrc, "we have buffer %p of size %u", *buf, buf_size);
priv->queued_bytes -= buf_size;
/* only update the offset when in random_access mode */
if (priv->stream_type == GST_APP_STREAM_TYPE_RANDOM_ACCESS)
priv->offset += buf_size;
/* signal that we removed an item */
g_cond_broadcast (&priv->cond);
/* see if we go lower than the empty-percent */
if (priv->min_percent && priv->max_bytes) {
if (priv->queued_bytes * 100 / priv->max_bytes <= priv->min_percent)
/* ignore flushing state, we got a buffer and we will return it now.
* Errors will be handled in the next round */
gst_app_src_emit_need_data (appsrc, size);
}
ret = GST_FLOW_OK;
break;
} else {
gst_app_src_emit_need_data (appsrc, size);
/* we can be flushing now because we released the lock above */
if (G_UNLIKELY (priv->flushing))
goto flushing;
/* if we have a buffer now, continue the loop and try to return it. In
* random-access mode (where a buffer is normally pushed in the above
* signal) we can still be empty because the pushed buffer got flushed or
* when the application pushes the requested buffer later, we support both
* possibilities. */
if (!g_queue_is_empty (priv->queue))
continue;
/* no buffer yet, maybe we are EOS, if not, block for more data. */
}
/* check EOS */
if (G_UNLIKELY (priv->is_eos))
goto eos;
/* nothing to return, wait a while for new data or flushing. */
g_cond_wait (&priv->cond, &priv->mutex);
}
g_mutex_unlock (&priv->mutex);
return ret;
/* ERRORS */
flushing:
{
GST_DEBUG_OBJECT (appsrc, "we are flushing");
g_mutex_unlock (&priv->mutex);
return GST_FLOW_FLUSHING;
}
eos:
{
GST_DEBUG_OBJECT (appsrc, "we are EOS");
g_mutex_unlock (&priv->mutex);
return GST_FLOW_EOS;
}
seek_error:
{
g_mutex_unlock (&priv->mutex);
GST_ELEMENT_ERROR (appsrc, RESOURCE, READ, ("failed to seek"),
GST_ERROR_SYSTEM);
return GST_FLOW_ERROR;
}
}
/* external API */
/**
* gst_app_src_set_caps:
* @appsrc: a #GstAppSrc
* @caps: caps to set
*
* Set the capabilities on the appsrc element. This function takes
* a copy of the caps structure. After calling this method, the source will
* only produce caps that match @caps. @caps must be fixed and the caps on the
* buffers must match the caps or left NULL.
*/
void
gst_app_src_set_caps (GstAppSrc * appsrc, const GstCaps * caps)
{
GstCaps *old;
GstAppSrcPrivate *priv;
g_return_if_fail (GST_IS_APP_SRC (appsrc));
priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
GST_OBJECT_LOCK (appsrc);
GST_DEBUG_OBJECT (appsrc, "setting caps to %" GST_PTR_FORMAT, caps);
if ((old = priv->caps) != caps) {
if (caps)
priv->caps = gst_caps_copy (caps);
else
priv->caps = NULL;
if (old)
gst_caps_unref (old);
priv->new_caps = TRUE;
}
GST_OBJECT_UNLOCK (appsrc);
g_mutex_unlock (&priv->mutex);
}
/**
* gst_app_src_get_caps:
* @appsrc: a #GstAppSrc
*
* Get the configured caps on @appsrc.
*
* Returns: the #GstCaps produced by the source. gst_caps_unref() after usage.
*/
GstCaps *
gst_app_src_get_caps (GstAppSrc * appsrc)
{
g_return_val_if_fail (GST_IS_APP_SRC (appsrc), NULL);
return gst_app_src_internal_get_caps (GST_BASE_SRC_CAST (appsrc), NULL);
}
/**
* gst_app_src_set_size:
* @appsrc: a #GstAppSrc
* @size: the size to set
*
* Set the size of the stream in bytes. A value of -1 means that the size is
* not known.
*/
void
gst_app_src_set_size (GstAppSrc * appsrc, gint64 size)
{
GstAppSrcPrivate *priv;
g_return_if_fail (GST_IS_APP_SRC (appsrc));
priv = appsrc->priv;
GST_OBJECT_LOCK (appsrc);
GST_DEBUG_OBJECT (appsrc, "setting size of %" G_GINT64_FORMAT, size);
priv->size = size;
GST_OBJECT_UNLOCK (appsrc);
}
/**
* gst_app_src_get_size:
* @appsrc: a #GstAppSrc
*
* Get the size of the stream in bytes. A value of -1 means that the size is
* not known.
*
* Returns: the size of the stream previously set with gst_app_src_set_size();
*/
gint64
gst_app_src_get_size (GstAppSrc * appsrc)
{
gint64 size;
GstAppSrcPrivate *priv;
g_return_val_if_fail (GST_IS_APP_SRC (appsrc), -1);
priv = appsrc->priv;
GST_OBJECT_LOCK (appsrc);
size = priv->size;
GST_DEBUG_OBJECT (appsrc, "getting size of %" G_GINT64_FORMAT, size);
GST_OBJECT_UNLOCK (appsrc);
return size;
}
/**
* gst_app_src_set_stream_type:
* @appsrc: a #GstAppSrc
* @type: the new state
*
* Set the stream type on @appsrc. For seekable streams, the "seek" signal must
* be connected to.
*
* A stream_type stream
*/
void
gst_app_src_set_stream_type (GstAppSrc * appsrc, GstAppStreamType type)
{
GstAppSrcPrivate *priv;
g_return_if_fail (GST_IS_APP_SRC (appsrc));
priv = appsrc->priv;
GST_OBJECT_LOCK (appsrc);
GST_DEBUG_OBJECT (appsrc, "setting stream_type of %d", type);
priv->stream_type = type;
GST_OBJECT_UNLOCK (appsrc);
}
/**
* gst_app_src_get_stream_type:
* @appsrc: a #GstAppSrc
*
* Get the stream type. Control the stream type of @appsrc
* with gst_app_src_set_stream_type().
*
* Returns: the stream type.
*/
GstAppStreamType
gst_app_src_get_stream_type (GstAppSrc * appsrc)
{
gboolean stream_type;
GstAppSrcPrivate *priv;
g_return_val_if_fail (GST_IS_APP_SRC (appsrc), FALSE);
priv = appsrc->priv;
GST_OBJECT_LOCK (appsrc);
stream_type = priv->stream_type;
GST_DEBUG_OBJECT (appsrc, "getting stream_type of %d", stream_type);
GST_OBJECT_UNLOCK (appsrc);
return stream_type;
}
/**
* gst_app_src_set_max_bytes:
* @appsrc: a #GstAppSrc
* @max: the maximum number of bytes to queue
*
* Set the maximum amount of bytes that can be queued in @appsrc.
* After the maximum amount of bytes are queued, @appsrc will emit the
* "enough-data" signal.
*/
void
gst_app_src_set_max_bytes (GstAppSrc * appsrc, guint64 max)
{
GstAppSrcPrivate *priv;
g_return_if_fail (GST_IS_APP_SRC (appsrc));
priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
if (max != priv->max_bytes) {
GST_DEBUG_OBJECT (appsrc, "setting max-bytes to %" G_GUINT64_FORMAT, max);
priv->max_bytes = max;
/* signal the change */
g_cond_broadcast (&priv->cond);
}
g_mutex_unlock (&priv->mutex);
}
/**
* gst_app_src_get_max_bytes:
* @appsrc: a #GstAppSrc
*
* Get the maximum amount of bytes that can be queued in @appsrc.
*
* Returns: The maximum amount of bytes that can be queued.
*/
guint64
gst_app_src_get_max_bytes (GstAppSrc * appsrc)
{
guint64 result;
GstAppSrcPrivate *priv;
g_return_val_if_fail (GST_IS_APP_SRC (appsrc), 0);
priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
result = priv->max_bytes;
GST_DEBUG_OBJECT (appsrc, "getting max-bytes of %" G_GUINT64_FORMAT, result);
g_mutex_unlock (&priv->mutex);
return result;
}
/**
* gst_app_src_get_current_level_bytes:
* @appsrc: a #GstAppSrc
*
* Get the number of currently queued bytes inside @appsrc.
*
* Returns: The number of currently queued bytes.
*
* Since: 1.2
*/
guint64
gst_app_src_get_current_level_bytes (GstAppSrc * appsrc)
{
gint64 queued;
GstAppSrcPrivate *priv;
g_return_val_if_fail (GST_IS_APP_SRC (appsrc), -1);
priv = appsrc->priv;
GST_OBJECT_LOCK (appsrc);
queued = priv->queued_bytes;
GST_DEBUG_OBJECT (appsrc, "current level bytes is %" G_GUINT64_FORMAT,
queued);
GST_OBJECT_UNLOCK (appsrc);
return queued;
}
static void
gst_app_src_set_latencies (GstAppSrc * appsrc, gboolean do_min, guint64 min,
gboolean do_max, guint64 max)
{
GstAppSrcPrivate *priv = appsrc->priv;
gboolean changed = FALSE;
g_mutex_lock (&priv->mutex);
if (do_min && priv->min_latency != min) {
priv->min_latency = min;
changed = TRUE;
}
if (do_max && priv->max_latency != max) {
priv->max_latency = max;
changed = TRUE;
}
g_mutex_unlock (&priv->mutex);
if (changed) {
GST_DEBUG_OBJECT (appsrc, "posting latency changed");
gst_element_post_message (GST_ELEMENT_CAST (appsrc),
gst_message_new_latency (GST_OBJECT_CAST (appsrc)));
}
}
/**
* gst_app_src_set_latency:
* @appsrc: a #GstAppSrc
* @min: the min latency
* @max: the min latency
*
* Configure the @min and @max latency in @src. If @min is set to -1, the
* default latency calculations for pseudo-live sources will be used.
*/
void
gst_app_src_set_latency (GstAppSrc * appsrc, guint64 min, guint64 max)
{
gst_app_src_set_latencies (appsrc, TRUE, min, TRUE, max);
}
/**
* gst_app_src_get_latency:
* @appsrc: a #GstAppSrc
* @min: the min latency
* @max: the min latency
*
* Retrieve the min and max latencies in @min and @max respectively.
*/
void
gst_app_src_get_latency (GstAppSrc * appsrc, guint64 * min, guint64 * max)
{
GstAppSrcPrivate *priv;
g_return_if_fail (GST_IS_APP_SRC (appsrc));
priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
if (min)
*min = priv->min_latency;
if (max)
*max = priv->max_latency;
g_mutex_unlock (&priv->mutex);
}
/**
* gst_app_src_set_emit_signals:
* @appsrc: a #GstAppSrc
* @emit: the new state
*
* Make appsrc emit the "new-preroll" and "new-buffer" signals. This option is
* by default disabled because signal emission is expensive and unneeded when
* the application prefers to operate in pull mode.
*/
void
gst_app_src_set_emit_signals (GstAppSrc * appsrc, gboolean emit)
{
GstAppSrcPrivate *priv;
g_return_if_fail (GST_IS_APP_SRC (appsrc));
priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
priv->emit_signals = emit;
g_mutex_unlock (&priv->mutex);
}
/**
* gst_app_src_get_emit_signals:
* @appsrc: a #GstAppSrc
*
* Check if appsrc will emit the "new-preroll" and "new-buffer" signals.
*
* Returns: %TRUE if @appsrc is emitting the "new-preroll" and "new-buffer"
* signals.
*/
gboolean
gst_app_src_get_emit_signals (GstAppSrc * appsrc)
{
gboolean result;
GstAppSrcPrivate *priv;
g_return_val_if_fail (GST_IS_APP_SRC (appsrc), FALSE);
priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
result = priv->emit_signals;
g_mutex_unlock (&priv->mutex);
return result;
}
static GstFlowReturn
gst_app_src_push_buffer_full (GstAppSrc * appsrc, GstBuffer * buffer,
gboolean steal_ref)
{
gboolean first = TRUE;
GstAppSrcPrivate *priv;
g_return_val_if_fail (GST_IS_APP_SRC (appsrc), GST_FLOW_ERROR);
g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
while (TRUE) {
/* can't accept buffers when we are flushing or EOS */
if (priv->flushing)
goto flushing;
if (priv->is_eos)
goto eos;
if (priv->max_bytes && priv->queued_bytes >= priv->max_bytes) {
GST_DEBUG_OBJECT (appsrc,
"queue filled (%" G_GUINT64_FORMAT " >= %" G_GUINT64_FORMAT ")",
priv->queued_bytes, priv->max_bytes);
if (first) {
gboolean emit;
emit = priv->emit_signals;
/* only signal on the first push */
g_mutex_unlock (&priv->mutex);
if (priv->callbacks.enough_data)
priv->callbacks.enough_data (appsrc, priv->user_data);
else if (emit)
g_signal_emit (appsrc, gst_app_src_signals[SIGNAL_ENOUGH_DATA], 0,
NULL);
g_mutex_lock (&priv->mutex);
/* continue to check for flushing/eos after releasing the lock */
first = FALSE;
continue;
}
if (priv->block) {
GST_DEBUG_OBJECT (appsrc, "waiting for free space");
/* we are filled, wait until a buffer gets popped or when we
* flush. */
g_cond_wait (&priv->cond, &priv->mutex);
} else {
/* no need to wait for free space, we just pump more data into the
* queue hoping that the caller reacts to the enough-data signal and
* stops pushing buffers. */
break;
}
} else
break;
}
GST_DEBUG_OBJECT (appsrc, "queueing buffer %p", buffer);
if (!steal_ref)
gst_buffer_ref (buffer);
g_queue_push_tail (priv->queue, buffer);
priv->queued_bytes += gst_buffer_get_size (buffer);
g_cond_broadcast (&priv->cond);
g_mutex_unlock (&priv->mutex);
return GST_FLOW_OK;
/* ERRORS */
flushing:
{
GST_DEBUG_OBJECT (appsrc, "refuse buffer %p, we are flushing", buffer);
if (steal_ref)
gst_buffer_unref (buffer);
g_mutex_unlock (&priv->mutex);
return GST_FLOW_FLUSHING;
}
eos:
{
GST_DEBUG_OBJECT (appsrc, "refuse buffer %p, we are EOS", buffer);
if (steal_ref)
gst_buffer_unref (buffer);
g_mutex_unlock (&priv->mutex);
return GST_FLOW_EOS;
}
}
/**
* gst_app_src_push_buffer:
* @appsrc: a #GstAppSrc
* @buffer: (transfer full): a #GstBuffer to push
*
* Adds a buffer to the queue of buffers that the appsrc element will
* push to its source pad. This function takes ownership of the buffer.
*
* When the block property is TRUE, this function can block until free
* space becomes available in the queue.
*
* Returns: #GST_FLOW_OK when the buffer was successfuly queued.
* #GST_FLOW_FLUSHING when @appsrc is not PAUSED or PLAYING.
* #GST_FLOW_EOS when EOS occured.
*/
GstFlowReturn
gst_app_src_push_buffer (GstAppSrc * appsrc, GstBuffer * buffer)
{
return gst_app_src_push_buffer_full (appsrc, buffer, TRUE);
}
/* push a buffer without stealing the ref of the buffer. This is used for the
* action signal. */
static GstFlowReturn
gst_app_src_push_buffer_action (GstAppSrc * appsrc, GstBuffer * buffer)
{
return gst_app_src_push_buffer_full (appsrc, buffer, FALSE);
}
/**
* gst_app_src_end_of_stream:
* @appsrc: a #GstAppSrc
*
* Indicates to the appsrc element that the last buffer queued in the
* element is the last buffer of the stream.
*
* Returns: #GST_FLOW_OK when the EOS was successfuly queued.
* #GST_FLOW_FLUSHING when @appsrc is not PAUSED or PLAYING.
*/
GstFlowReturn
gst_app_src_end_of_stream (GstAppSrc * appsrc)
{
GstAppSrcPrivate *priv;
g_return_val_if_fail (GST_IS_APP_SRC (appsrc), GST_FLOW_ERROR);
priv = appsrc->priv;
g_mutex_lock (&priv->mutex);
/* can't accept buffers when we are flushing. We can accept them when we are
* EOS although it will not do anything. */
if (priv->flushing)
goto flushing;
GST_DEBUG_OBJECT (appsrc, "sending EOS");
priv->is_eos = TRUE;
g_cond_broadcast (&priv->cond);
g_mutex_unlock (&priv->mutex);
return GST_FLOW_OK;
/* ERRORS */
flushing:
{
g_mutex_unlock (&priv->mutex);
GST_DEBUG_OBJECT (appsrc, "refuse EOS, we are flushing");
return GST_FLOW_FLUSHING;
}
}
/**
* gst_app_src_set_callbacks: (skip)
* @appsrc: a #GstAppSrc
* @callbacks: the callbacks
* @user_data: a user_data argument for the callbacks
* @notify: a destroy notify function
*
* Set callbacks which will be executed when data is needed, enough data has
* been collected or when a seek should be performed.
* This is an alternative to using the signals, it has lower overhead and is thus
* less expensive, but also less flexible.
*
* If callbacks are installed, no signals will be emitted for performance
* reasons.
*/
void
gst_app_src_set_callbacks (GstAppSrc * appsrc,
GstAppSrcCallbacks * callbacks, gpointer user_data, GDestroyNotify notify)
{
GDestroyNotify old_notify;
GstAppSrcPrivate *priv;
g_return_if_fail (GST_IS_APP_SRC (appsrc));
g_return_if_fail (callbacks != NULL);
priv = appsrc->priv;
GST_OBJECT_LOCK (appsrc);
old_notify = priv->notify;
if (old_notify) {
gpointer old_data;
old_data = priv->user_data;
priv->user_data = NULL;
priv->notify = NULL;
GST_OBJECT_UNLOCK (appsrc);
old_notify (old_data);
GST_OBJECT_LOCK (appsrc);
}
priv->callbacks = *callbacks;
priv->user_data = user_data;
priv->notify = notify;
GST_OBJECT_UNLOCK (appsrc);
}
/*** GSTURIHANDLER INTERFACE *************************************************/
static GstURIType
gst_app_src_uri_get_type (GType type)
{
return GST_URI_SRC;
}
static const gchar *const *
gst_app_src_uri_get_protocols (GType type)
{
static const gchar *protocols[] = { "appsrc", NULL };
return protocols;
}
static gchar *
gst_app_src_uri_get_uri (GstURIHandler * handler)
{
GstAppSrc *appsrc = GST_APP_SRC (handler);
return appsrc->priv->uri ? g_strdup (appsrc->priv->uri) : NULL;
}
static gboolean
gst_app_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
GError ** error)
{
GstAppSrc *appsrc = GST_APP_SRC (handler);
g_free (appsrc->priv->uri);
appsrc->priv->uri = uri ? g_strdup (uri) : NULL;
return TRUE;
}
static void
gst_app_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
{
GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
iface->get_type = gst_app_src_uri_get_type;
iface->get_protocols = gst_app_src_uri_get_protocols;
iface->get_uri = gst_app_src_uri_get_uri;
iface->set_uri = gst_app_src_uri_set_uri;
}
| 28.979203 | 83 | 0.7055 |
425b89c6883bcfb726c357f5a2ddfa33083309b8 | 3,069 | h | C | CoreUtils.framework/CUWiFiTrafficPeer.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 4 | 2021-10-06T12:15:26.000Z | 2022-02-21T02:26:00.000Z | CoreUtils.framework/CUWiFiTrafficPeer.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | null | null | null | CoreUtils.framework/CUWiFiTrafficPeer.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 1 | 2021-10-08T07:40:53.000Z | 2021-10-08T07:40:53.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/CoreUtils.framework/CoreUtils
*/
@interface CUWiFiTrafficPeer : NSObject {
bool _active;
union {
struct sockaddr {
unsigned char sa_len;
unsigned char sa_family;
BOOL sa_data[14];
} sa;
struct sockaddr_in {
unsigned char sin_len;
unsigned char sin_family;
unsigned short sin_port;
struct in_addr {
unsigned int s_addr;
} sin_addr;
BOOL sin_zero[8];
} v4;
struct sockaddr_in6 {
unsigned char sin6_len;
unsigned char sin6_family;
unsigned short sin6_port;
unsigned int sin6_flowinfo;
struct in6_addr {
union {
unsigned char __u6_addr8[16];
unsigned short __u6_addr16[8];
unsigned int __u6_addr32[4];
} __u6_addr;
} sin6_addr;
unsigned int sin6_scope_id;
} v6;
} _peerIP;
unsigned int _trafficFlags;
}
@property (nonatomic) bool active;
@property (nonatomic) union { struct sockaddr { unsigned char x_1_1_1; unsigned char x_1_1_2; BOOL x_1_1_3[14]; } x1; struct sockaddr_in { unsigned char x_2_1_1; unsigned char x_2_1_2; unsigned short x_2_1_3; struct in_addr { unsigned int x_4_2_1; } x_2_1_4; BOOL x_2_1_5[8]; } x2; struct sockaddr_in6 { unsigned char x_3_1_1; unsigned char x_3_1_2; unsigned short x_3_1_3; unsigned int x_3_1_4; struct in6_addr { union { unsigned char x_1_3_1[16]; unsigned short x_1_3_2[8]; unsigned int x_1_3_3[4]; } x_5_2_1; } x_3_1_5; unsigned int x_3_1_6; } x3; } peerIP;
@property (nonatomic) unsigned int trafficFlags;
- (bool)active;
- (union { struct sockaddr { unsigned char x_1_1_1; unsigned char x_1_1_2; BOOL x_1_1_3[14]; } x1; struct sockaddr_in { unsigned char x_2_1_1; unsigned char x_2_1_2; unsigned short x_2_1_3; struct in_addr { unsigned int x_4_2_1; } x_2_1_4; BOOL x_2_1_5[8]; } x2; struct sockaddr_in6 { unsigned char x_3_1_1; unsigned char x_3_1_2; unsigned short x_3_1_3; unsigned int x_3_1_4; struct in6_addr { union { unsigned char x_1_3_1[16]; unsigned short x_1_3_2[8]; unsigned int x_1_3_3[4]; } x_5_2_1; } x_3_1_5; unsigned int x_3_1_6; } x3; })peerIP;
- (id)peerMACAddressData;
- (void)setActive:(bool)arg1;
- (void)setPeerIP:(union { struct sockaddr { unsigned char x_1_1_1; unsigned char x_1_1_2; BOOL x_1_1_3[14]; } x1; struct sockaddr_in { unsigned char x_2_1_1; unsigned char x_2_1_2; unsigned short x_2_1_3; struct in_addr { unsigned int x_4_2_1; } x_2_1_4; BOOL x_2_1_5[8]; } x2; struct sockaddr_in6 { unsigned char x_3_1_1; unsigned char x_3_1_2; unsigned short x_3_1_3; unsigned int x_3_1_4; struct in6_addr { union { unsigned char x_1_3_1[16]; unsigned short x_1_3_2[8]; unsigned int x_1_3_3[4]; } x_5_2_1; } x_3_1_5; unsigned int x_3_1_6; } x3; })arg1;
- (void)setTrafficFlags:(unsigned int)arg1;
- (unsigned int)trafficFlags;
@end
| 57.90566 | 560 | 0.669599 |
9504dfca91bfa0022f7164ff359d5c65e05e1f25 | 6,803 | h | C | SubEthaEdit-Mac/Source/TCMMillionMonkeys/TCMMMSession.h | tamc/SubEthaEdit | dc56cf6b33a21c8c9ae7c5ebb31ce054abc38570 | [
"MIT"
] | null | null | null | SubEthaEdit-Mac/Source/TCMMillionMonkeys/TCMMMSession.h | tamc/SubEthaEdit | dc56cf6b33a21c8c9ae7c5ebb31ce054abc38570 | [
"MIT"
] | null | null | null | SubEthaEdit-Mac/Source/TCMMillionMonkeys/TCMMMSession.h | tamc/SubEthaEdit | dc56cf6b33a21c8c9ae7c5ebb31ce054abc38570 | [
"MIT"
] | null | null | null | // TCMMMSession.h
// SubEthaEdit
//
// Created by Martin Ott on Mon Mar 08 2004.
#import <Foundation/Foundation.h>
#import "SessionProfile.h"
extern NSString * const TCMMMSessionClientStateDidChangeNotification;
extern NSString * const TCMMMSessionParticipantsDidChangeNotification;
extern NSString * const TCMMMSessionPendingUsersDidChangeNotification;
extern NSString * const TCMMMSessionPendingInvitationsDidChange;
extern NSString * const TCMMMSessionDidChangeNotification;
extern NSString * const TCMMMSessionDidReceiveContentNotification;
extern NSString * const TCMMMSessionReadWriteGroupName;
extern NSString * const TCMMMSessionReadOnlyGroupName ;
extern NSString * const TCMMMSessionPoofGroupName;
// CloseGroup seems to be private to the session right now
extern NSString * const TCMMMSessionInvitedUserStateAwaitingResponse;
extern NSString * const TCMMMSessionInvitedUserStateInvitationDeclined;
@class SessionProfile, TCMMMOperation, TCMBEEPSession, TCMMMUser, TCMMMLoggingState;
typedef enum TCMMMSessionAccessState {
TCMMMSessionAccessLockedState=0,
TCMMMSessionAccessReadOnlyState=1,
TCMMMSessionAccessReadWriteState=2
} TCMMMSessionAccessState;
typedef enum TCMMMSessionClientState {
TCMMMSessionClientNoState=0,
TCMMMSessionClientJoiningState=1,
TCMMMSessionClientInvitedState=2,
TCMMMSessionClientParticipantState=3,
} TCMMMSessionClientState;
@class TCMMMSession,TCMMMState;
@protocol SEEDocument
- (NSDictionary *)sessionInformation;
- (void)sessionDidReceiveKick:(TCMMMSession *)aSession;
- (void)sessionDidReceiveClose:(TCMMMSession *)aSession;
- (void)sessionDidLoseConnection:(TCMMMSession *)aSession;
- (void)sessionDidAcceptJoinRequest:(TCMMMSession *)aSession;
- (void)sessionDidDenyJoinRequest:(TCMMMSession *)aSession;
- (void)sessionDidCancelInvitation:(TCMMMSession *)aSession;
- (void)sessionDidLeave:(TCMMMSession *)aSession;
- (void)session:(TCMMMSession *)aSession didReceiveSessionInformation:(NSDictionary *)aSessionInformation;
- (void)session:(TCMMMSession *)aSession didReceiveContent:(NSDictionary *)aContent;
- (NSString *)preparedDisplayName;
- (void)invalidateLayoutForRange:(NSRange)aRange;
- (NSDictionary *)textStorageDictionaryRepresentation;
- (void)updateProxyWindow;
- (void)showWindows;
- (NSSet *)userIDsOfContributors;
- (NSSet *)allUserIDs;
- (void)sendInitialUserStateViaMMState:(TCMMMState *)aState;
- (BOOL)isReceivingContent;
- (void)validateEditability;
- (BOOL)handleOperation:(TCMMMOperation *)aOperation;
@end
@protocol TCMMMSessionHelper <NSObject>
- (void)playSoundNamed:(NSString *)name;
- (void)playBeep;
- (void)addProxyDocumentWithSession:(TCMMMSession *)session;
@end
@class TCMMMState;
@interface TCMMMSession : NSObject <TCMBEEPProfileDelegate, SessionProfileDelegate>
{
id <SEEDocument> I_document;
NSString *I_sessionID;
NSString *I_hostID;
NSString *I_filename;
id <TCMMMSessionHelper> I_helper;
NSMutableDictionary *I_profilesByUserID;
NSMutableDictionary *I_participants;
NSMutableDictionary *I_invitedUsers;
NSMutableDictionary *I_groupOfInvitedUsers;
NSMutableDictionary *I_stateOfInvitedUsers;
NSMutableDictionary *I_sessionContentForUserID;
NSMutableSet *I_contributors;
NSMutableArray *I_pendingUsers;
NSMutableDictionary *I_groupByUserID;
NSMutableDictionary *I_statesByClientID;
NSMutableDictionary *I_groupByToken;
NSMutableSet *I_statesWithRemainingMessages;
TCMMMSessionAccessState I_accessState;
TCMMMSessionClientState I_clientState;
TCMMMLoggingState *I_loggingState;
struct {
BOOL isServer;
BOOL shouldSendJoinRequest;
BOOL wasInvited;
BOOL isPerformingRoundRobin;
BOOL isSecure;
int pauseCount;
} I_flags;
unsigned int I_sessionContentLength;
unsigned int I_receivedContentLength;
NSAttributedString *I_lastReplacedAttributedString;
}
+ (TCMMMSession *)sessionWithBencodedSession:(NSData *)aData;
+ (TCMMMSession *)sessionWithDictionaryRepresentation:(NSDictionary *)aDictionary;
- (id)initWithDocument:(id <SEEDocument>)aDocument;
- (id)initWithSessionID:(NSString *)aSessionID filename:(NSString *)aFileName;
- (void)setFilename:(NSString *)aFilename;
- (NSString *)filename;
- (void)setSessionID:(NSString *)aSessionID;
- (NSString *)sessionID;
- (void)setDocument:(id <SEEDocument>)aDocument;
- (id <SEEDocument>)document;
/*! userID of host */
@property (nonatomic, copy) NSString *hostID;
- (void)setIsServer:(BOOL)isServer;
- (BOOL)isServer;
- (BOOL)isSecure;
- (void)setIsSecure:(BOOL)aFlag;
- (void)setWasInvited:(BOOL)wasInvited;
- (BOOL)wasInvited;
- (void)setAccessState:(TCMMMSessionAccessState)aState;
- (TCMMMSessionAccessState)accessState;
- (void)setClientState:(TCMMMSessionClientState)aState;
- (TCMMMSessionClientState)clientState;
- (NSDictionary *)invitedUsers;
- (NSString *)stateOfInvitedUserById:(NSString *)aUserID;
- (TCMBEEPSession *)BEEPSessionForUserID:(NSString *)aUserID;
- (NSUInteger)participantCount;
- (NSUInteger)openInvitationCount;
- (NSDictionary *)participants;
- (NSArray *)pendingUsers;
/*! @return returns YES if the userID is either host, participant of any sort, invited or pending */
- (BOOL)isUserInvolvedInSession:(NSString *)aUserID;
- (NSData *)sessionBencoded;
- (NSDictionary *)dictionaryRepresentation;
- (void)addContributors:(NSArray *)Contributors;
- (NSArray *)contributors;
- (BOOL)isEditable;
- (BOOL)isEditableByUser:(TCMMMUser *)aUser;
- (NSString *)invitationTokenForGroup:(NSString *)aGroup;
- (void)setGroup:(NSString *)aGroup forParticipantsWithUserIDs:(NSArray *)aUserIDs;
- (void)addPendingUser:(TCMMMUser *)aUser toGroup:(NSString *)aGroup;
- (void)denyPendingUser:(TCMMMUser *)aUser;
- (void)setGroup:(NSString *)aGroup forPendingUsersWithIndexes:(NSIndexSet *)aSet;
- (void)joinUsingBEEPSession:(TCMBEEPSession *)aBEEPSession;
- (void)cancelJoin;
- (void)inviteUser:(TCMMMUser *)aUser intoGroup:(NSString *)aGroup usingBEEPSession:(TCMBEEPSession *)aBEEPSession;
- (void)cancelInvitationForUserWithID:(NSString *)aUserID;
- (void)acceptInvitation;
- (void)declineInvitation;
- (void)leave;
- (void)abandon;
- (void)joinRequestWithProfile:(SessionProfile *)profile;
- (void)invitationWithProfile:(SessionProfile *)profile;
- (void)documentDidApplyOperation:(TCMMMOperation *)anOperation;
- (double)percentOfSessionReceived;
- (void)startProcessing;
- (void)pauseProcessing;
- (BOOL)isAddressedByURL:(NSURL *)aURL;
- (TCMMMLoggingState *)loggingState;
- (void)setLoggingState:(TCMMMLoggingState *)aState;
- (void)setLastReplacedAttributedString:(NSAttributedString *)aLastReplacedAttributedString;
- (NSAttributedString *)lastReplacedAttributedString;
- (NSDictionary *)contributersAsDictionaryRepresentation;
@end
| 33.348039 | 115 | 0.792004 |
61b2b8169ffc56fb0138d481381a6a4403b66090 | 4,035 | c | C | kernel/system_call_hook/source/main.c | ps4dev/ps4sdk-examples | 161c63566a5c572766d40ac51f51cfd0d8f4bb30 | [
"Unlicense"
] | 16 | 2016-04-28T06:42:27.000Z | 2021-05-08T20:18:59.000Z | kernel/system_call_hook/source/main.c | ps4dev/ps4sdk-examples | 161c63566a5c572766d40ac51f51cfd0d8f4bb30 | [
"Unlicense"
] | null | null | null | kernel/system_call_hook/source/main.c | ps4dev/ps4sdk-examples | 161c63566a5c572766d40ac51f51cfd0d8f4bb30 | [
"Unlicense"
] | 10 | 2017-09-20T00:49:24.000Z | 2021-01-14T14:10:30.000Z | #define _XOPEN_SOURCE 700
#define __BSD_VISIBLE 1
#define _KERNEL
#define _STANDALONE
#define _WANT_UCRED
#include <sys/cdefs.h>
#include <sys/types.h>
#include <sys/limits.h>
#include <sys/param.h>
#include <sys/kernel.h>
//#include <sys/libkern.h>
#include <sys/systm.h>
#include <sys/sysproto.h>
//#include <sys/unistd.h>
#include <sys/syscallsubr.h>
#include <sys/syscall.h>
#include <sys/proc.h>
#include <sys/kthread.h>
#include <ps4/kernel.h>
#define SERVER_PORT 5088
static Ps4KernelSocket *sock;
int sysCloseHook(struct thread *td, struct close_args *uap)
{
Ps4KernelSystemCallHookArgument *arg;
// magic - do this in the first line thou!
// also allows you to interrupt via return and set a return via arg
// maybe that should be switch around ... ? -> issue
ps4KernelThreadGetSecondaryReturn(td, (register_t *)&arg);
ps4KernelSocketPrint(td, sock, "pre: %p %p %i\n", arg->hookTypeCurrent, arg->number, uap->fd);
return PS4_KERNEL_SYSTEM_CALL_HOOK_CONTROL_CONTINUE;
}
int sysCloseHookGeneric(struct thread *td, Ps4KernelSystemCallHookArgument *arg)
{
struct close_args *uap;
uap = (struct close_args *)arg->uap;
ps4KernelSocketPrint(td, sock, "generic: %p %p %i\n", arg->hookTypeCurrent, arg->number, uap->fd);
return PS4_KERNEL_SYSTEM_CALL_HOOK_CONTROL_CONTINUE;
}
void socketPrintHook(Ps4KernelThread *td, Ps4KernelSocket *s, Ps4KernelSystemCallHook *h)
{
Ps4KernelSystemCallHookArgument *arg = (Ps4KernelSystemCallHookArgument *)h;
ps4KernelSocketPrint(td, s,
"hook[%p] =\n"
"{\n"
"\tclone: %p,\n"
"\thandler: %p,\n"
"\tprologue: %p,\n"
"\thook: %p,\n"
"\thookType: %p,\n"
"\thookCount: %p,\n"
"\thookSize: %p,\n"
"\thookTypeCurrent: (will be null *) %p,\n"
"\tlock: %p,\n"
"\tentryCount: %p,\n"
"\tcallCount: %p,\n"
"\tsystemCalls: %p,\n"
"\tnumber: %p,\n"
"\toriginalCall: %p,\n"
"\tthread: (will be null *) %p,\n"
"\tuap: (will be null *) %p,\n"
"\tsysret: (will be (32bit) null *) %p,\n"
"\treturns[%p]:\n"
"\t{\n"
"\t\t0: (will be null *) %p,\n"
"\t\t1: (will be null *) %p,\n"
"\t}\n"
"\tuserArgument: %p,\n"
"\tallocate: %p,\n"
"\tfree: %p,\n"
"\tmt: %p\n"
"}\n"
"* = This is will not show per-hook runtime values due to the lock-less design.\n",
arg,
arg->clone,
arg->handler,
arg->prologue,
arg->hook,
arg->hookType,
arg->hookCount,
arg->hookSize,
arg->hookTypeCurrent,
arg->lock,
arg->entryCount,
arg->callCount,
arg->systemCalls,
arg->number,
arg->originalCall,
arg->thread,
arg->uap,
arg->sysret,
arg->returns,
arg->returns[0],
arg->returns[1],
arg->userArgument,
arg->allocate,
arg->free,
arg->mt
);
for(int i = 0; i < arg->hookCount; ++i)
ps4KernelSocketPrint(td, s, "hook[%i]: %p %p\n", i, arg->hook[i], arg->hookType[i]);
}
int main(int argc, char **argv)
{
struct thread *td;
struct socket *client;
int number;
Ps4KernelSystemCallHook *h;
struct sysent *sy;
int r;
ps4ExpressionReturnOnError(ps4KernelSymbolLookUp("sysent", (void **)&sy));
if(ps4KernelIsInKernel() != PS4_OK)
{
printf("This is not a user space application.\n");
return PS4_ERROR_IS_KERNEL_ELF;
}
ps4KernelThreadGetCurrent(&td);
r = ps4KernelSocketTCPServerCreateAcceptThenDestroy(td, &client, SERVER_PORT);
sock = client;
// press "options" to see menue handles getting closed
number = SYS_close;
r = ps4KernelSocketPrintHexDump(td, client, &sy[number], sizeof(struct sysent));
ps4KernelSystemCallHookCreate(&h, number);
r = ps4KernelSocketPrintHexDump(td, client, &sy[number], sizeof(struct sysent));
ps4KernelSystemCallHookAdd(h, (void *)sysCloseHookGeneric, PS4_KERNEL_SYSTEM_CALL_HOOK_TYPE_GENERIC_BOTH);
ps4KernelSystemCallHookAdd(h, (void *)sysCloseHook, PS4_KERNEL_SYSTEM_CALL_HOOK_TYPE_PRE);
pause("hooked", 10000);
socketPrintHook(td, client, h);
ps4KernelSystemCallHookDestroy(h);
r = ps4KernelSocketPrintHexDump(td, client, &sy[number], sizeof(struct sysent));
r = ps4KernelSocketDestroy(client);
return PS4_OK;
}
| 25.865385 | 107 | 0.68575 |
254a823aeb3de0df4238bd53bce23048842e2591 | 93,559 | c | C | lib/EMBOSS-6.6.0/ajax/core/ajtextread.c | alegione/CodonShuffle | bd6674b2eb21ee144a39d6d1e9b7264aba887240 | [
"MIT"
] | 5 | 2016-11-11T21:57:49.000Z | 2021-07-27T14:13:31.000Z | lib/EMBOSS-6.6.0/ajax/core/ajtextread.c | frantallukas10/CodonShuffle | 4c408e1a8617f2a52dcb0329bba9617e1be17313 | [
"MIT"
] | 4 | 2016-05-15T07:56:25.000Z | 2020-05-20T05:21:48.000Z | lib/EMBOSS-6.6.0/ajax/core/ajtextread.c | frantallukas10/CodonShuffle | 4c408e1a8617f2a52dcb0329bba9617e1be17313 | [
"MIT"
] | 10 | 2015-08-19T20:37:46.000Z | 2020-04-07T06:49:23.000Z | /* @source ajtextread *********************************************************
**
** AJAX text data reading functions
**
** These functions control all aspects of AJAX text data reading
**
** @author Copyright (C) 2010 Peter Rice
** @version $Revision: 1.40 $
** @modified Oct 5 pmr First version
** @modified $Date: 2013/07/15 20:54:52 $ by $Author: rice $
** @@
**
** This 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.
**
** This 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 this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
**
******************************************************************************/
#include "ajlib.h"
#include "ajtextread.h"
#include "ajtext.h"
#include "ajcall.h"
#include "ajlist.h"
#include "ajquery.h"
#include "ajnam.h"
#include "ajfileio.h"
#include "ajhttp.h"
#include "ajftp.h"
#include <string.h>
#ifndef WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
AjPTable textDbMethods = NULL;
static AjPStr textinReadLine = NULL;
static AjBool textinReadText(AjPTextin thys, AjPText text);
static AjBool textinReadXml(AjPTextin thys, AjPText text);
static AjBool textinReadObo(AjPTextin thys, AjPText text);
static AjBool textinReadEmbl(AjPTextin thys, AjPText text);
static AjBool textinReadGenbank(AjPTextin thys, AjPText text);
static AjBool textinReadPdb(AjPTextin thys, AjPText text);
/* @datastatic TextPInFormat **************************************************
**
** Text input formats data structure
**
** @alias TextSInFormat
** @alias TextOInFormat
**
** @attr Name [const char*] Format name
** @attr Obo [const char*] Ontology term id from EDAM
** @attr Desc [const char*] Format description
** @attr Alias [AjBool] Name is an alias for an identical definition
** @attr Try [AjBool] If true, try for an unknown input. Duplicate names
** and read-anything formats are set false
** @attr Read [AjBool function] Input function, returns ajTrue on success
** @@
******************************************************************************/
typedef struct TextSInFormat
{
const char *Name;
const char *Obo;
const char *Desc;
AjBool Alias;
AjBool Try;
AjBool (*Read) (AjPTextin thys, AjPText text);
} TextOInFormat;
#define TextPInFormat TextOInFormat*
static TextOInFormat textinFormatDef[] =
{
/* "Name", "Description" */
/* Alias, Try, */
/* ReadFunction */
{"unknown", "0000", "Unknown format",
AJFALSE, AJFALSE,
&textinReadText}, /* alias for text */
{"text", "2330", "Plain text format",
AJFALSE, AJTRUE,
&textinReadText},
{"xml", "2332", "XML data",
AJFALSE, AJTRUE,
&textinReadXml},
{"obo", "2196", "OBO data",
AJFALSE, AJTRUE,
&textinReadObo},
{"embl", "1927", "EMBL data",
AJFALSE, AJFALSE,
&textinReadEmbl},
{"genbank", "1936", "Genbank data",
AJFALSE, AJFALSE,
&textinReadGenbank},
{"swissprot", "1963", "SwissProt data",
AJTRUE, AJFALSE,
&textinReadEmbl},
{"swiss", "1963", "SwissProt data",
AJTRUE, AJFALSE,
&textinReadEmbl},
{"uniprot", "2188", "UniProt data",
AJTRUE, AJFALSE,
&textinReadEmbl},
{"uniprotkb", "2187", "UniProt-like data",
AJTRUE, AJFALSE,
&textinReadEmbl},
{"ipi", "2189", "UniProt-like data",
AJTRUE, AJFALSE,
&textinReadEmbl},
{"pdb", "1476", "PDB data",
AJFALSE, AJFALSE,
&textinReadPdb},
{"mmcif", "0000", "mmCIF structure data",
AJFALSE, AJFALSE,
&textinReadPdb},
{"csv", "0000", "Comma separated values",
AJFALSE, AJFALSE,
&textinReadText},
{"tab", "0000", "Tab separated values",
AJFALSE, AJFALSE,
&textinReadText},
{"tsv", "0000", "Tab separated values",
AJTRUE, AJFALSE,
&textinReadText},
{"iprmctab", "0000", "IPRMC tab separated values",
AJFALSE, AJFALSE,
&textinReadText},
{"iprmc", "0000", "IPRMC text",
AJFALSE, AJFALSE,
&textinReadText},
{"interpro", "0000", "InterPRO format",
AJFALSE, AJFALSE,
&textinReadText},
{"livelists", "0000", "EBI livelists format",
AJFALSE, AJFALSE,
&textinReadText},
{"hgbase", "0000", "HGBASE format",
AJFALSE, AJFALSE,
&textinReadText},
{"annot", "0000", "General annotation",
AJTRUE, AJFALSE,
&textinReadText},
{"entrysize", "0000", "Entry size",
AJTRUE, AJFALSE,
&textinReadText},
{"tinyseq", "0000", "Refseq tinyseq format",
AJTRUE, AJFALSE,
&textinReadText},
{"uniref50", "0000", "UniRef50 format",
AJTRUE, AJFALSE,
&textinReadText},
{"uniref90", "0000", "UniRef90 format",
AJTRUE, AJFALSE,
&textinReadText},
{"uniref100", "0000", "UniRef100 format",
AJTRUE, AJFALSE,
&textinReadText},
{"uniparc", "0000", "UniParc format",
AJTRUE, AJFALSE,
&textinReadText},
{"resid", "0000", "ResId format",
AJTRUE, AJFALSE,
&textinReadText},
{"nrl1", "0000", "Patent non-redundant level 1 format",
AJTRUE, AJFALSE,
&textinReadText},
{"nrl2", "0000", "Patent non-redundant level 2 format",
AJTRUE, AJFALSE,
&textinReadText},
{"ris", "0000", "MedLine RIS format",
AJTRUE, AJFALSE,
&textinReadText},
{"isi", "0000", "MedLine ISI format",
AJTRUE, AJFALSE,
&textinReadText},
{"bibtex", "0000", "MedLine BibTex format",
AJTRUE, AJFALSE,
&textinReadText},
{"endnote", "0000", "MedLine EndNote format",
AJTRUE, AJFALSE,
&textinReadText},
{"medlineref", "0000", "MedLine ref format",
AJTRUE, AJFALSE,
&textinReadText},
{"medlinefull", "0000", "MedLine full format",
AJTRUE, AJFALSE,
&textinReadText},
{NULL, NULL, NULL, 0, 0, NULL}
};
static ajuint textinReadFmt(AjPTextin textin, AjPText text,
ajuint format);
static AjBool textinRead(AjPTextin textin, AjPText text);
static AjBool textinformatFind(const AjPStr format, ajint* iformat);
static AjBool textinFormatSet(AjPTextin textin, AjPText text);
static AjBool textinListProcess(AjPTextin textin, AjPText text,
const AjPStr listfile);
static void textinListNoComment(AjPStr* text);
static void textinQryRestore(AjPTextin textin, const AjPQueryList node);
static void textinQrySave(AjPQueryList node, const AjPTextin textin);
static AjBool textDefine(AjPText thys, AjPTextin textin);
static AjBool textinQryProcess(AjPTextin textin, AjPText text);
static AjBool textinQueryMatch(const AjPQuery thys, const AjPText text);
/* @filesection ajtextread ****************************************************
**
** @nam1rule aj Function belongs to the AJAX library.
**
*/
/* @datasection [AjPTextin] Text input objects ********************************
**
** Function is for manipulating text input objects
**
** @nam2rule Textin
******************************************************************************/
/* @section Text Input Constructors *******************************************
**
** All constructors return a new text input object by pointer. It
** is the responsibility of the user to first destroy any previous
** text input object. The target pointer does not need to be
** initialised to NULL, but it is good programming practice to do so
** anyway.
**
** @fdata [AjPTextin]
**
** @nam3rule New Construct a new text input object
** @nam4rule Datatype Construct a new text input object for a
** specific datatype
**
** @argrule Datatype datatype [const AjEDataType] Enumerated datatype
**
** @valrule * [AjPTextin] New text input object
**
** @fcategory new
**
******************************************************************************/
/* @func ajTextinNew **********************************************************
**
** Creates a new text input object.
**
** @return [AjPTextin] New text input object.
** @category new [AjPTextin] Default constructor
**
** @release 6.4.0
** @@
******************************************************************************/
AjPTextin ajTextinNew(void)
{
return ajTextinNewDatatype(AJDATATYPE_UNKNOWN);
}
/* @func ajTextinNewDatatype **************************************************
**
** Creates a new text input object for assembly data
**
** @param [r] datatype [const AjEDataType] Enumerated datatype
** @return [AjPTextin] New text input object.
** @category new [AjPTextin] Default constructor
**
** @release 6.4.0
** @@
******************************************************************************/
AjPTextin ajTextinNewDatatype(const AjEDataType datatype)
{
AjPTextin pthis;
AJNEW0(pthis);
pthis->Db = ajStrNew();
pthis->Qry = ajStrNew();
pthis->Formatstr = ajStrNew();
pthis->QryFields = ajStrNew();
pthis->Filename = ajStrNew();
pthis->Query = ajQueryNew(datatype);
pthis->Search = ajTrue;
return pthis;
}
/* @section Text Input Destructors ********************************************
**
** Destruction destroys all internal data structures and frees the
** memory allocated for the text input object.
**
** @fdata [AjPTextin]
**
** @nam3rule Del Destructor
** @nam4rule Nofile File buffer is a copy, do not delete
**
** @argrule Del pthis [AjPTextin*] Text input
**
** @valrule * [void]
**
** @fcategory delete
**
******************************************************************************/
/* @func ajTextinDel **********************************************************
**
** Deletes a text input object.
**
** @param [d] pthis [AjPTextin*] Text input
** @return [void]
** @category delete [AjPTextin] Default destructor
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinDel(AjPTextin* pthis)
{
AjPTextin thys;
AjPQueryList node = NULL;
if(!pthis)
return;
thys = *pthis;
if(!thys)
return;
ajDebug("ajTextinDel called qry:'%S' filebuff: %x\n",
thys->Qry, thys->Filebuff);
ajStrDel(&thys->Db);
ajStrDel(&thys->Qry);
ajStrDel(&thys->Formatstr);
ajStrDel(&thys->QryFields);
ajStrDel(&thys->Filename);
while(ajListGetLength(thys->List))
{
ajListPop(thys->List, (void**) &node);
ajStrDel(&node->Qry);
ajStrDel(&node->Formatstr);
AJFREE(node);
}
ajListFree(&thys->List);
ajQueryDel(&thys->Query);
if(thys->Filebuff)
ajFilebuffDel(&thys->Filebuff);
AJFREE(*pthis);
return;
}
/* @func ajTextinDelNofile ****************************************************
**
** Deletes a text input object but do not close the file as it is a
** copy of a file buffer elsewhere
**
** @param [d] pthis [AjPTextin*] Text input
** @return [void]
** @category delete [AjPTextin] Default destructor
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinDelNofile(AjPTextin* pthis)
{
AjPTextin thys;
AjPQueryList node = NULL;
if(!pthis)
return;
thys = *pthis;
if(!thys)
return;
ajDebug("ajTextinDel called qry:'%S'\n", thys->Qry);
ajStrDel(&thys->Db);
ajStrDel(&thys->Qry);
ajStrDel(&thys->Formatstr);
ajStrDel(&thys->QryFields);
ajStrDel(&thys->Filename);
while(ajListGetLength(thys->List))
{
ajListPop(thys->List, (void**) &node);
ajStrDel(&node->Qry);
ajStrDel(&node->Formatstr);
AJFREE(node);
}
ajListFree(&thys->List);
ajQueryDel(&thys->Query);
AJFREE(*pthis);
return;
}
/* @section text input modifiers **********************************************
**
** These functions use the contents of a text input object and
** update them.
**
** @fdata [AjPTextin]
**
** @nam3rule Clear Clear all values
** @nam3rule Qry Reset using a query string
** @nam4rule Newfile Starting a new file to continue input
** @nam4rule Newinput Continue input from same file
** @nam4rule Nofile File buffer is a copy, do not delete
** @suffix C Character string input
** @suffix S String input
**
** @argrule * thys [AjPTextin] Text input object
** @argrule C txt [const char*] Query text
** @argrule S str [const AjPStr] query string
**
** @valrule * [void]
**
** @fcategory modify
**
******************************************************************************/
/* @func ajTextinClear ********************************************************
**
** Clears a text input object back to "as new" condition, except
** for the query list which must be preserved.
**
** @param [w] thys [AjPTextin] Text input
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinClear(AjPTextin thys)
{
ajDebug("ajTextinClear called\n");
if(!thys)
return;
ajStrSetClear(&thys->Db);
ajStrSetClear(&thys->Qry);
ajStrSetClear(&thys->Formatstr);
ajStrSetClear(&thys->QryFields);
ajStrSetClear(&thys->Filename);
/* preserve thys->List */
if(thys->Filebuff)
ajFilebuffDel(&thys->Filebuff);
if(thys->Filebuff)
ajFatal("ajTextinClear did not delete Filebuff");
ajQueryClear(thys->Query);
thys->TextData = NULL;
thys->Search = ajTrue;
thys->Single = ajFalse;
/* thys->CaseId= ajFalse;*/
/* thys->Multi = ajFalse;*/
/* thys->Text = ajFalse;*/
thys->ChunkEntries = ajFalse;
thys->Count = 0;
thys->Dataread = ajFalse;
thys->Datadone = ajFalse;
thys->Datacount = 0;
/* preserve thys->Filecount */
/* preserve thys->Entrycount */
thys->Records = 0;
thys->TotRecords = 0;
thys->Fpos = 0L;
thys->Curpos = 0L;
return;
}
/* @func ajTextinClearNewfile *************************************************
**
** Clears a text input object statistics for continued input with a new file
**
** @param [w] thys [AjPTextin] Text input
** @return [void]
** @category modify [AjPTextin] Resets ready for reuse.
**
** @release 6.6.0
** @@
******************************************************************************/
void ajTextinClearNewfile(AjPTextin thys)
{
ajDebug("ajTextinClearNewfile called\n");
thys->Filecount++;
thys->Records = 0;
thys->Fpos = 0L;
thys->Curpos = 0L;
return;
}
/* @func ajTextinClearNewinput ************************************************
**
** Clears a text input object statistics for continued input with same file
**
** @param [w] thys [AjPTextin] Text input
** @return [void]
** @category modify [AjPTextin] Resets ready for reuse.
**
** @release 6.6.0
** @@
******************************************************************************/
void ajTextinClearNewinput(AjPTextin thys)
{
ajDebug("ajTextinClearNewinput called\n");
thys->Records = 0;
return;
}
/* @func ajTextinClearNofile **************************************************
**
** Clears a text input object back to "as new" condition, except
** for the query list which must be preserved.
**
** @param [w] thys [AjPTextin] Text input
** @return [void]
** @category modify [AjPTextin] Resets ready for reuse.
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinClearNofile(AjPTextin thys)
{
ajDebug("ajTextinClearNofile called\n");
ajStrSetClear(&thys->Db);
ajStrSetClear(&thys->Qry);
ajStrSetClear(&thys->Formatstr);
ajStrSetClear(&thys->QryFields);
ajStrSetClear(&thys->Filename);
/* preserve thys->List */
ajQueryClear(thys->Query);
thys->TextData = NULL;
thys->Search = ajTrue;
thys->Single = ajFalse;
/* thys->CaseId= ajFalse;*/
/* thys->Multi = ajFalse;*/
/* thys->Text = ajFalse;*/
thys->ChunkEntries = ajFalse;
thys->Count = 0;
/* preserve thys->Filecount */
/* preserve thys->Entrycount */
thys->Records = 0;
thys->TotRecords = 0;
thys->Fpos = 0L;
thys->Curpos = 0L;
return;
}
/* @func ajTextinQryC *********************************************************
**
** Resets a text input object using a new Universal
** Query Address
**
** @param [u] thys [AjPTextin] text input object.
** @param [r] txt [const char*] Query
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinQryC(AjPTextin thys, const char* txt)
{
ajTextinClear(thys);
ajStrAssignC(&thys->Qry, txt);
return;
}
/* @func ajTextinQryS *********************************************************
**
** Resets a text input object using a new Universal
** Query Address
**
** @param [u] thys [AjPTextin] Text input object.
** @param [r] str [const AjPStr] Query
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinQryS(AjPTextin thys, const AjPStr str)
{
ajTextinClear(thys);
ajStrAssignS(&thys->Qry, str);
return;
}
/* @section store ************************************************************
**
** Read text data using a text input object and if saved text is
** defined, maintain a text argument.
**
** @fdata [AjPTextin]
**
** @nam3rule Store Manage a text buffer for all input to date
** @nam4rule Clear Reset the text buffer to the end if the last text input
** @nam4rule Readline Read the next line of input
** and store in buffer if required
** @nam4rule Reset Reset the file buffer and any buffered text.
**
** @argrule * thys [AjPTextin] Text input object
** @argrule Clear lines [ajint] Number of lines to keep in buffer
** @argrule Clear rdline [const AjPStr] Most recent input line to trim
** from buffer
** @argrule Readline pdest [AjPStr*] Latest input line
** @argrule Store astr [AjPStr*] Buffered text data
**
** @valrule * [void]
** @valrule *Readline [AjBool] True on success
**
** @fcategory cast
**
******************************************************************************/
/* @func ajTextinStoreClear ***************************************************
**
** Clear the latest record from a text input buffer and any saved buffered text
**
** @param [u] thys [AjPTextin] Text input object
** @param [r] lines [ajint] Number of lines to keep
** @param [r] rdline [const AjPStr] Last input record to trim
** @param [u] astr [AjPStr*] Current text buffer
** @return [void]
******************************************************************************/
void ajTextinStoreClear(AjPTextin thys,
ajint lines, const AjPStr rdline,
AjPStr* astr)
{
ajDebug("ajTextinStoreClear Records: %u lines: %d len: %Lu\n",
thys->Records, lines, (ajulong) ajStrGetLen(rdline));
ajFilebuffClearStore(thys->Filebuff, lines, rdline, thys->Text, astr);
if(lines < 0)
{
thys->TotRecords -= thys->Records;
thys->Records = 0;
}
if(lines > 0)
{
if((ajint) thys->Records >= lines)
thys->Records -= lines;
else
thys->Records = 0;
if((ajint) thys->TotRecords >= lines)
thys->TotRecords -= lines;
else
thys->TotRecords = 0;
}
return;
}
/* @func ajTextinStoreReadline ************************************************
**
** Read the next line of input and if required store in buffer
**
** @param [u] thys [AjPTextin] Text input object
** @param [w] pdest [AjPStr*] Next input record
** @param [u] astr [AjPStr*] Current text buffer
** @return [AjBool] True on success
******************************************************************************/
AjBool ajTextinStoreReadline(AjPTextin thys,
AjPStr* pdest, AjPStr* astr)
{
AjBool ret;
ret = ajBuffreadLinePosStore(thys->Filebuff, pdest,
&thys->Curpos, thys->Text,
astr);
if(ret)
{
thys->Records++;
thys->TotRecords++;
}
return ret;
}
/* @func ajTextinStoreReset ***************************************************
**
** Reset a text input object buffer and any saved buffered text
**
** @param [u] thys [AjPTextin] Text input object
** @param [u] astr [AjPStr*] Current text buffer
** @return [void]
******************************************************************************/
void ajTextinStoreReset(AjPTextin thys, AjPStr* astr)
{
ajDebug("ajTextinStoreReset Records: %u\n", thys->Records);
ajFilebuffResetStore(thys->Filebuff, thys->Text, astr);
thys->Records = 0;
return;
}
/* @section casts *************************************************************
**
** Return values
**
** @fdata [AjPTextin]
**
** @nam3rule Get Get text input stream values
** @nam4rule GetCount Get text input count
** @nam4rule GetFpos Get text input file position for latest record
** @nam4rule GetQry Get text query
** @nam4rule GetRecords get text input records count for this file
** @nam4rule GetTotrecords Get text input total record count
** @nam3rule Trace Write debugging output
** @suffix S Return as a string object
**
** @argrule * thys [const AjPTextin] Text input object
**
** @valrule * [void]
** @valrule *Count [ajuint] Count
** @valrule *Fpos [ajlong] File position
** @valrule *Records [ajuint] Record count
** @valrule *Totrecords [ajuint] Totalecord count
** @valrule *S [const AjPStr] String value
**
** @fcategory cast
**
******************************************************************************/
/* @func ajTextinGetCount *****************************************************
**
** Returns the input count of a text input object
**
** @param [r] thys [const AjPTextin] Text input object.
** @return [ajuint] Input count
**
** @release 6.6.0
** @@
******************************************************************************/
ajuint ajTextinGetCount(const AjPTextin thys)
{
return thys->Count;
}
/* @func ajTextinGetFpos ******************************************************
**
** Returns the file position of a text input object
**
** @param [r] thys [const AjPTextin] Text input object.
** @return [ajlong] File position
**
** @release 6.6.0
** @@
******************************************************************************/
ajlong ajTextinGetFpos(const AjPTextin thys)
{
return thys->Curpos;
}
/* @func ajTextinGetQryS ******************************************************
**
** Returns the query of a text input object
**
** @param [r] thys [const AjPTextin] Text input object.
** @return [const AjPStr] Query string
**
** @release 6.4.0
** @@
******************************************************************************/
const AjPStr ajTextinGetQryS(const AjPTextin thys)
{
return thys->Qry;
}
/* @func ajTextinGetRecords ***************************************************
**
** Returns the record count of a text input object
**
** @param [r] thys [const AjPTextin] Text input object.
** @return [ajuint] Record count
**
** @release 6.6.0
** @@
******************************************************************************/
ajuint ajTextinGetRecords(const AjPTextin thys)
{
return thys->Records;
}
/* @func ajTextinGetTotrecords ************************************************
**
** Returns the total record count of a text input object
**
** @param [r] thys [const AjPTextin] Text input object.
** @return [ajuint] Total record count
**
** @release 6.6.0
** @@
******************************************************************************/
ajuint ajTextinGetTotrecords(const AjPTextin thys)
{
return thys->TotRecords;
}
/* @func ajTextinTrace ********************************************************
**
** Debug calls to trace the data in a text input object.
**
** @param [r] thys [const AjPTextin] Text input object.
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinTrace(const AjPTextin thys)
{
ajDebug("text input trace\n");
ajDebug( "====================\n\n");
if(ajStrGetLen(thys->Db))
ajDebug( " Db: '%S'\n", thys->Db);
if(ajStrGetLen(thys->Formatstr))
ajDebug( " Format: '%S' (%u)\n", thys->Formatstr, thys->Format);
if(ajStrGetLen(thys->QryFields))
ajDebug( " Fields: '%S'\n", thys->QryFields);
if(ajStrGetLen(thys->Qry))
ajDebug( " Query: '%S'\n", thys->Qry);
if(ajStrGetLen(thys->Filename))
ajDebug( " Filename: '%S'\n", thys->Filename);
if(ajListGetLength(thys->List))
ajDebug( " List: (%Lu)\n", ajListGetLength(thys->List));
if(thys->Filebuff)
ajDebug( " Filebuff: %F (%Ld)\n",
ajFilebuffGetFile(thys->Filebuff),
ajFileResetPos(ajFilebuffGetFile(thys->Filebuff)));
if(thys->Search)
ajDebug( " Search: %B\n", thys->Search);
if(thys->Single)
ajDebug( " Single: %B\n", thys->Single);
if(thys->Multi)
ajDebug( " Multi: %B\n", thys->Multi);
if(thys->CaseId)
ajDebug( " CaseId: %B\n", thys->CaseId);
if(thys->Text)
ajDebug( " Savetext: %B\n", thys->Text);
if(thys->Count)
ajDebug( " Count: %u\n", thys->Count);
if(thys->Filecount)
ajDebug( " File count: %u\n", thys->Filecount);
if(thys->Entrycount)
ajDebug( " Entry count: %u\n", thys->Entrycount);
if(thys->Fpos)
ajDebug( " Fpos: %Ld\n", thys->Fpos);
if(thys->Curpos)
ajDebug( "Curpos: %Ld\n", thys->Curpos);
if(thys->Query)
ajQueryTrace(thys->Query);
if(thys->TextData)
ajDebug( " TextData: exists\n");
return;
}
/* @section Text data inputs **************************************************
**
** These functions read the text data provided by the first argument
**
** @fdata [AjPTextin]
**
** @nam3rule Read Read text data
**
** @argrule Read textin [AjPTextin] Text input object
** @argrule Read text [AjPText] Text data
**
** @valrule * [AjBool] true on success
**
** @fcategory input
**
******************************************************************************/
/* @func ajTextinRead *********************************************************
**
** If the file is not yet open, calls textinQryProcess to convert the
** query into an open file stream.
**
** Uses textinRead for the actual file reading.
**
** Returns the results in the AjPText object.
**
** @param [u] textin [AjPTextin] text data input definitions
** @param [w] text [AjPText] text data returned.
** @return [AjBool] ajTrue on success.
** @category input [AjPText] Master text data input, calls specific functions
** for file access type and text data format.
**
** @release 6.4.0
** @@
******************************************************************************/
AjBool ajTextinRead(AjPTextin textin, AjPText text)
{
AjBool ret = ajFalse;
AjPQueryList node = NULL;
AjBool listdata = ajFalse;
if(textin->Filebuff)
{
/* (a) if file still open, keep reading */
ajDebug("ajTextinRead: input file '%F' still there, try again\n",
textin->Filebuff->File);
ret = textinRead(textin, text);
ajDebug("ajTextinRead: open buffer qry: '%S' returns: %B\n",
textin->Qry, ret);
}
else
{
/* (b) if we have a list, try the next query in the list */
if(ajListGetLength(textin->List))
{
listdata = ajTrue;
ajListPop(textin->List, (void**) &node);
ajDebug("++pop from list '%S'\n", node->Qry);
ajTextinQryS(textin, node->Qry);
ajDebug("++SAVE TEXTIN '%S' '%S' %d\n",
textin->Qry,
textin->Formatstr, textin->Format);
textinQryRestore(textin, node);
ajStrDel(&node->Qry);
ajStrDel(&node->Formatstr);
AJFREE(node);
ajDebug("ajTextinRead: open list, try '%S'\n", textin->Qry);
if(!textinQryProcess(textin, text) &&
!ajListGetLength(textin->List))
return ajFalse;
ret = textinRead(textin, text);
ajDebug("ajTextinRead: list qry: '%S' returns: %B\n",
textin->Qry, ret);
}
else
{
ajDebug("ajTextinRead: no file yet - test query '%S'\n",
textin->Qry);
/* (c) Must be a query - decode it */
if(!textinQryProcess(textin, text) &&
!ajListGetLength(textin->List))
return ajFalse;
if(ajListGetLength(textin->List)) /* could be a new list */
listdata = ajTrue;
ret = textinRead(textin, text);
ajDebug("ajTextinRead: new qry: '%S' returns: %B\n",
textin->Qry, ret);
}
}
/* Now read whatever we got */
while(!ret && ajListGetLength(textin->List))
{
/* Failed, but we have a list still - keep trying it */
if(listdata)
ajErr("Failed to read text data '%S'", textin->Qry);
listdata = ajTrue;
ajListPop(textin->List,(void**) &node);
ajDebug("++try again: pop from list '%S'\n", node->Qry);
ajTextinQryS(textin, node->Qry);
ajDebug("++SAVE (AGAIN) TEXTIN '%S' '%S' %d\n",
textin->Qry,
textin->Formatstr, textin->Format);
textinQryRestore(textin, node);
ajStrDel(&node->Qry);
ajStrDel(&node->Formatstr);
AJFREE(node);
if(!textinQryProcess(textin, text))
continue;
ret = textinRead(textin, text);
ajDebug("ajTextinRead: list retry qry: '%S' returns: %B\n",
textin->Qry, ret);
}
if(!ret)
{
if(listdata)
ajErr("Failed to read text data '%S'", textin->Qry);
return ajFalse;
}
textDefine(text, textin);
return ajTrue;
}
/* @funcstatic textinQueryMatch ***********************************************
**
** Compares a text data item to a query and returns true if they match.
**
** @param [r] thys [const AjPQuery] query.
** @param [r] text [const AjPText] Text data.
** @return [AjBool] ajTrue if the text data matches the query.
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinQueryMatch(const AjPQuery thys, const AjPText text)
{
AjBool tested = ajFalse;
AjIList iterfield = NULL;
AjPQueryField field = NULL;
AjBool ok = ajFalse;
ajDebug("textinQueryMatch '%S' fields: %Lu Case %B Done %B\n",
text->Id, ajListGetLength(thys->QueryFields),
thys->CaseId, thys->QryDone);
if(!thys) /* no query to test, that's fine */
return ajTrue;
if(thys->QryDone) /* do we need to test here? */
return ajTrue;
/* test the query field(s) */
iterfield = ajListIterNewread(thys->QueryFields);
while(!ajListIterDone(iterfield))
{
field = ajListIterGet(iterfield);
ajDebug(" field: '%S' Query: '%S'\n",
field->Field, field->Wildquery);
if(ajStrMatchC(field->Field, "id"))
{
ajDebug(" id test: '%S'\n",
text->Id);
if(thys->CaseId)
{
if(ajStrMatchWildS(text->Id, field->Wildquery))
{
ajListIterDel(&iterfield);
return ajTrue;
}
}
else
{
if(ajStrMatchWildCaseS(text->Id, field->Wildquery))
{
ajListIterDel(&iterfield);
return ajTrue;
}
}
ajDebug("id test failed\n");
tested = ajTrue;
ok = ajFalse;
}
if(ajStrMatchC(field->Field, "acc")) /* test id, use trueid */
{
if(ajStrMatchWildCaseS(text->Id, field->Wildquery))
{
ajListIterDel(&iterfield);
return ajTrue;
}
}
}
ajListIterDel(&iterfield);
if(!tested) /* nothing to test, so accept it anyway */
{
ajDebug(" no tests: assume OK\n");
return ajTrue;
}
ajDebug("result: %B\n", ok);
return ok;
}
/* @funcstatic textDefine *****************************************************
**
** Make sure all text data object attributes are defined
** using values from the text input object if needed
**
** @param [w] thys [AjPText] Text data returned.
** @param [u] textin [AjPTextin] Text data input definitions
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textDefine(AjPText thys, AjPTextin textin)
{
/* if values are missing in the text object, we can use defaults
from textin or calculate where possible */
/* assign the dbname if defined in the textin object */
if(ajStrGetLen(textin->Db))
ajStrAssignS(&thys->Db, textin->Db);
return ajTrue;
}
/* @funcstatic textinReadFmt **************************************************
**
** Tests whether an text data can be read using the specified format.
** Then tests whether the text data matches text data query criteria
** and checks any specified type. Applies upper and lower case.
**
** @param [u] textin [AjPTextin] text data input object
** @param [w] text [AjPText] text data object
** @param [r] format [ajuint] input format code
** @return [ajuint] 0 if successful.
** 1 if the query match failed.
** 2 if the text data type failed
** 3 if it failed to read an text data
**
** @release 6.4.0
** @@
** This is the only function that calls the appropriate Read function
** textinReadXxxxxx where Xxxxxxx is the supported text data format.
**
** Some of the textReadXxxxxx functions fail to reset the buffer correctly,
** which is a very serious problem when cycling through all of them to
** identify an unknown format. The extra ajFileBuffReset call at the end is
** intended to address this problem. The individual functions should still
** reset the buffer in case they are called from elsewhere.
**
******************************************************************************/
static ajuint textinReadFmt(AjPTextin textin, AjPText text,
ajuint format)
{
ajDebug("++textinReadFmt format %d (%s) '%S'\n",
format, textinFormatDef[format].Name,
textin->Qry);
textin->Records = 0;
/* Calling funclist textinFormatDef() */
if((*textinFormatDef[format].Read)(textin, text))
{
ajDebug("textinReadFmt success with format %d (%s)\n",
format, textinFormatDef[format].Name);
ajDebug("id: '%S'\n",
text->Id);
textin->Format = format;
ajStrAssignC(&textin->Formatstr, textinFormatDef[format].Name);
ajStrAssignC(&text->Formatstr, textinFormatDef[format].Name);
ajStrAssignEmptyS(&text->Db, textin->Db);
ajStrAssignS(&text->Filename, textin->Filename);
if(!ajStrGetLen(text->Id))
{
ajStrAssignS(&text->Id,
ajFileGetPrintnameS(ajFilebuffGetFile(textin->Filebuff)));
ajFilenameTrimAll(&text->Id);
ajDebug("filename as id: '%S'\n",
text->Id);
}
if(textinQueryMatch(textin->Query, text))
{
/* ajTextinTrace(textin); */
return FMT_OK;
}
ajDebug("query match failed, continuing ...\n");
ajTextClear(text);
return FMT_NOMATCH;
}
else
{
ajDebug("Testing input buffer: IsBuff: %B Eof: %B\n",
ajFilebuffIsBuffered(textin->Filebuff),
ajFilebuffIsEof(textin->Filebuff));
if (!ajFilebuffIsBuffered(textin->Filebuff) &&
ajFilebuffIsEof(textin->Filebuff))
return FMT_EOF;
ajFilebuffReset(textin->Filebuff);
ajDebug("Format %d (%s) failed, file buffer reset by textinReadFmt\n",
format, textinFormatDef[format].Name);
/* ajFilebuffTraceFull(textin->Filebuff, 10, 10);*/
}
ajDebug("++textinReadFmt failed - nothing read\n");
return FMT_FAIL;
}
/* @funcstatic textinRead *****************************************************
**
** Given data in a textin structure, tries to read everything needed
** using the specified format or by trial and error.
**
** @param [u] textin [AjPTextin] text data input object
** @param [w] text [AjPText] text data object
** @return [AjBool] ajTrue on success
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinRead(AjPTextin textin, AjPText text)
{
ajuint i;
ajuint istat = 0;
ajuint jstat = 0;
AjPFilebuff buff = textin->Filebuff;
AjBool ok;
AjPTextAccess textaccess = textin->Query->TextAccess;
AjPTextAccess textonlyaccess = textin->Query->Access;
ajTextClear(text);
ajDebug("textinRead: cleared\n");
if(textin->Single && textin->Count)
{
/*
** One text data at a time is read.
** The first text data was read by ACD
** for the following ones we need to reset the AjPTextin
**
** Single is set by the access method
*/
ajDebug("textinRead: single access - count %d - call access"
" routine again\n",
textin->Count);
/* Calling funclist textinAccess() */
if(textaccess)
{
if(!(*textaccess->Access)(textin))
{
ajDebug("textinRead: (*textaccess->Access)(textin) "
"*failed*\n");
return ajFalse;
}
}
if(textonlyaccess)
{
if(!(*textonlyaccess->Access)(textin))
{
ajDebug("textinRead: (*textonlyaccess->Access)(textin) "
"*failed*\n");
return ajFalse;
}
}
buff = textin->Filebuff;
}
ajDebug("textinRead: textin format %d '%S'\n", textin->Format,
textin->Formatstr);
textin->Count++;
if(!textin->Filebuff)
return ajFalse;
ok = ajFilebuffIsBuffered(textin->Filebuff);
while(ok)
{ /* skip blank lines */
ok = ajBuffreadLine(textin->Filebuff, &textinReadLine);
if(!ajStrIsWhite(textinReadLine))
{
ajFilebuffClear(textin->Filebuff,1);
break;
}
}
if(!textin->Format)
{ /* no format specified, try all defaults */
for(i = 1; textinFormatDef[i].Name; i++)
{
if(!textinFormatDef[i].Try) /* skip if Try is ajFalse */
continue;
ajDebug("textinRead:try format %d (%s)\n",
i, textinFormatDef[i].Name);
istat = textinReadFmt(textin, text, i);
switch(istat)
{
case FMT_OK:
ajDebug("++textinRead OK, set format %d\n", textin->Format);
textDefine(text, textin);
return ajTrue;
case FMT_BADTYPE:
ajDebug("textinRead: (a1) textinReadFmt stat == BADTYPE "
"*failed*\n");
return ajFalse;
case FMT_FAIL:
ajDebug("textinRead: (b1) textinReadFmt stat == FAIL "
"*failed*\n");
break; /* we can try next format */
case FMT_NOMATCH:
ajDebug("textinRead: (c1) textinReadFmt stat==NOMATCH "
"try again\n");
break;
case FMT_EOF:
ajDebug("textinRead: (d1) textinReadFmt stat == EOF "
"*failed*\n");
return ajFalse; /* EOF and unbuffered */
case FMT_EMPTY:
ajWarn("text data '%S' has zero length, ignored",
ajTextGetQryS(text));
ajDebug("textinRead: (e1) textinReadFmt stat==EMPTY "
"try again\n");
break;
default:
ajDebug("unknown code %d from textinReadFmt\n", stat);
}
ajTextClear(text);
if(textin->Format)
break; /* we read something */
ajFilebuffTrace(textin->Filebuff);
}
if(!textin->Format)
{ /* all default formats failed, give up */
ajDebug("textinRead:all default formats failed, give up\n");
return ajFalse;
}
ajDebug("++textinRead set format %d\n", textin->Format);
}
else
{ /* one format specified */
ajDebug("textinRead: one format specified\n");
ajFilebuffSetUnbuffered(textin->Filebuff);
ajDebug("++textinRead known format %d\n", textin->Format);
istat = textinReadFmt(textin, text, textin->Format);
switch(istat)
{
case FMT_OK:
textDefine(text, textin);
return ajTrue;
case FMT_BADTYPE:
ajDebug("textinRead: (a2) textinReadFmt stat == BADTYPE "
"*failed*\n");
return ajFalse;
case FMT_FAIL:
ajDebug("textinRead: (b2) textinReadFmt stat == FAIL "
"*failed*\n");
return ajFalse;
case FMT_NOMATCH:
ajDebug("textinRead: (c2) textinReadFmt stat == NOMATCH "
"*try again*\n");
break;
case FMT_EOF:
ajDebug("textinRead: (d2) textinReadFmt stat == EOF "
"*try again*\n");
if(textin->Records)
ajErr("Error reading file '%F' with format '%s': "
"end-of-file before end of data "
"(read %u records)",
ajFilebuffGetFile(textin->Filebuff),
textinFormatDef[textin->Format].Name,
textin->Records);
break; /* simply end-of-file */
case FMT_EMPTY:
ajWarn("text data '%S' has zero length, ignored",
ajTextGetQryS(text));
ajDebug("textinRead: (e2) textinReadFmt stat == EMPTY "
"*try again*\n");
break;
default:
ajDebug("unknown code %d from textinReadFmt\n", stat);
}
ajTextClear(text); /* 1 : read, failed to match id/acc/query */
}
/* failed - probably entry/accession query failed. Can we try again? */
ajDebug("textinRead failed - try again with format %d '%s' code %d\n",
textin->Format,
textinFormatDef[textin->Format].Name, istat);
ajDebug("Search:%B Chunk:%B Data:%x ajFileBuffEmpty:%B\n",
textin->Search, textin->ChunkEntries,
textin->TextData, ajFilebuffIsEmpty(buff));
if(ajFilebuffIsEmpty(buff) && textin->ChunkEntries)
{
if(textaccess && !(*textaccess->Access)(textin))
return ajFalse;
else if(textonlyaccess && !(*textonlyaccess->Access)(textin))
return ajFalse;
buff = textin->Filebuff;
}
/* need to check end-of-file to avoid repeats */
while(textin->Search &&
(textin->TextData || !ajFilebuffIsEmpty(buff)))
{
jstat = textinReadFmt(textin, text, textin->Format);
switch(jstat)
{
case FMT_OK:
textDefine(text, textin);
return ajTrue;
case FMT_BADTYPE:
ajDebug("textinRead: (a3) textinReadFmt stat == BADTYPE "
"*failed*\n");
return ajFalse;
case FMT_FAIL:
ajDebug("textinRead: (b3) textinReadFmt stat == FAIL "
"*failed*\n");
return ajFalse;
case FMT_NOMATCH:
ajDebug("textinRead: (c3) textinReadFmt stat == NOMATCH "
"*try again*\n");
break;
case FMT_EOF:
ajDebug("textinRead: (d3) textinReadFmt stat == EOF "
"*failed*\n");
return ajFalse; /* we already tried again */
case FMT_EMPTY:
if(istat != FMT_EMPTY)
ajWarn("text data '%S' has zero length, ignored",
ajTextGetQryS(text));
ajDebug("textinRead: (e3) textinReadFmt stat == EMPTY "
"*try again*\n");
break;
default:
ajDebug("unknown code %d from textinReadFmt\n", stat);
}
ajTextClear(text); /* 1 : read, failed to match id/acc/query */
}
if(textin->Format)
ajDebug("textinRead: *failed* to read text data %S using format %s\n",
textin->Qry, textinFormatDef[textin->Format].Name);
else
ajDebug("textinRead: *failed* to read text data %S using any format\n",
textin->Qry);
return ajFalse;
}
/* @funcstatic textinReadText *************************************************
**
** Given data in a text structure, tries to read everything needed
** using the TEXT format.
**
** @param [u] textin [AjPTextin] Text input object
** @param [w] text [AjPText] Text object
** @return [AjBool] ajTrue on success
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinReadText(AjPTextin textin, AjPText text)
{
AjPFilebuff buff;
ajuint linecnt = 0;
ajDebug("textinReadText\n");
ajTextClear(text);
buff = textin->Filebuff;
/* ajFilebuffTrace(buff); */
textin->Curpos = 0L;
while (ajBuffreadLinePos(buff, &textinReadLine, &textin->Curpos))
{
linecnt++;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
}
ajDebug("textinReadText read %u lines\n", linecnt);
if(!linecnt)
return ajFalse;
return ajTrue;
}
/* @funcstatic textinReadXml **************************************************
**
** Given data in a text structure, tries to read everything needed
** using the XML format.
**
** @param [u] textin [AjPTextin] Text input object
** @param [w] text [AjPText] Text object
** @return [AjBool] ajTrue on success
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinReadXml(AjPTextin textin, AjPText text)
{
AjPFilebuff buff;
ajuint linecnt = 0;
ajDebug("textinReadXml\n");
ajTextClear(text);
buff = textin->Filebuff;
/* ajFilebuffTrace(buff); */
textin->Curpos = 0L;
while (ajBuffreadLinePos(buff, &textinReadLine, &textin->Curpos))
{
linecnt++;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
}
ajDebug("textinReadXml read %u lines\n", linecnt);
if(!linecnt)
return ajFalse;
return ajTrue;
}
/* @funcstatic textinReadEmbl *************************************************
**
** Given data in a text input stream, tries to read text
** using the EMBL format.
**
** @param [u] textin [AjPTextin] Text input object
** @param [w] text [AjPText] Text object
** @return [AjBool] ajTrue on success
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinReadEmbl(AjPTextin textin, AjPText text)
{
AjPFilebuff buff;
ajuint linecnt = 0;
AjBool ok = ajFalse;
ajDebug("textinReadObo\n");
ajTextClear(text);
buff = textin->Filebuff;
/* ajFilebuffTrace(buff); */
ok = ajBuffreadLine(buff, &textinReadLine);
while(ok && !ajStrPrefixC(textinReadLine, "ID "))
ok = ajBuffreadLine(buff, &textinReadLine);
if(!ok)
return ajFalse;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
ajFilebuffClear(buff, 1);
ok = ajBuffreadLine(buff, &textinReadLine);
if(ok)
ok = ajBuffreadLine(buff, &textinReadLine);
while (ok)
{
ajStrTrimWhite(&textinReadLine);
if(!ajStrGetLen(textinReadLine))
break;
linecnt++;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
if(ajStrMatchC(textinReadLine, "//"))
break;
ok = ajBuffreadLine(buff, &textinReadLine);
}
return ajTrue;
}
/* @funcstatic textinReadGenbank **********************************************
**
** Given data in a text inpur stream, tries to read text
** using the GENBANK format.
**
** @param [u] textin [AjPTextin] Text input object
** @param [w] text [AjPText] Text object
** @return [AjBool] ajTrue on success
**
** @release 6.6.0
** @@
******************************************************************************/
static AjBool textinReadGenbank(AjPTextin textin, AjPText text)
{
AjPFilebuff buff;
ajuint linecnt = 0;
AjBool ok = ajFalse;
ajDebug("textinReadObo\n");
ajTextClear(text);
buff = textin->Filebuff;
/* ajFilebuffTrace(buff); */
ok = ajBuffreadLine(buff, &textinReadLine);
while(ok && !ajStrPrefixC(textinReadLine, "LOCUS "))
ok = ajBuffreadLine(buff, &textinReadLine);
if(!ok)
return ajFalse;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
ajFilebuffClear(buff, 1);
ok = ajBuffreadLine(buff, &textinReadLine);
if(ok)
ok = ajBuffreadLine(buff, &textinReadLine);
while (ok)
{
ajStrTrimWhite(&textinReadLine);
if(!ajStrGetLen(textinReadLine))
break;
linecnt++;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
if(ajStrMatchC(textinReadLine, "//"))
break;
ok = ajBuffreadLine(buff, &textinReadLine);
}
return ajTrue;
}
/* @funcstatic textinReadObo **************************************************
**
** Given data in a text input stream, tries to read text
** using the OBO format.
**
** @param [u] textin [AjPTextin] Text input object
** @param [w] text [AjPText] Text object
** @return [AjBool] ajTrue on success
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinReadObo(AjPTextin textin, AjPText text)
{
AjPFilebuff buff;
ajuint linecnt = 0;
AjBool ok = ajFalse;
ajDebug("textinReadObo\n");
ajTextClear(text);
buff = textin->Filebuff;
/* ajFilebuffTrace(buff); */
ok = ajBuffreadLine(buff, &textinReadLine);
while(ok && !ajStrPrefixC(textinReadLine, "[Term]"))
ok = ajBuffreadLine(buff, &textinReadLine);
if(!ok)
return ajFalse;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
ajFilebuffClear(buff, 1);
ok = ajBuffreadLine(buff, &textinReadLine);
if(ok)
ok = ajBuffreadLine(buff, &textinReadLine);
while (ok)
{
ajStrTrimWhite(&textinReadLine);
if(!ajStrGetLen(textinReadLine))
break;
if(ajStrGetCharFirst(textinReadLine) == '[') /* new stanza */
break;
linecnt++;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
ok = ajBuffreadLine(buff, &textinReadLine);
}
return ajTrue;
}
/* @funcstatic textinReadPdb * ************************************************
**
** Given data in a text input stream, tries to read text
** using the PDB format.
**
** @param [u] textin [AjPTextin] Text input object
** @param [w] text [AjPText] Text object
** @return [AjBool] ajTrue on success
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinReadPdb(AjPTextin textin, AjPText text)
{
AjPFilebuff buff;
ajuint linecnt = 0;
AjBool ok = ajFalse;
ajDebug("textinReadPdb\n");
ajTextClear(text);
buff = textin->Filebuff;
/* ajFilebuffTrace(buff); */
ok = ajBuffreadLine(buff, &textinReadLine);
while(ok && !ajStrPrefixC(textinReadLine, "HEADER "))
ok = ajBuffreadLine(buff, &textinReadLine);
if(!ok)
return ajFalse;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
ajFilebuffClear(buff, 1);
ok = ajBuffreadLine(buff, &textinReadLine);
if(ok)
ok = ajBuffreadLine(buff, &textinReadLine);
while (ok)
{
ajStrTrimWhite(&textinReadLine);
if(!ajStrGetLen(textinReadLine))
break;
linecnt++;
ajStrTrimEndC(&textinReadLine, "\r\n");
ajDebug("line %u:%S\n", linecnt, textinReadLine);
/* add line to AjPText object */
ajListPushAppend(text->Lines, ajStrNewS(textinReadLine));
if(ajStrMatchC(textinReadLine, "END"))
break;
ok = ajBuffreadLine(buff, &textinReadLine);
}
return ajTrue;
}
/* @section File Access *******************************************************
**
** These functions manage the text file access methods.
**
** @fdata [AjPTextin]
**
** @nam3rule Access Access method
** @nam4rule Asis Reads text using the 'filename' as the single input line
** @nam4rule File Reading an input file
** @nam4rule Ftp Reads text using the 'filename' as an FTP URL
** @nam4rule Http Reads text using the 'filename' as an HTTP URL
** @nam4rule Offset Reading an input file starting at a given offset position
** within the text input query
**
** @argrule Access textin [AjPTextin] Text input object
** @valrule * [AjBool] True on success
**
** @fcategory input
**
******************************************************************************/
/* @func ajTextinAccessAsis ***************************************************
**
** Reads text using the 'filename' as the single input line
**
** @param [u] textin [AjPTextin] Text input.
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
AjBool ajTextinAccessAsis(AjPTextin textin)
{
AjPQuery qry;
qry = textin->Query;
if(!ajStrGetLen(qry->Filename))
{
ajErr("ASIS access: no text");
return ajFalse;
}
ajDebug("ajTextinAccessAsis %S\n", qry->Filename);
ajFilebuffDel(&textin->Filebuff);
textin->Filebuff = ajFilebuffNewLine(qry->Filename);
if(!textin->Filebuff)
{
ajDebug("Asis access: unable to use text '%S'\n", qry->Filename);
return ajFalse;
}
ajStrAssignC(&textin->Filename, "asis");
/*ajFilebuffTrace(textin->Filebuff);*/
return ajTrue;
}
/* @func ajTextinAccessFile ***************************************************
**
** Reads data from a named file.
**
** @param [u] textin [AjPTextin] Text input.
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
AjBool ajTextinAccessFile(AjPTextin textin)
{
AjPQuery qry;
qry = textin->Query;
if(!ajStrGetLen(qry->Filename))
{
ajErr("FILE access: no filename");
return ajFalse;
}
ajDebug("ajTextinAccessFile %S\n", qry->Filename);
/* ajStrTraceT(qry->Filename, "qry->Filename (before):"); */
ajFilebuffDel(&textin->Filebuff);
textin->Filebuff = ajFilebuffNewNameS(qry->Filename);
if(!textin->Filebuff)
{
ajDebug("FILE access: unable to open file '%S'\n", qry->Filename);
return ajFalse;
}
/* ajStrTraceT(textin->Filename, "textin->Filename:"); */
/* ajStrTraceT(qry->Filename, "qry->Filename (after):"); */
ajStrAssignS(&textin->Filename, qry->Filename);
return ajTrue;
}
/* @func ajTextinAccessFtp ****************************************************
**
** Reads data from an FTP URL
**
** @param [u] textin [AjPTextin] Text input.
** @return [AjBool] ajTrue on success.
**
** @release 6.5.0
** @@
******************************************************************************/
AjBool ajTextinAccessFtp(AjPTextin textin)
{
AjPQuery qry;
AjPStr url = NULL;
AjPStr host = NULL;
ajint iport;
AjPStr urlget = NULL;
AjPUrlref urlref = NULL;
iport = 21;
qry = textin->Query;
if(!ajStrGetLen(qry->Filename))
{
ajErr("FILE access: no filename");
return ajFalse;
}
ajDebug("ajTextinAccessFtp %S\n", qry->Filename);
/* ajStrTraceT(qry->Filename, "qry->Filename (before):"); */
ajStrAssignS(&url, qry->Filename);
urlref = ajHttpUrlrefNew();
ajHttpUrlrefParseS(&urlref, url);
ajHttpUrlrefSplitPort(urlref);
ajStrAssignS(&host,urlref->Host);
if(ajStrGetLen(urlref->Port))
ajStrToInt(urlref->Port, &iport);
ajFmtPrintS(&urlget,"/%S",urlref->Absolute);
ajHttpUrlrefDel(&urlref);
ajFilebuffDel(&textin->Filebuff);
textin->Filebuff = ajFtpRead(NULL, host, iport, textin->Fpos, urlget);
ajStrDel(&host);
ajStrDel(&urlget);
if(!textin->Filebuff)
{
ajDebug("FTP access: unable to open file '%S'\n", qry->Filename);
return ajFalse;
}
/* ajStrTraceT(textin->Filename, "textin->Filename:"); */
/* ajStrTraceT(qry->Filename, "qry->Filename (after):"); */
ajStrAssignS(&textin->Filename, qry->Filename);
ajDebug("FTP access: opened file '%S'\n", qry->Filename);
ajStrDel(&url);
return ajTrue;
}
/* @func ajTextinAccessHttp ***************************************************
**
** Reads data from an HTTP URL. No HTML is stripped.
**
** @param [u] textin [AjPTextin] Text input.
** @return [AjBool] ajTrue on success.
**
** @release 6.5.0
** @@
******************************************************************************/
AjBool ajTextinAccessHttp(AjPTextin textin)
{
AjPQuery qry;
AjPStr url = NULL;
AjPStr host = NULL;
ajint iport;
AjPStr urlget = NULL;
AjPUrlref urlref = NULL;
AjPStr version10 = NULL;
AjBool ok;
iport = 80;
qry = textin->Query;
if(!ajStrGetLen(qry->Filename))
{
ajErr("HTTP access: no filename");
return ajFalse;
}
ajDebug("ajTextinAccessHttp %S\n", qry->Filename);
ajStrAssignS(&url, qry->Filename);
urlref = ajHttpUrlrefNew();
ajHttpUrlrefParseS(&urlref, url);
ajHttpUrlrefSplitPort(urlref);
ajStrAssignS(&host,urlref->Host);
if(ajStrGetLen(urlref->Port))
ajStrToInt(urlref->Port, &iport);
ajFmtPrintS(&urlget,"/%S",urlref->Absolute);
ajHttpUrlrefDel(&urlref);
version10 = ajStrNewC("1.0");
ajFilebuffDel(&textin->Filebuff);
textin->Filebuff = ajHttpReadPos(version10, url,
NULL, host, iport, urlget, qry->Fpos);
ajStrDel(&version10);
if(!textin->Filebuff)
{
if(iport == 80)
ajErr("Cannot open HTTP connection 'http://%S%S'",
host, urlget);
else
ajErr("Cannot open HTTP connection 'http://%S:%d%S'",
host, iport, urlget);
return ajFalse;
}
/* skip past the header */
ok = ajBuffreadLine(textin->Filebuff, &textinReadLine);
switch(ajStrGetCharPos(textinReadLine, 9))
{
case '4':
return ajFalse;
default:
break;
}
while(ok && ajStrFindRestC(textinReadLine, "\r\n") >= 0)
ajBuffreadLine(textin->Filebuff, &textinReadLine);
ajFilebuffClear(textin->Filebuff,1);
ajStrDel(&host);
ajStrDel(&urlget);
if(!textin->Filebuff)
{
ajDebug("HTTP access: unable to open file '%S'\n", qry->Filename);
return ajFalse;
}
/* ajStrTraceT(textin->Filename, "textin->Filename:"); */
/* ajStrTraceT(qry->Filename, "qry->Filename (after):"); */
ajStrAssignS(&textin->Filename, url);
ajStrDel(&url);
return ajTrue;
}
/* @func ajTextinAccessOffset *************************************************
**
** Reads a text from a named file, at a given offset within the file.
**
** @param [u] textin [AjPTextin] Text input.
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
AjBool ajTextinAccessOffset(AjPTextin textin)
{
AjPQuery qry;
qry = textin->Query;
if(!ajStrGetLen(qry->Filename))
{
ajErr("FILE access: no filename");
return ajFalse;
}
ajDebug("ajTextinAccessOffset %S %Ld\n", qry->Filename, qry->Fpos);
/* ajStrTraceT(qry->Filename, "qry->Filename (before):"); */
ajFilebuffDel(&textin->Filebuff);
textin->Filebuff = ajFilebuffNewNameS(qry->Filename);
if(!textin->Filebuff)
{
ajDebug("OFFSET access: unable to open file '%S'\n", qry->Filename);
return ajFalse;
}
ajFileSeek(ajFilebuffGetFile(textin->Filebuff), qry->Fpos, 0);
/* ajStrTraceT(textin->Filename, "textin->Filename:"); */
/* ajStrTraceT(qry->Filename, "qry->Filename (after):"); */
ajStrAssignS(&textin->Filename, qry->Filename);
return ajTrue;
}
/* @datasection [none] Miscellaneous ******************************************
**
** Text input internals
**
** @nam2rule Textin Text input
**
******************************************************************************/
/* @section Printing **********************************************************
**
** Printing details of the internals to a file
**
** @fdata [none]
**
** @nam2rule Textinprint
**
** @fcategory output
**
******************************************************************************/
/* @section Print *************************************************************
**
** Printing to a file
**
** @fdata [none]
**
** @nam3rule Book Print as docbook table
** @nam3rule Html Print as html table
** @nam3rule Wiki Print as wiki table
** @nam3rule Text Print as text
**
** @argrule * outf [AjPFile] output file
** @argrule Text full [AjBool] Print all details
**
** @valrule * [void]
**
** @fcategory cast
**
******************************************************************************/
/* @func ajTextinprintBook ****************************************************
**
** Reports the internal data structures as a Docbook table
**
** @param [u] outf [AjPFile] Output file
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinprintBook(AjPFile outf)
{
ajuint i = 0;
ajuint j = 0;
AjPStr namestr = NULL;
AjPList fmtlist;
AjPStr* names;
fmtlist = ajListstrNew();
ajFmtPrintF(outf, "<para>The supported text formats are summarised "
"in the table below. "
"The columns are as follows: "
"<emphasis>Input format</emphasis> (format name), "
"<emphasis>Try</emphasis> (indicates whether the "
"format can be detected automatically on input), and "
"<emphasis>Description</emphasis> (short description of "
"the format).</para>\n\n");
ajFmtPrintF(outf, "<table frame=\"box\" rules=\"cols\">\n");
ajFmtPrintF(outf, " <caption>Input text formats</caption>\n");
ajFmtPrintF(outf, " <thead>\n");
ajFmtPrintF(outf, " <tr align=\"center\">\n");
ajFmtPrintF(outf, " <th>Input Format</th>\n");
ajFmtPrintF(outf, " <th>Try</th>\n");
ajFmtPrintF(outf, " <th>Description</th>\n");
ajFmtPrintF(outf, " </tr>\n");
ajFmtPrintF(outf, " </thead>\n");
ajFmtPrintF(outf, " <tbody>\n");
for(i=1; textinFormatDef[i].Name; i++)
{
if(!textinFormatDef[i].Alias)
{
namestr = ajStrNewC(textinFormatDef[i].Name);
ajListPushAppend(fmtlist, namestr);
namestr = NULL;
}
}
ajListSort(fmtlist, &ajStrVcmp);
ajListstrToarray(fmtlist, &names);
for(i=0; names[i]; i++)
{
for(j=0; textinFormatDef[j].Name; j++)
{
if(ajStrMatchC(names[i],textinFormatDef[j].Name))
{
ajFmtPrintF(outf, " <tr>\n");
ajFmtPrintF(outf, " <td>%s</td>\n",
textinFormatDef[j].Name);
ajFmtPrintF(outf, " <td>%B</td>\n",
textinFormatDef[j].Try);
ajFmtPrintF(outf, " <td>%s</td>\n",
textinFormatDef[j].Desc);
ajFmtPrintF(outf, " </tr>\n");
}
}
}
ajFmtPrintF(outf, " </tbody>\n");
ajFmtPrintF(outf, "</table>\n");
ajStrDel(&namestr);
names = NULL;
ajListstrFreeData(&fmtlist);
return;
}
/* @func ajTextinprintHtml ****************************************************
**
** Reports the internal data structures as an HTML table
**
** @param [u] outf [AjPFile] Output file
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinprintHtml(AjPFile outf)
{
ajuint i = 0;
ajuint j = 0;
AjPStr namestr = NULL;
ajFmtPrintF(outf, "<table border=3>");
ajFmtPrintF(outf, "<tr><th>Input Format</th><th>Auto</th>\n");
ajFmtPrintF(outf, "<th>Multi</th><th>Description</th></tr>\n");
for(i=1; textinFormatDef[i].Name; i++)
{
ajStrAssignC(&namestr, textinFormatDef[i].Name);
if(!textinFormatDef[i].Alias)
{
for(j=i+1; textinFormatDef[j].Name; j++)
{
if(textinFormatDef[j].Read == textinFormatDef[i].Read)
{
ajFmtPrintAppS(&namestr, " %s", textinFormatDef[j].Name);
if(!textinFormatDef[j].Alias)
{
ajWarn("Input format '%s' same as '%s' but not alias",
textinFormatDef[j].Name,
textinFormatDef[i].Name);
}
}
}
ajFmtPrintF(outf, "<tr><td>\n%S\n</td><td>%B</td>\n",
namestr,
textinFormatDef[i].Try);
ajFmtPrintF(outf, "<td>\n%s\n</td></tr>\n",
textinFormatDef[i].Desc);
}
}
ajFmtPrintF(outf, "</table>\n");
ajStrDel(&namestr);
return;
}
/* @func ajTextinprintText ****************************************************
**
** Reports the internal data structures
**
** @param [u] outf [AjPFile] Output file
** @param [r] full [AjBool] Full report (usually ajFalse)
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinprintText(AjPFile outf, AjBool full)
{
ajuint i = 0;
ajFmtPrintF(outf, "\n");
ajFmtPrintF(outf, "# Text input formats\n");
ajFmtPrintF(outf, "# Name Format name (or alias)\n");
ajFmtPrintF(outf, "# Alias Alias name\n");
ajFmtPrintF(outf, "# Try Test for unknown input files\n");
ajFmtPrintF(outf, "# Name Alias Try "
"Description");
ajFmtPrintF(outf, "\n");
ajFmtPrintF(outf, "InFormat {\n");
for(i=0; textinFormatDef[i].Name; i++)
if(full || !textinFormatDef[i].Alias)
ajFmtPrintF(outf,
" %-12s %5B %3B \"%s\"\n",
textinFormatDef[i].Name,
textinFormatDef[i].Alias,
textinFormatDef[i].Try,
textinFormatDef[i].Desc);
ajFmtPrintF(outf, "}\n\n");
return;
}
/* @func ajTextinprintWiki ****************************************************
**
** Reports the internal data structures as a wiki table
**
** @param [u] outf [AjPFile] Output file
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinprintWiki(AjPFile outf)
{
ajuint i = 0;
ajuint j = 0;
AjPStr namestr = NULL;
ajFmtPrintF(outf, "{| class=\"wikitable sortable\" border=\"2\"\n");
ajFmtPrintF(outf, "|-\n");
ajFmtPrintF(outf, "!Format!!Try!!"
"class=\"unsortable\"|Description\n");
for(i=1; textinFormatDef[i].Name; i++)
{
ajStrAssignC(&namestr, textinFormatDef[i].Name);
if(!textinFormatDef[i].Alias)
{
for(j=i+1; textinFormatDef[j].Name; j++)
{
if(textinFormatDef[j].Read == textinFormatDef[i].Read)
{
ajFmtPrintAppS(&namestr, "<br>%s",
textinFormatDef[j].Name);
if(!textinFormatDef[j].Alias)
{
ajWarn("Input format '%s' same as '%s' but not alias",
textinFormatDef[j].Name,
textinFormatDef[i].Name);
}
}
}
ajFmtPrintF(outf, "|-\n");
ajFmtPrintF(outf,
"|%S||%B||%s\n",
namestr,
textinFormatDef[i].Try,
textinFormatDef[i].Desc);
}
}
ajFmtPrintF(outf, "|}\n\n");
ajStrDel(&namestr);
return;
}
/* @datasection [none] Miscellaneous ******************************************
**
** Text internals
**
** @nam2rule Textin Text input
**
******************************************************************************/
/* @section Miscellaneous *****************************************************
**
** Functions to initialise and clean up internals
**
** @fdata [none]
**
** @nam3rule Exit Clean up and exit
**
** @valrule * [void]
**
** @fcategory misc
**
******************************************************************************/
/* @func ajTextinExit *********************************************************
**
** Cleans up text data input internal memory
**
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextinExit(void)
{
/* Query processing regular expressions */
ajStrDel(&textinReadLine);
ajTableDel(&textDbMethods);
return;
}
/* @section Internals *********************************************************
**
** Functions to return internal values
**
** @fdata [none]
**
** @nam3rule Type Internals for text datatype
** @nam4rule Get Return a value
** @nam5rule Fields Known query fields for ajTextinRead
** @nam5rule Qlinks Known query link operators for ajTextinRead
**
** @valrule * [const char*] Internal value
**
** @fcategory misc
**
******************************************************************************/
/* @func ajTextinTypeGetFields ************************************************
**
** Returns the listof known field names for ajTextinRead
**
** @return [const char*] List of field names
**
** @release 6.4.0
** @@
******************************************************************************/
const char* ajTextinTypeGetFields(void)
{
return "id";
}
/* @func ajTextinTypeGetQlinks ************************************************
**
** Returns the listof known query link operators for ajTextinRead
**
** @return [const char*] List of field names
**
** @release 6.4.0
** @@
******************************************************************************/
const char* ajTextinTypeGetQlinks(void)
{
return "|";
}
/* @datasection [AjPTable] Internal call register table ***********************
**
** Functions to manage the internal call register table that links the
** ajaxdb library functions with code in the core AJAX library.
**
** @nam2rule Textaccess Functions to manage textdb call tables.
**
******************************************************************************/
/* @section Cast **************************************************************
**
** Return a reference to the call table
**
** @fdata [AjPTable] textdb functions call table
**
** @nam3rule Get Return a value
** @nam4rule Db Database access functions table
** @nam3rule Method Lookup an access method by name
** @nam4rule Test Return true if the access method exists
** @nam4rule MethodGet Return a method value
** @nam5rule Qlinks Return query link operators
** @nam5rule Scope Return scope (entry, query or all) for a named method
**
** @argrule Method method [const AjPStr] Method name
**
** @valrule *Db [AjPTable] Call table of function names and references
** @valrule *Qlinks [const char*] Query link operators
** @valrule *Scope [ajuint] Scope flags
** @valrule *Test [AjBool] True if found
**
** @fcategory cast
**
******************************************************************************/
/* @func ajTextaccessGetDb ****************************************************
**
** Returns the table in which text database access details are registered
**
** @return [AjPTable] Access functions hash table
**
** @release 6.4.0
** @@
******************************************************************************/
AjPTable ajTextaccessGetDb(void)
{
if(!textDbMethods)
textDbMethods = ajCallTableNew();
return textDbMethods;
}
/* @func ajTextaccessMethodGetQlinks ******************************************
**
** Tests for a named method for text file reading and returns the
** known query link operators
**
** @param [r] method [const AjPStr] Method required.
** @return [const char*] Known link operators
**
** @release 6.4.0
** @@
******************************************************************************/
const char* ajTextaccessMethodGetQlinks(const AjPStr method)
{
AjPTextAccess methoddata;
methoddata = ajCallTableGetS(textDbMethods, method);
if(!methoddata)
return NULL;
return methoddata->Qlink;
}
/* @func ajTextaccessMethodGetScope *******************************************
**
** Tests for a named method for text file reading and returns the scope
** (entry, query or all).
*
** @param [r] method [const AjPStr] Method required.
** @return [ajuint] Scope flags
**
** @release 6.4.0
** @@
******************************************************************************/
ajuint ajTextaccessMethodGetScope(const AjPStr method)
{
AjPTextAccess methoddata;
ajuint ret = 0;
methoddata = ajCallTableGetS(textDbMethods, method);
if(!methoddata)
return 0;
if(methoddata->Entry)
ret |= AJMETHOD_ENTRY;
if(methoddata->Query)
ret |= AJMETHOD_QUERY;
if(methoddata->All)
ret |= AJMETHOD_ALL;
return ret;
}
/* @func ajTextaccessMethodTest ***********************************************
** Tests for a named method for text reading.
**
** @param [r] method [const AjPStr] Method required.
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
AjBool ajTextaccessMethodTest(const AjPStr method)
{
if(ajCallTableGetS(textDbMethods, method))
return ajTrue;
return ajFalse;
}
/* @funcstatic textinQryRestore ***********************************************
**
** Restores an text input specification from an AjPQueryList node
**
** @param [w] textin [AjPTextin] Text input object
** @param [r] node [const AjPQueryList] Query list node
** @return [void]
**
** @release 6.4.0
******************************************************************************/
static void textinQryRestore(AjPTextin textin, const AjPQueryList node)
{
textin->Format = node->Format;
textin->Fpos = node->Fpos;
textin->Curpos = node->Fpos;
ajStrAssignS(&textin->Formatstr, node->Formatstr);
ajStrAssignS(&textin->QryFields, node->QryFields);
return;
}
/* @funcstatic textinQrySave **************************************************
**
** Saves an text input specification in an AjPQueryList node
**
** @param [w] node [AjPQueryList] Query list node
** @param [r] textin [const AjPTextin] Text input object
** @return [void]
**
** @release 6.4.0
******************************************************************************/
static void textinQrySave(AjPQueryList node, const AjPTextin textin)
{
node->Format = textin->Format;
node->Fpos = textin->Fpos;
ajStrAssignS(&node->Formatstr, textin->Formatstr);
ajStrAssignS(&node->QryFields, textin->QryFields);
return;
}
/* @funcstatic textinQryProcess ***********************************************
**
** Converts an text query into an open file.
**
** Tests for "format::" and sets this if it is found
**
** Then tests for "list:" or "@" and processes as a list file
** using textinListProcess which in turn invokes textinQryProcess
** until a valid query is found.
**
** Then tests for dbname:query and opens the file (at the correct position
** if the database definition defines it)
**
** If there is no database, looks for file:query and opens the file.
** In this case the file position is not known and text data reading
** will have to scan for the entry/entries we need.
**
** @param [u] textin [AjPTextin] text data input structure.
** @param [u] text [AjPText] text data to be read. The format will be replaced
** if defined in the query string.
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinQryProcess(AjPTextin textin, AjPText text)
{
AjBool ret = ajTrue;
AjPStr qrystr = NULL;
AjBool nontextmethod = ajFalse;
const AjPStr fmtstr = NULL;
AjPQuery qry;
qry = textin->Query;
/* pick up the original query string */
qrystr = ajStrNewS(textin->Qry);
ajDebug("++textinQryProcess '%S' \n", qrystr);
/* look for a format:: prefix */
fmtstr = ajQuerystrParseFormat(&qrystr, textin, textinformatFind);
ajDebug("textinQryProcess ... fmtstr '%S' '%S'\n", fmtstr, qrystr);
/* (seq/feat only) DO NOT look for a [range] suffix */
/* look for a list:: or @:: listfile of queries - process and return */
if(ajQuerystrParseListfile(&qrystr))
{
ajDebug("textinQryProcess ... listfile '%S'\n", qrystr);
ret = textinListProcess(textin, text, qrystr);
ajStrDel(&qrystr);
return ret;
}
/* try general text access methods (file, asis, text database access */
ajDebug("textinQryProcess ... no listfile '%S'\n", qrystr);
if(!ajQuerystrParseRead(&qrystr, textin, textinformatFind, &nontextmethod))
{
ajStrDel(&qrystr);
return ajFalse;
}
textinFormatSet(textin, text);
ajDebug("textinQryProcess ... read nontext: %B '%S'\n",
nontextmethod, qrystr);
ajStrDel(&qrystr);
if(nontextmethod)
{
ajDebug("textinQryProcess ... call method '%S'\n", qry->Method);
ajDebug("textinQryProcess ... textin format %d '%S'\n",
textin->Format, textin->Formatstr);
ajDebug("textinQryProcess ... query format '%S'\n",
qry->Formatstr);
/*
** skip this for text .... we already tried text access methods!
qry->Access = ajCallTableGetS(xxxDbMethods,qry->Method);
xxxaccess = qry->Access;
return (*xxxaccess->Access)(oboin);
*/ }
ajDebug("seqinUsaProcess text method '%S' success\n", qry->Method);
return ajTrue;
}
/* @datasection [AjPList] Query field list ************************************
**
** Query fields lists are handled internally. Only static functions
** should appear here
**
******************************************************************************/
/* @funcstatic textinListProcess **********************************************
**
** Processes a file of queries.
** This function is called by, and calls, textinQryProcess. There is
** a depth check to avoid infinite loops, for example where a list file
** refers to itself.
**
** This function produces a list (AjPList) of queries with all list references
** expanded into lists of queries.
**
** Because queries in a list can have their own format
** the prior settings are stored with each query in the list node so that they
** can be restored after.
**
** @param [u] textin [AjPTextin] text data input
** @param [u] text [AjPText] text data
** @param [r] listfile [const AjPStr] Name of list file.,
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinListProcess(AjPTextin textin, AjPText text,
const AjPStr listfile)
{
AjPList list = NULL;
AjPFile file = NULL;
AjPStr token = NULL;
AjPStr rest = NULL;
AjBool ret = ajFalse;
AjPQueryList node = NULL;
ajuint recnum = 0;
static ajint depth = 0;
static ajint MAXDEPTH = 16;
depth++;
ajDebug("++textListProcess %S depth %d\n",
listfile, depth);
if(depth > MAXDEPTH)
ajFatal("Query list too deep");
if(!textin->List)
textin->List = ajListNew();
list = ajListNew();
file = ajFileNewInNameS(listfile);
if(!file)
{
ajErr("Failed to open list file '%S'", listfile);
depth--;
return ret;
}
while(ajReadlineTrim(file, &textinReadLine))
{
++recnum;
textinListNoComment(&textinReadLine);
if(ajStrExtractWord(textinReadLine, &rest, &token))
{
if(ajStrGetLen(rest))
{
ajErr("Bad record %u in list file '%S'\n'%S'",
recnum, listfile, textinReadLine);
}
else if(ajStrGetLen(token))
{
ajDebug("++Add to list: '%S'\n", token);
AJNEW0(node);
ajStrAssignS(&node->Qry, token);
textinQrySave(node, textin);
ajListPushAppend(list, node);
}
}
}
ajFileClose(&file);
ajStrDel(&token);
ajStrDel(&rest);
ajDebug("Trace textin->List\n");
ajQuerylistTrace(textin->List);
ajDebug("Trace new list\n");
ajQuerylistTrace(list);
ajListPushlist(textin->List, &list);
ajDebug("Trace combined textin->List\n");
ajQuerylistTrace(textin->List);
/*
** now try the first item on the list
** this can descend recursively if it is also a list
** which is why we check the depth above
*/
if(ajListPop(textin->List, (void**) &node))
{
ajDebug("++pop first item '%S'\n", node->Qry);
ajTextinQryS(textin, node->Qry);
textinQryRestore(textin, node);
ajStrDel(&node->Qry);
ajStrDel(&node->Formatstr);
AJFREE(node);
ajDebug("descending with query '%S'\n", textin->Qry);
ret = textinQryProcess(textin, text);
}
depth--;
ajDebug("++textListProcess depth: %d returns: %B\n", depth, ret);
return ret;
}
/* @funcstatic textinListNoComment ********************************************
**
** Strips comments from a character string (a line from an ACD file).
** Comments are blank lines or any text following a "#" character.
**
** @param [u] text [AjPStr*] Line of text from input file.
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
static void textinListNoComment(AjPStr* text)
{
ajuint i;
char *cp;
i = ajStrGetLen(*text);
if(!i) /* empty string */
return;
MAJSTRGETUNIQUESTR(text);
cp = strchr(ajStrGetPtr(*text), '#');
if(cp)
{ /* comment found */
*cp = '\0';
ajStrSetValid(text);
}
return;
}
/* @funcstatic textinFormatSet ************************************************
**
** Sets the input format for text data using the text data input object's
** defined format
**
** @param [u] textin [AjPTextin] text term input.
** @param [u] text [AjPText] text term.
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinFormatSet(AjPTextin textin, AjPText text)
{
if(ajStrGetLen(textin->Formatstr))
{
ajDebug("... input format value '%S'\n", textin->Formatstr);
if(textinformatFind(textin->Formatstr, &textin->Format))
{
ajStrAssignS(&text->Formatstr, textin->Formatstr);
text->Format = textin->Format;
ajDebug("...format OK '%S' = %d\n", textin->Formatstr,
textin->Format);
}
else
ajDebug("...format unknown '%S'\n", textin->Formatstr);
return ajTrue;
}
else
ajDebug("...input format not set\n");
return ajFalse;
}
/* @datasection [AjPTextall] Text Input Stream ********************************
**
** Function is for manipulating text block input stream objects
**
** @nam2rule Textall Text input stream objects
**
******************************************************************************/
/* @section Text Input Constructors *******************************************
**
** All constructors return a new text input stream object by pointer. It
** is the responsibility of the user to first destroy any previous
** text input object. The target pointer does not need to be
** initialised to NULL, but it is good programming practice to do so
** anyway.
**
** @fdata [AjPTextall]
**
** @nam3rule New Constructor
**
** @valrule * [AjPTextall] Text input stream object
**
** @fcategory new
**
******************************************************************************/
/* @func ajTextallNew *********************************************************
**
** Creates a new text input stream object.
**
** @return [AjPTextall] New text input stream object.
**
** @release 6.4.0
** @@
******************************************************************************/
AjPTextall ajTextallNew(void)
{
AjPTextall pthis;
AJNEW0(pthis);
pthis->Textin = ajTextinNew();
pthis->Text = ajTextNew();
return pthis;
}
/* ==================================================================== */
/* ========================== destructors ============================= */
/* ==================================================================== */
/* @section Text Input Stream Destructors *************************************
**
** Destruction destroys all internal data structures and frees the
** memory allocated for the text input stream object.
**
** @fdata [AjPTextall]
**
** @nam3rule Del Destructor
**
** @argrule Del pthis [AjPTextall*] Text input stream
**
** @valrule * [void]
**
** @fcategory delete
**
******************************************************************************/
/* @func ajTextallDel *********************************************************
**
** Deletes a text input stream object.
**
** @param [d] pthis [AjPTextall*] Text input stream
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextallDel(AjPTextall* pthis)
{
AjPTextall thys;
if(!pthis)
return;
thys = *pthis;
if(!thys)
return;
ajTextinDel(&thys->Textin);
if(!thys->Returned)
ajTextDel(&thys->Text);
AJFREE(*pthis);
return;
}
/* ==================================================================== */
/* =========================== Modifiers ============================== */
/* ==================================================================== */
/* @section Text input stream modifiers ***************************************
**
** These functions use the contents of a text input stream object and
** update them.
**
** @fdata [AjPTextall]
**
** @nam3rule Clear Clear all values
**
** @argrule * thys [AjPTextall] Text input stream object
**
** @valrule * [void]
**
** @fcategory modify
**
******************************************************************************/
/* @func ajTextallClear *******************************************************
**
** Clears a text input stream object back to "as new" condition, except
** for the query list which must be preserved.
**
** @param [w] thys [AjPTextall] Text input stream
** @return [void]
**
** @release 6.4.0
** @@
******************************************************************************/
void ajTextallClear(AjPTextall thys)
{
ajDebug("ajTextallClear called\n");
if(!thys)
return;
ajTextinClear(thys->Textin);
ajTextClear(thys->Text);
thys->Returned = ajFalse;
return;
}
/* @section Text input ********************************************************
**
** These functions use a text input stream object to read text
**
** @fdata [AjPTextall]
**
** @nam3rule Next Read next text block
**
** @argrule * thys [AjPTextall] Text input stream object
** @argrule * Ptext [AjPText*] Text object
**
** @valrule * [AjBool] True on success
**
** @fcategory input
**
******************************************************************************/
/* @func ajTextallNext ********************************************************
**
** Parse a text query into format, access, file and entry
**
** Split at delimiters. Check for the first part as a valid format
** Check for the remaining first part as a database name or as a file
** that can be opened.
** Anything left is an entryname spec.
**
** Return the results in the AjPText object but leave the file open for
** future calls.
**
** @param [w] thys [AjPTextall] Text input stream
** @param [u] Ptext [AjPText*] Text block returned
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
AjBool ajTextallNext(AjPTextall thys, AjPText *Ptext)
{
if(!thys->Count)
{
thys->Count = 1;
thys->Totterms++;
*Ptext = thys->Text;
thys->Returned = ajTrue;
return ajTrue;
}
if(ajTextinRead(thys->Textin, thys->Text))
{
thys->Count++;
thys->Totterms++;
*Ptext = thys->Text;
thys->Returned = ajTrue;
ajDebug("ajTextallNext success\n");
return ajTrue;
}
*Ptext = NULL;
ajDebug("ajTextallNext failed\n");
ajTextallClear(thys);
return ajFalse;
}
/* @datasection [none] Input formats ******************************************
**
** Input formats internals
**
** @nam2rule Textinformat Text data input format specific
**
******************************************************************************/
/* @section cast **************************************************************
**
** Values for input formats
**
** @fdata [none]
**
** @nam3rule Find Return index to named format
** @nam3rule Term Test format EDAM term
** @nam3rule Test Test format value
**
** @argrule Find format [const AjPStr] Format name
** @argrule Term term [const AjPStr] Format EDAM term
** @argrule Test format [const AjPStr] Format name
** @argrule Find iformat [ajuint*] Index matching format name
**
** @valrule * [AjBool] True if found
**
** @fcategory cast
**
******************************************************************************/
/* @funcstatic textinformatFind ***********************************************
**
** Looks for the specified format(s) in the internal definitions and
** returns the index.
**
** Sets iformat as the recognised format, and returns ajTrue.
**
** @param [r] format [const AjPStr] Format required.
** @param [w] iformat [ajint*] Index
** @return [AjBool] ajTrue on success.
**
** @release 6.4.0
** @@
******************************************************************************/
static AjBool textinformatFind(const AjPStr format, ajint* iformat)
{
AjPStr tmpformat = NULL;
ajuint i = 0;
ajDebug("textinformatFind '%S'\n", format);
if(!ajStrGetLen(format))
return ajFalse;
ajStrAssignS(&tmpformat, format);
ajStrFmtLower(&tmpformat);
for(i=0; textinFormatDef[i].Name; i++)
{
ajDebug("test %d '%s' '%s' '%s'\n",
i, textinFormatDef[i].Name,
textinFormatDef[i].Obo,
textinFormatDef[i].Desc);
if(ajStrMatchC(tmpformat, textinFormatDef[i].Name) ||
ajStrMatchC(format, textinFormatDef[i].Obo))
{
*iformat = i;
ajStrDel(&tmpformat);
ajDebug("found '%s' at %d\n", textinFormatDef[i].Name, i);
return ajTrue;
}
}
ajStrDel(&tmpformat);
return ajFalse;
}
/* @func ajTextinformatTerm ***************************************************
**
** tests whether a text input format term is known
**
** @param [r] term [const AjPStr] Format term EDAM ID
** @return [AjBool] ajTrue if term was accepted
**
** @release 6.4.0
** @@
******************************************************************************/
AjBool ajTextinformatTerm(const AjPStr term)
{
ajuint i;
for(i=0; textinFormatDef[i].Name; i++)
if(ajStrMatchC(term, textinFormatDef[i].Obo))
return ajTrue;
return ajFalse;
}
/* @func ajTextinformatTest ***************************************************
**
** tests whether a named text input format is known
**
** @param [r] format [const AjPStr] Format
** @return [AjBool] ajTrue if format was accepted
**
** @release 6.4.0
** @@
******************************************************************************/
AjBool ajTextinformatTest(const AjPStr format)
{
ajuint i;
for(i=0; textinFormatDef[i].Name; i++)
{
if(ajStrMatchCaseC(format, textinFormatDef[i].Name))
return ajTrue;
if(ajStrMatchC(format, textinFormatDef[i].Obo))
return ajTrue;
}
return ajFalse;
}
| 25.136754 | 79 | 0.544117 |
2555b60c1687342c2ee5c85c6cfd25708e79259a | 1,634 | h | C | src/platforms/windows/windowsservicemanager.h | vvalceanu/mozilla-vpn-client | bd682c5b7b12bb49e1b1c555f1ca973484b8ce5a | [
"MIT"
] | 222 | 2020-11-21T05:55:56.000Z | 2022-03-29T16:20:03.000Z | src/platforms/windows/windowsservicemanager.h | vvalceanu/mozilla-vpn-client | bd682c5b7b12bb49e1b1c555f1ca973484b8ce5a | [
"MIT"
] | 1,893 | 2020-11-16T19:31:50.000Z | 2022-03-31T21:51:31.000Z | src/platforms/windows/windowsservicemanager.h | vvalceanu/mozilla-vpn-client | bd682c5b7b12bb49e1b1c555f1ca973484b8ce5a | [
"MIT"
] | 68 | 2020-11-19T19:08:16.000Z | 2022-03-25T20:07:59.000Z | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef WINDOWSSERVICEMANAGER
#define WINDOWSSERVICEMANAGER
#include "Windows.h"
#include "Winsvc.h"
#include <QTimer>
#include <QObject>
/**
* @brief The WindowsServiceManager provides controll over the MozillaVPNBroker
* service via SCM
*/
class WindowsServiceManager : public QObject {
Q_OBJECT
Q_DISABLE_COPY_MOVE(WindowsServiceManager)
public:
WindowsServiceManager(LPCWSTR serviceName);
~WindowsServiceManager();
// true if the Service is running
bool isRunning() { return getStatus().dwCurrentState == SERVICE_RUNNING; };
// Starts the service if execute rights are present
// Starts to poll for serviceStarted
bool startService();
// Stops the service if execute rights are present.
// Starts to poll for serviceStopped
bool stopService();
signals:
// Gets Emitted after the Service moved From SERVICE_START_PENDING to
// SERVICE_RUNNING
void serviceStarted();
void serviceStopped();
private:
// Returns the State of the Process:
// See
// SERVICE_STOPPED,SERVICE_STOP_PENDING,SERVICE_START_PENDING,SERVICE_RUNNING
SERVICE_STATUS_PROCESS getStatus();
bool m_has_access = false;
LPWSTR m_serviceName;
SC_HANDLE m_serviceManager;
SC_HANDLE m_service; // Service handle with r/w priv.
DWORD m_state_target;
int m_currentWaitTime;
int m_maxWaitTime;
QTimer m_timer;
bool startPolling(DWORD goal_state, int maxS);
};
#endif // WINDOWSSERVICEMANAGER
| 27.233333 | 79 | 0.755202 |
252d8aa81e16fffae9fb843fa281292e0d724737 | 5,973 | h | C | Algorithm/BinaryTree/BinarySearchTree.h | tthhee/xiangyu | 7819b52e254ef5b72f251ae49c28b1acf78bbff8 | [
"BSD-3-Clause"
] | null | null | null | Algorithm/BinaryTree/BinarySearchTree.h | tthhee/xiangyu | 7819b52e254ef5b72f251ae49c28b1acf78bbff8 | [
"BSD-3-Clause"
] | null | null | null | Algorithm/BinaryTree/BinarySearchTree.h | tthhee/xiangyu | 7819b52e254ef5b72f251ae49c28b1acf78bbff8 | [
"BSD-3-Clause"
] | null | null | null | #ifndef _BINARYSEARCHTREE_H_
#define _BINARYSEARCHTREE_H_
#include <iostream>
using namespace std;
//typedef int Comparable;
template <typename Comparable>
class BinarySearchTree
{
public:
BinarySearchTree();
BinarySearchTree(const BinarySearchTree & rhs); //拷贝构造函数
BinarySearchTree(const BinarySearchTree && rhs); //移动构造函数
~BinarySearchTree();
const Comparable & findMin() const;
const Comparable & findMax() const;
bool contains(const Comparable & X) const;
bool isEmpty() const;
void makeEmpty();
void insert(const Comparable & X);
void insert(Comparable && X); //?????????插入右值
void remove(const Comparable & X);
void printtree();
BinarySearchTree & operator=(const BinarySearchTree & rhs); //拷贝赋值运算符
BinarySearchTree & operator=(BinarySearchTree && rhs); //移动赋值运算符
private:
struct BinaryNode
{
Comparable element;
BinaryNode* left;
BinaryNode* right;
BinaryNode(const Comparable & c, BinaryNode* l, BinaryNode* r)
: element(c), left(l), right(r){}
BinaryNode(Comparable && c, BinaryNode* l, BinaryNode* r)
: element(std::move(c)), left(l), right(r){}
};
BinaryNode* root;
void insert(const Comparable & X, BinaryNode* & t);
void insert(Comparable && X, BinaryNode* & t);
void remove(const Comparable & X, BinaryNode* & t);
BinaryNode* findMin(BinaryNode* & t) const;
BinaryNode* findMax(BinaryNode* & t) const;
bool contains(const Comparable & X, BinaryNode* t) const;
void makeEmpty(BinaryNode* & t);
void printTree(BinaryNode* & t, ostream & out) const;
BinaryNode* clone(BinaryNode* & t) const;
BinaryNode* clone(BinaryNode* && t) const;
};
/*************************private methods***********************************/
/**
* if X in the tree, return true, else return false
*/
template <typename Comparable>
bool BinarySearchTree<Comparable>::contains(const Comparable & X, BinaryNode* t) const
{
if(t == nullptr)
{
return false;
}
else if(X < t->element)
{
contains(X, t->left);
}
else if(X > t->element)
{
contains(X, t->right);
}
else
{
return true;
}
}
/**
* find the minimum element in the tree
* 为什么函数名前面要加一个 typename ???
* 前面加一个typename 意在说明 BinarySearchTree<Comparable>::BinaryNode 是一个类型,具体请见C++Primer P593
*/
template <typename Comparable>
typename BinarySearchTree<Comparable>::BinaryNode* BinarySearchTree<Comparable>::findMin(BinaryNode* & t) const
{
if(t == nullptr)
{
return nullptr;
}
else if(t->left == nullptr)
{
return t;
}
else
{
return findMin(t->left);
}
}
/**
* find the maxmum element in the tree
*/
template<typename Comparable>
typename BinarySearchTree<Comparable>::BinaryNode* BinarySearchTree<Comparable>::findMax(BinaryNode* & t) const
{
if(t == nullptr)
{
return nullptr;
}
while(t->right != nullptr)
{
t = t->right;
}
return t;
}
/*
* insert X into the tree, if X already exits in the tree t, do nothing, else do it!
*/
template<typename Comparable>
void BinarySearchTree<Comparable>::insert(const Comparable & X, BinaryNode * & t)
{
// if(root == nullptr)
// {
// root = new BinaryNode(X, nullptr, nullptr);
// }
if(t == nullptr)
{
t = new BinaryNode(X, nullptr, nullptr);
}
else if(X > t->element)
{
insert(X, t->right);
}
else if(X < t->element)
{
insert(X, t->left);
}
}
/*
* insert X into the tree by move, if X already exits in the tree t, do nothing, else do it!
*/
template<typename Comparable>
void BinarySearchTree<Comparable>::insert(Comparable && X, BinaryNode * & t)
{
if(t == nullptr)
{
t = new BinaryNode(std::move(X), nullptr, nullptr);
}
else if(X > t->element)
{
insert(std::move(X), t->right);
}
else if(X < t->element)
{
insert(std::move(X), t->left);
}
}
/**
* remove X from the tree t
*/
template <typename Comparable>
void BinarySearchTree<Comparable>::remove(const Comparable& X, BinaryNode* & t)
{
if(t == nullptr)
return;
else if(X < t->element)
{
remove(X, t->left);
}
else if(X > t->element)
{
remove(X, t->right);
}
else if(t->left != nullptr && t->right != nullptr)
{
BinaryNode* p=findMin(t->right);
t->element = p->element;
remove(p->element, t->right);
}
else
{
BinaryNode* old_node = t;
t = (t->left != nullptr)? t->left : t->right;
delete old_node;
}
// else if(t->left != nullptr)
// {
// t->element = t->left->element;
// delete t->left;
// }
// else if(t->right!= nullptr)
// {
// t->element = t->right->element;
// delete t->right;
// }
}
/**
* makeEmpty()
* make a tree node an empty node
*/
template <typename Comparable>
void BinarySearchTree<Comparable>::makeEmpty(BinaryNode* & t)
{
if(t != nullptr)
{
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
else
return;
}
/**
* clone
*/
template<typename Comparable>
typename BinarySearchTree<Comparable>::BinaryNode* BinarySearchTree<Comparable>::clone(BinaryNode* & t) const
{
if(t == nullptr)
return nullptr;
else
return new BinaryNode(t->element, clone(t->left), clone(t->right));
}
/**
* clone by move
*/
template<typename Comparable>
typename BinarySearchTree<Comparable>::BinaryNode* BinarySearchTree<Comparable>::clone(BinaryNode* && t) const
{
if(t == nullptr)
return nullptr;
else
return new BinaryNode(std::move(t->element), clone(t->left), clone(t->right));
}
/**
* 中序遍历
*/
template<typename Comparable>
void BinarySearchTree<Comparable>::printTree(BinaryNode* & t, ostream & out) const
{
if(t!=nullptr)
{
printTree(t->left, out);
out << t->element;
printTree(t->right, out);
}
}
/**
* 前序遍历
*/
// template<typename Comparable>
// void BinarySearchTree<Comparable>::printTree(BinaryNode* & t, ostream & out) const
// {
// if(t!=nullptr)
// {
// out << t->element;
// printTree(t->left, out);
// printTree(t->right, out);
// }
// }
/**
* 后序遍历
*/
// template<typename Comparable>
// void BinarySearchTree<Comparable>::printTree(BinaryNode* & t, ostream & out) const
// {
// if(t!=nullptr)
// {
// printTree(t->left, out);
// printTree(t->right, out);
// out << t->element;
// }
// }
#endif | 21.408602 | 111 | 0.656789 |
f96309cf382fab4bc5a60e8f3df3965c1a9c11b6 | 1,160 | c | C | main/ui/ui.c | thatoddmailbox/phone-fw | 2e8c9e2788992270ced302cdb3df79b28a3b3c4e | [
"MIT"
] | null | null | null | main/ui/ui.c | thatoddmailbox/phone-fw | 2e8c9e2788992270ced302cdb3df79b28a3b3c4e | [
"MIT"
] | null | null | null | main/ui/ui.c | thatoddmailbox/phone-fw | 2e8c9e2788992270ced302cdb3df79b28a3b3c4e | [
"MIT"
] | null | null | null | #include "ui/ui.h"
const char * UI_TAG = "ui";
ui_screen_t * ui_current_screen = NULL;
QueueHandle_t ui_event_queue;
bool ui_is_dirty = false;
void ui_init() {
ui_event_queue = xQueueCreate(UI_EVENT_QUEUE_SIZE, sizeof(ui_event_t));
}
void ui_set_screen(ui_screen_t * screen) {
if (ui_current_screen && ui_current_screen->deinit) {
ui_current_screen->deinit(ui_current_screen);
}
ui_current_screen = screen;
ui_is_dirty = true;
}
void ui_push_event(ui_event_t event) {
if (xQueueSendToBack(ui_event_queue, &event, 0) != pdTRUE) {
ESP_LOGW(UI_TAG, "ui_push_event: event dropped, couldn't add to queue!");
}
}
void ui_step() {
// update
ui_event_t event_to_process;
if (xQueueReceive(ui_event_queue, &event_to_process, 0)) {
if (ui_current_screen) {
ui_screen_process_event(ui_current_screen, &event_to_process);
}
}
if (ui_current_screen) {
ui_screen_update(ui_current_screen);
}
// draw
if (ui_current_screen) {
if (ui_is_dirty || ui_current_screen->force_redraw || ui_status_dirty()) {
ui_screen_draw(ui_current_screen);
graphics_flip();
ui_current_screen->force_redraw = false;
ui_is_dirty = false;
}
}
} | 22.745098 | 76 | 0.737931 |
bf9f0b9ab72cfe6b97e80c6b685658db328c74a8 | 1,795 | c | C | src/kernel/video.c | devinus/torix | d2dc49530838c6ba48027b2f6b9c167d7d25915e | [
"MIT"
] | 3 | 2015-12-07T10:53:20.000Z | 2019-08-28T15:49:16.000Z | src/kernel/video.c | devinus/torix | d2dc49530838c6ba48027b2f6b9c167d7d25915e | [
"MIT"
] | null | null | null | src/kernel/video.c | devinus/torix | d2dc49530838c6ba48027b2f6b9c167d7d25915e | [
"MIT"
] | null | null | null | /*
* ToriX - TORres Interactive eXecution
* Copyright (c) 2008 Devin Torres
* Licensed under the MIT license.
*/
#include <torix/kernel.h>
#include <torix/video.h>
#include <string.h>
static unsigned short int *videomem = (unsigned short *)0xB8000;
static unsigned short int attrib = 0x0700;
static unsigned short int pos = 0;
static unsigned short int off = 160;
void set_attribute(const unsigned short int att)
{
attrib = att;
}
void move_cursor(const unsigned short int row, const unsigned short int col)
{
unsigned short int position = (row * 80) + col;
outb(0x3D4, 0x0F);
outb(0x3D5, position & 0xFF);
outb(0x3D4, 0x0E);
outb(0x3D5, (position >> 8) & 0xFF);
}
void clear()
{
unsigned short int i = 0;
while (i < 2000) {
videomem[i] = ' ' | attrib;
++i;
}
pos = off = 0;
move_cursor(0, 0);
}
void write(const char* msg)
{
unsigned short int len = strlen(msg);
while (*msg) {
/*
* If the number of characters on the current line goes over 80
* characters, then wrap around the screen.
*/
if (pos >= 80) {
pos = 0;
off += 80;
}
/*
* If the text goes beyond 25 lines, then copy the first 24 lines one
* line up, and finally fill the 25th line with spaces to clear it for
* something else to be written over.
*/
if (off >= 2000) {
unsigned short int i = 0;
while (i < 1920) {
videomem[i] = videomem[i + 80];
++i;
}
while (i < 2000) {
videomem[i] = ' ' | attrib;
++i;
}
pos = 0;
off = (80 * 24);
}
switch (*msg) {
case '\n':
pos = 0;
off += 80;
++msg;
len = strlen(msg);
break;
case '\t':
write(" ");
len += 7;
++msg;
break;
default:
videomem[off + pos] = *msg | attrib;
++pos;
++msg;
}
}
move_cursor(off / 80, len);
}
| 17.095238 | 76 | 0.591086 |
c7716879b6a1bbc6f55e6325a5bc00266202edcd | 2,208 | h | C | include/Renderer/FE_MeshRenderData.h | antsouchlos/OxygenEngine | 11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48 | [
"MIT"
] | null | null | null | include/Renderer/FE_MeshRenderData.h | antsouchlos/OxygenEngine | 11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48 | [
"MIT"
] | null | null | null | include/Renderer/FE_MeshRenderData.h | antsouchlos/OxygenEngine | 11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48 | [
"MIT"
] | null | null | null | #ifndef FE_MESHRENDERDATA_H
#define FE_MESHRENDERDATA_H
#include "CSL_Interpreter.h"
#include "FE_GPU_API.h"
#include "FMath.h"
#define Shader(src) "#version 150 \n" #src
struct FE_MeshLightData{
FE_Vec4 position;
FE_Vec4 rotation;
FE_Vec4 color;
float range;
float value;
float fov;
float this_type;
/// GAMO TON COMPILER MOU MESA
/// DEN DOULEUEI AYTOMATA TO == OUTE TO =
bool compare(const FE_MeshLightData&);
void assignValue(const FE_MeshLightData&);
};
struct FE_MeshVertexData{
vector<GLfloat> vertices;
GLuint offset;
vector<GLuint> index_buffer;
GLuint ib_offset;
vector<GLfloat> light_data;
GLuint light_offset;
};
class FE_MeshRenderData
{
public:
FE_MeshRenderData();
~FE_MeshRenderData();
void init(FE_GPU_Thread*, FE_MeshVertexData, FE_Mat4);
void destroy(FE_GPU_Thread*);
void getVertices(FE_Mesh*, string);
void getObjectData(FE_Scene*, FE_Mesh*);
void update(FE_GPU_Thread*);
void draw(FE_GPU_CommandQueue*);
void drawDummy(FE_GPU_Thread*);
string name;
string mat;
string gpu_names;
FE_Mat4 model_mat;
size_t ib_size;
FE_MeshVertexData obj_data;
size_t num_polygons;
size_t vertices_size = 0;
bool created = false;
GLuint voffset;
GLuint vstart;
GLuint vend;
private:
map<string, FE_MeshLightData> light_data;
};
class FE_MaterialData{
public:
FE_MaterialData();
~FE_MaterialData();
void init(FE_GPU_Thread*, FE_Material);
void destroy(FE_GPU_Thread*);
void update(FE_GPU_Thread*);
void draw(FE_GPU_CommandQueue*);
void updateVertices(FE_GPU_Thread*);
void chooseProgram(FE_GPU_CommandQueue*);
void draw(FE_GPU_Thread*);
size_t computeVBOlength(size_t);
size_t computeIBlength(size_t);
string name;
string gpu_names;
vector<FE_MeshRenderData> meshes;
size_t previous_mesh_size = 0;
FE_Material updated_mat;
bool created = false;
private:
FE_Material old_mat;
//vector<string> mdata;
//GLuint ubo_binding;
};
#endif // FE_MESHRENDERDATA_H
| 22.30303 | 62 | 0.671649 |
b54c169b428103a34a7ed6e0db515f48932ff48f | 1,956 | h | C | Parallel_RVD/Polygon.h | stormHan/Parallel_RVD | 72cbc79848255ab3d4aa54cc31daecbba26e00ed | [
"MIT"
] | null | null | null | Parallel_RVD/Polygon.h | stormHan/Parallel_RVD | 72cbc79848255ab3d4aa54cc31daecbba26e00ed | [
"MIT"
] | null | null | null | Parallel_RVD/Polygon.h | stormHan/Parallel_RVD | 72cbc79848255ab3d4aa54cc31daecbba26e00ed | [
"MIT"
] | null | null | null | /*
a new data stucture to store the information
about the computation of RVD.
we compute the intersection of a polygon and a seed(cell)
*/
#ifndef H_POLYGON_H
#define H_POLYGON_H
#include <vector>
#include "RVD_Vertex.h"
#include "Common.h"
#include "Mesh.h"
#include "Points.h"
namespace P_RVD
{
class Vertex;
class Polygon
{
public:
Polygon(){}
Polygon(Polygon& _p)
{
m_vertex = _p.m_vertex;
}
/*
get the number of vertex in this Polygon
*/
t_index getVertex_nb() const
{
return (t_index)m_vertex.size();
}
/*
get a Vertex in m_vertex by indice.
*/
const Vertex& getVertex(t_index _t) const
{
if (_t >= getVertex_nb())
{
printf("wrong index to get the vertex : %d", _t);
exit(0);
}
return m_vertex[_t];
}
/*
get the index of the next Vertex of this Vertex
if this Vertex is the last one of this Polygon
return 0 ( the first one )
*/
t_index getNextVertexIndex(t_index _t)
{
if (_t >= getVertex_nb())
{
printf("wrong index to get the next vertex index : %d", _t);
exit(0);
}
return (_t == getVertex_nb() - 1) ? 0 : (_t + 1);
}
/*
Add a Vertex to this Polygon.
return the address of the stored Vertex.
*/
Vertex* add_vertex(const Vertex& v) {
m_vertex.push_back(v);
return &*(m_vertex.rbegin());
}
/*
clear the Polygon to empty
*/
void clear()
{
m_vertex.resize(0);
}
/*
clear the Polygon to a appointed size
*/
void clear(t_index _size)
{
m_vertex.resize(_size);
}
void initialize_from_mesh_facet(
const Mesh* _mesh, t_index _facetIdx
);
/*
be clipped by a bisector
points : the seeds set.
i : the core seed
j : the seed around the core seed i.
*/
void clip_by_plane(Polygon& _target, Points _points, t_index _i, t_index _j);
/*
print the polygon
*/
void show_polygon();
protected:
std::vector<Vertex> m_vertex;
};
}
#endif /* H_POLYGON_H */ | 17.464286 | 79 | 0.633947 |
688b91c932c645c0d4ac9b3d9923d9db04dbbc65 | 1,596 | h | C | System/Library/PrivateFrameworks/Celestial.framework/BWOverCaptureAttachedMediaSplitNode.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 11 | 2019-11-06T04:48:48.000Z | 2022-02-09T17:48:15.000Z | System/Library/PrivateFrameworks/Celestial.framework/BWOverCaptureAttachedMediaSplitNode.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 1 | 2020-04-16T01:41:56.000Z | 2020-04-16T04:32:00.000Z | System/Library/PrivateFrameworks/Celestial.framework/BWOverCaptureAttachedMediaSplitNode.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 3 | 2019-12-22T20:17:53.000Z | 2021-01-25T09:47:49.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:39:28 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/Celestial.framework/Celestial
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <Celestial/Celestial-Structs.h>
#import <Celestial/BWAttachedMediaSplitNode.h>
@class BWNodeOutput;
@interface BWOverCaptureAttachedMediaSplitNode : BWAttachedMediaSplitNode {
BWNodeOutput* _primaryFrameOutput;
BWNodeOutput* _synchronizedSlaveFrameOutput;
}
@property (nonatomic,readonly) BWNodeOutput * primaryFrameOutput; //@synthesize primaryFrameOutput=_primaryFrameOutput - In the implementation block
@property (nonatomic,readonly) BWNodeOutput * synchronizedSlaveFrameOutput; //@synthesize synchronizedSlaveFrameOutput=_synchronizedSlaveFrameOutput - In the implementation block
+(void)initialize;
-(void)dealloc;
-(void)renderSampleBuffer:(opaqueCMSampleBufferRef)arg1 forInput:(id)arg2 ;
-(void)_setupAttachedMediaConfigurationForInput:(id)arg1 attachedMediaKey:(id)arg2 ;
-(void)_setupAttachedMediaConfigurationForOutput:(id)arg1 attachedMediaKey:(id)arg2 ;
-(void)_updateSynchronizedSlaveFrameEnabledWithSampleBuffer:(opaqueCMSampleBufferRef)arg1 ;
-(void)handleIrisReferenceMovieRequest:(id)arg1 forInput:(id)arg2 ;
-(id)initWithBackPressureExtraRetainBufferCount:(int)arg1 videoStitchingEnabled:(BOOL)arg2 ;
-(BWNodeOutput *)primaryFrameOutput;
-(BWNodeOutput *)synchronizedSlaveFrameOutput;
@end
| 45.6 | 191 | 0.809524 |
68cd85ba2ee9e79d2e30c32417b534787cbd787a | 3,625 | c | C | machine/qemu/sources/u-boot/lib/efi_loader/efi_load_options.c | muddessir/framework | 5b802b2dd7ec9778794b078e748dd1f989547265 | [
"MIT"
] | 1 | 2021-11-21T19:56:29.000Z | 2021-11-21T19:56:29.000Z | machine/qemu/sources/u-boot/lib/efi_loader/efi_load_options.c | muddessir/framework | 5b802b2dd7ec9778794b078e748dd1f989547265 | [
"MIT"
] | null | null | null | machine/qemu/sources/u-boot/lib/efi_loader/efi_load_options.c | muddessir/framework | 5b802b2dd7ec9778794b078e748dd1f989547265 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: GPL-2.0+
/*
* EFI boot manager
*
* Copyright (c) 2018 AKASHI Takahiro, et.al.
*/
#define LOG_CATEGORY LOGC_EFI
#include <common.h>
#include <charset.h>
#include <log.h>
#include <malloc.h>
#include <efi_loader.h>
#include <asm/unaligned.h>
/**
* efi_set_load_options() - set the load options of a loaded image
*
* @handle: the image handle
* @load_options_size: size of load options
* @load_options: pointer to load options
* Return: status code
*/
efi_status_t efi_set_load_options(efi_handle_t handle,
efi_uintn_t load_options_size,
void *load_options)
{
struct efi_loaded_image *loaded_image_info;
efi_status_t ret;
ret = EFI_CALL(systab.boottime->open_protocol(
handle,
&efi_guid_loaded_image,
(void **)&loaded_image_info,
efi_root, NULL,
EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL));
if (ret != EFI_SUCCESS)
return EFI_INVALID_PARAMETER;
loaded_image_info->load_options = load_options;
loaded_image_info->load_options_size = load_options_size;
return EFI_CALL(systab.boottime->close_protocol(handle,
&efi_guid_loaded_image,
efi_root, NULL));
}
/**
* efi_deserialize_load_option() - parse serialized data
*
* Parse serialized data describing a load option and transform it to the
* efi_load_option structure.
*
* @lo: pointer to target
* @data: serialized data
* @size: size of the load option, on return size of the optional data
* Return: status code
*/
efi_status_t efi_deserialize_load_option(struct efi_load_option *lo, u8 *data,
efi_uintn_t *size)
{
efi_uintn_t len;
len = sizeof(u32);
if (*size < len + 2 * sizeof(u16))
return EFI_INVALID_PARAMETER;
lo->attributes = get_unaligned_le32(data);
data += len;
*size -= len;
len = sizeof(u16);
lo->file_path_length = get_unaligned_le16(data);
data += len;
*size -= len;
lo->label = (u16 *)data;
len = u16_strnlen(lo->label, *size / sizeof(u16) - 1);
if (lo->label[len])
return EFI_INVALID_PARAMETER;
len = (len + 1) * sizeof(u16);
if (*size < len)
return EFI_INVALID_PARAMETER;
data += len;
*size -= len;
len = lo->file_path_length;
if (*size < len)
return EFI_INVALID_PARAMETER;
lo->file_path = (struct efi_device_path *)data;
if (efi_dp_check_length(lo->file_path, len) < 0)
return EFI_INVALID_PARAMETER;
data += len;
*size -= len;
lo->optional_data = data;
return EFI_SUCCESS;
}
/**
* efi_serialize_load_option() - serialize load option
*
* Serialize efi_load_option structure into byte stream for BootXXXX.
*
* @data: buffer for serialized data
* @lo: load option
* Return: size of allocated buffer
*/
unsigned long efi_serialize_load_option(struct efi_load_option *lo, u8 **data)
{
unsigned long label_len;
unsigned long size;
u8 *p;
label_len = (u16_strlen(lo->label) + 1) * sizeof(u16);
/* total size */
size = sizeof(lo->attributes);
size += sizeof(lo->file_path_length);
size += label_len;
size += lo->file_path_length;
if (lo->optional_data)
size += (utf8_utf16_strlen((const char *)lo->optional_data)
+ 1) * sizeof(u16);
p = malloc(size);
if (!p)
return 0;
/* copy data */
*data = p;
memcpy(p, &lo->attributes, sizeof(lo->attributes));
p += sizeof(lo->attributes);
memcpy(p, &lo->file_path_length, sizeof(lo->file_path_length));
p += sizeof(lo->file_path_length);
memcpy(p, lo->label, label_len);
p += label_len;
memcpy(p, lo->file_path, lo->file_path_length);
p += lo->file_path_length;
if (lo->optional_data) {
utf8_utf16_strcpy((u16 **)&p, (const char *)lo->optional_data);
p += sizeof(u16); /* size of trailing \0 */
}
return size;
}
| 24.166667 | 78 | 0.697103 |
d53a3535481bfe393d3e5bf4c291688671dabcec | 845 | h | C | src/tibb/src/TiStreamObject.h | ssaracut/titanium_mobile_blackberry | 952a8100086dcc625584e33abc2dc03340cbb219 | [
"Apache-2.0"
] | 3 | 2015-03-07T15:41:18.000Z | 2015-11-05T05:07:45.000Z | src/tibb/src/TiStreamObject.h | ssaracut/titanium_mobile_blackberry | 952a8100086dcc625584e33abc2dc03340cbb219 | [
"Apache-2.0"
] | 1 | 2015-04-12T11:50:33.000Z | 2015-04-12T21:13:19.000Z | src/tibb/src/TiStreamObject.h | ssaracut/titanium_mobile_blackberry | 952a8100086dcc625584e33abc2dc03340cbb219 | [
"Apache-2.0"
] | 5 | 2015-01-13T17:14:41.000Z | 2015-05-25T16:54:26.000Z | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#ifndef TISTREAMOBJECT_H_
#define TISTREAMOBJECT_H_
#include "TiProxy.h"
/*
* TiStreamObject
*
* Stream module containing stream utility methods.
*/
class TiStreamObject : public TiProxy
{
public:
static void addObjectToParent(TiObject* parent);
protected:
virtual ~TiStreamObject();
virtual void onCreateStaticMembers();
private:
TiStreamObject();
TiStreamObject(const TiStreamObject&);
TiStreamObject& operator=(const TiStreamObject&);
static Handle<Value> _createStream(void* userContext, TiObject* caller, const Arguments& args);
};
#endif /* TISTREAMOBJECT_H_ */
| 23.472222 | 99 | 0.747929 |
84b1b332a0853a4d03fcdf25e03eca6d51442578 | 218 | h | C | Exchange/Classes/ViewModels/EXTradeViewModel.h | Modool/Exchange | b2d0e1f070a445f402bb107ff6558a22c57e410c | [
"MIT"
] | 2 | 2018-06-08T10:01:12.000Z | 2018-10-26T10:21:52.000Z | Exchange/Classes/ViewModels/EXTradeViewModel.h | Modool/Exchange | b2d0e1f070a445f402bb107ff6558a22c57e410c | [
"MIT"
] | null | null | null | Exchange/Classes/ViewModels/EXTradeViewModel.h | Modool/Exchange | b2d0e1f070a445f402bb107ff6558a22c57e410c | [
"MIT"
] | null | null | null | //
// EXTradeViewModel.h
// Exchange
//
// Created by Jave on 2018/1/23.
// Copyright © 2018年 Exchange. All rights reserved.
//
#import "RACTableViewModel.h"
@interface EXTradeViewModel : RACTableViewModel
@end
| 15.571429 | 52 | 0.711009 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.