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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a9b0d871e2729ab2e5225749abe7bebdf4785e5 | 1,428 | h | C | src/swganh_core/static/static_service_binding.h | obi-two/GameServer | 7d37024e2291a97d49522610cd8f1dbe5666afc2 | [
"MIT"
] | 20 | 2015-02-23T15:11:56.000Z | 2022-03-18T20:56:48.000Z | src/swganh_core/static/static_service_binding.h | obi-two/GameServer | 7d37024e2291a97d49522610cd8f1dbe5666afc2 | [
"MIT"
] | null | null | null | src/swganh_core/static/static_service_binding.h | obi-two/GameServer | 7d37024e2291a97d49522610cd8f1dbe5666afc2 | [
"MIT"
] | 20 | 2015-04-04T16:35:59.000Z | 2022-03-24T14:54:37.000Z | // This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#pragma once
#ifndef WIN32
#include <Python.h>
#endif
#include "swganh/scripting/python_shared_ptr.h"
#include "static_service_interface.h"
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace swganh::statics;
using namespace boost::python;
using namespace std;
void exportStaticService()
{
class_<ElevatorData, shared_ptr<ElevatorData>, boost::noncopyable>("ElevatorData", "A type to represent elevator data")
.def_readwrite("dst_cell", &ElevatorData::dst_cell)
.def_readwrite("dst_orientation", &ElevatorData::dst_orientation)
.def_readwrite("dst_position", &ElevatorData::dst_position)
.def_readwrite("effect_id", &ElevatorData::effect_id)
.def_readwrite("going_down", &ElevatorData::going_down)
;
class_<std::vector<shared_ptr<ElevatorData>>>("ElevatorDataList", "vector for elevator data")
.def(vector_indexing_suite<std::vector<shared_ptr<ElevatorData>>, true>());
class_<StaticServiceInterface, shared_ptr<StaticServiceInterface>, boost::noncopyable>("StaticService", "The static service loads and holds data that never changes.", no_init)
.def("getElevatorDataForObject", &StaticServiceInterface::GetElevatorDataForObject, "Returns elevator data for a particular terminal id.")
;
}
| 39.666667 | 179 | 0.768908 |
cd438d03d1866846a58f9e2b9d4617509e1b27ed | 3,989 | h | C | BCC55/Include/vsof.h | C14427818/CollegeYr1 | 2b551d70ae3cc14a354c49657d476515466ca66f | [
"MIT"
] | 1 | 2022-01-13T01:03:55.000Z | 2022-01-13T01:03:55.000Z | INCLUDE/VSOF.H | earthsiege2/borland-cpp-ide | 09bcecc811841444338e81b9c9930c0e686f9530 | [
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null | INCLUDE/VSOF.H | earthsiege2/borland-cpp-ide | 09bcecc811841444338e81b9c9930c0e686f9530 | [
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null | //--vsof.h---------------------------------------------------------------------
//
// Virtual Stream On File interface header file.
//
//
// Copyright (C) Microsoft Corp., 1986-1996. All Rights Reserved.
//
//-----------------------------------------------------------------------------
#ifndef __VSOF_H__
#pragma option push -b -a8 -pc -A- /*P_O_Push*/
#define __VSOF_H__
/* VirtualStreamOnFile (VSOF) */
/*
* Methods and #define's for implementing an OLE 2.0 storage stream
* (as defined in the OLE 2.0 specs) on top of a system file.
*/
#ifdef __cplusplus
extern "C" {
#endif
// Flags unique to VSOF IStream implementation
#define VSOF_CLONEABLE ((ULONG) 0x40000000) // allow stream to be cloned
#define VSOF_UNIQUEFILENAME ((ULONG) 0x80000000) // Want unique temporary file name
//$--HrOpenVirtualStreamOnFile---------------------------------------------------
//
// DESCRIPTION: Opens a virtual (buffered) stream on a file.
//
// INPUT: lpAllocateBuffer -- allocate routine
// lpFreeBuffer -- de-allocation routine
// ulFlags -- IStream interface flags--see notes
// lpszFileName -- file name with complete path
// lpszPrefix -- file name prefix
//
//
// OUTPUT: lppStream -- stream pointer
//
// RETURNS: HRESULT -- NOERROR if successful,
// E_INVALIDARG if bad input,
// E_FAIL otherwise.
//
// ulFlag notes:
//
// Specifying STGM_DELETEONRELEASE makes the file opened a temporary file (It
// will be deleted when the stream is released).
//
// Specifying STGM_SHARE_EXCLUSIVE makes the file accessible by only one application
// at a time.
//
// Specifying STGM_SHARE_DENY_READ makes the file readable by only one application
// at a time.
//
// Specifying STGM_SHARE_DENY_WRITE makes the file writable by only one application
// at a time.
//
// Failing to specify a STGM_SHARE flag makes the file readable and writable
// by mutliple applications at the same time.
//
//-----------------------------------------------------------------------------
STDMETHODIMP HrOpenVirtualStreamOnFile(
IN LPALLOCATEBUFFER lpAllocateBuffer, // allocation routine
IN LPFREEBUFFER lpFreeBuffer, // de-allocation routine
IN ULONG ulFlags, // stream interface flags
IN LPSTR lpszFileName, // file name
IN LPSTR lpszPrefix, // file name prefix
OUT LPSTREAM FAR * lppStream); // pointer to stream
typedef HRESULT (STDMETHODCALLTYPE FAR * LPOPENVIRTUALSTREAMONFILE)
(
LPALLOCATEBUFFER lpAllocateBuffer,
LPFREEBUFFER lpFreeBuffer,
ULONG ulFlags,
LPSTR lpszFileName,
LPSTR lpszPrefix,
LPSTREAM FAR * lppStream
);
// Special virtual stream interface extensions for performance...
// There are certain situations where knowing if the stream has changed can be
// used to make desicions that will improve performance.
//$--VSOF_SetClean-------------------------------------------------------------
//
// DESCRIPTION: Unsets stream dirty flag
//
// INPUT: lpStream -- stream pointer
//
// RETURNS: HRESULT -- NOERROF if successful,
// E_INVALIDARG if bad input.
//
//-----------------------------------------------------------------------------
HRESULT VSOF_SetClean(
IN LPSTREAM lpStream); // stream pointer
//$--VSOF_IsDirty-------------------------------------------------------------
//
// DESCRIPTION: Returns stream dirty flag
//
// INPUT: lpStream -- stream pointer
//
// RETURNS: HRESULT -- NOERROF if successful,
// E_INVALIDARG if bad input.
//
//-----------------------------------------------------------------------------
HRESULT VSOF_IsDirty(
IN LPSTREAM lpStream, // stream pointer
OUT BOOL * pfDirty); // dirty flag pointer
#ifdef WIN32
#define OPENVIRTUALSTREAMONFILE "HrOpenVirtualStreamOnFile"
#endif
#ifdef WIN16
#define OPENVIRTUALSTREAMONFILE "_OPENVIRTUALSTREAMONFILE"
#endif
#ifdef __cplusplus
}
#endif
#pragma option pop /*P_O_Pop*/
#endif //__VSOF_H__
| 31.65873 | 85 | 0.604914 |
a2243adc3c0db281e1d8bc85773b2f88536c5142 | 67 | h | C | src/Options.h | toml2/arduino-lorawan-sdk | aa56ed3c8200f3656f23a819ac82b60b7d26ff2a | [
"Apache-2.0"
] | 4 | 2020-03-12T12:44:42.000Z | 2022-02-11T04:18:36.000Z | src/Options.h | toml2/arduino-lorawan-sdk | aa56ed3c8200f3656f23a819ac82b60b7d26ff2a | [
"Apache-2.0"
] | 3 | 2021-08-18T13:41:47.000Z | 2022-03-30T22:16:02.000Z | src/Options.h | toml2/arduino-lorawan-sdk | aa56ed3c8200f3656f23a819ac82b60b7d26ff2a | [
"Apache-2.0"
] | 4 | 2019-09-23T11:56:44.000Z | 2022-02-15T22:27:16.000Z | #ifndef OPTIONS_H_
#define OPTIONS_H_
class Options {
};
#endif
| 7.444444 | 18 | 0.731343 |
9e573321f397eb95fb528244c6cdb110f1f1d341 | 6,265 | c | C | sfplock.c | rains31/sfplock | 2215365323aabfafcf8826365233d00e98f8411e | [
"MIT"
] | 2 | 2019-01-31T10:12:24.000Z | 2020-05-24T03:50:32.000Z | sfplock.c | rains31/sfplock | 2215365323aabfafcf8826365233d00e98f8411e | [
"MIT"
] | null | null | null | sfplock.c | rains31/sfplock | 2215365323aabfafcf8826365233d00e98f8411e | [
"MIT"
] | null | null | null | /* See LICENSE file for license details. */
#define _XOPEN_SOURCE 500
#include <ctype.h>
#include <errno.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/types.h>
#include <X11/keysym.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
typedef struct {
int screen;
Window root, win;
Pixmap pmap;
unsigned long colors[2];
} Lock;
static Lock **locks;
static int nscreens;
static Bool running = True;
static void
die(const char *errstr, ...) {
va_list ap;
va_start(ap, errstr);
vfprintf(stderr, errstr, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
static int fprint_verify(const char * user) {
FILE * fp;
char buf[80];
int ret = 1;
int uid = -1;
char cmd[200] = FPRINTD_PREFIX"/bin/fprintd-verify ";
uid = getuid();
strncat(cmd, user, 100);
setuid(0); //set uid 0 to get permission of reading everyone's fingerprint.
fp = popen(cmd, "r");
setuid(uid); //set uid back to normal user.
syslog(LOG_INFO, "cmd:%s", cmd);
while(!feof(fp)) {
fgets(buf,sizeof(buf),fp);
syslog(LOG_INFO, "%s", buf);
if (strstr(buf,"verify-match")!=NULL) {
ret = 0;
break;
}
else if (strstr(buf,"verify-no-match")!=NULL) {
ret = 1;
sleep(3);
break;
}
else if (strstr(buf,"failed to claim device")!=NULL) {
ret = 2;
sleep(3);
break;
}
}
pclose(fp);
return ret;
}
static void
wait_fingerprint(Display *dpy, const char * user)
{
int screen;
running = True;
while(running) {
running = fprint_verify(user);
if(running){
sleep(1);//prevent calling fprintd-verify too fast when fingerprint device doesn't work.
}
for(screen = 0; screen < nscreens; screen++) {
XRaiseWindow(dpy, locks[screen]->win);
}
}
}
static void
ensure_fprint_exists(const char * user) {
FILE * fp;
char buf[100];
char cmd[200] = FPRINTD_PREFIX"/bin/fprintd-list ";
strncat(cmd, user, 100);
fp = popen(cmd, "r");
while(!feof(fp)) {
fgets(buf, sizeof(buf), fp);
fprintf(stderr, "%s", buf);
if (strstr(buf,"Fingerprints for user")!=NULL) {
pclose(fp);
return;
}
}
pclose(fp);
die("sfplock: fingerprint not found for user '%s'.\n", user);
}
static void
unlockscreen(Display *dpy, Lock *lock) {
if(dpy == NULL || lock == NULL)
return;
XUngrabPointer(dpy, CurrentTime);
XFreeColors(dpy, DefaultColormap(dpy, lock->screen), lock->colors, 2, 0);
XFreePixmap(dpy, lock->pmap);
XDestroyWindow(dpy, lock->win);
free(lock);
}
static Lock *
lockscreen(Display *dpy, int screen) {
char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
unsigned int len;
Lock *lock;
XColor color, dummy;
XSetWindowAttributes wa;
Cursor invisible;
if(dpy == NULL || screen < 0)
return NULL;
lock = malloc(sizeof(Lock));
if(lock == NULL)
return NULL;
lock->screen = screen;
lock->root = RootWindow(dpy, lock->screen);
/* init */
wa.override_redirect = 1;
wa.background_pixel = BlackPixel(dpy, lock->screen);
lock->win = XCreateWindow(dpy, lock->root, 0, 0, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen),
0, DefaultDepth(dpy, lock->screen), CopyFromParent,
DefaultVisual(dpy, lock->screen), CWOverrideRedirect | CWBackPixel, &wa);
XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen), COLOR2, &color, &dummy);
lock->colors[1] = color.pixel;
XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen), COLOR1, &color, &dummy);
lock->colors[0] = color.pixel;
lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap, &color, &color, 0, 0);
XDefineCursor(dpy, lock->win, invisible);
XMapRaised(dpy, lock->win);
for(len = 1000; len; len--) {
if(XGrabPointer(dpy, lock->root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
break;
usleep(1000);
}
if(running && (len > 0)) {
for(len = 1000; len; len--) {
if(XGrabKeyboard(dpy, lock->root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
== GrabSuccess)
break;
usleep(1000);
}
}
running &= (len > 0);
if(!running) {
unlockscreen(dpy, lock);
lock = NULL;
}
else
XSelectInput(dpy, lock->root, SubstructureNotifyMask);
return lock;
}
int
main(int argc, char **argv) {
Display *dpy;
int screen;
int nlocks = 0;
int uid = -1;
struct passwd *pwd;
char user[100] = "";
if((argc == 2) && !strcmp("-v", argv[1]))
die("sfplock-%s © 2012 Rains<rains31(at)gmail.com>\nbased on slock-1.1 © 2006-2012 Anselm R Garbe\n", VERSION);
uid = getuid();
pwd = getpwuid(uid);
strncpy(user, pwd->pw_name, 100);
ensure_fprint_exists(user);
if(!(dpy = XOpenDisplay(0)))
die("sfplock: cannot open display\n");
/* Get the number of screens in display "dpy" and blank them all. */
nscreens = ScreenCount(dpy);
locks = malloc(sizeof(Lock *) * nscreens);
if(locks == NULL)
die("sfplock: malloc: %s\n", strerror(errno));
for(screen = 0; screen < nscreens; screen++) {
if ( (locks[screen] = lockscreen(dpy, screen)) != NULL)
nlocks++;
}
XSync(dpy, False);
/* Did we actually manage to lock something? */
if (nlocks == 0) { // nothing to protect
free(locks);
XCloseDisplay(dpy);
return 1;
}
openlog("sfplock", LOG_PID, LOG_USER);
/* Everything is now blank. Now wait for the correct finger... */
wait_fingerprint(dpy, user);
closelog();
/* verify ok, unlock everything and quit. */
for(screen = 0; screen < nscreens; screen++)
unlockscreen(dpy, locks[screen]);
free(locks);
XCloseDisplay(dpy);
return 0;
}
| 27.844444 | 119 | 0.586592 |
b11b29d4a4c1756c3d891ad6fe56051912adab82 | 277 | c | C | C/01 - Basics/ImpTypCon.c | dambergn/programing-examples | d1086047caa52c7cc6d2e7877cbbbebd2a1cbee0 | [
"MIT"
] | null | null | null | C/01 - Basics/ImpTypCon.c | dambergn/programing-examples | d1086047caa52c7cc6d2e7877cbbbebd2a1cbee0 | [
"MIT"
] | null | null | null | C/01 - Basics/ImpTypCon.c | dambergn/programing-examples | d1086047caa52c7cc6d2e7877cbbbebd2a1cbee0 | [
"MIT"
] | null | null | null | #include <stdio.h>
// implicit Type Conversion
// https://en.cppreference.com/w/cpp/language/implicit_conversion
int main()
{
// Implicit type conversion - promotion
float x = 50.0f;
print("%f", x); // printf takes a double
// x is PROMOTED to a double
return 0;
} | 19.785714 | 65 | 0.6787 |
fa07033a4bc8d8ac18d5bdc57ec03d38cb848164 | 19,646 | h | C | stuff/cpp netbeans/monkey.h | ra1ngo/monkey | 25eb57d7224283ccbb0b76217505bc171656c365 | [
"MIT"
] | null | null | null | stuff/cpp netbeans/monkey.h | ra1ngo/monkey | 25eb57d7224283ccbb0b76217505bc171656c365 | [
"MIT"
] | null | null | null | stuff/cpp netbeans/monkey.h | ra1ngo/monkey | 25eb57d7224283ccbb0b76217505bc171656c365 | [
"MIT"
] | null | null | null | //вместо #pragma once
#ifndef _MONKEY_H_
#define _MONKEY_H_
// GLEW нужно подключать до GLFW.
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#define STB_IMAGE_IMPLEMENTATION
#include <STB/stb_image.h>
#include <GLM/glm.hpp>
#include <GLM/gtc/matrix_transform.hpp>
#include <GLM/gtc/type_ptr.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <GLM/gtx/matrix_decompose.hpp>
// Включаем стандартные заголовки
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
class Monkey /*имя класса*/
{
private: /* список свойств и методов для использования внутри класса */
public: /* список методов доступных другим функциям и объектам программы */
//////////////////////////////
/* ВЛОЖЕННЫЕ КЛАССЫ "Monkey"*/
//////////////////////////////
class Viewport /*Viewport*/
{
protected:
public:
int width, height;
Viewport(int w,int h){
this->width = w;
this->height = h;
glViewport(0, 0, this->width, this->height);
}
};
class Screen /*Screen*/
{
protected:
public:
GLFWwindow* context;
Viewport* viewport;
Screen(){
// Открыть окно и создать в нем контекст OpenGL
this->context = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
//GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", null, null);
if( this->context == NULL ){
fprintf( stderr, "Невозможно открыть окно GLFW. Если у вас Intel GPU, то он не поддерживает версию 3.3." );
glfwTerminate();
//return -1;
}
int width, height;
glfwGetFramebufferSize(this->context, &width, &height);
this->viewport = (new Viewport(width, height));
}
Screen(Viewport *v){
// Открыть окно и создать в нем контекст OpenGL
this->context = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
//GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", null, null);
if( this->context == NULL ){
fprintf( stderr, "Невозможно открыть окно GLFW. Если у вас Intel GPU, то он не поддерживает версию 3.3." );
glfwTerminate();
//return -1;
}
this->viewport = v;
}
};
class Texture /*Texture*/
{
protected:
public:
class Shader
{
private:
GLuint vertexShader;
GLuint fragmentShader;
GLuint createShader(GLenum type, const char *source) {
// Create the shader object
GLuint shader = glCreateShader(type);
std::cout << shader << std::endl;
// Load the shader source
glShaderSource(shader, 1, &source, NULL);
// Compile the shader
glCompileShader(shader);
GLint status;
GLchar infoLog[512];
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if(!status)
{
glGetShaderInfoLog(shader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::COMPILATION_FAILED\n" << infoLog << std::endl;
}
return shader;
}
public:
GLuint shaderProgram;
std::string vertex;
std::string fragment;
Shader(){
this->vertex =
"#version 330 core\n"
"in vec3 position;\n"
"in vec3 color;\n"
"in vec2 texCoord;\n"
"out vec3 vertexColor;\n"
"out vec2 TexCoord;\n"
"uniform mat4 MVP;\n"
"void main()\n"
"{\n"
" gl_Position = MVP * vec4(position, 1.0f);\n"
" vertexColor = color;\n"
" TexCoord = vec2(texCoord.x, 1.0 - texCoord.y);\n"
"}\n";
this->fragment =
"#version 330 core\n"
"in vec3 vertexColor;\n"
"in vec2 TexCoord;\n"
"out vec4 FragColor;\n"
"uniform float alpha;\n"
"uniform sampler2D ourTexture;\n"
"void main()\n"
"{\n"
//" FragColor=vec4(vertexColor, alpha);\n"
" FragColor = texture(ourTexture, TexCoord);"
"}\n";
//prepareProgram
const char *source;
std::cout << "1" << std::endl;
//int length;
source = this->vertex.c_str();
std::cout << "2" << std::endl;
//length = shader_vertex_source.size();
this->vertexShader = createShader(GL_VERTEX_SHADER, source);
std::cout << "3" << std::endl;
//int length1;
source = this->fragment.c_str();
//length1 = shader_fragment_source.size();
this->fragmentShader = createShader(GL_FRAGMENT_SHADER, source);
std::cout << "10" << std::endl;
//linkProgram
this->shaderProgram = glCreateProgram();
glAttachShader(this->shaderProgram, this->vertexShader);
glAttachShader(this->shaderProgram, this->fragmentShader);
glLinkProgram(this->shaderProgram);
//отладка
GLint status;
glGetProgramiv(this->shaderProgram, GL_LINK_STATUS, &status);
if(status == GL_FALSE) {
GLint length;
glGetProgramiv(this->shaderProgram, GL_INFO_LOG_LENGTH, &length);
std::vector<char> log(length);
glGetProgramInfoLog(this->shaderProgram, length, &length, &log[0]);
std::cerr << &log[0];
//return false;
}
}
void Use() { glUseProgram(this->shaderProgram); }
};
class Mesh
{
private:
unsigned char *image;
GLuint *shaderProgram;
GLuint VAO;
int width, height;
public:
//массив вершин прямоугольника
GLfloat vertices[12];
GLfloat colors[12];
GLuint indices[6];
GLfloat texCoords[8];
//shaderProgram, image, image.width, image.height
Mesh(GLuint *s, unsigned char *i, int w, int h ):
vertices{
// Позиции
0.5f, 0.5f, 0.0f, // Верхний правый угол
0.5f, -0.5f, 0.0f, // Нижний правый угол
-0.5f, -0.5f, 0.0f, // Нижний левый угол
-0.5f, 0.5f, 0.0f // Верхний левый угол
},
colors{
// Цвета
1.0f, 0.0f, 0.0f, // Верхний правый угол
0.0f, 1.0f, 0.0f, // Нижний правый угол
0.0f, 0.0f, 1.0f, // Нижний левый угол
1.0f, 0.0f, 1.0f // Верхний левый угол
},
indices{ // Помните, что мы начинаем с 0!
0, 1, 3, // Первый треугольник
1, 2, 3 // Второй треугольник
},
texCoords{
1.0f, 1.0f, // Верхний правый угол
1.0f, 0.0f, // Нижний правый угол
0.0f, 0.0f, // Нижний левый угол
0.0f, 1.0f // Верхний левый угол
}
{
std::cout << "MeshStart" << std::endl;
//std::cout << "Array" << this->vertices << std::endl;
this->image = i;
this->shaderProgram = s;
this->width = w;
this->height = h;
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, this->image);
// Устанавливаем настройки фильтрации и преобразований (на текущей текстуре)
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(this->image);
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(this->vertices), this->vertices, GL_STATIC_DRAW);
GLuint colorBO;
glGenBuffers(1, &colorBO);
glBindBuffer(GL_ARRAY_BUFFER, colorBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(this->colors), this->colors, GL_STATIC_DRAW);
GLuint texBO;
glGenBuffers(1, &texBO);
glBindBuffer(GL_ARRAY_BUFFER, texBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(this->texCoords), this->texCoords, GL_STATIC_DRAW);
GLuint IBO;
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(this->indices), this->indices, GL_STATIC_DRAW);
//////////////////////////
/* ПОДГОТОВКА К UPDATE()*/
//////////////////////////
//Vertex Array Object!!!
glGenVertexArrays(1, &this->VAO);
glBindVertexArray(this->VAO);
// Атрибут с координатами
glBindBuffer(GL_ARRAY_BUFFER, VBO);
int posLoc = glGetAttribLocation(*this->shaderProgram, "position");
glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
glEnableVertexAttribArray(posLoc);
// Атрибут с цветом
glBindBuffer(GL_ARRAY_BUFFER, colorBO);
int colorLoc = glGetAttribLocation(*this->shaderProgram, "color");
glVertexAttribPointer(colorLoc, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
glEnableVertexAttribArray(colorLoc);
// Тексдура
//glBindTexture(GL_TEXTURE_2D, texture);
glBindBuffer(GL_ARRAY_BUFFER, texBO);
int texLoc = glGetAttribLocation(*this->shaderProgram, "texCoord");
glVertexAttribPointer(texLoc, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
glEnableVertexAttribArray(texLoc);
//glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
//int sampler2DLoc = glGetUniformLocation(shaderProgram, "ourTexture");
//glUniform1i(sampler2DLoc, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
// Отвязываем VAO (НЕ EBO)
glBindVertexArray(0);
}
void draw(){
glBindVertexArray(this->VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
};
//public
unsigned char *image;
int width, height;
Shader * shader;
Mesh * mesh;
//затем убрать это
glm::mat4 MVP;
Texture(const char *path){
//stbi_set_flip_vertically_on_load(true);
//unsigned char *image = stbi_load("res/img.jpg",&widthIMG,&heightIMG,&channels, STBI_rgb);
int channels;
this->image = stbi_load(path,&this->width,&this->height,&channels, STBI_rgb_alpha);
if(this->image == NULL) {
std::cout << "loadTexture failed" << image << std::endl;
//return false;
}
this->shader = new Shader();
this->mesh = new Mesh(&this->shader->shaderProgram, this->image, this->width, this->height);
//затем убрать это
glm::vec3 position = glm::vec3(0.0f, 0.5f, 0.0f);
glm::vec3 rotation = glm::vec3(0.0f, 0.0f, 1.0f);
glm::vec3 scale = glm::vec3(0.5f, 0.5f, 1.0f);
glm::mat4 trans = glm::mat4(1.0f);
float angle = 90.0f;
trans = glm::translate(trans, position);
trans = glm::rotate(trans, glm::radians(angle), rotation);
trans = glm::scale(trans, scale);
glm::vec3 scl;
glm::quat q;
glm::vec3 pos;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(trans, scl, q, pos, skew, perspective);
glm::vec3 rot = glm::eulerAngles(q);
std::cout << "eulerAngles.x: " << rot.x << "\neulerAngles.y: " << rot.y << "\neulerAngles.z: " << rot.z << std::endl;
rot = glm::degrees(rot);
std::cout << "pos.x: " << pos.x << "\npos.y: " << pos.y << "\npos.z: " << pos.z << std::endl;
std::cout << "scl.x: " << scl.x << "\nscl.y: " << scl.y << "\nscl.z: " << scl.z << std::endl;
std::cout << "rot.x: " << rot.x << "\nrot.y: " << rot.y << "\nrot.z: " << rot.z << std::endl;
float zoom = 1.f;
glm::vec3 cameraPosition = glm::vec3(0.f, 0.5f, 10.f);
glm::vec3 cameraTarget = glm::vec3(0.0f, 0.5f, 0.0f);
glm::vec3 upVector = glm::vec3(0.0f, 1.0f, 0.0f);
glm::mat4 projection = glm::ortho(-1.f * zoom, 1.f * zoom, -1.f * zoom, 1.f * zoom, 0.1f, 20.f);
glm::mat4 CameraMatrix = glm::lookAt(
cameraPosition, // Позиция камеры в мировом пространстве
cameraTarget, // Указывает куда вы смотрите в мировом пространстве
upVector // Вектор, указывающий направление вверх. Обычно (0, 1, 0)
);
zoom = 0.75f;
projection = glm::ortho(-1.f * zoom, 1.f * zoom, -1.f * zoom, 1.f * zoom, 0.1f, 20.f);
this->MVP = projection * CameraMatrix * trans;
}
void draw(){
// Включаем блендинг
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
this->shader->Use();
GLint alphaLoc = glGetUniformLocation(this->shader->shaderProgram, "alpha");
glUniform1f(alphaLoc, 1.0f);
GLuint MVPLoc = glGetUniformLocation(this->shader->shaderProgram, "MVP");
glUniformMatrix4fv(MVPLoc, 1, GL_FALSE, glm::value_ptr(MVP));
this->mesh->draw();
glDisable(GL_BLEND);
}
};
//поля
//
Monkey(){ /* конструктор */
// Инициализируем GLFW
if( !glfwInit() ){
fprintf( stderr, "Ошибка при инициализации GLFWn" );
//return -1;
}
// Инициализируем GLEW
GLenum err = glewInit();
if (GLEW_OK != err){
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
}
fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
// Устанавливаем параметры
//glfwWindowHint(GLFW_FSAA_SAMPLES, 4); // 4x Сглаживание
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Мы хотим использовать OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Мы не хотим старый OpenGL
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); //Выключение возможности изменения размера окна
// Включим режим отслеживания нажатия клавиш, для проверки ниже
//glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
}
void setScreen(Screen *s){
glfwMakeContextCurrent(s->context);
}
};
#endif | 41.36 | 139 | 0.428535 |
fa36f09ab85647431e4d52aa7be8a2756bea7021 | 2,885 | c | C | vp9/encoder/mips/msa/vp9_fdct4x4_msa.c | clear39/avcode-libvpx | f4653c1efc0a8d758195572de34ae05271453d93 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | vp9/encoder/mips/msa/vp9_fdct4x4_msa.c | clear39/avcode-libvpx | f4653c1efc0a8d758195572de34ae05271453d93 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | vp9/encoder/mips/msa/vp9_fdct4x4_msa.c | clear39/avcode-libvpx | f4653c1efc0a8d758195572de34ae05271453d93 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* Copyright (c) 2015 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <assert.h>
#include "vp9/common/vp9_enums.h"
#include "vp9/encoder/mips/msa/vp9_fdct_msa.h"
void vp9_fwht4x4_msa(const int16_t *input, int16_t *output,
int32_t src_stride) {
v8i16 in0, in1, in2, in3, in4;
LD_SH4(input, src_stride, in0, in1, in2, in3);
in0 += in1;
in3 -= in2;
in4 = (in0 - in3) >> 1;
SUB2(in4, in1, in4, in2, in1, in2);
in0 -= in2;
in3 += in1;
TRANSPOSE4x4_SH_SH(in0, in2, in3, in1, in0, in2, in3, in1);
in0 += in2;
in1 -= in3;
in4 = (in0 - in1) >> 1;
SUB2(in4, in2, in4, in3, in2, in3);
in0 -= in3;
in1 += in2;
SLLI_4V(in0, in1, in2, in3, 2);
TRANSPOSE4x4_SH_SH(in0, in3, in1, in2, in0, in3, in1, in2);
ST4x2_UB(in0, output, 4);
ST4x2_UB(in3, output + 4, 4);
ST4x2_UB(in1, output + 8, 4);
ST4x2_UB(in2, output + 12, 4);
}
void vp9_fht4x4_msa(const int16_t *input, int16_t *output, int32_t stride,
int32_t tx_type) {
v8i16 in0, in1, in2, in3;
LD_SH4(input, stride, in0, in1, in2, in3);
/* fdct4 pre-process */
{
v8i16 temp, mask;
v16i8 zero = { 0 };
v16i8 one = __msa_ldi_b(1);
mask = (v8i16)__msa_sldi_b(zero, one, 15);
SLLI_4V(in0, in1, in2, in3, 4);
temp = __msa_ceqi_h(in0, 0);
temp = (v8i16)__msa_xori_b((v16u8)temp, 255);
temp = mask & temp;
in0 += temp;
}
switch (tx_type) {
case DCT_DCT:
VP9_FDCT4(in0, in1, in2, in3, in0, in1, in2, in3);
TRANSPOSE4x4_SH_SH(in0, in1, in2, in3, in0, in1, in2, in3);
VP9_FDCT4(in0, in1, in2, in3, in0, in1, in2, in3);
break;
case ADST_DCT:
VP9_FADST4(in0, in1, in2, in3, in0, in1, in2, in3);
TRANSPOSE4x4_SH_SH(in0, in1, in2, in3, in0, in1, in2, in3);
VP9_FDCT4(in0, in1, in2, in3, in0, in1, in2, in3);
break;
case DCT_ADST:
VP9_FDCT4(in0, in1, in2, in3, in0, in1, in2, in3);
TRANSPOSE4x4_SH_SH(in0, in1, in2, in3, in0, in1, in2, in3);
VP9_FADST4(in0, in1, in2, in3, in0, in1, in2, in3);
break;
case ADST_ADST:
VP9_FADST4(in0, in1, in2, in3, in0, in1, in2, in3);
TRANSPOSE4x4_SH_SH(in0, in1, in2, in3, in0, in1, in2, in3);
VP9_FADST4(in0, in1, in2, in3, in0, in1, in2, in3);
break;
default: assert(0); break;
}
TRANSPOSE4x4_SH_SH(in0, in1, in2, in3, in0, in1, in2, in3);
ADD4(in0, 1, in1, 1, in2, 1, in3, 1, in0, in1, in2, in3);
SRA_4V(in0, in1, in2, in3, 2);
PCKEV_D2_SH(in1, in0, in3, in2, in0, in2);
ST_SH2(in0, in2, output, 8);
}
| 29.438776 | 74 | 0.612478 |
2ca42bfe62f97390d841866bb8f6b800c7d8c8f3 | 2,659 | h | C | submodules/LegacyComponents/LegacyComponents/TGMediaAssetsController.h | yfxiarigit/telegram | 8460ae1a90e0fe0ed8f7f04b0e6f78df40d261a3 | [
"MIT"
] | 1 | 2018-08-30T08:02:12.000Z | 2018-08-30T08:02:12.000Z | submodules/LegacyComponents/LegacyComponents/TGMediaAssetsController.h | yfxiarigit/telegram | 8460ae1a90e0fe0ed8f7f04b0e6f78df40d261a3 | [
"MIT"
] | null | null | null | submodules/LegacyComponents/LegacyComponents/TGMediaAssetsController.h | yfxiarigit/telegram | 8460ae1a90e0fe0ed8f7f04b0e6f78df40d261a3 | [
"MIT"
] | 2 | 2018-08-30T08:04:17.000Z | 2020-10-15T06:52:06.000Z | #import <LegacyComponents/TGNavigationController.h>
#import <LegacyComponents/LegacyComponentsContext.h>
#import <LegacyComponents/TGMediaAssetsLibrary.h>
#import <LegacyComponents/TGSuggestionContext.h>
@class TGMediaAssetsPickerController;
typedef enum
{
TGMediaAssetsControllerSendMediaIntent,
TGMediaAssetsControllerSendFileIntent,
TGMediaAssetsControllerSetProfilePhotoIntent,
TGMediaAssetsControllerSetCustomWallpaperIntent
} TGMediaAssetsControllerIntent;
@interface TGMediaAssetsController : TGNavigationController
@property (nonatomic, strong) TGSuggestionContext *suggestionContext;
@property (nonatomic, assign) bool localMediaCacheEnabled;
@property (nonatomic, assign) bool captionsEnabled;
@property (nonatomic, assign) bool inhibitDocumentCaptions;
@property (nonatomic, assign) bool shouldStoreAssets;
@property (nonatomic, assign) bool hasTimer;
@property (nonatomic, assign) bool liveVideoUploadEnabled;
@property (nonatomic, assign) bool shouldShowFileTipIfNeeded;
@property (nonatomic, strong) NSString *recipientName;
@property (nonatomic, copy) NSDictionary *(^descriptionGenerator)(id, NSString *, NSString *);
@property (nonatomic, copy) void (^avatarCompletionBlock)(UIImage *image);
@property (nonatomic, copy) void (^completionBlock)(NSArray *signals);
@property (nonatomic, copy) void (^dismissalBlock)(void);
@property (nonatomic, copy) TGViewController *(^requestSearchController)(void);
@property (nonatomic, readonly) TGMediaAssetsPickerController *pickerController;
@property (nonatomic, readonly) bool allowGrouping;
- (UIBarButtonItem *)rightBarButtonItem;
- (NSArray *)resultSignalsWithCurrentItem:(TGMediaAsset *)currentItem descriptionGenerator:(id (^)(id, NSString *, NSString *))descriptionGenerator;
- (void)completeWithAvatarImage:(UIImage *)image;
- (void)completeWithCurrentItem:(TGMediaAsset *)currentItem;
+ (instancetype)controllerWithContext:(id<LegacyComponentsContext>)context assetGroup:(TGMediaAssetGroup *)assetGroup intent:(TGMediaAssetsControllerIntent)intent recipientName:(NSString *)recipientName saveEditedPhotos:(bool)saveEditedPhotos allowGrouping:(bool)allowGrouping;
+ (TGMediaAssetType)assetTypeForIntent:(TGMediaAssetsControllerIntent)intent;
+ (NSArray *)resultSignalsForSelectionContext:(TGMediaSelectionContext *)selectionContext editingContext:(TGMediaEditingContext *)editingContext intent:(TGMediaAssetsControllerIntent)intent currentItem:(TGMediaAsset *)currentItem storeAssets:(bool)storeAssets useMediaCache:(bool)useMediaCache descriptionGenerator:(id (^)(id, NSString *, NSString *))descriptionGenerator saveEditedPhotos:(bool)saveEditedPhotos;
@end
| 48.345455 | 412 | 0.829259 |
c9103ccb66ad28a9a99f02bebd8b247e5284979e | 2,846 | h | C | Engine/Source/Core/SampleGenerator/SampleGenerator.h | MarvinChung/Photon-v2 | a42761797f5364525e5686cd7fe2eff6f5b04ddf | [
"MIT"
] | 1 | 2019-02-23T14:06:56.000Z | 2019-02-23T14:06:56.000Z | Engine/Source/Core/SampleGenerator/SampleGenerator.h | MarvinChung/Photon-v2 | a42761797f5364525e5686cd7fe2eff6f5b04ddf | [
"MIT"
] | null | null | null | Engine/Source/Core/SampleGenerator/SampleGenerator.h | MarvinChung/Photon-v2 | a42761797f5364525e5686cd7fe2eff6f5b04ddf | [
"MIT"
] | null | null | null | #pragma once
#include "Common/primitive_type.h"
#include "Core/Sample.h"
#include "Math/TVector2.h"
#include "Core/SampleGenerator/stages.h"
#include "FileIO/SDL/ISdlResource.h"
#include "FileIO/SDL/TCommandInterface.h"
#include "Core/SampleGenerator/samples.h"
#include <vector>
#include <memory>
#include <utility>
namespace ph
{
class Scene;
class InputPacket;
class SampleGenerator : public TCommandInterface<SampleGenerator>
{
public:
SampleGenerator(std::size_t numSampleBatches, std::size_t numCachedBatches);
virtual ~SampleGenerator();
void genSplitted(std::size_t numSplits,
std::vector<std::unique_ptr<SampleGenerator>>& out_sgs) const;
std::unique_ptr<SampleGenerator> genCopied(std::size_t numSampleBatches) const;
bool prepareSampleBatch();
Samples1DStage declare1DStage(std::size_t numElements);
Samples2DStage declare2DStage(
std::size_t numElements,
const Vector2S& dimSizeHints = {1, 1});
SamplesNDStage declareNDStage(
std::size_t numElements,
const std::vector<std::size_t>& dimSizeHints = {});
// TODO: these three methods can use a common helper method (input SamplesStageBase)
Samples1D getSamples1D(const Samples1DStage& stage);
Samples2D getSamples2D(const Samples2DStage& stage);
SamplesND getSamplesND(const SamplesNDStage& stage);
std::size_t numSampleBatches() const;
std::size_t numCachedBatches() const;
private:
virtual std::unique_ptr<SampleGenerator> genNewborn(std::size_t numSamples) const = 0;
virtual void genSamples1D(const Samples1DStage& stage, Samples1D* out_array) = 0;
virtual void genSamples2D(const Samples2DStage& stage, Samples2D* out_array) = 0;
virtual void genSamplesND(const SamplesNDStage& stage, SamplesND* out_array) = 0;
std::size_t m_numSampleBatches;
std::size_t m_numCachedBatches;
std::size_t m_numUsedBatches;
std::size_t m_numUsedCaches;
std::size_t m_totalElements;
std::vector<real> m_sampleBuffer;
std::vector<Samples1DStage> m_1DStages;
std::vector<Samples2DStage> m_2DStages;
std::vector<SamplesNDStage> m_NDStages;
void allocSampleBuffer();
void genSampleBatch();
void genSamples1DBatch();
void genSamples2DBatch();
void genSamplesNDBatch();
// command interface
public:
//SampleGenerator(const InputPacket& packet);
static SdlTypeInfo ciTypeInfo();
static void ciRegister(CommandRegister& cmdRegister);
};
// In-header Implementations:
inline std::size_t SampleGenerator::numSampleBatches() const
{
return m_numSampleBatches;
}
inline std::size_t SampleGenerator::numCachedBatches() const
{
return m_numCachedBatches;
}
}// end namespace ph
/*
<SDL_interface>
<category> sample-generator </category>
<type_name> sample-generator </type_name>
<name> Sample Generator </name>
<description>
Engine component for generating sample values.
</description>
</SDL_interface>
*/ | 27.104762 | 87 | 0.771961 |
3012eb2d65781c280f75123d40cc46b294ddfdda | 964 | h | C | experiments/Packaging and Configuration/package/resourceppc.h | hansmy/Webinos-Platform | 43950daebc41cd985adba4efc5670b61336aca7f | [
"Apache-2.0"
] | 1 | 2015-08-06T20:08:14.000Z | 2015-08-06T20:08:14.000Z | experiments/Packaging and Configuration/package/resourceppc.h | krishnabangalore/Webinos-Platform | 2ab4779112483a0213ae440118b1c2a3cf80c7bd | [
"Apache-2.0"
] | null | null | null | experiments/Packaging and Configuration/package/resourceppc.h | krishnabangalore/Webinos-Platform | 2ab4779112483a0213ae440118b1c2a3cf80c7bd | [
"Apache-2.0"
] | null | null | null | //{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by packageppc.rc
//
#define IDS_PROJNAME 100
#define IDR_PACKAGE 101
#define IDR_BONDIWIDGETCONFIG 102
#define IDR_BONDIWIDGETLIBRARY 103
#define IDR_BONDIWIDGET 104
#define IDR_BONDIWIDGETPROPERTIES 105
#define IDR_CBONDIWIDGETSIGNATURE 106
#define IDR_BONDIWIDGETSIGNATURE 107
#define IDR_BONDIWIDGETFEATURE 108
#define IDR_BONDIWIDGETAPPCONFIG 109
#define IDR_BONDISIGNINGHELPER 110
#define IDR_BONDIFEATUREPARAM 111
#define IDR_BONDIWIDGETPREFERENCE 112
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 201
#define _APS_NEXT_COMMAND_VALUE 32768
#define _APS_NEXT_CONTROL_VALUE 201
#define _APS_NEXT_SYMED_VALUE 113
#endif
#endif
| 33.241379 | 47 | 0.701245 |
30561ff7c3041cb3948b91b37c7ce3004754396e | 451 | h | C | Generator.h | lucky-patty/Maze-Solver | ff632d07d64bcecf4eaa23ddc7f8c826131c0378 | [
"Apache-2.0"
] | null | null | null | Generator.h | lucky-patty/Maze-Solver | ff632d07d64bcecf4eaa23ddc7f8c826131c0378 | [
"Apache-2.0"
] | null | null | null | Generator.h | lucky-patty/Maze-Solver | ff632d07d64bcecf4eaa23ddc7f8c826131c0378 | [
"Apache-2.0"
] | null | null | null | #ifndef Generator_H
#define Generator_H
#include<stdlib.h>
#include<random>
#include<vector>
#include<algorithm>
#include "Maze.h"
#include "Edge.h"
class Generator
{
private:
long seed;
public:
Generator(long);
void setNSEW(int,int,int,int, Maze*);
void ABgenerate(Maze*);
void EllerGenerate (Maze*);
int checkVertical(std::vector<Cell*>, int);
int findSetNumber(std::vector<std::vector<Cell*>>, int, int);
};
#endif | 17.346154 | 62 | 0.685144 |
68215da0f1d7c260b45ffeb01268474c21ba931e | 6,705 | h | C | src/c-compiler/parser/lexer.h | jondgoodwin/cone | 67d50e3d2d23367ff98dd893179bda02d7702f5a | [
"MIT-0",
"MIT"
] | 427 | 2017-09-22T05:33:40.000Z | 2022-03-23T06:26:18.000Z | src/c-compiler/parser/lexer.h | jondgoodwin/cone | 67d50e3d2d23367ff98dd893179bda02d7702f5a | [
"MIT-0",
"MIT"
] | 49 | 2019-01-03T19:34:26.000Z | 2022-03-05T03:35:57.000Z | src/c-compiler/parser/lexer.h | jondgoodwin/cone | 67d50e3d2d23367ff98dd893179bda02d7702f5a | [
"MIT-0",
"MIT"
] | 17 | 2018-04-16T06:45:46.000Z | 2022-02-14T17:26:17.000Z | /** Lexer
* @file
*
* This source file is part of the Cone Programming Language C compiler
* See Copyright Notice in conec.h
*/
#ifndef lexer_h
#define lexer_h
typedef struct INode INode; // ../ast/ast.h
typedef struct Name Name; // ../ast/nametbl.h
#include "../coneopts.h"
#include <stdint.h>
#define LEX_MAX_BLOCKS 1024
// What sort of block the lexer is working with
typedef enum {
FreeFormBlock, // Indentation is irrelevent
SigIndentBlock, // Indentation is significant
SameStmtBlock // Block statements on same line as statement
} LexBlockMode;
// Information about a block on the block stack
typedef struct {
uint16_t blkindent; // Indentation of stmt that started block
uint16_t paranscnt; // How many open parantheses/brackets in block
LexBlockMode blkmode; // Lexer block mode
} LexBlockInfo;
// Lexer state (one per source file)
typedef struct Lexer {
// Value info about a discovered token
union {
double floatlit;
uint64_t uintlit;
char *strlit;
Name *ident;
} val;
uint32_t strlen; // Size of string literal
INode *langtype;
// immutable info about source
char *url; // The url where the source text came from
char *fname; // The filename of the url (no extension)
char *source; // The source text (0-terminated)
struct Lexer *next; // Next lexer (linked list of injected lexers)
struct Lexer *prev; // Previous lexer
// Lexer's evolving state
char *srcp; // Current pointer
char *tokp; // Start of current token
char *linep; // Pointer to start of current line
uint32_t linenbr; // Current line number
uint32_t flags; // Lexer flags
uint16_t toktype; // TokenTypes
// ** Significant indentation state -->
int16_t curindent; // Indentation level of current line
int16_t stmtindent; // Indentation level of current statement
int16_t tokPosInLine; // 0=First token in line, 1=Second, etc.
char indentch; // Are we using spaces or tabs?
int16_t blkStackLvl; // How deep are we into block stack
LexBlockInfo blkStack[LEX_MAX_BLOCKS]; // Block stack
} Lexer;
// All the possible types for a token
enum TokenTypes {
EofToken, // End-of-file
// Numeric and Identifier tokens
IntLitToken, // Integer literal
FloatLitToken, // Float literal
StringLitToken, // String literal
IdentToken, // Identifier
MetaIdentToken, // Metaprogramming identifier (#if)
AttrIdentToken, // Attribute identifier (@samesize)
LifetimeToken, // Lifetime variable ('a)
PermToken, // Permission identifier
// Punctuation tokens
SemiToken, // ';'
ColonToken, // ':'
DblColonToken, // '::'
LCurlyToken, // '{'
RCurlyToken, // '}'
LBracketToken, // '['
RBracketToken, // ']'
LParenToken, // '('
RParenToken, // ')'
CommaToken, // ','
DotToken, // '.'
QuesDotToken, // '?.'
PlusToken, // '+'
PlusArrayRefToken, // '+[]'
PlusVirtRefToken, // '+<'
DashToken, // '-'
StarToken, // '*'
PercentToken, // '%'
SlashToken, // '/'
AmperToken, // '&'
ArrayRefToken, // '&[]'
VirtRefToken, // '&<'
AndToken, // 'and'
BarToken, // '|'
OrToken, // 'or'
CaretToken, // '^'
NotToken, // '!'
QuesToken, // '?'
TildeToken, // '~'
LessDashToken, // '<-'
AssgnToken, // '='
LAssgnToken, // ':='
SwapToken, // '<=>'
IsToken, // 'is'
EqToken, // '=='
NeToken, // '!='
LtToken, // '<'
LeToken, // '<='
GtToken, // '>'
GeToken, // '>='
ShlToken, // '<<'
ShrToken, // '>>'
PlusEqToken, // '+='
MinusEqToken, // '-='
MultEqToken, // '*='
DivEqToken, // '/='
RemEqToken, // '%='
OrEqToken, // '|='
AndEqToken, // '&='
XorEqToken, // '^='
ShlEqToken, // '<<='
ShrEqToken, // '>>='
IncrToken, // '++'
DecrToken, // '--'
// Keywords
IncludeToken, // 'include'
ImportToken, // 'import'
ExternToken, // 'extern'
SetToken, // 'set'
MacroToken, // 'macro'
FnToken, // 'fn'
TypedefToken, // 'typedef'
StructToken, // 'struct'
TraitToken, // 'trait'
StaticToken, // '@static'
SamesizeToken, // '@samesize'
MoveToken, // '@move'
OpaqueToken, // '@opaque'
ExtendsToken, // 'extends'
MixinToken, // 'mixin'
EnumToken, // 'enum'
RegionToken, // 'region'
RetToken, // 'return'
WithToken, // 'with'
IfToken, // 'if'
ElifToken, // 'elif'
ElseToken, // 'else'
MatchToken, // 'match'
LoopToken, // 'loop'
WhileToken, // 'while'
EachToken, // 'each'
InToken, // 'in'
ByToken, // 'step'
BreakToken, // 'break'
ContinueToken, // 'continue'
AsToken, // 'as'
IntoToken, // 'into'
InlineToken, // 'inline'
VoidToken, // 'void'
nilToken, // 'nil'
trueToken, // 'true'
falseToken, // 'false'
NbrTokens
};
// Current lexer
extern Lexer *lex;
#define lexIsToken(tok) (lex->toktype == (tok))
// Lexer functions
void lexInit(ConeOptions *opt);
void lexInjectFile(char *url);
void lexInject(char *src, char *url);
void lexPop();
void lexNextToken();
// Parser indicates new block starts here, e.g., '{'
void lexBlockStart(LexBlockMode mode);
// Does block end here, based on block mode?
int lexIsBlockEnd();
// Parser indicates block finishes here, e.g., '}'
void lexBlockEnd();
// Decrement counter for parentheses/brackets
void lexDecrParens();
// Increment counter for parentheses/brackets
void lexIncrParens();
// Is next token at start of line?
int lexIsEndOfLine();
// Parser signals the start of a new statement (for continuation analysis)
void lexStmtStart();
// Return true if current token is first on a line that has not been indented
// This is used by parser to determine whether an operator that starts a new line
// should be treated as a continuation (infix) or a new statement (prefix).
int lexIsStmtBreak();
#endif
| 30.616438 | 81 | 0.550336 |
a9223de08c0c12b04e12f999fcac0b106920ce59 | 10,839 | c | C | apps/speed_tests/firmware/src/cryptoST/cryptoSTE_aes_ctr.c | Microchip-MPLAB-Harmony/crypto_apps_speed_test | 3fdbdc79b8125c9d68c024a2c86bf42686b05111 | [
"0BSD"
] | null | null | null | apps/speed_tests/firmware/src/cryptoST/cryptoSTE_aes_ctr.c | Microchip-MPLAB-Harmony/crypto_apps_speed_test | 3fdbdc79b8125c9d68c024a2c86bf42686b05111 | [
"0BSD"
] | null | null | null | apps/speed_tests/firmware/src/cryptoST/cryptoSTE_aes_ctr.c | Microchip-MPLAB-Harmony/crypto_apps_speed_test | 3fdbdc79b8125c9d68c024a2c86bf42686b05111 | [
"0BSD"
] | null | null | null | /*******************************************************************************
Crypto Speed Test Source File
Company:
Microchip Technology Inc.
File Name:
cryptoST_aes_ctr.c
Summary:
AES CTR mode encryption driver
Description:
This file contains functions to measure the time required
to perform AES CTR encryption. Time is reported in clock ticks.
******************************************************************************
*/
//DOM-IGNORE-BEGIN
/*****************************************************************************
Copyright (C) 2013-2020 Microchip Technology Inc. and its subsidiaries.
Microchip Technology Inc. and its subsidiaries.
Subject to your compliance with these terms, you may use Microchip software
and any derivatives exclusively with Microchip products. It is your
responsibility to comply with third party license terms applicable to your
use of third party software (including open source software) that may
accompany Microchip software.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR
PURPOSE.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*****************************************************************************/
//DOM-IGNORE-END
// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************
#include "cryptoSTE_definitions.h"
#include "cryptoSTE_print.h"
#include "cryptoSTE_announce.h"
#include "cryptoSTE_aes_ctr.h"
#include "../../test_data/cryptoSpeedTestData.h"
// theory: one of these "fixes" build-time issues with wolfssl
#include <stddef.h>
#include <string.h>
#include <stdbool.h>
#include <wolfssl/wolfcrypt/settings.h>
// #include <wolfssl/wolfssl/verion.h>
#ifdef USE_FLAT_TEST_H
#include "test.h"
#else
// #include "wolfssl/wolfcrypt/test/test.h"
#endif
#include <wolfssl/wolfcrypt/types.h>
#include <wolfssl/wolfcrypt/des3.h>
#include <wolfssl/wolfcrypt/aes.h>
#include <wolfssl/wolfcrypt/wc_encrypt.h>
#if defined(WOLFSSL_AES_COUNTER)
// *****************************************************************************
// *****************************************************************************
// Section: Local data structures
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
// Section: Support routines
// *****************************************************************************
// *****************************************************************************
/* This is the generic encryption package.
* The public entry points are defined below.
* */
static const char * cryptoSTE_aes_ctr_timed(const cryptoST_testDetail_t * td,
cryptoSTE_testExecution_t * param)
{
const cryptoST_testVector_t * vector = td->rawData;
if (CSTE_VERBOSE > 2)
{
P0_UINT( " data=", vector->vector.length);
cryptoSTE_announceVector(2, vector);
cryptoSTE_announceDetails(2, td);
}
// Data validation
if ( (NULL == td->io.sym.in.key.data)
|| (NULL == td->io.sym.in.ivNonce.data) )
return "missing vector, key or initialization data" CRLF
" AES CTR test not activated." CRLF;
Aes enc;
int ret = 0;
byte* cipher = (byte*)malloc(vector->vector.length);
if (NULL == cipher)
return "cannot allocate memory (" __BASE_FILE__ " line " BASE_LINE ")";
ret = wc_AesSetKeyDirect(&enc, td->io.sym.in.key.data, td->io.sym.in.key.length,
td->io.sym.in.ivNonce.data, AES_ENCRYPTION);
if (ret != 0) return "failed to set key";
// Hold off until the serial port is finished
PRINT_WAIT_WHILE_BUSY();
/* If the golden ciphertext is shorter than the given data,
* use only that amount of data. This is a special test case
* for truncating the input buffer.
* */
size_t testLength = vector->vector.length;
if (td->io.sym.out.cipher.data && td->io.sym.out.cipher.length)
{
if (td->io.sym.out.cipher.length < testLength)
testLength = td->io.sym.out.cipher.length;
}
// Remove any data noise that is in the target buffer
XMEMSET(cipher, 0, sizeof(vector->vector.length));
param->results.encryption.iterations = param->parameters.iterationOverride?
param->parameters.iterationOverride
: td->recommendedRepetitions;
param->results.encryption.size = vector->vector.length;
param->results.encryption.start = SYS_TIME_CounterGet();
for (int i = param->results.encryption.iterations; i > 0; i--)
{
ret = wc_AesCtrEncrypt(&enc, cipher, vector->vector.data,
vector->vector.length);
if (ret != 0) return "encryption failed (" BASE_LINE ")";
}
param->results.encryption.stop = SYS_TIME_CounterGet();
param->results.encryption.startStopIsValid = true;
if (param->parameters.verifyByGoldenCiphertext)
{
if ((NULL == td->io.sym.out.cipher.data) || (0 == td->io.sym.out.cipher.length))
param->results.warningCount++,
param->results.warningMessage = "can't verify cipher: no golden data";
else if (XMEMCMP(cipher, td->io.sym.out.cipher.data, td->io.sym.out.cipher.length))
{
if (CSTE_VERBOSE)
{
P0_UINT(CRLF "test length = ", testLength);
cryptoST_PRINT_hexLine(CRLF "key : ",
td->io.sym.in.key.data, td->io.sym.in.key.length);
cryptoST_PRINT_hexLine(CRLF "initV : ",
td->io.sym.in.ivNonce.data, td->io.sym.in.ivNonce.length);
cryptoST_PRINT_hexLine(CRLF "given : ",
vector->vector.data, vector->vector.length);
cryptoST_PRINT_hexLine(CRLF "cipher: ",
cipher, ALENGTH(sizeof(cipher)));
cryptoST_PRINT_hexLine(CRLF "gold : ",
td->io.sym.out.cipher.data, td->io.sym.out.cipher.length);
PRINT(CRLF);
}
return "computed ciphertext does not match golden data (was iterate==1?)";
}
// Note: the test above will fail if iterate!=1.
}
if (param->parameters.verifyByDecryption)
{
Aes dec;
byte plain[AES_BLOCK_SIZE * 4]; // trouble here?
/* decrypt uses AES_ENCRYPTION */
ret = wc_AesSetKeyDirect(&dec, td->io.sym.in.key.data, td->io.sym.in.key.length,
td->io.sym.in.ivNonce.data, AES_ENCRYPTION);
if (ret != 0) return "setting decryption key failed";
// Conventional decrypt and comparison
if (CSTE_VERBOSE > 1)
PRINT_WAIT("-- decrypting and comparing" CRLF)
/* no such thing as wc_AesCtrDecrypt() */
ret = wc_AesCtrEncrypt(&dec, plain, cipher, AES_BLOCK_SIZE * 4);
if (ret != 0) return "decryption failed (" BASE_LINE ")";
if (XMEMCMP(plain, vector->vector.data, AES_BLOCK_SIZE))
{
if (CSTE_VERBOSE)
{
cryptoST_PRINT_hexLine(CRLF "key : ",
td->io.sym.in.key.data, td->io.sym.in.key.length);
cryptoST_PRINT_hexLine(CRLF "initV : ",
td->io.sym.in.ivNonce.data, td->io.sym.in.ivNonce.length);
cryptoST_PRINT_hexLine(CRLF "given : ",
vector->vector.data, vector->vector.length);
cryptoST_PRINT_hexLine(CRLF "plain : ",
plain, ALENGTH(plain));
PRINT(CRLF);
}
return "recovered data does not match original";
}
}
free(cipher);
return 0;
}
// *****************************************************************************
// *****************************************************************************
// Section: External API
// *****************************************************************************
// *****************************************************************************
#undef TNAME
#define TNAME "WOLF AES CTR 128"
const char * cryptoSTE_aes_ctr_128_timed(const cryptoST_testDetail_t * td,
cryptoSTE_testExecution_t * param)
{
param->results.testHandler = TNAME;
if (CSTE_VERBOSE > 1) PRINT(CRLF);
// Data validation
if (td->io.sym.in.key.length != 128/8)
return "incorrect key length" CRLF
" " TNAME " test not activated." CRLF;
else
return cryptoSTE_aes_ctr_timed(td, param);
}
#undef TNAME
#define TNAME "WOLF AES CTR 192"
const char * cryptoSTE_aes_ctr_192_timed(const cryptoST_testDetail_t * td,
cryptoSTE_testExecution_t * param)
{
param->results.testHandler = TNAME;
if (CSTE_VERBOSE > 1) PRINT(CRLF);
// Data validation
if (td->io.sym.in.key.length != 192/8)
return "incorrect key length" CRLF
" " TNAME " test not activated." CRLF;
else
return cryptoSTE_aes_ctr_timed(td, param);
}
#undef TNAME
#define TNAME "WOLF AES CTR 256"
const char * cryptoSTE_aes_ctr_256_timed(const cryptoST_testDetail_t * td,
cryptoSTE_testExecution_t * param)
{
param->results.testHandler = TNAME;
if (CSTE_VERBOSE > 1) PRINT(CRLF);
// Data validation
if (td->io.sym.in.key.length != 256/8)
return "incorrect key length" CRLF
" " TNAME " test not activated." CRLF;
else
return cryptoSTE_aes_ctr_timed(td, param);
}
#endif // WOLFSSL_AES_COUNTER
| 39.271739 | 91 | 0.532798 |
650a35cc4cb85ac3444d62ad0eeaf19a7301eb59 | 4,731 | h | C | ll_codec/impl/msdk/utility/mfx_external_buffers.h | LoSealL/lltech | 5acb399820c99f84345e88537c7db259e13d63e4 | [
"MIT"
] | 1 | 2019-09-11T11:55:07.000Z | 2019-09-11T11:55:07.000Z | ll_codec/impl/msdk/utility/mfx_external_buffers.h | LoSealL/lltech | 5acb399820c99f84345e88537c7db259e13d63e4 | [
"MIT"
] | null | null | null | ll_codec/impl/msdk/utility/mfx_external_buffers.h | LoSealL/lltech | 5acb399820c99f84345e88537c7db259e13d63e4 | [
"MIT"
] | null | null | null | /********************************************************************
Copyright 2017-2018 Tang, Wenyi. All Rights Reserved.
Author : Wenyi Tang
Email : wenyi.tang@intel.com
Created : Feb. 15th, 2017
Mod : Date Author
Intel MediaSDK external buffer wrappers
********************************************************************/
#ifndef LL_CODEC_MFXVR_UTILITY_MFX_EXTERNAL_BUFFERS_H_
#define LL_CODEC_MFXVR_UTILITY_MFX_EXTERNAL_BUFFERS_H_
#include <mfxdefs.h>
#include <mfxstructures.h>
#include "ll_codec/impl/msdk/utility/mfx_error.h"
namespace mfxvr {
/* External buffer template */
template <typename T>
class CExtBuffer {
public:
CExtBuffer() { std::memset(&extbuff, 0, sizeof(T)); }
mfxExtBuffer *getAddressOf() {
return reinterpret_cast<mfxExtBuffer *>(&extbuff);
}
T *get() { return &extbuff; }
protected:
T extbuff;
};
class CVPPDoNotUse : public CExtBuffer<mfxExtVPPDoNotUse> {
public:
CVPPDoNotUse() {
extbuff.Header.BufferId = MFX_EXTBUFF_VPP_DONOTUSE;
extbuff.Header.BufferSz = sizeof(extbuff);
extbuff.NumAlg = 4;
extbuff.AlgList = new mfxU32[extbuff.NumAlg];
// turn off denoising (on by default)
extbuff.AlgList[0] = MFX_EXTBUFF_VPP_DENOISE;
// turn off scene analysis (on by default)
extbuff.AlgList[1] = MFX_EXTBUFF_VPP_SCENE_ANALYSIS;
// turn off detail enhancement (on by default)
extbuff.AlgList[2] = MFX_EXTBUFF_VPP_DETAIL;
// turn off processing amplified (on by default)
extbuff.AlgList[3] = MFX_EXTBUFF_VPP_PROCAMP;
}
virtual ~CVPPDoNotUse() { delete[] extbuff.AlgList; }
};
class CVPPScaling : public CExtBuffer<mfxExtVPPScaling> {
public:
CVPPScaling() {
extbuff.Header.BufferId = MFX_EXTBUFF_VPP_SCALING;
extbuff.Header.BufferSz = sizeof(extbuff);
extbuff.ScalingMode = MFX_SCALING_MODE_LOWPOWER;
}
virtual ~CVPPScaling() {}
};
class CVPPMirror : public CExtBuffer<mfxExtVPPMirroring> {
public:
CVPPMirror() {
extbuff.Header.BufferId = MFX_EXTBUFF_VPP_MIRRORING;
extbuff.Header.BufferSz = sizeof(extbuff);
}
virtual ~CVPPMirror() {}
void SetType(mfxU16 type) { extbuff.Type = type; }
};
class CVPPRotate : public CExtBuffer<mfxExtVPPRotation> {
public:
CVPPRotate() {
extbuff.Header.BufferId = MFX_EXTBUFF_VPP_ROTATION;
extbuff.Header.BufferSz = sizeof(extbuff);
}
virtual ~CVPPRotate() {}
void SetAngle(mfxU16 r) { extbuff.Angle = r; }
};
class CVPPMVC : public CExtBuffer<mfxExtMVCSeqDesc> {
public:
CVPPMVC() {
extbuff.Header.BufferId = MFX_EXTBUFF_MVC_SEQ_DESC;
extbuff.Header.BufferSz = sizeof(extbuff);
extbuff.NumView = extbuff.NumViewAlloc = 2;
extbuff.NumViewId = extbuff.NumViewIdAlloc = 2;
extbuff.NumOP = extbuff.NumOPAlloc = 1;
extbuff.View = new mfxMVCViewDependency[extbuff.NumViewAlloc];
for (mfxU16 i = 0; extbuff.NumViewAlloc > i; ++i) {
extbuff.View[i].ViewId = i;
}
extbuff.View[1].NumAnchorRefsL0 = 1;
extbuff.View[1].AnchorRefL0[0] = 0;
extbuff.View[1].NumNonAnchorRefsL0 = 1;
extbuff.View[1].NonAnchorRefL0[0] = 0;
extbuff.ViewId = new mfxU16[extbuff.NumViewIdAlloc];
for (mfxU16 i = 0; extbuff.NumViewIdAlloc > i; ++i) {
extbuff.ViewId[i] = i;
}
extbuff.OP = new mfxMVCOperationPoint[extbuff.NumOPAlloc];
for (mfxU16 i = 0; extbuff.NumOPAlloc > i; ++i) {
std::memset(&extbuff.OP[i], 0, sizeof(extbuff.OP[i]));
extbuff.OP[i].NumViews = 2;
extbuff.OP[i].NumTargetViews = 2;
extbuff.OP[i].TargetViewId = extbuff.ViewId;
}
}
virtual ~CVPPMVC() {
delete[] extbuff.View;
delete[] extbuff.ViewId;
delete[] extbuff.OP;
}
};
class CENCROI : public CExtBuffer<mfxExtEncoderROI> {
public:
CENCROI() {
extbuff.Header.BufferId = MFX_EXTBUFF_ENCODER_ROI;
extbuff.Header.BufferSz = sizeof(extbuff);
extbuff.NumROI = 1;
extbuff.ROIMode = MFX_ROI_MODE_QP_DELTA;
}
void setRoiRegion(const mfxU32 width, const mfxU32 height,
const mfxU32 regions, const mfxI16 *qpi,
const mfxU32 *ratioN, const mfxU32 ratioD = 16) {
extbuff.NumROI = static_cast<mfxU16>(regions);
if (regions >= 256 || !qpi || !ratioN || !ratioD) {
throw CVRMFXError("ROI Region overflow!", MFX_ERR_INVALID_VIDEO_PARAM);
}
for (mfxU32 i = 0; i < regions; i++) {
extbuff.ROI[i].Left = width * ratioN[i] / ratioD;
extbuff.ROI[i].Right = width * (ratioD - ratioN[i]) / ratioD;
extbuff.ROI[i].Top = height * ratioN[i] / ratioD;
extbuff.ROI[i].Bottom = height * (ratioD - ratioN[i]) / ratioD;
extbuff.ROI[i].DeltaQP = qpi[i];
}
}
};
} // namespace mfxvr
#endif // LL_CODEC_MFXVR_UTILITY_MFX_EXTERNAL_BUFFERS_H_
| 30.326923 | 77 | 0.662862 |
650d843c4a86eedc6ccde610ec87420464b629a3 | 304 | h | C | WeekEndHigh/Classes/Discover/Views/DiscoverTableViewCell.h | Wangxiaoqi-One/weekEndHigh | a951e1f7df188048c40c2d6e0e47126ed1aba182 | [
"Apache-2.0"
] | null | null | null | WeekEndHigh/Classes/Discover/Views/DiscoverTableViewCell.h | Wangxiaoqi-One/weekEndHigh | a951e1f7df188048c40c2d6e0e47126ed1aba182 | [
"Apache-2.0"
] | null | null | null | WeekEndHigh/Classes/Discover/Views/DiscoverTableViewCell.h | Wangxiaoqi-One/weekEndHigh | a951e1f7df188048c40c2d6e0e47126ed1aba182 | [
"Apache-2.0"
] | null | null | null | //
// DiscoverTableViewCell.h
// WeekEndHigh
//
// Created by scjy on 16/1/12.
// Copyright © 2016年 scjy. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "DiscoverModel.h"
@interface DiscoverTableViewCell : UITableViewCell
@property (nonatomic, strong) DiscoverModel *discoverModel;
@end
| 17.882353 | 59 | 0.730263 |
04b4dac1055cdc956b52312121265a9bf30dcdd8 | 7,046 | c | C | src/render/vector.c | oskar404/thesis | 092e1d298bccf396329a7ffd1f5afbacb0794db3 | [
"Apache-2.0"
] | null | null | null | src/render/vector.c | oskar404/thesis | 092e1d298bccf396329a7ffd1f5afbacb0794db3 | [
"Apache-2.0"
] | null | null | null | src/render/vector.c | oskar404/thesis | 092e1d298bccf396329a7ffd1f5afbacb0794db3 | [
"Apache-2.0"
] | null | null | null | /***************************************************************/
/* vector.c */
/***************************************************************/
/*
MODULE PURPOSE:
This module contains routines that preform common
vector geometric manipulations for image synthesis.
MODULE CONTENTS:
VecotrDot - vector dot product
VectorCross - vector cross product
VectorNorm - vector normalization
VectorGetv - generate a vector
VectorReflected - compute the reflected vector
VectorRefracted - compute the refracted vector
VectorH - compute H vector
VectorHt - compute the H' vector
*/
#include <stdio.h>
#include <math.h>
#include "vector.h"
/***************************************************************
double VectorDot (VECTOR *v0,VECTOR *vl)
v0, vl normalised direction vectors
Returns the dot product of two direction vectors.
Note that the dot product is the cosine between the
direction vectors because the direction vectors are
normalised.
*/
double VectorDot (VECTOR *v0,VECTOR *v1)
{
return ((v0->i*v1->i)+(v0->j*v1->j)+(v0->k*v1->k));
}
/***************************************************************
VECTOR VectorCross (VECTOR *v0,VECTOR *vl)
v0, vl normalised direction vectors
Returns the cross product of two direction vectors.
*/
VECTOR *VectorCross (VECTOR *v0,VECTOR *v1)
{
static VECTOR v2;
v2.i = (v0->j * v1->k) - (v0->k * v1->j);
v2.j = (v0->k * v1->i) - (v0->i * v1->k);
v2.k = (v0->i * v1->j) - (v0->j * v1->i);
return &v2;
}
/***************************************************************
double VectorNorm (VECTOR *v0)
v0 (mod) vector to be normalised
Returns the vector length before normalization.
Returns zero if the vector could not be normalised.
Note that the input vector is modified.
*/
double VectorNorm (VECTOR *v0)
{
double len;
if ((len = VectorDot(v0, v0)) <= 0.0)
return FALSE;
len = sqrt((double)len);
v0->i /= len;
v0->j /= len;
v0->k /= len;
return len;
}
/***************************************************************
double VectorLine (POINT *p0,POINT *p1,LINE *v)
p0, p1 (in) from, to points
v (out) generated line
Returns the distance from p0 to p1. Returns 0.0
on error (p0=p1). The line is expressed in parametric
form with a start point (p0) and a normalised direction
vector.
*/
double VectorLine (POINT *p0,POINT *p1,LINE *v)
{
v->start = *p0;
v->dir.i = p1->x - p0->x;
v->dir.j = p1->y - p0->y;
v->dir.k = p1->z - p0->z;
return VectorNorm(&v->dir);
}
/***************************************************************
VECTOR *VectorReflected (VECTOR *L,VECTOR *N)
L (in) incident vector
N (in) surface normal
Returns the reflected direction vector. The reflected
direction is computed using the method given by Whitted
(1980).
*/
VECTOR *VectorReflected (VECTOR *L,VECTOR *N)
{
double N_dot_L;
static VECTOR rfl;
N_dot_L = VectorDot (N,L);
rfl.i = (2.0 * N_dot_L * N->i) - L->i;
rfl.j = (2.0 * N_dot_L * N->j) - L->j;
rfl.k = (2.0 * N_dot_L * N->k) - L->k;
return &rfl;
}
/***************************************************************
VECTOR *VectorRefracted (VECTOR *L,VECTOR *N,double ni,double nt)
L (in) incident vector
N (in) surface normal
ni (in) index of refraction for the
material on the front of the
interface (same side as N)
nt (in) index of refraction for the
material on the back of the
interface (opposite size as N)
Returns the refracted vector, if thereis complete internal
refracted vector otherwise a NULL vector is returned. The
vector is computed using the method given by Hall (1983).
*/
VECTOR *VectorRefracted (VECTOR *L,VECTOR *N,double ni,double nt)
{
static VECTOR T; /* the refracted vector */
VECTOR sin_T; /* sin vector of the refracted vector */
VECTOR cos_L; /* cos vector of the incident vector */
double len_sin_T; /* length of sin T squared */
double n_mult; /* ni over nt */
double N_dot_L;
double N_dot_T;
if ((N_dot_L = VectorDot(N,L)) > 0.0)
n_mult = ni / nt;
else
n_mult = nt / ni;
cos_L.i = N_dot_L * N->i;
cos_L.j = N_dot_L * N->j;
cos_L.k = N_dot_L * N->k;
sin_T.i = (n_mult) * (cos_L.i - L->i);
sin_T.j = (n_mult) * (cos_L.j - L->j);
sin_T.k = (n_mult) * (cos_L.k - L->k);
if ((len_sin_T = VectorDot(&sin_T, &sin_T)) >= 1.0)
return NULL; /* internal reflection */
N_dot_T=sqrt(1.0-len_sin_T);
if(N_dot_L<0.0)
N_dot_T=-N_dot_T;
T.i = sin_T.i - (N->i * N_dot_T);
T.j = sin_T.j - (N->j * N_dot_T);
T.k = sin_T.k - (N->k * N_dot_T);
return &T;
}
/***************************************************************
VECTOR *VectorH (VECTOR *L,VECTOR *E)
L (in) incident vector
E (in) reflected vector
Returns H, NULL on error (if L+H = 0).
*/
VECTOR *VectorH (VECTOR *L,VECTOR *E)
{
static VECTOR H;
H.i = L->i + E->i;
H.j = L->j + E->j;
H.k = L->k + E->k;
if (VectorNorm(&H))
return NULL;
return &H;
}
/***************************************************************
VECTOR *VectorHt(VECTOR *L,VECTOR *T,double ni,double nt)
L (in) incident vector
T (in) transmitted hector
ni (in) incident index
nt (in) transmitted index
Returns H' oriented to the same side of the surface
as L computed using the method suggested by
Hall (1983). Returns NULL on error (if the angle
between V and L is less than the critical angle).
*/
VECTOR *VectorHt(VECTOR *L,VECTOR *T,double ni,double nt)
{
double L_dot_T;
double divisor;
static VECTOR Ht;
L_dot_T = -(VectorDot(L,T));
/* check for special cases */
if (ni == nt) {
if (L_dot_T == 1.0)
return L;
else
return NULL;
}
if (ni < nt) {
if (L_dot_T < ni/nt)
return NULL;
divisor = (nt / ni) - 1.0;
Ht.i = -(((L->i + T->i) / divisor) + T->i);
Ht.j = -(((L->j + T->j) / divisor) + T->j);
Ht.k = -(((L->k + T->k) / divisor) + T->k);
}
else
{
if (L_dot_T < nt/ni)
return NULL;
divisor = (ni / nt) - 1.0;
Ht.i = ((L->i + T->i) / divisor) + L->i;
Ht.j = ((L->j + T->j) / divisor) + L->j;
Ht.k = ((L->k + T->k) / divisor) + L->k;
}
(void)VectorNorm(&Ht);
return &Ht;
}
| 26.193309 | 74 | 0.490775 |
04cb550c7b1ceccf4c0127e2aea2f35b9be00677 | 17,781 | c | C | cas/index_gc.c | gshipra/cortx-motr | 41fb5b1f99d928f54d9c5005939d9b7bead621d9 | [
"Apache-2.0"
] | null | null | null | cas/index_gc.c | gshipra/cortx-motr | 41fb5b1f99d928f54d9c5005939d9b7bead621d9 | [
"Apache-2.0"
] | null | null | null | cas/index_gc.c | gshipra/cortx-motr | 41fb5b1f99d928f54d9c5005939d9b7bead621d9 | [
"Apache-2.0"
] | null | null | null | /* -*- C -*- */
/*
* Copyright (c) 2015-2020 Seagate Technology LLC and/or its Affiliates
*
* 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.
*
* For any questions about this software or licensing,
* please email opensource@seagate.com or cortx-questions@seagate.com.
*
*/
#define M0_TRACE_SUBSYSTEM M0_TRACE_SUBSYS_CAS
#include "lib/trace.h"
#include "lib/memory.h"
#include "lib/assert.h"
#include "lib/cond.h" /* m0_cond */
#include "fop/fop.h" /* M0_FOP_TYPE_INIT */
#include "fop/fom_long_lock.h"
#include "fop/fom_generic.h"
#include "rpc/rpc_opcodes.h"
#include "rpc/item.h" /* M0_RPC_ITEM_TYPE_REQUEST */
#include "cas/ctg_store.h"
#include "motr/setup.h"
/**
* @page cas-gc Deleted index garbage collection
*
* @subsection cgc-lspec-state State Specification
*
* @verbatim
*
* FOPH_INIT
* |
* V
* [generic phases]
* .
* .
* V
* M0_FOPH_AUTHORISATION
* |
* V
* CGC_LOOKUP
* |
* V
* SUCCESS<----------CGC_INDEX_FOUND
* |
* V
* TXN_INIT
* |
* V
* CGC_CREDITS
* |
* V
* TXN_OPEN
* |
* V
* [generic phases]
* .
* .
* V
* CGC_TREE_CLEAN
* |
* V
* SUCCESS<-----------CGC_TREE_DROP
* |
* V
* CGC_LOCK_DEAD_INDEX
* |
* V
* CGC_RM_FROM_DEAD_INDEX
* |
* V
* CGC_SUCCESS
* |
* V
* SUCCESS
* @endverbatim
*/
static size_t cgc_fom_home_locality (const struct m0_fom *fom);
static int cgc_fom_tick (struct m0_fom *fom);
static void cgc_fom_fini (struct m0_fom *fom);
static void cgc_retry (void);
enum cgc_fom_phase {
CGC_TREE_CLEAN = M0_FOPH_TYPE_SPECIFIC,
CGC_LOOKUP,
CGC_INDEX_FOUND,
CGC_CREDITS,
CGC_TREE_DROP,
CGC_LOCK_DEAD_INDEX,
CGC_RM_FROM_DEAD_INDEX,
CGC_SUCCESS,
CGC_NR
};
struct cgc_fom {
struct m0_fom cg_fom;
struct m0_fop cg_fop;
struct m0_long_lock_link cg_dead_index;
struct m0_long_lock_addb2 cg_dead_index_addb2;
struct m0_cas_ctg *cg_ctg;
struct m0_ctg_op cg_ctg_op;
bool cg_ctg_op_initialized;
struct m0_buf cg_ctg_key;
struct m0_reqh *cg_reqh;
m0_bcount_t cg_del_limit;
};
struct cgc_context {
struct m0_mutex cgc_mutex;
struct m0_cond cgc_cond;
int cgc_running;
bool cgc_waiting;
struct m0_be_op *cgc_op;
};
static struct cgc_context gc;
static const struct m0_fom_ops cgc_fom_ops = {
.fo_fini = &cgc_fom_fini,
.fo_tick = &cgc_fom_tick,
.fo_home_locality = &cgc_fom_home_locality
};
M0_INTERNAL struct m0_fop_type cgc_fake_fopt;
static const struct m0_fom_type_ops cgc_fom_type_ops = {
.fto_create = NULL
};
static struct m0_sm_state_descr cgc_fom_phases[] = {
[CGC_LOOKUP] = {
.sd_name = "cgc-lookup",
.sd_allowed = M0_BITS(CGC_INDEX_FOUND)
},
[CGC_INDEX_FOUND] = {
.sd_name = "cgc-index-found",
.sd_allowed = M0_BITS(M0_FOPH_TXN_INIT, M0_FOPH_SUCCESS)
},
[CGC_CREDITS] = {
.sd_name = "cgc-credits-get",
.sd_allowed = M0_BITS(M0_FOPH_TXN_OPEN)
},
[CGC_TREE_CLEAN] = {
.sd_name = "cgc-tree-clean",
.sd_allowed = M0_BITS(CGC_TREE_DROP)
},
[CGC_TREE_DROP] = {
.sd_name = "cgc-tree-drop",
.sd_allowed = M0_BITS(CGC_LOCK_DEAD_INDEX, M0_FOPH_SUCCESS)
},
[CGC_LOCK_DEAD_INDEX] = {
.sd_name = "cgc-lock-dead-index",
.sd_allowed = M0_BITS(CGC_RM_FROM_DEAD_INDEX)
},
[CGC_RM_FROM_DEAD_INDEX] = {
.sd_name = "cgc-rm-from-dead-index",
.sd_allowed = M0_BITS(CGC_SUCCESS),
},
[CGC_SUCCESS] = {
.sd_name = "cgc-success",
.sd_allowed = M0_BITS(M0_FOPH_SUCCESS)
},
};
struct m0_sm_trans_descr cgc_fom_trans[] = {
[ARRAY_SIZE(m0_generic_phases_trans)] =
{ "cgc-starting", M0_FOPH_TXN_INIT, CGC_LOOKUP },
{ "cgc-index-lookup", CGC_LOOKUP, CGC_INDEX_FOUND },
{ "cgc-start-txn", CGC_INDEX_FOUND, M0_FOPH_TXN_INIT },
{ "cgc-no-job", CGC_INDEX_FOUND, M0_FOPH_SUCCESS },
{ "cgc-starting", M0_FOPH_TXN_OPEN, CGC_CREDITS },
{ "cgc-credits", CGC_CREDITS, M0_FOPH_TXN_OPEN },
{ "cgc-tree-drop", CGC_TREE_CLEAN, CGC_TREE_DROP },
{ "cgc-start-lock", CGC_TREE_DROP, CGC_LOCK_DEAD_INDEX },
{ "cgc-commit-clean", CGC_TREE_DROP, M0_FOPH_SUCCESS },
{ "cgc-rm-dead", CGC_LOCK_DEAD_INDEX, CGC_RM_FROM_DEAD_INDEX },
{ "cgc-forget", CGC_RM_FROM_DEAD_INDEX, CGC_SUCCESS },
{ "cgc-done", CGC_SUCCESS, M0_FOPH_SUCCESS }
};
static struct m0_sm_conf cgc_sm_conf = {
.scf_name = "cgc-fom",
.scf_nr_states = ARRAY_SIZE(cgc_fom_phases),
.scf_state = cgc_fom_phases,
.scf_trans_nr = ARRAY_SIZE(cgc_fom_trans),
.scf_trans = cgc_fom_trans
};
static size_t cgc_fom_home_locality(const struct m0_fom *fom)
{
return 0;
}
static int cgc_fom_tick(struct m0_fom *fom0)
{
struct cgc_fom *fom = M0_AMB(fom, fom0, cg_fom);
int phase = m0_fom_phase(fom0);
struct m0_ctg_op *ctg_op = &fom->cg_ctg_op;
int result = M0_FSO_AGAIN;
int rc;
M0_ENTRY("fom %p phase %d", fom, phase);
switch (phase) {
case M0_FOPH_INIT ... M0_FOPH_NR - 1:
if (phase == M0_FOPH_FAILURE) {
struct m0_long_lock *ll;
ll = m0_ctg_lock(m0_ctg_dead_index());
M0_LOG(M0_DEBUG, "Cleanup CGC");
if (m0_long_is_write_locked(ll, fom0)) {
m0_long_unlock(ll, &fom->cg_dead_index);
M0_LOG(M0_DEBUG, "Lock released");
}
m0_ctg_fini(fom0, fom->cg_ctg);
if (fom->cg_ctg_op_initialized) {
m0_ctg_op_fini(ctg_op);
fom->cg_ctg_op_initialized = false;
M0_LOG(M0_DEBUG, "ctg op finalized");
}
}
result = m0_fom_tick_generic(fom0);
/*
* Intercept generic fom control flow when starting transaction
* init. Note: when we intercepted it here, state is already set
* to M0_FOPH_TXN_INIT.
* Seek for an index to drop and collect credits before
* transaction initialized.
*/
if (phase == M0_FOPH_AUTHORISATION) {
if (M0_FI_ENABLED("fail_in_cgc_generic_phase")) {
M0_LOG(M0_DEBUG, "Fail the FOM at TXN_INIT");
m0_fom_phase_move(fom0, -ENOMEM,
M0_FOPH_FAILURE);
result = M0_FSO_AGAIN;
break;
}
m0_fom_phase_set(fom0, CGC_LOOKUP);
}
/*
* Intercept generic fom control flow control after transaction
* init but before its start complete: need to reserve credits.
*/
if (phase == M0_FOPH_TXN_INIT)
m0_fom_phase_set(fom0, CGC_CREDITS);
/*
* Jump over fom_queue_reply() which does nothing if fom is
* local, but still asserts in absence of fo_rep_fop which we do
* not need.
*/
if (phase == M0_FOPH_TXN_COMMIT)
m0_fom_phase_set(fom0, M0_FOPH_TXN_COMMIT_WAIT);
break;
case CGC_LOOKUP:
m0_ctg_op_init(ctg_op, fom0, 0);
fom->cg_ctg_op_initialized = true;
/*
* Actually we need any value from the dead index. Min key value
* is ok. Do not need to lock dead index here: btree logic uses
* its own short time lock.
*/
result = m0_ctg_minkey(ctg_op, m0_ctg_dead_index(),
CGC_INDEX_FOUND);
break;
case CGC_INDEX_FOUND:
rc = m0_ctg_op_rc(ctg_op);
if (rc == 0) {
fom->cg_ctg_key = ctg_op->co_out_key;
fom->cg_ctg = *(struct m0_cas_ctg **)
ctg_op->co_out_key.b_addr;
M0_LOG(M0_DEBUG, "got index, ctg %p", fom->cg_ctg);
m0_ctg_try_init(fom->cg_ctg);
/*
* Use generic fom to open transaction already having
* credits in hands.
* Also lock dead index for write.
*/
result = m0_long_write_lock(
m0_ctg_lock(m0_ctg_dead_index()),
&fom->cg_dead_index,
M0_FOPH_TXN_INIT);
result = M0_FOM_LONG_LOCK_RETURN(result);
if (M0_FI_ENABLED("fail_after_index_found")) {
M0_LOG(M0_DEBUG, "Fail after CGC_INDEX_FOUND");
m0_fom_phase_move(fom0, -ENOMEM,
M0_FOPH_FAILURE);
result = M0_FSO_AGAIN;
}
} else {
/*
* -ENOENT is expected here meaning no entries in dead
* index. Otherwise it's some unexpected error.
*/
if (rc == -ENOENT)
M0_LOG(M0_DEBUG, "nothing in dead index");
else
M0_LOG(M0_WARN, "cgc lookup error %d", rc);
/*
* Done, exit fom. cgc_fom_fini() may decide to re-start
* GC fom if cas service dropped some index while we
* were busy here. Abort transaction.
*/
m0_fom_phase_set(fom0, M0_FOPH_SUCCESS);
}
m0_ctg_op_fini(ctg_op);
fom->cg_ctg_op_initialized = false;
break;
case CGC_CREDITS:
/*
* Calculate credits. Must not delete more than
* del_limit records in the single transaction.
* Must calculate credits now, after transaction init but before
* its open in the generic fom.
*/
m0_ctg_dead_clean_credit(&fom0->fo_tx.tx_betx_cred);
m0_ctg_drop_credit(fom0, &fom0->fo_tx.tx_betx_cred,
fom->cg_ctg, &fom->cg_del_limit);
m0_fom_phase_set(fom0, M0_FOPH_TXN_OPEN);
break;
/*
* This is M0_FOPH_TYPE_SPECIFIC in generic fom - kind of
* "legal" entry point for us.
*/
case CGC_TREE_CLEAN:
/*
* Transaction is now open. Start tree cleanup process. Remove
* all records from the tree but keep empty tree alive.
*/
m0_ctg_op_init(ctg_op, fom0, 0);
fom->cg_ctg_op_initialized = true;
result = m0_ctg_truncate(ctg_op, fom->cg_ctg,
fom->cg_del_limit,
CGC_TREE_DROP);
break;
case CGC_TREE_DROP:
rc = m0_ctg_op_rc(ctg_op);
m0_ctg_op_fini(ctg_op);
fom->cg_ctg_op_initialized = false;
if (rc == 0 && m0_be_btree_is_empty(&fom->cg_ctg->cc_tree)) {
M0_LOG(M0_DEBUG, "tree cleaned, now drop it");
m0_ctg_op_init(ctg_op, fom0, 0);
fom->cg_ctg_op_initialized = true;
result = m0_ctg_drop(ctg_op, fom->cg_ctg,
CGC_LOCK_DEAD_INDEX);
} else {
M0_LOG(M0_DEBUG, "out of credits, commit & restart");
m0_long_unlock(m0_ctg_lock(m0_ctg_dead_index()),
&fom->cg_dead_index);
cgc_retry();
/*
* If out of credits. Commit transaction and
* start from the very beginning, by creating
* new fom.
* Let generic fom commit transaction for us.
*/
m0_fom_phase_set(fom0, M0_FOPH_SUCCESS);
}
break;
case CGC_LOCK_DEAD_INDEX:
m0_ctg_op_fini(ctg_op);
m0_ctg_op_init(ctg_op, fom0, 0);
fom->cg_ctg_op_initialized = true;
m0_ctg_fini(fom0, fom->cg_ctg);
m0_fom_phase_set(fom0, CGC_RM_FROM_DEAD_INDEX);
result = M0_FSO_AGAIN;
break;
case CGC_RM_FROM_DEAD_INDEX:
m0_ctg_op_fini(ctg_op);
m0_ctg_op_init(ctg_op, fom0, 0);
fom->cg_ctg_op_initialized = true;
/*
* Now completely forget this ctg by deleting its descriptor
* from "dead index" catalogue.
*/
result = m0_ctg_delete(ctg_op, m0_ctg_dead_index(),
&fom->cg_ctg_key, CGC_SUCCESS);
break;
case CGC_SUCCESS:
m0_long_unlock(m0_ctg_lock(m0_ctg_dead_index()),
&fom->cg_dead_index);
m0_ctg_op_fini(ctg_op);
fom->cg_ctg_op_initialized = false;
/*
* Retry: maybe, have more trees to drop.
*/
cgc_retry();
/*
* Let generic fom commit transaction for us.
*/
m0_fom_phase_set(fom0, M0_FOPH_SUCCESS);
break;
}
return M0_RC(result);
}
static void cgc_retry(void)
{
/*
* Increment gc.cgc_running to launch same GC fom again
* just after fini: we still have data to delete.
*/
m0_mutex_lock(&gc.cgc_mutex);
gc.cgc_running++;
m0_mutex_unlock(&gc.cgc_mutex);
}
M0_INTERNAL void m0_cas_gc_init(void)
{
M0_ENTRY();
m0_sm_conf_extend(m0_generic_conf.scf_state, cgc_fom_phases,
m0_generic_conf.scf_nr_states);
m0_sm_conf_trans_extend(&m0_generic_conf, &cgc_sm_conf);
cgc_fom_phases[M0_FOPH_TXN_INIT].sd_allowed |= M0_BITS(CGC_LOOKUP);
cgc_fom_phases[M0_FOPH_TXN_OPEN].sd_allowed |= M0_BITS(CGC_CREDITS);
m0_sm_conf_init(&cgc_sm_conf);
m0_mutex_init(&gc.cgc_mutex);
m0_cond_init(&gc.cgc_cond, &gc.cgc_mutex);
gc.cgc_running = 0;
/*
* Actually we do not need a fop. But generic fom wants it, and it must
* be of type request and mutabo.
*/
M0_FOP_TYPE_INIT(&cgc_fake_fopt,
.name = "cgc-fake",
.opcode = M0_CAS_GCF_FOP_OPCODE,
.rpc_flags = M0_RPC_ITEM_TYPE_REQUEST |
M0_RPC_ITEM_TYPE_MUTABO,
.fom_ops = &cgc_fom_type_ops,
.sm = &cgc_sm_conf,
.svc_type = &m0_cas_service_type);
M0_LEAVE();
}
M0_INTERNAL void m0_cas_gc_fini(void)
{
M0_ENTRY();
gc.cgc_running = 0;
m0_fop_type_fini(&cgc_fake_fopt);
m0_cond_fini(&gc.cgc_cond);
m0_mutex_fini(&gc.cgc_mutex);
m0_sm_conf_fini(&cgc_sm_conf);
M0_LEAVE();
}
static void cgc_fop_release(struct m0_ref *ref)
{
struct m0_fop *fop;
M0_ENTRY();
fop = container_of(ref, struct m0_fop, f_ref);
/* Fop is a part of cgc_fom, it shouldn't be freed. */
m0_fop_fini(fop);
M0_LEAVE();
}
static void cgc_start_fom(struct m0_fom *fom0, struct m0_fop *fop)
{
struct cgc_fom *fom = M0_AMB(fom, fom0, cg_fom);
M0_ENTRY();
/*
* Need a fop to use transactions from generic fom. If it is null, crash
* in fom_is_update().
*/
m0_fop_init(fop, &cgc_fake_fopt, NULL, &cgc_fop_release);
m0_fom_init(fom0, &fop->f_type->ft_fom_type,
&cgc_fom_ops, fop, NULL, fom->cg_reqh);
fom0->fo_local = true;
fom->cg_ctg_op_initialized = false;
m0_long_lock_link_init(&fom->cg_dead_index, fom0,
&fom->cg_dead_index_addb2);
m0_fom_queue(fom0);
M0_LOG(M0_DEBUG, "CGC fom enqueued");
M0_LEAVE();
}
/**
* Finalise current index GC fom and, maybe, start new one.
*/
static void cgc_fom_fini(struct m0_fom *fom0)
{
struct cgc_fom *fom = M0_AMB(fom, fom0, cg_fom);
M0_ENTRY();
M0_ASSERT(fom0->fo_fop != NULL);
M0_ASSERT(fom0->fo_fop == &fom->cg_fop);
m0_mutex_lock(&gc.cgc_mutex);
gc.cgc_running--;
/*
* Our fop has 2 reference counts: 1 for create, 1 for fom init.
* Actually we do not use fop but it required by asserts inside
* transaction routines.
* We do not use and do not have rpc so can't directly use m0_fop_put():
* it crashes inside assert for m0_fop_rpc_is_locked().
* So use m0_ref_put() manually.
*/
m0_ref_put(&fom0->fo_fop->f_ref);
m0_ref_put(&fom0->fo_fop->f_ref);
fom0->fo_fop = NULL;
m0_fom_fini(fom0);
m0_long_lock_link_fini(&fom->cg_dead_index);
/*
* If have more job to do, start another fom using current fom memory.
*/
if (gc.cgc_running > 0) {
/*
* Must fill fom0 by zeroes when reusing fom memory. Else assert
* in m0_be_tx_init() because tx is not all-zero.
*/
M0_SET0(fom0);
M0_SET0(&fom->cg_fop);
cgc_start_fom(fom0, &fom->cg_fop);
} else {
m0_free(fom);
if (gc.cgc_waiting) {
M0_LOG(M0_DEBUG, "Waking waiter for gc complete");
m0_be_op_done(gc.cgc_op);
}
gc.cgc_waiting = false;
m0_ctg_store_fini();
m0_cond_broadcast(&gc.cgc_cond);
}
m0_mutex_unlock(&gc.cgc_mutex);
M0_LEAVE();
}
M0_INTERNAL void m0_cas_gc_start(struct m0_reqh_service *service)
{
struct cgc_fom *fom;
int rc;
struct m0_reqh *reqh = service->rs_reqh;
struct m0_reqh_context *rctx;
struct m0_be_domain *dom;
M0_ENTRY();
/* Check if UT domain is preset */
dom = m0_cas__ut_svc_be_get(service);
if (dom == NULL) {
rctx = m0_cs_reqh_context(reqh);
dom = rctx->rc_beseg->bs_domain;
}
m0_mutex_lock(&gc.cgc_mutex);
if (gc.cgc_running == 0) {
/*
* GC fom was not running, start it now.
*/
M0_LOG(M0_DEBUG, "Starting CGC fom");
M0_ALLOC_PTR(fom);
rc = m0_ctg_store_init(dom);
if (rc != 0 || fom == NULL) {
M0_LOG(M0_WARN, "CGC start error fom=%p, rc=%d",
fom, rc);
m0_free(fom);
if (rc == 0)
m0_ctg_store_fini();
} else {
fom->cg_reqh = reqh;
cgc_start_fom(&fom->cg_fom, &fom->cg_fop);
gc.cgc_running++;
}
} else
gc.cgc_running++;
m0_mutex_unlock(&gc.cgc_mutex);
M0_LEAVE();
}
M0_INTERNAL void m0_cas_gc_wait_sync(void)
{
M0_ENTRY();
m0_mutex_lock(&gc.cgc_mutex);
while (gc.cgc_running > 0)
m0_cond_wait(&gc.cgc_cond);
m0_mutex_unlock(&gc.cgc_mutex);
M0_LEAVE();
}
M0_INTERNAL void m0_cas_gc_wait_async(struct m0_be_op *beop)
{
M0_ENTRY();
m0_be_op_active(beop);
m0_mutex_lock(&gc.cgc_mutex);
if (gc.cgc_running == 0)
m0_be_op_done(beop);
else {
M0_LOG(M0_DEBUG, "Setup wait for gc complete");
gc.cgc_waiting = true;
gc.cgc_op = beop;
}
m0_mutex_unlock(&gc.cgc_mutex);
M0_LEAVE();
}
#undef M0_TRACE_SUBSYSTEM
/*
* Local variables:
* c-indentation-style: "K&R"
* c-basic-offset: 8
* tab-width: 8
* fill-column: 80
* scroll-step: 1
* End:
*/
/*
* vim: tabstop=8 shiftwidth=8 noexpandtab textwidth=80 nowrap
*/
| 28.179081 | 75 | 0.639278 |
ca219d40896a5ef68e80153060d679b00e8e9831 | 1,350 | c | C | examples/basic/srtest.c | RWTH-OS/MP-MPICH | f2ae296477bb9d812fda587221b3419c09f85b4a | [
"mpich2"
] | null | null | null | examples/basic/srtest.c | RWTH-OS/MP-MPICH | f2ae296477bb9d812fda587221b3419c09f85b4a | [
"mpich2"
] | null | null | null | examples/basic/srtest.c | RWTH-OS/MP-MPICH | f2ae296477bb9d812fda587221b3419c09f85b4a | [
"mpich2"
] | 1 | 2021-01-23T11:01:01.000Z | 2021-01-23T11:01:01.000Z | #include <stdio.h>
#include <string.h>
#include "mpi.h"
#define BUFLEN 512
int main(int argc, char *argv[])
{
int myid, numprocs, next, namelen;
char buffer[BUFLEN], processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
MPI_Get_processor_name(processor_name,&namelen);
fprintf(stderr,"Process %d on %s\n", myid, processor_name);
strcpy(buffer,"hello there");
if (myid == numprocs-1)
next = 0;
else
next = myid+1;
if (myid == 0)
{
printf("%d sending '%s' \n",myid,buffer);
MPI_Send(buffer, (int)strlen(buffer)+1, MPI_CHAR, next, 99, MPI_COMM_WORLD);
printf("%d receiving \n",myid);
MPI_Recv(buffer, BUFLEN, MPI_CHAR, MPI_ANY_SOURCE, 99, MPI_COMM_WORLD,
&status);
printf("%d received '%s' \n",myid,buffer);
/* mpdprintf(001,"%d receiving \n",myid); */
}
else
{
printf("%d receiving \n",myid);
MPI_Recv(buffer, BUFLEN, MPI_CHAR, MPI_ANY_SOURCE, 99, MPI_COMM_WORLD,
&status);
printf("%d received '%s' \n",myid,buffer);
/* mpdprintf(001,"%d receiving \n",myid); */
MPI_Send(buffer, (int)strlen(buffer)+1, MPI_CHAR, next, 99, MPI_COMM_WORLD);
printf("%d sent '%s' \n",myid,buffer);
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
return (0);
}
| 27 | 77 | 0.659259 |
30ecca537823e8c3575b763e65ac10b27734884a | 446 | h | C | Quartz2D/Quartz2D/Classes/First/Model/CHFlagItem.h | dongcidongci/demo | fb48ed4d2cade7dfad32921e9a70056ab7b97401 | [
"Apache-2.0"
] | null | null | null | Quartz2D/Quartz2D/Classes/First/Model/CHFlagItem.h | dongcidongci/demo | fb48ed4d2cade7dfad32921e9a70056ab7b97401 | [
"Apache-2.0"
] | null | null | null | Quartz2D/Quartz2D/Classes/First/Model/CHFlagItem.h | dongcidongci/demo | fb48ed4d2cade7dfad32921e9a70056ab7b97401 | [
"Apache-2.0"
] | null | null | null | //
// CHFlagItem.h
// 自定义键盘(UITextField)
//
// Created by moxuyou on 16/9/2.
// Copyright © 2016年 moxuyou. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CHFlagItem : NSObject
/** 名字 */
@property (nonatomic, copy)NSString *name;
/**图片对象*/
//@property (nonatomic, weak)UIImage *icon;
/***/
@property (nonatomic, strong)NSString *icon;
+ (instancetype)flagItemWithDict:(NSDictionary *)dict;
@end
| 21.238095 | 54 | 0.697309 |
b781edf862b0732ff0a05c151296a603d856ade5 | 1,120 | h | C | System/Library/Frameworks/HealthKit.framework/HKConceptIndexKeyPath.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 5 | 2021-04-29T04:31:43.000Z | 2021-08-19T18:59:58.000Z | System/Library/Frameworks/HealthKit.framework/HKConceptIndexKeyPath.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | null | null | null | System/Library/Frameworks/HealthKit.framework/HKConceptIndexKeyPath.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 1 | 2022-03-19T11:16:23.000Z | 2022-03-19T11:16:23.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 28, 2021 at 9:06:08 PM Mountain Standard Time
* Operating System: Version 14.5 (Build 18L204)
* Image Source: /System/Library/Frameworks/HealthKit.framework/HealthKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <HealthKit/HealthKit-Structs.h>
@class NSString;
@interface HKConceptIndexKeyPath : NSObject {
NSString* _fullKeyPath;
NSRange _range;
}
@property (nonatomic,copy,readonly) NSString * fullKeyPath; //@synthesize fullKeyPath=_fullKeyPath - In the implementation block
@property (nonatomic,readonly) NSRange range; //@synthesize range=_range - In the implementation block
+(id)conceptIndexKeyPathWithFullKeyPath:(id)arg1 error:(id*)arg2 ;
-(id)init;
-(NSRange)range;
-(id)head;
-(id)tail;
-(id)initWithFullKeyPath:(id)arg1 range:(NSRange)arg2 ;
-(NSString *)fullKeyPath;
@end
| 36.129032 | 141 | 0.644643 |
b782a059cc05e511729407107c126da3143c0a42 | 232 | h | C | Source/BrickGame/BrickGame.h | raycar5/BrickGame | 128f76c7fe5fc11b67bd870a1f1a7e0eb186c528 | [
"Unlicense"
] | null | null | null | Source/BrickGame/BrickGame.h | raycar5/BrickGame | 128f76c7fe5fc11b67bd870a1f1a7e0eb186c528 | [
"Unlicense"
] | null | null | null | Source/BrickGame/BrickGame.h | raycar5/BrickGame | 128f76c7fe5fc11b67bd870a1f1a7e0eb186c528 | [
"Unlicense"
] | null | null | null | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#ifndef __BRICKGAME_H__
#define __BRICKGAME_H__
#include "Engine.h"
#include "EngineKismetLibraryClasses.h"
#define COLLISION_PROJECTILE ECC_GameTraceChannel1
#endif
| 17.846154 | 60 | 0.810345 |
4e36700ee6e117182ef6e5efee012d2d846c9d04 | 3,054 | c | C | ccmode/src/ccmode_gcm_aad.c | rajohns08/corecrypto | 0344fab1747c1e187f12233f353d73c331a77653 | [
"AML"
] | null | null | null | ccmode/src/ccmode_gcm_aad.c | rajohns08/corecrypto | 0344fab1747c1e187f12233f353d73c331a77653 | [
"AML"
] | null | null | null | ccmode/src/ccmode_gcm_aad.c | rajohns08/corecrypto | 0344fab1747c1e187f12233f353d73c331a77653 | [
"AML"
] | null | null | null | /* Copyright (c) (2011,2012,2014,2015,2016,2018,2019) Apple Inc. All rights reserved.
*
* corecrypto is licensed under Apple Inc.’s Internal Use License Agreement (which
* is contained in the License.txt file distributed with corecrypto) and only to
* people who accept that license. IMPORTANT: Any license rights granted to you by
* Apple Inc. (if any) are limited to internal use within your organization only on
* devices and computers you own or control, for the sole purpose of verifying the
* security characteristics and correct functioning of the Apple Software. You may
* not, directly or indirectly, redistribute the Apple Software or any portions thereof.
*/
#include <corecrypto/cc_runtime_config.h>
#include "ccaes_vng_gcm.h"
#include "ccmode_internal.h"
/**
Add AAD to the GCM state
@param key The state
@param in The additional authentication data to add to the GCM state
@param nbytes The length of the AAD data.
@return 0 on success
*/
//ccmode_gcm_aad(key, 0, NULL) is okay.
int ccmode_gcm_aad(ccgcm_ctx *key, size_t nbytes, const void *in)
{
const uint8_t *bytes = in;
uint8_t *X = CCMODE_GCM_KEY_X(key);
uint32_t X_nbytes = _CCMODE_GCM_KEY(key)->aad_nbytes % CCGCM_BLOCK_NBYTES;
uint32_t X_nbytes_needed = CCGCM_BLOCK_NBYTES - X_nbytes;
cc_require(_CCMODE_GCM_KEY(key)->state == CCMODE_GCM_STATE_AAD, errOut);
// finish a partial block, if possible
if (X_nbytes > 0 && nbytes >= X_nbytes_needed) {
cc_xor(X_nbytes_needed, (X + X_nbytes), (X + X_nbytes), bytes);
ccmode_gcm_mult_h(key, CCMODE_GCM_KEY_X(key));
nbytes -= X_nbytes_needed;
bytes += X_nbytes_needed;
_CCMODE_GCM_KEY(key)->aad_nbytes += X_nbytes_needed;
X_nbytes = 0;
}
// process full blocks, if any
if (X_nbytes == 0) {
#if CCMODE_GCM_VNG_SPEEDUP
#ifdef __x86_64__
if (CC_HAS_AESNI() && CC_HAS_SupplementalSSE3())
#endif //__x86_64__
if (nbytes >= CCGCM_BLOCK_NBYTES) {
size_t j = nbytes & (size_t)(-16);
gcm_ghash(X, (void *) CCMODE_GCM_VNG_KEY_Htable(key), (const void*) bytes, j);
bytes += j;
nbytes -= j;
_CCMODE_GCM_KEY(key)->aad_nbytes += j;
}
#endif //CCMODE_GCM_VNG_SPEEDUP
/* fallback in absence of vng */
/* including this in ifdef is tricky */
/* due to runtime checks for aesni and sse3 */
while (nbytes >= CCGCM_BLOCK_NBYTES) {
cc_xor(CCGCM_BLOCK_NBYTES, X, X, bytes);
ccmode_gcm_mult_h(key, X);
nbytes -= CCGCM_BLOCK_NBYTES;
bytes += CCGCM_BLOCK_NBYTES;
_CCMODE_GCM_KEY(key)->aad_nbytes += CCGCM_BLOCK_NBYTES;
}
}
// process the remainder
if (nbytes > 0) {
cc_xor(nbytes, (X + X_nbytes), (X + X_nbytes), bytes);
_CCMODE_GCM_KEY(key)->aad_nbytes += nbytes;
}
return 0;
errOut:
return CCMODE_INVALID_CALL_SEQUENCE;
}
| 35.929412 | 94 | 0.646693 |
bd6b4dceb5d2b72ac1755ce89fcf59981f90ebd4 | 1,132 | h | C | include/cborcpp/output_static.h | rockercheng/uvm | 48f01ae86ba78a487d22662da12b7460609db50e | [
"MIT"
] | 10 | 2020-09-26T12:00:03.000Z | 2021-07-27T06:41:40.000Z | libraries/uvm/include/cborcpp/output_static.h | wuhua103/Whitecoin-core | 9225520dcdc8404022f29acdc3c17ebeb5e9cb67 | [
"MIT"
] | 23 | 2020-05-31T13:08:03.000Z | 2021-12-08T09:07:30.000Z | libraries/uvm/include/cborcpp/output_static.h | wuhua103/Whitecoin-core | 9225520dcdc8404022f29acdc3c17ebeb5e9cb67 | [
"MIT"
] | 4 | 2019-12-05T15:32:08.000Z | 2021-09-21T17:53:41.000Z | /*
Copyright 2014-2015 Stanislav Ovsyannikov
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include "cborcpp/output.h"
namespace cbor {
class output_static : public output {
private:
unsigned char *_buffer;
unsigned int _capacity;
unsigned int _offset;
public:
output_static(unsigned int capacity);
~output_static();
virtual unsigned char *getData() const;
virtual unsigned int getSize() const;
virtual void put_byte(unsigned char value);
virtual void put_bytes(const unsigned char *data, int size);
};
}
| 26.952381 | 76 | 0.69523 |
8356672891667d85b39a23a490940c5f5f54c42f | 2,291 | h | C | HJDanmakuDemo/DanmakuDemoView/DanmakuView.h | NealWills/HJDanmaku | be7d77ea2d5048d62ddbe8cf7d8a425911cca27e | [
"MIT"
] | 935 | 2015-03-12T11:20:28.000Z | 2022-02-03T22:05:24.000Z | HJDanmakuDemo/DanmakuDemoView/DanmakuView.h | NealWills/HJDanmaku | be7d77ea2d5048d62ddbe8cf7d8a425911cca27e | [
"MIT"
] | 27 | 2015-11-27T02:57:03.000Z | 2021-02-09T02:09:39.000Z | HJDanmakuDemo/DanmakuDemoView/DanmakuView.h | NealWills/HJDanmaku | be7d77ea2d5048d62ddbe8cf7d8a425911cca27e | [
"MIT"
] | 226 | 2015-03-30T15:04:21.000Z | 2021-10-19T06:19:38.000Z | //
// DanmakuView.h
// DanmakuView
//
// Created by Haijiao on 15/3/12.
// Copyright (c) 2015年 olinone. All rights reserved.
// http://www.olinone.com
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface DanmakuConfiguration : NSObject
@property (nonatomic) CGFloat duration;
@property (nonatomic) CGFloat paintHeight;
@property (nonatomic) CGFloat fontSize;
@property (nonatomic) CGFloat largeFontSize;
@property (nonatomic) NSUInteger maxLRShowCount;
@property (nonatomic) NSUInteger maxShowCount;
//发送弹幕是否显示下划线
@property (nonatomic) BOOL isShowLineWhenSelf;
@end
//_______________________________________________________________________________________________________________
// 时间(毫秒),类型(0:向左滚动 1:顶部 2底部),字体大小(0:中字体 1:大字体),颜色(16进制),用户ID
// "p": "25,1,0,FFFFFF,0",
// "m": "olinone.com"
@interface DanmakuSource : NSObject
@property (nonatomic, strong) NSString *p;
@property (nonatomic, strong) NSString *m;
+ (instancetype)createWithP:(NSString *)p M:(NSString *)m;
@end
//_______________________________________________________________________________________________________________
@protocol DanmakuDelegate;
@interface DanmakuView : UIView
@property (nonatomic, weak) id<DanmakuDelegate> delegate;
@property (nonatomic, readonly) BOOL isPrepared;
@property (nonatomic, readonly) BOOL isPlaying;
- (instancetype)initWithFrame:(CGRect)frame configuration:(DanmakuConfiguration *)configuration;
// DanmakuSource组成的数组
- (void)prepareDanmakuSources:(NSArray<DanmakuSource *> *)danmakuSources;
- (void)start;
- (void)pause;
- (void)resume;
- (void)stop;
- (void)sendDanmakuSource:(DanmakuSource *)danmakuSource;
@end
@interface DanmakuView (Deprecated)
// 字典组成的数组,已弃用,推荐prepareDanmakuSources
// "p": "25,1,0,FFFFFF,0",
// "m": "olinone.com"
- (void)prepareDanmakus:(NSArray <NSDictionary *> *)danmakus;
@end
//_______________________________________________________________________________________________________________
@protocol DanmakuDelegate <NSObject>
@required
// 视频播放进度,单位秒
- (float)danmakuViewGetPlayTime:(DanmakuView *)danmakuView;
// 视频播放缓冲状态,如果设为YES,不会绘制新弹幕,已绘制弹幕会继续动画直至消失
- (BOOL)danmakuViewIsBuffering:(DanmakuView *)danmakuView;
@optional
// 弹幕初始化完成
- (void)danmakuViewPerpareComplete:(DanmakuView *)danmakuView;
@end
| 25.455556 | 113 | 0.780882 |
64606eea742c46d9c2ed510f27d54edb3561de69 | 1,156 | h | C | Sample app/Navigation/View Controllers/SplashViewController.h | indoor-onyourmap/iOS-SDK | cf49803db5193b04a79b1c9788cda6b3046794c6 | [
"MIT"
] | 5 | 2015-06-29T11:22:17.000Z | 2020-11-06T13:48:10.000Z | Sample app/Navigation/View Controllers/SplashViewController.h | indoor-onyourmap/iOS-SDK | cf49803db5193b04a79b1c9788cda6b3046794c6 | [
"MIT"
] | null | null | null | Sample app/Navigation/View Controllers/SplashViewController.h | indoor-onyourmap/iOS-SDK | cf49803db5193b04a79b1c9788cda6b3046794c6 | [
"MIT"
] | 2 | 2016-07-25T04:29:42.000Z | 2017-09-13T10:08:00.000Z | //
// ViewController.h
// Navigation
//
// Created by onyourmap on 19/1/15.
// Copyright (c) 2015 OnYourMap. All rights reserved.
//
#ifndef NAV_SPLASHVIEWCONTROLLER_H
#define NAV_SPLASHVIEWCONTROLLER_H
#import <UIKit/UIKit.h>
#import "Delegate.h"
#import "GlobalState.h"
#import "MapViewController.h"
#import "Colors.h"
#import "OYMTransparentTextField.h"
@interface SplashViewController : UIViewController <UITextFieldDelegate, UIAlertViewDelegate>
// View
@property IBOutlet UIScrollView* scrollView;
// Login
@property IBOutlet OYMTransparentTextField* accountField;
@property IBOutlet OYMTransparentTextField* passwordField;
@property IBOutlet UIButton* loginButton;
// Connecting
@property IBOutlet UILabel* text;
@property IBOutlet UIActivityIndicatorView* spinner;
// Help
@property IBOutlet UIImage* helpImage;
@property IBOutlet UIButton* helpButton;
- (IBAction) onLogin:(id)sender;
- (IBAction) onHelp:(id)sender;
- (void) onBeingLoggedOut;
- (void) showText:(NSString*)text;
- (void) showError:(NSString*)text;
- (void) promptEnableLocationServices;
- (void) onLocationServicesChecked:(BOOL)succeed;
- (void) ready;
@end
#endif | 23.12 | 93 | 0.774221 |
64b1c798590bf2123086a9fd1b4843fcb17744dc | 6,998 | h | C | MonoNative/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices__FieldInfo.h | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices__FieldInfo.h | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices__FieldInfo.h | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | #ifndef __MONO_NATIVE_MSCORLIB_SYSTEM_RUNTIME_INTEROPSERVICES__FIELDINFO_H
#define __MONO_NATIVE_MSCORLIB_SYSTEM_RUNTIME_INTEROPSERVICES__FIELDINFO_H
#include <mscorlib/System/mscorlib_System_Object.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_BindingFlags.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_FieldAttributes.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_MemberTypes.h>
namespace mscorlib
{
namespace System
{
class Type;
class Guid;
class TypedReference;
class String;
class RuntimeFieldHandle;
}
}
namespace mscorlib
{
namespace System
{
namespace Reflection
{
class Binder;
}
}
}
namespace mscorlib
{
namespace System
{
namespace Globalization
{
class CultureInfo;
}
}
}
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace InteropServices
{
class _FieldInfo
{
public:
_FieldInfo(MonoObject *nativeObject)
{
__mscorlib_System_Runtime_InteropServices__FieldInfo = nativeObject;
};
~_FieldInfo()
{
};
_FieldInfo & operator=(_FieldInfo &value) { __mscorlib_System_Runtime_InteropServices__FieldInfo = value.__mscorlib_System_Runtime_InteropServices__FieldInfo; return value; };
operator MonoObject*() { return __mscorlib_System_Runtime_InteropServices__FieldInfo; };
MonoObject* operator=(MonoObject* value) { __mscorlib_System_Runtime_InteropServices__FieldInfo = value; return value; };
virtual mscorlib::System::Boolean Equals(mscorlib::System::Object other);
virtual std::vector<mscorlib::System::Object*> GetCustomAttributes(mscorlib::System::Boolean inherit);
virtual std::vector<mscorlib::System::Object*> GetCustomAttributes(mscorlib::System::Type attributeType, mscorlib::System::Boolean inherit);
virtual mscorlib::System::Int32 GetHashCode();
virtual mscorlib::System::Type GetType();
virtual void GetIDsOfNames(mscorlib::System::Guid riid, mscorlib::System::IntPtr rgszNames, mscorlib::System::UInt32 cNames, mscorlib::System::UInt32 lcid, mscorlib::System::IntPtr rgDispId);
virtual void GetTypeInfo(mscorlib::System::UInt32 iTInfo, mscorlib::System::UInt32 lcid, mscorlib::System::IntPtr ppTInfo);
virtual void GetTypeInfoCount(mscorlib::System::UInt32 pcTInfo);
virtual void Invoke(mscorlib::System::UInt32 dispIdMember, mscorlib::System::Guid riid, mscorlib::System::UInt32 lcid, mscorlib::System::Int16 wFlags, mscorlib::System::IntPtr pDispParams, mscorlib::System::IntPtr pVarResult, mscorlib::System::IntPtr pExcepInfo, mscorlib::System::IntPtr puArgErr);
virtual mscorlib::System::Object GetValue(mscorlib::System::Object obj);
virtual mscorlib::System::Object GetValueDirect(mscorlib::System::TypedReference obj);
virtual mscorlib::System::Boolean IsDefined(mscorlib::System::Type attributeType, mscorlib::System::Boolean inherit);
virtual void SetValue(mscorlib::System::Object obj, mscorlib::System::Object value);
virtual void SetValue(mscorlib::System::Object obj, mscorlib::System::Object value, mscorlib::System::Reflection::BindingFlags::__ENUM__ invokeAttr, mscorlib::System::Reflection::Binder binder, mscorlib::System::Globalization::CultureInfo culture);
virtual void SetValueDirect(mscorlib::System::TypedReference obj, mscorlib::System::Object value);
virtual mscorlib::System::String ToString();
//Public Properties
__declspec(property(get=get_Attributes)) mscorlib::System::Reflection::FieldAttributes::__ENUM__ Attributes;
__declspec(property(get=get_DeclaringType)) mscorlib::System::Type DeclaringType;
__declspec(property(get=get_FieldHandle)) mscorlib::System::RuntimeFieldHandle FieldHandle;
__declspec(property(get=get_FieldType)) mscorlib::System::Type FieldType;
__declspec(property(get=get_IsAssembly)) mscorlib::System::Boolean IsAssembly;
__declspec(property(get=get_IsFamily)) mscorlib::System::Boolean IsFamily;
__declspec(property(get=get_IsFamilyAndAssembly)) mscorlib::System::Boolean IsFamilyAndAssembly;
__declspec(property(get=get_IsFamilyOrAssembly)) mscorlib::System::Boolean IsFamilyOrAssembly;
__declspec(property(get=get_IsInitOnly)) mscorlib::System::Boolean IsInitOnly;
__declspec(property(get=get_IsLiteral)) mscorlib::System::Boolean IsLiteral;
__declspec(property(get=get_IsNotSerialized)) mscorlib::System::Boolean IsNotSerialized;
__declspec(property(get=get_IsPinvokeImpl)) mscorlib::System::Boolean IsPinvokeImpl;
__declspec(property(get=get_IsPrivate)) mscorlib::System::Boolean IsPrivate;
__declspec(property(get=get_IsPublic)) mscorlib::System::Boolean IsPublic;
__declspec(property(get=get_IsSpecialName)) mscorlib::System::Boolean IsSpecialName;
__declspec(property(get=get_IsStatic)) mscorlib::System::Boolean IsStatic;
__declspec(property(get=get_MemberType)) mscorlib::System::Reflection::MemberTypes::__ENUM__ MemberType;
__declspec(property(get=get_Name)) mscorlib::System::String Name;
__declspec(property(get=get_ReflectedType)) mscorlib::System::Type ReflectedType;
//Get Set Properties Methods
// Get:Attributes
mscorlib::System::Reflection::FieldAttributes::__ENUM__ get_Attributes() const;
// Get:DeclaringType
mscorlib::System::Type get_DeclaringType() const;
// Get:FieldHandle
mscorlib::System::RuntimeFieldHandle get_FieldHandle() const;
// Get:FieldType
mscorlib::System::Type get_FieldType() const;
// Get:IsAssembly
mscorlib::System::Boolean get_IsAssembly() const;
// Get:IsFamily
mscorlib::System::Boolean get_IsFamily() const;
// Get:IsFamilyAndAssembly
mscorlib::System::Boolean get_IsFamilyAndAssembly() const;
// Get:IsFamilyOrAssembly
mscorlib::System::Boolean get_IsFamilyOrAssembly() const;
// Get:IsInitOnly
mscorlib::System::Boolean get_IsInitOnly() const;
// Get:IsLiteral
mscorlib::System::Boolean get_IsLiteral() const;
// Get:IsNotSerialized
mscorlib::System::Boolean get_IsNotSerialized() const;
// Get:IsPinvokeImpl
mscorlib::System::Boolean get_IsPinvokeImpl() const;
// Get:IsPrivate
mscorlib::System::Boolean get_IsPrivate() const;
// Get:IsPublic
mscorlib::System::Boolean get_IsPublic() const;
// Get:IsSpecialName
mscorlib::System::Boolean get_IsSpecialName() const;
// Get:IsStatic
mscorlib::System::Boolean get_IsStatic() const;
// Get:MemberType
mscorlib::System::Reflection::MemberTypes::__ENUM__ get_MemberType() const;
// Get:Name
mscorlib::System::String get_Name() const;
// Get:ReflectedType
mscorlib::System::Type get_ReflectedType() const;
protected:
MonoObject *__mscorlib_System_Runtime_InteropServices__FieldInfo;
private:
};
}
}
}
}
#endif
| 37.623656 | 304 | 0.744356 |
c1ad1243cf020b01cd2d7211935a83927ab0ae3e | 2,958 | h | C | src/runtime/ext/ext_url.ext_hhvm.h | justintung/hiphop-php | 5c736b05b0ec3289c11448c23b7893dfe47eeaff | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2020-12-02T03:08:16.000Z | 2020-12-02T03:08:16.000Z | src/runtime/ext/ext_url.ext_hhvm.h | bogdan2412/hiphop-php | 1ab828426096d0e7ae74544189e2f4cd6924570b | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | src/runtime/ext/ext_url.ext_hhvm.h | bogdan2412/hiphop-php | 1ab828426096d0e7ae74544189e2f4cd6924570b | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 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. |
+----------------------------------------------------------------------+
*/
namespace HPHP {
/*
HPHP::Variant HPHP::f_base64_decode(HPHP::String const&, bool)
_ZN4HPHP15f_base64_decodeERKNS_6StringEb
(return value) => rax
_rv => rdi
data => rsi
strict => rdx
*/
TypedValue* fh_base64_decode(TypedValue* _rv, Value* data, bool strict) asm("_ZN4HPHP15f_base64_decodeERKNS_6StringEb");
/*
HPHP::String HPHP::f_base64_encode(HPHP::String const&)
_ZN4HPHP15f_base64_encodeERKNS_6StringE
(return value) => rax
_rv => rdi
data => rsi
*/
Value* fh_base64_encode(Value* _rv, Value* data) asm("_ZN4HPHP15f_base64_encodeERKNS_6StringE");
/*
HPHP::Variant HPHP::f_get_headers(HPHP::String const&, int)
_ZN4HPHP13f_get_headersERKNS_6StringEi
(return value) => rax
_rv => rdi
url => rsi
format => rdx
*/
TypedValue* fh_get_headers(TypedValue* _rv, Value* url, int format) asm("_ZN4HPHP13f_get_headersERKNS_6StringEi");
/*
HPHP::Array HPHP::f_get_meta_tags(HPHP::String const&, bool)
_ZN4HPHP15f_get_meta_tagsERKNS_6StringEb
(return value) => rax
_rv => rdi
filename => rsi
use_include_path => rdx
*/
Value* fh_get_meta_tags(Value* _rv, Value* filename, bool use_include_path) asm("_ZN4HPHP15f_get_meta_tagsERKNS_6StringEb");
/*
HPHP::Variant HPHP::f_http_build_query(HPHP::Variant const&, HPHP::String const&, HPHP::String const&)
_ZN4HPHP18f_http_build_queryERKNS_7VariantERKNS_6StringES5_
(return value) => rax
_rv => rdi
formdata => rsi
numeric_prefix => rdx
arg_separator => rcx
*/
TypedValue* fh_http_build_query(TypedValue* _rv, TypedValue* formdata, Value* numeric_prefix, Value* arg_separator) asm("_ZN4HPHP18f_http_build_queryERKNS_7VariantERKNS_6StringES5_");
/*
HPHP::Variant HPHP::f_parse_url(HPHP::String const&, int)
_ZN4HPHP11f_parse_urlERKNS_6StringEi
(return value) => rax
_rv => rdi
url => rsi
component => rdx
*/
TypedValue* fh_parse_url(TypedValue* _rv, Value* url, int component) asm("_ZN4HPHP11f_parse_urlERKNS_6StringEi");
} // !HPHP
| 31.468085 | 183 | 0.629479 |
d86f0ff898da801271a5cfc9182a68dcec4f93bf | 8,680 | h | C | Amcl/cpp_i686/ff_RSA2048.h | UoS-SCCS/ecc-daa | eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9 | [
"BSD-2-Clause"
] | 2 | 2020-02-28T10:40:12.000Z | 2021-02-18T03:32:28.000Z | Amcl/cpp_i686/ff_RSA2048.h | UoS-SCCS/ecc-daa | eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9 | [
"BSD-2-Clause"
] | null | null | null | Amcl/cpp_i686/ff_RSA2048.h | UoS-SCCS/ecc-daa | eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9 | [
"BSD-2-Clause"
] | null | null | null | #ifndef FF_RSA2048_H
#define FF_RSA2048_H
#include "big_B1024_28.h"
#include "config_ff_RSA2048.h"
using namespace amcl;
#define HFLEN_RSA2048 (FFLEN_RSA2048/2) /**< Useful for half-size RSA private key operations */
#define P_MBITS_RSA2048 (MODBYTES_B1024_28*8)
#define P_TBITS_RSA2048 (P_MBITS_RSA2048%BASEBITS_B1024_28)
#define P_EXCESS_RSA2048(a) (((a[NLEN_B1024_28-1])>>(P_TBITS_RSA2048))+1)
#define P_FEXCESS_RSA2048 ((chunk)1<<(BASEBITS_B1024_28*NLEN_B1024_28-P_MBITS_RSA2048-1))
namespace RSA2048 {
/* Finite Field Prototypes */
/** @brief Copy one FF element of given length to another
*
@param x FF instance to be copied to, on exit = y
@param y FF instance to be copied from
@param n size of FF in BIGs
*/
extern void FF_copy(B1024_28::BIG *x,B1024_28::BIG *y,int n);
/** @brief Initialize an FF element of given length from a 32-bit integer m
*
@param x FF instance to be copied to, on exit = m
@param m integer
@param n size of FF in BIGs
*/
extern void FF_init(B1024_28::BIG *x,sign32 m,int n);
/** @brief Set FF element of given size to zero
*
@param x FF instance to be set to zero
@param n size of FF in BIGs
*/
extern void FF_zero(B1024_28::BIG *x,int n);
/** @brief Tests for FF element equal to zero
*
@param x FF number to be tested
@param n size of FF in BIGs
@return 1 if zero, else returns 0
*/
extern int FF_iszilch(B1024_28::BIG *x,int n);
/** @brief return parity of an FF, that is the least significant bit
*
@param x FF number
@return 0 or 1
*/
extern int FF_parity(B1024_28::BIG *x);
/** @brief return least significant m bits of an FF
*
@param x FF number
@param m number of bits to return. Assumed to be less than BASEBITS.
@return least significant n bits as an integer
*/
extern int FF_lastbits(B1024_28::BIG *x,int m);
/** @brief Set FF element of given size to unity
*
@param x FF instance to be set to unity
@param n size of FF in BIGs
*/
extern void FF_one(B1024_28::BIG *x,int n);
/** @brief Compares two FF numbers. Inputs must be normalised externally
*
@param x first FF number to be compared
@param y second FF number to be compared
@param n size of FF in BIGs
@return -1 is x<y, 0 if x=y, 1 if x>y
*/
extern int FF_comp(B1024_28::BIG *x,B1024_28::BIG *y,int n);
/** @brief addition of two FFs
*
@param x FF instance, on exit = y+z
@param y FF instance
@param z FF instance
@param n size of FF in BIGs
*/
extern void FF_add(B1024_28::BIG *x,B1024_28::BIG *y,B1024_28::BIG *z,int n);
/** @brief subtraction of two FFs
*
@param x FF instance, on exit = y-z
@param y FF instance
@param z FF instance
@param n size of FF in BIGs
*/
extern void FF_sub(B1024_28::BIG *x,B1024_28::BIG *y,B1024_28::BIG *z,int n);
/** @brief increment an FF by an integer,and normalise
*
@param x FF instance, on exit = x+m
@param m an integer to be added to x
@param n size of FF in BIGs
*/
extern void FF_inc(B1024_28::BIG *x,int m,int n);
/** @brief Decrement an FF by an integer,and normalise
*
@param x FF instance, on exit = x-m
@param m an integer to be subtracted from x
@param n size of FF in BIGs
*/
extern void FF_dec(B1024_28::BIG *x,int m,int n);
/** @brief Normalises the components of an FF
*
@param x FF instance to be normalised
@param n size of FF in BIGs
*/
extern void FF_norm(B1024_28::BIG *x,int n);
/** @brief Shift left an FF by 1 bit
*
@param x FF instance to be shifted left
@param n size of FF in BIGs
*/
extern void FF_shl(B1024_28::BIG *x,int n);
/** @brief Shift right an FF by 1 bit
*
@param x FF instance to be shifted right
@param n size of FF in BIGs
*/
extern void FF_shr(B1024_28::BIG *x,int n);
/** @brief Formats and outputs an FF to the console
*
@param x FF instance to be printed
@param n size of FF in BIGs
*/
extern void FF_output(B1024_28::BIG *x,int n);
/** @brief Formats and outputs an FF to the console, in raw form
*
@param x FF instance to be printed
@param n size of FF in BIGs
*/
extern void FF_rawoutput(B1024_28::BIG *x,int n);
/** @brief Formats and outputs an FF instance to an octet string
*
Converts an FF to big-endian base 256 form.
@param S output octet string
@param x FF instance to be converted to an octet string
@param n size of FF in BIGs
*/
extern void FF_toOctet(octet *S,B1024_28::BIG *x,int n);
/** @brief Populates an FF instance from an octet string
*
Creates FF from big-endian base 256 form.
@param x FF instance to be created from an octet string
@param S input octet string
@param n size of FF in BIGs
*/
extern void FF_fromOctet(B1024_28::BIG *x,octet *S,int n);
/** @brief Multiplication of two FFs
*
Uses Karatsuba method internally
@param x FF instance, on exit = y*z
@param y FF instance
@param z FF instance
@param n size of FF in BIGs
*/
extern void FF_mul(B1024_28::BIG *x,B1024_28::BIG *y,B1024_28::BIG *z,int n);
/** @brief Reduce FF mod a modulus
*
This is slow
@param x FF instance to be reduced mod m - on exit = x mod m
@param m FF modulus
@param n size of FF in BIGs
*/
extern void FF_mod(B1024_28::BIG *x,B1024_28::BIG *m,int n);
/** @brief Square an FF
*
Uses Karatsuba method internally
@param x FF instance, on exit = y^2
@param y FF instance to be squared
@param n size of FF in BIGs
*/
extern void FF_sqr(B1024_28::BIG *x,B1024_28::BIG *y,int n);
/** @brief Reduces a double-length FF with respect to a given modulus
*
This is slow
@param x FF instance, on exit = y mod z
@param y FF instance, of double length 2*n
@param z FF modulus
@param n size of FF in BIGs
*/
extern void FF_dmod(B1024_28::BIG *x,B1024_28::BIG *y,B1024_28::BIG *z,int n);
/** @brief Invert an FF mod a prime modulus
*
@param x FF instance, on exit = 1/y mod z
@param y FF instance
@param z FF prime modulus
@param n size of FF in BIGs
*/
extern void FF_invmodp(B1024_28::BIG *x,B1024_28::BIG *y,B1024_28::BIG *z,int n);
/** @brief Create an FF from a random number generator
*
@param x FF instance, on exit x is a random number of length n BIGs with most significant bit a 1
@param R an instance of a Cryptographically Secure Random Number Generator
@param n size of FF in BIGs
*/
extern void FF_random(B1024_28::BIG *x,csprng *R,int n);
/** @brief Create a random FF less than a given modulus from a random number generator
*
@param x FF instance, on exit x is a random number < y
@param y FF instance, the modulus
@param R an instance of a Cryptographically Secure Random Number Generator
@param n size of FF in BIGs
*/
extern void FF_randomnum(B1024_28::BIG *x,B1024_28::BIG *y,csprng *R,int n);
/** @brief Calculate r=x^e mod m, side channel resistant
*
@param r FF instance, on exit = x^e mod p
@param x FF instance
@param e FF exponent
@param m FF modulus
@param n size of FF in BIGs
*/
extern void FF_skpow(B1024_28::BIG *r,B1024_28::BIG *x,B1024_28::BIG * e,B1024_28::BIG *m,int n);
/** @brief Calculate r=x^e mod m, side channel resistant
*
For short BIG exponent
@param r FF instance, on exit = x^e mod p
@param x FF instance
@param e BIG exponent
@param m FF modulus
@param n size of FF in BIGs
*/
extern void FF_skspow(B1024_28::BIG *r,B1024_28::BIG *x,B1024_28::BIG e,B1024_28::BIG *m,int n);
/** @brief Calculate r=x^e mod m
*
For very short integer exponent
@param r FF instance, on exit = x^e mod p
@param x FF instance
@param e integer exponent
@param m FF modulus
@param n size of FF in BIGs
*/
extern void FF_power(B1024_28::BIG *r,B1024_28::BIG *x,int e,B1024_28::BIG *m,int n);
/** @brief Calculate r=x^e mod m
*
@param r FF instance, on exit = x^e mod p
@param x FF instance
@param e FF exponent
@param m FF modulus
@param n size of FF in BIGs
*/
extern void FF_pow(B1024_28::BIG *r,B1024_28::BIG *x,B1024_28::BIG *e,B1024_28::BIG *m,int n);
/** @brief Test if an FF has factor in common with integer s
*
@param x FF instance to be tested
@param s the supplied integer
@param n size of FF in BIGs
@return 1 if gcd(x,s)!=1, else return 0
*/
extern int FF_cfactor(B1024_28::BIG *x,sign32 s,int n);
/** @brief Test if an FF is prime
*
Uses Miller-Rabin Method
@param x FF instance to be tested
@param R an instance of a Cryptographically Secure Random Number Generator
@param n size of FF in BIGs
@return 1 if x is (almost certainly) prime, else return 0
*/
extern int FF_prime(B1024_28::BIG *x,csprng *R,int n);
/** @brief Calculate r=x^e.y^f mod m
*
@param r FF instance, on exit = x^e.y^f mod p
@param x FF instance
@param e BIG exponent
@param y FF instance
@param f BIG exponent
@param m FF modulus
@param n size of FF in BIGs
*/
extern void FF_pow2(B1024_28::BIG *r,B1024_28::BIG *x,B1024_28::BIG e,B1024_28::BIG *y,B1024_28::BIG f,B1024_28::BIG *m,int n);
}
#endif
| 31.33574 | 127 | 0.707604 |
142bd116a42f86fbde9b23a12d1bd2220d28e0ad | 30,031 | c | C | subversion/mod_dav_svn/util.c | timgates42/subversion | 0f088f530747140c6783c2eeb77ceff8e8613c42 | [
"Apache-2.0"
] | 3 | 2017-01-03T03:20:56.000Z | 2018-12-24T22:05:09.000Z | subversion/mod_dav_svn/util.c | timgates42/subversion | 0f088f530747140c6783c2eeb77ceff8e8613c42 | [
"Apache-2.0"
] | 3 | 2016-06-12T17:02:25.000Z | 2019-02-03T11:08:18.000Z | subversion/mod_dav_svn/util.c | timgates42/subversion | 0f088f530747140c6783c2eeb77ceff8e8613c42 | [
"Apache-2.0"
] | 3 | 2017-01-21T00:15:13.000Z | 2020-11-04T07:23:50.000Z | /*
* util.c:
* # ****************************************************************************
* # TRASHY LITTLE SUBROUTINES
* # ****************************************************************************
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
#include <apr_xml.h>
#include <apr_errno.h>
#include <apr_uri.h>
#include <apr_buckets.h>
#include <mod_dav.h>
#include <http_protocol.h>
#include <http_core.h>
#include "svn_error.h"
#include "svn_fs.h"
#include "svn_dav.h"
#include "svn_base64.h"
#include "svn_ctype.h"
#include "dav_svn.h"
#include "private/svn_fspath.h"
#include "private/svn_string_private.h"
dav_error *
dav_svn__new_error(apr_pool_t *pool,
int status,
int error_id,
apr_status_t aprerr,
const char *desc)
{
if (error_id == 0)
error_id = SVN_ERR_RA_DAV_REQUEST_FAILED;
/*
* Note: dav_new_error() in httpd 2.0/2.2 always treated
* the errno field in dav_error as an apr_status_t when
* logging; on some platforms errno and apr_status_t
* aren't directly interchangeable. The code for httpd
* > 2.2 below perpetuates this.
*/
#if AP_MODULE_MAGIC_AT_LEAST(20091119,0)
return dav_new_error(pool, status, error_id, aprerr, desc);
#else
errno = aprerr; /* For the same reason as in dav_svn__new_error_svn */
return dav_new_error(pool, status, error_id, desc);
#endif
}
dav_error *
dav_svn__new_error_svn(apr_pool_t *pool,
int status,
int error_id,
apr_status_t aprerr,
const char *desc)
{
if (error_id == 0)
error_id = SVN_ERR_RA_DAV_REQUEST_FAILED;
#if AP_MODULE_MAGIC_AT_LEAST(20091119,0)
return dav_new_error_tag(pool, status, error_id, aprerr,
desc, SVN_DAV_ERROR_NAMESPACE, SVN_DAV_ERROR_TAG);
#else
/* dav_new_error_tag will record errno so we use it to pass aprerr.
This overrwites any existing errno value but since Subversion
makes no attempt to avoid system calls after a failed system call
there is no guarantee that any existing errno represents a
relevant error. */
errno = aprerr;
return dav_new_error_tag(pool, status, error_id, desc,
SVN_DAV_ERROR_NAMESPACE, SVN_DAV_ERROR_TAG);
#endif
}
/* Build up a chain of DAV errors that correspond to the underlying SVN
errors that caused this problem. */
static dav_error *
build_error_chain(apr_pool_t *pool, svn_error_t *err, int status)
{
char buffer[128];
const char *msg = svn_err_best_message(err, buffer, sizeof(buffer));
dav_error *derr = dav_svn__new_error_svn(pool, status, err->apr_err, 0,
apr_pstrdup(pool, msg));
if (err->child)
derr->prev = build_error_chain(pool, err->child, status);
return derr;
}
dav_error *
dav_svn__convert_err(svn_error_t *serr,
int status,
const char *message,
apr_pool_t *pool)
{
dav_error *derr;
/* Remove the trace-only error chain links. We need predictable
protocol behavior regardless of whether or not we're in a
debugging build. */
svn_error_t *purged_serr = svn_error_purge_tracing(serr);
/* ### someday mod_dav_svn will send back 'rich' error tags, much
finer grained than plain old svn_error_t's. But for now, all
svn_error_t's are marshalled to the client via the single
generic <svn:error/> tag nestled within a <D:error> block. */
/* Examine the Subverion error code, and select the most
appropriate HTTP status code. If no more appropriate HTTP
status code maps to the Subversion error code, use the one
suggested status provided by the caller. */
switch (purged_serr->apr_err)
{
case SVN_ERR_FS_NOT_FOUND:
case SVN_ERR_FS_NO_SUCH_REVISION:
status = HTTP_NOT_FOUND;
break;
case SVN_ERR_UNSUPPORTED_FEATURE:
status = HTTP_NOT_IMPLEMENTED;
break;
case SVN_ERR_FS_LOCK_OWNER_MISMATCH:
case SVN_ERR_FS_PATH_ALREADY_LOCKED:
status = HTTP_LOCKED;
break;
case SVN_ERR_FS_PROP_BASEVALUE_MISMATCH:
status = HTTP_PRECONDITION_FAILED;
break;
/* add other mappings here */
}
derr = build_error_chain(pool, purged_serr, status);
if (message != NULL
&& !svn_error_find_cause(purged_serr, SVN_ERR_REPOS_HOOK_FAILURE))
/* Don't hide hook failures; we might hide the error text */
derr = dav_push_error(pool, status, purged_serr->apr_err,
message, derr);
/* Now, destroy the Subversion error. */
svn_error_clear(serr);
return derr;
}
/* Set *REVISION to the youngest revision in which an interesting
history item (a modification, or a copy) occurred for PATH under
ROOT. Use POOL for scratchwork. */
static svn_error_t *
get_last_history_rev(svn_revnum_t *revision,
svn_fs_root_t *root,
const char *path,
apr_pool_t *pool)
{
svn_fs_history_t *history;
const char *ignored;
/* Get an initial HISTORY baton. */
SVN_ERR(svn_fs_node_history2(&history, root, path, pool, pool));
/* Now get the first *real* point of interesting history. */
SVN_ERR(svn_fs_history_prev2(&history, history, FALSE, pool, pool));
/* Fetch the location information for this history step. */
return svn_fs_history_location(&ignored, revision, history, pool);
}
svn_revnum_t
dav_svn__get_safe_cr(svn_fs_root_t *root, const char *path, apr_pool_t *pool)
{
svn_revnum_t revision = svn_fs_revision_root_revision(root);
svn_revnum_t history_rev;
svn_fs_root_t *other_root;
svn_fs_t *fs = svn_fs_root_fs(root);
svn_fs_node_relation_t node_relation;
svn_error_t *err;
if ((err = get_last_history_rev(&history_rev, root, path, pool)))
{
svn_error_clear(err);
return revision; /* couldn't find last history rev */
}
if ((err = svn_fs_revision_root(&other_root, fs, history_rev, pool)))
{
svn_error_clear(err);
return revision; /* couldn't open the history rev */
}
if ((err = svn_fs_node_relation(&node_relation, root, path,
other_root, path, pool)))
{
svn_error_clear(err);
return revision;
}
if (node_relation == svn_fs_node_unchanged)
return history_rev; /* the history rev is safe! the same node
exists at the same path in both revisions. */
/* default */
return revision;
}
const char *
dav_svn__build_uri(const dav_svn_repos *repos,
enum dav_svn__build_what what,
svn_revnum_t revision,
const char *path,
svn_boolean_t add_href,
apr_pool_t *pool)
{
const char *root_path = repos->root_path;
const char *special_uri = repos->special_uri;
const char *path_uri = path ? svn_path_uri_encode(path, pool) : NULL;
const char *href1 = add_href ? "<D:href>" : "";
const char *href2 = add_href ? "</D:href>" : "";
/* The first character of root_path is guaranteed to be "/". If
there's no component beyond that, then just use "", so that
appending another "/" later does not result in "//". */
if (root_path[1] == '\0')
root_path = "";
switch (what)
{
case DAV_SVN__BUILD_URI_ACT_COLLECTION:
return apr_psprintf(pool, "%s%s/%s/act/%s",
href1, root_path, special_uri, href2);
case DAV_SVN__BUILD_URI_BASELINE:
return apr_psprintf(pool, "%s%s/%s/bln/%ld%s",
href1, root_path, special_uri, revision, href2);
case DAV_SVN__BUILD_URI_BC:
return apr_psprintf(pool, "%s%s/%s/bc/%ld/%s",
href1, root_path, special_uri, revision, href2);
case DAV_SVN__BUILD_URI_PUBLIC:
return apr_psprintf(pool, "%s%s%s%s",
href1, root_path, path_uri, href2);
case DAV_SVN__BUILD_URI_VERSION:
return apr_psprintf(pool, "%s%s/%s/ver/%ld%s%s",
href1, root_path, special_uri,
revision, path_uri, href2);
case DAV_SVN__BUILD_URI_REVROOT:
return apr_psprintf(pool, "%s%s/%s/rvr/%ld%s%s",
href1, root_path, special_uri,
revision, path_uri, href2);
case DAV_SVN__BUILD_URI_VCC:
return apr_psprintf(pool, "%s%s/%s/vcc/" DAV_SVN__DEFAULT_VCC_NAME "%s",
href1, root_path, special_uri, href2);
default:
/* programmer error somewhere */
SVN_ERR_MALFUNCTION_NO_RETURN();
}
/* NOTREACHED */
}
svn_error_t *
dav_svn__simple_parse_uri(dav_svn__uri_info *info,
const dav_resource *relative,
const char *uri,
apr_pool_t *pool)
{
apr_uri_t comp;
const char *path;
apr_size_t len1;
apr_size_t len2;
const char *slash;
const char *created_rev_str;
/* parse the input URI, in case it is more than just a path */
if (apr_uri_parse(pool, uri, &comp) != APR_SUCCESS)
goto malformed_uri;
/* ### ignore all URI parts but the path (for now) */
/* clean up the URI */
if (comp.path == NULL)
path = "/";
else
{
ap_getparents(comp.path);
ap_no2slash(comp.path);
path = comp.path;
}
/*
* Does the URI path specify the same repository? It does not if one of:
*
* 1) input is shorter than the path to our repository
* 2) input is longer, but there is no separator
* [ http://host/repos vs http://host/repository ]
* 3) the two paths do not match
*/
len1 = strlen(path);
len2 = strlen(relative->info->repos->root_path);
if (len2 == 1 && relative->info->repos->root_path[0] == '/')
len2 = 0;
if (len1 < len2
|| (len1 > len2 && path[len2] != '/')
|| memcmp(path, relative->info->repos->root_path, len2) != 0)
{
return svn_error_create(SVN_ERR_APMOD_MALFORMED_URI, NULL,
"Unusable URI: it does not refer to this "
"repository");
}
/* prep the return value */
memset(info, 0, sizeof(*info));
info->rev = SVN_INVALID_REVNUM;
path += len2; /* now points to "/" or "\0" */
len1 -= len2;
if (len1 <= 1)
{
info->repos_path = "/";
return NULL;
}
/* skip over the leading "/" */
++path;
--len1;
/* is this a special URI? */
len2 = strlen(relative->info->repos->special_uri);
if (len1 < len2
|| (len1 > len2 && path[len2] != '/')
|| memcmp(path, relative->info->repos->special_uri, len2) != 0)
{
/* this is an ordinary "public" URI, so back up to include the
leading '/' and just return... no need to parse further. */
info->repos_path = svn_path_uri_decode(path - 1, pool);
return NULL;
}
path += len2; /* now points to "/" or "\0" just past the special URI */
len1 -= len2;
/* ### we don't handle the root of the special area yet */
if (len1 <= 1)
goto unhandled_form;
/* Find the next component, and ensure something is there. */
slash = ap_strchr_c(path + 1, '/');
if (slash == NULL || slash[1] == '\0')
goto unhandled_form;
len2 = slash - path;
/* Figure out what we have here */
if (len2 == 4 && memcmp(path, "/act/", 5) == 0)
{
/* an activity */
info->activity_id = path + 5;
}
else if (len2 == 4 &&
(memcmp(path, "/ver/", 5) == 0 || memcmp(path, "/rvr/", 5) == 0))
{
/* a version resource */
path += 5;
len1 -= 5;
slash = ap_strchr_c(path, '/');
if (slash == NULL)
{
created_rev_str = apr_pstrndup(pool, path, len1);
info->rev = SVN_STR_TO_REV(created_rev_str);
info->repos_path = "/";
}
else
{
created_rev_str = apr_pstrndup(pool, path, slash - path);
info->rev = SVN_STR_TO_REV(created_rev_str);
info->repos_path = svn_path_uri_decode(slash, pool);
}
if (info->rev == SVN_INVALID_REVNUM)
goto malformed_uri;
}
else
goto unhandled_form;
return NULL;
malformed_uri:
return svn_error_create(SVN_ERR_APMOD_MALFORMED_URI, NULL,
"The specified URI could not be parsed");
unhandled_form:
return svn_error_create(SVN_ERR_UNSUPPORTED_FEATURE, NULL,
"Unsupported URI form");
}
svn_boolean_t
dav_svn__is_parentpath_list(request_rec *r)
{
const char *fs_parent_path = dav_svn__get_fs_parent_path(r);
if (fs_parent_path && dav_svn__get_list_parentpath_flag(r))
{
const char *root_path = dav_svn__get_root_dir(r);
char *uri = apr_pstrdup(r->pool, r->uri);
char *parentpath = apr_pstrdup(r->pool, root_path);
apr_size_t uri_len = strlen(uri);
apr_size_t parentpath_len = strlen(parentpath);
if (uri[uri_len-1] == '/')
uri[uri_len-1] = '\0';
if (parentpath[parentpath_len-1] == '/')
parentpath[parentpath_len-1] = '\0';
if (strcmp(parentpath, uri) == 0)
{
return TRUE;
}
}
return FALSE;
}
/* ### move this into apr_xml */
int
dav_svn__find_ns(const apr_array_header_t *namespaces, const char *uri)
{
int i;
for (i = 0; i < namespaces->nelts; ++i)
if (strcmp(APR_XML_GET_URI_ITEM(namespaces, i), uri) == 0)
return i;
return -1;
}
/*** Output helpers ***/
struct dav_svn__output
{
request_rec *r;
};
dav_svn__output *
dav_svn__output_create(request_rec *r,
apr_pool_t *pool)
{
dav_svn__output *output = apr_pcalloc(pool, sizeof(*output));
output->r = r;
return output;
}
apr_bucket_alloc_t *
dav_svn__output_get_bucket_alloc(dav_svn__output *output)
{
return output->r->connection->bucket_alloc;
}
svn_error_t *
dav_svn__output_pass_brigade(dav_svn__output *output,
apr_bucket_brigade *bb)
{
apr_status_t status;
status = ap_pass_brigade(output->r->output_filters, bb);
/* Empty the brigade here, as required by ap_pass_brigade(). */
apr_brigade_cleanup(bb);
if (status)
return svn_error_create(status, NULL, "Could not write data to filter");
/* Check for an aborted connection, since the brigade functions don't
appear to return useful errors when the connection is dropped. */
if (output->r->connection->aborted)
return svn_error_create(SVN_ERR_APMOD_CONNECTION_ABORTED, NULL, NULL);
return SVN_NO_ERROR;
}
/*** Brigade I/O wrappers ***/
svn_error_t *
dav_svn__brigade_write(apr_bucket_brigade *bb,
dav_svn__output *output,
const char *data,
apr_size_t len)
{
apr_status_t apr_err;
apr_err = apr_brigade_write(bb, ap_filter_flush,
output->r->output_filters, data, len);
if (apr_err)
return svn_error_create(apr_err, 0, NULL);
/* Check for an aborted connection, since the brigade functions don't
appear to be return useful errors when the connection is dropped. */
if (output->r->connection->aborted)
return svn_error_create(SVN_ERR_APMOD_CONNECTION_ABORTED, 0, NULL);
return SVN_NO_ERROR;
}
svn_error_t *
dav_svn__brigade_puts(apr_bucket_brigade *bb,
dav_svn__output *output,
const char *str)
{
apr_status_t apr_err;
apr_err = apr_brigade_puts(bb, ap_filter_flush,
output->r->output_filters, str);
if (apr_err)
return svn_error_create(apr_err, 0, NULL);
/* Check for an aborted connection, since the brigade functions don't
appear to be return useful errors when the connection is dropped. */
if (output->r->connection->aborted)
return svn_error_create(SVN_ERR_APMOD_CONNECTION_ABORTED, 0, NULL);
return SVN_NO_ERROR;
}
svn_error_t *
dav_svn__brigade_printf(apr_bucket_brigade *bb,
dav_svn__output *output,
const char *fmt,
...)
{
apr_status_t apr_err;
va_list ap;
va_start(ap, fmt);
apr_err = apr_brigade_vprintf(bb, ap_filter_flush,
output->r->output_filters, fmt, ap);
va_end(ap);
if (apr_err)
return svn_error_create(apr_err, 0, NULL);
/* Check for an aborted connection, since the brigade functions don't
appear to be return useful errors when the connection is dropped. */
if (output->r->connection->aborted)
return svn_error_create(SVN_ERR_APMOD_CONNECTION_ABORTED, 0, NULL);
return SVN_NO_ERROR;
}
svn_error_t *
dav_svn__brigade_putstrs(apr_bucket_brigade *bb,
dav_svn__output *output,
...)
{
apr_status_t apr_err;
va_list ap;
va_start(ap, output);
apr_err = apr_brigade_vputstrs(bb, ap_filter_flush,
output->r->output_filters, ap);
va_end(ap);
if (apr_err)
return svn_error_create(apr_err, NULL, NULL);
/* Check for an aborted connection, since the brigade functions don't
appear to return useful errors when the connection is dropped. */
if (output->r->connection->aborted)
return svn_error_create(SVN_ERR_APMOD_CONNECTION_ABORTED, NULL, NULL);
return SVN_NO_ERROR;
}
dav_error *
dav_svn__test_canonical(const char *path, apr_pool_t *pool)
{
if (path[0] == '\0')
return NULL;
if (svn_path_is_url(path) && svn_uri_is_canonical(path, pool))
return NULL;
if ((path[0] == '/') && svn_fspath__is_canonical(path))
return NULL;
if (svn_relpath_is_canonical(path))
return NULL;
/* Otherwise, generate a generic HTTP_BAD_REQUEST error. */
return dav_svn__new_error_svn(
pool, HTTP_BAD_REQUEST, 0, 0,
apr_psprintf(pool,
"Path '%s' is not canonicalized; "
"there is a problem with the client.", path));
}
dav_error *
dav_svn__sanitize_error(svn_error_t *serr,
const char *new_msg,
int http_status,
request_rec *r)
{
svn_error_t *safe_err = serr;
if (new_msg != NULL)
{
/* Purge error tracing from the error chain. */
svn_error_t *purged_serr = svn_error_purge_tracing(serr);
/* Sanitization is necessary. Create a new, safe error and
log the original error. */
safe_err = svn_error_create(purged_serr->apr_err, NULL, new_msg);
ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, r,
"%s", purged_serr->message);
/* Log the entire error chain. */
while (purged_serr->child)
{
purged_serr = purged_serr->child;
ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, r,
"%s", purged_serr->message);
}
svn_error_clear(serr);
}
return dav_svn__convert_err(safe_err, http_status,
apr_psprintf(r->pool, "%s", safe_err->message),
r->pool);
}
struct brigade_write_baton
{
apr_bucket_brigade *bb;
dav_svn__output *output;
};
/* This implements 'svn_write_fn_t'. */
static svn_error_t *
brigade_write_fn(void *baton, const char *data, apr_size_t *len)
{
struct brigade_write_baton *wb = baton;
apr_status_t apr_err;
apr_err = apr_brigade_write(wb->bb, ap_filter_flush,
wb->output->r->output_filters, data, *len);
if (apr_err != APR_SUCCESS)
return svn_error_wrap_apr(apr_err, "Error writing base64 data");
return SVN_NO_ERROR;
}
svn_stream_t *
dav_svn__make_base64_output_stream(apr_bucket_brigade *bb,
dav_svn__output *output,
apr_pool_t *pool)
{
struct brigade_write_baton *wb = apr_palloc(pool, sizeof(*wb));
svn_stream_t *stream = svn_stream_create(wb, pool);
wb->bb = bb;
wb->output = output;
svn_stream_set_write(stream, brigade_write_fn);
return svn_base64_encode2(stream, FALSE, pool);
}
void
dav_svn__operational_log(struct dav_resource_private *info, const char *line)
{
apr_table_set(info->r->subprocess_env, "SVN-ACTION", line);
apr_table_set(info->r->subprocess_env, "SVN-REPOS",
svn_path_uri_encode(info->repos->fs_path, info->r->pool));
apr_table_set(info->r->subprocess_env, "SVN-REPOS-NAME",
svn_path_uri_encode(info->repos->repo_basename, info->r->pool));
}
dav_error *
dav_svn__final_flush_or_error(request_rec *r,
apr_bucket_brigade *bb,
dav_svn__output *output,
dav_error *preferred_err,
apr_pool_t *pool)
{
dav_error *derr = preferred_err;
svn_boolean_t do_flush;
do_flush = r->sent_bodyct > 0;
if (! do_flush)
{
/* Ask about the length of the bucket brigade, ignoring errors. */
apr_off_t len = 0;
(void)apr_brigade_length(bb, FALSE, &len);
do_flush = (len != 0);
}
/* If there's something in the bucket brigade to flush, or we've
already started sending data down the wire, flush what we've
got. We only keep any error retrieved from the flush if weren't
provided a more-important DERR, though. */
if (do_flush)
{
apr_status_t apr_err = ap_fflush(output->r->output_filters, bb);
if (apr_err && (! derr))
derr = dav_svn__new_error(pool, HTTP_INTERNAL_SERVER_ERROR, 0, apr_err,
"Error flushing brigade.");
}
return derr;
}
void dav_svn__log_err(request_rec *r,
dav_error *err,
int level)
{
dav_error *errscan;
/* Log the errors */
/* ### should have a directive to log the first or all */
for (errscan = err; errscan != NULL; errscan = errscan->prev) {
apr_status_t status;
if (errscan->desc == NULL)
continue;
#if AP_MODULE_MAGIC_AT_LEAST(20091119,0)
status = errscan->aprerr;
#else
status = errscan->save_errno;
#endif
ap_log_rerror(APLOG_MARK, level, status, r,
"%s [%d, #%d]",
errscan->desc, errscan->status, errscan->error_id);
}
}
int
dav_svn__error_response_tag(request_rec *r,
dav_error *err)
{
r->status = err->status;
/* ### I really don't think this is needed; gotta test */
r->status_line = ap_get_status_line(err->status);
ap_set_content_type(r, DAV_XML_CONTENT_TYPE);
ap_rputs(DAV_XML_HEADER DEBUG_CR "<D:error xmlns:D=\"DAV:\"", r);
if (err->desc != NULL)
ap_rputs(" xmlns:m=\"http://apache.org/dav/xmlns\"", r);
if (err->namespace != NULL)
ap_rprintf(r, " xmlns:C=\"%s\">" DEBUG_CR "<C:%s/>" DEBUG_CR,
err->namespace, err->tagname);
else if (err->tagname != NULL)
ap_rprintf(r, ">" DEBUG_CR "<D:%s/>" DEBUG_CR, err->tagname);
else
ap_rputs(">" DEBUG_CR, r);
/* here's our mod_dav specific tag: */
if (err->desc != NULL)
ap_rprintf(r, "<m:human-readable errcode=\"%d\">" DEBUG_CR "%s" DEBUG_CR
"</m:human-readable>" DEBUG_CR, err->error_id,
apr_xml_quote_string(r->pool, err->desc, 0));
ap_rputs("</D:error>" DEBUG_CR, r);
/* the response has been sent. */
/*
* ### Use of DONE obviates logging..!
*/
return DONE;
}
/* Set *REQUEST_STR to a string containing the contents of the body of
request R, allocated from POOL.
NOTE: This was shamelessly stolen and modified from Apache's
ap_xml_parse_input(). */
static int
request_body_to_string(svn_string_t **request_str,
request_rec *r,
apr_pool_t *pool)
{
apr_bucket_brigade *brigade;
int seen_eos;
apr_status_t status;
apr_off_t total_read = 0;
apr_off_t limit_req_body = ap_get_limit_xml_body(r);
int result = HTTP_BAD_REQUEST;
const char *content_length_str;
char *endp;
apr_off_t content_length;
svn_stringbuf_t *buf;
*request_str = NULL;
content_length_str = apr_table_get(r->headers_in, "Content-Length");
if (content_length_str)
{
if (apr_strtoff(&content_length, content_length_str, &endp, 10)
|| endp == content_length_str || *endp || content_length < 0)
{
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid Content-Length");
return HTTP_REQUEST_ENTITY_TOO_LARGE;
}
}
else
content_length = 0;
if (limit_req_body && (limit_req_body < content_length))
{
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Requested content-length of %" APR_OFF_T_FMT " is larger "
"than the configured limit of %" APR_OFF_T_FMT,
content_length, limit_req_body);
return HTTP_REQUEST_ENTITY_TOO_LARGE;
}
if (content_length)
{
/* Do not allocate more than 1 MB until we receive request body. */
apr_size_t alloc_len = 1 * 1024 *1024;
if (content_length < alloc_len)
alloc_len = (apr_size_t) content_length;
buf = svn_stringbuf_create_ensure(alloc_len, pool);
}
else
{
buf = svn_stringbuf_create_empty(pool);
}
brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
seen_eos = 0;
total_read = 0;
do
{
apr_bucket *bucket;
status = ap_get_brigade(r->input_filters, brigade, AP_MODE_READBYTES,
APR_BLOCK_READ, 2048);
if (status != APR_SUCCESS)
goto cleanup;
for (bucket = APR_BRIGADE_FIRST(brigade);
bucket != APR_BRIGADE_SENTINEL(brigade);
bucket = APR_BUCKET_NEXT(bucket))
{
const char *data;
apr_size_t len;
if (APR_BUCKET_IS_EOS(bucket))
{
seen_eos = 1;
break;
}
if (APR_BUCKET_IS_METADATA(bucket))
continue;
status = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
if (status != APR_SUCCESS)
goto cleanup;
total_read += len;
if (limit_req_body && total_read > limit_req_body)
{
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"Request body is larger than the configured "
"limit of %" APR_OFF_T_FMT, limit_req_body);
result = HTTP_REQUEST_ENTITY_TOO_LARGE;
goto cleanup;
}
svn_stringbuf_appendbytes(buf, data, len);
}
apr_brigade_cleanup(brigade);
}
while (!seen_eos);
apr_brigade_destroy(brigade);
/* Make an svn_string_t from our svn_stringbuf_t. */
*request_str = svn_stringbuf__morph_into_string(buf);
return OK;
cleanup:
apr_brigade_destroy(brigade);
/* Apache will supply a default error, plus the error log above. */
return result;
}
int
dav_svn__parse_request_skel(svn_skel_t **skel,
request_rec *r,
apr_pool_t *pool)
{
svn_string_t *skel_str;
int status;
*skel = NULL;
status = request_body_to_string(&skel_str, r, pool);
if (status != OK)
return status;
*skel = svn_skel__parse(skel_str->data, skel_str->len, pool);
return OK;
}
svn_error_t *
dav_svn__get_youngest_rev(svn_revnum_t *youngest_p,
dav_svn_repos *repos,
apr_pool_t *scratch_pool)
{
if (repos->youngest_rev == SVN_INVALID_REVNUM)
{
svn_revnum_t revnum;
SVN_ERR(svn_fs_youngest_rev(&revnum, repos->fs, scratch_pool));
repos->youngest_rev = revnum;
}
*youngest_p = repos->youngest_rev;
return SVN_NO_ERROR;
}
const char *
dav_svn__fuzzy_escape_author(const char *author,
svn_boolean_t is_svn_client,
apr_pool_t *result_pool,
apr_pool_t *scratch_pool)
{
apr_size_t len = strlen(author);
if (is_svn_client && !svn_xml_is_xml_safe(author, len))
{
/* We are talking to a Subversion client, which will (like any proper
xml parser) error out if we produce control characters in XML.
However Subversion clients process both the generic
<creator-displayname /> as the custom element for svn:author.
Let's skip outputting the invalid characters here to make the XML
valid, so clients can see the custom element.
Subversion Clients will then either use a slightly invalid
author (unlikely) or more likely use the second result, which
will be transferred with full escaping capabilities.
We have tests in place to assert proper behavior over the RA layer.
*/
apr_size_t i;
svn_stringbuf_t *buf;
buf = svn_stringbuf_ncreate(author, len, scratch_pool);
for (i = 0; i < buf->len; i++)
{
char c = buf->data[i];
if (svn_ctype_iscntrl(c))
{
svn_stringbuf_remove(buf, i--, 1);
}
}
author = buf->data;
}
return apr_xml_quote_string(result_pool, author, 1);
}
| 29.941176 | 81 | 0.619427 |
9f04eb5128ca3c40273416ccd4dbbf951c1bb9ba | 2,125 | h | C | HiClass_SDK/USFrameworks/YSLib/expandLib/CHWhiteBoard/CloudHubWhiteBoardKit/CloudHubWhiteBoardKit.framework/Headers/CloudHubWhiteBoardConfig.h | jia-hisense/HiClasss_SDK | 24e10c8fc46d66c332c132f3026d67dba56e9bd3 | [
"MIT"
] | null | null | null | HiClass_SDK/USFrameworks/YSLib/expandLib/CHWhiteBoard/CloudHubWhiteBoardKit/CloudHubWhiteBoardKit.framework/Headers/CloudHubWhiteBoardConfig.h | jia-hisense/HiClasss_SDK | 24e10c8fc46d66c332c132f3026d67dba56e9bd3 | [
"MIT"
] | null | null | null | HiClass_SDK/USFrameworks/YSLib/expandLib/CHWhiteBoard/CloudHubWhiteBoardKit/CloudHubWhiteBoardKit.framework/Headers/CloudHubWhiteBoardConfig.h | jia-hisense/HiClasss_SDK | 24e10c8fc46d66c332c132f3026d67dba56e9bd3 | [
"MIT"
] | null | null | null | //
// CHWhiteBoardSDKConfig.h
// YSWhiteBoardSDK
//
//
#import "CloudHubWhiteBoardViewConfig.h"
NS_ASSUME_NONNULL_BEGIN
@interface CloudHubWhiteBoardConfig : CloudHubWhiteBoardViewConfig
/// 是否同步 默认: YES
@property (nonatomic, assign) BOOL isSync;
/// 是否多课件 默认: NO,不能即时修改
@property (nonatomic, assign, readonly) BOOL isMultiCourseware;
/// PDF文件解析度 >1整数 默认: 2 越大越清晰
@property (nonatomic, assign) NSUInteger PDFLevel;
/// 默认画笔工具 默认: CHBrushToolTypeMouse,不能即时修改
@property (nonatomic, assign, readonly) CHBrushToolType defaultToolType;
/// 是否实例化画笔数据(可以删除移动画笔数据,取消橡皮擦功能) 默认: NO,不能即时修改
@property (nonatomic, assign, readonly) BOOL isObjectLevel;
/// 是否可以点击交互 默认: YES
/// 只对H5及动态ppt课件有效
@property (nonatomic, assign) BOOL isPenCanPenetration;
/// 是否可以手势缩放课件(动态ppt及H5课件不支持) 默认: YES,不能即时修改
/// 注意:只是限制手势缩放,关闭后仍然可以通过翻页工具条控制缩放
@property (nonatomic, assign, readonly) BOOL canGestureZoom;
/// 是否使用HttpDNS加载课件 默认: NO,不能即时修改
@property (nonatomic, assign, readonly) BOOL useHttpDNS;
/// 是否使用预加载课件 默认: NO,不能即时修改
@property (nonatomic, assign, readonly) BOOL isPreloading;
/// H5课件cookie 默认: nil,不能即时修改
@property (nonatomic, strong, readonly) NSArray <NSDictionary *> *connectH5CoursewareUrlCookies;
/// 初始化配置项
/// @param params @{CHWhiteBoardKitConfigMultiCoursewareKey : BOOL,
/// CHWhiteBoardKitConfigDefaultToolTypeKey : CHBrushToolType,
/// CHWhiteBoardKitConfigObjectLevelKey : BOOL,
/// CHWhiteBoardKitConfigCanvasRatioKey : CGFloat,
/// CHWhiteBoardKitConfigGestureZoomKey : BOOL,
/// CHWhiteBoardKitConfigHttpDNSKey : BOOL,
/// CHWhiteBoardKitConfigPreloadingKey : BOOL }
- (instancetype)initWithParams:(NSDictionary *)params;
- (instancetype)initWithMultiCourseware:(BOOL)isMultiCourseware defaultToolType:(CHBrushToolType)defaultToolType isObjectLevel:(BOOL)isObjectLevel canvasRatio:(CGFloat)canvasRatio canGestureZoom:(BOOL)canGestureZoom useHttpDNS:(BOOL)useHttpDNS cookies:(nullable NSArray <NSDictionary *> *)urlCookies;
- (CloudHubWhiteBoardViewConfig *)cloneToWhiteBoardViewConfig;
@end
NS_ASSUME_NONNULL_END
| 34.274194 | 300 | 0.759529 |
886dcf960423a85611c1e44aeb6035e7a23832f9 | 2,113 | h | C | code/application/attic/physicsfeature/physicsfeatureunit.h | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/application/attic/physicsfeature/physicsfeatureunit.h | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/application/attic/physicsfeature/physicsfeatureunit.h | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | #ifndef PHYSICSFEATURE_PHYSICSFEATUREUNIT_H
#define PHYSICSFEATURE_PHYSICSFEATUREUNIT_H
//------------------------------------------------------------------------------
/**
@class Game::PhysicsFeatureUnit
The physicsfeature offers the use of collision and
physical representation of game objects.
It uses the physics addon with use of a third party physics system (like ODE).
It offers a collide property for static environment objects and a physicsproperty
for passiv moving dynamic objects and an actorphysicsproperty for active dynamic moving
objects.
Additional there is a mousegripperproperty for grabbing and throwing
physics object around.
IMPORTANT: the physics server and so the physics simulation system is triggered in
OnFrame of the feature so
(C) 2007 Radon Labs GmbH
*/
#include "game/featureunit.h"
#include "physics/physicsserver.h"
#include "debug/debugtimer.h"
//------------------------------------------------------------------------------
namespace PhysicsFeature
{
class PhysicsFeatureUnit : public Game::FeatureUnit
{
__DeclareClass(PhysicsFeatureUnit);
__DeclareSingleton(PhysicsFeatureUnit);
public:
/// constructor
PhysicsFeatureUnit();
/// destructor
virtual ~PhysicsFeatureUnit();
/// called from GameServer::ActivateProperties()
virtual void OnActivate();
/// called from GameServer::DeactivateProperties()
virtual void OnDeactivate();
/// called after loading game state
virtual void OnLoad();
/// called in the middle of the feature trigger cycle
virtual void OnFrame();
/// called when game debug visualization is on
virtual void OnRenderDebug();
/// create default physics world
void CreateDefaultPhysicsWorld();
/// cleanup physics world
void CleanupPhysicsWorld();
protected:
Ptr<Physics::PhysicsServer> physicsServer;
_declare_timer(PhysicsFeatureUpdatePhysics);
};
}; // namespace PhysicsFeature
//------------------------------------------------------------------------------
#endif | 30.185714 | 92 | 0.644581 |
7afd5960e0b1f7b840f67b38ff837d4f430b3a7e | 516 | h | C | RDExtensions/UIButton+Extensions.h | Ryder-Cheng/RDExtensions | e224246a7415d6821db267bd7e0f5d611bc111b5 | [
"MIT"
] | null | null | null | RDExtensions/UIButton+Extensions.h | Ryder-Cheng/RDExtensions | e224246a7415d6821db267bd7e0f5d611bc111b5 | [
"MIT"
] | null | null | null | RDExtensions/UIButton+Extensions.h | Ryder-Cheng/RDExtensions | e224246a7415d6821db267bd7e0f5d611bc111b5 | [
"MIT"
] | null | null | null | //
// UIButton+Extensions.h
// RDExtensions
//
// Created by ChengYaojun on 2017/4/17.
// Copyright © 2017年 ChengYaojun. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIButton (Extensions)
- (void)setBorderColor:(nullable UIColor *)color forState:(UIControlState)state;
- (void)setBackgroundColor:(nullable UIColor *)color forState:(UIControlState)state;
- (nullable UIColor *)borderColorForState:(UIControlState)state;
- (nullable UIColor *)backgroundColorForState:(UIControlState)state;
@end
| 25.8 | 84 | 0.761628 |
0af53e38877fac6e2b69b16fc998e87bf4cbfa12 | 3,799 | h | C | src/script/bitcoinrconsensus.h | fancywarlock/bitcoinr | 12b4dee6342556c0890218b843f29cadfab06214 | [
"MIT"
] | 2 | 2020-05-31T01:06:06.000Z | 2021-06-07T22:29:32.000Z | src/script/bitcoinrconsensus.h | fancywarlock/bitcoinr | 12b4dee6342556c0890218b843f29cadfab06214 | [
"MIT"
] | null | null | null | src/script/bitcoinrconsensus.h | fancywarlock/bitcoinr | 12b4dee6342556c0890218b843f29cadfab06214 | [
"MIT"
] | 3 | 2020-09-24T16:46:45.000Z | 2021-06-07T22:29:33.000Z | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2020 The bitcoinR Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOINR_SCRIPT_BITCOINRCONSENSUS_H
#define BITCOINR_SCRIPT_BITCOINRCONSENSUS_H
#include <stdint.h>
#if defined(BUILD_BITCOINR_INTERNAL) && defined(HAVE_CONFIG_H)
#include <config/bitcoinr-config.h>
#if defined(_WIN32)
#if defined(DLL_EXPORT)
#if defined(HAVE_FUNC_ATTRIBUTE_DLLEXPORT)
#define EXPORT_SYMBOL __declspec(dllexport)
#else
#define EXPORT_SYMBOL
#endif
#endif
#elif defined(HAVE_FUNC_ATTRIBUTE_VISIBILITY)
#define EXPORT_SYMBOL __attribute__ ((visibility ("default")))
#endif
#elif defined(MSC_VER) && !defined(STATIC_LIBBITCOINRCONSENSUS)
#define EXPORT_SYMBOL __declspec(dllimport)
#endif
#ifndef EXPORT_SYMBOL
#define EXPORT_SYMBOL
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define BITCOINRCONSENSUS_API_VER 1
typedef enum bitcoinrconsensus_error_t
{
bitcoinrconsensus_ERR_OK = 0,
bitcoinrconsensus_ERR_TX_INDEX,
bitcoinrconsensus_ERR_TX_SIZE_MISMATCH,
bitcoinrconsensus_ERR_TX_DESERIALIZE,
bitcoinrconsensus_ERR_AMOUNT_REQUIRED,
bitcoinrconsensus_ERR_INVALID_FLAGS,
} bitcoinrconsensus_error;
/** Script verification flags */
enum
{
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_NONE = 0,
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_P2SH = (1U << 0), // evaluate P2SH (BIP16) subscripts
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_DERSIG = (1U << 2), // enforce strict DER (BIP66) compliance
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_NULLDUMMY = (1U << 4), // enforce NULLDUMMY (BIP147)
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9), // enable CHECKLOCKTIMEVERIFY (BIP65)
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_CHECKSEQUENCEVERIFY = (1U << 10), // enable CHECKSEQUENCEVERIFY (BIP112)
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_WITNESS = (1U << 11), // enable WITNESS (BIP141)
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_ALL = bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_P2SH | bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_DERSIG |
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_NULLDUMMY | bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_CHECKLOCKTIMEVERIFY |
bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_CHECKSEQUENCEVERIFY | bitcoinrconsensus_SCRIPT_FLAGS_VERIFY_WITNESS
};
/// Returns 1 if the input nIn of the serialized transaction pointed to by
/// txTo correctly spends the scriptPubKey pointed to by scriptPubKey under
/// the additional constraints specified by flags.
/// If not nullptr, err will contain an error/success code for the operation
EXPORT_SYMBOL int bitcoinrconsensus_verify_script(const unsigned char *scriptPubKey, unsigned int scriptPubKeyLen,
const unsigned char *txTo , unsigned int txToLen,
unsigned int nIn, unsigned int flags, bitcoinrconsensus_error* err);
EXPORT_SYMBOL int bitcoinrconsensus_verify_script_with_amount(const unsigned char *scriptPubKey, unsigned int scriptPubKeyLen, int64_t amount,
const unsigned char *txTo , unsigned int txToLen,
unsigned int nIn, unsigned int flags, bitcoinrconsensus_error* err);
EXPORT_SYMBOL unsigned int bitcoinrconsensus_version();
#ifdef __cplusplus
} // extern "C"
#endif
#undef EXPORT_SYMBOL
#endif // BITCOINR_SCRIPT_BITCOINRCONSENSUS_H
| 44.694118 | 172 | 0.722032 |
5bb1d6197b7c80baca7314a28a90c73585d47f6b | 3,101 | h | C | Scripts/Template/Headers/guava/com/google/common/collect/TreeRangeMap.h | zhouxl/J2ObjC-Framework | ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/guava/com/google/common/collect/TreeRangeMap.h | zhouxl/J2ObjC-Framework | ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/guava/com/google/common/collect/TreeRangeMap.h | zhouxl/J2ObjC-Framework | ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: /Users/antoniocortes/j2objcprj/relases/j2objc/guava/build_result/java/com/google/common/collect/TreeRangeMap.java
//
#include "../../../../../J2ObjC_header.h"
#pragma push_macro("INCLUDE_ALL_ComGoogleCommonCollectTreeRangeMap")
#ifdef RESTRICT_ComGoogleCommonCollectTreeRangeMap
#define INCLUDE_ALL_ComGoogleCommonCollectTreeRangeMap 0
#else
#define INCLUDE_ALL_ComGoogleCommonCollectTreeRangeMap 1
#endif
#undef RESTRICT_ComGoogleCommonCollectTreeRangeMap
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif
#if !defined (ComGoogleCommonCollectTreeRangeMap_) && (INCLUDE_ALL_ComGoogleCommonCollectTreeRangeMap || defined(INCLUDE_ComGoogleCommonCollectTreeRangeMap))
#define ComGoogleCommonCollectTreeRangeMap_
#define RESTRICT_ComGoogleCommonCollectRangeMap 1
#define INCLUDE_ComGoogleCommonCollectRangeMap 1
#include "../../../../../com/google/common/collect/RangeMap.h"
@class ComGoogleCommonCollectRange;
@protocol JavaLangComparable;
@protocol JavaUtilMap;
@protocol JavaUtilMap_Entry;
/*!
@brief An implementation of <code>RangeMap</code> based on a <code>TreeMap</code>, supporting all optional
operations.
<p>Like all <code>RangeMap</code> implementations, this supports neither null keys nor null values.
@author Louis Wasserman
@since 14.0
*/
@interface ComGoogleCommonCollectTreeRangeMap : NSObject < ComGoogleCommonCollectRangeMap >
#pragma mark Public
- (id<JavaUtilMap>)asDescendingMapOfRanges;
- (id<JavaUtilMap>)asMapOfRanges;
- (void)clear;
+ (ComGoogleCommonCollectTreeRangeMap *)create;
- (jboolean)isEqual:(id __nullable)o;
- (id)getWithJavaLangComparable:(id<JavaLangComparable>)key;
- (id<JavaUtilMap_Entry> __nullable)getEntryWithJavaLangComparable:(id<JavaLangComparable>)key;
- (NSUInteger)hash;
- (void)putWithComGoogleCommonCollectRange:(ComGoogleCommonCollectRange *)range
withId:(id)value;
- (void)putAllWithComGoogleCommonCollectRangeMap:(id<ComGoogleCommonCollectRangeMap>)rangeMap;
- (void)putCoalescingWithComGoogleCommonCollectRange:(ComGoogleCommonCollectRange *)range
withId:(id)value;
- (void)removeWithComGoogleCommonCollectRange:(ComGoogleCommonCollectRange *)rangeToRemove;
- (ComGoogleCommonCollectRange *)span;
- (id<ComGoogleCommonCollectRangeMap>)subRangeMapWithComGoogleCommonCollectRange:(ComGoogleCommonCollectRange *)subRange;
- (NSString *)description;
@end
J2OBJC_STATIC_INIT(ComGoogleCommonCollectTreeRangeMap)
FOUNDATION_EXPORT ComGoogleCommonCollectTreeRangeMap *ComGoogleCommonCollectTreeRangeMap_create(void);
J2OBJC_TYPE_LITERAL_HEADER(ComGoogleCommonCollectTreeRangeMap)
#endif
#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_ComGoogleCommonCollectTreeRangeMap")
| 31.969072 | 157 | 0.807804 |
9db133d65c0ed519695a08e64d6df75070d5b430 | 273 | h | C | BTE/Classes/HomePageVC/View/BTEZTYLineKBottonView.h | sophiemarceau/bte_iOS | 3e44be16be9559709e5dfbe24855f929e68832b1 | [
"MIT"
] | 1 | 2022-02-08T06:42:11.000Z | 2022-02-08T06:42:11.000Z | BTE/Classes/HomePageVC/View/BTEZTYLineKBottonView.h | sophiemarceau/bte_iOS | 3e44be16be9559709e5dfbe24855f929e68832b1 | [
"MIT"
] | 1 | 2021-11-12T02:04:11.000Z | 2021-11-12T02:04:11.000Z | BTE/Classes/HomePageVC/View/BTEZTYLineKBottonView.h | sophiemarceau/bte_iOS | 3e44be16be9559709e5dfbe24855f929e68832b1 | [
"MIT"
] | null | null | null | //
// BTEZTYLineKBottonView.h
// BTE
//
// Created by wanmeizty on 2018/7/10.
// Copyright © 2018年 wangli. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface BTEZTYLineKBottonView : UIView
@property (nonatomic,copy) void(^clickBlock)(NSInteger index);
@end
| 17.0625 | 62 | 0.710623 |
8d5f2d07a0df752c2dbae885d6c34861573328f8 | 1,900 | h | C | Runtime/Source/Runtime/VulkanRHI/VulkanComputeShader.h | Rohfel/Kraken | b0d15b4e5fc132f90f5a2aed6b598a1f1509d059 | [
"MIT"
] | 3 | 2021-07-21T05:02:13.000Z | 2021-09-03T07:28:18.000Z | Runtime/Source/Runtime/VulkanRHI/VulkanComputeShader.h | Rohfel/Kraken | b0d15b4e5fc132f90f5a2aed6b598a1f1509d059 | [
"MIT"
] | null | null | null | Runtime/Source/Runtime/VulkanRHI/VulkanComputeShader.h | Rohfel/Kraken | b0d15b4e5fc132f90f5a2aed6b598a1f1509d059 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2021 Rohfel Adyaraka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include "Runtime/RHI/RHIComputeShader.h"
#include "Runtime/VulkanRHI/VulkanDevice.h"
namespace Kraken::VulkanRHI
{
class KComputeShader : public RHI::IComputeShader
{
public:
KComputeShader(const RHI::KComputeShaderCreationData& CreationData);
~KComputeShader() override
{
vkDestroyShaderModule(Device->GetDeviceHandle(), ComputeShaderModuleHandle, nullptr);
}
public:
const VkPipelineShaderStageCreateInfo& GetPipelineShaderStageCreationInformation() const
{
return PipelineShaderStageCreationInformation;
}
private:
std::vector<char> ReadShader(const std::filesystem::path& ShaderPath);
private:
std::shared_ptr<KDevice> Device;
VkPipelineShaderStageCreateInfo PipelineShaderStageCreationInformation;
VkShaderModule ComputeShaderModuleHandle;
};
} | 33.928571 | 90 | 0.793158 |
a5128bc0319f342ba1b1a3908361d51b03620cca | 346 | h | C | Software/Remote-Control/App/App.h | Nils2332/Timelapsebuild | b52f6aef94047295e815dabe2a9db1f44e46d883 | [
"MIT"
] | null | null | null | Software/Remote-Control/App/App.h | Nils2332/Timelapsebuild | b52f6aef94047295e815dabe2a9db1f44e46d883 | [
"MIT"
] | null | null | null | Software/Remote-Control/App/App.h | Nils2332/Timelapsebuild | b52f6aef94047295e815dabe2a9db1f44e46d883 | [
"MIT"
] | null | null | null | #ifndef SRC_APP_H_
#define SRC_APP_H_
#include <stdint.h>
#include <usart.h>
#ifdef __cplusplus
extern "C" {
#endif
void InterruptPIN(uint16_t GPIO_PIN);
void Timer_IT1();
void Timer_IT2();
void Timer_IT3();
void App_Start();
void JoyconUpdate();
double getJoycon(uint8_t channel);
#ifdef __cplusplus
}
#endif
#endif /* SRC_APP_H_ */
| 11.16129 | 37 | 0.728324 |
8b22ececb51e804ddb533673d33b7581257e3d4e | 33,675 | c | C | src/nccl_ofi_net.c | dmitrygladkov/aws-ofi-nccl | 11ce3ae9f5cd89277a594bf02681dc03afa0ac4a | [
"Apache-2.0"
] | null | null | null | src/nccl_ofi_net.c | dmitrygladkov/aws-ofi-nccl | 11ce3ae9f5cd89277a594bf02681dc03afa0ac4a | [
"Apache-2.0"
] | null | null | null | src/nccl_ofi_net.c | dmitrygladkov/aws-ofi-nccl | 11ce3ae9f5cd89277a594bf02681dc03afa0ac4a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2018 Amazon.com, Inc. or its affiliates. All rights reserved.
* Copyright (c) 2015-2018, NVIDIA CORPORATION. All rights reserved.
*/
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stack.h>
/* NICs info list for a provider */
struct fi_info* ofi_info_list = NULL;
/* Number of NICs */
int ofi_ndevices = -1;
/* NCCL OFI component array for all NICs */
nccl_ofi_t **nccl_ofi_component = NULL;
/*
* @brief Allocates free list
*/
static free_list_t *allocate_free_list(void)
{
free_list_t *fl = NULL;
fl = (free_list_t *)malloc(sizeof(free_list_t));
if (fl == NULL) {
NCCL_OFI_WARN("Unable to allocate free list structure");
goto exit;
}
fl->buffers = NULL;
fl->free_index = NULL;
exit:
return fl;
}
/*
* @brief Allocates free list for NCCL OFI requests
*/
static ncclResult_t allocate_ofi_fl(free_list_t **nccl_ofi_req_fl, size_t fl_size,
size_t buffer_size)
{
ncclResult_t ret = ncclSuccess, idx;
free_list_t *fl = NULL;
/* Validate free list size and buffer size */
if (fl_size < 1 || buffer_size < 1) {
ret = ncclSystemError;
NCCL_OFI_WARN("Invalid free list size and/or buffer size. Provided fl_size: %zu and buffer size: %zu",
fl_size, buffer_size);
goto error;
}
/* Allocate free list structure */
fl = allocate_free_list();
if (fl == NULL) {
ret = ncclSystemError;
goto error;
}
fl->size = fl_size;
/* Allocate buffers */
fl->buffers = calloc(fl->size, buffer_size);
if (fl->buffers == NULL) {
NCCL_OFI_WARN("Unable to allocate NCCL OFI free list buffers");
ret = ncclSystemError;
goto error;
}
/* Allocate stack of free indexes */
fl->free_index = allocate_stack(fl->size);
if (fl->free_index == NULL) {
NCCL_OFI_WARN("Couldn't allocate free index stack");
ret = ncclSystemError;
goto error;
}
/* Initialise stack */
for (idx = 0; idx < fl->free_index->size; idx++) {
ret = stack_push(fl->free_index, idx);
if (ret != 0)
goto error;
}
*nccl_ofi_req_fl = fl;
goto exit;
error:
if (fl->buffers)
free(fl->buffers);
if (fl->free_index)
free_stack(fl->free_index);
if (fl)
free(fl);
exit:
return ret;
}
/*
* @brief Assign an allocated NCCL OFI request buffer
*/
static inline nccl_ofi_req_t *allocate_nccl_ofi_request(free_list_t *fl)
{
nccl_ofi_req_t *req = NULL;
uint64_t next_avail_index;
if (OFI_UNLIKELY(fl == NULL || fl->free_index == NULL)) {
NCCL_OFI_WARN("Free list is empty or Free Index stack does not exist.");
goto exit;
}
/* Get free index */
next_avail_index = stack_pop(fl->free_index);
if (OFI_UNLIKELY(next_avail_index >= fl->free_index->size)) {
NCCL_OFI_WARN("No pre-allocated buffer is available for use. next_avail_index: %lu and free_index Size: %d",
next_avail_index, fl->free_index->size);
goto exit;
}
/* Get buffer */
if (OFI_UNLIKELY(fl->buffers == NULL)) {
NCCL_OFI_WARN("No pre-allocated buffers are present.");
goto exit;
}
req = &((nccl_ofi_req_t *)fl->buffers)[next_avail_index];
req->buffer_index = next_avail_index;
exit:
return req;
}
/*
* @brief Zero out NCCL OFI request
*/
static inline void zero_nccl_ofi_req(nccl_ofi_req_t *req)
{
req->src_addr = FI_ADDR_NOTAVAIL;
req->lComm = NULL;
req->sComm = NULL;
req->rComm = NULL;
req->buffer_index = 0ULL;
memset(&req->ctx, 0, sizeof(struct fi_context));
req->dev = -1;
req->size = 0;
req->state = NCCL_OFI_REQ_CREATED;
req->direction = -1;
}
/*
* @brief Prepares NCCL OFI request for reuse
*/
static inline int free_nccl_ofi_req(nccl_ofi_req_t *req, bool dec_inflight_cmds)
{
int ret = ncclSuccess;
sendComm_t *sComm = NULL;
recvComm_t *rComm = NULL;
uint64_t buffer_index;
if (OFI_UNLIKELY(req == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Provided null request for cleanup");
goto exit;
}
if (req->direction == NCCL_OFI_SEND) {
sComm = req->sComm;
if (OFI_UNLIKELY(sComm == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Invalid sComm provided for request of device %d\n",
sComm->dev);
goto exit;
}
/* Update free list */
if (OFI_UNLIKELY(sComm->nccl_ofi_reqs_fl == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("sComm for device %d does not have valid free list",
sComm->dev);
goto exit;
}
buffer_index = req->buffer_index;
/* Zero out buffer */
zero_nccl_ofi_req(req);
ret = stack_push(sComm->nccl_ofi_reqs_fl->free_index,
buffer_index);
if (OFI_UNLIKELY(ret != 0))
goto exit;
/* Reduce inflight commands */
if (OFI_LIKELY(dec_inflight_cmds == true))
sComm->num_inflight_reqs--;
}
else if (req->direction == NCCL_OFI_RECV) {
rComm = req->rComm;
if (OFI_UNLIKELY(rComm == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Invalid rComm provided for request of device %d",
rComm->dev);
goto exit;
}
/* Update free list */
if (OFI_UNLIKELY(rComm->nccl_ofi_reqs_fl == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("rComm for device %d does not have valid free list",
rComm->dev);
goto exit;
}
buffer_index = req->buffer_index;
/* Zero out buffer */
zero_nccl_ofi_req(req);
ret = stack_push(rComm->nccl_ofi_reqs_fl->free_index,
buffer_index);
if (OFI_UNLIKELY(ret != 0))
goto exit;
/* Reduce inflight commands */
if (OFI_LIKELY(dec_inflight_cmds == true))
rComm->num_inflight_reqs--;
}
else {
ret = ncclSystemError;
NCCL_OFI_WARN("Unexpected transaction direction. Transaction direction: %d",
req->direction);
}
exit:
return ret;
}
static int in_list(char *prov_name, char *prov_include)
{
int ret = 0;
char *name = NULL;
if (prov_include == NULL)
goto exit;
name = strtok((char *)prov_include, ",");
while (name) {
if (strcmp(prov_name, name) == 0) {
ret = 1;
goto exit;
}
name = strtok(NULL, ",");
}
exit:
return ret;
}
/*
* @brief Calls fi_getinfo() to find a list of usable providers for RDM
* tagged endpoints.
*
* @param prov_include_list
* Contains a list of preferred provider names.
*
* @return A list of fi_info structures for a single provider.
* @return 0 on success
* non-zero on error
*/
static int get_ofi_provider(char *prov_include, struct fi_info **prov_info_list)
{
int ret = ncclSuccess, idx = 0, prov_idx;
struct fi_info *hints, *providers, *prov;
struct fi_info *prov_info_vec[MAX_PROV_INFO] = {NULL};
char *prov_name;
hints = fi_allocinfo();
if (OFI_UNLIKELY(hints == NULL)) {
NCCL_OFI_WARN("Unable to allocate fi_info");
ret = ncclSystemError;
goto exit;
}
/* Hints to filter providers */
hints->caps = FI_TAGGED | FI_MSG | FI_SOURCE;
hints->mode = FI_CONTEXT;
hints->ep_attr->type = FI_EP_RDM;
hints->domain_attr->av_type = FI_AV_TABLE;
hints->domain_attr->control_progress = FI_PROGRESS_AUTO;
hints->domain_attr->data_progress = FI_PROGRESS_AUTO;
hints->tx_attr->msg_order = FI_ORDER_SAS;
hints->rx_attr->msg_order = FI_ORDER_SAS;
ret = fi_getinfo(ofi_version, NULL, NULL, 0ULL, hints, &providers);
if (ret == -FI_ENODATA) {
NCCL_OFI_WARN("Could not find any optimal provider");
ret = ncclSystemError;
goto error;
}
else if (ret != 0) {
NCCL_OFI_WARN("OFI call failed with RC %d, %s", ret,
fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
fi_freeinfo(hints);
/*
* Create an array of providers where each index represents
* a info structure list for a single provider name.
*/
prov_info_vec[idx] = providers;
prov = providers;
prov_name = prov->fabric_attr->prov_name;
while (prov != NULL && prov->next != NULL) {
char *name = prov->next->fabric_attr->prov_name;
if (strcmp(prov_name, name) != 0) {
prov_name = name;
prov_info_vec[++idx] = prov->next;
prov->next = NULL;
prov = prov_info_vec[idx];
}
else {
prov = prov->next;
}
}
if (prov_include == NULL)
*prov_info_list = prov_info_vec[0];
else {
for (prov_idx = 0; prov_idx < idx; prov_idx++) {
prov_name = prov_info_vec[idx]->fabric_attr->prov_name;
if (in_list(prov_name, prov_include)) {
*prov_info_list = prov_info_vec[idx];
break;
}
}
}
return ret;
error:
if (hints)
fi_freeinfo(hints);
if (providers)
fi_freeinfo(providers);
exit:
return ret;
}
/*
* @brief Returns provider info structure for the given NIC ID.
*/
static struct fi_info *get_nic_info(int dev, struct fi_info *nic_info_list)
{
int dev_idx = 0;
struct fi_info *nic_info = NULL;
nic_info = nic_info_list;
while ((nic_info != NULL) && (dev_idx < dev)) {
dev_idx++;
nic_info = nic_info->next;
}
return nic_info;
}
/*
* @brief Allocates and initialises various libfabric resources like
* fabric, domain, endpoint, CQ and AV.
*
* @return Initialised nccl_ofi_comp structure
*/
static ncclResult_t create_nccl_ofi_component(struct fi_info *prov,
nccl_ofi_t *nccl_ofi_comp)
{
ncclResult_t ret = ncclSuccess;
struct fi_cq_attr cq_attr = {0};
struct fi_av_attr av_attr = {0};
int ofi_tag_leading_zeroes = 0, ofi_tag_bits_for_ring_id = 64;
/* Determine if any tag bits are used by provider */
while (!((prov->ep_attr->mem_tag_format << ofi_tag_leading_zeroes++) &
(uint64_t) OFI_HIGHEST_TAG_BIT) &&
(ofi_tag_bits_for_ring_id >= MIN_TAG_BITS_FOR_RING_ID)) {
ofi_tag_bits_for_ring_id--;
}
if (OFI_UNLIKELY(ofi_tag_bits_for_ring_id < MIN_TAG_BITS_FOR_RING_ID)) {
NCCL_OFI_WARN("Provider %s does not provide enough tag bits %d for ring ID. Minimum required is %d",
prov->fabric_attr->prov_name,
ofi_tag_bits_for_ring_id,
MIN_TAG_BITS_FOR_RING_ID);
ret = ncclSystemError;
goto exit;
}
/* Set maximum tag information; Reserving 1 bit for control information */
nccl_ofi_comp->max_tag = (uint64_t)((1ULL <<
(ofi_tag_bits_for_ring_id - 1)) - 1);
/* Create fabric */
ret = fi_fabric(prov->fabric_attr, &(nccl_ofi_comp->fabric), NULL);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Couldn't open a fabric provider. RC: %d, ERROR: %s",
ret, fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
/* Create domain */
ret = fi_domain(nccl_ofi_comp->fabric, prov,
&(nccl_ofi_comp->domain), NULL);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Couldn't open a fabric access domain. RC: %d, ERROR: %s",
ret, fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
/* Create transport level communication endpoint(s) */
ret = fi_endpoint(nccl_ofi_comp->domain, prov, &(nccl_ofi_comp->ep), NULL);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Couldn't allocate endpoint. RC: %d, ERROR: %s",
ret, fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
cq_attr.format = FI_CQ_FORMAT_TAGGED;
ret = fi_cq_open(nccl_ofi_comp->domain, &cq_attr, &nccl_ofi_comp->cq, NULL);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Couldn't open CQ. RC: %d, ERROR: %s",
ret, fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
av_attr.type = FI_AV_TABLE;
ret = fi_av_open(nccl_ofi_comp->domain, &av_attr, &nccl_ofi_comp->av, NULL);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Couldn't open AV. RC: %d, ERROR: %s",
ret, fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
/* Bind CQ and AV to endpoint */
ret = fi_ep_bind(nccl_ofi_comp->ep, (fid_t)nccl_ofi_comp->cq, FI_SEND | FI_RECV);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Couldn't bind EP-CQ. RC: %d, ERROR: %s",
ret, fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
ret = fi_ep_bind(nccl_ofi_comp->ep, (fid_t)nccl_ofi_comp->av, 0);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Couldn't bind EP-CQ. RC: %d, ERROR: %s",
ret, fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
/* Enable endpoint for communication */
ret = fi_enable(nccl_ofi_comp->ep);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Couldn't enable endpoint. RC: %d, ERROR: %s",
ret, fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
return ret;
error:
if (nccl_ofi_comp->domain)
fi_close((fid_t)nccl_ofi_comp->domain);
if (nccl_ofi_comp->fabric)
fi_close((fid_t)nccl_ofi_comp->fabric);
if (nccl_ofi_comp->ep)
fi_close((fid_t)nccl_ofi_comp->ep);
if (nccl_ofi_comp->av)
fi_close((fid_t)nccl_ofi_comp->av);
if (nccl_ofi_comp->cq)
fi_close((fid_t)nccl_ofi_comp->cq);
exit:
return ret;
}
/*
* @brief Allocate and initialize nccl_ofi_component for the given NIC ID
*/
static ncclResult_t create_nccl_ofi_comp_for_dev(int dev, struct fi_info *nic_info_list)
{
ncclResult_t ret = ncclSuccess;
struct fi_info *prov = NULL;
prov = get_nic_info(dev, nic_info_list);
if (prov == NULL) {
ret = ncclSystemError;
NCCL_OFI_WARN("Could not extract provider information for given NIC ID %d",
dev);
goto exit;
}
nccl_ofi_component[dev] = (nccl_ofi_t *)calloc(1, sizeof(nccl_ofi_t));
if (OFI_UNLIKELY(nccl_ofi_component[dev] == NULL)) {
ret = ncclSystemError;
goto exit;
}
/* Initialise tag and num_cqes */
nccl_ofi_component[dev]->tag = 1;
nccl_ofi_component[dev]->num_cqes = NCCL_OFI_MAX_REQUESTS;
nccl_ofi_component[dev]->prov_name = prov->fabric_attr->prov_name;
ret = create_nccl_ofi_component(prov, nccl_ofi_component[dev]);
if (ret != 0)
goto exit;
return ret;
exit:
if (nccl_ofi_component[dev] != NULL)
free(nccl_ofi_component[dev]);
return ret;
}
/*
* @brief Processes completion entries from CQ
*
* @return 0, on success
* error, on others
*/
static inline ncclResult_t process_completions(
struct fi_cq_tagged_entry *cq_entry,
fi_addr_t *src_addrs,
uint64_t num_cqes, uint64_t control_bit_mask)
{
ncclResult_t ret = ncclSuccess;
nccl_ofi_req_t *req = NULL;
uint64_t comp_idx = 0, comp_flags = 0;
for (comp_idx = 0; comp_idx < num_cqes; comp_idx++) {
comp_flags = cq_entry[comp_idx].flags;
req = container_of(cq_entry[comp_idx].op_context,
nccl_ofi_req_t, ctx);
if (OFI_UNLIKELY(req == NULL)) {
NCCL_OFI_WARN("Invalid request context provided");
ret = ncclSystemError;
goto exit;
}
req->state = NCCL_OFI_REQ_COMPLETED;
req->size = cq_entry[comp_idx].len;
/* Identify receive using completion flags */
if (comp_flags & FI_RECV) {
/* Determine if this is control message */
if (cq_entry[comp_idx].tag & control_bit_mask) {
/* Mark listenComm to accepted state */
req->lComm->accepted = true;
/* Retrieve source information */
if (OFI_UNLIKELY(src_addrs[comp_idx]) ==
FI_ADDR_NOTAVAIL) {
NCCL_OFI_TRACE(NCCL_INIT | NCCL_NET,
"Source address for device %d and ring %ld is not set",
req->dev,
cq_entry[comp_idx].tag &
~(control_bit_mask));
}
req->src_addr = src_addrs[comp_idx];
}
}
}
exit:
return ret;
}
/*
* @brief Process completion entries for the given NCCL OFI component.
* This also updates several request fileds like size, status, etc
*
* @return 0, on success
* error, on others
*/
static ncclResult_t ofi_process_cq(nccl_ofi_t *nccl_ofi_comp)
{
ssize_t rc = 0;
ncclResult_t ret = ncclSuccess;
struct fi_cq_err_entry err_buffer = { 0 };
uint64_t cqe_burst = nccl_ofi_comp->num_cqes;
struct fi_cq_tagged_entry cqe_tagged_buffers[cqe_burst];
fi_addr_t src_addrs[cqe_burst];
nccl_ofi_req_t *req = NULL;
struct fid_cq *cq = nccl_ofi_comp->cq;
uint64_t control_bit_mask = ~(nccl_ofi_comp->max_tag);
while (true) {
/* Zero-out buffers */
memset(&cqe_tagged_buffers, 0, sizeof(cqe_tagged_buffers));
memset(&src_addrs, 0, sizeof(src_addrs));
/* Receive completions for the given endpoint */
rc = fi_cq_readfrom(cq,
&cqe_tagged_buffers[0],
cqe_burst,
&src_addrs[0]);
if (rc > 0) {
ret = process_completions(
&cqe_tagged_buffers[0],
&src_addrs[0], rc,
control_bit_mask);
if (OFI_UNLIKELY(ret != 0))
goto exit;
}
else if (OFI_UNLIKELY(rc == -FI_EAVAIL)) {
rc = fi_cq_readerr(cq, &err_buffer, 0);
if (OFI_UNLIKELY(rc < 0)) {
NCCL_OFI_WARN("Unable to read from fi_cq_readerr. RC: %zd. Error: %s",
rc,
fi_cq_strerror(cq,
err_buffer.prov_errno,
err_buffer.err_data, NULL, 0));
ret = ncclSystemError;
goto exit;
}
/* TODO: Add debug log to dump failed request details */
req = container_of(err_buffer.op_context,
nccl_ofi_req_t, ctx);
req->state = NCCL_OFI_REQ_ERROR;
req->size = err_buffer.len;
}
else if (rc == -FI_EAGAIN) {
/* No completions to process */
break;
}
else {
NCCL_OFI_WARN("Unable to retrieve completion queue entries. RC: %zd, ERROR: %s",
rc, fi_strerror(-ret));
ret = ncclSystemError;
goto exit;
}
}
exit:
return ret;
}
static inline ncclResult_t nccl_ofi_progress(nccl_ofi_t *nccl_ofi_comp)
{
ncclResult_t ret = ncclSuccess;
/* Read completion queue entries */
ret = ofi_process_cq(nccl_ofi_comp);
if (OFI_UNLIKELY(ret != 0))
goto exit;
exit:
return ret;
}
static ncclResult_t ofi_init(ncclDebugLogger_t logFunction)
{
ncclResult_t ret = ncclSuccess;
char *prov_include = NULL;
int idx;
ofi_log_function = logFunction;
/* Get list of NICs fi_info structures for a single provider */
ret = get_ofi_provider(prov_include, &ofi_info_list);
if (ret != 0 || ofi_info_list == NULL) {
ret = ncclSystemError;
goto exit;
}
/*
* TODO: Find way to identify unique structures and remove lo.
* For P3 platform, topology is known. Therefore, we return
* the first NIC.
*/
ofi_ndevices = 1;
ofi_info_list->next = NULL;
NCCL_OFI_INFO(NCCL_INIT | NCCL_NET, "Selected Provider is %s",
ofi_info_list->fabric_attr->prov_name);
/*
* Allocate NCCL OFI component array. Individual components are
* allocated as we use them.
*/
nccl_ofi_component =
(nccl_ofi_t **)malloc(sizeof(nccl_ofi_t *) * ofi_ndevices);
if (OFI_UNLIKELY(nccl_ofi_component == NULL)) {
NCCL_OFI_WARN("Unable to allocate nccl_ofi_component");
ret = ncclSystemError;
goto exit;
}
for (idx = 0; idx < ofi_ndevices; idx++) {
nccl_ofi_component[idx] = NULL;
}
exit:
return ret;
}
static ncclResult_t ofi_devices(int *ndev)
{
*ndev = ofi_ndevices;
return ncclSuccess;
}
static ncclResult_t ofi_pciPath(int dev, char** path)
{
ncclResult_t ret = ncclSuccess;
struct fi_info* prov = NULL;
struct fid_nic *nic_info = NULL;
struct fi_pci_attr *pci = NULL;
char device_path[] = "/sys/class/pci_bus/0000:00/../../0000:00:00.0";
prov = get_nic_info(dev, ofi_info_list);
if (prov == NULL) {
NCCL_OFI_INFO(NCCL_INIT | NCCL_NET,
"Unable to find provider for dev %d", dev);
ret = ncclSystemError;
goto exit;
}
nic_info = (struct fid_nic *)prov->nic;
if (nic_info == NULL) {
NCCL_OFI_INFO(NCCL_INIT | NCCL_NET,
"No NIC info for dev %d", dev);
ret = ncclSystemError;
goto exit;
}
if (nic_info->bus_attr->bus_type != FI_BUS_PCI) {
NCCL_OFI_INFO(NCCL_INIT | NCCL_NET,
"Invalid type of PCI bus returned %d",
nic_info->bus_attr->bus_type);
ret = ncclSystemError;
goto exit;
}
pci = &nic_info->bus_attr->attr.pci;
sprintf(device_path,
"/sys/class/pci_bus/%04x:%02x/../../%04x:%02x:%02x.%01x",
pci->domain_id, pci->bus_id,
pci->domain_id, pci->bus_id, pci->device_id, pci->function_id);
*path = realpath(device_path, NULL);
if (*path == NULL) {
NCCL_OFI_WARN("pciPath: Could not find real path of %s",
device_path);
ret = ncclSystemError;
}
exit:
return ret;
}
static ncclResult_t ofi_ptrSupport(int dev, int *supportedTypes)
{
*supportedTypes = NCCL_PTR_HOST;
return ncclSuccess;
}
static ncclResult_t ofi_listen(int dev, void *handle, void **listenComm)
{
ncclResult_t ret = ncclSuccess;
char ep_name[MAX_EP_ADDR] = {0};
size_t namelen = sizeof(ep_name);
listenComm_t *lComm = NULL;
uint64_t tag;
if (OFI_UNLIKELY(dev < 0 || dev >= ofi_ndevices)) {
NCCL_OFI_WARN("Incorrect device ID %d provided. Correct values are from 0 to %d",
dev, ofi_ndevices - 1);
ret = ncclSystemError;
goto exit;
}
if (OFI_UNLIKELY(nccl_ofi_component == NULL)) {
NCCL_OFI_WARN("NCCL OFI component is not initialised.");
ret = ncclSystemError;
goto error;
}
/*
* Create libfabric components for the given NIC, if not
* already created, else increase tag ID.
*/
pthread_mutex_lock(&nccl_ofi_lock);
if (OFI_UNLIKELY(nccl_ofi_component[dev] == NULL)) {
ret = create_nccl_ofi_comp_for_dev(dev, ofi_info_list);
if (ret != 0)
goto unlock;
}
else {
nccl_ofi_component[dev]->tag++;
if (nccl_ofi_component[dev]->tag ==
nccl_ofi_component[dev]->max_tag) {
NCCL_OFI_WARN("Cannot open more connection for the device ID %d. Maximum is %ld",
dev, nccl_ofi_component[dev]->max_tag);
ret = ncclSystemError;
goto unlock;
}
}
tag = nccl_ofi_component[dev]->tag;
pthread_mutex_unlock(&nccl_ofi_lock);
/* Build handle */
ret = fi_getname(&(nccl_ofi_component[dev]->ep->fid), (void *)&ep_name,
&namelen);
if (ret != 0) {
NCCL_OFI_WARN("Call to fi_getname() failed with RC: %d, ERROR: %s",
ret, fi_strerror(-ret));
ret = ncclSystemError;
goto error;
}
memcpy(handle, ep_name, MAX_EP_ADDR);
memcpy(handle + MAX_EP_ADDR, &tag, sizeof(tag));
/* Build listenComm */
lComm = (listenComm_t *)calloc(1, sizeof(listenComm_t));
lComm->tag = tag;
lComm->local_ep = nccl_ofi_component[dev]->ep;
lComm->accepted = false;
lComm->dev = dev;
*listenComm = lComm;
goto exit;
unlock:
pthread_mutex_unlock(&nccl_ofi_lock);
error:
if (lComm)
free(lComm);
exit:
return ret;
}
static ncclResult_t ofi_connect(int dev, void *handle, void **sendComm)
{
ncclResult_t ret = ncclSuccess;
ssize_t rc = 0;
uint64_t tag = 0ULL;
char remote_ep_addr[MAX_EP_ADDR] = {0};
fi_addr_t remote_addr;
sendComm_t *sComm = NULL;
uint64_t max_tag = 0;
size_t req_size = sizeof(nccl_ofi_req_t);
if (OFI_UNLIKELY(dev < 0 || dev >= ofi_ndevices)) {
NCCL_OFI_WARN("Incorrect device ID %d provided. Correct values are from 0 to %d",
dev, ofi_ndevices - 1);
ret = ncclSystemError;
goto exit;
}
if (OFI_UNLIKELY(nccl_ofi_component == NULL)) {
NCCL_OFI_WARN("NCCL OFI component is not initialised.");
ret = ncclSystemError;
goto exit;
}
/*
* Create libfabric components for the given NIC, if not
* already created.
*/
pthread_mutex_lock(&nccl_ofi_lock);
if (OFI_UNLIKELY(nccl_ofi_component[dev] == NULL)) {
ret = create_nccl_ofi_comp_for_dev(dev, ofi_info_list);
if (ret != 0)
goto unlock;
}
pthread_mutex_unlock(&nccl_ofi_lock);
max_tag = nccl_ofi_component[dev]->max_tag;
/* Parse handle to get tag and remote name */
memcpy(&remote_ep_addr, (char *)handle, MAX_EP_ADDR);
memcpy(&tag, (char *)handle + MAX_EP_ADDR, sizeof(tag));
if (tag < 1 || tag > max_tag) {
NCCL_OFI_WARN("Received an invalid tag %lu for device %d", tag,
dev);
goto exit;
}
/* Insert remote address into AV */
ret = fi_av_insert(nccl_ofi_component[dev]->av,
(void *)remote_ep_addr, 1,
&remote_addr, 0, NULL);
if (OFI_UNLIKELY(ret != 1)) {
NCCL_OFI_WARN("Unable to insert remote address into address vector for device %d. RC: %d",
dev, ret);
ret = ncclSystemError;
goto exit;
}
/* Build sendComm */
sComm = (sendComm_t *)calloc(1, sizeof(sendComm_t));
if (OFI_UNLIKELY(sComm == NULL)) {
NCCL_OFI_WARN("Couldn't allocate sendComm for dev %d", dev);
ret = ncclSystemError;
goto error;
}
sComm->tag = tag;
sComm->local_ep = nccl_ofi_component[dev]->ep;
sComm->remote_ep = remote_addr;
sComm->dev = dev;
/* Pre-allocated buffers for data path */
ret = allocate_ofi_fl(&sComm->nccl_ofi_reqs_fl, NCCL_OFI_MAX_REQUESTS,
req_size);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Could not allocate NCCL OFI requests free list for dev %d",
dev);
goto error;
}
/* Send "connect" message to remote EP */
do {
req = allocate_nccl_ofi_request(sComm->nccl_ofi_reqs_fl);
if (OFI_UNLIKELY(req == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Unable to get NCCL OFI request for device %d",
sComm->dev);
goto error;
}
rc = fi_tsend(sComm->local_ep, NULL, 0, NULL, sComm->remote_ep,
sComm->tag | ~max_tag, &req->ctx);
if (rc == 0)
break;
else if (rc == -FI_EAGAIN) {
/*
* Process completions so that you have enough
* resources for sending connect message
*/
ret = nccl_ofi_progress(nccl_ofi_component[dev]);
if (OFI_UNLIKELY(ret != 0))
goto error;
}
else {
NCCL_OFI_WARN("Unable to send connect message for dev %d. RC: %zd, ERROR: %s",
dev, rc, fi_strerror(-rc));
ret = ncclSystemError;
goto error;
}
} while (true);
*sendComm = sComm;
goto exit;
unlock:
pthread_mutex_unlock(&nccl_ofi_lock);
error:
if (sComm)
free(sComm);
exit:
return ret;
}
static ncclResult_t ofi_accept(void *listenComm, void **recvComm)
{
ncclResult_t ret = ncclSuccess;
ssize_t rc = 0;
recvComm_t *rComm = NULL;
listenComm_t *lComm = (listenComm_t *)listenComm;
int dev = lComm->dev;
nccl_ofi_t *nccl_ofi_comp = nccl_ofi_component[dev];
nccl_ofi_req_t *req = NULL;
uint64_t max_tag = nccl_ofi_comp->max_tag;
size_t req_size = sizeof(nccl_ofi_req_t);
if (nccl_ofi_comp == NULL) {
ret = ncclSystemError;
NCCL_OFI_WARN("NCCL OFI component for dev %d is uninitialised",
dev);
goto exit;
}
if (lComm->accepted == true) {
ret = ncclSystemError;
NCCL_OFI_WARN("listenComm object already has an active connection.");
goto exit;
}
/* Allocate a NCCL OFI request */
req = (nccl_ofi_req_t *)calloc(1, sizeof(nccl_ofi_req_t));
if (OFI_UNLIKELY(req == NULL)) {
NCCL_OFI_WARN("Unable to allocate nccl_ofi_req_t");
ret = ncclSystemError;
goto exit;
}
req->state = NCCL_OFI_REQ_CREATED;
if (OFI_UNLIKELY(ret != 0))
goto exit;
req->lComm = lComm;
req->dev = dev;
/* Post a buffer for receiving connection requests */
do {
rc = fi_trecv(lComm->local_ep, NULL, 0, NULL, FI_ADDR_UNSPEC,
lComm->tag | ~max_tag, 0, &req->ctx);
if (rc == 0)
break;
else if (rc == -FI_EAGAIN) {
/*
* Process completions so that you have enough
* resources for posting receive buffer
*/
ret = nccl_ofi_progress(nccl_ofi_comp);
if (OFI_UNLIKELY(ret != 0))
goto exit;
}
else {
NCCL_OFI_WARN("Unable to post a buffer for receving connections for dev %d. RC: %zd, ERROR: %s",
dev, rc, fi_strerror(-rc));
ret = ncclSystemError;
goto exit;
}
} while (true);
/* Progress NCCL_OFI until connection is accepted */
while (lComm->accepted == false) {
ret = nccl_ofi_progress(nccl_ofi_comp);
if (OFI_UNLIKELY(ret != 0))
goto exit;
}
/* Build recvComm */
rComm = (recvComm_t *)calloc(1, sizeof(recvComm_t));
if (rComm == NULL) {
NCCL_OFI_WARN("Unable to allocate receive Comm object for device %d",
dev);
ret = ncclSystemError;
goto exit;
}
rComm->tag = lComm->tag;
rComm->local_ep = lComm->local_ep;
/* This is populated while processing completion */
rComm->remote_ep = req->src_addr;
rComm->dev = dev;
/* Pre-allocated buffers for data path */
ret = allocate_ofi_fl(&rComm->nccl_ofi_reqs_fl, NCCL_OFI_MAX_REQUESTS,
req_size);
if (OFI_UNLIKELY(ret != 0)) {
NCCL_OFI_WARN("Could not allocate NCCL OFI requests free list for dev %d",
dev);
goto exit;
}
*recvComm = rComm;
goto exit;
exit:
if (req)
free(req);
return ret;
}
static ncclResult_t ofi_isend(void *sendComm, void* data, int size,
int type, void** request)
{
ncclResult_t ret = ncclSuccess;
ssize_t rc = 0;
nccl_ofi_req_t *req = NULL;
sendComm_t *sComm = (sendComm_t *)sendComm;
nccl_ofi_t *nccl_ofi_comp = NULL;
/* Validate sendComm */
if (OFI_UNLIKELY(sComm == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Invalid sendComm provided");
goto error;
}
/* Support only NCCL_OFI_MAX_REQUESTS inflight requests. */
if (OFI_UNLIKELY(sComm->num_inflight_reqs == NCCL_OFI_MAX_REQUESTS)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Can not support more than %d inflight requests",
NCCL_OFI_MAX_REQUESTS);
goto error;
}
/* Allocate NCCL OFI request */
req = allocate_nccl_ofi_request(sComm->nccl_ofi_reqs_fl);
if (OFI_UNLIKELY(req == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Unable to get NCCL OFI request for device %d",
sComm->dev);
goto error;
}
req->sComm = sComm;
req->dev = sComm->dev;
req->direction = NCCL_OFI_SEND;
nccl_ofi_comp = nccl_ofi_component[sComm->dev];
if (OFI_UNLIKELY(nccl_ofi_comp == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("NCCL OFI component for dev %d is not initialised",
sComm->dev);
goto error;
}
/* Progress NCCL OFI */
ret = nccl_ofi_progress(nccl_ofi_comp);
if (OFI_UNLIKELY(ret != 0))
goto error;
/*
* Try sending data to remote EP; Return NULL request
* if not able to send.
*/
rc = fi_tsend(sComm->local_ep, data, size, NULL,
sComm->remote_ep, sComm->tag, &req->ctx);
if (OFI_UNLIKELY(rc == -FI_EAGAIN)) {
/* Return NULL */
*request = NULL;
goto error;
}
else if (OFI_UNLIKELY(rc != 0)) {
NCCL_OFI_WARN("Could not send request for device %d. RC: %zd",
sComm->dev, rc);
ret = ncclSystemError;
goto error;
}
sComm->num_inflight_reqs++;
/* Return request to NCCL */
*request = req;
goto exit;
error:
if (req)
free_nccl_ofi_req(req, false);
exit:
return ret;
}
static ncclResult_t ofi_irecv(void* recvComm, void* data, int size, int type, void** request)
{
ncclResult_t ret = ncclSuccess;
ssize_t rc = 0;
nccl_ofi_req_t *req = NULL;
recvComm_t *rComm = (recvComm_t *)recvComm;
/* Validate recvComm */
if (OFI_UNLIKELY(rComm == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Invalid recvComm provided");
goto error;
}
/* Support only NCCL_OFI_MAX_REQUESTS inflight requests. */
if (OFI_UNLIKELY(rComm->num_inflight_reqs == NCCL_OFI_MAX_REQUESTS)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Can not support more than %d inflight requests",
NCCL_OFI_MAX_REQUESTS);
goto error;
}
/* Allocate NCCL OFI request */
req = allocate_nccl_ofi_request(rComm->nccl_ofi_reqs_fl);
if (OFI_UNLIKELY(req == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("Unable to get NCCL OFI request for device %d",
rComm->dev);
goto error;
}
/* Progress NCCL OFI */
ret = nccl_ofi_progress(nccl_ofi_component[rComm->dev]);
if (OFI_UNLIKELY(ret != 0))
goto error;
req->rComm = rComm;
req->dev = rComm->dev;
req->direction = NCCL_OFI_RECV;
/* Try posting buffer to local EP */
rc = fi_trecv(rComm->local_ep, data, size, NULL,
rComm->remote_ep, rComm->tag, 0, &req->ctx);
if (rc == -FI_EAGAIN) {
/* Return NULL request */
*request = NULL;
goto error;
}
else if (rc != 0) {
NCCL_OFI_WARN("Unable to post receive buffer for dev %d. RC: %zd, ERROR: %s",
rComm->dev, rc, fi_strerror(-rc));
ret = ncclSystemError;
goto error;
}
rComm->num_inflight_reqs++;
/* Return request to NCCL */
*request = req;
goto exit;
error:
if (req)
free_nccl_ofi_req(req, false);
exit:
return ret;
}
static ncclResult_t ofi_flush(void* recvComm, void* data, int size)
{
/* NO-OP until we support NCCL_PTR_CUDA */
return ncclSuccess;
}
static ncclResult_t ofi_test(void* request, int* done, int* size)
{
ncclResult_t ret = ncclSuccess;
/* Check if request is valid */
if (OFI_UNLIKELY(request == NULL)) {
ret = ncclSystemError;
goto exit;
}
nccl_ofi_req_t *req = (nccl_ofi_req_t *)request;
nccl_ofi_t *nccl_ofi_comp = NULL;
/* Progress NCCL OFI in order to process completions */
nccl_ofi_comp = nccl_ofi_component[req->dev];
if (OFI_UNLIKELY(nccl_ofi_comp == NULL)) {
ret = ncclSystemError;
NCCL_OFI_WARN("NCCL OFI component for dev %d is uninitialised",
req->dev);
goto exit;
}
ret = nccl_ofi_progress(nccl_ofi_comp);
if (OFI_UNLIKELY(ret != 0))
goto exit;
/* Determine whether the request has finished and free if done */
if (OFI_LIKELY(req->state == NCCL_OFI_REQ_COMPLETED ||
req->state == NCCL_OFI_REQ_ERROR)) {
if (size)
*size = req->size;
/* Mark as done */
*done = 1;
free_nccl_ofi_req(req, true);
}
else
*done = 0;
if (OFI_UNLIKELY(req->state == NCCL_OFI_REQ_ERROR))
ret = ncclSystemError;
exit:
return ret;
}
static ncclResult_t ofi_closeSend(void *sendComm)
{
ncclResult_t ret = ncclSuccess;
if (OFI_UNLIKELY(sendComm == NULL)) {
ret = ncclSystemError;
goto exit;
}
/*
* We do not want to free EP associated with the comm
* object as it my be used by other rings
*/
((sendComm_t *)sendComm)->local_ep = NULL;
free(sendComm);
exit:
return ret;
}
static ncclResult_t ofi_closeRecv(void *recvComm)
{
ncclResult_t ret = ncclSuccess;
if (OFI_UNLIKELY(recvComm == NULL)) {
ret = ncclSystemError;
goto exit;
}
/*
* We do not want to free EP associated with the comm
* object as it may be used by other rings
*/
((recvComm_t *)recvComm)->local_ep = NULL;
free(recvComm);
exit:
return ret;
}
static ncclResult_t ofi_closeListen(void *listenComm)
{
ncclResult_t ret = ncclSuccess;
if (OFI_UNLIKELY(listenComm == NULL)) {
ret = ncclSystemError;
goto exit;
}
/*
* We do not want to free EP associated with the comm
* object as it may be used by other rings
*/
((listenComm_t *)listenComm)->local_ep = NULL;
free(listenComm);
exit:
return ret;
}
const ncclNet_t NCCL_PLUGIN_SYMBOL = {
.name = "AWS Libfabric",
.init = ofi_init,
.devices = ofi_devices,
.pciPath = ofi_pciPath,
.ptrSupport = ofi_ptrSupport,
.listen = ofi_listen,
.connect = ofi_connect,
.accept = ofi_accept,
.isend = ofi_isend,
.irecv = ofi_irecv,
.flush = ofi_flush,
.test = ofi_test,
.closeSend = ofi_closeSend,
.closeRecv = ofi_closeRecv,
.closeListen = ofi_closeListen,
};
| 24.526584 | 110 | 0.681277 |
856d29fd46211185d572321f6889505948893440 | 3,764 | h | C | products/sparrow-serial-radio/serial-radio-stats.h | sics-iot/sparrow | 3ab386ccd80293928da7d5a98c2b7a9ef5fb96f9 | [
"BSD-3-Clause"
] | 26 | 2016-07-15T06:18:27.000Z | 2021-12-15T19:54:49.000Z | products/sparrow-serial-radio/serial-radio-stats.h | sics-iot/sparrow | 3ab386ccd80293928da7d5a98c2b7a9ef5fb96f9 | [
"BSD-3-Clause"
] | 34 | 2016-08-16T09:55:55.000Z | 2018-02-19T09:53:47.000Z | products/sparrow-serial-radio/serial-radio-stats.h | sics-iot/sparrow | 3ab386ccd80293928da7d5a98c2b7a9ef5fb96f9 | [
"BSD-3-Clause"
] | 16 | 2016-08-21T06:38:29.000Z | 2021-11-28T22:02:44.000Z | /*
* Copyright (c) 2014-2016, SICS, Swedish ICT AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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.
*/
/**
* \file
* Serial radio statistics
* \author
* Niclas Finne <nfi@sics.se>
* Joakim Eriksson <joakime@sics.se>
*/
#ifndef SERIAL_RADIO_STATS_H_
#define SERIAL_RADIO_STATS_H_
#include "contiki-conf.h"
enum {
SERIAL_RADIO_STATS_ENCAP_RECV,
SERIAL_RADIO_STATS_ENCAP_TLV,
SERIAL_RADIO_STATS_ENCAP_SERIAL,
SERIAL_RADIO_STATS_ENCAP_UNPROCESSED,
SERIAL_RADIO_STATS_ENCAP_ERRORS,
SERIAL_RADIO_STATS_MAX
};
extern uint32_t serial_radio_stats[];
#define SERIAL_RADIO_STATS_INC(x) do { \
uint32_t tmp_radio_stats = ntohl(serial_radio_stats[x]); \
tmp_radio_stats++; \
serial_radio_stats[x] = htonl(tmp_radio_stats); \
} while(0)
#define SERIAL_RADIO_STATS_ADD(x, y) do { \
uint32_t tmp_radio_stats = ntohl(serial_radio_stats[x]); \
tmp_radio_stats += y; \
serial_radio_stats[x] = htonl(tmp_radio_stats); \
} while(0)
#define SERIAL_RADIO_STATS_GET(x) (ntohl(serial_radio_stats[x]))
enum {
SERIAL_RADIO_STATS_DEBUG_SLIP_RECV,
SERIAL_RADIO_STATS_DEBUG_SLIP_FRAMES,
SERIAL_RADIO_STATS_DEBUG_SLIP_DROPPED,
SERIAL_RADIO_STATS_DEBUG_SLIP_OVERFLOWS,
SERIAL_RADIO_STATS_DEBUG_SLIP_ERRORS,
SERIAL_RADIO_STATS_DEBUG_MAX
};
extern uint32_t serial_radio_stats_debug[];
#define SERIAL_RADIO_STATS_DEBUG_INC(x) do { \
uint32_t tmp_radio_stats = ntohl(serial_radio_stats_debug[x]); \
tmp_radio_stats++; \
serial_radio_stats_debug[x] = htonl(tmp_radio_stats); \
} while(0)
#define SERIAL_RADIO_STATS_DEBUG_ADD(x, y) do { \
uint32_t tmp_radio_stats = ntohl(serial_radio_stats_debug[x]); \
tmp_radio_stats += y; \
serial_radio_stats_debug[x] = htonl(tmp_radio_stats); \
} while(0)
#define SERIAL_RADIO_STATS_DEBUG_GET(x) (ntohl(serial_radio_stats_debug[x]))
#endif /* SERIAL_RADIO_STATS_H_ */
| 40.913043 | 77 | 0.678533 |
8bafa650b5b0ebac1f6a6e3cac493a3686d7c7f4 | 7,262 | c | C | kernel/linux-5.4/drivers/bluetooth/hci_ag6xx.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 27 | 2021-10-04T18:56:52.000Z | 2022-03-28T08:23:06.000Z | kernel/linux-5.4/drivers/bluetooth/hci_ag6xx.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 1 | 2022-01-12T04:05:36.000Z | 2022-01-16T15:48:42.000Z | kernel/linux-5.4/drivers/bluetooth/hci_ag6xx.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | // SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Bluetooth HCI UART driver for Intel/AG6xx devices
*
* Copyright (C) 2016 Intel Corporation
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/skbuff.h>
#include <linux/firmware.h>
#include <linux/module.h>
#include <linux/tty.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include "hci_uart.h"
#include "btintel.h"
struct ag6xx_data {
struct sk_buff *rx_skb;
struct sk_buff_head txq;
};
struct pbn_entry {
__le32 addr;
__le32 plen;
__u8 data[0];
} __packed;
static int ag6xx_open(struct hci_uart *hu)
{
struct ag6xx_data *ag6xx;
BT_DBG("hu %p", hu);
ag6xx = kzalloc(sizeof(*ag6xx), GFP_KERNEL);
if (!ag6xx)
return -ENOMEM;
skb_queue_head_init(&ag6xx->txq);
hu->priv = ag6xx;
return 0;
}
static int ag6xx_close(struct hci_uart *hu)
{
struct ag6xx_data *ag6xx = hu->priv;
BT_DBG("hu %p", hu);
skb_queue_purge(&ag6xx->txq);
kfree_skb(ag6xx->rx_skb);
kfree(ag6xx);
hu->priv = NULL;
return 0;
}
static int ag6xx_flush(struct hci_uart *hu)
{
struct ag6xx_data *ag6xx = hu->priv;
BT_DBG("hu %p", hu);
skb_queue_purge(&ag6xx->txq);
return 0;
}
static struct sk_buff *ag6xx_dequeue(struct hci_uart *hu)
{
struct ag6xx_data *ag6xx = hu->priv;
struct sk_buff *skb;
skb = skb_dequeue(&ag6xx->txq);
if (!skb)
return skb;
/* Prepend skb with frame type */
memcpy(skb_push(skb, 1), &bt_cb(skb)->pkt_type, 1);
return skb;
}
static int ag6xx_enqueue(struct hci_uart *hu, struct sk_buff *skb)
{
struct ag6xx_data *ag6xx = hu->priv;
skb_queue_tail(&ag6xx->txq, skb);
return 0;
}
static const struct h4_recv_pkt ag6xx_recv_pkts[] = {
{ H4_RECV_ACL, .recv = hci_recv_frame },
{ H4_RECV_SCO, .recv = hci_recv_frame },
{ H4_RECV_EVENT, .recv = hci_recv_frame },
};
static int ag6xx_recv(struct hci_uart *hu, const void *data, int count)
{
struct ag6xx_data *ag6xx = hu->priv;
if (!test_bit(HCI_UART_REGISTERED, &hu->flags))
return -EUNATCH;
ag6xx->rx_skb = h4_recv_buf(hu->hdev, ag6xx->rx_skb, data, count,
ag6xx_recv_pkts,
ARRAY_SIZE(ag6xx_recv_pkts));
if (IS_ERR(ag6xx->rx_skb)) {
int err = PTR_ERR(ag6xx->rx_skb);
bt_dev_err(hu->hdev, "Frame reassembly failed (%d)", err);
ag6xx->rx_skb = NULL;
return err;
}
return count;
}
static int intel_mem_write(struct hci_dev *hdev, u32 addr, u32 plen,
const void *data)
{
/* Can write a maximum of 247 bytes per HCI command.
* HCI cmd Header (3), Intel mem write header (6), data (247).
*/
while (plen > 0) {
struct sk_buff *skb;
u8 cmd_param[253], fragment_len = (plen > 247) ? 247 : plen;
__le32 leaddr = cpu_to_le32(addr);
memcpy(cmd_param, &leaddr, 4);
cmd_param[4] = 0;
cmd_param[5] = fragment_len;
memcpy(cmd_param + 6, data, fragment_len);
skb = __hci_cmd_sync(hdev, 0xfc8e, fragment_len + 6, cmd_param,
HCI_INIT_TIMEOUT);
if (IS_ERR(skb))
return PTR_ERR(skb);
kfree_skb(skb);
plen -= fragment_len;
data += fragment_len;
addr += fragment_len;
}
return 0;
}
static int ag6xx_setup(struct hci_uart *hu)
{
struct hci_dev *hdev = hu->hdev;
struct sk_buff *skb;
struct intel_version ver;
const struct firmware *fw;
const u8 *fw_ptr;
char fwname[64];
bool patched = false;
int err;
hu->hdev->set_diag = btintel_set_diag;
hu->hdev->set_bdaddr = btintel_set_bdaddr;
err = btintel_enter_mfg(hdev);
if (err)
return err;
err = btintel_read_version(hdev, &ver);
if (err)
return err;
btintel_version_info(hdev, &ver);
/* The hardware platform number has a fixed value of 0x37 and
* for now only accept this single value.
*/
if (ver.hw_platform != 0x37) {
bt_dev_err(hdev, "Unsupported Intel hardware platform: 0x%X",
ver.hw_platform);
return -EINVAL;
}
/* Only the hardware variant iBT 2.1 (AG6XX) is supported by this
* firmware setup method.
*/
if (ver.hw_variant != 0x0a) {
bt_dev_err(hdev, "Unsupported Intel hardware variant: 0x%x",
ver.hw_variant);
return -EINVAL;
}
snprintf(fwname, sizeof(fwname), "intel/ibt-hw-%x.%x.bddata",
ver.hw_platform, ver.hw_variant);
err = request_firmware(&fw, fwname, &hdev->dev);
if (err < 0) {
bt_dev_err(hdev, "Failed to open Intel bddata file: %s (%d)",
fwname, err);
goto patch;
}
fw_ptr = fw->data;
bt_dev_info(hdev, "Applying bddata (%s)", fwname);
skb = __hci_cmd_sync_ev(hdev, 0xfc2f, fw->size, fw->data,
HCI_EV_CMD_STATUS, HCI_CMD_TIMEOUT);
if (IS_ERR(skb)) {
bt_dev_err(hdev, "Applying bddata failed (%ld)", PTR_ERR(skb));
release_firmware(fw);
return PTR_ERR(skb);
}
kfree_skb(skb);
release_firmware(fw);
patch:
/* If there is no applied patch, fw_patch_num is always 0x00. In other
* cases, current firmware is already patched. No need to patch it.
*/
if (ver.fw_patch_num) {
bt_dev_info(hdev, "Device is already patched. patch num: %02x",
ver.fw_patch_num);
patched = true;
goto complete;
}
snprintf(fwname, sizeof(fwname),
"intel/ibt-hw-%x.%x.%x-fw-%x.%x.%x.%x.%x.pbn",
ver.hw_platform, ver.hw_variant, ver.hw_revision,
ver.fw_variant, ver.fw_revision, ver.fw_build_num,
ver.fw_build_ww, ver.fw_build_yy);
err = request_firmware(&fw, fwname, &hdev->dev);
if (err < 0) {
bt_dev_err(hdev, "Failed to open Intel patch file: %s(%d)",
fwname, err);
goto complete;
}
fw_ptr = fw->data;
bt_dev_info(hdev, "Patching firmware file (%s)", fwname);
/* PBN patch file contains a list of binary patches to be applied on top
* of the embedded firmware. Each patch entry header contains the target
* address and patch size.
*
* Patch entry:
* | addr(le) | patch_len(le) | patch_data |
* | 4 Bytes | 4 Bytes | n Bytes |
*
* PBN file is terminated by a patch entry whose address is 0xffffffff.
*/
while (fw->size > fw_ptr - fw->data) {
struct pbn_entry *pbn = (void *)fw_ptr;
u32 addr, plen;
if (pbn->addr == 0xffffffff) {
bt_dev_info(hdev, "Patching complete");
patched = true;
break;
}
addr = le32_to_cpu(pbn->addr);
plen = le32_to_cpu(pbn->plen);
if (fw->data + fw->size <= pbn->data + plen) {
bt_dev_info(hdev, "Invalid patch len (%d)", plen);
break;
}
bt_dev_info(hdev, "Patching %td/%zu", (fw_ptr - fw->data),
fw->size);
err = intel_mem_write(hdev, addr, plen, pbn->data);
if (err) {
bt_dev_err(hdev, "Patching failed");
break;
}
fw_ptr = pbn->data + plen;
}
release_firmware(fw);
complete:
/* Exit manufacturing mode and reset */
err = btintel_exit_mfg(hdev, true, patched);
if (err)
return err;
/* Set the event mask for Intel specific vendor events. This enables
* a few extra events that are useful during general operation.
*/
btintel_set_event_mask_mfg(hdev, false);
btintel_check_bdaddr(hdev);
return 0;
}
static const struct hci_uart_proto ag6xx_proto = {
.id = HCI_UART_AG6XX,
.name = "AG6XX",
.manufacturer = 2,
.open = ag6xx_open,
.close = ag6xx_close,
.flush = ag6xx_flush,
.setup = ag6xx_setup,
.recv = ag6xx_recv,
.enqueue = ag6xx_enqueue,
.dequeue = ag6xx_dequeue,
};
int __init ag6xx_init(void)
{
return hci_uart_register_proto(&ag6xx_proto);
}
int __exit ag6xx_deinit(void)
{
return hci_uart_unregister_proto(&ag6xx_proto);
}
| 22.482972 | 73 | 0.677912 |
16a8fd59f323ce9c68dd19bc5262e01ff83e31ca | 1,061 | h | C | include/ionir/construct/operation_value.h | ionlang/ir-c | f5be3d0a6bed76b3fe354018045b82ded7d792ae | [
"Unlicense"
] | 3 | 2019-07-11T14:41:28.000Z | 2019-07-12T10:29:08.000Z | include/ionir/construct/operation_value.h | ionlang/ir-c | f5be3d0a6bed76b3fe354018045b82ded7d792ae | [
"Unlicense"
] | 22 | 2019-12-05T04:43:34.000Z | 2020-11-05T23:29:25.000Z | include/ionir/construct/operation_value.h | ionlang/ir-c | f5be3d0a6bed76b3fe354018045b82ded7d792ae | [
"Unlicense"
] | 3 | 2020-07-20T19:20:26.000Z | 2020-10-12T15:24:47.000Z | #pragma once
#include <ionir/construct/value.h>
namespace ionir {
enum struct OperatorKind {
Equal,
NotEqual,
Addition,
Subtraction,
Multiplication,
Division,
Exponent,
Modulo,
LessThan,
GreaterThan,
LessThanOrEqualTo,
GreaterThanOrEqualTo,
And,
Or,
Not
};
// TODO: Consider making template<T type>, to constrain left & right side values' types.
struct OperationValue : Value<> {
const OperatorKind operatorKind;
std::shared_ptr<Value<>> leftSideValue;
ionshared::OptPtr<Value<>> rightSideValue;
/**
* The constructor assumes that both left side and right
* side values' types are the same, since there are no
* implicit conversions done by the compiler.
*/
OperationValue(
OperatorKind operatorKind,
std::shared_ptr<Value<>> leftSideValue,
ionshared::OptPtr<Value<>> rightSideValue = std::nullopt
) noexcept;
void accept(Pass& visitor) override;
[[nodiscard]] Ast getChildrenNodes() override;
};
}
| 17.112903 | 90 | 0.656927 |
757e78b58f35fc0d1af01d4c7512c1873d5d2269 | 1,473 | c | C | 8.x/thread-2.6.6/win/threadWin.c | apnadkarni/kitgen | 3523d429733ac8c8915fc749b3af72e92b429530 | [
"MIT"
] | 19 | 2015-03-16T05:35:52.000Z | 2022-03-06T01:37:29.000Z | 8.x/thread-2.6.6/win/threadWin.c | apnadkarni/kitgen | 3523d429733ac8c8915fc749b3af72e92b429530 | [
"MIT"
] | 4 | 2015-03-13T09:27:24.000Z | 2020-07-27T13:23:38.000Z | 8.x/thread-2.6.6/win/threadWin.c | apnadkarni/kitgen | 3523d429733ac8c8915fc749b3af72e92b429530 | [
"MIT"
] | 16 | 2015-01-17T20:31:34.000Z | 2022-03-25T07:52:03.000Z | /*
* threadWin.c --
*
* Windows specific aspects for the thread extension.
*
* see http://dev.activestate.com/doc/howto/thread_model.html
*
* Some of this code is based on work done by Richard Hipp on behalf of
* Conservation Through Innovation, Limited, with their permission.
*
* Copyright (c) 1998 by Sun Microsystems, Inc.
* Copyright (c) 1999,2000 by Scriptics Corporation.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
* RCS: @(#) $Id: threadWin.c,v 1.5 2002/01/27 04:52:21 davygrvy Exp $
*/
#include "../generic/tclThread.h"
#include <windows.h>
#include <process.h>
#if 0
/* only Windows 2000 (XP, too??) has this function */
HANDLE (WINAPI *winOpenThreadProc)(DWORD, BOOL, DWORD);
void
ThreadpInit (void)
{
HMODULE hKernel = GetModuleHandle("kernel32.dll");
winOpenThreadProc = (HANDLE (WINAPI *)(DWORD, BOOL, DWORD))
GetProcAddress(hKernel, "OpenThread");
}
int
ThreadpKill (Tcl_Interp *interp, long id)
{
HANDLE hThread;
int result = TCL_OK;
if (winOpenThreadProc) {
hThread = winOpenThreadProc(THREAD_TERMINATE, FALSE, id);
/*
* not to be misunderstood as "devilishly clever",
* but evil in it's pure form.
*/
TerminateThread(hThread, 666);
} else {
Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
"Can't (yet) kill threads on this OS, sorry.", NULL);
result = TCL_ERROR;
}
return result;
}
#endif
| 25.842105 | 75 | 0.695859 |
0dab4289cac95cd18fbe203b61f97d53fca77456 | 1,424 | h | C | cpp/include/Rows/IO2GAccountRow.h | JamesKBowler/fxcpy | 1953a2e20cb68fabdbb7aa3a137eac8d932bd352 | [
"MIT"
] | 7 | 2018-11-09T07:05:15.000Z | 2021-03-25T07:21:56.000Z | cpp/include/Rows/IO2GAccountRow.h | JamesKBowler/fxcpy | 1953a2e20cb68fabdbb7aa3a137eac8d932bd352 | [
"MIT"
] | null | null | null | cpp/include/Rows/IO2GAccountRow.h | JamesKBowler/fxcpy | 1953a2e20cb68fabdbb7aa3a137eac8d932bd352 | [
"MIT"
] | 7 | 2019-01-31T03:14:29.000Z | 2022-03-12T19:22:56.000Z |
/*
!!! Caution:
Do not change anything in this source code because it was automatically generated
from XML class description
*/
#pragma once
class IO2GAccountRow : public IO2GRow
{
protected:
IO2GAccountRow();
public:
virtual const char* getAccountID() = 0;
virtual const char* getAccountName() = 0;
virtual const char* getAccountKind() = 0;
virtual double getBalance() = 0;
virtual double getNonTradeEquity() = 0;
virtual double getM2MEquity() = 0;
virtual const char* getMarginCallFlag() = 0;
virtual DATE getLastMarginCallDate() = 0;
virtual const char* getMaintenanceType() = 0;
virtual int getAmountLimit() = 0;
virtual int getBaseUnitSize() = 0;
virtual bool getMaintenanceFlag() = 0;
virtual const char* getManagerAccountID() = 0;
virtual const char* getLeverageProfileID() = 0;
virtual double getHadgeMarginPCT() = 0;
virtual const char* getATPID() = 0;
//
};
class IO2GAccountTableRow : public IO2GAccountRow
{
protected:
IO2GAccountTableRow();
public:
virtual double getUsedMargin() = 0;
virtual double getUsedMargin3() = 0;
virtual double getEquity() = 0;
virtual double getDayPL() = 0;
virtual double getUsableMargin() = 0;
virtual double getGrossPL() = 0;
virtual int getUsableMarginInPercentage() = 0;
virtual int getUsableMaintMarginInPercentage() = 0;
//
};
| 24.982456 | 85 | 0.678371 |
8da179d1e08c52308c8952d509b65185b7b809aa | 449 | h | C | Example/Pods/Headers/Public/Jasonette/JasonComponentProtocol.h | titer18/Jasonette | 55a4935ff93115c6fc4150aee760942f5a3d9ab4 | [
"MIT"
] | null | null | null | Example/Pods/Headers/Public/Jasonette/JasonComponentProtocol.h | titer18/Jasonette | 55a4935ff93115c6fc4150aee760942f5a3d9ab4 | [
"MIT"
] | null | null | null | Example/Pods/Headers/Public/Jasonette/JasonComponentProtocol.h | titer18/Jasonette | 55a4935ff93115c6fc4150aee760942f5a3d9ab4 | [
"MIT"
] | null | null | null | //
// JasonComponentProtocol.h
// Jasonette
//
// Copyright © 2016 gliechtenstein. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@protocol JasonComponentProtocol <NSObject>
+ (UIView *)build: (UIView*)component withJSON: (NSDictionary *)json withOptions: (NSDictionary *)options;
+ (void)stylize: (NSDictionary *)json component: (UIView *)el;
+ (void)stylize: (NSDictionary *)json text: (UIView *)el;
@end
| 24.944444 | 106 | 0.721604 |
8de84c8295add680d46feb2ba7c788b4858d3202 | 5,414 | c | C | HW06/OpenMP-Example/src/sphereDynamics.c | VikChawla/cmda3634_assignments | 09cd93ebb513f87fc4ab8ca8650d66ab5098e077 | [
"MIT"
] | 1 | 2018-12-03T19:55:36.000Z | 2018-12-03T19:55:36.000Z | HW06/OpenMP-Example/src/sphereDynamics.c | VikChawla/cmda3634_assignments | 09cd93ebb513f87fc4ab8ca8650d66ab5098e077 | [
"MIT"
] | null | null | null | HW06/OpenMP-Example/src/sphereDynamics.c | VikChawla/cmda3634_assignments | 09cd93ebb513f87fc4ab8ca8650d66ab5098e077 | [
"MIT"
] | 5 | 2018-08-27T17:33:44.000Z | 2018-12-06T20:29:55.000Z | #include "simpleRayTracer.h"
void sphereCollisions(const grid_t *grid,
const dfloat dt,
const dfloat g,
const int Nshapes,
shape_t *shapes){
// loop over all shapes
for(int id=0;id<Nshapes;++id){
shape_t &shape = shapes[id];
// only do something if shape is a sphere
if(shape.type==SPHERE){
// sum up all sphere-sphere interactions
// do hard reflections for collision with nearest non-sphere
shape.sphere.newVelocity = shape.sphere.velocity;
// find range of cells that overlap with sphere
const int imin = shape.bbox.imin;
const int imax = shape.bbox.imax;
const int jmin = shape.bbox.jmin;
const int jmax = shape.bbox.jmax;
const int kmin = shape.bbox.kmin;
const int kmax = shape.bbox.kmax;
int NcollisionSpheres = 0;
int collisionSphereIds[p_maxNcollisions];
int collisionShapeId = -1;
int m;
dfloat mindist = 1e9;
// loop over cells that overlap with sphere
for(int k=kmin;k<=kmax;++k){
for(int j=jmin;j<=jmax;++j){
for(int i=imin;i<=imax;++i){
const int cellID = i + grid->NI*j + grid->NI*grid->NJ*k;
const int start = grid->boxStarts[cellID];
const int end = grid->boxStarts[cellID+1];
// check for collision with objects that are contained in this cell
for(int offset=start;offset<end;++offset){
const int otherShapeId = grid->boxContents[offset];
const shape_t otherShape = shapes[otherShapeId];
// do not collide sphere with self
if(shape.id != otherShapeId){
// if other shape is sphere do Newtonian collision with old velocity
if(otherShape.type == SPHERE && NcollisionSpheres<p_maxNcollisions){
vector_t dX = vectorSub(otherShape.sphere.pos, shape.sphere.pos);
dfloat dist = vectorNorm(dX);
if(dist< shape.sphere.radius+otherShape.sphere.radius){
// use rough sphere colliding model
dfloat vdotdX1 = vectorDot( shape.sphere.velocity,dX)/(dist*dist + p_eps);
dfloat vdotdX2 = vectorDot(otherShape.sphere.velocity,dX)/(dist*dist + p_eps);
// spheres not diverging to avoid capture
if(!(vdotdX1<0 && vdotdX2>0)){
// check that this collision did not already get recorded
for(m=0;m<NcollisionSpheres;++m)
if(collisionSphereIds[m] == otherShapeId)
break;
if(m==NcollisionSpheres)
collisionSphereIds[NcollisionSpheres++] = otherShapeId;
}
}
}
else if(otherShape.type != SPHERE){
// if other shape is not a sphere then
// check if this is the nearest other object to sphere
vector_t closest;
dfloat dist = projectPointShape(shape.sphere.pos, otherShape, &closest);
if(dist<shape.sphere.radius && dist<mindist){ // find maximum penetration
collisionShapeId = otherShapeId;
mindist = dist;
}
}
}
}
}
}
}
// collide with nearest spheres
for(m=0;m<NcollisionSpheres;++m){
const int collisionSphereId = collisionSphereIds[m];
const shape_t otherShape = shapes[collisionSphereId];
vector_t dX = vectorSub(otherShape.sphere.pos, shape.sphere.pos);
dfloat dist = vectorNorm(dX);
// use rough sphere colliding model
dfloat vdotdX1 = vectorDot( shape.sphere.velocity,dX)/(dist*dist + p_eps);
dfloat vdotdX2 = vectorDot(otherShape.sphere.velocity,dX)/(dist*dist + p_eps);
// spheres not diverging to avoid capture
if(!(vdotdX1<0 && vdotdX2>0)){
dfloat dVdotdX = vdotdX2-vdotdX1;
dfloat bounceFactor = 1;
shape.sphere.newVelocity =
vectorAdd(shape.sphere.newVelocity, vectorScale(bounceFactor*dVdotdX, dX));
}
}
vector_t gforce = vectorCreate(0,g,0);
// perform collision with nearest non-sphere if any
if(collisionShapeId!=-1){
const shape_t otherShape = shapes[collisionShapeId];
// bounce back
vector_t closest;
dfloat dist = projectPointShape(shape.sphere.pos, otherShape, &closest);
if(dist<shape.sphere.radius){
vector_t disp = vectorSub(shape.sphere.pos, closest);
dfloat vdotdisp = vectorDot(shape.sphere.velocity, disp);
vector_t n = shapeComputeNormal(closest, otherShape);
if(vdotdisp<0){
dfloat vdotn = vectorDot(shape.sphere.velocity, n);
dfloat bounceFactor = 1.8; // sticky at 1, bounce at 2
shape.sphere.newVelocity =
vectorAdd(shape.sphere.newVelocity, vectorScale(-bounceFactor*vdotn, n));
}
// project out gravity when in collision state
dfloat gdotdisp = vectorDot(gforce, disp);
// if(gdotdisp<0){
{
gforce = vectorSub(gforce, vectorScale(vectorDot(n, gforce), n));
}
}
}
shape.sphere.force = gforce;
}
}
}
void sphereUpdates(grid_t *grid,
const dfloat dt,
const dfloat g,
const int Nshapes,
shape_t *shapes){
for(int id=0;id<Nshapes;++id){
shape_t &shape = shapes[id];
if(shape.type == SPHERE){
sphere_t sphere = shape.sphere;
sphere.velocity = sphere.newVelocity;
// Euler-forward update position
shape.sphere.pos = vectorAdd(sphere.pos,
vectorScale(dt, sphere.velocity));
// Euler-forward accelerate (assume gravity in y )
shape.sphere.velocity = vectorAdd(sphere.velocity,
vectorScale(dt, sphere.force));
}
}
}
| 29.911602 | 84 | 0.646287 |
e1adb3005f0dc42bc231a8f6036d9bf1ec95e161 | 1,462 | h | C | UClothLib/src/c_api/uclothinterface.h | gpiffaretti/ucloth_base | c15376a57221c974391dbab2fd19b0cebadd2b48 | [
"MIT"
] | null | null | null | UClothLib/src/c_api/uclothinterface.h | gpiffaretti/ucloth_base | c15376a57221c974391dbab2fd19b0cebadd2b48 | [
"MIT"
] | null | null | null | UClothLib/src/c_api/uclothinterface.h | gpiffaretti/ucloth_base | c15376a57221c974391dbab2fd19b0cebadd2b48 | [
"MIT"
] | null | null | null | #ifndef UCLOTH_INTERFACE_H
#define UCLOTH_INTERFACE_H
#include "uclothexport.h"
#include "uclothhandles.h"
#include "uclothstructures.h"
#include "uclothdebug.h"
extern "C"
{
UCLOTH_EXPORT void ucloth_registerDebugCallback(FuncCallBack cb);
UCLOTH_EXPORT WorldHandle ucloth_createWorld(void);
UCLOTH_EXPORT void ucloth_deleteWorld(WorldHandle world);
UCLOTH_EXPORT void ucloth_addAcceleration(WorldHandle world, UClothVector3f acceleration);
UCLOTH_EXPORT PBDSystemHandle ucloth_createPBDSimulation(void);
UCLOTH_EXPORT void ucloth_deletePBDSimulation(PBDSystemHandle pbdSimulation);
UCLOTH_EXPORT void ucloth_simulate(PBDSystemHandle simulationHandle, WorldHandle worldHandle, int solverIterations, float deltaTime);
UCLOTH_EXPORT ClothHandle ucloth_addCloth(
WorldHandle worldHandle,
UClothVector3f* positions,
size_t posSize, int* faces,
size_t facesSize,
float mass,
float elasticity,
float damping);
UCLOTH_EXPORT void ucloth_retrieveClothInfo(
ClothHandle clothHandle,
WorldHandle worldHandle,
UClothVector3f*& positions,
size_t& posSize,
int*& faces,
size_t& faces_size
);
UCLOTH_EXPORT void ucloth_attachParticleToPosition(
WorldHandle worldHandle,
ClothHandle clothHandle,
unsigned int index,
UClothVector3f position
);
}
#endif // UCLOTH_INTERFACE_H | 31.106383 | 137 | 0.736662 |
b4a9392b100413b37d1052e4f46910897db7f7e0 | 1,168 | c | C | src/c/colors.c | Spitemare/tnm | 295f257ddbf875b6f65730df96094244a0ad8777 | [
"0BSD"
] | null | null | null | src/c/colors.c | Spitemare/tnm | 295f257ddbf875b6f65730df96094244a0ad8777 | [
"0BSD"
] | null | null | null | src/c/colors.c | Spitemare/tnm | 295f257ddbf875b6f65730df96094244a0ad8777 | [
"0BSD"
] | null | null | null | #include <pebble.h>
#include <pebble-events/pebble-events.h>
#include "logging.h"
#include "enamel.h"
#include "colors.h"
static bool s_connected;
static EventHandle s_connection_event_handle;
static void connection_handler(bool connected) {
log_func();
s_connected = connected;
}
void colors_init(void) {
log_func();
s_connected = connection_service_peek_pebble_app_connection();
s_connection_event_handle = events_connection_service_subscribe((ConnectionHandlers) {
.pebble_app_connection_handler = connection_handler
});
}
void colors_deinit(void) {
log_func();
events_connection_service_unsubscribe(s_connection_event_handle);
}
GColor get_background_color(void) {
log_func();
if (!s_connected) return GColorDarkGray;
#ifdef PBL_COLOR
return enamel_get_COLOR_BACKGROUND();
#else
return enamel_get_COLOR_INVERT() ? GColorWhite : GColorBlack;
#endif
}
GColor get_foreground_color(void) {
log_func();
if (!s_connected) return GColorDarkGray;
#ifdef PBL_COLOR
return gcolor_legible_over(get_background_color());
#else
return enamel_get_COLOR_INVERT() ? GColorBlack : GColorWhite;
#endif
}
| 24.333333 | 90 | 0.760274 |
37005fb7ebaf643d5bda909e066d5d27db9707eb | 22,508 | h | C | sdk/JN-SW-4170/Components/MicroSpecific/Include/MicroSpecific_ba.h | freechw/JN5169-for-xiaomi-wireless-switch | d2b605d4727e61108e9a91d97e7993fc950b3973 | [
"BSD-3-Clause"
] | 71 | 2019-01-17T02:22:09.000Z | 2022-03-17T02:18:35.000Z | sdk/JN-SW-4170/Components/MicroSpecific/Include/MicroSpecific_ba.h | freechw/JN5169-for-xiaomi-wireless-switch | d2b605d4727e61108e9a91d97e7993fc950b3973 | [
"BSD-3-Clause"
] | 2 | 2019-02-15T05:01:30.000Z | 2019-07-09T02:27:41.000Z | sdk/JN-SW-4170/Components/MicroSpecific/Include/MicroSpecific_ba.h | freechw/JN5169-for-xiaomi-wireless-switch | d2b605d4727e61108e9a91d97e7993fc950b3973 | [
"BSD-3-Clause"
] | 19 | 2019-01-21T06:15:35.000Z | 2021-08-06T02:16:05.000Z | /*****************************************************************************
*
* MODULE: Definitions specific to a particular processor
*
* DESCRIPTION:
* Definitions for a specific processor, i.e. functions that can only be
* resolved by op codes
*
****************************************************************************
*
* This software is owned by NXP B.V. and/or its supplier and is protected
* under applicable copyright laws. All rights are reserved. We grant You,
* and any third parties, a license to use this software solely and
* exclusively on NXP products [NXP Microcontrollers such as JN5148, JN5142, JN5139].
* You, and any third parties must reproduce the copyright and warranty notice
* and any other legend of ownership on each copy or partial copy of the
* software.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Copyright NXP B.V. 2012. All rights reserved
*
***************************************************************************/
#ifndef MICRO_SPECIFIC_INCLUDED
#define MICRO_SPECIFIC_INCLUDED
#if defined __cplusplus
extern "C" {
#endif
/****************************************************************************/
/*** Include Files ***/
/****************************************************************************/
#include <jendefs.h>
extern void (*isr_handlers[])(void);
/****************************************************************************/
/*** Macro Definitions ***/
/****************************************************************************/
/** @{ Defined system call numbers */
#define SYSCALL_RESET 0
#define SYSCALL_DBG_IO 1
/** @} */
#ifdef EMBEDDED
/* Defines for ROM size (NOTE: not used anywhere!), CPU (BA1 or BA2), priority
interrupt support */
#if defined JENNIC_CHIP_JN5121
#define MICRO_ROM_SIZE 0x00010000
#define JENNIC_CPU_BA1
#elif (defined JENNIC_CHIP_JN5139) || (defined JENNIC_CHIP_JN5139R) || (defined JENNIC_CHIP_JN5139R1)
#define MICRO_ROM_SIZE 0x00030000
#define JENNIC_CPU_BA1
#elif defined JENNIC_CHIP_JN5139J01
#define MICRO_ROM_SIZE 0x00030000
#define JENNIC_CPU_BA1
#elif defined JENNIC_CHIP_JN5139T01
#define MICRO_ROM_SIZE 0x00030000
#define JENNIC_CPU_BA1
#elif defined JENNIC_CHIP_JN5147
#define MICRO_ROM_SIZE 0x00020000
#define JENNIC_CPU_BA2
#elif (defined JENNIC_CHIP_JN5142) || (defined JENNIC_CHIP_JN5142_HDK) || (defined JENNIC_CHIP_JN5142J01)
#define MICRO_ROM_SIZE 0x00020000
#define JENNIC_CPU_BA2
#define JENNIC_HW_PRIORITY_INTERRUPTS
#elif defined JENNIC_CHIP_JN5148
#define MICRO_ROM_SIZE 0x00020000
#define JENNIC_CPU_BA2
#elif (defined JENNIC_CHIP_JN5148T01) || (defined JENNIC_CHIP_JN5148T01_HDK) || (defined JENNIC_CHIP_JN5148J01) || (defined JENNIC_CHIP_JN5148Z01)
#define MICRO_ROM_SIZE 0x00020000
#define JENNIC_CPU_BA2
#define JENNIC_HW_PRIORITY_INTERRUPTS
#elif (defined JENNIC_CHIP_FAMILY_JN516x)
#define JENNIC_CPU_BA2
#define JENNIC_HW_PRIORITY_INTERRUPTS
#else
#error Chip not supported!
#endif
/* ISR and VSR table addresses. VSR is table for all exception handlers,
ISR table is for peripheral interrupts. ISR table definition is now
redundant */
#ifdef CHIP_RELEASE_1
#define MICRO_VSR_BASE 0xf0016800
#define MICRO_ISR_BASE 0xf0017008
#else
#ifdef CHIP_RELEASE_2
#define MICRO_VSR_BASE 0xf0017f80
#define MICRO_ISR_BASE 0xf001700c
#else
#ifdef CHIP_RELEASE_3
#define MICRO_VSR_BASE 0xf0017f80
#define MICRO_ISR_BASE 0xf001702c
#else
#define MICRO_VSR_BASE 0x04000000
#endif
#endif
#endif
#define MICRO_ROM_BASE 0x00000000
/* CPU defines for VSR numbers and supervisor mask bits. Values are the same
for BA1 and BA2 */
#define MICRO_VSR_NUM_TICK 5
#define MICRO_VSR_NUM_EXT 8
#define MICRO_IEE_MASK (1 << 2)
#define MICRO_TEE_MASK (1 << 1)
/* The indeces below should be used as the INT value passed to the
MICRO_SET_VSR_HANDLER macro */
#if defined JENNIC_CPU_BA1
#define MICRO_VSR_IDX_BUS_ERROR 2
#define MICRO_VSR_IDX_TICK 5
#define MICRO_VSR_IDX_UNALIGNED 6
#define MICRO_VSR_IDX_ILLEGAL_INST 7
#define MICRO_VSR_IDX_EXT_INT 8
#define MICRO_VSR_IDX_SYSCALL 12
#define MICRO_VSR_IDX_TRAP 14
#endif
#if defined JENNIC_CHIP_FAMILY_JN514x
#define MICRO_VSR_IDX_BUS_ERROR 0
#define MICRO_VSR_IDX_TICK 1
#define MICRO_VSR_IDX_UNALIGNED 2
#define MICRO_VSR_IDX_ILLEGAL_INST 3
#define MICRO_VSR_IDX_EXT_INT 4
#define MICRO_VSR_IDX_SYSCALL 5
#define MICRO_VSR_IDX_TRAP 6
#define MICRO_VSR_IDX_GENERIC 7
#define MICRO_VSR_IDX_STACK_OVER 8
#endif
/* Defines for peripheral interrupt source bits in the PIC */
#ifdef JENNIC_CPU_BA2
#if (defined JENNIC_CHIP_JN5142) || (defined JENNIC_CHIP_JN5142_HDK) || (defined JENNIC_CHIP_JN5142J01)
#define MICRO_ISR_NUM_TMR1 0
#define MICRO_ISR_NUM_TMR2 1
#define MICRO_ISR_NUM_SYSCTRL 2
#define MICRO_ISR_NUM_BBC 3
#define MICRO_ISR_NUM_AES 4
#define MICRO_ISR_NUM_PHY 5
#define MICRO_ISR_NUM_UART0 6
#define MICRO_ISR_NUM_TMR0 8
#define MICRO_ISR_NUM_I2C 10
#define MICRO_ISR_NUM_SPIM 11
#define MICRO_ISR_NUM_ANPER 13
#define MICRO_ISR_NUM_TMR3 14
#define MICRO_ISR_NUM_TICK_TMR 15
#elif (defined JENNIC_CHIP_FAMILY_JN514x) /* Rest of JN514x family */
#define MICRO_ISR_NUM_AUDIOFIFO 0
#define MICRO_ISR_NUM_I2S 1
#define MICRO_ISR_NUM_SYSCTRL 2
#define MICRO_ISR_NUM_BBC 3
#define MICRO_ISR_NUM_AES 4
#define MICRO_ISR_NUM_PHY 5
#define MICRO_ISR_NUM_UART0 6
#define MICRO_ISR_NUM_UART1 7
#define MICRO_ISR_NUM_TMR0 8
#define MICRO_ISR_NUM_TMR1 9
#define MICRO_ISR_NUM_I2C 10
#define MICRO_ISR_NUM_SPIM 11
#define MICRO_ISR_NUM_INTPER 12
#define MICRO_ISR_NUM_ANPER 13
#define MICRO_ISR_NUM_TMR2 14
#define MICRO_ISR_NUM_TICK_TMR 15
#else /* Assume JN516x */
#define MICRO_ISR_NUM_TMR1 0
#define MICRO_ISR_NUM_TMR2 1
#define MICRO_ISR_NUM_SYSCTRL 2
#define MICRO_ISR_NUM_BBC 3
#define MICRO_ISR_NUM_AES 4
#define MICRO_ISR_NUM_PHY 5
#define MICRO_ISR_NUM_UART0 6
#define MICRO_ISR_NUM_UART1 7
#define MICRO_ISR_NUM_TMR0 8
#define MICRO_ISR_NUM_SPIS 9
#define MICRO_ISR_NUM_I2C 10
#define MICRO_ISR_NUM_SPIM 11
#define MICRO_ISR_NUM_TMR4 12
#define MICRO_ISR_NUM_ANPER 13
#define MICRO_ISR_NUM_TMR3 14
#define MICRO_ISR_NUM_TICK_TMR 15
#endif
#else /* JENNIC_CPU */
/* For user VSR, tick timer is at index 0, system controller at 1, BBC at 2,
etc. for efficiency */
#define MICRO_ISR_NUM_TICK_TMR 0
#define MICRO_ISR_NUM_SYSCTRL 1
#define MICRO_ISR_NUM_BBC 2
#define MICRO_ISR_NUM_AES 3
#define MICRO_ISR_NUM_PHY 4
#define MICRO_ISR_NUM_UART0 5
#define MICRO_ISR_NUM_UART1 6
#define MICRO_ISR_NUM_TMR0 7
#define MICRO_ISR_NUM_TMR1 8
#ifdef CHIP_RELEASE_1
#define MICRO_ISR_NUM_TMR2 9
#else
#define MICRO_ISR_NUM_I2C 9
#endif
#define MICRO_ISR_NUM_SPIM 10
#define MICRO_ISR_NUM_INTPER 11
#define MICRO_ISR_NUM_ANPER 12
#endif /* JENNIC_CPU */
/* NOTE: Following are based on values above. Not all are defined for all
chips. So if an error is raised by the MICRO_ISR_MASK_* macros below, look
to see if the corresponding MICRO_ISR_NUM_* macro is defined above. If it
isn't, that peripheral is not present on the defined chip */
#define MICRO_ISR_MASK_TICK_TMR (1 << MICRO_ISR_NUM_TICK_TMR)
#define MICRO_ISR_MASK_SYSCTRL (1 << MICRO_ISR_NUM_SYSCTRL)
#define MICRO_ISR_MASK_BBC (1 << MICRO_ISR_NUM_BBC)
#define MICRO_ISR_MASK_AES (1 << MICRO_ISR_NUM_AES)
#define MICRO_ISR_MASK_PHY (1 << MICRO_ISR_NUM_PHY)
#define MICRO_ISR_MASK_UART0 (1 << MICRO_ISR_NUM_UART0)
#define MICRO_ISR_MASK_UART1 (1 << MICRO_ISR_NUM_UART1)
#define MICRO_ISR_MASK_TMR0 (1 << MICRO_ISR_NUM_TMR0)
#define MICRO_ISR_MASK_TMR1 (1 << MICRO_ISR_NUM_TMR1)
#define MICRO_ISR_MASK_TMR2 (1 << MICRO_ISR_NUM_TMR2)
#define MICRO_ISR_MASK_TMR3 (1 << MICRO_ISR_NUM_TMR3)
#define MICRO_ISR_MASK_TMR4 (1 << MICRO_ISR_NUM_TMR4)
#define MICRO_ISR_MASK_I2C (1 << MICRO_ISR_NUM_I2C)
#define MICRO_ISR_MASK_SPIM (1 << MICRO_ISR_NUM_SPIM)
#define MICRO_ISR_MASK_SPIS (1 << MICRO_ISR_NUM_SPIS)
#define MICRO_ISR_MASK_INTPER (1 << MICRO_ISR_NUM_INTPER)
#define MICRO_ISR_MASK_ANPER (1 << MICRO_ISR_NUM_ANPER)
/* Handy macros for controlling interrupts, PIC, interrupt levels */
#ifdef JENNIC_CPU_BA2
#define FF1(__input) \
({ uint32 __result; \
asm volatile ("b.ff1 %[result], %[input];" \
: [result] "=r" (__result) \
: [input] "r" (__input) \
); \
__result; })
#define MICRO_ENABLE_INTERRUPTS(); \
asm volatile ("b.ei;" : : );
#define MICRO_DISABLE_INTERRUPTS(); \
asm volatile ("b.di;" : : );
#define MICRO_DISABLE_AND_SAVE_INTERRUPTS(u32Store); \
{ \
asm volatile ("bw.mfspr %0, r0, 17;" :"=r"(u32Store) : ); \
asm volatile ("b.di;" : : ); \
}
#define MICRO_RESTORE_INTERRUPTS(u32Store); \
asm volatile ("bw.mtspr r0, %0, 17;" : :"r"(u32Store));
#ifdef JENNIC_HW_PRIORITY_INTERRUPTS
extern void vAHI_InterruptSetPriority(uint16 u16Mask, uint8 u8Level);
#define MICRO_ENABLE_TICK_TIMER_INTERRUPT(); \
vAHI_InterruptSetPriority(MICRO_ISR_MASK_TICK_TMR,8);
#define MICRO_SET_PIC_ENABLE(A); \
vAHI_InterruptSetPriority(A,8);
#define MICRO_CLEAR_PIC_ENABLE(A); \
vAHI_InterruptSetPriority(A,0);
#define MICRO_SET_PIC_PRIORITY_LEVEL(A,B); \
asm volatile ("bw.mtspr r0, %0, %1;" : : "r"(B), "i"(0x4820+(A)));
#define MICRO_GET_PIC_PRIORITY_LEVEL(A) \
({ \
register uint32 __result; \
asm volatile ("bw.mfspr %0, r0, %1;":"=r"(__result):"i"(0x4820+(A)));\
__result; \
})
#define MICRO_SET_ACTIVE_INT_LEVEL(A); \
asm volatile ("bw.mtspr r0, %0, 0x4810;" : :"r"(A));
#define MICRO_GET_ACTIVE_INT_LEVEL() \
({ \
register uint32 __result; \
asm volatile ("bw.mfspr %0, r0, 0x4810;" : "=r"(__result) :); \
__result; \
})
#else /* JENNIC_HW_PRIORITY_INTERRUPTS */
#define MICRO_ENABLE_TICK_TIMER_INTERRUPT(); \
{ \
register uint32 ruCtrlReg; \
asm volatile ("bw.mfspr %0, r0, 17;" :"=r"(ruCtrlReg) : ); \
ruCtrlReg |= 2; \
asm volatile ("bw.mtspr r0, %0, 17;" : :"r"(ruCtrlReg)); \
}
#define MICRO_SET_PIC_ENABLE(A); \
{ \
register uint32 ruCtrlReg; \
asm volatile ("bw.mfspr %0, r0, %1;" :"=r"(ruCtrlReg) : "i"(0x4800));\
ruCtrlReg |= A; \
asm volatile ("bw.mtspr r0, %0, %1;" : :"r"(ruCtrlReg), "i"(0x4800));\
}
#define MICRO_CLEAR_PIC_ENABLE(A); \
{ \
register uint32 ruCtrlReg; \
asm volatile ("bw.mfspr %0, r0, %1;" :"=r"(ruCtrlReg) : "i"(0x4800));\
ruCtrlReg &= ~(A); \
asm volatile ("bw.mtspr r0, %0, %1;" : :"r"(ruCtrlReg), "i"(0x4800));\
}
#define MICRO_CLEAR_PIC(); \
asm volatile ("bw.mtspr r0, r0, 0x4802;" : : );
#endif /* JENNIC_HW_PRIORITY_INTERRUPTS */
/** Read SPR at u32Address and return.
* \param u32Address must be a constant value.
*/
#define MICRO_READ_SPR(u32Address) \
({ register uint32 __result; \
asm volatile ("bw.mfspr %0, r0, %1;" :"=r"(__result) : "i"(u32Address)); \
__result; \
})
/** Read from SPR at offset u32Offset from u32Address and return.
* \param u32Address must be a constant value
* \param u32Offset must be a variable
*/
#define MICRO_READ_SPR_OFFSET(u32Address, u32Offset) \
({ register uint32 __result; \
asm volatile ("bw.mfspr %0, %1, %2;" :"=r"(__result) : "r"(u32Offset), "i"(u32Address)); \
__result; \
})
/** Write SPR at u32Address with u32Data.
* \param u32Address must be a constant value.
* \param u32Data must be a variable
*/
#define MICRO_WRITE_SPR(u32Address, u32Data) \
({ \
asm volatile ("bw.mtspr r0, %0, %1;" : :"r"(u32Data), "i"(u32Address)); \
})
/** Write SPR at offset u32Offset from u32Address with u32Data.
* \param u32Address must be a constant value.
* \param u32Offset must be a variable
* \param u32Data must be a variable
*/
#define MICRO_WRITE_SPR_OFFSET(u32Address, u32Offset, u32Data) \
({ \
asm volatile ("bw.mtspr %1, %0, %2;" : :"r"(u32Data), "r"(u32Offset), "i"(u32Address)); \
})
/** Generate a system call exception. Pass the system call number in R3.
* Pass further arguments as applicable in R4 - R8.
*/
void __attribute__((noinline)) vMicroSyscall(volatile uint32 u32SysCallNumber, ...);
#else /* JENNIC_CPU */
#define MICRO_ENABLE_INTERRUPTS(); \
{ \
register uint32 ruCtrlReg; \
asm volatile ("l.mfspr %0, r0, 17;" :"=r"(ruCtrlReg) : ); \
ruCtrlReg |= 4; \
asm volatile ("l.mtspr r0, %0, 17;" : :"r"(ruCtrlReg)); \
}
#define MICRO_DISABLE_AND_SAVE_INTERRUPTS(u32Store); \
{ \
register uint32 ruCtrlReg; \
asm volatile ("l.mfspr %0, r0, 17;" :"=r"(u32Store) : ); \
ruCtrlReg = u32Store & 0xfffffff9; \
asm volatile ("l.mtspr r0, %0, 17;" : :"r"(ruCtrlReg)); \
}
#define MICRO_RESTORE_INTERRUPTS(u32Store); \
asm volatile ("l.mtspr r0, %0, 17;" : :"r"(u32Store));
#define MICRO_ENABLE_TICK_TIMER_INTERRUPT(); \
{ \
register uint32 ruCtrlReg; \
asm volatile ("l.mfspr %0, r0, 17;" :"=r"(ruCtrlReg) : ); \
ruCtrlReg |= 2; \
asm volatile ("l.mtspr r0, %0, 17;" : :"r"(ruCtrlReg)); \
}
#define MICRO_SET_PIC_ENABLE(A); \
{ \
register uint32 ruCtrlReg; \
asm volatile ("l.mfspr %0, r0, %1;" :"=r"(ruCtrlReg) : "i"(0x4800));\
ruCtrlReg |= A; \
asm volatile ("l.mtspr r0, %0, %1;" : :"r"(ruCtrlReg), "i"(0x4800));\
}
#define MICRO_CLEAR_PIC_ENABLE(A); \
{ \
register uint32 ruCtrlReg; \
asm volatile ("b.mfspr %0, r0, %1;" :"=r"(ruCtrlReg) : "i"(0x4800));\
ruCtrlReg &= ~(A); \
asm volatile ("b.mtspr r0, %0, %1;" : :"r"(ruCtrlReg), "i"(0x4800));\
}
#define MICRO_CLEAR_PIC(); \
asm volatile ("l.mtspr r0, r0, 0x4802;" : : );
#endif /* JENNIC_CPU */
/* Handler registration */
#if (defined JENNIC_CHIP_FAMILY_JN514x) || (defined JENNIC_CPU_BA1)
#define MICRO_SET_INT_HANDLER(INT, FUNC); \
((void **)(*(uint32 *)0x44))[(INT)] = (void *)(FUNC);
#define MICRO_GET_INT_HANDLER(INT) \
(((void **)(*(uint32 *)0x44))[(INT)])
/* The index values MICRO_VSR_IDX_xxx defined earlier should be used as the
INT value passed to the following macro */
#define MICRO_SET_VSR_HANDLER(INT, FUNC); \
*(void **)(MICRO_VSR_BASE + ((INT) << 2)) = (void *)(FUNC);
#else
/* Location of isr_handlers is no longer at a known location, but we can link
to it directly instead */
#define MICRO_SET_INT_HANDLER(INT, FUNC); \
isr_handlers[(INT)] = (void *)(FUNC);
#define MICRO_GET_INT_HANDLER(INT) \
(isr_handlers[(INT)])
#endif
/* NOP instruction */
#define MICRO_NOP() \
{ \
asm volatile ("b.nop;"); \
}
/* TRAP instruction */
#define MICRO_TRAP() \
{ \
asm volatile("b.trap 0"); \
}
/* JUMP instruction */
#define MICRO_JUMP_TO_ADDRESS(ADDRESS) \
{ \
asm volatile ("b.jr %0;" : :"r"(ADDRESS)); \
asm volatile ("b.nop 0"); \
}
#else /* EMBEDDED */
#define MICRO_ENABLE_INTERRUPTS();
#define MICRO_DISABLE_INTERRUPTS();
#define MICRO_ENABLE_TICK_TIMER_INTERRUPT();
#define MICRO_SET_PIC_ENABLE(A);
#define MICRO_CLEAR_PIC_ENABLE(A);
#define MICRO_CLEAR_PIC();
#define MICRO_SET_INT_HANDLER(INT, FUNC);
#define MICRO_SET_VSR_HANDLER(INT, FUNC);
#endif /* EMBEDDED */
/* Nested interrupt control */
#if defined NO_NESTED_INTERRUPTS
/* Map nested interrupt support to basic macros */
#define MICRO_INT_STORAGE uint32 u32InterruptStore
#define MICRO_INT_ENABLE_ONLY(A) MICRO_DISABLE_AND_SAVE_INTERRUPTS(u32InterruptStore)
#define MICRO_INT_RESTORE_STATE() MICRO_RESTORE_INTERRUPTS(u32InterruptStore)
#else
/* Nested interrupt support */
#define MICRO_INT_STORAGE tsMicroIntStorage sIntStorage
#define MICRO_INT_ENABLE_ONLY(A) vMicroIntEnableOnly(&sIntStorage, A)
#define MICRO_INT_RESTORE_STATE() vMicroIntRestoreState(&sIntStorage)
#endif
/****************************************************************************/
/*** Type Definitions ***/
/****************************************************************************/
/* Nested interrupt control */
#if !(defined NO_NESTED_INTERRUPTS)
#if defined JENNIC_HW_PRIORITY_INTERRUPTS
typedef struct
{
uint8 u8Level;
} tsMicroIntStorage;
#else
typedef struct
{
uint32 u32Pic;
uint32 u32Sr;
} tsMicroIntStorage;
#endif
#endif
/****************************************************************************/
/*** Exported Functions ***/
/****************************************************************************/
/* Nested interrupt control */
#if !(defined NO_NESTED_INTERRUPTS)
PUBLIC void vMicroIntSetGlobalEnable(uint32 u32EnableMask);
PUBLIC void vMicroIntEnableOnly(tsMicroIntStorage *, uint32 u32EnableMask);
PUBLIC void vMicroIntRestoreState(tsMicroIntStorage *);
#endif
/****************************************************************************/
/*** Exported Variables ***/
/****************************************************************************/
#if defined __cplusplus
}
#endif
#endif /* MICRO_SPECIFIC_INCLUDED */
/****************************************************************************/
/*** END OF FILE ***/
/****************************************************************************/
| 41.375 | 146 | 0.530567 |
984362ff775d2600a55ebef27da50e69f6ed7d58 | 6,057 | c | C | Space Shooter/source/jogo/player/player.c | JulioEvencio/Space_Shooter | 51a4c4990760d8f4d497785eb0b7efb7949cecdd | [
"MIT"
] | null | null | null | Space Shooter/source/jogo/player/player.c | JulioEvencio/Space_Shooter | 51a4c4990760d8f4d497785eb0b7efb7949cecdd | [
"MIT"
] | null | null | null | Space Shooter/source/jogo/player/player.c | JulioEvencio/Space_Shooter | 51a4c4990760d8f4d497785eb0b7efb7949cecdd | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <SDL.h>
#include <SDL_image.h>
#include "../../janela/janela.h"
#include "tiro/tiro.h"
#include "player.h"
enum Enum_Player_Textura {
PLAYER_TEXTURA_1,
PLAYER_TEXTURA_2,
PLAYER_TEXTURA_EXPLOSAO_1,
PLAYER_TEXTURA_EXPLOSAO_2,
PLAYER_TEXTURA_EXPLOSAO_3,
PLAYER_TEXTURA_EXPLOSAO_4,
PLAYER_TEXTURA_EXPLOSAO_5,
PLAYER_TEXTURA_EXPLOSAO_6,
PLAYER_TEXTURA_EXPLOSAO_7,
PLAYER_TEXTURA_QUANTIDADE = 9
};
struct Movimento {
int cima;
int baixo;
int direita;
int esquerda;
int velocidade;
};
typedef struct Movimento Movimento;
struct Player {
int explodiu;
int sprite;
SDL_Rect player;
Movimento movimento;
Tiro *tiro;
SDL_Event *evento;
SDL_Renderer *tela;
SDL_Texture *textura[PLAYER_TEXTURA_QUANTIDADE];
};
int player_criar(Player **player, SDL_Renderer *tela, SDL_Event *evento) {
*player = malloc(sizeof **player);
if (*player == NULL) return PLAYER_SEM_MEMORIA;
const char *player_arquivo[PLAYER_TEXTURA_QUANTIDADE] = {
"sprites/Topview Sci-Fi Patreon Collection/player/player_0.png",
"sprites/Topview Sci-Fi Patreon Collection/player/player_1.png",
"sprites/Topview Sci-Fi Patreon Collection/explosao/explosao_1.png",
"sprites/Topview Sci-Fi Patreon Collection/explosao/explosao_2.png",
"sprites/Topview Sci-Fi Patreon Collection/explosao/explosao_3.png",
"sprites/Topview Sci-Fi Patreon Collection/explosao/explosao_4.png",
"sprites/Topview Sci-Fi Patreon Collection/explosao/explosao_5.png",
"sprites/Topview Sci-Fi Patreon Collection/explosao/explosao_6.png",
"sprites/Topview Sci-Fi Patreon Collection/explosao/explosao_7.png"
};
for (int i = 0; i < PLAYER_TEXTURA_QUANTIDADE; i++) {
SDL_Surface *imagem = IMG_Load(player_arquivo[i]);
if (imagem == NULL) {
while (i > 0) SDL_DestroyTexture((*player)->textura[--i]);
free(*player);
return PLAYER_ERRO_AO_CARREGAR_IMAGEM;
}
(*player)->textura[i] = SDL_CreateTextureFromSurface(tela, imagem);
SDL_FreeSurface(imagem);
}
if (tiro_criar(&(*player)->tiro, tela, evento)) {
for (int i = 0; i < PLAYER_TEXTURA_QUANTIDADE; i++) {
SDL_DestroyTexture((*player)->textura[i]);
}
free(*player);
return PLAYER_ERRO_AO_CARREGAR_TIRO;
}
(*player)->tela = tela;
(*player)->evento = evento;
(*player)->movimento.velocidade = 4;
player_resetar(player);
return PLAYER_SUCESSO;
}
void player_liberar(Player **player) {
tiro_liberar(&(*player)->tiro);
for (int i = 0; i < PLAYER_TEXTURA_QUANTIDADE; i++) {
SDL_DestroyTexture((*player)->textura[i]);
}
free(*player);
}
int player_logica(Player **player) {
tiro_logica(&(*player)->tiro);
SDL_RenderCopy((*player)->tela, (*player)->textura[(*player)->sprite++], NULL, &(*player)->player);
if ((*player)->explodiu) {
if ((*player)->sprite == PLAYER_TEXTURA_QUANTIDADE) return PLAYER_GAME_OVER;
} else {
if ((*player)->sprite == PLAYER_TEXTURA_EXPLOSAO_1) (*player)->sprite = PLAYER_TEXTURA_1;
if ((*player)->movimento.cima && (*player)->player.y > 0) (*player)->player.y -= (*player)->movimento.velocidade;
if ((*player)->movimento.baixo && (*player)->player.y + (*player)->player.h < JANELA_ALTURA) (*player)->player.y += (*player)->movimento.velocidade;
if ((*player)->movimento.direita && (*player)->player.x + (*player)->player.w < JANELA_LARGURA) (*player)->player.x += (*player)->movimento.velocidade;
if ((*player)->movimento.esquerda && (*player)->player.x > 0) (*player)->player.x -= (*player)->movimento.velocidade;
}
return PLAYER_CONTINUE;
}
void player_evento(Player **player) {
tiro_evento(&(*player)->tiro);
if ((*player)->evento->type == SDL_KEYDOWN) {
if ((*player)->evento->key.keysym.sym == SDLK_UP) (*player)->movimento.cima = 1;
if ((*player)->evento->key.keysym.sym == SDLK_DOWN) (*player)->movimento.baixo = 1;
if ((*player)->evento->key.keysym.sym == SDLK_RIGHT) (*player)->movimento.direita = 1;
if ((*player)->evento->key.keysym.sym == SDLK_LEFT) (*player)->movimento.esquerda = 1;
if ((*player)->evento->key.keysym.sym == SDLK_SPACE) {
/* Calculando onde eh o meio do player. O 8 eh metade da largura do tiro */
/* int x = (*player)->player.x + ((*player)->player.w / 2) - 8; */
tiro_atirar(&(*player)->tiro, (*player)->player.x + 20, (*player)->player.y);
tiro_atirar(&(*player)->tiro, (*player)->player.x + 60, (*player)->player.y);
}
}
if ((*player)->evento->type == SDL_KEYUP) {
if ((*player)->evento->key.keysym.sym == SDLK_UP) (*player)->movimento.cima = 0;
if ((*player)->evento->key.keysym.sym == SDLK_DOWN) (*player)->movimento.baixo = 0;
if ((*player)->evento->key.keysym.sym == SDLK_RIGHT) (*player)->movimento.direita = 0;
if ((*player)->evento->key.keysym.sym == SDLK_LEFT) (*player)->movimento.esquerda = 0;
}
}
SDL_Rect player_obter(Player **player) {
return (*player)->player;
}
void player_colisao(Player **player) {
(*player)->explodiu = 1;
(*player)->player.w = 160;
(*player)->player.h = 160;
}
SDL_Rect *player_obter_tiro(Player **player) {
return tiro_obter(&(*player)->tiro);
}
void player_colisao_tiro(Player **player, int i) {
tiro_colisao(&(*player)->tiro, i);
}
void player_resetar(Player **player) {
tiro_resetar(&(*player)->tiro);
(*player)->explodiu = 0;
(*player)->sprite = PLAYER_TEXTURA_1;
(*player)->player.w = 84;
(*player)->player.h = 88;
(*player)->player.x = JANELA_LARGURA / 2 - (*player)->player.w / 2;
(*player)->player.y = JANELA_ALTURA - (*player)->player.h;
(*player)->movimento.cima = 0;
(*player)->movimento.baixo = 0;
(*player)->movimento.direita = 0;
(*player)->movimento.esquerda = 0;
} | 32.047619 | 159 | 0.633152 |
895eec5c2a68a041f690c848a9b9769759245c00 | 1,324 | c | C | test/ga/test-population-get-set-gene.c | torsina/S3_C_projet | ecb20ee852eebe0a7090edf9e78572865640f6a8 | [
"MIT"
] | 2 | 2019-11-17T21:19:13.000Z | 2021-03-09T09:03:54.000Z | test/ga/test-population-get-set-gene.c | torsina/S3_C_projet | ecb20ee852eebe0a7090edf9e78572865640f6a8 | [
"MIT"
] | null | null | null | test/ga/test-population-get-set-gene.c | torsina/S3_C_projet | ecb20ee852eebe0a7090edf9e78572865640f6a8 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <assert.h>
#include "../../src/ga/includes/ga.h"
int main(void) {
ga_init();
{
const unsigned int NB_CHROMOSOMES = 10;
const unsigned int NB_INDIVIDUALS = 10;
GeneticGenerator* generator = genetic_generator_create(NB_CHROMOSOMES);
assert(generator);
assert(genetic_generator_get_size(generator) == NB_CHROMOSOMES);
for (unsigned int cardinality_index = 0; cardinality_index < NB_CHROMOSOMES;
cardinality_index++) {
assert(genetic_generator_set_cardinality(generator, cardinality_index,
cardinality_index + 1));
}
Population* population = ga_population_create(generator, NB_INDIVIDUALS);
assert(population);
for (unsigned int x = 0; x < NB_INDIVIDUALS; x++) {
for (unsigned int y = 0; y < NB_CHROMOSOMES; y++) {
unsigned int gene = ga_population_get_individual_gene(population, x, y);
assert(gene >= 0);
assert(gene < NB_CHROMOSOMES);
assert(ga_population_set_individual_gene(population, x, y, 0));
assert(ga_population_get_individual_gene(population, x, y) == 0);
}
}
ga_population_destroy(population);
genetic_generator_destroy(generator);
}
ga_finish();
return EXIT_SUCCESS;
}
| 31.52381 | 80 | 0.672205 |
54b17750ad312e4ac9e5bf40292d1dbb23d883db | 2,257 | h | C | libPdu/src/pdu_userdataheader.h | a-ilin/wwaneric | b27026313399c1075764e4ace85356d1dd2efc8a | [
"MIT"
] | 2 | 2017-03-06T23:44:30.000Z | 2017-10-02T21:49:54.000Z | libPdu/src/pdu_userdataheader.h | a-ilin/wwaneric | b27026313399c1075764e4ace85356d1dd2efc8a | [
"MIT"
] | null | null | null | libPdu/src/pdu_userdataheader.h | a-ilin/wwaneric | b27026313399c1075764e4ace85356d1dd2efc8a | [
"MIT"
] | null | null | null | /*
* pdu_userdataheader.h
* libPDU
*
* Created by James Pitts on 13/02/2005.
* Copyright 2005 James Pitts. All rights reserved.
*
*/
#ifndef _PDU_USER_DATA_HEADER
#define _PDU_USER_DATA_HEADER
#include <sys/types.h>
#include "caststring.h"
#include "common.h"
class Pdu_Packed;
/**
* Abstraction of a user data header
*/
class PDU_DECODE_API Pdu_User_Data_Header
{
unsigned int identifier_;
unsigned int length_;
protected:
Pdu_User_Data_Header ( unsigned int identifier, unsigned int length ) : identifier_ ( identifier ), length_ ( length ) {}
Pdu_User_Data_Header ( ) : identifier_(0), length_(0) {}
public:
enum
{
IEI_CONCATENATED = 0,
IEI_SPECIAL = 1,
IEI_RESERVED = 2,
IEI_LF = 3,
IEI_PORT8BIT = 4,
IEI_PORT16BIT = 5,
IEI_SMSC = 6,
IEI_UDH_SOURCE = 7,
IEI_CONCATENATED_16BIT = 8,
IEI_CONTROL = 9
};
virtual ~Pdu_User_Data_Header ( );
unsigned int getLength ( void ) const { return length_; }
unsigned int getIdentifier ( void ) const { return identifier_; }
static Pdu_User_Data_Header *create ( Pdu_Packed *packed );
virtual void decode ( Pdu_Packed *packed );
virtual void dump ( void ) const;
};
/**
* Abstraction of a concatenated message user data header
*/
class PDU_DECODE_API Pdu_Concatenated : public Pdu_User_Data_Header
{
unsigned int ref_;
unsigned int max_;
unsigned int seq_;
bool _16bit_;
Pdu_Concatenated( ) {}
public:
Pdu_Concatenated ( unsigned int identifier, unsigned int length, bool _16bit ) :
Pdu_User_Data_Header ( identifier, length ),
_16bit_(_16bit)
{}
void decode ( Pdu_Packed *packed );
void dump ( void ) const;
unsigned int getReference ( void ) const { return ref_; }
unsigned int getMax ( void ) const { return max_; }
unsigned int getSequence ( void ) const { return seq_; }
const char *getReferenceAsCStr ( void ) const { return cast_string ( ref_ ).c_str(); }
const char *getMaxAsCStr ( void ) const { return cast_string ( max_ ).c_str(); }
const char *getSequenceAsCStr ( void ) const { return cast_string ( seq_ ).c_str(); }
};
#endif
| 24.268817 | 127 | 0.652636 |
8e510eda047655748b2b9db271d5bcd62444ddcd | 2,952 | h | C | src/strategy/include/strategy/USinfo.h | TKUICLab-humanoid/US | 9c6bd9f8085e886f4ecfade7b2aaa0b5b917ad68 | [
"MIT"
] | null | null | null | src/strategy/include/strategy/USinfo.h | TKUICLab-humanoid/US | 9c6bd9f8085e886f4ecfade7b2aaa0b5b917ad68 | [
"MIT"
] | null | null | null | src/strategy/include/strategy/USinfo.h | TKUICLab-humanoid/US | 9c6bd9f8085e886f4ecfade7b2aaa0b5b917ad68 | [
"MIT"
] | null | null | null | #define TurnLeft 1
#define TurnRight 0
#define etNear 0
#define etMiddle 1
#define etClose 2
#define etFar 0
#define TraceDegreePercent 0.2
enum StrategymainState { Initial = 0, Find_Soccer, Trace_Soccer};
enum BodyActionState { SmallMove = 0, Move, BigMove, SmallLMove, LMove, SmallRMove, RMove, SmallLRotation, LRotation, BigLRotation, SmallRRotation, RRotation, BigRRotation, OneStep, Back,
Continuous, ContinuousStart, ContinuousStop, ContinuousShift, ContinuousMaxValue, ContinuousMinValue, ContinuousLMove, ContinuousRMove, ContinuousSmallLRotation, ContinuousBigLRotation, \
ContinuousSmallRRotation, ContinuousBigRRotation, ContinuousKickBallLRotation, ContinuousKickBallRRotation, ContinuousLShiftRotation, ContinuousRShiftRotation,ContinuousLRotation,\
ContinuousRRotation, ContinuousOneStep,ContinuousRStart,ContinuousLStart, ContinuousSmallRMove,ContinuousSmallLMove,ContinuousBack };
enum ContinuousValseStates {ShiftX, ShiftY, ShiftTheta};
struct Datainfo
{
int X, Y;
int XMin, XMax;
int YMin, YMax;
int Width, Height;
int size;
};
struct imnoiseSize
{
int soccer;
int goal;
int obstacle;
};
struct BodyActionValue
{
int X, Y, Z, theta, Mode, IMU;
};
class USInfo
{
public:
USInfo();
~USInfo();
public:
void Initialize_tracksoccer();
void Initialize_Obstacle();
void Initialize_Soccer();
public:
//------------IMU-------------
int IMU_Yaw_initial;
int IMU_Pitch_initial ;
//----------------tracksoccer---------------------------
bool avoidobsflag;
int HeadState;
int HeadTurnSide;
int HeadTurnSpeed;
int HeadHorizontalIni;
int HeadVerticalIni;
int HorizontalHeadPosition;
int HorizontalMaxAngle;
int HorizontalMinAngle;
int HorizontalRange;
int KickSoccerHeadVertical;
int VerticalHeadPosition;
int VerticalMaxAngle;
int VerticalMinAngle;
int VerticalRange;
int RobotVisionHeight;
int RobotVisionWidth;
int soccorcnt;
int SoccerHortionalBaseLine;
int SoccerVerticalBaseLine;
int cannotsee;
double ErrorHorizontalAngle;
double ErrorVerticalAngle;
double ImgHorizontalAngle;
double ImgVerticalAngle;
double MotorMoveOneDegree;
double SoccerMoveX;
double SoccerMoveY;
//------.ini------
bool seesoccer;
bool seeobsflag;
int HeadHorizontal;
int HeadVertical;
int upMax;
Datainfo soccer;
Datainfo obstacle;
imnoiseSize imnoisesize;
//------------------------strategymain-------------------------------
public:
ContinuousValseStates ContinuousValseState;
StrategymainState BodyStrategySelect;
bool AimGoalFlag;
bool ContinuousFlag;
bool ContinuousLRotationFlag;
bool ContinuousRRotationFlag;
int FixHead_LB_Limit;
int FixHead_RB_Limit;
int MiddleDecade;
int NearDecade;
double ContinuousTimeError;
double ContinuousTimeRatio;
double OneSteptoContinuousRatio;
double StartPositionError;
//------.ini------
BodyActionValue MoveValue[ContinuousBack];
};
extern USInfo* USinfo;
| 25.669565 | 189 | 0.747967 |
882c1280269d61741dc69153cbe007c939b645da | 39,290 | c | C | b4860/fapi_b4860_cpri_eth.c | yakovenkov/enb_l1_b4860_ppc | 9bd7512fa97481365c51af8d6a5910a6b3288c5e | [
"BSD-2-Clause-Patent"
] | null | null | null | b4860/fapi_b4860_cpri_eth.c | yakovenkov/enb_l1_b4860_ppc | 9bd7512fa97481365c51af8d6a5910a6b3288c5e | [
"BSD-2-Clause-Patent"
] | null | null | null | b4860/fapi_b4860_cpri_eth.c | yakovenkov/enb_l1_b4860_ppc | 9bd7512fa97481365c51af8d6a5910a6b3288c5e | [
"BSD-2-Clause-Patent"
] | null | null | null | /*
* Copyright (c) 2013-2021 Valentin Yakovenkov
* SPDX-License-Identifier: BSD-2-Clause-Patent
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/if.h>
#include <linux/if_tun.h>
#include <netinet/in.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <lib/core/block_queue.h>
#include <lib/core/log.h>
#include <lib/core/thread_helper.h>
#include "fapi_interface.h"
#include "libb4860/ipc/include/fsl_bsc913x_ipc.h"
#include "libb4860/ipc/include/fsl_ipc_errorcodes.h"
#include "libb4860/ipc/include/fsl_usmmgr.h"
#include "fapi.h"
#include "fapi_scheduler.h"
#include "fapi_b4860.h"
#include "fapi_b4860_cfg.h"
#include "fapi_b4860_cpri_eth.h"
/*
#define USE_3MHZ
#define USE_2T2R
*/
static int32_t initialized;
static char devname[16];
static bool running;
static int32_t tap_fd;
static int32_t cfg_fd;
static uint32_t bbu_ip;
static uint32_t rru_ip;
static uint32_t netmask;
static int32_t rru_need_reset;
static int32_t tx_pipe_write, tx_pipe_read;
static pthread_t cpri_rru_manager_h;
#define MAX_RRU_CLIENTS 10
#define RRU_INACTIVITY_TIMEOUT_SECS 10
static int32_t control_fd;
static rru_t rrus[MAX_RRU_CLIENTS];
#define POLL_FD_CFG (MAX_RRU_CLIENTS + 0)
#define POLL_FD_CONTROL (MAX_RRU_CLIENTS + 1)
#define POLL_FD_TX_READ (MAX_RRU_CLIENTS + 2)
#define POLL_FD_TAP (MAX_RRU_CLIENTS + 3)
#define MAX_POLL_FDS (MAX_RRU_CLIENTS + 4)
#define THREAD_PRIO_CPRI_ETH 60
static int cpri_eth_tun_alloc(char *dev, int flags);
static int32_t cpri_rru_manager_init(char *ifname);
static rru_t *cpri_rru_manager_find_rru_by_mac(ir_cfg_req_t *cfg_req);
static rru_t *cpri_rru_manager_add_rru_by_mac(ir_cfg_req_t *cfg_req);
static rru_t *cpri_rru_manager_find_rru_by_ip(uint32_t ip);
static void cpri_rru_manager_rrus_reconfigure();
static void cpri_rru_manager_start();
static void cpri_rru_manager_stop();
static void *cpri_rru_manager_run_thread(void *);
static void cpri_rru_manager_send_bbu_heartbeat(rru_t *rru);
static void cpri_rru_manager_send_channel_establishment_config(rru_t *rru);
static void cpri_rru_manager_send_rru_reset_req(rru_t *rru);
static void cpri_rru_manager_send_parameter_configuration(rru_t *rru);
static void cpri_rru_manager_send_cell_clear_fdd(rru_t *rru);
static void cpri_rru_manager_send_cell_configuration_fdd(rru_t *rru);
static void cpri_rru_manager_send_cell_clear_tdd(rru_t *rru);
static void cpri_rru_manager_send_cell_configuration_tdd(rru_t *rru);
static void cpri_rru_manager_send_delay_measure(rru_t *rru);
static void cpri_rru_manager_send_delay_configuration(rru_t *rru);
static void cpri_rru_manager_process_rru_message(rru_t *rru, uint8_t *buf, int32_t len);
static int32_t cpri_rru_manager_connected();
extern FAPI_B4860_CONFIG_t *g_fapi_b4860_cfg;
extern fapi_config_t g_fapi_cfg_req;
void cpri_eth_init()
{
int32_t pipefd[2];
bzero(devname, sizeof(devname));
strcpy(devname, "tap10");
tap_fd = cpri_eth_tun_alloc(devname, IFF_TAP | IFF_NO_PI);
if(tap_fd > 0)
{
initialized = 1;
if(pipe2(pipefd, O_DIRECT) != 0)
{
LOG_E(HW, "Error creating CPRI Ethernet TX pipe!\n");
return;
}
tx_pipe_read = pipefd[0];
tx_pipe_write = pipefd[1];
cpri_rru_manager_init(devname);
}
}
void cpri_eth_start()
{
cpri_rru_manager_start();
running = 1;
LOG_I(HW, "Using CPRI ethernet interface %s\n", devname);
}
void cpri_eth_stop()
{
cpri_rru_manager_stop();
}
void cpri_eth_process_cpri_msg(fapi_ipc_msg_t *msg)
{
// write(tx_pipe_write, msg, sizeof(msg));
int32_t len = msg->length - sizeof(fapi_ipc_msg_t);
if(msg->body_addr != 0 && len > 0)
{
write(tap_fd, (void *)msg->body_addr, len);
}
}
static int cpri_eth_tun_alloc(char *dev, int flags)
{
struct ifreq ifr;
int fd, err;
char *clonedev = "/dev/net/tun";
/* Arguments taken by the function:
*
* char *dev: the name of an interface (or '\0'). MUST have enough
* space to hold the interface name if '\0' is passed
* int flags: interface flags (eg, IFF_TUN etc.)
*/
/* open the clone device */
if((fd = open(clonedev, O_RDWR)) < 0)
{
return fd;
}
/* preparation of the struct ifr, of type "struct ifreq" */
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = flags; /* IFF_TUN or IFF_TAP, plus maybe IFF_NO_PI */
if(*dev)
{
/* if a device name was specified, put it in the structure; otherwise,
* the kernel will try to allocate the "next" device of the
* specified type */
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
}
/* try to create the device */
if((err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0)
{
close(fd);
return err;
}
/* if the operation was successful, write back the name of the
* interface to the variable "dev", so the caller can know
* it. Note that the caller MUST reserve space in *dev (see calling
* code below) */
strcpy(dev, ifr.ifr_name);
/* this is the special file descriptor that the caller will use to talk
* with the virtual interface */
return fd;
}
static int32_t cpri_eth_connected()
{
return cpri_rru_manager_connected();
}
static void cpri_eth_rrus_reconfigure()
{
cpri_rru_manager_rrus_reconfigure();
}
static int32_t cpri_rx_thr_send_to_cpri(void *buf, int32_t buflen)
{
return fapi_b4860_fapi_cpri_eth_send(buf, buflen);
}
static int32_t cpri_rru_manager_init(char *iface)
{
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
bbu_ip = htonl(0xc0a81f01);
rru_ip = htonl(0xc0a81f41);
netmask = htonl(0xffffff00);
int enable = 1;
// сокет для приёма
cfg_fd = socket(AF_INET, SOCK_DGRAM, 0);
if(cfg_fd < 0)
{
return -1;
}
#if defined(SO_REUSEADDR)
if(setsockopt(cfg_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
{
}
#endif
#if defined(SO_REUSEPORT)
if(setsockopt(cfg_fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(int)) < 0)
{
}
#endif
#if defined(SO_BROADCAST)
if(setsockopt(cfg_fd, SOL_SOCKET, SO_BROADCAST, &enable, sizeof(int)) < 0)
{
}
#endif
if(setsockopt(cfg_fd, SOL_SOCKET, SO_BINDTODEVICE, iface, strlen(iface) + 1) < 0)
{
return -1;
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
address.sin_port = htons(33333);
if(bind(cfg_fd, (struct sockaddr *)&address, addrlen))
{
return -1;
}
// RRU control socket tcp/30000
if((control_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
return -1;
}
if(setsockopt(control_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
{
return -1;
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(30000);
if(bind(control_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
{
return -1;
}
if(listen(control_fd, 10) < 0)
{
return -1;
}
return 0;
}
static void cpri_rru_manager_start()
{
running = 1;
pthread_create(&cpri_rru_manager_h, NULL, cpri_rru_manager_run_thread, NULL);
// thread::start(CPRI_THREAD_PRIO);
}
static void cpri_rru_manager_stop()
{
close(cfg_fd);
close(control_fd);
close(tx_pipe_read);
close(tx_pipe_write);
if(running)
{
running = 0;
pthread_cancel(cpri_rru_manager_h);
pthread_join(cpri_rru_manager_h, NULL);
}
}
static void cpri_rru_manager_rrus_reconfigure()
{
int32_t i;
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
if(rrus[i].state == RRU_STATE_READY)
{
rrus[i].state = RRU_STATE_NEED_PARAMS_CONFIG;
rrus[i].timer = 0;
}
}
}
static rru_t *cpri_rru_manager_find_rru_by_mac(ir_cfg_req_t *cfg_req)
{
int32_t i;
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
if(rrus[i].mac[0] == cfg_req->rru_mac[0] && rrus[i].mac[1] == cfg_req->rru_mac[1] &&
rrus[i].mac[2] == cfg_req->rru_mac[2] && rrus[i].mac[3] == cfg_req->rru_mac[3] &&
rrus[i].mac[4] == cfg_req->rru_mac[4] && rrus[i].mac[5] == cfg_req->rru_mac[5])
{
return &rrus[i];
}
}
return NULL;
}
static rru_t *cpri_rru_manager_find_rru_by_fd(uint32_t fd)
{
int32_t i;
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
if(rrus[i].fd == fd)
{
return &rrus[i];
}
}
return NULL;
}
static rru_t *cpri_rru_manager_find_rru_by_ip(uint32_t ip)
{
int32_t i;
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
if(rrus[i].ip == ip)
{
return &rrus[i];
}
}
return NULL;
}
static rru_t *cpri_rru_manager_add_rru_by_mac(ir_cfg_req_t *cfg_req)
{
int32_t i;
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
// if position is empty
if(rrus[i].state == RRU_STATE_NONE)
{
rrus[i].mac[0] = cfg_req->rru_mac[0];
rrus[i].mac[1] = cfg_req->rru_mac[1];
rrus[i].mac[2] = cfg_req->rru_mac[2];
rrus[i].mac[3] = cfg_req->rru_mac[3];
rrus[i].mac[4] = cfg_req->rru_mac[4];
rrus[i].mac[5] = cfg_req->rru_mac[5];
rrus[i].timeout = 0;
rrus[i].need_reset = 1;
return &rrus[i];
}
}
return NULL;
}
static void *cpri_rru_manager_run_thread(void *param)
{
struct sockaddr_in rruaddr;
socklen_t len;
uint8_t bbu_id = 0;
struct sockaddr_in address;
int addrlen = sizeof(address);
int new_socket, activity, i, fd;
uint8_t recv_buf[4096];
uint32_t rru_count = 0;
struct pollfd pollfds[MAX_POLL_FDS];
uint8_t pkt_buf[8192];
LOG_I(FAPI, "Starting B4860 CPRI RRU manager thread\n");
thread_helper_thread_top_init("l2_cpri_mgr", THREAD_PRIO_CPRI_ETH, 0, 0, 0);
// initialise all client_socket[] to 0 so not checked
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
memset(&rrus[i], 0, sizeof(rru_t));
}
for(i = 0; i < MAX_POLL_FDS; i++)
{
pollfds[i].fd = -1;
pollfds[i].events = 0;
}
rru_need_reset = 1;
while(running)
{
int32_t recv_len, send_len;
uint8_t rx_buf[128], tx_buf[128];
// Wait for RRU configuration request
memset(&rruaddr, 0, sizeof(rruaddr));
len = sizeof(rruaddr);
pollfds[POLL_FD_CONTROL].fd = control_fd;
pollfds[POLL_FD_CONTROL].events = POLLIN;
pollfds[POLL_FD_CFG].fd = cfg_fd;
pollfds[POLL_FD_CFG].events = POLLIN;
pollfds[POLL_FD_TAP].fd = tap_fd;
pollfds[POLL_FD_TAP].events = POLLIN;
// add RRU sockets to set
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
if(rrus[i].state == RRU_STATE_NONE)
{
pollfds[i].fd = -1;
continue;
}
// socket descriptor
fd = rrus[i].fd;
// if valid socket descriptor then add to read list
if(fd > 0)
{
pollfds[i].fd = fd;
pollfds[i].events = POLLIN;
}
}
/* Ожидание событий чтения на сокетах 10 секунд */
activity = poll(pollfds, MAX_POLL_FDS, 1000);
if((activity < 0) && (errno != EINTR))
{
LOG_E(HW, "CPRI manager: fd poll error");
// TODO: what to do???
continue;
}
#if 1
/* Обработка состояния PARAMS_CONFIG RRU */
if(activity == 0)
{
// Send BBU hearbeat to active RRUs
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
if(rrus[i].state == RRU_STATE_NEED_PARAMS_CONFIG)
{
if(rrus[i].timer >= 10)
{
cpri_rru_manager_send_parameter_configuration(&rrus[i]);
rrus[i].state = RRU_STATE_WAIT;
}
else
{
rrus[i].timer++;
}
}
}
}
#endif
if(activity == 0)
{
// Timeout, check active RRUs and close inactive ones
// add RRU socket to array of sockets
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
// if position is empty
if(rrus[i].state != RRU_STATE_NONE)
{
if(rrus[i].timeout++ > RRU_INACTIVITY_TIMEOUT_SECS)
{
fd = rrus[i].fd;
// RRU disconnected , get his details and print
getpeername(fd, (struct sockaddr *)&address, (socklen_t *)&addrlen);
LOG_I(HW, "RRU disconnected by timeout, ip %s, port %d \n", inet_ntoa(address.sin_addr),
ntohs(address.sin_port));
// Close the socket and mark as 0 in list for reuse
close(fd);
rrus[i].state = RRU_STATE_NONE;
rrus[i].timeout = 0;
rru_need_reset = 1;
}
}
}
// There was no activity, so loop again
continue;
}
// Обработка cfg_fd
if(pollfds[POLL_FD_CFG].revents & POLLIN)
{
recv_len = recvfrom(cfg_fd, rx_buf, sizeof(rx_buf), 0, (struct sockaddr *)&rruaddr, &len);
if(recv_len == -1)
{
}
else
{
ir_cfg_req_t *cfg_req = (ir_cfg_req_t *)rx_buf;
ir_cfg_resp_t *cfg_resp = (ir_cfg_resp_t *)tx_buf;
int32_t bbu_port = cfg_req->bbu_port;
memset(tx_buf, 0, sizeof(tx_buf));
rru_t *rru = cpri_rru_manager_find_rru_by_mac(cfg_req);
if(rru == NULL)
{
// New RRU
rru = cpri_rru_manager_add_rru_by_mac(cfg_req);
}
rru->state = RRU_STATE_INIT;
rru->timeout = 0;
rru->ip = 0;
if(bbu_port < g_fapi_b4860_cfg->rrus.list.count)
{
struct in_addr ia;
if(inet_aton(g_fapi_b4860_cfg->rrus.list.array[cfg_req->bbu_port]->ip.buf, &ia))
{
rru->ip = ia.s_addr;
rru->cfg = g_fapi_b4860_cfg->rrus.list.array[cfg_req->bbu_port];
}
}
else
{
LOG_E(HW, "Invalid BBU port received from RRU: %i\n", bbu_port);
}
if(rru->ip == 0)
{
// Базовый адрес 192.168.30.65
rru->ip = 0xc0a81e41 + (rru_count & 0xff);
// Проверка на переполнение адресов IP при прибавлении счетчика RRU к базовому адресу
rru_count++;
if(rru_count > 0xfe - 0x41)
rru_count = 0;
}
struct in_addr ia;
ia.s_addr = rru->ip;
LOG_I(HW, "Adding new RRU in chain, ip %s\n", inet_ntoa(ia));
cfg_resp->bbu_port = cfg_req->bbu_port;
cfg_resp->rru_id = cfg_req->rru_id;
cfg_resp->bbu_id = bbu_id;
bbu_id += 0x10;
cfg_resp->rru_mac[0] = cfg_req->rru_mac[0];
cfg_resp->rru_mac[1] = cfg_req->rru_mac[1];
cfg_resp->rru_mac[2] = cfg_req->rru_mac[2];
cfg_resp->rru_mac[3] = cfg_req->rru_mac[3];
cfg_resp->rru_mac[4] = cfg_req->rru_mac[4];
cfg_resp->rru_mac[5] = cfg_req->rru_mac[5];
cfg_resp->bbu_ip = bbu_ip;
cfg_resp->rru_ip = rru_ip;
cfg_resp->netmask = netmask;
cfg_resp->bbu_ip = htonl(0xc0a81e01);
cfg_resp->rru_ip = rru->ip; // htonl(0xc0a81e41);
cfg_resp->netmask = htonl(0xffffff00);
// Configuration response sent to port 33334
rruaddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
rruaddr.sin_port = htons(33334);
// Prepare RRU configuration answer
send_len = sendto(cfg_fd, (const char *)tx_buf, sizeof(ir_cfg_resp_t), 0,
(const struct sockaddr *)&rruaddr, len);
}
}
// Прием соединения на control_fd
if(pollfds[POLL_FD_CONTROL].revents & POLLIN)
{
if((new_socket = accept(control_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0)
{
// pLOG_E(HW, "accept");
// exit(EXIT_FAILURE);
}
LOG_I(HW, "New RRU, fd %d, ip %s, port %d \n", new_socket, inet_ntoa(address.sin_addr),
ntohs(address.sin_port));
rru_t *rru = cpri_rru_manager_find_rru_by_ip(address.sin_addr.s_addr);
if(rru != NULL)
{
// add RRU socket to array of sockets
// if position is empty
if(rru->state == RRU_STATE_INIT)
{
rru->fd = new_socket;
rru->state = RRU_STATE_CONNECTED;
rru->timeout = 0;
// printf("Adding to list of sockets as %d\n" , i);
// break;
}
}
}
/* Обработка TAP */
if(pollfds[POLL_FD_TAP].revents & POLLIN)
{
int32_t n_read = read(tap_fd, pkt_buf, sizeof(pkt_buf));
if(n_read < 0)
break;
cpri_rx_thr_send_to_cpri(pkt_buf, n_read);
}
// else its some IO operation on some other socket
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
if(rrus[i].state == RRU_STATE_NONE)
continue;
fd = rrus[i].fd;
if(pollfds[i].revents & POLLIN)
{
// Check if it was for closing , and also read the
// incoming message
if((recv_len = read(fd, recv_buf, 4096)) == 0)
{
// RRU disconnected , get his details and print
getpeername(fd, (struct sockaddr *)&address, (socklen_t *)&addrlen);
LOG_I(HW, "RRU disconnected, ip %s, port %d \n", inet_ntoa(address.sin_addr),
ntohs(address.sin_port));
rrus[i].state = RRU_STATE_NONE;
// Close the socket and mark as 0 in list for reuse
close(fd);
// memset(&rrus[i], 0, sizeof(rru_t));
/*
rrus[i].fd = 0;
rrus[i].state = RRU_STATE_NONE;
rrus[i].timeout = 0;
*/
}
else
{
// Process RRU message
cpri_rru_manager_process_rru_message(&rrus[i], recv_buf, recv_len);
// Reset timeout
rrus[i].timeout = 0;
/*
if(rrus[i].state == RRU_STATE_NEED_PARAMS_CONFIG)
{
send_parameter_configuration(&rrus[i]);
rrus[i].state = RRU_STATE_WAIT;
}
*/
}
}
}
}
return NULL;
}
static void cpri_rru_manager_process_channel_establishment_req(rru_t *rru, uint8_t *buf, int32_t len)
{
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
ir_ie_header_t *ie_hdr;
int32_t off;
off = sizeof(ir_msg_header_t);
rru->id = hdr->rru_id;
rru->bbu_id = hdr->bbu_id;
rru->port = hdr->port;
// First IE is after msg header
while(off < len)
{
ie_hdr = (ir_ie_header_t *)(buf + off);
// TODO: implement length checks
off += ie_hdr->ie_len;
switch(ie_hdr->ie_no)
{
case 1: {
ir_ie_1_t *ie_1 = (ir_ie_1_t *)ie_hdr;
if(ie_1->ie_len != 100)
{
LOG_E(HW, "invalid IE 1 length %i (should be 100)", ie_1->ie_len);
}
else
{
memcpy(&rru->ie_1, ie_1, sizeof(ir_ie_1_t));
LOG_I(HW, "RRU manufacturer: %s\n", rru->ie_1.rru_manufacturer);
LOG_I(HW, "RRU vendor: %s\n", rru->ie_1.rru_vendor);
LOG_I(HW, "RRU serial: %s\n", rru->ie_1.serial);
LOG_I(HW, "RRU production date: %s\n", rru->ie_1.date_prod);
if(rru->ie_1.date_service[0] != 0x00)
LOG_I(HW, "RRU last service date: %s\n", rru->ie_1.date_service);
}
}
break;
case 2:
break;
case 3:
break;
}
}
// Send channel configuration
cpri_rru_manager_send_channel_establishment_config(rru);
}
static void cpri_rru_manager_send_channel_establishment_config(rru_t *rru)
{
uint8_t buf[2048];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
int32_t off = 0;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = 2;
off += sizeof(ir_msg_header_t);
ir_ie_11_t *ie_11 = (ir_ie_11_t *)(buf + off);
ie_11->ie_no = 11;
ie_11->ie_len = sizeof(ir_ie_11_t);
ie_11->hour = tm.tm_hour;
ie_11->minute = tm.tm_min;
ie_11->second = tm.tm_sec;
ie_11->day = tm.tm_mday;
ie_11->month = tm.tm_mon + 1;
ie_11->year = tm.tm_year + 1900;
off += sizeof(ir_ie_11_t);
ir_ie_12_t *ie_12 = (ir_ie_12_t *)(buf + off);
ie_12->ie_no = 12;
ie_12->ie_len = sizeof(ir_ie_12_t);
ie_12->bbu_ftp_addr[0] = (bbu_ip & 0xff000000) >> 24;
ie_12->bbu_ftp_addr[1] = (bbu_ip & 0x00ff0000) >> 16;
ie_12->bbu_ftp_addr[2] = (bbu_ip & 0x0000ff00) >> 8;
ie_12->bbu_ftp_addr[3] = (bbu_ip & 0x000000ff) >> 0;
off += sizeof(ir_ie_12_t);
ir_ie_13_t *ie_13 = (ir_ie_13_t *)(buf + off);
ie_13->ie_no = 13;
ie_13->ie_len = sizeof(ir_ie_13_t);
ie_13->status = 0; // RRU normal operation
off += sizeof(ir_ie_13_t);
// Software version check result OK
ir_ie_14_t *ie_14 = (ir_ie_14_t *)(buf + off);
ie_14->ie_no = 14;
ie_14->ie_len = sizeof(ir_ie_14_t);
ie_14->software_type = 0;
ie_14->result = 0;
off += sizeof(ir_ie_14_t);
#if 0
// Firmware version check result OK
ie_14 = (ir_ie_14_t *)(buf + off);
ie_14->ie_no = 14;
ie_14->ie_len = sizeof(ir_ie_14_t);
ie_14->software_type = 1;
ie_14->result = 0;
off += sizeof(ir_ie_14_t);
#endif
// Ir port working mode = 1 (normal mode)
ir_ie_504_t *ie_15 = (ir_ie_504_t *)(buf + off);
ie_15->ie_no = 504;
ie_15->ie_len = sizeof(ir_ie_504_t);
ie_15->mode = 1;
off += sizeof(ir_ie_504_t);
hdr->msg_len = off;
if(send(rru->fd, buf, off, 0) != off)
{
LOG_E(HW, "Error sending channel configuration!\n");
}
rru->state = RRU_STATE_CONN_SETUP_SENT;
rru->timeout = 0;
}
static void cpri_rru_manager_process_channel_establishment_resp(rru_t *rru, uint8_t *buf, int32_t len)
{
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
ir_ie_21_t *ie_21;
int32_t off;
off = sizeof(ir_msg_header_t);
ie_21 = (ir_ie_21_t *)(buf + off);
if(ie_21->ie_no != 21)
{
LOG_E(HW, "Invalid IE %i in channel configuration response!\n", ie_21->ie_no);
return;
}
LOG_I(HW, "Channel establishment response %i\n", ie_21->result);
rru->state = RRU_STATE_CONN_SETUP_ACK;
rru->timeout = 0;
if(rru->need_reset)
{
cpri_rru_manager_send_rru_reset_req(rru);
rru->need_reset = 0;
}
else
{
cpri_rru_manager_send_delay_measure(rru);
}
}
static void cpri_rru_manager_process_rru_init_calibration_report(rru_t *rru, uint8_t *buf, int32_t len)
{
// Send CELL clear message
#ifdef ENABLE_CPRI_ETH_FDD
cpri_rru_manager_send_cell_clear_fdd(rru);
#else
cpri_rru_manager_send_cell_clear_tdd(rru);
#endif
}
static void cpri_rru_manager_process_delay_measure_resp(rru_t *rru, uint8_t *buf, int32_t len)
{
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
ir_ie_911_t *ie_911;
int32_t off;
off = sizeof(ir_msg_header_t);
ie_911 = (ir_ie_911_t *)(buf + off);
if(ie_911->ie_no != 911)
{
LOG_E(HW, "Invalid IE %i in channel configuration response!\n", ie_911->ie_no);
return;
}
LOG_I(HW, "t_offset=%i tb_delay_dl=%i tb_delay_ul=%i t2a=%i ta3=%i N=%i\n", ie_911->t_offset, ie_911->tb_delay_dl,
ie_911->tb_delay_ul, ie_911->t2a, ie_911->ta3, ie_911->N);
rru->state = RRU_STATE_CONN_SETUP_ACK;
rru->timeout = 0;
cpri_rru_manager_send_delay_configuration(rru);
}
static void cpri_rru_manager_process_delay_configuration_resp(rru_t *rru, uint8_t *buf, int32_t len)
{
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
ir_ie_931_t *ie_931;
int32_t off;
off = sizeof(ir_msg_header_t);
ie_931 = (ir_ie_931_t *)(buf + off);
if(ie_931->ie_no != 931)
{
LOG_E(HW, "Invalid IE %i in delay configuration response!\n", ie_931->ie_no);
return;
}
LOG_I(HW, "Delay configuration for port %i result %i\n", ie_931->port, ie_931->result);
// rru->state = RRU_STATE_READY;
rru->timeout = 0;
cpri_rru_manager_send_parameter_configuration(rru);
}
static void cpri_rru_manager_process_rru_heartbeat(rru_t *rru, uint8_t *buf, int32_t len)
{
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
LOG_D(HW, "RRU heartbeat\n");
cpri_rru_manager_send_bbu_heartbeat(rru); //, hdr->flow);
rru->timeout = 0;
// Switch to WAIT state after 3 heartbeats received
// if(rru->heartbeat_counter++ == 3)
//{
// rru->state = RRU_STATE_NEED_PARAMS_CONFIG;
//}
}
static void cpri_rru_manager_process_rru_reset_event(rru_t *rru, uint8_t *buf, int32_t len)
{
// send_rru_reset_req(rru);
rru->timeout = 0;
}
#if 0
void cpri_rru_manager_send_bbu_heartbeat(rru_t *rru, uint32_t id)
{
uint8_t buf[128];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
//hdr->flow = rru->serial_out++;
hdr->flow = id;
hdr->msg_no = 181;
hdr->msg_len = sizeof(ir_msg_header_t);
send(rru->fd, buf, hdr->msg_len, 0);
}
#endif
static void cpri_rru_manager_send_bbu_heartbeat(rru_t *rru)
{
uint8_t buf[128];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = 181;
hdr->msg_len = sizeof(ir_msg_header_t);
send(rru->fd, buf, hdr->msg_len, 0);
}
static void cpri_rru_manager_send_rru_reset_req(rru_t *rru)
{
uint8_t buf[128];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
int32_t off = 0;
LOG_I(HW, "Resetting RRU\n");
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = IR_MSG_RRU_RESET_REQ;
off += sizeof(ir_msg_header_t);
ir_ie_1301_t *ie_1301 = (ir_ie_1301_t *)(buf + off);
ie_1301->ie_no = 1301;
ie_1301->ie_len = sizeof(ir_ie_1301_t);
ie_1301->reset_type = 0;
off += sizeof(ir_ie_1301_t);
hdr->msg_len = off;
send(rru->fd, buf, hdr->msg_len, 0);
}
static void cpri_rru_manager_send_parameter_configuration(rru_t *rru)
{
uint8_t buf[2048];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
time_t t = time(NULL);
int32_t off = 0;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = IR_MSG_RRU_PARAMETERS_CONFIGURATION_REQ;
off += sizeof(ir_msg_header_t);
#if 1
ir_ie_501_t *ie_501;
/*
// Clear IQ configuration, antenna 1
ie_501 = (ir_ie_501_t *)(buf + off);
ie_501->ie_no = 501;
ie_501->ie_len = sizeof(ir_ie_501_t);
ie_501->carrier = 1;
ie_501->antenna = 1;
ie_501->axc = 254;
ie_501->fiber = 0;
off += sizeof(ir_ie_501_t);
// Clear IQ configuration, antenna 2
ie_501 = (ir_ie_501_t *)(buf + off);
ie_501->ie_no = 501;
ie_501->ie_len = sizeof(ir_ie_501_t);
ie_501->carrier = 1;
ie_501->antenna = 2;
ie_501->axc = 254;
ie_501->fiber = 0;
off += sizeof(ir_ie_501_t);
*/
// Antenna 1, AxC 0&1
ie_501 = (ir_ie_501_t *)(buf + off);
ie_501->ie_no = 501;
ie_501->ie_len = sizeof(ir_ie_501_t);
ie_501->carrier = 1;
ie_501->antenna = 1;
ie_501->axc = 0;
ie_501->fiber = 0;
off += sizeof(ir_ie_501_t);
if(g_fapi_cfg_req.rf_config.dl_channel_bandwidth == 25)
{
ie_501 = (ir_ie_501_t *)(buf + off);
ie_501->ie_no = 501;
ie_501->ie_len = sizeof(ir_ie_501_t);
ie_501->carrier = 1;
ie_501->antenna = 1;
ie_501->axc = 1;
ie_501->fiber = 0;
off += sizeof(ir_ie_501_t);
}
if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 2)
{
// Antenna 2
ie_501 = (ir_ie_501_t *)(buf + off);
ie_501->ie_no = 501;
ie_501->ie_len = sizeof(ir_ie_501_t);
ie_501->carrier = 1;
ie_501->antenna = 2;
ie_501->axc = 2;
ie_501->fiber = 0;
off += sizeof(ir_ie_501_t);
if(g_fapi_cfg_req.rf_config.dl_channel_bandwidth == 25)
{
ie_501 = (ir_ie_501_t *)(buf + off);
ie_501->ie_no = 501;
ie_501->ie_len = sizeof(ir_ie_501_t);
ie_501->carrier = 1;
ie_501->antenna = 2;
ie_501->axc = 3;
ie_501->fiber = 0;
off += sizeof(ir_ie_501_t);
}
}
#if 0
// Antenna 3
ie_501 = (ir_ie_501_t *)(buf + off);
ie_501->ie_len = sizeof(ir_ie_501_t);
ie_501->carrier = 3;
ie_501->antenna = 3;
ie_501->axc = 2;
ie_501->fiber = 0;
off += sizeof(ir_ie_501_t);
// Antenna 3
ie_501 = (ir_ie_501_t *)(buf + off);
ie_501->ie_len = sizeof(ir_ie_501_t);
ie_501->carrier = 4;
ie_501->antenna = 4;
ie_501->axc = 3;
ie_501->fiber = 0;
off += sizeof(ir_ie_501_t);
#endif
#endif
// Antenna group configuration
ir_ie_507_t *ie_507 = (ir_ie_507_t *)(buf + off);
ie_507->ie_no = 507;
ie_507->ie_len = sizeof(ir_ie_507_t);
ie_507->mode = 1;
ie_507->group = 1;
if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 2)
{
// 2 antennas
ie_507->uplink = 0xfc;
ie_507->downlink = 0xfc;
}
else if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 1)
{
// 1 antenna
ie_507->uplink = 0xfe;
ie_507->downlink = 0xfe;
}
off += sizeof(ir_ie_507_t);
hdr->msg_len = off;
if(send(rru->fd, buf, off, 0) != off)
{
LOG_E(HW, "Error sending channel configuration!\n");
}
rru->state = RRU_STATE_WAIT_PARAMS_CONFIG_RESP;
rru->timeout = 0;
}
static void cpri_rru_manager_process_parameter_configuration_resp(rru_t *rru, uint8_t *buf, int32_t len)
{
LOG_I(HW, "RRU parameters configuration response\n");
// Теперь необходимо дождаться сообщения INIT_CALIBRATION_RESULT
// Send CELL clear message
// send_cell_clear(rru);
}
static void cpri_rru_manager_process_cell_clear_resp(rru_t *rru, uint8_t *buf, int32_t len)
{
LOG_I(HW, "RRU cell clear response\n");
// Send CELL configuration message
#ifdef ENABLE_CPRI_ETH_FDD
cpri_rru_manager_send_cell_configuration_fdd(rru);
#else
cpri_rru_manager_send_cell_configuration_tdd(rru);
#endif
}
static void cpri_rru_manager_send_cell_clear_tdd(rru_t *rru)
{
uint8_t buf[2048];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
time_t t = time(NULL);
int32_t off = 0;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = IR_MSG_RRU_CELL_CONFIGURATION_REQ;
off += sizeof(ir_msg_header_t);
// Cell 1 RX clear
ir_ie_1501_t *ie_1501 = (ir_ie_1501_t *)(buf + off);
ie_1501->ie_no = 1501;
ie_1501->ie_len = sizeof(ir_ie_1501_t);
ie_1501->reason = 1; // delete
ie_1501->cell_id = 0x00000001;
ie_1501->power = 20;
ie_1501->ant_group = 1;
/*
if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 2)
{
ie_1501->n_freqs = 2;
}
else if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 1)
{
ie_1501->n_freqs = 1;
}
*/
ie_1501->n_freqs = 1;
off += sizeof(ir_ie_1501_t);
// Cell 1 Frequency clear
ir_ie_1502_t *ie_1502 = (ir_ie_1502_t *)(buf + off);
ie_1502->ie_no = 1502;
ie_1502->ie_len = sizeof(ir_ie_1502_t);
ie_1502->reason = 1; // delete
ie_1502->cell_id = 0x00000001;
ie_1502->carrier = 1;
ie_1502->center = 23500;
ie_1502->type = 0;
ie_1502->bandwidth = 20;
ie_1502->cp_length = 0;
off += sizeof(ir_ie_1502_t);
hdr->msg_len = off;
if(send(rru->fd, buf, off, 0) != off)
{
LOG_E(HW, "Error sending cell clear!\n");
}
rru->state = RRU_STATE_WAIT_CELL_CLEAR_RESP;
rru->timeout = 0;
}
static void cpri_rru_manager_send_cell_configuration_tdd(rru_t *rru)
{
uint8_t buf[2048];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
time_t t = time(NULL);
int32_t off = 0;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = IR_MSG_RRU_CELL_CONFIGURATION_REQ;
off += sizeof(ir_msg_header_t);
// Cell 1 configuration
// Cell 1 RX
ir_ie_1501_t *ie_1501 = (ir_ie_1501_t *)(buf + off);
ie_1501->ie_no = 1501;
ie_1501->ie_len = sizeof(ir_ie_1501_t);
ie_1501->reason = 0; // establish
ie_1501->cell_id = 0x00000001;
//ie_1501->power = 20 * 256; // 43*256;
ie_1501->power = rru->cfg->power_dbm * 256;
ie_1501->ant_group = 1;
/*
if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 2)
{
ie_1501->n_freqs = 2;
}
else if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 1)
{
ie_1501->n_freqs = 1;
}
*/
ie_1501->n_freqs = 1;
off += sizeof(ir_ie_1501_t);
// Cell 1
ir_ie_1502_t *ie_1502 = (ir_ie_1502_t *)(buf + off);
ie_1502->ie_no = 1502;
ie_1502->ie_len = sizeof(ir_ie_1502_t);
ie_1502->reason = 2; // delete
ie_1502->cell_id = 0x00000001;
ie_1502->carrier = 1;
ie_1502->center = rru->cfg->freq_dl;
ie_1502->type = 0;
switch(g_fapi_cfg_req.rf_config.dl_channel_bandwidth)
{
case 15:
ie_1502->bandwidth = 3;
break;
case 25:
ie_1502->bandwidth = 5;
break;
case 50:
ie_1502->bandwidth = 10;
break;
case 100:
ie_1502->bandwidth = 20;
break;
}
ie_1502->cp_length = 0;
off += sizeof(ir_ie_1502_t);
hdr->msg_len = off;
if(send(rru->fd, buf, off, 0) != off)
{
LOG_E(HW, "Error sending channel configuration!\n");
}
rru->state = RRU_STATE_WAIT_CELL_CONFIG_RESP;
rru->timeout = 0;
}
static void cpri_rru_manager_send_cell_clear_fdd(rru_t *rru)
{
uint8_t buf[2048];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
time_t t = time(NULL);
int32_t off = 0;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = IR_MSG_RRU_CELL_CONFIGURATION_REQ;
off += sizeof(ir_msg_header_t);
// Cell 1 RX clear
ir_ie_1501_t *ie_1501 = (ir_ie_1501_t *)(buf + off);
ie_1501->ie_no = 1501;
ie_1501->ie_len = sizeof(ir_ie_1501_t);
ie_1501->reason = 2; // delete
ie_1501->cell_id = 0x00000001;
ie_1501->power = 20;
ie_1501->ant_group = 1;
/*
if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 2)
{
ie_1501->n_freqs = 2;
}
else if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 1)
{
ie_1501->n_freqs = 1;
}
*/
ie_1501->n_freqs = 1;
off += sizeof(ir_ie_1501_t);
// Cell 1 Frequency clear
ir_ie_1503_t *ie_1503 = (ir_ie_1503_t *)(buf + off);
ie_1503->ie_no = 1503;
ie_1503->ie_len = sizeof(ir_ie_1503_t);
ie_1503->reason = 2; // delete
ie_1503->cell_id = 0x00000001;
ie_1503->carrier = 1;
ie_1503->dl_mid_freq = 4650;
ie_1503->ul_mid_freq = 4550;
ie_1503->type = 0;
ie_1503->dl_bandwidth = 5;
ie_1503->ul_bandwidth = 5;
ie_1503->cp_length = 0;
off += sizeof(ir_ie_1503_t);
#ifdef NOUSE_2T2R
ie_1503 = (ir_ie_1503_t *)(buf + off);
ie_1503->ie_no = 1503;
ie_1503->ie_len = sizeof(ir_ie_1503_t);
ie_1503->reason = 2; // delete
ie_1503->cell_id = 0x00000001;
ie_1503->carrier = 1;
ie_1503->dl_mid_freq = 4650;
ie_1503->ul_mid_freq = 4550;
ie_1503->type = 0;
ie_1503->dl_bandwidth = 5;
ie_1503->ul_bandwidth = 5;
ie_1503->cp_length = 0;
off += sizeof(ir_ie_1503_t);
#endif
hdr->msg_len = off;
if(send(rru->fd, buf, off, 0) != off)
{
LOG_E(HW, "Error sending cell clear!\n");
}
rru->state = RRU_STATE_WAIT_CELL_CLEAR_RESP;
rru->timeout = 0;
}
static void cpri_rru_manager_send_cell_configuration_fdd(rru_t *rru)
{
uint8_t buf[2048];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
time_t t = time(NULL);
int32_t off = 0;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = IR_MSG_RRU_CELL_CONFIGURATION_REQ;
off += sizeof(ir_msg_header_t);
// Cell 1 configuration
// Cell 1 RX
ir_ie_1501_t *ie_1501 = (ir_ie_1501_t *)(buf + off);
ie_1501->ie_no = 1501;
ie_1501->ie_len = sizeof(ir_ie_1501_t);
ie_1501->reason = 0; // establish
ie_1501->cell_id = 0x00000001;
//ie_1501->power = 20 * 256; // 43*256;
ie_1501->power = rru->cfg->power_dbm * 256;
ie_1501->ant_group = 1;
/*
if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 2)
{
ie_1501->n_freqs = 2;
}
else if(g_fapi_cfg_req.rf_config.tx_antenna_ports == 1)
{
ie_1501->n_freqs = 1;
}
*/
ie_1501->n_freqs = 1;
off += sizeof(ir_ie_1501_t);
// Cell 1 Frequency 455
ir_ie_1503_t *ie_1503 = (ir_ie_1503_t *)(buf + off);
ie_1503->ie_no = 1503;
ie_1503->ie_len = sizeof(ir_ie_1503_t);
ie_1503->reason = 0;
ie_1503->cell_id = 0x00000001;
ie_1503->carrier = 1;
ie_1503->type = 0;
ie_1503->dl_mid_freq = rru->cfg->freq_dl / 100000;// 4650;
ie_1503->ul_mid_freq = rru->cfg->freq_ul / 100000; // 4550;
if(g_fapi_cfg_req.rf_config.dl_channel_bandwidth == 15)
{
ie_1503->dl_bandwidth = 3;
ie_1503->ul_bandwidth = 3;
}
else if(g_fapi_cfg_req.rf_config.dl_channel_bandwidth == 25)
{
ie_1503->dl_bandwidth = 5;
ie_1503->ul_bandwidth = 5;
}
//ie_1503->dl_bandwidth = 5;
//ie_1503->ul_bandwidth = 5;
ie_1503->cp_length = 0;
off += sizeof(ir_ie_1503_t);
#ifdef NOUSE_2T2R
ie_1503 = (ir_ie_1503_t *)(buf + off);
ie_1503->ie_no = 1503;
ie_1503->ie_len = sizeof(ir_ie_1503_t);
ie_1503->reason = 0;
ie_1503->cell_id = 0x00000001;
ie_1503->carrier = 1;
ie_1503->type = 0;
#ifdef USE_3MHZ
ie_1503->dl_mid_freq = 4660;
ie_1503->ul_mid_freq = 4560;
ie_1503->dl_bandwidth = 3;
ie_1503->ul_bandwidth = 3;
#else
ie_1503->dl_mid_freq = 4650;
ie_1503->ul_mid_freq = 4550;
ie_1503->dl_bandwidth = 5;
ie_1503->ul_bandwidth = 5;
#endif
ie_1503->cp_length = 0;
off += sizeof(ir_ie_1503_t);
#endif
hdr->msg_len = off;
if(send(rru->fd, buf, off, 0) != off)
{
LOG_E(HW, "Error sending channel configuration!\n");
}
rru->state = RRU_STATE_WAIT_CELL_CONFIG_RESP;
rru->timeout = 0;
}
static void cpri_rru_manager_send_delay_measure(rru_t *rru)
{
uint8_t buf[2048];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
time_t t = time(NULL);
int32_t off = 0;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = IR_MSG_RRU_DELAY_MEASURE_REQ;
off += sizeof(ir_msg_header_t);
// Delay measure request
ir_ie_901_t *ie_901 = (ir_ie_901_t *)(buf + off);
ie_901->ie_no = 901;
ie_901->ie_len = sizeof(ir_ie_901_t);
ie_901->port = 0;
off += sizeof(ir_ie_901_t);
hdr->msg_len = off;
if(send(rru->fd, buf, off, 0) != off)
{
LOG_E(HW, "Error sending delay measure request!\n");
}
rru->state = RRU_STATE_WAIT_CELL_CONFIG_RESP;
rru->timeout = 0;
}
static void cpri_rru_manager_send_delay_configuration(rru_t *rru)
{
uint8_t buf[2048];
ir_msg_header_t *hdr = (ir_msg_header_t *)buf;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
int32_t off = 0;
memset(buf, 0, sizeof(buf));
hdr->rru_id = rru->id;
hdr->bbu_id = rru->bbu_id;
hdr->port = rru->port;
hdr->flow = rru->serial_out++;
hdr->msg_no = IR_MSG_RRU_DELAY_CONFIG_REQ;
off += sizeof(ir_msg_header_t);
// Delay measure request
ir_ie_921_t *ie_921 = (ir_ie_921_t *)(buf + off);
ie_921->ie_no = 921;
ie_921->ie_len = sizeof(ir_ie_921_t);
ie_921->port = 0;
ie_921->t12 = 943 + 2573;
ie_921->t32 = 943 + 2426;
ie_921->dl_offset = 256;
ie_921->dl_cal_rru = 24240;
ie_921->ul_cal_rru = 40227;
// ie_921->dl_cal_rru = 0;
// ie_921->ul_cal_rru = 15987;
// ie_921->dl_cal_rru = 90907;
// ie_921->ul_cal_rru = 106894;
// ie_921->dl_cal_rru = 0;
// ie_921->ul_cal_rru = 0;
off += sizeof(ir_ie_921_t);
hdr->msg_len = off;
if(send(rru->fd, buf, off, 0) != off)
{
LOG_E(HW, "Error sending delay measure request!\n");
}
rru->state = RRU_STATE_WAIT_CELL_CONFIG_RESP;
rru->timeout = 0;
}
static void cpri_rru_manager_process_cell_configuration_resp(rru_t *rru, uint8_t *buf, int32_t len)
{
LOG_I(HW, "RRU cell configuration response\n");
rru->state = RRU_STATE_READY;
rru->timeout = 0;
}
static void cpri_rru_manager_process_rru_message(rru_t *rru, uint8_t *buf, int32_t len)
{
ir_msg_header_t *hdr;
ir_ie_header_t *ie_hdr;
int32_t off;
if(len < sizeof(ir_msg_header_t))
{
// Error message
return;
}
hdr = (ir_msg_header_t *)buf;
// LOG_I(HW, "Rx RRU msg %i\n", hdr->msg_no);
switch(hdr->msg_no)
{
case 1:
// Channel establishment request
cpri_rru_manager_process_channel_establishment_req(rru, buf, len);
break;
case 3:
cpri_rru_manager_process_channel_establishment_resp(rru, buf, len);
// Channel configuration response
break;
case IR_MSG_RRU_PARAMETERS_CONFIGURATION_RESP:
cpri_rru_manager_process_parameter_configuration_resp(rru, buf, len);
break;
case IR_MSG_RRU_CELL_CONFIGURATION_RESP:
if(rru->state == RRU_STATE_WAIT_CELL_CLEAR_RESP)
{
cpri_rru_manager_process_cell_clear_resp(rru, buf, len);
}
else
{
cpri_rru_manager_process_cell_configuration_resp(rru, buf, len);
}
break;
case IR_MSG_RRU_DELAY_MEASURE_RESP:
cpri_rru_manager_process_delay_measure_resp(rru, buf, len);
break;
case IR_MSG_RRU_DELAY_CONFIG_RESP:
cpri_rru_manager_process_delay_configuration_resp(rru, buf, len);
break;
case 171:
cpri_rru_manager_process_rru_heartbeat(rru, buf, len);
// RRU heartbeat
break;
case IR_MSG_RRU_ALARM_REPORT:
cpri_rru_manager_process_rru_reset_event(rru, buf, len);
break;
case IR_MSG_RRU_INIT_CALIBRATION_REPORT:
case IR_MSG_RRU_RESET_EVENT:
if(rru->state != RRU_STATE_READY)
{
cpri_rru_manager_process_rru_init_calibration_report(rru, buf, len);
}
break;
default:
LOG_I(HW, "RRU msg_no %i not known\n", hdr->msg_no);
}
}
static int32_t cpri_rru_manager_connected()
{
int32_t i;
for(i = 0; i < MAX_RRU_CLIENTS; i++)
{
if(rrus[i].state == RRU_STATE_READY)
break;
}
return (i < MAX_RRU_CLIENTS);
}
| 22.724118 | 115 | 0.681497 |
b04742b0c461e0c8381e279afc560de1b532ebfd | 48 | c | C | src/video.c | benjinx/CHIP-8 | 7b8e28b6460f933e2ac4ff5e872b1601c6e905f1 | [
"MIT"
] | null | null | null | src/video.c | benjinx/CHIP-8 | 7b8e28b6460f933e2ac4ff5e872b1601c6e905f1 | [
"MIT"
] | null | null | null | src/video.c | benjinx/CHIP-8 | 7b8e28b6460f933e2ac4ff5e872b1601c6e905f1 | [
"MIT"
] | null | null | null | #include "video.h"
uint8_t VRAM[HEIGHT][WIDTH]; | 16 | 28 | 0.729167 |
61e2ab8d6f170aefd8b159d070b3de7729ee2b59 | 3,272 | h | C | lsp_shiloh/third_party/net_snmp_subagent/include/sdhEngGeneral.h | internaru/Pinetree_P | 1f1525454c8b20c6c589529ff4bc159404611297 | [
"FSFAP"
] | null | null | null | lsp_shiloh/third_party/net_snmp_subagent/include/sdhEngGeneral.h | internaru/Pinetree_P | 1f1525454c8b20c6c589529ff4bc159404611297 | [
"FSFAP"
] | null | null | null | lsp_shiloh/third_party/net_snmp_subagent/include/sdhEngGeneral.h | internaru/Pinetree_P | 1f1525454c8b20c6c589529ff4bc159404611297 | [
"FSFAP"
] | null | null | null | /*
* ============================================================================
* Copyright (c) 2012 Marvell International, Ltd. All Rights Reserved
*
* Marvell Confidential
* ============================================================================
*
* sdhEngGeneralTable Printer MIB (Header)
*
* based on an auto-generated file from Printer-MIB by mib2c
* using mib2c.array-user.conf (15997 2007-03-25 22:28:35Z dts12)
*/
#ifndef SDHENGGENERALTABLE_H
#define SDHENGGENERALTABLE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/library/container.h>
#include <net-snmp/agent/table_array.h>
#include "printer_mib_translation.h"
/*************************************************************
* table definition
*/
typedef struct sdhEngGeneralTable_context_s {
netsnmp_index index;
PRTMIB_OID_MAP *columnInfo;
} sdhEngGeneralTable_context;
/*************************************************************
* APIs for printer application
*/
void init_sdhEngGeneralTable(void);
void populate_sdhEngGeneralTable(PRTMIB_OID_MAP *);
/*************************************************************
* internal function declarations and APIs for net-snmp master agent
*/
//int add_sdhEngGeneralTable_entry(sdhEngGeneralTable_context *);
//int del_sdhEngGeneralTable_entry(long);
void initialize_table_sdhEngGeneralTable(void);
const sdhEngGeneralTable_context *sdhEngGeneralTable_get_by_idx(netsnmp_index *);
const sdhEngGeneralTable_context *sdhEngGeneralTable_get_by_idx_rs(
netsnmp_index *, int row_status);
int sdhEngGeneralTable_get_value(
netsnmp_request_info *, netsnmp_index *, netsnmp_table_request_info *);
sdhEngGeneralTable_context *sdhEngGeneralTable_create_row(netsnmp_index *);
int sdhEngGeneralTable_extract_index(sdhEngGeneralTable_context *, netsnmp_index *);
void sdhEngGeneralTable_set_reserve1(netsnmp_request_group *);
void sdhEngGeneralTable_set_reserve2(netsnmp_request_group *);
void sdhEngGeneralTable_set_action(netsnmp_request_group *);
void sdhEngGeneralTable_set_commit(netsnmp_request_group *);
void sdhEngGeneralTable_set_free(netsnmp_request_group *);
void sdhEngGeneralTable_set_undo(netsnmp_request_group *);
sdhEngGeneralTable_context *sdhEngGeneralTable_duplicate_row(
sdhEngGeneralTable_context *);
netsnmp_index * sdhEngGeneralTable_delete_row(sdhEngGeneralTable_context *);
int sdhEngGeneralTable_can_delete(sdhEngGeneralTable_context *,
sdhEngGeneralTable_context *, netsnmp_request_group *);
/*************************************************************
* oid declarations
*/
extern oid sdhEngGeneralTable_oid[];
extern size_t sdhEngGeneralTable_oid_len;
#define SDHENGGENERALTABLE_TABLE_OID 1,3,6,1,4,1,27278,1
/*************************************************************
* column number definitions for table sdhEngGeneralTable
*/
#define COLUMN_SDHENGSERIALNUMBER 1
#define COLUMN_SDHENGSEARCHFUNCTION 2
#define COLUMN_SDHENGCOUNTER 3
#define COLUMN_SDHENGTONERLEVEL 4
#define COLUMN_SDHENGHDDMAX 5
#define COLUMN_SDHENGHDDUSED 6
#define SDHENGGENERALTABLE_COL_MIN 1
#define SDHENGGENERALTABLE_COL_MAX 6
#ifdef __cplusplus
}
#endif
#endif /** SDHENGGENERALTABLE_H */
| 32.39604 | 84 | 0.691015 |
5fc9b42eb0635b317806737d26cc44be0d4059fa | 360 | h | C | CJWatchDemo/CJWatchDemo WatchKit Extension/InterfaceController.h | klasower/CJWatchDemo | a5a62e991321e268fc78db91f38c53678a7496da | [
"MIT"
] | 4 | 2019-09-06T10:12:33.000Z | 2019-09-12T01:32:16.000Z | CJWatchDemo/CJWatchDemo WatchKit Extension/InterfaceController.h | klasower/CJWatchDemo | a5a62e991321e268fc78db91f38c53678a7496da | [
"MIT"
] | null | null | null | CJWatchDemo/CJWatchDemo WatchKit Extension/InterfaceController.h | klasower/CJWatchDemo | a5a62e991321e268fc78db91f38c53678a7496da | [
"MIT"
] | null | null | null | //
// InterfaceController.h
// CJWatchDemo WatchKit Extension
//
// Created by chujian.zheng on 2019/9/6.
// Copyright © 2019 BIT Net Technology(Tian Jin)co.,Ltd. All rights reserved.
//
#import <WatchKit/WatchKit.h>
#import <Foundation/Foundation.h>
@interface RowController: NSObject
@end
@interface InterfaceController : WKInterfaceController
@end
| 18.947368 | 78 | 0.75 |
5bf77695ad869115402bea349c3392d838972be8 | 2,376 | h | C | MMOCoreORB/src/server/zone/objects/creature/commands/FlourishCommand.h | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/src/server/zone/objects/creature/commands/FlourishCommand.h | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/src/server/zone/objects/creature/commands/FlourishCommand.h | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | /*
Copyright <SWGEmu>
See file COPYING for copying conditions. */
#ifndef FLOURISHCOMMAND_H_
#define FLOURISHCOMMAND_H_
#include "server/zone/objects/player/sessions/EntertainingSession.h"
class FlourishCommand: public QueueCommand {
public:
FlourishCommand(const String& name, ZoneProcessServer* server) :
QueueCommand(name, server) {
}
int doQueueCommand(CreatureObject* creature, const uint64& target,
const UnicodeString& arguments) const {
if (!checkStateMask(creature))
return INVALIDSTATE;
if (!checkInvalidLocomotions(creature))
return INVALIDLOCOMOTION;
ManagedReference<Facade*> facade = creature->getActiveSession(
SessionFacadeType::ENTERTAINING);
ManagedReference<EntertainingSession*> session =
dynamic_cast<EntertainingSession*> (facade.get());
if (session == nullptr) {
creature->sendSystemMessage("@performance:flourish_not_performing");
return GENERALERROR;
}
if (!session->isDancing() && !session->isPlayingMusic()) {
creature->sendSystemMessage("@performance:flourish_not_performing");
return GENERALERROR;
}
String args = arguments.toString();
int mod = Integer::valueOf(args);
Reference<PlayerObject*> ghost =
creature->getSlottedObject(
"ghost").castTo<PlayerObject*> ();
String fullString = String("flourish") + "+" + args;
if (!ghost->hasAbility(fullString)) {
creature->sendSystemMessage("@performance:flourish_not_valid");
return GENERALERROR;
}
session->doFlourish(mod, true);
return SUCCESS;
}
float getCommandDuration(CreatureObject* object, const UnicodeString& arguments) const {
ManagedReference<Facade*> facade = object->getActiveSession(
SessionFacadeType::ENTERTAINING);
ManagedReference<EntertainingSession*> session =
dynamic_cast<EntertainingSession*> (facade.get());
if (session == nullptr)
return 0.0f;
int knowledgeSkillMod = 0;
if (session->isPlayingMusic()) {
knowledgeSkillMod = object->getSkillMod("healing_music_ability");
} else if (session->isDancing()) {
knowledgeSkillMod = object->getSkillMod("healing_dance_ability");
} else {
return 0.0f;
}
//calculating cooldown as defaultTime(5s) - 1s per 30 skill mod val
//gives a minimum time of 2s at master
float duration = defaultTime - (knowledgeSkillMod / 30.0f);
return duration;
}
};
#endif //FLOURISHCOMMAND_H_
| 26.696629 | 89 | 0.731902 |
55f2511ef6ea84ee3ad432b161f48127efb7613d | 4,637 | c | C | ion/agents/instrument/direct_access/Com0Com/com0com-2.2.2.0/sys/write.c | ooici/coi-services | 43246f46a82e597345507afd7dfc7373cb346afa | [
"BSD-2-Clause"
] | 3 | 2016-09-20T09:50:06.000Z | 2018-08-10T01:41:38.000Z | ion/agents/instrument/direct_access/Com0Com/com0com-2.2.2.0/sys/write.c | ooici/coi-services | 43246f46a82e597345507afd7dfc7373cb346afa | [
"BSD-2-Clause"
] | null | null | null | ion/agents/instrument/direct_access/Com0Com/com0com-2.2.2.0/sys/write.c | ooici/coi-services | 43246f46a82e597345507afd7dfc7373cb346afa | [
"BSD-2-Clause"
] | 2 | 2016-03-16T22:25:49.000Z | 2016-11-26T14:54:21.000Z | /*
* $Id: write.c,v 1.10 2008/12/02 16:10:09 vfrolov Exp $
*
* Copyright (c) 2004-2008 Vyacheslav Frolov
*
* 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
*
*
* $Log: write.c,v $
* Revision 1.10 2008/12/02 16:10:09 vfrolov
* Separated tracing and debuging
*
* Revision 1.9 2007/02/20 12:05:11 vfrolov
* Implemented IOCTL_SERIAL_XOFF_COUNTER
* Fixed cancel and timeout routines
*
* Revision 1.8 2006/06/23 11:44:52 vfrolov
* Mass replacement pDevExt by pIoPort
*
* Revision 1.7 2006/06/21 16:23:57 vfrolov
* Fixed possible BSOD after one port of pair removal
*
* Revision 1.6 2006/01/10 10:17:23 vfrolov
* Implemented flow control and handshaking
* Implemented IOCTL_SERIAL_SET_XON and IOCTL_SERIAL_SET_XOFF
* Added setting of HoldReasons, WaitForImmediate and AmountInOutQueue
* fields of SERIAL_STATUS for IOCTL_SERIAL_GET_COMMSTATUS
*
* Revision 1.5 2005/12/05 10:54:56 vfrolov
* Implemented IOCTL_SERIAL_IMMEDIATE_CHAR
*
* Revision 1.4 2005/09/13 14:56:16 vfrolov
* Implemented IRP_MJ_FLUSH_BUFFERS
*
* Revision 1.3 2005/09/06 07:23:44 vfrolov
* Implemented overrun emulation
*
* Revision 1.2 2005/08/23 15:49:21 vfrolov
* Implemented baudrate emulation
*
* Revision 1.1 2005/01/26 12:18:54 vfrolov
* Initial revision
*
*/
#include "precomp.h"
NTSTATUS StartIrpWrite(
IN PC0C_IO_PORT pIoPort,
IN PLIST_ENTRY pQueueToComplete)
{
return ReadWrite(
pIoPort->pIoPortRemote, FALSE,
pIoPort, TRUE,
pQueueToComplete);
}
NTSTATUS FdoPortImmediateChar(
IN PC0C_IO_PORT pIoPort,
IN PIRP pIrp,
IN PIO_STACK_LOCATION pIrpStack)
{
if (pIrpStack->Parameters.DeviceIoControl.InputBufferLength < sizeof(UCHAR))
return STATUS_BUFFER_TOO_SMALL;
return FdoPortStartIrp(pIoPort, pIrp, C0C_QUEUE_WRITE, StartIrpWrite);
}
NTSTATUS FdoPortXoffCounter(
IN PC0C_IO_PORT pIoPort,
IN PIRP pIrp,
IN PIO_STACK_LOCATION pIrpStack)
{
PSERIAL_XOFF_COUNTER pXoffCounter;
if (pIrpStack->Parameters.DeviceIoControl.InputBufferLength < sizeof(SERIAL_XOFF_COUNTER))
return STATUS_BUFFER_TOO_SMALL;
pXoffCounter = (PSERIAL_XOFF_COUNTER)pIrp->AssociatedIrp.SystemBuffer;
if (pXoffCounter->Counter <= 0)
return STATUS_INVALID_PARAMETER;
return FdoPortStartIrp(pIoPort, pIrp, C0C_QUEUE_WRITE, StartIrpWrite);
}
NTSTATUS FdoPortWrite(IN PC0C_IO_PORT pIoPort, IN PIRP pIrp)
{
NTSTATUS status;
pIrp->IoStatus.Information = 0;
if ((pIoPort->handFlow.ControlHandShake & SERIAL_ERROR_ABORT) && pIoPort->errors) {
status = STATUS_CANCELLED;
} else {
if (IoGetCurrentIrpStackLocation(pIrp)->MajorFunction == IRP_MJ_FLUSH_BUFFERS ||
IoGetCurrentIrpStackLocation(pIrp)->Parameters.Write.Length)
status = FdoPortStartIrp(pIoPort, pIrp, C0C_QUEUE_WRITE, StartIrpWrite);
else
status = STATUS_SUCCESS;
}
if (status != STATUS_PENDING) {
TraceIrp("FdoPortWrite", pIrp, &status, TRACE_FLAG_RESULTS);
pIrp->IoStatus.Status = status;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
}
return status;
}
NTSTATUS c0cWrite(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp)
{
NTSTATUS status;
PC0C_COMMON_EXTENSION pDevExt = pDevObj->DeviceExtension;
#if ENABLE_TRACING
ULONG code = IoGetCurrentIrpStackLocation(pIrp)->MajorFunction;
#endif /* ENABLE_TRACING */
TraceIrp("c0cWrite", pIrp, NULL, TRACE_FLAG_PARAMS);
switch (pDevExt->doType) {
case C0C_DOTYPE_FP:
status = FdoPortWrite(((PC0C_FDOPORT_EXTENSION)pDevExt)->pIoPortLocal, pIrp);
break;
default:
status = STATUS_INVALID_DEVICE_REQUEST;
pIrp->IoStatus.Information = 0;
pIrp->IoStatus.Status = status;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
}
if (!NT_SUCCESS(status))
TraceCode(pDevExt, "IRP_MJ_", codeNameTableIrpMj, code, &status);
return status;
}
| 30.708609 | 93 | 0.712961 |
8a47eba43300d8a75a5972fc2eaaac0b98c7ca63 | 1,017 | c | C | Sources/memory/sdl.c | meika-sweet-factory/snake | 1b53c3d869b63a6bffc19215e3b48b58da4bcc83 | [
"MIT"
] | null | null | null | Sources/memory/sdl.c | meika-sweet-factory/snake | 1b53c3d869b63a6bffc19215e3b48b58da4bcc83 | [
"MIT"
] | null | null | null | Sources/memory/sdl.c | meika-sweet-factory/snake | 1b53c3d869b63a6bffc19215e3b48b58da4bcc83 | [
"MIT"
] | null | null | null | #include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include "../../Headers/memory.h"
#define INIT_CONFIG SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER
#define RENDER_CONFIG SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC
/* Usable functions */
inline SDL_Renderer *init_sdl(t_game *g, SDL_Window *w, SDL_Renderer *r)
{
if (SDL_Init(INIT_CONFIG) < 0) return ERROR;
if (TTF_Init() < 0) return ERROR;
if (!(w = SDL_CreateWindow("Snake 2.0", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
g->map->size.x * 10 + 100, g->map->size.y * 10,
SDL_WINDOW_SHOWN))) return ERROR;
if (!(r = SDL_CreateRenderer(w, -1, RENDER_CONFIG))) return ERROR;
SDL_SetRenderDrawColor(r, 0, 0, 0, 255);
SDL_RenderClear(r);
SDL_RenderPresent(r);
return r;
}
inline void free_sdl(SDL_Window *w, SDL_Renderer *r)
{
SDL_DestroyRenderer(r);
SDL_DestroyWindow(w);
TTF_Quit();
SDL_Quit();
}
| 32.806452 | 83 | 0.635202 |
e1e64059a0cd3b01c2ba81efa0e4b1be61a257ce | 16,910 | h | C | src/app/voltdb/voltdb_src/src/ee/expressions/numericfunctions.h | OpenMPDK/SMDK | 8f19d32d999731242cb1ab116a4cb445d9993b15 | [
"BSD-3-Clause"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | src/app/voltdb/voltdb_src/src/ee/expressions/numericfunctions.h | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | src/app/voltdb/voltdb_src/src/ee/expressions/numericfunctions.h | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | /* This file is part of VoltDB.
* Copyright (C) 2008-2020 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common/NValue.hpp"
#include "boost/math/constants/constants.hpp"
namespace voltdb {
static const TTInt CONST_ONE("1");
static const TTInt CONST_FIVE("5");
/** implement the SQL ABS (absolute value) function for all numeric types */
template<> inline NValue NValue::callUnary<FUNC_ABS>() const {
if (isNull()) {
return *this;
}
const ValueType type = getValueType();
NValue retval(type);
switch(type) {
/*abs() in C++ returns int (32-bits) if input is int, and long (64-bit) if input is long.
VoltDB INTEGER is 32-bit, BIGINT is 64-bit, so for TINYINT (8-bit) and SMALLINT (16-bit),
we need to cast.*/
case ValueType::tTINYINT:
retval.getTinyInt() = static_cast<int8_t>(std::abs(getTinyInt())); break;
case ValueType::tSMALLINT:
retval.getSmallInt() = static_cast<int16_t>(std::abs(getSmallInt())); break;
case ValueType::tINTEGER:
retval.getInteger() = std::abs(getInteger()); break;
case ValueType::tBIGINT:
retval.getBigInt() = std::abs(getBigInt()); break;
case ValueType::tDOUBLE:
retval.getDouble() = std::abs(getDouble()); break;
case ValueType::tDECIMAL:
retval.getDecimal() = getDecimal();
retval.getDecimal().Abs(); // updates in place!
break;
case ValueType::tTIMESTAMP:
default:
throwCastSQLException (type, ValueType::NumericDiagnostics);
break;
}
return retval;
}
/** implement the SQL FLOOR function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_FLOOR>() const {
if (isNull()) {
return *this;
}
const ValueType type = getValueType();
NValue retval(type);
switch(type) {
case ValueType::tTINYINT:
case ValueType::tSMALLINT:
case ValueType::tINTEGER:
case ValueType::tBIGINT:
return *this;
/*floor() in C++ returns double (64-bits) if input is double, float (32-bit) if input is float,
and long double (128-bit) if input is long double (128-bit).*/
case ValueType::tDOUBLE:
retval.getDouble() = std::floor(getDouble());
break;
case ValueType::tDECIMAL: {
TTInt scaledValue = getDecimal();
TTInt fractional(scaledValue);
fractional %= NValue::kMaxScaleFactor;
if (fractional == 0) {
return *this;
}
TTInt whole(scaledValue);
whole /= NValue::kMaxScaleFactor;
if (scaledValue.IsSign()) {
//whole has the sign at this point.
whole--;
}
whole *= NValue::kMaxScaleFactor;
retval.getDecimal() = whole;
}
break;
default:
throwCastSQLException (type, ValueType::NumericDiagnostics);
break;
}
return retval;
}
/** implement the SQL CEIL function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_CEILING>() const {
if (isNull()) {
return *this;
}
const ValueType type = getValueType();
NValue retval(type);
switch(type) {
case ValueType::tTINYINT:
case ValueType::tSMALLINT:
case ValueType::tINTEGER:
case ValueType::tBIGINT:
return *this;
/*ceil() in C++ returns double (64-bits) if input is double, float (32-bit) if input is float,
and long double (128-bit) if input is long double (128-bit). VoltDB INTEGER is 32-bit, BIGINT is 64-bit,
so for TINYINT (8-bit) and SMALLINT (16-bit), we need to cast.*/
case ValueType::tDOUBLE:
retval.getDouble() = std::ceil(getDouble());
break;
case ValueType::tDECIMAL:
{
TTInt scaledValue = getDecimal();
TTInt fractional(scaledValue);
fractional %= NValue::kMaxScaleFactor;
if (fractional == 0) {
return *this;
}
TTInt whole(scaledValue);
whole /= NValue::kMaxScaleFactor;
if (!scaledValue.IsSign()) {
whole++;
}
whole *= NValue::kMaxScaleFactor;
retval.getDecimal() = whole;
}
break;
default:
throwCastSQLException(type, ValueType::NumericDiagnostics);
break;
}
return retval;
}
/** implement the SQL SQRT function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_SQRT>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
/*sqrt() in C++ returns double (64-bits) if input is double, float (32-bit) if input is float,
and long double (128-bit) if input is long double (128-bit).*/
double inputValue = castAsDoubleAndGetValue();
double resultDouble = std::sqrt(inputValue);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function SQRT");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL EXP function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_EXP>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
//exp() in C++ returns double (64-bits) if input is double, float (32-bit) if input is float,
//and long double (128-bit) if input is long double (128-bit).
double exponentValue = castAsDoubleAndGetValue();
double resultDouble = std::exp(exponentValue);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function EXP");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL LOG/LN function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_LN>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double resultDouble = std::log(inputValue);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function LN");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL LOG10 function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_LOG10>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double resultDouble = std::log10(inputValue);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function LOG10");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL SIN function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_SIN>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double resultDouble = std::sin(inputValue);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function SIN");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL COS function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_COS>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double resultDouble = std::cos(inputValue);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function COS");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL TAN function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_TAN>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double resultDouble = std::tan(inputValue);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function TAN");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL COT function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_COT>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double tanDouble = std::tan(inputValue);
double resultDouble = 1 / tanDouble;
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function COT");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL CSC function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_CSC>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double sinDouble = std::sin(inputValue);
double resultDouble = 1 / sinDouble;
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function CSC");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL SEC function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_SEC>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double cosDouble = std::cos(inputValue);
double resultDouble = 1 / cosDouble;
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function SEC");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL DEGREE function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_DEGREES>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double resultDouble = inputValue*(180.0 / M_PI);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function DEGREES");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL RADIAN function for all numeric values */
template<> inline NValue NValue::callUnary<FUNC_RADIANS>() const {
if (isNull()) {
return *this;
}
NValue retval(ValueType::tDOUBLE);
double inputValue = castAsDoubleAndGetValue();
double resultDouble = inputValue*(M_PI / 180.0);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function Radians");
retval.getDouble() = resultDouble;
return retval;
}
/** implement the SQL POWER function for all numeric values */
template<> inline NValue NValue::call<FUNC_POWER>(const std::vector<NValue>& arguments) {
vassert(arguments.size() == 2);
NValue retval(ValueType::tDOUBLE);
const NValue& base = arguments[0];
const NValue& exponent = arguments[1];
if (base.isNull()) {
return base;
}
if (exponent.isNull())
{
return exponent;
}
double baseValue = base.castAsDoubleAndGetValue();
double exponentValue = exponent.castAsDoubleAndGetValue();
double resultDouble = std::pow(baseValue, exponentValue);
throwDataExceptionIfInfiniteOrNaN(resultDouble, "function POWER");
retval.getDouble() = resultDouble;
return retval;
}
/**
* FYI, http://stackoverflow.com/questions/7594508/modulo-operator-with-negative-values
*
* It looks like having any negative operand results in undefined behavior,
* meaning different C++ compilers could get different answers here.
* In C++2003, the modulo operator (%) is implementation defined.
* In C++2011 the policy is slavish devotion to Fortran semantics. This makes sense because,
* apparently, all the current hardware uses Fortran semantics anyway. So, even if it's implementation
* defined it's likely to be implementation defined in the same way.
*
* FYI, Fortran semantics: https://gcc.gnu.org/onlinedocs/gfortran/MOD.html
* It has the same semantics with C99 as: int(a / b) * b + MOD(a,b) == a
*/
template<> inline NValue NValue::call<FUNC_MOD>(const std::vector<NValue>& arguments) {
vassert(arguments.size() == 2);
const NValue& base = arguments[0];
const NValue& divisor = arguments[1];
const ValueType baseType = base.getValueType();
const ValueType divisorType = divisor.getValueType();
// planner should guard against any invalid number type
if (!isNumeric(baseType) || !isNumeric(divisorType)) {
throw SQLException(SQLException::dynamic_sql_error, "unsupported non-numeric type for SQL MOD function");
}
bool areAllIntegralOrDecimalType = (isIntegralType(baseType) && isIntegralType(divisorType))
|| (baseType == ValueType::tDECIMAL && divisorType == ValueType::tDECIMAL);
if (! areAllIntegralOrDecimalType) {
throw SQLException(SQLException::dynamic_sql_error, "unsupported non-integral or non-decimal type for SQL MOD function");
}
if (base.isNull() || divisor.isNull()) {
return getNullValue(ValueType::tBIGINT);
} else if (divisor.castAsDoubleAndGetValue() == 0) {
throw SQLException(SQLException::data_exception_division_by_zero, "division by zero");
}
if (isIntegralType(baseType)){
int64_t baseValue = base.castAsBigIntAndGetValue();
int64_t divisorValue = divisor.castAsBigIntAndGetValue();
int64_t result = std::abs(baseValue) % std::abs(divisorValue);
if (baseValue < 0) {
result *= -1;
}
return getBigIntValue(result);
} else {
TTInt result_decimal = base.castAsDecimalAndGetValue() % divisor.castAsDecimalAndGetValue();
return NValue::getDecimalValue(result_decimal);
}
}
/*
* implement the SQL PI function
*/
template<> inline NValue NValue::callConstant<FUNC_PI>() {
return getDoubleValue(boost::math::constants::pi<double>());
}
/** implement the Volt SQL round function for decimal values */
template<> inline NValue NValue::call<FUNC_VOLT_ROUND>(const std::vector<NValue>& arguments) {
vassert(arguments.size() == 2);
const NValue &arg1 = arguments[0];
if (arg1.isNull()) {
return getNullStringValue();
}
const ValueType type = arg1.getValueType();
//only double and decimal is allowed
if (type != ValueType::tDECIMAL && type != ValueType::tDOUBLE) {
throwCastSQLException (type, ValueType::tDECIMAL);
}
std::ostringstream out;
TTInt scaledValue;
if(type == ValueType::tDOUBLE) {
scaledValue = arg1.castAsDecimal().castAsDecimalAndGetValue();
} else {
scaledValue = arg1.castAsDecimalAndGetValue();
}
if (scaledValue.IsSign()) {
out << '-';
scaledValue.ChangeSign();
}
// rounding
const NValue &arg2 = arguments[1];
int32_t places = arg2.castAsIntegerAndGetValue();
if (places >= 12 || places <= -26) {
throw SQLException(SQLException::data_exception_numeric_value_out_of_range,
"the second parameter should be < 12 and > -26");
}
TTInt ten(10);
if (places <= 0) {
ten.Pow(-places);
}
else {
ten.Pow(places);
}
TTInt denominator = (places <= 0) ? (TTInt(kMaxScaleFactor) * ten):
(TTInt(kMaxScaleFactor) / ten);
TTInt fractional(scaledValue);
fractional %= denominator;
TTInt barrier = CONST_FIVE * (denominator / 10);
if (fractional > barrier) {
scaledValue += denominator;
}
if (fractional == barrier) {
TTInt prev = scaledValue / denominator;
if (prev % 2 == CONST_ONE) {
scaledValue += denominator;
}
}
if (places <= 0) {
scaledValue -= fractional;
int64_t whole = narrowDecimalToBigInt(scaledValue);
out << std::fixed << whole;
}
else {
int64_t whole = narrowDecimalToBigInt(scaledValue);
int64_t fraction = getFractionalPart(scaledValue);
// here denominator is guarateed to be able to converted to int64_t
fraction /= denominator.ToInt();
out << std::fixed << whole;
// fractional part does not need groups
out << '.' << std::setfill('0') << std::setw(places) << fraction;
}
// TODO: Although there should be only one copy of newloc (and money_numpunct),
// we still need to test and make sure no memory leakage in this piece of code.
std::string rv = out.str();
return getDecimalValueFromString(rv);
}
}
| 34.794239 | 129 | 0.652454 |
c06fff5eaa98081c6076230512161b81e5d3da21 | 163 | h | C | lab01/src/Networks/IpAddress_types.h | actpohabtNS/oop_labs | 0284dc3b494e5b1246e8b4956d92ea659e6c00a9 | [
"CC0-1.0"
] | null | null | null | lab01/src/Networks/IpAddress_types.h | actpohabtNS/oop_labs | 0284dc3b494e5b1246e8b4956d92ea659e6c00a9 | [
"CC0-1.0"
] | null | null | null | lab01/src/Networks/IpAddress_types.h | actpohabtNS/oop_labs | 0284dc3b494e5b1246e8b4956d92ea659e6c00a9 | [
"CC0-1.0"
] | null | null | null | #ifndef IPADDRESS_TYPES_H
#define IPADDRESS_TYPES_H
enum class IpAddress_type {
IPv4,
IPv6,
};
using IA_t = IpAddress_type;
#endif // IPADDRESS_TYPES_H
| 13.583333 | 28 | 0.748466 |
e016ea8ac999118f05047ac17401c9ed5c252d30 | 3,716 | h | C | tests/biomolecules/sprelay/core/impl/mock_serial_port_test.h | lumik/sprelay | aaae1167038fc5477fc5dc9ee026d08c1d1b88bc | [
"BSD-3-Clause"
] | null | null | null | tests/biomolecules/sprelay/core/impl/mock_serial_port_test.h | lumik/sprelay | aaae1167038fc5477fc5dc9ee026d08c1d1b88bc | [
"BSD-3-Clause"
] | 65 | 2017-04-11T14:40:39.000Z | 2022-01-28T18:24:39.000Z | tests/biomolecules/sprelay/core/impl/mock_serial_port_test.h | lumik/sprelay | aaae1167038fc5477fc5dc9ee026d08c1d1b88bc | [
"BSD-3-Clause"
] | null | null | null | // -*-c++-*-
/***************************************************************************
** **
** Controlling interface for K8090 8-Channel Relay Card from Velleman **
** through usb using virtual serial port in Qt. **
** Copyright (C) 2018 Jakub Klener **
** **
** This file is part of SpRelay application. **
** **
** You can redistribute it and/or modify it under the terms of the **
** 3-Clause BSD License as published by the Open Source Initiative. **
** **
** 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 **
** 3-Clause BSD License for more details. **
** **
** You should have received a copy of the 3-Clause BSD License along **
** with this program. **
** If not, see https://opensource.org/licenses/ **
** **
****************************************************************************/
/*!
* \file mock_serial_port_test.h
* \brief The biomolecules::sprelay::core::MockSerialPortTest class which implements tests for
* biomolecules::sprelay::core::MockSerialPort.
*
* \author Jakub Klener <lumiksro@centrum.cz>
* \date 2018-04-24
* \copyright Copyright (C) 2018 Jakub Klener. All rights reserved.
*
* \copyright This project is released under the 3-Clause BSD License. You should have received a copy of the 3-Clause
* BSD License along with this program. If not, see https://opensource.org/licenses/.
*/
#ifndef BIOMOLECULES_SPRELAY_CORE_IMPL_MOCK_SERIAL_PORT_TEST_H_
#define BIOMOLECULES_SPRELAY_CORE_IMPL_MOCK_SERIAL_PORT_TEST_H_
#include <QObject>
#include <QString>
#include <memory>
#include "lumik/qtest_suite/qtest_suite.h"
#include "biomolecules/sprelay/core/mock_serial_port.h"
namespace biomolecules {
namespace sprelay {
namespace core {
class MockSerialPort;
class MockSerialPortTest : public QObject
{
Q_OBJECT
public:
static const int kCommandTimeoutMs;
static const int kDelayBetweenCommandsMs;
private slots:
void init();
void cleanup();
void commandBenchmark_data();
void commandBenchmark();
void jumperStatus();
void firmwareVersion();
void queryAllTimers();
void setMoreTimers();
void startTimer();
void defaultTimer();
void moreTimers();
void moreDefaultTimers();
// TODO(lumik): add test for factory defaults command
private:
bool compareResponse(const unsigned char* response, const unsigned char* expected);
void sendCommand(MockSerialPort* serial_port, const unsigned char* command) const;
bool measureCommandWithResponse(MockSerialPort* serial_port, const unsigned char* message, qint64* elapsed_ms);
std::unique_ptr<MockSerialPort> mock_serial_port_;
};
// NOLINTNEXTLINE(cert-err58-cpp, fuchsia-statically-constructed-objects)
ADD_TEST(MockSerialPortTest)
} // namespace core
} // namespace sprelay
} // namespace biomolecules
#endif // BIOMOLECULES_SPRELAY_CORE_IMPL_MOCK_SERIAL_PORT_TEST_H_
| 39.115789 | 118 | 0.565931 |
e072e12fbc6ecf75dc2a00ddae87c8a87bab4c98 | 2,572 | c | C | samples/xtensa_asm2/src/main.c | dmgerman/zephyrd3 | b6a23cc9c5d534c352e33fd18fff7799ac3c2886 | [
"Apache-2.0"
] | null | null | null | samples/xtensa_asm2/src/main.c | dmgerman/zephyrd3 | b6a23cc9c5d534c352e33fd18fff7799ac3c2886 | [
"Apache-2.0"
] | null | null | null | samples/xtensa_asm2/src/main.c | dmgerman/zephyrd3 | b6a23cc9c5d534c352e33fd18fff7799ac3c2886 | [
"Apache-2.0"
] | null | null | null | DECL|HAL_SPILL|enumerator|NO_SPILL, HAL_SPILL, ZEPHYR_SPILL, NUM_MODES
DECL|NO_SPILL|enumerator|NO_SPILL, HAL_SPILL, ZEPHYR_SPILL, NUM_MODES
DECL|NUM_MODES|enumerator|NO_SPILL, HAL_SPILL, ZEPHYR_SPILL, NUM_MODES
DECL|TIMER_INT|macro|TIMER_INT
DECL|TIMER_INT|macro|TIMER_INT
DECL|XSTACK_CANARY|macro|XSTACK_CANARY
DECL|XSTACK_SIZE|macro|XSTACK_SIZE
DECL|ZEPHYR_SPILL|enumerator|NO_SPILL, HAL_SPILL, ZEPHYR_SPILL, NUM_MODES
DECL|_test_highreg_a0_save|variable|_test_highreg_a0_save
DECL|_test_highreg_sp_save|variable|_test_highreg_sp_save
DECL|ccount|function|static inline unsigned int ccount(void)
DECL|disable_timer|function|void disable_timer(void)
DECL|enable_timer|function|void enable_timer(void)
DECL|excint_cpu|variable|excint_cpu
DECL|excint_stack_top|variable|excint_stack_top
DECL|excint_stack|variable|excint_stack
DECL|handle_int5_c|function|void *handle_int5_c(void *handle)
DECL|highreg_tests|variable|highreg_tests
DECL|int5_result|variable|int5_result
DECL|interrupt_test|function|int interrupt_test(void)
DECL|main|function|void main(void)
DECL|nest|member|static struct { int nest; void *stack_top; } excint_cpu;
DECL|rfi_jump_c|function|void rfi_jump_c(void)
DECL|spill_end|variable|spill_end
DECL|spill_expect|variable|spill_expect
DECL|spill_fnp|variable|spill_fnp
DECL|spill_fn|function|static int spill_fn(int level, int a, int b, int c)
DECL|spill_mode|variable|spill_mode
DECL|spill_start|variable|spill_start
DECL|spill_wb0|variable|spill_wb0
DECL|spill_wb1|variable|spill_wb1
DECL|spill_ws0|variable|spill_ws0
DECL|spill_ws1|variable|spill_ws1
DECL|stack_top|member|static struct { int nest; void *stack_top; } excint_cpu;
DECL|switch_count|variable|switch_count
DECL|switch_handle0|variable|switch_handle0
DECL|switch_handle1|variable|switch_handle1
DECL|test_fn_t|typedef|typedef void (*test_fn_t)(void);
DECL|test_highreg_handle|variable|test_highreg_handle
DECL|test_highreg_save|function|int test_highreg_save(void)
DECL|test_highreg_sp_top|variable|test_highreg_sp_top
DECL|test_highreg_stack|variable|test_highreg_stack
DECL|test_reg_spill|function|int test_reg_spill(void)
DECL|test_switch_top|function|void test_switch_top(void)
DECL|test_switch|function|int test_switch(void)
DECL|test_xstack|function|int test_xstack(void)
DECL|testfw_wb|variable|testfw_wb
DECL|testfw_ws|variable|testfw_ws
DECL|timer2_fired|variable|timer2_fired
DECL|white|variable|white
DECL|xstack_bottom|function|void xstack_bottom(void)
DECL|xstack_ok|variable|xstack_ok
DECL|xstack_stack2|variable|xstack_stack2
DECL|xstack_top|function|void xstack_top(void)
| 46.763636 | 78 | 0.868585 |
ef30d93d46a52ecf7f25207f6968ce6322774a91 | 2,314 | h | C | src/ehl/span.h | hiddeninplainsight/EmbeddedHelperLibrary | dd194d364497fb1fdd8bccacd874e84e91a1a9f8 | [
"MIT"
] | null | null | null | src/ehl/span.h | hiddeninplainsight/EmbeddedHelperLibrary | dd194d364497fb1fdd8bccacd874e84e91a1a9f8 | [
"MIT"
] | null | null | null | src/ehl/span.h | hiddeninplainsight/EmbeddedHelperLibrary | dd194d364497fb1fdd8bccacd874e84e91a1a9f8 | [
"MIT"
] | 1 | 2021-07-20T04:59:30.000Z | 2021-07-20T04:59:30.000Z | #ifndef EMBEDDEDHELPERLIBRARY_SPAN_H
#define EMBEDDEDHELPERLIBRARY_SPAN_H
#include <cstddef>
#include "type_traits/enable_if.h"
#include "type_traits/is_container.h"
namespace ehl
{
template <typename T, typename = void>
struct span_types
{
using value_type = T;
using reference = T&;
using const_reference = T const&;
using iterator = T*;
using const_iterator = T const*;
using size_type = std::size_t;
};
template <typename T>
class span
{
public:
using value_type = typename span_types<T>::value_type;
using reference = typename span_types<T>::reference;
using const_reference = typename span_types<T>::const_reference;
using iterator = typename span_types<T>::iterator;
using const_iterator = typename span_types<T>::const_iterator;
using size_type = typename span_types<T>::size_type;
private:
iterator dataBegin;
iterator dataEnd;
public:
span(iterator begin, size_type length)
: dataBegin(begin)
, dataEnd(begin + length)
{
}
span(iterator begin, iterator end)
: dataBegin(begin)
, dataEnd(end)
{
}
template <typename Cont,
typename = enable_if_t<is_container<Cont>::value>>
span(Cont& cont)
: dataBegin(&cont[0])
, dataEnd(&cont[0] + cont.size())
{
}
template <std::size_t length>
span(T (&data)[length])
: dataBegin(data)
, dataEnd(data + length)
{
}
friend class span<const value_type>;
template <typename U>
span(span<U> const& other)
: dataBegin(other.dataBegin)
, dataEnd(other.dataEnd)
{
}
template <typename U>
span<T>& operator=(span<U> const& other)
{
dataBegin = other.dataBegin;
dataEnd = other.dataEnd;
return *this;
}
size_type length() const
{
return dataEnd - dataBegin;
}
iterator begin()
{
return dataBegin;
}
const_iterator begin() const
{
return dataBegin;
}
const_iterator cbegin() const
{
return dataBegin;
}
iterator end()
{
return dataEnd;
}
const_iterator end() const
{
return dataEnd;
}
const_iterator cend() const
{
return dataEnd;
}
reference operator[](size_type index)
{
return dataBegin[index];
}
const_reference operator[](size_type index) const
{
return dataBegin[index];
}
};
} // namespace ehl
#endif // EMBEDDEDHELPERLIBRARY_SPAN_H
| 17.268657 | 66 | 0.676318 |
b48fbe1932636215ff95fc2dae39b840a7598316 | 741 | h | C | src/command/control/control.h | marco44/pgbackrest | d211c2b8b51ae5b796bbb581d21a4a406e3ed972 | [
"MIT"
] | null | null | null | src/command/control/control.h | marco44/pgbackrest | d211c2b8b51ae5b796bbb581d21a4a406e3ed972 | [
"MIT"
] | null | null | null | src/command/control/control.h | marco44/pgbackrest | d211c2b8b51ae5b796bbb581d21a4a406e3ed972 | [
"MIT"
] | null | null | null | /***********************************************************************************************************************************
Command Control
***********************************************************************************************************************************/
#ifndef COMMAND_CONTROL_CONTROL_H
#define COMMAND_CONTROL_CONTROL_H
#include "common/type/string.h"
/***********************************************************************************************************************************
Functions
***********************************************************************************************************************************/
String *lockStopFileName(const String *stanza);
void lockStopTest(void);
#endif
| 46.3125 | 132 | 0.233468 |
772501e5a03530f00fd28b9cc01f14cadb2ee3fc | 4,653 | h | C | test/common_factory_test.h | SpineEventEngine/client-cpp | ce5d4efa0ca4eed4edc6df494dc0334460e7ed72 | [
"Apache-2.0"
] | 2 | 2018-02-12T08:24:00.000Z | 2020-02-17T12:52:23.000Z | test/common_factory_test.h | SpineEventEngine/client-cpp | ce5d4efa0ca4eed4edc6df494dc0334460e7ed72 | [
"Apache-2.0"
] | 14 | 2018-01-15T10:28:56.000Z | 2018-10-12T12:35:21.000Z | test/common_factory_test.h | SpineEventEngine/client-cpp | ce5d4efa0ca4eed4edc6df494dc0334460e7ed72 | [
"Apache-2.0"
] | 1 | 2020-02-17T12:52:43.000Z | 2020-02-17T12:52:43.000Z | /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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 SPINE_COMMONFACTORYTEST_H
#define SPINE_COMMONFACTORYTEST_H
#include <gtest/gtest.h>
#include <google/protobuf/util/field_comparator.h>
#include <google/protobuf/util/message_differencer.h>
#include "spine/command_factory.h"
#include "spine/query_factory.h"
#include "spine/topic_factory.h"
#include "spine/actor_request_factory.h"
#include "unit_tests.pb.h"
#include "unit_tests_no_prefix.pb.h"
using namespace spine::client;
using namespace spine::core;
using namespace spine::time;
using namespace spine::test;
using namespace google::protobuf::util;
class CommonFactoryTest : public ::testing::Test
{
const std::string USER_ID { "user@example.com" };
const std::string TENANT_ID { "example.com" };
protected:
virtual void SetUp() override
{
auto actor = std::make_unique<UserId>();
actor->set_value(USER_ID);
auto tenant_id = std::make_unique<TenantId>();
tenant_id->set_value(TENANT_ID);
auto zone_offset = std::make_unique<ZoneOffset>();
zone_offset->set_amount_seconds(42);
params_.set_actor(actor)
.set_tenant_id(tenant_id)
.set_zone_offset(zone_offset);
query_factory_ = ActorRequestFactory::create(params_).query_factory();
command_factory_ = ActorRequestFactory::create(params_).command_factory();
topic_factory_ = ActorRequestFactory::create(params_).topic_factory();
}
std::vector<std::unique_ptr<ProjectId>> make_project_ids()
{
std::vector<std::unique_ptr<ProjectId>> project_ids;
project_ids.emplace_back(std::make_unique<ProjectId>());
project_ids.emplace_back(std::make_unique<ProjectId>());
project_ids.emplace_back(std::make_unique<ProjectId>());
int i = 1;
for (auto& project_id : project_ids)
{
project_id->set_value(i++);
}
return project_ids;
}
void check_filters_are_empty(const Target& target)
{
ASSERT_TRUE(target.has_filters());
ASSERT_TRUE(MessageDifferencer::Equals(target.filters(), EntityFilters::default_instance()));
ASSERT_FALSE(target.filters().has_id_filter());
}
void check_filters_are_equal(const Target& target, const std::vector<std::unique_ptr<ProjectId>>& ids)
{
ASSERT_TRUE(target.has_filters());
ASSERT_TRUE(target.filters().has_id_filter());
for (const EntityId &id_filter : target.filters().id_filter().ids())
{
ASSERT_TRUE(id_filter.has_id());
ASSERT_EQ(id_filter.id().type_url(), "type.test.spine.io/spine.test.ProjectId");
const std::unique_ptr<ProjectId>& entity_id = from_any<ProjectId>(id_filter.id());
ASSERT_TRUE(std::find_if(std::begin(ids), std::end(ids),
[&] ( const std::unique_ptr<ProjectId>& val) -> bool
{
return MessageDifferencer::Equals(*val, *entity_id);
}
)
!= std::end(ids) );
}
}
void verifyContext(const ActorContext& context)
{
ASSERT_EQ(params_.actor()->value(), context.actor().value());
ASSERT_EQ(params_.tenant_id()->value(), context.tenant_id().value());
ASSERT_EQ(params_.zone_offset()->amount_seconds(), context.zone_offset().amount_seconds());
}
QueryFactoryPtr query_factory_;
TopicFactoryPtr topic_factory_;
CommandFactoryPtr command_factory_;
private:
ActorRequestFactoryParams params_;
};
#endif //SPINE_COMMONFACTORYTEST_H
| 36.928571 | 106 | 0.673329 |
e67dd446f958ba7595e3b58f0327a77d7209ccca | 766 | h | C | src/tools.h | zhou-wenbin/Udacity-KalmanFilter | 9d1c72b9aff6cd2f64aef28c1504193af2275896 | [
"MIT"
] | null | null | null | src/tools.h | zhou-wenbin/Udacity-KalmanFilter | 9d1c72b9aff6cd2f64aef28c1504193af2275896 | [
"MIT"
] | null | null | null | src/tools.h | zhou-wenbin/Udacity-KalmanFilter | 9d1c72b9aff6cd2f64aef28c1504193af2275896 | [
"MIT"
] | null | null | null | #ifndef TOOLS_H_
#define TOOLS_H_
#include <vector>
#include "Eigen/Dense"
using Eigen::MatrixXd;
using Eigen::VectorXd;
using namespace std;
class Tools {
// Variables for running computation of root mean standard
// error using Kahan sum
VectorXd mse;
VectorXd lastmse;
VectorXd residual;
VectorXd kahanerror;
VectorXd rmse;
// Reset running root mean standard error calculation to zero
void resetRMSE();
public:
Tools();
virtual ~Tools();
// Method to return running root mean standard error
VectorXd CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth);
// Method to calculate Jacobian for radar measurements
MatrixXd CalculateJacobian(const VectorXd& x_state);
};
#endif /* TOOLS_H_ */
| 21.277778 | 100 | 0.746736 |
b0f7b3b213c03f7f50448f8e20b7cfaa59aa38da | 5,356 | h | C | 3rdparty/webkit/Source/WebKit/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMHTMLTableSectionElement.h | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 1 | 2021-05-27T07:29:31.000Z | 2021-05-27T07:29:31.000Z | WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMHTMLTableSectionElement.h | mlcldh/appleWebKit2 | 39cc42a4710c9319c8da269621844493ab2ccdd6 | [
"MIT"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/WebKit/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMHTMLTableSectionElement.h | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 1 | 2019-01-25T13:55:25.000Z | 2019-01-25T13:55:25.000Z | /*
* This file is part of the WebKit open source project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#if !defined(__WEBKITDOM_H_INSIDE__) && !defined(BUILDING_WEBKIT)
#error "Only <webkitdom/webkitdom.h> can be included directly."
#endif
#ifndef WebKitDOMHTMLTableSectionElement_h
#define WebKitDOMHTMLTableSectionElement_h
#include <glib-object.h>
#include <webkitdom/WebKitDOMHTMLElement.h>
#include <webkitdom/webkitdomdefines.h>
G_BEGIN_DECLS
#define WEBKIT_DOM_TYPE_HTML_TABLE_SECTION_ELEMENT (webkit_dom_html_table_section_element_get_type())
#define WEBKIT_DOM_HTML_TABLE_SECTION_ELEMENT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_DOM_TYPE_HTML_TABLE_SECTION_ELEMENT, WebKitDOMHTMLTableSectionElement))
#define WEBKIT_DOM_HTML_TABLE_SECTION_ELEMENT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_DOM_TYPE_HTML_TABLE_SECTION_ELEMENT, WebKitDOMHTMLTableSectionElementClass)
#define WEBKIT_DOM_IS_HTML_TABLE_SECTION_ELEMENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_DOM_TYPE_HTML_TABLE_SECTION_ELEMENT))
#define WEBKIT_DOM_IS_HTML_TABLE_SECTION_ELEMENT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_DOM_TYPE_HTML_TABLE_SECTION_ELEMENT))
#define WEBKIT_DOM_HTML_TABLE_SECTION_ELEMENT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_DOM_TYPE_HTML_TABLE_SECTION_ELEMENT, WebKitDOMHTMLTableSectionElementClass))
struct _WebKitDOMHTMLTableSectionElement {
WebKitDOMHTMLElement parent_instance;
};
struct _WebKitDOMHTMLTableSectionElementClass {
WebKitDOMHTMLElementClass parent_class;
};
WEBKIT_API GType
webkit_dom_html_table_section_element_get_type(void);
/**
* webkit_dom_html_table_section_element_insert_row:
* @self: A #WebKitDOMHTMLTableSectionElement
* @index: A #glong
* @error: #GError
*
* Returns: (transfer none): A #WebKitDOMHTMLElement
**/
WEBKIT_API WebKitDOMHTMLElement*
webkit_dom_html_table_section_element_insert_row(WebKitDOMHTMLTableSectionElement* self, glong index, GError** error);
/**
* webkit_dom_html_table_section_element_delete_row:
* @self: A #WebKitDOMHTMLTableSectionElement
* @index: A #glong
* @error: #GError
*
**/
WEBKIT_API void
webkit_dom_html_table_section_element_delete_row(WebKitDOMHTMLTableSectionElement* self, glong index, GError** error);
/**
* webkit_dom_html_table_section_element_get_align:
* @self: A #WebKitDOMHTMLTableSectionElement
*
* Returns: A #gchar
**/
WEBKIT_API gchar*
webkit_dom_html_table_section_element_get_align(WebKitDOMHTMLTableSectionElement* self);
/**
* webkit_dom_html_table_section_element_set_align:
* @self: A #WebKitDOMHTMLTableSectionElement
* @value: A #gchar
*
**/
WEBKIT_API void
webkit_dom_html_table_section_element_set_align(WebKitDOMHTMLTableSectionElement* self, const gchar* value);
/**
* webkit_dom_html_table_section_element_get_ch:
* @self: A #WebKitDOMHTMLTableSectionElement
*
* Returns: A #gchar
**/
WEBKIT_API gchar*
webkit_dom_html_table_section_element_get_ch(WebKitDOMHTMLTableSectionElement* self);
/**
* webkit_dom_html_table_section_element_set_ch:
* @self: A #WebKitDOMHTMLTableSectionElement
* @value: A #gchar
*
**/
WEBKIT_API void
webkit_dom_html_table_section_element_set_ch(WebKitDOMHTMLTableSectionElement* self, const gchar* value);
/**
* webkit_dom_html_table_section_element_get_ch_off:
* @self: A #WebKitDOMHTMLTableSectionElement
*
* Returns: A #gchar
**/
WEBKIT_API gchar*
webkit_dom_html_table_section_element_get_ch_off(WebKitDOMHTMLTableSectionElement* self);
/**
* webkit_dom_html_table_section_element_set_ch_off:
* @self: A #WebKitDOMHTMLTableSectionElement
* @value: A #gchar
*
**/
WEBKIT_API void
webkit_dom_html_table_section_element_set_ch_off(WebKitDOMHTMLTableSectionElement* self, const gchar* value);
/**
* webkit_dom_html_table_section_element_get_v_align:
* @self: A #WebKitDOMHTMLTableSectionElement
*
* Returns: A #gchar
**/
WEBKIT_API gchar*
webkit_dom_html_table_section_element_get_v_align(WebKitDOMHTMLTableSectionElement* self);
/**
* webkit_dom_html_table_section_element_set_v_align:
* @self: A #WebKitDOMHTMLTableSectionElement
* @value: A #gchar
*
**/
WEBKIT_API void
webkit_dom_html_table_section_element_set_v_align(WebKitDOMHTMLTableSectionElement* self, const gchar* value);
/**
* webkit_dom_html_table_section_element_get_rows:
* @self: A #WebKitDOMHTMLTableSectionElement
*
* Returns: (transfer full): A #WebKitDOMHTMLCollection
**/
WEBKIT_API WebKitDOMHTMLCollection*
webkit_dom_html_table_section_element_get_rows(WebKitDOMHTMLTableSectionElement* self);
G_END_DECLS
#endif /* WebKitDOMHTMLTableSectionElement_h */
| 34.333333 | 180 | 0.813107 |
905736e90342a11e16b49fcf8f947bc190073656 | 668 | h | C | firmware/main/ui/filebrowser.h | natarii/MegaGRRL | 5d10f3a95ee2036efcc60a37d73d2ea1411a8e3e | [
"BSD-2-Clause"
] | 16 | 2019-06-11T06:11:19.000Z | 2022-03-28T11:04:02.000Z | firmware/main/ui/filebrowser.h | natarii/MegaGRRL | 5d10f3a95ee2036efcc60a37d73d2ea1411a8e3e | [
"BSD-2-Clause"
] | null | null | null | firmware/main/ui/filebrowser.h | natarii/MegaGRRL | 5d10f3a95ee2036efcc60a37d73d2ea1411a8e3e | [
"BSD-2-Clause"
] | 1 | 2020-02-11T22:01:50.000Z | 2020-02-11T22:01:50.000Z | #ifndef AGR_UI_FILEBROWSER_H
#define AGR_UI_FILEBROWSER_H
#include "esp_system.h"
#include "lvgl.h"
#include "../key.h"
typedef enum {
SORT_ASCENDING,
SORT_DESCENDING,
SORT_COUNT
} SortDirection_t;
extern volatile SortDirection_t Ui_FileBrowser_SortDir;
extern volatile bool Ui_FileBrowser_Sort;
extern volatile bool Ui_FileBrowser_DirsBeforeFiles;
extern volatile bool Ui_FileBrowser_Narrow;
void Ui_FileBrowser_Setup();
bool Ui_FileBrowser_Activate(lv_obj_t *uiscreen);
void Ui_FileBrowser_Destroy();
void Ui_FileBrowser_Key(KeyEvent_t event);
void Ui_FileBrowser_Tick();
void Ui_FileBrowser_InvalidateDirEntry();
void Ui_FileBrowser_Reset();
#endif | 24.740741 | 55 | 0.826347 |
74300e7f97ddda17f8f18ca2f6dc81ee853334d3 | 1,521 | h | C | src/sal/refer-op.h | hihi-dev/linphone | 45814404943a0c8a4e341dbebf5da71fc6e44b67 | [
"BSD-2-Clause"
] | null | null | null | src/sal/refer-op.h | hihi-dev/linphone | 45814404943a0c8a4e341dbebf5da71fc6e44b67 | [
"BSD-2-Clause"
] | null | null | null | src/sal/refer-op.h | hihi-dev/linphone | 45814404943a0c8a4e341dbebf5da71fc6e44b67 | [
"BSD-2-Clause"
] | null | null | null | /*
Linphone library
Copyright (C) 2010-2018 Belledonne Communications SARL
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _L_SAL_REFER_OP_H_
#define _L_SAL_REFER_OP_H_
#include "sal/op.h"
LINPHONE_BEGIN_NAMESPACE
class SalReferOp : public SalOp {
public:
SalReferOp (Sal *sal);
int sendRefer (const SalAddress *referTo);
int reply (SalReason reason);
private:
virtual void fillCallbacks () override;
void processError ();
static void processIoErrorCb (void *userCtx, const belle_sip_io_error_event_t *event);
static void processResponseEventCb (void *userCtx, const belle_sip_response_event_t *event);
static void processTimeoutCb (void *userCtx, const belle_sip_timeout_event_t *event);
static void processRequestEventCb (void *userCtx, const belle_sip_request_event_t *event);
};
LINPHONE_END_NAMESPACE
#endif // ifndef _L_SAL_REFER_OP_H_
| 32.361702 | 93 | 0.789612 |
dac3d4f5ac5d5c191247d60255e031b89f5501a8 | 1,052 | h | C | ClanTagChanger.h | fengjixuchui/X-HOOK-For-CSGO | abe00bcff7ba40d5bc369aaba9b2b7ce9212cf70 | [
"MIT"
] | 48 | 2018-11-10T06:39:17.000Z | 2022-03-10T18:44:52.000Z | ClanTagChanger.h | fengjixuchui/X-HOOK-For-CSGO | abe00bcff7ba40d5bc369aaba9b2b7ce9212cf70 | [
"MIT"
] | 7 | 2018-01-04T15:10:41.000Z | 2020-11-14T03:54:30.000Z | ClanTagChanger.h | fengjixuchui/X-HOOK-For-CSGO | abe00bcff7ba40d5bc369aaba9b2b7ce9212cf70 | [
"MIT"
] | 21 | 2018-11-23T23:13:09.000Z | 2022-03-14T21:11:38.000Z | #pragma once
namespace ClanTagChanger
{
struct Frame
{
int time;
std::wstring text;
Frame(std::wstring text, int time)
{
this->text = text;
this->time = time;
}
};
enum AnimationLoopType
{
ANIM_LOOP,
ANIM_LOOP_BACK
};
struct Animation
{
std::string name;
unsigned int currentFrame;
std::vector<Frame> frames;
AnimationLoopType loopType;
Animation(std::string name, std::vector<Frame> frames, AnimationLoopType loopType)
{
currentFrame = 0;
this->name = name;
this->frames = frames;
this->loopType = loopType;
}
Frame GetCurrentFrame()
{
return frames[currentFrame];
}
void NextFrame()
{
currentFrame++;
if (currentFrame >= frames.size())
currentFrame = 0;
}
};
extern std::vector<Animation> animations;
extern Animation* animation;
void UpdateClanTagCallback();
void SaveOriginalClanTag();
void RestoreOriginalClanTag();
//Hooks
void BeginFrame(float frameTime);
}
extern SendClanTagFn SendClanTag; | 16.4375 | 85 | 0.65019 |
d3803957c2264d15743f4c282b47a44049331c74 | 4,522 | h | C | source/gpu_perf_api_vk/vk_software_counters_results.h | roobre/gpu_performance_api | 948c67c6fd04222f6b4ee038a9b940f3fd60d0d9 | [
"MIT"
] | null | null | null | source/gpu_perf_api_vk/vk_software_counters_results.h | roobre/gpu_performance_api | 948c67c6fd04222f6b4ee038a9b940f3fd60d0d9 | [
"MIT"
] | null | null | null | source/gpu_perf_api_vk/vk_software_counters_results.h | roobre/gpu_performance_api | 948c67c6fd04222f6b4ee038a9b940f3fd60d0d9 | [
"MIT"
] | null | null | null | //==============================================================================
// Copyright (c) 2015-2020 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief Struct used to store VK query counter results
//==============================================================================
#ifndef _VK_SOFTWARE_COUNTERS_RESULTS_H_
#define _VK_SOFTWARE_COUNTERS_RESULTS_H_
#include "vk_includes.h"
/// Enum of the different Vulkan queries used by GPA.
/// These are used as both identifiers and indexes into arrays of VkQueryPools.
/// These indices need to match up with the indices exposed in GPA_CounterGeneratorVK::s_VKSWCounters
typedef enum
{
GPA_VK_QUERY_TYPE_OCCLUSION, //!< Occlusion query, with the PRECISE flag
GPA_VK_QUERY_TYPE_OCCLUSION_BINARY, //!< Occlusion query, without the PRECISE flag
GPA_VK_QUERY_TYPE_TIMESTAMP, //!< Timestamp query, will automatically enable both begin and end timestamps
GPA_VK_QUERY_TYPE_PIPELINE_STATISTICS, //!< Pipeline Statistics query, which collects the stats from the entire pipeline
GPA_VK_QUERY_TYPE_COUNT //!< The number of GPA_VK_SW_QUERY_TYPE types; not to be used as an actual enum value.
} GPA_VK_SW_QUERY_TYPE;
/// Struct used to store Vk query results
struct GpaVkSoftwareQueryResults
{
uint64_t occlusion; ///< Occlusion results
uint64_t occlusionAvailable; ///< Occlusion results are Available
uint64_t occlusionBinary; ///< Occlusion binary results
uint64_t occlusionBinaryAvailable; ///< Occlusion binary results are Available
uint64_t timestampBegin; ///< TimestampBegin results
uint64_t timestampBeginAvailable; ///< TImestampBegin results are available
uint64_t timestampEnd; ///< TimestampEnd results
uint64_t timestampEndAvailable; ///< TImestampEnd results are available
uint64_t inputAssemblyVertices; ///< Pipeline Stats: Input Assembly vertices results
uint64_t inputAssemblyPrimitives; ///< Pipeline Stats: Input Assembly primitives results
uint64_t vertexShaderInvocations; ///< Pipeline Stats: vertex shader invocations results
uint64_t geometryShaderInvocations; ///< Pipeline Stats: geometry shader invocations results
uint64_t geometryShaderPrimitives; ///< Pipeline Stats: geometry shader primitives results
uint64_t clippingInvocations; ///< Pipeline Stats: clipping invocations results
uint64_t clippingPrimitives; ///< Pipeline Stats: clipping primitives results
uint64_t fragmentShaderInvocations; ///< Pipeline Stats: fragment shader invocations results
uint64_t tessellationControlShaderPatches; ///< Pipeline Stats: tessellation control shader patches results
uint64_t tessellationEvaluationShaderInvocations; ///< Pipeline Stats: tessellation evalutation shader invocations results
uint64_t computeShaderInvocations; ///< Pipeline Stats: compute shader invocations results
uint64_t pipelineStatsAvailable; ///< Pipeline Stats results are available
};
/// An array whose indexes correspond to the GPA_VK_SW_QUERY_TYPE enums and
/// whose values indicate the memory size (in bytes) needed to store the results.
/// Occlusion queries only need two 64-bit uints (one for the result, and one for the availability bit).
/// Timestamps need four 64-bit uints because we collect both 'begin' and 'end' timestamps.
/// Pipeline Stats have 11 64-bit uint results, plus an availablity bit.
static const size_t ms_gpaVkSoftwareResultSizes[] = {sizeof(uint64_t) * 2, sizeof(uint64_t) * 2, sizeof(uint64_t) * 4, sizeof(uint64_t) * 12};
/// An array whose indexes correspond to the GPA_VK_SW_QUERY_TYPE enums and
/// whose values indicate the memory stride (in bytes) to collect the query results.
/// Occlusion and Timestamps only need to stride two 64-bit uints (the result and the availability bit).
/// Pipeline Stat queries need to stride over all 11 results and the availability bit.
static const size_t ms_gpaVkSoftwareResultStrides[] = {sizeof(uint64_t) * 2, sizeof(uint64_t) * 2, sizeof(uint64_t) * 2, sizeof(uint64_t) * 12};
#endif // _VK_SOFTWARE_COUNTERS_RESULTS_H_
| 70.65625 | 144 | 0.682884 |
de8a27f6d2da7b426a8dc8e7fcaba8eb7058d3eb | 1,014 | h | C | qqtw/qqheaders7.2/QQMessageRecallPackageHandler.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 5 | 2018-02-20T14:24:17.000Z | 2020-08-06T09:31:21.000Z | qqtw/qqheaders7.2/QQMessageRecallPackageHandler.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 1 | 2020-06-10T07:49:16.000Z | 2020-06-12T02:08:35.000Z | qqtw/qqheaders7.2/QQMessageRecallPackageHandler.h | onezens/SmartQQ | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@interface QQMessageRecallPackageHandler : NSObject
{
}
+ (void)parseC2CRecallInOut:(struct RecallItemForC2C *)arg1;
+ (_Bool)parseC2CRecallNotify:(const void *)arg1 bufferLen:(int)arg2 subcmd:(int)arg3 model:(struct RecallModel *)arg4;
+ (void)parseDicussRecallNotify:(unsigned long long)arg1 decoder:(struct CPBMessageDecoder *)arg2 model:(struct RecallModel *)arg3;
+ (_Bool)parseDiscussRecallNotify:(char *)arg1 bufferLen:(unsigned int)arg2 model:(struct RecallModel *)arg3;
+ (_Bool)parseGroupRecallNotify:(char *)arg1 bufferLen:(unsigned int)arg2 model:(struct RecallModel *)arg3;
+ (void)parseGroupRecallNotify:(unsigned long long)arg1 decoder:(struct CPBMessageDecoder *)arg2 model:(struct RecallModel *)arg3;
+ (void)parseRecallResp:(CDStruct_7895f40e)arg1 outC2C:(struct RecallResp **)arg2 outGroup:(struct RecallRespForGroup **)arg3;
@end
| 44.086957 | 131 | 0.767258 |
de9aef55c6e0ed7cc3fbdff6ad352ce0a4f3a522 | 1,467 | c | C | Externals/micromegas_4.3.5/CPVMSSM/lib/nngg12/util/suave/util.c | yuanfangtardis/vscode_project | 2d78a85413cc85789cc4fee8ec991eb2a0563ef8 | [
"Apache-2.0"
] | null | null | null | Externals/micromegas_4.3.5/CPVMSSM/lib/nngg12/util/suave/util.c | yuanfangtardis/vscode_project | 2d78a85413cc85789cc4fee8ec991eb2a0563ef8 | [
"Apache-2.0"
] | null | null | null | Externals/micromegas_4.3.5/CPVMSSM/lib/nngg12/util/suave/util.c | yuanfangtardis/vscode_project | 2d78a85413cc85789cc4fee8ec991eb2a0563ef8 | [
"Apache-2.0"
] | 1 | 2022-01-15T12:22:30.000Z | 2022-01-15T12:22:30.000Z | /*
util.c
Utility functions
this file is part of Suave
last modified 13 Apr 04 th
*/
#include "decl.h"
static count ndim_, ncomp_, nregions_, neval_;
#define Allocate(p, n) \
if( (p = malloc(n)) == NULL ) { \
fprintf(stderr, "Out of memory in " __FILE__ " line %d.\n", __LINE__); \
exit(1); \
}
#define RegionAlloc(p, n, nnew) \
Allocate(p, sizeof(Region) + \
(n)*(ndim_ + ncomp_ + 1)*sizeof(real) + \
(nnew)*ndim_*sizeof(bin_t))
#define Elements(x) (sizeof(x)/sizeof(*x))
#define Copy(d, s, n) memcpy(d, s, (n)*sizeof(*(d)))
#define Clear(d, n) memset(d, 0, (n)*sizeof(*(d)))
#define Zap(d) memset(d, 0, sizeof(d))
#define BITS (sizeof(int)*8 - 1)
static inline int NegQ(cint a)
{
/* return (a < 0) ? -1 : 0; */
return a >> BITS;
}
static inline int IDim(cint a)
{
/* return (a < 0) ? 0 : a; */
return a & NegQ(-a);
}
static inline int IMin(cint a, cint b)
{
/* return (a < b) ? a : b; */
return a - IDim(a - b);
}
static inline int IMax(cint a, cint b)
{
/* return (a > b) ? a : b; */
return b + IDim(a - b);
}
static inline real Min(creal a, creal b)
{
return (a < b) ? a : b;
}
static inline real Max(creal a, creal b)
{
return (a > b) ? a : b;
}
static inline real Sq(creal x)
{
return x*x;
}
static inline real Weight(creal sum, creal sqsum, ccount n)
{
creal w = sqrt(sqsum*n);
return (n - 1)/Max((w + sum)*(w - sum), NOTZERO);
}
#ifdef DEBUG
#include "debug.c"
#endif
| 16.862069 | 76 | 0.573279 |
46a83bf6c914634fed588279971fc05896129e2a | 225 | c | C | src/init.c | Henje/x86-Toy-OS | 38673c72db017b4b42a059f03eedb4a60dc43d3e | [
"MIT"
] | 9 | 2018-07-24T02:13:53.000Z | 2021-09-05T07:49:45.000Z | src/init.c | Henje/x86-Toy-OS | 38673c72db017b4b42a059f03eedb4a60dc43d3e | [
"MIT"
] | null | null | null | src/init.c | Henje/x86-Toy-OS | 38673c72db017b4b42a059f03eedb4a60dc43d3e | [
"MIT"
] | 2 | 2018-08-31T15:34:29.000Z | 2020-04-01T20:49:42.000Z | void init(void) {
char *video = (char*) 0xb8000;
const char *msg = "Hello World!";
for(int i = 0; i < 25*80; i++) {
video[2*i] = 0;
}
for(int i = 0; msg[i]; i++) {
video[2*i] = msg[i];
video[2*i + 1] = 0x07;
}
}
| 17.307692 | 34 | 0.497778 |
ee0b0498abbdf01e3fbf7857bb0608ec5ff64c12 | 425 | h | C | zhibo/zhibo/Class/Near/Tools/STLocationManager.h | tmac24/zhibo | dabcd9ae7fc49458be58cb7bb18c25bd41276f9a | [
"Apache-2.0"
] | 1 | 2017-12-14T05:47:16.000Z | 2017-12-14T05:47:16.000Z | zhibo/zhibo/Class/Near/Tools/STLocationManager.h | tmac24/zhibo | dabcd9ae7fc49458be58cb7bb18c25bd41276f9a | [
"Apache-2.0"
] | null | null | null | zhibo/zhibo/Class/Near/Tools/STLocationManager.h | tmac24/zhibo | dabcd9ae7fc49458be58cb7bb18c25bd41276f9a | [
"Apache-2.0"
] | null | null | null | //
// STLocationManager.h
// zhibo
//
// Created by 孙涛 on 2017/4/27.
// Copyright © 2017年 孙涛. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef void(^LocationBlock)(NSString * lat, NSString * lon);
@interface STLocationManager : NSObject
+ (instancetype)sharedManager;
- (void)getGps:(LocationBlock)block;
@property (nonatomic, copy) NSString * lat;
@property (nonatomic, copy) NSString * lon;
@end
| 19.318182 | 61 | 0.712941 |
5a88cca1cd9ae4f41b00765c545420ef8d8bc2b2 | 919 | c | C | bucket_21/utox/patches/patch-third__party_minini_minini_dev_minIni.c | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 17 | 2017-04-22T21:53:52.000Z | 2021-01-21T16:57:55.000Z | bucket_21/utox/patches/patch-third__party_minini_minini_dev_minIni.c | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 186 | 2017-09-12T20:46:52.000Z | 2021-11-27T18:15:14.000Z | bucket_21/utox/patches/patch-third__party_minini_minini_dev_minIni.c | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 74 | 2017-09-06T14:48:01.000Z | 2021-08-28T02:48:27.000Z | --- third_party/minini/minini/dev/minIni.c.orig 2021-01-25 02:56:27 UTC
+++ third_party/minini/minini/dev/minIni.c
@@ -71,7 +71,7 @@
#pragma warning(disable: 4996) /* for Microsoft Visual C/C++ */
#endif
#if !defined strnicmp && !defined PORTABLE_STRNICMP
- #if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__
+ #if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__ || defined __DragonFly__ || defined __NetBSD_
#define strnicmp strncasecmp
#endif
#endif
@@ -80,7 +80,7 @@
#endif
#if !defined INI_LINETERM
- #if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__
+ #if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__ || defined __DragonFly__ || defined __NetBSD__
#define INI_LINETERM __T("\n")
#else
#define INI_LINETERM __T("\r\n")
| 43.761905 | 138 | 0.709467 |
e171fbbdd9c24b589cd900492200e2603c7250e8 | 82 | c | C | ppu.c | ValerioMerli/aiv_gb | 1698dc52f530d43100baaa2034206f4552524b7a | [
"MIT"
] | null | null | null | ppu.c | ValerioMerli/aiv_gb | 1698dc52f530d43100baaa2034206f4552524b7a | [
"MIT"
] | null | null | null | ppu.c | ValerioMerli/aiv_gb | 1698dc52f530d43100baaa2034206f4552524b7a | [
"MIT"
] | null | null | null | #include <aiv_gb.h>
void aiv_gb_vram_to_rgb(aiv_gameboy *gb, u8_t *data)
{
} | 13.666667 | 52 | 0.695122 |
f6df88675a4e8de7f35fd196f146a1a404955291 | 24,690 | h | C | ugene/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/hashMap.h | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/hashMap.h | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/hashMap.h | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | // -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: hashMap.h,v 1.41 2005-12-23 17:01:42 amoll Exp $
//
#ifndef BALL_DATATYPE_HASHMAP_H
#define BALL_DATATYPE_HASHMAP_H
#ifndef BALL_COMMON_H
# include <BALL/common.h>
#endif
#ifndef BALL_COMMON_HASH_H
# include <BALL/COMMON/hash.h>
#endif
#ifndef BALL_CONCEPT_FORWARDITERATOR_H
# include <BALL/CONCEPT/forwardIterator.h>
#endif
#ifndef BALL_CONCEPT_VISITOR_H
# include <BALL/CONCEPT/visitor.h>
#endif
#ifndef BALL_DATATYPE_FOREACH_H
# include <BALL/DATATYPE/forEach.h>
#endif
#ifndef BALL_CONCEPT_PREDICATE_H
# include <BALL/CONCEPT/predicate.h>
#endif
#ifndef BALL_CONCEPT_PROCESSOR_H
# include <BALL/CONCEPT/processor.h>
#endif
#ifndef BALL_COMMON_EXCEPTION_H
# include <BALL/COMMON/exception.h>
#endif
#include <utility>
#include <algorithm>
namespace BALL
{
/** Generic Hash Map Class.
\ingroup GenericHash
*/
template <class Key, class T>
class HashMap
{
public:
/**
*/
typedef ::std::pair<Key, T> ValueType;
/**
*/
typedef Key KeyType;
/**
*/
typedef ::std::pair<Key, T>* PointerType;
// --- EXTERNAL ITERATORS
struct Node
{
Node* next;
ValueType value;
Node(const ValueType& my_value, const Node* my_next)
throw()
: next(const_cast<Node*>(my_next)),
value(const_cast<ValueType&>(my_value))
{
}
};
typedef Node* IteratorPosition;
class IteratorTraits_
{
friend class HashMap<Key, T>;
public:
IteratorTraits_()
throw()
: bound_(0),
position_(0),
bucket_(0)
{
}
IteratorTraits_(const HashMap& hash_map)
throw()
: bound_(const_cast<HashMap*>(&hash_map)),
position_(0),
bucket_(0)
{
}
IteratorTraits_(const IteratorTraits_& traits)
throw()
: bound_(traits.bound_),
position_(traits.position_),
bucket_(traits.bucket_)
{
}
const IteratorTraits_& operator = (const IteratorTraits_& traits)
throw()
{
bound_ = traits.bound_;
position_ = traits.position_;
bucket_ = traits.bucket_;
return *this;
}
HashMap* getContainer()
throw()
{
return bound_;
}
const HashMap* getContainer() const
throw()
{
return bound_;
}
bool isSingular() const
throw()
{
return (bound_ == 0);
}
IteratorPosition& getPosition()
throw()
{
return position_;
}
const IteratorPosition& getPosition() const
throw()
{
return position_;
}
bool operator == (const IteratorTraits_& traits) const
throw()
{
return (position_ == traits.position_);
}
bool operator != (const IteratorTraits_& traits) const
throw()
{
return (position_ != traits.position_);
}
bool isValid() const
throw()
{
return ((bound_ != 0) && (position_ != 0) && (bucket_ < (Position)bound_->bucket_.size()));
}
void invalidate()
throw()
{
bound_ = 0;
position_ = 0;
bucket_ = INVALID_POSITION;
}
void toBegin()
throw()
{
for (bucket_ = 0; bucket_ < (Position)bound_->bucket_.size(); ++bucket_)
{
position_ = bound_->bucket_[bucket_];
if (position_ != 0)
{
return;
}
}
}
bool isBegin() const
throw()
{
for (Position bucket = 0; bucket < (Position)bound_->bucket_.size(); ++bucket)
{
if (bound_->bucket_[bucket_] != 0)
{
if (position_ == bound_->bucket_[bucket_])
{
return true;
}
else
{
return false;
}
}
}
return false;
}
void toEnd()
throw()
{
position_ = 0;
}
bool isEnd() const
throw()
{
return (position_ == 0);
}
ValueType& getData()
throw()
{
return position_->value;
}
const ValueType& getData() const
throw()
{
return position_->value;
}
void forward()
throw()
{
position_ = position_->next;
if (position_ != 0)
{
return;
}
for (++bucket_; bucket_ < (Position)bound_->bucket_.size(); ++bucket_)
{
position_ = bound_->bucket_[bucket_];
if (position_ != 0)
{
return;
}
}
}
protected:
HashMap* bound_;
IteratorPosition position_;
Position bucket_;
};
/** @name Enums and Constants
*/
//@{
enum
{
/// Initial capacity of the empty hash map
INITIAL_CAPACITY = 4,
/// Initial number of buckets of the empty hash map
INITIAL_NUMBER_OF_BUCKETS = 3
};
//@}
/** @name Exceptions
*/
//@{
/** IllegalKey exception
*/
class IllegalKey
: public Exception::GeneralException
{
public:
IllegalKey(const char* file, int line)
: Exception::GeneralException(file, line) {}
};
//@}
/** @name Type definitions
*/
//@{
/**
*/
typedef
ForwardIterator<HashMap<Key, T>, ValueType, PointerType, IteratorTraits_>
Iterator;
/**
*/
typedef
ConstForwardIterator <HashMap<Key, T>, ValueType, PointerType, IteratorTraits_>
ConstIterator;
//@}
/** @name Constructors and Destructors
*/
//@{
BALL_CREATE(HashMap)
/** Default constructor.
Create a new and empty hash map.
@param initial_capacity the capacity of the hash map
@param number_of_buckets the number of buckets to create
*/
HashMap(Size initial_capacity = INITIAL_CAPACITY, Size number_of_buckets = INITIAL_NUMBER_OF_BUCKETS)
throw();
/** Copy Constructor.
*/
HashMap(const HashMap& hash_map) throw();
/** Destructor.
*/
BALL_INLINE
virtual ~HashMap() throw()
{
destroy();
deleteBuckets_();
}
/** Clear the hash map.
Remove all nodes from all buckets.
The capacity and the number of buckets remain unchanged.
*/
virtual void clear() throw();
/** Clear the hash map.
Remove all nodes from all buckets.
The capacity and the number of buckets remain unchanged.
Simply calls clear.
*/
void destroy() throw();
//@}
/** @name Assignment
*/
//@{
/** Assignment from another hash map.
@param hash_map the hash map to assign from
*/
void set(const HashMap& hash_map) throw();
/** Assignment operator.
Assign the contents of a hash map to another.
@param hash_map the hash map to assign from
*/
const HashMap& operator = (const HashMap& hash_map) throw();
/** Assign the contents of this hash map to another map.
*/
void get(HashMap& hash_map) const throw();
/** Swap the contents of two hash maps.
*/
void swap(HashMap& hash_map) throw();
//@}
/** @name Accessors
*/
//@{
/** Return the number of buckets
*/
Size getBucketSize() const throw();
/** Return the capcacity of the hash map.
*/
Size getCapacity() const throw();
/** Return the number of entries in the map.
*/
Size getSize() const throw();
/** Return the number of entries in the map.
*/
Size size() const throw();
/** Find the element whose key is <tt>key</tt>.
*/
Iterator find(const Key& key) throw();
/** Find the element whose key is <tt>key</tt>.
*/
ConstIterator find(const Key& key) const throw();
/** Return a mutable reference to the element whose key is <tt>key</tt>.
If an element with the key <tt>key</tt> does not exist, it is inserted.
@param key the key
*/
T& operator [] (const Key& key) throw();
/** Return a constant reference to the element whose key is <tt>key</tt>.
@exception IllegalKey if the given key does not exist
@param key the key
*/
const T& operator [] (const Key& key) const
throw(typename HashMap<Key, T>::IllegalKey);
/** Insert a new entry into the hash map.
*/
::std::pair<Iterator, bool> insert(const ValueType& entry) throw();
/** Insert a new entry into the hash map.
For STL compatibility. The value of <tt>pos</tt> is ignored.
*/
Iterator insert(Iterator pos, const ValueType& entry) throw();
/** Erase element with key <tt>key</tt>.
@return Size the number of elements erased (0 or 1)
*/
Size erase(const Key& key) throw();
/** Erase element at a given position.
@param pos an iterator pointing to the element to delete
*/
void erase(Iterator pos) throw(Exception::IncompatibleIterators, Exception::InvalidIterator);
/** Erase a range of elements.
Erase all elements in the range <tt>first - last</tt>.
*/
void erase(Iterator first, Iterator last) throw(Exception::IncompatibleIterators);
//@}
/** @name Miscellaneous
*/
//@{
/** Host a visitor for all map entries.
*/
void host(Visitor<HashMap<Key, T> >& visitor) throw();
//@}
/** @name Predicates
*/
//@{
/** Test whether the map contains the given key.
*/
bool has(const Key& key) const throw();
/** Test whether the map is empty.
*/
bool isEmpty() const throw();
/** Compare two hash maps.
*/
bool operator == (const HashMap& hash_map) const throw();
/** Compare two hash maps.
*/
bool operator != (const HashMap& hash_map) const throw();
//@}
/** @name Debugging and Diagnostics
*/
//@{
/** Return true if the hash map is consistent.
Condition: the number of entries in all buckets has to be equal the
stored number of entries (getSize()).
*/
bool isValid() const throw();
/** Dump the constent of this instance to an ostream.
*/
virtual void dump(::std::ostream& s = ::std::cout, Size depth = 0) const throw();
//@}
/** @name Iternal iterators
*/
//@{
/** Apply a processor to the hashmap.
@return true if the processor could be applied.
*/
bool apply(UnaryProcessor<ValueType>& processor) throw();
//@}
friend class IteratorTraits_;
BALL_INLINE
Iterator begin()
throw()
{
return Iterator::begin(*this);
}
BALL_INLINE
Iterator end()
throw()
{
return Iterator::end(*this);
}
BALL_INLINE
ConstIterator begin() const
throw()
{
return ConstIterator::begin(*this);
}
BALL_INLINE
ConstIterator end() const
throw()
{
return ConstIterator::end(*this);
}
protected:
virtual Node* newNode_(const ValueType& value, Node* next) const throw();
virtual void deleteNode_(Node* node) const throw();
virtual HashIndex hash(const Key& key) const throw();
virtual bool needRehashing_() const throw();
virtual void rehash() throw();
void deleteBuckets_() throw();
HashIndex hash_(const Key& key) const throw();
void rehash_() throw();
/** @name Attributes
*/
//@{
/** The number of entries in the map
*/
Size size_;
/** The maximum number of entries before a resize operation is required
*/
Size capacity_;
/** Buckets are stored as a vector of linked lists of Nodes
*/
vector<Node*> bucket_;
//@}
};
template <class Key, class T>
BALL_INLINE
HashMap<Key, T>::HashMap(Size initial_capacity, Size number_of_buckets)
throw()
: size_(0),
capacity_(initial_capacity),
bucket_(number_of_buckets)
{
for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket)
{
bucket_[bucket] = 0;
}
}
template <class Key, class T>
BALL_INLINE
HashMap<Key, T>::HashMap(const HashMap& hash_map)
throw()
: size_(hash_map.size_),
capacity_(hash_map.capacity_),
bucket_((Size)hash_map.bucket_.size())
{
Node* node = 0;
for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket)
{
bucket_[bucket] = 0;
for (node = hash_map.bucket_[bucket]; node != 0; node = node->next)
{
bucket_[bucket] = newNode_(node->value, bucket_[bucket]);
}
}
}
template <class Key, class T>
void HashMap<Key, T>::clear()
throw()
{
Node* node = 0;
Node* next_node = 0;
for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket)
{
for (node = bucket_[bucket]; node != 0; node = next_node)
{
next_node = node->next;
deleteNode_(node);
}
bucket_[bucket] = 0;
}
size_ = 0;
}
template <class Key, class T>
BALL_INLINE
void HashMap<Key, T>::destroy()
throw()
{
clear();
}
template <class Key, class T>
void HashMap<Key, T>::set(const HashMap& hash_map)
throw()
{
if (&hash_map == this)
{
return;
}
destroy();
deleteBuckets_();
size_ = hash_map.size_;
capacity_ = hash_map.capacity_;
bucket_.resize(hash_map.bucket_.size());
Node* node = 0;
for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket)
{
bucket_[bucket] = 0;
for (node = hash_map.bucket_[bucket]; node != 0; node = node->next)
{
bucket_[bucket] = newNode_(node->value, bucket_[bucket]);
}
}
}
template <class Key, class T>
BALL_INLINE
const HashMap<Key, T>& HashMap<Key, T>::operator = (const HashMap& hash_map)
throw()
{
set(hash_map);
return *this;
}
template <class Key, class T>
BALL_INLINE
void HashMap<Key, T>::get(HashMap& hash_map) const
throw()
{
hash_map.set(*this);
}
template <class Key, class T>
BALL_INLINE
void HashMap<Key, T>::swap(HashMap& hash_map)
throw()
{
::std::swap(size_, hash_map.size_);
::std::swap(capacity_, hash_map.capacity_);
::std::swap(bucket_, hash_map.bucket_);
}
template <class Key, class T>
BALL_INLINE
Size HashMap<Key, T>::getBucketSize() const
throw()
{
return (Size)bucket_.size();
}
template <class Key, class T>
BALL_INLINE
Size HashMap<Key, T>::getCapacity() const
throw()
{
return capacity_;
}
template <class Key, class T>
BALL_INLINE
Size HashMap<Key, T>::getSize() const
throw()
{
return size_;
}
template <class Key, class T>
BALL_INLINE
Size HashMap<Key, T>::size() const
throw()
{
return size_;
}
template <class Key, class T>
typename HashMap<Key, T>::Iterator HashMap<Key, T>::find(const Key& key)
throw()
{
Iterator it = end();
HashIndex bucket = hash_(key);
Node* node_ptr = bucket_[hash_(key)];
for (; node_ptr != 0; node_ptr = node_ptr->next)
{
if (node_ptr->value.first == key)
{
it.getTraits().bound_ = this;
it.getTraits().position_ = node_ptr;
it.getTraits().bucket_ = bucket;
break;
}
}
return it;
}
template <class Key, class T>
BALL_INLINE
typename HashMap<Key, T>::ConstIterator HashMap<Key, T>::find(const Key& key) const
throw()
{
return (const_cast<HashMap*>(this))->find(key);
}
template <class Key, class T>
BALL_INLINE
T& HashMap<Key, T>::operator [] (const Key& key)
throw()
{
Iterator it = find(key);
if (it == end())
{
T value;
std::pair<Iterator, bool> result = insert(ValueType(key, value));
it = result.first;
}
return it->second;
}
template <class Key, class T>
BALL_INLINE
const T& HashMap<Key, T>::operator [] (const Key& key) const
throw(typename HashMap<Key, T>::IllegalKey)
{
ConstIterator it = find(key);
if (it == end())
{
throw IllegalKey(__FILE__, __LINE__);
}
else
{
return it->second;
}
}
template <class Key, class T>
::std::pair<typename HashMap<Key, T>::Iterator, bool> HashMap<Key, T>::insert
(const ValueType& item) throw()
{
Iterator it = find(item.first);
if (it == end())
{
if (needRehashing_() == true)
{
rehash_();
}
HashIndex bucket = hash_(item.first);
Node* node_ptr = bucket_[bucket];
bucket_[bucket] = newNode_(item, node_ptr);
++size_;
it.getTraits().bound_ = this;
it.getTraits().position_ = bucket_[bucket];
it.getTraits().bucket_ = bucket;
return ::std::pair<Iterator, bool>(it, true);
}
else
{
// replace the existing value
it->second = item.second;
return ::std::pair<Iterator, bool>(it, false);
}
}
template <class Key, class T>
BALL_INLINE
typename HashMap<Key, T>::Iterator HashMap<Key, T>::insert
(typename HashMap<Key, T>::Iterator /* pos */, const ValueType& entry) throw()
{
return insert(entry).first;
}
template <class Key, class T>
Size HashMap<Key, T>::erase(const Key& key)
throw()
{
Node* previous = 0;
HashIndex bucket = hash_(key);
Node* node_ptr = bucket_[bucket];
while (node_ptr != 0 && node_ptr->value.first != key)
{
previous = node_ptr;
node_ptr = node_ptr->next;
}
if (node_ptr == 0)
{
return false;
}
if (node_ptr == bucket_[bucket])
{
bucket_[bucket] = node_ptr->next;
}
else
{
previous->next = node_ptr->next;
}
deleteNode_(node_ptr);
--size_;
return true;
}
template <class Key, class T>
void HashMap<Key, T>::erase(Iterator pos)
throw(Exception::IncompatibleIterators, Exception::InvalidIterator)
{
if (pos.getTraits().bound_ != this)
{
throw Exception::IncompatibleIterators(__FILE__, __LINE__);
}
if ((pos == end()) || (size_ == 0))
{
return;
}
if (pos.getTraits().position_ == bucket_[pos.getTraits().bucket_])
{
bucket_[pos.getTraits().bucket_] = pos.getTraits().position_->next;
}
else
{
// walk over all nodes in this bucket and identify the predecessor
// of the node refered to by the iterator pos
Node* prev = bucket_[pos.getTraits().bucket_];
for (; (prev != 0) && (prev->next != pos.getTraits().position_); prev = prev->next);
if (prev != 0)
{
// remove the node and reconnect the list
prev->next = pos.getTraits().position_->next;
}
else
{
throw Exception::InvalidIterator(__FILE__, __LINE__);
}
}
// delete the node and decrement the set size
deleteNode_(pos.getTraits().position_);
--size_;
}
template <class Key, class T>
void HashMap<Key, T>::erase(Iterator f, Iterator l)
throw(Exception::IncompatibleIterators)
{
if (f.getTraits().bound_ != this || l.getTraits().bound_ != this)
{
throw Exception::IncompatibleIterators(__FILE__, __LINE__);
}
if (f == end())
{
return;
}
Position last_bucket = l.getTraits().bucket_;
if (l == end())
{
last_bucket = (Position)bucket_.size() - 1;
}
if (f.getTraits().bucket_ > last_bucket)
{
// empty range - l < f
return;
}
// count the deleted entries to correct the set size
Size no_deletions = 0;
Position bucket = f.getTraits().bucket_;
for (; bucket <= last_bucket; bucket++)
{
if (bucket_[bucket] == 0)
{
// skip all empty buckets
continue;
}
if ((bucket == f.getTraits().bucket_) && (bucket_[bucket] != f.getTraits().position_))
{
// find the predecessor of f
Node* n = bucket_[bucket];
Node* next;
for (; (n->next != f.getTraits().position_) && (n->next != 0); n = n->next);
if (bucket == last_bucket)
{
// delete everything from f to l in this bucket
next = n->next;
n->next = l.getTraits().position_;
for (n = next; (n != 0) && (n != l.getTraits().position_); n = next)
{
next = n->next;
deleteNode_(n);
no_deletions++;
}
}
else
{
// delete everything from f to the end in this bucket
if (n != 0)
{
// mark the end of the list
next = n->next;
n->next = 0;
// delete all remaining nodes
for (n = next; n != 0; n = next)
{
next = n->next;
deleteNode_(n);
no_deletions++;
}
}
}
}
// if the current bucket lies between the first and the last bucket...
else if (bucket < last_bucket)
{
// ...delete the whole bucket
Node* next;
for (Node* n = bucket_[bucket]; n != 0; n = next)
{
next = n->next;
deleteNode_(n);
no_deletions++;
}
bucket_[bucket] = 0;
}
else if (bucket == last_bucket)
{
// we delete everything in this bucket up to the iterator l
// find the predecessor of l
Node* n = bucket_[bucket];
Node* next;
for (; (n != 0) && (n != l.getTraits().position_); n = next)
{
next = n->next;
deleteNode_(n);
no_deletions++;
}
bucket_[bucket] = l.getTraits().position_;
}
}
// correct the set size
size_ -= no_deletions;
}
template <class Key, class T>
bool HashMap<Key, T>::apply(UnaryProcessor<ValueType>& processor)
throw()
{
if (processor.start() == false)
{
return false;
}
Processor::Result result;
Iterator it = begin();
while (it != end())
{
result = processor(*it);
if (result <= Processor::BREAK)
{
return (result == Processor::BREAK);
}
it++;
}
return processor.finish();
}
template <class Key, class T>
void HashMap<Key, T>::host(Visitor<HashMap<Key, T> >& visitor)
throw()
{
visitor.visit(*this);
}
template <class Key, class T>
BALL_INLINE
bool HashMap<Key, T>::has(const Key& key) const
throw()
{
return (find(key) != end());
}
template <class Key, class T>
BALL_INLINE
bool HashMap<Key, T>::isEmpty() const
throw()
{
return (size_ == 0);
}
template <class Key, class T>
bool HashMap<Key, T>::operator == (const HashMap& hash_map) const
throw()
{
if (size_ != hash_map.size_)
{
return false;
}
for (ConstIterator it(begin()); it != end(); ++it)
{
ConstIterator hash_map_it(hash_map.find(it->first));
if ((hash_map_it == hash_map.end()) || (hash_map_it->second != it->second))
{
return false;
}
}
return true;
}
template <class Key, class T>
BALL_INLINE
bool HashMap<Key, T>::operator != (const HashMap& hash_map) const
throw()
{
return !(*this == hash_map);
}
template <class Key, class T>
bool HashMap<Key, T>::isValid() const
throw()
{
Size size = 0;
Node* node = 0;
for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket)
{
for (node = bucket_[bucket]; node != 0; node = node->next)
{
++size;
if (node->next == 0)
{
break;
}
}
}
return (size_ == size);
}
template <class Key, class T>
void HashMap<Key, T>::dump(::std::ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_DEPTH(s, depth);
s << " size: " << getSize() << ::std::endl;
BALL_DUMP_DEPTH(s, depth);
s << " bucket size: " << getBucketSize() << ::std::endl;
BALL_DUMP_DEPTH(s, depth);
s << " capacity: " << getCapacity() << ::std::endl;
BALL_DUMP_DEPTH(s, depth);
if (bucket_.size() != 0)
{
s << " load factor: " << (float)size_ / (float)bucket_.size() << ::std::endl;
}
for (Position bucket = 0; bucket < (Position)bucket_.size(); ++bucket)
{
BALL_DUMP_DEPTH(s, depth);
s << " bucket " << bucket << " (" << (void*)bucket_[bucket] << "):" << ::std::endl;
}
BALL_DUMP_STREAM_SUFFIX(s);
}
template <class Key, class T>
BALL_INLINE
HashIndex HashMap<Key, T>::hash(const Key& key) const
throw()
{
return Hash(key);
}
template <class Key, class T>
BALL_INLINE
void HashMap<Key, T>::rehash()
throw()
{
capacity_ = (Size)getNextPrime((Size)bucket_.size() * 2);
}
template <class Key, class T>
void HashMap<Key, T>::deleteBuckets_()
throw()
{
Node* node = 0;
Node* next_node = 0;
for (Position i = 0; i < (Position)bucket_.size(); i++)
{
node = bucket_[i];
while (node != 0)
{
next_node = node->next;
deleteNode_(node);
node = next_node;
}
bucket_[i] = 0;
}
}
template <class Key, class T>
BALL_INLINE
typename HashMap<Key, T>::Node* HashMap<Key, T>::newNode_
(const ValueType& value, typename HashMap<Key, T>::Node* next) const
throw()
{
return new Node(value, next);
}
template <class Key, class T>
BALL_INLINE
void HashMap<Key, T>::deleteNode_(typename HashMap<Key, T>::Node* node) const
throw()
{
delete node;
}
template <class Key, class T>
BALL_INLINE
bool HashMap<Key, T>::needRehashing_() const
throw()
{
return (size_ >= capacity_);
}
template <class Key, class T>
BALL_INLINE
HashIndex HashMap<Key, T>::hash_(const Key& key) const
throw()
{
return (HashIndex)(hash(key) % bucket_.size());
}
template <class Key, class T>
void HashMap<Key, T>::rehash_()
throw()
{
// calculate the new number of buckets (in capacity_)
rehash();
// save the old contents
vector<Node*> old_buckets(bucket_);
// resize the bucket vector and initialize it with zero
bucket_.clear();
bucket_.resize(capacity_);
Position i;
for (i = 0; i < capacity_; i++)
{
bucket_[i] = 0;
}
// rehash the old contents into the new buckets
Node* node;
Node* next_node;
for (Position i = 0; i < (Position)old_buckets.size(); ++i)
{
for (node = old_buckets[i]; node != 0; node = next_node)
{
next_node = node->next;
Position new_bucket = (Position)hash_(node->value.first);
node->next = bucket_[new_bucket];
bucket_[new_bucket] = node;
}
}
}
} // namespace BALL
#endif // BALL_DATATYPE_HASHMAP_H
| 19.425649 | 103 | 0.611908 |
11f9eebfa7ca7b1192de37ff8d0a52cc036cfe1c | 267 | h | C | error.h | johenglisch/fps-tester | ddac0d56a6a5a6ce1e230abb687da558eec7339d | [
"MIT"
] | null | null | null | error.h | johenglisch/fps-tester | ddac0d56a6a5a6ce1e230abb687da558eec7339d | [
"MIT"
] | null | null | null | error.h | johenglisch/fps-tester | ddac0d56a6a5a6ce1e230abb687da558eec7339d | [
"MIT"
] | null | null | null | #ifndef ERROR_H_
#define ERROR_H_
#include <stdio.h>
typedef enum { SUCCESS, FAILURE } result;
#define warn(msg) fprintf(stderr, "[%s:%d]: %s\n", __FILE__, __LINE__, msg)
#define goto_fail(msg) {warn(msg); goto fail;}
#define MEMORY_ERROR "Out of memory"
#endif
| 19.071429 | 75 | 0.70412 |
f560b3e3386f978043c00af9fbe49d74b3a4c5ef | 3,125 | h | C | include/object.h | fishilico/funguloids | f96ecc6a3197da355cbb5d3b822a23756b803d88 | [
"Zlib"
] | 2 | 2016-08-10T10:35:03.000Z | 2021-05-23T17:47:52.000Z | include/object.h | fishilico/funguloids | f96ecc6a3197da355cbb5d3b822a23756b803d88 | [
"Zlib"
] | 2 | 2018-10-18T12:30:49.000Z | 2018-10-21T10:17:39.000Z | include/object.h | fishilico/funguloids | f96ecc6a3197da355cbb5d3b822a23756b803d88 | [
"Zlib"
] | 1 | 2018-10-18T12:01:39.000Z | 2018-10-18T12:01:39.000Z | //****************************************************************************
// "Those Funny Funguloids!"
// http://funguloids.sourceforge.net
// Copyright (c) 2006-2007, Mika Halttunen
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the
// use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software in a
// product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
//***************************************************************************/
#ifndef OBJECT_H
#define OBJECT_H
#include <Ogre.h>
using namespace Ogre;
// Basic object type
const int OTYPE_BASIC = 0;
// Object
class Object {
protected:
Entity *mEntity; // Object entity
SceneNode *mNode; // Object node
AnimationState *mAnimState; // Object animation
String mName; // Object name
SceneManager *mSceneMgr; // SceneManager
Real mRadius; // Object radius
int mType; // Object type
public:
Object(const String &name, SceneManager *sceneMgr, const String &mesh, const Vector3 &pos, bool managed=true);
virtual ~Object();
int getType() const { return mType; }
void setAnim(const String name) {
mAnimState = mEntity->getAnimationState(name);
mAnimState->setEnabled(true);
mAnimState->setLoop(true);
}
void setScale(Real x, Real y, Real z) {
mNode->setScale(x, y, z);
setRadius(mEntity->getBoundingRadius());
}
void setRadius(Real rad) { mRadius = rad; }
Real getRadius() const { return mRadius; }
void updateAnim(Real time) {
if(mAnimState)
mAnimState->addTime(time);
}
Entity *getEntity() const {
return mEntity;
}
SceneNode *getSceneNode() const {
return mNode;
}
const String getName() const {
return mName;
}
Vector3 getPosition() const {
return mNode->getPosition();
}
void setPosition(const Vector3 &pos) {
mNode->setPosition(pos);
}
void yaw(Radian angle) {
mNode->yaw(angle);
}
void pitch(Radian angle) {
mNode->pitch(angle);
}
void translate(Real x, Real y, Real z) {
mNode->translate(x, y, z);
}
void translate(const Vector3 &trans) {
mNode->translate(trans);
}
Vector3 getDir() const {
return mNode->getOrientation() * Vector3::UNIT_Y;
}
void setDir(const Vector3 &dir) {
mNode->setDirection(-dir, SceneNode::TS_WORLD, Vector3::NEGATIVE_UNIT_Y);
}
void setCastShadows(bool cast) {
mEntity->setCastShadows(cast);
}
void setVisible(bool v) { mEntity->setVisible(v); }
bool getVisible() const { return mEntity->isVisible(); }
};
#endif
| 24.606299 | 111 | 0.67104 |
676f4cb0cd6e813a9c05651dd0288c270bbf53ab | 760 | h | C | src/Util/UpgradeOrTechType.h | bmnielsen/Stardust | 343e0c123f85e080e5d3a744d1cc47b3adfe9efd | [
"MIT"
] | 15 | 2020-10-01T07:04:33.000Z | 2022-03-20T12:41:25.000Z | src/Util/UpgradeOrTechType.h | bmnielsen/Stardust | 343e0c123f85e080e5d3a744d1cc47b3adfe9efd | [
"MIT"
] | null | null | null | src/Util/UpgradeOrTechType.h | bmnielsen/Stardust | 343e0c123f85e080e5d3a744d1cc47b3adfe9efd | [
"MIT"
] | null | null | null | #pragma once
#include "Common.h"
class UpgradeOrTechType
{
public:
BWAPI::UpgradeType upgradeType;
BWAPI::TechType techType;
UpgradeOrTechType(BWAPI::UpgradeType upgradeType) : upgradeType(upgradeType), techType(BWAPI::TechTypes::None) {}
UpgradeOrTechType(BWAPI::TechType techType) : upgradeType(BWAPI::UpgradeTypes::None), techType(techType) {}
bool isTechType() const { return techType != BWAPI::TechTypes::None; }
int mineralPrice() const;
int gasPrice() const;
int upgradeOrResearchTime() const;
BWAPI::UnitType whatUpgradesOrResearches() const;
int currentLevel() const;
bool operator==(const UpgradeOrTechType &other);
};
std::ostream &operator<<(std::ostream &os, const UpgradeOrTechType &type);
| 24.516129 | 117 | 0.725 |
407fc2fa33b0ed27cce4fb242083025c749decab | 1,923 | h | C | src/core/scripted_controller/scripted_controller_component.h | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 3 | 2015-02-22T20:34:28.000Z | 2020-03-04T08:55:25.000Z | src/core/scripted_controller/scripted_controller_component.h | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 22 | 2015-12-13T16:29:40.000Z | 2017-03-04T15:45:44.000Z | src/core/scripted_controller/scripted_controller_component.h | Reaping2/Reaping2 | 0d4c988c99413e50cc474f6206cf64176eeec95d | [
"MIT"
] | 14 | 2015-11-23T21:25:09.000Z | 2020-07-17T17:03:23.000Z | #ifndef INCLUDED_CORE_SCRIPTED_CONTROLLER_COMPONENT_H
#define INCLUDED_CORE_SCRIPTED_CONTROLLER_COMPONENT_H
#include "core/controller_component.h"
#include "core/property_loader.h"
#include "platform/export.h"
#include <vector>
#include "state.h"
#include <boost/serialization/map.hpp>
namespace scriptedcontroller {
class ScriptedControllerComponent : public ControllerComponent
{
public:
ScriptedControllerComponent();
typedef std::map<int32_t, State> States_t;
virtual void SetStates( States_t states );
virtual States_t& GetStates();
virtual void SetStateIdentifier( int32_t StateIdentifier );
virtual int32_t GetStateIdentifier() const;
virtual Opt<State> GetState();
protected:
States_t mStates;
int32_t mStateIdentifier;
public:
friend class ::boost::serialization::access;
template<class Archive>
void serialize( Archive& ar, const unsigned int version );
};
template<class Archive>
void ScriptedControllerComponent::serialize(Archive& ar, const unsigned int version)
{
ar& boost::serialization::base_object<ControllerComponent>(*this);
// scripted controller is not for clients
// if for some reason this needs to be serialized acts transitions etc need to be exported
// ar& mStates;
// ar& mStateIdentifier;
}
class ScriptedControllerComponentLoader : public ComponentLoader<ScriptedControllerComponent>
{
public:
DEFINE_COMPONENT_LOADER_BASE( ScriptedControllerComponentLoader )
ScriptedControllerComponentLoader();
virtual void BindValues();
};
} // namespace scriptedcontroller
REAPING2_CLASS_EXPORT_KEY2( scriptedcontroller__ScriptedControllerComponent, scriptedcontroller::ScriptedControllerComponent, "scripted_controller_component" );
#endif//INCLUDED_CORE_SCRIPTED_CONTROLLER_COMPONENT_H
//command: "classgenerator.exe" -g "component" -p "controller_component" -c "scripted_controller_component" -m "States_t-states"
| 34.339286 | 160 | 0.790952 |
734f1d5b0d7b90a22e77655d823896183a69c270 | 562 | h | C | V3.1/src/no/eos/kernel/medium/0ctr.h | ruibailin/rblos | 63107905b13bbf486584ccf3fbeba4d6444cdba5 | [
"Apache-2.0"
] | null | null | null | V3.1/src/no/eos/kernel/medium/0ctr.h | ruibailin/rblos | 63107905b13bbf486584ccf3fbeba4d6444cdba5 | [
"Apache-2.0"
] | null | null | null | V3.1/src/no/eos/kernel/medium/0ctr.h | ruibailin/rblos | 63107905b13bbf486584ccf3fbeba4d6444cdba5 | [
"Apache-2.0"
] | null | null | null |
/*------------------------------------
* 0ctr.h
* Create: 2021-10-16
* Author: Steve Rui
*------------------------------------
* Record:
*
*
*
*
*------------------------------------
*/
#ifndef EOS_KERNEL_MEDIUM_0CTR_H_
#define EOS_KERNEL_MEDIUM_0CTR_H_
#include "../0ctr.h"
#if EOS_MEDIUM_MODE
/*================================================================*/
#define MAX_MSG_NUM 240
#define MAX_PAT_NUM 120
#define MAX_TCB_NUM 360
/*================================================================*/
#endif
#endif
/* end of 0ctr.h */
| 19.37931 | 68 | 0.373665 |
488a22e35f960664449a73a185a12679433bf285 | 616 | h | C | Example/DYCircleImage/ZYBaseUtilsFramework.framework/Headers/ZYDataDefine.h | xufengbj/DYCircleImage | e88a57aeec2ca5850bc9bed0f484bc57a2e22681 | [
"MIT"
] | null | null | null | Example/DYCircleImage/ZYBaseUtilsFramework.framework/Headers/ZYDataDefine.h | xufengbj/DYCircleImage | e88a57aeec2ca5850bc9bed0f484bc57a2e22681 | [
"MIT"
] | null | null | null | Example/DYCircleImage/ZYBaseUtilsFramework.framework/Headers/ZYDataDefine.h | xufengbj/DYCircleImage | e88a57aeec2ca5850bc9bed0f484bc57a2e22681 | [
"MIT"
] | null | null | null | //
// ZYDataDefine.h
// GChat
//
// Created by 许锋 on 2020/6/2.
// Copyright © 2020 zhangmeng. All rights reserved.
//
// 描述:主要声明一些项目中经常用到的数据类型宏定义
// 1: 常见数字,比如分割线大小 0.5,一行文字高度15等
// 2: 自定义基础类型数据 KData(d)
// 3: 网络请求常用状态码
#ifndef ZYDataDefine_h
#define ZYDataDefine_h
#define KData_Min 0.5
#define KData_2 2
#define KData_10 10
#define KData_15 15
#define KData_20 20
#define KData_44 44
#define KData(d) d
//请求成功码
#define KSuccessCode 200
//请求成功状态
#define KSuccessStatus 0
//请求错误码
#define KErrorCode 401
#endif /* ZYDataDefine_h */
| 18.117647 | 52 | 0.636364 |
5e99039fc9aded6ebfc8286491a7a2ba36e2f8ad | 28,931 | c | C | Sources/C/io.c | dowobeha/Foma | 4cca7f9601b52eee35b06289f71d477b075a9d23 | [
"Apache-2.0"
] | null | null | null | Sources/C/io.c | dowobeha/Foma | 4cca7f9601b52eee35b06289f71d477b075a9d23 | [
"Apache-2.0"
] | null | null | null | Sources/C/io.c | dowobeha/Foma | 4cca7f9601b52eee35b06289f71d477b075a9d23 | [
"Apache-2.0"
] | null | null | null | /* Foma: a finite-state toolkit and library. */
/* Copyright © 2008-2015 Mans Hulden */
/* This file is part of foma. */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include "foma.h"
#include "zlib.h"
#define TYPE_TRANSITION 1
#define TYPE_SYMBOL 2
#define TYPE_FINAL 3
#define TYPE_PROPERTY 4
#define TYPE_END 5
#define TYPE_ERROR 6
#define READ_BUF_SIZE 4096
struct binaryline {
int type;
int state;
int in;
int target;
int out;
int symbol;
char *name;
char *value;
};
extern char *g_att_epsilon;
struct io_buf_handle {
char *io_buf;
char *io_buf_ptr;
};
struct io_buf_handle *io_init();
void io_free(struct io_buf_handle *iobh);
static int io_gets(struct io_buf_handle *iobh, char *target);
static size_t io_get_gz_file_size(char *filename);
static size_t io_get_file_size(char *filename);
static size_t io_get_regular_file_size(char *filename);
size_t io_gz_file_to_mem (struct io_buf_handle *iobh, char *filename);
int foma_net_print(struct fsm *net, gzFile outfile);
struct fsm *io_net_read(struct io_buf_handle *iobh, char **net_name);
static INLINE int explode_line (char *buf, int *values);
void escape_print(FILE *stream, char* string) {
int i;
if (strchr(string, '"') != NULL) {
for (i = 0; *(string+i) != '\0'; i++) {
if (*(string+i) == '"') {
fprintf(stream, "\\\"");
} else {
fputc(*(string+i), stream);
}
}
} else {
fprintf(stream, "%s", string);
}
}
int foma_write_prolog (struct fsm *net, char *filename) {
struct fsm_state *stateptr;
int i, *finals, *used_symbols, maxsigma;
FILE *out;
char *outstring, *instring, identifier[100];
if (filename == NULL) {
out = stdout;
} else {
if ((out = fopen(filename, "w")) == NULL) {
printf("Error writing to file '%s'. Using stdout.\n", filename);
out = stdout;
}
printf("Writing prolog to file '%s'.\n", filename);
}
fsm_count(net);
maxsigma = sigma_max(net->sigma);
used_symbols = xxcalloc(maxsigma+1,sizeof(int));
finals = xxmalloc(sizeof(int)*(net->statecount));
stateptr = net->states;
identifier[0] = '\0';
strcpy(identifier, net->name);
/* Print identifier */
fprintf(out, "%s%s%s", "network(",identifier,").\n");
for (i=0; (stateptr+i)->state_no != -1; i++) {
if ((stateptr+i)->final_state == 1) {
*(finals+((stateptr+i)->state_no)) = 1;
} else {
*(finals+((stateptr+i)->state_no)) = 0;
}
if ((stateptr+i)->in != -1) {
*(used_symbols+((stateptr+i)->in)) = 1;
}
if ((stateptr+i)->out != -1) {
*(used_symbols+((stateptr+i)->out)) = 1;
}
}
for (i = 3; i <= maxsigma; i++) {
if (*(used_symbols+i) == 0) {
instring = sigma_string(i, net->sigma);
if (strcmp(instring,"0") == 0) {
instring = "%0";
}
fprintf(out, "symbol(%s, \"", identifier);
escape_print(out, instring);
fprintf(out, "\").\n");
}
}
for (; stateptr->state_no != -1; stateptr++) {
if (stateptr->target == -1)
continue;
fprintf(out, "arc(%s, %i, %i, ", identifier, stateptr->state_no, stateptr->target);
if (stateptr->in == 0) instring = "0";
else if (stateptr->in == 1) instring = "?";
else if (stateptr->in == 2) instring = "?";
else instring = sigma_string(stateptr->in, net->sigma);
if (stateptr->out == 0) outstring = "0";
else if (stateptr->out == 1) outstring = "?";
else if (stateptr->out == 2) outstring = "?";
else outstring = sigma_string(stateptr->out, net->sigma);
if (strcmp(instring,"0") == 0 && stateptr->in != 0) instring = "%0";
if (strcmp(outstring,"0") == 0 && stateptr->out != 0) outstring = "%0";
if (strcmp(instring,"?") == 0 && stateptr->in > 2) instring = "%?";
if (strcmp(outstring,"?") == 0 && stateptr->in > 2) outstring = "%?";
/* Escape quotes */
if (net->arity == 2 && stateptr->in == IDENTITY && stateptr->out == IDENTITY) {
fprintf(out, "\"?\").\n");
}
else if (net->arity == 2 && stateptr->in == stateptr->out && stateptr->in != UNKNOWN) {
fprintf(out, "\"");
escape_print(out, instring);
fprintf(out, "\").\n");
}
else if (net->arity == 2) {
fprintf(out, "\"");
escape_print(out, instring);
fprintf(out, "\":\"");
escape_print(out, outstring);
fprintf(out, "\").\n");
}
else if (net->arity == 1) {
fprintf(out, "\"");
escape_print(out, instring);
fprintf(out, "\").\n");
}
}
for (i = 0; i < net->statecount; i++) {
if (*(finals+i)) {
fprintf(out, "final(%s, %i).\n", identifier, i);
}
}
if (filename != NULL) {
fclose(out);
}
xxfree(finals);
xxfree(used_symbols);
return 1;
}
struct fsm *read_att(char *filename) {
struct fsm_construct_handle *h;
struct fsm *net;
int i;
char inword[1024], delimiters[] = "\t", *tokens[6];
FILE *INFILE;
INFILE = fopen(filename, "r");
if (INFILE == NULL) {
return(NULL);
}
h = fsm_construct_init(filename);
while (fgets(inword, 1024, INFILE) != NULL) {
if (inword[strlen(inword)-1] == '\n') {
inword[strlen(inword)-1] = '\0';
}
tokens[0] = strtok(inword, delimiters);
i = 0;
if (tokens[0] != NULL) {
i = 1;
for ( ; ; ) {
tokens[i] = strtok(NULL, delimiters);
if (tokens[i] == NULL) {
break;
}
i++;
if (i == 6)
break;
}
}
if (i == 0) { continue; }
if (i >= 4) {
if (strcmp(tokens[2],g_att_epsilon) == 0)
tokens[2] = "@_EPSILON_SYMBOL_@";
if (strcmp(tokens[3],g_att_epsilon) == 0)
tokens[3] = "@_EPSILON_SYMBOL_@";
fsm_construct_add_arc(h, atoi(tokens[0]), atoi(tokens[1]), tokens[2], tokens[3]);
}
else if (i <= 3 && i > 0) {
fsm_construct_set_final(h,atoi(tokens[0]));
}
}
fsm_construct_set_initial(h,0);
fclose(INFILE);
net = fsm_construct_done(h);
fsm_count(net);
net = fsm_topsort(net);
return(net);
}
struct fsm *fsm_read_prolog (char *filename) {
char buf [1024], temp [1024], in [128], out[128], *temp_ptr, *temp_ptr2;
int arity, source, target, has_net;
struct fsm *outnet;
struct fsm_construct_handle *outh = NULL;
FILE *prolog_file;
has_net = 0;
prolog_file = fopen(filename, "r");
if (prolog_file == NULL) {
return NULL;
}
while (fgets(buf, 1023, prolog_file) != NULL) {
if (strstr(buf, "network(") == buf) {
/* Extract network name */
if (has_net == 1) {
perror("WARNING: prolog file contains multiple nets. Only returning the first one.\n");
break;
} else {
has_net = 1;
}
temp_ptr = strstr(buf, "network(")+8;
temp_ptr2 = strstr(buf, ").");
strncpy(temp, temp_ptr, (temp_ptr2 - temp_ptr));
temp[(temp_ptr2-temp_ptr)] = '\0';
/* Start network */
outh = fsm_construct_init(temp);
}
if (strstr(buf, "final(") == buf) {
temp_ptr = strstr(buf, " ");
temp_ptr++;
temp_ptr2 = strstr(temp_ptr, ").");
strncpy(temp, temp_ptr, (temp_ptr2 - temp_ptr));
temp[(temp_ptr2-temp_ptr)] = '\0';
fsm_construct_set_final(outh, atoi(temp));
}
if (strstr(buf, "symbol(") == buf) {
temp_ptr = strstr(buf, ", \"")+3;
temp_ptr2 = strstr(temp_ptr, "\").");
strncpy(temp, temp_ptr, (temp_ptr2 - temp_ptr));
temp[(temp_ptr2-temp_ptr)] = '\0';
if (strcmp(temp, "%0") == 0)
strcpy(temp, "0");
//printf("special: %s\n",temp);
if (fsm_construct_check_symbol(outh, temp) == -1) {
fsm_construct_add_symbol(outh, temp);
}
continue;
}
if (strstr(buf, "arc(") == buf) {
in[0] = '\0';
out[0] = '\0';
if (strstr(buf, "\":\"") == NULL || strstr(buf, ", \":\").") != NULL) {
arity = 1;
} else {
arity = 2;
}
/* Get source */
temp_ptr = strstr(buf, " ");
temp_ptr++;
temp_ptr2 = strstr(temp_ptr, ",");
strncpy(temp, temp_ptr, (temp_ptr2 - temp_ptr));
temp[(temp_ptr2-temp_ptr)] = '\0';
source = atoi(temp);
/* Get target */
temp_ptr = strstr(temp_ptr2, " ");
temp_ptr++;
temp_ptr2 = strstr(temp_ptr, ",");
strncpy(temp, temp_ptr, (temp_ptr2 - temp_ptr));
temp[(temp_ptr2-temp_ptr)] = '\0';
target = atoi(temp);
temp_ptr = strstr(temp_ptr2, "\"");
temp_ptr++;
if (arity == 2) {
temp_ptr2 = strstr(temp_ptr, "\":");
} else {
temp_ptr2 = strstr(temp_ptr, "\").");
}
strncpy(in, temp_ptr, (temp_ptr2 - temp_ptr));
in[(temp_ptr2 - temp_ptr)] = '\0';
if (arity == 2) {
temp_ptr = strstr(temp_ptr2, ":\"");
temp_ptr += 2;
temp_ptr2 = strstr(temp_ptr, "\").");
strncpy(out, temp_ptr, (temp_ptr2 - temp_ptr));
out[(temp_ptr2 - temp_ptr)] = '\0';
}
if (arity == 1 && (strcmp(in, "?") == 0)) {
strcpy(in,"@_IDENTITY_SYMBOL_@");
}
if (arity == 2 && (strcmp(in, "?") == 0)) {
strcpy(in,"@_UNKNOWN_SYMBOL_@");
}
if (arity == 2 && (strcmp(out, "?") == 0)) {
strcpy(out,"@_UNKNOWN_SYMBOL_@");
}
if (strcmp(in, "0") == 0) {
strcpy(in,"@_EPSILON_SYMBOL_@");
}
if (strcmp(out, "0") == 0) {
strcpy(out,"@_EPSILON_SYMBOL_@");
}
if (strcmp(in, "%0") == 0) {
strcpy(in,"0");
}
if (strcmp(out, "%0") == 0) {
strcpy(out,"0");
}
if (strcmp(in, "%?") == 0) {
strcpy(in,"?");
}
if (strcmp(out, "%?") == 0) {
strcpy(out,"?");
}
if (arity == 1) {
fsm_construct_add_arc(outh, source, target, in, in);
} else {
fsm_construct_add_arc(outh, source, target, in, out);
}
}
}
fclose(prolog_file);
if (has_net == 1) {
fsm_construct_set_initial(outh, 0);
outnet = fsm_construct_done(outh);
fsm_topsort(outnet);
return(outnet);
} else {
return(NULL);
}
}
struct io_buf_handle *io_init() {
struct io_buf_handle *iobh;
iobh = xxmalloc(sizeof(struct io_buf_handle));
(iobh->io_buf) = NULL;
(iobh->io_buf_ptr) = NULL;
return(iobh);
}
void io_free(struct io_buf_handle *iobh) {
if (iobh->io_buf != NULL) {
xxfree(iobh->io_buf);
(iobh->io_buf) = NULL;
}
xxfree(iobh);
}
char *spacedtext_get_next_line(char **text) {
char *t, *ret;
ret = *text;
if (**text == '\0')
return NULL;
for (t = *text; *t != '\0' && *t != '\n'; t++) {
}
if (*t == '\0')
*text = t;
else
*text = t+1;
*t = '\0';
return(ret);
}
char *spacedtext_get_next_token(char **text) {
char *t, *ret;
if (**text == '\0' || **text == '\n')
return NULL;
for ( ; **text == ' ' ; (*text)++) {
}
ret = *text;
for (t = *text; *t != '\0' && *t != '\n' && *t != ' '; t++) {
}
if (*t == '\0' || *t == '\n')
*text = t;
else
*text = t+1;
*t = '\0';
return(ret);
}
struct fsm *fsm_read_spaced_text_file(char *filename) {
struct fsm_trie_handle *th;
char *text, *textorig, *insym, *outsym, *t1, *t2, *l1, *l2;
text = textorig = file_to_mem(filename);
if (text == NULL)
return NULL;
th = fsm_trie_init();
for (;;) {
for ( ; *text != '\0' && *text == '\n'; text++) { }
t1 = spacedtext_get_next_line(&text);
if (t1 == NULL)
break;
if (strlen(t1) == 0)
continue;
t2 = spacedtext_get_next_line(&text);
if (t2 == NULL || strlen(t2) == 0) {
for (l1 = t1; (insym = spacedtext_get_next_token(&l1)) != NULL; ) {
if (strcmp(insym, "0") == 0)
fsm_trie_symbol(th, "@_EPSILON_SYMBOL_@", "@_EPSILON_SYMBOL_@");
else if (strcmp(insym, "%0") == 0)
fsm_trie_symbol(th, "0", "0");
else
fsm_trie_symbol(th, insym, insym);
}
fsm_trie_end_word(th);
} else {
for (l1 = t1, l2 = t2; ; ) {
insym = spacedtext_get_next_token(&l1);
outsym = spacedtext_get_next_token(&l2);
if (insym == NULL && outsym == NULL)
break;
if (insym == NULL || strcmp(insym, "0") == 0)
insym = "@_EPSILON_SYMBOL_@";
if (strcmp(insym, "%0") == 0)
insym = "0";
if (outsym == NULL || strcmp(outsym, "0") == 0)
outsym = "@_EPSILON_SYMBOL_@";
if (strcmp(outsym, "%0") == 0)
outsym = "0";
fsm_trie_symbol(th, insym, outsym);
}
fsm_trie_end_word(th);
}
}
xxfree(textorig);
return(fsm_trie_done(th));
}
struct fsm *fsm_read_text_file(char *filename) {
struct fsm_trie_handle *th;
char *text, *textp1, *textp2;
int lastword;
text = file_to_mem(filename);
if (text == NULL) {
return NULL;
}
textp1 = text;
th = fsm_trie_init();
for (lastword = 0 ; lastword == 0 ; textp1 = textp2+1) {
for (textp2 = textp1 ; *textp2 != '\n' && *textp2 != '\0'; textp2++) {
}
if (*textp2 == '\0') {
lastword = 1;
if (textp2 == textp1)
break;
}
*textp2 = '\0';
if (strlen(textp1) > 0)
fsm_trie_add_word(th, textp1);
}
xxfree(text);
return(fsm_trie_done(th));
}
int fsm_write_binary_file(struct fsm *net, char *filename) {
gzFile outfile;
if ((outfile = gzopen(filename,"wb")) == NULL) {
return(1);
}
foma_net_print(net, outfile);
gzclose(outfile);
return(0);
}
struct fsm *fsm_read_binary_file_multiple(fsm_read_binary_handle fsrh) {
char *net_name;
struct fsm *net;
struct io_buf_handle *iobh;
iobh = (struct io_buf_handle *) fsrh;
net = io_net_read(iobh, &net_name);
if (net == NULL) {
io_free(iobh);
return(NULL);
} else {
xxfree(net_name);
return(net);
}
}
fsm_read_binary_handle fsm_read_binary_file_multiple_init(char *filename) {
struct io_buf_handle *iobh;
fsm_read_binary_handle fsm_read_handle;
iobh = io_init();
if (io_gz_file_to_mem(iobh, filename) == 0) {
io_free(iobh);
return NULL;
}
fsm_read_handle = (void *) iobh;
return(fsm_read_handle);
}
struct fsm *fsm_read_binary_file(char *filename) {
char *net_name;
struct fsm *net;
struct io_buf_handle *iobh;
iobh = io_init();
if (io_gz_file_to_mem(iobh, filename) == 0) {
io_free(iobh);
return NULL;
}
net = io_net_read(iobh, &net_name);
io_free(iobh);
return(net);
}
int save_defined(struct defined_networks *def, char *filename) {
struct defined_networks *d;
gzFile outfile;
if (def == NULL) {
fprintf(stderr, "No defined networks.\n");
return(0);
}
if ((outfile = gzopen(filename, "wb")) == NULL) {
printf("Error opening file %s for writing.\n", filename);
return(-1);
}
printf("Writing definitions to file %s.\n", filename);
for (d = def; d != NULL; d = d->next) {
strcpy(d->net->name, d->name);
foma_net_print(d->net, outfile);
}
gzclose(outfile);
return(1);
}
int load_defined(struct defined_networks *def, char *filename) {
struct fsm *net;
char *net_name;
struct io_buf_handle *iobh;
iobh = io_init();
printf("Loading definitions from %s.\n",filename);
if (io_gz_file_to_mem(iobh, filename) == 0) {
fprintf(stderr, "File error.\n");
io_free(iobh);
return 0;
}
while ((net = io_net_read(iobh, &net_name)) != NULL) {
add_defined(def, net, net_name);
}
io_free(iobh);
return(1);
}
static INLINE int explode_line(char *buf, int *values) {
int i, j, items;
j = i = items = 0;
for (;;) {
for (i = j; *(buf+j) != ' ' && *(buf+j) != '\0'; j++) { }
if (*(buf+j) == '\0') {
*(values+items) = atoi(buf+i);
items++;
break;
} else{
*(buf+j) = '\0';
*(values+items) = atoi(buf+i);
items++;
j++;
}
}
return(items);
}
/* The file format we use is an extremely simple text format */
/* which is gzip compressed through libz and consists of the following sections: */
/* ##foma-net VERSION##*/
/* ##props## */
/* PROPERTIES LINE */
/* ##sigma## */
/* ...SIGMA LINES... */
/* ##states## */
/* ...TRANSITION LINES... */
/* ##end## */
/* Several networks may be concatenated in one file */
/* The initial identifier is "##foma-net 1.0##" */
/* where 1.0 is the version number for the file format */
/* followed by the line "##props##" */
/* which is followed by a line of space separated integers */
/* which correpond to: */
/* arity arccount statecount linecount finalcount pathcount is_deterministic */
/* is_pruned is_minimized is_epsilon_free is_loop_free is_completed name */
/* where name is used if defined networks are saved/loaded */
/* Following the props line, we accept anything (for future expansion) */
/* until we find ##sigma## */
/* the section beginning with "##sigma##" consists of lines with two fields: */
/* number string */
/* correponding to the symbol number and the symbol string */
/* the section beginning with "##states##" consists of lines of ASCII integers */
/* with 2-5 fields to avoid some redundancy in every line corresponding to a */
/* transition where otherwise state numbers would be unnecessarily repeated and */
/* out symbols also (if in = out as is the case for recognizers/simple automata) */
/* The information depending on the number of fields in the lines is as follows: */
/* 2: in target (here state_no is the same as the last mentioned one and out = in) */
/* 3: in out target (again, state_no is the same as the last mentioned one) */
/* 4: state_no in target final_state (where out = in) */
/* 5: state_no in out target final_state */
/* There is no harm in always using 5 fields; however this will take up more space */
/* As in struct fsm_state, states without transitions are represented as a 4-field: */
/* state_no -1 -1 final_state (since in=out for 4-field lines, out = -1 as well) */
/* AS gzopen will read uncompressed files as well, one can gunzip a file */
/* that contains a network and still read it */
struct fsm *io_net_read(struct io_buf_handle *iobh, char **net_name) {
char buf[READ_BUF_SIZE];
struct fsm *net;
struct fsm_state *fsm;
char *new_symbol;
int i, items, new_symbol_number, laststate, lineint[5], *cm;
int extras;
char last_final = '1';
if (io_gets(iobh, buf) == 0) {
return NULL;
}
net = fsm_create("");
if (strcmp(buf, "##foma-net 1.0##") != 0) {
fsm_destroy(net);
perror("File format error foma!\n");
return NULL;
}
io_gets(iobh, buf);
if (strcmp(buf, "##props##") != 0) {
perror("File format error props!\n");
fsm_destroy(net);
return NULL;
}
/* Properties */
io_gets(iobh, buf);
extras = 0;
sscanf(buf, "%i %i %i %i %i %lld %i %i %i %i %i %i %s", &net->arity, &net->arccount, &net->statecount, &net->linecount, &net->finalcount, &net->pathcount, &net->is_deterministic, &net->is_pruned, &net->is_minimized, &net->is_epsilon_free, &net->is_loop_free, &extras, buf);
strcpy(net->name, buf);
*net_name = xxstrdup(buf);
io_gets(iobh, buf);
net->is_completed = (extras & 3);
net->arcs_sorted_in = (extras & 12) >> 2;
net->arcs_sorted_out = (extras & 48) >> 4;
/* Sigma */
while (strcmp(buf, "##sigma##") != 0) { /* Loop until we encounter ##sigma## */
if (buf[0] == '\0') {
printf("File format error at sigma definition!\n");
fsm_destroy(net);
return NULL;
}
io_gets(iobh, buf);
}
for (;;) {
io_gets(iobh, buf);
if (buf[0] == '#') break;
if (buf[0] == '\0') continue;
new_symbol = strstr(buf, " ");
new_symbol[0] = '\0';
new_symbol++;
if (new_symbol[0] == '\0') {
sscanf(buf,"%i", &new_symbol_number);
sigma_add_number(net->sigma, "\n", new_symbol_number);
} else {
sscanf(buf,"%i", &new_symbol_number);
sigma_add_number(net->sigma, new_symbol, new_symbol_number);
}
}
/* States */
if (strcmp(buf, "##states##") != 0) {
printf("File format error!\n");
return NULL;
}
net->states = xxmalloc(net->linecount*sizeof(struct fsm_state));
fsm = net->states;
laststate = -1;
for (i=0; ;i++) {
io_gets(iobh, buf);
if (buf[0] == '#') break;
/* scanf is just too slow here */
//items = sscanf(buf, "%i %i %i %i %i",&lineint[0], &lineint[1], &lineint[2], &lineint[3], &lineint[4]);
items = explode_line(buf, &lineint[0]);
switch (items) {
case 2:
(fsm+i)->state_no = laststate;
(fsm+i)->in = lineint[0];
(fsm+i)->out = lineint[0];
(fsm+i)->target = lineint[1];
(fsm+i)->final_state = last_final;
break;
case 3:
(fsm+i)->state_no = laststate;
(fsm+i)->in = lineint[0];
(fsm+i)->out = lineint[1];
(fsm+i)->target = lineint[2];
(fsm+i)->final_state = last_final;
break;
case 4:
(fsm+i)->state_no = lineint[0];
(fsm+i)->in = lineint[1];
(fsm+i)->out = lineint[1];
(fsm+i)->target = lineint[2];
(fsm+i)->final_state = lineint[3];
laststate = lineint[0];
last_final = lineint[3];
break;
case 5:
(fsm+i)->state_no = lineint[0];
(fsm+i)->in = lineint[1];
(fsm+i)->out = lineint[2];
(fsm+i)->target = lineint[3];
(fsm+i)->final_state = lineint[4];
laststate = lineint[0];
last_final = lineint[4];
break;
default:
printf("File format error\n");
return NULL;
}
if (laststate > 0) {
(fsm+i)->start_state = 0;
} else if (laststate == -1) {
(fsm+i)->start_state = -1;
} else {
(fsm+i)->start_state = 1;
}
}
if (strcmp(buf, "##cmatrix##") == 0) {
cmatrix_init(net);
cm = net->medlookup->confusion_matrix;
for (;;) {
io_gets(iobh, buf);
if (buf[0] == '#') break;
sscanf(buf,"%i", &i);
*cm = i;
cm++;
}
}
if (strcmp(buf, "##end##") != 0) {
printf("File format error!\n");
return NULL;
}
return(net);
}
static int io_gets(struct io_buf_handle *iobh, char *target) {
int i;
for (i = 0; *((iobh->io_buf_ptr)+i) != '\n' && *((iobh->io_buf_ptr)+i) != '\0'; i++) {
*(target+i) = *((iobh->io_buf_ptr)+i);
}
*(target+i) = '\0';
if (*((iobh->io_buf_ptr)+i) == '\0')
(iobh->io_buf_ptr) = (iobh->io_buf_ptr) + i;
else
(iobh->io_buf_ptr) = (iobh->io_buf_ptr) + i + 1;
return(i);
}
int foma_net_print(struct fsm *net, gzFile outfile) {
struct sigma *sigma;
struct fsm_state *fsm;
int i, maxsigma, laststate, *cm, extras;
/* Header */
gzprintf(outfile, "%s","##foma-net 1.0##\n");
/* Properties */
gzprintf(outfile, "%s","##props##\n");
extras = (net->is_completed) | (net->arcs_sorted_in << 2) | (net->arcs_sorted_out << 4);
gzprintf(outfile,
"%i %i %i %i %i %lld %i %i %i %i %i %i %s\n", net->arity, net->arccount, net->statecount, net->linecount, net->finalcount, net->pathcount, net->is_deterministic, net->is_pruned, net->is_minimized, net->is_epsilon_free, net->is_loop_free, extras, net->name);
/* Sigma */
gzprintf(outfile, "%s","##sigma##\n");
for (sigma = net->sigma; sigma != NULL && sigma->number != -1; sigma = sigma->next) {
gzprintf(outfile, "%i %s\n",sigma->number, sigma->symbol);
}
/* State array */
laststate = -1;
gzprintf(outfile, "%s","##states##\n");
for (fsm = net->states; fsm->state_no !=-1; fsm++) {
if (fsm->state_no != laststate) {
if (fsm->in != fsm->out) {
gzprintf(outfile, "%i %i %i %i %i\n",fsm->state_no, fsm->in, fsm->out, fsm->target, fsm->final_state);
} else {
gzprintf(outfile, "%i %i %i %i\n",fsm->state_no, fsm->in, fsm->target, fsm->final_state);
}
} else {
if (fsm->in != fsm->out) {
gzprintf(outfile, "%i %i %i\n", fsm->in, fsm->out, fsm->target);
} else {
gzprintf(outfile, "%i %i\n", fsm->in, fsm->target);
}
}
laststate = fsm->state_no;
}
/* Sentinel for states */
gzprintf(outfile, "-1 -1 -1 -1 -1\n");
/* Store confusion matrix */
if (net->medlookup != NULL && net->medlookup->confusion_matrix != NULL) {
gzprintf(outfile, "%s","##cmatrix##\n");
cm = net->medlookup->confusion_matrix;
maxsigma = sigma_max(net->sigma)+1;
for (i=0; i < maxsigma*maxsigma; i++) {
gzprintf(outfile, "%i\n", *(cm+i));
}
}
/* End */
gzprintf(outfile, "%s","##end##\n");
return(1);
}
int net_print_att(struct fsm *net, FILE *outfile) {
struct fsm_state *fsm;
struct fsm_sigma_list *sl;
int i, prev;
fsm = net->states;
sl = sigma_to_list(net->sigma);
if (sigma_max(net->sigma) >= 0) {
(sl+0)->symbol = g_att_epsilon;
}
for (i=0; (fsm+i)->state_no != -1; i++) {
if ((fsm+i)->target != -1) {
fprintf(outfile, "%i\t%i\t%s\t%s\n",(fsm+i)->state_no,(fsm+i)->target, (sl+(fsm+i)->in)->symbol, (sl+(fsm+i)->out)->symbol);
}
}
prev = -1;
for (i=0; (fsm+i)->state_no != -1; prev = (fsm+i)->state_no, i++) {
if ((fsm+i)->state_no != prev && (fsm+i)->final_state == 1) {
fprintf(outfile, "%i\n",(fsm+i)->state_no);
}
}
xxfree(sl);
return(1);
}
static size_t io_get_gz_file_size(char *filename) {
FILE *infile;
size_t numbytes;
unsigned char bytes[4];
unsigned int ints[4], i;
/* The last four bytes in a .gz file shows the size of the uncompressed data */
infile = fopen(filename, "r");
fseek(infile, -4, SEEK_END);
fread(&bytes, 1, 4, infile);
fclose(infile);
for (i = 0 ; i < 4 ; i++) {
ints[i] = bytes[i];
}
numbytes = ints[0] | (ints[1] << 8) | (ints[2] << 16 ) | (ints[3] << 24);
return(numbytes);
}
static size_t io_get_regular_file_size(char *filename) {
FILE *infile;
size_t numbytes;
infile = fopen(filename, "r");
fseek(infile, 0L, SEEK_END);
numbytes = ftell(infile);
fclose(infile);
return(numbytes);
}
static size_t io_get_file_size(char *filename) {
gzFile FILE;
size_t size;
FILE = gzopen(filename, "r");
if (FILE == NULL) {
return(0);
}
if (gzdirect(FILE) == 1) {
gzclose(FILE);
size = io_get_regular_file_size(filename);
} else {
gzclose(FILE);
size = io_get_gz_file_size(filename);
}
return(size);
}
size_t io_gz_file_to_mem(struct io_buf_handle *iobh, char *filename) {
size_t size;
gzFile FILE;
size = io_get_file_size(filename);
if (size == 0) {
return 0;
}
(iobh->io_buf) = xxmalloc((size+1)*sizeof(char));
FILE = gzopen(filename, "rb");
gzread(FILE, iobh->io_buf, size);
gzclose(FILE);
*((iobh->io_buf)+size) = '\0';
iobh->io_buf_ptr = iobh->io_buf;
return(size);
}
char *file_to_mem(char *name) {
FILE *infile;
size_t numbytes;
char *buffer;
infile = fopen(name, "r");
if(infile == NULL) {
printf("Error opening file '%s'\n",name);
return NULL;
}
fseek(infile, 0L, SEEK_END);
numbytes = ftell(infile);
fseek(infile, 0L, SEEK_SET);
buffer = (char*)xxmalloc((numbytes+1) * sizeof(char));
if(buffer == NULL) {
printf("Error reading file '%s'\n",name);
return NULL;
}
if (fread(buffer, sizeof(char), numbytes, infile) != numbytes) {
printf("Error reading file '%s'\n",name);
return NULL;
}
fclose(infile);
*(buffer+numbytes)='\0';
return(buffer);
}
| 28.616222 | 277 | 0.546887 |
fbfed3983f19a82ee36d1578c35a1ee3b7f2ef93 | 2,452 | h | C | POKITTO_CORE/Pokitto_disk.h | epicdude312/Arcade-Classics | dd66023dcfe890cece2473f5b928a3e13fc09e74 | [
"BSD-3-Clause"
] | 1 | 2017-06-13T10:45:28.000Z | 2017-06-13T10:45:28.000Z | POKITTO_CORE/Pokitto_disk.h | epicdude312/Arcade-Classics | dd66023dcfe890cece2473f5b928a3e13fc09e74 | [
"BSD-3-Clause"
] | null | null | null | POKITTO_CORE/Pokitto_disk.h | epicdude312/Arcade-Classics | dd66023dcfe890cece2473f5b928a3e13fc09e74 | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************************/
/*!
@file Pokitto_disk.h
@author Jonne Valola
@section LICENSE
Pokitto development stage library
Software License Agreement
Copyright (c) 2015, Jonne Valola ("Author")
All rights reserved.
This library is intended solely for the purpose of Pokitto development.
Redistribution and use in source and binary forms, with or without
modification requires written permission from Author.
*/
/**************************************************************************/
#ifndef POKITTO_DISK_H
#define POKITTO_DISK_H
#ifndef POK_SIM
// real hardware disk driver
#include "diskio.h"
#include "pff.h"
#include "connect.h"
#include "mbed.h"
extern BYTE res;
extern FATFS fs; /* File system object */
extern FATDIR dir; /* Directory object */
extern FILINFO fno; /* File information */
extern SPI device;
extern DigitalOut mmccs;
/**************************************************************************/
/** SD CONTROL MACROS **/
/**************************************************************************/
// CS ... #define CONNECT_CS P0_7 //p13
#define CLR_SD_CS LPC_GPIO_PORT->CLR[0] = (1 << 7)
#define SET_SD_CS LPC_GPIO_PORT->SET[0] = (1 << 7)
#define GET_SD_CS LPC_GPIO_PORT->PIN[0] & (1 << 7)
#else
// simulated disk driver
#endif
#include <stdint.h>
extern int pokInitSD();
// File IO modes
#define FILE_MODE_APPEND 0x1
#define FILE_MODE_OVERWRITE 0
#define FILE_MODE_READONLY 0x2
#define FILE_MODE_READWRITE 0
#define FILE_MODE_BINARY 0x4
#define FILE_MODE_ASCII 0
#define FILE_MODE_FAILED 0x8
#define FILE_MODE_UNINITIALIZED 0x10
extern uint8_t fileOpen(char*, char);
extern void fileClose();
extern int fileGetChar();
extern void filePutChar(char);
extern void fileWriteBytes(uint8_t *, uint16_t);
extern uint16_t fileReadBytes(uint8_t *, uint16_t);
extern void fileSeekAbsolute(long);
extern void fileSeekRelative(long);
extern void fileRewind();
extern void fileEnd();
extern long int fileGetPosition();
#define fileSetPosition(n) (fileSeekAbsolute(n))
extern uint8_t filePeek(long);
extern void filePoke(long, uint8_t);
extern char* getCurrentFileName ();
extern int isThisFileOpen(char*);
extern int fileOK();
#endif // POKITTO_DISK_H
| 28.511628 | 77 | 0.603997 |
068157e9f1cdf57b2965b8053af295c42f89ac24 | 124 | h | C | external/include/avs-device-sdk/avs-device-sdk.h | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 511 | 2017-03-29T09:14:09.000Z | 2022-03-30T23:10:29.000Z | external/include/avs-device-sdk/avs-device-sdk.h | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 4,673 | 2017-03-29T10:43:43.000Z | 2022-03-31T08:33:44.000Z | external/include/avs-device-sdk/avs-device-sdk.h | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 642 | 2017-03-30T20:45:33.000Z | 2022-03-24T17:07:33.000Z | #ifndef __AVS_DEVICE_SDK_H__
#define __AVS_DEVICE_SDK_H__
#include <tinyara/config.h>
int avsSampleAppEntry(void);
#endif | 15.5 | 28 | 0.822581 |
5ea9663661ddc0e469e008543fcc57a7542390cf | 2,670 | h | C | Hanse/Behaviour_WallFollowing/behaviour_wallfollowing.h | iti-luebeck/HANSE2011 | 0bd5b3f1e0bc5a02516e7514b2241897337334c2 | [
"BSD-3-Clause"
] | null | null | null | Hanse/Behaviour_WallFollowing/behaviour_wallfollowing.h | iti-luebeck/HANSE2011 | 0bd5b3f1e0bc5a02516e7514b2241897337334c2 | [
"BSD-3-Clause"
] | null | null | null | Hanse/Behaviour_WallFollowing/behaviour_wallfollowing.h | iti-luebeck/HANSE2011 | 0bd5b3f1e0bc5a02516e7514b2241897337334c2 | [
"BSD-3-Clause"
] | null | null | null | #ifndef WALLFOLLOWINGBEHAVIOUR_H
#define WALLFOLLOWINGBEHAVIOUR_H
#include <Framework/robotbehaviour.h>
#include <Module_EchoSounder/module_echosounder.h>
class WallFollowingForm;
class Module_ThrusterControlLoop;
class Module_Simulation;
class Module_XsensMTi;
// Follow wall right to hanse
#define FLAG_SOUNDER_RIGHT true
// Wall states
#define WALL_NO_WALL "No average distance, turn..."
#define WALL_ADJUST_START "Adjust startdistance"
#define WALL_CONTROL_WALLFOLLOW "Average distance existing"
#define WALL_TURN_LEFT "Turn left"
#define WALL_TURN_RIGHT "Turn right"
#define WALL_NO_TURN "Only forward"
#define WALL_ERROR "Echosignal error"
#define WALL_STOP " - Stopped -"
#define ADJUST_IDLE "Adjust distance idle"
#define ADJUST_TURN90_START "First adjust turn 90"
#define ADJUST_DRIVE "Adjust drive"
#define ADJUST_TURN90_END "Second adjust turn 90"
class Behaviour_WallFollowing : public RobotBehaviour
{
Q_OBJECT
public:
// Methods
Behaviour_WallFollowing(QString id, Module_ThrusterControlLoop* tcl, Module_EchoSounder *echo, Module_XsensMTi* x);
QList<RobotModule*> getDependencies();
QWidget* createView(QWidget *parent);
bool isActive();
private:
void init();
void controlWallFollow();
void controlThrusterEchoLeft();
void controlThrusterEchoRight();
void updateOutput();
// Parameters
bool active;
Module_EchoSounder *echo;
Module_XsensMTi* xsens;
Module_ThrusterControlLoop * tcl;
float avgDistance;
float distanceInput;
float angSpeed;
float fwdSpeed;
float corridorWidth;
float initialHeading;
float targetHeading;
float diff;
float allowedDist;
QString wallState;
QString adjustState;
QString guiShow;
signals:
void timerStart( int msec );
void timerStop();
void dataError();
void forwardSpeed(float fwSpeed);
void angularSpeed(float anSpeed);
void startControlTimer();
void newWallUiData(const EchoReturnData data, float avgDistance);
void updateGUI(QString caseW);
void updateUi();
public slots:
void updateFromSettings();
void startBehaviour();
void stop();
void reset();
void terminate();
void stopOnEchoError();
void newData(const EchoReturnData data, float avgDistance);
void controlEnabledChanged(bool);
void adjustTurnOne();
void adjustDrive();
void adjustTurnTwo();
};
#endif // WallFollowingBEHAVIOUR_H
| 28.105263 | 120 | 0.680899 |
d7748acd3954691a2eda6be94b2ac137e357bf5b | 133 | h | C | platform/mcu/rtl8710bn/sdk/component/common/example/ssl_download/example_ssl_download.h | ghsecuritylab/AliOS-Things_rel_1.3.1 | 9d511c3d3b4b278a1aed91958bef87501c445c0e | [
"Apache-2.0"
] | 54 | 2018-10-10T01:43:10.000Z | 2022-02-26T01:36:40.000Z | platform/mcu/rtl8710bn/sdk/component/common/example/ssl_download/example_ssl_download.h | jason-sophia/AliOS-Things | c3ae527f1265b8dbb1f39c1f789fd5bdee0b3812 | [
"Apache-2.0"
] | 6 | 2020-01-08T06:50:30.000Z | 2021-03-17T05:44:50.000Z | platform/mcu/rtl8710bn/sdk/component/common/example/ssl_download/example_ssl_download.h | jason-sophia/AliOS-Things | c3ae527f1265b8dbb1f39c1f789fd5bdee0b3812 | [
"Apache-2.0"
] | 48 | 2018-08-14T07:12:33.000Z | 2022-03-01T03:52:32.000Z | #ifndef EXAMPLE_SSL_DOWNLOAD_H
#define EXAMPLE_SSL_DOWNLOAD_H
void example_ssl_download(void);
#endif /* EXAMPLE_SSL_DOWNLOAD_H */
| 19 | 35 | 0.834586 |
b903335fb47465229237e28db518bc4c75b912e3 | 41,626 | h | C | src/smartpeak/include/SmartPeak/ml/ModelInterpreterGpu.h | dmccloskey/EvoNet | 8d7fafe1069593024e5b63fd6b81a341a3bf33b5 | [
"MIT"
] | 3 | 2020-12-28T11:07:26.000Z | 2021-12-30T11:38:13.000Z | src/smartpeak/include/SmartPeak/ml/ModelInterpreterGpu.h | dmccloskey/EvoNet | 8d7fafe1069593024e5b63fd6b81a341a3bf33b5 | [
"MIT"
] | 20 | 2018-10-03T11:35:23.000Z | 2019-10-14T09:17:07.000Z | src/smartpeak/include/SmartPeak/ml/ModelInterpreterGpu.h | dmccloskey/EvoNet | 8d7fafe1069593024e5b63fd6b81a341a3bf33b5 | [
"MIT"
] | null | null | null | /**TODO: Add copyright*/
#ifndef SMARTPEAK_MODELINTERPRETERGPU_H
#define SMARTPEAK_MODELINTERPRETERGPU_H
#if COMPILE_WITH_CUDA
#define EIGEN_DEFAULT_DENSE_INDEX_TYPE int
#define EIGEN_USE_GPU
#include <cuda.h>
#include <cuda_runtime.h>
// .h
#include <SmartPeak/ml/ModelInterpreter.h>
#include <unsupported/Eigen/CXX11/Tensor>
#include <cereal/access.hpp> // serialiation of private members
#undef min // clashes with std::limit on windows in polymorphic.hpp
#undef max // clashes with std::limit on windows in polymorphic.hpp
#include <cereal/types/polymorphic.hpp>
// .cpp
#include <SmartPeak/ml/ModelErrorData.h>
#include <SmartPeak/ml/ModelKernalGpu.h>
namespace SmartPeak
{
template<typename TensorT>
class ModelInterpreterGpu : public ModelInterpreter<TensorT, Eigen::GpuDevice>
{
public:
using ModelInterpreter<TensorT, Eigen::GpuDevice>::ModelInterpreter;
void allocateForwardPropogationLayerTensors(const std::vector<OperationList<TensorT>>& FP_operations,
const std::map<std::string, std::vector<int>>& operations_map,
const std::vector<int>& source_layer_sizes, const std::vector<int>& sink_layer_sizes, const std::vector<std::vector<std::pair<int, int>>> weight_indices,
std::vector<std::map<std::string, std::vector<std::pair<int, int>>>>& shared_weight_indices, const std::vector<std::vector<TensorT>>& weight_values,
const std::vector<bool>& make_source_tensors, const std::vector<bool>& make_sink_tensors, const std::vector<bool>& make_weight_tensors,
const int& batch_size, const int& memory_size, const bool& train) override;
void executeForwardPropogationOperations(const int& time_step) override;
void executeModelErrorOperations(Eigen::Tensor<TensorT, 2>& expected, const int& layer_id, std::shared_ptr<LossFunctionTensorOp<TensorT,Eigen::GpuDevice>>& loss_function, std::shared_ptr<LossFunctionGradTensorOp<TensorT,Eigen::GpuDevice>>& loss_function_grad, const int& time_step) override;
void executeModelMetricOperations(Eigen::Tensor<TensorT, 2>& expected, const int& layer_id, std::shared_ptr<MetricFunctionTensorOp<TensorT,Eigen::GpuDevice>> metric_function, const int& time_step, const int& metric_index) override;
void executeBackwardPropogationOperations(const int& time_step) override;
void executeWeightErrorOperations() override;
void executeWeightUpdateOperations(const int& iter) override;
void allocateModelErrorTensor(const int& batch_size, const int& memory_size, const int& n_metrics) override;
void getModelResults(Model<TensorT>& model, const bool& output_nodes, const bool& weights, const bool& model_error, const bool& input_nodes) override;
void checkMemory(const Model<TensorT>& model, const int& batch_size, const int& memory_size) override;
void updateSolverParams(const int& param_index, const TensorT& param_factor) override;
private:
friend class cereal::access;
template<class Archive>
void serialize(Archive& archive) {
archive(cereal::base_class<ModelInterpreter<TensorT, Eigen::GpuDevice>>(this));
}
};
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::allocateForwardPropogationLayerTensors(
const std::vector<OperationList<TensorT>>& FP_operations, const std::map<std::string, std::vector<int>>& operations_map, const std::vector<int>& source_layer_sizes,
const std::vector<int>& sink_layer_sizes, const std::vector<std::vector<std::pair<int, int>>> weight_indices, std::vector<std::map<std::string, std::vector<std::pair<int, int>>>>& shared_weight_indices,
const std::vector<std::vector<TensorT>>& weight_values, const std::vector<bool>& make_source_tensors, const std::vector<bool>& make_sink_tensors, const std::vector<bool>& make_weight_tensors, const int & batch_size, const int & memory_size, const bool & train)
{
// ensure that all tensors are allocated on the correct device
assert(cudaSetDevice(this->getModelResources().at(0).getID()) == cudaSuccess); // is this needed?
std::vector<OperationTensorStep<TensorT, Eigen::GpuDevice>> operation_step_list;
ActivationOpToActivationTensorOp<TensorT, Eigen::GpuDevice> activation_conv;
SolverOpToSolverTensorOp<TensorT, Eigen::GpuDevice> solver_conv;
IntegrationOpToIntegrationTensorOp<TensorT, Eigen::GpuDevice> integration_conv;
IntegrationErrorOpToIntegrationErrorTensorOp<TensorT, Eigen::GpuDevice> integration_error_conv;
IntegrationWeightGradOpToIntegrationWeightGradTensorOp<TensorT, Eigen::GpuDevice> integration_weight_grad_conv;
int iter = 0;
for (const auto& operations : operations_map) {
// make the tensors
OperationTensorStep<TensorT, Eigen::GpuDevice> operation_step;
// [NOTE: order matters! sink layer should come before the source layer to keep with
// the ordering generated in getForwardPropogationTensorDimensions.]
std::shared_ptr<NodeTensorData<TensorT, Eigen::GpuDevice>> sink_node_data(new NodeTensorDataGpu<TensorT>());
{ // make the sink layer tensor and add it to the cache and operation step
std::shared_ptr<ActivationTensorOp<TensorT, Eigen::GpuDevice>> activation = nullptr;
std::shared_ptr<ActivationTensorOp<TensorT, Eigen::GpuDevice>> activation_grad = nullptr;
std::shared_ptr<IntegrationTensorOp<TensorT, Eigen::GpuDevice>> integration = nullptr;
std::shared_ptr<IntegrationErrorTensorOp<TensorT, Eigen::GpuDevice>> integration_error = nullptr;
std::shared_ptr<IntegrationWeightGradTensorOp<TensorT, Eigen::GpuDevice>> integration_weight_grad = nullptr;
if (make_sink_tensors[iter]) {
sink_node_data->initNodeTensorData(batch_size, memory_size, sink_layer_sizes[iter],
FP_operations[operations.second[0]].result.sink_node->getType(),
FP_operations[operations.second[0]].result.sink_node->getIntegrationShared()->getName(),
train);
this->layer_tensors_.push_back(sink_node_data);
operation_step.sink_layer.time_step = FP_operations[operations.second[0]].result.time_step;
activation_conv(FP_operations[operations.second[0]].result.sink_node->getActivationShared(), activation, std::vector<TensorT>() = {});
operation_step.sink_layer.activation = activation;
activation_conv(FP_operations[operations.second[0]].result.sink_node->getActivationGradShared(), activation_grad, std::vector<TensorT>() = {});
operation_step.sink_layer.activation_grad = activation_grad;
integration_conv(FP_operations[operations.second[0]].result.sink_node->getIntegrationShared(), integration, std::vector<TensorT>() = {});
operation_step.sink_layer.integration = integration;
integration_error_conv(FP_operations[operations.second[0]].result.sink_node->getIntegrationErrorShared(), integration_error, std::vector<TensorT>() = {});
operation_step.sink_layer.integration_error = integration_error;
integration_weight_grad_conv(FP_operations[operations.second[0]].result.sink_node->getIntegrationWeightGradShared(), integration_weight_grad, std::vector<TensorT>() = {});
operation_step.sink_layer.integration_weight_grad = integration_weight_grad;
operation_step.sink_layer.tensor_index = FP_operations[operations.second[0]].result.sink_node->getTensorIndex().first;
}
else {
operation_step.sink_layer.tensor_index = FP_operations[operations.second[0]].result.sink_node->getTensorIndex().first;
operation_step.sink_layer.time_step = FP_operations[operations.second[0]].result.time_step;
activation_conv(FP_operations[operations.second[0]].result.sink_node->getActivationShared(), activation, std::vector<TensorT>() = {});
operation_step.sink_layer.activation = activation;
activation_conv(FP_operations[operations.second[0]].result.sink_node->getActivationGradShared(), activation_grad, std::vector<TensorT>() = {});
operation_step.sink_layer.activation_grad = activation_grad;
integration_conv(FP_operations[operations.second[0]].result.sink_node->getIntegrationShared(), integration, std::vector<TensorT>() = {});
operation_step.sink_layer.integration = integration;
integration_error_conv(FP_operations[operations.second[0]].result.sink_node->getIntegrationErrorShared(), integration_error, std::vector<TensorT>() = {});
operation_step.sink_layer.integration_error= integration_error;
integration_weight_grad_conv(FP_operations[operations.second[0]].result.sink_node->getIntegrationWeightGradShared(), integration_weight_grad, std::vector<TensorT>() = {});
operation_step.sink_layer.integration_weight_grad = integration_weight_grad;
operation_step.sink_layer.time_step = FP_operations[operations.second[0]].result.time_step;
}
}
std::shared_ptr<NodeTensorData<TensorT, Eigen::GpuDevice>> source_node_data(new NodeTensorDataGpu<TensorT>());
{ // make the source layer tensor and add it to the cache and operation step
std::shared_ptr<ActivationTensorOp<TensorT, Eigen::GpuDevice>> activation = nullptr;
std::shared_ptr<ActivationTensorOp<TensorT, Eigen::GpuDevice>> activation_grad = nullptr;
std::shared_ptr<IntegrationTensorOp<TensorT, Eigen::GpuDevice>> integration = nullptr;
std::shared_ptr<IntegrationErrorTensorOp<TensorT, Eigen::GpuDevice>> integration_error = nullptr;
std::shared_ptr<IntegrationWeightGradTensorOp<TensorT, Eigen::GpuDevice>> integration_weight_grad = nullptr;
if (make_source_tensors[iter]) {
source_node_data->initNodeTensorData(batch_size, memory_size, source_layer_sizes[iter],
FP_operations[operations.second[0]].arguments[0].source_node->getType(),
FP_operations[operations.second[0]].arguments[0].source_node->getIntegrationShared()->getName(), train);
operation_step.source_layer.time_step = FP_operations[operations.second[0]].arguments[0].time_step;
this->layer_tensors_.push_back(source_node_data);
activation_conv(FP_operations[operations.second[0]].arguments[0].source_node->getActivationShared(), activation, std::vector<TensorT>() = {});
operation_step.source_layer.activation = activation;
activation_conv(FP_operations[operations.second[0]].arguments[0].source_node->getActivationGradShared(), activation_grad, std::vector<TensorT>() = {});
operation_step.source_layer.activation_grad = activation_grad;
integration_conv(FP_operations[operations.second[0]].arguments[0].source_node->getIntegrationShared(), integration, std::vector<TensorT>() = {});
operation_step.source_layer.integration = integration;
integration_error_conv(FP_operations[operations.second[0]].arguments[0].source_node->getIntegrationErrorShared(), integration_error, std::vector<TensorT>() = {});
operation_step.source_layer.integration_error = integration_error;
integration_weight_grad_conv(FP_operations[operations.second[0]].arguments[0].source_node->getIntegrationWeightGradShared(), integration_weight_grad, std::vector<TensorT>() = {});
operation_step.source_layer.integration_weight_grad = integration_weight_grad;
operation_step.source_layer.tensor_index = FP_operations[operations.second[0]].arguments[0].source_node->getTensorIndex().first;
}
else {
operation_step.source_layer.tensor_index = FP_operations[operations.second[0]].arguments[0].source_node->getTensorIndex().first;
operation_step.source_layer.time_step = FP_operations[operations.second[0]].arguments[0].time_step;
activation_conv(FP_operations[operations.second[0]].arguments[0].source_node->getActivationShared(), activation, std::vector<TensorT>() = {});
operation_step.source_layer.activation = activation;
activation_conv(FP_operations[operations.second[0]].arguments[0].source_node->getActivationGradShared(), activation_grad, std::vector<TensorT>() = {});
operation_step.source_layer.activation_grad = activation_grad;
integration_conv(FP_operations[operations.second[0]].arguments[0].source_node->getIntegrationShared(), integration, std::vector<TensorT>() = {});
operation_step.source_layer.integration = integration;
integration_error_conv(FP_operations[operations.second[0]].arguments[0].source_node->getIntegrationErrorShared(), integration_error, std::vector<TensorT>() = {});
operation_step.source_layer.integration_error = integration_error;
integration_weight_grad_conv(FP_operations[operations.second[0]].arguments[0].source_node->getIntegrationWeightGradShared(), integration_weight_grad, std::vector<TensorT>() = {});
operation_step.source_layer.integration_weight_grad = integration_weight_grad;
}
}
// make the weight tensor and add it to the cache and operation step
std::shared_ptr<WeightTensorData<TensorT, Eigen::GpuDevice>> weight_data = std::make_shared<WeightTensorDataGpu<TensorT>>(WeightTensorDataGpu<TensorT>());
if (make_weight_tensors[iter]) {
std::shared_ptr<SolverTensorOp<TensorT, Eigen::GpuDevice>> solver = nullptr;
std::vector<TensorT> solver_params;
solver_conv(FP_operations[operations.second[0]].arguments[0].weight->getSolverOpShared(), solver, solver_params);
weight_data->initWeightTensorData(source_layer_sizes[iter], sink_layer_sizes[iter], weight_indices[iter], shared_weight_indices[iter], weight_values[iter], train,
solver_params, FP_operations[operations.second[0]].result.sink_node->getIntegrationShared()->getName());
this->weight_tensors_.push_back(weight_data);
operation_step.weight.tensor_index = std::get<0>(FP_operations[operations.second[0]].arguments[0].weight->getTensorIndex()[0]);
operation_step.weight.solver = solver;
}
else {
std::cout << "Weight tensor is not being created...Check!" << std::endl;
}
operation_step_list.push_back(operation_step);
++iter;
}
// add the operations to the cache
this->operation_steps_.push_back(operation_step_list);
}
template<typename TensorT>
void ModelInterpreterGpu<TensorT>::executeForwardPropogationOperations(const int& time_step)
{
for (auto& operations_list : this->operation_steps_) {
// Set up the device, streams, and kernals
ModelKernalGpu<TensorT> model_kernal;
assert(cudaSetDevice(this->getModelResources().at(0).getID()) == cudaSuccess); // is this needed?
std::vector<cudaStream_t> streams;
for (size_t i = 0; i < operations_list.size(); ++i) {
cudaStream_t stream; // The stream will be destroyed by GpuStreamDevice once the function goes out of scope!
assert(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess);
streams.push_back(stream);
}
// execute the forward propogation steps
int device_iter = 0;
for (OperationTensorStep<TensorT, Eigen::GpuDevice>& operation : operations_list) {
Eigen::GpuStreamDevice stream_device(&streams[device_iter], getModelResources().at(0).getID());
Eigen::GpuDevice device(&stream_device);
if (!this->layer_tensors_.at(operation.source_layer.tensor_index)->getOutputStatus().second)
this->layer_tensors_.at(operation.source_layer.tensor_index)->syncHAndDOutput(device);
if (!this->weight_tensors_.at(operation.weight.tensor_index)->getWeightStatus().second)
this->weight_tensors_.at(operation.weight.tensor_index)->syncHAndDWeight(device);
if (!this->layer_tensors_.at(operation.sink_layer.tensor_index)->getInputStatus().second)
this->layer_tensors_.at(operation.sink_layer.tensor_index)->syncHAndDInput(device);
model_kernal.executeForwardPropogation(
this->layer_tensors_.at(operation.source_layer.tensor_index)->getHOutputPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getDOutputPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getHWeightPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getDWeightPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getHInputPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getDInputPointer().get(),
operation.sink_layer.integration,
this->layer_tensors_.at(operation.source_layer.tensor_index)->getBatchSize(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getMemorySize(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getLayerSize(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getLayerSize(),
operation.source_layer.time_step + time_step,
operation.sink_layer.time_step + time_step,
device);
if (!this->layer_tensors_.at(operation.sink_layer.tensor_index)->getOutputStatus().second)
this->layer_tensors_.at(operation.sink_layer.tensor_index)->syncHAndDOutput(device);
if (!this->layer_tensors_.at(operation.sink_layer.tensor_index)->getDtStatus().second)
this->layer_tensors_.at(operation.sink_layer.tensor_index)->syncHAndDDt(device);
model_kernal.executeNodeActivation(
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getHInputPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getDInputPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getHOutputPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getDOutputPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getHDtPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getDDtPointer().get(),
operation.sink_layer.activation,
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getBatchSize(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getMemorySize(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getLayerSize(),
operation.sink_layer.time_step + time_step,
device);
++device_iter;
}
// sync and destroy the streams
for (size_t i = 0; i < operations_list.size(); ++i) {
assert(cudaStreamSynchronize(streams[i]) == cudaSuccess);
assert(cudaStreamDestroy(streams[i]) == cudaSuccess);
}
}
}
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::executeBackwardPropogationOperations(const int & time_step)
{
for (int iter = this->operation_steps_.size() - 1; iter >= 0; --iter) { //iterate backwards
// Set up the device, streams, and kernals
ModelKernalGpu<TensorT> model_kernal;
assert(cudaSetDevice(this->getModelResources().at(0).getID()) == cudaSuccess); // is this needed?
std::vector<cudaStream_t> streams;
for (size_t i = 0; i < this->operation_steps_[iter].size(); ++i) {
cudaStream_t stream; // The stream will be destroyed by GpuStreamDevice once the function goes out of scope!
assert(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess);
streams.push_back(stream);
}
// execute the forward propogation steps
int device_iter = 0;
for (OperationTensorStep<TensorT, Eigen::GpuDevice>& operation : this->operation_steps_[iter]) { //reverse source/sink
Eigen::GpuStreamDevice stream_device(&streams[device_iter], getModelResources().at(0).getID());
Eigen::GpuDevice device(&stream_device);
if (!this->layer_tensors_.at(operation.source_layer.tensor_index)->getOutputStatus().second)
this->layer_tensors_.at(operation.source_layer.tensor_index)->syncHAndDOutput(device);
if (!this->layer_tensors_.at(operation.source_layer.tensor_index)->getDerivativeStatus().second)
this->layer_tensors_.at(operation.source_layer.tensor_index)->syncHAndDDerivative(device);
model_kernal.executeNodeDerivative(
this->layer_tensors_.at(operation.source_layer.tensor_index)->getHOutputPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getDOutputPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getHDerivativePointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getDDerivativePointer().get(),
operation.source_layer.activation_grad,
this->layer_tensors_.at(operation.source_layer.tensor_index)->getBatchSize(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getMemorySize(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getLayerSize(),
operation.source_layer.time_step + time_step,
device);
if (!this->layer_tensors_.at(operation.sink_layer.tensor_index)->getErrorStatus().second)
this->layer_tensors_.at(operation.sink_layer.tensor_index)->syncHAndDError(device);
if (!this->layer_tensors_.at(operation.sink_layer.tensor_index)->getInputStatus().second)
this->layer_tensors_.at(operation.sink_layer.tensor_index)->syncHAndDInput(device);
if (!this->weight_tensors_.at(operation.weight.tensor_index)->getWeightStatus().second)
this->weight_tensors_.at(operation.weight.tensor_index)->syncHAndDWeight(device);
if (!this->layer_tensors_.at(operation.source_layer.tensor_index)->getErrorStatus().second)
this->layer_tensors_.at(operation.source_layer.tensor_index)->syncHAndDError(device);
model_kernal.executeBackwardPropogation(
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getHErrorPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getDErrorPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getHInputPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getDInputPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getHOutputPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getDOutputPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getHWeightPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getDWeightPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getHErrorPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getDErrorPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getHDerivativePointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getDDerivativePointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getLayerSize(), // [TODO: replace with N]
operation.sink_layer.integration_error, // changed from source_layer
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getBatchSize(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getMemorySize(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getLayerSize(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getLayerSize(),
operation.sink_layer.time_step + time_step,
operation.source_layer.time_step + time_step,
device);
++device_iter;
}
// sync and destroy the streams
for (size_t i = 0; i < this->operation_steps_[iter].size(); ++i) {
assert(cudaStreamSynchronize(streams[i]) == cudaSuccess);
assert(cudaStreamDestroy(streams[i]) == cudaSuccess);
}
}
}
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::executeModelErrorOperations(Eigen::Tensor<TensorT, 2>& expected, const int& layer_id, std::shared_ptr<LossFunctionTensorOp<TensorT,Eigen::GpuDevice>>& loss_function, std::shared_ptr<LossFunctionGradTensorOp<TensorT,Eigen::GpuDevice>>& loss_function_grad, const int& time_step)
{
// More performant if all model error calculations were passed at the same time
ModelKernalGpu<TensorT> model_kernal;
cudaStream_t stream; // The stream will be destroyed by GpuStreamDevice once the function goes out of scope!
assert(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess);
Eigen::GpuStreamDevice stream_device(&stream, getModelResources().at(0).getID());
Eigen::GpuDevice device(&stream_device);
auto layer_tensor_data = this->getLayerTensor(layer_id);
// Sync the model error, node error, and node output
if (!this->model_error_->getErrorStatus().second)
this->model_error_->syncHAndDError(device);
if (!layer_tensor_data->getErrorStatus().second)
layer_tensor_data->syncHAndDError(device);
if (!layer_tensor_data->getOutputStatus().second)
layer_tensor_data->syncHAndDOutput(device);
// Calculate the model and node errors
model_kernal.executeModelErrors(
expected,
layer_tensor_data->getHOutputPointer().get(),
layer_tensor_data->getDOutputPointer().get(),
this->model_error_->getHErrorPointer().get(),
this->model_error_->getDErrorPointer().get(),
layer_tensor_data->getHErrorPointer().get(),
layer_tensor_data->getDErrorPointer().get(),
loss_function,
loss_function_grad,
layer_tensor_data->getBatchSize(),
layer_tensor_data->getMemorySize(),
layer_tensor_data->getLayerSize(),
time_step,
device);
assert(cudaStreamSynchronize(stream) == cudaSuccess);
assert(cudaStreamDestroy(stream) == cudaSuccess);
}
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::executeModelMetricOperations(Eigen::Tensor<TensorT, 2>& expected, const int & layer_id, std::shared_ptr<MetricFunctionTensorOp<TensorT,Eigen::GpuDevice>> metric_function, const int & time_step, const int & metric_index)
{
// More performant if all model error calculations were passed at the same time
ModelKernalGpu<TensorT> model_kernal;
cudaStream_t stream; // The stream will be destroyed by GpuStreamDevice once the function goes out of scope!
assert(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess);
Eigen::GpuStreamDevice stream_device(&stream, getModelResources().at(0).getID());
Eigen::GpuDevice device(&stream_device);
auto layer_tensor_data = this->getLayerTensor(layer_id);
// Sync the model metric and node output
if (!this->model_error_->getMetricStatus().second)
this->model_error_->syncHAndDMetric(device);
if (!layer_tensor_data->getOutputStatus().second)
layer_tensor_data->syncHAndDOutput(device);
// Calculate the model metric
model_kernal.executeModelMetric(
expected,
layer_tensor_data->getHOutputPointer().get(),
layer_tensor_data->getDOutputPointer().get(),
this->model_error_->getHMetricPointer().get(),
this->model_error_->getDMetricPointer().get(),
metric_function,
layer_tensor_data->getBatchSize(),
layer_tensor_data->getMemorySize(),
layer_tensor_data->getLayerSize(),
this->model_error_->getNMetrics(),
time_step,
metric_index,
device);
assert(cudaStreamSynchronize(stream) == cudaSuccess);
assert(cudaStreamDestroy(stream) == cudaSuccess);
}
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::executeWeightErrorOperations()
{
for (std::vector<OperationTensorStep<TensorT, Eigen::GpuDevice>>& operations_list : this->operation_steps_) {
// Set up the device, streams, and kernals
ModelKernalGpu<TensorT> model_kernal;
assert(cudaSetDevice(this->getModelResources().at(0).getID()) == cudaSuccess); // is this needed?
std::vector<cudaStream_t> streams;
for (size_t i = 0; i < operations_list.size(); ++i) {
cudaStream_t stream; // The stream will be destroyed by GpuStreamDevice once the function goes out of scope!
assert(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess);
streams.push_back(stream);
}
// execute the forward propogation steps
int device_iter = 0;
for (OperationTensorStep<TensorT, Eigen::GpuDevice>& operation : operations_list) {
Eigen::GpuStreamDevice stream_device(&streams[device_iter], getModelResources().at(0).getID());
Eigen::GpuDevice device(&stream_device);
if (!this->layer_tensors_.at(operation.sink_layer.tensor_index)->getErrorStatus().second)
this->layer_tensors_.at(operation.sink_layer.tensor_index)->syncHAndDError(device);
if (!this->layer_tensors_.at(operation.source_layer.tensor_index)->getInputStatus().second)
this->layer_tensors_.at(operation.source_layer.tensor_index)->syncHAndDInput(device);
if (!this->layer_tensors_.at(operation.source_layer.tensor_index)->getOutputStatus().second)
this->layer_tensors_.at(operation.source_layer.tensor_index)->syncHAndDOutput(device);
if (!this->weight_tensors_.at(operation.weight.tensor_index)->getWeightStatus().second)
this->weight_tensors_.at(operation.weight.tensor_index)->syncHAndDWeight(device);
if (!this->weight_tensors_.at(operation.weight.tensor_index)->getErrorStatus().second)
this->weight_tensors_.at(operation.weight.tensor_index)->syncHAndDError(device);
model_kernal.executeWeightErrors(
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getHErrorPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getDErrorPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getHOutputPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getDOutputPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getHInputPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getDInputPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getLayerSize(), // [TODO: change to N]
operation.sink_layer.integration_weight_grad,
this->weight_tensors_.at(operation.weight.tensor_index)->getHWeightPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getDWeightPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getHErrorPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getDErrorPointer().get(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getBatchSize(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getMemorySize(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getLayerSize(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getLayerSize(),
device);
if (!this->weight_tensors_.at(operation.weight.tensor_index)->getSharedWeightsStatus().second)
this->weight_tensors_.at(operation.weight.tensor_index)->syncHAndDSharedWeights(device);
model_kernal.executeSharedWeightErrors(
this->weight_tensors_.at(operation.weight.tensor_index)->getHErrorPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getDErrorPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getHSharedWeightsPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getDSharedWeightsPointer().get(),
this->layer_tensors_.at(operation.source_layer.tensor_index)->getLayerSize(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getLayerSize(),
this->weight_tensors_.at(operation.weight.tensor_index)->getNSharedWeights(),
device);
++device_iter;
}
// sync and destroy the streams
for (size_t i = 0; i < operations_list.size(); ++i) {
assert(cudaStreamSynchronize(streams[i]) == cudaSuccess);
assert(cudaStreamDestroy(streams[i]) == cudaSuccess);
}
}
}
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::executeWeightUpdateOperations(const int& iter)
{
for (std::vector<OperationTensorStep<TensorT, Eigen::GpuDevice>>& operations_list : this->operation_steps_) {
// Set up the device, streams, and kernals
ModelKernalGpu<TensorT> model_kernal;
assert(cudaSetDevice(this->getModelResources().at(0).getID()) == cudaSuccess); // is this needed?
std::vector<cudaStream_t> streams;
for (size_t i = 0; i < operations_list.size(); ++i) {
cudaStream_t stream; // The stream will be destroyed by GpuStreamDevice once the function goes out of scope!
assert(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess);
streams.push_back(stream);
}
// execute the forward propogation steps
int device_iter = 0;
for (OperationTensorStep<TensorT, Eigen::GpuDevice>& operation : operations_list) {
Eigen::GpuStreamDevice stream_device(&streams[device_iter], getModelResources().at(0).getID());
Eigen::GpuDevice device(&stream_device);
if (!this->weight_tensors_.at(operation.weight.tensor_index)->getWeightStatus().second)
this->weight_tensors_.at(operation.weight.tensor_index)->syncHAndDWeight(device);
if (!this->weight_tensors_.at(operation.weight.tensor_index)->getErrorStatus().second)
this->weight_tensors_.at(operation.weight.tensor_index)->syncHAndDError(device);
if (!this->weight_tensors_.at(operation.weight.tensor_index)->getSolverParamsStatus().second)
this->weight_tensors_.at(operation.weight.tensor_index)->syncHAndDSolverParams(device);
model_kernal.executeWeightUpdate(
this->weight_tensors_.at(operation.weight.tensor_index)->getHWeightPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getDWeightPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getHSolverParamsPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getDSolverParamsPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getHErrorPointer().get(),
this->weight_tensors_.at(operation.weight.tensor_index)->getDErrorPointer().get(),
operation.weight.solver,
this->layer_tensors_.at(operation.source_layer.tensor_index)->getLayerSize(),
this->layer_tensors_.at(operation.sink_layer.tensor_index)->getLayerSize(),
iter,
device);
++device_iter;
}
// sync and destroy the streams
for (size_t i = 0; i < operations_list.size(); ++i) {
assert(cudaStreamSynchronize(streams[i]) == cudaSuccess);
assert(cudaStreamDestroy(streams[i]) == cudaSuccess);
}
}
}
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::allocateModelErrorTensor(const int& batch_size, const int& memory_size, const int& n_metrics) {
std::shared_ptr<ModelErrorData<TensorT, Eigen::GpuDevice>> model_error_data = std:: make_shared<ModelErrorDataGpu<TensorT>>(ModelErrorDataGpu<TensorT>());
model_error_data->initModelErrorData(batch_size, memory_size, n_metrics);
this->model_error_ = model_error_data;
}
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::getModelResults(Model<TensorT>& model, const bool& output_nodes, const bool& weights, const bool& model_error, const bool& input_nodes)
{
// Synchronize all data with the host
cudaStream_t stream; // The stream will be destroyed by GpuStreamDevice once the function goes out of scope!
assert(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess);
Eigen::GpuStreamDevice stream_device(&stream, getModelResources().at(0).getID());
Eigen::GpuDevice device(&stream_device);
// sync the weight values
if (weights) {
for (auto& weight_map : model.getWeightsMap()) {
if (weight_map.second->getTensorIndex().size() > 0) {
const int tensor_index = std::get<0>(weight_map.second->getTensorIndex()[0]);
if (!this->getWeightTensor(tensor_index)->getWeightStatus().first)
this->getWeightTensor(tensor_index)->syncHAndDWeight(device);
}
}
}
// sync the model error
if (model_error) {
if (!this->model_error_->getErrorStatus().first)
this->model_error_->syncHAndDError(device);
if (!this->model_error_->getMetricStatus().first)
this->model_error_->syncHAndDMetric(device);
}
// sync the output node values
if (output_nodes) {
for (auto& output_node : model.getOutputNodes()) {
// NOTE: there is a strange bug where the tensor indices of the output nodes pointer are not updated
//const int tensor_index = output_node->getTensorIndex().first;
//const int layer_index = output_node->getTensorIndex().second;
const int tensor_index = model.getNodesMap().at(output_node->getName())->getTensorIndex().first;
if (!this->getLayerTensor(tensor_index)->getOutputStatus().first)
this->getLayerTensor(tensor_index)->syncHAndDOutput(device);
}
}
// sync the input node values
if (input_nodes) {
for (auto& input_node : model.getInputNodes()) {
// NOTE: there is a strange bug where the tensor indices of the input nodes pointer are not updated
//const int tensor_index = input_node->getTensorIndex().first;
//const int layer_index = input_node->getTensorIndex().second;
const int tensor_index = model.getNodesMap().at(input_node->getName())->getTensorIndex().first;
if (!this->getLayerTensor(tensor_index)->getInputStatus().first)
this->getLayerTensor(tensor_index)->syncHAndDInput(device);
}
}
assert(cudaStreamSynchronize(stream) == cudaSuccess);
assert(cudaStreamDestroy(stream) == cudaSuccess);
// copy out the weight values
if (weights) {
for (auto& weight_map : model.getWeightsMap()) {
if (weight_map.second->getTensorIndex().size() > 0) {
const int tensor_index = std::get<0>(weight_map.second->getTensorIndex()[0]);
const int layer1_index = std::get<1>(weight_map.second->getTensorIndex()[0]);
const int layer2_index = std::get<2>(weight_map.second->getTensorIndex()[0]);
weight_map.second->setWeight(this->getWeightTensor(tensor_index)->getWeight()(layer1_index, layer2_index));
}
}
}
// copy out the model error
if (model_error) {
model.setError(this->model_error_->getError());
model.setMetric(this->model_error_->getMetric());
}
// copy out the output node values
if (output_nodes) {
for (auto& output_node : model.getOutputNodes()) {
// NOTE: there is a strange bug where the tensor indices of the output nodes pointer are not updated
//const int tensor_index = output_node->getTensorIndex().first;
//const int layer_index = output_node->getTensorIndex().second;
const int tensor_index = model.getNodesMap().at(output_node->getName())->getTensorIndex().first;
const int layer_index = model.getNodesMap().at(output_node->getName())->getTensorIndex().second;
output_node->setOutput(this->getLayerTensor(tensor_index)->getOutput().chip(layer_index, 2));
}
}
// copy out the input node values
if (input_nodes) {
for (auto& input_node : model.getInputNodes()) {
const int tensor_index = model.getNodesMap().at(input_node->getName())->getTensorIndex().first;
const int layer_index = model.getNodesMap().at(input_node->getName())->getTensorIndex().second;
input_node->setInput(this->getLayerTensor(tensor_index)->getInput().chip(layer_index, 2));
}
}
}
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::checkMemory(const Model<TensorT>& model, const int& batch_size, const int& memory_size)
{
assert(cudaSetDevice(this->getModelResources().at(0).getID()) == cudaSuccess); // is this needed?
// get the device memory
size_t free_byte, total_byte;
cudaMemGetInfo(&free_byte, &total_byte);
// estimate the needed model memory
size_t node_mem = model.nodes_.size() * 4 * batch_size * (memory_size + 1) * sizeof(TensorT);
// best and worst case scenario estimation of weight, error, and solver parameter sizes
size_t weight_mem_best = model.weights_.size() * 3 * 6 * sizeof(TensorT); // assumptions: all fully connected nodes with adam optimizer (6 params)
size_t weight_mem_worst = model.weights_.size() * model.weights_.size() * 3 * 6 * sizeof(TensorT); // assumptions: all singly connected nodes with adam optimizer (6 params)
//size_t weight_mem = (size_t)((float)weight_mem_best * 0.8 + (float)weight_mem_worst * 0.2);
size_t weight_mem = weight_mem_best;
assert(free_byte > (node_mem + weight_mem));
}
template<typename TensorT>
inline void ModelInterpreterGpu<TensorT>::updateSolverParams(const int & param_index, const TensorT & param_factor)
{
assert(cudaSetDevice(this->getModelResources().at(0).getID()) == cudaSuccess); // is this needed?
assert(cudaSetDevice(this->getModelResources().at(0).getID()) == cudaSuccess); // is this needed?
std::vector<cudaStream_t> streams;
for (size_t i = 0; i < this->weight_tensors_.size(); ++i) {
cudaStream_t stream; // The stream will be destroyed by GpuStreamDevice once the function goes out of scope!
assert(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess);
streams.push_back(stream);
}
size_t device_iter = 0;
for (auto& weight_tensor_data : this->weight_tensors_) {
if (weight_tensor_data->getNSolverParams() > 0) {
Eigen::GpuStreamDevice stream_device(&streams[device_iter], getModelResources().at(0).getID());
Eigen::GpuDevice device(&stream_device);
if (!weight_tensor_data->getSolverParamsStatus().second)
weight_tensor_data->syncHAndDSolverParams(device);
Eigen::TensorMap<Eigen::Tensor<TensorT, 3>> solver_params(weight_tensor_data->getDSolverParamsPointer().get(), weight_tensor_data->getLayer1Size(), weight_tensor_data->getLayer2Size(), weight_tensor_data->getNSolverParams());
solver_params.chip(param_index, 2).device(device) = solver_params.chip(param_index, 2) * solver_params.chip(param_index, 2).constant(param_factor);
++device_iter;
}
}
// sync and destroy the streams
for (size_t i = 0; i < this->weight_tensors_.size(); ++i) {
assert(cudaStreamSynchronize(streams[i]) == cudaSuccess);
assert(cudaStreamDestroy(streams[i]) == cudaSuccess);
}
}
}
CEREAL_REGISTER_TYPE(SmartPeak::ModelInterpreterGpu<float>);
// TODO: add double, int, etc.
#endif
#endif //SMARTPEAK_MODELINTERPRETERGPU_H | 58.96034 | 319 | 0.756378 |
47df59e86cfbe6263a972f040f4cd35bdf868595 | 837 | h | C | TRAP/src/Graphics/API/OpenGL/OpenGLContext.h | GamesTrap/TRAP | 007de9ce70273cb8ae11066cc8488d9db78b1038 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-23T18:18:19.000Z | 2019-05-27T21:10:07.000Z | TRAP/src/Graphics/API/OpenGL/OpenGLContext.h | GamesTrap/TRAP | 007de9ce70273cb8ae11066cc8488d9db78b1038 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | 88 | 2018-08-02T01:08:04.000Z | 2019-07-24T19:13:26.000Z | TRAP/src/Graphics/API/OpenGL/OpenGLContext.h | GamesTrap/TRAP | 007de9ce70273cb8ae11066cc8488d9db78b1038 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2018-08-02T01:10:40.000Z | 2020-08-14T14:05:58.000Z | #ifndef _TRAP_OPENGLCONTEXT_H_
#define _TRAP_OPENGLCONTEXT_H_
#include "Graphics/API/Context.h"
namespace TRAP::Graphics::API
{
class OpenGLContext final : public Context
{
public:
explicit OpenGLContext(Window* window);
~OpenGLContext();
OpenGLContext(const OpenGLContext&) = default;
OpenGLContext& operator=(const OpenGLContext&) = default;
OpenGLContext(OpenGLContext&&) = default;
OpenGLContext& operator=(OpenGLContext&&) = default;
void SetVSyncIntervalInternal(uint32_t interval) override;
static void Present(const Scope<Window>& window);
void UseInternal(Window* window) override;
static OpenGLContext* Get();
static bool IsOpenGLCapable();
private:
static bool IsExtensionSupported(std::string_view extension);
static bool s_IsOpenGLInitialized;
};
}
#endif /*_TRAP_OPENGLCONTEXT_H_*/ | 24.617647 | 63 | 0.76822 |
2a23b83adcb813e9103745ac329fcafa3c0977f9 | 223 | h | C | examples/BlinkyDemo/patterns.h | Blinkinlabs/EightByEight | 9df6381c33987d6e1bdc88115bfc41287b6bc875 | [
"MIT"
] | 18 | 2016-08-23T03:45:16.000Z | 2021-02-20T20:50:02.000Z | examples/BlinkyDemo/patterns.h | Blinkinlabs/EightByEight | 9df6381c33987d6e1bdc88115bfc41287b6bc875 | [
"MIT"
] | 3 | 2016-10-22T19:02:44.000Z | 2020-09-21T18:12:24.000Z | examples/BlinkyDemo/patterns.h | Blinkinlabs/EightByEight | 9df6381c33987d6e1bdc88115bfc41287b6bc875 | [
"MIT"
] | 8 | 2016-08-19T20:56:57.000Z | 2020-12-25T01:39:12.000Z | #ifndef PATTERNS_H
#define PATTERNS_H
#include "patterndemo.h"
class Patterns
{
private:
uint32_t count;
public:
void begin();
uint32_t getCount();
PatternDemo open(int index);
};
#endif // PATTERNS_H
| 11.15 | 32 | 0.686099 |
46741f4d717f9b067ddc11711189789e6b779670 | 1,108 | h | C | src/constants.h | rahulsalvi/formula_dash_2019 | 5bc64f16c7df3e978fcd44c1f95a0bb9bf528ad4 | [
"MIT"
] | 1 | 2020-08-24T06:33:20.000Z | 2020-08-24T06:33:20.000Z | src/constants.h | rahulsalvi/formula_dash_2019 | 5bc64f16c7df3e978fcd44c1f95a0bb9bf528ad4 | [
"MIT"
] | null | null | null | src/constants.h | rahulsalvi/formula_dash_2019 | 5bc64f16c7df3e978fcd44c1f95a0bb9bf528ad4 | [
"MIT"
] | null | null | null | #ifndef CONSTANTS_H
#define CONSTANTS_H
#define LOOP_PERIOD 2000 // us
#define COOLANT 0
#define STATUS_BARS 1
#define SHIFT_LIGHTS 2
#define TACHOMETER 3
#define STARTER 1
#define DEBUG_ACTIVE 1
#define DEBUG_CONTROL 0
#define STATE_IDLE 0
#define STATE_INIT 1
#define STATE_NORMAL 2
#define STATE_DEBUG 3
#define ECU_ON_F_CYCLES 500
#define ECU_ON_T_CYCLES 1
#define DEBUG_ON_F_CYCLES 100
#define DEBUG_ON_T_CYCLES 100
#define PRESSED_CYCLES 5
#define SHORT_HELD_CYCLES 250
#define LONG_HELD_CYCLES 2500
#define CEL_CODES 48
#define CEL_OFFSET 0
#define FPR_CRITICAL_PSI 20
#define FPR_CRITICAL_F_CYCLES 99999999
#define FPR_CRITICAL_T_CYCLES 5000
#define FPR_CRITICAL_CODE 0
#define FPR_LOW_PSI 40
#define FPR_LOW_F_CYCLES 99999999
#define FPR_LOW_T_CYCLES 5000
#define FPR_LOW_CODE 1
#define BATTERY_CRITICAL_VOLTS 11.9
#define BATTERY_LOW_VOLTS 12.5
#define DEBUG_CLEAR_ERRORS 0
#define DEBUG_INC_BRIGHTNESS 1
#define DEBUG_DEC_BRIGHTNESS 2
#define DEBUG_NONE 0
#define DEBUG_PRESSED 1
#define DEBUG_SHORT_HELD 2
#define DEBUG_LONG_HELD 3
#define BRIGHTNESS_ADDR 97
#endif // CONSTANTS_H
| 19.103448 | 38 | 0.829422 |
a8fcd3d7caf16c4a53138dc9ad7b1f05d06a8a3f | 16,274 | h | C | fonts/NotoSans-Italic-7pt-ascii+degree+rus.h | virxkane/nucleo-f446re-st7735spi-shield | bd02a33ee2693424f08fdea26f463b964e95cb71 | [
"BSD-3-Clause"
] | 2 | 2022-01-11T12:22:43.000Z | 2022-01-22T22:32:39.000Z | fonts/NotoSans-Italic-7pt-ascii+degree+rus.h | virxkane/nucleo-f446re-st7735spi-shield | bd02a33ee2693424f08fdea26f463b964e95cb71 | [
"BSD-3-Clause"
] | null | null | null | fonts/NotoSans-Italic-7pt-ascii+degree+rus.h | virxkane/nucleo-f446re-st7735spi-shield | bd02a33ee2693424f08fdea26f463b964e95cb71 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************
* Generated by fontconvert utility:
* Font Name: 'Noto Sans', filepath: '/usr/share/fonts/noto/NotoSans-Italic.ttf'
* Size: 7pt
* DPI: 116
* Hinting: auto
Characters set ranges:
0: 0x0020 - 0x007E ('space' - 'asciitilde')
1: 0x00B0 - 0x00B0 ('degree' - 'degree')
2: 0x0401 - 0x0401 ('uni0401' - 'uni0401')
3: 0x0410 - 0x044F ('uni0410' - 'uni044F')
4: 0x0451 - 0x0451 ('uni0451' - 'uni0451')
*******************************************************************/
const uint8_t NotoSans_Italic7pt_mixed_Bitmaps[] = {
0x00, 0x25, 0xA4, 0x86, 0x7A, 0xA0, 0x14, 0x29, 0xF9, 0x22, 0x9F, 0xD2,
0x28, 0x11, 0xE5, 0x0C, 0x28, 0xAF, 0x08, 0x62, 0xA4, 0xA8, 0xAE, 0xD9,
0x2A, 0x4A, 0x4E, 0x18, 0x48, 0x91, 0xC5, 0x31, 0xB3, 0x3B, 0x68, 0x12,
0x44, 0x48, 0x88, 0x44, 0x21, 0x11, 0x13, 0x22, 0x48, 0x17, 0x0E, 0xA1,
0x00, 0x21, 0x3E, 0x42, 0x00, 0x68, 0xE0, 0xC0, 0x04, 0x20, 0x84, 0x20,
0x84, 0x10, 0x72, 0x63, 0x18, 0xCE, 0x5C, 0x75, 0x24, 0x94, 0x38, 0x10,
0x42, 0x10, 0x84, 0x3E, 0x38, 0x10, 0xCC, 0x08, 0x20, 0xBC, 0x0C, 0x51,
0x8A, 0x4B, 0xF0, 0x84, 0x3C, 0x82, 0x1E, 0x08, 0x20, 0xBC, 0x3A, 0x31,
0x6D, 0xC6, 0x5C, 0xF8, 0x44, 0x22, 0x21, 0x10, 0x3C, 0x92, 0x4A, 0x79,
0x24, 0x9E, 0x74, 0x63, 0x36, 0x88, 0xDC, 0x40, 0x01, 0x80, 0x20, 0x00,
0x64, 0x40, 0x00, 0xD9, 0x83, 0x04, 0xF8, 0x3E, 0x06, 0x0C, 0x36, 0x40,
0xF1, 0x12, 0x48, 0x08, 0x1E, 0x61, 0x9D, 0xA5, 0xA5, 0xA9, 0xB6, 0xC0,
0x7C, 0x0C, 0x18, 0x50, 0xA3, 0x47, 0x90, 0xA1, 0x3C, 0x4C, 0x93, 0xC4,
0x48, 0x91, 0x3C, 0x3D, 0x8C, 0x20, 0x82, 0x08, 0x1E, 0x3C, 0x4C, 0x8A,
0x14, 0x28, 0xD3, 0x3C, 0x3C, 0x82, 0x1E, 0x41, 0x04, 0x1E, 0x3C, 0x82,
0x10, 0x79, 0x04, 0x10, 0x3D, 0x8C, 0x20, 0x9E, 0x18, 0x9E, 0x21, 0x22,
0x22, 0x7E, 0x42, 0x46, 0x44, 0x44, 0x72, 0x22, 0x44, 0x4E, 0x08, 0x42,
0x21, 0x08, 0x42, 0x27, 0x00, 0x22, 0x48, 0xA2, 0x87, 0x09, 0x12, 0x26,
0x21, 0x08, 0x84, 0x21, 0x0F, 0x30, 0x8C, 0x63, 0x19, 0x4A, 0x54, 0x95,
0x44, 0x91, 0x24, 0x21, 0x31, 0x31, 0x4A, 0x4A, 0x4A, 0x46, 0x44, 0x3C,
0x8A, 0x0C, 0x18, 0x30, 0xA3, 0x3C, 0x3C, 0x92, 0x51, 0x79, 0x04, 0x10,
0x3C, 0x8A, 0x0C, 0x18, 0x30, 0xA3, 0x3C, 0x10, 0x10, 0x3C, 0x92, 0x51,
0x79, 0x24, 0x93, 0x3D, 0x84, 0x08, 0x18, 0x20, 0xBC, 0xFC, 0x82, 0x08,
0x61, 0x04, 0x10, 0x42, 0x89, 0x14, 0x28, 0x51, 0xA2, 0x38, 0x86, 0x28,
0xA4, 0x91, 0x86, 0x10, 0x88, 0xA2, 0x29, 0x5A, 0x54, 0xA5, 0x29, 0x8C,
0x61, 0x10, 0x22, 0x12, 0x14, 0x08, 0x18, 0x28, 0x24, 0x44, 0x8A, 0x25,
0x18, 0x61, 0x04, 0x10, 0x3C, 0x10, 0x84, 0x21, 0x84, 0x3E, 0x32, 0x44,
0x44, 0x48, 0x8C, 0xA5, 0x55, 0x31, 0x11, 0x12, 0x22, 0x2C, 0x10, 0xC4,
0x92, 0x44, 0xF8, 0xA0, 0x7C, 0x63, 0x29, 0x78, 0x20, 0x85, 0xD9, 0x45,
0x14, 0xAE, 0x78, 0x88, 0x8E, 0x04, 0x27, 0xA2, 0x8A, 0x69, 0x3C, 0x79,
0xE8, 0x8F, 0x1C, 0x43, 0x88, 0x20, 0x82, 0x08, 0x41, 0x0C, 0x00, 0x3D,
0x34, 0x52, 0x49, 0xE0, 0x86, 0xF0, 0x20, 0x83, 0xD9, 0x45, 0x14, 0xA2,
0x21, 0x24, 0x94, 0x10, 0x22, 0x22, 0x24, 0x44, 0xC0, 0x20, 0x82, 0x94,
0x61, 0x45, 0x22, 0x24, 0xA4, 0x94, 0x59, 0xB3, 0x51, 0x29, 0x14, 0x8C,
0x48, 0x5D, 0x94, 0x53, 0x4A, 0x20, 0x74, 0x63, 0x19, 0x70, 0x5D, 0x94,
0x51, 0x4A, 0xE8, 0x20, 0x80, 0x7C, 0x63, 0x29, 0x78, 0x42, 0x20, 0x5B,
0x10, 0x84, 0x40, 0x7A, 0x10, 0x61, 0x78, 0x22, 0x74, 0x44, 0x46, 0x8C,
0x63, 0x29, 0x78, 0x9C, 0xA9, 0x4C, 0x60, 0x92, 0xB2, 0xB4, 0xD4, 0xD8,
0x88, 0x48, 0xC3, 0x08, 0x52, 0x40, 0x26, 0x48, 0xB1, 0x43, 0x06, 0x08,
0x10, 0xC0, 0x78, 0x88, 0x84, 0x78, 0x11, 0x08, 0x48, 0x21, 0x08, 0x43,
0x00, 0xFF, 0xE0, 0x62, 0x22, 0x23, 0x44, 0x48, 0xE1, 0xC0, 0xF6, 0xF0,
0x14, 0x03, 0xC8, 0x21, 0xE4, 0x10, 0x41, 0xE0, 0x0C, 0x18, 0x50, 0xA3,
0x47, 0x90, 0xA1, 0x3C, 0x82, 0x1E, 0x4D, 0x14, 0x9C, 0x3C, 0x4C, 0x93,
0xC4, 0x48, 0x91, 0x3C, 0x3C, 0x82, 0x10, 0x41, 0x04, 0x10, 0x07, 0x09,
0x0A, 0x12, 0x12, 0x22, 0x22, 0x7E, 0x82, 0x82, 0x3C, 0x82, 0x1E, 0x41,
0x04, 0x1E, 0x32, 0x42, 0x58, 0x36, 0x07, 0x80, 0xE0, 0x2A, 0x09, 0x42,
0x44, 0x38, 0x10, 0x4E, 0x08, 0x20, 0xBC, 0x23, 0x23, 0x26, 0x4A, 0x52,
0x72, 0x62, 0x44, 0x12, 0x0E, 0x23, 0x23, 0x26, 0x4A, 0x52, 0x72, 0x62,
0x44, 0x22, 0x48, 0xA2, 0x87, 0x0A, 0x12, 0x26, 0x1E, 0x24, 0x49, 0x12,
0x44, 0x91, 0x62, 0x30, 0x8C, 0x63, 0x19, 0x4A, 0x54, 0x95, 0x44, 0x91,
0x24, 0x21, 0x22, 0x22, 0x7E, 0x42, 0x46, 0x44, 0x44, 0x3C, 0x8A, 0x0C,
0x18, 0x30, 0xA3, 0x3C, 0x3F, 0x22, 0x22, 0x42, 0x42, 0x42, 0x44, 0x44,
0x3C, 0x92, 0x51, 0x79, 0x04, 0x10, 0x3D, 0x8C, 0x20, 0x82, 0x08, 0x1E,
0xFC, 0x82, 0x08, 0x61, 0x04, 0x10, 0x42, 0x26, 0x24, 0x28, 0x28, 0x10,
0x20, 0xC0, 0x08, 0xFB, 0x4C, 0x99, 0x32, 0xDE, 0x10, 0x22, 0x12, 0x14,
0x08, 0x18, 0x28, 0x24, 0x44, 0x22, 0x22, 0x22, 0x42, 0x42, 0x44, 0x44,
0x7E, 0x02, 0x04, 0x45, 0x1C, 0x63, 0x78, 0x20, 0x82, 0x22, 0x24, 0x44,
0x99, 0x22, 0x24, 0x44, 0x88, 0x91, 0x33, 0xFC, 0x22, 0x24, 0x44, 0x99,
0x22, 0x24, 0x44, 0x88, 0x91, 0x23, 0xFE, 0x00, 0x40, 0x08, 0xE1, 0x10,
0xF4, 0xA5, 0x3E, 0x20, 0x90, 0x48, 0x4F, 0x24, 0xD2, 0x29, 0x24, 0xE4,
0x20, 0x82, 0x1E, 0x4D, 0x14, 0x9C, 0x78, 0x10, 0x4F, 0x04, 0x10, 0xBC,
0x23, 0xC4, 0x88, 0xB0, 0xBC, 0x14, 0x86, 0x90, 0x93, 0x32, 0x3C, 0x3C,
0xC9, 0x11, 0x23, 0xCD, 0x12, 0x44, 0x7C, 0x63, 0x29, 0x78, 0x19, 0x8C,
0x2C, 0xDA, 0x29, 0x24, 0xE0, 0x74, 0x7D, 0x29, 0x78, 0x78, 0x44, 0xC8,
0x38, 0x70, 0xC2, 0xF9, 0xC6, 0x52, 0xE0, 0x79, 0xE8, 0x8F, 0x65, 0xCE,
0xC3, 0xE0, 0xA8, 0x2A, 0x32, 0x60, 0x70, 0x5C, 0x21, 0x70, 0x8C, 0x63,
0x29, 0x78, 0x49, 0xC1, 0x18, 0xC6, 0x52, 0xF0, 0x4D, 0x67, 0x18, 0x52,
0x20, 0x0E, 0x24, 0x51, 0x22, 0x58, 0x80, 0x62, 0x66, 0x66, 0x6A, 0x6A,
0x94, 0x45, 0x17, 0xD1, 0x4A, 0x20, 0x74, 0x63, 0x19, 0x70, 0x5D, 0x94,
0x53, 0x4A, 0x20, 0x5D, 0x94, 0x51, 0x4A, 0xE8, 0x20, 0x80, 0x78, 0x88,
0x8E, 0x59, 0xB3, 0x51, 0x29, 0x14, 0x8C, 0x48, 0x26, 0x48, 0xB1, 0x43,
0x06, 0x08, 0x10, 0xC0, 0x10, 0x47, 0xA5, 0xA6, 0x9A, 0xBC, 0x21, 0x04,
0x00, 0x48, 0xC3, 0x08, 0x52, 0x40, 0x8C, 0x63, 0x29, 0x7C, 0x21, 0x8C,
0x65, 0xE1, 0x08, 0x89, 0x44, 0xA4, 0x52, 0x2B, 0x36, 0x70, 0x89, 0x44,
0xA4, 0x52, 0x2B, 0x36, 0x68, 0x04, 0x02, 0x60, 0x83, 0xC9, 0x24, 0xE0,
0x83, 0x07, 0xD4, 0xA9, 0x5C, 0x80, 0x88, 0xF9, 0x9E, 0x70, 0x5E, 0x31,
0x70, 0x4F, 0x49, 0x71, 0x51, 0x51, 0x8E, 0x3D, 0x24, 0x8E, 0x4A, 0x40,
0x50, 0x79, 0xE8, 0x8F };
const GFXglyph NotoSans_Italic7pt_mixed_Glyphs[] = {
{ 0, 1, 1, 3, 0, 0 }, // 0x20 'space'
{ 1, 3, 8, 3, 0, -7 }, // 0x21 'exclam'
{ 4, 4, 3, 4, 1, -7 }, // 0x22 'quotedbl'
{ 6, 7, 8, 7, 0, -7 }, // 0x23 'numbersign'
{ 13, 6, 8, 6, 0, -7 }, // 0x24 'dollar'
{ 19, 8, 8, 9, 1, -7 }, // 0x25 'percent'
{ 27, 7, 8, 8, 0, -7 }, // 0x26 'ampersand'
{ 34, 2, 3, 2, 1, -7 }, // 0x27 'quotesingle'
{ 35, 4, 10, 3, 0, -7 }, // 0x28 'parenleft'
{ 40, 4, 10, 3, -1, -7 }, // 0x29 'parenright'
{ 45, 5, 5, 6, 1, -7 }, // 0x2A 'asterisk'
{ 49, 5, 5, 6, 1, -5 }, // 0x2B 'plus'
{ 53, 2, 3, 3, 0, -1 }, // 0x2C 'comma'
{ 54, 3, 1, 4, 0, -2 }, // 0x2D 'hyphen'
{ 55, 2, 1, 3, 0, 0 }, // 0x2E 'period'
{ 56, 6, 8, 4, -1, -7 }, // 0x2F 'slash'
{ 62, 5, 8, 6, 1, -7 }, // 0x30 'zero'
{ 67, 3, 8, 6, 2, -7 }, // 0x31 'one'
{ 70, 6, 8, 6, 0, -7 }, // 0x32 'two'
{ 76, 6, 8, 6, 0, -7 }, // 0x33 'three'
{ 82, 6, 8, 6, 0, -7 }, // 0x34 'four'
{ 88, 6, 8, 6, 0, -7 }, // 0x35 'five'
{ 94, 5, 8, 6, 1, -7 }, // 0x36 'six'
{ 99, 5, 8, 6, 1, -7 }, // 0x37 'seven'
{ 104, 6, 8, 6, 0, -7 }, // 0x38 'eight'
{ 110, 5, 8, 6, 1, -7 }, // 0x39 'nine'
{ 115, 3, 6, 3, 0, -5 }, // 0x3A 'colon'
{ 118, 4, 7, 3, -1, -5 }, // 0x3B 'semicolon'
{ 122, 5, 6, 6, 1, -6 }, // 0x3C 'less'
{ 126, 5, 3, 6, 1, -4 }, // 0x3D 'equal'
{ 128, 5, 6, 6, 1, -6 }, // 0x3E 'greater'
{ 132, 4, 8, 5, 1, -7 }, // 0x3F 'question'
{ 136, 8, 9, 10, 1, -7 }, // 0x40 'at'
{ 145, 7, 8, 6, -1, -7 }, // 0x41 'A'
{ 152, 7, 8, 7, 0, -7 }, // 0x42 'B'
{ 159, 6, 8, 7, 1, -7 }, // 0x43 'C'
{ 165, 7, 8, 8, 0, -7 }, // 0x44 'D'
{ 172, 6, 8, 6, 0, -7 }, // 0x45 'E'
{ 178, 6, 8, 5, 0, -7 }, // 0x46 'F'
{ 184, 6, 8, 8, 1, -7 }, // 0x47 'G'
{ 190, 8, 8, 8, 0, -7 }, // 0x48 'H'
{ 198, 4, 8, 4, 0, -7 }, // 0x49 'I'
{ 202, 5, 10, 3, -2, -7 }, // 0x4A 'J'
{ 209, 7, 8, 6, 0, -7 }, // 0x4B 'K'
{ 216, 5, 8, 5, 0, -7 }, // 0x4C 'L'
{ 221, 10, 8, 9, 0, -7 }, // 0x4D 'M'
{ 231, 8, 8, 8, 0, -7 }, // 0x4E 'N'
{ 239, 7, 8, 8, 1, -7 }, // 0x4F 'O'
{ 246, 6, 8, 6, 0, -7 }, // 0x50 'P'
{ 252, 7, 10, 8, 1, -7 }, // 0x51 'Q'
{ 261, 6, 8, 6, 0, -7 }, // 0x52 'R'
{ 267, 6, 8, 6, 0, -7 }, // 0x53 'S'
{ 273, 6, 8, 6, 1, -7 }, // 0x54 'T'
{ 279, 7, 8, 8, 1, -7 }, // 0x55 'U'
{ 286, 6, 8, 6, 1, -7 }, // 0x56 'V'
{ 292, 10, 8, 10, 1, -7 }, // 0x57 'W'
{ 302, 8, 8, 6, -1, -7 }, // 0x58 'X'
{ 310, 6, 8, 6, 1, -7 }, // 0x59 'Y'
{ 316, 6, 8, 6, 0, -7 }, // 0x5A 'Z'
{ 322, 4, 10, 3, 0, -7 }, // 0x5B 'bracketleft'
{ 327, 2, 8, 4, 1, -7 }, // 0x5C 'backslash'
{ 329, 4, 10, 3, -1, -7 }, // 0x5D 'bracketright'
{ 334, 6, 5, 6, 0, -7 }, // 0x5E 'asciicircum'
{ 338, 5, 1, 4, -1, 2 }, // 0x5F 'underscore'
{ 339, 2, 2, 3, 2, -8 }, // 0x60 'grave'
{ 340, 5, 6, 6, 1, -5 }, // 0x61 'a'
{ 344, 6, 8, 7, 0, -7 }, // 0x62 'b'
{ 350, 4, 6, 5, 1, -5 }, // 0x63 'c'
{ 353, 6, 8, 7, 1, -7 }, // 0x64 'd'
{ 359, 4, 6, 6, 1, -5 }, // 0x65 'e'
{ 362, 6, 11, 4, -1, -7 }, // 0x66 'f'
{ 371, 6, 9, 7, 0, -5 }, // 0x67 'g'
{ 378, 6, 8, 7, 0, -7 }, // 0x68 'h'
{ 384, 3, 8, 3, 0, -7 }, // 0x69 'i'
{ 387, 4, 11, 3, -1, -7 }, // 0x6A 'j'
{ 393, 6, 8, 6, 0, -7 }, // 0x6B 'k'
{ 399, 3, 8, 3, 0, -7 }, // 0x6C 'l'
{ 402, 9, 6, 10, 0, -5 }, // 0x6D 'm'
{ 409, 6, 6, 7, 0, -5 }, // 0x6E 'n'
{ 414, 5, 6, 6, 1, -5 }, // 0x6F 'o'
{ 418, 6, 9, 7, 0, -5 }, // 0x70 'p'
{ 425, 5, 9, 7, 1, -5 }, // 0x71 'q'
{ 431, 5, 6, 4, 0, -5 }, // 0x72 'r'
{ 435, 5, 6, 5, 0, -5 }, // 0x73 's'
{ 439, 4, 8, 4, 0, -7 }, // 0x74 't'
{ 443, 5, 6, 7, 1, -5 }, // 0x75 'u'
{ 447, 5, 6, 5, 1, -5 }, // 0x76 'v'
{ 451, 8, 6, 8, 1, -5 }, // 0x77 'w'
{ 457, 6, 6, 5, 0, -5 }, // 0x78 'x'
{ 462, 7, 9, 5, -1, -5 }, // 0x79 'y'
{ 470, 5, 6, 5, 0, -5 }, // 0x7A 'z'
{ 474, 5, 10, 4, 0, -7 }, // 0x7B 'braceleft'
{ 481, 1, 11, 6, 3, -7 }, // 0x7C 'bar'
{ 483, 4, 10, 4, 0, -7 }, // 0x7D 'braceright'
{ 488, 5, 2, 6, 1, -4 }, // 0x7E 'asciitilde'
{ 490, 3, 4, 5, 1, -7 }, // 0xB0 'degree'
{ 492, 6, 10, 6, 0, -9 }, // 0x401 'uni0401'
{ 500, 7, 8, 6, -1, -7 }, // 0x410 'uni0410'
{ 507, 6, 8, 6, 0, -7 }, // 0x411 'uni0411'
{ 513, 7, 8, 7, 0, -7 }, // 0x412 'uni0412'
{ 520, 6, 8, 5, 0, -7 }, // 0x413 'uni0413'
{ 526, 8, 10, 7, -1, -7 }, // 0x414 'uni0414'
{ 536, 6, 8, 6, 0, -7 }, // 0x415 'uni0415'
{ 542, 11, 8, 9, -1, -7 }, // 0x416 'uni0416'
{ 553, 6, 8, 6, 0, -7 }, // 0x417 'uni0417'
{ 559, 8, 8, 8, 0, -7 }, // 0x418 'uni0418'
{ 567, 8, 10, 8, 0, -9 }, // 0x419 'uni0419'
{ 577, 7, 8, 6, 0, -7 }, // 0x41A 'uni041A'
{ 584, 7, 8, 7, 0, -7 }, // 0x41B 'uni041B'
{ 591, 10, 8, 9, 0, -7 }, // 0x41C 'uni041C'
{ 601, 8, 8, 8, 0, -7 }, // 0x41D 'uni041D'
{ 609, 7, 8, 8, 1, -7 }, // 0x41E 'uni041E'
{ 616, 8, 8, 8, 0, -7 }, // 0x41F 'uni041F'
{ 624, 6, 8, 6, 0, -7 }, // 0x420 'uni0420'
{ 630, 6, 8, 7, 1, -7 }, // 0x421 'uni0421'
{ 636, 6, 8, 6, 1, -7 }, // 0x422 'uni0422'
{ 642, 8, 8, 6, 0, -7 }, // 0x423 'uni0423'
{ 650, 7, 8, 8, 1, -7 }, // 0x424 'uni0424'
{ 657, 8, 8, 6, -1, -7 }, // 0x425 'uni0425'
{ 665, 8, 10, 8, 0, -7 }, // 0x426 'uni0426'
{ 675, 6, 8, 7, 1, -7 }, // 0x427 'uni0427'
{ 681, 11, 8, 11, 0, -7 }, // 0x428 'uni0428'
{ 692, 11, 10, 11, 0, -7 }, // 0x429 'uni0429'
{ 706, 5, 8, 7, 1, -7 }, // 0x42A 'uni042A'
{ 711, 9, 8, 9, 0, -7 }, // 0x42B 'uni042B'
{ 720, 6, 8, 6, 0, -7 }, // 0x42C 'uni042C'
{ 726, 6, 8, 7, 0, -7 }, // 0x42D 'uni042D'
{ 732, 11, 8, 11, 0, -7 }, // 0x42E 'uni042E'
{ 743, 7, 8, 6, 0, -7 }, // 0x42F 'uni042F'
{ 750, 5, 6, 6, 1, -5 }, // 0x430 'uni0430'
{ 754, 6, 9, 6, 1, -8 }, // 0x431 'uni0431'
{ 761, 5, 6, 6, 1, -5 }, // 0x432 'uni0432'
{ 765, 5, 6, 5, 0, -5 }, // 0x433 'uni0433'
{ 769, 5, 9, 6, 1, -8 }, // 0x434 'uni0434'
{ 775, 4, 6, 6, 1, -5 }, // 0x435 'uni0435'
{ 778, 10, 6, 10, 0, -5 }, // 0x436 'uni0436'
{ 786, 5, 6, 5, 0, -5 }, // 0x437 'uni0437'
{ 790, 5, 6, 7, 1, -5 }, // 0x438 'uni0438'
{ 794, 5, 9, 7, 1, -8 }, // 0x439 'uni0439'
{ 800, 6, 6, 5, 0, -5 }, // 0x43A 'uni043A'
{ 805, 7, 6, 6, -1, -5 }, // 0x43B 'uni043B'
{ 811, 8, 6, 8, 0, -5 }, // 0x43C 'uni043C'
{ 817, 6, 6, 7, 0, -5 }, // 0x43D 'uni043D'
{ 822, 5, 6, 6, 1, -5 }, // 0x43E 'uni043E'
{ 826, 6, 6, 7, 0, -5 }, // 0x43F 'uni043F'
{ 831, 6, 9, 7, 0, -5 }, // 0x440 'uni0440'
{ 838, 4, 6, 5, 1, -5 }, // 0x441 'uni0441'
{ 841, 9, 6, 10, 0, -5 }, // 0x442 'uni0442'
{ 848, 7, 9, 5, -1, -5 }, // 0x443 'uni0443'
{ 856, 6, 11, 8, 1, -7 }, // 0x444 'uni0444'
{ 865, 6, 6, 5, 0, -5 }, // 0x445 'uni0445'
{ 870, 5, 8, 7, 1, -5 }, // 0x446 'uni0446'
{ 875, 5, 6, 6, 1, -5 }, // 0x447 'uni0447'
{ 879, 9, 6, 10, 1, -5 }, // 0x448 'uni0448'
{ 886, 9, 8, 10, 1, -5 }, // 0x449 'uni0449'
{ 895, 6, 6, 7, 0, -5 }, // 0x44A 'uni044A'
{ 900, 7, 6, 8, 1, -5 }, // 0x44B 'uni044B'
{ 906, 4, 6, 6, 1, -5 }, // 0x44C 'uni044C'
{ 909, 5, 6, 5, 0, -5 }, // 0x44D 'uni044D'
{ 913, 8, 6, 9, 0, -5 }, // 0x44E 'uni044E'
{ 919, 6, 6, 6, 0, -5 }, // 0x44F 'uni044F'
{ 924, 4, 8, 6, 1, -7 } }; // 0x451 'uni0451'
const GFXglyphRange NotoSans_Italic7pt_mixed_Ranges[] = {
{ 0x0020, 0x007E },
{ 0x00B0, 0x00B0 },
{ 0x0401, 0x0401 },
{ 0x0410, 0x044F },
{ 0x0451, 0x0451 } };
const GFXfont NotoSans_Italic7pt_mixed = {
NotoSans_Italic7pt_mixed_Bitmaps,
NotoSans_Italic7pt_mixed_Glyphs,
NotoSans_Italic7pt_mixed_Ranges, 5,
162, // characters count
15, // newline distance in pixels
928 }; // bitmap size
// Approx. 2296 bytes
| 59.178182 | 80 | 0.442239 |
627fa4c50303178f4b4f423a3f539ac2a5ade09e | 851 | h | C | Sort/ShellSort.h | zhuifeng740643787/algorithm-CPP | 94a17ffe822659c8264ae6cf3fb30525748108de | [
"MIT"
] | 1 | 2017-07-03T02:42:12.000Z | 2017-07-03T02:42:12.000Z | Sort/ShellSort.h | zhuifeng740643787/algorithm-CPP | 94a17ffe822659c8264ae6cf3fb30525748108de | [
"MIT"
] | null | null | null | Sort/ShellSort.h | zhuifeng740643787/algorithm-CPP | 94a17ffe822659c8264ae6cf3fb30525748108de | [
"MIT"
] | null | null | null | //
// Created by 宫宜栋 on 2017/6/16.
//
#ifndef ALGORITHM_SHELLSORT_H
#define ALGORITHM_SHELLSORT_H
#include <iostream>
using namespace std;
/**
* 希尔排序 O(n2)
* 基于插入排序,将数组先分成以d=n/2为间隔的组,依次对这d组进行一次插入排序,完成后,再将数组分成d=d/2份,。。。直到d=1
* 优点:通过设置间隔d,可以让一个元素一次性的朝最终位置前进一大步(插入排序一次只能移动一步)
*/
class ShellSort {
public:
static void run(int arr[], int n) {
int d;//元素间的间隔
for (d = n / 2; d >= 1; d /= 2) {
for (int i = 0; i < d; i++) {
for (int j = i + d; j < n; j += d) {
//插入排序
int e = arr[j];
int k;
for (k = j; k > i && arr[k - 1] > e; k -= d) {
arr[k] = arr[k - d];
}
arr[k] = e;
}
}
}
}
};
#endif //ALGORITHM_SHELLSORT_H
| 21.275 | 68 | 0.430082 |
d10ed04bb0f44fca68d4424c02cf7c1b256bd3ce | 548 | c | C | testing/fulltests/unit-tests/T026read_config_clib.c | minfrin/net-snmp | 4cb9a49f7af376dad63912f85f0cdb4dd2a90a4f | [
"Net-SNMP"
] | 156 | 2018-05-11T09:50:50.000Z | 2022-03-21T17:22:11.000Z | testing/fulltests/unit-tests/T026read_config_clib.c | minfrin/net-snmp | 4cb9a49f7af376dad63912f85f0cdb4dd2a90a4f | [
"Net-SNMP"
] | 384 | 2018-06-15T11:40:56.000Z | 2022-03-28T16:28:39.000Z | testing/fulltests/unit-tests/T026read_config_clib.c | minfrin/net-snmp | 4cb9a49f7af376dad63912f85f0cdb4dd2a90a4f | [
"Net-SNMP"
] | 151 | 2018-04-27T10:14:09.000Z | 2022-03-10T16:22:11.000Z | /*
* HEADER Testing read_config()
*/
static const unsigned char data[] = { 0xff, 0x20, 0xff };
char *path;
FILE *f;
int res;
register_mib_handlers();
res = asprintf(&path, "/tmp/read-config-input-%d", getpid());
OKF(res >= 0, ("asprintf() returned %d", res));
f = fopen(path, "wb");
OKF(f != NULL, ("fopen() %s", f ? "succeeded" : "failed"));
res = fwrite(data, sizeof(data), 1, f);
OKF(res == 1, ("fwrite() %s", res == 1 ? "succeeded" : "failed"));
fclose(f);
read_config(path, read_config_get_handlers("snmp"), 0);
unlink(path);
free(path);
| 24.909091 | 66 | 0.618613 |
2f7d0ed4ff1cdde3aa0f4e1cb6929ac96e88f56c | 1,058 | c | C | Courses/Operating_Systems/Notes and code/Fork_wait_exec.c | biancaguzenski/roadmap | adb7f9405080f616df2ddb5fc2007917f46f265f | [
"MIT"
] | 1 | 2020-10-29T21:33:16.000Z | 2020-10-29T21:33:16.000Z | Courses/Operating_Systems/Notes and code/Fork_wait_exec.c | biancaguzenski/learning-path | adb7f9405080f616df2ddb5fc2007917f46f265f | [
"MIT"
] | null | null | null | Courses/Operating_Systems/Notes and code/Fork_wait_exec.c | biancaguzenski/learning-path | adb7f9405080f616df2ddb5fc2007917f46f265f | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(){
printf("Hello world (pid:%d)\n", (int) getpid());
int rc = fork();
if (rc < 0){
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) {
printf("Hello, I'm a new process! (pid:%d)\n", (int) getpid());
char *myargs[3];
myargs[0] = strdup("wc"); /* program wc (word count) */
myargs[1] = strdup("Fork_wait_exec.c"); /* arg: file to count */
myargs[2] = NULL; /* end of array */
execvp(myargs[0], myargs); /* runs word count */
printf("This souldn't print out");
} else {
int rc_wait = wait(NULL);
printf("Hello, I'm a process-parent of %d (rc_wait:%d) (pid:%d)\n", rc, rc_wait, (int) getpid());
}
return 0;
}
/* T he child process calls execvp() in order to run the program wc,
which is the word counting program. In fact, it runs wc on the source file,
thus telling us how many lines, words, and bytes are found in the file. */
| 34.129032 | 104 | 0.58034 |
4dc055b7bea48885a16e3b92703752d09e8d013e | 1,745 | h | C | dali-extension/web-engine-chromium/tizen-web-engine-security-origin.h | dalihub/dali-extension | 9bd20cbbf588828621acc1467c61c5168d7e1772 | [
"Apache-2.0"
] | null | null | null | dali-extension/web-engine-chromium/tizen-web-engine-security-origin.h | dalihub/dali-extension | 9bd20cbbf588828621acc1467c61c5168d7e1772 | [
"Apache-2.0"
] | null | null | null | dali-extension/web-engine-chromium/tizen-web-engine-security-origin.h | dalihub/dali-extension | 9bd20cbbf588828621acc1467c61c5168d7e1772 | [
"Apache-2.0"
] | 2 | 2020-08-29T01:26:29.000Z | 2021-05-24T07:35:51.000Z | #ifndef DALI_PLUGIN_TIZEN_WEB_ENGINE_SECURITY_ORIGIN_H
#define DALI_PLUGIN_TIZEN_WEB_ENGINE_SECURITY_ORIGIN_H
/*
* Copyright (c) 2021 Samsung Electronics 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.
*
*/
// EXTERNAL INCLUDES
#include <ewk_security_origin.h>
#include <string>
#include <dali/devel-api/adaptor-framework/web-engine-security-origin.h>
namespace Dali
{
namespace Plugin
{
/**
* @brief A class TizenWebEngineSecurityOrigin for security origin.
*/
class TizenWebEngineSecurityOrigin : public Dali::WebEngineSecurityOrigin
{
public:
/**
* @brief Constructor.
*/
TizenWebEngineSecurityOrigin(Ewk_Security_Origin*);
/**
* @brief Destructor.
*/
~TizenWebEngineSecurityOrigin();
/**
* @copydoc Dali::WebEngineSecurityOrigin::GetHost()
*/
std::string GetHost() const override;
/**
* @copydoc Dali::WebEngineSecurityOrigin::GetProtocol()
*/
std::string GetProtocol() const override;
/**
* @brief Get security origin.
*
* @return origin pointer.
*/
Ewk_Security_Origin* GetSecurityOrigin() const;
private:
Ewk_Security_Origin* ewkSecurityOrigin;
};
} // namespace Plugin
} // namespace Dali
#endif // DALI_PLUGIN_TIZEN_WEB_ENGINE_SECURITY_ORIGIN_H
| 23.90411 | 75 | 0.736963 |
b13133413ac399cc7463743f3c28784b6dd23ae9 | 598 | c | C | rush_00/rush04.c | rodrigowe1988/basecamp_42 | 6861755ea7e035a6156129ca7c16c6006b51f172 | [
"MIT"
] | null | null | null | rush_00/rush04.c | rodrigowe1988/basecamp_42 | 6861755ea7e035a6156129ca7c16c6006b51f172 | [
"MIT"
] | null | null | null | rush_00/rush04.c | rodrigowe1988/basecamp_42 | 6861755ea7e035a6156129ca7c16c6006b51f172 | [
"MIT"
] | null | null | null | void ft_putchar(char c);
void rush(int x, int y)
{
int width;
int height;
width = 1;
while (width <= y)
{
height = 1;
while (height <= x)
{
if ((height == 1 && width == 1) || (height == x && width == y))
ft_putchar('A');
else if ((height == x && width == 1) || (height == 1 && width == y))
ft_putchar('C');
else if ((height > 1 && height < x) && (width == 1 || width == y))
ft_putchar('B');
else if ((width > 1 && width < y) && (height == 1 || height == x))
ft_putchar('B');
else
ft_putchar(' ');
height++;
}
ft_putchar('\n');
width++;
}
} | 20.62069 | 71 | 0.488294 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.