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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9e23a7a94307770fc8019198ff772dce9e0c6d99 | 14,395 | h | C | clients/watchpoints/clients/leak_detector/kernel/scanner.h | Granary/granary | f9ac2b6af0864f420b93917dc21a38041905b3aa | [
"BSD-3-Clause"
] | 37 | 2015-03-13T08:29:46.000Z | 2022-03-04T06:54:29.000Z | clients/watchpoints/clients/leak_detector/kernel/scanner.h | Granary/granary | f9ac2b6af0864f420b93917dc21a38041905b3aa | [
"BSD-3-Clause"
] | null | null | null | clients/watchpoints/clients/leak_detector/kernel/scanner.h | Granary/granary | f9ac2b6af0864f420b93917dc21a38041905b3aa | [
"BSD-3-Clause"
] | 3 | 2015-10-16T21:18:01.000Z | 2022-03-04T06:54:31.000Z | /*
* scanner.h
*
* Created on: 2013-06-24
* Author: akshayk
*/
#ifndef _LEAK_POLICY_SCANNER_H_
#define _LEAK_POLICY_SCANNER_H_
template<typename T>
class type_class {
public:
static unsigned get_size(void) throw () {
unsigned size_ = sizeof(T);
return size_;
}
};
/// dummy for returning the same type; guarantees typdef syntax correctness
template <typename T>
class identity_type {
public:
typedef T type;
};
#define TYPE_SCAN_WRAPPER(type_name, body) \
template <> \
struct scan_function<type_name> { \
public: \
enum { \
IS_DEFINED = 1 \
}; \
typedef identity_type<type_name>::type ArgT__; \
static void scan(ArgT__ &arg, const int depth__) \
body \
};
#define TYPE_SCANNER_CLASS(type_name) \
template <> \
struct scan_function<type_name> { \
public: \
enum { \
IS_DEFINED = 1 \
}; \
typedef identity_type<type_name>::type ArgT__; \
static void scan(ArgT__ &arg, const int depth__); \
};
#define TYPE_SCANNER_BODY(type_name, body) \
void scan_function<type_name>:: \
scan(identity_type<type_name>::type &arg, const int depth__) \
body
#define SCAN_FUNCTION(lval) \
type_scanner_field(lval); \
#define SCAN_RECURSIVE(lval) \
if(scan_function<decltype(lval)>::IS_DEFINED) { \
scan_function<decltype(lval)>::scan(lval, depth__ + 1); \
}
#define SCAN_RECURSIVE_PTR(lval) \
if(scan_function<decltype(lval)>::IS_DEFINED) { \
scan_function<decltype(lval)>::scan(lval, depth__ + 1); \
}
#define MAX_DEPTH_SCANNER 5
#define SCAN_HEAD_FUNC(type_name) \
scan_function<type_name>::scan
template <typename T>
struct scan_function{
public:
enum {
IS_DEFINED = 0
};
static void scan(T & , const int) { }
};
template <>
struct scan_function<void *> {
public:
enum {
IS_DEFINED = 1
};
static void scan(void *, const int depth__) { }
};
template <typename T>
struct scan_function<T &> {
public:
enum {
IS_DEFINED = scan_function<T>::IS_DEFINED
};
static void scan(T &val, const int depth) {
if(IS_DEFINED) {
scan_function<T>::scan(val, depth);
}
}
static inline void pre_scan(T &, const int) { }
};
template <typename T>
struct scan_function<T *> {
public:
enum {
IS_DEFINED = scan_function<T>::IS_DEFINED
};
static void scan(T *ptr, const int depth) {
if(IS_DEFINED && granary::is_valid_address(ptr)) {
scan_function<T>::scan(*ptr, depth);
}
}
};
template <typename T>
struct scan_function<const T> {
public:
enum {
IS_DEFINED = scan_function<T>::IS_DEFINED
};
static void scan(const T &val, const int depth) {
if(IS_DEFINED) {
scan_function<T>::scan(const_cast<T &>(val), depth);
}
}
};
template <typename T>
struct scan_function<volatile T> {
public:
enum {
IS_DEFINED = scan_function<T>::IS_DEFINED
};
static void scan(const T &val, const int depth) {
if(IS_DEFINED) {
scan_function<T>::scan(const_cast<T &>(val), depth);
}
}
};
template <typename T>
struct scan_function<const volatile T> {
public:
enum {
IS_DEFINED = scan_function<T>::IS_DEFINED
};
static void scan(const T &val, const int depth) {
if(IS_DEFINED) {
scan_function<T>::scan(const_cast<T &>(val), depth);
}
}
};
template <typename T>
bool type_scanner_field(T* ptr) {
if(client::wp::is_watched_address(ptr)){
granary::printf("watchpoint : %llx\n", ptr);
return true;
}
return false;
}
template <typename T>
bool type_scanner_field(T addr) {
if(client::wp::is_watched_address(&addr)){
granary::printf("watchpoint : %llx\n", addr);
return true;
}
return false;
}
#define SCANNER_FOR_struct_kobject
#define SCANNER_FOR_struct_file
#define SCANNER_FOR_struct_ts_ops
#define SCANNER_FOR_struct_dma_chan
#define SCANNER_FOR_struct_bus_type
#define SCANNER_FOR_struct_input_handle
#define SCANNER_FOR_struct_transaction_s
#define SCANNER_FOR_struct_device
#define SCANNER_FOR_struct_io_context
#define SCANNER_FOR_struct_backing_dev_info
#define SCANNER_FOR_struct_dst_ops
#define SCANNER_FOR_struct_bio
#define SCANNER_FOR_struct_request_queue
#define SCANNER_FOR_struct_sock
#define SCANNER_FOR_struct_gendisk
#define SCANNER_FOR_struct_block_device
#define SCANNER_FOR_struct_page
#define SCANNER_FOR_struct_crypto_tfm
#define SCANNER_FOR_struct_kthread_work
#define SCANNER_FOR_struct_mm_struct
#define SCANNER_FOR_struct_sk_buff_head
#define SCANNER_FOR_struct_module
#define SCANNER_FOR_struct_super_block
#define SCANNER_FOR_struct_ata_port_operations
#define SCANNER_FOR_struct_pci_dev
#define SCANNER_FOR_struct_ctl_table_header
#define SCANNER_FOR_struct_ctl_table_set
#define SCANNER_FOR_struct_ata_device
#define SCANNER_FOR_struct_sk_buff
#define SCANNER_FOR_struct_net
#define SCANNER_FOR_struct_neigh_parms
#define SCANNER_FOR_struct_mii_bus
#define SCANNER_FOR_struct_net_device
#define SCANNER_FOR_struct_dsa_switch_tree
#define SCANNER_FOR_struct_Qdisc
#define SCANNER_FOR_struct_request_sock_ops
#define SCANNER_FOR_struct_ata_port
#if 0
#define SCAN_OBJECT(arg) \
unsigned long size = type_class<decltype(arg)>::get_size(); \
granary::printf("size : %llx\n", size); \
if(!granary::is_valid_address(&arg)){ \
return; \
} \
unsigned long i = 0; \
uint64_t *ptr = (uint64_t*)(&arg); \
while(i < size){ \
uint64_t value = (uint64_t)(*ptr); \
if(client::wp::is_watched_address(value)) { \
granary::printf("watchpoint like object %llx,\n",(void*)value); \
if(client::wp::is_active_watchpoint(granary::unsafe_cast<void*>(value))){ \
granary::printf("%llx, %llx,\n", ptr, (void*)value); \
}\
} \
ptr++; \
i = i + sizeof(void*); \
}
#ifndef SCANNER_FOR_struct_inode
#define SCANNER_FOR_struct_inode
TYPE_SCANNER_CLASS(struct inode);
#endif
#ifndef SCANNER_FOR_struct_dentry
#define SCANNER_FOR_struct_dentry
TYPE_SCANNER_CLASS(struct dentry);
#endif
#ifndef SCANNER_FOR_struct_task_struct
#define SCANNER_FOR_struct_task_struct
TYPE_SCANNER_CLASS(struct task_struct);
#endif
#include "clients/gen/kernel_type_scanners.h"
TYPE_SCANNER_BODY(struct inode, {
granary::printf( "struct inode\n");
SCAN_OBJECT(arg);
SCAN_FUNCTION(arg.i_mode);
SCAN_FUNCTION(arg.i_opflags);
SCAN_FUNCTION(arg.i_uid);
SCAN_FUNCTION(arg.i_gid);
SCAN_FUNCTION(arg.i_flags);
SCAN_RECURSIVE_PTR(arg.i_acl);
SCAN_RECURSIVE_PTR(arg.i_default_acl);
SCAN_RECURSIVE_PTR(arg.i_op);
SCAN_RECURSIVE_PTR(arg.i_sb);
SCAN_RECURSIVE_PTR(arg.i_mapping);
SCAN_FUNCTION(arg.i_ino);
// Union(union anon_union_120) None
SCAN_FUNCTION(arg.i_rdev);
SCAN_FUNCTION(arg.i_size);
SCAN_RECURSIVE(arg.i_atime);
SCAN_RECURSIVE(arg.i_mtime);
SCAN_RECURSIVE(arg.i_ctime);
SCAN_RECURSIVE(arg.i_lock);
SCAN_FUNCTION(arg.i_bytes);
SCAN_FUNCTION(arg.i_blkbits);
SCAN_FUNCTION(arg.i_blocks);
SCAN_FUNCTION(arg.i_state);
SCAN_RECURSIVE(arg.i_mutex);
SCAN_FUNCTION(arg.dirtied_when);
SCAN_RECURSIVE(arg.i_hash);
SCAN_RECURSIVE(arg.i_wb_list);
SCAN_RECURSIVE(arg.i_lru);
SCAN_RECURSIVE(arg.i_sb_list);
// Union(union anon_union_121) None
SCAN_FUNCTION(arg.i_version);
SCAN_RECURSIVE(arg.i_count);
SCAN_RECURSIVE(arg.i_dio_count);
SCAN_RECURSIVE(arg.i_writecount);
SCAN_RECURSIVE_PTR(arg.i_fop);
SCAN_RECURSIVE_PTR(arg.i_flock);
SCAN_RECURSIVE(arg.i_data);
// Array(Pointer(Use(Struct(struct dquot)))) arg.i_dquot
SCAN_RECURSIVE(arg.i_devices);
// Union(union anon_union_122) None
SCAN_FUNCTION(arg.i_generation);
SCAN_FUNCTION(arg.i_fsnotify_mask);
SCAN_RECURSIVE(arg.i_fsnotify_marks);
SCAN_FUNCTION(arg.i_private);
})
TYPE_SCANNER_BODY(struct dentry, {
granary::printf( "struct dentry\n");
SCAN_OBJECT(arg);
SCAN_FUNCTION(arg.d_flags);
SCAN_RECURSIVE(arg.d_seq);
SCAN_RECURSIVE(arg.d_hash);
SCAN_RECURSIVE_PTR(arg.d_parent);
SCAN_RECURSIVE(arg.d_name);
SCAN_RECURSIVE_PTR(arg.d_inode);
// Array(Attributed(unsigned , BuiltIn(char))) arg.d_iname
SCAN_FUNCTION(arg.d_count);
SCAN_RECURSIVE(arg.d_lock);
SCAN_RECURSIVE_PTR(arg.d_op);
SCAN_RECURSIVE_PTR(arg.d_sb);
SCAN_FUNCTION(arg.d_time);
SCAN_FUNCTION(arg.d_fsdata);
SCAN_RECURSIVE(arg.d_lru);
// Union(union anon_union_113) arg.d_u
SCAN_RECURSIVE(arg.d_subdirs);
SCAN_RECURSIVE(arg.d_alias);
})
TYPE_SCANNER_BODY(struct task_struct, {
granary::printf( "struct task_struct\n");
SCAN_OBJECT(arg);
SCAN_FUNCTION(arg.state);
SCAN_FUNCTION(arg.stack);
SCAN_RECURSIVE(arg.usage);
SCAN_FUNCTION(arg.flags);
SCAN_FUNCTION(arg.ptrace);
SCAN_RECURSIVE(arg.wake_entry);
SCAN_FUNCTION(arg.on_cpu);
SCAN_FUNCTION(arg.on_rq);
SCAN_FUNCTION(arg.prio);
SCAN_FUNCTION(arg.static_prio);
SCAN_FUNCTION(arg.normal_prio);
SCAN_FUNCTION(arg.rt_priority);
SCAN_RECURSIVE_PTR(arg.sched_class);
SCAN_RECURSIVE(arg.se);
SCAN_RECURSIVE(arg.rt);
SCAN_RECURSIVE_PTR(arg.sched_task_group);
SCAN_RECURSIVE(arg.preempt_notifiers);
SCAN_FUNCTION(arg.fpu_counter);
SCAN_FUNCTION(arg.policy);
SCAN_FUNCTION(arg.nr_cpus_allowed);
SCAN_RECURSIVE(arg.cpus_allowed);
SCAN_RECURSIVE(arg.sched_info);
SCAN_RECURSIVE(arg.tasks);
SCAN_RECURSIVE(arg.pushable_tasks);
SCAN_RECURSIVE_PTR(arg.mm);
SCAN_RECURSIVE_PTR(arg.active_mm);
SCAN_RECURSIVE(arg.rss_stat);
SCAN_FUNCTION(arg.exit_state);
SCAN_FUNCTION(arg.exit_code);
SCAN_FUNCTION(arg.exit_signal);
SCAN_FUNCTION(arg.pdeath_signal);
SCAN_FUNCTION(arg.jobctl);
SCAN_FUNCTION(arg.personality);
// Bitfield(Attributed(unsigned , BuiltIn(int))) arg.did_exec
// Bitfield(Attributed(unsigned , BuiltIn(int))) arg.in_execve
// Bitfield(Attributed(unsigned , BuiltIn(int))) arg.in_iowait
// Bitfield(Attributed(unsigned , BuiltIn(int))) arg.no_new_privs
// Bitfield(Attributed(unsigned , BuiltIn(int))) arg.sched_reset_on_fork
// Bitfield(Attributed(unsigned , BuiltIn(int))) arg.sched_contributes_to_load
SCAN_FUNCTION(arg.pid);
SCAN_FUNCTION(arg.tgid);
SCAN_FUNCTION(arg.stack_canary);
SCAN_RECURSIVE_PTR(arg.real_parent);
SCAN_RECURSIVE_PTR(arg.parent);
SCAN_RECURSIVE(arg.children);
SCAN_RECURSIVE(arg.sibling);
SCAN_RECURSIVE_PTR(arg.group_leader);
SCAN_RECURSIVE(arg.ptraced);
SCAN_RECURSIVE(arg.ptrace_entry);
// Array(Use(Struct(struct pid_link))) arg.pids
SCAN_RECURSIVE(arg.thread_group);
SCAN_RECURSIVE_PTR(arg.vfork_done);
SCAN_FUNCTION(arg.set_child_tid);
SCAN_FUNCTION(arg.clear_child_tid);
SCAN_FUNCTION(arg.utime);
SCAN_FUNCTION(arg.stime);
SCAN_FUNCTION(arg.utimescaled);
SCAN_FUNCTION(arg.stimescaled);
SCAN_FUNCTION(arg.gtime);
SCAN_RECURSIVE(arg.prev_cputime);
SCAN_FUNCTION(arg.nvcsw);
SCAN_FUNCTION(arg.nivcsw);
SCAN_RECURSIVE(arg.start_time);
SCAN_RECURSIVE(arg.real_start_time);
SCAN_FUNCTION(arg.min_flt);
SCAN_FUNCTION(arg.maj_flt);
SCAN_RECURSIVE(arg.cputime_expires);
// Array(Use(Struct(struct list_head))) arg.cpu_timers
SCAN_RECURSIVE_PTR(arg.real_cred);
SCAN_RECURSIVE_PTR(arg.cred);
// Array(BuiltIn(char)) arg.comm
SCAN_FUNCTION(arg.link_count);
SCAN_FUNCTION(arg.total_link_count);
SCAN_RECURSIVE(arg.sysvsem);
SCAN_FUNCTION(arg.last_switch_count);
SCAN_RECURSIVE(arg.thread);
SCAN_RECURSIVE_PTR(arg.fs);
SCAN_RECURSIVE_PTR(arg.files);
SCAN_RECURSIVE_PTR(arg.nsproxy);
SCAN_RECURSIVE_PTR(arg.signal);
SCAN_RECURSIVE_PTR(arg.sighand);
SCAN_RECURSIVE(arg.blocked);
SCAN_RECURSIVE(arg.real_blocked);
SCAN_RECURSIVE(arg.saved_sigmask);
SCAN_RECURSIVE(arg.pending);
SCAN_FUNCTION(arg.sas_ss_sp);
SCAN_FUNCTION(arg.sas_ss_size);
SCAN_FUNCTION(arg.notifier);
SCAN_FUNCTION(arg.notifier_data);
SCAN_RECURSIVE_PTR(arg.notifier_mask);
SCAN_RECURSIVE_PTR(arg.task_works);
SCAN_RECURSIVE_PTR(arg.audit_context);
SCAN_FUNCTION(arg.loginuid);
SCAN_FUNCTION(arg.sessionid);
SCAN_RECURSIVE(arg.seccomp);
SCAN_FUNCTION(arg.parent_exec_id);
SCAN_FUNCTION(arg.self_exec_id);
SCAN_RECURSIVE(arg.alloc_lock);
SCAN_RECURSIVE(arg.pi_lock);
SCAN_RECURSIVE(arg.pi_waiters);
SCAN_RECURSIVE_PTR(arg.pi_blocked_on);
SCAN_FUNCTION(arg.journal_info);
SCAN_RECURSIVE_PTR(arg.bio_list);
SCAN_RECURSIVE_PTR(arg.plug);
SCAN_RECURSIVE_PTR(arg.reclaim_state);
SCAN_RECURSIVE_PTR(arg.backing_dev_info);
SCAN_RECURSIVE_PTR(arg.io_context);
SCAN_FUNCTION(arg.ptrace_message);
SCAN_RECURSIVE_PTR(arg.last_siginfo);
SCAN_RECURSIVE(arg.ioac);
SCAN_FUNCTION(arg.acct_rss_mem1);
SCAN_FUNCTION(arg.acct_vm_mem1);
SCAN_FUNCTION(arg.acct_timexpd);
SCAN_RECURSIVE(arg.mems_allowed);
SCAN_RECURSIVE(arg.mems_allowed_seq);
SCAN_FUNCTION(arg.cpuset_mem_spread_rotor);
SCAN_FUNCTION(arg.cpuset_slab_spread_rotor);
SCAN_RECURSIVE_PTR(arg.cgroups);
SCAN_RECURSIVE(arg.cg_list);
SCAN_RECURSIVE_PTR(arg.robust_list);
SCAN_RECURSIVE_PTR(arg.compat_robust_list);
SCAN_RECURSIVE(arg.pi_state_list);
SCAN_RECURSIVE_PTR(arg.pi_state_cache);
// Array(Pointer(Use(Struct(struct perf_event_context)))) arg.perf_event_ctxp
SCAN_RECURSIVE(arg.perf_event_mutex);
SCAN_RECURSIVE(arg.perf_event_list);
SCAN_RECURSIVE_PTR(arg.mempolicy);
SCAN_FUNCTION(arg.il_next);
SCAN_FUNCTION(arg.pref_node_fork);
SCAN_RECURSIVE(arg.rcu);
SCAN_RECURSIVE_PTR(arg.splice_pipe);
SCAN_RECURSIVE(arg.task_frag);
SCAN_RECURSIVE_PTR(arg.delays);
SCAN_FUNCTION(arg.nr_dirtied);
SCAN_FUNCTION(arg.nr_dirtied_pause);
SCAN_FUNCTION(arg.dirty_paused_when);
SCAN_FUNCTION(arg.latency_record_count);
// Array(Use(Struct(struct latency_record))) arg.latency_record
SCAN_FUNCTION(arg.timer_slack_ns);
SCAN_FUNCTION(arg.default_timer_slack_ns);
SCAN_RECURSIVE(arg.ptrace_bp_refcnt);
})
#endif
#endif /* SCANNER_H_ */
| 28.79 | 89 | 0.714901 |
d2196040db3a9206def6947fdef203081fed7754 | 19,800 | c | C | sapi/phpdbg/phpdbg_cmd.c | slusarz/php-src | 961da40809a8a01d76a52f93f6c20a4d6e5aeec2 | [
"PHP-3.01"
] | null | null | null | sapi/phpdbg/phpdbg_cmd.c | slusarz/php-src | 961da40809a8a01d76a52f93f6c20a4d6e5aeec2 | [
"PHP-3.01"
] | null | null | null | sapi/phpdbg/phpdbg_cmd.c | slusarz/php-src | 961da40809a8a01d76a52f93f6c20a4d6e5aeec2 | [
"PHP-3.01"
] | null | null | null | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2014 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <felipe@php.net> |
| Authors: Joe Watkins <joe.watkins@live.co.uk> |
| Authors: Bob Weinand <bwoebi@php.net> |
+----------------------------------------------------------------------+
*/
#include "phpdbg.h"
#include "phpdbg_cmd.h"
#include "phpdbg_utils.h"
#include "phpdbg_set.h"
#include "phpdbg_prompt.h"
#include "phpdbg_io.h"
ZEND_EXTERN_MODULE_GLOBALS(phpdbg);
static inline const char *phpdbg_command_name(const phpdbg_command_t *command, char *buffer) {
size_t pos = 0;
if (command->parent) {
memcpy(&buffer[pos], command->parent->name, command->parent->name_len);
pos += command->parent->name_len;
memcpy(&buffer[pos], " ", sizeof(" ")-1);
pos += (sizeof(" ")-1);
}
memcpy(&buffer[pos], command->name, command->name_len);
pos += command->name_len;
buffer[pos] = 0;
return buffer;
}
PHPDBG_API const char *phpdbg_get_param_type(const phpdbg_param_t *param) /* {{{ */
{
switch (param->type) {
case STACK_PARAM:
return "stack";
case EMPTY_PARAM:
return "empty";
case ADDR_PARAM:
return "address";
case NUMERIC_PARAM:
return "numeric";
case METHOD_PARAM:
return "method";
case NUMERIC_FUNCTION_PARAM:
return "function opline";
case NUMERIC_METHOD_PARAM:
return "method opline";
case FILE_PARAM:
return "file or file opline";
case STR_PARAM:
return "string";
default: /* this is bad */
return "unknown";
}
}
PHPDBG_API void phpdbg_clear_param(phpdbg_param_t *param) /* {{{ */
{
if (param) {
switch (param->type) {
case FILE_PARAM:
efree(param->file.name);
break;
case METHOD_PARAM:
efree(param->method.class);
efree(param->method.name);
break;
case STR_PARAM:
efree(param->str);
break;
default:
break;
}
}
} /* }}} */
PHPDBG_API char* phpdbg_param_tostring(const phpdbg_param_t *param, char **pointer) /* {{{ */
{
switch (param->type) {
case STR_PARAM:
asprintf(pointer, "%s", param->str);
break;
case ADDR_PARAM:
asprintf(pointer, "%#llx", param->addr);
break;
case NUMERIC_PARAM:
asprintf(pointer, "%li", param->num);
break;
case METHOD_PARAM:
asprintf(pointer, "%s::%s", param->method.class, param->method.name);
break;
case FILE_PARAM:
if (param->num) {
asprintf(pointer, "%s:%lu#%lu", param->file.name, param->file.line, param->num);
} else {
asprintf(pointer, "%s:%lu", param->file.name, param->file.line);
}
break;
case NUMERIC_FUNCTION_PARAM:
asprintf(pointer, "%s#%lu", param->str, param->num);
break;
case NUMERIC_METHOD_PARAM:
asprintf(pointer, "%s::%s#%lu", param->method.class, param->method.name, param->num);
break;
default:
*pointer = strdup("unknown");
}
return *pointer;
} /* }}} */
PHPDBG_API void phpdbg_copy_param(const phpdbg_param_t* src, phpdbg_param_t* dest) /* {{{ */
{
switch ((dest->type = src->type)) {
case STACK_PARAM:
/* nope */
break;
case STR_PARAM:
dest->str = estrndup(src->str, src->len);
dest->len = src->len;
break;
case OP_PARAM:
dest->str = estrndup(src->str, src->len);
dest->len = src->len;
break;
case ADDR_PARAM:
dest->addr = src->addr;
break;
case NUMERIC_PARAM:
dest->num = src->num;
break;
case METHOD_PARAM:
dest->method.class = estrdup(src->method.class);
dest->method.name = estrdup(src->method.name);
break;
case NUMERIC_FILE_PARAM:
case FILE_PARAM:
dest->file.name = estrdup(src->file.name);
dest->file.line = src->file.line;
if (src->num)
dest->num = src->num;
break;
case NUMERIC_FUNCTION_PARAM:
dest->str = estrndup(src->str, src->len);
dest->num = src->num;
dest->len = src->len;
break;
case NUMERIC_METHOD_PARAM:
dest->method.class = estrdup(src->method.class);
dest->method.name = estrdup(src->method.name);
dest->num = src->num;
break;
case EMPTY_PARAM: { /* do nothing */ } break;
default: {
/* not yet */
}
}
} /* }}} */
PHPDBG_API zend_ulong phpdbg_hash_param(const phpdbg_param_t *param) /* {{{ */
{
zend_ulong hash = param->type;
switch (param->type) {
case STACK_PARAM:
/* nope */
break;
case STR_PARAM:
hash += zend_inline_hash_func(param->str, param->len);
break;
case METHOD_PARAM:
hash += zend_inline_hash_func(param->method.class, strlen(param->method.class));
hash += zend_inline_hash_func(param->method.name, strlen(param->method.name));
break;
case FILE_PARAM:
hash += zend_inline_hash_func(param->file.name, strlen(param->file.name));
hash += param->file.line;
if (param->num)
hash += param->num;
break;
case ADDR_PARAM:
hash += param->addr;
break;
case NUMERIC_PARAM:
hash += param->num;
break;
case NUMERIC_FUNCTION_PARAM:
hash += zend_inline_hash_func(param->str, param->len);
hash += param->num;
break;
case NUMERIC_METHOD_PARAM:
hash += zend_inline_hash_func(param->method.class, strlen(param->method.class));
hash += zend_inline_hash_func(param->method.name, strlen(param->method.name));
if (param->num)
hash+= param->num;
break;
case EMPTY_PARAM: { /* do nothing */ } break;
default: {
/* not yet */
}
}
return hash;
} /* }}} */
PHPDBG_API zend_bool phpdbg_match_param(const phpdbg_param_t *l, const phpdbg_param_t *r) /* {{{ */
{
if (l && r) {
if (l->type == r->type) {
switch (l->type) {
case STACK_PARAM:
/* nope, or yep */
return 1;
break;
case NUMERIC_FUNCTION_PARAM:
if (l->num != r->num) {
break;
}
/* break intentionally omitted */
case STR_PARAM:
return (l->len == r->len) &&
(memcmp(l->str, r->str, l->len) == SUCCESS);
case NUMERIC_PARAM:
return (l->num == r->num);
case ADDR_PARAM:
return (l->addr == r->addr);
case FILE_PARAM: {
if (l->file.line == r->file.line) {
size_t lengths[2] = {
strlen(l->file.name), strlen(r->file.name)};
if (lengths[0] == lengths[1]) {
if ((!l->num && !r->num) || (l->num == r->num)) {
return (memcmp(
l->file.name, r->file.name, lengths[0]) == SUCCESS);
}
}
}
} break;
case NUMERIC_METHOD_PARAM:
if (l->num != r->num) {
break;
}
/* break intentionally omitted */
case METHOD_PARAM: {
size_t lengths[2] = {
strlen(l->method.class), strlen(r->method.class)};
if (lengths[0] == lengths[1]) {
if (memcmp(l->method.class, r->method.class, lengths[0]) == SUCCESS) {
lengths[0] = strlen(l->method.name);
lengths[1] = strlen(r->method.name);
if (lengths[0] == lengths[1]) {
return (memcmp(
l->method.name, r->method.name, lengths[0]) == SUCCESS);
}
}
}
} break;
case EMPTY_PARAM:
return 1;
default: {
/* not yet */
}
}
}
}
return 0;
} /* }}} */
/* {{{ */
PHPDBG_API void phpdbg_param_debug(const phpdbg_param_t *param, const char *msg) {
if (param && param->type) {
switch (param->type) {
case STR_PARAM:
fprintf(stderr, "%s STR_PARAM(%s=%lu)\n", msg, param->str, param->len);
break;
case ADDR_PARAM:
fprintf(stderr, "%s ADDR_PARAM(%llu)\n", msg, param->addr);
break;
case NUMERIC_FILE_PARAM:
fprintf(stderr, "%s NUMERIC_FILE_PARAM(%s:#%lu)\n", msg, param->file.name, param->file.line);
break;
case FILE_PARAM:
fprintf(stderr, "%s FILE_PARAM(%s:%lu)\n", msg, param->file.name, param->file.line);
break;
case METHOD_PARAM:
fprintf(stderr, "%s METHOD_PARAM(%s::%s)\n", msg, param->method.class, param->method.name);
break;
case NUMERIC_METHOD_PARAM:
fprintf(stderr, "%s NUMERIC_METHOD_PARAM(%s::%s)\n", msg, param->method.class, param->method.name);
break;
case NUMERIC_FUNCTION_PARAM:
fprintf(stderr, "%s NUMERIC_FUNCTION_PARAM(%s::%ld)\n", msg, param->str, param->num);
break;
case NUMERIC_PARAM:
fprintf(stderr, "%s NUMERIC_PARAM(%ld)\n", msg, param->num);
break;
case COND_PARAM:
fprintf(stderr, "%s COND_PARAM(%s=%lu)\n", msg, param->str, param->len);
break;
case OP_PARAM:
fprintf(stderr, "%s OP_PARAM(%s=%lu)\n", msg, param->str, param->len);
break;
default: {
/* not yet */
}
}
}
} /* }}} */
/* {{{ */
PHPDBG_API void phpdbg_stack_free(phpdbg_param_t *stack) {
if (stack && stack->next) {
phpdbg_param_t *remove = stack->next;
while (remove) {
phpdbg_param_t *next = NULL;
if (remove->next)
next = remove->next;
switch (remove->type) {
case NUMERIC_METHOD_PARAM:
case METHOD_PARAM:
if (remove->method.class)
free(remove->method.class);
if (remove->method.name)
free(remove->method.name);
break;
case NUMERIC_FUNCTION_PARAM:
case STR_PARAM:
case OP_PARAM:
if (remove->str)
free(remove->str);
break;
case NUMERIC_FILE_PARAM:
case FILE_PARAM:
if (remove->file.name)
free(remove->file.name);
break;
default: {
/* nothing */
}
}
free(remove);
remove = NULL;
if (next)
remove = next;
else break;
}
}
stack->next = NULL;
} /* }}} */
/* {{{ */
PHPDBG_API void phpdbg_stack_push(phpdbg_param_t *stack, phpdbg_param_t *param) {
phpdbg_param_t *next = calloc(1, sizeof(phpdbg_param_t));
if (!next)
return;
*(next) = *(param);
next->next = NULL;
if (stack->top == NULL) {
stack->top = next;
next->top = NULL;
stack->next = next;
} else {
stack->top->next = next;
next->top = stack->top;
stack->top = next;
}
stack->len++;
} /* }}} */
PHPDBG_API int phpdbg_stack_verify(const phpdbg_command_t *command, phpdbg_param_t **stack) {
if (command) {
char buffer[128] = {0,};
const phpdbg_param_t *top = (stack != NULL) ? *stack : NULL;
const char *arg = command->args;
size_t least = 0L,
received = 0L,
current = 0L;
zend_bool optional = 0;
/* check for arg spec */
if (!(arg) || !(*arg)) {
if (!top) {
return SUCCESS;
}
phpdbg_error("command", "type=\"toomanyargs\" command=\"%s\" expected=\"0\"", "The command \"%s\" expected no arguments",
phpdbg_command_name(command, buffer));
return FAILURE;
}
least = 0L;
/* count least amount of arguments */
while (arg && *arg) {
if (arg[0] == '|') {
break;
}
least++;
arg++;
}
arg = command->args;
#define verify_arg(e, a, t) if (!(a)) { \
if (!optional) { \
phpdbg_error("command", "type=\"noarg\" command=\"%s\" expected=\"%s\" num=\"%lu\"", "The command \"%s\" expected %s and got nothing at parameter %lu", \
phpdbg_command_name(command, buffer), \
(e), \
current); \
return FAILURE;\
} \
} else if ((a)->type != (t)) { \
phpdbg_error("command", "type=\"wrongarg\" command=\"%s\" expected=\"%s\" got=\"%s\" num=\"%lu\"", "The command \"%s\" expected %s and got %s at parameter %lu", \
phpdbg_command_name(command, buffer), \
(e),\
phpdbg_get_param_type((a)), \
current); \
return FAILURE; \
}
while (arg && *arg) {
current++;
switch (*arg) {
case '|': {
current--;
optional = 1;
arg++;
} continue;
case 'i': verify_arg("raw input", top, STR_PARAM); break;
case 's': verify_arg("string", top, STR_PARAM); break;
case 'n': verify_arg("number", top, NUMERIC_PARAM); break;
case 'm': verify_arg("method", top, METHOD_PARAM); break;
case 'a': verify_arg("address", top, ADDR_PARAM); break;
case 'f': verify_arg("file:line", top, FILE_PARAM); break;
case 'c': verify_arg("condition", top, COND_PARAM); break;
case 'o': verify_arg("opcode", top, OP_PARAM); break;
case 'b': verify_arg("boolean", top, NUMERIC_PARAM); break;
case '*': { /* do nothing */ } break;
}
if (top ) {
top = top->next;
} else break;
received++;
arg++;
}
#undef verify_arg
if ((received < least)) {
phpdbg_error("command", "type=\"toofewargs\" command=\"%s\" expected=\"%d\" argtypes=\"%s\" got=\"%d\"", "The command \"%s\" expected at least %lu arguments (%s) and received %lu",
phpdbg_command_name(command, buffer),
least,
command->args,
received);
return FAILURE;
}
}
return SUCCESS;
}
/* {{{ */
PHPDBG_API const phpdbg_command_t *phpdbg_stack_resolve(const phpdbg_command_t *commands, const phpdbg_command_t *parent, phpdbg_param_t **top) {
const phpdbg_command_t *command = commands;
phpdbg_param_t *name = *top;
const phpdbg_command_t *matched[3] = {NULL, NULL, NULL};
ulong matches = 0L;
while (command && command->name && command->handler) {
if (name->len == 1 || command->name_len >= name->len) {
/* match single letter alias */
if (command->alias && (name->len == 1)) {
if (command->alias == (*name->str)) {
matched[matches] = command;
matches++;
}
} else {
/* match full, case insensitive, command name */
if (strncasecmp(command->name, name->str, name->len) == SUCCESS) {
if (matches < 3) {
/* only allow abbreviating commands that can be aliased */
if ((name->len != command->name_len && command->alias) || name->len == command->name_len) {
matched[matches] = command;
matches++;
}
/* exact match */
if (name->len == command->name_len) {
break;
}
} else {
break;
}
}
}
}
command++;
}
switch (matches) {
case 0:
if (parent) {
phpdbg_error("command", "type=\"notfound\" command=\"%s\" subcommand=\"%s\"", "The command \"%s %s\" could not be found", parent->name, name->str);
} else {
phpdbg_error("command", "type=\"notfound\" command=\"%s\"", "The command \"%s\" could not be found", name->str);
}
return parent;
case 1:
(*top) = (*top)->next;
command = matched[0];
break;
default: {
char *list = NULL;
uint32_t it = 0;
size_t pos = 0;
while (it < matches) {
if (!list) {
list = emalloc(matched[it]->name_len + 1 + (it + 1 < matches ? sizeof(", ") - 1 : 0));
} else {
list = erealloc(list, (pos + matched[it]->name_len) + 1 + (it + 1 < matches ? sizeof(", ") - 1 : 0));
}
memcpy(&list[pos], matched[it]->name, matched[it]->name_len);
pos += matched[it]->name_len;
if ((it + 1) < matches) {
memcpy(&list[pos], ", ", sizeof(", ") - 1);
pos += (sizeof(", ") - 1);
}
list[pos] = 0;
it++;
}
/* ", " separated matches */
phpdbg_error("command", "type=\"ambiguous\" command=\"%s\" matches=\"%lu\" matched=\"%s\"", "The command \"%s\" is ambigious, matching %lu commands (%s)", name->str, matches, list);
efree(list);
return NULL;
}
}
if (command->subs && (*top) && ((*top)->type == STR_PARAM)) {
return phpdbg_stack_resolve(command->subs, command, top);
} else {
return command;
}
return NULL;
} /* }}} */
/* {{{ */
PHPDBG_API int phpdbg_stack_execute(phpdbg_param_t *stack, zend_bool allow_async_unsafe) {
phpdbg_param_t *top = NULL;
const phpdbg_command_t *handler = NULL;
if (stack->type != STACK_PARAM) {
phpdbg_error("command", "type=\"nostack\"", "The passed argument was not a stack !");
return FAILURE;
}
if (!stack->len) {
phpdbg_error("command", "type=\"emptystack\"", "The stack contains nothing !");
return FAILURE;
}
top = (phpdbg_param_t *) stack->next;
switch (top->type) {
case EVAL_PARAM:
phpdbg_activate_err_buf(0);
phpdbg_free_err_buf();
return PHPDBG_COMMAND_HANDLER(ev)(top);
case RUN_PARAM:
if (!allow_async_unsafe) {
phpdbg_error("signalsegv", "command=\"run\"", "run command is disallowed during hard interrupt");
}
phpdbg_activate_err_buf(0);
phpdbg_free_err_buf();
return PHPDBG_COMMAND_HANDLER(run)(top);
case SHELL_PARAM:
if (!allow_async_unsafe) {
phpdbg_error("signalsegv", "command=\"sh\"", "sh command is disallowed during hard interrupt");
return FAILURE;
}
phpdbg_activate_err_buf(0);
phpdbg_free_err_buf();
return PHPDBG_COMMAND_HANDLER(sh)(top);
case STR_PARAM: {
handler = phpdbg_stack_resolve(phpdbg_prompt_commands, NULL, &top);
if (handler) {
if (!allow_async_unsafe && !(handler->flags & PHPDBG_ASYNC_SAFE)) {
phpdbg_error("signalsegv", "command=\"%s\"", "%s command is disallowed during hard interrupt", handler->name);
return FAILURE;
}
if (phpdbg_stack_verify(handler, &top) == SUCCESS) {
phpdbg_activate_err_buf(0);
phpdbg_free_err_buf();
return handler->handler(top);
}
}
} return FAILURE;
default:
phpdbg_error("command", "type=\"invalidcommand\"", "The first parameter makes no sense !");
return FAILURE;
}
return SUCCESS;
} /* }}} */
PHPDBG_API char *phpdbg_read_input(char *buffered) /* {{{ */
{
char buf[PHPDBG_MAX_CMD];
char *cmd = NULL;
char *buffer = NULL;
if ((PHPDBG_G(flags) & (PHPDBG_IS_STOPPING | PHPDBG_IS_RUNNING)) != PHPDBG_IS_STOPPING) {
if ((PHPDBG_G(flags) & PHPDBG_IS_REMOTE) && (buffered == NULL) && !phpdbg_active_sigsafe_mem()) {
fflush(PHPDBG_G(io)[PHPDBG_STDOUT].ptr);
}
if (buffered == NULL) {
#define USE_LIB_STAR (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDIT))
/* note: EOF makes readline write prompt again in local console mode - and ignored if compiled without readline */
#if USE_LIB_STAR
readline:
if (PHPDBG_G(flags) & PHPDBG_IS_REMOTE)
#endif
{
phpdbg_write("prompt", "", "%s", phpdbg_get_prompt());
phpdbg_consume_stdin_line(cmd = buf);
}
#if USE_LIB_STAR
else {
cmd = readline(phpdbg_get_prompt());
PHPDBG_G(last_was_newline) = 1;
}
if (!cmd) {
goto readline;
}
if (!(PHPDBG_G(flags) & PHPDBG_IS_REMOTE)) {
add_history(cmd);
}
#endif
} else {
cmd = buffered;
}
buffer = estrdup(cmd);
#if USE_LIB_STAR
if (!buffered && cmd && !(PHPDBG_G(flags) & PHPDBG_IS_REMOTE)) {
free(cmd);
}
#endif
}
if (buffer && isspace(*buffer)) {
char *trimmed = buffer;
while (isspace(*trimmed))
trimmed++;
trimmed = estrdup(trimmed);
efree(buffer);
buffer = trimmed;
}
if (buffer && strlen(buffer)) {
if (PHPDBG_G(buffer)) {
efree(PHPDBG_G(buffer));
}
PHPDBG_G(buffer) = estrdup(buffer);
} else {
if (PHPDBG_G(buffer)) {
buffer = estrdup(PHPDBG_G(buffer));
}
}
return buffer;
} /* }}} */
PHPDBG_API void phpdbg_destroy_input(char **input) /*{{{ */
{
efree(*input);
} /* }}} */
PHPDBG_API int phpdbg_ask_user_permission(const char *question) {
if (!(PHPDBG_G(flags) & PHPDBG_WRITE_XML)) {
char buf[PHPDBG_MAX_CMD];
phpdbg_out("%s", question);
phpdbg_out(" (type y or n): ");
while (1) {
phpdbg_consume_stdin_line(buf);
if (buf[1] == '\n' && (buf[0] == 'y' || buf[0] == 'n')) {
if (buf[0] == 'y') {
return SUCCESS;
}
return FAILURE;
}
phpdbg_out("Please enter either y (yes) or n (no): ");
}
}
return SUCCESS;
}
| 24.688279 | 184 | 0.593131 |
2c9e0d0303a98abd4a9170e81ff6affebe6fa343 | 3,727 | h | C | arch/renesas/include/rx65n/inttypes.h | fofolevrai/incubator-nuttx | 13be542385d9f51b9b3292e884190aa44a43f1f6 | [
"Apache-2.0"
] | 1 | 2021-11-23T16:34:56.000Z | 2021-11-23T16:34:56.000Z | arch/renesas/include/rx65n/inttypes.h | fofolevrai/incubator-nuttx | 13be542385d9f51b9b3292e884190aa44a43f1f6 | [
"Apache-2.0"
] | 6 | 2020-07-21T02:03:18.000Z | 2021-05-13T20:12:40.000Z | arch/renesas/include/rx65n/inttypes.h | fofolevrai/incubator-nuttx | 13be542385d9f51b9b3292e884190aa44a43f1f6 | [
"Apache-2.0"
] | 1 | 2021-11-23T16:35:31.000Z | 2021-11-23T16:35:31.000Z | /****************************************************************************
* arch/renesas/include/rx65n/inttypes.h
*
* Copyright (C) 2008-2019 Gregory Nutt. All rights reserved.
* Author: Anjana <anjana@tataelxsi.co.in>
*
* 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 NuttX 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 OWNER 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.
****************************************************************************/
#ifndef __ARCH_RENESAS_INCLUDE_RX65N_INTTYPES_H
#define __ARCH_RENESAS_INCLUDE_RX65N_INTTYPES_H
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define PRId8 "d"
#define PRId16 "d"
#define PRId32 "d"
#define PRId64 "lld"
#define PRIdPTR "d"
#define PRIi8 "i"
#define PRIi16 "i"
#define PRIi32 "i"
#define PRIi64 "lli"
#define PRIiPTR "i"
#define PRIo8 "o"
#define PRIo16 "o"
#define PRIo32 "o"
#define PRIo64 "llo"
#define PRIoPTR "o"
#define PRIu8 "u"
#define PRIu16 "u"
#define PRIu32 "u"
#define PRIu64 "llu"
#define PRIuPTR "u"
#define PRIx8 "x"
#define PRIx16 "x"
#define PRIx32 "x"
#define PRIx64 "llx"
#define PRIxPTR "x"
#define PRIX8 "X"
#define PRIX16 "X"
#define PRIX32 "X"
#define PRIX64 "llX"
#define PRIXPTR "X"
#define SCNd8 "hhd"
#define SCNd16 "hd"
#define SCNd32 "d"
#define SCNd64 "lld"
#define SCNdPTR "d"
#define SCNi8 "hhi"
#define SCNi16 "hi"
#define SCNi32 "i"
#define SCNi64 "lli"
#define SCNiPTR "i"
#define SCNo8 "hho"
#define SCNo16 "ho"
#define SCNo32 "o"
#define SCNo64 "llo"
#define SCNoPTR "o"
#define SCNu8 "hhu"
#define SCNu16 "hu"
#define SCNu32 "u"
#define SCNu64 "llu"
#define SCNuPTR "u"
#define SCNx8 "hhx"
#define SCNx16 "hx"
#define SCNx32 "x"
#define SCNx64 "llx"
#define SCNxPTR "x"
#define INT8_C(x) x
#define INT16_C(x) x
#define INT32_C(x) x
#define INT64_C(x) x ## ll
#define UINT8_C(x) x
#define UINT16_C(x) x
#define UINT32_C(x) x ## u
#define UINT64_C(x) x ## ull
#endif /* __ARCH_RENESAS_INCLUDE_RX65N_INTTYPES_H */
| 28.669231 | 78 | 0.617118 |
323bea3616732e7657db67ea6abe2ffbf1c8c474 | 2,421 | h | C | interfaces/kits/ui/events/key_event.h | OpenHarmony-mirror/graphic_lite | 92b27fd13906e660b1958e1f4508129996d07fd4 | [
"Apache-2.0"
] | null | null | null | interfaces/kits/ui/events/key_event.h | OpenHarmony-mirror/graphic_lite | 92b27fd13906e660b1958e1f4508129996d07fd4 | [
"Apache-2.0"
] | null | null | null | interfaces/kits/ui/events/key_event.h | OpenHarmony-mirror/graphic_lite | 92b27fd13906e660b1958e1f4508129996d07fd4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020 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.
*/
/**
* @addtogroup Graphic
* @{
*
* @brief Defines a lightweight graphics system that provides basic UI and container views,
* including buttons, images, labels, lists, animators, scroll views, swipe views, and layouts.
* This system also provides the Design for X (DFX) capability to implement features such as
* view rendering, animation, and input event distribution.
*
* @since 1.0
* @version 1.0
*/
/**
* @file key_event.h
*
* @brief Declares a key event, which indicates that a physical button is pressed or released.
*
* @since 1.0
* @version 1.0
*/
#ifndef GRAPHIC_LITE_KEY_EVENT_H
#define GRAPHIC_LITE_KEY_EVENT_H
#include "event.h"
namespace OHOS {
constexpr uint16_t INVALID_KEY_STATE = UINT16_MAX;
/**
* @brief Defines a key event, which indicates that a physical button is pressed or released.
*
* @since 1.0
* @version 1.0
*/
class KeyEvent : public Event {
public:
KeyEvent() = delete;
/**
* @brief A constructor used to create a <b>KeyEvent</b> instance.
* @param keyId Indicates the key ID.
* @param state Indicates the key state.
* @since 1.0
* @version 1.0
*/
KeyEvent(uint16_t keyId, uint16_t state) : keyId_(keyId), state_(state) {}
/**
* @brief A destructor used to delete the <b>KeyEvent</b> instance.
* @since 1.0
* @version 1.0
*/
~KeyEvent() {}
/**
* @brief Obtains the key ID.
* @since 1.0
* @version 1.0
*/
uint16_t GetKeyId() const
{
return keyId_;
}
/**
* @brief Obtains the key state.
* @since 1.0
* @version 1.0
*/
uint16_t GetState() const
{
return state_;
}
private:
uint16_t keyId_;
uint16_t state_;
};
} // namespace OHOS
#endif // GRAPHIC_LITE_KEY_EVENT_H
| 24.704082 | 102 | 0.653449 |
d0f135ca1b684f13ca8741ac5b814ec10a1d3347 | 31,012 | c | C | Boss2D/addon/libvorbis-1.3.6_for_boss/lib/floor1.c | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/addon/libvorbis-1.3.6_for_boss/lib/floor1.c | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/addon/libvorbis-1.3.6_for_boss/lib/floor1.c | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | /********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2015 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: floor backend 1 implementation
********************************************************************/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include BOSS_LIBOGG_V_ogg__ogg_h //original-code:<ogg/ogg.h>
#include BOSS_LIBVORBIS_U_vorbis__codec_h //original-code:"vorbis/codec.h"
#include "codec_internal.h"
#include "registry.h"
#include "codebook.h"
#include "misc.h"
#include "scales.h"
#include <stdio.h>
#define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
typedef struct lsfit_acc{
int x0;
int x1;
int xa;
int ya;
int x2a;
int y2a;
int xya;
int an;
int xb;
int yb;
int x2b;
int y2b;
int xyb;
int bn;
} lsfit_acc;
/***********************************************/
static void floor1_free_info(vorbis_info_floor *i){
vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
if(info){
memset(info,0,sizeof(*info));
_ogg_free(info);
}
}
static void floor1_free_look(vorbis_look_floor *i){
vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
if(look){
/*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
(float)look->phrasebits/look->frames,
(float)look->postbits/look->frames,
(float)(look->postbits+look->phrasebits)/look->frames);*/
memset(look,0,sizeof(*look));
_ogg_free(look);
}
}
static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
int j,k;
int count=0;
int rangebits;
int maxposit=info->postlist[1];
int maxclass=-1;
/* save out partitions */
oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
for(j=0;j<info->partitions;j++){
oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
}
/* save out partition classes */
for(j=0;j<maxclass+1;j++){
oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
for(k=0;k<(1<<info->class_subs[j]);k++)
oggpack_write(opb,info->class_subbook[j][k]+1,8);
}
/* save out the post list */
oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
/* maxposit cannot legally be less than 1; this is encode-side, we
can assume our setup is OK */
oggpack_write(opb,ov_ilog(maxposit-1),4);
rangebits=ov_ilog(maxposit-1);
for(j=0,k=0;j<info->partitions;j++){
count+=info->class_dim[info->partitionclass[j]];
for(;k<count;k++)
oggpack_write(opb,info->postlist[k+2],rangebits);
}
}
static int icomp(const void *a,const void *b){
return(**(int **)a-**(int **)b);
}
static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
codec_setup_info *ci=vi->codec_setup;
int j,k,count=0,maxclass=-1,rangebits;
vorbis_info_floor1 *info=_ogg_calloc(1,sizeof(*info));
/* read partitions */
info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
for(j=0;j<info->partitions;j++){
info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
if(info->partitionclass[j]<0)goto err_out;
if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
}
/* read partition classes */
for(j=0;j<maxclass+1;j++){
info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
if(info->class_subs[j]<0)
goto err_out;
if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
goto err_out;
for(k=0;k<(1<<info->class_subs[j]);k++){
info->class_subbook[j][k]=oggpack_read(opb,8)-1;
if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
goto err_out;
}
}
/* read the post list */
info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
rangebits=oggpack_read(opb,4);
if(rangebits<0)goto err_out;
for(j=0,k=0;j<info->partitions;j++){
count+=info->class_dim[info->partitionclass[j]];
if(count>VIF_POSIT) goto err_out;
for(;k<count;k++){
int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
if(t<0 || t>=(1<<rangebits))
goto err_out;
}
}
info->postlist[0]=0;
info->postlist[1]=1<<rangebits;
/* don't allow repeated values in post list as they'd result in
zero-length segments */
{
int *sortpointer[VIF_POSIT+2];
for(j=0;j<count+2;j++)sortpointer[j]=info->postlist+j;
qsort(sortpointer,count+2,sizeof(*sortpointer),icomp);
for(j=1;j<count+2;j++)
if(*sortpointer[j-1]==*sortpointer[j])goto err_out;
}
return(info);
err_out:
floor1_free_info(info);
return(NULL);
}
static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
vorbis_info_floor *in){
int *sortpointer[VIF_POSIT+2];
vorbis_info_floor1 *info=(vorbis_info_floor1 *)in;
vorbis_look_floor1 *look=_ogg_calloc(1,sizeof(*look));
int i,j,n=0;
(void)vd;
look->vi=info;
look->n=info->postlist[1];
/* we drop each position value in-between already decoded values,
and use linear interpolation to predict each new value past the
edges. The positions are read in the order of the position
list... we precompute the bounding positions in the lookup. Of
course, the neighbors can change (if a position is declined), but
this is an initial mapping */
for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
n+=2;
look->posts=n;
/* also store a sorted position index */
for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
qsort(sortpointer,n,sizeof(*sortpointer),icomp);
/* points from sort order back to range number */
for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
/* points from range order to sorted position */
for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
/* we actually need the post values too */
for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
/* quantize values to multiplier spec */
switch(info->mult){
case 1: /* 1024 -> 256 */
look->quant_q=256;
break;
case 2: /* 1024 -> 128 */
look->quant_q=128;
break;
case 3: /* 1024 -> 86 */
look->quant_q=86;
break;
case 4: /* 1024 -> 64 */
look->quant_q=64;
break;
}
/* discover our neighbors for decode where we don't use fit flags
(that would push the neighbors outward) */
for(i=0;i<n-2;i++){
int lo=0;
int hi=1;
int lx=0;
int hx=look->n;
int currentx=info->postlist[i+2];
for(j=0;j<i+2;j++){
int x=info->postlist[j];
if(x>lx && x<currentx){
lo=j;
lx=x;
}
if(x<hx && x>currentx){
hi=j;
hx=x;
}
}
look->loneighbor[i]=lo;
look->hineighbor[i]=hi;
}
return(look);
}
static int render_point(int x0,int x1,int y0,int y1,int x){
y0&=0x7fff; /* mask off flag */
y1&=0x7fff;
{
int dy=y1-y0;
int adx=x1-x0;
int ady=abs(dy);
int err=ady*(x-x0);
int off=err/adx;
if(dy<0)return(y0-off);
return(y0+off);
}
}
static int vorbis_dBquant(const float *x){
int i= *x*7.3142857f+1023.5f;
if(i>1023)return(1023);
if(i<0)return(0);
return i;
}
static const float FLOOR1_fromdB_LOOKUP[256]={
1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
0.82788260F, 0.88168307F, 0.9389798F, 1.F,
};
static void render_line(int n, int x0,int x1,int y0,int y1,float *d){
int dy=y1-y0;
int adx=x1-x0;
int ady=abs(dy);
int base=dy/adx;
int sy=(dy<0?base-1:base+1);
int x=x0;
int y=y0;
int err=0;
ady-=abs(base*adx);
if(n>x1)n=x1;
if(x<n)
d[x]*=FLOOR1_fromdB_LOOKUP[y];
while(++x<n){
err=err+ady;
if(err>=adx){
err-=adx;
y+=sy;
}else{
y+=base;
}
d[x]*=FLOOR1_fromdB_LOOKUP[y];
}
}
static void render_line0(int n, int x0,int x1,int y0,int y1,int *d){
int dy=y1-y0;
int adx=x1-x0;
int ady=abs(dy);
int base=dy/adx;
int sy=(dy<0?base-1:base+1);
int x=x0;
int y=y0;
int err=0;
ady-=abs(base*adx);
if(n>x1)n=x1;
if(x<n)
d[x]=y;
while(++x<n){
err=err+ady;
if(err>=adx){
err-=adx;
y+=sy;
}else{
y+=base;
}
d[x]=y;
}
}
/* the floor has already been filtered to only include relevant sections */
static int accumulate_fit(const float *flr,const float *mdct,
int x0, int x1,lsfit_acc *a,
int n,vorbis_info_floor1 *info){
long i;
int xa=0,ya=0,x2a=0,y2a=0,xya=0,na=0, xb=0,yb=0,x2b=0,y2b=0,xyb=0,nb=0;
memset(a,0,sizeof(*a));
a->x0=x0;
a->x1=x1;
if(x1>=n)x1=n-1;
for(i=x0;i<=x1;i++){
int quantized=vorbis_dBquant(flr+i);
if(quantized){
if(mdct[i]+info->twofitatten>=flr[i]){
xa += i;
ya += quantized;
x2a += i*i;
y2a += quantized*quantized;
xya += i*quantized;
na++;
}else{
xb += i;
yb += quantized;
x2b += i*i;
y2b += quantized*quantized;
xyb += i*quantized;
nb++;
}
}
}
a->xa=xa;
a->ya=ya;
a->x2a=x2a;
a->y2a=y2a;
a->xya=xya;
a->an=na;
a->xb=xb;
a->yb=yb;
a->x2b=x2b;
a->y2b=y2b;
a->xyb=xyb;
a->bn=nb;
return(na);
}
static int fit_line(lsfit_acc *a,int fits,int *y0,int *y1,
vorbis_info_floor1 *info){
double xb=0,yb=0,x2b=0,y2b=0,xyb=0,bn=0;
int i;
int x0=a[0].x0;
int x1=a[fits-1].x1;
for(i=0;i<fits;i++){
double weight = (a[i].bn+a[i].an)*info->twofitweight/(a[i].an+1)+1.;
xb+=a[i].xb + a[i].xa * weight;
yb+=a[i].yb + a[i].ya * weight;
x2b+=a[i].x2b + a[i].x2a * weight;
y2b+=a[i].y2b + a[i].y2a * weight;
xyb+=a[i].xyb + a[i].xya * weight;
bn+=a[i].bn + a[i].an * weight;
}
if(*y0>=0){
xb+= x0;
yb+= *y0;
x2b+= x0 * x0;
y2b+= *y0 * *y0;
xyb+= *y0 * x0;
bn++;
}
if(*y1>=0){
xb+= x1;
yb+= *y1;
x2b+= x1 * x1;
y2b+= *y1 * *y1;
xyb+= *y1 * x1;
bn++;
}
{
double denom=(bn*x2b-xb*xb);
if(denom>0.){
double a=(yb*x2b-xyb*xb)/denom;
double b=(bn*xyb-xb*yb)/denom;
*y0=rint(a+b*x0);
*y1=rint(a+b*x1);
/* limit to our range! */
if(*y0>1023)*y0=1023;
if(*y1>1023)*y1=1023;
if(*y0<0)*y0=0;
if(*y1<0)*y1=0;
return 0;
}else{
*y0=0;
*y1=0;
return 1;
}
}
}
static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
const float *mdct,
vorbis_info_floor1 *info){
int dy=y1-y0;
int adx=x1-x0;
int ady=abs(dy);
int base=dy/adx;
int sy=(dy<0?base-1:base+1);
int x=x0;
int y=y0;
int err=0;
int val=vorbis_dBquant(mask+x);
int mse=0;
int n=0;
ady-=abs(base*adx);
mse=(y-val);
mse*=mse;
n++;
if(mdct[x]+info->twofitatten>=mask[x]){
if(y+info->maxover<val)return(1);
if(y-info->maxunder>val)return(1);
}
while(++x<x1){
err=err+ady;
if(err>=adx){
err-=adx;
y+=sy;
}else{
y+=base;
}
val=vorbis_dBquant(mask+x);
mse+=((y-val)*(y-val));
n++;
if(mdct[x]+info->twofitatten>=mask[x]){
if(val){
if(y+info->maxover<val)return(1);
if(y-info->maxunder>val)return(1);
}
}
}
if(info->maxover*info->maxover/n>info->maxerr)return(0);
if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
if(mse/n>info->maxerr)return(1);
return(0);
}
static int post_Y(int *A,int *B,int pos){
if(A[pos]<0)
return B[pos];
if(B[pos]<0)
return A[pos];
return (A[pos]+B[pos])>>1;
}
int *floor1_fit(vorbis_block *vb,vorbis_look_floor1 *look,
const float *logmdct, /* in */
const float *logmask){
long i,j;
vorbis_info_floor1 *info=look->vi;
long n=look->n;
long posts=look->posts;
long nonzero=0;
lsfit_acc fits[VIF_POSIT+1];
int fit_valueA[VIF_POSIT+2]; /* index by range list position */
int fit_valueB[VIF_POSIT+2]; /* index by range list position */
int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
int hineighbor[VIF_POSIT+2];
int *output=NULL;
int memo[VIF_POSIT+2];
for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
/* quantize the relevant floor points and collect them into line fit
structures (one per minimal division) at the same time */
if(posts==0){
nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
}else{
for(i=0;i<posts-1;i++)
nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
look->sorted_index[i+1],fits+i,
n,info);
}
if(nonzero){
/* start by fitting the implicit base case.... */
int y0=-200;
int y1=-200;
fit_line(fits,posts-1,&y0,&y1,info);
fit_valueA[0]=y0;
fit_valueB[0]=y0;
fit_valueB[1]=y1;
fit_valueA[1]=y1;
/* Non degenerate case */
/* start progressive splitting. This is a greedy, non-optimal
algorithm, but simple and close enough to the best
answer. */
for(i=2;i<posts;i++){
int sortpos=look->reverse_index[i];
int ln=loneighbor[sortpos];
int hn=hineighbor[sortpos];
/* eliminate repeat searches of a particular range with a memo */
if(memo[ln]!=hn){
/* haven't performed this error search yet */
int lsortpos=look->reverse_index[ln];
int hsortpos=look->reverse_index[hn];
memo[ln]=hn;
{
/* A note: we want to bound/minimize *local*, not global, error */
int lx=info->postlist[ln];
int hx=info->postlist[hn];
int ly=post_Y(fit_valueA,fit_valueB,ln);
int hy=post_Y(fit_valueA,fit_valueB,hn);
if(ly==-1 || hy==-1){
exit(1);
}
if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
/* outside error bounds/begin search area. Split it. */
int ly0=-200;
int ly1=-200;
int hy0=-200;
int hy1=-200;
int ret0=fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1,info);
int ret1=fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1,info);
if(ret0){
ly0=ly;
ly1=hy0;
}
if(ret1){
hy0=ly1;
hy1=hy;
}
if(ret0 && ret1){
fit_valueA[i]=-200;
fit_valueB[i]=-200;
}else{
/* store new edge values */
fit_valueB[ln]=ly0;
if(ln==0)fit_valueA[ln]=ly0;
fit_valueA[i]=ly1;
fit_valueB[i]=hy0;
fit_valueA[hn]=hy1;
if(hn==1)fit_valueB[hn]=hy1;
if(ly1>=0 || hy0>=0){
/* store new neighbor values */
for(j=sortpos-1;j>=0;j--)
if(hineighbor[j]==hn)
hineighbor[j]=i;
else
break;
for(j=sortpos+1;j<posts;j++)
if(loneighbor[j]==ln)
loneighbor[j]=i;
else
break;
}
}
}else{
fit_valueA[i]=-200;
fit_valueB[i]=-200;
}
}
}
}
output=_vorbis_block_alloc(vb,sizeof(*output)*posts);
output[0]=post_Y(fit_valueA,fit_valueB,0);
output[1]=post_Y(fit_valueA,fit_valueB,1);
/* fill in posts marked as not using a fit; we will zero
back out to 'unused' when encoding them so long as curve
interpolation doesn't force them into use */
for(i=2;i<posts;i++){
int ln=look->loneighbor[i-2];
int hn=look->hineighbor[i-2];
int x0=info->postlist[ln];
int x1=info->postlist[hn];
int y0=output[ln];
int y1=output[hn];
int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
int vx=post_Y(fit_valueA,fit_valueB,i);
if(vx>=0 && predicted!=vx){
output[i]=vx;
}else{
output[i]= predicted|0x8000;
}
}
}
return(output);
}
int *floor1_interpolate_fit(vorbis_block *vb,vorbis_look_floor1 *look,
int *A,int *B,
int del){
long i;
long posts=look->posts;
int *output=NULL;
if(A && B){
output=_vorbis_block_alloc(vb,sizeof(*output)*posts);
/* overly simpleminded--- look again post 1.2 */
for(i=0;i<posts;i++){
output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
}
}
return(output);
}
int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
vorbis_look_floor1 *look,
int *post,int *ilogmask){
long i,j;
vorbis_info_floor1 *info=look->vi;
long posts=look->posts;
codec_setup_info *ci=vb->vd->vi->codec_setup;
int out[VIF_POSIT+2];
static_codebook **sbooks=ci->book_param;
codebook *books=ci->fullbooks;
/* quantize values to multiplier spec */
if(post){
for(i=0;i<posts;i++){
int val=post[i]&0x7fff;
switch(info->mult){
case 1: /* 1024 -> 256 */
val>>=2;
break;
case 2: /* 1024 -> 128 */
val>>=3;
break;
case 3: /* 1024 -> 86 */
val/=12;
break;
case 4: /* 1024 -> 64 */
val>>=4;
break;
}
post[i]=val | (post[i]&0x8000);
}
out[0]=post[0];
out[1]=post[1];
/* find prediction values for each post and subtract them */
for(i=2;i<posts;i++){
int ln=look->loneighbor[i-2];
int hn=look->hineighbor[i-2];
int x0=info->postlist[ln];
int x1=info->postlist[hn];
int y0=post[ln];
int y1=post[hn];
int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
if((post[i]&0x8000) || (predicted==post[i])){
post[i]=predicted|0x8000; /* in case there was roundoff jitter
in interpolation */
out[i]=0;
}else{
int headroom=(look->quant_q-predicted<predicted?
look->quant_q-predicted:predicted);
int val=post[i]-predicted;
/* at this point the 'deviation' value is in the range +/- max
range, but the real, unique range can always be mapped to
only [0-maxrange). So we want to wrap the deviation into
this limited range, but do it in the way that least screws
an essentially gaussian probability distribution. */
if(val<0)
if(val<-headroom)
val=headroom-val-1;
else
val=-1-(val<<1);
else
if(val>=headroom)
val= val+headroom;
else
val<<=1;
out[i]=val;
post[ln]&=0x7fff;
post[hn]&=0x7fff;
}
}
/* we have everything we need. pack it out */
/* mark nontrivial floor */
oggpack_write(opb,1,1);
/* beginning/end post */
look->frames++;
look->postbits+=ov_ilog(look->quant_q-1)*2;
oggpack_write(opb,out[0],ov_ilog(look->quant_q-1));
oggpack_write(opb,out[1],ov_ilog(look->quant_q-1));
/* partition by partition */
for(i=0,j=2;i<info->partitions;i++){
int class=info->partitionclass[i];
int cdim=info->class_dim[class];
int csubbits=info->class_subs[class];
int csub=1<<csubbits;
int bookas[8]={0,0,0,0,0,0,0,0};
int cval=0;
int cshift=0;
int k,l;
/* generate the partition's first stage cascade value */
if(csubbits){
int maxval[8]={0,0,0,0,0,0,0,0}; /* gcc's static analysis
issues a warning without
initialization */
for(k=0;k<csub;k++){
int booknum=info->class_subbook[class][k];
if(booknum<0){
maxval[k]=1;
}else{
maxval[k]=sbooks[info->class_subbook[class][k]]->entries;
}
}
for(k=0;k<cdim;k++){
for(l=0;l<csub;l++){
int val=out[j+k];
if(val<maxval[l]){
bookas[k]=l;
break;
}
}
cval|= bookas[k]<<cshift;
cshift+=csubbits;
}
/* write it */
look->phrasebits+=
vorbis_book_encode(books+info->class_book[class],cval,opb);
#ifdef TRAIN_FLOOR1
{
FILE *of;
char buffer[80];
sprintf(buffer,"line_%dx%ld_class%d.vqd",
vb->pcmend/2,posts-2,class);
of=fopen(buffer,"a");
fprintf(of,"%d\n",cval);
fclose(of);
}
#endif
}
/* write post values */
for(k=0;k<cdim;k++){
int book=info->class_subbook[class][bookas[k]];
if(book>=0){
/* hack to allow training with 'bad' books */
if(out[j+k]<(books+book)->entries)
look->postbits+=vorbis_book_encode(books+book,
out[j+k],opb);
/*else
fprintf(stderr,"+!");*/
#ifdef TRAIN_FLOOR1
{
FILE *of;
char buffer[80];
sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
vb->pcmend/2,posts-2,class,bookas[k]);
of=fopen(buffer,"a");
fprintf(of,"%d\n",out[j+k]);
fclose(of);
}
#endif
}
}
j+=cdim;
}
{
/* generate quantized floor equivalent to what we'd unpack in decode */
/* render the lines */
int hx=0;
int lx=0;
int ly=post[0]*info->mult;
int n=ci->blocksizes[vb->W]/2;
for(j=1;j<look->posts;j++){
int current=look->forward_index[j];
int hy=post[current]&0x7fff;
if(hy==post[current]){
hy*=info->mult;
hx=info->postlist[current];
render_line0(n,lx,hx,ly,hy,ilogmask);
lx=hx;
ly=hy;
}
}
for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
return(1);
}
}else{
oggpack_write(opb,0,1);
memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
return(0);
}
}
static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
vorbis_info_floor1 *info=look->vi;
codec_setup_info *ci=vb->vd->vi->codec_setup;
int i,j,k;
codebook *books=ci->fullbooks;
/* unpack wrapped/predicted values from stream */
if(oggpack_read(&vb->opb,1)==1){
int *fit_value=_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
fit_value[0]=oggpack_read(&vb->opb,ov_ilog(look->quant_q-1));
fit_value[1]=oggpack_read(&vb->opb,ov_ilog(look->quant_q-1));
/* partition by partition */
for(i=0,j=2;i<info->partitions;i++){
int class=info->partitionclass[i];
int cdim=info->class_dim[class];
int csubbits=info->class_subs[class];
int csub=1<<csubbits;
int cval=0;
/* decode the partition's first stage cascade value */
if(csubbits){
cval=vorbis_book_decode(books+info->class_book[class],&vb->opb);
if(cval==-1)goto eop;
}
for(k=0;k<cdim;k++){
int book=info->class_subbook[class][cval&(csub-1)];
cval>>=csubbits;
if(book>=0){
if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
goto eop;
}else{
fit_value[j+k]=0;
}
}
j+=cdim;
}
/* unwrap positive values and reconsitute via linear interpolation */
for(i=2;i<look->posts;i++){
int predicted=render_point(info->postlist[look->loneighbor[i-2]],
info->postlist[look->hineighbor[i-2]],
fit_value[look->loneighbor[i-2]],
fit_value[look->hineighbor[i-2]],
info->postlist[i]);
int hiroom=look->quant_q-predicted;
int loroom=predicted;
int room=(hiroom<loroom?hiroom:loroom)<<1;
int val=fit_value[i];
if(val){
if(val>=room){
if(hiroom>loroom){
val = val-loroom;
}else{
val = -1-(val-hiroom);
}
}else{
if(val&1){
val= -((val+1)>>1);
}else{
val>>=1;
}
}
fit_value[i]=(val+predicted)&0x7fff;
fit_value[look->loneighbor[i-2]]&=0x7fff;
fit_value[look->hineighbor[i-2]]&=0x7fff;
}else{
fit_value[i]=predicted|0x8000;
}
}
return(fit_value);
}
eop:
return(NULL);
}
static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
float *out){
vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
vorbis_info_floor1 *info=look->vi;
codec_setup_info *ci=vb->vd->vi->codec_setup;
int n=ci->blocksizes[vb->W]/2;
int j;
if(memo){
/* render the lines */
int *fit_value=(int *)memo;
int hx=0;
int lx=0;
int ly=fit_value[0]*info->mult;
/* guard lookup against out-of-range values */
ly=(ly<0?0:ly>255?255:ly);
for(j=1;j<look->posts;j++){
int current=look->forward_index[j];
int hy=fit_value[current]&0x7fff;
if(hy==fit_value[current]){
hx=info->postlist[current];
hy*=info->mult;
/* guard lookup against out-of-range values */
hy=(hy<0?0:hy>255?255:hy);
render_line(n,lx,hx,ly,hy,out);
lx=hx;
ly=hy;
}
}
for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
return(1);
}
memset(out,0,sizeof(*out)*n);
return(0);
}
/* export hooks */
const vorbis_func_floor floor1_exportbundle={
&floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
&floor1_free_look,&floor1_inverse1,&floor1_inverse2
};
| 28.529899 | 79 | 0.574584 |
cf995f47bb647cda9e1271cb10b9372b82fda93d | 4,800 | h | C | mediapipe/calculators/tflite/tflite_inference_calculator_test_common.h | virdio/mediapipe | 4a20e9909d55838d5630366ce719844cf06ae85c | [
"Apache-2.0"
] | 17,242 | 2019-06-16T23:19:19.000Z | 2022-03-31T20:19:41.000Z | mediapipe/calculators/tflite/tflite_inference_calculator_test_common.h | virdio/mediapipe | 4a20e9909d55838d5630366ce719844cf06ae85c | [
"Apache-2.0"
] | 3,148 | 2019-06-23T19:45:17.000Z | 2022-03-31T16:53:40.000Z | mediapipe/calculators/tflite/tflite_inference_calculator_test_common.h | virdio/mediapipe | 4a20e9909d55838d5630366ce719844cf06ae85c | [
"Apache-2.0"
] | 3,712 | 2019-06-18T20:18:54.000Z | 2022-03-31T15:46:46.000Z | // Copyright 2019 The MediaPipe 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
//
// 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 MEDIAPIPE_CALCULATORS_TFLITE_TFLITE_INFERENCE_CALCULATOR_TEST_H_
#define MEDIAPIPE_CALCULATORS_TFLITE_TFLITE_INFERENCE_CALCULATOR_TEST_H_
#include <memory>
#include <string>
#include <vector>
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"
#include "mediapipe/calculators/tflite/tflite_inference_calculator.pb.h"
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/calculator_runner.h"
#include "mediapipe/framework/deps/file_path.h"
#include "mediapipe/framework/port/gmock.h"
#include "mediapipe/framework/port/gtest.h"
#include "mediapipe/framework/port/integral_types.h"
#include "mediapipe/framework/port/parse_text_proto.h"
#include "mediapipe/framework/port/status_matchers.h" // NOLINT
#include "mediapipe/framework/tool/validate_type.h"
#include "tensorflow/lite/error_reporter.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/portable_type_to_tflitetype.h"
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#endif // defined(__APPLE__)
namespace mediapipe {
using ::tflite::Interpreter;
template <typename T>
void DoSmokeTest(const std::string& graph_proto) {
const int width = 8;
const int height = 8;
const int channels = 3;
static_assert(std::is_same_v<T, float> || std::is_same_v<T, uint8>,
"Only float & uint8 currently supported.");
// Prepare interpreter and input tensor.
std::unique_ptr<Interpreter> interpreter(new Interpreter);
ASSERT_NE(interpreter, nullptr);
interpreter->AddTensors(1);
interpreter->SetInputs({0});
interpreter->SetOutputs({0});
TfLiteQuantization quant;
if (std::is_integral_v<T>) {
auto* affine_quant = static_cast<TfLiteAffineQuantization*>(
malloc(sizeof(TfLiteAffineQuantization)));
affine_quant->scale = TfLiteFloatArrayCreate(1);
affine_quant->zero_point = TfLiteIntArrayCreate(1);
affine_quant->scale->data[0] = 1.0;
affine_quant->zero_point->data[0] = 0;
quant.type = kTfLiteAffineQuantization;
quant.params = affine_quant;
}
interpreter->SetTensorParametersReadWrite(0, tflite::typeToTfLiteType<T>(),
"", {3}, quant);
int t = interpreter->inputs()[0];
TfLiteTensor* input_tensor = interpreter->tensor(t);
interpreter->ResizeInputTensor(t, {width, height, channels});
interpreter->AllocateTensors();
T* input_tensor_buffer = tflite::GetTensorData<T>(input_tensor);
ASSERT_NE(input_tensor_buffer, nullptr);
for (int i = 0; i < width * height * channels - 1; i++) {
input_tensor_buffer[i] = 1;
}
auto input_vec = absl::make_unique<std::vector<TfLiteTensor>>();
input_vec->emplace_back(*input_tensor);
// Prepare single calculator graph to and wait for packets.
CalculatorGraphConfig graph_config =
ParseTextProtoOrDie<CalculatorGraphConfig>(graph_proto);
std::vector<Packet> output_packets;
tool::AddVectorSink("tensor_out", &graph_config, &output_packets);
CalculatorGraph graph(graph_config);
MP_ASSERT_OK(graph.StartRun({}));
// Push the tensor into the graph.
MP_ASSERT_OK(graph.AddPacketToInputStream(
"tensor_in", Adopt(input_vec.release()).At(Timestamp(0))));
// Wait until the calculator done processing.
MP_ASSERT_OK(graph.WaitUntilIdle());
ASSERT_EQ(1, output_packets.size());
// Get and process results.
const std::vector<TfLiteTensor>& result_vec =
output_packets[0].Get<std::vector<TfLiteTensor>>();
ASSERT_EQ(1, result_vec.size());
const TfLiteTensor* result = &result_vec[0];
const T* result_buffer = tflite::GetTensorData<T>(result);
ASSERT_NE(result_buffer, nullptr);
for (int i = 0; i < width * height * channels - 1; i++) {
ASSERT_EQ(3, result_buffer[i]);
}
// Fully close graph at end, otherwise calculator+tensors are destroyed
// after calling WaitUntilDone().
MP_ASSERT_OK(graph.CloseInputStream("tensor_in"));
MP_ASSERT_OK(graph.WaitUntilDone());
}
} // namespace mediapipe
#endif // MEDIAPIPE_CALCULATORS_TFLITE_TFLITE_INFERENCE_CALCULATOR_TEST_H_
| 37.209302 | 77 | 0.744375 |
65f794b781e42b973c94c2e38e82ade06d941db2 | 1,693 | h | C | include/learner.h | Phantomape/paxos | d88ab88fa5b6c7d74b508580729c4dea4de6f180 | [
"MIT"
] | null | null | null | include/learner.h | Phantomape/paxos | d88ab88fa5b6c7d74b508580729c4dea4de6f180 | [
"MIT"
] | 5 | 2018-05-30T03:09:10.000Z | 2018-06-02T22:56:05.000Z | include/learner.h | Phantomape/paxos | d88ab88fa5b6c7d74b508580729c4dea4de6f180 | [
"MIT"
] | null | null | null | #pragma once
#include "base.h"
#include "checkpoint_mgr.h"
#include "ioloop.h"
#include "learner_synchronizer.h"
#include "paxos_log.h"
namespace paxos {
class Acceptor;
class CheckpoingMgr;
class StateMachineFac;
class Learner : public Base {
public:
Learner(
const Config* config,
const Communicate* communicate,
const Instance* instance,
const Acceptor* acceptor,
const LogStorage* log_storage,
const IoLoop* ioloop,
const CheckpointMgr* checkpoint_mgr,
const StateMachineFac* state_machine_fac
);
~Learner();
const uint64_t GetLatestInstanceID();
virtual void InitInstance();
const bool IsLearned();
void InitLearnerSynchronizer();
void LearnValueWithoutWrite(
const uint64_t instance_id,
const std::string & val,
const uint32_t checksum
);
void TransmitToFollower();
void ProposerSendSuccess(
const uint64_t instance_id,
const uint64_t proposal_id
);
void OnProposerSendSuccess(const PaxosMsg& paxos_msg);
void Stop();
private:
Acceptor* acceptor_;
LearnerSynchronizer learner_synchronizer_;
uint64_t highest_instance_id_;
IoLoop* ioloop_;
std::string learned_val_;
bool is_learned_;
uint32_t new_checksum_;
Config* config_;
PaxosLog paxos_log_;
uint32_t ask_for_learn_noop_timer_id_;
uint64_t highest_seen_instance_id_;
uint64_t highest_seen_instance_id_from_node_id_;
bool is_im_learning_;
uint64_t last_ack_instance_id_;
CheckpointMgr * checkpoint_mgr_;
StateMachineFac * state_machine_fac_;
};
} | 20.646341 | 58 | 0.685765 |
049b4a41a48332ece7e1f46b8c3b63e9218795c1 | 2,036 | h | C | mindspore/lite/tools/converter/legacy_optimizer/graph/select_pass.h | GuoSuiming/mindspore | 48afc4cfa53d970c0b20eedfb46e039db2a133d5 | [
"Apache-2.0"
] | 4 | 2021-01-26T09:14:01.000Z | 2021-01-26T09:17:24.000Z | mindspore/lite/tools/converter/legacy_optimizer/graph/select_pass.h | forwhat461/mindspore | 59a277756eb4faad9ac9afcc7fd526e8277d4994 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/converter/legacy_optimizer/graph/select_pass.h | forwhat461/mindspore | 59a277756eb4faad9ac9afcc7fd526e8277d4994 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies 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.
*/
#ifndef MINDSPORE_PREDICT_SELECT_PASS_H
#define MINDSPORE_PREDICT_SELECT_PASS_H
#include <unordered_map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <functional>
#include "tools/common/graph_util.h"
#include "tools/converter/optimizer.h"
using mindspore::schema::TensorT;
namespace mindspore {
namespace lite {
class SelectPass : public GraphPass {
public:
explicit SelectPass(schema::MetaGraphT *graph) : graph_(graph) {}
~SelectPass() override = default;
STATUS Run(schema::MetaGraphT *graph) override;
STATUS RemoveSelectNodes();
private:
std::vector<uint32_t> select_indices_;
schema::MetaGraphT *graph_ = nullptr;
};
class SingleSelectPass {
public:
SingleSelectPass(schema::MetaGraphT *graph, const size_t &node_index)
: graph_(graph), select_node_index_(node_index) {}
~SingleSelectPass() = default;
STATUS Run();
private:
STATUS Init();
size_t InitThisGraphIndex();
STATUS ConvertSelectToSwitch();
std::unique_ptr<schema::TensorT> NewTensor(const std::unique_ptr<schema::TensorT> &in_tensor);
void RemoveUselessNode(schema::CNodeT *partial_node);
schema::MetaGraphT *graph_ = nullptr;
schema::CNodeT *select_node_ = nullptr;
size_t select_node_index_ = -1;
int32_t this_subgraph_index_ = -1;
const size_t kSelectMinInputSize = 2;
const size_t kSelectMinOutputSize = 2;
};
} // namespace lite
} // namespace mindspore
#endif
| 30.848485 | 96 | 0.751473 |
8014720e3095a256591e602ba936ee8142c6d77a | 7,675 | h | C | _old_reference_code/src/STRIPS_test.h | alexandresoaresilva/STRIPS_prg | ada84083a8b4f96036261669092bcf3cb4539e73 | [
"MIT"
] | null | null | null | _old_reference_code/src/STRIPS_test.h | alexandresoaresilva/STRIPS_prg | ada84083a8b4f96036261669092bcf3cb4539e73 | [
"MIT"
] | null | null | null | _old_reference_code/src/STRIPS_test.h | alexandresoaresilva/STRIPS_prg | ada84083a8b4f96036261669092bcf3cb4539e73 | [
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// /* STRIPS_program checker*/
//
// does: returns true if input (vector of strings) is a tokenized STRIPS instance
// Written by: Alexandre Soares da Silva
// Date: April 2, 2017
// Submitted as assignment 2 solution for dr. Rushton's CS 2413 - Data Structures class
// (Texas Tech University)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
#include <vector>
#include <string>
using namespace std;
vector<string> slice(const vector<string> &s, int loBound, int upBound);
bool STRIPS_program(vector<string> s);
bool initial_state_declaration(vector<string> s);
bool goal_declaration(vector<string> s);
bool action_set(vector<string> s);
bool NEaction_list(vector<string> s);
bool action_declaration(vector<string> s);
bool action_prototype(vector<string> s);
bool preconditions_declaration(vector<string> s);
bool effects_declaration(vector<string> s);
bool NEliteral_list(vector<string> s);
bool literal_list(vector<string> s);
bool literal(vector<string> s);
bool atom_list(vector<string> s);
bool NEatom_list(vector<string> s);
bool atomic_statement(vector<string> s);
bool symbol_list(vector<string> s);
bool NEsymbol_list(vector<string> s);
bool symbol(vector<string> s);
bool STRIPS_keyword(vector<string> s);
//helper function to slice the vector
vector<string> slice(const vector<string> &s, int loBound, int upBound)
{
vector<string> sliced;
for (int i = static_cast<uint16_t>(loBound); i < static_cast<uint16_t>(upBound); i++)
{
sliced.push_back(s[i]);
}
return sliced;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MAIN function- starts the recursive descent calls
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool STRIPS_program(vector<string> s)
{
if (s.size() > 7) // minimum list: (0. "Initial", 1. "state", 2. ":", 3. "Goal",4. ":",5. "Actions",6. ":",7. NEaction_list)
{
int initStateEndIndex(0), goalDeclEndIndex(0);
bool initStateTrue(0), goalDeclTrue(0);
for (int i = 1; i < static_cast<uint16_t>(s.size() - 4); i++) //so avoids the minimum list for Goal & Actions
if (initial_state_declaration(slice(s, 0, i)) && s[i] == "Goal") //i and NOT i+1 because slicing happens at i-1
{
initStateEndIndex = i;//it will evaluate to true before reaching
initStateTrue = 1;
break;
}
if (initStateTrue)
for (int j = initStateEndIndex; j < static_cast<uint16_t>(s.size() - 2); j++) //s.size()-2 because "Actions",":",NEaction_list
if (goal_declaration(slice(s, initStateEndIndex, j)))
if (s[j] == "Actions")
{
goalDeclEndIndex = j;
goalDeclTrue = 1;
break;
}
if (initStateTrue && goalDeclTrue)
for (int z = goalDeclEndIndex; z < static_cast<uint16_t>(s.size()); z++)
if (action_set(slice(s, z, s.size())))return true;
}
return false;
}
bool initial_state_declaration(vector<string> s)
{
if (s.size() >= 3) // size >= 3 to avoid crashing when testing smaller parts of the strips vector
if (s[0] == "Initial" && s[1] == "state" && s[2] == ":" && atom_list(slice(s, 3, s.size())))return true;
return false;
}
bool action_set(vector<string> s) //might need adjustment in loop condition i <=
{
if (s.size() >= 3 && (s[0] == "Actions" && s[1] == ":"))
if (NEaction_list(slice(s, 2, s.size())))return true;
return false;
}
bool action_declaration(vector<string> s)
{
if (s.size() >= 3)
{
for (int i = 1; i < static_cast<uint16_t>(s.size()); i++)
if (action_prototype(slice(s, 0, i)))
for (int j = 2; j < static_cast<uint16_t>(s.size()); j++) //they have to grow separatelly
if (preconditions_declaration(slice(s, i, j)) && effects_declaration(slice(s, j, s.size())))return true;
}
return false;
}
bool action_prototype(vector<string> s)
{
//for (int i = 1; i < s.size(); i++) //might need adjustment in loop condition i <=
if (s[0] == "_" && s[s.size() - 1] == "_")
if (atomic_statement(slice(s, 1, s.size() - 1)))return true;
return false;
}
bool preconditions_declaration(vector<string> s)
{
if (s.size()>1 && (s[0] == "Preconditions" && s[1] == ":"))
if (literal_list(slice(s, 2, s.size())))return true;
return false;
}
bool effects_declaration(vector<string> s)
{
if (s.size()>1 && (s[0] == "Effects" && s[1] == ":"))
if (literal_list(slice(s, 2, s.size())))return true;
return false;
}
bool goal_declaration(vector<string> s) //NOTE: declaration on the Wikipedia's example is followed by "state"; here, it's not.
{
if (s.size() >= 2)
if (s[0] == "Goal" && s[1] == ":" && literal_list(slice(s, 2, s.size())))return true;
//if ( s[0] == "Goal" && s[1] == "state" && s[2] == ":" && literal_list(slice(s,3,s.size())) )return true; // WITH "state"
return false;
}
bool NEaction_list(vector<string> s) //might need adjustment in loop condition i <=
{
if (s.size()> 0)
{
if (action_declaration(s))return true;
else
{
for (int i = 1; i < static_cast<uint16_t>(s.size()); i++)
{
if (action_declaration(slice(s, 0, i)) && NEaction_list(slice(s, i, s.size())))return true;
}
}
}
return false;
}
bool NEliteral_list(vector<string> s) //might need adjustment in loop condition i <=
{
if (literal(s))return true;
else
for (int i = 1; i < static_cast<uint16_t>(s.size() - 1); i++)
if (s[i] == ",")
if (literal(slice(s, 0, i)) && NEliteral_list(slice(s, i + 1, s.size())))return true;
return false;
}
bool literal_list(vector<string> s)// I don't know if this will actually work
{
for (int i = 1; i < static_cast<uint16_t>(s.size()); i++)
{
if (s.empty() || NEliteral_list(s))
return true;
}
return false;
}
bool literal(vector<string> s)// I don't know if this will actually work
{
if (atomic_statement(s))return true;
else if ( s.size() > 0 && (s[0] == "not" || s[0] == "NOT") && atomic_statement(slice(s, 1, s.size())))
return true;
return false;
}
bool NEatom_list(vector<string> s)
{
if (atomic_statement(s)) return true;
else
{
for (int i = 1; i < static_cast<uint16_t>(s.size() - 1); i++)
{
if (s[i] == ",")
if (atomic_statement(slice(s, 0, i)) && NEatom_list(slice(s, i + 1, s.size())))return true;
}
}
return false;
}
bool atom_list(vector<string> s)// I don't know if this will actually work
{
for (int i = 1; i < static_cast<uint16_t>(s.size()); i++)
{
if (s.empty() || NEatom_list(s))
return true;
}
// if ( slice(s,0,1).empty() || NEliteral_list(slice(s,0,1)))
// return true;
return false;
}
bool atomic_statement(vector<string> s)
{
if (s.size() >= 4)
if (symbol(slice(s, 0, 1)) && s[1] == "(" && s[s.size() - 1] == ")")
if (symbol_list(slice(s, 2, s.size() - 1)))return true;
return false;
}
bool NEsymbol_list(vector<string> s)
{
if (s.size() == 1 && symbol(slice(s, 0, 1))) return true;
else if (s.size() >= 3 && symbol(slice(s, 0, 1)) && s[1] == ",")
if (NEsymbol_list(slice(s, 2, s.size())))return true;
return false;
}
bool symbol_list(vector<string> s)// I don't know if this will actually work
{
return (s.empty() || NEsymbol_list(s));
}
bool symbol(vector<string> s)
{
return(!s.empty() && s.size() == 1 && !STRIPS_keyword(s));
}
bool STRIPS_keyword(vector<string> s)//s needs to be sliced to be used in here
{
if ((!s.empty() && s.size() == 1) && (s[0] == "Initial" || s[0] == "state" || s[0] == "Goal" || s[0] == "Actions" || s[0] == "Preconditions" || s[0] == "Effects" || s[0] == "not" || s[0] == "NOT"))
return true;
return false;
}
| 31.072874 | 198 | 0.595309 |
b78b47e03c161092f13a049d1228e647915a119f | 10,122 | h | C | Bin/iOS/DConnectSDK.framework/Versions/A/Headers/DConnectSettingsProfile.h | nokok/DeviceConnect | fa93a692f3ad231f869304b02a17e96326205eb0 | [
"MIT"
] | 1 | 2015-11-08T09:17:26.000Z | 2015-11-08T09:17:26.000Z | sourcecode/iOS/dConnectSDK/dConnectSDKSample/DConnectSDK.framework/Versions/Current/Headers/DConnectSettingsProfile.h | nokok/DeviceConnect | fa93a692f3ad231f869304b02a17e96326205eb0 | [
"MIT"
] | null | null | null | sourcecode/iOS/dConnectSDK/dConnectSDKSample/DConnectSDK.framework/Versions/Current/Headers/DConnectSettingsProfile.h | nokok/DeviceConnect | fa93a692f3ad231f869304b02a17e96326205eb0 | [
"MIT"
] | null | null | null | //
// DConnectSettingsProfile.h
// DConnectSDK
//
// Copyright (c) 2014 NTT DOCOMO,INC.
// Released under the MIT license
// http://opensource.org/licenses/mit-license.php
//
/*!
@file
@brief Settingsプロファイルを実装するための機能を提供する。
@author NTT DOCOMO
*/
#import <DConnectSDK/DConnectProfile.h>
/*!
@brief プロファイル名: settings。
*/
extern NSString *const DConnectSettingsProfileName;
/*!
@brief インターフェース: sound。
*/
extern NSString *const DConnectSettingsProfileInterfaceSound;
/*!
@brief インターフェース: display。
*/
extern NSString *const DConnectSettingsProfileInterfaceDisplay;
/*!
@brief アトリビュート: volume。
*/
extern NSString *const DConnectSettingsProfileAttrVolume;
/*!
@brief アトリビュート: date。
*/
extern NSString *const DConnectSettingsProfileAttrDate;
/*!
@brief アトリビュート: light。
*/
extern NSString *const DConnectSettingsProfileAttrLight;
/*!
@brief アトリビュート: sleep。
*/
extern NSString *const DConnectSettingsProfileAttrSleep;
/*!
@brief パラメータ: kind。
*/
extern NSString *const DConnectSettingsProfileParamKind;
/*!
@brief パラメータ: level。
*/
extern NSString *const DConnectSettingsProfileParamLevel;
/*!
@brief パラメータ: date。
*/
extern NSString *const DConnectSettingsProfileParamDate;
/*!
@brief パラメータ: time。
*/
extern NSString *const DConnectSettingsProfileParamTime;
/*!
@brief ボリュームのレベルの最大値: 1.0。
*/
extern const double DConnectSettingsProfileMaxLevel;
/*!
@brief ボリュームのレベルの最小値: 0.0。
*/
extern const double DConnectSettingsProfileMinLevel;
/*!
@enum DConnectSettingsProfileVolumeKind
@brief 音量の種別定数。
*/
typedef NS_ENUM(NSInteger, DConnectSettingsProfileVolumeKind) {
DConnectSettingsProfileVolumeKindUnknown = -1, /*!< 未定義値 */
DConnectSettingsProfileVolumeKindAlarm = 1, /*!< アラーム */
DConnectSettingsProfileVolumeKindCall, /*!< 通話音 */
DConnectSettingsProfileVolumeKindRingtone, /*!< 着信音 */
DConnectSettingsProfileVolumeKindMail, /*!< メール着信音 */
DConnectSettingsProfileVolumeKindOther, /*!< その他SNS等の着信音 */
DConnectSettingsProfileVolumeKindMediaPlay, /*!< メディアプレーヤーの音量 */
};
@class DConnectSettingsProfile;
/*!
@protocol DConnectSettingsProfileDelegate
@brief Settings Profileの各APIリクエスト通知用デリゲート。
Settings Profileの各APIへのリクエスト受信通知を受け取るデリゲート。
*/
@protocol DConnectSettingsProfileDelegate <NSObject>
@optional
#pragma mark - Get Methods
/*!
@brief デバイス音量取得リクエストを受け取ったことをデリゲートに通知する。
profileがデバイスの音量取得リクエストを受け取ったことをデリゲートに通知する。<br>
実装されない場合には、Not supportのエラーが返却される。
<p>
[対応するAPI] Volume Settings API [GET]
</p>
@param[in] profile プロファイル
@param[in] request リクエストパラメータ
@param[in,out] response レスポンスパラメータ
@param[in] deviceId デバイスID
@param[in] kind 種別
@retval YES レスポンスパラメータを返却する。
@retval NO レスポンスパラメータを返却しないので、@link DConnectManager::sendResponse: @endlinkで返却すること。
*/
- (BOOL) profile:(DConnectSettingsProfile *)profile didReceiveGetVolumeRequest:(DConnectRequestMessage *)request
response:(DConnectResponseMessage *)response
deviceId:(NSString *)deviceId
kind:(DConnectSettingsProfileVolumeKind)kind;
/*!
@brief デバイスの日時取得リクエストを受け取ったことをデリゲートに通知する。
profileがデバイスの日時取得リクエストを受け取ったことをデリゲートに通知する。<br>
実装されない場合には、Not supportのエラーが返却される。
<p>
[対応するAPI] Date Settings API [GET]
</p>
@param[in] profile プロファイル
@param[in] request リクエストパラメータ
@param[in,out] response レスポンスパラメータ
@param[in] deviceId デバイスID
@retval YES レスポンスパラメータを返却する。
@retval NO レスポンスパラメータを返却しないので、@link DConnectManager::sendResponse: @endlinkで返却すること。
*/
- (BOOL) profile:(DConnectSettingsProfile *)profile didReceiveGetDateRequest:(DConnectRequestMessage *)request
response:(DConnectResponseMessage *)response
deviceId:(NSString *)deviceId;
/*!
@brief デバイスのバックライト明度取得リクエストを受け取ったことをデリゲートに通知する。
profileがデバイスのバックライト明度取得リクエストを受け取ったことをデリゲートに通知する。<br>
実装されない場合には、Not supportのエラーが返却される。
<p>
[対応するAPI] Display Light Settings API [GET]
</p>
@param[in] profile プロファイル
@param[in] request リクエストパラメータ
@param[in,out] response レスポンスパラメータ
@param[in] deviceId デバイスID
@retval YES レスポンスパラメータを返却する。
@retval NO レスポンスパラメータを返却しないので、@link DConnectManager::sendResponse: @endlinkで返却すること。
*/
- (BOOL) profile:(DConnectSettingsProfile *)profile didReceiveGetLightRequest:(DConnectRequestMessage *)request
response:(DConnectResponseMessage *)response
deviceId:(NSString *)deviceId;
/*!
@brief デバイスの画面消灯設定取得リクエストを受け取ったことをデリゲートに通知する。
profileがデバイスの画面消灯設定取得リクエストを受け取ったことをデリゲートに通知する。<br>
実装されない場合には、Not supportのエラーが返却される。
<p>
[対応するAPI] Display Sleep Settings API [GET]
</p>
@param[in] profile プロファイル
@param[in] request リクエストパラメータ
@param[in,out] response レスポンスパラメータ
@param[in] deviceId デバイスID
@retval YES レスポンスパラメータを返却する。
@retval NO レスポンスパラメータを返却しないので、@link DConnectManager::sendResponse: @endlinkで返却すること。
*/
- (BOOL) profile:(DConnectSettingsProfile *)profile didReceiveGetSleepRequest:(DConnectRequestMessage *)request
response:(DConnectResponseMessage *)response
deviceId:(NSString *)deviceId;
#pragma mark - Put Methods
/*!
@brief デバイスの音量設定リクエストを受け取ったことをデリゲートに通知する。
profileがデバイスの音量設定リクエストを受け取ったことをデリゲートに通知する。<br>
実装されない場合には、Not supportのエラーが返却される。
<p>
[対応するAPI] Volume Settings API [PUT]
</p>
@param[in] profile プロファイル
@param[in] request リクエストパラメータ
@param[in,out] response レスポンスパラメータ
@param[in] deviceId デバイスID
@param[in] kind 種別
@param[in] level 音量
@retval YES レスポンスパラメータを返却する。
@retval NO レスポンスパラメータを返却しないので、@link DConnectManager::sendResponse: @endlinkで返却すること。
*/
- (BOOL) profile:(DConnectSettingsProfile *)profile didReceivePutVolumeRequest:(DConnectRequestMessage *)request
response:(DConnectResponseMessage *)response
deviceId:(NSString *)deviceId
kind:(DConnectSettingsProfileVolumeKind)kind
level:(NSNumber *)level;
/*!
@brief デバイスの日時設定リクエストを受け取ったことをデリゲートに通知する。
profileがデバイスの日時設定リクエストを受け取ったことをデリゲートに通知する。<br>
実装されない場合には、Not supportのエラーが返却される。
<p>
[対応するAPI] Date Settings API [PUT]
</p>
@param[in] profile プロファイル
@param[in] request リクエストパラメータ
@param[in,out] response レスポンスパラメータ
@param[in] deviceId デバイスID
@param[in] date 日時
@retval YES レスポンスパラメータを返却する。
@retval NO レスポンスパラメータを返却しないので、@link DConnectManager::sendResponse: @endlinkで返却すること。
*/
- (BOOL) profile:(DConnectSettingsProfile *)profile didReceivePutDateRequest:(DConnectRequestMessage *)request
response:(DConnectResponseMessage *)response
deviceId:(NSString *)deviceId
date:(NSString *)date;
/*!
@brief デバイスのバックライト明度設定リクエストを受け取ったことをデリゲートに通知する。
profileがデバイスのバックライト明度設定リクエストを受け取ったことをデリゲートに通知する。<br>
実装されない場合には、Not supportのエラーが返却される。
<p>
[対応するAPI] Display Light Settings API [PUT]
</p>
@param[in] profile プロファイル
@param[in] request リクエストパラメータ
@param[in,out] response レスポンスパラメータ
@param[in] deviceId デバイスID
@param[in] level 明度パーセント
@retval YES レスポンスパラメータを返却する。
@retval NO レスポンスパラメータを返却しないので、@link DConnectManager::sendResponse: @endlinkで返却すること。
*/
- (BOOL) profile:(DConnectSettingsProfile *)profile didReceivePutLightRequest:(DConnectRequestMessage *)request
response:(DConnectResponseMessage *)response
deviceId:(NSString *)deviceId
level:(NSNumber *)level;
/*!
@brief デバイスの画面消灯設定リクエストを受け取ったことをデリゲートに通知する。
profileがデバイスの画面消灯設定リクエストを受け取ったことをデリゲートに通知する。<br>
実装されない場合には、Not supportのエラーが返却される。
<p>
[対応するAPI] Display Sleep Settings API [PUT]
</p>
@param[in] profile プロファイル
@param[in] request リクエストパラメータ
@param[in,out] response レスポンスパラメータ
@param[in] deviceId デバイスID
@param[in] time 消灯するまでの時間(ミリ秒)
@retval YES レスポンスパラメータを返却する。
@retval NO レスポンスパラメータを返却しないので、@link DConnectManager::sendResponse: @endlinkで返却すること。
*/
- (BOOL) profile:(DConnectSettingsProfile *)profile didReceivePutSleepRequest:(DConnectRequestMessage *)request
response:(DConnectResponseMessage *)response
deviceId:(NSString *)deviceId
time:(NSNumber *)time;
@end
/*!
@class DConnectSettingsProfile
@brief Settingsプロファイル.
Settings Profileの各APIへのリクエストを受信する。
受信したリクエストは各API毎にデリゲートに通知される。
*/
@interface DConnectSettingsProfile : DConnectProfile
/*!
@brief DConnectSettingsProfileのデリゲートオブジェクト。
デリゲートは @link DConnectSettingsProfileDelegate @endlink を実装しなくてはならない。
デリゲートはretainされない。
*/
@property (nonatomic, weak) id<DConnectSettingsProfileDelegate> delegate;
#pragma mark - Getter
/*!
@brief リクエストから音量種別を取得する。
@param[in] request リクエストパラメータ
@retval DConnectSettingsProfileVolumeKindUnknown
@retval DConnectSettingsProfileVolumeKindAlarm
@retval DConnectSettingsProfileVolumeKindCall
@retval DConnectSettingsProfileVolumeKindRingtone
@retval DConnectSettingsProfileVolumeKindMail
@retval DConnectSettingsProfileVolumeKindOther
@retval DConnectSettingsProfileVolumeKindMediaPlay
*/
+ (DConnectSettingsProfileVolumeKind) volumeKindFromRequest:(DConnectMessage *)request;
/*!
@brief リクエストから音量を取得する。
@param[in] request リクエストパラメータ
@retval 音量
@retval nil 音量が指定されていない場合
*/
+ (NSNumber *) levelFromRequest:(DConnectMessage *)request;
/*!
@brief リクエストから日時(RFC3339)を取得する。
@param[in] request リクエストパラメータ
@retval 日時文字列(RFC3339)
@retval nil 日時が指定されていない場合
*/
+ (NSString *) dateFromRequest:(DConnectMessage *)request;
/*!
@brief リクエストから消灯するまでの時間(ミリ秒)を取得する。
@param[in] request リクエストパラメータ
@retval 消灯するまでの時間(ミリ秒)。
@retval nil 消灯時間が指定されていない場合
*/
+ (NSNumber *) timeFromRequest:(DConnectMessage *)request;
#pragma mark - Setter
/*!
@brief メッセージに音量を設定する。
@param[in] level 音量パーセント(0〜1.0)
@param[in,out] message 音量を格納するメッセージ
*/
+ (void) setVolumeLevel:(double)level target:(DConnectMessage *)message;
/*!
@brief メッセージにバックライト明度を設定する。
@param[in] level 明度パーセント(0〜1.0)
@param[in,out] message バックライト明度を格納するメッセージ
*/
+ (void) setLightLevel:(double)level target:(DConnectMessage *)message;
/*!
@brief メッセージに日時を設定する。
@param[in] date 日時文字列(RFC3339)
@param[in,out] message 日時を格納するメッセージ
*/
+ (void) setDate:(NSString *)date target:(DConnectMessage *)message;
/*!
@brief メッセージに消灯するまでの時間(ミリ秒)を設定する。
@param[in] time 消灯するまでの時間(ミリ秒)
@param[in,out] message 消灯するまでの時間を格納するメッセージ
*/
+ (void) setTime:(int)time target:(DConnectMessage *)message;
@end
| 24.808824 | 112 | 0.757459 |
a2d706a980745f012648e5337212583057ae2d6f | 12,278 | c | C | UspLib/UspPaint.c | kxkx5150/kxEditor | 390504226220498556c4239842bc9b61edc7537d | [
"MIT"
] | null | null | null | UspLib/UspPaint.c | kxkx5150/kxEditor | 390504226220498556c4239842bc9b61edc7537d | [
"MIT"
] | null | null | null | UspLib/UspPaint.c | kxkx5150/kxEditor | 390504226220498556c4239842bc9b61edc7537d | [
"MIT"
] | null | null | null | //
// UspPaint.c
//
// Contains routines used for the display of styled Unicode text
//
// UspTextOut
// UspInitFont
// UspFreeFont
// UspSetSelColor
//
// Written by J Brown 2006 Freeware
// www.catch22.net
//
#define _WIN32_WINNT 0x0A00
#ifndef _UNICODE
#define _UNICODE
#endif
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <usp10.h>
#include <tchar.h>
#include "usplib.h"
// UspLib.c
ITEM_RUN *GetItemRun(USPDATA *uspData, int visualIdx);
// UspCtrl.c
void InitCtrlChar(HDC hdc, USPFONT *uspFont);
void PaintCtrlCharRun(USPDATA *uspData, USPFONT *uspFont, ITEM_RUN *itemRun, HDC hdc, int xpos, int ypos);
//
// Locate the glyph-index positions for the specified logical character positions
//
static
void GetGlyphClusterIndices (
ITEM_RUN * itemRun,
WORD * clusterList,
int clusterIdx1,
int clusterIdx2,
int * glyphIdx1,
int * glyphIdx2
)
{
// RTL scripts
if(itemRun->analysis.fRTL)
{
*glyphIdx1 = clusterIdx1 < itemRun->len ? clusterList[clusterIdx1] + 1 : 0;
*glyphIdx2 = clusterList[clusterIdx2];
}
// LTR scripts
else
{
*glyphIdx1 = clusterList[clusterIdx2];
*glyphIdx2 = clusterIdx1 < itemRun->len ? clusterList[clusterIdx1] - 1 : itemRun->glyphCount - 1;
}
}
//
// Draw a rectangle in a single colour. Depending on the run-direction (left/right),
// the rectangle's position may need to be mirrored within the run before output
//
static
void PaintRectBG(USPDATA *uspData, ITEM_RUN *itemRun, HDC hdc, int xpos, RECT *rect, ATTR *attr)
{
RECT rc = *rect;
// rectangle must be mirrored within the run for RTL scripts
if(itemRun->analysis.fRTL)
{
int rtlOffset = xpos*2 + itemRun->width - rc.right - rc.left;
OffsetRect(&rc, rtlOffset, 0);
}
// draw selection highlight + add to clipping region
if(attr->sel)
{
SetBkColor(hdc, uspData->selBG);
ExtTextOut(hdc, 0, 0, ETO_OPAQUE|ETO_CLIPPED, &rc, 0, 0, 0);
ExcludeClipRect(hdc, rc.left, rc.top, rc.right, rc.bottom);
}
// draw normal background
else
{
SetBkColor(hdc, attr->bg);
ExtTextOut(hdc, 0, 0, ETO_OPAQUE|ETO_CLIPPED, &rc, 0, 0, 0);
}
}
//
// Paint a single run's background
//
static
void PaintItemRunBackground (
USPDATA * uspData,
ITEM_RUN * itemRun,
HDC hdc,
int xpos,
int ypos,
int lineHeight,
RECT * bounds
)
{
int i, lasti;
RECT rect = { xpos, ypos, xpos, ypos+lineHeight };
WORD * clusterList = uspData->clusterList + itemRun->charPos;
ATTR * attrList = uspData->attrList + itemRun->charPos;
int * widthList = uspData->widthList + itemRun->glyphPos;
ATTR attr = attrList[0];
// loop over the character-positions in the run, in logical order
for(i = 0, lasti = 0; i <= itemRun->len; i++)
{
// search for a cluster boundary (or end of run)
if(i == itemRun->len || clusterList[lasti] != clusterList[i])
{
int clusterWidth;
int advanceWidth;
int a;
int glyphIdx1, glyphIdx2;
// locate glyph-positions for the cluster
GetGlyphClusterIndices(itemRun, clusterList, i, lasti, &glyphIdx1, &glyphIdx2);
// measure cluster width
for(clusterWidth = 0; glyphIdx1 <= glyphIdx2; )
clusterWidth += widthList[glyphIdx1++];
// divide the cluster-width by the number of code-points that cover it
// advanceWidth = clusterWidth / (i - lasti);
advanceWidth = MulDiv(clusterWidth, 1, i-lasti);
// interpolate the characters-positions (between lasti and i)
// over the whole cluster
for(a = lasti; a <= i; a++)
{
// adjust for possible rounding errors in the
// last iteration (due to the division)
if(a == i)
rect.right += clusterWidth - advanceWidth * (i-lasti);
// look for change in attribute background
if(a == itemRun->len ||
attr.bg != attrList[a].bg ||
attr.sel != attrList[a].sel)
{
PaintRectBG(uspData, itemRun, hdc, xpos, &rect, &attr);
rect.left = rect.right;
}
if(a != i)
{
attr = attrList[a];
rect.right += advanceWidth;
}
}
lasti = i;
}
}
}
//
// Paint the entire line's background
//
static
void PaintBackground (
USPDATA * uspData,
HDC hdc,
int xpos,
int ypos,
int lineHeight,
RECT * bounds
)
{
int i;
ITEM_RUN * itemRun;
//
// Loop over each item-run in turn
//
for(i = 0; i < uspData->itemRunCount; i++)
{
// Generate glyph data for this run
if((itemRun = GetItemRun(uspData, i)) == 0)
break;
// if run is not visible then don't bother displaying it!
if(xpos + itemRun->width < bounds->left || xpos > bounds->right)
{
xpos += itemRun->width;
continue;
}
// paint the background of the specified item-run
PaintItemRunBackground(
uspData,
itemRun,
hdc,
xpos,
ypos,
lineHeight,
bounds
);
xpos += itemRun->width;
}
}
//
// PaintItemRunForeground
//
// Output a whole ITEM_RUN of text. Use clusterList and attrList
// to break the glyphs into whole-cluster runs before calling ScriptTextOut
//
// We don't attempt to interpolate colours over each cluster. If there
// is more than one ATTR per cluster then tough - only one gets used and
// whole clusters (even if they contain multiple glyphs) get painted in
// a single colour
//
static
void PaintItemRunForeground (
USPDATA * uspData,
USPFONT * uspFont,
ITEM_RUN * itemRun,
HDC hdc,
int xpos,
int ypos,
RECT * bounds,
BOOL forcesel
)
{
HRESULT hr;
int i, lasti, g;
int glyphIdx1;
int glyphIdx2;
int runWidth;
int runDir = 1;
UINT oldMode;
// make pointers to the run's various glyph buffers
ATTR * attrList = uspData->attrList + itemRun->charPos;
WORD * clusterList = uspData->clusterList + itemRun->charPos;
WORD * glyphList = uspData->glyphList + itemRun->glyphPos;
int * widthList = uspData->widthList + itemRun->glyphPos;
GOFFSET * offsetList = uspData->offsetList + itemRun->glyphPos;
// right-left runs can be drawn backwards for simplicity
if(itemRun->analysis.fRTL)
{
oldMode = SetTextAlign(hdc, TA_RIGHT);
xpos += itemRun->width;
runDir = -1;
}
// loop over all the logical character-positions
for(lasti = 0, i = 0; i <= itemRun->len; i++)
{
// find a change in attribute
if(i == itemRun->len || attrList[i].fg != attrList[lasti].fg )
{
// scan forward to locate end of cluster (we must always
// handle whole-clusters because the attr[] might fall in the middle)
for( ; i < itemRun->len; i++)
if(clusterList[i - 1] != clusterList[i])
break;
// locate glyph-positions for the cluster [i,lasti]
GetGlyphClusterIndices(itemRun, clusterList, i, lasti, &glyphIdx1, &glyphIdx2);
// measure the width (in pixels) of the run
for(runWidth = 0, g = glyphIdx1; g <= glyphIdx2; g++)
runWidth += widthList[g];
// only need the text colour as we are drawing transparently
SetTextColor(hdc, forcesel ? uspData->selFG : attrList[lasti].fg);
//
// Finally output the run of glyphs
//
hr = ScriptTextOut(
hdc,
&uspFont->scriptCache,
xpos,
ypos,
0,
NULL,
&itemRun->analysis,
0,
0,
glyphList + glyphIdx1,
glyphIdx2 - glyphIdx1 + 1,
widthList + glyphIdx1,
0,
offsetList + glyphIdx1
);
// +ve/-ve depending on run direction
xpos += runWidth * runDir;
lasti = i;
}
}
// restore the mapping mode
if(itemRun->analysis.fRTL)
oldMode = SetTextAlign(hdc, oldMode);
}
//
// optimization: if the two neighbouring item-runs share the
// same 'selection state' as the current run, then we can completely skip drawing
//
static
BOOL CanSkip(USPDATA *uspData, int i, BOOL forcesel)
{
BOOL canSkip = FALSE;
if(i > 0 && i < uspData->itemRunCount - 1)
{
ITEM_RUN *prevRun = GetItemRun(uspData, i - 1);
ITEM_RUN *thisRun = GetItemRun(uspData, i );
ITEM_RUN *nextRun = GetItemRun(uspData, i + 1);
// skip drawing regular text if all three runs are selected
if(forcesel == FALSE && prevRun->selstate == 1 && thisRun->selstate == 1 && nextRun->selstate == 1 &&
prevRun->width != 0 && thisRun->width != 0 && nextRun->width != 0)
{
return TRUE;
}
// skip drawing selected text if all three runs are unselected
if(forcesel == TRUE && prevRun->selstate == 0 && thisRun->selstate == 0 && nextRun->selstate == 0 &&
prevRun->width != 0 && thisRun->width != 0 && nextRun->width != 0)
{
return TRUE;
}
}
return FALSE;
}
//
// Paint the entire line of text
//
static
int PaintForeground (
USPDATA * uspData,
HDC hdc,
int xpos,
int ypos,
RECT * bounds,
BOOL forcesel
)
{
int i;
int yoff;
ITEM_RUN * itemRun;
USPFONT * uspFont;
//
// Loop over each item-run in turn
//
for(i = 0; i < uspData->itemRunCount; i++)
{
// Generate glyph data for this run
if((itemRun = GetItemRun(uspData, i)) == 0)
break;
// if run is not visible then don't bother displaying it!
if(xpos + itemRun->width < bounds->left || xpos > bounds->right)
{
xpos += itemRun->width;
continue;
}
// see if we can avoid drawing this run
if(CanSkip(uspData, i, forcesel))
{
xpos += itemRun->width;
continue;
}
// select the appropriate font
uspFont = &uspData->uspFontList[itemRun->font];
SelectObject(hdc, uspFont->hFont);
yoff = uspFont->yoffset;
if(itemRun->ctrl && !itemRun->tab)
{
// draw control-characters, as long as it's not a tab
PaintCtrlCharRun(
uspData,
uspFont,
itemRun,
hdc,
xpos,
ypos + yoff
);
}
else
{
// display a whole run of glyphs
PaintItemRunForeground(
uspData,
uspFont,
itemRun,
hdc,
xpos,
ypos + yoff,
bounds,
forcesel
);
}
xpos += itemRun->width;
}
return xpos;
}
//
// UspAttrTextOut
//
// Display a line of text previously analyzed with UspAnalyze. The stored
// ATTR[] visual-attribute list is used to stylize the text as it is drawn.
//
// Coloured text-display using Uniscribe is very complicated.
// Three passes are required if high-quality text output is the goal.
//
// Returns: adjusted x-coordinate
//
int WINAPI UspTextOut (
USPDATA * uspData,
HDC hdc,
int xpos,
int ypos,
int lineHeight,
int lineAdjustY,
RECT * bounds
)
{
HRGN hrgn, hrgnClip;
if(uspData->stringLen == 0 || uspData->glyphCount == 0)
return xpos;
hrgnClip = CreateRectRgn(0,0,1,1);
GetClipRgn(hdc, hrgnClip);
//
// 1. draw all background colours, including selection-highlights;
// selected areas are added to the HDC clipping region which prevents
// step#2 (below) from drawing over them
//
SetBkMode(hdc, OPAQUE);
PaintBackground(uspData, hdc, xpos, ypos, lineHeight, bounds);
//
// 2. draw the text normally. Selected areas are left untouched
// because of the clipping-region created in step#1
//
SetBkMode(hdc, TRANSPARENT);
PaintForeground(uspData, hdc, xpos, ypos + lineAdjustY, bounds, FALSE);
//
// 3. redraw the text using a single text-selection-colour (i.e. white)
// in the same position, directly over the top of the text drawn in step#2
//
// Before we do this, the HDC clipping-region is inverted,
// so only selection areas are modified this time
//
hrgn = CreateRectRgnIndirect(bounds);
ExtSelectClipRgn(hdc, hrgn, RGN_XOR);
SetBkMode(hdc, TRANSPARENT);
xpos =
PaintForeground(uspData, hdc, xpos, ypos + lineAdjustY, bounds, TRUE);
// remove clipping regions
SelectClipRgn(hdc, hrgnClip);
DeleteObject(hrgn);
DeleteObject(hrgnClip);
return xpos;
}
//
// Set the colours used for drawing text-selection
//
void WINAPI UspSetSelColor (
USPDATA * uspData,
COLORREF fg,
COLORREF bg
)
{
uspData->selFG = fg;
uspData->selBG = bg;
}
//
// Used to initialize a font
//
void WINAPI UspInitFont (
USPFONT * uspFont,
HDC hdc,
HFONT hFont
)
{
ZeroMemory(uspFont, sizeof(USPFONT));
uspFont->hFont = hFont;
uspFont->scriptCache = 0;
hFont = SelectObject(hdc, hFont);
GetTextMetrics(hdc, &uspFont->tm);
InitCtrlChar(hdc, uspFont);
SelectObject(hdc, hFont);
}
//
// Free the font resources
//
void WINAPI UspFreeFont (
USPFONT * uspFont
)
{
DeleteObject(uspFont->hFont);
ScriptFreeCache(&uspFont->scriptCache);
}
| 22.695009 | 106 | 0.652712 |
4e588bfb07c274dcf9aac4ef9840c3a288eea122 | 2,420 | h | C | SwpCateGoryDemo/Pods/Headers/Private/SwpCateGory/UITextField+SwpSetTextField.h | swp-song/SwpCateGory | 53065cb20ca09e5259d16f7f5103b35dcb86cc67 | [
"MIT"
] | 2 | 2016-06-15T07:43:26.000Z | 2017-06-20T14:33:24.000Z | SwpCateGoryDemo/Pods/Headers/Public/SwpCateGory/UITextField+SwpSetTextField.h | swp-song/SwpCateGory | 53065cb20ca09e5259d16f7f5103b35dcb86cc67 | [
"MIT"
] | null | null | null | SwpCateGoryDemo/Pods/Headers/Public/SwpCateGory/UITextField+SwpSetTextField.h | swp-song/SwpCateGory | 53065cb20ca09e5259d16f7f5103b35dcb86cc67 | [
"MIT"
] | null | null | null | //
// UITextField+SwpSetTextField.h
// swp_song
//
// Created by swp_song on 16/6/3.
// Copyright © 2016年 swp_song. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UITextField (SwpSetTextField)
/**!
* @author swp_song
*
* @ brief swpSetTextFieldStyle:setBorderColor:setTextColor:setBorderWidth:setCornerRadius:setPlaceholder:setTextFontSize:setKeyboardType:setTextEncrypt: ( 设置 textField <没有左侧图片> )
*
* @param textField textField
*
* @param borderColor textField 边框颜色
*
* @param textColor textField 文字颜色
*
* @param borderWidth textField 边框
*
* @param cornerRadius textField 圆角弧度
*
* @param placeholder textField 显示的提示
*
* @param textFontSize textField 文字大小
*
* @param keyboardType textField 键盘样式
*
* @param isEncrypt textField 是否是密码键盘
*/
+ (void)swpSetTextFieldStyle:(UITextField *)textField setBorderColor:(nullable UIColor *)borderColor setTextColor:(nullable UIColor *)textColor setBorderWidth:(CGFloat)borderWidth setCornerRadius:(CGFloat)cornerRadius setPlaceholder:(NSString *)placeholder setTextFontSize:(CGFloat)textFontSize setKeyboardType:(UIKeyboardType)keyboardType setTextEncrypt:(BOOL)isEncrypt;
/**!
* @author swp_song
*
* @ brief swpSetTextFieldImage:setBorderColor:setTextColor:setBorderWidth:setCornerRadius:setPlaceholder:setTextFontSize:setKeyboardType:setTextEncrypt: ( 设置 textField <带左侧图片> )
*
* @param textField textField
*
* @param imageName textField 图片名称
*
* @param borderColor textField 边框颜色
*
* @param textColor textField 文字颜色
*
* @param borderWidth textField 边框
*
* @param cornerRadius textField 圆角弧度
*
* @param placeholder textField 显示的提示
*
* @param textFontSize textField 文字大小
*
* @param keyboardType textField 键盘样式
*
* @param isEncrypt textField 是否是密码键盘
*/
+ (void)swpSetTextFieldImage:(UITextField *)textField setImageName:(NSString *)imageName setBorderColor:(nullable UIColor *)borderColor setTextColor:(nullable UIColor *)textColor setBorderWidth:(CGFloat)borderWidth setCornerRadius:(CGFloat)cornerRadius setPlaceholder:(NSString *)placeholder setTextFontSize:(CGFloat)textFontSize setKeyboardType:(UIKeyboardType)keyboardType setTextEncrypt:(BOOL)isEncrypt;
@end
NS_ASSUME_NONNULL_END
| 35.588235 | 406 | 0.720248 |
08715e57336fb344c7d203cbfbe701325ceb92ed | 1,904 | h | C | OpenTESArena/src/World/ArenaCityUtils.h | Alucowie/OpenTESArena | f8e04f288dfb587e390d15bf9eb6e017fe991d83 | [
"MIT"
] | null | null | null | OpenTESArena/src/World/ArenaCityUtils.h | Alucowie/OpenTESArena | f8e04f288dfb587e390d15bf9eb6e017fe991d83 | [
"MIT"
] | null | null | null | OpenTESArena/src/World/ArenaCityUtils.h | Alucowie/OpenTESArena | f8e04f288dfb587e390d15bf9eb6e017fe991d83 | [
"MIT"
] | null | null | null | #ifndef ARENA_CITY_UTILS_H
#define ARENA_CITY_UTILS_H
#include <cstdint>
#include <vector>
#include "ArenaLevelUtils.h"
#include "LevelData.h"
#include "VoxelUtils.h"
#include "../Assets/ArenaTypes.h"
#include "../Assets/MIFFile.h"
#include "components/utilities/Buffer2D.h"
#include "components/utilities/BufferView2D.h"
class ArenaRandom;
class BinaryAssetLibrary;
class LocationDefinition;
class ProvinceDefinition;
class TextAssetLibrary;
class VoxelGrid;
enum class ClimateType;
enum class WeatherType;
// @todo: these should probably all be BufferView2D instead of Buffer2D
namespace ArenaCityUtils
{
// Max height of .MIF with highest MAP2 extension.
constexpr int LEVEL_HEIGHT = 6;
// Generates the .INF name for a city given a climate and current weather.
std::string generateInfName(ClimateType climateType, WeatherType weatherType);
// Writes the barebones city layout (just ground and walls).
void writeSkeleton(const MIFFile::Level &level, BufferView2D<ArenaTypes::VoxelID> &dstFlor,
BufferView2D<ArenaTypes::VoxelID> &dstMap1, BufferView2D<ArenaTypes::VoxelID> &dstMap2);
// Writes generated city building data into the output buffers. The buffers should already
// be initialized with the city skeleton.
void generateCity(uint32_t citySeed, int cityDim, WEInt gridDepth,
const BufferView<const uint8_t> &reservedBlocks, const OriginalInt2 &startPosition,
ArenaRandom &random, const BinaryAssetLibrary &binaryAssetLibrary,
Buffer2D<ArenaTypes::VoxelID> &dstFlor, Buffer2D<ArenaTypes::VoxelID> &dstMap1,
Buffer2D<ArenaTypes::VoxelID> &dstMap2);
// Iterates over the perimeter of a city map and changes palace graphics and their gates to the
// actual ones used in-game.
// @todo: this should use Arena dimensions (from MAP1?), not modern dimensions
void revisePalaceGraphics(Buffer2D<ArenaTypes::VoxelID> &map1, SNInt gridWidth, WEInt gridDepth);
}
#endif
| 34.618182 | 98 | 0.78834 |
089b2a6b06e8849674a0fe3a2d018ce38a7ea92d | 1,710 | h | C | power_manager/powerd/policy/user_proximity_voting.h | ascii33/platform2 | b78891020724e9ff26b11ca89c2a53f949e99748 | [
"BSD-3-Clause"
] | null | null | null | power_manager/powerd/policy/user_proximity_voting.h | ascii33/platform2 | b78891020724e9ff26b11ca89c2a53f949e99748 | [
"BSD-3-Clause"
] | null | null | null | power_manager/powerd/policy/user_proximity_voting.h | ascii33/platform2 | b78891020724e9ff26b11ca89c2a53f949e99748 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef POWER_MANAGER_POWERD_POLICY_USER_PROXIMITY_VOTING_H_
#define POWER_MANAGER_POWERD_POLICY_USER_PROXIMITY_VOTING_H_
#include "power_manager/common/power_constants.h"
#include <unordered_map>
namespace power_manager {
namespace policy {
// Aggregates votes from one or more sensors about the user's physical
// proximity to the device.
class UserProximityVoting {
public:
explicit UserProximityVoting(bool prefer_far);
UserProximityVoting(const UserProximityVoting&) = delete;
UserProximityVoting& operator=(const UserProximityVoting&) = delete;
~UserProximityVoting();
// Sets the vote of sensor |id| to |vote|. The sensor is added
// to the voting pool if no previous vote for |id| was registered.
// Returns true if the consensus changes due to |vote|.
bool Vote(int id, UserProximity vote);
// Returns the current consensus among all the sensors in this voting pool.
// If |prefer_far_| is false, then NEAR is returned if at least one sensor is
// claiming proximity, otherwise FAR is returned. If |prefer_far_| is true,
// then NEAR is returned when all sensors claim proximity, otherwise FAR is
// returned. If there are no sensors, then UNKNOWN is returned.
UserProximity GetVote() const;
private:
UserProximity CalculateVote() const;
std::unordered_map<int, UserProximity> votes_;
UserProximity consensus_ = UserProximity::UNKNOWN;
bool prefer_far_ = false;
};
} // namespace policy
} // namespace power_manager
#endif // POWER_MANAGER_POWERD_POLICY_USER_PROXIMITY_VOTING_H_
| 34.897959 | 79 | 0.771345 |
262304f73ee8eaf00cfbe8f5b8cd1820a063b0e0 | 1,721 | c | C | Operation-System/prj3/start_code/libs/string.c | D-Hank/UCAS-CS | e2b8a214057e6a411e742a78a988b43a49c7741f | [
"MIT"
] | 9 | 2020-12-02T05:42:03.000Z | 2022-03-29T11:25:26.000Z | Operation-System/prj3/start_code/libs/string.c | Hambaobao/UCAS-CS | e2b8a214057e6a411e742a78a988b43a49c7741f | [
"MIT"
] | null | null | null | Operation-System/prj3/start_code/libs/string.c | Hambaobao/UCAS-CS | e2b8a214057e6a411e742a78a988b43a49c7741f | [
"MIT"
] | 4 | 2021-03-27T04:02:55.000Z | 2022-01-26T06:35:22.000Z | #include "string.h"
int strlen(char *src)
{
int i;
for (i = 0; src[i] != '\0'; i++)
{
}
return i;
}
void memcpy(uint8_t *dest, uint8_t *src, uint32_t len)
{
for (; len != 0; len--)
{
*dest++ = *src++;
}
}
void memset(void *dest, uint8_t val, uint32_t len)
{
uint8_t *dst = (uint8_t *)dest;
for (; len != 0; len--)
{
*dst++ = val;
}
}
void bzero(void *dest, uint32_t len)
{
memset(dest, 0, len);
}
/*
int strcmp(char *str1, char *str2)
{
while (*str1 && *str2 && (*str1++ == *str2++))
{
};
return (*str1) - (*str2);
}
*/
int strcmp(char *str1, char *str2)
{
while (*str1 && *str2 && (*str1 == *str2))
{
str1++;
str2++;
};
return (*str1) - (*str2);
}
int memcmp(char *str1, char *str2, uint32_t size)
{
int i;
for (i = 0; i < size; i++)
{
if (str1[i] > str2[i])
{
return 1;
}
else if (str1[i] < str2[i])
{
return -1;
}
}
return 0;
}
void strcpy(char *dest, char *src)
{
int l = strlen(src);
int i;
for (i = 0; i < l; i++)
{
dest[i] = src[i];
}
dest[i] = '\0';
}
int atoi(char* str)
{
int result = 0;
int sign = 0;
// assert(str != NULL);
// proc whitespace characters
while (*str == ' ' || *str == '\t' || *str == '\n')
++str;
// proc sign character
if (*str == '-')
{
sign = 1;
++str;
}
else if (*str == '+')
{
++str;
}
// proc numbers
while (*str >= '0' && *str <= '9')
{
result = result * 10 + *str - '0';
++str;
}
// return result
if (sign == 1)
return -result;
else
return result;
}
| 14.22314 | 56 | 0.432888 |
2305ce5376ed22a0224c6179fcea8c020b32006f | 686 | c | C | ProgramasClase/MPI/C/gather.c | mbsuarezg/ComputacionParalela | b06ab20b27662a1f9a461214d6e6ed6bd648bed6 | [
"Unlicense"
] | null | null | null | ProgramasClase/MPI/C/gather.c | mbsuarezg/ComputacionParalela | b06ab20b27662a1f9a461214d6e6ed6bd648bed6 | [
"Unlicense"
] | null | null | null | ProgramasClase/MPI/C/gather.c | mbsuarezg/ComputacionParalela | b06ab20b27662a1f9a461214d6e6ed6bd648bed6 | [
"Unlicense"
] | null | null | null | //mpicc gather.c -o gt -lm
//mpirun -np 4 ./gt
#include <stdio.h>
#include <string.h>
#include <mpi.h>
#include <math.h>
#define MSG_LENGTH 10
#define MAXTASKS 32
int main (int argc, char *argv[])
{
int i, tasks, iam, root=0, buff2send, buff2recv[MAXTASKS];
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &tasks);
MPI_Comm_rank(MPI_COMM_WORLD, &iam);
buff2send = iam;
MPI_Gather((void *)&buff2send, 1, MPI_INT, buff2recv, 1, MPI_INT, root, MPI_COMM_WORLD);
if (iam == 0) {
for(i = 0; i < tasks; i++)
printf("%i\n", buff2recv[i]);
}
MPI_Finalize();
} | 26.384615 | 92 | 0.637026 |
033294ccd8cca59c9616008e061a81da430d78e2 | 2,424 | h | C | physicalrobots/player/server/drivers/mixed/erratic/robot_params.h | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/server/drivers/mixed/erratic/robot_params.h | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/server/drivers/mixed/erratic/robot_params.h | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /**
* Videre Erratic robot driver for Player
*
* Copyright (C) 2006
* Videre Design
* Copyright (C) 2000
* Brian Gerkey, Kasper Stoy, Richard Vaughan, & Andrew Howard
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
**/
#ifndef _ROBOT_PARAMS_H
#define _ROBOT_PARAMS_H
#include "libplayerinterface/player.h"
void initialize_robot_params(void);
#define PLAYER_NUM_ROBOT_TYPES 30
typedef struct
{
double AngleConvFactor; //
const char* Class;
double DiffConvFactor; //
double DistConvFactor; //
int FrontBumpers; //
double GyroScaler; //
int HasMoveCommand; //
int Holonomic; //
int IRNum; //
int IRUnit; //
int LaserFlipped; //
const char* LaserIgnore;
const char* LaserPort;
int LaserPossessed; //
int LaserPowerControlled; //
int LaserTh; //
int LaserX; //
int LaserY; //
int MaxRVelocity; //
int MaxVelocity; //
int NewTableSensingIR; //
int NumFrontBumpers; //
int NumRearBumpers; //
double RangeConvFactor; //
int RearBumpers; //
int RequestEncoderPackets; //
int RequestIOPackets; //
int RobotDiagonal; //
int RobotLength; //
int RobotRadius; //
int RobotWidth; //
int RobotAxleOffset; //
int RotAccel; //
int RotDecel; //
int RotVelMax; //
int SettableAccsDecs; //
int SettableVelMaxes; //
const char* Subclass;
int SwitchToBaudRate; //
int TableSensingIR; //
int TransAccel; //
int TransDecel; //
int TransVelMax; //
int Vel2Divisor; //
double VelConvFactor; //
int NumSonars;
player_pose3d_t sonar_pose[32];
int NumIR;
player_pose3d_t IRPose[8];
} RobotParams_t;
//extern RobotParams_t PlayerRobotParams[];
//extern RobotParams_t erratic_params;
extern RobotParams_t *RobotParams[];
#endif
| 25.515789 | 78 | 0.70132 |
03570f92db94a94bf13a8d21f5ee67661e83336c | 416 | h | C | Address.h | johnpaulloco/LocalOye | 7651c36f8c320c6be05b07a0720b26339f896dcd | [
"MIT"
] | null | null | null | Address.h | johnpaulloco/LocalOye | 7651c36f8c320c6be05b07a0720b26339f896dcd | [
"MIT"
] | null | null | null | Address.h | johnpaulloco/LocalOye | 7651c36f8c320c6be05b07a0720b26339f896dcd | [
"MIT"
] | null | null | null | //
// Address.h
// LocalOye
//
// Created by Imma Web Pvt Ltd on 22/09/15.
// Copyright © 2015 Imma Web Pvt Ltd. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
NS_ASSUME_NONNULL_BEGIN
@interface Address : NSManagedObject
// Insert code here to declare functionality of your managed object subclass
@end
NS_ASSUME_NONNULL_END
#import "Address+CoreDataProperties.h"
| 18.086957 | 76 | 0.75 |
eaf6ab82205666fa678f7ea104e50adee37108e5 | 3,639 | h | C | toonz/sources/include/ttoonzimage.h | wofogen/tahoma2d | ce5a89a7b1027b2c1769accb91184a2ee6442b4d | [
"BSD-3-Clause"
] | 3,710 | 2016-03-26T00:40:48.000Z | 2022-03-31T21:35:12.000Z | toonz/sources/include/ttoonzimage.h | wofogen/tahoma2d | ce5a89a7b1027b2c1769accb91184a2ee6442b4d | [
"BSD-3-Clause"
] | 4,246 | 2016-03-26T01:21:45.000Z | 2022-03-31T23:10:47.000Z | toonz/sources/include/ttoonzimage.h | wofogen/tahoma2d | ce5a89a7b1027b2c1769accb91184a2ee6442b4d | [
"BSD-3-Clause"
] | 633 | 2016-03-26T00:42:25.000Z | 2022-03-17T02:55:13.000Z | #pragma once
#ifndef TTOONZIMAGE_INCLUDED
#define TTOONZIMAGE_INCLUDED
#include "trastercm.h"
#include "tthreadmessage.h"
#include "timage.h"
#undef DVAPI
#undef DVVAR
#ifdef TNZCORE_EXPORTS
#define DVAPI DV_EXPORT_API
#define DVVAR DV_EXPORT_VAR
#else
#define DVAPI DV_IMPORT_API
#define DVVAR DV_IMPORT_VAR
#endif
class TToonzImageP;
//! An image containing a Toonz raster.
class DVAPI TToonzImage final : public TImage {
//! dpi value for x axis
double m_dpix,
//! dpi value for y axis
m_dpiy;
int m_subsampling;
//! The name of the image
std::string m_name;
//! The savebox of the image
TRect m_savebox;
// double m_hPos;
//! The offset of the image
TPoint m_offset;
//! ColorMapped raster of the image.
TRasterCM32P m_ras;
TThread::Mutex m_mutex;
public:
TToonzImage();
TToonzImage(const TRasterCM32P &raster, const TRect &saveBox);
~TToonzImage();
private:
//! Is used to clone an existing ToonzImage.
TToonzImage(const TToonzImage &);
//! Not implemented
TToonzImage &operator=(const TToonzImage &);
public:
//! Return the type of the image.
TImage::Type getType() const override { return TImage::TOONZ_RASTER; }
//! Return the size of the Image.
TDimension getSize() const { return m_size; }
//! Get the dpi values of the image for x and y axes.
void getDpi(double &dpix, double &dpiy) const {
dpix = m_dpix;
dpiy = m_dpiy;
}
//! Set the dpi values of the image for x and y axes.
void setDpi(double dpix, double dpiy) {
m_dpix = dpix;
m_dpiy = dpiy;
}
int getSubsampling() const { return m_subsampling; }
void setSubsampling(int s);
//! Return the savebox of the image
TRect getSavebox() const { return m_savebox; }
//! Set the savebox of the image.
/*! The set savebox is the intersection between \b rect and the image
* box.*/
void setSavebox(const TRect &rect);
//! Return the bounding box of the image.
TRectD getBBox() const override { return convert(m_savebox); }
//! Return the offset point of the image.
TPoint getOffset() const { return m_offset; }
//! Set the offset point of the image.
void setOffset(const TPoint &offset) { m_offset = offset; }
//! Return raster hPos \b m_hPos
// double gethPos() const {return m_hPos;}
//! Return a clone of image
// void sethPos(double hPos) {m_hPos= hPos;}
//! Return a clone of the current image
TImage *cloneImage() const override;
//! Return the image's raster
TRasterCM32P getCMapped() const;
//! Return a copy of the image's raster.
void getCMapped(const TRasterCM32P &ras);
//! Set the image's raster
void setCMapped(const TRasterCM32P &ras);
//! Return the image's raster.
/*! Call the getCMapped() method.*/
TRasterCM32P getRaster() const { return getCMapped(); }
TRasterP raster() const override { return (TRasterP)getCMapped(); }
//! Return a clone of the current image.
TToonzImageP clone() const;
private:
//! Image dimension
TDimension m_size;
};
//-------------------------------------------------------------------
#ifdef _WIN32
template class DVAPI TSmartPointerT<TToonzImage>;
template class DVAPI TDerivedSmartPointerT<TToonzImage, TImage>;
#endif
class DVAPI TToonzImageP final
: public TDerivedSmartPointerT<TToonzImage, TImage> {
public:
TToonzImageP() {}
TToonzImageP(TToonzImage *image) : DerivedSmartPointer(image) {}
TToonzImageP(TImageP image) : DerivedSmartPointer(image) {}
TToonzImageP(const TRasterCM32P &ras, const TRect &saveBox)
: DerivedSmartPointer(new TToonzImage(ras, saveBox)) {}
operator TImageP() { return TImageP(m_pointer); }
};
#endif
| 26.562044 | 72 | 0.694696 |
d98c0acc414231989d4bc3c8a6552431540fe63e | 298 | h | C | Qt-2048-cmake/GUI/MainWindow.h | Life4gal/CPP-EASY-PROJECT | 4bf66284b4990e6d7b3ab74ce15fe72fb52b5a41 | [
"MIT"
] | null | null | null | Qt-2048-cmake/GUI/MainWindow.h | Life4gal/CPP-EASY-PROJECT | 4bf66284b4990e6d7b3ab74ce15fe72fb52b5a41 | [
"MIT"
] | null | null | null | Qt-2048-cmake/GUI/MainWindow.h | Life4gal/CPP-EASY-PROJECT | 4bf66284b4990e6d7b3ab74ce15fe72fb52b5a41 | [
"MIT"
] | null | null | null | #ifndef GUI_MAINWINDOW_H
#define GUI_MAINWINDOW_H
#include <QMainWindow>
#include "GameBoard.h"
namespace GUI
{
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = nullptr);
private:
GameBoard* gameBoard;
};
}
#endif //GUI_MAINWINDOW_H
| 12.416667 | 51 | 0.741611 |
fce2b15e7c6bef724fba01369c283a31e99ec112 | 1,102 | h | C | PrivateFrameworks/CloudKitDaemon.framework/CKDPZoneRetrieveChangesResponseChangedZone.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | PrivateFrameworks/CloudKitDaemon.framework/CKDPZoneRetrieveChangesResponseChangedZone.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | PrivateFrameworks/CloudKitDaemon.framework/CKDPZoneRetrieveChangesResponseChangedZone.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/CloudKitDaemon.framework/CloudKitDaemon
*/
@interface CKDPZoneRetrieveChangesResponseChangedZone : PBCodable <NSCopying> {
int _changeType;
struct {
unsigned int changeType : 1;
} _has;
CKDPRecordZoneIdentifier * _zoneIdentifier;
}
@property (nonatomic) int changeType;
@property (nonatomic) bool hasChangeType;
@property (nonatomic, readonly) bool hasZoneIdentifier;
@property (nonatomic, retain) CKDPRecordZoneIdentifier *zoneIdentifier;
- (void).cxx_destruct;
- (int)StringAsChangeType:(id)arg1;
- (int)changeType;
- (id)changeTypeAsString:(int)arg1;
- (void)copyTo:(id)arg1;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (id)description;
- (id)dictionaryRepresentation;
- (bool)hasChangeType;
- (bool)hasZoneIdentifier;
- (unsigned long long)hash;
- (bool)isEqual:(id)arg1;
- (void)mergeFrom:(id)arg1;
- (bool)readFrom:(id)arg1;
- (void)setChangeType:(int)arg1;
- (void)setHasChangeType:(bool)arg1;
- (void)setZoneIdentifier:(id)arg1;
- (void)writeTo:(id)arg1;
- (id)zoneIdentifier;
@end
| 28.25641 | 83 | 0.742287 |
1e344d502cd9774ebb8353e5d539f1b53694b8c8 | 216 | h | C | source/IO.h | vectorgrp/LightContolDemo | 6917c73b31f22b5b9723ec7e26056454b5bcfaf5 | [
"MIT"
] | null | null | null | source/IO.h | vectorgrp/LightContolDemo | 6917c73b31f22b5b9723ec7e26056454b5bcfaf5 | [
"MIT"
] | null | null | null | source/IO.h | vectorgrp/LightContolDemo | 6917c73b31f22b5b9723ec7e26056454b5bcfaf5 | [
"MIT"
] | null | null | null | #ifndef IO_H
#define IO_H
#include "LightCtrl_SWC.h"
void Output_HeadLight(uint8_T headLightValue);
void Input_LightSwitch(uint8_T *value);
void Input_LightIntensity(uint16_T * lightIntesityValue);
#endif // IO_H
| 19.636364 | 57 | 0.805556 |
149e4a63b4986f6ec0a9299f73c4e0bcb8b29cb5 | 569 | c | C | tests/compiler_features_tests/linux_u32.c | bryce-shang/aws-lc | da13e558ce545ff1fd27e0720e1db41bd10dd54d | [
"BSD-3-Clause"
] | 45 | 2020-09-02T17:15:04.000Z | 2022-03-25T19:24:53.000Z | tests/compiler_features_tests/linux_u32.c | bryce-shang/aws-lc | da13e558ce545ff1fd27e0720e1db41bd10dd54d | [
"BSD-3-Clause"
] | 133 | 2020-09-03T20:24:53.000Z | 2022-03-30T23:24:44.000Z | tests/compiler_features_tests/linux_u32.c | bryce-shang/aws-lc | da13e558ce545ff1fd27e0720e1db41bd10dd54d | [
"BSD-3-Clause"
] | 35 | 2020-09-02T17:28:45.000Z | 2022-03-08T17:37:09.000Z | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// This file is to check if <linux/random.h> can be included.
// Currently, I assume the compiler error is caused by '__u32' is not defined.
// Background:
// crypto/fipsmodule/rand/urandom.c includes below Linux header file for FIPS.
// Some old Linux OS does not define '__u32', and then reports below error.
// /usr/include/linux/random.h:38:2: error: unknown type name '__u32'
// __u32 buf[0];
// ^
#include <linux/random.h>
int main() {
return 0;
}
| 33.470588 | 78 | 0.713533 |
8864f0a5fde9aebaa0841d0d58d869f4ebb93f99 | 1,738 | h | C | fix_unistd.h | Taromati2/yaya-shiori | c49e3d4d03f167a8833f2e68810fb46dc33bac90 | [
"BSD-3-Clause"
] | null | null | null | fix_unistd.h | Taromati2/yaya-shiori | c49e3d4d03f167a8833f2e68810fb46dc33bac90 | [
"BSD-3-Clause"
] | 2 | 2022-01-12T03:25:46.000Z | 2022-01-12T07:15:38.000Z | fix_unistd.h | Taromati2/yaya-shiori | c49e3d4d03f167a8833f2e68810fb46dc33bac90 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#if defined(POSIX)
#include <unistd.h>
#else
//<unistd.h> for Windows
#ifndef _UNISTD_H_
#define _UNISTD_H_
#ifdef _WIN32
#pragma once
#include <io.h>
/*
access
chmod
chsize
close
creat
dup
dup2
eof
filelength
isatty
locking
lseek
mktemp
open
read
setmode
sopen
tell
umask
unlink
write
*/
#include <direct.h>
/*
chdir
getcwd
mkdir
rmdir
*/
#include <process.h>
/*
cwait
execl
execle
execlp
execlpe
execv
execve
execvp
execvpe
spawnl
spawnle
spawnlp
spawnlpe
spawnv
spawnve
spawnvp
spawnvpe
*/
#pragma comment( lib, "ws2_32" )
#include <winsock2.h>
/*
gethostname
*/
#include <process.h>
/*
_getpid
*/
#include <time.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef int pid_t; /* process id type */
#ifndef _SSIZE_T_DEFINED
typedef int ssize_t;
#define _SSIZE_T_DEFINED
#endif
#ifndef getpid
#define getpid() _getpid()
#ifdef _ACRTIMP
_ACRTIMP
#endif
extern pid_t __cdecl _getpid(void);
#endif
#define nice(incr) (SetPriorityClass(GetCurrentProcess(),incr))//TODO
#define sleep(seconds) (Sleep(seconds*1000))
#define usleep(useconds) (Sleep(useconds))
#define stime(tp) UNISTD_stime(tp)
__forceinline int UNISTD_stime(const time_t *tp ){
FILETIME ft;
SYSTEMTIME st;
LONGLONG ll = Int32x32To64(*tp, 10000000) + 116444736000000000;
ft.dwLowDateTime = (DWORD) ll;
ft.dwHighDateTime = (unsigned __int64)ll >>32;
FileTimeToSystemTime(&ft,&st);
return SetSystemTime(&st);
}
//<sys/stat.h>
#define fstat64(fildes, stat) (_fstati64(fildes, stat))
#define stat64(path, buffer) (_stati64(path,buffer))
#ifdef __cplusplus
}
#endif
#endif /* _WIN32 */
#endif /* _UNISTD_H_ */
#endif
| 13.793651 | 70 | 0.686997 |
5324ae2fc5e452ff31131267779c9956756bfecb | 1,132 | h | C | src/common/engine/idownloadsystem.h | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/common/engine/idownloadsystem.h | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/common/engine/idownloadsystem.h | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
//=======================================================================================//
#ifndef IDOWNLOADSYSTEM_H
#define IDOWNLOADSYSTEM_H
#ifdef _WIN32
#pragma once
#endif
//----------------------------------------------------------------------------------------
#include "interface.h"
#if defined( WIN32 ) && !defined( _X360 ) // DWORD
#include "winlite.h"
#include <windows.h>
#else
#include "platform.h"
#endif
//----------------------------------------------------------------------------------------
#define INTERFACEVERSION_DOWNLOADSYSTEM "DownloadSystem001"
//----------------------------------------------------------------------------------------
struct RequestContext_t;
//----------------------------------------------------------------------------------------
class IDownloadSystem : public IBaseInterface {
public:
virtual DWORD CreateDownloadThread(RequestContext_t *pContext) = 0;
};
//----------------------------------------------------------------------------------------
#endif // IDOWNLOADSYSTEM_H | 27.609756 | 91 | 0.369258 |
bb012cc3061742e3a69ad4396a04b5dffb97fc2a | 1,988 | h | C | bsp/airm2m/air105/libraries/HAL_Driver/Inc/core_timer.h | cazure/rt-thread | 1bdde743433d331740766c895ff867df6268df20 | [
"Apache-2.0"
] | 1 | 2022-03-02T12:48:01.000Z | 2022-03-02T12:48:01.000Z | bsp/airm2m/air105/libraries/HAL_Driver/Inc/core_timer.h | cazure/rt-thread | 1bdde743433d331740766c895ff867df6268df20 | [
"Apache-2.0"
] | 1 | 2018-12-20T00:02:50.000Z | 2018-12-20T00:02:50.000Z | bsp/airm2m/air105/libraries/HAL_Driver/Inc/core_timer.h | cazure/rt-thread | 1bdde743433d331740766c895ff867df6268df20 | [
"Apache-2.0"
] | 1 | 2022-01-25T02:14:32.000Z | 2022-01-25T02:14:32.000Z | /*
* Copyright (c) 2022 OpenLuat & AirM2M
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __CORE_TIMER_H__
#define __CORE_TIMER_H__
typedef enum
{
TIMER_SN_START = 0,
TIMER_SN_MAX,
}STATIC_TIMER_ENUM;
typedef struct Timer_InfoStruct Timer_t;
/*********************************TimerList*****************************************/
void Timer_Init(void);
//void Timer_Task(void *Param);
//void Timer_Run(void);
Timer_t * Timer_Create(CBFuncEx_t CB, void *Param, void *NotifyTask);
Timer_t * Timer_GetStatic(uint32_t Sn, CBFuncEx_t CB, void *Param, void *NotifyTask);
int Timer_Start(Timer_t *Timer, uint64_t Tick, uint8_t IsRepeat);
int Timer_StartMS(Timer_t *Timer, uint32_t MS, uint8_t IsRepeat);
int Timer_StartUS(Timer_t *Timer, uint32_t US, uint8_t IsRepeat);
void Timer_Stop(Timer_t *Timer);
void Timer_Release(Timer_t *Timer);
uint32_t Timer_NextToRest(void);
uint8_t Timer_IsRunning(Timer_t *Timer);
void Timer_PrintAll(void);
#endif
| 40.571429 | 85 | 0.744467 |
1803e6aa0c1e03ea9ae8eeb6e19a64862df00036 | 12,027 | h | C | darkness-engine/include/components/Camera.h | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 6 | 2019-10-17T11:31:55.000Z | 2022-02-11T08:51:20.000Z | darkness-engine/include/components/Camera.h | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 1 | 2020-08-11T09:01:29.000Z | 2020-08-11T09:01:29.000Z | darkness-engine/include/components/Camera.h | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 1 | 2020-06-02T15:48:20.000Z | 2020-06-02T15:48:20.000Z | #pragma once
#include "engine/EngineComponent.h"
#include "engine/primitives/Quaternion.h"
#include "engine/primitives/Vector3.h"
#include "engine/primitives/Matrix4.h"
#include "engine/graphics/Resources.h"
#include "engine/graphics/Device.h"
#include "tools/image/Image.h"
#include "tools/Property.h"
#include "components/Transform.h"
#include "components/PostprocessComponent.h"
#include "tools/hash/Hash.h"
#include <memory>
namespace engine
{
struct ViewCornerRays
{
Vector3f topLeft;
Vector3f topRight;
Vector3f bottomLeft;
Vector3f bottomRight;
};
enum class Projection
{
Perspective,
Orthographic
};
std::string projectionToString(const Projection& projection);
Projection stringToProjection(const std::string& projection);
constexpr int HaltonValueCount = 16;
class Camera : public EngineComponent
{
Property m_width;
Property m_height;
Property m_nearPlane;
Property m_farPlane;
Property m_fieldOfView;
Property m_projection;
Property m_followSpeed;
Property m_environmentMap;
Property m_environmentMapStrength;
Property m_exposure;
Property m_pbrShadingModel;
std::shared_ptr<Transform> m_transform;
std::shared_ptr<image::ImageIf> m_environmentMapImage;
std::unique_ptr<TextureSRV> m_environmentMapSRV;
std::unique_ptr<TextureSRV> m_environmentIrradianceSRV;
std::unique_ptr<TextureSRV> m_environmentBrdfLUTSRV;
std::unique_ptr<TextureSRV> m_environmentSpecularSRV;
bool m_cpuDirty;
bool m_gpuDirty;
public:
std::shared_ptr<EngineComponent> clone() const override
{
auto res = std::make_shared<engine::Camera>();
res->name(m_name);
res->width(width());
res->height(height());
res->nearPlane(nearPlane());
res->farPlane(farPlane());
res->fieldOfView(fieldOfView());
res->projection(projection());
res->followSpeed(followSpeed());
res->environmentMapPath(environmentMapPath());
res->environmentMapStrength(environmentMapStrength());
res->exposure(exposure());
res->pbrShadingModel(pbrShadingModel());
res->smoothPosition(smoothPosition());
res->target(target());
return res;
}
Camera()
: m_width{ this, "width", int(1024) }
, m_height{ this, "height", int(1024) }
, m_nearPlane{ this, "near", float(0.1f) }
, m_farPlane{ this, "far", float(1000.0f) }
, m_fieldOfView{ this, "fov", float(60.0f) }
, m_projection{ this, "projection", Projection::Perspective }
, m_followSpeed{ this, "followspeed", float(1.0f) }
, m_environmentMap{ this, "environment map", std::string(""), [this]() { this->m_cpuDirty = true; } }
, m_environmentMapStrength{ this, "environment strength", float(1.0f) }
, m_exposure{ this, "exposure", 1.0f }
, m_pbrShadingModel{ this, "PBR Shading Model", engine::ButtonToggle::NotPressed }
, m_smoothPosition{ 0.0f, 0.0f, 0.0f }
, m_forward{ 0.0f, 0.0f, 1.0f }
, m_up{ 0.0f, 1.0f, 0.0f }
, m_right{ 1.0f, 0.0f, 0.0f }
, m_environmentMapSRV{ std::make_unique<TextureSRV>() }
, m_environmentIrradianceSRV{ std::make_unique<TextureSRV>() }
, m_environmentSpecularSRV{ std::make_unique<TextureSRV>() }
, m_environmentBrdfLUTSRV{ std::make_unique<TextureSRV>() }
{
m_name = "Camera";
createHaltonValues();
}
Camera(std::shared_ptr<Transform> transform)
: m_width{ this, "width", int(1024) }
, m_height{ this, "height", int(1024) }
, m_nearPlane{ this, "near", float(0.1f) }
, m_farPlane{ this, "far", float(1000.0f) }
, m_fieldOfView{ this, "fov", float(60.0f) }
, m_projection{ this, "projection", Projection::Perspective }
, m_followSpeed{ this, "followspeed", float(1.0f) }
, m_environmentMap{ this, "environment map", std::string(""), [this]() { this->m_cpuDirty = true; } }
, m_environmentMapStrength{ this, "environment strength", float(1.0f) }
, m_exposure{ this, "exposure", 1.0f }
, m_pbrShadingModel{ this, "PBR Shading Model", engine::ButtonToggle::NotPressed }
, m_smoothPosition{ 0.0f, 0.0f, 0.0f }
, m_forward{ 0.0f, 0.0f, 1.0f }
, m_up{ 0.0f, 1.0f, 0.0f }
, m_right{ 1.0f, 0.0f, 0.0f }
, m_transform{ transform }
, m_environmentMapSRV{ std::make_unique<TextureSRV>() }
, m_environmentIrradianceSRV{ std::make_unique<TextureSRV>() }
, m_environmentSpecularSRV{ std::make_unique<TextureSRV>() }
, m_environmentBrdfLUTSRV{ std::make_unique<TextureSRV>() }
{
m_name = "Camera";
createHaltonValues();
}
void invalidateGpu()
{
m_gpuDirty = true;
}
void cpuRefresh(Device& device)
{
if (m_cpuDirty)
{
m_cpuDirty = false;
if (m_environmentMap.value<std::string>() != "")
m_environmentMapImage = device.createImage(
tools::hash(m_environmentMap.value<std::string>()),
m_environmentMap.value<std::string>());
else
m_environmentMapImage = nullptr;
m_gpuDirty = true;
}
}
void gpuRefresh(Device& device)
{
if (m_gpuDirty)
{
m_gpuDirty = false;
auto path = m_environmentMap.value<std::string>();
if (path != "" && m_environmentMapImage)
{
m_environmentMapSRV = std::make_unique<TextureSRV>(device.createTextureSRV(
tools::hash(path),
TextureDescription()
.name("Environment Cubemap")
.width(static_cast<uint32_t>(m_environmentMapImage->width()))
.height(static_cast<uint32_t>(m_environmentMapImage->height()))
.format(m_environmentMapImage->format())
.arraySlices(static_cast<uint32_t>(m_environmentMapImage->arraySlices()))
.dimension(m_environmentMapImage->arraySlices() == 6 ? ResourceDimension::TextureCubemap : ResourceDimension::Texture2D)
.mipLevels(static_cast<uint32_t>(m_environmentMapImage->mipCount()))
.setInitialData(TextureDescription::InitialData(
std::vector<uint8_t>(m_environmentMapImage->data(), m_environmentMapImage->data() + m_environmentMapImage->bytes()),
static_cast<uint32_t>(m_environmentMapImage->width()), static_cast<uint32_t>(m_environmentMapImage->width() * m_environmentMapImage->height())))));
}
else
{
m_environmentMapSRV = std::make_unique<TextureSRV>();
}
}
}
void start() override
{
m_transform = getComponent<Transform>();
}
int width() const;
void width(int _width);
int height() const;
void height(int _height);
float nearPlane() const;
void nearPlane(float _near);
float farPlane() const;
void farPlane(float _far);
float fieldOfView() const;
void fieldOfView(float _fov);
bool bloomEnabled()
{
auto post = getComponent<PostprocessComponent>();
return post->bloomEnabled();
}
void bloomEnabled(bool value)
{
auto post = getComponent<PostprocessComponent>();
post->bloomEnabled(value);
}
Projection projection() const;
void projection(Projection _projection);
Quaternionf rotation() const;
void rotation(Quaternionf _rotation);
Vector3f position() const;
void position(Vector3f _position);
void forward(Vector3f forward);
Vector3f forward() const;
void up(Vector3f up);
Vector3f up() const;
void right(Vector3f right);
Vector3f right() const;
void updateDelta(float delta);
Vector3f smoothPosition() const;
void smoothPosition(const Vector3f& smooth)
{
m_smoothPosition = smooth;
}
Vector3f target() const;
void target(Vector3f target);
Matrix4f viewMatrix() const;
Matrix4f viewMatrix(Vector3f withPosition) const;
Matrix4f projectionMatrix() const;
Matrix4f projectionMatrix(Vector2<int> screenSize) const;
Matrix4f jitterMatrix(uint64_t frameNumber, Vector2<int> screenSize) const;
Vector2f jitterValue(uint64_t frameNumber) const;
Matrix4f lookAt(
const Vector3f& position,
const Vector3f& target,
const Vector3f& up) const;
TextureSRV& environmentMap()
{
return *m_environmentMapSRV;
}
void environmentMap(const TextureSRV& srv)
{
m_environmentMapSRV = std::make_unique<TextureSRV>(srv);
}
TextureSRV& environmentIrradiance()
{
return *m_environmentIrradianceSRV;
}
void environmentIrradiance(TextureSRV& srv)
{
m_environmentIrradianceSRV = std::make_unique<TextureSRV>(srv);
}
TextureSRV& environmentBrdfLUT()
{
return *m_environmentBrdfLUTSRV;
}
void environmentBrdfLUT(TextureSRV& srv)
{
m_environmentBrdfLUTSRV = std::make_unique<TextureSRV>(srv);
}
TextureSRV& environmentSpecular()
{
return *m_environmentSpecularSRV;
}
void environmentSpecular(TextureSRV& tex)
{
m_environmentSpecularSRV = std::make_unique<TextureSRV>(tex);
}
const std::string& environmentMapPath() const
{
return m_environmentMap.value<std::string>();
}
void environmentMapPath(const std::string& path)
{
m_environmentMap.value<std::string>(path);
}
float environmentMapStrength() const
{
return m_environmentMapStrength.value<float>();
}
void environmentMapStrength(float val)
{
m_environmentMapStrength.value<float>(val);
}
float followSpeed() const
{
return m_followSpeed.value<float>();
}
void followSpeed(float val)
{
m_followSpeed.value<float>(val);
}
float exposure() const { return m_exposure.value<float>(); }
void exposure(float val) { m_exposure.value<float>(val); }
bool pbrShadingModel() const { return static_cast<bool>(m_pbrShadingModel.value<engine::ButtonToggle>()); }
void pbrShadingModel(bool val) { m_pbrShadingModel.value<engine::ButtonToggle>(static_cast<engine::ButtonToggle>(val)); }
ViewCornerRays viewRays() const;
private:
Vector3f m_target;
Vector3f m_smoothPosition;
Vector3f m_forward;
Vector3f m_up;
Vector3f m_right;
Matrix4f orthographicMatrix() const;
Matrix4f perspectiveMatrix() const;
Matrix4f orthographicMatrix(Vector2<int> screenSize) const;
Matrix4f perspectiveMatrix(Vector2<int> screenSize) const;
void createHaltonValues();
std::vector<Vector2<double>> m_haltonValues;
};
}
| 34.264957 | 175 | 0.580693 |
63cfc6122d6724d82b12524bccda636e8886fafb | 384 | h | C | include/il2cpp/UgMiniMapComponent/__c__DisplayClass61_0.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/UgMiniMapComponent/__c__DisplayClass61_0.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/UgMiniMapComponent/__c__DisplayClass61_0.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void UgMiniMapComponent___c__DisplayClass61_0___ctor (UgMiniMapComponent___c__DisplayClass61_0_o* __this, const MethodInfo* method_info);
void UgMiniMapComponent___c__DisplayClass61_0___ChangeVisibleDigPoint_b__0 (UgMiniMapComponent___c__DisplayClass61_0_o* __this, Dpr_UnderGround_UgFieldManager_DigPointModel_o* x, const MethodInfo* method_info);
| 54.857143 | 210 | 0.893229 |
af9a1afc57488a5933c68c59d620171277fd60a1 | 3,934 | c | C | wrap_wrap_gpio.c | hackerspace/wrap_gpio | 88aa7900a81e3ad46ec20e21fa0406670162ffaf | [
"BSD-3-Clause"
] | 1 | 2020-01-21T10:48:10.000Z | 2020-01-21T10:48:10.000Z | wrap_wrap_gpio.c | hackerspace/wrap_gpio | 88aa7900a81e3ad46ec20e21fa0406670162ffaf | [
"BSD-3-Clause"
] | null | null | null | wrap_wrap_gpio.c | hackerspace/wrap_gpio | 88aa7900a81e3ad46ec20e21fa0406670162ffaf | [
"BSD-3-Clause"
] | null | null | null | #include <sys/io.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
/* This is the offset (this is always the offset on the WRAP board) of the F0BAR0 register */
#define DATA 0xf400
#define CMD_LEN 100
#define MIN_PIN 32
#define MAX_PIN 37
char *cmd, *line, *param;
unsigned int val, oldval;
int stdin_ready() {
struct timeval tv;
fd_set fds;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO (&fds);
FD_SET (0, &fds); //STDIN
select (1, &fds, NULL, NULL, &tv); // number of fds+1
return FD_ISSET (0, &fds);
}
size_t get_line(char *s, size_t n, FILE * f) {
char *p = fgets(s, n, f);
if (p == NULL) return -1;
size_t len = strlen(s);
if (s[len-1] == '\n') {
s[--len] = '\0';
}
return len;
}
int check_pin(int pin_number) {
return (pin_number >= MIN_PIN &&
pin_number <= MAX_PIN &&
pin_number != 36);
}
int get_byte() {
param = strtok(NULL, " ");
if(param == NULL) {
fprintf(stderr, "missing byte parameter\n");
return -1;
}
return atoi(param);
}
int get_pin_param() {
param = strtok(NULL, " ");
if(param == NULL) {
fprintf(stderr, "missing pin parameter\n");
return -1;
}
int pin = atoi(param);
if(!check_pin(pin)) {
fprintf(stderr, "invalid pin: %d\n");
return -1;
}
return pin;
}
int in(int pin) {
// 1 high, 0 low
int res = val & (1 << (pin-32));
return res!=0;
}
void on(int pin) {
val = val | (1 << (pin-32));
outl(val, DATA+0x10);
}
void off(int pin) {
val = val & ~(1 << (pin-32));
outl(val, DATA+0x10);
}
void pulse(int pin) {
on(pin);
off(pin);
}
void shift(int data_pin, int clock_pin, int latch_pin,
unsigned int data) {
unsigned int i = 0;
for(; i < 8; i++) {
off(data_pin);
if(data & (1 << (7-i))) {
on(data_pin);
}
pulse(clock_pin);
}
pulse(latch_pin);
}
int main (int nargs, char **argv) {
int data, pin, data_pin, clock_pin, latch_pin;
unsigned int watch_mask;
int len, err;
/* Request I/O privileges */
iopl (3);
/* Buffers */
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IOLBF, 0);
/*
* Offset 0x14 is GPIO-Data-In-1-Register.
* See table 6-30 on the SC1100 data sheet.
* This register contains 1 bit status for each GPIO in range 32 to 63
*/
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 1000000;
line = malloc(CMD_LEN);
oldval = inl(DATA + 0x14);
for (;;) {
if (stdin_ready() != 0) {
len = get_line(line, CMD_LEN, stdin);
fprintf(stderr, "in: '%s' length: %d\n", line, len);
if(len < 0) break; // EOF
if(!len) continue; // EMPTY
cmd = strtok(line, " ");
if(strncmp(cmd, "IN", CMD_LEN) == 0) {
pin = get_pin_param();
if(pin > 0) {
printf("S %d %d\n", pin, in(pin));
}
}
if(strncmp(cmd, "ON", CMD_LEN) == 0) {
pin = get_pin_param();
if(pin > 0) {
on(pin);
}
}
if(strncmp(cmd, "OFF", CMD_LEN) == 0) {
pin = get_pin_param();
if(pin > 0) {
off(pin);
}
}
if(strncmp(cmd, "SHIFT", CMD_LEN) == 0) {
data_pin = get_pin_param();
clock_pin = get_pin_param();
latch_pin = get_pin_param();
data = get_byte();
if(data_pin > 0 && clock_pin > 0 && latch_pin > 0) {
shift(data_pin, clock_pin, latch_pin, data);
}
}
if(strncmp(cmd, "WATCH", CMD_LEN) == 0) {
pin = get_pin_param();
watch_mask |= 1 << (pin-32);
}
if(strncmp(cmd, "UNWATCH", CMD_LEN) == 0) {
pin = get_pin_param();
watch_mask &= ~(1 << (pin-32));
}
}
/* check states */
val = inl(DATA + 0x14);
if (oldval != val) {
pin = (oldval ^ val) & watch_mask;
if(pin) {
printf("IN%x\n", pin);
}
oldval = val;
}
nanosleep (&ts, NULL);
}
}
| 21.150538 | 93 | 0.535587 |
769e811199f78b2143297d1c37555c2847bae501 | 4,175 | h | C | hand_cpp/source/hog_descriptor.h | LuciaXu/libhand_generate | ed3eda62c91e4eafbac09c4d78a298d6a764140a | [
"CC-BY-3.0"
] | 19 | 2015-11-28T03:49:10.000Z | 2021-04-12T13:19:26.000Z | hand_cpp/source/hog_descriptor.h | LuciaXu/libhand_generate | ed3eda62c91e4eafbac09c4d78a298d6a764140a | [
"CC-BY-3.0"
] | 4 | 2015-12-24T08:53:10.000Z | 2017-11-08T10:58:16.000Z | hand_cpp/source/hog_descriptor.h | jsupancic/libhand-public | da9b92fa5440d06fdd4ba72c2327c50c88a1d469 | [
"CC-BY-3.0"
] | 7 | 2015-12-16T05:27:22.000Z | 2020-08-24T07:59:29.000Z | // Copyright (c) 2011, Marin Saric <marin.saric@gmail.com>
// All rights reserved.
//
// This file is a part of LibHand. LibHand is open-source software. You can
// redistribute it and/or modify it under the terms of the LibHand
// license. The LibHand license is the BSD license with an added clause that
// requires academic citation. You should have received a copy of the
// LibHand license (the license.txt file) along with LibHand. If not, see
// <http://www.libhand.org/>
// HogDescriptor
//
// The HogDescriptor class defines a Histogram of Gradients feature
// descriptor that is an array of histograms. In this HoG
// implementation, the region of interest is divided into
// approximately equal rectangular regions called HoG cells.
//
// Each HoG cell contains a histogram corresponding to the histogram
// of gradients for the portion of the image defined by the hog cell
// rectangle.
//
// The HoG cell rectangle is defined by the HogCellRectangles class
// in hog_cell_rectangles.h
#ifndef HOG_DESCRIPTOR_H
#define HOG_DESCRIPTOR_H
# include <cstring>
# include <vector>
# include "hog_cell.h"
namespace libhand {
using namespace std;
class HogDescriptor {
public:
// Common HoG descriptor constructor
// By default, HogDescriptor stores all the data inside the class.
// However, if the data is stored externally, a pointer to it can be
// passed with hog_data_in.
// All the HoG cells are initialized to 0 with this constructor.
HogDescriptor(int num_rows = kDefaultNumRows,
int num_cols = kDefaultNumCols,
int cell_num_bins = kDefaultCellNumBins,
const float *hog_data_in = NULL);
// This constructor allows for initializing the descriptor from an
// existing vector of floats.
HogDescriptor(int num_rows,
int num_cols,
int cell_num_bins,
const vector<float> &hog_data_in);
// Copy and assignment constructors
HogDescriptor(const HogDescriptor &rhs);
HogDescriptor& operator= (const HogDescriptor &rhs);
// Simple accessors
int num_rows() const { return num_rows_; }
int num_cols() const { return num_cols_; }
int num_cells() const { return num_rows() * num_cols(); }
int cell_num_bins() const { return cell_num_bins_; }
// Simple setters
void Zero();
// Access to individual HoG cells
HogCell &hog_cell(int row, int col) {
return hog_cells_[cell_number(row, col)];
}
const HogCell &hog_cell(int row, int col) const {
return hog_cells_[cell_number(row, col)];
}
// Data-store size (in number of elements)
int data_store_size() const { return num_cells() * cell_num_bins(); }
// The default number of cell rows the image is divided into
static const int kDefaultNumRows = 8;
// The default number of cell column the image is divided into
static const int kDefaultNumCols = 8;
// The default number of histogram bins in a cell
static const int kDefaultCellNumBins = 8;
private:
// Private accessors (read-write and read-only)
float *data_store() { return local_data_store_.data(); };
const float *data_store() const { return local_data_store_.data(); };
// Row-major cell 2D index into row-by-row 1D index
int cell_number(int row, int col) const { return row * num_cols() + col; }
// Access into individual cell data (read-write and read-only)
float *cell_data(int row, int col) {
return data_store() + cell_number(row, col) * cell_num_bins();
}
const float *cell_data(int row, int col) const {
return data_store() + cell_number(row, col) * cell_num_bins();
}
// Utility routines for descriptor initialization and copying
void InitializeHogCells();
void AdjustHogCells(const HogDescriptor &rhs);
void CopyFromRHS(const HogDescriptor &rhs);
// The number of HoG cell rows the image is divided into
int num_rows_;
// The number of HoG cell columns the image is divided into
int num_cols_;
// The number of bins for each HoG cell
int cell_num_bins_;
// Local data store
vector<float> local_data_store_;
// HoG Cell structures
vector<HogCell> hog_cells_;
};
} // namespace libhand
#endif // HOG_DESCRIPTOR_H
| 32.364341 | 76 | 0.716407 |
5b9dffe30656f30095d93b38dad7676c3d2bb9a3 | 3,973 | h | C | src/FWlib/peripheral_gpio.h | ingchips/ING918XX_SDK_SOURCE | 32a87c3809bb4218abe3b75ca8b5a29d702eb325 | [
"Apache-2.0"
] | 9 | 2020-01-15T07:42:08.000Z | 2021-12-06T06:56:09.000Z | src/FWlib/peripheral_gpio.h | ingchips/ING918XX_SDK_SOURCE | 32a87c3809bb4218abe3b75ca8b5a29d702eb325 | [
"Apache-2.0"
] | null | null | null | src/FWlib/peripheral_gpio.h | ingchips/ING918XX_SDK_SOURCE | 32a87c3809bb4218abe3b75ca8b5a29d702eb325 | [
"Apache-2.0"
] | null | null | null | #ifndef __PERIPHERAL_GPIO_H__
#define __PERIPHERAL_GPIO_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "ingsoc.h"
typedef enum
{
GIO_GPIO_0 ,
GIO_GPIO_1 ,
GIO_GPIO_2 ,
GIO_GPIO_3 ,
GIO_GPIO_4 ,
GIO_GPIO_5 ,
GIO_GPIO_6 ,
GIO_GPIO_7 ,
GIO_GPIO_8 ,
GIO_GPIO_9 ,
GIO_GPIO_10 ,
GIO_GPIO_11 ,
GIO_GPIO_12 ,
GIO_GPIO_13 ,
GIO_GPIO_14 ,
GIO_GPIO_15 ,
GIO_GPIO_16 ,
GIO_GPIO_17 ,
GIO_GPIO_18 ,
GIO_GPIO_19 ,
GIO_GPIO_20 ,
GIO_GPIO_21 ,
GIO_GPIO_22 ,
GIO_GPIO_23 ,
GIO_GPIO_24 ,
GIO_GPIO_25 ,
GIO_GPIO_26 ,
GIO_GPIO_27 ,
GIO_GPIO_28 ,
GIO_GPIO_29 ,
GIO_GPIO_30 ,
GIO_GPIO_31
} GIO_Index_t;
typedef enum
{
GIO_DIR_INPUT,
GIO_DIR_OUTPUT,
GIO_DIR_BOTH,
GIO_DIR_NONE // set to tri-state
} GIO_Direction_t;
typedef enum
{
GIO_INT_EN_LOGIC_LOW_OR_FALLING_EDGE = 1,
GIO_INT_EN_LOGIC_HIGH_OR_RISING_EDGE = 2
} GIO_IntTriggerEnable_t;
typedef enum
{
GIO_INT_EDGE,
GIO_INT_LOGIC
} GIO_IntTriggerType_t;
typedef enum
{
GIO_PULL_UP,
GIO_PULL_DOWN
} GIO_PullType_t;
#define GPIO_DI ((__IO uint32_t *)(APB_GIO_BASE+0x00))
#define GPIO_DO ((__IO uint32_t *)(APB_GIO_BASE+0x10))
#define GPIO_OEB ((__IO uint32_t *)(APB_GIO_BASE+0x20))
#define GPIO_IS ((__IO uint32_t *)(APB_GIO_BASE+0x40)) // interrupt status
#define GPIO_LV ((__IO uint32_t *)(APB_GIO_BASE+0x50)) // interrupt type 0-edge 1-level
#define GPIO_PE ((__IO uint32_t *)(APB_GIO_BASE+0x60)) // Positive edge and High Level interrupt enable
#define GPIO_NE ((__IO uint32_t *)(APB_GIO_BASE+0x70)) // Negtive edge and Low Level interrupt enable
/**
* @brief Set I/O direction of a GPIO
*
* @param[in] io_index the GPIO
* @param[in] dir I/O direction
*/
void GIO_SetDirection(const GIO_Index_t io_index, const GIO_Direction_t dir);
/**
* @brief Get current I/O direction of a GPIO
*
* @param[in] io_index the GPIO
* @return I/O direction
*/
GIO_Direction_t GIO_GetDirection(const GIO_Index_t io_index);
/**
* @brief Write output value of a GPIO
*
* @param[in] io_index the GPIO
* @param[in] bit value
*/
void GIO_WriteValue(const GIO_Index_t io_index, const uint8_t bit);
/**
* @brief Write output value of all 32 GPIO
*
* @param[in] value value
*/
static __INLINE void GIO_WriteAll(const uint32_t value) { *GPIO_DO = value; }
/**
* @brief Get current value of a GPIO
*
* @param[in] io_index the GPIO
* @return value
*/
uint8_t GIO_ReadValue(const GIO_Index_t io_index);
/**
* @brief Get current value of all 32 GPIO
*
* @return value
*/
static __INLINE uint32_t GIO_ReadAll(void) { return *GPIO_DI; }
/**
* @brief Config interrupt trigger type of a GPIO
*
* @param[in] io_index the GPIO
* @param[in] enable a combination of GIO_IntTriggerEnable_t.
* If = 0, interrupt triggering is disable for this GPIO.
* @param[in] type logic or edge
*/
void GIO_ConfigIntSource(const GIO_Index_t io_index, const uint8_t enable, const GIO_IntTriggerType_t type);
/**
* @brief Get current interrupt status of a GPIO
*
* @param[in] io_index the GPIO
* @return if interrup is triggered by this GPIO
*/
uint8_t GIO_GetIntStatus(const GIO_Index_t io_index);
/**
* @brief Get current interrupt status of all GPIO
*
* @return interrupt status
*/
static __INLINE uint32_t GIO_GetAllIntStatus(void) { return (*GPIO_IS); }
/**
* @brief Clear current interrupt status of a GPIO
*
* @param[in] io_index the GPIO
*/
void GIO_ClearIntStatus(const GIO_Index_t io_index);
/**
* @brief Clear current interrupt status of all GPIO
*
*/
static __INLINE void GIO_ClearAllIntStatus(void) { *GPIO_IS = 0; }
#ifdef __cplusplus
}
#endif
#endif
| 23.508876 | 108 | 0.656431 |
a0c885c0cbd4c4cb43fb8e9c6d4a054fc5a5a3b8 | 1,174 | h | C | FileGrabber/SystemConfig.h | jsjtsty/FileGrabber | 5f64c2d58eb7cec158df0133ece55837f55a3114 | [
"Apache-2.0"
] | null | null | null | FileGrabber/SystemConfig.h | jsjtsty/FileGrabber | 5f64c2d58eb7cec158df0133ece55837f55a3114 | [
"Apache-2.0"
] | null | null | null | FileGrabber/SystemConfig.h | jsjtsty/FileGrabber | 5f64c2d58eb7cec158df0133ece55837f55a3114 | [
"Apache-2.0"
] | 1 | 2020-06-28T03:57:55.000Z | 2020-06-28T03:57:55.000Z | #pragma once
#include <xercesc/dom/DOM.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax/HandlerBase.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <vector>
class SystemConfig
{
public:
static SystemConfig* getInstance();
enum class ListenMode {
LISTEN,
DISABLED
};
struct ConfigData {
struct {
int Major;
int Minor;
int Fix;
} MinimumVersion;
struct {
bool Enabled;
std::string Path;
} Encryption;
struct DeviceConfig {
std::string Name;
unsigned int SerialNumber;
ListenMode ListenMode;
struct {
bool LimitEnbaled;
bool MaxSizeLimited;
uint64 MaxSize;
bool MaxCountLimited;
uint64 MaxCount;
} Limit;
bool FileListerEnabled;
struct {
bool NormalCopyEnabled;
std::vector<std::wstring> NormalFilters;
bool RegexCopyEnabled;
std::vector<std::wstring> RegexFilters;
} FileCopyer;
};
struct {
bool Enabled;
DeviceConfig DefaultConfig;
std::vector<DeviceConfig> DeviceConfig;
} Service;
};
ConfigData readConfig();
protected:
SystemConfig();
bool CompareVersion(int major, int minor, int fix, int mmajor, int mminor, int mfix);
}; | 20.241379 | 86 | 0.704429 |
17995fa476fa6a8e02e61d2973d682fc49d3511b | 6,676 | h | C | soft/hello/font.h | ElectronAsh/jag_sim | 4010826e758463e925732fa42e9af7918e2737ce | [
"FSFAP"
] | 10 | 2015-11-29T03:11:17.000Z | 2020-11-30T21:18:40.000Z | soft/hello/font.h | ElectronAsh/jag_sim | 4010826e758463e925732fa42e9af7918e2737ce | [
"FSFAP"
] | null | null | null | soft/hello/font.h | ElectronAsh/jag_sim | 4010826e758463e925732fa42e9af7918e2737ce | [
"FSFAP"
] | 1 | 2022-02-20T19:43:06.000Z | 2022-02-20T19:43:06.000Z | #define F_WIDTH 0x08
#define F_HEIGHT 0x08
#define F_CHARSIZE 0x08
#define T_XREZ 320
#define T_YREZ 200
unsigned char textfont[] =
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x81, 0xA5, 0x81,
0xBD, 0x99, 0x81, 0x7E, 0x7E, 0xFF, 0xDB, 0xFF, 0xC3, 0xE7, 0xFF, 0x7E,
0x6C, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x10, 0x38, 0x7C, 0xFE,
0x7C, 0x38, 0x10, 0x00, 0x38, 0x7C, 0x38, 0xFE, 0xFE, 0x7C, 0x38, 0x7C,
0x10, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x7C, 0x00, 0x00, 0x18, 0x3C,
0x3C, 0x18, 0x00, 0x00, 0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF,
0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00, 0xFF, 0xC3, 0x99, 0xBD,
0xBD, 0x99, 0xC3, 0xFF, 0x0F, 0x07, 0x0F, 0x7D, 0xCC, 0xCC, 0xCC, 0x78,
0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x3F, 0x33, 0x3F, 0x30,
0x30, 0x70, 0xF0, 0xE0, 0x7F, 0x63, 0x7F, 0x63, 0x63, 0x67, 0xE6, 0xC0,
0x99, 0x5A, 0x3C, 0xE7, 0xE7, 0x3C, 0x5A, 0x99, 0x80, 0xE0, 0xF8, 0xFE,
0xF8, 0xE0, 0x80, 0x00, 0x02, 0x0E, 0x3E, 0xFE, 0x3E, 0x0E, 0x02, 0x00,
0x18, 0x3C, 0x7E, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x66, 0x66, 0x66, 0x66,
0x66, 0x00, 0x66, 0x00, 0x7F, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x00,
0x3E, 0x63, 0x38, 0x6C, 0x6C, 0x38, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00,
0x7E, 0x7E, 0x7E, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x7E, 0x3C, 0x18, 0xFF,
0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18,
0x7E, 0x3C, 0x18, 0x00, 0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00,
0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0,
0xC0, 0xFE, 0x00, 0x00, 0x00, 0x24, 0x66, 0xFF, 0x66, 0x24, 0x00, 0x00,
0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x7E,
0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x30, 0x78, 0x78, 0x78, 0x30, 0x00, 0x30, 0x00, 0x6C, 0x6C, 0x6C, 0x00,
0x00, 0x00, 0x00, 0x00, 0x6C, 0x6C, 0xFE, 0x6C, 0xFE, 0x6C, 0x6C, 0x00,
0x30, 0x7C, 0xC0, 0x78, 0x0C, 0xF8, 0x30, 0x00, 0x00, 0xC6, 0xCC, 0x18,
0x30, 0x66, 0xC6, 0x00, 0x38, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0x76, 0x00,
0x60, 0x60, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x60,
0x60, 0x30, 0x18, 0x00, 0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00,
0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x30, 0x30, 0xFC,
0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x60,
0x00, 0x00, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x30, 0x30, 0x00, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00,
0x7C, 0xC6, 0xCE, 0xDE, 0xF6, 0xE6, 0x7C, 0x00, 0x30, 0x70, 0x30, 0x30,
0x30, 0x30, 0xFC, 0x00, 0x78, 0xCC, 0x0C, 0x38, 0x60, 0xCC, 0xFC, 0x00,
0x78, 0xCC, 0x0C, 0x38, 0x0C, 0xCC, 0x78, 0x00, 0x1C, 0x3C, 0x6C, 0xCC,
0xFE, 0x0C, 0x1E, 0x00, 0xFC, 0xC0, 0xF8, 0x0C, 0x0C, 0xCC, 0x78, 0x00,
0x38, 0x60, 0xC0, 0xF8, 0xCC, 0xCC, 0x78, 0x00, 0xFC, 0xCC, 0x0C, 0x18,
0x30, 0x30, 0x30, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x78, 0xCC, 0xCC, 0x7C, 0x0C, 0x18, 0x70, 0x00, 0x00, 0x30, 0x30, 0x00,
0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x60,
0x18, 0x30, 0x60, 0xC0, 0x60, 0x30, 0x18, 0x00, 0x00, 0x00, 0xFC, 0x00,
0x00, 0xFC, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x60, 0x00,
0x78, 0xCC, 0x0C, 0x18, 0x30, 0x00, 0x30, 0x00, 0x7C, 0xC6, 0xDE, 0xDE,
0xDE, 0xC0, 0x78, 0x00, 0x30, 0x78, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x66, 0x66, 0xFC, 0x00, 0x3C, 0x66, 0xC0, 0xC0,
0xC0, 0x66, 0x3C, 0x00, 0xF8, 0x6C, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00,
0x7E, 0x60, 0x60, 0x78, 0x60, 0x60, 0x7E, 0x00, 0x7E, 0x60, 0x60, 0x78,
0x60, 0x60, 0x60, 0x00, 0x3C, 0x66, 0xC0, 0xC0, 0xCE, 0x66, 0x3E, 0x00,
0xCC, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0xCC, 0x00, 0x78, 0x30, 0x30, 0x30,
0x30, 0x30, 0x78, 0x00, 0x1E, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78, 0x00,
0xE6, 0x66, 0x6C, 0x78, 0x6C, 0x66, 0xE6, 0x00, 0x60, 0x60, 0x60, 0x60,
0x60, 0x60, 0x7E, 0x00, 0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0x00,
0xC6, 0xE6, 0xF6, 0xDE, 0xCE, 0xC6, 0xC6, 0x00, 0x38, 0x6C, 0xC6, 0xC6,
0xC6, 0x6C, 0x38, 0x00, 0xFC, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00,
0x78, 0xCC, 0xCC, 0xCC, 0xDC, 0x78, 0x1C, 0x00, 0xFC, 0x66, 0x66, 0x7C,
0x6C, 0x66, 0xE6, 0x00, 0x78, 0xCC, 0xE0, 0x70, 0x1C, 0xCC, 0x78, 0x00,
0xFC, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x00, 0xCC, 0xCC, 0xCC, 0xCC,
0xCC, 0xCC, 0xFC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00,
0xC6, 0xC6, 0xC6, 0xD6, 0xFE, 0xEE, 0xC6, 0x00, 0xC6, 0xC6, 0x6C, 0x38,
0x38, 0x6C, 0xC6, 0x00, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x30, 0x78, 0x00,
0xFE, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xFE, 0x00, 0x78, 0x60, 0x60, 0x60,
0x60, 0x60, 0x78, 0x00, 0xC0, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x02, 0x00,
0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00, 0x10, 0x38, 0x6C, 0xC6,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF,
0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0C,
0x7C, 0xCC, 0x76, 0x00, 0xE0, 0x60, 0x60, 0x7C, 0x66, 0x66, 0xDC, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xC0, 0xCC, 0x78, 0x00, 0x1C, 0x0C, 0x0C, 0x7C,
0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0x38, 0x6C, 0x60, 0xF0, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x76, 0xCC,
0xCC, 0x7C, 0x0C, 0xF8, 0xE0, 0x60, 0x6C, 0x76, 0x66, 0x66, 0xE6, 0x00,
0x30, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00, 0x0C, 0x00, 0x0C, 0x0C,
0x0C, 0xCC, 0xCC, 0x78, 0xE0, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0xE6, 0x00,
0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0x00, 0x00, 0xCC, 0xFE,
0xFE, 0xD6, 0xC6, 0x00, 0x00, 0x00, 0xF8, 0xCC, 0xCC, 0xCC, 0xCC, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0xDC, 0x66,
0x66, 0x7C, 0x60, 0xF0, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0x1E,
0x00, 0x00, 0xDC, 0x76, 0x66, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x7C, 0xC0,
0x78, 0x0C, 0xF8, 0x00, 0x10, 0x30, 0x7C, 0x30, 0x30, 0x34, 0x18, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0xCC, 0xCC,
0xCC, 0x78, 0x30, 0x00, 0x00, 0x00, 0xC6, 0xD6, 0xFE, 0xFE, 0x6C, 0x00,
0x00, 0x00, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0xCC, 0xCC,
0xCC, 0x7C, 0x0C, 0xF8, 0x00, 0x00, 0xFC, 0x98, 0x30, 0x64, 0xFC, 0x00,
0x1C, 0x30, 0x30, 0xE0, 0x30, 0x30, 0x1C, 0x00, 0x18, 0x18, 0x18, 0x00,
0x18, 0x18, 0x18, 0x00, 0xE0, 0x30, 0x30, 0x1C, 0x30, 0x30, 0xE0, 0x00,
0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C,
0xC6, 0xC6, 0xFE, 0x00, 0xE9
};
| 67.434343 | 75 | 0.629868 |
c0af65c27d5e569c9ac10cb0ee49fe8030bd0d41 | 565 | c | C | Capitolo 2/Es04/matematica.c | matteogianferrari/Esercizi-di-Programmazione-in-C | 8c92be59f91c679f56167c44ef37bba37e8fe8ca | [
"MIT"
] | null | null | null | Capitolo 2/Es04/matematica.c | matteogianferrari/Esercizi-di-Programmazione-in-C | 8c92be59f91c679f56167c44ef37bba37e8fe8ca | [
"MIT"
] | null | null | null | Capitolo 2/Es04/matematica.c | matteogianferrari/Esercizi-di-Programmazione-in-C | 8c92be59f91c679f56167c44ef37bba37e8fe8ca | [
"MIT"
] | null | null | null | /* Author: Matteo Gianferrari
* Data: 16/02/2022
*/
#include "matematica.h"
/* double semifattoriale(char n)
* Parameters:
* char n; numero di cui calcolare il semifattoriale
*
* Purpose:
* Calcola il semifattoriale del numero in input
*
* Return:
* Se n negativo ritorna -1
* Se n uguale a 0 o 1 ritorna 1
* Altrimenti ritorna n * (n - 2)!!
*
* Notes:
* Funzione ricorsiva.
*/
double semifattoriale(char n){
if(n < 0)
return -1.0;
else if(n == 0 || n == 1)
return 1.0;
else
return n * semifattoriale(n - 2);
}
| 19.482759 | 58 | 0.610619 |
9d5f099cbb46bb7bb7c0c6e763230ef3db284adc | 4,467 | h | C | bindings/gumjs/gumv8platform.h | suy/frida-gum | e43cdd324c8e75548d3634ffe84e85137a972508 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2021-06-10T08:16:43.000Z | 2021-06-10T08:16:43.000Z | bindings/gumjs/gumv8platform.h | suy/frida-gum | e43cdd324c8e75548d3634ffe84e85137a972508 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | bindings/gumjs/gumv8platform.h | suy/frida-gum | e43cdd324c8e75548d3634ffe84e85137a972508 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2015-2020 Ole André Vadla Ravnås <oleavr@nowsecure.com>
*
* Licence: wxWindows Library Licence, Version 3.1
*/
#ifndef __GUM_V8_PLATFORM_H__
#define __GUM_V8_PLATFORM_H__
#include "gumv8bundle.h"
#include "gumscriptscheduler.h"
#include <functional>
#include <map>
#include <unordered_set>
#include <v8/v8-platform.h>
class GumV8Operation;
class GumV8MainContextOperation;
class GumV8ThreadPoolOperation;
class GumV8DelayedThreadPoolOperation;
class GumV8PlatformLocker;
class GumV8PlatformUnlocker;
class GumV8Platform : public v8::Platform
{
public:
GumV8Platform ();
GumV8Platform (const GumV8Platform &) = delete;
GumV8Platform & operator= (const GumV8Platform &) = delete;
~GumV8Platform ();
v8::Isolate * GetIsolate () const { return shared_isolate; }
GumV8Bundle * GetRuntimeBundle () const { return runtime_bundle; }
const gchar * GetRuntimeSourceMap () const;
GumV8Bundle * GetObjCBundle ();
const gchar * GetObjCSourceMap () const;
GumV8Bundle * GetJavaBundle ();
const gchar * GetJavaSourceMap () const;
GumScriptScheduler * GetScheduler () const { return scheduler; }
std::shared_ptr<GumV8Operation> ScheduleOnJSThread (std::function<void ()> f);
std::shared_ptr<GumV8Operation> ScheduleOnJSThread (gint priority,
std::function<void ()> f);
std::shared_ptr<GumV8Operation> ScheduleOnJSThreadDelayed (
guint delay_in_milliseconds, std::function<void ()> f);
std::shared_ptr<GumV8Operation> ScheduleOnJSThreadDelayed (
guint delay_in_milliseconds, gint priority, std::function<void ()> f);
void PerformOnJSThread (std::function<void ()> f);
void PerformOnJSThread (gint priority, std::function<void ()> f);
std::shared_ptr<GumV8Operation> ScheduleOnThreadPool (
std::function<void ()> f);
std::shared_ptr<GumV8Operation> ScheduleOnThreadPoolDelayed (
guint delay_in_milliseconds, std::function<void ()> f);
v8::PageAllocator * GetPageAllocator () override;
int NumberOfWorkerThreads () override;
std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner (
v8::Isolate * isolate) override;
void CallOnWorkerThread (std::unique_ptr<v8::Task> task) override;
void CallDelayedOnWorkerThread (std::unique_ptr<v8::Task> task,
double delay_in_seconds) override;
bool IdleTasksEnabled (v8::Isolate * isolate) override;
std::unique_ptr<v8::JobHandle> PostJob (v8::TaskPriority priority,
std::unique_ptr<v8::JobTask> job_task) override;
double MonotonicallyIncreasingTime () override;
double CurrentClockTimeMillis () override;
v8::ThreadingBackend * GetThreadingBackend () override;
v8::TracingController * GetTracingController () override;
private:
void InitRuntime ();
void Dispose ();
void CancelPendingOperations ();
static void OnFatalError (const char * location, const char * message);
static gboolean PerformMainContextOperation (gpointer data);
static void ReleaseMainContextOperation (gpointer data);
static void ReleaseSynchronousMainContextOperation (gpointer data);
static void PerformThreadPoolOperation (gpointer data);
static void ReleaseThreadPoolOperation (gpointer data);
static gboolean StartDelayedThreadPoolOperation (gpointer data);
static void PerformDelayedThreadPoolOperation (gpointer data);
static void ReleaseDelayedThreadPoolOperation (gpointer data);
GMutex mutex;
v8::Isolate * shared_isolate;
GumV8Bundle * runtime_bundle;
GumV8Bundle * objc_bundle;
GumV8Bundle * java_bundle;
GumScriptScheduler * scheduler;
std::unordered_set<std::shared_ptr<GumV8Operation>> js_ops;
std::unordered_set<std::shared_ptr<GumV8Operation>> pool_ops;
std::map<v8::Isolate *, std::shared_ptr<v8::TaskRunner>> foreground_runners;
std::unique_ptr<v8::PageAllocator> page_allocator;
std::unique_ptr<v8::ArrayBuffer::Allocator> array_buffer_allocator;
std::unique_ptr<v8::ThreadingBackend> threading_backend;
std::unique_ptr<v8::TracingController> tracing_controller;
friend class GumV8MainContextOperation;
friend class GumV8ThreadPoolOperation;
friend class GumV8DelayedThreadPoolOperation;
friend class GumV8PlatformLocker;
friend class GumV8PlatformUnlocker;
};
class GumV8Operation
{
public:
GumV8Operation () = default;
GumV8Operation (const GumV8Operation &) = delete;
GumV8Operation & operator= (const GumV8Operation &) = delete;
virtual ~GumV8Operation () = default;
virtual void Cancel () = 0;
virtual void Await () = 0;
};
#endif
| 37.537815 | 80 | 0.766286 |
99003ae101c7985cdbd1bef5d163f873084379c6 | 6,032 | c | C | Hash.c | Ruthsilvapereira/ED2_20211 | 300d3828ac36df96fc43c65b7a8b3f8b1445f21d | [
"MIT"
] | null | null | null | Hash.c | Ruthsilvapereira/ED2_20211 | 300d3828ac36df96fc43c65b7a8b3f8b1445f21d | [
"MIT"
] | null | null | null | Hash.c | Ruthsilvapereira/ED2_20211 | 300d3828ac36df96fc43c65b7a8b3f8b1445f21d | [
"MIT"
] | null | null | null | //Olá a todos! Estou adiantando a atividade Hash do AVA
//Por gentileza coloque o nome à frente da sua escolha de implementação, comente sempre seu nome em tudo que foi feito e detalhe para melhor entendimento dos demais.
//Tabela Hash
//Sem varrer todas as chaves ou posições, a tabela hash consegue localizar a posição em que o elemento se encontra.
//Função de hash: é a fórmula de matemática que está sendo usada
//Tabela de hash: é o vetor (tabela com todos os valores, resultado da função de hash)
//Tratamento de colisões em hash: usou no exemplo a Lista Simplesmente ligada para tratamento das colisões
//Hash: pode ser usado para criptografia, verificação de integridade do dado (saber se não foi alterado/modificado)
//Hash: não aceita dados duplos (exemplo: nome do aluno, nome do aluno)
// Funções Hash a ser implementada
// 5.2.1 initHash ======> Ruth
// 5.2.2 hash ======> Matheus Santiago
// 5.2.3 containsKey ======> Leandro Klein
// 5.2.4 put ======> Wenderson Farias
// 5.2.5 get ======> Carlos Henrique Teixeira Carneiro
// 5.2.6 removeKey ======> Wallatan França / Mickael Luiz
// 5.2.7 showHashStruct ======> Lucio Lisboa
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Hash.h"
//Inicio
//Nesta função de inicialização iremos percorrer cada posição de nossa tabela de hash inicializando a lista duplamente ligada de cada posição (Definição em http://www.jppreti.com/2019/07/29/tabela-hash/#Hashh)
//init usado é o da DoublyLinkedList, Lista Duplamente Ligada.
void initHash(HashStruct *hashStruct) {
for (int i=0;i<MAX;i++) {
//chamando init de DoublyLinkedList para inicializar cada lista do vetor
init(&(hashStruct->hashes[i]));
}
hashStruct->size = 0;
}
bool isHashEmpty(HashStruct *hashStruct) {
return hashStruct->size==0;
}
// hash (by Matheus Santiago) : Recebe uma chave e calcula qual posição deveremos inserir o dado associado a chave. A chave pode ser um nome, numero ou codigo de barras, normalmente é um dado unico.
int hash(char *key) {
int sum = 0;
// percorremos todos os caracteres da string passada
for (int i = 0; key[i]!=0;i++) {
//acumulamos os códigos ascii de cada letra com um peso
sum+=key[i]*(i+1);
}
return sum%MAX; //retorna o resto da divisão
}
// put by Wenderson Farias / verifica se a chave ja foi inserida na tabela
// caso nao, então é inserido um novo elemento na tabela.
int put(HashStruct *hashStruct, char *key, void *data, compare equal) {
//alterado
if (!containsKey(hashStruct, key, equal)){
//adiciona na fila que está na posição devolvida pela função hash
int res = enqueue(&hashStruct->hashes[hash(key)],data);
//incrementa a qtde de elementos baseado na quantidade inserida por enqueue
hashStruct->size+=res;
return res;, m
}
return 0;
}
// containsKey (by Leandro Klein) : verificar se a chave já existe na tabela de hash.
bool containsKey(HashStruct *hashStruct, char *key, compare equal) {
//calcula a posição
int hashValue = hash(key);//função para descobrir em que lista está a chave.
//busca na fila a posição da chave
int pos = indexOf(&hashStruct->hashes[hashValue], key, equal); //A função indexOf retorna a posição da chave na lista. Caso o retorno seja -1 a chave não está na lista.
return (pos!=-1)?true:false;
}
//Função get by Carlos Henrique: Reqaliza busca no codigo e retorna o dado procurado, se não houverem dados retorna o primeiro nó (sentinela) de valor nulo.
void* get(HashStruct *hashStruct, char *key, compare equal) {
// descobre em qual fila/lista está o dado
int hashValue = hash(key);
//first é nó sentinela, começamos do segundo nó
Node *aux = hashStruct->hashes[hashValue].first->next;
// procuramos o dado na lista
while(aux!=hashStruct->hashes[hashValue].first && !equal(aux->data, key))
aux=aux->next;
return aux->data;
}
// função hash(thiago ramalho) gera uma chave e calcula qual a posição em que deve-se inserir o dado associado a chave, na qual a chave pode ser um nome, código de barras ou número, mas na maioria dos casos é um dado único
int hash(char *key) {
int sum = 0;
for (int i = 0; key[i]!=0;i++) {
sum+=key[i]*(i+1);
}
return sum%MAX;
//Função removeKey (by Wallatan França / Mickael Luiz) remove um par (chave, valor)
void* removeKey(HashStruct *hashStruct, char *key, compare equal) {
int hashValue = hash(key);// após calcular o hash da chave enviada, atribui o valor a váriavel do tipo hashValue
int pos = indexOf(&hashStruct->hashes[hashValue], key, equal);// a váriavel pos tipo int, recebe a posição encontrada por indexOf com base nos parâmetros passados
//remove o valor da posição
void* result = removePos(&hashStruct->hashes[hashValue], pos);
//Verifica se é o unico nó da lista, se nao for, diminui um valor de size em 1
if (result!=NULL) hashStruct->size--;
return result;
}
//função ShowHashStruct por Lucio Lisboa. Função com o proposito de exibir os pares armazenados, ou seja, mostra quantos hash tem e quantos elementos cada hash tem
void showHashStruct(HashStruct *hashStruct, printNode print) {
//printf mostrando na tela quantos elementos a hash tem
printf("There are %d elements in the Hash\n\n",hashStruct->size);
//estrutura de repetição com o intuito de navegar entre as hashes e mostrar quantos elementos cada hash tem
for (int i=0; i < MAX; i++) {
printf("Hash %d has %d elements: ",i,hashStruct->hashes[i].size);
show(&hashStruct->hashes[i],print);
printf("\n");
}
}
//Comandos para compilar codigo completo no goormIDE (Disponivel em: http://www.jppreti.com/2019/07/29/tabela-hash/#Biblioteca)
//gcc DoublyLinkedList.c Hash.c Hash.h DoublyLinkedList.h HashTest.c -o hash
//./hash
//OBSERVAÇÃO: Usar o .h e .c da DoublyLinkedList no comando (DoublyLinkedList.h HashTest.c), pois na biblioteca da Hash tem o include de DoublyLinkedList
| 50.689076 | 222 | 0.703249 |
48d87b1a0fcc96cac64a4a189196fd9c2e5b414e | 957 | h | C | runtime/Heap.h | asheraryam/stabilizer | f1aefc1a3799687670a21d402818e643704d08d6 | [
"Apache-2.0"
] | 430 | 2015-01-05T19:21:10.000Z | 2022-03-29T07:19:18.000Z | runtime/Heap.h | asheraryam/stabilizer | f1aefc1a3799687670a21d402818e643704d08d6 | [
"Apache-2.0"
] | 9 | 2015-01-20T17:42:30.000Z | 2022-03-04T22:05:43.000Z | runtime/Heap.h | asheraryam/stabilizer | f1aefc1a3799687670a21d402818e643704d08d6 | [
"Apache-2.0"
] | 41 | 2015-05-10T17:08:50.000Z | 2022-01-19T01:15:19.000Z | #if !defined(RUNTIME_HEAP_H)
#define RUNTIME_HEAP_H
#include <heaplayers>
#include <shuffleheap.h>
#include "Util.h"
#include "MMapSource.h"
enum {
DataShuffle = 256,
DataProt = PROT_READ | PROT_WRITE,
DataFlags = MAP_PRIVATE | MAP_ANONYMOUS,
DataSize = 0x2000000,
CodeShuffle = 256,
CodeProt = PROT_READ | PROT_WRITE | PROT_EXEC,
CodeFlags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT,
CodeSize = 0x2000000
};
class DataSource : public SizeHeap<FreelistHeap<BumpAlloc<DataSize, MMapSource<DataProt, DataFlags>, 16> > > {};
class CodeSource : public SizeHeap<FreelistHeap<BumpAlloc<CodeSize, MMapSource<CodeProt, CodeFlags>, CODE_ALIGN> > > {};
typedef ANSIWrapper<KingsleyHeap<ShuffleHeap<DataShuffle, DataSource>, DataSource> > DataHeapType;
typedef ANSIWrapper<KingsleyHeap<ShuffleHeap<CodeShuffle, CodeSource>, CodeSource> > CodeHeapType;
DataHeapType* getDataHeap();
CodeHeapType* getCodeHeap();
#endif
| 29.90625 | 120 | 0.746082 |
5b02bb7e0829c69854bee41639286dfb95aa00b2 | 925 | c | C | arch/mips/ralink/clk.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | arch/mips/ralink/clk.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | arch/mips/ralink/clk.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | // SPDX-License-Identifier: GPL-2.0-only
/*
*
* Copyright (C) 2011 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2013 John Crispin <john@phrozen.org>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/export.h>
#include <linux/clkdev.h>
#include <linux/clk.h>
#include <linux/clk-provider.h>
#include <asm/time.h>
#include "common.h"
void ralink_clk_add(const char *dev, unsigned long rate)
{
struct clk *clk = clk_register_fixed_rate(NULL, dev, NULL, 0, rate);
if (!clk)
panic("failed to add clock");
clkdev_create(clk, NULL, "%s", dev);
}
void __init plat_time_init(void)
{
struct clk *clk;
ralink_of_remap();
ralink_clk_init();
clk = clk_get_sys("cpu", NULL);
if (IS_ERR(clk))
panic("unable to get CPU clock, err=%ld", PTR_ERR(clk));
pr_info("CPU Clock: %ldMHz\n", clk_get_rate(clk) / 1000000);
mips_hpt_frequency = clk_get_rate(clk) / 2;
clk_put(clk);
timer_probe();
}
| 21.022727 | 69 | 0.68973 |
12586321357a7f5683eb791880d64795b8d2615d | 630 | h | C | src/gb-lib/gb_factories/apuregisterfactory.h | johannes51/GBEmu | bb85debc8191d7eaa3917c2d441172f97731374c | [
"MIT"
] | null | null | null | src/gb-lib/gb_factories/apuregisterfactory.h | johannes51/GBEmu | bb85debc8191d7eaa3917c2d441172f97731374c | [
"MIT"
] | null | null | null | src/gb-lib/gb_factories/apuregisterfactory.h | johannes51/GBEmu | bb85debc8191d7eaa3917c2d441172f97731374c | [
"MIT"
] | null | null | null | #ifndef APUREGISTERFACTORY_H
#define APUREGISTERFACTORY_H
#include <cstdint>
#include "registerfactory.h"
enum class ApuRegisters {
NR10,
NR11,
NR12,
NR13,
NR14,
NR21,
NR22,
NR23,
NR24,
NR30,
NR31,
NR32,
NR33,
NR34,
NR41,
NR42,
NR43,
NR44,
NR50,
NR51,
NR52
};
class ApuRegisterFactory : public RegisterFactory<ApuRegisters> {
public:
explicit ApuRegisterFactory(const IMemoryViewSP& ioBank)
: RegisterFactory(ioBank, ApuRegisterAddresses)
{
}
private:
static const std::unordered_map<ApuRegisters, address_type> ApuRegisterAddresses;
};
#endif // APUREGISTERFACTORY_H
| 14.318182 | 83 | 0.714286 |
e9ccae015589939d01a200986b132d0d837cd137 | 730 | h | C | include/minix/boot.h | arabusov/minix-ne | 09ee75e5c788013c81ae71685d6b6457a752b296 | [
"BSD-3-Clause"
] | 71 | 2017-04-03T22:37:27.000Z | 2022-02-20T04:27:19.000Z | include/minix/boot.h | arabusov/minix-ne | 09ee75e5c788013c81ae71685d6b6457a752b296 | [
"BSD-3-Clause"
] | 8 | 2020-05-26T20:08:40.000Z | 2020-06-03T21:07:07.000Z | include/minix/boot.h | arabusov/my-minix-1.7.5 | 09ee75e5c788013c81ae71685d6b6457a752b296 | [
"BSD-3-Clause"
] | 30 | 2017-09-26T23:10:58.000Z | 2021-10-01T04:46:12.000Z | /* boot.h */
#ifndef _BOOT_H
#define _BOOT_H
/* Redefine root and root image devices as variables.
* This keeps the diffs small but may cause future confusion.
*/
#define ROOT_DEV (boot_parameters.bp_rootdev)
#define IMAGE_DEV (boot_parameters.bp_ramimagedev)
/* Device numbers of RAM, floppy and hard disk devices.
* h/com.h defines RAM_DEV but only as the minor number.
*/
#define DEV_FD0 0x200
#define DEV_HD0 0x300
#define DEV_RAM 0x100
#define DEV_SCSI 0x700 /* Atari TT only */
/* Structure to hold boot parameters. */
struct bparam_s
{
dev_t bp_rootdev;
dev_t bp_ramimagedev;
unsigned short bp_ramsize;
unsigned short bp_processor;
};
extern struct bparam_s boot_parameters;
#endif /* _BOOT_H */
| 23.548387 | 61 | 0.745205 |
5fd50a8d13be803bce2b53d7eb16d75fbd44d009 | 6,955 | h | C | Reload Pro.cydsn/codegentemp/opamp_pos.h | Aleksei521/ReloadPro_v2_0 | 3c458373e6ac5ade34e00c5e74ac64d8703e30a3 | [
"Apache-2.0"
] | 2 | 2019-10-13T21:11:32.000Z | 2019-10-13T21:11:34.000Z | Reload Pro.cydsn/codegentemp/opamp_pos.h | Aleksei521/ReloadPro_v2_0 | 3c458373e6ac5ade34e00c5e74ac64d8703e30a3 | [
"Apache-2.0"
] | null | null | null | Reload Pro.cydsn/codegentemp/opamp_pos.h | Aleksei521/ReloadPro_v2_0 | 3c458373e6ac5ade34e00c5e74ac64d8703e30a3 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* File Name: opamp_pos.h
* Version 2.20
*
* Description:
* This file contains Pin function prototypes and register defines
*
********************************************************************************
* Copyright 2008-2015, 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_PINS_opamp_pos_H) /* Pins opamp_pos_H */
#define CY_PINS_opamp_pos_H
#include "cytypes.h"
#include "cyfitter.h"
#include "opamp_pos_aliases.h"
/***************************************
* Data Struct Definitions
***************************************/
/**
* \addtogroup group_structures
* @{
*/
/* Structure for sleep mode support */
typedef struct
{
uint32 pcState; /**< State of the port control register */
uint32 sioState; /**< State of the SIO configuration */
uint32 usbState; /**< State of the USBIO regulator */
} opamp_pos_BACKUP_STRUCT;
/** @} structures */
/***************************************
* Function Prototypes
***************************************/
/**
* \addtogroup group_general
* @{
*/
uint8 opamp_pos_Read(void);
void opamp_pos_Write(uint8 value);
uint8 opamp_pos_ReadDataReg(void);
#if defined(opamp_pos__PC) || (CY_PSOC4_4200L)
void opamp_pos_SetDriveMode(uint8 mode);
#endif
void opamp_pos_SetInterruptMode(uint16 position, uint16 mode);
uint8 opamp_pos_ClearInterrupt(void);
/** @} general */
/**
* \addtogroup group_power
* @{
*/
void opamp_pos_Sleep(void);
void opamp_pos_Wakeup(void);
/** @} power */
/***************************************
* API Constants
***************************************/
#if defined(opamp_pos__PC) || (CY_PSOC4_4200L)
/* Drive Modes */
#define opamp_pos_DRIVE_MODE_BITS (3)
#define opamp_pos_DRIVE_MODE_IND_MASK (0xFFFFFFFFu >> (32 - opamp_pos_DRIVE_MODE_BITS))
/**
* \addtogroup group_constants
* @{
*/
/** \addtogroup driveMode Drive mode constants
* \brief Constants to be passed as "mode" parameter in the opamp_pos_SetDriveMode() function.
* @{
*/
#define opamp_pos_DM_ALG_HIZ (0x00u) /**< \brief High Impedance Analog */
#define opamp_pos_DM_DIG_HIZ (0x01u) /**< \brief High Impedance Digital */
#define opamp_pos_DM_RES_UP (0x02u) /**< \brief Resistive Pull Up */
#define opamp_pos_DM_RES_DWN (0x03u) /**< \brief Resistive Pull Down */
#define opamp_pos_DM_OD_LO (0x04u) /**< \brief Open Drain, Drives Low */
#define opamp_pos_DM_OD_HI (0x05u) /**< \brief Open Drain, Drives High */
#define opamp_pos_DM_STRONG (0x06u) /**< \brief Strong Drive */
#define opamp_pos_DM_RES_UPDWN (0x07u) /**< \brief Resistive Pull Up/Down */
/** @} driveMode */
/** @} group_constants */
#endif
/* Digital Port Constants */
#define opamp_pos_MASK opamp_pos__MASK
#define opamp_pos_SHIFT opamp_pos__SHIFT
#define opamp_pos_WIDTH 1u
/**
* \addtogroup group_constants
* @{
*/
/** \addtogroup intrMode Interrupt constants
* \brief Constants to be passed as "mode" parameter in opamp_pos_SetInterruptMode() function.
* @{
*/
#define opamp_pos_INTR_NONE ((uint16)(0x0000u)) /**< \brief Disabled */
#define opamp_pos_INTR_RISING ((uint16)(0x5555u)) /**< \brief Rising edge trigger */
#define opamp_pos_INTR_FALLING ((uint16)(0xaaaau)) /**< \brief Falling edge trigger */
#define opamp_pos_INTR_BOTH ((uint16)(0xffffu)) /**< \brief Both edge trigger */
/** @} intrMode */
/** @} group_constants */
/* SIO LPM definition */
#if defined(opamp_pos__SIO)
#define opamp_pos_SIO_LPM_MASK (0x03u)
#endif
/* USBIO definitions */
#if !defined(opamp_pos__PC) && (CY_PSOC4_4200L)
#define opamp_pos_USBIO_ENABLE ((uint32)0x80000000u)
#define opamp_pos_USBIO_DISABLE ((uint32)(~opamp_pos_USBIO_ENABLE))
#define opamp_pos_USBIO_SUSPEND_SHIFT CYFLD_USBDEVv2_USB_SUSPEND__OFFSET
#define opamp_pos_USBIO_SUSPEND_DEL_SHIFT CYFLD_USBDEVv2_USB_SUSPEND_DEL__OFFSET
#define opamp_pos_USBIO_ENTER_SLEEP ((uint32)((1u << opamp_pos_USBIO_SUSPEND_SHIFT) \
| (1u << opamp_pos_USBIO_SUSPEND_DEL_SHIFT)))
#define opamp_pos_USBIO_EXIT_SLEEP_PH1 ((uint32)~((uint32)(1u << opamp_pos_USBIO_SUSPEND_SHIFT)))
#define opamp_pos_USBIO_EXIT_SLEEP_PH2 ((uint32)~((uint32)(1u << opamp_pos_USBIO_SUSPEND_DEL_SHIFT)))
#define opamp_pos_USBIO_CR1_OFF ((uint32)0xfffffffeu)
#endif
/***************************************
* Registers
***************************************/
/* Main Port Registers */
#if defined(opamp_pos__PC)
/* Port Configuration */
#define opamp_pos_PC (* (reg32 *) opamp_pos__PC)
#endif
/* Pin State */
#define opamp_pos_PS (* (reg32 *) opamp_pos__PS)
/* Data Register */
#define opamp_pos_DR (* (reg32 *) opamp_pos__DR)
/* Input Buffer Disable Override */
#define opamp_pos_INP_DIS (* (reg32 *) opamp_pos__PC2)
/* Interrupt configuration Registers */
#define opamp_pos_INTCFG (* (reg32 *) opamp_pos__INTCFG)
#define opamp_pos_INTSTAT (* (reg32 *) opamp_pos__INTSTAT)
/* "Interrupt cause" register for Combined Port Interrupt (AllPortInt) in GSRef component */
#if defined (CYREG_GPIO_INTR_CAUSE)
#define opamp_pos_INTR_CAUSE (* (reg32 *) CYREG_GPIO_INTR_CAUSE)
#endif
/* SIO register */
#if defined(opamp_pos__SIO)
#define opamp_pos_SIO_REG (* (reg32 *) opamp_pos__SIO)
#endif /* (opamp_pos__SIO_CFG) */
/* USBIO registers */
#if !defined(opamp_pos__PC) && (CY_PSOC4_4200L)
#define opamp_pos_USB_POWER_REG (* (reg32 *) CYREG_USBDEVv2_USB_POWER_CTRL)
#define opamp_pos_CR1_REG (* (reg32 *) CYREG_USBDEVv2_CR1)
#define opamp_pos_USBIO_CTRL_REG (* (reg32 *) CYREG_USBDEVv2_USB_USBIO_CTRL)
#endif
/***************************************
* The following code is DEPRECATED and
* must not be used in new designs.
***************************************/
/**
* \addtogroup group_deprecated
* @{
*/
#define opamp_pos_DRIVE_MODE_SHIFT (0x00u)
#define opamp_pos_DRIVE_MODE_MASK (0x07u << opamp_pos_DRIVE_MODE_SHIFT)
/** @} deprecated */
#endif /* End Pins opamp_pos_H */
/* [] END OF FILE */
| 36.798942 | 111 | 0.591373 |
b168252e6d4843bb6fc70ea9306032a7f0afc5ec | 1,320 | h | C | Chat21/Chat21UI/util/CellConfigurator.h | mohsinalimat/ios-sdk-5 | 71470269a69b6487be9dac1606592889e71f4b56 | [
"MIT"
] | 1 | 2019-06-25T12:26:49.000Z | 2019-06-25T12:26:49.000Z | Chat21/Chat21UI/util/CellConfigurator.h | mohsinalimat/ios-sdk-5 | 71470269a69b6487be9dac1606592889e71f4b56 | [
"MIT"
] | null | null | null | Chat21/Chat21UI/util/CellConfigurator.h | mohsinalimat/ios-sdk-5 | 71470269a69b6487be9dac1606592889e71f4b56 | [
"MIT"
] | null | null | null | //
// CellConfigurator.h
// Chat21
//
// Created by Andrea Sponziello on 28/03/16.
// Copyright © 2016 Frontiere21. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class ChatConversation;
@class ChatImageCache;
@class ChatConversationsVC;
@class ChatDiskImageCache;
static int CONVERSATION_LIST_CELL_SIZE = 120;
@interface CellConfigurator : NSObject
@property(strong, nonatomic) NSArray<ChatConversation *> *conversations;
@property(strong, nonatomic) UITableView *tableView;
@property(strong, nonatomic) ChatDiskImageCache *imageCache;
-(id)initWithTableView:(UITableView *)tableView imageCache:(ChatDiskImageCache *)imageCache conversations:(NSArray<ChatConversation *> *)conversations;
-(UITableViewCell *)configureConversationCell:(ChatConversation *)conversation indexPath:(NSIndexPath *)indexPath;
+(void)changeReadStatus:(ChatConversation *)conversation forCell:(UITableViewCell *)cell;
+(void)archiveLabel:(UITableViewCell *)cell archived:(BOOL)archived;
+(UIImage *)avatarTypeDirect:(BOOL)typeDirect;
+(UIImage *)setupPhotoCell:(UIImageView *)image_view typeDirect:(BOOL)typeDirect imageURL:(NSString *)imageURL imageCache:(ChatDiskImageCache *)imageCache size:(int)size;
+(BOOL)isIndexPathVisible:(NSIndexPath *)indexPath tableView:(UITableView *)tableView;
@end
| 38.823529 | 170 | 0.799242 |
166e01be7df1c10c4f144675e7b5e41cd247f13e | 273 | c | C | BaseDataStructure/TestFloat.c | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 39 | 2020-05-31T06:14:39.000Z | 2021-01-09T11:06:39.000Z | BaseDataStructure/TestFloat.c | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 7 | 2020-06-02T11:04:14.000Z | 2020-06-11T14:11:58.000Z | BaseDataStructure/TestFloat.c | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 20 | 2020-05-31T06:21:57.000Z | 2020-10-01T04:48:38.000Z | //
// Created by Jesson on 2021/2/9.
//
#include <stdio.h>
void main(){
int num =9;
float* pFloat = #
printf("num的数值是%d\n",num);
printf("pFloat的数值是%p\n",pFloat);
*pFloat = 9.0;
printf("num的数值是%d\n",num);
printf("pFloat的数值是%p\n",pFloat);
} | 17.0625 | 36 | 0.575092 |
1d4d5726cb789118d7e00ff10de6dfc588b30b53 | 2,447 | c | C | src/remap/mapping.c | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | 3 | 2017-12-31T05:33:28.000Z | 2021-07-28T01:51:22.000Z | src/remap/mapping.c | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | null | null | null | src/remap/mapping.c | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | 7 | 2017-04-26T18:18:33.000Z | 2020-05-15T08:01:09.000Z | /*
Mapping.c: the guts of remap.
The main entry point is perform_mapping (about halfway down). It is responsible for all the
actual image processing, spec'd by the input and output DDRs, and its parameters "map" and "samp".
5/97, ASF ISAR Tools. By Orion Lawlor.
*/
#include "asf.h"
#include "las.h"
#include "Matrix2D.h"
#include "remap.h"
/****************************Perform_mapping-- the most important call********************
This is the function which does the file I/O and image manipulation.
There are a few caveats:
If complex-valued input is specified, the output DDR must also have a dtype of
either DTYPE_COMPLEXREAL or DTYPE_COMPLEXIMAG.
If either of these options are specified, the output file will be
created in a bizarre way-- only the correct fields of the input image
will be read in, and only those same fields will be written out.
Hence, to generate a correct Complex image, you have to call perform_mapping twice--
once to remap the real fields, and again to remap the imaginary fields.
*/
void perform_mapping(FILE *in, struct DDR *inDDR, FILE *out, struct DDR *outDDR,
mappingFunction map, sampleFunction samp,int bandNo)
{
int x,y,maxOutX=outDDR->ns,maxOutY=outDDR->nl;
float *thisLine=(float *)MALLOC(maxOutX*sizeof(float));
char *outBuf;
char *pixelDescription;
pixelFetcher *getRec=createFetchRec(in,inDDR,outDDR->dtype,bandNo);
int outPixelSize;
outPixelSize=dtype2dsize(outDDR->dtype,&pixelDescription);
outBuf=(char *)MALLOC((unsigned int)(maxOutX*outPixelSize));
printf(" Output Pixel type/size: %s",pixelDescription);
printf(" Sampling Type: %s\n",samp->description);
if (logflag) {
sprintf(logbuf," Output Pixel type/size: %s",pixelDescription);
printLog(logbuf);
sprintf(logbuf," Sampling Type: %s\n",samp->description);
printLog(logbuf);
}
/*Iterate over each pixel of the output image.*/
for (y=0;y<maxOutY;y++)
{
fPoint outPt,inPt;
outPt.y=y;
for (x=0;x<maxOutX;x++)
{
outPt.x=x;
/*Compute the pixel's position in input space...*/
map->doMap((void *)map,outPt,&inPt);
/*Now read that pixel's value and put it in the "thisLine" array as a float...*/
thisLine[x]=samp->doSamp((void *)samp,getRec,inPt);
}
writePixelLine(out,outDDR,y,bandNo,thisLine,outBuf);
}
/* printf("\n\tperform_mapping complete!\n");*/
killFetchRec(getRec);
FREE(thisLine);
FREE(outBuf);
}
| 33.067568 | 98 | 0.692276 |
5929bed352adacca7eae2706446eaff44f0dad23 | 5,981 | h | C | Code/Legacy/CryCommon/CryThread.h | LB-JakubSkoczylas/o3de | 4cf384c2c555919e9e234c02c4d87fa0aef21840 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-08-08T19:54:51.000Z | 2021-08-08T19:54:51.000Z | Code/Legacy/CryCommon/CryThread.h | LB-JakubSkoczylas/o3de | 4cf384c2c555919e9e234c02c4d87fa0aef21840 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Legacy/CryCommon/CryThread.h | LB-JakubSkoczylas/o3de | 4cf384c2c555919e9e234c02c4d87fa0aef21840 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
// Description : Public include file for the multi-threading API.
#pragma once
// Include basic multithread primitives.
#include "MultiThread.h"
#include "BitFiddling.h"
#include <AzCore/std/string/string.h>
//////////////////////////////////////////////////////////////////////////
// Lock types:
//
// CRYLOCK_FAST
// A fast potentially (non-recursive) mutex.
// CRYLOCK_RECURSIVE
// A recursive mutex.
//////////////////////////////////////////////////////////////////////////
enum CryLockType
{
CRYLOCK_FAST = 1,
CRYLOCK_RECURSIVE = 2,
};
#define CRYLOCK_HAVE_FASTLOCK 1
/////////////////////////////////////////////////////////////////////////////
//
// Primitive locks and conditions.
//
// Primitive locks are represented by instance of class CryLockT<Type>
//
//
template<CryLockType Type>
class CryLockT
{
/* Unsupported lock type. */
};
//////////////////////////////////////////////////////////////////////////
// Typedefs.
//////////////////////////////////////////////////////////////////////////
typedef CryLockT<CRYLOCK_RECURSIVE> CryCriticalSection;
typedef CryLockT<CRYLOCK_FAST> CryCriticalSectionNonRecursive;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//
// CryAutoCriticalSection implements a helper class to automatically
// lock critical section in constructor and release on destructor.
//
//////////////////////////////////////////////////////////////////////////
template<class LockClass>
class CryAutoLock
{
private:
LockClass* m_pLock;
CryAutoLock();
CryAutoLock(const CryAutoLock<LockClass>&);
CryAutoLock<LockClass>& operator = (const CryAutoLock<LockClass>&);
public:
CryAutoLock(LockClass& Lock)
: m_pLock(&Lock) { m_pLock->Lock(); }
CryAutoLock(const LockClass& Lock)
: m_pLock(const_cast<LockClass*>(&Lock)) { m_pLock->Lock(); }
~CryAutoLock() { m_pLock->Unlock(); }
};
//////////////////////////////////////////////////////////////////////////
//
// Auto critical section is the most commonly used type of auto lock.
//
//////////////////////////////////////////////////////////////////////////
typedef CryAutoLock<CryCriticalSection> CryAutoCriticalSection;
/////////////////////////////////////////////////////////////////////////////
//
// Threads.
// Base class for runnable objects.
//
// A runnable is an object with a Run() and a Cancel() method. The Run()
// method should perform the runnable's job. The Cancel() method may be
// called by another thread requesting early termination of the Run() method.
// The runnable may ignore the Cancel() call, the default implementation of
// Cancel() does nothing.
class CryRunnable
{
public:
virtual ~CryRunnable() { }
virtual void Run() = 0;
virtual void Cancel() { }
};
// Class holding information about a thread.
//
// A reference to the thread information can be obtained by calling GetInfo()
// on the CrySimpleThread (or derived class) instance.
//
// NOTE:
// If the code is compiled with NO_THREADINFO defined, then the GetInfo()
// method will return a reference to a static dummy instance of this
// structure. It is currently undecided if NO_THREADINFO will be defined for
// release builds!
struct CryThreadInfo
{
// The symbolic name of the thread.
//
// You may set this name directly or through the SetName() method of
// CrySimpleThread (or derived class).
AZStd::string m_Name;
// A thread identification number.
// The number is unique but architecture specific. Do not assume anything
// about that number except for being unique.
//
// This field is filled when the thread is started (i.e. before the Run()
// method or thread routine is called). It is advised that you do not
// change this number manually.
uint32 m_ID;
};
// Simple thread class.
//
// CrySimpleThread is a simple wrapper around a system thread providing
// nothing but system-level functionality of a thread. There are two typical
// ways to use a simple thread:
//
// 1. Derive from the CrySimpleThread class and provide an implementation of
// the Run() (and optionally Cancel()) methods.
// 2. Specify a runnable object when the thread is started. The default
// runnable type is CryRunnable.
//
// The Runnable class specfied as the template argument must provide Run()
// and Cancel() methods compatible with the following signatures:
//
// void Runnable::Run();
// void Runnable::Cancel();
//
// If the Runnable does not support cancellation, then the Cancel() method
// should do nothing.
//
// The same instance of CrySimpleThread may be used for multiple thread
// executions /in sequence/, i.e. it is valid to re-start the thread by
// calling Start() after the thread has been joined by calling WaitForThread().
template<class Runnable = CryRunnable>
class CrySimpleThread;
///////////////////////////////////////////////////////////////////////////////
// Include architecture specific code.
#if AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS
#include <CryThread_pthreads.h>
#define AZ_RESTRICTED_SECTION_IMPLEMENTED
#elif defined(WIN32) || defined(WIN64)
#include <CryThread_windows.h>
#define AZ_RESTRICTED_SECTION_IMPLEMENTED
#elif defined(AZ_RESTRICTED_PLATFORM)
#include AZ_RESTRICTED_FILE(CryThread_h)
#endif
#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
#else
// Put other platform specific includes here!
#include <CryThread_dummy.h>
#endif
#if !defined _CRYTHREAD_CONDLOCK_GLITCH
typedef CryLockT<CRYLOCK_RECURSIVE> CryMutex;
#endif // !_CRYTHREAD_CONDLOCK_GLITCH
// Include all multithreading containers.
#include "MultiThread_Containers.h"
| 31.983957 | 100 | 0.624812 |
df765b7f5d96017e6621af974a890b96dea76512 | 4,190 | c | C | Maligaro/c_lib/c02_empirical_wavelet/output_long_phase_window.c | Leviyu/EQTime | 7f49f2fb6f8c7e84f4579ff4714834177b88a9cc | [
"MIT"
] | 1 | 2018-09-20T19:12:47.000Z | 2018-09-20T19:12:47.000Z | Maligaro/c_lib/c02_empirical_wavelet/output_long_phase_window.c | Leviyu/EQTime | 7f49f2fb6f8c7e84f4579ff4714834177b88a9cc | [
"MIT"
] | null | null | null | Maligaro/c_lib/c02_empirical_wavelet/output_long_phase_window.c | Leviyu/EQTime | 7f49f2fb6f8c7e84f4579ff4714834177b88a9cc | [
"MIT"
] | null | null | null |
#include "hongyulib.h"
#include "ESF.h"
int output_long_phase_window(new_RECORD* my_record, new_INPUT* my_input)
{
printf("--->Output long phase window! \n");
int output_long_phase_window_for_each(new_RECORD* my_record, new_INPUT* my_input);
int count;
for(count = 0; count < my_input->sta_num; count ++)
{
if(my_record[count].beyong_window_flag == -1)
continue;
output_long_phase_window_for_each(&my_record[count], my_input);
}
return 0;
}
int output_long_phase_window_for_each(new_RECORD* my_record, new_INPUT* my_input)
{
char long_win_name[200];
char phase_win_name[200];
double x_long[100000];
double x_phase[100000];
// normalize both long and phase window with amp of long
int max_loc;
double amp;
amplitudeloc(my_record->long_win, (int)( my_record->long_len / my_input->delta) ,&max_loc, &, 0);
int max_loc2;
double amp2;
amplitudeloc(my_record->phase_win,my_record->npts_phase,&max_loc2, &2,1);
if(amp == 0 )
amp =1;
if(amp2 == 0)
amp2 = 1;
// when S gets close to ScS, we make this differently
// when phase is ScS and the distance > 76 and the peak location is within
// the first 7second then we get rid of the first 7 second and find the amplitude
int npts_skip = 50;
if( max_loc2 < npts_skip )
{
double new_cut[3000];
int kkk;
for(kkk = 0; kkk< my_record->npts_phase -npts_skip; kkk++)
{
new_cut[kkk] = my_record->phase_win[kkk+npts_skip];
}
amplitudeloc(new_cut, my_record->npts_phase -npts_skip, &max_loc2, &2,1);
}
else if( max_loc2 > my_record->npts_phase - npts_skip )
{
double new_cut[3000];
int kkk;
for(kkk = 0; kkk< my_record->npts_phase -npts_skip; kkk++)
{
new_cut[kkk] = my_record->phase_win[kkk];
}
amplitudeloc(new_cut, my_record->npts_phase -npts_skip, &max_loc2, &2,1);
}
my_record->long_amplitude = fabs(amp) / amp2;
if( my_record->long_amplitude == 0)
my_record->long_amplitude =1;
if(amp == 0)
amp = 1;
int i;
// ======================================================
// if long_win / phase_win ratio <= 2, we normalize long window to 1
int increment = 5;
// if is PHASE P, then make it 2
if(strstr(my_input->PHASE,"P") != NULL )
increment = 1;
int new_npts_phase = (int) (my_record->npts_phase / increment);
int new_npts_long = (int)(my_record->npts_long / increment);
if(my_record->long_amplitude <=2 )
{
for(i=0;i<new_npts_phase; i++)
{
my_record->phase_win[i] = my_record->phase_win[i*increment] / fabs(amp);
x_phase[i] = my_record->phase_beg + i*increment*my_input->delta;
}
for(i=0;i<new_npts_long;i++)
{
my_record->long_win[i] = my_record->long_win[i*increment] / fabs(amp);
my_record->long_orig[i] = my_record->long_orig[i*increment] / fabs(amp);
x_long[i] = my_record->long_beg + i*increment*my_input->delta;
}
}
// ======================================================
// if long_win / phase_win ratio > 2, we normalize phase win to 1
if(my_record->long_amplitude >2 )
{
//for(i=0;i<my_record->npts_phase;i++)
for(i=0;i<new_npts_phase;i++)
{
my_record->phase_win[i] = my_record->phase_win[i*increment] / fabs(amp2) *0.5;
x_phase[i] = my_record->phase_beg + i*increment*my_input->delta;
}
//for(i=0;i<my_record->npts_long;i++)
for(i=0;i<new_npts_long;i++)
{
my_record->long_win[i] = my_record->long_win[i*increment] / fabs(amp2) * 0.5;
my_record->long_orig[i] = my_record->long_orig[i*increment] / fabs(amp2) * 0.5;
x_long[i] = my_record->long_beg + i*increment*my_input->delta;
}
}
sprintf(long_win_name,"%s.%s.%s.%s.long", my_record->EQ,my_record->name,my_record->PHASE,my_record->COMP);
sprintf(phase_win_name,"%s.%s.%s.%s.phase", my_record->EQ,my_record->name,my_record->PHASE,my_record->COMP);
//output_array2(long_win_name,x_long,my_record->long_orig, my_record->npts_long, 1);
output_array2(long_win_name,x_long,my_record->long_orig, new_npts_long, 1);
output_array2(phase_win_name,x_phase,my_record->phase_win, new_npts_phase, 1);
//output_array2(long_win_name,x_long,my_record->long_orig, my_record->npts_long, 1);
//output_array2(phase_win_name,x_phase,my_record->phase_win, my_record->npts_phase, 1);
return 0;
}
| 31.742424 | 109 | 0.681146 |
be0c5d48098acbedfebe3dc7569962697437acb3 | 1,072 | h | C | lib/FrameworkManager/sample/packages/ProjectPackage/iOSSample/Project/Classes/Controll/ChatCell.h | atarun/web | 86ae10893655396b5c7c1b0b6b21b174388e6628 | [
"MIT"
] | null | null | null | lib/FrameworkManager/sample/packages/ProjectPackage/iOSSample/Project/Classes/Controll/ChatCell.h | atarun/web | 86ae10893655396b5c7c1b0b6b21b174388e6628 | [
"MIT"
] | null | null | null | lib/FrameworkManager/sample/packages/ProjectPackage/iOSSample/Project/Classes/Controll/ChatCell.h | atarun/web | 86ae10893655396b5c7c1b0b6b21b174388e6628 | [
"MIT"
] | null | null | null | //
// ABCell.h
// Withly
//
// Created by admin on 7/24/13.
// Copyright (c) 2013 n00886. All rights reserved.
//
#import "common.h"
#import "ChatRoomViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MediaPlayer/MediaPlayer.h>
#define TABLE_VIEW_HEIGHT_FOR_ROW 65
#define SELECTED_FONT_COLOR [UIColor colorWithRed:1.00 green:0.67 blue:0.00 alpha:1.0]
@interface ChatCell : UITableViewCell
{
UIImageView *thumbImageView;
MPMoviePlayerController *player;
ChatRoomViewController *parentViewController;
}
@property (strong, nonatomic) UIImageView *thumbImageView;
@property (strong, nonatomic) UILabel *lblLike;
@property (strong, nonatomic) UIButton *likeButton;
@property (strong, nonatomic) MPMoviePlayerController *player;
@property (strong, nonatomic) ChatRoomViewController *parentViewController;
@property (strong, nonatomic) NSIndexPath *indexpath;
- (id)init:(UITableViewCellStyle)style :(NSString *)reuseIdentifier :(NSURL *)argMovieURL :(NSIndexPath *)index :(NSString *)like;
@end
| 30.628571 | 130 | 0.767724 |
3dc6eeed87e3cf2c63a06ddb76c7ddd4c1c0c866 | 4,731 | h | C | sim/RegressionMemory.h | snumrl/CAR | af2ef26860bae56c42df71df0de4682d4898f380 | [
"Apache-2.0"
] | 2 | 2022-01-28T08:47:27.000Z | 2022-03-31T10:56:21.000Z | sim/RegressionMemory.h | snumrl/CAR | af2ef26860bae56c42df71df0de4682d4898f380 | [
"Apache-2.0"
] | null | null | null | sim/RegressionMemory.h | snumrl/CAR | af2ef26860bae56c42df71df0de4682d4898f380 | [
"Apache-2.0"
] | null | null | null | #ifndef __REGMEM_H__
#define __REGMEM_H__
#include <vector>
#include <string>
#include <map>
#include <Eigen/Dense>
#include <random>
template<>
struct std::less<Eigen::VectorXd>
{
bool operator()(Eigen::VectorXd const& a, Eigen::VectorXd const& b) const {
assert(a.size() == b.size());
for(size_t i = 0; i < a.size(); i++)
{
if(a[i] < b[i])
return true;
if(a[i] > b[i])
return false;
}
return false;
}
};
namespace DPhy
{
struct Param
{
Eigen::VectorXd param_normalized;
std::vector<Eigen::VectorXd> cps;
double reward;
int update;
};
class ParamCube
{
public:
ParamCube(Eigen::VectorXd i) { idx = i; activated = false; }
Eigen::VectorXd GetIdx(){ return idx; }
void PutParam(Param* p) { param.push_back(p); }
int GetNumParams() { return param.size(); }
std::vector<Param*> GetParams() {return param;}
void PutParams(std::vector<Param*> ps);
void SetActivated(bool ac) { activated = ac; }
bool GetActivated() { return activated;}
private:
Eigen::VectorXd idx;
std::vector<Param*> param;
bool activated;
};
class RegressionMemory
{
public:
RegressionMemory();
void InitParamSpace(Eigen::VectorXd paramBvh, std::pair<Eigen::VectorXd, Eigen::VectorXd> paramSpace , Eigen::VectorXd paramUnit,
double nDOF, double nknots);
void SaveParamSpace(std::string path);
void LoadParamSpace(std::string path);
std::pair<Eigen::VectorXd , bool> UniformSample(int visited);
std::pair<Eigen::VectorXd , bool> UniformSample(double d0, double d1);
bool UpdateParamSpace(std::tuple<std::vector<Eigen::VectorXd>, Eigen::VectorXd, double> candidate);
void AddMapping(Param* p);
void AddMapping(Eigen::VectorXd nearest, Param* p);
void DeleteMappings(Eigen::VectorXd nearest, std::vector<Param*> ps);
double GetDistanceNorm(Eigen::VectorXd p0, Eigen::VectorXd p1);
double GetDensity(Eigen::VectorXd p, bool old=false);
Eigen::VectorXd GetNearestPointOnGrid(Eigen::VectorXd p);
Eigen::VectorXd GetNearestActivatedParam(Eigen::VectorXd p);
std::vector<Eigen::VectorXd> GetNeighborPointsOnGrid(Eigen::VectorXd p, double radius);
std::vector<Eigen::VectorXd> GetNeighborPointsOnGrid(Eigen::VectorXd p, Eigen::VectorXd nearest, double radius);
std::vector<Eigen::VectorXd> GetNeighborParams(Eigen::VectorXd p);
std::vector<std::pair<double, Param*>> GetNearestParams(Eigen::VectorXd p, int n, bool search_neighbor=false, bool old=false, bool inside=false);
Eigen::VectorXd Normalize(Eigen::VectorXd p);
Eigen::VectorXd Denormalize(Eigen::VectorXd p);
void SaveContinuousParamSpace(std::string path);
double GetVisitedRatio();
Eigen::VectorXd GetParamGoal() {return mParamGoalCur; }
void SetParamGoal(Eigen::VectorXd paramGoal);
void SetRadius(double rn) { mRadiusNeighbor = rn; }
void SetParamGridUnit(Eigen::VectorXd gridUnit) { mParamGridUnit = gridUnit;}
int GetDim() {return mDim; }
std::tuple<std::vector<Eigen::VectorXd>,
std::vector<Eigen::VectorXd>,
std::vector<double>> GetTrainingData();
double GetParamReward(Eigen::VectorXd p, Eigen::VectorXd p_goal);
std::vector<Eigen::VectorXd> GetCPSFromNearestParams(Eigen::VectorXd p_goal);
void SaveLog(std::string path);
std::vector<Param*> mloadAllSamples;
int GetNumSamples();
std::pair<double, double> GetExplorationRate() {return std::pair<double, double>(mNewSamplesNearGoal, mUpdatedSamplesNearGoal);}
std::tuple<std::vector<Eigen::VectorXd>,
std::vector<Eigen::VectorXd>,
std::vector<double>,
std::vector<double>> GetParamSpaceSummary();
double GetFitness(Eigen::VectorXd p);
double GetFitnessMean();
private:
std::map<Eigen::VectorXd, int> mParamActivated;
std::map<Eigen::VectorXd, int> mParamDeactivated;
std::map<Eigen::VectorXd, Param*> mParamNew;
std::map<Eigen::VectorXd, std::vector<std::pair<Eigen::VectorXd, double>>> mTrashMap;
Eigen::VectorXd mParamScale;
Eigen::VectorXd mParamScaleInv;
Eigen::VectorXd mParamGoalCur;
Eigen::VectorXd mParamMin;
Eigen::VectorXd mParamMax;
Eigen::VectorXd mParamGridUnit;
Param* mParamBVH;
std::map< Eigen::VectorXd, ParamCube* > mGridMap;
std::vector<std::pair<double, Param*>> mPrevElite;
std::vector<Eigen::VectorXd> mPrevCPS;
double mPrevReward;
double mRadiusNeighbor;
double mThresholdInside;
double mRangeExplore;
int mDim;
int mDimDOF;
int mNumKnots;
int mThresholdUpdate;
int mThresholdActivate;
int mNumElite;
int mNumSamples;
int mExplorationStep;
int mNumGoalCandidate;
int mIdxCandidate;
std::random_device mRD;
std::mt19937 mMT;
std::uniform_real_distribution<double> mUniform;
std::vector<std::string> mRecordLog;
double mEliteGoalDistance;
double mNewSamplesNearGoal;
double mUpdatedSamplesNearGoal;
};
}
#endif | 30.720779 | 146 | 0.732192 |
e1e34f37f79a7590924d9623cd6cb741f2aaeb63 | 2,066 | c | C | 03_Data Structure/Sample Code/CLion/ExerciseBook/02.37/DuLinkList.c | Robert-Stackflow/HUST-Courses | 300752552e7af035b0e5c7663953850c81871242 | [
"MIT"
] | 4 | 2021-11-01T09:27:32.000Z | 2022-03-07T14:24:10.000Z | 03_Data Structure/Sample Code/CLion/ExerciseBook/02.37/DuLinkList.c | Robert-Stackflow/HUST-Courses | 300752552e7af035b0e5c7663953850c81871242 | [
"MIT"
] | null | null | null | 03_Data Structure/Sample Code/CLion/ExerciseBook/02.37/DuLinkList.c | Robert-Stackflow/HUST-Courses | 300752552e7af035b0e5c7663953850c81871242 | [
"MIT"
] | null | null | null | /*=====================
* 双向循环链表
*
* 包含算法: 2.18、2.19
======================*/
#include "DuLinkList.h" //**▲02 线性表**//
/*
* 初始化
*
* 初始化成功则返回OK,否则返回ERROR。
*/
Status InitList(DuLinkList* L) {
*L = (DuLinkList) malloc(sizeof(DuLNode));
if(*L == NULL) {
exit(OVERFLOW);
}
// 前驱和后继均指向自身
(*L)->next = (*L)->prior = *L;
return OK;
}
/*
* ████████ 算法2.18 ████████
*
* 插入
*
* 向双向循环链表第i个位置上插入e,插入成功则返回OK,否则返回ERROR。
*
*【备注】
* 教材中i的含义是元素位置,从1开始计数
*/
Status ListInsert(DuLinkList L, int i, ElemType e) {
DuLinkList p, s;
// 确保双向循环链表存在(但可能为空表)
if(L == NULL) {
return ERROR;
}
// 查找第i个结点位置(引用)
if((p = GetElemP(L, i)) == NULL) {
return ERROR;
}
// 创建新结点
s = (DuLinkList) malloc(sizeof(DuLNode));
if(s == NULL) {
exit(OVERFLOW);
}
s->data = e;
// 将s插入到p的前面,称为第i个结点
s->prior = p->prior;
p->prior->next = s;
s->next = p;
p->prior = s;
return OK;
}
/*
* 遍历
*
* 用visit函数访问双向循环链表L
*/
void ListTraverse(DuLinkList L, void(Visit)(ElemType)) {
DuLinkList p;
// 确保双向循环链表存在
if(L == NULL || L->next == L || L->prior == L) {
return;
}
p = L->next;
while(p != L) {
Visit(p->data);
p = p->next;
}
printf("\n");
}
/*
* 获取循环链表L上第i个元素的引用
*
* ▓▓▓▓ 注 ▓▓▓▓
* 1.加static的含义是当前函数只在DuLinkList中使用,不会被别的文件引用
* 2.假设链表长度为len,且需要获取第len+1个元素的引用时,由于这里是循环链表,所以返回的是头结点
*/
static DuLinkList GetElemP(DuLinkList L, int i) {
DuLinkList p;
int count;
// 确保双向循环链表存在(但可能为空表)
if(L == NULL) {
return NULL;
}
// 位置不合规
if(i < 1) {
return NULL;
}
p = L;
count = 0;
// 尝试查找第i个元素
while(p->next != L && count < i) {
p = p->next;
++count;
}
// 恰好找到第i个元素
if(count == i) {
return p;
}
// 至此,说明p->next==L,此时需要判断i是否过大
if(count + 1 < i) {
return NULL;
}
// 至此,说明需要在len+1的位置上插入元素
return L;
}
| 15.770992 | 56 | 0.467086 |
a3422f2c5ebc8fdd6ba3a495bfcd1709e9eb7416 | 752 | c | C | test/small/union2.c | chrisvrose/deputy-old-mirror | 657350639cfd358ff14090d31813473885c44c7e | [
"BSD-3-Clause"
] | null | null | null | test/small/union2.c | chrisvrose/deputy-old-mirror | 657350639cfd358ff14090d31813473885c44c7e | [
"BSD-3-Clause"
] | null | null | null | test/small/union2.c | chrisvrose/deputy-old-mirror | 657350639cfd358ff14090d31813473885c44c7e | [
"BSD-3-Clause"
] | null | null | null | //no pointers? then no WHEN clause is needed.
//This is from the CCured regression suite
extern int printf(const char * NTS format, ...);
extern void exit(int);
/* Always call E with a non-zero number */
#define E(n) { printf("Error %d\n", n); exit(n); }
typedef unsigned long ULONG;
typedef long LONG;
#ifdef _GNUCC
typedef long long LONGLONG;
#else
typedef __int64 LONGLONG;
#endif
typedef union _LARGE_INTEGER {
struct {
ULONG LowPart;
LONG HighPart;
};
struct {
ULONG LowPart;
LONG HighPart;
} u;
LONGLONG QuadPart;
} LARGE_INTEGER;
int main() {
LARGE_INTEGER foo;
foo.LowPart = 3;
foo.HighPart = 7;
if (foo.u.LowPart != 3) {
E(1);
}
if (foo.u.HighPart != 7) {
E(2);
}
return 0;
}
| 16.347826 | 50 | 0.638298 |
ed2342b8f4c445dbdbea09f37f77b94dcead2589 | 1,051 | h | C | May 25/MathInput.h | gitletH/may-25 | 8b696967a1997df25dace7dbe339a62f1f78798b | [
"MIT"
] | 1 | 2022-02-15T14:56:09.000Z | 2022-02-15T14:56:09.000Z | May 25/MathInput.h | gitletH/may-25 | 8b696967a1997df25dace7dbe339a62f1f78798b | [
"MIT"
] | null | null | null | May 25/MathInput.h | gitletH/may-25 | 8b696967a1997df25dace7dbe339a62f1f78798b | [
"MIT"
] | null | null | null | //******************************************************//
// MathInput.h by Tianjiao Huang, 2016-2018 //
//******************************************************//
#pragma once
#ifndef MATHINPUT_H
#define MATHINPUT_H
// Reference: https://msdn.microsoft.com/en-us/library/windows/desktop/dd371425(v=vs.85).aspx
#include "micaut.h"
#include <atlbase.h> // CComPtr
#include "Imathinput.h" // This should be the lase one
class MathInput;
const _ATL_FUNC_INFO CMathInputControlEventHandler<MathInput>::OnMICInsertInfo = { CC_STDCALL, VT_I4, 1,{ VT_BSTR } };
const _ATL_FUNC_INFO CMathInputControlEventHandler<MathInput>::OnMICCloseInfo = { CC_STDCALL, VT_I4, 0,{ VT_EMPTY } };
class MathInput : public CMathInputControlEventHandler<MathInput>
{
public:
HWND TargetHWND;
CComPtr<IMathInputControl> spMIC; // Math Input Control
std::string RecognitionResult;
public:
HRESULT CreateMathInput();
HRESULT SetParent(HWND hWNd);
HRESULT Show();
void OnInsert(std::wstring result);
};
extern MathInput* g_pMathInput;
#endif // !MATHINPUT_H
| 26.948718 | 118 | 0.67745 |
81d6c78f76759df206e1209aa42883f14ee7a66f | 1,445 | h | C | Twitter-Dumped/7.60.6/_TtC9T1Twitter28TopicEducationViewController.h | ichitaso/TwitterListEnabler | d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df | [
"MIT"
] | 1 | 2019-10-15T09:26:49.000Z | 2019-10-15T09:26:49.000Z | Twitter-Dumped/7.60.6/_TtC9T1Twitter28TopicEducationViewController.h | ichitaso/TwitterListEnabler | d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df | [
"MIT"
] | null | null | null | Twitter-Dumped/7.60.6/_TtC9T1Twitter28TopicEducationViewController.h | ichitaso/TwitterListEnabler | d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df | [
"MIT"
] | 1 | 2019-11-17T06:06:49.000Z | 2019-11-17T06:06:49.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <TFNUI/TFNViewController.h>
@class UIBarButtonItem, UIView;
__attribute__((visibility("hidden")))
@interface _TtC9T1Twitter28TopicEducationViewController : TFNViewController
{
// Error parsing type: , name: topicName
// Error parsing type: , name: legacyScribeMethods
// Error parsing type: , name: richTextInteractionHandlerFactory
// Error parsing type: , name: sourceView
// Error parsing type: , name: sourceRect
// Error parsing type: , name: barButtonItem
// Error parsing type: , name: allowCenteredPresentationWithoutSource
// Error parsing type: , name: sizingViewForModalHeight
// Error parsing type: , name: $__lazy_storage_$_richTextDescription
}
- (void).cxx_destruct;
- (id)initWithNibName:(id)arg1 bundle:(id)arg2;
- (void)viewLayoutMarginsDidChange;
- (void)didTapDismissButton;
- (void)loadView;
- (id)initWithCoder:(id)arg1;
@property(nonatomic) _Bool allowCenteredPresentationWithoutSource; // @synthesize allowCenteredPresentationWithoutSource;
@property(nonatomic, retain) UIBarButtonItem *barButtonItem; // @synthesize barButtonItem;
@property(nonatomic) struct CGRect sourceRect; // @synthesize sourceRect;
@property(nonatomic, retain) UIView *sourceView; // @synthesize sourceView;
@end
| 38.026316 | 121 | 0.750865 |
c2ea148a7b5ddbe400d0341458f86bb51fa07adb | 27,009 | c | C | tg/queries-encrypted.c | mohamad007/lunch | 2dfe26ed15d0278d3993ba3f5061cd0d18733cf4 | [
"MIT"
] | null | null | null | tg/queries-encrypted.c | mohamad007/lunch | 2dfe26ed15d0278d3993ba3f5061cd0d18733cf4 | [
"MIT"
] | null | null | null | tg/queries-encrypted.c | mohamad007/lunch | 2dfe26ed15d0278d3993ba3f5061cd0d18733cf4 | [
"MIT"
] | null | null | null |
/* {{{ Encrypt decrypted */
static int *encr_extra;
static int *encr_ptr;
static int *encr_end;
static char *encrypt_decrypted_message (struct tgl_secret_chat *E) {
static int msg_key[4];
static unsigned char sha1a_buffer[20];
static unsigned char sha1b_buffer[20];
static unsigned char sha1c_buffer[20];
static unsigned char sha1d_buffer[20];
int x = *(encr_ptr);
assert (x >= 0 && !(x & 3));
TGLC_sha1 ((void *)encr_ptr, 4 + x, sha1a_buffer);
memcpy (msg_key, sha1a_buffer + 4, 16);
static unsigned char buf[64];
memcpy (buf, msg_key, 16);
memcpy (buf + 16, E->key, 32);
TGLC_sha1 (buf, 48, sha1a_buffer);
memcpy (buf, E->key + 8, 16);
memcpy (buf + 16, msg_key, 16);
memcpy (buf + 32, E->key + 12, 16);
TGLC_sha1 (buf, 48, sha1b_buffer);
memcpy (buf, E->key + 16, 32);
memcpy (buf + 32, msg_key, 16);
TGLC_sha1 (buf, 48, sha1c_buffer);
memcpy (buf, msg_key, 16);
memcpy (buf + 16, E->key + 24, 32);
TGLC_sha1 (buf, 48, sha1d_buffer);
static unsigned char key[32];
memcpy (key, sha1a_buffer + 0, 8);
memcpy (key + 8, sha1b_buffer + 8, 12);
memcpy (key + 20, sha1c_buffer + 4, 12);
static unsigned char iv[32];
memcpy (iv, sha1a_buffer + 8, 12);
memcpy (iv + 12, sha1b_buffer + 0, 8);
memcpy (iv + 20, sha1c_buffer + 16, 4);
memcpy (iv + 24, sha1d_buffer + 0, 8);
TGLC_aes_key aes_key;
TGLC_aes_set_encrypt_key (key, 256, &aes_key);
TGLC_aes_ige_encrypt ((void *)encr_ptr, (void *)encr_ptr, 4 * (encr_end - encr_ptr), &aes_key, iv, 1);
memset (&aes_key, 0, sizeof (aes_key));
return (void *)msg_key;
}
static void encr_start (void) {
encr_extra = packet_ptr;
packet_ptr += 1; // str len
packet_ptr += 2; // fingerprint
packet_ptr += 4; // msg_key
packet_ptr += 1; // len
}
static void encr_finish (struct tgl_secret_chat *E) {
int l = packet_ptr - (encr_extra + 8);
while (((packet_ptr - encr_extra) - 3) & 3) {
int t;
tglt_secure_random (&t, 4);
out_int (t);
}
*encr_extra = ((packet_ptr - encr_extra) - 1) * 4 * 256 + 0xfe;
encr_extra ++;
*(long long *)encr_extra = E->key_fingerprint;
encr_extra += 2;
encr_extra[4] = l * 4;
encr_ptr = encr_extra + 4;
encr_end = packet_ptr;
memcpy (encr_extra, encrypt_decrypted_message (E), 16);
}
/* }}} */
void tgl_do_send_encr_action (struct tgl_state *TLS, struct tgl_secret_chat *E, struct tl_ds_decrypted_message_action *A) {
long long t;
tglt_secure_random (&t, 8);
int date = time (0);
struct tgl_message_id id = tgl_peer_id_to_random_msg_id (E->id);
tgl_peer_id_t from_id = TLS->our_id;
bl_do_edit_message_encr (TLS, &id, &from_id, &E->id, &date, NULL, 0, NULL, A, NULL, TGLMF_PENDING | TGLMF_OUT | TGLMF_UNREAD | TGLMF_CREATE | TGLMF_CREATED | TGLMF_ENCRYPTED);
struct tgl_message *M = tgl_message_get (TLS, &id);
assert (M);
tgl_do_send_msg (TLS, M, 0, 0);
}
void tgl_do_send_encr_chat_layer (struct tgl_state *TLS, struct tgl_secret_chat *E) {
static struct tl_ds_decrypted_message_action A;
A.magic = CODE_decrypted_message_action_notify_layer;
int layer = TGL_ENCRYPTED_LAYER;
A.layer = &layer;
tgl_do_send_encr_action (TLS, E, &A);
}
void tgl_do_set_encr_chat_ttl (struct tgl_state *TLS, struct tgl_secret_chat *E, int ttl, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_message *M), void *callback_extra) {
static struct tl_ds_decrypted_message_action A;
A.magic = CODE_decrypted_message_action_set_message_t_t_l;
A.layer = &ttl;
tgl_do_send_encr_action (TLS, E, &A);
}
/* {{{ Seng msg (plain text, encrypted) */
static int msg_send_encr_on_answer (struct tgl_state *TLS, struct query *q, void *D) {
struct tgl_message *M = q->extra;
assert (M->flags & TGLMF_ENCRYPTED);
if (M->flags & TGLMF_PENDING) {
bl_do_edit_message_encr (TLS, &M->permanent_id, NULL, NULL,
&M->date,
NULL, 0, NULL, NULL, NULL, M->flags ^ TGLMF_PENDING);
bl_do_msg_update (TLS, &M->permanent_id);
}
if (q->callback) {
((void (*)(struct tgl_state *TLS, void *, int, struct tgl_message *))q->callback) (TLS, q->callback_extra, 1, M);
}
return 0;
}
static int msg_send_encr_on_error (struct tgl_state *TLS, struct query *q, int error_code, int error_len, const char *error) {
struct tgl_message *M = q->extra;
tgl_peer_t *P = tgl_peer_get (TLS, M->to_id);
if (P && P->encr_chat.state != sc_deleted && error_code == 400) {
if (strncmp (error, "ENCRYPTION_DECLINED", 19) == 0) {
bl_do_peer_delete (TLS, P->id);
}
}
if (q->callback) {
((void (*)(struct tgl_state *TLS, void *, int, struct tgl_message *))q->callback) (TLS, q->callback_extra, 0, M);
}
if (M) {
bl_do_message_delete (TLS, &M->permanent_id);
}
return 0;
}
static struct query_methods msg_send_encr_methods = {
.on_answer = msg_send_encr_on_answer,
.on_error = msg_send_encr_on_error,
.type = TYPE_TO_PARAM(messages_sent_encrypted_message),
.name = "send encrypted (message)",
.timeout = 0,
};
/* }}} */
void tgl_do_send_encr_msg_action (struct tgl_state *TLS, struct tgl_message *M, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_message *M), void *callback_extra) {
tgl_peer_t *P = tgl_peer_get (TLS, M->to_id);
if (!P || P->encr_chat.state != sc_ok) {
vlogprintf (E_WARNING, "Unknown encrypted chat\n");
if (callback) {
callback (TLS, callback_extra, 0, 0);
}
return;
}
assert (M->flags & TGLMF_ENCRYPTED);
clear_packet ();
out_int (CODE_messages_send_encrypted_service);
out_int (CODE_input_encrypted_chat);
out_int (M->permanent_id.peer_id);
out_long (M->permanent_id.access_hash);
out_long (M->permanent_id.id);
encr_start ();
out_int (CODE_decrypted_message_layer);
out_random (15 + 4 * (rand () % 3));
out_int (TGL_ENCRYPTED_LAYER);
out_int (2 * P->encr_chat.in_seq_no + (P->encr_chat.admin_id != tgl_get_peer_id (TLS->our_id)));
out_int (2 * P->encr_chat.out_seq_no + (P->encr_chat.admin_id == tgl_get_peer_id (TLS->our_id)) - 2);
out_int (CODE_decrypted_message_service);
out_long (M->permanent_id.id);
switch (M->action.type) {
case tgl_message_action_notify_layer:
out_int (CODE_decrypted_message_action_notify_layer);
out_int (M->action.layer);
break;
case tgl_message_action_set_message_ttl:
out_int (CODE_decrypted_message_action_set_message_t_t_l);
out_int (M->action.ttl);
break;
case tgl_message_action_request_key:
out_int (CODE_decrypted_message_action_request_key);
out_long (M->action.exchange_id);
out_cstring ((void *)M->action.g_a, 256);
break;
case tgl_message_action_accept_key:
out_int (CODE_decrypted_message_action_accept_key);
out_long (M->action.exchange_id);
out_cstring ((void *)M->action.g_a, 256);
out_long (M->action.key_fingerprint);
break;
case tgl_message_action_commit_key:
out_int (CODE_decrypted_message_action_commit_key);
out_long (M->action.exchange_id);
out_long (M->action.key_fingerprint);
break;
case tgl_message_action_abort_key:
out_int (CODE_decrypted_message_action_abort_key);
out_long (M->action.exchange_id);
break;
case tgl_message_action_noop:
out_int (CODE_decrypted_message_action_noop);
break;
default:
assert (0);
}
encr_finish (&P->encr_chat);
tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &msg_send_encr_methods, M, callback, callback_extra);
}
void tgl_do_send_encr_msg (struct tgl_state *TLS, struct tgl_message *M, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_message *M), void *callback_extra) {
if (M->flags & TGLMF_SERVICE) {
tgl_do_send_encr_msg_action (TLS, M, callback, callback_extra);
return;
}
tgl_peer_t *P = tgl_peer_get (TLS, M->to_id);
if (!P || P->encr_chat.state != sc_ok) {
vlogprintf (E_WARNING, "Unknown encrypted chat\n");
if (callback) {
callback (TLS, callback_extra, 0, M);
}
return;
}
assert (M->flags & TGLMF_ENCRYPTED);
clear_packet ();
out_int (CODE_messages_send_encrypted);
out_int (CODE_input_encrypted_chat);
out_int (tgl_get_peer_id (M->to_id));
out_long (P->encr_chat.access_hash);
out_long (M->permanent_id.id);
encr_start ();
out_int (CODE_decrypted_message_layer);
out_random (15 + 4 * (rand () % 3));
out_int (TGL_ENCRYPTED_LAYER);
out_int (2 * P->encr_chat.in_seq_no + (P->encr_chat.admin_id != tgl_get_peer_id (TLS->our_id)));
out_int (2 * P->encr_chat.out_seq_no + (P->encr_chat.admin_id == tgl_get_peer_id (TLS->our_id)) - 2);
out_int (CODE_decrypted_message);
out_long (M->permanent_id.id);
out_int (P->encr_chat.ttl);
out_cstring ((void *)M->message, M->message_len);
switch (M->media.type) {
case tgl_message_media_none:
out_int (CODE_decrypted_message_media_empty);
break;
case tgl_message_media_geo:
out_int (CODE_decrypted_message_media_geo_point);
out_double (M->media.geo.latitude);
out_double (M->media.geo.longitude);
break;
default:
assert (0);
}
encr_finish (&P->encr_chat);
tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &msg_send_encr_methods, M, callback, callback_extra);
}
static int mark_read_encr_on_receive (struct tgl_state *TLS, struct query *q, void *D) {
if (q->callback) {
((void (*)(struct tgl_state *, void *, int))q->callback)(TLS, q->callback_extra, 1);
}
return 0;
}
static int mark_read_encr_on_error (struct tgl_state *TLS, struct query *q, int error_code, int error_len, const char *error) {
tgl_peer_t *P = q->extra;
if (P && P->encr_chat.state != sc_deleted && error_code == 400) {
if (strncmp (error, "ENCRYPTION_DECLINED", 19) == 0) {
bl_do_peer_delete (TLS, P->id);
}
}
return 0;
}
static struct query_methods mark_read_encr_methods = {
.on_answer = mark_read_encr_on_receive,
.on_error = mark_read_encr_on_error,
.type = TYPE_TO_PARAM(bool),
.name = "read encrypted",
.timeout = 0,
};
void tgl_do_messages_mark_read_encr (struct tgl_state *TLS, tgl_peer_id_t id, long long access_hash, int last_time, void (*callback)(struct tgl_state *TLS, void *callback_extra, int), void *callback_extra) {
clear_packet ();
out_int (CODE_messages_read_encrypted_history);
out_int (CODE_input_encrypted_chat);
out_int (tgl_get_peer_id (id));
out_long (access_hash);
out_int (last_time);
tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &mark_read_encr_methods, tgl_peer_get (TLS, id), callback, callback_extra);
}
static int send_encr_file_on_answer (struct tgl_state *TLS, struct query *q, void *D) {
struct tl_ds_messages_sent_encrypted_message *DS_MSEM = D;
struct tgl_message *M = q->extra;
if (M->flags & TGLMF_PENDING) {
bl_do_edit_message_encr (TLS, &M->permanent_id, NULL, NULL, DS_MSEM->date,
NULL, 0, NULL, NULL, DS_MSEM->file, M->flags ^ TGLMF_PENDING);
bl_do_msg_update (TLS, &M->permanent_id);
}
if (q->callback) {
((void (*)(struct tgl_state *, void *, int, struct tgl_message *))q->callback)(TLS, q->callback_extra, 1, M);
}
return 0;
}
static struct query_methods send_encr_file_methods = {
.on_answer = send_encr_file_on_answer,
.on_error = msg_send_encr_on_error,
.type = TYPE_TO_PARAM(messages_sent_encrypted_message),
.name = "send encrypted (file)",
.timeout = 0,
};
static void send_file_encrypted_end (struct tgl_state *TLS, struct send_file *f, void *callback, void *callback_extra) {
out_int (CODE_messages_send_encrypted_file);
out_int (CODE_input_encrypted_chat);
out_int (tgl_get_peer_id (f->to_id));
tgl_peer_t *P = tgl_peer_get (TLS, f->to_id);
assert (P);
out_long (P->encr_chat.access_hash);
long long r;
tglt_secure_random (&r, 8);
out_long (r);
encr_start ();
out_int (CODE_decrypted_message_layer);
out_random (15 + 4 * (rand () % 3));
out_int (TGL_ENCRYPTED_LAYER);
out_int (2 * P->encr_chat.in_seq_no + (P->encr_chat.admin_id != tgl_get_peer_id (TLS->our_id)));
out_int (2 * P->encr_chat.out_seq_no + (P->encr_chat.admin_id == tgl_get_peer_id (TLS->our_id)));
out_int (CODE_decrypted_message);
out_long (r);
out_int (P->encr_chat.ttl);
out_string ("");
int *save_ptr = packet_ptr;
if (f->flags == -1) {
out_int (CODE_decrypted_message_media_photo);
} else if ((f->flags & TGLDF_VIDEO)) {
out_int (CODE_decrypted_message_media_video);
} else if ((f->flags & TGLDF_AUDIO)) {
out_int (CODE_decrypted_message_media_audio);
} else {
out_int (CODE_decrypted_message_media_document);
}
if (f->flags == -1 || !(f->flags & TGLDF_AUDIO)) {
out_cstring ("", 0);
out_int (90);
out_int (90);
}
if (f->flags == -1) {
out_int (f->w);
out_int (f->h);
} else if (f->flags & TGLDF_VIDEO) {
out_int (f->duration);
out_string (tg_mime_by_filename (f->file_name));
out_int (f->w);
out_int (f->h);
} else if (f->flags & TGLDF_AUDIO) {
out_int (f->duration);
out_string (tg_mime_by_filename (f->file_name));
} else {
out_string ("");
out_string (tg_mime_by_filename (f->file_name));
// document
}
out_int (f->size);
out_cstring ((void *)f->key, 32);
out_cstring ((void *)f->init_iv, 32);
int *save_in_ptr = in_ptr;
int *save_in_end = in_end;
in_ptr = save_ptr;
in_end = packet_ptr;
assert (skip_type_any (TYPE_TO_PARAM(decrypted_message_media)) >= 0);
assert (in_ptr == in_end);
in_ptr = save_ptr;
in_end = packet_ptr;
struct tl_ds_decrypted_message_media *DS_DMM = fetch_ds_type_decrypted_message_media (TYPE_TO_PARAM (decrypted_message_media));
in_end = save_in_ptr;
in_ptr = save_in_end;
int date = time (NULL);
encr_finish (&P->encr_chat);
if (f->size < (16 << 20)) {
out_int (CODE_input_encrypted_file_uploaded);
} else {
out_int (CODE_input_encrypted_file_big_uploaded);
}
out_long (f->id);
out_int (f->part_num);
if (f->size < (16 << 20)) {
out_string ("");
}
unsigned char md5[16];
unsigned char str[64];
memcpy (str, f->key, 32);
memcpy (str + 32, f->init_iv, 32);
TGLC_md5 (str, 64, md5);
out_int ((*(int *)md5) ^ (*(int *)(md5 + 4)));
tfree_secure (f->iv, 32);
tgl_peer_id_t from_id = TLS->our_id;
struct tgl_message_id id = tgl_peer_id_to_msg_id (P->id, r);
bl_do_edit_message_encr (TLS, &id, &from_id, &f->to_id, &date, NULL, 0, DS_DMM, NULL, NULL, TGLMF_OUT | TGLMF_UNREAD | TGLMF_ENCRYPTED | TGLMF_CREATE | TGLMF_CREATED);
free_ds_type_decrypted_message_media (DS_DMM, TYPE_TO_PARAM (decrypted_message_media));
struct tgl_message *M = tgl_message_get (TLS, &id);
assert (M);
tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &send_encr_file_methods, M, callback, callback_extra);
tfree_str (f->file_name);
tfree (f, sizeof (*f));
}
void tgl_do_send_location_encr (struct tgl_state *TLS, tgl_peer_id_t peer_id, double latitude, double longitude, unsigned long long flags, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_message *M), void *callback_extra) {
struct tl_ds_decrypted_message_media TDSM;
TDSM.magic = CODE_decrypted_message_media_geo_point;
TDSM.latitude = talloc (sizeof (double));
*TDSM.latitude = latitude;
TDSM.longitude = talloc (sizeof (double));
*TDSM.longitude = longitude;
int date = time (0);
tgl_peer_id_t from_id = TLS->our_id;
tgl_peer_t *P = tgl_peer_get (TLS, peer_id);
struct tgl_message_id id = tgl_peer_id_to_random_msg_id (P->id);;
bl_do_edit_message_encr (TLS, &id, &from_id, &peer_id, &date, NULL, 0, &TDSM, NULL, NULL, TGLMF_UNREAD | TGLMF_OUT | TGLMF_PENDING | TGLMF_CREATE | TGLMF_CREATED | TGLMF_ENCRYPTED);
tfree (TDSM.latitude, sizeof (double));
tfree (TDSM.longitude, sizeof (double));
struct tgl_message *M = tgl_message_get (TLS, &id);
tgl_do_send_encr_msg (TLS, M, callback, callback_extra);
}
/* {{{ Encr accept */
static int send_encr_accept_on_answer (struct tgl_state *TLS, struct query *q, void *D) {
struct tgl_secret_chat *E = tglf_fetch_alloc_encrypted_chat (TLS, D);
if (E->state == sc_ok) {
tgl_do_send_encr_chat_layer (TLS, E);
}
if (q->callback) {
((void (*)(struct tgl_state *, void *, int, struct tgl_secret_chat *))q->callback) (TLS, q->callback_extra, E->state == sc_ok, E);
}
return 0;
}
static int send_encr_request_on_answer (struct tgl_state *TLS, struct query *q, void *D) {
struct tgl_secret_chat *E = tglf_fetch_alloc_encrypted_chat (TLS, D);
if (q->callback) {
((void (*)(struct tgl_state *, void *, int, struct tgl_secret_chat *))q->callback) (TLS, q->callback_extra, E->state != sc_deleted, E);
}
return 0;
}
static int encr_accept_on_error (struct tgl_state *TLS, struct query *q, int error_code, int error_len, const char *error) {
tgl_peer_t *P = q->extra;
if (P && P->encr_chat.state != sc_deleted && error_code == 400) {
if (strncmp (error, "ENCRYPTION_DECLINED", 19) == 0) {
bl_do_peer_delete (TLS, P->id);
}
}
if (q->callback) {
((void (*)(struct tgl_state *, void *, int, struct tgl_secret_chat *))q->callback) (TLS, q->callback_extra, 0, NULL);
}
return 0;
}
static struct query_methods send_encr_accept_methods = {
.on_answer = send_encr_accept_on_answer,
.on_error = encr_accept_on_error,
.type = TYPE_TO_PARAM(encrypted_chat),
.name = "send encrypted (chat accept)",
.timeout = 0,
};
static struct query_methods send_encr_request_methods = {
.on_answer = send_encr_request_on_answer,
.on_error = q_ptr_on_error,
.type = TYPE_TO_PARAM(encrypted_chat),
.name = "send encrypted (chat request)",
.timeout = 0,
};
//int encr_root;
//unsigned char *encr_prime;
//int encr_param_version;
//static TGLC_bn_ctx *ctx;
void tgl_do_send_accept_encr_chat (struct tgl_state *TLS, struct tgl_secret_chat *E, unsigned char *random, void (*callback)(struct tgl_state *TLS,void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra) {
int i;
int ok = 0;
for (i = 0; i < 64; i++) {
if (E->key[i]) {
ok = 1;
break;
}
}
if (ok) {
if (callback) {
callback (TLS, callback_extra, 1, E);
}
return;
} // Already generated key for this chat
assert (E->g_key);
assert (TLS->TGLC_bn_ctx);
unsigned char random_here[256];
tglt_secure_random (random_here, 256);
for (i = 0; i < 256; i++) {
random[i] ^= random_here[i];
}
TGLC_bn *b = TGLC_bn_bin2bn (random, 256, 0);
ensure_ptr (b);
TGLC_bn *g_a = TGLC_bn_bin2bn (E->g_key, 256, 0);
ensure_ptr (g_a);
assert (tglmp_check_g_a (TLS, TLS->encr_prime_bn, g_a) >= 0);
//if (!ctx) {
// ctx = TGLC_bn_ctx_new ();
// ensure_ptr (ctx);
//}
TGLC_bn *p = TLS->encr_prime_bn;
TGLC_bn *r = TGLC_bn_new ();
ensure_ptr (r);
ensure (TGLC_bn_mod_exp (r, g_a, b, p, TLS->TGLC_bn_ctx));
static unsigned char kk[256];
memset (kk, 0, sizeof (kk));
TGLC_bn_bn2bin (r, kk + (256 - TGLC_bn_num_bytes (r)));
static unsigned char sha_buffer[20];
TGLC_sha1 (kk, 256, sha_buffer);
long long fingerprint = *(long long *)(sha_buffer + 12);
//bl_do_encr_chat_set_key (TLS, E, kk, *(long long *)(sha_buffer + 12));
//bl_do_encr_chat_set_sha (TLS, E, sha_buffer);
int state = sc_ok;
bl_do_encr_chat (TLS, tgl_get_peer_id (E->id),
NULL, NULL, NULL, NULL,
kk, NULL, sha_buffer, &state,
NULL, NULL, NULL, NULL, NULL,
&fingerprint,
TGL_FLAGS_UNCHANGED,
NULL, 0
);
clear_packet ();
out_int (CODE_messages_accept_encryption);
out_int (CODE_input_encrypted_chat);
out_int (tgl_get_peer_id (E->id));
out_long (E->access_hash);
ensure (TGLC_bn_set_word (g_a, TLS->encr_root));
ensure (TGLC_bn_mod_exp (r, g_a, b, p, TLS->TGLC_bn_ctx));
static unsigned char buf[256];
memset (buf, 0, sizeof (buf));
TGLC_bn_bn2bin (r, buf + (256 - TGLC_bn_num_bytes (r)));
out_cstring ((void *)buf, 256);
out_long (E->key_fingerprint);
TGLC_bn_clear_free (b);
TGLC_bn_clear_free (g_a);
TGLC_bn_clear_free (r);
tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &send_encr_accept_methods, E, callback, callback_extra);
}
void tgl_do_create_keys_end (struct tgl_state *TLS, struct tgl_secret_chat *U) {
assert (TLS->encr_prime);
TGLC_bn *g_b = TGLC_bn_bin2bn (U->g_key, 256, 0);
ensure_ptr (g_b);
assert (tglmp_check_g_a (TLS, TLS->encr_prime_bn, g_b) >= 0);
TGLC_bn *p = TLS->encr_prime_bn;
ensure_ptr (p);
TGLC_bn *r = TGLC_bn_new ();
ensure_ptr (r);
TGLC_bn *a = TGLC_bn_bin2bn ((void *)U->key, 256, 0);
ensure_ptr (a);
ensure (TGLC_bn_mod_exp (r, g_b, a, p, TLS->TGLC_bn_ctx));
unsigned char *t = talloc (256);
memcpy (t, U->key, 256);
memset (U->key, 0, sizeof (U->key));
TGLC_bn_bn2bin (r, (void *)(((char *)(U->key)) + (256 - TGLC_bn_num_bytes (r))));
static unsigned char sha_buffer[20];
TGLC_sha1 ((void *)U->key, 256, sha_buffer);
long long k = *(long long *)(sha_buffer + 12);
if (k != U->key_fingerprint) {
vlogprintf (E_WARNING, "Key fingerprint mismatch (my 0x%" INT64_PRINTF_MODIFIER "x 0x%" INT64_PRINTF_MODIFIER "x)\n", (unsigned long long)k, (unsigned long long)U->key_fingerprint);
U->state = sc_deleted;
}
memcpy (U->first_key_sha, sha_buffer, 20);
tfree_secure (t, 256);
TGLC_bn_clear_free (g_b);
TGLC_bn_clear_free (r);
TGLC_bn_clear_free (a);
}
void tgl_do_send_create_encr_chat (struct tgl_state *TLS, void *x, unsigned char *random, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra) {
int user_id = (long)x;
int i;
unsigned char random_here[256];
tglt_secure_random (random_here, 256);
for (i = 0; i < 256; i++) {
random[i] ^= random_here[i];
}
TGLC_bn *a = TGLC_bn_bin2bn (random, 256, 0);
ensure_ptr (a);
TGLC_bn *p = TGLC_bn_bin2bn (TLS->encr_prime, 256, 0);
ensure_ptr (p);
TGLC_bn *g = TGLC_bn_new ();
ensure_ptr (g);
ensure (TGLC_bn_set_word (g, TLS->encr_root));
TGLC_bn *r = TGLC_bn_new ();
ensure_ptr (r);
ensure (TGLC_bn_mod_exp (r, g, a, p, TLS->TGLC_bn_ctx));
TGLC_bn_clear_free (a);
static char g_a[256];
memset (g_a, 0, 256);
TGLC_bn_bn2bin (r, (void *)(g_a + (256 - TGLC_bn_num_bytes (r))));
int t = rand ();
while (tgl_peer_get (TLS, TGL_MK_ENCR_CHAT (t))) {
t = rand ();
}
//bl_do_encr_chat_init (TLS, t, user_id, (void *)random, (void *)g_a);
int state = sc_waiting;
int our_id = tgl_get_peer_id (TLS->our_id);
bl_do_encr_chat (TLS, t, NULL, NULL, &our_id, &user_id, random, NULL, NULL, &state, NULL, NULL, NULL, NULL, NULL, NULL, TGLPF_CREATE | TGLPF_CREATED, NULL, 0);
tgl_peer_t *_E = tgl_peer_get (TLS, TGL_MK_ENCR_CHAT (t));
assert (_E);
struct tgl_secret_chat *E = &_E->encr_chat;
clear_packet ();
out_int (CODE_messages_request_encryption);
tgl_peer_t *U = tgl_peer_get (TLS, TGL_MK_USER (E->user_id));
assert (U);
out_int (CODE_input_user);
out_int (E->user_id);
out_long (U ? U->user.access_hash : 0);
out_int (tgl_get_peer_id (E->id));
out_cstring (g_a, 256);
//write_secret_chat_file ();
TGLC_bn_clear_free (g);
TGLC_bn_clear_free (p);
TGLC_bn_clear_free (r);
tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &send_encr_request_methods, E, callback, callback_extra);
}
static int send_encr_discard_on_answer (struct tgl_state *TLS, struct query *q, void *D) {
struct tgl_secret_chat *E = q->extra;
bl_do_peer_delete (TLS, E->id);
if (q->callback) {
((void (*)(struct tgl_state *, void *, int, struct tgl_secret_chat *))q->callback) (TLS, q->callback_extra, 1, E);
}
return 0;
}
static struct query_methods send_encr_discard_methods = {
.on_answer = send_encr_discard_on_answer,
.on_error = q_ptr_on_error,
.type = TYPE_TO_PARAM(bool),
.name = "send encrypted (chat discard)",
.timeout = 0,
};
void tgl_do_discard_secret_chat (struct tgl_state *TLS, struct tgl_secret_chat *E, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra) {
assert (E);
assert (tgl_get_peer_id (E->id) > 0);
if (E->state == sc_deleted || E->state == sc_none) {
if (callback) {
callback (TLS, callback_extra, 0, E);
}
return;
}
clear_packet ();
out_int (CODE_messages_discard_encryption);
out_int (tgl_get_peer_id (E->id));
tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &send_encr_discard_methods, E, callback, callback_extra);
}
static int get_dh_config_on_answer (struct tgl_state *TLS, struct query *q, void *D) {
struct tl_ds_messages_dh_config *DS_MDC = D;
if (DS_MDC->magic == CODE_messages_dh_config) {
assert (DS_MDC->p->len == 256);
bl_do_set_dh_params (TLS, DS_LVAL (DS_MDC->g), (void *)DS_MDC->p->data, DS_LVAL (DS_MDC->version));
} else {
assert (TLS->encr_param_version);
}
unsigned char *random = talloc (256);
assert (DS_MDC->random->len == 256);
memcpy (random, DS_MDC->random->data, 256);
if (q->extra) {
void **x = q->extra;
((void (*)(struct tgl_state *, void *, void *, void *, void *))(*x))(TLS, x[1], random, q->callback, q->callback_extra);
tfree (x, 2 * sizeof (void *));
tfree_secure (random, 256);
} else {
tfree_secure (random, 256);
}
return 0;
}
static struct query_methods get_dh_config_methods = {
.on_answer = get_dh_config_on_answer,
.on_error = q_void_on_error,
.type = TYPE_TO_PARAM(messages_dh_config),
.name = "dh config",
.timeout = 0,
};
void tgl_do_accept_encr_chat_request (struct tgl_state *TLS, struct tgl_secret_chat *E, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra) {
if (E->state != sc_request) {
if (callback) {
callback (TLS, callback_extra, 0, E);
}
return;
}
assert (E->state == sc_request);
clear_packet ();
out_int (CODE_messages_get_dh_config);
out_int (TLS->encr_param_version);
out_int (256);
void **x = talloc (2 * sizeof (void *));
x[0] = tgl_do_send_accept_encr_chat;
x[1] = E;
tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &get_dh_config_methods, x, callback, callback_extra);
}
void tgl_do_create_encr_chat_request (struct tgl_state *TLS, int user_id, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra) {
clear_packet ();
out_int (CODE_messages_get_dh_config);
out_int (TLS->encr_param_version);
out_int (256);
void **x = talloc (2 * sizeof (void *));
x[0] = tgl_do_send_create_encr_chat;
x[1] = (void *)(long)(user_id);
tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &get_dh_config_methods, x, callback, callback_extra);
}
/* }}} */
| 33.385661 | 261 | 0.68592 |
60b89a62058b3bd9a4353b343145488716667d36 | 4,364 | h | C | include/simple_stl/application/stack_application/infix_calculator.h | wujiazheng2020/simple_stl | f04ccd049a92e463bde4c34fed67679fb5822eb9 | [
"MIT"
] | 6 | 2021-08-31T04:44:50.000Z | 2022-03-10T15:15:29.000Z | include/simple_stl/application/stack_application/infix_calculator.h | wujiazheng2020/simple_stl | f04ccd049a92e463bde4c34fed67679fb5822eb9 | [
"MIT"
] | null | null | null | include/simple_stl/application/stack_application/infix_calculator.h | wujiazheng2020/simple_stl | f04ccd049a92e463bde4c34fed67679fb5822eb9 | [
"MIT"
] | null | null | null | /*
* Copyright 2021 Jiazheng Wu
*
* FileName: infix_calculator.h
*
* Author: Jiazheng Wu
* Email: wujiazheng2020@gmail.com
* Licensed under the MIT License
*/
#pragma once
#include "simple_stl/container/stack/stack.h"
#include "simple_stl/container/vector/vector.h"
#include "simple_stl/application/stack_application/math_calculator.h"
namespace sstl {
constexpr const char kOperatorNum = 9;
// should be load using io, but for simplification, ignore it
constexpr const char operator_prior[kOperatorNum][kOperatorNum] = {
/* + */ '>', '>', '<', '<', '<', '<', '<', '>', '>',
/* - */ '>', '>', '<', '<', '<', '<', '<', '>', '>',
/* * */ '>', '>', '>', '>', '<', '<', '<', '>', '>',
/* / */ '>', '>', '>', '>', '<', '<', '<', '>', '>',
/* ^ */ '>', '>', '>', '>', '>', '<', '<', '>', '>',
/* ! */ '>', '>', '>', '>', '>', '>', ' ', '>', '>',
/* ( */ '<', '<', '<', '<', '<', '<', '<', '=', ' ',
/* ) */ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
/* \0 */ '<', '<', '<', '<', '<', '<', '<', ' ', '='
// + - * / ^ ! ( ) \0
};
class InfixCalculator {
public:
static int Calculate(const Vector<char>& seq) {
Stack<char> operator_stack;
Stack<int> num_stack;
operator_stack.Push('E');
int now_index = 0;
// for number
while (!operator_stack.Empty() && now_index < seq.Size()) {
int num = 0;
bool has_digit = false;
while (IsDigit(seq[now_index])) {
num *= 10;
num += (seq[now_index] - '0');
++now_index;
has_digit = true;
}
if (has_digit) {
num_stack.Push(num);
}
switch (operator_prior[CharToIndex(operator_stack.Top())]
[CharToIndex(seq[now_index])]) {
case '<':
operator_stack.Push(seq[now_index]);
++now_index;
break;
case '>':
if (operator_stack.Top() == '!') {
num_stack.Push(MathCalulator::OneOperatorCalculate(
operator_stack.Top(), num_stack.Pop()));
} else {
num_stack.Push(MathCalulator::TwoOpertorCalculate(
operator_stack.Top(), num_stack.Pop(), num_stack.Pop()));
}
operator_stack.Pop();
// don't ++now_index
break;
case '=':
operator_stack.Pop();
++now_index;
break;
default:
++now_index;
break;
}
}
return num_stack.Top();
}
static Vector<char> GetRpnExpression(const Vector<char>& seq) {
Stack<char> operator_stack;
Stack<int> num_stack;
Vector<char> rpn_expression;
operator_stack.Push('E');
int now_index = 0;
// for number
while (!operator_stack.Empty() && now_index < seq.Size()) {
int num = 0;
bool has_digit = false;
while (IsDigit(seq[now_index])) {
num *= 10;
num += (seq[now_index] - '0');
rpn_expression.PushBack(seq[now_index]);
++now_index;
has_digit = true;
}
if (has_digit) {
num_stack.Push(num);
}
switch (operator_prior[CharToIndex(operator_stack.Top())]
[CharToIndex(seq[now_index])]) {
case '<':
operator_stack.Push(seq[now_index]);
++now_index;
break;
case '>':
if (operator_stack.Top() == '!') {
rpn_expression.PushBack('!');
} else {
rpn_expression.PushBack(operator_stack.Top());
num_stack.Pop();
}
operator_stack.Pop();
// don't ++now_index
break;
case '=':
operator_stack.Pop();
++now_index;
break;
default:
++now_index;
break;
}
}
return rpn_expression;
}
private:
static bool IsDigit(const char& my_char) {
return (my_char >= '0' && my_char <= '9');
}
static int CharToIndex(const char& my_char) {
switch (my_char) {
case '+':
return 0;
case '-':
return 1;
case '*':
return 2;
case '/':
return 3;
case '^':
return 4;
case '!':
return 5;
case '(':
return 6;
case ')':
return 7;
case 'E':
return 8;
default:
return 0;
}
}
};
} // namespace sstl
| 26.609756 | 73 | 0.469065 |
c2c008d08786ed2c32e7ece26b54a6d6141d93df | 7,807 | c | C | test/mpm.c | n13l/OpenAAA | 31f07d9b756e81d864acdf1da360633aa09e92f1 | [
"MIT"
] | 10 | 2015-05-06T09:15:54.000Z | 2020-07-08T14:23:17.000Z | test/mpm.c | n13l/OpenAAA | 31f07d9b756e81d864acdf1da360633aa09e92f1 | [
"MIT"
] | null | null | null | test/mpm.c | n13l/OpenAAA | 31f07d9b756e81d864acdf1da360633aa09e92f1 | [
"MIT"
] | 9 | 2016-05-27T17:20:46.000Z | 2019-08-19T00:23:17.000Z | /*
* The MIT License (MIT)
* Copyright (c) 2017 Daniel Kubec <niel@rtfm.cz>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef CONFIG_WIN32
#include <signal.h>
#include <sys/compiler.h>
#include <sys/cpu.h>
#include <sys/log.h>
#include <sys/irq.h>
#include <sys/mpm.h>
#include <list.h>
#include <mem/alloc.h>
#include <mem/pool.h>
#include <buffer.h>
#include <list.h>
#include <dict.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <net/proto.h>
#include <net/stack.h>
int fd;
struct ip_peer {
struct sockaddr_in6 sa;
socklen_t len;
char name[INET6_ADDRSTRLEN];
int fd;
};
static void
socket_init(void)
{
struct sockaddr_in6 sa = {
.sin6_family = AF_INET6,
.sin6_port = htons(6666),
.sin6_addr = in6addr_any
};
if ((fd = socket(AF_INET6, SOCK_STREAM, 0)) == -1)
die("Can not create socket");
socket_reuseaddr(fd);
socket_blocking(fd);
if (bind(fd, (struct sockaddr *)&sa,sizeof(sa)) == -1)
die("Error binding socket");
if (listen(fd, 16) == -1)
die("Error listen socket");
}
static void
socket_fini(void)
{
if (fd != -1)
close(fd);
}
static int
worksvc_ctor(struct task *proc)
{
debug1("worksvc pid: %d started", proc->pid);
return 0;
}
static int
worksvc_dtor(struct task *proc)
{
debug1("worksvc pid: %d exiting", proc->pid);
return 0;
}
static int
worksvc_entry(struct task *proc)
{
return 0;
}
static int
process_ctor(struct task *proc)
{
setproctitle("mpm/%d", proc->index);
debug1("process pid: %d started", proc->pid);
return 0;
}
static int
process_dtor(struct task *proc)
{
debug1("process pid: %d exiting", proc->pid);
return 0;
}
static int
workque_add(struct task *proc, int fd, const char *arg)
{
struct bb bb = { .addr = alloca(PIPE_BUF), .len = PIPE_BUF};
int size = strlen(arg);
for (u8 *u = (u8*)arg; size; size--, u++)
if (*u == '\n') *u = 0;
int id = sched_workque(proc, arg);
debug2("workque id=%d added", id);
snprintf(bb.addr, bb.len - 1, "%d\n", id);
write(fd, bb.addr, strlen(bb.addr));
return 0;
}
static int
workque_status(struct task *proc, int fd, const char *arg)
{
int size, rv, id = atoi(arg);
struct bb bb = { .addr = zalloca(PIPE_BUF), .len = PIPE_BUF};
struct task_status *status = (struct task_status *)bb.addr;
if ((rv = sched_getstat(proc, id, status)))
goto exit;
if (status->state == TASK_RUNNING)
goto done;
if (status->state != TASK_FINISHED)
goto exit;
if ((size = sched_getcbuf(proc, id, bb.addr, PIPE_BUF)) < 1)
goto exit;
struct mm_pool *mp = mm_pool_create(CPU_PAGE_SIZE, 0);
struct dict dict;
dict_init(&dict, mm_pool(mp));
dict_unpack(&dict, bb.addr, size);
dict_dump(&dict);
dict_pack(&dict, bb.addr, PIPE_BUF);
mm_pool_destroy(mp);
write(fd, bb.addr, strlen(bb.addr));
done:
write(fd, "1", 1);
return 0;
exit:
error("operation status id=%d failed", id);
snprintf(bb.addr, bb.len - 1, "%d\n", rv);
write(fd, bb.addr, strlen(bb.addr));
return 1;
}
static int
process_entry(struct task *proc)
{
struct ip_peer ip = { .len = sizeof(ip.sa) };
do {
if ((ip.fd = accept(fd, NULL, NULL)) < 0)
goto error;
socket_blocking(ip.fd);
getpeername(ip.fd, (struct sockaddr *)&ip.sa, &ip.len);
const char *from = inet_ntopa(AF_INET6, &ip.sa.sin6_addr);
debug1("Accepted connection from %s:%d", from, htons(ip.sa.sin6_port));
char buffer[8192] = {0};
int rv = read(ip.fd, buffer, sizeof(buffer));
if (rv < 1)
goto error;
buffer[rv] = 0;
if (!strncmp(buffer, "add", 3)) {
const char *arg = buffer + 3;
workque_add(proc, ip.fd, arg);
} else if (!strncmp(buffer, "status", 6)) {
const char *arg = buffer + 7;
workque_status(proc, ip.fd, arg);
}
close(ip.fd);
debug1("Connection closed with %s:%d", from, htons(ip.sa.sin6_port));
} while(1);
return 0;
error:
debug1("%d:%s", errno, strerror(errno));
return 1;
}
static int
workque_ctor(struct task *proc)
{
setproctitle("mpm id=%d", proc->id);
debug1("workque pid: %d started", proc->pid);
return 0;
}
static int
workque_dtor(struct task *proc)
{
debug1("workque pid: %d exiting", proc->pid);
return 0;
}
static int
workque_entry(struct task *proc)
{
struct dict dict;
struct bb bb = { .addr = alloca(PIPE_BUF), .len = PIPE_BUF};
const char *arg = task_arg(proc);
debug1("workque pid: %d id=%d arg=%s", proc->pid, proc->id, arg);
struct mm_pool *mp = mm_pool_create(CPU_PAGE_SIZE, 0);
dict_init(&dict, mm_pool(mp));
dict_set(&dict, "tx.id", "1");
dict_set(&dict, "tx.type", "2");
dict_sort(&dict);
int size = dict_pack(&dict, bb.addr, bb.len);
if (size < 1)
goto exit;
sched_setcbuf(proc, proc->id, bb.addr, size);
exit:
mm_pool_destroy(mp);
return 0;
}
static const struct sched_params sched_params = {
.max_processes = 4, /* number of processes */
.max_job_parallel = 2, /* number of running queued processes */
.max_job_queue = 8, /* size of the workqueue */
.max_job_unique = 0, /* maximum unique jobs */
.timeout_interuptible = 15, /* timeout for interuptible code area */
.timeout_killable = 5, /* timeout before process is killed */
.timeout_throttled = 1, /* slowdown on trashing / fatal errors */
.timeout_status = 360, /* 5 minutes for process status */
};
static const struct sched_callbacks sched_callbacks = {
.worksvc = {
.ctor = worksvc_ctor,
.dtor = worksvc_dtor,
.entry = worksvc_entry
},
.workque = {
.ctor = workque_ctor,
.dtor = workque_dtor,
.entry = workque_entry
},
.process = {
.ctor = process_ctor,
.dtor = process_dtor,
.entry = process_entry
},
};
static const struct mpm_module mpm_module = {
.mpm_model = MPM_HYBRID, /* threads in dedicated processes */
.cpu_model = CPU_DEDICATED, /* dedicated process workers */
.net_model = NET_ROUNDROBIN,
.params = &sched_params,
.callbacks = &sched_callbacks
};
const char *pidfile = "/var/run/mpmd.pid";
int
main(int argc, char *argv[])
{
irq_init();
irq_disable();
int pid;
if ((pid = pid_read(pidfile)))
die("process already running pid: %d", pid);
if (!pid_write(pidfile))
die("can't write pid file: %s", pidfile);
argv = setproctitle_init(argc, argv);
setproctitle("mpmd");
log_setcaps(15);
log_verbose = 2;
const char *verb = getenv("MPM_VERBOSE");
if (verb)
log_verbose = atoi(verb);
socket_init();
info("scheduler started.");
_sched_start(&mpm_module);
_sched_wait(&mpm_module);
_sched_stop(&mpm_module);
info("scheduler stopped.");
socket_fini();
return 0;
}
#else
int
main(int argc, char *argv[])
{
return 0;
}
#endif
| 22.694767 | 80 | 0.66133 |
746e1fb918c3ada04b398968c8dd12698e0c6d43 | 386 | h | C | StainlessClient/OverlayView.h | internetzel/stainless | 7b7d040bd0d9ccf138356154b5fcbe75ca6da761 | [
"MIT"
] | 26 | 2015-01-21T01:52:34.000Z | 2020-07-15T19:24:23.000Z | StainlessClient/OverlayView.h | internetzel/stainless | 7b7d040bd0d9ccf138356154b5fcbe75ca6da761 | [
"MIT"
] | null | null | null | StainlessClient/OverlayView.h | internetzel/stainless | 7b7d040bd0d9ccf138356154b5fcbe75ca6da761 | [
"MIT"
] | 10 | 2015-03-13T16:43:11.000Z | 2022-02-06T16:55:22.000Z | //
// OverlayView.h
// StainlessClient
//
// Created by Danny Espinoza on 10/28/08.
// Copyright 2008 Mesa Dynamics, LLC. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface OverlayView : NSView {
NSMutableArray* holes;
NSPoint offset;
NSRect selection;
}
@property(nonatomic, retain) NSMutableArray* holes;
@property NSPoint offset;
@property NSRect selection;
@end
| 16.782609 | 59 | 0.727979 |
a1aba124907db2008ab730b6dc4b78418deaa65e | 20,295 | c | C | library_dir_dir/system_library_unbundled/source/pc_wsterm_.s.archive/kbdisp.c | dancrossnyc/multics | dc291689edf955c660e57236da694630e2217151 | [
"RSA-MD"
] | 65 | 2021-07-27T16:54:21.000Z | 2022-03-30T17:50:19.000Z | library_dir_dir/system_library_unbundled/source/pc_wsterm_.s.archive/kbdisp.c | dancrossnyc/multics | dc291689edf955c660e57236da694630e2217151 | [
"RSA-MD"
] | 1 | 2021-07-29T13:24:12.000Z | 2021-07-29T13:28:22.000Z | library_dir_dir/system_library_unbundled/source/pc_wsterm_.s.archive/kbdisp.c | dancrossnyc/multics | dc291689edf955c660e57236da694630e2217151 | [
"RSA-MD"
] | 4 | 2021-07-27T16:05:31.000Z | 2021-12-30T08:38:51.000Z | /* ********************************************
* *
* Copyright, (C) Honeywell Bull Inc., 1988 *
* *
******************************************** */
/* HISTORY COMMENTS:
1) change(88-06-13,Lee), approve(88-05-16,MCR7897), audit(88-09-19,Flegel),
install(88-10-12,MR12.2-1160):
Created.
2) change(88-07-25,Lee), approve(88-05-16,MCR7897), audit(88-09-19,Flegel),
install(88-10-12,MR12.2-1160):
Documentation additions only. Added header comments to all routines.
3) change(88-08-09,Lee), approve(88-05-16,MCR7897), audit(88-09-19,Flegel),
install(88-10-12,MR12.2-1160):
Fix references to include files; "wstdefs.h" was split into
"wstdefs.h" and "wsttype.h" to avoid declaration clash; also,
various constants defined to descriptive names.
4) change(89-01-18,Lee), approve(89-01-02,MCR8043), audit(89-03-14,Flegel),
install(89-04-24,MR12.3-1033):
phx21233 - Converted display_char() to display_char_prim() for handling
primitive display function; new display_char() added which calls the
primitive and displays only when keyboard echoing is enabled. Added
routine get_echoed_input() for extracting only echoed input from line
buffer.
END HISTORY COMMENTS */
#include <dos.h>
#include "wstdefs.h"
#include "wstglob.h"
/*
***********************************************************************
Routine: DISPLAY_CHAR_STR
Function:
This routine returns the display string for a character
displayed in line editing. In particular, it determines how
non-printable characters are displayed.
Parameters:
(input) ch - specifies the ASCII character being
displayed
Returns: a pointer to a static string containing the
displayed form of the ASCII character
**********************************************************************/
char *display_char_str(ch)
int ch; /* character to display */
{
static char display_string[MAX_DISPLAY_CHAR_SIZE+1]; /* string to pass back result */
int octval;
/* check for non-printable control character */
if (ch < MIN_PRINTABLE_ASCII) {
octval = ch;
display_string[0] = '\\';
display_string[3] = (ch & 07) + '0';
ch >>= 3;
display_string[2] = (ch & 07) + '0';
ch >>= 3;
display_string[1] = (ch & 07) + '0';
display_string[4] = NUL_TERMINATOR;
}
/* check for printable ASCII */
else if (ch < ASCII_DEL) {
display_string[0] = ch;
display_string[1] = NUL_TERMINATOR;
}
/* check for ASCII DEL character */
else if (ch == ASCII_DEL) {
strcpy(display_string,"\\177");
}
/* extended ASCII character */
else {
sprintf(display_string,"<%d>", ch);
}
return(display_string);
}
/*
***********************************************************************
Routine: DISPLAY_TAB_STR
Function:
This routine returns a string filled with enough blanks to pad
to the next tab column.
Parameters:
(input) cur_col - specifies the current column on the
screen to tab from
Returns: a pointer to a static string containing enough
spaces to pad to the next tab position on
the screen
**********************************************************************/
char *display_tab_str(cur_col)
int cur_col; /* specifies current cursor column coordinate */
{
static char display_string[TAB_SIZE+1]; /* result string to pass back */
int n_spaces; /* number of spaces to pad */
register int i; /* working index */
/* if column exceeds right screen edge, assume wrap around to
leftmost edge on next line
*/
if (cur_col >= ss.right)
n_spaces = TAB_SIZE;
/* handle current column within screen */
else {
/* calculate padding to next tab column */
n_spaces = TAB_SIZE - ((cur_col - ss.left) % TAB_SIZE);
/* if exceeds right edge, truncate to get to leftmost
column on next line; this handles the case where the
screen width is not a multiple of the tab size and
guarantees wrap around to the leftmost column
*/
if (cur_col + n_spaces >= ss.right)
n_spaces = ss.right - cur_col + 1;
}
/* initialize the string with the correct number of spaces */
for (i = 0; i < n_spaces; i++)
display_string[i] = ' ';
/* null-terminate the string */
display_string[i] = NUL_TERMINATOR;
return(display_string);
}
/*
***********************************************************************
Routine: DISPLAY_CHAR_PRIM
Function:
This routine displays a character entered from the keyboard in
an appropriate representation. It keeps track of cursor position,
line wrap arounds and scrolling.
Parameters:
(input/output) pos - pointer to a structure which maintains
cursor position information; information is
updated after the display
(input) ch - specifies the ASCII character to display
Returns: The number of characters displayed to represent
the keyboard character
**********************************************************************/
display_char_prim(pos,ch)
CURPOS *pos; /* pointer to structure for keeping track of cursor position */
int ch; /* character to display */
{
char *display_char_str();
char *ptr; /* pointer to display string */
int display_length; /* holds length of display string */
/* character is the TAB character ? */
if (ch == TAB)
/* get the string to display for the tab */
ptr = display_tab_str(pos->cur_col);
/* not tab, get the string to display for the character */
else
ptr = display_char_str(ch);
/* determine the length of the display string */
display_length = strlen(ptr);
/* display the display string, keeping track of cursor position */
while (TRUE) {
/* cursor column past right screen edge */
if (pos->cur_col > ss.right) {
/* wrap around to left edge */
pos->cur_col = ss.left;
/* at bottom of screen? */
if (pos->cur_row >= ss.bottom) {
/* scroll and tally the scroll */
pos->scroll_flag++;
wst_scroll();
}
/* not at bottom of screen, at next line */
else
pos->cur_row++;
/* update the physical cursor */
set_cursor(pos->cur_row,pos->cur_col);
}
/* if NUL terminator reached, exit print loop */
if (!*ptr) break;
/* display the character */
putch(*ptr);
/* point to next character in display string */
ptr++;
/* move the cursor forward */
pos->cur_col++;
}
return(display_length);
}
/*
***********************************************************************
Routine: REDISPLAY
Function:
This routine redisplays the edited line from a particular
position in the line until the end or the end of the screen is
reached, whichever is reached first. The fields in the line
structure passed to this routine are not directly altered.
Parameters:
(input) line - pointer to the structure containing the
line and information about the line being
edited
(input) pos - specifies what position in the line to
begin redisplaying
(output) max_row - specifies the integer to pass back
the ending row coordinate after the
redisplay
(output) max_col - specifies the integer to pass back
the ending column coordinate after the
redisplay
Returns: NONE
Note 1 - It is assumed that the physical cursor on the screen is at
the line position specified by the parameter 'pos'.
**********************************************************************/
redisplay(line,pos,max_row,max_col)
EDIT_LINE *line;
int pos;
int *max_row;
int *max_col;
{
char *display_char_str();
char *display_tab_str();
char *ptr;
int row;
int col;
int i;
int tmp_row;
int tmp_col;
/* get a working copy of current cursor row and column coordinates */
row = line->cur_row;
col = line->cur_col;
/* check that position in line buffer to start redisplay is valid */
if (pos >= 0 && pos < line->length) {
/* display each character until end of line */
for (i = pos; i < line->length; i++) {
/* check if character is a tab */
if (line->line[i] == TAB)
/* get tab string and update size of tab */
ptr = display_tab_str(col);
/* otherwise just get character string */
else
ptr = display_char_str(line->line[i]);
/* phx21233 R.L. - size of 0 means character not echoed and */
/* should not be displayed */
if (line->size[i])
line->size[i] = strlen(ptr);
else
continue;
/* display character string until NUL terminator reached */
while (*ptr) {
/* check for wrap around past right edge of screen */
if (check_line_wrap(line,&row,&col,max_row,max_col) < 0)
return;
/* display the current character in the string */
putch(*ptr);
/* point to next character in the string */
ptr++;
/* increment cursor position */
col++;
/* check if a text key was hit */
if (stop_display(line)) {
/* stop redisplay routine because another character
has been entered from the keyboard which will
call redisplay again to finish updating the screen
*/
set_cursor(line->cur_row,line->cur_col);
return;
}
}
}
/* check for wrap around past right edge of screen */
if (check_line_wrap(line,&row,&col,max_row,max_col) < 0)
return;
}
/* save ending coordinates (coordinates of where line
displayed ends)
*/
tmp_row = row;
tmp_col = col;
/* reached the end of line, but must pad to ending
coordinates with blanks to erase leftover characters
*/
while (row < line->max_row) {
if (col > ss.right) {
col = ss.left;
row++;
set_cursor(row,col);
}
else {
putch(' ');
col++;
}
}
if (row == line->max_row) {
while (col <= line->max_col) {
putch(' ');
col++;
}
}
/* update the physical location of the cursor */
set_cursor(line->cur_row,line->cur_col);
*max_row = tmp_row;
*max_col = tmp_col;
}
/*
***********************************************************************
Routine: CHECK_LINE_WRAP
Function:
This routine checks to see if the cursor has gone past the
defined right edge of the screen and moves the cursor to the left
most column of the next line. If the line is wrapped at the bottom
most line of the defined screen area, a flag in the line structure
is set and the maximum row and col coordinates of the screen are
past back to the caller.
Parameters:
(input) line - pointer to the structure containing the
line and information about the line being
edited
(input/output) row - contains the address of the variable containing
the current row coordinates of the cursor
(input/output) col - contains the address of the variable containing
the current column coordinates of the cursor
(output) max_row - this variable is initialized to the
maximum screen row coordinate if the line
wraps on the last row
(output) max_col - this variable is initialized to the
maximum screen column coordinate if the
line wraps on the last row
Returns: 0 if screen not completely filled
-1 if the line extends beyond the end of the
screen
**********************************************************************/
check_line_wrap(line,row,col,max_row,max_col)
EDIT_LINE *line;
int *row;
int *col;
int *max_row;
int *max_col;
{
/* check for wrap around past right edge of screen */
if (*col > ss.right) {
/* wrap around to left side of screen */
*col = ss.left;
/* reached bottom of screen? */
if (*row >= ss.bottom) {
/* update max row and col variables */
*max_row = ss.bottom;
*max_col = ss.right;
/* flag not all characters displayed */
line->off_screen = TRUE;
/* restore physical cursor position */
set_cursor(line->cur_row,line->cur_col);
return(-1);
}
/* not bottom of screen, go to next line */
else
(*row)++;
/* update location of physical cursor */
set_cursor(*row,*col);
}
return(0);
}
/*
***********************************************************************
Routine: STOP_DISPLAY
Function:
This routine is used to optimize screen updates by checking to
see if updating of the screen may be stopped before it is
completed. This is possible if another key is detected that
guarantees the redisplay routine will be called again to update the
screen.
Parameters:
(input) line - pointer to the structure containing the
line and information about the line being
edited
Returns: TRUE if a key was detected that guarantees a
subsequent screen update
FALSE otherwise
**********************************************************************/
stop_display(line)
EDIT_LINE *line;
{
int ch;
/* don't stop update if no key hit or key is not ASCII */
if ((ch = checkkey()) < 0 || ch > ASCII_EXTEND_CODE) return(FALSE);
switch (ch) {
/* kill to beginning of line will update if not already at */
/* beginning of line */
case '@':
if (line->index > ZERO_INDEX_VALUE) return(TRUE);
return(FALSE);
/* literal escape or escape does not guarantee subsequent */
/* redisplay */
case '\\':
case ESC:
return(FALSE);
/* backspace and delete key redisplays if a character is */
/* deleted */
case BACKSPACE:
case DEL_KEY:
if (line->index > ZERO_INDEX_VALUE) return(TRUE);
return(FALSE);
/* delete character key redisplays if cursor is before end */
/* of line */
case CTRL_D:
if (line->index < line->length) return(TRUE);
return(FALSE);
/* kill to end of line redisplays if not already at end of */
/* line */
case CTRL_K:
if (line->index < line->length) return(TRUE);
return(FALSE);
default:
/* if not a tab and not a printable character, may not */
/* force a redraw */
if (ch != TAB &&
(ch < MIN_PRINTABLE_ASCII || ch > MAX_PRINTABLE_ASCII))
return(FALSE);
/* a printable character; if in replace mode, redraws */
/* if not at end of line */
if (line->mode) {
if (line->length < MAX_LINE_SIZE) return(TRUE);
return(FALSE);
}
/* in insert mode, redraws if maximum line size has */
/* not been reached */
else {
if (line->index < MAX_LINE_SIZE) return(TRUE);
return(FALSE);
}
}
}
/*
***********************************************************************
Routine: GET_ECHOED_INPUT
Function:
This routine is used to extract echoed input from a specified
part of the edit-mode input line buffer. Only characters echoed will
be extracted. The results are passed back in a static string, along
with the length of the extracted input item.
Parameters:
(input) line - pointer to the structure containing the
line and information about the line being
edited
(input) item_pos - index to position in line buffer
to begin extracting
(input) item_size - number of characters in line buffer
from which to extract
(output) display_str - pointer to the string extracted
(output) display_len - length of string extract
Returns: None
**********************************************************************/
get_echoed_input(line,item_pos,item_size,display_str,display_len)
EDIT_LINE *line;
int item_pos;
int item_size;
char **display_str;
int *display_len;
{
static char echoed_str[MAX_LINE_SIZE+1];
register int i;
register int count;
/* ensure specified position for extraction is valid */
if (item_pos > line->length) item_pos = line->length;
else if (item_pos < 0) item_pos = 0;
/* ensure specified number of chars for extraction is valid */
if (item_pos+item_size > line->length)
item_size = line->length - item_pos;
/* tally and copy over the echoed input characters from input buffer */
count = 0;
for (i = item_pos; i < item_size; i++)
/* if represented by at least 1 character */
if (line->size[i] > 0)
echoed_str[count++] = line->line[i];
echoed_str[count] = 0;
/* pass back the results */
*display_str = echoed_str;
*display_len = count;
}
/*
***********************************************************************
Routine: DISPLAY_CHAR
Function:
This routine displays a character entered from the keyboard in
an appropriate representation by calling display_char_prim() if
keyboard echoing is enabled. If echoing is disabled, nothing is
displayed and 0 is returned.
Parameters:
(input/output) pos - pointer to a structure which maintains
cursor position information; information is
updated after the display
(input) ch - specifies the ASCII character to display
Returns: The number of characters displayed to represent
the keyboard character if keyboard echoing enabled
0 if keyboard character echoing is disabled
**********************************************************************/
display_char(pos,ch)
CURPOS *pos; /* pointer to structure for keeping track of cursor position */
int ch; /* character to display */
{
if (!kb.echo)
return(0);
return(display_char_prim(pos,ch));
}
| 32.472 | 93 | 0.521902 |
50d17afbc57e26547037723bb19cb514bd0c117b | 752 | h | C | HttpWebserver/HttpCredential.h | depeter/keypad-alarm | 35e1dc739290ab373eb286db43c6b88881854433 | [
"MIT"
] | null | null | null | HttpWebserver/HttpCredential.h | depeter/keypad-alarm | 35e1dc739290ab373eb286db43c6b88881854433 | [
"MIT"
] | null | null | null | HttpWebserver/HttpCredential.h | depeter/keypad-alarm | 35e1dc739290ab373eb286db43c6b88881854433 | [
"MIT"
] | null | null | null | #pragma once
namespace HttpWebServer
{
namespace DetailClasses
{
/// <summary>Authentication credential for web request.</summary>
public ref class HttpCredential sealed
{
public:
/// <summary>Username for authentication.</summary>
property Platform::String ^Username
{
Platform::String^ get()
{
return username;
}
}
/// <summary>Password for authentication.</summary>
property Platform::String ^Password
{
Platform::String^ get()
{
return password;
}
}
internal:
HttpCredential(char *credentialText);
private:
int Base64Decode(unsigned char *utTekst, const unsigned char *innTekst, int innLengde);
Platform::String ^username;
Platform::String ^password;
};
}
} | 19.789474 | 90 | 0.674202 |
9718175f3d2312c7bc3d2883f69ebdac1a3c896b | 1,082 | h | C | PlexATV/theos/include/BackRow/BRMainMenuShelfErrorControl.h | quiqueck/Plex-ATV-Plugin | dfb2b10d458476cf7ce00e23ae26c2bde59856be | [
"MIT"
] | 3 | 2017-01-15T21:48:12.000Z | 2020-12-07T23:57:57.000Z | PlexATV/theos/include/BackRow/BRMainMenuShelfErrorControl.h | plex-unofficial/Plex-ATV-Plugin.bundle | dfb2b10d458476cf7ce00e23ae26c2bde59856be | [
"MIT"
] | 1 | 2018-12-27T10:21:51.000Z | 2018-12-27T10:21:51.000Z | PlexATV/theos/include/BackRow/BRMainMenuShelfErrorControl.h | quiqueck/Plex-ATV-Plugin | dfb2b10d458476cf7ce00e23ae26c2bde59856be | [
"MIT"
] | null | null | null | /**
* This header is generated by class-dump-z 0.2a.
* class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3.
*
* Source: /System/Library/PrivateFrameworks/BackRow.framework/BackRow
*/
#import "BackRow-Structs.h"
#import "BRControl.h"
@class BRTextControl;
@interface BRMainMenuShelfErrorControl : BRControl {
@private
BRTextControl *_text; // 40 = 0x28
BRTextControl *_subtext; // 44 = 0x2c
}
@property(retain) BRTextControl *subtext; // G=0x32e37915; S=0x32e37945; converted property
@property(retain) BRTextControl *text; // G=0x32e37999; S=0x32e379c9; converted property
- (id)init; // 0x32e37a79
- (id)_subtextAttributes; // 0x32e37d89
- (id)_textAttributes; // 0x32e37b2d
- (id)accessibilityLabel; // 0x32e37c79
- (void)dealloc; // 0x32e37a1d
- (void)layoutSubcontrols; // 0x32e37cad
// converted property setter: - (void)setSubtext:(id)subtext; // 0x32e37945
// converted property setter: - (void)setText:(id)text; // 0x32e379c9
// converted property getter: - (id)subtext; // 0x32e37915
// converted property getter: - (id)text; // 0x32e37999
@end
| 33.8125 | 91 | 0.733826 |
1c6997125c41f9eb687fb73a8d7b9f4f442e84af | 807 | h | C | src/boot/ksdk1.1.0/pedometer.h | kayjayB/Warp-firmware | 5b1460048d12eab766d738235f6cce0b857e3e06 | [
"BSD-3-Clause"
] | null | null | null | src/boot/ksdk1.1.0/pedometer.h | kayjayB/Warp-firmware | 5b1460048d12eab766d738235f6cce0b857e3e06 | [
"BSD-3-Clause"
] | null | null | null | src/boot/ksdk1.1.0/pedometer.h | kayjayB/Warp-firmware | 5b1460048d12eab766d738235f6cce0b857e3e06 | [
"BSD-3-Clause"
] | null | null | null | #ifdef WARP_BUILD_ENABLE_DEVMMA8451Q
volatile WarpI2CDeviceState deviceMMA8451QState;
#endif
void calibratePedometer();
int movingAverage(int16_t *window, long *sum, uint16_t pos, uint8_t numSamples, int16_t nextNum);
void pedometer();
uint8_t numReadings = 50;
int16_t acceleration[3];
int16_t X_acc;
int16_t Y_acc;
int16_t Z_acc;
int16_t X_acc_Prev;
int16_t Y_acc_Prev;
int16_t Z_acc_Prev;
int16_t minX;
int16_t maxX;
int16_t minY;
int16_t maxY;
int16_t minZ;
int16_t maxZ;
uint8_t activeAxis=1;
int16_t threshold=0;
int tempXSum = 0;
int tempYSum = 0;
int tempZSum = 0;
long sumX=0;
long sumY=0;
long sumZ=0;
int16_t average=0;
int16_t previous=0;
uint16_t delay1=20;
uint16_t delay2=18;
bool flag = false;
int X_avg=0, Y_avg=0, Z_avg=0;
uint16_t steps = 0;
uint16_t I2cPullupValue = 32768; | 17.543478 | 97 | 0.775713 |
31cf9fe45539865aa492876327cd1e78dccf0a50 | 21,587 | c | C | src/c/watchface_window.c | jahdaic/WunderTime | 7467d0e6d475180a9d44d5ef0ffe0415b95ad1a9 | [
"MIT"
] | null | null | null | src/c/watchface_window.c | jahdaic/WunderTime | 7467d0e6d475180a9d44d5ef0ffe0415b95ad1a9 | [
"MIT"
] | null | null | null | src/c/watchface_window.c | jahdaic/WunderTime | 7467d0e6d475180a9d44d5ef0ffe0415b95ad1a9 | [
"MIT"
] | null | null | null | #include <pebble.h>
#include "watchface_window.h"
static bool started = false;
static int hours, minutes, seconds, stroke_width = 5;
callback minute_callback;
// BEGIN AUTO-GENERATED UI CODE; DO NOT MODIFY
static Window *s_window;
static GBitmap *s_res_image_steps;
static GFont s_res_gothic_14;
static GFont s_res_bitham_34_medium_numbers;
static GFont s_res_gothic_18;
static GBitmap *s_res_image_battery;
static GBitmap *s_res_image_tasks;
static BitmapLayer *steps_bitmaplayer;
static Layer *canvas_layer;
static TextLayer *date_textlayer;
static TextLayer *time_textlayer;
static TextLayer *seconds_textlayer;
static TextLayer *task_due_textlayer;
static TextLayer *task_desc_textlayer;
static BitmapLayer *battery_bitmaplayer;
static TextLayer *tasks_textlayer;
static TextLayer *steps_textlayer;
static TextLayer *battery_textlayer;
static BitmapLayer *tasks_bitmaplayer;
static void initialise_ui(void) {
s_window = window_create();
window_set_background_color(s_window, GColorBlack);
#ifndef PBL_SDK_3
window_set_fullscreen(s_window, true);
#endif
s_res_image_steps = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_STEPS);
s_res_gothic_14 = fonts_get_system_font(FONT_KEY_GOTHIC_14);
s_res_bitham_34_medium_numbers = fonts_get_system_font(FONT_KEY_BITHAM_34_MEDIUM_NUMBERS);
s_res_gothic_18 = fonts_get_system_font(FONT_KEY_GOTHIC_18);
s_res_image_battery = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BATTERY);
s_res_image_tasks = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_TASKS);
// steps_bitmaplayer
steps_bitmaplayer = bitmap_layer_create(GRect(65, 120, 16, 16));
bitmap_layer_set_bitmap(steps_bitmaplayer, s_res_image_steps);
layer_add_child(window_get_root_layer(s_window), (Layer *)steps_bitmaplayer);
// canvas_layer
canvas_layer = layer_create(GRect(0, 0, 144, 168));
layer_add_child(window_get_root_layer(s_window), (Layer *)canvas_layer);
// date_textlayer
date_textlayer = text_layer_create(GRect(0, 20, 144, 14));
text_layer_set_background_color(date_textlayer, GColorClear);
text_layer_set_text_color(date_textlayer, GColorWhite);
text_layer_set_text(date_textlayer, "SUN 01");
text_layer_set_text_alignment(date_textlayer, GTextAlignmentCenter);
text_layer_set_font(date_textlayer, s_res_gothic_14);
layer_add_child(window_get_root_layer(s_window), (Layer *)date_textlayer);
// time_textlayer
time_textlayer = text_layer_create(GRect(7, 29, 89, 36));
text_layer_set_background_color(time_textlayer, GColorClear);
text_layer_set_text_color(time_textlayer, GColorWhite);
text_layer_set_text(time_textlayer, "10:00");
text_layer_set_text_alignment(time_textlayer, GTextAlignmentCenter);
text_layer_set_font(time_textlayer, s_res_bitham_34_medium_numbers);
layer_add_child(window_get_root_layer(s_window), (Layer *)time_textlayer);
// seconds_textlayer
seconds_textlayer = text_layer_create(GRect(100, 47, 37, 20));
text_layer_set_background_color(seconds_textlayer, GColorClear);
text_layer_set_text_color(seconds_textlayer, GColorWhite);
text_layer_set_text(seconds_textlayer, "00 PM");
text_layer_set_font(seconds_textlayer, s_res_gothic_18);
layer_add_child(window_get_root_layer(s_window), (Layer *)seconds_textlayer);
// task_due_textlayer
task_due_textlayer = text_layer_create(GRect(0, 70, 144, 16));
text_layer_set_background_color(task_due_textlayer, GColorClear);
text_layer_set_text_color(task_due_textlayer, GColorWhite);
text_layer_set_text(task_due_textlayer, "Due Wednesday");
text_layer_set_text_alignment(task_due_textlayer, GTextAlignmentCenter);
layer_add_child(window_get_root_layer(s_window), (Layer *)task_due_textlayer);
// task_desc_textlayer
task_desc_textlayer = text_layer_create(GRect(0, 85, 144, 30));
text_layer_set_background_color(task_desc_textlayer, GColorClear);
text_layer_set_text_color(task_desc_textlayer, GColorWhite);
text_layer_set_text(task_desc_textlayer, "This is the text layer that contains the tasky description");
text_layer_set_text_alignment(task_desc_textlayer, GTextAlignmentCenter);
text_layer_set_font(task_desc_textlayer, s_res_gothic_14);
layer_add_child(window_get_root_layer(s_window), (Layer *)task_desc_textlayer);
// battery_bitmaplayer
battery_bitmaplayer = bitmap_layer_create(GRect(111, 120, 16, 16));
bitmap_layer_set_bitmap(battery_bitmaplayer, s_res_image_battery);
layer_add_child(window_get_root_layer(s_window), (Layer *)battery_bitmaplayer);
// tasks_textlayer
tasks_textlayer = text_layer_create(GRect(0, 140, 48, 14));
text_layer_set_background_color(tasks_textlayer, GColorClear);
text_layer_set_text_color(tasks_textlayer, GColorWhite);
text_layer_set_text(tasks_textlayer, "00");
text_layer_set_text_alignment(tasks_textlayer, GTextAlignmentCenter);
text_layer_set_font(tasks_textlayer, s_res_gothic_14);
layer_add_child(window_get_root_layer(s_window), (Layer *)tasks_textlayer);
// steps_textlayer
steps_textlayer = text_layer_create(GRect(48, 140, 48, 14));
text_layer_set_background_color(steps_textlayer, GColorClear);
text_layer_set_text_color(steps_textlayer, GColorWhite);
text_layer_set_text(steps_textlayer, "0");
text_layer_set_text_alignment(steps_textlayer, GTextAlignmentCenter);
text_layer_set_font(steps_textlayer, s_res_gothic_14);
layer_add_child(window_get_root_layer(s_window), (Layer *)steps_textlayer);
// battery_textlayer
battery_textlayer = text_layer_create(GRect(96, 140, 48, 14));
text_layer_set_background_color(battery_textlayer, GColorClear);
text_layer_set_text_color(battery_textlayer, GColorWhite);
text_layer_set_text(battery_textlayer, "100%");
text_layer_set_text_alignment(battery_textlayer, GTextAlignmentCenter);
text_layer_set_font(battery_textlayer, s_res_gothic_14);
layer_add_child(window_get_root_layer(s_window), (Layer *)battery_textlayer);
// tasks_bitmaplayer
tasks_bitmaplayer = bitmap_layer_create(GRect(20, 120, 16, 16));
bitmap_layer_set_bitmap(tasks_bitmaplayer, s_res_image_tasks);
layer_add_child(window_get_root_layer(s_window), (Layer *)tasks_bitmaplayer);
}
static void destroy_ui(void) {
window_destroy(s_window);
bitmap_layer_destroy(steps_bitmaplayer);
layer_destroy(canvas_layer);
text_layer_destroy(date_textlayer);
text_layer_destroy(time_textlayer);
text_layer_destroy(seconds_textlayer);
text_layer_destroy(task_due_textlayer);
text_layer_destroy(task_desc_textlayer);
bitmap_layer_destroy(battery_bitmaplayer);
text_layer_destroy(tasks_textlayer);
text_layer_destroy(steps_textlayer);
text_layer_destroy(battery_textlayer);
bitmap_layer_destroy(tasks_bitmaplayer);
gbitmap_destroy(s_res_image_steps);
gbitmap_destroy(s_res_image_battery);
gbitmap_destroy(s_res_image_tasks);
}
// END AUTO-GENERATED UI CODE
// UTILITY FUNCTIONS
float get_sqrt(const float num) {
const uint MAX_STEPS = 40;
const float MAX_ERROR = 0.001;
float answer = num;
float ans_sqr = answer * answer;
uint step = 0;
while((ans_sqr - num > MAX_ERROR) && (step++ < MAX_STEPS)) {
answer = (answer + (num / answer)) / 2;
ans_sqr = answer * answer;
}
return answer;
}
float get_pow(const float num, const float exp) {
float answer = num;
for(int i = 1; i < exp; i++) {
answer = answer * num;
}
return answer;
}
float get_distance(GPoint p1, GPoint p2) {
float answer = get_sqrt(get_pow(p2.x - p1.x, 2) + get_pow(p2.y - p1.y, 2));
return answer;
}
char lower_to_upper(char c) {
return (c>='a' && c<='z')?c&0xdf:c;
}
int32_t get_angle_for_minute(int minute) {
return (minute * 360) / 60;
}
GPoint get_start_point_for_hour(int hour) {
GRect window_bounds = layer_get_bounds(window_get_root_layer(s_window));
int perimeter = (2 * window_bounds.size.h) + (2 * window_bounds.size.w);
int hour_position = perimeter / 12 * hour;
if(hour_position < window_bounds.size.w / 2) {
return GPoint(window_bounds.size.w / 2 + hour_position, 0);
}
else if(hour_position < window_bounds.size.w / 2 + window_bounds.size.h) {
return GPoint(window_bounds.size.w - 1, hour_position - (window_bounds.size.w / 2));
}
else if(hour_position < window_bounds.size.w / 2 + window_bounds.size.h + window_bounds.size.w) {
return GPoint(hour_position - (window_bounds.size.w / 2) - window_bounds.size.h, window_bounds.size.h - 1);
}
else if(hour_position < window_bounds.size.w / 2 + (2 * window_bounds.size.h) + window_bounds.size.w) {
return GPoint(0, hour_position - (window_bounds.size.w / 2) - window_bounds.size.h - window_bounds.size.w);
}
else {
return GPoint(hour_position - (window_bounds.size.w / 2) - (window_bounds.size.h * 2) - window_bounds.size.w, 0);
}
}
//UPDATE FUNCTIONS
void update_battery(BatteryChargeState battery) {
static char battery_text[] = "100%";
if(battery.is_charging) {
gbitmap_destroy(s_res_image_battery);
s_res_image_battery = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BATTERY_CHARGING);
bitmap_layer_set_bitmap(battery_bitmaplayer, s_res_image_battery);
layer_mark_dirty(bitmap_layer_get_layer(battery_bitmaplayer));
}
else if(battery.charge_percent <= 20) {
gbitmap_destroy(s_res_image_battery);
s_res_image_battery = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BATTERY_LOW);
bitmap_layer_set_bitmap(battery_bitmaplayer, s_res_image_battery);
layer_mark_dirty(bitmap_layer_get_layer(battery_bitmaplayer));
}
else {
gbitmap_destroy(s_res_image_battery);
s_res_image_battery = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BATTERY);
bitmap_layer_set_bitmap(battery_bitmaplayer, s_res_image_battery);
layer_mark_dirty(bitmap_layer_get_layer(battery_bitmaplayer));
}
snprintf(battery_text, sizeof(battery_text), "%d%%", battery.charge_percent);
text_layer_set_text(battery_textlayer, battery_text);
layer_mark_dirty(text_layer_get_layer(battery_textlayer));
}
void update_minutes(struct tm* tick_time, TimeUnits units_changed) {
static char time_text[] = "00:00";
static char date_text[] = "SUN 01";
static char steps_text[] = "99999";
char * time_format = "%i:%i";
hours = tick_time->tm_hour;
minutes = tick_time->tm_min;
if(hours > 12) { hours -= 12; }
if(minutes < 10) { time_format = "%i:0%u"; }
snprintf(time_text, sizeof(time_text), time_format, hours, minutes);
int steps = health_service_sum_today(HealthMetricStepCount);
// APP_LOG(APP_LOG_LEVEL_INFO, "Time: %s", time_text);
strftime(date_text, sizeof(date_text), "%a %d", tick_time);
snprintf(steps_text, sizeof(steps_text), "%d", steps);
for (int i = 0; date_text[i]; i++) {
date_text[i] = lower_to_upper(date_text[i]);
}
text_layer_set_text(time_textlayer, time_text);
text_layer_set_text(date_textlayer, date_text);
text_layer_set_text(steps_textlayer, steps_text);
layer_mark_dirty(text_layer_get_layer(time_textlayer));
layer_mark_dirty(text_layer_get_layer(date_textlayer));
layer_mark_dirty(text_layer_get_layer(steps_textlayer));
(*minute_callback)();
}
void update_seconds(struct tm* tick_time, TimeUnits units_changed) {
static char seconds_text[] = "00 AM";
strftime(seconds_text, sizeof(seconds_text), "%S %p", tick_time);
seconds = tick_time->tm_sec;
text_layer_set_text(seconds_textlayer, seconds_text);
if(seconds == 0 || !started) {
update_minutes(tick_time, units_changed);
update_battery(battery_state_service_peek());
started = true;
}
layer_mark_dirty(text_layer_get_layer(seconds_textlayer));
layer_mark_dirty(canvas_layer);
}
// LAYER UPDATES
void update_task_due(const char *date) {
text_layer_set_text(task_due_textlayer, date);
layer_mark_dirty(text_layer_get_layer(task_due_textlayer));
}
void update_task_desc(const char *description) {
text_layer_set_text(task_desc_textlayer, description);
layer_mark_dirty(text_layer_get_layer(task_desc_textlayer));
}
void update_task_count(const char *count) {
text_layer_set_text(tasks_textlayer, count);
layer_mark_dirty(text_layer_get_layer(tasks_textlayer));
}
void update_round_canvas(Layer *layer, GContext *ctx) {
GRect window_bounds = layer_get_bounds(window_get_root_layer(s_window));
GPoint center_point = GPoint(window_bounds.size.w / 2, window_bounds.size.h / 2);
int minute_angle = get_angle_for_minute(seconds);
graphics_context_set_fill_color(ctx, GColorRed);
graphics_fill_radial(ctx, window_bounds, GOvalScaleModeFillCircle, stroke_width, 0, DEG_TO_TRIGANGLE(minute_angle));
// Draw Ticks
graphics_context_set_stroke_color(ctx, PBL_IF_COLOR_ELSE(GColorWhite, GColorBlack));
graphics_context_set_stroke_width(ctx, 1);
for(int i = 0; i < 12; i++) {
GPoint start_point = gpoint_from_polar(window_bounds, GOvalScaleModeFillCircle, DEG_TO_TRIGANGLE((360 / 12) * i));
GPoint end_point;
end_point.x = start_point.x + (((stroke_width + 1) / get_distance(start_point, center_point)) * (center_point.x - start_point.x));
end_point.y = start_point.y + (((stroke_width + 1) / get_distance(start_point, center_point)) * (center_point.y - start_point.y));
graphics_draw_line(ctx, start_point, end_point);
}
}
void update_rectangle_canvas(Layer *layer, GContext *ctx) {
GRect window_bounds = layer_get_bounds(window_get_root_layer(s_window));
GPoint center_point = GPoint(window_bounds.size.w / 2, window_bounds.size.h / 2);
int perimeter = (2 * window_bounds.size.h) + (2 * window_bounds.size.w);
int minute_position = perimeter / 60 * (seconds + 1);
bool done = false;
// Drawing Settings
graphics_context_set_stroke_color(ctx, PBL_IF_COLOR_ELSE(GColorRed, GColorWhite));
graphics_context_set_stroke_width(ctx, stroke_width * 2);
// Top right
if(window_bounds.size.w / 2 < minute_position) {
graphics_draw_line(ctx, GPoint(window_bounds.size.w / 2, 0), GPoint(window_bounds.size.w - 1, 0));
minute_position -= window_bounds.size.w / 2;
}
else {
graphics_draw_line(ctx, GPoint(window_bounds.size.w / 2, 0), GPoint((window_bounds.size.w / 2) + minute_position, 0));
done = true;
}
// Right
if(!done) {
if(window_bounds.size.h < minute_position) {
graphics_draw_line(ctx, GPoint(window_bounds.size.w - 1, 0), GPoint(window_bounds.size.w - 1, window_bounds.size.h));
minute_position -= window_bounds.size.h;
}
else {
graphics_draw_line(ctx, GPoint(window_bounds.size.w - 1, 0), GPoint(window_bounds.size.w - 1, minute_position));
done = true;
}
}
// Bottom
if(!done) {
if(window_bounds.size.w < minute_position) {
graphics_draw_line(ctx, GPoint(window_bounds.size.w - 1, window_bounds.size.h), GPoint(0, window_bounds.size.h));
minute_position -= window_bounds.size.w;
}
else {
graphics_draw_line(ctx, GPoint(window_bounds.size.w - 1, window_bounds.size.h), GPoint(window_bounds.size.w - minute_position, window_bounds.size.h));
done = true;
}
}
// Left
if(!done) {
if(window_bounds.size.h < minute_position) {
graphics_draw_line(ctx, GPoint(0, window_bounds.size.h), GPoint(0, 0));
minute_position -= window_bounds.size.w;
}
else {
graphics_draw_line(ctx, GPoint(0, window_bounds.size.h), GPoint(0, window_bounds.size.h - minute_position));
done = true;
}
}
// Top left
if(!done) {
if(window_bounds.size.w / 2 < minute_position) {
graphics_draw_line(ctx, GPoint(0, 0), GPoint(window_bounds.size.w / 2, 0));
minute_position -= window_bounds.size.w / 2;
}
else {
graphics_draw_line(ctx, GPoint(0, 0), GPoint(minute_position, 0));
done = true;
}
}
// Draw Ticks
graphics_context_set_stroke_color(ctx, PBL_IF_COLOR_ELSE(GColorWhite, GColorBlack));
graphics_context_set_stroke_width(ctx, 1);
for(int i = 0; i < 12; i++) {
GPoint start_point = get_start_point_for_hour(i);
GPoint end_point;
end_point.x = start_point.x + (((stroke_width + 1) / get_distance(start_point, center_point)) * (center_point.x - start_point.x));
end_point.y = start_point.y + (((stroke_width + 1) / get_distance(start_point, center_point)) * (center_point.y - start_point.y));
graphics_draw_line(ctx, start_point, end_point);
}
}
void update_canvas_layer(Layer *layer, GContext *ctx) {
if(PBL_IF_ROUND_ELSE(true, false)) {
update_round_canvas(layer, ctx);
}
else {
update_rectangle_canvas(layer, ctx);
}
}
void set_minute_callback(callback callback_func) {
minute_callback = callback_func;
}
// WINDOW HANDLING
void fit_watchface(void) {
GRect window_bounds = layer_get_bounds(window_get_root_layer(s_window));
int16_t window_height = window_bounds.size.h;
int16_t window_width = window_bounds.size.w;
GRect date_bounds = layer_get_bounds(text_layer_get_layer(date_textlayer));
GRect time_bounds = layer_get_bounds(text_layer_get_layer(time_textlayer));
GRect seconds_bounds = layer_get_bounds(text_layer_get_layer(seconds_textlayer));
GRect task_due_bounds = layer_get_bounds(text_layer_get_layer(task_due_textlayer));
GRect task_desc_bounds = layer_get_bounds(text_layer_get_layer(task_desc_textlayer));
GRect tasks_bounds = layer_get_bounds(text_layer_get_layer(tasks_textlayer));
GRect steps_bounds = layer_get_bounds(text_layer_get_layer(steps_textlayer));
GRect battery_bounds = layer_get_bounds(text_layer_get_layer(battery_textlayer));
GRect tasks_icon_bounds = layer_get_bounds(bitmap_layer_get_layer(tasks_bitmaplayer));
GRect steps_icon_bounds = layer_get_bounds(bitmap_layer_get_layer(steps_bitmaplayer));
GRect battery_icon_bounds = layer_get_bounds(bitmap_layer_get_layer(battery_bitmaplayer));
// Date
date_bounds.origin.y = window_height / 3 / 2 - date_bounds.size.h;
date_bounds.size.w = window_width;
layer_set_frame(text_layer_get_layer(date_textlayer), date_bounds);
layer_mark_dirty(text_layer_get_layer(date_textlayer));
// Time
time_bounds.origin.x = (window_width - time_bounds.size.w - seconds_bounds.size.w) / 2;
time_bounds.origin.y = window_height / 3 / 2;
layer_set_frame(text_layer_get_layer(time_textlayer), time_bounds);
layer_mark_dirty(text_layer_get_layer(time_textlayer));
// Seconds
seconds_bounds.origin.x = (window_width - time_bounds.size.w - seconds_bounds.size.w) / 2 + time_bounds.size.w;
seconds_bounds.origin.y = time_bounds.origin.y + time_bounds.size.h - seconds_bounds.size.h;
layer_set_frame(text_layer_get_layer(seconds_textlayer), seconds_bounds);
layer_mark_dirty(text_layer_get_layer(seconds_textlayer));
// Task Due
task_due_bounds.origin.y = window_height / 2 - task_due_bounds.size.h;
task_due_bounds.size.w = window_width;
layer_set_frame(text_layer_get_layer(task_due_textlayer), task_due_bounds);
text_layer_set_text_color(task_due_textlayer, PBL_IF_COLOR_ELSE(GColorBlueMoon, GColorWhite));
text_layer_set_overflow_mode(task_due_textlayer, GTextOverflowModeWordWrap);
layer_mark_dirty(text_layer_get_layer(task_due_textlayer));
// Task Description
task_desc_bounds.origin.y = window_height / 2;
task_desc_bounds.size.w = window_width;
layer_set_frame(text_layer_get_layer(task_desc_textlayer), task_desc_bounds);
text_layer_enable_screen_text_flow_and_paging(task_desc_textlayer, 12);
layer_mark_dirty(text_layer_get_layer(task_desc_textlayer));
// Task Count
tasks_bounds.origin.x = (window_width / 4) - (tasks_bounds.size.w / 2);
tasks_bounds.origin.y = window_height / 3 * 2.5;
layer_set_frame(text_layer_get_layer(tasks_textlayer), tasks_bounds);
layer_mark_dirty(text_layer_get_layer(tasks_textlayer));
// Steps Count
steps_bounds.origin.x = (window_width / 4 * 2) - (steps_bounds.size.w / 2);
steps_bounds.origin.y = window_height / 3 * 2.5;
layer_set_frame(text_layer_get_layer(steps_textlayer), steps_bounds);
layer_mark_dirty(text_layer_get_layer(steps_textlayer));
// Battery Level
battery_bounds.origin.x = (window_width / 4 * 3) - (battery_bounds.size.w / 2);
battery_bounds.origin.y = window_height / 3 * 2.5;
layer_set_frame(text_layer_get_layer(battery_textlayer), battery_bounds);
layer_mark_dirty(text_layer_get_layer(battery_textlayer));
// Task Count
tasks_icon_bounds.origin.x = (window_width / 4) - (tasks_icon_bounds.size.w / 2);
tasks_icon_bounds.origin.y = window_height / 3 * 2.5 - tasks_icon_bounds.size.h;
layer_set_frame(bitmap_layer_get_layer(tasks_bitmaplayer), tasks_icon_bounds);
layer_mark_dirty(bitmap_layer_get_layer(tasks_bitmaplayer));
// Steps Count
steps_icon_bounds.origin.x = (window_width / 4 * 2) - (steps_icon_bounds.size.w / 2);
steps_icon_bounds.origin.y = window_height / 3 * 2.5 - steps_icon_bounds.size.h;
layer_set_frame(bitmap_layer_get_layer(steps_bitmaplayer), steps_icon_bounds);
layer_mark_dirty(bitmap_layer_get_layer(steps_bitmaplayer));
// Battery Level
battery_icon_bounds.origin.x = (window_width / 4 * 3) - (battery_icon_bounds.size.w / 2);
battery_icon_bounds.origin.y = window_height / 3 * 2.5 - battery_icon_bounds.size.h;
layer_set_frame(bitmap_layer_get_layer(battery_bitmaplayer), battery_icon_bounds);
layer_mark_dirty(bitmap_layer_get_layer(battery_bitmaplayer));
// Canvas
layer_set_frame(canvas_layer, GRect(0, 0, window_width, window_height));
layer_mark_dirty(canvas_layer);
}
void handle_window_unload(Window* window) {
destroy_ui();
}
void show_watchface_window(void) {
initialise_ui();
fit_watchface();
tick_timer_service_subscribe(SECOND_UNIT, update_seconds);
//tick_timer_service_subscribe(MINUTE_UNIT, update_minutes);
battery_state_service_subscribe(update_battery);
layer_set_update_proc(canvas_layer, update_canvas_layer);
window_set_window_handlers(s_window, (WindowHandlers) {
.unload = handle_window_unload,
});
window_stack_push(s_window, true);
}
void hide_watchface_window(void) {
window_stack_remove(s_window, true);
}
| 39.036166 | 153 | 0.783342 |
ee2884256ec96b45747644f74c443d3cac39e820 | 286 | h | C | Telecomm/Telecomm/Lib/Componet/Zone/include/ZoneAboutMeCell.h | telecommai/ios | 0dce4eeba342466ffe0db72fc0b77ba7d708d8cf | [
"BSD-3-Clause"
] | 1 | 2019-04-19T08:05:34.000Z | 2019-04-19T08:05:34.000Z | Telecomm/Telecomm/Lib/Componet/Zone/include/ZoneAboutMeCell.h | telecommai/ios | 0dce4eeba342466ffe0db72fc0b77ba7d708d8cf | [
"BSD-3-Clause"
] | null | null | null | Telecomm/Telecomm/Lib/Componet/Zone/include/ZoneAboutMeCell.h | telecommai/ios | 0dce4eeba342466ffe0db72fc0b77ba7d708d8cf | [
"BSD-3-Clause"
] | 1 | 2019-09-05T01:54:54.000Z | 2019-09-05T01:54:54.000Z | //
// ZoneAboutMeCell.h
// Zone
//
// Created by 高建飞 on 2018/5/15.
// Copyright © 2018年 pansoft. All rights reserved.
// 引力场与我相关Cell
//
#import <UIKit/UIKit.h>
#import "Zone.h"
@interface ZoneAboutMeCell : UITableViewCell
- (void)cellWithZoneModel:(ZoneModel *)zoneModel;
@end
| 15.888889 | 51 | 0.695804 |
eee52676566f39b39225339fc8893127b05df839 | 500 | h | C | Example Projects/Example-for-iOS-7-and-6/Example/Classes/ActionSheetPickerCustomPickerDelegate.h | thanhcuong1990/ActionSheetPicker-3.0 | c46107a703245ddb01bee7b3bfaf9c14432925ba | [
"BSD-3-Clause"
] | 292 | 2015-01-05T11:36:23.000Z | 2022-03-01T06:26:28.000Z | Example Projects/Example-for-iOS-7-and-6/Example/Classes/ActionSheetPickerCustomPickerDelegate.h | thanhcuong1990/ActionSheetPicker-3.0 | c46107a703245ddb01bee7b3bfaf9c14432925ba | [
"BSD-3-Clause"
] | 15 | 2015-01-09T07:21:58.000Z | 2021-07-14T08:42:03.000Z | Example Projects/Example-for-iOS-7-and-6/Example/Classes/ActionSheetPickerCustomPickerDelegate.h | thanhcuong1990/ActionSheetPicker-3.0 | c46107a703245ddb01bee7b3bfaf9c14432925ba | [
"BSD-3-Clause"
] | 61 | 2015-01-09T04:18:17.000Z | 2021-06-02T16:50:45.000Z | //
// ActionSheetPickerCustomPickerDelegate.h
// ActionSheetPicker
//
// Created by on 13/03/2012.
// Copyright (c) 2012 Club 15CC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ActionSheetPicker.h"
@interface ActionSheetPickerCustomPickerDelegate : NSObject <ActionSheetCustomPickerDelegate>
{
NSArray *notesToDisplayForKey;
NSArray *scaleNames;
}
@property (nonatomic, strong) NSString *selectedKey;
@property (nonatomic, strong) NSString *selectedScale;
@end
| 22.727273 | 93 | 0.764 |
7c57316cf19a7bb7afb8fd3e026e3797e5fa8d59 | 361 | h | C | MUpdate/MUIObserver.h | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | MUpdate/MUIObserver.h | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | MUpdate/MUIObserver.h | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | #pragma once
enum MUICATEGORY {
MUICATEGORY_INFO,
MUICATEGORY_FILE,
MUICATEGORY_END
};
class MUIObserver {
public:
MUIObserver() {}
virtual ~MUIObserver() {}
virtual void UpdateMsg(int nCategory, char* pszMsg) = 0;
virtual void UpdateProgress(char* pszFileName, unsigned long dwRead, unsigned long nTransSumBytes, unsigned long nMaxBytes) = 0;
};
| 19 | 129 | 0.753463 |
c6edad54d9a6c32f5cbeb517fcc030f8bae62ba6 | 129 | h | C | svn_code/nsuite/trunk/nstream/lib/libnspike/ext/libcfu-0.03/include/cfuconf.h | coganlab/MATLAB-env | a387fdf29da39be616cb60e444b0958dda4d6759 | [
"MIT"
] | null | null | null | svn_code/nsuite/trunk/nstream/lib/libnspike/ext/libcfu-0.03/include/cfuconf.h | coganlab/MATLAB-env | a387fdf29da39be616cb60e444b0958dda4d6759 | [
"MIT"
] | null | null | null | svn_code/nsuite/trunk/nstream/lib/libnspike/ext/libcfu-0.03/include/cfuconf.h | coganlab/MATLAB-env | a387fdf29da39be616cb60e444b0958dda4d6759 | [
"MIT"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:fb93dbc2d6f009ed7e72f1744c03e85954f73f0e2c21f4bb949f2cba7143d910
size 4248
| 32.25 | 75 | 0.883721 |
0c74d8985af1c5363929d48a2475c0108ff5ce32 | 207 | h | C | TNScrollView/ViewController.h | terrynie/TNScrollView | 3317631aacf759471a888b28c6b89ec5c390dc89 | [
"MIT"
] | 1 | 2016-04-22T07:39:08.000Z | 2016-04-22T07:39:08.000Z | TNScrollView/ViewController.h | terrynie/TNScrollView | 3317631aacf759471a888b28c6b89ec5c390dc89 | [
"MIT"
] | null | null | null | TNScrollView/ViewController.h | terrynie/TNScrollView | 3317631aacf759471a888b28c6b89ec5c390dc89 | [
"MIT"
] | null | null | null | //
// ViewController.h
// TNScrollView
//
// Created by Terry on 4/9/16.
// Copyright © 2016 Terry. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
| 12.9375 | 48 | 0.681159 |
91dc70fd0f9ce46640274d98d66ef5d16fb6598f | 2,129 | h | C | Src/Gui/SpellCastingWindow.h | XoDeR/RioRpg | dedba1c6440b29087ad688f19fd74414dd5d1fb5 | [
"MIT"
] | 1 | 2017-11-23T09:00:26.000Z | 2017-11-23T09:00:26.000Z | Src/Gui/SpellCastingWindow.h | XoDeR/RioRpg | dedba1c6440b29087ad688f19fd74414dd5d1fb5 | [
"MIT"
] | null | null | null | Src/Gui/SpellCastingWindow.h | XoDeR/RioRpg | dedba1c6440b29087ad688f19fd74414dd5d1fb5 | [
"MIT"
] | null | null | null | // Copyright (c) 2012-2017 Volodymyr Syvochka
#pragma once
#include <vector>
#include <string>
#include "GuiWindow.h"
namespace RioGame
{
class Spellcaster;
// Class representing the spell selection window, allows the player to cast registered (unlocked) spells
class SpellCastingWindow : public GuiWindow
{
private:
// Names of all registered spells
std::vector<std::string> spellNameList;
// Number of the current rightmost selection
// The window shows buildings with indices <selectionNumber - 3, selectionNumber>
uint32_t selectionNumber = 3;
// Does the actual spell casting once a spell is selected in this window
Spellcaster* spellcaster = nullptr;
// Keeps track of the spell that is being currently casted
int currentActiveSpell = -1;
public:
// Appends a table name to the vector of all spell tables
void registerSpell(const std::string& spellName);
// Sets the caster instance used to cast the spells
void setCaster(Spellcaster* newSpellCaster);
// Hides the "active" label
void deactivateCurrentSpell();
// Returns a vector containing the names of all unlocked spells (Used for serialization)
const std::vector<std::string>& getSpells() const;
// Removes all unlocked spell
void clearSpells();
// Decrements selectionNumber by one and updates the window
bool decreaseSelection();
// Increments selectionNumber by one and updates the window
bool increaseSelection();
// Marks a given spell as active
// Position of the spell in the current view (0-3)
void setSpellActive(int);
// Casts a spell at a given position
// The position of the spell (1-4)
void cast(int);
protected:
// Initializes the window and subscribes events
void init() override;
private:
// Range checked this->buildingNameList index access, returns the name
// of the building at a given index or "UNKNOWN" if the index is out of bounds
// Index of the building in the buildings vector
const std::string& getSpell(uint32_t);
// Updates building names on the buttons
void updateSelection();
};
} // namespace RioGame
// Copyright (c) 2012-2017 Volodymyr Syvochka | 35.483333 | 105 | 0.743542 |
91e7802646cbdbd810ca438d237925f5250f712d | 982 | h | C | TheEssenceOfAGoodDay/Input/Input.h | ongornbk/TheEssenceOfAGoodDay | f9a89228d49d52fd0a6c22428f88d687b341330b | [
"MIT"
] | null | null | null | TheEssenceOfAGoodDay/Input/Input.h | ongornbk/TheEssenceOfAGoodDay | f9a89228d49d52fd0a6c22428f88d687b341330b | [
"MIT"
] | 1 | 2019-04-11T09:19:08.000Z | 2019-04-11T09:19:08.000Z | TheEssenceOfAGoodDay/Input/Input.h | ongornbk/TheEssenceOfAGoodDay | f9a89228d49d52fd0a6c22428f88d687b341330b | [
"MIT"
] | null | null | null | #pragma once
#include "..\Core\Src\mmemory.h"
class Input
{
public:
enum DeviceReadingState
{
READ_KEYBOARD, READ_MOUSE, READ_KEYBOARDANDMOUSE, READ_NOTHING
};
virtual bool Initialize(const HINSTANCE hInstance, const HWND hwnd, const int32 screenWidth, const int32 screenHeight) = 0;
virtual bool Update() = 0;
virtual void Release() = 0;
virtual bool IsKeyDown(const uint32 key) const noexcept = 0;
virtual bool IsKeyHit(const uint32 key) const noexcept = 0;
virtual void GetMousePosition(int32& x, int32& y) const noexcept = 0;
virtual void SetReadingState(const DeviceReadingState readingState) noexcept = 0;
virtual BYTE GetMouseState(const int32 index) const noexcept = 0;
virtual bool GetMousePressed(const int32 index) const noexcept = 0;
};
enum MouseButton
{
MOUSE_LEFT_BUTTON = 0,
MOUSE_RIGHT_BUTTON = 1
};
enum KeyboardKey
{
KEYBOARD_KEY_ESCAPE = 0x01,
KEYBOARD_KEY_1 = 0x02,
KEYBOARD_KEY_2 = 0x03,
KEYBOARD_KEY_3 = 0x04,
KEYBOARD_KEY_4 = 0x05
}; | 27.277778 | 124 | 0.765784 |
dc251dc304a10204705e2b60985da29d1da9d6ce | 5,599 | h | C | Sources/include/manipulate_memory/manipulate_memory.h | KumarjitDas/Manipulate-Memory | 7e206f3d3874ff9f75f2c07664120e6ce68b62ee | [
"MIT"
] | null | null | null | Sources/include/manipulate_memory/manipulate_memory.h | KumarjitDas/Manipulate-Memory | 7e206f3d3874ff9f75f2c07664120e6ce68b62ee | [
"MIT"
] | null | null | null | Sources/include/manipulate_memory/manipulate_memory.h | KumarjitDas/Manipulate-Memory | 7e206f3d3874ff9f75f2c07664120e6ce68b62ee | [
"MIT"
] | null | null | null | /**
* \file manipulate_memory.h
* \author Kumarjit Das (kumarjitdas1999@gmail.com)
* \brief Contains all `Manipulate-Memory` library function declarations.
* \version 0.3.0
* \date 2021-12-10
*
* \copyright Copyright (c) 2021
*
* License(MIT License):
*
* Copyright (c) 2021 Kumarjit Das | কুমারজিৎ দাস
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef _KDI_MANIPULATE_MEMORY_H_
#define _KDI_MANIPULATE_MEMORY_H_
#include "manipulate_memory_api.h"
#include "manipulate_memory_version.h"
#include <stdint.h>
#if defined(INT64_MAX) && defined(INT64_MIN)
#ifndef KDI_MANIPULATE_MEMORY_ARCHITECTURE_64_BIT
#define KDI_MANIPULATE_MEMORY_ARCHITECTURE_64_BIT
#endif /* KDI_MANIPULATE_MEMORY_ARCHITECTURE_64_BIT */
#endif /* defined(INT64_MAX) && defined(INT64_MIN) */
// #undef KDI_MANIPULATE_MEMORY_ARCHITECTURE_64_BIT
#ifdef KDI_MANIPULATE_MEMORY_ARCHITECTURE_64_BIT
/**
* \brief Copy the source to the destination and return the destination.
*
* \param pDestination destination memory location
* \param pSource source memory location
* \param u64Size copying size
*
* \return destination memory location
*
* \warning `pDestination` and `pSource` should be non-null pointers
* \warning `u64Size` should be a non-zero value
*
* \since v0.3.0
*/
void KDI_MANIPULATE_MEMORY_API *
kdi_copy_memory(void *pDestination,
void *pSource,
uint64_t u64Size);
/**
* \brief Copy the source to the destination while avoiding any overlap and
* return the destination.
*
* \param pDestination destination memory location
* \param pSource source memory location
* \param u64Size copying size
*
* \return destination memory location
*
* \warning `pDestination` and `pSource` should be non-null pointers
* \warning `u64Size` should be a non-zero value
*
* \since v0.3.0
*/
void KDI_MANIPULATE_MEMORY_API *
kdi_move_memory(void *pDestination,
void *pSource,
uint64_t u64Size);
/**
* \brief Copy the source to the destination and return the destination.
*
* \param pMemory destination memory location
* \param u64Memory_size destination memory size
* \param pValue source memory location
* \param u64Value_size source memory size
*
* \return destination memory location
*
* \warning `pMemory` and `pValue` should be non-null pointers
* \warning `u64Memory_size` and `u64Value_size` should be a non-zero value
*/
void KDI_MANIPULATE_MEMORY_API *
kdi_set_memory(void *pMemory,
uint64_t u64Memory_size,
void *pValue,
uint64_t u64Value_size);
void KDI_MANIPULATE_MEMORY_API *
kdi_find_in_memory(void *pMemory,
uint64_t u64Memory_size,
void *pValue,
uint64_t u64Value_size);
uint64_t KDI_MANIPULATE_MEMORY_API
kdi_find_index_in_memory(void *pMemory,
uint64_t u64Memory_size,
void *pValue,
uint64_t u64Value_size);
uint64_t KDI_MANIPULATE_MEMORY_API
kdi_find_element_index_in_memory(void *pMemory,
uint64_t u64Memory_size,
void *pValue,
uint64_t u64Value_size);
void KDI_MANIPULATE_MEMORY_API *
kdi_replace_in_memory(void *pMemory,
uint64_t u64Memory_size,
void *pFind_value,
void *pReplace_value,
uint64_t u64Value_size);
int64_t KDI_MANIPULATE_MEMORY_API
kdi_compare_memory(void *p1,
void *p2,
uint64_t u64Size);
void KDI_MANIPULATE_MEMORY_API *
kdi_apply_function_in_memory(void *pMemory,
uint64_t u64Size,
void (*pfFunction)(void *));
void KDI_MANIPULATE_MEMORY_API *
kdi_apply_index_function_in_memory(void *pMemory,
uint64_t u64Size,
void (*pfFunction)(uint64_t,
void *));
void KDI_MANIPULATE_MEMORY_API *
kdi_apply_element_index_function_in_memory(void *pMemory,
uint64_t u64Size,
void (*pfFunction)(uint64_t,
void *));
#else /* KDI_MANIPULATE_MEMORY_ARCHITECTURE_64_BIT not defined */
#endif /* KDI_MANIPULATE_MEMORY_ARCHITECTURE_64_BIT */
#endif /* _KDI_MANIPULATE_MEMORY_H_ */
| 35.213836 | 79 | 0.665297 |
09cfcef5bbd7b3ddcc1491e92bb3cd8f9aa917e8 | 2,563 | h | C | qt-creator-opensource-src-4.6.1/tests/auto/generichighlighter/highlighterengine/highlightermock.h | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/tests/auto/generichighlighter/highlighterengine/highlightermock.h | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/tests/auto/generichighlighter/highlighterengine/highlightermock.h | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include <texteditor/generichighlighter/highlighter.h>
#include <QList>
struct HighlightSequence
{
HighlightSequence() {}
HighlightSequence(int from, int to, const QTextCharFormat &format = QTextCharFormat())
{ add(from, to, format); }
HighlightSequence(const HighlightSequence &sequence)
{ m_formats = sequence.m_formats; }
void add(int from, int to, const QTextCharFormat &format = QTextCharFormat())
{
for (int i = from; i < to; ++i)
m_formats.append(format);
}
QList<QTextCharFormat> m_formats;
};
class HighlighterMock : public TextEditor::Highlighter
{
public:
HighlighterMock(QTextDocument *parent = 0);
void reset();
void showDebugDetails();
void considerEmptyLines();
void startNoTestCalls();
void endNoTestCalls();
void setExpectedBlockState(const int state);
void setExpectedBlockStates(const QList<int> &states);
void setExpectedHighlightSequence(const HighlightSequence &format);
void setExpectedHighlightSequences(const QList<HighlightSequence> &formats);
protected:
virtual void highlightBlock(const QString &text);
private:
QList<int> m_states;
int m_statesCounter;
QList<HighlightSequence> m_formatSequence;
int m_formatsCounter;
bool m_debugDetails;
bool m_noTestCall;
bool m_considerEmptyLines;
};
| 32.858974 | 90 | 0.692158 |
86ff927c74d7187732b992be46f81bad33b116de | 655 | h | C | Vibe/Plug-ins/MAXON CINEWARE AE/(CINEWARE Support)/bin/resource/modules/tpoperators/description/op_particledraw.h | kaapiel/Vibe-Rendering-Template | d2aee7aab21dc32831e9e298576caac3db7bdef3 | [
"Apache-2.0"
] | 1 | 2022-02-06T06:24:04.000Z | 2022-02-06T06:24:04.000Z | Vibe/Plug-ins/MAXON CINEWARE AE/(CINEWARE Support)/bin/resource/modules/tpoperators/description/op_particledraw.h | kaapiel/Vibe-Rendering-Template | d2aee7aab21dc32831e9e298576caac3db7bdef3 | [
"Apache-2.0"
] | null | null | null | Vibe/Plug-ins/MAXON CINEWARE AE/(CINEWARE Support)/bin/resource/modules/tpoperators/description/op_particledraw.h | kaapiel/Vibe-Rendering-Template | d2aee7aab21dc32831e9e298576caac3db7bdef3 | [
"Apache-2.0"
] | null | null | null | #ifndef OP_PARTICLEDRAW_H__
#define OP_PARTICLEDRAW_H__
#include "gvbase.h"
enum
{
OP_PARTICLEDRAW_SEED = 1000,
OP_PARTICLEDRAW_TYPE = 1001,
OP_PARTICLEDRAW_RADIUS = 1002,
OP_PARTICLEDRAW_COUNT = 1003,
OP_PARTICLEDRAW_LIFE = 1004,
OP_PARTICLEDRAW_LIFEVAR = 1005,
OP_PARTICLEDRAW_DRAWPOS = 1006,
OP_PARTICLEDRAW_REMOVE = 1007,
OP_PARTICLEDRAW_TYPE_POINT = 0,
OP_PARTICLEDRAW_TYPE_SPHERICAL = 1,
OP_PARTICLEDRAW_ON = 2000,
OP_PARTICLEDRAW_ATIME = 2001,
OP_PARTICLEDRAW_OUT_PARTICLE = 3000,
OP_PARTICLEDRAW_OUT_PARTICLECOUNT = 3001,
OP_PARTICLEDRAW_OUT_PARTICLENUM = 3002
};
#endif // OP_PARTICLEDRAW_H__
| 21.833333 | 42 | 0.769466 |
c65fd877e4fd9ea3efc011fd34bc92d1d51b78d7 | 2,137 | h | C | blades/xbmc/xbmc/linux/LinuxTimezone.h | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/linux/LinuxTimezone.h | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/linux/LinuxTimezone.h | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | #ifndef LINUX_TIMEZONE_
#define LINUX_TIMEZONE_
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "settings/lib/ISettingCallback.h"
#include "settings/lib/ISettingsHandler.h"
#include <string>
#include <vector>
#include <map>
class CSetting;
class CLinuxTimezone : public ISettingCallback, public ISettingsHandler
{
public:
CLinuxTimezone();
virtual void OnSettingChanged(const CSetting *setting) override;
virtual void OnSettingsLoaded() override;
std::string GetOSConfiguredTimezone();
std::vector<std::string> GetCounties();
std::vector<std::string> GetTimezonesByCountry(const std::string& country);
std::string GetCountryByTimezone(const std::string& timezone);
void SetTimezone(std::string timezone);
int m_IsDST;
static void SettingOptionsTimezoneCountriesFiller(const CSetting *setting, std::vector< std::pair<std::string, std::string> > &list, std::string ¤t, void *data);
static void SettingOptionsTimezonesFiller(const CSetting *setting, std::vector< std::pair<std::string, std::string> > &list, std::string ¤t, void *data);
private:
std::vector<std::string> m_counties;
std::map<std::string, std::string> m_countryByCode;
std::map<std::string, std::string> m_countryByName;
std::map<std::string, std::vector<std::string> > m_timezonesByCountryCode;
std::map<std::string, std::string> m_countriesByTimezoneName;
};
extern CLinuxTimezone g_timezone;
#endif
| 32.876923 | 170 | 0.736079 |
3ce32524cc560777c79fe8d1de243377216e25e9 | 6,205 | h | C | src/loginserver/rmiclient/rmidaloginclient.h | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 3 | 2021-12-16T13:57:28.000Z | 2022-03-26T07:50:08.000Z | src/loginserver/rmiclient/rmidaloginclient.h | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | null | null | null | src/loginserver/rmiclient/rmidaloginclient.h | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 1 | 2022-03-26T07:50:11.000Z | 2022-03-26T07:50:11.000Z |
#ifndef RMILOGINCLIENT_H
#define RMILOGINCLIENT_H
#include "rmi/rmibase.h"
#include "servercommon/logindef.h"
class RMILoginClient : public rmi::RMIProxyObject
{
public:
RMILoginClient(){};
virtual ~RMILoginClient(){};
bool GetProfNum(rmi::RMIBackObject *backobj);
bool UserLoginAsyn(const char *pname, char can_insert, rmi::RMIBackObject *backobj);
bool AddRoleAsyn(const char *pname, int db_index, int role_id, rmi::RMIBackObject *backobj);
bool RemoveRoleAsyn(const char *pname, int db_index, int role_id, rmi::RMIBackObject *backobj);
bool Frobid(const char *pname, unsigned int forbid_time, rmi::RMIBackObject *backobj);
bool FrobidOneRole(const char *pname, int role_id, unsigned int forbid_time, rmi::RMIBackObject *backobj);
bool AddNameInfoAsyn(const char *role_name, const char *pname, rmi::RMIBackObject *backobj);
bool UpdateNameInfoAsyn(const char *role_name, int db_index, int role_id, rmi::RMIBackObject *backobj);
bool DeleteNameInfoAsyn(int db_index, int role_id, const char *pname, rmi::RMIBackObject *backobj);
bool DeleteNameInfoByNameAsyn(const char *role_name, rmi::RMIBackObject *backobj);
bool AddIdentityAsyn(const char *pname, const char *name, const char *id, bool check_repeat, rmi::RMIBackObject *backobj);
bool InitWorldStatus(rmi::RMIBackObject *backobj);
bool SaveWorldStatus(bool is_register_limit, rmi::RMIBackObject *backobj);
};
class RMIGetProfNumBackObject : public rmi::RMIBackObject
{
public:
RMIGetProfNumBackObject(){};
virtual ~RMIGetProfNumBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){};
virtual void __timeout(){};
virtual void __free();
protected:
virtual void GetProfNumRet(int ret, int prof1_num, int prof2_num, int prof3_num, int prof4_num);
};
class RMIUserLoginBackObject : public rmi::RMIBackObject
{
public:
RMIUserLoginBackObject(){};
virtual ~RMIUserLoginBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){};
virtual void __timeout(){};
virtual void __free();
protected:
virtual void UserLoginRet(int ret, int db_index, int role_1, int role_2, int role_3);
};
class RMIAddRoleBackObject : public rmi::RMIBackObject
{
public:
RMIAddRoleBackObject(){};
virtual ~RMIAddRoleBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){ Error(); }
virtual void __timeout(){ Error(); }
virtual void __free();
protected:
virtual void AddRoleRet(int result);
virtual void Error(){}
};
class RMIRemoveRoleBackObject : public rmi::RMIBackObject
{
public:
RMIRemoveRoleBackObject(){};
virtual ~RMIRemoveRoleBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){};
virtual void __timeout(){};
virtual void __free();
protected:
virtual void RemoveRoleRet(int result);
};
class RMIPassAntiWallowBackObject : public rmi::RMIBackObject
{
public:
RMIPassAntiWallowBackObject(){};
virtual ~RMIPassAntiWallowBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){};
virtual void __timeout(){};
virtual void __free();
protected:
virtual void PassAntiWallowRet(int ret);
};
class RMIForbidBackObject : public rmi::RMIBackObject
{
public:
RMIForbidBackObject(){};
virtual ~RMIForbidBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){};
virtual void __timeout(){};
virtual void __free();
protected:
virtual void ForbidRet(int result, int db_index, int role_1, int role_2, int role_3);
};
class RMIForbidOneRoleBackObject : public rmi::RMIBackObject
{
public:
RMIForbidOneRoleBackObject() {};
virtual ~RMIForbidOneRoleBackObject() {};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error) {}
virtual void __timeout() {}
virtual void __free();
protected:
virtual void ForbidOneRoleRet(int result, int db_index);
};
class RMIAddNameInfoBackObject : public rmi::RMIBackObject
{
public:
RMIAddNameInfoBackObject(){};
virtual ~RMIAddNameInfoBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){};
virtual void __timeout(){};
virtual void __free();
protected:
virtual void AddNameInfoRet(int result);
};
class RMIUpdateNameInfoBackObject : public rmi::RMIBackObject
{
public:
RMIUpdateNameInfoBackObject(){};
virtual ~RMIUpdateNameInfoBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){};
virtual void __timeout(){};
virtual void __free();
protected:
virtual void UpdateNameInfoRet(int result);
};
class RMIDeleteNameInfoBackObject : public rmi::RMIBackObject
{
public:
RMIDeleteNameInfoBackObject(){};
virtual ~RMIDeleteNameInfoBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){};
virtual void __timeout(){};
virtual void __free();
protected:
virtual void DeleteNameInfoRet(int result);
};
class RMIDeleteNameInfoByNameBackObject : public rmi::RMIBackObject
{
public:
RMIDeleteNameInfoByNameBackObject(){};
virtual ~RMIDeleteNameInfoByNameBackObject(){};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error){};
virtual void __timeout(){};
virtual void __free();
protected:
virtual void DeleteNameInfoByNameRet(int result);
};
class RMILoginInitWorldStatusBackObject : public rmi::RMIBackObject
{
public:
RMILoginInitWorldStatusBackObject() {};
virtual ~RMILoginInitWorldStatusBackObject() {};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error) {};
virtual void __timeout() {};
virtual void __free();
protected:
virtual void InitWorldStatusRet(int result, bool is_register_limit);
};
class RMILoginSaveWorldStatusBackObject : public rmi::RMIBackObject
{
public:
RMILoginSaveWorldStatusBackObject() {};
virtual ~RMILoginSaveWorldStatusBackObject() {};
virtual bool __response(TLVUnserializer &out_param);
virtual void __exception(int error) {};
virtual void __timeout() {};
virtual void __free();
protected:
virtual void SaveWorldStatusRet(int ret);
};
#endif
| 29.131455 | 123 | 0.77776 |
ef469cd9625c7b9b0c6ba1dc11a53e4b3d284401 | 1,153 | c | C | A05/glitch.c | paigeschaefer16/assignments | 74af6d5e6d53602c257ba9a25bb18587eb93d747 | [
"MIT"
] | null | null | null | A05/glitch.c | paigeschaefer16/assignments | 74af6d5e6d53602c257ba9a25bb18587eb93d747 | [
"MIT"
] | null | null | null | A05/glitch.c | paigeschaefer16/assignments | 74af6d5e6d53602c257ba9a25bb18587eb93d747 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "read_ppm.h"
int main(int argc, char** argv) {
const char * fileName = argv[1];
int width = 0;
int height = 0;
struct ppm_pixel* pixelArray = read_ppm(fileName, &width,&height);
printf("Reading %s with %d and height %d\n",fileName,width,height);
for(int i = 0; i < width* height; i++){
pixelArray[i].red = pixelArray[i].red << (rand() % 2);
pixelArray[i].green = pixelArray[i].green << (rand() % 4);
pixelArray[i].blue = pixelArray[i].blue << (rand() % 6);
}
const char * outputFile = fileName;
char result[100];
strcpy(result,outputFile);
for(int i = 0; i < strlen(outputFile) + 7;i++){
if(result[i] == '.'){
result[i] = '-';
result[i+1] = 'g';
result[i+2] = 'l';
result[i+3] = 'i';
result[i+4] = 't';
result[i+5] = 'c';
result[i+6] = 'h';
result[i+7] = '.';
result[i+8] = 'p';
result[i+9] = 'p';
result[i+10] = 'm';
result[i+11] = '\0';
break;
}
}
printf("Writing file %s\n",result);
write_ppm(result,pixelArray,width,height);
return 0;
}
| 24.020833 | 69 | 0.542064 |
89b732fd612c1d19067c7c119de3cc7147b85641 | 6,773 | c | C | Model-code/DAYCENT/SOURCE/wrtyrcflows.c | bsulman/INTERFACE-model-experiment-synthesis | a20eebe34f9271233ecc4e7c84403b805bb0b523 | [
"MIT"
] | 1 | 2018-11-13T17:03:43.000Z | 2018-11-13T17:03:43.000Z | Model-code/DAYCENT/SOURCE/wrtyrcflows.c | yuanhongdeng/INTERFACE-model-experiment-synthesis | a20eebe34f9271233ecc4e7c84403b805bb0b523 | [
"MIT"
] | null | null | null | Model-code/DAYCENT/SOURCE/wrtyrcflows.c | yuanhongdeng/INTERFACE-model-experiment-synthesis | a20eebe34f9271233ecc4e7c84403b805bb0b523 | [
"MIT"
] | 3 | 2018-11-04T14:40:41.000Z | 2021-07-16T11:33:52.000Z |
/* Copyright 1993 Colorado State University */
/* All Rights Reserved */
/*****************************************************************************
**
** FILE: wrtyrcflows.c
**
** FUNCTION: void wrtyrcflows()
**
** PURPOSE: This function writes daily values for tracking carbon flows
** from decomposition.
**
** INPUTS:
** ametc1tosom11 - annual accumulator for carbon flow from surface
** metabolic pool to fast surface organic matter
** pool (g/m^2)
** ametc2tosom12 - annual accumulator for carbon flow from soil
** metabolic pool to fast soil organic matter pool
** (g/m^2)
** asom11tosom21 - annual accumulator of carbon flow from fast surface
** organic matter pool to intermediate surface organic
** matter pool (g/m^2)
** asom12tosom22 - annual accumulator of carbon flow from fast soil
** organic matter pool to intermediate soil organic matter
** pool (g/m^2)
** asom12tosom3 - annual accumulator of carbon flow from fast soil
** organic matter pool to slow soil organic matter pool
** (g/m^2)
** asom21tosom11 - annual accumulator of carbon flow from intermediate
** surface organic matter pool to fast surface organic
** matter pool (g/m^2)
** asom21tosom22 - annual accumulator of carbon flow from intermediate
** surface organic matter pool to intermediate soil
** organic matter pool (g/m^2)
** asom22tosom12 - annual accumulator of carbon flow from intermediate
** soil organic matter pool to fast soil organic matter
** pool (g/m^2)
** asom22tosom3 - annual accumulator of carbon flow from intermediate
** soil organic matter pool to slow soil organic matter
** pool (g/m^2)
** asom3tosom12 - annual accumulator of carbon flow from slow soil
** organic matter pool to fast soil organic matter pool
** (g/m^2)
** astruc1tosom11 - annual accumulator for carbon flow from surface
** structural pool to fast surface organic matter
** pool (g/m^2)
** astruc1tosom21 - annual accumulator for carbon flow from surface
** structural pool to intermediate surface organic
** matter pool (g/m^2)
** astruc2tosom12 - annual accumulator for carbon flow from soil
** structural pool to fast soil organic matter pool
** (g/m^2)
** astruc2tosom22 - annual accumulator for carbon flow from soil
** structural pool to intermediate soil organic
** matter pool (g/m^2)
** awood1tosom11 - annual accumulator for carbon flow from dead
** fine branch pool to fast surface organic matter pool
** (g/m^2)
** awood1tosom21 - annual accumulator for carbon flow from dead fine
** branch pool pool to intermediate surface organic matter
** pool (g/m^2)
** awood2tosom11 - annual accumulator for carbon flow from dead large wood
** pool to fast surface organic matter pool (g/m^2)
** awood2tosom21 - annual accumulator for carbon flow from dead large wood
** pool to intermediate surface organic matter pool
** (g/m^2)
** awood3tosom12 - annual accumulator for carbon flow from dead coarse
** root pool to fast soil organic matter pool (g/m^2)
** awood3tosom22 - annual accumulator for carbon flow from dead coarse
** root pool to intermediate soil organic matter pool
** (g/m^2)
** time - current simulation time (years)
**
** GLOBAL VARIABLES:
** None
**
** EXTERNAL VARIABLES:
** files->fp_yrcflows - file pointer to year_cflows.out output file
** files->write_yrcflows - flag to indicate if yearcflows.out output file
** should be created, 0 = do not create, 1 = create
**
** LOCAL VARIABLES:
** None
**
** OUTPUTS:
** None
**
** CALLED BY:
** dailymoist()
**
*****************************************************************************/
#include <math.h>
#include <stdio.h>
#include "soilwater.h"
void wrtyrcflows(double *time, double *asom11tosom21, double *asom12tosom22,
double *asom12tosom3, double *asom21tosom11,
double *asom21tosom22, double *asom22tosom12,
double *asom22tosom3, double *asom3tosom12,
double *ametc1tosom11, double *ametc2tosom12,
double *astruc1tosom11, double *astruc1tosom21,
double *astruc2tosom12, double *astruc2tosom22,
double *awood1tosom11, double *awood1tosom21,
double *awood2tosom11, double *awood2tosom21,
double *awood3tosom12, double *awood3tosom22)
{
extern FILES_SPT files;
if (!files->write_yrcflows) {
return;
}
fprintf(files->fp_yrcflows, "%8.2lf,", *time);
fprintf(files->fp_yrcflows, "%12.6lf,", *asom11tosom21);
fprintf(files->fp_yrcflows, "%12.6lf,", *asom12tosom22);
fprintf(files->fp_yrcflows, "%12.6lf,", *asom12tosom3);
fprintf(files->fp_yrcflows, "%12.6lf,", *asom21tosom11);
fprintf(files->fp_yrcflows, "%12.6lf,", *asom21tosom22);
fprintf(files->fp_yrcflows, "%12.6lf,", *asom22tosom12);
fprintf(files->fp_yrcflows, "%12.6lf,", *asom22tosom3);
fprintf(files->fp_yrcflows, "%12.6lf,", *asom3tosom12);
fprintf(files->fp_yrcflows, "%12.6lf,", *ametc1tosom11);
fprintf(files->fp_yrcflows, "%12.6lf,", *ametc2tosom12);
fprintf(files->fp_yrcflows, "%12.6lf,", *astruc1tosom11);
fprintf(files->fp_yrcflows, "%12.6lf,", *astruc1tosom21);
fprintf(files->fp_yrcflows, "%12.6lf,", *astruc2tosom12);
fprintf(files->fp_yrcflows, "%12.6lf,", *astruc2tosom22);
fprintf(files->fp_yrcflows, "%12.6lf,", *awood1tosom11);
fprintf(files->fp_yrcflows, "%12.6lf,", *awood1tosom21);
fprintf(files->fp_yrcflows, "%12.6lf,", *awood2tosom11);
fprintf(files->fp_yrcflows, "%12.6lf,", *awood2tosom21);
fprintf(files->fp_yrcflows, "%12.6lf,", *awood3tosom12);
fprintf(files->fp_yrcflows, "%12.6lf", *awood3tosom22);
fprintf(files->fp_yrcflows, "\n");
return;
}
| 48.035461 | 80 | 0.57552 |
e6899f3614a1103c7266eefc98067eabab271445 | 1,561 | h | C | Introduction to Computer/HW5_prolog_heap/minheap.h | christinesfkao/MyFreshmanYear | 56aaf3356b6caf00749af3d272140d1e711f981e | [
"MIT"
] | null | null | null | Introduction to Computer/HW5_prolog_heap/minheap.h | christinesfkao/MyFreshmanYear | 56aaf3356b6caf00749af3d272140d1e711f981e | [
"MIT"
] | null | null | null | Introduction to Computer/HW5_prolog_heap/minheap.h | christinesfkao/MyFreshmanYear | 56aaf3356b6caf00749af3d272140d1e711f981e | [
"MIT"
] | null | null | null | #ifndef _MINHEAP_H_
#define _MINHEAP_H_
#include <iostream>
using namespace std;
class MinHeap : public AbsHeap
{
public:
virtual void push(int _key, char _element)
{
int target = size + 1;
while (_key < ary[(target - 1) / 2].key)
// allocate it to ary[size + 1], and then compare with its parent
{
swap ( (target - 1) / 2, target );
target = (target - 1) / 2;
} // end while and do nothing as long as it is larger than its parent
size++; // size of heap increases as long as a "push" is executed
};
virtual char pop()
{
int index = 0;
swap (0, size); //replace the root with the last element
// sink down choosing the smaller path
while ((ary[index].key > ary[2 * index + 1].key) && (ary[index].key > ary[2 * index + 2].key))
// target node is larger than both of its children => sink
{
if (ary[2 * index + 1].key > ary[2 * index + 2].key) // choose the smaller path
{
swap (index, 2 * index + 2);
index = 2 * index + 2;
}
else
{
swap (index, 2 * index + 1);
index = 2 * index + 1;
}
}
return ary[size].key; // return root (smallest node of all)
size--;
};
};
#endif
| 31.857143 | 107 | 0.444587 |
e4f913b461677a492100034065150e5a14376e2e | 795 | h | C | src/Providers/UNIXProviders/BootConfigSetting/UNIX_BootConfigSettingPrivate.h | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/BootConfigSetting/UNIX_BootConfigSettingPrivate.h | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/BootConfigSetting/UNIX_BootConfigSettingPrivate.h | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null |
#if defined(PEGASUS_OS_HPUX)
# include "UNIX_BootConfigSettingPrivate_HPUX.h"
#elif defined(PEGASUS_OS_LINUX)
# include "UNIX_BootConfigSettingPrivate_LINUX.h"
#elif defined(PEGASUS_OS_DARWIN)
# include "UNIX_BootConfigSettingPrivate_DARWIN.h"
#elif defined(PEGASUS_OS_AIX)
# include "UNIX_BootConfigSettingPrivate_AIX.h"
#elif defined(PEGASUS_OS_FREEBSD)
# include "UNIX_BootConfigSettingPrivate_FREEBSD.h"
#elif defined(PEGASUS_OS_SOLARIS)
# include "UNIX_BootConfigSettingPrivate_SOLARIS.h"
#elif defined(PEGASUS_OS_ZOS)
# include "UNIX_BootConfigSettingPrivate_ZOS.h"
#elif defined(PEGASUS_OS_VMS)
# include "UNIX_BootConfigSettingPrivate_VMS.h"
#elif defined(PEGASUS_OS_TRU64)
# include "UNIX_BootConfigSettingPrivate_TRU64.h"
#else
# include "UNIX_BootConfigSettingPrivate_STUB.h"
#endif
| 34.565217 | 51 | 0.849057 |
c265eb376c6a1842d94b01cffbcf1209482351c7 | 32,342 | c | C | tests/perlbench/Dumper.c | asheraryam/stabilizer | f1aefc1a3799687670a21d402818e643704d08d6 | [
"Apache-2.0"
] | 430 | 2015-01-05T19:21:10.000Z | 2022-03-29T07:19:18.000Z | tests/perlbench/Dumper.c | asheraryam/stabilizer | f1aefc1a3799687670a21d402818e643704d08d6 | [
"Apache-2.0"
] | 9 | 2015-01-20T17:42:30.000Z | 2022-03-04T22:05:43.000Z | tests/perlbench/Dumper.c | asheraryam/stabilizer | f1aefc1a3799687670a21d402818e643704d08d6 | [
"Apache-2.0"
] | 41 | 2015-05-10T17:08:50.000Z | 2022-01-19T01:15:19.000Z | /*
* This file was generated automatically by xsubpp version 1.9508 from the
* contents of Dumper.xs. Do not edit this file, edit Dumper.xs instead.
*
* ANY CHANGES MADE HERE WILL BE LOST!
*
*/
/* #line 1 "Dumper.xs" */
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
static I32 num_q (char *s, STRLEN slen);
static I32 esc_q (char *dest, char *src, STRLEN slen);
static I32 esc_q_utf8 (pTHX_ SV *sv, char *src, STRLEN slen);
static SV *sv_x (pTHX_ SV *sv, char *str, STRLEN len, I32 n);
static I32 DD_dump (pTHX_ SV *val, char *name, STRLEN namelen, SV *retval,
HV *seenhv, AV *postav, I32 *levelp, I32 indent,
SV *pad, SV *xpad, SV *apad, SV *sep, SV *pair,
SV *freezer, SV *toaster,
I32 purity, I32 deepcopy, I32 quotekeys, SV *bless,
I32 maxdepth, SV *sortkeys);
#if PERL_VERSION <= 6 /* Perl 5.6 and earlier */
# ifdef EBCDIC
# define UNI_TO_NATIVE(ch) (((ch) > 255) ? (ch) : ASCII_TO_NATIVE(ch))
# else
# define UNI_TO_NATIVE(ch) (ch)
# endif
UV
Perl_utf8_to_uvchr(pTHX_ U8 *s, STRLEN *retlen)
{
UV uv = utf8_to_uv(s, UTF8_MAXLEN, retlen,
ckWARN(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY);
return UNI_TO_NATIVE(uv);
}
# if !defined(PERL_IMPLICIT_CONTEXT)
# define utf8_to_uvchr Perl_utf8_to_uvchr
# else
# define utf8_to_uvchr(a,b) Perl_utf8_to_uvchr(aTHX_ a,b)
# endif
#endif /* PERL_VERSION <= 6 */
/* Changes in 5.7 series mean that now IOK is only set if scalar is
precisely integer but in 5.6 and earlier we need to do a more
complex test */
#if PERL_VERSION <= 6
#define DD_is_integer(sv) (SvIOK(sv) && (SvIsUV(val) ? SvUV(sv) == SvNV(sv) : SvIV(sv) == SvNV(sv)))
#else
#define DD_is_integer(sv) SvIOK(sv)
#endif
/* does a string need to be protected? */
static I32
needs_quote(register char *s)
{
TOP:
if (s[0] == ':') {
if (*++s) {
if (*s++ != ':')
return 1;
}
else
return 1;
}
if (isIDFIRST(*s)) {
while (*++s)
if (!isALNUM(*s)) {
if (*s == ':')
goto TOP;
else
return 1;
}
}
else
return 1;
return 0;
}
/* count the number of "'"s and "\"s in string */
static I32
num_q(register char *s, register STRLEN slen)
{
register I32 ret = 0;
while (slen > 0) {
if (*s == '\'' || *s == '\\')
++ret;
++s;
--slen;
}
return ret;
}
/* returns number of chars added to escape "'"s and "\"s in s */
/* slen number of characters in s will be escaped */
/* destination must be long enough for additional chars */
static I32
esc_q(register char *d, register char *s, register STRLEN slen)
{
register I32 ret = 0;
while (slen > 0) {
switch (*s) {
case '\'':
case '\\':
*d = '\\';
++d; ++ret;
default:
*d = *s;
++d; ++s; --slen;
break;
}
}
return ret;
}
static I32
esc_q_utf8(pTHX_ SV* sv, register char *src, register STRLEN slen)
{
char *s, *send, *r, *rstart;
STRLEN j, cur = SvCUR(sv);
/* Could count 128-255 and 256+ in two variables, if we want to
be like &qquote and make a distinction. */
STRLEN grow = 0; /* bytes needed to represent chars 128+ */
/* STRLEN topbit_grow = 0; bytes needed to represent chars 128-255 */
STRLEN backslashes = 0;
STRLEN single_quotes = 0;
STRLEN qq_escapables = 0; /* " $ @ will need a \ in "" strings. */
STRLEN normal = 0;
/* this will need EBCDICification */
for (s = src, send = src + slen; s < send; s += UTF8SKIP(s)) {
UV k = utf8_to_uvchr((U8*)s, NULL);
if (k > 127) {
/* 4: \x{} then count the number of hex digits. */
grow += 4 + (k <= 0xFF ? 2 : k <= 0xFFF ? 3 : k <= 0xFFFF ? 4 :
#if UVSIZE == 4
8 /* We may allocate a bit more than the minimum here. */
#else
k <= 0xFFFFFFFF ? 8 : UVSIZE * 4
#endif
);
} else if (k == '\\') {
backslashes++;
} else if (k == '\'') {
single_quotes++;
} else if (k == '"' || k == '$' || k == '@') {
qq_escapables++;
} else {
normal++;
}
}
if (grow) {
/* We have something needing hex. 3 is ""\0 */
sv_grow(sv, cur + 3 + grow + 2*backslashes + single_quotes
+ 2*qq_escapables + normal);
rstart = r = SvPVX(sv) + cur;
*r++ = '"';
for (s = src; s < send; s += UTF8SKIP(s)) {
UV k = utf8_to_uvchr((U8*)s, NULL);
if (k == '"' || k == '\\' || k == '$' || k == '@') {
*r++ = '\\';
*r++ = (char)k;
}
else if (k < 0x80)
*r++ = (char)k;
else {
/* The return value of sprintf() is unportable.
* In modern systems it returns (int) the number of characters,
* but in older systems it might return (char*) the original
* buffer, or it might even be (void). The easiest portable
* thing to do is probably use sprintf() in void context and
* then strlen(buffer) for the length. The more proper way
* would of course be to figure out the prototype of sprintf.
* --jhi */
sprintf(r, "\\x{%"UVxf"}", k);
r += strlen(r);
}
}
*r++ = '"';
} else {
/* Single quotes. */
sv_grow(sv, cur + 3 + 2*backslashes + 2*single_quotes
+ qq_escapables + normal);
rstart = r = SvPVX(sv) + cur;
*r++ = '\'';
for (s = src; s < send; s ++) {
char k = *s;
if (k == '\'' || k == '\\')
*r++ = '\\';
*r++ = k;
}
*r++ = '\'';
}
*r = '\0';
j = r - rstart;
SvCUR_set(sv, cur + j);
return j;
}
/* append a repeated string to an SV */
static SV *
sv_x(pTHX_ SV *sv, register char *str, STRLEN len, I32 n)
{
if (sv == Nullsv)
sv = newSVpvn("", 0);
else
assert(SvTYPE(sv) >= SVt_PV);
if (n > 0) {
SvGROW(sv, len*n + SvCUR(sv) + 1);
if (len == 1) {
char *start = SvPVX(sv) + SvCUR(sv);
SvCUR(sv) += n;
start[n] = '\0';
while (n > 0)
start[--n] = str[0];
}
else
while (n > 0) {
sv_catpvn(sv, str, len);
--n;
}
}
return sv;
}
/*
* This ought to be split into smaller functions. (it is one long function since
* it exactly parallels the perl version, which was one long thing for
* efficiency raisins.) Ugggh!
*/
static I32
DD_dump(pTHX_ SV *val, char *name, STRLEN namelen, SV *retval, HV *seenhv,
AV *postav, I32 *levelp, I32 indent, SV *pad, SV *xpad,
SV *apad, SV *sep, SV *pair, SV *freezer, SV *toaster, I32 purity,
I32 deepcopy, I32 quotekeys, SV *bless, I32 maxdepth, SV *sortkeys)
{
char tmpbuf[128];
U32 i;
char *c, *r, *realpack, id[128];
SV **svp;
SV *sv, *ipad, *ival;
SV *blesspad = Nullsv;
AV *seenentry = Nullav;
char *iname;
STRLEN inamelen, idlen = 0;
U32 realtype;
if (!val)
return 0;
realtype = SvTYPE(val);
if (SvGMAGICAL(val))
mg_get(val);
if (SvROK(val)) {
/* If a freeze method is provided and the object has it, call
it. Warn on errors. */
if (SvOBJECT(SvRV(val)) && freezer &&
SvPOK(freezer) && SvCUR(freezer) &&
gv_fetchmeth(SvSTASH(SvRV(val)), SvPVX(freezer),
SvCUR(freezer), -1) != NULL)
{
dSP; ENTER; SAVETMPS; PUSHMARK(sp);
XPUSHs(val); PUTBACK;
i = call_method(SvPVX(freezer), G_EVAL|G_VOID);
SPAGAIN;
if (SvTRUE(ERRSV))
warn("WARNING(Freezer method call failed): %"SVf"", ERRSV);
PUTBACK; FREETMPS; LEAVE;
}
ival = SvRV(val);
realtype = SvTYPE(ival);
(void) sprintf(id, "0x%"UVxf, PTR2UV(ival));
idlen = strlen(id);
if (SvOBJECT(ival))
realpack = HvNAME(SvSTASH(ival));
else
realpack = Nullch;
/* if it has a name, we need to either look it up, or keep a tab
* on it so we know when we hit it later
*/
if (namelen) {
if ((svp = hv_fetch(seenhv, id, idlen, FALSE))
&& (sv = *svp) && SvROK(sv) && (seenentry = (AV*)SvRV(sv)))
{
SV *othername;
if ((svp = av_fetch(seenentry, 0, FALSE))
&& (othername = *svp))
{
if (purity && *levelp > 0) {
SV *postentry;
if (realtype == SVt_PVHV)
sv_catpvn(retval, "{}", 2);
else if (realtype == SVt_PVAV)
sv_catpvn(retval, "[]", 2);
else
sv_catpvn(retval, "do{my $o}", 9);
postentry = newSVpvn(name, namelen);
sv_catpvn(postentry, " = ", 3);
sv_catsv(postentry, othername);
av_push(postav, postentry);
}
else {
if (name[0] == '@' || name[0] == '%') {
if ((SvPVX(othername))[0] == '\\' &&
(SvPVX(othername))[1] == name[0]) {
sv_catpvn(retval, SvPVX(othername)+1,
SvCUR(othername)-1);
}
else {
sv_catpvn(retval, name, 1);
sv_catpvn(retval, "{", 1);
sv_catsv(retval, othername);
sv_catpvn(retval, "}", 1);
}
}
else
sv_catsv(retval, othername);
}
return 1;
}
else {
warn("ref name not found for %s", id);
return 0;
}
}
else { /* store our name and continue */
SV *namesv;
if (name[0] == '@' || name[0] == '%') {
namesv = newSVpvn("\\", 1);
sv_catpvn(namesv, name, namelen);
}
else if (realtype == SVt_PVCV && name[0] == '*') {
namesv = newSVpvn("\\", 2);
sv_catpvn(namesv, name, namelen);
(SvPVX(namesv))[1] = '&';
}
else
namesv = newSVpvn(name, namelen);
seenentry = newAV();
av_push(seenentry, namesv);
(void)SvREFCNT_inc(val);
av_push(seenentry, val);
(void)hv_store(seenhv, id, strlen(id),
newRV_inc((SV*)seenentry), 0);
SvREFCNT_dec(seenentry);
}
}
if (realpack && *realpack == 'R' && strEQ(realpack, "Regexp")) {
STRLEN rlen;
char *rval = SvPV(val, rlen);
char *slash = strchr(rval, '/');
sv_catpvn(retval, "qr/", 3);
while (slash) {
sv_catpvn(retval, rval, slash-rval);
sv_catpvn(retval, "\\/", 2);
rlen -= slash-rval+1;
rval = slash+1;
slash = strchr(rval, '/');
}
sv_catpvn(retval, rval, rlen);
sv_catpvn(retval, "/", 1);
return 1;
}
/* If purity is not set and maxdepth is set, then check depth:
* if we have reached maximum depth, return the string
* representation of the thing we are currently examining
* at this depth (i.e., 'Foo=ARRAY(0xdeadbeef)').
*/
if (!purity && maxdepth > 0 && *levelp >= maxdepth) {
STRLEN vallen;
char *valstr = SvPV(val,vallen);
sv_catpvn(retval, "'", 1);
sv_catpvn(retval, valstr, vallen);
sv_catpvn(retval, "'", 1);
return 1;
}
if (realpack) { /* we have a blessed ref */
STRLEN blesslen;
char *blessstr = SvPV(bless, blesslen);
sv_catpvn(retval, blessstr, blesslen);
sv_catpvn(retval, "( ", 2);
if (indent >= 2) {
blesspad = apad;
apad = newSVsv(apad);
sv_x(aTHX_ apad, " ", 1, blesslen+2);
}
}
(*levelp)++;
ipad = sv_x(aTHX_ Nullsv, SvPVX(xpad), SvCUR(xpad), *levelp);
if (realtype <= SVt_PVBM) { /* scalar ref */
SV *namesv = newSVpvn("${", 2);
sv_catpvn(namesv, name, namelen);
sv_catpvn(namesv, "}", 1);
if (realpack) { /* blessed */
sv_catpvn(retval, "do{\\(my $o = ", 13);
DD_dump(aTHX_ ival, SvPVX(namesv), SvCUR(namesv), retval, seenhv,
postav, levelp, indent, pad, xpad, apad, sep, pair,
freezer, toaster, purity, deepcopy, quotekeys, bless,
maxdepth, sortkeys);
sv_catpvn(retval, ")}", 2);
} /* plain */
else {
sv_catpvn(retval, "\\", 1);
DD_dump(aTHX_ ival, SvPVX(namesv), SvCUR(namesv), retval, seenhv,
postav, levelp, indent, pad, xpad, apad, sep, pair,
freezer, toaster, purity, deepcopy, quotekeys, bless,
maxdepth, sortkeys);
}
SvREFCNT_dec(namesv);
}
else if (realtype == SVt_PVGV) { /* glob ref */
SV *namesv = newSVpvn("*{", 2);
sv_catpvn(namesv, name, namelen);
sv_catpvn(namesv, "}", 1);
sv_catpvn(retval, "\\", 1);
DD_dump(aTHX_ ival, SvPVX(namesv), SvCUR(namesv), retval, seenhv,
postav, levelp, indent, pad, xpad, apad, sep, pair,
freezer, toaster, purity, deepcopy, quotekeys, bless,
maxdepth, sortkeys);
SvREFCNT_dec(namesv);
}
else if (realtype == SVt_PVAV) {
SV *totpad;
I32 ix = 0;
I32 ixmax = av_len((AV *)ival);
SV *ixsv = newSViv(0);
/* allowing for a 24 char wide array index */
New(0, iname, namelen+28, char);
(void)strcpy(iname, name);
inamelen = namelen;
if (name[0] == '@') {
sv_catpvn(retval, "(", 1);
iname[0] = '$';
}
else {
sv_catpvn(retval, "[", 1);
/* omit "->" in $foo{bar}->[0], but not in ${$foo}->[0] */
/*if (namelen > 0
&& name[namelen-1] != ']' && name[namelen-1] != '}'
&& (namelen < 4 || (name[1] != '{' && name[2] != '{')))*/
if ((namelen > 0
&& name[namelen-1] != ']' && name[namelen-1] != '}')
|| (namelen > 4
&& (name[1] == '{'
|| (name[0] == '\\' && name[2] == '{'))))
{
iname[inamelen++] = '-'; iname[inamelen++] = '>';
iname[inamelen] = '\0';
}
}
if (iname[0] == '*' && iname[inamelen-1] == '}' && inamelen >= 8 &&
(instr(iname+inamelen-8, "{SCALAR}") ||
instr(iname+inamelen-7, "{ARRAY}") ||
instr(iname+inamelen-6, "{HASH}"))) {
iname[inamelen++] = '-'; iname[inamelen++] = '>';
}
iname[inamelen++] = '['; iname[inamelen] = '\0';
totpad = newSVsv(sep);
sv_catsv(totpad, pad);
sv_catsv(totpad, apad);
for (ix = 0; ix <= ixmax; ++ix) {
STRLEN ilen;
SV *elem;
svp = av_fetch((AV*)ival, ix, FALSE);
if (svp)
elem = *svp;
else
elem = &PL_sv_undef;
ilen = inamelen;
sv_setiv(ixsv, ix);
(void) sprintf(iname+ilen, "%"IVdf, (IV)ix);
ilen = strlen(iname);
iname[ilen++] = ']'; iname[ilen] = '\0';
if (indent >= 3) {
sv_catsv(retval, totpad);
sv_catsv(retval, ipad);
sv_catpvn(retval, "#", 1);
sv_catsv(retval, ixsv);
}
sv_catsv(retval, totpad);
sv_catsv(retval, ipad);
DD_dump(aTHX_ elem, iname, ilen, retval, seenhv, postav,
levelp, indent, pad, xpad, apad, sep, pair,
freezer, toaster, purity, deepcopy, quotekeys, bless,
maxdepth, sortkeys);
if (ix < ixmax)
sv_catpvn(retval, ",", 1);
}
if (ixmax >= 0) {
SV *opad = sv_x(aTHX_ Nullsv, SvPVX(xpad), SvCUR(xpad), (*levelp)-1);
sv_catsv(retval, totpad);
sv_catsv(retval, opad);
SvREFCNT_dec(opad);
}
if (name[0] == '@')
sv_catpvn(retval, ")", 1);
else
sv_catpvn(retval, "]", 1);
SvREFCNT_dec(ixsv);
SvREFCNT_dec(totpad);
Safefree(iname);
}
else if (realtype == SVt_PVHV) {
SV *totpad, *newapad;
SV *iname, *sname;
HE *entry;
char *key;
I32 klen;
SV *hval;
AV *keys = Nullav;
iname = newSVpvn(name, namelen);
if (name[0] == '%') {
sv_catpvn(retval, "(", 1);
(SvPVX(iname))[0] = '$';
}
else {
sv_catpvn(retval, "{", 1);
/* omit "->" in $foo[0]->{bar}, but not in ${$foo}->{bar} */
if ((namelen > 0
&& name[namelen-1] != ']' && name[namelen-1] != '}')
|| (namelen > 4
&& (name[1] == '{'
|| (name[0] == '\\' && name[2] == '{'))))
{
sv_catpvn(iname, "->", 2);
}
}
if (name[0] == '*' && name[namelen-1] == '}' && namelen >= 8 &&
(instr(name+namelen-8, "{SCALAR}") ||
instr(name+namelen-7, "{ARRAY}") ||
instr(name+namelen-6, "{HASH}"))) {
sv_catpvn(iname, "->", 2);
}
sv_catpvn(iname, "{", 1);
totpad = newSVsv(sep);
sv_catsv(totpad, pad);
sv_catsv(totpad, apad);
/* If requested, get a sorted/filtered array of hash keys */
if (sortkeys) {
if (sortkeys == &PL_sv_yes) {
#if PERL_VERSION < 8
sortkeys = sv_2mortal(newSVpvn("Data::Dumper::_sortkeys", 23));
#else
keys = newAV();
(void)hv_iterinit((HV*)ival);
while ((entry = hv_iternext((HV*)ival))) {
sv = hv_iterkeysv(entry);
SvREFCNT_inc(sv);
av_push(keys, sv);
}
# ifdef USE_LOCALE_NUMERIC
sortsv(AvARRAY(keys),
av_len(keys)+1,
IN_LOCALE ? Perl_sv_cmp_locale : Perl_sv_cmp);
# else
sortsv(AvARRAY(keys),
av_len(keys)+1,
Perl_sv_cmp);
# endif
#endif
}
if (sortkeys != &PL_sv_yes) {
dSP; ENTER; SAVETMPS; PUSHMARK(sp);
XPUSHs(sv_2mortal(newRV_inc(ival))); PUTBACK;
i = call_sv(sortkeys, G_SCALAR | G_EVAL);
SPAGAIN;
if (i) {
sv = POPs;
if (SvROK(sv) && (SvTYPE(SvRV(sv)) == SVt_PVAV))
keys = (AV*)SvREFCNT_inc(SvRV(sv));
}
if (! keys)
warn("Sortkeys subroutine did not return ARRAYREF\n");
PUTBACK; FREETMPS; LEAVE;
}
if (keys)
sv_2mortal((SV*)keys);
}
else
(void)hv_iterinit((HV*)ival);
/* foreach (keys %hash) */
for (i = 0; 1; i++) {
char *nkey;
char *nkey_buffer = NULL;
I32 nticks = 0;
SV* keysv;
STRLEN keylen;
I32 nlen;
bool do_utf8 = FALSE;
if ((sortkeys && !(keys && (I32)i <= av_len(keys))) ||
!(entry = hv_iternext((HV *)ival)))
break;
if (i)
sv_catpvn(retval, ",", 1);
if (sortkeys) {
char *key;
svp = av_fetch(keys, i, FALSE);
keysv = svp ? *svp : sv_mortalcopy(&PL_sv_undef);
key = SvPV(keysv, keylen);
svp = hv_fetch((HV*)ival, key,
SvUTF8(keysv) ? -(I32)keylen : keylen, 0);
hval = svp ? *svp : sv_mortalcopy(&PL_sv_undef);
}
else {
keysv = hv_iterkeysv(entry);
hval = hv_iterval((HV*)ival, entry);
}
do_utf8 = DO_UTF8(keysv);
key = SvPV(keysv, keylen);
klen = keylen;
sv_catsv(retval, totpad);
sv_catsv(retval, ipad);
/* old logic was first to check utf8 flag, and if utf8 always
call esc_q_utf8. This caused test to break under -Mutf8,
because there even strings like 'c' have utf8 flag on.
Hence with quotekeys == 0 the XS code would still '' quote
them based on flags, whereas the perl code would not,
based on regexps.
The perl code is correct.
needs_quote() decides that anything that isn't a valid
perl identifier needs to be quoted, hence only correctly
formed strings with no characters outside [A-Za-z0-9_:]
won't need quoting. None of those characters are used in
the byte encoding of utf8, so anything with utf8
encoded characters in will need quoting. Hence strings
with utf8 encoded characters in will end up inside do_utf8
just like before, but now strings with utf8 flag set but
only ascii characters will end up in the unquoted section.
There should also be less tests for the (probably currently)
more common doesn't need quoting case.
The code is also smaller (22044 vs 22260) because I've been
able to pull the common logic out to both sides. */
if (quotekeys || needs_quote(key)) {
if (do_utf8) {
STRLEN ocur = SvCUR(retval);
nlen = esc_q_utf8(aTHX_ retval, key, klen);
nkey = SvPVX(retval) + ocur;
}
else {
nticks = num_q(key, klen);
New(0, nkey_buffer, klen+nticks+3, char);
nkey = nkey_buffer;
nkey[0] = '\'';
if (nticks)
klen += esc_q(nkey+1, key, klen);
else
(void)Copy(key, nkey+1, klen, char);
nkey[++klen] = '\'';
nkey[++klen] = '\0';
nlen = klen;
sv_catpvn(retval, nkey, klen);
}
}
else {
nkey = key;
nlen = klen;
sv_catpvn(retval, nkey, klen);
}
sname = newSVsv(iname);
sv_catpvn(sname, nkey, nlen);
sv_catpvn(sname, "}", 1);
sv_catsv(retval, pair);
if (indent >= 2) {
char *extra;
I32 elen = 0;
newapad = newSVsv(apad);
New(0, extra, klen+4+1, char);
while (elen < (klen+4))
extra[elen++] = ' ';
extra[elen] = '\0';
sv_catpvn(newapad, extra, elen);
Safefree(extra);
}
else
newapad = apad;
DD_dump(aTHX_ hval, SvPVX(sname), SvCUR(sname), retval, seenhv,
postav, levelp, indent, pad, xpad, newapad, sep, pair,
freezer, toaster, purity, deepcopy, quotekeys, bless,
maxdepth, sortkeys);
SvREFCNT_dec(sname);
Safefree(nkey_buffer);
if (indent >= 2)
SvREFCNT_dec(newapad);
}
if (i) {
SV *opad = sv_x(aTHX_ Nullsv, SvPVX(xpad), SvCUR(xpad), *levelp-1);
sv_catsv(retval, totpad);
sv_catsv(retval, opad);
SvREFCNT_dec(opad);
}
if (name[0] == '%')
sv_catpvn(retval, ")", 1);
else
sv_catpvn(retval, "}", 1);
SvREFCNT_dec(iname);
SvREFCNT_dec(totpad);
}
else if (realtype == SVt_PVCV) {
sv_catpvn(retval, "sub { \"DUMMY\" }", 15);
if (purity)
warn("Encountered CODE ref, using dummy placeholder");
}
else {
warn("cannot handle ref type %ld", realtype);
}
if (realpack) { /* free blessed allocs */
if (indent >= 2) {
SvREFCNT_dec(apad);
apad = blesspad;
}
sv_catpvn(retval, ", '", 3);
sv_catpvn(retval, realpack, strlen(realpack));
sv_catpvn(retval, "' )", 3);
if (toaster && SvPOK(toaster) && SvCUR(toaster)) {
sv_catpvn(retval, "->", 2);
sv_catsv(retval, toaster);
sv_catpvn(retval, "()", 2);
}
}
SvREFCNT_dec(ipad);
(*levelp)--;
}
else {
STRLEN i;
if (namelen) {
(void) sprintf(id, "0x%"UVxf, PTR2UV(val));
if ((svp = hv_fetch(seenhv, id, (idlen = strlen(id)), FALSE)) &&
(sv = *svp) && SvROK(sv) &&
(seenentry = (AV*)SvRV(sv)))
{
SV *othername;
if ((svp = av_fetch(seenentry, 0, FALSE)) && (othername = *svp)
&& (svp = av_fetch(seenentry, 2, FALSE)) && *svp && SvIV(*svp) > 0)
{
sv_catpvn(retval, "${", 2);
sv_catsv(retval, othername);
sv_catpvn(retval, "}", 1);
return 1;
}
}
else if (val != &PL_sv_undef) {
SV *namesv;
namesv = newSVpvn("\\", 1);
sv_catpvn(namesv, name, namelen);
seenentry = newAV();
av_push(seenentry, namesv);
av_push(seenentry, newRV_inc(val));
(void)hv_store(seenhv, id, strlen(id), newRV_inc((SV*)seenentry), 0);
SvREFCNT_dec(seenentry);
}
}
if (DD_is_integer(val)) {
STRLEN len;
if (SvIsUV(val))
(void) sprintf(tmpbuf, "%"UVuf, SvUV(val));
else
(void) sprintf(tmpbuf, "%"IVdf, SvIV(val));
len = strlen(tmpbuf);
if (SvPOK(val)) {
/* Need to check to see if this is a string such as " 0".
I'm assuming from sprintf isn't going to clash with utf8.
Is this valid on EBCDIC? */
STRLEN pvlen;
const char *pv = SvPV(val, pvlen);
if (pvlen != len || memNE(pv, tmpbuf, len))
goto integer_came_from_string;
}
if (len > 10) {
/* Looks like we're on a 64 bit system. Make it a string so that
if a 32 bit system reads the number it will cope better. */
sv_catpvf(retval, "'%s'", tmpbuf);
} else
sv_catpvn(retval, tmpbuf, len);
}
else if (realtype == SVt_PVGV) {/* GLOBs can end up with scribbly names */
c = SvPV(val, i);
++c; --i; /* just get the name */
if (i >= 6 && strncmp(c, "main::", 6) == 0) {
c += 4;
i -= 4;
}
if (needs_quote(c)) {
sv_grow(retval, SvCUR(retval)+6+2*i);
r = SvPVX(retval)+SvCUR(retval);
r[0] = '*'; r[1] = '{'; r[2] = '\'';
i += esc_q(r+3, c, i);
i += 3;
r[i++] = '\''; r[i++] = '}';
r[i] = '\0';
}
else {
sv_grow(retval, SvCUR(retval)+i+2);
r = SvPVX(retval)+SvCUR(retval);
r[0] = '*'; strcpy(r+1, c);
i++;
}
SvCUR_set(retval, SvCUR(retval)+i);
if (purity) {
static char *entries[] = { "{SCALAR}", "{ARRAY}", "{HASH}" };
static STRLEN sizes[] = { 8, 7, 6 };
SV *e;
SV *nname = newSVpvn("", 0);
SV *newapad = newSVpvn("", 0);
GV *gv = (GV*)val;
I32 j;
for (j=0; j<3; j++) {
e = ((j == 0) ? GvSV(gv) : (j == 1) ? (SV*)GvAV(gv) : (SV*)GvHV(gv));
if (!e)
continue;
if (j == 0 && !SvOK(e))
continue;
{
I32 nlevel = 0;
SV *postentry = newSVpvn(r,i);
sv_setsv(nname, postentry);
sv_catpvn(nname, entries[j], sizes[j]);
sv_catpvn(postentry, " = ", 3);
av_push(postav, postentry);
e = newRV_inc(e);
SvCUR(newapad) = 0;
if (indent >= 2)
(void)sv_x(aTHX_ newapad, " ", 1, SvCUR(postentry));
DD_dump(aTHX_ e, SvPVX(nname), SvCUR(nname), postentry,
seenhv, postav, &nlevel, indent, pad, xpad,
newapad, sep, pair, freezer, toaster, purity,
deepcopy, quotekeys, bless, maxdepth,
sortkeys);
SvREFCNT_dec(e);
}
}
SvREFCNT_dec(newapad);
SvREFCNT_dec(nname);
}
}
else if (val == &PL_sv_undef || !SvOK(val)) {
sv_catpvn(retval, "undef", 5);
}
else {
integer_came_from_string:
c = SvPV(val, i);
if (DO_UTF8(val))
i += esc_q_utf8(aTHX_ retval, c, i);
else {
sv_grow(retval, SvCUR(retval)+3+2*i); /* 3: ""\0 */
r = SvPVX(retval) + SvCUR(retval);
r[0] = '\'';
i += esc_q(r+1, c, i);
++i;
r[i++] = '\'';
r[i] = '\0';
SvCUR_set(retval, SvCUR(retval)+i);
}
}
}
if (idlen) {
if (deepcopy)
(void)hv_delete(seenhv, id, idlen, G_DISCARD);
else if (namelen && seenentry) {
SV *mark = *av_fetch(seenentry, 2, TRUE);
sv_setiv(mark,1);
}
}
return 1;
}
/* #line 918 "Dumper.c" */
XS(XS_Data__Dumper_Dumpxs); /* prototype to pass -Wmissing-prototypes */
XS(XS_Data__Dumper_Dumpxs)
{
dXSARGS;
if (items < 1)
Perl_croak(aTHX_ "Usage: Data::Dumper::Dumpxs(href, ...)");
SP -= items;
{
SV * href = ST(0);
/* #line 921 "Dumper.xs" */
{
HV *hv;
SV *retval, *valstr;
HV *seenhv = Nullhv;
AV *postav, *todumpav, *namesav;
I32 level = 0;
I32 indent, terse, i, imax, postlen;
SV **svp;
SV *val, *name, *pad, *xpad, *apad, *sep, *pair, *varname;
SV *freezer, *toaster, *bless, *sortkeys;
I32 purity, deepcopy, quotekeys, maxdepth = 0;
char tmpbuf[1024];
I32 gimme = GIMME;
if (!SvROK(href)) { /* call new to get an object first */
if (items < 2)
croak("Usage: Data::Dumper::Dumpxs(PACKAGE, VAL_ARY_REF, [NAME_ARY_REF])");
ENTER;
SAVETMPS;
PUSHMARK(sp);
XPUSHs(href);
XPUSHs(sv_2mortal(newSVsv(ST(1))));
if (items >= 3)
XPUSHs(sv_2mortal(newSVsv(ST(2))));
PUTBACK;
i = call_method("new", G_SCALAR);
SPAGAIN;
if (i)
href = newSVsv(POPs);
PUTBACK;
FREETMPS;
LEAVE;
if (i)
(void)sv_2mortal(href);
}
todumpav = namesav = Nullav;
seenhv = Nullhv;
val = pad = xpad = apad = sep = pair = varname
= freezer = toaster = bless = &PL_sv_undef;
name = sv_newmortal();
indent = 2;
terse = purity = deepcopy = 0;
quotekeys = 1;
retval = newSVpvn("", 0);
if (SvROK(href)
&& (hv = (HV*)SvRV((SV*)href))
&& SvTYPE(hv) == SVt_PVHV) {
if ((svp = hv_fetch(hv, "seen", 4, FALSE)) && SvROK(*svp))
seenhv = (HV*)SvRV(*svp);
if ((svp = hv_fetch(hv, "todump", 6, FALSE)) && SvROK(*svp))
todumpav = (AV*)SvRV(*svp);
if ((svp = hv_fetch(hv, "names", 5, FALSE)) && SvROK(*svp))
namesav = (AV*)SvRV(*svp);
if ((svp = hv_fetch(hv, "indent", 6, FALSE)))
indent = SvIV(*svp);
if ((svp = hv_fetch(hv, "purity", 6, FALSE)))
purity = SvIV(*svp);
if ((svp = hv_fetch(hv, "terse", 5, FALSE)))
terse = SvTRUE(*svp);
#if 0 /* useqq currently unused */
if ((svp = hv_fetch(hv, "useqq", 5, FALSE)))
useqq = SvTRUE(*svp);
#endif
if ((svp = hv_fetch(hv, "pad", 3, FALSE)))
pad = *svp;
if ((svp = hv_fetch(hv, "xpad", 4, FALSE)))
xpad = *svp;
if ((svp = hv_fetch(hv, "apad", 4, FALSE)))
apad = *svp;
if ((svp = hv_fetch(hv, "sep", 3, FALSE)))
sep = *svp;
if ((svp = hv_fetch(hv, "pair", 4, FALSE)))
pair = *svp;
if ((svp = hv_fetch(hv, "varname", 7, FALSE)))
varname = *svp;
if ((svp = hv_fetch(hv, "freezer", 7, FALSE)))
freezer = *svp;
if ((svp = hv_fetch(hv, "toaster", 7, FALSE)))
toaster = *svp;
if ((svp = hv_fetch(hv, "deepcopy", 8, FALSE)))
deepcopy = SvTRUE(*svp);
if ((svp = hv_fetch(hv, "quotekeys", 9, FALSE)))
quotekeys = SvTRUE(*svp);
if ((svp = hv_fetch(hv, "bless", 5, FALSE)))
bless = *svp;
if ((svp = hv_fetch(hv, "maxdepth", 8, FALSE)))
maxdepth = SvIV(*svp);
if ((svp = hv_fetch(hv, "sortkeys", 8, FALSE))) {
sortkeys = *svp;
if (! SvTRUE(sortkeys))
sortkeys = NULL;
else if (! (SvROK(sortkeys) &&
SvTYPE(SvRV(sortkeys)) == SVt_PVCV) )
{
/* flag to use qsortsv() for sorting hash keys */
sortkeys = &PL_sv_yes;
}
}
postav = newAV();
if (todumpav)
imax = av_len(todumpav);
else
imax = -1;
valstr = newSVpvn("",0);
for (i = 0; i <= imax; ++i) {
SV *newapad;
av_clear(postav);
if ((svp = av_fetch(todumpav, i, FALSE)))
val = *svp;
else
val = &PL_sv_undef;
if ((svp = av_fetch(namesav, i, TRUE)))
sv_setsv(name, *svp);
else
(void)SvOK_off(name);
if (SvOK(name)) {
if ((SvPVX(name))[0] == '*') {
if (SvROK(val)) {
switch (SvTYPE(SvRV(val))) {
case SVt_PVAV:
(SvPVX(name))[0] = '@';
break;
case SVt_PVHV:
(SvPVX(name))[0] = '%';
break;
case SVt_PVCV:
(SvPVX(name))[0] = '*';
break;
default:
(SvPVX(name))[0] = '$';
break;
}
}
else
(SvPVX(name))[0] = '$';
}
else if ((SvPVX(name))[0] != '$')
sv_insert(name, 0, 0, "$", 1);
}
else {
STRLEN nchars = 0;
sv_setpvn(name, "$", 1);
sv_catsv(name, varname);
(void) sprintf(tmpbuf, "%"IVdf, (IV)(i+1));
nchars = strlen(tmpbuf);
sv_catpvn(name, tmpbuf, nchars);
}
if (indent >= 2) {
SV *tmpsv = sv_x(aTHX_ Nullsv, " ", 1, SvCUR(name)+3);
newapad = newSVsv(apad);
sv_catsv(newapad, tmpsv);
SvREFCNT_dec(tmpsv);
}
else
newapad = apad;
DD_dump(aTHX_ val, SvPVX(name), SvCUR(name), valstr, seenhv,
postav, &level, indent, pad, xpad, newapad, sep, pair,
freezer, toaster, purity, deepcopy, quotekeys,
bless, maxdepth, sortkeys);
if (indent >= 2)
SvREFCNT_dec(newapad);
postlen = av_len(postav);
if (postlen >= 0 || !terse) {
sv_insert(valstr, 0, 0, " = ", 3);
sv_insert(valstr, 0, 0, SvPVX(name), SvCUR(name));
sv_catpvn(valstr, ";", 1);
}
sv_catsv(retval, pad);
sv_catsv(retval, valstr);
sv_catsv(retval, sep);
if (postlen >= 0) {
I32 i;
sv_catsv(retval, pad);
for (i = 0; i <= postlen; ++i) {
SV *elem;
svp = av_fetch(postav, i, FALSE);
if (svp && (elem = *svp)) {
sv_catsv(retval, elem);
if (i < postlen) {
sv_catpvn(retval, ";", 1);
sv_catsv(retval, sep);
sv_catsv(retval, pad);
}
}
}
sv_catpvn(retval, ";", 1);
sv_catsv(retval, sep);
}
sv_setpvn(valstr, "", 0);
if (gimme == G_ARRAY) {
XPUSHs(sv_2mortal(retval));
if (i < imax) /* not the last time thro ? */
retval = newSVpvn("",0);
}
}
SvREFCNT_dec(postav);
SvREFCNT_dec(valstr);
}
else
croak("Call to new() method failed to return HASH ref");
if (gimme == G_SCALAR)
XPUSHs(sv_2mortal(retval));
}
/* #line 1145 "Dumper.c" */
PUTBACK;
return;
}
}
#ifdef __cplusplus
extern "C"
#endif
XS(boot_Data__Dumper); /* prototype to pass -Wmissing-prototypes */
XS(boot_Data__Dumper)
{
dXSARGS;
char* file = __FILE__;
XS_VERSION_BOOTCHECK ;
newXSproto("Data::Dumper::Dumpxs", XS_Data__Dumper_Dumpxs, file, "$;$$");
XSRETURN_YES;
}
| 27.761373 | 100 | 0.533919 |
b8122aad228925c9f7f86c4edc63f1f81f7e30a3 | 1,492 | h | C | KinectRecorder/src/ofApp.h | baku89/depthcope-tools | b5dc8cb57ea8f7463d4cf3abed9143ae385256a5 | [
"MIT"
] | 7 | 2016-08-24T04:04:50.000Z | 2018-05-30T13:58:43.000Z | KinectRecorder/src/ofApp.h | baku89/Kinect2Test | b5dc8cb57ea8f7463d4cf3abed9143ae385256a5 | [
"MIT"
] | null | null | null | KinectRecorder/src/ofApp.h | baku89/Kinect2Test | b5dc8cb57ea8f7463d4cf3abed9143ae385256a5 | [
"MIT"
] | null | null | null | #pragma once
#include "ofMain.h"
#include "ofxMultiKinectV2.h"
#include "ofxDatGui.h"
#include "ofxImageSequenceRecorder.h"
#include "ofxXmlSettings.h"
#include "PostProcessing.h"
#include "DepthFiller.h"
#include "Config.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void exit();
void initScene();
void drawScene();
void drawUi();
void loadGui();
void saveGui();
void doPostProcessing();
string getTakeName();
void keyPressed(int key);
// mesh
ofEasyCam camera;
ofCamera orthoCamera;
ofShader pointShader;
ofMesh mesh;
ofShader depthShader, filledShader;
// kinect
ofxMultiKinectV2 kinect;
DepthFiller depthFiller;
ofFloatPixels depthPixels, testPixels, testFilledPixels;
ofFloatImage depthImage, testImage, testFilledImage;
ofxImageSequenceRecorder recorder;
PostProcessing postProcessing;
ofPolyline guide;
stringstream ss;
bool isRecording = false;
bool willStopRecording = false;
bool isPreviewHeight = false;
bool isPreviewThumb = true;
bool isFlipHorizontal = true;
string takeName;
// parameters
ofxDatGui* gui;
float near, far; // cm
int cropWidth, cropHeight;
ofVec2f focus;
};
| 19.893333 | 66 | 0.595174 |
ccd452cc1a32bc68c35447037f5764686b4ce401 | 1,005 | c | C | Pods/cmark-gfm-swift/Source/cmark_gfm/footnotes.c | jmpotter19/GitHawk | 18fef6cf3962eeb4ef3ec751e5bd1fb30fc62121 | [
"MIT"
] | 2,210 | 2018-03-12T13:08:48.000Z | 2022-03-31T03:14:56.000Z | Pods/cmark-gfm-swift/Source/cmark_gfm/footnotes.c | darran8061/GitHawk | 7d85c5e76221d1ca1947db2133b3e883a307f686 | [
"MIT"
] | 1,148 | 2018-03-12T12:32:45.000Z | 2022-03-31T03:06:56.000Z | Pods/cmark-gfm-swift/Source/cmark_gfm/footnotes.c | darran8061/GitHawk | 7d85c5e76221d1ca1947db2133b3e883a307f686 | [
"MIT"
] | 414 | 2018-03-14T01:18:54.000Z | 2022-03-30T04:43:25.000Z | #include "cmark.h"
#include "parser.h"
#include "footnotes.h"
#include "inlines.h"
#include "chunk.h"
static void footnote_free(cmark_map *map, cmark_map_entry *_ref) {
cmark_footnote *ref = (cmark_footnote *)_ref;
cmark_mem *mem = map->mem;
if (ref != NULL) {
mem->free(ref->entry.label);
if (ref->node)
cmark_node_free(ref->node);
mem->free(ref);
}
}
void cmark_footnote_create(cmark_map *map, cmark_node *node) {
cmark_footnote *ref;
unsigned char *reflabel = normalize_map_label(map->mem, &node->as.literal);
/* empty footnote name, or composed from only whitespace */
if (reflabel == NULL)
return;
assert(map->sorted == NULL);
ref = (cmark_footnote *)map->mem->calloc(1, sizeof(*ref));
ref->entry.label = reflabel;
ref->node = node;
ref->entry.age = map->size;
ref->entry.next = map->refs;
map->refs = (cmark_map_entry *)ref;
map->size++;
}
cmark_map *cmark_footnote_map_new(cmark_mem *mem) {
return cmark_map_new(mem, footnote_free);
}
| 24.512195 | 77 | 0.673632 |
0a70a1e58bd0075a35d046aa5be3ab29830153b7 | 2,011 | h | C | ManualBuilds/UpToDateMinGw/lib/gcc/x86_64-w64-mingw32/11.2.0/plugin/include/gimple-ssa-evrp-analyze.h | WeLikeIke/DubitaC | 4c0b797b43112fd967c604d6dd7f55e4a38bf9d9 | [
"MIT"
] | 5 | 2021-10-16T13:52:16.000Z | 2021-12-20T10:16:21.000Z | ManualBuilds/UpToDateMinGw/lib/gcc/x86_64-w64-mingw32/11.2.0/plugin/include/gimple-ssa-evrp-analyze.h | WeLikeIke/DubitaC | 4c0b797b43112fd967c604d6dd7f55e4a38bf9d9 | [
"MIT"
] | null | null | null | ManualBuilds/UpToDateMinGw/lib/gcc/x86_64-w64-mingw32/11.2.0/plugin/include/gimple-ssa-evrp-analyze.h | WeLikeIke/DubitaC | 4c0b797b43112fd967c604d6dd7f55e4a38bf9d9 | [
"MIT"
] | 3 | 2021-10-16T11:24:04.000Z | 2021-11-13T13:04:39.000Z | /* Support routines for Value Range Propagation (VRP).
Copyright (C) 2016-2021 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef GCC_GIMPLE_SSA_EVRP_ANALYZE_H
#define GCC_GIMPLE_SSA_EVRP_ANALYZE_H
class evrp_range_analyzer : public vr_values
{
public:
evrp_range_analyzer (bool update_global_ranges);
~evrp_range_analyzer (void)
{
stack.release ();
}
void enter (basic_block);
void push_marker (void);
void pop_to_marker (void);
void leave (basic_block);
void record_ranges_from_stmt (gimple *, bool);
/* Record a new unwindable range. */
void push_value_range (tree var, value_range_equiv *vr);
/* A bit of a wart. This should ideally go away. */
void vrp_visit_cond_stmt (gcond *cond, edge *e)
{
simplify_using_ranges simpl (this);
simpl.vrp_visit_cond_stmt (cond, e);
}
private:
DISABLE_COPY_AND_ASSIGN (evrp_range_analyzer);
void pop_value_range ();
value_range_equiv *try_find_new_range (tree, tree op, tree_code code,
tree limit);
void record_ranges_from_incoming_edge (basic_block);
void record_ranges_from_phis (basic_block);
void set_ssa_range_info (tree, value_range_equiv *);
/* STACK holds the old VR. */
auto_vec<std::pair <tree, value_range_equiv *> > stack;
/* True if we are updating global ranges, false otherwise. */
bool m_update_global_ranges;
};
#endif /* GCC_GIMPLE_SSA_EVRP_ANALYZE_H */
| 30.469697 | 71 | 0.75087 |
fd3bc625247415323a340b3d71e52d48b9c675c7 | 3,136 | c | C | games/trek/help.c | weiss/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 114 | 2015-01-18T22:55:52.000Z | 2022-02-17T10:45:02.000Z | games/trek/help.c | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | null | null | null | games/trek/help.c | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 29 | 2015-11-03T22:05:22.000Z | 2022-02-08T15:36:37.000Z | /*
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* %sccs.include.redist.c%
*/
#ifndef lint
static char sccsid[] = "@(#)help.c 8.1 (Berkeley) 05/31/93";
#endif /* not lint */
# include "trek.h"
/*
** call starbase for help
**
** First, the closest starbase is selected. If there is a
** a starbase in your own quadrant, you are in good shape.
** This distance takes quadrant distances into account only.
**
** A magic number is computed based on the distance which acts
** as the probability that you will be rematerialized. You
** get three tries.
**
** When it is determined that you should be able to be remater-
** ialized (i.e., when the probability thing mentioned above
** comes up positive), you are put into that quadrant (anywhere).
** Then, we try to see if there is a spot adjacent to the star-
** base. If not, you can't be rematerialized!!! Otherwise,
** it drops you there. It only tries five times to find a spot
** to drop you. After that, it's your problem.
*/
char *Cntvect[3] =
{"first", "second", "third"};
help()
{
register int i;
double dist, x;
register int dx, dy;
int j, l;
/* check to see if calling for help is reasonable ... */
if (Ship.cond == DOCKED)
return (printf("Uhura: But Captain, we're already docked\n"));
/* or possible */
if (damaged(SSRADIO))
return (out(SSRADIO));
if (Now.bases <= 0)
return (printf("Uhura: I'm not getting any response from starbase\n"));
/* tut tut, there goes the score */
Game.helps += 1;
/* find the closest base */
dist = 1e50;
if (Quad[Ship.quadx][Ship.quady].bases <= 0)
{
/* there isn't one in this quadrant */
for (i = 0; i < Now.bases; i++)
{
/* compute distance */
dx = Now.base[i].x - Ship.quadx;
dy = Now.base[i].y - Ship.quady;
x = dx * dx + dy * dy;
x = sqrt(x);
/* see if better than what we already have */
if (x < dist)
{
dist = x;
l = i;
}
}
/* go to that quadrant */
Ship.quadx = Now.base[l].x;
Ship.quady = Now.base[l].y;
initquad(1);
}
else
{
dist = 0.0;
}
/* dematerialize the Enterprise */
Sect[Ship.sectx][Ship.secty] = EMPTY;
printf("Starbase in %d,%d responds\n", Ship.quadx, Ship.quady);
/* this next thing acts as a probability that it will work */
x = pow(1.0 - pow(0.94, dist), 0.3333333);
/* attempt to rematerialize */
for (i = 0; i < 3; i++)
{
sleep(2);
printf("%s attempt to rematerialize ", Cntvect[i]);
if (franf() > x)
{
/* ok, that's good. let's see if we can set her down */
for (j = 0; j < 5; j++)
{
dx = Etc.starbase.x + ranf(3) - 1;
if (dx < 0 || dx >= NSECTS)
continue;
dy = Etc.starbase.y + ranf(3) - 1;
if (dy < 0 || dy >= NSECTS || Sect[dx][dy] != EMPTY)
continue;
break;
}
if (j < 5)
{
/* found an empty spot */
printf("succeeds\n");
Ship.sectx = dx;
Ship.secty = dy;
Sect[dx][dy] = Ship.ship;
dock();
compkldist(0);
return;
}
/* the starbase must have been surrounded */
}
printf("fails\n");
}
/* one, two, three strikes, you're out */
lose(L_NOHELP);
}
| 23.757576 | 73 | 0.603954 |
fd7d4492e060729eefd18582ce24434f8973a9f9 | 1,490 | h | C | Filter/GL/ShaderUtilities.h | michelf/sim-daltonism | 99a61293a063b7588404b4ab5e286f3ee38b0bef | [
"Apache-2.0"
] | 196 | 2016-01-28T13:44:31.000Z | 2022-03-23T15:32:34.000Z | Filter/GL/ShaderUtilities.h | importRyan/sim-daltonism | b7e4c9e53335b02e4dc2a22c48222a7406ffad60 | [
"Apache-2.0"
] | 25 | 2016-01-29T01:13:27.000Z | 2022-03-01T22:17:04.000Z | Filter/GL/ShaderUtilities.h | importRyan/sim-daltonism | b7e4c9e53335b02e4dc2a22c48222a7406ffad60 | [
"Apache-2.0"
] | 19 | 2016-06-23T19:25:52.000Z | 2022-01-10T06:47:28.000Z |
// Copyright 2005-2017 Michel Fortin
//
// 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 RosyWriter_ShaderUtilities_h
#define RosyWriter_ShaderUtilities_h
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE
# include <OpenGLES/ES3/gl.h>
# include <OpenGLES/ES3/glext.h>
#elif TARGET_OS_MAC
# include <OpenGL/OpenGL.h>
# include <OpenGL/gl3.h>
#endif
GLint glueCompileShader(GLenum target, GLsizei count, const GLchar **sources, GLuint *shader);
GLint glueLinkProgram(GLuint program);
GLint glueValidateProgram(GLuint program);
GLint glueGetUniformLocation(GLuint program, const GLchar *name);
GLint glueCreateProgram(const GLchar *vertSource, const GLchar *fragSource,
GLsizei attribNameCt, const GLchar **attribNames,
const GLint *attribLocations,
GLsizei uniformNameCt, const GLchar **uniformNames,
GLint *uniformLocations,
GLuint *program);
#endif
| 35.47619 | 94 | 0.720805 |
134bdd1f8d98c279590d6c0e8c44da065374ca43 | 1,669 | h | C | geometry/Track.h | fermi-lat/geometry | 71a08bdb0caf952566fed8d8aeb62bd264a4bab7 | [
"BSD-3-Clause"
] | null | null | null | geometry/Track.h | fermi-lat/geometry | 71a08bdb0caf952566fed8d8aeb62bd264a4bab7 | [
"BSD-3-Clause"
] | null | null | null | geometry/Track.h | fermi-lat/geometry | 71a08bdb0caf952566fed8d8aeb62bd264a4bab7 | [
"BSD-3-Clause"
] | null | null | null | // $Heading: Track.h $
// Author: T. Burnett
//
#ifndef GEOMETRY_TRACK_H
#define GEOMETRY_TRACK_H
#include "geometry/GeomObject.h"
#include "geometry/Point.h"
class Ray;
#include <string> // gcc bug
#include <vector>
/// A Track is a list of Ray objects: it will document the complete trajectory of a particle.
class Track : public GeomObject
{
public:
/// constructor: must specify first ray and if not charged
Track( Ray* first, bool charged=true);
/// destructor: deletes all rays in the list
~Track();
GeomObject& transform(const CoordTransform&);
/// add a new ray: assumes ownership
void addSegment( Ray* next );
/// position and direction
Point position( double s ) const;
Vector direction( double s ) const;
bool charged()const{return m_charged;}
const char *nameOf() const { return "Track"; }
void printOn( std::ostream& os = std::cout ) const;
typedef std::vector<Ray*> Raylist;
typedef Raylist::const_iterator const_iterator;
typedef Raylist::iterator iterator;
const_iterator begin()const{return rayList.begin();}
const_iterator end()const{return rayList.end();}
iterator begin() {return rayList.begin();}
iterator end() {return rayList.end();}
private:
void findSegment( double s );
// used to find the right segment
static Ray* currentRay;
static double currentArcLength;
// set by findSegment
static float maxKink;
// maximum angle tolerated in line segment approximation to
// curved tracks.
bool m_charged; // true if charged
float arclength; // length along the Track
Raylist rayList; // the list of Rays
};
#endif
| 24.188406 | 93 | 0.688436 |
dd16edc082cc4cbacc30b585ad585a81e62a563a | 1,035 | h | C | plugins/cbbViewImage/cbbViewImagePlugin.h | CBBProject/CBBProject | a8e57f1a370eef647895fba8d7a04a032013aeb7 | [
"BSD-3-Clause"
] | 1 | 2016-11-05T00:04:48.000Z | 2016-11-05T00:04:48.000Z | plugins/cbbViewImage/cbbViewImagePlugin.h | CBBProject/CBBProject | a8e57f1a370eef647895fba8d7a04a032013aeb7 | [
"BSD-3-Clause"
] | null | null | null | plugins/cbbViewImage/cbbViewImagePlugin.h | CBBProject/CBBProject | a8e57f1a370eef647895fba8d7a04a032013aeb7 | [
"BSD-3-Clause"
] | null | null | null | // /////////////////////////////////////////////////////////////////
// Generated by dtkPluginGenerator
// /////////////////////////////////////////////////////////////////
#pragma once
#include <dtkCore/dtkPlugin.h>
#include "cbbExport.h"
class CBB_WINDOWS_EXPORT cbbViewImagePluginPrivate;
// /////////////////////////////////////////////////////////////////
// cbbViewImagePlugin interface
// /////////////////////////////////////////////////////////////////
class CBB_WINDOWS_EXPORT cbbViewImagePlugin : public dtkPlugin
{
Q_OBJECT
Q_INTERFACES(dtkPlugin)
public:
cbbViewImagePlugin(QObject *parent = 0);
cbbViewImagePlugin(const cbbViewImagePlugin& other);
~cbbViewImagePlugin(void);
public:
virtual bool initialize(void);
virtual bool uninitialize(void);
virtual QString name(void) const;
virtual QString description(void) const;
virtual QStringList tags(void) const;
virtual QStringList types(void) const;
private:
DTK_DECLARE_PRIVATE(cbbViewImagePlugin);
};
#endif
| 24.642857 | 68 | 0.557488 |
940601bd25a48d5936fa7b24b1313db94312d4d6 | 1,083 | h | C | PhysicsKitBridge/Source/Internal/DataStructures/PKBStructs.h | AdamEisfeld/PhysicsKitBridge | 8c0d0eea6552dd8684d160e659fcfeff27a33188 | [
"MIT"
] | null | null | null | PhysicsKitBridge/Source/Internal/DataStructures/PKBStructs.h | AdamEisfeld/PhysicsKitBridge | 8c0d0eea6552dd8684d160e659fcfeff27a33188 | [
"MIT"
] | null | null | null | PhysicsKitBridge/Source/Internal/DataStructures/PKBStructs.h | AdamEisfeld/PhysicsKitBridge | 8c0d0eea6552dd8684d160e659fcfeff27a33188 | [
"MIT"
] | null | null | null | //
// BLStructs.h
// BulletPhysics
//
// Created by Adam Eisfeld on 2020-06-12.
// Copyright © 2020 adam. All rights reserved.
//
struct BLVector3 {
float x;
float y;
float z;
};
struct BLQuaternion {
float x;
float y;
float z;
float w;
};
struct BLMatrix4 {
float m11;
float m12;
float m13;
float m14;
float m21;
float m22;
float m23;
float m24;
float m31;
float m32;
float m33;
float m34;
float m41;
float m42;
float m43;
float m44;
};
#ifdef __cplusplus
extern "C" {
#endif
extern struct BLVector3 BLVector3Make(float x, float y, float z);
extern struct BLQuaternion BLQuaternionMake(float x, float y, float z, float w);
extern struct BLQuaternion BLQuaternionMakeIdentity();
extern struct BLMatrix4 BLMatrix4Make(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44);
extern struct BLMatrix4 BLMatrix4MakeIdentity();
#ifdef __cplusplus
}
#endif
| 18.05 | 214 | 0.666667 |
f6e88a6c253f5e6723e5eeac7684a78aa896ca3e | 7,203 | c | C | alice4/software/ideas/draw_logo_line.c | lkesteloot/alice | 44b85caf744e5830536b5e813e761cc0ce3f695e | [
"Apache-2.0"
] | 63 | 2015-08-14T23:27:39.000Z | 2022-03-09T22:46:11.000Z | alice4/software/ideas/draw_logo_line.c | lkesteloot/alice | 44b85caf744e5830536b5e813e761cc0ce3f695e | [
"Apache-2.0"
] | 64 | 2015-09-11T23:13:03.000Z | 2018-10-29T09:38:06.000Z | alice4/software/ideas/draw_logo_line.c | lkesteloot/alice | 44b85caf744e5830536b5e813e761cc0ce3f695e | [
"Apache-2.0"
] | 9 | 2016-01-06T00:06:33.000Z | 2021-12-07T10:38:15.000Z | #include <gl.h>
#include "objects.h"
float scp[14][3] = {
{1.000000, 0.000000, 0.000000}, {1.000000, 0.000000, 5.000000},
{0.500000, 0.866025, 0.000000}, {0.500000, 0.866025, 5.000000},
{-0.500000, 0.866025, 0.000000}, {-0.500000, 0.866025, 5.000000},
{-1.000000, 0.000000, 0.000000}, {-1.000000, 0.000000, 5.000000},
{-0.500000, -0.866025, 0.000000}, {-0.500000, -0.866025, 5.000000},
{0.500000, -0.866025, 0.000000}, {0.500000, -0.866025, 5.000000},
{1.000000, 0.000000, 0.000000}, {1.000000, 0.000000, 5.000000},
};
float dcp[14][3] = {
{1.000000, 0.000000, 0.000000}, {1.000000, 0.000000, 7.000000},
{0.500000, 0.866025, 0.000000}, {0.500000, 0.866025, 7.000000},
{-0.500000, 0.866025, 0.000000}, {-0.500000, 0.866025, 7.000000},
{-1.000000, 0.000000, 0.000000}, {-1.000000, 0.000000, 7.000000},
{-0.500000, -0.866025, 0.000000}, {-0.500000, -0.866025, 7.000000},
{0.500000, -0.866025, 0.000000}, {0.500000, -0.866025, 7.000000},
{1.000000, 0.000000, 0.000000}, {1.000000, 0.000000, 7.000000},
};
float ep[7][7][3] = {
{
{1.000000, 0.000000, 0.000000},
{0.500000, 0.866025, 0.000000},
{-0.500000, 0.866025, 0.000000},
{-1.000000, 0.000000, 0.000000},
{-0.500000, -0.866025, 0.000000},
{0.500000, -0.866025, 0.000000},
{1.000000, 0.000000, 0.000000},
},
{
{1.000000, 0.034074, 0.258819},
{0.500000, 0.870590, 0.034675},
{-0.500000, 0.870590, 0.034675},
{-1.000000, 0.034074, 0.258819},
{-0.500000, -0.802442, 0.482963},
{0.500000, -0.802442, 0.482963},
{1.000000, 0.034074, 0.258819},
},
{
{1.000000, 0.133975, 0.500000},
{0.500000, 0.883975, 0.066987},
{-0.500000, 0.883975, 0.066987},
{-1.000000, 0.133975, 0.500000},
{-0.500000, -0.616025, 0.933013},
{0.500000, -0.616025, 0.933013},
{1.000000, 0.133975, 0.500000},
},
{
{1.000000, 0.292893, 0.707107},
{0.500000, 0.905266, 0.094734},
{-0.500000, 0.905266, 0.094734},
{-1.000000, 0.292893, 0.707107},
{-0.500000, -0.319479, 1.319479},
{0.500000, -0.319479, 1.319479},
{1.000000, 0.292893, 0.707107},
},
{
{1.000000, 0.500000, 0.866025},
{0.500000, 0.933013, 0.116025},
{-0.500000, 0.933013, 0.116025},
{-1.000000, 0.500000, 0.866025},
{-0.500000, 0.066987, 1.616025},
{0.500000, 0.066987, 1.616025},
{1.000000, 0.500000, 0.866025},
},
{
{1.000000, 0.741181, 0.965926},
{0.500000, 0.965325, 0.129410},
{-0.500000, 0.965325, 0.129410},
{-1.000000, 0.741181, 0.965926},
{-0.500000, 0.517037, 1.802442},
{0.500000, 0.517037, 1.802442},
{1.000000, 0.741181, 0.965926},
},
{
{1.000000, 1.000000, 1.000000},
{0.500000, 1.000000, 0.133975},
{-0.500000, 1.000000, 0.133975},
{-1.000000, 1.000000, 1.000000},
{-0.500000, 1.000000, 1.866025},
{0.500000, 1.000000, 1.866025},
{1.000000, 1.000000, 1.000000},
},
};
draw_single_cylinder() {
bgnline();
v3f(scp[0]);
v3f(scp[1]);
v3f(scp[2]);
v3f(scp[3]);
v3f(scp[4]);
v3f(scp[5]);
v3f(scp[6]);
v3f(scp[7]);
v3f(scp[8]);
v3f(scp[9]);
v3f(scp[10]);
v3f(scp[11]);
v3f(scp[12]);
v3f(scp[13]);
endline();
}
draw_double_cylinder() {
bgnline();
v3f(dcp[0]);
v3f(dcp[1]);
v3f(dcp[2]);
v3f(dcp[3]);
v3f(dcp[4]);
v3f(dcp[5]);
v3f(dcp[6]);
v3f(dcp[7]);
v3f(dcp[8]);
v3f(dcp[9]);
v3f(dcp[10]);
v3f(dcp[11]);
v3f(dcp[12]);
v3f(dcp[13]);
endline();
}
draw_elbow() {
bgnline();
v3f(ep[0][0]);
v3f(ep[1][0]);
v3f(ep[0][1]);
v3f(ep[1][1]);
v3f(ep[0][2]);
v3f(ep[1][2]);
v3f(ep[0][3]);
v3f(ep[1][3]);
v3f(ep[0][4]);
v3f(ep[1][4]);
v3f(ep[0][5]);
v3f(ep[1][5]);
v3f(ep[0][6]);
v3f(ep[1][6]);
endline();
bgnline();
v3f(ep[1][0]);
v3f(ep[2][0]);
v3f(ep[1][1]);
v3f(ep[2][1]);
v3f(ep[1][2]);
v3f(ep[2][2]);
v3f(ep[1][3]);
v3f(ep[2][3]);
v3f(ep[1][4]);
v3f(ep[2][4]);
v3f(ep[1][5]);
v3f(ep[2][5]);
v3f(ep[1][6]);
v3f(ep[2][6]);
endline();
bgnline();
v3f(ep[2][0]);
v3f(ep[3][0]);
v3f(ep[2][1]);
v3f(ep[3][1]);
v3f(ep[2][2]);
v3f(ep[3][2]);
v3f(ep[2][3]);
v3f(ep[3][3]);
v3f(ep[2][4]);
v3f(ep[3][4]);
v3f(ep[2][5]);
v3f(ep[3][5]);
v3f(ep[2][6]);
v3f(ep[3][6]);
endline();
bgnline();
v3f(ep[3][0]);
v3f(ep[4][0]);
v3f(ep[3][1]);
v3f(ep[4][1]);
v3f(ep[3][2]);
v3f(ep[4][2]);
v3f(ep[3][3]);
v3f(ep[4][3]);
v3f(ep[3][4]);
v3f(ep[4][4]);
v3f(ep[3][5]);
v3f(ep[4][5]);
v3f(ep[3][6]);
v3f(ep[4][6]);
endline();
bgnline();
v3f(ep[4][0]);
v3f(ep[5][0]);
v3f(ep[4][1]);
v3f(ep[5][1]);
v3f(ep[4][2]);
v3f(ep[5][2]);
v3f(ep[4][3]);
v3f(ep[5][3]);
v3f(ep[4][4]);
v3f(ep[5][4]);
v3f(ep[4][5]);
v3f(ep[5][5]);
v3f(ep[4][6]);
v3f(ep[5][6]);
endline();
bgnline();
v3f(ep[5][0]);
v3f(ep[6][0]);
v3f(ep[5][1]);
v3f(ep[6][1]);
v3f(ep[5][2]);
v3f(ep[6][2]);
v3f(ep[5][3]);
v3f(ep[6][3]);
v3f(ep[5][4]);
v3f(ep[6][4]);
v3f(ep[5][5]);
v3f(ep[6][5]);
v3f(ep[5][6]);
v3f(ep[6][6]);
endline();
}
bend_forward() {
translate(0.0, 1.000000, 0.0);
rotate(900, 'x');
translate(0.0, -1.000000, 0.0);
}
bend_left() {
rotate(-900, 'z');
translate(0.0, 1.000000, 0.0);
rotate(900, 'x');
translate(0.0, -1.000000, 0.0);
}
bend_right() {
rotate(900, 'z');
translate(0.0, 1.000000, 0.0);
rotate(900, 'x');
translate(0.0, -1.000000, 0.0);
}
draw_logo_line() {
lmbind(MATERIAL, MAT_LOGO);
translate(5.500000, -3.500000, 4.500000);
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -5.000000);
draw_single_cylinder();
bend_right();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -5.000000);
draw_single_cylinder();
bend_left();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -5.000000);
draw_single_cylinder();
bend_right();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -5.000000);
draw_single_cylinder();
bend_left();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -5.000000);
draw_single_cylinder();
bend_right();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -7.000000);
draw_double_cylinder();
bend_forward();
draw_elbow();
translate(0.0, 0.0, -5.000000);
draw_single_cylinder();
bend_left();
draw_elbow();
}
| 21.123167 | 71 | 0.554769 |
91d5dd4e61578717eef8a12b9fd395ac64bc2e9c | 604 | h | C | gbbs/flags.h | darchr/gbbs | 345e9cab341ffbb2457fc9948bfc176cd3553ca2 | [
"MIT"
] | null | null | null | gbbs/flags.h | darchr/gbbs | 345e9cab341ffbb2457fc9948bfc176cd3553ca2 | [
"MIT"
] | null | null | null | gbbs/flags.h | darchr/gbbs | 345e9cab341ffbb2457fc9948bfc176cd3553ca2 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
namespace gbbs {
typedef uint32_t flags;
const flags no_output = 1;
const flags pack_edges = 2;
const flags sparse_blocked = 4;
const flags dense_forward = 8;
const flags dense_parallel = 16;
const flags remove_duplicates = 32;
const flags no_dense = 64;
const flags in_edges = 128; // map over in edges instead of out edges
const flags fine_parallel = 256; // split to a node-size of 1
const flags compact_blocks = 512; // used in SAGE
const flags dense_only = 1024;
inline bool should_output(const flags &fl) { return !(fl & no_output); }
} // namespace gbbs
| 27.454545 | 75 | 0.736755 |
8cf15296efd9877451a7bdc6ce0ffbf567f66009 | 771 | h | C | driver/CANDriver.h | VincentCheungM/esrforusi | 22db50d63163d7f01462918359c6a796f0fe6d1b | [
"Apache-2.0"
] | 5 | 2018-08-09T07:11:28.000Z | 2021-06-03T06:18:31.000Z | driver/CANDriver.h | VincentCheungM/esrforusi | 22db50d63163d7f01462918359c6a796f0fe6d1b | [
"Apache-2.0"
] | null | null | null | driver/CANDriver.h | VincentCheungM/esrforusi | 22db50d63163d7f01462918359c6a796f0fe6d1b | [
"Apache-2.0"
] | 2 | 2018-08-09T07:11:36.000Z | 2018-08-16T03:06:10.000Z | #ifndef candriver_h
#define candriver_h
#include <cstdio>
#include <string>
#include <cstdlib>
#include "controlcan.h"
#include "../Util.h"
#include "../Esr.h"
#include "driver.h"
//using namespace std;
class CANDriver: public Driver {
/*****************************parameter***********************************/
private:
/* can structure */
VCI_CAN_OBJ vco_receive[64];
VCI_CAN_OBJ vco_send[8];
VCI_INIT_CONFIG vic_1;
int nDeviceType;
int nDeviceInd;
int nCANInd_1;
int nCANInd_2;
/*****************************method************************************/
public:
CANDriver();
~CANDriver();
/* can device */
int init();
int close();
int start();
int recv();
int send();
};
#endif
| 17.133333 | 76 | 0.513619 |
87a69976373d1be52b283e76e41197d558fbf720 | 1,513 | h | C | orca/gporca/libnaucrates/include/naucrates/md/IMDTrigger.h | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | 3 | 2017-12-10T16:41:21.000Z | 2020-07-08T12:59:12.000Z | orca/gporca/libnaucrates/include/naucrates/md/IMDTrigger.h | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | orca/gporca/libnaucrates/include/naucrates/md/IMDTrigger.h | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | 4 | 2017-12-10T16:41:35.000Z | 2020-11-28T12:20:30.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// IMDTrigger.h
//
// @doc:
// Interface for triggers in the metadata cache
//
// @owner:
//
//
// @test:
//
//
//---------------------------------------------------------------------------
#ifndef GPMD_IMDTrigger_H
#define GPMD_IMDTrigger_H
#include "gpos/base.h"
#include "naucrates/md/IMDCacheObject.h"
namespace gpmd
{
using namespace gpos;
//---------------------------------------------------------------------------
// @class:
// IMDTrigger
//
// @doc:
// Interface for triggers in the metadata cache
//
//---------------------------------------------------------------------------
class IMDTrigger : public IMDCacheObject
{
public:
// object type
virtual
Emdtype Emdt() const
{
return EmdtTrigger;
}
// does trigger execute on a row-level
virtual
BOOL FRow() const = 0;
// is this a before trigger
virtual
BOOL FBefore() const = 0;
// is this an insert trigger
virtual
BOOL FInsert() const = 0;
// is this a delete trigger
virtual
BOOL FDelete() const = 0;
// is this an update trigger
virtual
BOOL FUpdate() const = 0;
// relation mdid
virtual
IMDId *PmdidRel() const = 0;
// function mdid
virtual
IMDId *PmdidFunc() const = 0;
// is trigger enabled
virtual
BOOL FEnabled() const = 0;
};
}
#endif // !GPMD_IMDTrigger_H
// EOF
| 17.193182 | 78 | 0.496365 |
0cf2ef7eeae93994c550fc5d899665496cb41430 | 1,256 | h | C | src/resourcemanager.h | Hopson97/Pyoro | a61890f193618e3aa9f3fac87defc6b3bce03520 | [
"MIT"
] | 15 | 2015-12-05T03:40:49.000Z | 2020-11-23T20:47:13.000Z | src/resourcemanager.h | Hopson97/Pyoro | a61890f193618e3aa9f3fac87defc6b3bce03520 | [
"MIT"
] | 1 | 2015-12-24T22:17:19.000Z | 2015-12-24T22:17:19.000Z | src/resourcemanager.h | Hopson97/Pyoro | a61890f193618e3aa9f3fac87defc6b3bce03520 | [
"MIT"
] | 4 | 2015-12-05T04:45:05.000Z | 2022-01-28T15:20:31.000Z | #ifndef RESOURCEMANAGER_H
#define RESOURCEMANAGER_H
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
class ResourceManager
{
public:
ResourceManager();
sf::Font& getFont(std::string fontName);
sf::Texture& getTexture(std::string textureName);
sf::SoundBuffer& getSound(std::string soundName);
private: //METHODS
void loadTextures();
void loadFonts();
void loadSounds();
private: //TEXTURES
std::map<std::string, sf::Texture> mTextures; //A dictionary as it were to store textures
sf::Texture background; //Background texture
sf::Texture pyoro; //Player/ Pyoro texture
sf::Texture seed; //Seeds/ "bomb" texture
sf::Texture tile; //Floor tile textures
private: //FONTS
std::map<std::string, sf::Font> mFonts; //A dictionary as it were to store fonts
sf::Font arial; //Arial font
sf::Font instruction; //Instruction font (from 1001freefonts.com)
private: //Sounds
std::map<std::string, sf::SoundBuffer> mSounds;
sf::SoundBuffer playerWalk;
sf::SoundBuffer licking;
};
#endif // RESOURCEMANAGER_H
| 28.545455 | 99 | 0.602707 |
9504b6a5fc9bf86971329ce1da8945aefe110030 | 609 | h | C | util/cache.h | ZiheLiu/tinykv | c5c35643474edbd87a31c03158979d9f59845f4b | [
"MIT"
] | 1 | 2021-04-24T02:34:04.000Z | 2021-04-24T02:34:04.000Z | util/cache.h | ZiheLiu/tinykv | c5c35643474edbd87a31c03158979d9f59845f4b | [
"MIT"
] | null | null | null | util/cache.h | ZiheLiu/tinykv | c5c35643474edbd87a31c03158979d9f59845f4b | [
"MIT"
] | null | null | null | //
// Created by liuzihe on 2020/10/16.
//
#ifndef TINYKV_CACHE_H
#define TINYKV_CACHE_H
#include <string>
#include "slice.h"
namespace tinykv {
class Cache {
public:
Cache() = default;
virtual ~Cache();
Cache(const Cache&) = delete;
Cache& operator=(const Cache&) = delete;
virtual bool Get(const std::string& key, Slice* result, char* payload) = 0;
virtual void Put(const std::string& key, const std::string& value, size_t charge) = 0;
};
inline Cache::~Cache() = default;
Cache *NewLRUCache(size_t capacity);
} // End tinykv namespace.
#endif //TINYKV_CACHE_H
| 17.911765 | 90 | 0.663383 |
16e67031c318691d8950e372a84cfa60f409027b | 2,990 | c | C | sdk-6.5.20/libs/sdklt/shr/pb/shr_pb_format_uint32.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/shr/pb/shr_pb_format_uint32.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/shr/pb/shr_pb_format_uint32.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /*! \file shr_pb_format_uint32.c
*
* Format uint32_t value(s) to print buffer.
*/
/*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#include <shr/shr_pb_format.h>
const char *
shr_pb_format_uint32(shr_pb_t *pb, const char *prefix,
const uint32_t *val, int count, uint32_t bitwidth)
{
int idx, bit;
int start = 0, minwidth = 0;
uint32_t datawidth = 0;
if (pb == NULL || count <= 0) {
return SHR_PB_ERR_STR;
}
if (prefix) {
shr_pb_printf(pb, "%s", prefix);
}
if (bitwidth > 0) {
/*
* If the format bit width is specified, get the number of hex-digits
* for the most significant word to support leading zeros format.
*/
minwidth = ((bitwidth + 3) / 4) % 8;
if (minwidth == 0) {
minwidth = 8;
}
start = (bitwidth - 1) / 32;
/* Check the data bit width of the given array. */
for (idx = count - 1; idx >= 0; idx--) {
if (val[idx] == 0) {
continue;
}
if (datawidth == 0) {
for (bit = 31; bit >= 0; bit--) {
if (val[idx] >> bit) {
datawidth = bit + 1;
break;
}
}
} else {
datawidth += 32;
}
}
/* Ignore leading zeros format if data exceeds the format width. */
if (datawidth > bitwidth) {
minwidth = 0;
}
}
if (minwidth > 0) {
uint32_t val32;
/*
* Left-justify with the leading zeros to
* match the specified bit width.
*/
for (idx = start; idx >= 0; idx--) {
if (idx >= count) {
val32 = 0;
} else {
val32 = val[idx];
}
if (idx == start) {
shr_pb_printf(pb, "0x%.*"PRIx32, minwidth, val32);
} else {
shr_pb_printf(pb, "_%08"PRIx32, val32);
}
}
} else {
/*
* Format values without leading zeros.
*/
for (start = -1, idx = count - 1; idx >= 0; idx--) {
if (start < 0) {
if (idx == 0 && val[idx] < 10) {
shr_pb_printf(pb, "%"PRIu32, *val);
return shr_pb_str(pb);
}
/* Skip the leading zero elements. */
if (val[idx] == 0) {
continue;
}
/* format the first non-zero element. */
shr_pb_printf(pb, "0x%"PRIx32, val[idx]);
start = idx;
continue;
}
shr_pb_printf(pb, "_%08"PRIx32, val[idx]);
}
}
return shr_pb_str(pb);
}
| 27.943925 | 134 | 0.444482 |
05fde5e308d961cfed6d7356f891f5d8f5bd7eb9 | 209 | h | C | lib/template/lanekit-ios-project/lanekit-ios-project/Controllers/LKAppDelegate.h | larryaasen/LaneK | a88df741b2612435d0a73e2e293224868b088d99 | [
"MIT"
] | 27 | 2015-01-29T03:26:25.000Z | 2021-02-07T08:23:38.000Z | lib/template/lanekit-ios-project/lanekit-ios-project/Controllers/LKAppDelegate.h | larryaasen/LaneK | a88df741b2612435d0a73e2e293224868b088d99 | [
"MIT"
] | null | null | null | lib/template/lanekit-ios-project/lanekit-ios-project/Controllers/LKAppDelegate.h | larryaasen/LaneK | a88df741b2612435d0a73e2e293224868b088d99 | [
"MIT"
] | 2 | 2015-01-11T21:24:11.000Z | 2017-07-31T05:13:51.000Z | //
// LKAppDelegate.h
//
#import <UIKit/UIKit.h>
@interface LKAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
+ (LKAppDelegate *)sharedAppDelegate;
@end
| 14.928571 | 62 | 0.741627 |
e850bdbea77dd84c3ae600b2ef40e4471529df97 | 129 | h | C | dependencies/physx-4.1/source/physxextensions/src/ExtPvd.h | realtehcman/-UnderwaterSceneProject | 72cbd375ef5e175bed8f4e8a4d117f5340f239a4 | [
"MIT"
] | null | null | null | dependencies/physx-4.1/source/physxextensions/src/ExtPvd.h | realtehcman/-UnderwaterSceneProject | 72cbd375ef5e175bed8f4e8a4d117f5340f239a4 | [
"MIT"
] | null | null | null | dependencies/physx-4.1/source/physxextensions/src/ExtPvd.h | realtehcman/-UnderwaterSceneProject | 72cbd375ef5e175bed8f4e8a4d117f5340f239a4 | [
"MIT"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:4642d86c0d212a64b05fbc540910702d3b0adc51201fb430a19b91723620a9b0
size 6905
| 32.25 | 75 | 0.883721 |
c3e8ac7d26f5385aea64eb35509d1ade91efe0b2 | 287 | c | C | asm/libfunctions.c | billzorn/msp-pymodel | dc567844ceb45442524e9c04519201ce724e05d9 | [
"MIT"
] | null | null | null | asm/libfunctions.c | billzorn/msp-pymodel | dc567844ceb45442524e9c04519201ce724e05d9 | [
"MIT"
] | null | null | null | asm/libfunctions.c | billzorn/msp-pymodel | dc567844ceb45442524e9c04519201ce724e05d9 | [
"MIT"
] | null | null | null | #include <msp430.h>
void main (void) {
const char *s1 = "hello world !";
const char *s2 = "how are you today";
volatile char buf[32];
volatile short x;
volatile short y;
volatile short z;
x = strcmp(s1, buf);
y = 17;
z = x * y;
while(1){}
}
| 14.35 | 41 | 0.54007 |
d76c028ac018149af86256664eb3353bacd14d94 | 424 | h | C | examples/very_angry_robots/runner/systems/event_system.h | badlydrawnrod/arviss | be028e9e49160d30d460d148214b996a053a7ad7 | [
"Zlib"
] | 1 | 2021-04-21T13:26:28.000Z | 2021-04-21T13:26:28.000Z | examples/very_angry_robots/runner/systems/event_system.h | badlydrawnrod/arviss | be028e9e49160d30d460d148214b996a053a7ad7 | [
"Zlib"
] | null | null | null | examples/very_angry_robots/runner/systems/event_system.h | badlydrawnrod/arviss | be028e9e49160d30d460d148214b996a053a7ad7 | [
"Zlib"
] | null | null | null | #pragma once
typedef void (*EventHandler)(int firstEvent, int lastEvent);
void RegisterHandlerWithEventSystem(EventHandler handler);
void ResetEventSystem(void);
void UpdateEventSystem(void);
static struct
{
void (*Register)(EventHandler handler);
void (*Reset)(void);
void (*Update)(void);
} EventSystem = {.Register = RegisterHandlerWithEventSystem, .Reset = ResetEventSystem, .Update = UpdateEventSystem};
| 28.266667 | 117 | 0.761792 |
bab61be4afe37bc959d4c562d92bbf9bd84cc182 | 40,499 | h | C | linux-3.0/drivers/mtd/nand/mtk_nand.h | spartan263/vizio_oss | 74270002d874391148119b48882db6816e7deedc | [
"Linux-OpenIB"
] | 4 | 2016-07-01T04:50:02.000Z | 2021-11-14T21:29:42.000Z | linux-3.0/drivers/mtd/nand/mtk_nand.h | spartan263/vizio_oss | 74270002d874391148119b48882db6816e7deedc | [
"Linux-OpenIB"
] | null | null | null | linux-3.0/drivers/mtd/nand/mtk_nand.h | spartan263/vizio_oss | 74270002d874391148119b48882db6816e7deedc | [
"Linux-OpenIB"
] | null | null | null | /*
* drivers/mtd/nand/mtk_nand.h
*
* This is the MTD driver for MTK NAND controller
*
*
* Copyright (c) 2010-2012 MediaTek Inc.
* This file is based ARM Realview platform
* Copyright (C) 2002 ARM Ltd.
* All Rights Reserved
* $Author: dtvbm11 $
*
* 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.
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
*/
/** @file nand_reg.h
* nand_reg.h The NAND register constant macros
*/
#ifndef NAND_REG_H
#define NAND_REG_H
#if defined(CC_MT5398) || defined(CONFIG_ARCH_MT5398)
#define CC_NAND_60BIT_NFI (0)
#else
#define CC_NAND_60BIT_NFI (0)
#endif
#if defined(CC_MT5880) || defined(CC_MT5860) || defined(CONFIG_ARCH_MT5880) || defined(CONFIG_ARCH_MT5881) || defined(CONFIG_ARCH_MT5860)
#define CC_NAND_DMMERGE_NFI (1)
#else
#define CC_NAND_DMMERGE_NFI (0)
#endif
#if !(defined(CONFIG_ARCH_MT5396) || defined(CONFIG_ARCH_MT5368) || defined(CONFIG_ARCH_MT5389))
#define CC_NAND_WDLE_CFG (1)
#else
#define CC_NAND_WDLE_CFG (0)
#endif
//-----------------------------------------------------------------------------
// Constant definitions
//-----------------------------------------------------------------------------
#define NAND_DRAM_BASE ((UINT32)0x80000000)
#if defined(CC_AC_DROP_GPIO_ISR)
#if defined(Wistron_MT5580_MODEL)||defined(Wistron_MT5580_E_MODEL)
#define DETECTION_GPIO_LEVEL (0)
#define REG_ACDROP_GPIO 0xF000D744 //GPIOIN58
#define REG_ACDROP_GPIOMASK 0x04000000 //GPIOIN58
#elif defined(Foxconn_MT5580_MODEL)
#define DETECTION_GPIO_LEVEL (0)
#define REG_ACDROP_GPIO 0xF000D744 //GPIOIN58
#define REG_ACDROP_GPIOMASK 0x04000000 //GPIOIN58
#elif defined(AMTRAN_MT5580_E_MODEL)
#define DETECTION_GPIO_LEVEL (1)
#define REG_ACDROP_GPIO 0xF000D744 //GPIOIN58
#define REG_ACDROP_GPIOMASK 0x04000000 //GPIOIN58
#elif defined(Wistron_MT5590_MODEL)
#define DETECTION_GPIO_LEVEL (0)
#define REG_ACDROP_GPIO 0xF000D744 //GPIOIN38
#define REG_ACDROP_GPIOMASK 0x00000040 //GPIOIN38
#elif defined(Foxconn_MT5590_MODEL)
#define DETECTION_GPIO_LEVEL (0)
#define REG_ACDROP_GPIO 0xF000D744 //GPIOIN38
#define REG_ACDROP_GPIOMASK 0x00000040 //GPIOIN38
#elif defined(TPV_MT5590_MODEL)
#define DETECTION_GPIO_LEVEL (0)
#define REG_ACDROP_GPIO 0xF000D744 //GPIOIN38
#define REG_ACDROP_GPIOMASK 0x00000040 //GPIOIN38
#else
#define DETECTION_GPIO_LEVEL (0)
#define REG_ACDROP_GPIO 0xF000D744 //GPIOIN38
#define REG_ACDROP_GPIOMASK 0x00000040 //GPIOIN38
#endif
#endif
//#define REG_ACDROP_GPIO 0xF000D540 //GPIOIN23
// #define REG_ACDROP_GPIOMASK 0x800000 //GPIOIN23
// RS232 12-bit/24-bit ECC controller selection
#define NAND_NFI_PERMISC 0x004028
#define NAND_NFI_PERMISC_NFI_SEL (((UINT32) 1) << 0)
#define NAND_NFI_CNFG 0x00800
#define NAND_NFI_CNFG_AHB_MODE (((UINT32) 1) << 0)
#define NAND_NFI_CNFG_READ_MODE (((UINT32) 1) << 1)
#define NAND_NFI_CNFG_SEL_SEC_512BYTE (((UINT32) 1) << 5)
#define NAND_NFI_CNFG_BYTE_RW (((UINT32) 1) << 6)
#define NAND_NFI_CNFG_HW_ECC_EN (((UINT32) 1) << 8)
#define NAND_NFI_CNFG_AUTO_FMT_EN (((UINT32) 1) << 9)
#define NAND_NFI_CNFG_OP_MODE(x) ((((UINT32) x ) & 0x07) << 12)
#define NAND_NFI_CNFG_OP_IDLE (((UINT32) 0) << 12)
#define NAND_NFI_CNFG_OP_READ (((UINT32) 1) << 12)
#define NAND_NFI_CNFG_OP_SINGLE (((UINT32) 2) << 12)
#define NAND_NFI_CNFG_OP_PROGRAM (((UINT32) 3) << 12)
#define NAND_NFI_CNFG_OP_ERASE (((UINT32) 4) << 12)
#define NAND_NFI_CNFG_OP_RESET (((UINT32) 5) << 12)
#define NAND_NFI_CNFG_OP_CUSTOM (((UINT32) 6) << 12)
#define NAND_NFI_CNFG_OP_RESERVE (((UINT32) 7) << 12)
#define NAND_NFI_PAGEFMT 0x00804
#define NAND_NFI_PAGEFMT_PAGE(x) ((((UINT32) x ) & 0x03) << 0)
#define NAND_NFI_PAGEFMT_PAGE_SIZE_512_2k (((UINT32) 0) << 0)
#define NAND_NFI_PAGEFMT_PAGE_SIZE_4k (((UINT32) 1) << 0)
#define NAND_NFI_PAGEFMT_PAGE_SIZE_8k (((UINT32) 2) << 0)
#if CC_NAND_60BIT_NFI
#define NAND_NFI_PAGEFMT_SPARE(x) ((((UINT32) x ) & 0x0F) << 2)
#define NAND_NFI_PAGEFMT_SPARE_16 (((UINT32) 0) << 2)
#define NAND_NFI_PAGEFMT_SPARE_26 (((UINT32) 1) << 2)
#define NAND_NFI_PAGEFMT_SPARE_27 (((UINT32) 2) << 2)
#define NAND_NFI_PAGEFMT_SPARE_28 (((UINT32) 3) << 2)
#define NAND_NFI_PAGEFMT_SPARE_32 (((UINT32) 4) << 2)
#define NAND_NFI_PAGEFMT_SPARE_36 (((UINT32) 5) << 2)
#define NAND_NFI_PAGEFMT_SPARE_40 (((UINT32) 6) << 2)
#define NAND_NFI_PAGEFMT_SPARE_44 (((UINT32) 7) << 2)
#define NAND_NFI_PAGEFMT_SPARE_48 (((UINT32) 8) << 2)
#define NAND_NFI_PAGEFMT_SPARE_50 (((UINT32) 9) << 2)
#define NAND_NFI_PAGEFMT_SPARE_52 (((UINT32) 10) << 2)
#define NAND_NFI_PAGEFMT_SPARE_54 (((UINT32) 11) << 2)
#define NAND_NFI_PAGEFMT_SPARE_56 (((UINT32) 12) << 2)
#define NAND_NFI_PAGEFMT_SPARE_62 (((UINT32) 13) << 2)
#define NAND_NFI_PAGEFMT_SPARE_63 (((UINT32) 14) << 2)
#define NAND_NFI_PAGEFMT_SPARE_64 (((UINT32) 15) << 2)
#else
#define NAND_NFI_PAGEFMT_SPARE(x) ((((UINT32) x ) & 0x03) << 4)
#define NAND_NFI_PAGEFMT_SPARE_16 (((UINT32) 0) << 4)
#define NAND_NFI_PAGEFMT_SPARE_26 (((UINT32) 1) << 4)
#define NAND_NFI_PAGEFMT_SPARE_27 (((UINT32) 2) << 4)
#define NAND_NFI_PAGEFMT_SPARE_28 (((UINT32) 3) << 4)
#endif
#define NAND_NFI_PAGEFMT_FDM_NUM(x) ((((UINT32) x ) & 0x1F) << 6)
#define NAND_NFI_PAGEFMT_ECC_NUM(x) ((((UINT32) x ) & 0x1F) << 11)
#if CC_NAND_60BIT_NFI
#define NAND_NFI_PAGEFMT_SECTOR_SIZE(x) ((((UINT32) x ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_512_16 ((((UINT32) 0x210 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_32 ((((UINT32) 0x420 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_52 ((((UINT32) 0x434 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_54 ((((UINT32) 0x436 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_56 ((((UINT32) 0x438 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_64 ((((UINT32) 0x440 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_72 ((((UINT32) 0x448 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_80 ((((UINT32) 0x450 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_88 ((((UINT32) 0x458 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_96 ((((UINT32) 0x460 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_100 ((((UINT32) 0x464 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_104 ((((UINT32) 0x468 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_108 ((((UINT32) 0x46C ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_112 ((((UINT32) 0x470 ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_124 ((((UINT32) 0x47C ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_126 ((((UINT32) 0x47E ) & 0x7FF) << 16)
#define NAND_NFI_PAGEFMT_SECTOR_SIZE_1024_128 ((((UINT32) 0x480 ) & 0x7FF) << 16)
#endif
#define NAND_NFI_CON 0x00808
#define NAND_NFI_CON_FIFO_FLUSH (((UINT32) 1) << 0)
#define NAND_NFI_CON_NFI_RST (((UINT32) 1) << 1)
#define NAND_NFI_CON_SRD (((UINT32) 1) << 4)
#define NAND_NFI_CON_NOB(x) ((((UINT32) x ) & 0x7) << 5)
#define NAND_NFI_CON_BRD (((UINT32) 1) << 8)
#define NAND_NFI_CON_BWR (((UINT32) 1) << 9)
#define NAND_NFI_CON_SEC_NUM(x) ((((UINT32) x ) & 0xF) << 12)
#define NAND_NFI_ACCCON1 0x0080C
#define NAND_NFI_ACCCON2 0x009A4
#define NAND_NFI_INTR_EN 0x00810
#define NAND_NFI_INTR_EN_RD_DONE (((UINT32) 1) << 0)
#define NAND_NFI_INTR_EN_WR_DONE (((UINT32) 1) << 1)
#define NAND_NFI_INTR_EN_RESET_DONE (((UINT32) 1) << 2)
#define NAND_NFI_INTR_EN_ERASE_DONE (((UINT32) 1) << 3)
#define NAND_NFI_INTR_EN_BUSY_RETURN (((UINT32) 1) << 4)
#define NAND_NFI_INTR_EN_ACCESS_LOCK (((UINT32) 1) << 5)
#define NAND_NFI_INTR_EN_AHB_DONE (((UINT32) 1) << 6)
#if CC_NAND_60BIT_NFI
#define NAND_NFI_INTR_EN_BUSY_RETURN_EN2 (((UINT32) 1) << 7)
#endif
#define NAND_NFI_INTR_EN_RS232RD_DONE (((UINT32) 1) << 8)
#define NAND_NFI_INTR_EN_RS232WR_DONE (((UINT32) 1) << 9)
#define NAND_NFI_INTR_EN_MDMA_DONE (((UINT32) 1) << 10)
#define NAND_NFI_INTR 0x00814
#define NAND_NFI_INTR_RD_DONE (((UINT32) 1) << 0)
#define NAND_NFI_INTR_WR_DONE (((UINT32) 1) << 1)
#define NAND_NFI_INTR_RESET_DONE (((UINT32) 1) << 2)
#define NAND_NFI_INTR_ERASE_DONE (((UINT32) 1) << 3)
#define NAND_NFI_INTR_BUSY_RETURN (((UINT32) 1) << 4)
#define NAND_NFI_INTR_ACCESS_LOCK (((UINT32) 1) << 5)
#define NAND_NFI_INTR_AHB_DONE (((UINT32) 1) << 6)
#define NAND_NFI_INTR_RS232RD_DONE (((UINT32) 1) << 8)
#define NAND_NFI_INTR_RS232WR_DONE (((UINT32) 1) << 9)
#define NAND_NFI_INTR_MDMA_DONE (((UINT32) 1) << 10)
#define NAND_NFI_INTR_MASK ((UINT32) 0x44B)
#define NAND_NFI_CMD 0x00820
#define NAND_NFI_ADDRNOB 0x00830
#define NAND_NFI_COLADDR 0x00834
#define NAND_NFI_ROWADDR 0x00838
#define NAND_NFI_STRDATA 0x00840
#define NAND_NFI_STRDATA_STRDATA (((UINT32) 0x1) << 0)
#define NAND_NFI_DATAW 0x00850
#define NAND_NFI_DATAWB 0x00850
#define NAND_NFI_DATAR 0x00854
#define NAND_NFI_DATARB 0x00854
#define NAND_NFI_STA 0x00860
#define NAND_NFI_STA_NFI_FSM (((UINT32) 0xF) << 16)
#define NAND_NFI_STA_NFI_FSM_READ_DATA (((UINT32) 0x3) << 16)
#define NAND_NFI_FIFOSTA 0x00864
#define NAND_NFI_FIFOSTA_RD_REMAIN (((UINT32) 0x1F) << 0)
#define NAND_NFI_FIFOSTA_RD_EMPTY (((UINT32) 1) << 6)
#define NAND_NFI_FIFOSTA_WT_EMPTY (((UINT32) 1) << 14)
#define NAND_NFI_LOCKSTA 0x00868
#define NAND_NFI_ADDRCNTR 0x00870
#define NAND_NFI_ADDRCNTR_SEC_CNTR(x) ((((UINT32) x ) & 0xF) << 12)
#define NAND_NFI_STRADDR 0x00880
#define NAND_NFI_BYTELEN 0x00884
// I/O Pin Control
#define NAND_NFI_CSEL 0x00890
#define NAND_NFI_IOCON 0x00894
//FDM Data Content
#define NAND_NFI_FDM0L 0x008A0
#define NAND_NFI_FDM0M 0x008A4
#define NAND_NFI_FDM0L2 0x008A8
#define NAND_NFI_FDM0M2 0x008AC
#define NAND_NFI_FDM_LEN 16
#define NAND_NFI_FDM_SECTNUM 8
//Flash Lock
#define NAND_NFI_LOCKEN 0x009E0
#define NAND_NFI_LOCKCON 0x009E4
#define NAND_NFI_LOCKANOB 0x009E8
#define NAND_NFI_LOCK00ADD 0x009F0
#define NAND_NFI_LOCK00FMT 0x009F4
#define NAND_NFI_LOCK01ADD 0x009F8
#define NAND_NFI_LOCK01FMT 0x009FC
#define NAND_NFI_LOCK02ADD 0x00920
#define NAND_NFI_LOCK02FMT 0x00924
#define NAND_NFI_LOCK03ADD 0x00928
#define NAND_NFI_LOCK03FMT 0x0092C
#define NAND_NFI_LOCK04ADD 0x00930
#define NAND_NFI_LOCK04FMT 0x00934
#define NAND_NFI_LOCK05ADD 0x00938
#define NAND_NFI_LOCK05FMT 0x0093C
#define NAND_NFI_LOCK06ADD 0x00940
#define NAND_NFI_LOCK06FMT 0x00944
#define NAND_NFI_LOCK07ADD 0x00948
#define NAND_NFI_LOCK07FMT 0x0094C
#define NAND_NFI_LOCK08ADD 0x00950
#define NAND_NFI_LOCK08FMT 0x00954
#define NAND_NFI_LOCK09ADD 0x00958
#define NAND_NFI_LOCK09FMT 0x0095C
#define NAND_NFI_LOCK10ADD 0x00960
#define NAND_NFI_LOCK10FMT 0x00964
#define NAND_NFI_LOCK11ADD 0x00968
#define NAND_NFI_LOCK11FMT 0x0096C
#define NAND_NFI_LOCK12ADD 0x00970
#define NAND_NFI_LOCK12FMT 0x00974
#define NAND_NFI_LOCK13ADD 0x00978
#define NAND_NFI_LOCK13FMT 0x0097C
#define NAND_NFI_LOCK14ADD 0x00980
#define NAND_NFI_LOCK14FMT 0x00984
#define NAND_NFI_LOCK15ADD 0x00988
#define NAND_NFI_LOCK15FMT 0x0098C
//Debug Register
#define NAND_NFI_FIFODATA0 0x00990
#define NAND_NFI_FIFODATA1 0x00994
#define NAND_NFI_FIFODATA2 0x00998
#define NAND_NFI_FIFODATA3 0x0099C
#define NAND_NFI_MISC 0x009A0
#define NAND_NFI_MISC_FLASH_PMUX (((UINT32) 1) << 2)
#define NAND_NFI_LCD2NAND 0x009A4
// clock division
#define NAND_NFI_CLKDIV 0x009AC
#define NAND_NFI_CLKDIV_EN (((UINT32) 1) << 0)
// multi-page dma
#define NAND_NFI_MDMACON 0x009B0
#define NAND_NFI_MDMA_TRIG (((UINT32) 1) << 0)
#define NAND_NFI_MDMA_EN (((UINT32) 1) << 4)
#define NAND_NFI_MDMA_MODE(x) ((((UINT32) x ) & 0x3) << 8)
#define NAND_NFI_MDMA_READ (((UINT32) 0) << 8)
#define NAND_NFI_MDMA_WRITE (((UINT32) 1) << 8)
#define NAND_NFI_MDMA_ERASE (((UINT32) 2) << 8)
#define NAND_NFI_MDMA_LEN(x) ((((UINT32) x ) & 0x7) << 12)
#define NAND_NFI_MDMA_PAGENUM 8
#define NAND_NFI_MDMAADDR 0x009B4
#define NAND_NFI_MDMAADDR_DRAMADDR (NAND_NFI_MDMA_PAGENUM * 0)
#define NAND_NFI_MDMAADDR_ROWADDR (NAND_NFI_MDMA_PAGENUM * 1)
#define NAND_NFI_MDMAADDR_FDM (NAND_NFI_MDMA_PAGENUM * 2)
#define NAND_NFI_MDMAADDR_DECDONE (NAND_NFI_MDMA_PAGENUM * 34)
#define NAND_NFI_MDMAADDR_DECFER (NAND_NFI_MDMA_PAGENUM * 35)
#define NAND_NFI_MDMAADDR_DECENUM0 (NAND_NFI_MDMA_PAGENUM * 36)
#define NAND_NFI_MDMAADDR_DECENUM1 (NAND_NFI_MDMA_PAGENUM * 37)
#define NAND_NFI_MDMAADDR_DECEL0 (NAND_NFI_MDMA_PAGENUM * 38)
#define NAND_NFI_MDMADATA 0x009B8
#if CC_NAND_60BIT_NFI
// random mizer
#define NAND_NFI_RANDOM_CFG 0x009BC
#define NAND_NFI_ENCODING_RANDON_EN (((UINT32) 1) << 0)
#define NAND_NFI_ENCODING_RANDON_SEED(x) ((((UINT32) x ) & 0x7FFF) << 1)
#define NAND_NFI_DECODING_RANDON_EN (((UINT32) 1) << 16)
#define NAND_NFI_DECODING_RANDON_SEED(x) ((((UINT32) x ) & 0x7FFF) << 17)
#else
// scramble
#define NAND_NFI_SCRAMBLE 0x009BC
#define NAND_NFI_INTERLEAVE_EN (((UINT32) 1) << 0)
#define NAND_NFI_SCRAMBLE_EN (((UINT32) 1) << 4)
#define NAND_NFI_SCRAMBLE_PAT(x) ((((UINT32) x ) & 0xFF) << 8)
#endif
// ECC
#define NAND_NFIECC_1BIT 14 // 1 bit ECC need 14 bit ecc code
#define NAND_NFIECC_ENCON 0x00A00
#define NAND_NFIECC_ENCCNFG 0x00A04
#if CC_NAND_60BIT_NFI
// 5398 60bit ECC ability
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_4 (((UINT32) 0) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_8 (((UINT32) 2) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_10 (((UINT32) 3) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_12 (((UINT32) 4) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_20 (((UINT32) 8) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_22 (((UINT32) 9) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_24 (((UINT32) 10) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_28 (((UINT32) 11) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_32 (((UINT32) 12) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_36 (((UINT32) 13) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_40 (((UINT32) 14) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_44 (((UINT32) 15) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_48 (((UINT32) 16) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_52 (((UINT32) 17) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_56 (((UINT32) 18) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_60 (((UINT32) 19) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_NFI_MODE (((UINT32) 1) << 5)
#define NAND_NFIECC_ENCCNFG_ENC_MS_520 (((UINT32) 0x1040) << 16)
#define NAND_NFIECC_ENCCNFG_ENC_MS_1032 (((UINT32) 0x2040) << 16)
#define NAND_NFIECC_ENCCNFG_ENC_MS_1040 (((UINT32) 0x2080) << 16)
#else
// 24bit ECC ability
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_4 (((UINT32) 0) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_8 (((UINT32) 2) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_10 (((UINT32) 3) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_12 (((UINT32) 4) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_20 (((UINT32) 8) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_TNUM_24 (((UINT32) 10) << 0)
#define NAND_NFIECC_ENCCNFG_ENC_NFI_MODE (((UINT32) 1) << 4)
#define NAND_NFIECC_ENCCNFG_ENC_MS_520 (((UINT32) 0x1040) << 16)
#define NAND_NFIECC_ENCCNFG_ENC_MS_1032 (((UINT32) 0x2040) << 16)
#define NAND_NFIECC_ENCCNFG_ENC_MS_1040 (((UINT32) 0x2080) << 16)
#endif
#define NAND_NFIECC_ENCDIADDR 0x00A08
#define NAND_NFIECC_ENCIDLE 0x00A0C
#define NAND_NFIECC_ENCSTA 0x00A24
#define NAND_NFIECC_ENCSTA_FSM_MASK (((UINT32) 0x3F) << 0)
#define NAND_NFIECC_ENCSTA_FSM_IDLE (((UINT32) 0) << 0)
#define NAND_NFIECC_ENCSTA_FSM_WAITIN (((UINT32) 1) << 0)
#define NAND_NFIECC_ENCSTA_FSM_BUSY (((UINT32) 2) << 0)
#define NAND_NFIECC_ENCSTA_FSM_PAROUT (((UINT32) 4) << 0)
#define NAND_NFIECC_ENCSTA_COUNT_PS (((UINT32) 0x1FF) << 7)
#define NAND_NFIECC_ENCSTA_COUNT_MS (((UINT32) 0x3FFF) << 16)
#define NAND_NFIECC_ENCIRQEN 0x00A28
#define NAND_NFIECC_ENCIRQSTA 0x00A2C
#define NAND_NFIECC_ENCPAR0 0x00A30
#if CC_NAND_60BIT_NFI
#define NAND_NFI_ENCPAR_NUM 27
#else
#define NAND_NFI_ENCPAR_NUM 11
#endif
#define NAND_NFIECC_DECCON 0x00B00
#define NAND_NFIECC_DECCNFG 0x00B04
#if CC_NAND_60BIT_NFI
#define NAND_NFIECC_DECCNFG_DEC_TNUM_4 (((UINT32) 0) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_8 (((UINT32) 2) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_10 (((UINT32) 3) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_12 (((UINT32) 4) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_20 (((UINT32) 8) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_24 (((UINT32) 10) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_28 (((UINT32) 11) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_32 (((UINT32) 12) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_36 (((UINT32) 13) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_40 (((UINT32) 14) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_44 (((UINT32) 15) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_48 (((UINT32) 16) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_52 (((UINT32) 17) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_56 (((UINT32) 18) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_60 (((UINT32) 19) << 0)
#define NAND_NFIECC_DECCNFG_DEC_NFI_MODE (((UINT32) 1) << 5)
#define NAND_NFIECC_DECCNFG_SEL_CHIEN_SEARCH (((UINT32) 1) << 7)
#else
#define NAND_NFIECC_DECCNFG_DEC_TNUM_4 (((UINT32) 0) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_8 (((UINT32) 2) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_10 (((UINT32) 3) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_12 (((UINT32) 4) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_20 (((UINT32) 8) << 0)
#define NAND_NFIECC_DECCNFG_DEC_TNUM_24 (((UINT32) 10) << 0)
#define NAND_NFIECC_DECCNFG_DEC_NFI_MODE (((UINT32) 1) << 4)
#endif
#define NAND_NFIECC_DECCNFG_DEC_CON_NONE (((UINT32) 1) << 12)
#define NAND_NFIECC_DECCNFG_DEC_CON_SOFT (((UINT32) 2) << 12)
#define NAND_NFIECC_DECCNFG_DEC_CON_AUTO (((UINT32) 3) << 12)
#define NAND_NFIECC_DECCNFG_DEC_CS_520_4 (((UINT32) 0x1078) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_520_10 (((UINT32) 0x10CC) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_8 (((UINT32) 0x20B0) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_12 (((UINT32) 0x20E8) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1040_8 (((UINT32) 0x20F0) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1040_20 (((UINT32) 0x2198) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_24 (((UINT32) 0x2190) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_28 (((UINT32) 0x21C8) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_32 (((UINT32) 0x2200) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_36 (((UINT32) 0x2238) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_40 (((UINT32) 0x2270) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_44 (((UINT32) 0x22A8) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_48 (((UINT32) 0x22E0) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_52 (((UINT32) 0x2318) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_56 (((UINT32) 0x2350) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_1032_60 (((UINT32) 0x2388) << 16)
#define NAND_NFIECC_DECCNFG_DEC_CS_EMPTY_EN (((UINT32) 1) << 31)
#define NAND_NFIECC_DECDIADDR 0x00B08
#define NAND_NFIECC_DECIDLE 0x00B0C
#define NAND_NFIECC_DECFER 0x00B10
#define NAND_NFIECC_DECDONE 0x00B18
#define NAND_NFIECC_DECIRQEN 0x00B34
#define NAND_NFIECC_DECIRQSTA 0x00B38
#define NAND_NFIECC_FDMADDR 0x00B3C
#define NAND_NFIECC_DECFSM 0x00B40
#define NAND_NFIECC_SYNSTA 0x00B44
#define NAND_NFIECC_DECNFIDI 0x00B48
#define NAND_NFIECC_SYN0 0x00B4C
#define NAND_NFIECC_DECENUM0 0x00B50
#define NAND_NFIECC_DECENUM1 0x00B54
#define NAND_NFIECC_DECEL0 0x00B60
#if CC_NAND_60BIT_NFI
#define NAND_SELECT_REGISTER 0x00BF0
#endif
#define NAND_DMMERGE_CFG 0x00FF8
#define NAND_NFI_MLC_CFG 0x00FFC+0xF0029000
#define NAND_CHK_DRAM_WDLE_EN (((UINT32) 1) << 30)
#define NAND_CHK_DRAM_WDLE_EN2 (((UINT32) 1) << 31)
//-----------------------------------------------------------------------------
// Common
//-----------------------------------------------------------------------------
// linux kernel has command define. (include\linux\mtd\nand.h)
#if 0
#define NAND_CMD_READ1_00 0x00
#define NAND_CMD_READ1_01 0x01
#define NAND_CMD_PROG_PAGE 0x10 /* WRITE 2 */
#define NAND_CMD_READ_30 0x30
#define NAND_CMD_READ2 0x50
#define NAND_CMD_ERASE1_BLK 0x60
#define NAND_CMD_STATUS 0x70
#define NAND_CMD_INPUT_PAGE 0x80 /* WRITE 1 */
#define NAND_CMD_READ_ID 0x90
#define NAND_CMD_ERASE2_BLK 0xD0
#define NAND_CMD_RESET 0xFF
#endif
#define STATUS_WRITE_PROTECT 0x80
#define STATUS_READY_BUSY 0x40
#define STATUS_ERASE_SUSPEND 0x20
#define STATUS_PASS_FAIL 0x01
//-----------------------------------------------------------------------------
// Constant definitions
//-----------------------------------------------------------------------------
#define NAND_SUCC (0)
#define NAND_FAIL (1)
#define NAND_ECC_ERROR (4)
#define NAND_CMD_ERROR (8)
#define NAND_INVALID_ARG (16)
#define POLLING_RETRY (512*512)
#define NAND_MAX_PAGE_SIZE (1024*8)
#define NAND_MAX_OOB_SIZE (64*8)
//-----------------------------------------------------------------------------
// Macros of register read/write
//-----------------------------------------------------------------------------
#if CC_NAND_60BIT_NFI
#define NAND_REG_BASE ((UINT32)0xF0029400)
#else
#define NAND_REG_BASE ((UINT32)0xF0029000)
#endif
#define NAND_READ16(offset) (*((volatile UINT16*)(NAND_REG_BASE + offset)))
#define NAND_READ32(offset) (*((volatile UINT32*)(NAND_REG_BASE + offset)))
#define NAND_WRITE32(offset, _val_) (*((volatile UINT32*)(NAND_REG_BASE + offset)) = (_val_))
#define NAND_IO_READ32(offset) (*((volatile UINT32*)(offset)))
#define NAND_IO_WRITE32(offset, _val_) (*((volatile UINT32*)(offset)) = (_val_))
#if defined(YES_BIMSWAP)
#define NAND_BIMSWAP(X) ((((X) & 0xf00) > 0x200) ? (X) : (((X) & 0xffffffeb) | (((X) & 0x10) >> 2) | (((X) & 0x4) << 2)))
#else
#define NAND_BIMSWAP(X) (X)
#endif
#define NAND_BIM_READ32(offset) (*((volatile UINT32*)(BIM_VIRT + NAND_BIMSWAP(offset))))
#define NAND_BIM_WRITE32(offset, _val_) (*((volatile UINT32*)(BIM_VIRT + NAND_BIMSWAP(offset))) = (_val_))
//-----------------------------------------------------------------------------
// Device information
//-----------------------------------------------------------------------------
#define NAND_BBMODE_BBMARK 0x0000FF00
#define NAND_BBMODE_ECCBIT 0x000000FF
typedef struct
{
CHAR acName[32];
UINT8 u1AddrCycle;
UINT32 u4IDVal;
UINT32 u4IDMask;
UINT32 u4PageSize;
UINT32 u4OOBSize;
UINT32 u4BBMode;
UINT32 u4BlkSize;
UINT32 u4BlkPgCount;
UINT32 u4ChipSize;
UINT32 u4AccCon;
UINT32 u4RdAcc;
} NAND_FLASH_DEV_T;
const static NAND_FLASH_DEV_T _arNand_DevInfo[] =
{
{ "SS K9F2808U0B", 3, 0x000073EC, 0x0000FFFF, 512, 16, 0x00000501, 0x04000, 32, 0x01000000, 0x00411888, 0x00080008},
{ "SS K9F5608U0B", 3, 0x000075EC, 0x0000FFFF, 512, 16, 0x00000501, 0x04000, 32, 0x02000000, 0x00411888, 0x00080008},
{ "SS K9F1208U0B/C", 4, 0x000076EC, 0x0000FFFF, 512, 16, 0x00000501, 0x04000, 32, 0x04000000, 0x00411888, 0x00080008},
{ "SS K9F1G08U0B/C/D", 4, 0x9500F1EC, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00433322, 0x00050005},
{ "SS K9F2G08U0B/C", 5, 0x9510DAEC, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00433322, 0x00050005},
{ "SS K9F4G08U0B/D", 5, 0x9510DCEC, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x20000000, 0x00433322, 0x00050005},
{ "SS K9K8G08U0D", 5, 0x9551D3EC, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x40000000, 0x00433322, 0x00050005},
{ "SS K9F8G08U0M", 5, 0xA610D3EC, 0xFFFFFFFF, 4096, 16, 0x00000001, 0x40000, 64, 0x40000000, 0x00433322, 0x00050005},
{ "SS K9GAG08U0E", 5, 0x7284D5EC, 0xFFFFFFFF, 8192, 26, 0x00000018, 0x100000, 128, 0x80000000, 0x00433322, 0x00050005},
{ "SS K9GAG08U0F", 5, 0x7694D5EC, 0xFFFFFFFF, 8192, 26, 0x00000018, 0x100000, 128, 0x80000000, 0x00433322, 0x00050005},
//1.8V nand
{ "SS KF91G08Q2V", 5, 0x1900A1EC, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00433322, 0x00050005},
{ "SS KF92G08Q2V", 5, 0x1900AAEC, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00433322, 0x00050005},
{ "SS 1Gb", 4, 0x0000F1EC, 0x0000FFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00411888, 0x00080008},
{ "NAND128W3A2B", 3, 0x00007320, 0x0000FFFF, 512, 16, 0x00000501, 0x04000, 32, 0x01000000, 0x00411888, 0x00080008},
{ "NAND256W3A2B", 3, 0x00007520, 0x0000FFFF, 512, 16, 0x00000501, 0x04000, 32, 0x02000000, 0x00411888, 0x00080008},
{ "NAND512W3A2B/D", 4, 0x00007620, 0x0000FFFF, 512, 16, 0x00000501, 0x04000, 32, 0x04000000, 0x00411888, 0x00080008},
{ "NAND01GW3B2B", 4, 0x1D80F120, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00411888, 0x00080008},
{ "NAND01GW3B2C", 4, 0x1D00F120, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00433322, 0x00050005},
{ "NAND02GW3B2C", 5, 0x1D80DA20, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00411888, 0x00080008},
{ "NAND02GW3B2D", 5, 0x9510DA20, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00433322, 0x00050005},
{ "NAND04GW3B2B", 5, 0x9580DC20, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x20000000, 0x00411888, 0x00080008},
{ "NAND04GW3B2D", 5, 0x9510DC20, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x20000000, 0x00411888, 0x00080008},
{ "NAND08GW3B2C", 5, 0x9551D320, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x40000000, 0x00411888, 0x00080008},
{ "NAND08GW3C2B/16GW3C4B", 5, 0xA514D320, 0xFFFFFFFF, 2048, 16, 0x00000008, 0x40000, 128, 0x40000000, 0x00411888, 0x00080008},
{ "NAND08GW3F2A", 5, 0xA610D320, 0xFFFFFFFF, 4096, 16, 0x00000001, 0x40000, 64, 0x40000000, 0x00433322, 0x00050005},
{ "ST 1Gb", 4, 0x0000F120, 0x0000FFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00411888, 0x00080008},
{ "ST 2Gb", 5, 0x0000DA20, 0x0000FFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00411888, 0x00080008},
{ "ST 4Gb", 5, 0x0000DC20, 0x0000FFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x20000000, 0x00411888, 0x00080008},
{ "ST 8Gb", 5, 0x0000D320, 0x0000FFFF, 4096, 16, 0x00000001, 0x40000, 64, 0x40000000, 0x00411888, 0x00080008},
{ "HY27US08281A", 3, 0x000073AD, 0x0000FFFF, 512, 16, 0x00000501, 0x04000, 32, 0x01000000, 0x00411888, 0x00080008},
{ "HY27US08561A", 3, 0x000075AD, 0x0000FFFF, 512, 16, 0x00000501, 0x04000, 32, 0x02000000, 0x00411888, 0x00080008},
{ "H27U518S2CTR/P", 4, 0x000076AD, 0x0000FFFF, 512, 16, 0x00000001, 0x04000, 32, 0x04000000, 0x00433322, 0x00050005},
{ "HY27UF081G2A", 4, 0x1D80F1AD, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00411888, 0x00080008},
{ "HY27U1G8F2BTR", 4, 0x1D00F1AD, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00433322, 0x00050005},
{ "HY27UF082G2B", 5, 0x9510DAAD, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00433322, 0x00050005},
{ "HY27U2G8F2CTR", 5, 0x9590DAAD, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00433322, 0x00050005},
{ "HY27U4G8F2DTR", 5, 0x9590DCAD, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x20000000, 0x00433433, 0x00060006},
{ "HY27UF084G2B", 5, 0x9510DCAD, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x20000000, 0x00433322, 0x00050005},
{ "HY27UT088G2A", 5, 0xA514D3AD, 0xFFFFFFFF, 2048, 16, 0x00000008, 0x40000, 128, 0x40000000, 0x00411888, 0x00080008},
{ "H27U8G8T2BTR", 5, 0xB614D3AD, 0xFFFFFFFF, 4096, 16, 0x00000008, 0x80000, 128, 0x40000000, 0x00433322, 0x00050005},
{ "H27UAG8T2MTR", 5, 0xB614D5AD, 0xFFFFFFFF, 4096, 16, 0x00000008, 0x80000, 128, 0x80000000, 0x00433322, 0x00050005},
{ "H27UAG8T2ATR", 5, 0x2594D5AD, 0xFFFFFFFF, 4096, 26, 0x00000018, 0x80000, 128, 0x80000000, 0x00433322, 0x00050005},
{ "H27UAG8T2BTR", 5, 0x9A94D5AD, 0xFFFFFFFF, 8192, 26, 0x00000018, 0x200000, 256, 0x80000000, 0x00433322, 0x00050005},
{ "HYNIX 1Gb", 4, 0x0000F1AD, 0x0000FFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00411888, 0x00080008},
{ "HYNIX 2Gb", 5, 0x0000DAAD, 0x0000FFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00411888, 0x00080008},
{ "HYNIX 4Gb", 5, 0x0000DCAD, 0x0000FFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x20000000, 0x00411888, 0x00080008},
{ "HYNIX 8Gb", 5, 0x0000D3AD, 0x0000FFFF, 2048, 16, 0x00000001, 0x40000, 128, 0x40000000, 0x00411888, 0x00080008},
{ "MT29F1G08AAC/ABAD/EA", 4, 0x9580F12C, 0xFFFFFFFF, 2048, 16, 0x00000008, 0x20000, 64, 0x08000000, 0x00433322, 0x00050005},
{ "MT29F2G08AAD", 5, 0x9580DA2C, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00433322, 0x00050005},
{ "MT29F2G08ABAE/FA", 5, 0x9590DA2C, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00433322, 0x00050005},
{ "MT29F4G08ABADA", 5, 0x9590DC2C, 0xFFFFFFFF, 2048, 16, 0x00000008, 0x20000, 64, 0x20000000, 0x00433322, 0x00050005},
{ "MT29F4G08ABAEA", 5, 0xA690DC2C, 0xFFFFFFFF, 4096, 26, 0x00000008, 0x40000, 64, 0x20000000, 0x00433322, 0x00050005},
{ "MT29F8G08ABABA", 5, 0x2600382C, 0xFFFFFFFF, 4096, 26, 0x00000008, 0x80000, 128, 0x40000000, 0x00433322, 0x00050005},
{ "MT29F16G08CBABA", 5, 0x4604482C, 0xFFFFFFFF, 4096, 26, 0x00000018, 0x100000, 256, 0x80000000, 0x00433322, 0x00050005},
{ "MT29F16G08CBACA", 5, 0x4A04482C, 0xFFFFFFFF, 4096, 26, 0x00000018, 0x100000, 256, 0x80000000, 0x00433999, 0x00080008},
{ "Micron 1Gb", 4, 0x0000F12C, 0x0000FFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00411888, 0x00080008},
{ "Micron 2Gb", 5, 0x0000DA2C, 0x0000FFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00411888, 0x00080008},
{ "Micron 16GB", 5, 0x0000D92C, 0x0000FFFF, 4096, 26, 0x00000004, 0x80000, 128, 0x80000000, 0x00411888, 0x00080008},
{ "TC58DVM92A5TAI0/J0", 4, 0x00007698, 0x0000FFFF, 512, 16, 0x00000501, 0x04000, 32, 0x04000000, 0x00433322, 0x00050005},
{ "TC58NVM9S3ETA00/I0", 4, 0x1500F098, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x04000000, 0x00433322, 0x00050005},
{ "TC58NVG0S3ETA00", 4, 0x1590D198, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00433322, 0x00050005},
{ "TC58NVG0S3ETA0B", 4, 0x1590F198, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00433322, 0x00050005},
{ "TC58NVG0S3HTA00", 4, 0x1580F198, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00433322, 0x00050005},
{ "TC58NVG1S3E/HTA00/I0", 5, 0x1590DA98, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x10000000, 0x00433322, 0x00050005},
{ "TC58NVG2S3ETA00/I0", 5, 0x1590DC98, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x20000000, 0x00433322, 0x00050005},
{ "TC58NVG2S0FTA00/I0", 5, 0x2690DC98, 0xFFFFFFFF, 4096, 26, 0x00000008, 0x40000, 64, 0x20000000, 0x00433322, 0x00050005},
{ "TC58D/NVG3S0E/FTA00", 5, 0x2690D398, 0xFFFFFFFF, 4096, 16, 0x00000008, 0x40000, 64, 0x40000000, 0x00433322, 0x00050005},
{ "TC58NVG4D2FTA00", 5, 0x3294D598, 0xFFFFFFFF, 8192, 26, 0x00000018, 0x100000, 128, 0x80000000, 0x00433322, 0x00050005},
{ "TH58NVG7DDJTA20", 5, 0x9394DE98, 0xFFFFFFFF, 16384,32, 0x00000018, 0x400000, 256, 0xFFFFFFFF, 0x00433322, 0x00050005},
{ "MX30LF1G08AM-TIB", 4, 0x1D80F1C2, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00433322, 0x00050005},
{ "S34ML04G100TFI000", 5, 0x9590DC01, 0xFFFFFFFF, 2048, 16, 0x00000001, 0x20000, 64, 0x20000000, 0x00433322, 0x00050005},
{ "Small 16MB", 3, 0x00007300, 0x0000FF00, 512, 16, 0x00000501, 0x04000, 32, 0x01000000, 0x00411888, 0x00080008},
{ "Small 32MB", 3, 0x00007500, 0x0000FF00, 512, 16, 0x00000501, 0x04000, 32, 0x02000000, 0x00411888, 0x00080008},
{ "Small 64MB", 4, 0x00007600, 0x0000FF00, 512, 16, 0x00000501, 0x04000, 32, 0x04000000, 0x00411888, 0x00080008},
{ "Small 128MB", 4, 0x00007900, 0x0000FF00, 512, 16, 0x00000501, 0x04000, 32, 0x08000000, 0x00411888, 0x00080008},
{ "Large 128MB", 4, 0x0000F100, 0x0000FF00, 2048, 16, 0x00000001, 0x20000, 64, 0x08000000, 0x00411888, 0x00080008},
};
#endif /* NAND_REG_H */
| 63.777953 | 137 | 0.577767 |
be80adc3a2b7de1927e8d94ed8ce7dcc021d4242 | 537 | h | C | include/dtrace/fasttrap_ioctl.h | MrCull/dtrace-utils | 187c56aa3f781c63e8e393010682f1414c42fa95 | [
"UPL-1.0"
] | null | null | null | include/dtrace/fasttrap_ioctl.h | MrCull/dtrace-utils | 187c56aa3f781c63e8e393010682f1414c42fa95 | [
"UPL-1.0"
] | null | null | null | include/dtrace/fasttrap_ioctl.h | MrCull/dtrace-utils | 187c56aa3f781c63e8e393010682f1414c42fa95 | [
"UPL-1.0"
] | null | null | null | /*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
*/
#ifndef _DTRACE_FASTRRAP_IOCTL_H_
#define _DTRACE_FASTTRAP_IOCTL_H_
#include <linux/ioctl.h>
#include <dtrace/fasttrap.h>
#define FASTTRAPIOC 0xf4
#define FASTTRAPIOC_MAKEPROBE _IOW(FASTTRAPIOC, 1, fasttrap_probe_spec_t)
#define FASTTRAPIOC_GETINSTR _IOR(FASTTRAPIOC, 2, fasttrap_instr_query_t)
#endif /* _DTRACE_FASTTRAP_IOCTL_H_ */
| 28.263158 | 79 | 0.783985 |
db66503fca93c75463e7162a449f50777d01b844 | 27,896 | c | C | src/supplemental/mqtt/mqtt_qos_db.c | nanomq/NanoNNG | d770acd6b2f13406ec6aacb31c2bb316b04ce9c5 | [
"MIT"
] | 3 | 2022-03-05T04:22:43.000Z | 2022-03-22T12:39:18.000Z | src/supplemental/mqtt/mqtt_qos_db.c | nanomq/NanoNNG | d770acd6b2f13406ec6aacb31c2bb316b04ce9c5 | [
"MIT"
] | 19 | 2022-02-18T11:16:05.000Z | 2022-03-26T03:13:43.000Z | src/supplemental/mqtt/mqtt_qos_db.c | nanomq/NanoNNG | d770acd6b2f13406ec6aacb31c2bb316b04ce9c5 | [
"MIT"
] | 2 | 2022-02-11T09:33:38.000Z | 2022-03-05T03:43:31.000Z | #include "mqtt_qos_db.h"
#include "core/nng_impl.h"
#include "nng/nng.h"
#include "nng/supplemental/sqlite/sqlite3.h"
#include "supplemental/mqtt/mqtt_msg.h"
#define table_main "t_main"
#define table_msg "t_msg"
#define table_pipe_client "t_pipe_client"
#define table_client_msg "t_client_msg"
#define table_client_offline_msg "t_client_offline_msg"
static uint8_t *nni_msg_serialize(nni_msg *msg, size_t *out_len);
static nni_msg *nni_msg_deserialize(uint8_t *bytes, size_t len);
static uint8_t *nni_mqtt_msg_serialize(nni_msg *msg, size_t *out_len);
static nni_msg *nni_mqtt_msg_deserialize(
uint8_t *bytes, size_t len, bool aio_available);
static int create_msg_table(sqlite3 *db);
static int create_pipe_client_table(sqlite3 *db);
static int create_main_table(sqlite3 *db);
static int create_client_msg_table(sqlite3 *db);
static int create_client_offline_msg_table(sqlite3 *db);
static int64_t get_id_by_msg(sqlite3 *db, nni_msg *msg);
static int64_t insert_msg(sqlite3 *db, nni_msg *msg);
static int64_t get_id_by_pipe(sqlite3 *db, uint32_t pipe_id);
static int64_t get_id_by_client_id(sqlite3 *db, const char *client_id);
static int get_id_by_p_id(sqlite3 *db, int64_t p_id, uint16_t packet_id,
uint8_t *out_qos, int64_t *out_m_id);
static int insert_main(
sqlite3 *db, int64_t p_id, uint16_t packet_id, uint8_t qos, int64_t m_id);
static int update_main(
sqlite3 *db, int64_t p_id, uint16_t packet_id, uint8_t qos, int64_t m_id);
static void set_main(sqlite3 *db, uint32_t pipe_id, uint16_t packet_id,
uint8_t qos, nni_msg *msg);
static int
create_client_msg_table(sqlite3 *db)
{
char sql[] = "CREATE TABLE IF NOT EXISTS " table_client_msg ""
" (id INTEGER PRIMARY KEY AUTOINCREMENT, "
" packet_id INTEGER NOT NULL, "
" pipe_id INTEGER NOT NULL, "
" data BLOB)";
return sqlite3_exec(db, sql, 0, 0, 0);
}
static int
create_client_offline_msg_table(sqlite3 *db)
{
char sql[] = "CREATE TABLE IF NOT EXISTS " table_client_offline_msg ""
" (id INTEGER PRIMARY KEY AUTOINCREMENT, "
" data BLOB)";
return sqlite3_exec(db, sql, 0, 0, 0);
}
static int
create_msg_table(sqlite3 *db)
{
char sql[] = "CREATE TABLE IF NOT EXISTS " table_msg ""
" (id INTEGER PRIMARY KEY AUTOINCREMENT, "
" data BLOB)";
return sqlite3_exec(db, sql, 0, 0, 0);
}
static int
create_pipe_client_table(sqlite3 *db)
{
char sql[] = "CREATE TABLE IF NOT EXISTS " table_pipe_client ""
"(id INTEGER PRIMARY KEY AUTOINCREMENT, "
" pipe_id INTEGER NOT NULL, "
" client_id TEXT NOT NULL)";
return sqlite3_exec(db, sql, 0, 0, 0);
}
static int
create_main_table(sqlite3 *db)
{
char sql[] = "CREATE TABLE IF NOT EXISTS " table_main ""
"(id INTEGER PRIMARY KEY AUTOINCREMENT,"
" p_id INTEGER NOT NULL, "
" packet_id INTEGER NOT NULL, "
" qos TINYINT NOT NULL , "
" m_id INTEGER NOT NULL )";
return sqlite3_exec(db, sql, 0, 0, 0);
}
void
nni_mqtt_qos_db_init(sqlite3 **db, const char *db_name, bool is_broker)
{
char pwd[512] = { 0 };
char path[1024] = { 0 };
if (getcwd(pwd, sizeof(pwd)) != NULL) {
sprintf(path, "%s/%s", pwd, db_name);
if (sqlite3_open(path, db) != 0) {
return;
}
if (is_broker) {
if (create_msg_table(*db) != 0) {
return;
}
if (create_pipe_client_table(*db) != 0) {
return;
}
if (create_main_table(*db) != 0) {
return;
}
} else {
if (create_client_msg_table(*db) != 0) {
return;
}
if (create_client_offline_msg_table(*db) != 0) {
return;
}
}
}
}
void
nni_mqtt_qos_db_close(sqlite3 *db)
{
sqlite3_close(db);
}
// static char *
// bytes2Hex(uint8_t *bytes, size_t sz)
// {
// char *hex = nng_zalloc(sz * 2 + 1);
// char *p = hex;
// for (size_t i = 0; i < sz; i++) {
// p += sprintf(p, "%.2x", bytes[i]);
// }
// return hex;
// }
static int64_t
get_id_by_msg(sqlite3 *db, nni_msg *msg)
{
int64_t id = 0;
sqlite3_stmt *stmt;
size_t len = 0;
uint8_t * blob = nni_msg_serialize(msg, &len);
char sql[] = "SELECT id FROM " table_msg " where data = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_blob64(stmt, 1, blob, len, SQLITE_TRANSIENT);
if (SQLITE_ROW == sqlite3_step(stmt)) {
id = sqlite3_column_int64(stmt, 0);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
nng_free(blob, len);
return id;
}
static int64_t
insert_msg(sqlite3 *db, nni_msg *msg)
{
int64_t id = 0;
sqlite3_stmt *stmt;
char * sql = "INSERT INTO " table_msg " (data) VALUES (?)";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
size_t len = 0;
uint8_t *blob = nni_msg_serialize(msg, &len);
sqlite3_bind_blob64(stmt, 1, blob, len, SQLITE_TRANSIENT);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
nng_free(blob, len);
id = sqlite3_last_insert_rowid(db);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
return id;
}
static int64_t
get_id_by_pipe(sqlite3 *db, uint32_t pipe_id)
{
int64_t id = 0;
sqlite3_stmt *stmt;
char sql[] = "SELECT id FROM " table_pipe_client " WHERE pipe_id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, pipe_id);
if (SQLITE_ROW == sqlite3_step(stmt)) {
id = sqlite3_column_int64(stmt, 0);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
return id;
}
static int64_t
get_id_by_client_id(sqlite3 *db, const char *client_id)
{
int64_t id = 0;
sqlite3_stmt *stmt;
char sql[] =
"SELECT id FROM " table_pipe_client " WHERE client_id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_text(
stmt, 1, client_id, strlen(client_id), SQLITE_TRANSIENT);
if (SQLITE_ROW == sqlite3_step(stmt)) {
id = sqlite3_column_int64(stmt, 0);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
return id;
}
static int
get_id_by_p_id(sqlite3 *db, int64_t p_id, uint16_t packet_id, uint8_t *out_qos,
int64_t *out_m_id)
{
int64_t id = 0;
sqlite3_stmt *stmt;
char sql[] = "SELECT id, qos, m_id FROM " table_main
" WHERE p_id = ? AND packet_id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, p_id);
sqlite3_bind_int(stmt, 2, packet_id);
if (SQLITE_ROW == sqlite3_step(stmt)) {
id = sqlite3_column_int64(stmt, 0);
*out_qos = sqlite3_column_int(stmt, 1);
*out_m_id = sqlite3_column_int64(stmt, 2);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
return id;
}
static int
insert_main(
sqlite3 *db, int64_t p_id, uint16_t packet_id, uint8_t qos, int64_t m_id)
{
sqlite3_stmt *stmt;
char * sql = "INSERT INTO " table_main ""
" (p_id, packet_id, qos, m_id) VALUES (?, ?, ?, ?)";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, p_id);
sqlite3_bind_int(stmt, 2, packet_id);
sqlite3_bind_int(stmt, 3, qos);
sqlite3_bind_int64(stmt, 4, m_id);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
static int
update_main(
sqlite3 *db, int64_t p_id, uint16_t packet_id, uint8_t qos, int64_t m_id)
{
sqlite3_stmt *stmt;
char * sql = "UPDATE " table_main ""
" SET qos = ?, m_id = ? WHERE p_id = ? AND packet_id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int(stmt, 1, qos);
sqlite3_bind_int64(stmt, 2, m_id);
sqlite3_bind_int64(stmt, 3, p_id);
sqlite3_bind_int(stmt, 4, packet_id);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_insert_pipe(
sqlite3 *db, uint32_t pipe_id, const char *client_id)
{
sqlite3_stmt *stmt;
char * sql = "INSERT INTO " table_pipe_client ""
" (pipe_id, client_id) VALUES (?, ?)";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, pipe_id);
sqlite3_bind_text(
stmt, 2, client_id, strlen(client_id), SQLITE_TRANSIENT);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_remove_pipe(sqlite3 *db, uint32_t pipe_id)
{
sqlite3_stmt *stmt;
char * sql = "DELETE FROM " table_pipe_client ""
" where pipe_id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, pipe_id);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_update_pipe_by_clientid(
sqlite3 *db, uint32_t pipe_id, const char *client_id)
{
sqlite3_stmt *stmt;
char * sql = "UPDATE " table_pipe_client " SET pipe_id = ?"
" where client_id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, pipe_id);
sqlite3_bind_text(
stmt, 2, client_id, strlen(client_id), SQLITE_TRANSIENT);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_set_pipe(sqlite3 *db, uint32_t pipe_id, const char *client_id)
{
int64_t id = get_id_by_client_id(db, client_id);
if (id == 0) {
nni_mqtt_qos_db_insert_pipe(db, pipe_id, client_id);
} else {
nni_mqtt_qos_db_update_pipe_by_clientid(
db, pipe_id, client_id);
}
}
void
nni_mqtt_qos_db_update_all_pipe(sqlite3 *db, uint32_t pipe_id)
{
sqlite3_stmt *stmt;
char * sql = "UPDATE " table_pipe_client " SET pipe_id = ?"
" where id > 0";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, pipe_id);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_remove_msg(sqlite3 *db, nni_msg *msg)
{
sqlite3_stmt *stmt;
char * sql = "DELETE FROM " table_msg " WHERE data = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
size_t len = 0;
uint8_t *blob = nni_msg_serialize(msg, &len);
sqlite3_bind_blob64(stmt, 1, blob, len, SQLITE_TRANSIENT);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
nng_free(blob, len);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_remove_all_msg(sqlite3 *db)
{
char *sql = "UPDATE " table_main " SET m_id = 0 WHERE m_id > 0;"
"DELETE FROM " table_msg " WHERE id > 0;";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_exec(db, sql, 0, 0, NULL);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_check_remove_msg(sqlite3 *db, nni_msg *msg)
{
sqlite3_stmt *stmt;
// remove the msg if it was not referenced by table `t_main`
char sql[] = "DELETE FROM " table_msg " AS msg WHERE "
"( SELECT COUNT(main.id) FROM " table_main " AS main "
"WHERE m_id = "
"( SELECT msg.id FROM t_msg "
"AS msg WHERE data = ? )) = 0 AND msg.data = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
size_t len = 0;
uint8_t *blob = nni_msg_serialize(msg, &len);
sqlite3_bind_blob64(stmt, 1, blob, len, SQLITE_TRANSIENT);
sqlite3_bind_blob64(stmt, 2, blob, len, SQLITE_TRANSIENT);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
nng_free(blob, len);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_remove_unused_msg(sqlite3 *db)
{
sqlite3_stmt *stmt;
// remove the msg if it was not referenced by table `t_main`
char sql[] = "DELETE FROM " table_msg
" WHERE id NOT IN (SELECT m_id FROM t_main)";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_set(
sqlite3 *db, uint32_t pipe_id, uint16_t packet_id, nni_msg *msg)
{
uint8_t qos = MQTT_DB_GET_QOS_BITS(msg);
nni_msg *m = MQTT_DB_GET_MSG_POINTER(msg);
set_main(db, pipe_id, packet_id, qos, m);
}
static void
set_main(sqlite3 *db, uint32_t pipe_id, uint16_t packet_id, uint8_t qos,
nni_msg *msg)
{
int64_t p_id = get_id_by_pipe(db, pipe_id);
if (p_id == 0) {
// can not find client
return;
}
int64_t msg_id = get_id_by_msg(db, msg);
if (msg_id == 0) {
msg_id = insert_msg(db, msg);
}
uint8_t main_qos = 0;
int64_t main_m_id = 0;
int64_t main_id =
get_id_by_p_id(db, p_id, packet_id, &main_qos, &main_m_id);
if (main_id == 0) {
insert_main(db, p_id, packet_id, qos, msg_id);
} else {
if (main_qos != qos || main_m_id != msg_id) {
update_main(db, p_id, packet_id, qos, msg_id);
}
}
}
nni_msg *
nni_mqtt_qos_db_get(sqlite3 *db, uint32_t pipe_id, uint16_t packet_id)
{
nni_msg * msg = NULL;
uint8_t qos = 0;
sqlite3_stmt *stmt;
char sql[] =
"SELECT main.qos, msg.data FROM " table_pipe_client ""
" AS pipe JOIN "
"" table_main " AS main ON main.p_id = pipe.id JOIN " table_msg ""
" AS msg ON main.m_id = msg.id "
"WHERE pipe.pipe_id = ? AND main.packet_id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, pipe_id);
sqlite3_bind_int64(stmt, 2, packet_id);
if (SQLITE_ROW == sqlite3_step(stmt)) {
qos = sqlite3_column_int(stmt, 0);
size_t nbyte = (size_t) sqlite3_column_bytes16(stmt, 1);
uint8_t *bytes = sqlite3_malloc(nbyte);
memcpy(bytes, sqlite3_column_blob(stmt, 1), nbyte);
// deserialize blob data to nni_msg
msg = nni_msg_deserialize(bytes, nbyte);
msg = MQTT_DB_PACKED_MSG_QOS(msg, qos);
sqlite3_free(bytes);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
return msg;
}
nni_msg *
nni_mqtt_qos_db_get_one(sqlite3 *db, uint32_t pipe_id, uint16_t *packet_id)
{
nni_msg * msg = NULL;
uint8_t qos = 0;
sqlite3_stmt *stmt;
char sql[] =
"SELECT main.packet_id, main.qos, msg.data FROM " table_pipe_client
" AS pipe JOIN "
"" table_main " AS main ON main.p_id = pipe.id JOIN " table_msg ""
" AS msg ON "
" main.m_id = msg.id WHERE pipe.pipe_id = ? AND main.m_id > 0 "
"LIMIT 1";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int(stmt, 1, pipe_id);
if (SQLITE_ROW == sqlite3_step(stmt)) {
*packet_id = sqlite3_column_int64(stmt, 0);
qos = sqlite3_column_int(stmt, 1);
size_t nbyte = (size_t) sqlite3_column_bytes16(stmt, 2);
uint8_t *bytes = sqlite3_malloc(nbyte);
memcpy(bytes, sqlite3_column_blob(stmt, 2), nbyte);
// deserialize blob data to nni_msg
msg = nni_msg_deserialize(bytes, nbyte);
msg = MQTT_DB_PACKED_MSG_QOS(msg, qos);
sqlite3_free(bytes);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
return msg;
}
void
nni_mqtt_qos_db_remove(sqlite3 *db, uint32_t pipe_id, uint16_t packet_id)
{
sqlite3_stmt *stmt;
char *sql = "DELETE FROM " table_main " AS main WHERE main.p_id = "
"(SELECT pipe.id FROM " table_pipe_client ""
" AS pipe where pipe.pipe_id = ? AND packet_id = ?)";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int(stmt, 1, pipe_id);
sqlite3_bind_int(stmt, 2, packet_id);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_remove_by_pipe(sqlite3 *db, uint32_t pipe_id)
{
sqlite3_stmt *stmt;
char *sql = "DELETE FROM " table_main " AS main WHERE main.p_id = "
"(SELECT pipe.id FROM " table_pipe_client ""
" AS pipe where pipe.pipe_id = ?)";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int(stmt, 1, pipe_id);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_foreach(sqlite3 *db, nni_idhash_cb cb)
{
sqlite3_stmt *stmt;
char sql[] =
"SELECT pipe.pipe_id, msg.data FROM " table_main " AS main JOIN "
" " table_msg
" AS msg ON main.m_id = msg.id JOIN " table_pipe_client " "
" AS pipe ON main.p_id = pipe.id";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
while (SQLITE_ROW == sqlite3_step(stmt)) {
uint32_t pipe_id = sqlite3_column_int64(stmt, 0);
size_t nbyte = (size_t) sqlite3_column_bytes16(stmt, 1);
uint8_t *bytes = sqlite3_malloc(nbyte);
memcpy(bytes, sqlite3_column_blob(stmt, 1), nbyte);
// deserialize blob data to nni_msg
nni_msg *msg = nni_msg_deserialize(bytes, nbyte);
cb(&pipe_id, msg);
if (msg) {
nni_msg_free(msg);
}
sqlite3_free(bytes);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
int
nni_mqtt_qos_db_set_client_msg(
sqlite3 *db, uint32_t pipe_id, uint16_t packet_id, nni_msg *msg)
{
char sql[] =
"INSERT INTO " table_client_msg " ( pipe_id, packet_id, data ) "
"VALUES (?, ?, ?)";
size_t len = 0;
uint8_t *blob = nni_mqtt_msg_serialize(msg, &len);
if (!blob) {
printf("nni_mqtt_msg_serialize failed\n");
return -1;
}
sqlite3_stmt *stmt;
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int(stmt, 1, pipe_id);
sqlite3_bind_int64(stmt, 2, packet_id);
sqlite3_bind_blob64(stmt, 3, blob, len, SQLITE_TRANSIENT);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
nng_free(blob, len);
int rv = sqlite3_exec(db, "COMMIT;", 0, 0, 0);
nni_msg_free(msg);
return rv;
}
nni_msg *
nni_mqtt_qos_db_get_client_msg(sqlite3 *db, uint32_t pipe_id, uint16_t packet_id)
{
nni_msg * msg = NULL;
sqlite3_stmt *stmt;
char sql[] = "SELECT data FROM " table_client_msg ""
" WHERE pipe_id = ? AND packet_id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, pipe_id);
sqlite3_bind_int(stmt, 2, packet_id);
if (SQLITE_ROW == sqlite3_step(stmt)) {
size_t nbyte = (size_t) sqlite3_column_bytes16(stmt, 0);
uint8_t *bytes = sqlite3_malloc(nbyte);
memcpy(bytes, sqlite3_column_blob(stmt, 0), nbyte);
// deserialize blob data to nni_msg
msg = nni_mqtt_msg_deserialize(
bytes, nbyte, pipe_id > 0 ? true : false);
sqlite3_free(bytes);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
return msg;
}
void
nni_mqtt_qos_db_remove_client_msg(
sqlite3 *db, uint32_t pipe_id, uint16_t packet_id)
{
sqlite3_stmt *stmt;
char sql[] =
"DELETE FROM " table_client_msg " WHERE pipe_id = ? AND packet_id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, pipe_id);
sqlite3_bind_int(stmt, 2, packet_id);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_remove_client_msg_by_id(sqlite3 *db, uint64_t id)
{
sqlite3_stmt *stmt;
char sql[] = "DELETE FROM " table_client_msg " WHERE id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, id);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
void
nni_mqtt_qos_db_reset_client_msg_pipe_id(sqlite3 *db)
{
sqlite3_stmt *stmt;
char sql[] = "UPDATE " table_client_msg " SET pipe_id = 0";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
nni_msg *
nni_mqtt_qos_db_get_one_client_msg(sqlite3 *db, uint64_t *id, uint16_t *packet_id)
{
nni_msg * msg = NULL;
sqlite3_stmt *stmt;
char sql[] =
"SELECT id, pipe_id, packet_id, data FROM " table_client_msg
" ORDER BY id LIMIT 1";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
if (SQLITE_ROW == sqlite3_step(stmt)) {
*id = (uint64_t) sqlite3_column_int64(stmt, 0);
uint32_t pipe_id = sqlite3_column_int64(stmt, 1);
*packet_id = sqlite3_column_int(stmt, 2);
size_t nbyte = (size_t) sqlite3_column_bytes16(stmt, 3);
uint8_t *bytes = sqlite3_malloc(nbyte);
memcpy(bytes, sqlite3_column_blob(stmt, 3), nbyte);
// deserialize blob data to nni_msg
msg = nni_mqtt_msg_deserialize(
bytes, nbyte, pipe_id > 0 ? true : false);
sqlite3_free(bytes);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
return msg;
}
/**
* @brief serialize msg into sqlite db as KV, and free the original msg no
* matter it is successed or not
* only use this with mqtt_ctx
* @param db
* @param msg
* @return int
*/
int
nni_mqtt_qos_db_set_client_offline_msg(sqlite3 *db, nni_msg *msg)
{
char sql[] = "INSERT INTO " table_client_offline_msg " ( data ) "
"VALUES ( ? )";
size_t len = 0;
uint8_t *blob = nni_mqtt_msg_serialize(msg, &len);
if (!blob) {
printf("nni_mqtt_msg_serialize failed\n");
nni_msg_free(msg);
return -1;
}
sqlite3_stmt *stmt;
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_blob64(stmt, 1, blob, len, SQLITE_TRANSIENT);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
nng_free(blob, len);
int rv = sqlite3_exec(db, "COMMIT;", 0, 0, 0);
nni_msg_free(msg);
return rv;
}
nng_msg *
nni_mqtt_qos_db_get_client_offline_msg(sqlite3 *db, int64_t *row_id)
{
nni_msg * msg = NULL;
sqlite3_stmt *stmt;
char sql[] = "SELECT id, data FROM " table_client_offline_msg
" ORDER BY id ASC LIMIT 1 ";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
if (SQLITE_ROW == sqlite3_step(stmt)) {
*row_id = sqlite3_column_int64(stmt, 0);
size_t nbyte = (size_t) sqlite3_column_bytes16(stmt, 1);
uint8_t *bytes = sqlite3_malloc(nbyte);
memcpy(bytes, sqlite3_column_blob(stmt, 1), nbyte);
// deserialize blob data to nni_msg
msg = nni_mqtt_msg_deserialize(bytes, nbyte, false);
sqlite3_free(bytes);
}
sqlite3_finalize(stmt);
sqlite3_exec(db, "COMMIT;", 0, 0, 0);
return msg;
}
int
nni_mqtt_qos_db_remove_client_offline_msg(sqlite3 *db, int64_t row_id)
{
sqlite3_stmt *stmt;
char sql[] = "DELETE FROM " table_client_offline_msg " WHERE id = ?";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_bind_int64(stmt, 1, row_id);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
int
nni_mqtt_qos_db_remove_all_client_offline_msg(sqlite3 *db)
{
sqlite3_stmt *stmt;
char sql[] = "DELETE FROM " table_client_offline_msg "";
sqlite3_exec(db, "BEGIN;", 0, 0, 0);
sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, 0);
sqlite3_reset(stmt);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return sqlite3_exec(db, "COMMIT;", 0, 0, 0);
}
static uint8_t *
nni_mqtt_msg_serialize(nni_msg *msg, size_t *out_len)
{
// int rv;
// if ((rv = nni_mqtt_msg_encode(msg)) != 0) {
// printf("nni_mqtt_msg_encode failed: %d\n", rv);
// return NULL;
// }
nni_mqtt_msg_encode(msg);
size_t len = nni_msg_header_len(msg) + nni_msg_len(msg) +
(sizeof(uint32_t) * 2) + sizeof(nni_time) + sizeof(nni_aio *);
*out_len = len;
// bytes:
// header: header_len(uint32) + header(header_len)
// body: body_len(uint32) + body(body_len)
// time: nni_time(uint64)
// aio: address value
uint8_t *bytes = nng_zalloc(len);
struct pos_buf buf = { .curpos = &bytes[0], .endpos = &bytes[len] };
if (write_uint32(nni_msg_header_len(msg), &buf) != 0) {
goto out;
}
if (write_bytes(nni_msg_header(msg), nni_msg_header_len(msg), &buf) !=
0) {
goto out;
}
if (write_uint32(nni_msg_len(msg), &buf) != 0) {
goto out;
}
if (write_bytes(nni_msg_body(msg), nni_msg_len(msg), &buf) != 0) {
goto out;
}
if (write_uint64(nni_msg_get_timestamp(msg), &buf) != 0) {
goto out;
}
nni_aio *aio = NULL;
if ((aio = nni_mqtt_msg_get_aio(msg)) != NULL) {
write_uint64((uint64_t) aio, &buf);
} else {
write_uint64((uint64_t) 0UL, &buf);
}
return bytes;
out:
free(bytes);
return NULL;
}
static nni_msg *
nni_mqtt_msg_deserialize(uint8_t *bytes, size_t len, bool aio_available)
{
nni_msg *msg;
if (nni_mqtt_msg_alloc(&msg, 0) != 0) {
return NULL;
}
struct pos_buf buf = { .curpos = &bytes[0], .endpos = &bytes[len] };
// bytes:
// header: header_len(uint32) + header(header_len)
// body: body_len(uint32) + body(body_len)
// time: nni_time(uint64)
// aio: address value
uint32_t header_len;
if (read_uint32(&buf, &header_len) != 0) {
goto out;
}
nni_msg_header_append(msg, buf.curpos, header_len);
buf.curpos += header_len;
uint32_t body_len;
if (read_uint32(&buf, &body_len) != 0) {
goto out;
}
nni_msg_append(msg, buf.curpos, body_len);
buf.curpos += body_len;
nni_time ts = 0;
if (read_uint64(&buf, &ts) != 0) {
goto out;
}
nni_msg_set_timestamp(msg, ts);
nni_mqtt_msg_decode(msg);
if (aio_available) {
uint64_t addr = 0;
if (read_uint64(&buf, &addr) != 0) {
goto out;
}
nni_mqtt_msg_set_aio(msg, (nni_aio *) addr);
} else {
nni_mqtt_msg_set_aio(msg, NULL);
}
return msg;
out:
if (msg) {
nni_msg_free(msg);
}
return NULL;
}
static uint8_t *
nni_msg_serialize(nni_msg *msg, size_t *out_len)
{
size_t len = nni_msg_header_len(msg) + nni_msg_len(msg) +
(sizeof(uint32_t) * 2) + sizeof(nni_time) + sizeof(nni_aio *);
*out_len = len;
// bytes:
// header: header_len(uint32) + header(header_len)
// body: body_len(uint32) + body(body_len)
// time: nni_time(uint64)
uint8_t *bytes = nng_zalloc(len);
struct pos_buf buf = { .curpos = &bytes[0], .endpos = &bytes[len] };
if (write_uint32(nni_msg_header_len(msg), &buf) != 0) {
goto out;
}
if (write_bytes(nni_msg_header(msg), nni_msg_header_len(msg), &buf) !=
0) {
goto out;
}
if (write_uint32(nni_msg_len(msg), &buf) != 0) {
goto out;
}
if (write_bytes(nni_msg_body(msg), nni_msg_len(msg), &buf) != 0) {
goto out;
}
if (write_uint64(nni_msg_get_timestamp(msg), &buf) != 0) {
goto out;
}
return bytes;
out:
free(bytes);
return NULL;
}
static nni_msg *
nni_msg_deserialize(uint8_t *bytes, size_t len)
{
nni_msg *msg;
if (nni_msg_alloc(&msg, 0) != 0) {
return NULL;
}
struct pos_buf buf = { .curpos = &bytes[0], .endpos = &bytes[len] };
// bytes:
// header: header_len(uint32) + header(header_len)
// body: body_len(uint32) + body(body_len)
// time: nni_time(uint64)
uint32_t header_len;
if (read_uint32(&buf, &header_len) != 0) {
goto out;
}
nni_msg_header_append(msg, buf.curpos, header_len);
buf.curpos += header_len;
uint32_t body_len;
if (read_uint32(&buf, &body_len) != 0) {
goto out;
}
nni_msg_append(msg, buf.curpos, body_len);
buf.curpos += body_len;
nni_time ts = 0;
if (read_uint64(&buf, &ts) != 0) {
goto out;
}
nni_msg_set_timestamp(msg, ts);
return msg;
out:
nni_msg_free(msg);
return NULL;
}
| 26.900675 | 82 | 0.671136 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.