blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
963ca51b4860678d20535de3f4cbf8a11e868747 | befabce8ca2542eba05059240e8b5e826ea02ef8 | /kill-ball/src/core/input.h | 09ea38042a8660a33abed2db653b493c930b86bf | [] | no_license | merenciano/school-projects | 64dd7ddc7f5fba682c86f6cdf96a75457dbf2bfb | 76fb1d688420920a43e32d4882ce891a87a20016 | refs/heads/master | 2023-06-15T17:07:35.911267 | 2021-07-14T13:33:53 | 2021-07-14T13:33:53 | 385,950,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 882 | h | #ifndef __LEEP_CORE_INPUT_H__
#define __LEEP_CORE_INPUT_H__ 1
#include "core/input-state.h"
namespace leep
{
enum class Button
{
NONE,
UP,
DOWN,
LEFT,
RIGHT,
B1,
B2,
B3,
B4,
MOUSE_LEFT,
MOUSE_RIGHT
};
class Input
{
public:
Input();
~Input();
void init(void *window);
void updateInput();
void set_scroll(float offset);
void enableCursor() const;
void disableCursor() const;
bool isButtonDown(Button b) const;
bool isButtonPressed(Button b) const;
bool isButtonUp(Button b) const;
float mouseX() const;
float mouseY() const;
float scroll() const;
private:
struct InputData;
InputData *data_;
};
}
#endif // __LEEP_CORE_INPUT_H__ | [
"lucasmermar@gmail.com"
] | lucasmermar@gmail.com |
5e3ddfd4c222d5a11d83a687b3f6b8b400454f27 | 28c74f542bc5a880ed4c44fffe7d9e220313d7a5 | /4DPlugin.cpp | 38d3963d43a6e30129110ae23ab6e73142faf7da | [] | no_license | vrosnet/4d-plugin-help-menu | 8ad9cbf735fcd6c8904f4ec9fe33f6941ba0c0bc | 4e6e344efb0b1e7d212a9c0caf1f187d852ff56e | refs/heads/master | 2020-12-26T13:05:02.798012 | 2016-07-25T03:20:14 | 2016-07-25T03:20:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,961 | cpp | /* --------------------------------------------------------------------------------
#
# 4DPlugin.cpp
# source generated by 4D Plugin Wizard
# Project : Help Menu
# author : miyako
# 2015/11/16
#
# --------------------------------------------------------------------------------*/
#include "4DPluginAPI.h"
#include "4DPlugin.h"
namespace Help
{
BOOL isHelpDisabled;
#if VERSIONWIN
HWND mdiWindowRef;
#else
#if !__LP64__
MenuRef helpMenuRef;
#endif
#endif
void enable()
{
if(Help::isHelpDisabled)
{
#if VERSIONMAC
#if !__LP64__
//carbon
MenuRef carbonHelpMenu;
MenuItemIndex i;
HMGetHelpMenu(&carbonHelpMenu, &i);
if(carbonHelpMenu)
{
CopyMenuItems(Help::helpMenuRef, 1, CountMenuItems(Help::helpMenuRef), carbonHelpMenu, 0);
DeleteMenuItem(carbonHelpMenu, CountMenuItems(carbonHelpMenu));
}
#endif
//cocoa
NSMenu *helpMenu = [NSApp helpMenu];
if(helpMenu)
{
for(NSUInteger i = 0; i <[helpMenu numberOfItems]; ++i)
{
[helpMenu itemAtIndex:i].hidden = false;
}
}
#else
HMENU mdiHelpRef = GetMenu(Help::mdiWindowRef);
EnableMenuItem(mdiHelpRef, GetMenuItemCount(mdiHelpRef)-1, MF_BYPOSITION | MF_ENABLED);
DrawMenuBar(Help::mdiWindowRef);
#endif
Help::isHelpDisabled = false;
}
}
void disable()
{
if(!Help::isHelpDisabled)
{
#if VERSIONMAC
#if !__LP64__
//carbon
MenuRef carbonHelpMenu;
MenuItemIndex i;
HMGetHelpMenu(&carbonHelpMenu, &i);
if(carbonHelpMenu)
{
DisposeMenu(carbonHelpMenu);
}
#endif
//cocoa
NSMenu *helpMenu = [NSApp helpMenu];
if(helpMenu)
{
for(NSUInteger i = 0; i <[helpMenu numberOfItems]; ++i)
{
[helpMenu itemAtIndex:i].hidden = true;
}
}
#else
HMENU mdiHelpRef = GetMenu(Help::mdiWindowRef);
EnableMenuItem(mdiHelpRef, GetMenuItemCount(mdiHelpRef)-1, MF_BYPOSITION | MF_DISABLED);
DrawMenuBar(Help::mdiWindowRef);
#endif
Help::isHelpDisabled = true;
}
}
}
bool IsProcessOnExit(){
C_TEXT name;
PA_long32 state, time;
PA_GetProcessInfo(PA_GetCurrentProcessNumber(), name, &state, &time);
CUTF16String procName(name.getUTF16StringPtr());
CUTF16String exitProcName((PA_Unichar *)"$\0x\0x\0\0\0");
return (!procName.compare(exitProcName));
}
void OnStartup(){
#if VERSIONMAC
#if !__LP64__
//carbon
MenuRef helpMenu;
MenuItemIndex i;
HMGetHelpMenu(&helpMenu, &i);
DuplicateMenu(helpMenu, &Help::helpMenuRef);
#endif
#else
//the window class is the folder name of the application
Help::mdiWindowRef = NULL;
wchar_t path[_MAX_PATH] = {0};
wchar_t * applicationPath = wcscpy(path, (const wchar_t *)PA_GetApplicationFullPath().fString);
//remove file name (4D.exe)
PathRemoveFileSpec(path);
//check instance as well, to be sure
HINSTANCE h = (HINSTANCE)PA_Get4DHInstance();
do{
Help::mdiWindowRef = FindWindowEx(NULL, Help::mdiWindowRef, (LPCTSTR)path, NULL);
if(Help::mdiWindowRef){
if(h == (HINSTANCE)GetWindowLongPtr(Help::mdiWindowRef, GWLP_HINSTANCE)){
break;
}
}
}while(Help::mdiWindowRef);
#endif
Help::isHelpDisabled = false;
}
void OnCloseProcess(){
if(IsProcessOnExit()){
Help::enable();
#if VERSIONMAC
#if !__LP64__
DisposeMenu(Help::helpMenuRef);
#endif
#endif
}
}
void PluginMain(PA_long32 selector, PA_PluginParameters params)
{
try
{
PA_long32 pProcNum = selector;
sLONG_PTR *pResult = (sLONG_PTR *)params->fResult;
PackagePtr pParams = (PackagePtr)params->fParameters;
CommandDispatcher(pProcNum, pResult, pParams);
}
catch(...)
{
}
}
void CommandDispatcher (PA_long32 pProcNum, sLONG_PTR *pResult, PackagePtr pParams)
{
switch(pProcNum)
{
case kInitPlugin :
case kServerInitPlugin :
OnStartup();
break;
case kCloseProcess :
OnCloseProcess();
break;
// --- Help Menu
case 1 :
HELP_SET_ENABLED(pResult, pParams);
break;
case 2 :
HELP_Get_enabled(pResult, pParams);
break;
}
}
// ----------------------------------- Help Menu ----------------------------------
void HELP_SET_ENABLED(sLONG_PTR *pResult, PackagePtr pParams)
{
C_LONGINT Param1;
Param1.fromParamAtIndex(pParams, 1);
if(Param1.getIntValue())
{
Help::enable();
}else
{
Help::disable();
}
}
void HELP_Get_enabled(sLONG_PTR *pResult, PackagePtr pParams)
{
C_LONGINT returnValue;
returnValue.setIntValue(!Help::isHelpDisabled);
returnValue.setReturn(pResult);
}
| [
"miyako@wakanda.jp"
] | miyako@wakanda.jp |
62bbbe3c9bcad6d7c44cd2313497762206a209b9 | 5f5c557d53c2975ce09e5ce34060b5e42f7b2c90 | /Chain/libraries/glua/ldblib.cpp | 2f57e05336f6f69b9dab89e623f50ac509fbf32c | [
"MIT"
] | permissive | Achain-Dev/Achain_linux | c27b8c1ea0ae6b9c8db9b8d686849af07d7c255b | 8c6daad526c84fa513f119206e45f62eb68b8a86 | refs/heads/master | 2022-04-10T23:25:12.234124 | 2020-03-29T12:07:39 | 2020-03-29T12:07:39 | 108,964,152 | 27 | 25 | MIT | 2018-03-28T08:33:18 | 2017-10-31T08:06:09 | C++ | UTF-8 | C++ | false | false | 13,549 | cpp | /*
** $Id: ldblib.c,v 1.151 2015/11/23 11:29:43 roberto Exp $
** Interface from Lua to its debug API
** See Copyright Notice in lua.h
*/
#define ldblib_cpp
#include "glua/lprefix.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "glua/lua.h"
#include "glua/lauxlib.h"
#include "glua/lualib.h"
/*
** The hook table at registry[&HOOKKEY] maps threads to their current
** hook function. (We only need the unique address of 'HOOKKEY'.)
*/
static const int HOOKKEY = 0;
/*
** If L1 != L, L1 can be in any state, and therefore there are no
** guarantees about its stack space; any push in L1 must be
** checked.
*/
static void checkstack(lua_State *L, lua_State *L1, int n) {
if (L != L1 && !lua_checkstack(L1, n))
luaL_error(L, "stack overflow");
}
static int db_getregistry(lua_State *L) {
lua_pushvalue(L, LUA_REGISTRYINDEX);
return 1;
}
static int db_getmetatable(lua_State *L) {
luaL_checkany(L, 1);
if (!lua_getmetatable(L, 1)) {
lua_pushnil(L); /* no metatable */
}
return 1;
}
static int db_setmetatable(lua_State *L) {
int t = lua_type(L, 2);
luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
"nil or table expected");
lua_settop(L, 2);
lua_setmetatable(L, 1);
return 1; /* return 1st argument */
}
static int db_getuservalue(lua_State *L) {
if (lua_type(L, 1) != LUA_TUSERDATA)
lua_pushnil(L);
else
lua_getuservalue(L, 1);
return 1;
}
static int db_setuservalue(lua_State *L) {
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checkany(L, 2);
lua_settop(L, 2);
lua_setuservalue(L, 1);
return 1;
}
/*
** Auxiliary function used by several library functions: check for
** an optional thread as function's first argument and set 'arg' with
** 1 if this argument is present (so that functions can skip it to
** access their other arguments)
*/
static lua_State *getthread(lua_State *L, int *arg) {
if (lua_isthread(L, 1)) {
*arg = 1;
return lua_tothread(L, 1);
}
else {
*arg = 0;
return L; /* function will operate over current thread */
}
}
/*
** Variations of 'lua_settable', used by 'db_getinfo' to put results
** from 'lua_getinfo' into result table. Key is always a string;
** value can be a string, an int, or a boolean.
*/
static void settabss(lua_State *L, const char *k, const char *v) {
lua_pushstring(L, v);
lua_setfield(L, -2, k);
}
static void settabsi(lua_State *L, const char *k, int v) {
lua_pushinteger(L, v);
lua_setfield(L, -2, k);
}
static void settabsb(lua_State *L, const char *k, int v) {
lua_pushboolean(L, v);
lua_setfield(L, -2, k);
}
/*
** In function 'db_getinfo', the call to 'lua_getinfo' may push
** results on the stack; later it creates the result table to put
** these objects. Function 'treatstackoption' puts the result from
** 'lua_getinfo' on top of the result table so that it can call
** 'lua_setfield'.
*/
static void treatstackoption(lua_State *L, lua_State *L1, const char *fname) {
if (L == L1)
lua_rotate(L, -2, 1); /* exchange object and table */
else
lua_xmove(L1, L, 1); /* move object to the "main" stack */
lua_setfield(L, -2, fname); /* put object into table */
}
/*
** Calls 'lua_getinfo' and collects all results in a new table.
** L1 needs stack space for an optional input (function) plus
** two optional outputs (function and line table) from function
** 'lua_getinfo'.
*/
static int db_getinfo(lua_State *L) {
lua_Debug ar;
int arg;
lua_State *L1 = getthread(L, &arg);
const char *options = luaL_optstring(L, arg + 2, "flnStu");
checkstack(L, L1, 3);
if (lua_isfunction(L, arg + 1)) { /* info about a function? */
options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */
lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */
lua_xmove(L, L1, 1);
}
else { /* stack level */
if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) {
lua_pushnil(L); /* level out of range */
return 1;
}
}
if (!lua_getinfo(L1, options, &ar))
return luaL_argerror(L, arg + 2, "invalid option");
lua_newtable(L); /* table to collect results */
if (strchr(options, 'S')) {
settabss(L, "source", ar.source);
settabss(L, "short_src", ar.short_src);
settabsi(L, "linedefined", ar.linedefined);
settabsi(L, "lastlinedefined", ar.lastlinedefined);
settabss(L, "what", ar.what);
}
if (strchr(options, 'l'))
settabsi(L, "currentline", ar.currentline);
if (strchr(options, 'u')) {
settabsi(L, "nups", ar.nups);
settabsi(L, "nparams", ar.nparams);
settabsb(L, "isvararg", ar.isvararg);
}
if (strchr(options, 'n')) {
settabss(L, "name", ar.name);
settabss(L, "namewhat", ar.namewhat);
}
if (strchr(options, 't'))
settabsb(L, "istailcall", ar.istailcall);
if (strchr(options, 'L'))
treatstackoption(L, L1, "activelines");
if (strchr(options, 'f'))
treatstackoption(L, L1, "func");
return 1; /* return table */
}
static int db_getlocal(lua_State *L) {
int arg;
lua_State *L1 = getthread(L, &arg);
lua_Debug ar;
const char *name;
int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */
if (lua_isfunction(L, arg + 1)) { /* function argument? */
lua_pushvalue(L, arg + 1); /* push function */
lua_pushstring(L, lua_getlocal(L, nullptr, nvar)); /* push local name */
return 1; /* return only name (there is no value) */
}
else { /* stack-level argument */
int level = (int)luaL_checkinteger(L, arg + 1);
if (!lua_getstack(L1, level, &ar)) /* out of range? */
return luaL_argerror(L, arg + 1, "level out of range");
checkstack(L, L1, 1);
name = lua_getlocal(L1, &ar, nvar);
if (name) {
lua_xmove(L1, L, 1); /* move local value */
lua_pushstring(L, name); /* push name */
lua_rotate(L, -2, 1); /* re-order */
return 2;
}
else {
lua_pushnil(L); /* no name (nor value) */
return 1;
}
}
}
static int db_setlocal(lua_State *L) {
int arg;
const char *name;
lua_State *L1 = getthread(L, &arg);
lua_Debug ar;
int level = (int)luaL_checkinteger(L, arg + 1);
int nvar = (int)luaL_checkinteger(L, arg + 2);
if (!lua_getstack(L1, level, &ar)) /* out of range? */
return luaL_argerror(L, arg + 1, "level out of range");
luaL_checkany(L, arg + 3);
lua_settop(L, arg + 3);
checkstack(L, L1, 1);
lua_xmove(L, L1, 1);
name = lua_setlocal(L1, &ar, nvar);
if (name == nullptr)
lua_pop(L1, 1); /* pop value (if not popped by 'lua_setlocal') */
lua_pushstring(L, name);
return 1;
}
/*
** get (if 'get' is true) or set an upvalue from a closure
*/
static int auxupvalue(lua_State *L, int get) {
const char *name;
int n = (int)luaL_checkinteger(L, 2); /* upvalue index */
luaL_checktype(L, 1, LUA_TFUNCTION); /* closure */
name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
if (name == nullptr) return 0;
lua_pushstring(L, name);
lua_insert(L, -(get + 1)); /* no-op if get is false */
return get + 1;
}
static int db_getupvalue(lua_State *L) {
return auxupvalue(L, 1);
}
static int db_setupvalue(lua_State *L) {
luaL_checkany(L, 3);
return auxupvalue(L, 0);
}
/*
** Check whether a given upvalue from a given closure exists and
** returns its index
*/
static int checkupval(lua_State *L, int argf, int argnup) {
int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */
luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */
luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != nullptr), argnup,
"invalid upvalue index");
return nup;
}
static int db_upvalueid(lua_State *L) {
int n = checkupval(L, 1, 2);
lua_pushlightuserdata(L, lua_upvalueid(L, 1, n));
return 1;
}
static int db_upvaluejoin(lua_State *L) {
int n1 = checkupval(L, 1, 2);
int n2 = checkupval(L, 3, 4);
luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected");
luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected");
lua_upvaluejoin(L, 1, n1, 3, n2);
return 0;
}
/*
** Call hook function registered at hook table for the current
** thread (if there is one)
*/
static void hookf(lua_State *L, lua_Debug *ar) {
static const char *const hooknames[] =
{ "call", "return", "line", "count", "tail call" };
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
lua_pushthread(L);
if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */
lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */
if (ar->currentline >= 0)
lua_pushinteger(L, ar->currentline); /* push current line */
else lua_pushnil(L);
lua_assert(lua_getinfo(L, "lS", ar));
lua_call(L, 2, 0); /* call hook function */
}
}
/*
** Convert a string mask (for 'sethook') into a bit mask
*/
static int makemask(const char *smask, int count) {
int mask = 0;
if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
if (strchr(smask, 'r')) mask |= LUA_MASKRET;
if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
if (count > 0) mask |= LUA_MASKCOUNT;
return mask;
}
/*
** Convert a bit mask (for 'gethook') into a string mask
*/
static char *unmakemask(int mask, char *smask) {
int i = 0;
if (mask & LUA_MASKCALL) smask[i++] = 'c';
if (mask & LUA_MASKRET) smask[i++] = 'r';
if (mask & LUA_MASKLINE) smask[i++] = 'l';
smask[i] = '\0';
return smask;
}
static int db_sethook(lua_State *L) {
int arg, mask, count;
lua_Hook func;
lua_State *L1 = getthread(L, &arg);
if (lua_isnoneornil(L, arg + 1)) { /* no hook? */
lua_settop(L, arg + 1);
func = nullptr; mask = 0; count = 0; /* turn off hooks */
}
else {
const char *smask = luaL_checkstring(L, arg + 2);
luaL_checktype(L, arg + 1, LUA_TFUNCTION);
count = (int)luaL_optinteger(L, arg + 3, 0);
func = hookf; mask = makemask(smask, count);
}
if (lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY) == LUA_TNIL) {
lua_createtable(L, 0, 2); /* create a hook table */
lua_pushvalue(L, -1);
lua_rawsetp(L, LUA_REGISTRYINDEX, &HOOKKEY); /* set it in position */
lua_pushstring(L, "k");
lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */
lua_pushvalue(L, -1);
lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */
}
checkstack(L, L1, 1);
lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */
lua_pushvalue(L, arg + 1); /* value (hook function) */
lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */
lua_sethook(L1, func, mask, count);
return 0;
}
static int db_gethook(lua_State *L) {
int arg;
lua_State *L1 = getthread(L, &arg);
char buff[5];
int mask = lua_gethookmask(L1);
lua_Hook hook = lua_gethook(L1);
if (hook == nullptr) /* no hook? */
lua_pushnil(L);
else if (hook != hookf) /* external hook? */
lua_pushliteral(L, "external hook");
else { /* hook table must exist */
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
checkstack(L, L1, 1);
lua_pushthread(L1); lua_xmove(L1, L, 1);
lua_rawget(L, -2); /* 1st result = hooktable[L1] */
lua_remove(L, -2); /* remove hook table */
}
lua_pushstring(L, unmakemask(mask, buff)); /* 2nd result = mask */
lua_pushinteger(L, lua_gethookcount(L1)); /* 3rd result = count */
return 3;
}
static int db_debug(lua_State *L) {
for (;;) {
char buffer[250];
lua_writestringerror("%s", "lua_debug> ");
if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
strcmp(buffer, "cont\n") == 0)
return 0;
if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
lua_pcall(L, 0, 0, 0))
lua_writestringerror("%s\n", lua_tostring(L, -1));
lua_settop(L, 0); /* remove eventual returns */
}
}
static int db_traceback(lua_State *L) {
int arg;
lua_State *L1 = getthread(L, &arg);
const char *msg = lua_tostring(L, arg + 1);
if (msg == nullptr && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */
lua_pushvalue(L, arg + 1); /* return it untouched */
else {
int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0);
luaL_traceback(L, L1, msg, level);
}
return 1;
}
static const luaL_Reg dblib[] = {
{ "debug", db_debug },
{ "getuservalue", db_getuservalue },
{ "gethook", db_gethook },
{ "getinfo", db_getinfo },
{ "getlocal", db_getlocal },
{ "getregistry", db_getregistry },
{ "getmetatable", db_getmetatable },
{ "getupvalue", db_getupvalue },
{ "upvaluejoin", db_upvaluejoin },
{ "upvalueid", db_upvalueid },
{ "setuservalue", db_setuservalue },
{ "sethook", db_sethook },
{ "setlocal", db_setlocal },
{ "setmetatable", db_setmetatable },
{ "setupvalue", db_setupvalue },
{ "traceback", db_traceback },
{ nullptr, nullptr }
};
LUAMOD_API int luaopen_debug(lua_State *L) {
luaL_newlib(L, dblib);
return 1;
}
| [
"lipu@new4g.cn"
] | lipu@new4g.cn |
e60d1cca0afcf572062b0979d6de448745252943 | 3fda279305f0e62140cb0d87dc3d2f7f6ae313b8 | /src/module.cpp | cd9ffe8d985bcfaa9d74d2957bcff0ddb31f9f35 | [] | no_license | clamp03/wain | 62fe02938814793634d914e956c15106e602f45a | c1ff876f07fdb80411554863c95ed33a3e0d2992 | refs/heads/master | 2023-02-18T07:05:26.862207 | 2020-09-20T15:53:22 | 2020-09-20T15:53:22 | 200,845,416 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,253 | cpp | #include <stdio.h>
#include <string.h>
#include "interpreter.h"
#include "loader.h"
#include "module.h"
#include "section_v1.h"
Module::Module()
: version_(0),
sections_(nullptr) {
}
Module::~Module() {
if (sections_) {
free(sections_);
sections_ = nullptr;
}
}
bool Module::loadFile(const char* fname) {
FILE* fp = fopen(fname, "rb");
uint8_t* buf = nullptr;
if (!fp) {
std::cerr << "Cannot open file: " << fname << std::endl;
return false;
}
fseek(fp, 0 , SEEK_END);
size_t size = ftell(fp);
buf = (uint8_t*)malloc(sizeof(uint8_t) * size);
rewind(fp);
size_t s = fread(buf, 1, size, fp);
if (s != size)
return false;
load(buf, size);
free(buf);
fclose(fp);
return true;
}
bool Module::load(const uint8_t* buf, size_t size) {
if (buf == nullptr) {
return false;
}
Loader l(buf, size);
DEV_ASSERT(loadMagicNumber(l), "Invalid magic number");
DEV_ASSERT(loadVersion(l), "Invalid version number");
DEV_ASSERT(version_ == 1, "Not supported version number");
if (version_ == 1) {
sections_ = new SectionsV1(l);
sections_->load();
} else {
// Currently, there is only version 1
return false;
}
return true;
}
bool Module::loadMagicNumber(Loader& r) {
#define MAGIC_NUMBER "\0asm"
#define MAGIC_NUMBER_SIZE sizeof(uint32_t)
char magic_number[MAGIC_NUMBER_SIZE];
r.loadBytes(magic_number, MAGIC_NUMBER_SIZE);
return strncmp(magic_number, MAGIC_NUMBER, MAGIC_NUMBER_SIZE) == 0;
}
bool Module::loadVersion(Loader& r) {
version_ = r.loadUint32();
return true;
}
bool Module::run() {
ExportSection* exports = sections_->getExportSection();
for (int i = 0; i < exports->count(); i++)
{
const ExportEntry* entry = exports->getExportEntry(i);
if (entry->getFieldLen() == 4 &&
entry->getKind() == ExternalKind::Function &&
strncmp((const char*)entry->getFieldStr(), "main", 4) == 0)
{
Interpreter inter(sections_);
int32_t val = inter.start(entry->getIndex());
printf("%d\n", val);
return true;
}
}
return false;
}
| [
"clamp03@gmail.com"
] | clamp03@gmail.com |
997ad4f1d09d9d4aa9c7c817276e1bab0bebc55f | 6e4aeb90271122b02cf297a890b8e35957ce3b94 | /breathinsp.cpp | f719dd6766d49a4d20f64982416064e87124173e | [] | no_license | jyce3d/breathmachine | 74bf752564df604ab77c0fd70a3929c26a5667a0 | 247e70e5263a6922bca17c68599addbfdc24957e | refs/heads/master | 2022-04-26T00:37:25.991237 | 2020-04-28T00:08:38 | 2020-04-28T00:08:38 | 259,483,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | cpp | #include "breathinsp.h"
#include "breathmachine.h"
CBreathInsp::CBreathInsp(CBreathMachine *ctx):CBreathState(ctx) {
this->m_szStateName = (char*)"Insp";
}
void CBreathInsp::Expiration() {
ChangeStatus(this->context->m_stExpiration);
}
/*void CBreathInsp::Insp() {
throw "Invalid State!";
}
void CBreathInsp::Recalib() {
throw "Invalid State!";
}*/
| [
"42608645+jyce3d@users.noreply.github.com"
] | 42608645+jyce3d@users.noreply.github.com |
5b45d68fc9cc2432200f614406ccb6fe2a884fa2 | 8def5f6df6538000dd5e6758fe7ab472c56a3f7b | /include/TreeNode.h | 3bf53c622f260debc97da6a575dc242db5e570ff | [] | no_license | DaanMiddelkoop/GPUTracer | c848d83864f636a6c3265ac0b14a67c4192198ac | 0785146ab5fa6c7a569988c9a6542e7e8bd57a08 | refs/heads/master | 2021-08-14T14:31:27.750279 | 2017-11-16T01:18:29 | 2017-11-16T01:18:29 | 110,390,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | h | #ifndef TREENODE_H
#define TREENODE_H
#include <Box.h>
class TreeNode
{
public:
TreeNode(Box bounding, int child1, int child2, int t1, int t2, int depth);
Box bounding;
int child1;
int child2;
int t1;
int t2;
int depth = 0;
protected:
private:
};
#endif // TREENODE_H
| [
"daantje676@gmail.com"
] | daantje676@gmail.com |
564b437133bb9010b6aee26f1846f9e2f70001ae | 99488b8c4d67a5432dff3021f27aaae36c86d0ea | /codeforces/1428/B.cpp | 3ab63ad8a8b5d03eea7cb54b6c1a93564076383a | [] | no_license | Pratims10/CodeForces-Submissions | e1a2a8892547fca6e9e89ceb328cb84f80e86a1b | 506af8b80a41e0310ea09ec3bb3f0c076f8b8cd8 | refs/heads/master | 2023-02-06T23:31:24.431536 | 2018-08-27T17:29:00 | 2020-12-21T08:08:09 | 323,261,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll i,j,k,m,n,t;
cin>>t;
while(t--)
{
cin>>n;
string s;
cin>>s;
ll l=0,r=0,b=0;
for(i=0;i<n;i++)
{
if(s[i]=='<')
l++;
else if(s[i]=='>')
r++;
else b++;
}
if(l==0 or r==0)
cout<<n<<endl;
else
{
ll ctr=0;
for(i=0;i<n;i++)
{
ll x=i;
ll y=i-1;
if(y==-1)
y=n-1;
if(s[x]=='-' or s[y]=='-')
ctr++;
}
cout<<ctr<<endl;
}
}
} | [
"pratimsarkar23@gmail.com"
] | pratimsarkar23@gmail.com |
5e853c7348955129abc009d83760b3e27b868ba7 | 47ebaa434e78c396c4e6baa14f0b78073f08a549 | /branches/NewDatabaseBackbone/server/src/profile.cpp | 9fa71c6042af167611e6b28ffb911623c0dbda0d | [] | no_license | BackupTheBerlios/wolfpack-svn | d0730dc59b6c78c6b517702e3825dd98410c2afd | 4f738947dd076479af3db0251fb040cd665544d0 | refs/heads/master | 2021-10-13T13:52:36.548015 | 2013-11-01T01:16:57 | 2013-11-01T01:16:57 | 40,748,157 | 1 | 2 | null | 2021-09-30T04:28:19 | 2015-08-15T05:35:25 | C++ | UTF-8 | C++ | false | false | 2,835 | cpp | /*
* Wolfpack Emu (WP)
* UO Server Emulation Program
*
* Copyright 2001-2004 by holders identified in AUTHORS.txt
* 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 Palace - Suite 330, Boston, MA 02111-1307, USA.
*
* In addition to that license, if you are running this program or modified
* versions of it on a public system you HAVE TO make the complete source of
* the version used by you available or provide people with a location to
* download it.
*
* Wolfpack Homepage: http://developer.berlios.de/projects/wolfpack/
*/
#include "profile.h"
#include "console.h"
#if defined(ENABLE_PROFILING)
const char *profileNames[PF_COUNT] = {
"Niceness/PythonThreads",
"Spawnregion Checks",
"DecayCheck",
"WorldSave",
"UO Time Check",
"Combat Check",
"Timers Check",
"AI Check",
"NPC Check",
"Player Check",
"Regeneration Check",
"AI Check\\Search New Action",
"AI Check\\Execute Action",
};
// Time in MS spent in the given profile keys
unsigned int profileData[PF_COUNT];
unsigned int profileStart[PF_COUNT];
// Time spent from first to last profiling
unsigned int startTime = 0;
void startProfiling( eProfileKeys key )
{
Server::instance()->refreshTime();
unsigned int time = Server::instance()->time();
// Let's just say this has been the server start
if ( !startTime )
{
startTime = time;
}
profileStart[key] = time;
}
void stopProfiling( eProfileKeys key )
{
Server::instance()->refreshTime();
unsigned int time = Server::instance()->time();
unsigned int diff = time - profileStart[key];
profileData[key] += diff;
}
void clearProfilingInfo()
{
Server::instance()->refreshTime();
startTime = Server::instance()->time();
for ( int i = 0; i < PF_COUNT; ++i )
{
profileData[i] = 0;
}
}
void dumpProfilingInfo()
{
Server::instance()->refreshTime();
unsigned int total = Server::instance()->time() - startTime;
Console::instance()->send( "PROFILING INFORMATION:\n" );
Console::instance()->send( "TOTAL TIME: " + QString::number( total ) + "\n" );
for ( int i = 0; i < PF_COUNT; ++i )
{
Console::instance()->send( profileNames[i] );
Console::instance()->send( QString( ": %1\n" ).arg( profileData[i] ) );
}
// Clear Profiling Info
clearProfilingInfo();
}
#endif
| [
"fkollmann@db57ef4e-4fe8-0310-84ee-c23f6f2f8b61"
] | fkollmann@db57ef4e-4fe8-0310-84ee-c23f6f2f8b61 |
2530cba02236fa6d873e6ea01df6539a3fbdc6a2 | a0b91eea1da602802ad787170f671e2e5356b67b | /src/CurrencyClientApplication.cpp | b567684bdf064e949f1271a9e377a3dac314e429 | [
"MIT"
] | permissive | RamSaw/NetworksLab2019HSE | ca57897cf3d7d81768d871e39ffdb8a15e82810f | 0e987918ed021a5174aa58ef634cc6ce0bbe2e17 | refs/heads/master | 2020-04-17T21:40:43.600596 | 2019-02-03T14:12:54 | 2019-02-03T14:12:54 | 166,961,065 | 0 | 0 | MIT | 2019-01-22T08:59:14 | 2019-01-22T08:59:14 | null | UTF-8 | C++ | false | false | 154 | cpp | //
// Created by mikhail on 03.02.19.
//
#include <cstdio>
#include "include/CurrencyClientApplication.h"
int main() {
printf("Hello World!\n");
}
| [
"mikhail@pravilov.com"
] | mikhail@pravilov.com |
74e04eef67ab2d0b98aeb6ddd1c97dcfb15236c9 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/11_819_65.cpp | 304951c25d56f22e037aaee2cc355c6353e411fd | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | cpp | #include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <iostream>
#include <cstring>
#include <set>
using namespace std;
char in_grid[51][51],out_grid[51][51];
int main(){
int cases=1,r,c;
scanf("%d",&cases);
for(int t=1;t<=cases;t++){
scanf("%d%d",&r,&c);
for(int i=0;i<r;i++){
scanf("%s",in_grid[i]);
}
bool valid=true;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(in_grid[i][j]=='#'){
if(i<r-1 && j<c-1 && \
in_grid[i][j+1]=='#' && \
in_grid[i+1][j]=='#' && \
in_grid[i+1][j+1]=='#'){
in_grid[i][j]='/';
in_grid[i+1][j]='\\';
in_grid[i][j+1]='\\';
in_grid[i+1][j+1]='/';
} else {
valid=false;
break;
}
}
}
if(!valid)break;
}
printf("Case #%d:\n", t);
if(!valid){
printf("Impossible\n");
} else {
for(int i=0;i<r;i++){
printf("%s\n",in_grid[i]);
}
}
}
return 0;
}
| [
"nikola.mrzljak@fer.hr"
] | nikola.mrzljak@fer.hr |
fb55b746dfb0923bf1d9ce7bc09071f6e0ee7ac1 | 309aa602a733df09d71987abf97140c10965ebf8 | /screenmain.cpp | 5ef96e7a4a24efdf474edd8b0ef6edf388fb07fd | [
"MIT"
] | permissive | jimfinnis/jackmix | 333891ded11e386ae8cf3cb53d183e5ee8c39358 | d48ee1f60c6963a9b525e19c5dde69359d30a721 | refs/heads/master | 2021-01-12T06:53:05.402311 | 2020-08-19T12:53:24 | 2020-08-19T12:53:24 | 76,853,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,904 | cpp | /**
* @file screenmain.cpp
* @brief Brief description of file.
*
*/
#include "monitor.h"
#include "process.h"
#include "save.h"
#include "screenmain.h"
#include "screenchan.h"
#include "screenctrl.h"
#include "screenchain.h"
#include <ncurses.h>
#include <sstream>
MainScreen scrMain;
#define RIGHTWIDTH 20
#define COLWIDTH 10
static MonitorData lastDisplayed;
void MainScreen::display(MonitorData *d){
title("MAIN VIEW");
// how many channels (cols) can we do, not including MASTER?
// There's a bit of space over
// to the right we need to leave free.
int w = MonitorThread::get()->w;
int numcols = (w-RIGHTWIDTH)/COLWIDTH-1; // (-1 because master)
// there is a current col, which must be on the screen.
int firstcol = 0; // first col on screen
// curchan may be -1, in which case we are editing master values.
if(curchan >= firstcol+numcols){
firstcol = curchan-numcols/2;
}
displayChan(0,&d->master,curchan==-1);
curchanptr=NULL;
for(int i=0;i<numcols;i++){
ChanMonData *c;
int chanidx = i+firstcol;
if(chanidx>=0 && chanidx<(int)d->numchans){
c=&d->chans[chanidx];
if(chanidx==curchan)curchanptr=c->chan;
} else
c=NULL;
if(c)
displayChan(i+1,c,chanidx==curchan);
}
}
void MainScreen::displayChan(int i,ChanMonData* c,bool cur){
int x = i*COLWIDTH;
float l,r,gain,pan;
const char *name;
int h = MonitorThread::get()->h;
Value *pv,*gv;
if(c){
l=c->l;
r=c->r;
if(c->chan){
pv=c->chan->pan;
gv=c->chan->gain;
} else {
pv = Process::masterPan;
gv = Process::masterGain;
}
gain=c->gain;
pan=c->pan;
name = c->name;
if(c->chan){
Channel *ch = c->chan;
if(ch->isReturn()){
attrset(COLOR_PAIR(0)|A_BOLD);
string rn = ch->getReturnName();
rn = "("+rn.substr(0,COLWIDTH-3)+")";
mvaddstr(1,x,rn.c_str());
}
if(ch->isMute()){
attrset(COLOR_PAIR(PAIR_BLUETEXT)|A_BOLD);
mvaddstr(1,x,"MUTE");
}
if(ch->isSolo()){
attrset(COLOR_PAIR(PAIR_REDTEXT)|A_BOLD);
mvaddstr(1,x+5,"SOLO");
}
}
} else {
l=r=gain=pan=0;
pv=gv=NULL;
name="xxxx";
}
if(cur)
attrset(COLOR_PAIR(PAIR_HILIGHT)|A_BOLD);
else
attrset(COLOR_PAIR(0));
mvprintw(0,x,"%s",name);
// inputs to pan/gain bars are range 0-1 unless a value is given
drawVertBar(2,x,h-3,1,l,NULL,VU,false);
drawVertBar(2,x+2,h-3,1,r,NULL,VU,false);
drawVertBar(2,x+4,h-3,1,gain,gv,Gain,cur);
drawVertBar(2,x+6,h-3,1,pan,pv,Pan,cur);
attrset(COLOR_PAIR(0));
}
void MainScreen::commandGainNudge(float v){
ProcessCommand cmd(ProcessCommandType::NudgeValue);
if(curchanptr){
if(curchanptr->gain->db)v*=0.1f;
cmd.setvalptr(curchanptr->gain);
} else {
v*=0.1f; // master gain is always log
cmd.setvalptr(Process::masterGain);
}
cmd.setfloat(v);
Process::writeCmd(cmd);
}
void MainScreen::commandPanNudge(float v){
ProcessCommand cmd(ProcessCommandType::NudgeValue);
cmd.setvalptr(curchanptr ? curchanptr->pan : Process::masterPan)->setfloat(v);
Process::writeCmd(cmd);
}
void MainScreen::flow(InputManager *im){
stringstream ss;
int c = im->getKey();
switch(c){
case 'p':
if(curchanptr){
ss << curchanptr->name << " pan";
im->editVal(ss.str(),curchanptr->pan);
} else {
im->editVal("Master pan",Process::masterPan);
}
break;
case 'g':
if(curchanptr){
ss << curchanptr->name << " gain";
im->editVal(ss.str(),curchanptr->gain);
} else {
im->editVal("Master gain",Process::masterGain);
}
break;
case 'h':
im->push();
im->go(&scrHelp);
break;
case 'a':{
c=im->getKey("Stereo or mono ('a' to abort)","12sma");
if(c=='a')break;
int chans = (c=='1' || c=='m') ? 1:2;
bool ab,isret;
string name = im->getString("New channel name",&ab);
if(!ab && name.size()>0){
if(Channel::getChannel(name,isret)){
im->setStatus("Channel already exists",4);
} else {
ProcessCommand cmd(ProcessCommandType::AddChannel);
cmd.setstr(name)->setarg0(chans);
Process::writeCmd(cmd);
}
}
break;
}
case KEY_DC:{
if(curchanptr){
if(curchanptr->isReturn())
im->setStatus("Channel is a return channel - delete the chain instead",4);
else if(im->getKey("remove channel - are you sure?","yn")=='y'){
ProcessCommand cmd(ProcessCommandType::DelChan);
cmd.setchan(curchanptr);
Process::writeCmd(cmd);
}
} else
im->setStatus("Cannot remove master channel",4);
break;
}
case 'w':{
bool ab;
string name =im->getString("Filename",&ab);
if(!ab){
// we'd better lock, although nothing should be writing
// this state.
im->lock();
saveConfig(name.c_str());
im->unlock();
}
im->setStatus("Saved.",2);
}
break;
case 'c':
im->push();
im->go(&scrChain);
break;
case 'C':
im->push();
im->go(&scrCtrl);
break;
case 'm':case 'M':
if(curchanptr){
ProcessCommand cmd(ProcessCommandType::ChannelMute);
cmd.setchan(curchanptr);
Process::writeCmd(cmd);
}
break;
case 's':case 'S':
if(curchanptr){
ProcessCommand cmd(ProcessCommandType::ChannelSolo);
cmd.setchan(curchanptr);
Process::writeCmd(cmd);
}
break;
case 10:
if(curchan>=0){
im->push();
scrChan.setChan(curchan);
im->go(&scrChan);
}
break;
case 'x':
curchan++;
break;
case 'z':
if(--curchan<-1)
curchan=0;
break;
case KEY_UP:
commandGainNudge(1);break;
case KEY_DOWN:
commandGainNudge(-1);break;
case KEY_LEFT:
commandPanNudge(-1);break;
case KEY_RIGHT:
commandPanNudge(1);break;
case 'q':case 'Q':
c = im->getKey("are you sure?","yn");
if(c=='y'||c=='Y')im->go(NULL);
default:break;
}
}
| [
"jim.finnis@gmail.com"
] | jim.finnis@gmail.com |
a760437d07dde13c6a22c86478cf9362816ccc28 | 184180d341d2928ab7c5a626d94f2a9863726c65 | /issuestests/dHSIC/inst/testfiles/discrete_grammat_rcpp/libFuzzer_discrete_grammat_rcpp/discrete_grammat_rcpp_DeepState_TestHarness.cpp | 55987b9eea3dfd0dcc61e3f0009274e9f7985bba | [] | no_license | akhikolla/RcppDeepStateTest | f102ddf03a22b0fc05e02239d53405c8977cbc2b | 97e73fe4f8cb0f8e5415f52a2474c8bc322bbbe5 | refs/heads/master | 2023-03-03T12:19:31.725234 | 2021-02-12T21:50:12 | 2021-02-12T21:50:12 | 254,214,504 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,937 | cpp | // AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT
// discrete_grammat_rcpp_DeepState_TestHarness_generation.cpp and discrete_grammat_rcpp_DeepState_TestHarness_checks.cpp
#include <fstream>
#include <RInside.h>
#include <iostream>
#include <RcppDeepState.h>
#include <qs.h>
#include <DeepState.hpp>
NumericMatrix discrete_grammat_rcpp(NumericMatrix x, int n, int d);
TEST(dHSIC_deepstate_test,discrete_grammat_rcpp_test){
static int rinside_flag = 0;
if(rinside_flag == 0)
{
rinside_flag = 1;
RInside R;
} std::time_t current_timestamp = std::time(0);
std::cout << "input starts" << std::endl;
NumericMatrix x = RcppDeepState_NumericMatrix();
std::string x_t = "/home/akhila/fuzzer_packages/fuzzedpackages/dHSIC/inst/testfiles/discrete_grammat_rcpp/libFuzzer_discrete_grammat_rcpp/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_x.qs";
qs::c_qsave(x,x_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "x values: "<< x << std::endl;
IntegerVector n(1);
n[0] = RcppDeepState_int();
std::string n_t = "/home/akhila/fuzzer_packages/fuzzedpackages/dHSIC/inst/testfiles/discrete_grammat_rcpp/libFuzzer_discrete_grammat_rcpp/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_n.qs";
qs::c_qsave(n,n_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "n values: "<< n << std::endl;
IntegerVector d(1);
d[0] = RcppDeepState_int();
std::string d_t = "/home/akhila/fuzzer_packages/fuzzedpackages/dHSIC/inst/testfiles/discrete_grammat_rcpp/libFuzzer_discrete_grammat_rcpp/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_d.qs";
qs::c_qsave(d,d_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "d values: "<< d << std::endl;
std::cout << "input ends" << std::endl;
try{
discrete_grammat_rcpp(x,n[0],d[0]);
}
catch(Rcpp::exception& e){
std::cout<<"Exception Handled"<<std::endl;
}
}
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
a38f78a186748ff9fca14f5706fcd5a3b86f8341 | da5e98d792f2de2bfc35283c6934f36b8f51a59e | /GraPhysAni_Template/GraPhysAniFinal/ShaderUniformVariables.h | c2ebb4084e9c2f2d76fdecfdcfca769a73dcd9c1 | [] | no_license | jameskelly396/ObsessiveCompulsiveRabbitAssassins | 37cc37f2b0125deaec4e0ab17b07011beb109806 | bd1dc441eec8d7e7947a28e9003c81571bf74fc1 | refs/heads/master | 2020-06-02T21:13:52.213255 | 2015-05-13T17:03:47 | 2015-05-13T17:03:47 | 35,254,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,921 | h | #ifndef _ShaderUniformVariables_HG_
#define _ShaderUniformVariables_HG_
#include <GL\glew.h> // Because it complains when we don't include it
#include <GL\freeglut.h> // Because of the GLuint
#define GLM_FORCE_CXX98
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/vec4.hpp>
#include <glm/vec3.hpp>
#include <glm/mat4x4.hpp> // glm::mat4
// From Fragment shader:
//struct LightProperties
//{
// bool isEnabled;
// bool isLocal;
// bool isSpot;
// vec3 ambient;
// vec3 color;
// vec3 position;
// vec3 halfVector;
// vec3 coneDirection;
// float spotCosCutoff;
// float spotExponent;
// float constantAttenuation;
// float linearAttenuation;
// float quadraticAttenuation;
//};
struct CLightProperties //struct LightProperties
{
public:
CLightProperties() {};
//isEnabled(GL_FALSE), isLocal(GL_FALSE), isSpot(GL_FALSE),
//spotCosCutoff(0.0f), spotExponent(0.0f),
//constantAttenuation(0.0f), linearAttenuation(0.0f), quadraticAttenuation(0.0f) {};
GLuint isEnabled_LocID; /*GLboolean isEnabled;*/ // bool isEnabled;
GLuint isLocal_LocID; /*GLboolean isLocal;*/ // bool isLocal;
GLuint isSpot_LocID; /*GLboolean isSpot;*/ // bool isSpot;
GLuint ambient_LocID; /*glm::vec3 ambient;*/ // vec3 ambient;
GLuint color_LocID; /*glm::vec3 color;*/ // vec3 color;
GLuint position_LocID; /*glm::vec3 position;*/ // vec3 position;
GLuint halfVector_LocID; /*glm::vec3 halfVector;*/ // vec3 halfVector;
GLuint coneDirection_LocID; /*glm::vec3 coneDirection;*/ // vec3 coneDirection;
GLuint spotCosCutoff_LocID; /*GLfloat spotCosCutoff;*/ // float spotCosCutoff;
GLuint spotExponent_LocID; /*GLfloat spotExponent;*/ // float spotExponent;
GLuint constantAttenuation_LocID; /*GLfloat constantAttenuation;*/ // float constantAttenuation;
GLuint linearAttenuation_LocID; /*GLfloat linearAttenuation;*/ // float linearAttenuation;
GLuint quadraticAttenuation_LocID; /*GLfloat quadraticAttenuation;*/ // float quadraticAttenuation;
};
const int MaxLights = 10;
struct CShaderUniformVariables
{
// From Vertex shader:
glm::mat4 matProjection; // uniform mat4 ProjectionMatrix;
GLuint matProjection_LocationID; // GLuint g_ProjectionMatrixUniformLocation;
glm::mat4 matView; // uniform mat4 ViewMatrix;
GLuint matView_LocationID; // GLuint g_ViewMatrixUniformLocation;
glm::mat4 matWorld; // uniform mat4 ModelMatrix;
GLuint matWorld_LocationID; // GLuint g_ModelMatrixUniformLocation;
// From Fragment shader:
//GLfloat Shininess;
GLuint Shininess_LocationID; // uniform float Shininess;
//GLfloat Strength;
GLuint Strength_LocationID; // uniform float Strength;
//glm::vec3 EyeDirection;
GLuint EyeDirection_LocationID; // uniform vec3 EyeDirection
static const int MAXLIGHTS = 1; // --HAS-- to match the shader //Also change max light value in CLightManager.h and OpenGL.LightTexSkyUber.fragment_texture.glsl
CLightProperties Lights[MAXLIGHTS]; // uniform LightProperties Lights[MaxLights];
// ******************************************************************
// ********* Can override the colour on screen (for debugging) ******
GLuint DebugObjectColourOverride_Locaiton_ID; // uniform vec4 DebugObjectColourOverride; // If the w is != 0, this colour is used
};
bool g_SetShaderUniformVariables(void);
//
//// the set of lights to apply, per invocation of this shader
//const int MaxLights = 10;
//uniform LightProperties Lights[MaxLights];
//
//uniform float Shininess;
//uniform float Strength;
//uniform vec3 EyeDirection;
// From Vertex shader:
//
//extern GLuint g_ObjectColourUniformLocation;
//
//extern GLuint g_slot_LightPosition; //uniform vec4 LightPosition;
//extern GLuint g_slot_LightColour; //uniform vec4 LightColour;
//extern GLuint g_slot_attenuation; //uniform float attenuation;
#endif
| [
"jamie-wizard@hotmail.com"
] | jamie-wizard@hotmail.com |
15e50d703c6c01bee8bf1dabc71315cf38e128c5 | 3d8ed3cc1eeeb85e4c984cf4d010401966d94b6d | /countingbits.cpp | 5ccb70355b926a6b62e39efb99257a89e2a315ac | [] | no_license | krishna-mathuria/competitive | 805c4ba56e37e7ffa87d749e465a0d4051b2452a | 549b6fb7ec849f3082ba06faaff58efba849e18c | refs/heads/main | 2023-08-22T07:21:26.260193 | 2021-10-26T13:32:31 | 2021-10-26T13:32:31 | 386,506,918 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | cpp | class Solution {
public:
vector<int> countBits(int n) {
vector<int> v(n+1, 0);
for(int i=1;i<= n; i++)
v[i]=v[i/2]+i%2;
return v;
}
}; | [
"kmathuria13@gmail.com"
] | kmathuria13@gmail.com |
05d772cecfcef3d432cecdc062d1d319bd0be43c | afd2087e80478010d9df66e78280f75e1ff17d45 | /torch/csrc/jit/backends/xnnpack/xnnpack_backend_lib.cpp | 6de9d5d6357ef44553177957ca9fc9f576056dae | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-secret-labs-2011",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
] | permissive | pytorch/pytorch | 7521ac50c47d18b916ae47a6592c4646c2cb69b5 | a6f7dd4707ac116c0f5fb5f44f42429f38d23ab4 | refs/heads/main | 2023-08-03T05:05:02.822937 | 2023-08-03T00:40:33 | 2023-08-03T04:14:52 | 65,600,975 | 77,092 | 24,610 | NOASSERTION | 2023-09-14T21:58:39 | 2016-08-13T05:26:41 | Python | UTF-8 | C++ | false | false | 4,038 | cpp | #include <ATen/Functions.h>
#include <ATen/Utils.h>
#include <c10/core/TensorImpl.h>
#include <torch/csrc/jit/backends/backend.h>
#include <torch/csrc/jit/backends/backend_exception.h>
#include <caffe2/torch/csrc/jit/backends/xnnpack/compiler/xnn_compiler.h>
#include <torch/csrc/jit/backends/xnnpack/serialization/schema_generated.h>
namespace torch {
namespace jit {
namespace xnnpack {
namespace delegate {
class XNNModelWrapper : public CustomClassHolder {
public:
XNNExecutor executor_;
XNNModelWrapper(XNNExecutor executor) : executor_(std::move(executor)){};
XNNModelWrapper() = delete;
XNNModelWrapper(const XNNModelWrapper& oldObject) = delete;
};
class XNNPackBackend : public PyTorchBackendInterface {
public:
// Constructor.
// NOLINTNEXTLINE(modernize-use-equals-default)
explicit XNNPackBackend() {}
virtual ~XNNPackBackend() override = default;
bool is_available() override {
return xnn_status_success == xnn_initialize(/*allocator=*/nullptr);
}
c10::impl::GenericDict compile(
c10::IValue processed,
c10::impl::GenericDict method_compile_spec) override {
auto dict = processed.toGenericDict();
// Compiling and wrapping exeuction object
const std::string& ser_model = dict.at("ser_model").toStringRef();
XNNExecutor executor;
XNNCompiler::compileModel(ser_model.data(), ser_model.length(), &executor);
auto model_ptr = c10::make_intrusive<XNNModelWrapper>(std::move(executor));
auto runtime_handle = IValue::make_capsule(model_ptr);
auto wrapper = c10::static_intrusive_pointer_cast<XNNModelWrapper>(
runtime_handle.toCapsule());
// Packing outputs into generic dict
c10::Dict<c10::IValue, c10::IValue> handles(
c10::StringType::get(), c10::AnyType::get());
c10::Dict<c10::IValue, c10::IValue> ret(
c10::StringType::get(), c10::AnyType::get());
ret.insert("runtime", runtime_handle);
ret.insert("output_shapes", dict.at("outputs"));
handles.insert("forward", ret);
return handles;
}
// Currently this is not implemented, and everything is computed a head of
// time the current implementation just takes the computed results from ahead
// of time and grabs them. The inputs are fed in through the compile spec for
// the sake of testing. In reality, the inputs will be fed in at this stage
// and ran here.
c10::impl::GenericList execute(
c10::IValue handle,
c10::impl::GenericList inputs) override {
auto dict = handle.toGenericDict();
auto output_shapes = dict.at("output_shapes").toList();
auto capsule = dict.at("runtime").toCapsule();
auto model_wrapper =
c10::static_intrusive_pointer_cast<XNNModelWrapper>(capsule);
XNNExecutor& executor = model_wrapper->executor_;
std::vector<float*> input_pointers;
for (int i = 0; i < inputs.size(); ++i) {
at::IValue val = inputs.get(i);
TORCH_CHECK(val.isTensor(), "Non-tensor inputs not supported");
input_pointers.push_back(val.toTensor().data_ptr<float>());
}
std::vector<at::Tensor> output_tensors;
std::vector<float*> output_pointers;
output_tensors.reserve(output_shapes.size());
for (int i = 0; i < output_shapes.size(); i++) {
auto o_shape = output_shapes.get(i).toIntVector();
auto output = at::empty(o_shape, c10::ScalarType::Float);
output_tensors.push_back(output);
output_pointers.push_back(output.data_ptr<float>());
}
TORCH_CHECK(
executor.set_inputs(input_pointers, output_pointers),
"Number of inputs/outputs does not match expected number of inputs/outputs");
TORCH_CHECK(executor.forward(), "Failed to invoke XNNPack runtime");
c10::List<at::Tensor> output_list(output_tensors);
return c10::impl::toList(output_list);
}
};
namespace {
constexpr auto backend_name = "xnnpack";
static auto cls = torch::jit::backend<XNNPackBackend>(backend_name);
} // namespace
} // namespace delegate
} // namespace xnnpack
} // namespace jit
} // namespace torch
| [
"pytorchmergebot@users.noreply.github.com"
] | pytorchmergebot@users.noreply.github.com |
1206090a67caecfc999ab17f1f4dc0cefed9a6dc | 3b5a11bce7cdbe7875284e094e3c0b0a53806f28 | /Core/Src/LuaScript.cpp | 69a93673e26c7905f6b631edd1c07a685098d276 | [] | no_license | dennisscully/Cheezy | 6e6fcd13c2474374afcd2a40d9596aed17635f1c | ccca48d0a41a2adbdb3e58509e748a867b1d74ab | refs/heads/master | 2020-12-29T03:06:45.524558 | 2011-09-05T01:39:33 | 2011-09-05T01:39:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,741 | cpp |
CLASS_IMP(LuaScript);
ATTRIBUTE_GETSET(data,&LuaScript::getData,&LuaScript::setData);
FUNCTION(&LuaScript::load);
FUNCTION(&LuaScript::checkValidity);
FUNCTION(&LuaScript::execute);
FUNCTION(&LuaScript::pause);
FUNCTION(&LuaScript::resume);
FUNCTION(&LuaScript::kill);
CLASS_END;
void LuaScript::setData(const std::string& d){
innerData().validityChecked = false;
data = d;
}
const std::string& LuaScript::getData() const{
return data;
}
void LuaScript::load(const std::string& path){
data.clear();
std::string line;
std::ifstream myfile (path.c_str());
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
data.append( line );
data.append("\r\n");
}
myfile.close();
}
else{
//error could not open file
}
}
void LuaScript::_newState(){
if(innerData().refKeya > 0){
luaL_unref(LuaScriptManager::getInstance()->L, LUA_REGISTRYINDEX, InnerData().refKeya);
}
innerData().L = lua_newthread(LuaScriptManager::getInstance()->L);
innerData().refKeya = luaL_ref(LuaScriptManager::getInstance()->L, LUA_REGISTRYINDEX);
}
void LuaScript::checkValidity(){
//if we pass the data as string !!! luaL_loadstring( as, script.c_str() )
if(data.empty())
return;
_newState();
if (luaL_loadstring( innerData().L, data.c_str() )!= 0){
// compile-time error
innerData().lastCompileError = lua_tostring(innerData().L, -1);
printf("%s\n",innerData().lastCompileError);
}
}
void LuaScript::execute(){
checkValidity();
resume();
}
void LuaScript::pause(){
}
void LuaScript::resume(){
if (lua_resume( innerData().L, 0 )!= 0){
innerData().lastRuntimeError = lua_tostring(innerData().L, -1);
printf("%s\n",innerData().lastRuntimeError);
}
}
void LuaScript::kill(){
} | [
"seb@.(none)"
] | seb@.(none) |
b73cb186e78f97d5cab2fe1ead316ad432902cc6 | 44f9596d19a3627095c3cbf58f0bb49a476a41bb | /递归打印星星.cpp | 9406d25d86c867777f6a2ec29455577f859247ae | [] | no_license | elssm/C-code | 985f5672cdcd8f0aa703a76b8bb96281e20b539c | 4e51601a7dadc7a98c7406a4bd24a393403401be | refs/heads/master | 2020-12-11T00:35:41.639148 | 2020-01-15T02:14:15 | 2020-01-15T02:14:15 | 233,754,885 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 271 | cpp | //屏幕输出四行星星
#include<stdio.h>
void printstar(int raw)
{
if(raw==0)
return;
else
{
printf("* * * * *\n");
printstar(raw-1);
}
}
int main(void)
{
int n;
printf("请输入星星的行数: ");
scanf("%d",&n);
printstar(n);
}
| [
"noreply@github.com"
] | noreply@github.com |
53f634c507d5749d76932884e2e2fd8f4d85847b | 817cc371e2eb56f37c400b7f96d658d0683476b1 | /12_practice/1092c.cpp | 566dafc9a007beefd23e8f345c666c832b129524 | [] | no_license | KanadeSiina/PracticeCode | c696495bd71395648ac62a41d0a41869f50c5eb4 | 146c8d5889eee7917a355feb8b03d1415a29ae9d | refs/heads/master | 2020-09-05T00:49:29.165600 | 2020-06-30T12:48:15 | 2020-06-30T12:48:15 | 219,937,221 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | cpp | #include<bits/stdc++.h>
using namespace std;
vector<string> cons;
int ans[305];
int len[305];
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
int n;
memset(ans,0,sizeof(ans));
cons.clear();
cin>>n;
string temp;
for(int i=0;i<2*n-2;i++)
{
cin>>temp;
cons.push_back(temp);
}
}
| [
"820233016@qq.com"
] | 820233016@qq.com |
2ce88578963438d773b4c24d3550e15e79258c1a | 8d93110cfdbd626543a3550c8350547cbed67124 | /Experiment1/main.cpp | 983fa262c5ac1b2d4b456553f8495fbf7122b90e | [] | no_license | EXIA97/NetWorkProgramming | 14432f974037ff3951e3a8a7dd34e3e5c73dc1e7 | ceb848b43acb6b339762d84d9ef7419c133afd9a | refs/heads/master | 2020-04-12T22:41:08.024078 | 2018-12-23T11:51:50 | 2018-12-23T11:51:50 | 162,796,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,809 | cpp | #include <QCoreApplication>
#include <iostream>
#include <QNetworkAddressEntry>
#include <QNetworkInterface>
#include <QHostAddress>
#include <QHostInfo>
#include <QList>
int main(int argc, char *argv[])
{
using namespace std;
QCoreApplication a(argc, argv);
//QHostInfo类作用,获取主机名,也可以通过主机名来查找IP地址,或者通过IP地址来反向查找主机名。
QString localHostName = QHostInfo::localHostName();
cout << "LocalHostName:" << localHostName.toStdString() << endl;
//获取IP地址
QHostInfo info = QHostInfo::fromName(localHostName);
foreach(QHostAddress address, info.addresses())
{
if (address.protocol() == QAbstractSocket::IPv4Protocol)
cout << "IPv4 Address:" << address.toString().toStdString() << endl;
}
foreach (QHostAddress address, QNetworkInterface::allAddresses())
{
cout << "Address:" << address.toString().toStdString() << endl;
}
//获取所有网络接口的列表
foreach (QNetworkInterface netInterface, QNetworkInterface::allInterfaces())
{
//设备名
cout << "Device:" << netInterface.name().toStdString() << endl;
cout << "HardwareAddress:" << netInterface.hardwareAddress().toStdString() << endl;
QList<QNetworkAddressEntry> entryList = netInterface.addressEntries();
foreach(QNetworkAddressEntry entry, entryList)
{
//IP地址
cout << "IP Address:" << entry.ip().toString().toStdString() << endl;
//子网掩码
cout << "Netmask:" << entry.netmask().toString().toStdString() << endl;
//广播地址
cout << "Broadcast:" << entry.broadcast().toString().toStdString() << endl;
}
return a.exec();
}
}
| [
"937316740@qq.com"
] | 937316740@qq.com |
f8220101d0761b0f5f2236be0477cd52d20e96de | 3b0dea94bc9816a94a71e10449339ad7047a0954 | /itunesvisualswindowssdk - muSee/MelodyToneAccept.h | f4370b0d69ad1596e93e4cc8eb0bd2e42a1b6803 | [] | no_license | GritBear/MuSee | c492d133f67f5dc74e93ddeb5823eeb2d43d77ee | 5c86d8a631d9feeb6c4f52b5f3633d4a14a46a8c | refs/heads/master | 2021-01-18T23:37:08.102614 | 2016-05-14T18:34:54 | 2016-05-14T18:34:54 | 12,175,490 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 805 | h | #pragma once
#include "Global.h"
#include "DataReader.h"
#include "CreationCore.h"
#include "control.h"
class MelodyToneAccept{
private:
protected:
//Storage members
// melody collision bounds
int boundY;
int boundX;
public:
MelodyToneAccept(){Init();}
~MelodyToneAccept(){Destroy();}
void Destroy();
void Init();
/*
float virtual EvaluateToneAcceptanceScore(int tone, int tone_rank);
float virtual ToneClosenessEvaluation(int tone);
float virtual TrendFittingEvaluation(int tone, int order);
bool virtual CheckMelodyTouching(MelodyObj *otherMelody);
void UpdateMelodyVector();
void AcceptTone(int tone, int rank, unsigned time);
void Clean(bool ChangeTrack = false, bool Removeall = false);
int GetMelodyBoundX(){return boundX;}
int GetMelodyBoundY(){return boundY;}
*/
}; | [
"6fenxls@gmail.com"
] | 6fenxls@gmail.com |
ae9d6c260fcdb7d1489c14914c38154aa7555f1b | 81464366d3d2ab91a6600be8646d0856d413d8be | /Ease_the_array.cpp | 2eeee45fa3b21b068ec7b4c0d9ed586f05897cb5 | [] | no_license | SunnyJaiswal5297/Basic_c_programs | 08f289d04817f81222ceaacd7362e47fbae2935e | a2fd6168ce4ff075be6488c172200da21058dd93 | refs/heads/master | 2022-12-03T09:53:35.189234 | 2020-07-28T17:17:17 | 2020-07-28T17:17:17 | 283,201,986 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 760 | cpp | #include<iostream>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n],i;
for(i=0;i<n;i++)
cin>>a[i];
int count=0;
for(i=0;i<n-1;i++)
{
if(a[i] && a[i+1]==a[i] && a[i+1])
{
a[i]*=2;
a[i+1]=0;
}
}
for(i=0;i<n;i++)
if(!a[i])
count++;
int k=0;
for(i=0;i<n;i++)
{
if(a[i])
a[k++]=a[i];
}
for(i=n-count;i<n;i++)
a[i]=0;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<"\n";
}
return 0;
} | [
"s2jaiswal.sj@gmail.com"
] | s2jaiswal.sj@gmail.com |
c7cfcf079997da622a5e6f4646e952d2222693b5 | d7527de44d4cd4d551bfe96efd32a1b852c96488 | /Simulation/Bremsstrahlung.cc | 2d43aaba3b00f5005ea2e6b21b6fad8e769fe0cf | [] | no_license | fuyanliu/TrackingPositrons | e91cdaca8eeaa01231b469376859c1d551ccc3ca | e5ded0944de8d1b586a7dfc18df7da86ac20fb18 | refs/heads/master | 2021-01-22T18:23:37.843314 | 2013-06-30T20:47:55 | 2013-06-30T20:47:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,601 | cc | #include <iostream>
#include <fstream>
#include <TApplication.h>
#include <TCanvas.h>
#include <TGraph.h>
#include <TH1.h>
#include <TH2.h>
#include <TRandom3.h>
#include <TStyle.h>
#include <cassert>
#include <sstream>
#include <TLegend.h>
#include "Geometry/Geometry.hh"
#include "Geometry/SimpleBox.hh"
#include "Simulation/GEANT4Bremsstrahlung.hh"
#include "Simulation/GEANT4PairProduction.hh"
#include "Simulation/BetheEnergyLoss.hh"
#include "Simulation/Simulator.hh"
#include "Simulation/GetTime.hh"
#include "Simulation/EnergyLoss.hh"
using namespace na63;
int main(int argc,char *argv[]) {
const unsigned n_tracks = 64;
bool plot = false;
// Run on CPU
bool runcpu = false;
for (int i=1;i<argc;i++) {
std::string arg(argv[i]);
if (arg == "CPU") {
runcpu = true;
}
if (arg == "plot") {
plot = true;
}
}
// Geometry
Geometry geometry;
const Float scale = 1e3;
geometry.AddMaterial(Material("vacuum",0.0,0.0,0.0,0.0,0.0));
geometry.AddMaterial(Material("iron",kIronAtomicNumber,kIronDensity,kIronAtomicWeight,kIronMeanExcitationPotential,kIronRadiationLength));
geometry.SetBounds(SimpleBox("vacuum",ThreeVector(5*scale,0,0),ThreeVector(10*scale,2*scale,2*scale)));
// geometry.AddVolume(SimpleBox("iron",ThreeVector(50,1e2+5,0),ThreeVector(30,2e2,4e2)));
// geometry.AddVolume(SimpleBox("iron",ThreeVector(50,-(1e2+5),0),ThreeVector(30,2e2,4e2)));
// geometry.AddVolume(SimpleBox("iron",ThreeVector(2*scale,0,0),ThreeVector(1*scale,1*scale,1*scale)));
// geometry.AddVolume(SimpleBox("iron",ThreeVector(1*scale,1*scale,1*scale),ThreeVector(1*scale,1*scale,1*scale)));
// geometry.AddVolume(SimpleBox("iron",ThreeVector(3*scale,-1*scale,1*scale),ThreeVector(1*scale,1*scale,1*scale)));
// geometry.AddVolume(SimpleBox("iron",ThreeVector(2*scale,0,0),ThreeVector(1*scale,1*scale,1*scale)));
geometry.AddVolume(SimpleBox("iron",ThreeVector(5*scale,0,0),ThreeVector(10*scale,2*scale,2*scale)));
// Simulator
Simulator simulator(&geometry);
Particle electron("electron",11,kElectronMass);
Bremsstrahlung bremsstrahlung(&electron);
BetheEnergyLoss bethe_energy_loss;
PairProduction pairproduction;
Particle photon("photon",22,0);
electron.RegisterProcess(&bremsstrahlung);
electron.RegisterProcess(&bethe_energy_loss);
photon.RegisterProcess(&pairproduction);
simulator.AddParticle(electron);
simulator.AddParticle(photon);
simulator.step_size = 0.01;
simulator.sorting = PARTICLE;
simulator.thread_multiplier = 1;
const Float xmin = 0;
const Float xmax = 100;
const Float xy_dim = 0.4;
const unsigned xy_bins = 300;
EnergyLoss energyloss(
600,xmin,xmax,
xy_bins,-xy_dim,xy_dim,
xy_bins,-xy_dim,xy_dim);
simulator.RecordEnergyLoss(&energyloss);
// Arguments
simulator.device = (runcpu) ? CPU : GPU;
simulator.debug = true;
simulator.cpu_threads = 8;
simulator.pool_size = 1000;
simulator.steps_per_launch = 500;
// Tracks
std::vector<Track> tracks;
const Float arc = kPi/16;
const Float E = 5e3; // MeV
const Float gamma = E / kElectronMass;
simulator.secondary_threshold = 1.0;
bremsstrahlung.SetSecondaryThreshold(1.0);
const Float beta = Beta(gamma);
const Float momentum = sqrt(E*E - kElectronMass*kElectronMass);
TRandom3 rng((size_t)clock());
for (int i=0;i<n_tracks;i++) {
Float angle_phi = 0;
Float angle_theta = 0.5 * kPi;
if (n_tracks > 1) {
// angle_phi = -arc + 2*arc * (rng.Rndm());
// angle_theta = 2.0 * kPi * (rng.Rndm());
} else {
angle_phi = 0.00;
angle_theta = 0.00;
}
ThreeVector direction = SphericalToCartesian(momentum,angle_phi,angle_theta);
direction.Rotate(ThreeVector(1,0,0));
tracks.push_back(Track(11,-1,FourVector(),FourVector(direction,E)));
}
simulator.AddTracks(tracks);
// Propagate
simulator.Propagate();
unsigned electrons = 0, electrons_live = 0, photons = 0, photons_live = 0;
Float final_energy = 0;
tracks = simulator.GetTracks();
// simulator.PrintTracks();
// std::ofstream outfile;
// outfile.open("Data/bremsstrahlung_shower");
for (int i=0;i<tracks.size();i++) {
Track t = tracks[i];
if (t.particle_id == 11) {
electrons++;
if (t.momentum[3] > kElectronMass) {
final_energy += t.momentum[3];
electrons_live++;
}
} else if (t.particle_id == 22) {
photons++;
if (t.momentum[3] > 0) {
final_energy += t.momentum[3];
photons_live++;
}
}
FourVector vertex = t.vertex();
// outfile << t.particle_id << ","
// << vertex[0] << ","
// << vertex[1] << ","
// << vertex[2] << ","
// << vertex[3] << ","
// << t.position[0] << ","
// << t.position[1] << ","
// << t.position[2] << ","
// << t.position[3] << std::endl;
}
// outfile.close();
std::cout << "Simulator returned " << tracks.size() << " particles, of which " << electrons << " are electrons (" << electrons_live << " alive), and " << photons << " are photons (" << photons_live << " alive)." << std::endl;
Float initial_energy = (Float)n_tracks * E;
std::cout << "(" << final_energy << " MeV) / (" << initial_energy << " MeV) = " << 100.0*(final_energy/initial_energy) << " percent energy remaining in system." << std::endl;
if (plot) {
TApplication app("app",&argc,argv);
// TH3F *loss_3d = energyloss.Build3DHistogram();
// loss_3d->SaveAs("Data/energyloss_3d.pdf");
TH1F* loss_x = energyloss.BuildXHistogram();
TH2F* loss_xy = energyloss.BuildXYHistogram();
TH2F* loss_yz = energyloss.BuildYZHistogram();
loss_x->SetTitle("Energy loss with bremsstrahlung in x;x [cm];Energy [MeV]");
loss_xy->SetTitle("Energy loss with bremsstrahlung in iron;x [cm];y [cm];Energy [MeV]");
loss_yz->SetTitle("Energy loss with bremsstrahlung in iron;y [cm];z [cm];Energy [MeV]");
loss_xy->SetStats(0);
loss_xy->GetXaxis()->SetLabelSize(0.04);
loss_xy->GetYaxis()->SetLabelSize(0.04);
loss_xy->GetZaxis()->SetLabelSize(0.04);
loss_yz->SetStats(0);
loss_yz->GetXaxis()->SetLabelSize(0.04);
loss_yz->GetYaxis()->SetLabelSize(0.04);
loss_yz->GetZaxis()->SetLabelSize(0.04);
loss_x->SetStats(0);
TCanvas *canvas = new TCanvas();
TLegend *legend = new TLegend(0.63,0.89,0.87,0.80);
std::stringstream ss;
ss << "<x> = " << loss_x->GetMean();
legend->AddEntry("Mean x",ss.str().c_str(),"");
legend->SetTextSize(0.04);
canvas->SetLogz();
canvas->SetRightMargin(0.125);
loss_xy->Draw("colz");
legend->Draw();
// gPad->WaitPrimitive();
canvas->SaveAs("Plots/energyloss_xy.pdf");
TCanvas *canvas2 = new TCanvas();
canvas2->SetLogz();
canvas2->SetRightMargin(0.125);
loss_yz->Draw("colz");
// gPad->WaitPrimitive();
canvas2->SaveAs("Plots/energyloss_yz.pdf");
}
// Analyze
// TApplication app("app",&argc,argv);
// TCanvas canvas;
// TH1F electrons("Bremsstrahlung electrons","Bremsstrahlung electrons",96,-arc,arc);
// TH1F photons("Bremsstrahlung photons","Bremsstrahlung photons",96,-arc,arc);
// electrons.SetLineColor(kRed);
// photons.SetLineColor(kBlue);
// std::ofstream outfile;
// outfile.open("Data/bremsstrahlung_shower");
// FourVector zero_vertex;
// int i=0;
// while (i<simulator.TrackSize()) {
// Track t = simulator.GetTrack(i);
// FourVector vertex = t.vertex();
// // if (t.particle_id == 11 && vertex == zero_vertex) {
// // std::cout << i << ": " << t.particle_id << ", " << t.position << ", " << t.momentum << std::endl;
// // }
// if (t.particle_id == 11) {
// electrons.Fill(angles[t.initial_index]);
// } else if (t.particle_id == 22) {
// photons.Fill(angles[t.initial_index]);
// }
// // outfile << t.particle_id << ","
// // << vertex[0] << ","
// // << vertex[1] << ","
// // << vertex[2] << ","
// // << vertex[3] << ","
// // << t.position[0] << ","
// // << t.position[1] << ","
// // << t.position[2] << ","
// // << t.position[3] << std::endl;
// i++;
// }
// outfile.close();
// std::cout << "Copied back " << i << " tracks." << std::endl;
// photons.Draw();
// electrons.Draw("same");
// photons.SetTitle("Bremsstrahlung");
// photons.GetXaxis()->SetTitle("Angle [radians]");
// canvas.Modified();
// canvas.Update();
//canvas.SaveAs("Plots/bremsstrahlung.png");
//gPad->WaitPrimitive();
return 0;
} | [
"johannes@musicmedia.dk"
] | johannes@musicmedia.dk |
8d95e8c3fecbc78296b3c2f7fb6aab9973ec795b | 484dac4580221d2cd2e190d72f717238fc6a8d1d | /Projectile/Sprite.cpp | df0f6544ab77f92d56d16ff92be44a60741ed5b8 | [] | no_license | DMistera/Project | 737eb16f8bba7dcd52e1f01ba1bf38ed49e3e4b2 | a0eb02183cf2d2556a3a2aa3bf3b4adbb2fc31b5 | refs/heads/master | 2021-06-17T19:10:45.179916 | 2017-06-08T00:07:55 | 2017-06-08T00:07:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,987 | cpp | #include "Sprite.h"
Sprite::Sprite(State* stateP, Texture * texture, Shader * shader, Model * model) : Renderable(stateP) {
this->texture = texture;
this->shader = shader;
this->model = model;
}
bool Sprite::initialize(Direct3D* direct3D, HWND* hwnd, list<Texture*>* loadedTextures, list<Shader*>* loadedShaders, list<Model*>* loadedModels) {
if (!initializeShader(loadedShaders, direct3D, hwnd))
return false;
if (!initializeModel(loadedModels, direct3D, hwnd))
return false;
if (!initializeTexture(loadedTextures, direct3D, hwnd))
return false;
return true;
}
bool Sprite::render(Direct3D* direct3D, HWND* hwnd, Camera* camera) {
// Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing.
model->render(direct3D->getDeviceContext());
D3DXMATRIX worldMatrix;
D3DXMATRIX viewMatrix = camera->getViewMatrix();
D3DXMATRIX orthographicMatrix;
direct3D->getWorldMatrix(worldMatrix);
direct3D->getOrthographicMatrix(orthographicMatrix);
//Set position
worldMatrix._41 = position.getX();
worldMatrix._42 = position.getY();
//Set scale
worldMatrix._11 = scaleVector.getX();
worldMatrix._22 = scaleVector.getY();
D3DXVECTOR3 d3color = D3DXVECTOR3(colorVector.getX(), colorVector.getY(), colorVector.getZ());
// Render the model using the color shader.
if (!(shader->render(*hwnd, direct3D->getDeviceContext(), model->getIndexCount(), worldMatrix, viewMatrix, orthographicMatrix, texture->getResourceView(), d3color, alpha)))
return false;
return true;
}
//Initialization
void Sprite::shutdownComponent() {
}
bool Sprite::initializeTexture(list<Texture*>* loadedTextures, Direct3D* direct3D, HWND* hwnd) {
if (!texture->isInitialized()) {
bool unique = true;
for (Texture* &t : *loadedTextures) {
if (t->getFileName() == texture->getFileName()) {
texture->shutdown();
delete texture;
texture = t;
unique = false;
}
}
if (unique)
loadedTextures->push_back(texture);
if (!(texture->initialize(direct3D->getDevice(), hwnd))) {
MessageBox(*hwnd, "Could not initialize texture", "Error", NULL);
return false;
}
}
return true;
}
bool Sprite::initializeShader(list<Shader*>* loadedShaders, Direct3D* direct3D, HWND* hwnd) {
if (!shader->isInitialized()) {
bool unique = true;
for (Shader* &s : *loadedShaders) {
if (typeid(s) == typeid(shader)) {
shader->shutdown();
delete shader;
shader = s;
unique = false;
}
}
if (unique)
loadedShaders->push_back(shader);
if (!(shader->initialize(direct3D->getDevice(), hwnd))) {
MessageBox(*hwnd, "Could not initialize shader", "Error", NULL);
return false;
}
}
return true;
}
bool Sprite::initializeModel(list<Model*>*, Direct3D* direct3D, HWND* hwnd) {
if (!(model->initialize(direct3D->getDevice(), hwnd))) {
MessageBox(*hwnd, "Could not initialize model", "Error", NULL);
return false;
}
return true;
}
bool Sprite::updateComponent(unsigned long deltaTime) {
return true;
}
| [
"dmistera2@gmail.com"
] | dmistera2@gmail.com |
7dd87877e1ed4c6db2dd3e16896a76e1d0fcdc4a | 1dd9b53629ccee884bbe5b47332f7c8b9943264d | /Arduino Codes_Freshman Projects/Control_Motors_Remote/Control_Motors_Remote.ino | 5c2235f20bc2b4d8deaf3c82ad8fbb6105de7b2e | [
"MIT"
] | permissive | TheGiraffe/RoboBluetooth | ae35faddab9a56dd7238ff52983364862979032c | a5ad098c2336d7e7cb5ea7f0a5351f50e79494d3 | refs/heads/master | 2021-01-20T04:55:04.142759 | 2020-03-06T22:24:43 | 2020-03-06T22:24:43 | 89,747,454 | 0 | 0 | null | 2017-04-28T22:17:11 | 2017-04-28T21:53:10 | null | UTF-8 | C++ | false | false | 522 | ino | #include <IRremote.h>
const int irReceiverPin = 2;
const int ledPin = 13;
IRrecv irrecv(irReceiverPin);
decode_results results;
void remotesetup()
{
Serial.begin(9600);
irrecv.enableIRIn();
}
void remoteloop()
{
if (irrecv.decode(&results)) {
Serial.print("irCode: ");
Serial.print(results.value, HEX);
Serial.print(", bits: ");
Serial.println(results.bits);
irrecv.resume();
}
switch(results.value){
case 16712445:
}
}
| [
"sodavis10@gmail.com"
] | sodavis10@gmail.com |
ea6527149d1fa7554c4d6cb1a792889650a0f945 | 72b451bad6e2972ade5f06f83ad0623dbf28ce22 | /kernel/include/net/alpha.hpp | 0c62711fe68cf72cb9954c46eedbd293bb0d0b6a | [
"MIT"
] | permissive | cekkr/thor-os | b7d31901959d8c4c2686e8af1dfcf156fbef477a | 841b088eddc378ef38c98878a51958479dce4a31 | refs/heads/develop | 2021-03-30T23:26:56.990768 | 2018-03-31T16:53:16 | 2018-03-31T16:53:16 | 124,933,350 | 0 | 0 | MIT | 2018-03-31T16:53:17 | 2018-03-12T18:28:19 | C++ | UTF-8 | C++ | false | false | 443 | hpp | //=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#ifndef NET_ALPHA_H
#define NET_ALPHA_H
namespace network {
void alpha();
} // end of network namespace
#endif
| [
"baptiste.wicht@gmail.com"
] | baptiste.wicht@gmail.com |
c36029f972a1b2886d3596157797bcf1aaf995f5 | 32dcb940b8ce3481a7e099c8eec59e315af1fe04 | /high-performance-computing-noor/lab2/question1/exp2_generate_random_number_ced17i029.cpp | f38fcab2fc9455b21c77c73fc34660d2e6497c36 | [] | no_license | LacErnest/College-Courses | 77c45a140a92cb4123d7b74a156ee106e096c546 | e61b87d8b8f0b5f331b08203aa614140c0f115db | refs/heads/main | 2023-05-29T11:19:02.712172 | 2021-06-08T15:51:12 | 2021-06-08T15:51:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 744 | cpp | #include<bits/stdc++.h>
using namespace std;
const long long m = 100,n=100;
long double gen_rand(){
long double x = rand() % 1000000;
x = x + x*1.5235449874618;
return x;
}
int main(){
long double a[m][n],b[m][n];
for(long long row=0 ; row<m ; ++row ){
for(long long col=0 ; col<n ; ++col){
a[row][col] = gen_rand();
b[row][col] = gen_rand();
}
}
for(long long row=0 ; row<m ; ++row ){
for(long long col=0 ; col<n ; ++col){
cout<<a[row][col]<<" ";
}
cout<<endl;
}
for(long long row=0 ; row<m ; ++row ){
for(long long col=0 ; col<n ; ++col){
cout<<b[row][col]<<" ";
}
cout<<endl;
}
} | [
"9801amarkumar@gmail.com"
] | 9801amarkumar@gmail.com |
5e3b15f6ddaffb9709a5268b132e627d8825f494 | eed8026f1f9d9f56c4d536b9403d1ff50567af8a | /JzOffer/从尾到头打印链表.cpp | afe3ff642bdfab49f485e8eb859b79c90a1cdd29 | [] | no_license | atmqq1990/JzOffer | f1ef36749e58f57b2e0159b3e9e697ce853bc0a0 | ba240e91b44f9473364d97f28863700622c3af8e | refs/heads/master | 2021-01-10T21:23:43.621669 | 2015-08-11T09:33:10 | 2015-08-11T09:33:10 | 40,455,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | cpp | #include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> res;
if (head == NULL)
return res;
stack<int> st;
ListNode *p = head;
while (p != NULL)
{
st.push(p->val);
p = p->next;
}
while (!st.empty())
{
res.push_back(st.top());
st.pop();
}
return res;
}
}; | [
"atmqq1990@gmail.com"
] | atmqq1990@gmail.com |
8642217955571df238a29ec9dc5b8e50e9a47957 | fecc16f49ce72a3a39764bffb826514a2481cf06 | /Optimizer.cpp | 681efea1a8df96c4f3ed248455b268acf0c16542 | [] | no_license | kazu-kinugawa/HNES | 98959e6070c620f4991d10332b54e833854cda0d | 46539e3cbc6540a6bcbd4ad395c652fa3c752995 | refs/heads/master | 2021-04-09T17:29:26.966624 | 2018-03-19T16:17:15 | 2018-03-19T16:17:15 | 125,871,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,685 | cpp | #include "Optimizer.hpp"
#include <cmath>
void Optimizer::sgd(const MatD& grad, const Real learningRate, MatD& param){
param -= learningRate * grad;
}
void Optimizer::sgd(const VecD& grad, const Real learningRate, VecD& param){
param -= learningRate * grad;
}
void Optimizer::sgd(const Real& grad, const Real learningRate, Real& param){
param -= learningRate * grad;
}
void Optimizer::adagrad(MatD& grad, const Real learningRate, MatD& gradHist, MatD& param){
gradHist.array() += grad.array().square();
grad.array() /= gradHist.array().sqrt();
Optimizer::sgd(grad, learningRate, param);
}
void Optimizer::adagrad(VecD& grad, const Real learningRate, VecD& gradHist, VecD& param){
gradHist.array() += grad.array().square();
grad.array() /= gradHist.array().sqrt();
Optimizer::sgd(grad, learningRate, param);
}
void Optimizer::adagrad(Real& grad, const Real learningRate, Real& gradHist, Real& param){
gradHist += grad * grad;
grad /= sqrt(gradHist);
Optimizer::sgd(grad, learningRate, param);
}
void Optimizer::momentum(MatD& grad, const Real learningRate, const Real m, MatD& gradHist, MatD& param){
gradHist.array() *= m;
Optimizer::sgd(grad, -learningRate, gradHist);
Optimizer::sgd(gradHist, 1.0, param);
}
void Optimizer::momentum(VecD& grad, const Real learningRate, const Real m, VecD& gradHist, VecD& param){
gradHist.array() *= m;
Optimizer::sgd(grad, -learningRate, gradHist);
Optimizer::sgd(gradHist, 1.0, param);
}
void Optimizer::momentum(Real& grad, const Real learningRate, const Real m, Real& gradHist, Real& param){
gradHist *= m;
Optimizer::sgd(grad, -learningRate, gradHist);
Optimizer::sgd(gradHist, 1.0, param);
}
| [
"kinugawa@owl1.logos.ic.i.u-tokyo.ac.jp"
] | kinugawa@owl1.logos.ic.i.u-tokyo.ac.jp |
faa5760b10fc648b63bb022135ef6e06fa86ebf7 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/inetcore/outlookexpress/import/pch/pch.hxx | 01c4fd714b579390b183f6d48f517802e476bd33 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 228 | hxx | #include <windows.h>
#include <windowsx.h>
#include <shlobj.h>
#include <comctrlp.h>
#include <shlobjp.h>
#include <tchar.h>
#include <shlwapi.h>
#include <msoert.h>
#include <oestore.h>
#include <BadStrFunctions.h>
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
2a2b893720b0946ea611913a1012c63f75198987 | d806396011b0ab8503449fc8ac30a27d131acac4 | /InterviewBit/Array/Min Steps in Infinite Grid/solve.cpp | c1a2d4c2778fa67a396ea4cce9350d0868c3bd07 | [] | no_license | divyanshusahu/CodeMonk | 768a207c77e772cf8ac41d1d31bcd7328f4ac16d | 5b2b9332e74dd05098d9d2f1a0ac90bd27f2f7f5 | refs/heads/master | 2020-04-09T12:29:20.492917 | 2019-11-25T17:24:28 | 2019-11-25T17:24:28 | 160,352,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | cpp | #include <bits/stdc++.h>
using namespace std;
int coverPoints(vector<int> &A, vector<int> &B)
{
int min_distance = 0;
for (int i = 0; i < A.size() - 1; i++)
{
int xi = A[i];
int xf = A[i + 1];
int yi = B[i];
int yf = B[i + 1];
int dx = abs(xf - xi);
int dy = abs(yf - yi);
min_distance += min(dx, dy) + abs(dx - dy);
}
return min_distance;
} | [
"dsahu1997@gmail.com"
] | dsahu1997@gmail.com |
6ace11cdcaef8f7664b04f44eb8da240f5064949 | c75e00a4569cf9eb5392f48f81623f6d7991ce3e | /Goding/Framework/ColladaLoader/ColladaStaticMesh.h | c8a13f7a17a5e92f0dce6e7ed2d5e6dc160d6db1 | [] | no_license | rodrigobmg/choding | b90dd63ff3916d969ca625134553e1ff034e1de8 | 7b559066e0c0989720a507c011bbfd0168c7de8f | refs/heads/master | 2021-01-01T03:41:36.274647 | 2012-04-02T07:03:21 | 2012-04-02T07:03:21 | 57,394,584 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,546 | h | #pragma once
#include <vector>
#include <dae.h>
#include <dom.h>
#include <dom/domCOLLADA.h>
#include <dae\daeElement.h>
#include "..\..\EntitySystem\EntitySystem.h"
#include "TempMesh.h"
#include "..\..\EntitySystem\Component\Visual\StaticMesh.h"
#ifdef _DEBUG
#pragma comment( lib , "libcollada14dom22-d.lib" )
#else
#pragma comment( lib , "libcollada14dom22.lib" )
#endif
using namespace std;
class ColladaStaticMesh
{
private:
//Dae file
DAE dae;
//Root node
domCOLLADA* root;
//<library_visual_scenes> node
daeElement* library_visual_scenes;
//<library_geometries> node
daeElement* library_geometries;
//<library_animations> node
daeElement* library_animations;
std::vector<TempMesh*> mesh_container_t;
public:
//Constructor
ColladaStaticMesh();
~ColladaStaticMesh();
//Load all the meshes from a file
void Load(std::string filename , EntitySystem* pEntitySystem );
void processVisualScenes( std::vector<TempMesh*>& Meshs );
void processGeometries( std::vector<TempMesh*>& Meshs );
//Process a <source> node
void processSource(TempMesh* mesh, daeElement* source);
//Process a <triangles> node
void processTriangles(TempMesh* mesh, daeElement* triangles);
Matrix44 processMatrix(daeElement* matrix);
//Convert matrix
Matrix44 collada2DirectX(Matrix44 input);
void MakeTempMeshToMeshComponent( std::vector<TempMesh*>& Meshs , EntitySystem* pEntitySystem );
void MakeDirectXFriendly( Entity* pEntity, StaticMesh* Meshs );
}; | [
"LeeOneHyo@gmail.com"
] | LeeOneHyo@gmail.com |
ce829c36a7e480b6239aade0a725c1ef2efdb283 | fec81bfe0453c5646e00c5d69874a71c579a103d | /blazetest/src/mathtest/operations/dmatsmatadd/LDaSCb.cpp | 905c20c9e4e294923e2308f1d3778deac43ddb81 | [
"BSD-3-Clause"
] | permissive | parsa/blaze | 801b0f619a53f8c07454b80d0a665ac0a3cf561d | 6ce2d5d8951e9b367aad87cc55ac835b054b5964 | refs/heads/master | 2022-09-19T15:46:44.108364 | 2022-07-30T04:47:03 | 2022-07-30T04:47:03 | 105,918,096 | 52 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 4,237 | cpp | //=================================================================================================
/*!
// \file src/mathtest/operations/dmatsmatadd/LDaSCb.cpp
// \brief Source file for the LDaSCb dense matrix/sparse matrix addition math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/LowerMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/operations/dmatsmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'LDaSCb'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using LDa = blaze::LowerMatrix< blaze::DynamicMatrix<TypeA> >;
using SCb = blaze::SymmetricMatrix< blaze::CompressedMatrix<TypeB> >;
// Creator type definitions
using CLDa = blazetest::Creator<LDa>;
using CSCb = blazetest::Creator<SCb>;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i*i; ++j ) {
RUN_DMATSMATADD_OPERATION_TEST( CLDa( i ), CSCb( i, j ) );
}
}
// Running tests with large matrices
RUN_DMATSMATADD_OPERATION_TEST( CLDa( 67UL ), CSCb( 67UL, 7UL ) );
RUN_DMATSMATADD_OPERATION_TEST( CLDa( 128UL ), CSCb( 128UL, 16UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix addition:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
9f9e33f2d5d68cf95360fb4386e5e2f1850af51e | a7606c8002a84aa5e7cce9b0446b242386316b82 | /textures/texture.h | 47713866538f9617c1a4c0de5244e16d9c029584 | [] | no_license | cache-tlb/rt-from-the-ground-up | 5fdcfadccb686c65a6be43c6e165786471e8a4a1 | 2784799e5124bc8bc09e673d65e5b8bf8f149758 | refs/heads/master | 2016-09-11T09:37:44.312899 | 2012-10-12T16:04:36 | 2012-10-12T16:04:36 | 32,261,877 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | h | #ifndef TEXTURE_H
#define TEXTURE_H
// Copyright (C) Kevin Suffern 2000-2007.
// This C++ code is for non-commercial purposes only.
// This C++ code is licensed under the GNU General Public License Version 2.
// See the file COPYING.txt for the full license.
#include <math.h>
#include "shaderec.h"
#include "rgbcolor.h"
class Texture {
public:
Texture(void);
Texture(const Texture& texture);
virtual Texture*
clone(void) const = 0;
virtual
~Texture(void);
virtual RGBColor
get_color(const ShadeRec& sr) const = 0;
protected:
Texture&
operator= (const Texture& rhs);
};
#endif // TEXTURE_H
| [
"liub91@gmail.com@66790ea4-9dcb-8dae-10e5-9860326c6d77"
] | liub91@gmail.com@66790ea4-9dcb-8dae-10e5-9860326c6d77 |
56a8361deda15d3856969c3d0e66750c574d545a | 4207610c48cbb9021f4420791a9c9d07550b72d9 | /Source/Lua/JuceClasses/LTime.h | b3ca59b88c45b1ecaae6ef09b95e1e8c0b12e42f | [
"GPL-2.0-only",
"BSD-3-Clause"
] | permissive | RomanKubiak/ctrlr | d98a910eb46f6cf4324da3fc3ae664cc7dd5aec9 | 8aa00d82127acda42ad9ac9b7b479461e9436aa4 | refs/heads/master | 2023-02-13T00:21:04.546585 | 2022-06-24T10:53:16 | 2022-06-24T10:53:16 | 14,671,067 | 435 | 82 | BSD-3-Clause | 2022-05-31T18:18:23 | 2013-11-24T22:53:11 | C++ | UTF-8 | C++ | false | false | 1,390 | h | #ifndef L_TIME
#define L_TIME
#include "JuceHeader.h"
extern "C"
{
#include "lua.h"
}
class LTime : public Time
{
public:
LTime() : Time()
{
}
LTime(int year, int month, int day, int hours, int minutes, int seconds, int milliseconds, bool useLocalTime)
: Time(year, month, day, hours, minutes, seconds, milliseconds, useLocalTime)
{}
LTime(double millisecondsSinceEpoch) : Time((int64)millisecondsSinceEpoch)
{}
LTime(const LTime &other) : Time(other)
{}
LTime(const Time &other) : Time(other)
{}
double toMilliseconds()
{
return ( (double) Time::toMilliseconds());
}
static LTime getCurrentTime()
{
return (Time::getCurrentTime());
}
static double currentTimeMillis()
{
return ( (double) Time::currentTimeMillis());
}
static double getHighResolutionTicks()
{
return ( (double) Time::getHighResolutionTicks());
}
static double getHighResolutionTicksPerSecond()
{
return ( (double) Time::getHighResolutionTicksPerSecond());
}
static double highResolutionTicksToSeconds(double ticks)
{
return (Time::highResolutionTicksToSeconds(ticks));
}
static double secondsToHighResolutionTicks(double seconds)
{
return ( (double) Time::secondsToHighResolutionTicks(seconds));
}
static void wrapForLua (lua_State *L);
};
#endif
| [
"kubiak.roman@gmail.com"
] | kubiak.roman@gmail.com |
fc564bfaad637ba17a313c30748c9ac215798fec | f682279f25021b1808638a4c713c4c57e56ff26d | /app/src/main/jni/fingerprint/fingerprint_jni_register.cpp | bc37a8985d138862b7c95356144bce08bb9606a1 | [] | no_license | aungmk/wizarpos-apidemo | 882cc0c8abc3feb456f05e3a4c5656f55e6366eb | eda85198709f827ba7c7dde32e1be542400441aa | refs/heads/master | 2020-09-03T13:25:12.715626 | 2018-01-01T14:24:25 | 2018-01-01T14:24:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <jni.h>
#include "hal_sys_log.h"
#include "fingerprint_jni_interface.h"
/*
* Register several native methods for one class
*/
static int register_native_methods(JNIEnv* env, const char* strClassName, JNINativeMethod* pMethods, int nMethodNumber)
{
jclass clazz;
clazz = env->FindClass(strClassName);
if(clazz == NULL)
return JNI_FALSE;
if(env->RegisterNatives(clazz, pMethods, nMethodNumber) < 0)
return JNI_FALSE;
return JNI_TRUE;
}
/*
* Register native methods for all class
*
*/
static int register_native_for_all_class(JNIEnv* env)
{
int nCount = 0;
JNINativeMethod* pMethods = fingerprint_get_methods(&nCount);
int nResult = register_native_methods(env, fingerprint_get_class_name(), pMethods, nCount);
// +update by pengli
if(nResult == JNI_FALSE){
env->ExceptionClear();
nResult = register_native_methods(env, get_class_name_internal(), pMethods, nCount);
}
// -update by pengli
return nResult;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint nResult = -1;
if(vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK)
{
hal_sys_info("led JNI_OnLoad(), failed in GetEnv()");
return -1;
}
assert(env != NULL);
if(!register_native_for_all_class(env))
return -1;
return JNI_VERSION_1_4;
}
| [
"rizupz@gmail.com"
] | rizupz@gmail.com |
ccf7ba7178aaa405dfd92468c86c4133ba92405a | 443416bab5d7c258936dae678feb27de6c537758 | /applications/MeshingApplication/custom_io/mmg_io.cpp | 0ffccdc9cf3ef1aae16acd58b4bcf1764ec52f42 | [
"BSD-3-Clause"
] | permissive | pyfsi/Kratos | b941e12594ec487eafcd5377b869c6b6a44681f4 | 726aa15a04d92c958ba10c8941ce074716115ee8 | refs/heads/master | 2020-04-27T17:10:10.357084 | 2019-11-22T09:05:35 | 2019-11-22T09:05:35 | 174,507,074 | 2 | 0 | NOASSERTION | 2020-03-27T16:38:28 | 2019-03-08T09:22:47 | C++ | UTF-8 | C++ | false | false | 6,595 | cpp | // KRATOS __ __ _____ ____ _ _ ___ _ _ ____
// | \/ | ____/ ___|| | | |_ _| \ | |/ ___|
// | |\/| | _| \___ \| |_| || || \| | | _
// | | | | |___ ___) | _ || || |\ | |_| |
// |_| |_|_____|____/|_| |_|___|_| \_|\____| APPLICATION
//
// License: BSD License
// license: MeshingApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
// System includes
#include <unordered_set>
// External includes
// Project includes
#include "utilities/timer.h"
#include "custom_io/mmg_io.h"
#include "utilities/assign_unique_model_part_collection_tag_utility.h"
// NOTE: The following contains the license of the MMG library
/* =============================================================================
** Copyright (c) Bx INP/Inria/UBordeaux/UPMC, 2004- .
**
** mmg is free software: you can redistribute it and/or modify it
** under the terms of the GNU Lesser General Public License as published
** by the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** mmg is distributed in the hope that it will be useful, but WITHOUT
** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
** FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
** License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License and of the GNU General Public License along with mmg (in
** files COPYING.LESSER and COPYING). If not, see
** <http://www.gnu.org/licenses/>. Please read their terms carefully and
** use this copy of the mmg distribution only if you accept them.
** =============================================================================
*/
namespace Kratos
{
/************************************* CONSTRUCTOR *********************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
MmgIO<TMMGLibrary>::MmgIO(
std::string const& rFilename,
Parameters ThisParameters,
const Flags Options
)
: mFilename(rFilename)
, mThisParameters(ThisParameters)
, mOptions(Options)
{
Parameters default_parameters = GetDefaultParameters();
mThisParameters.RecursivelyValidateAndAssignDefaults(default_parameters);
// Check the mode
if (mOptions.Is(IO::APPEND)) {
KRATOS_ERROR << "APPEND not compatible with MmgIO" << std::endl;
}
if (mOptions.IsNot(IO::SKIP_TIMER)) Timer::SetOuputFile(rFilename + ".time");
/* We restart the MMG mesh and solution */
mMmmgUtilities.SetEchoLevel(mThisParameters["echo_level"].GetInt());
mMmmgUtilities.InitMesh();
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgIO<TMMGLibrary>::ReadModelPart(ModelPart& rModelPart)
{
KRATOS_TRY;
// Automatically read the mesh
mMmmgUtilities.InputMesh(mFilename);
// Automatically read the solution
mMmmgUtilities.InputSol(mFilename);
// Read JSON of colors
std::unordered_map<IndexType,std::vector<std::string>> colors; /// Where the sub model parts IDs are stored
AssignUniqueModelPartCollectionTagUtility::ReadTagsFromJson(mFilename, colors);
// Create the submodelparts
const std::string& r_main_name = rModelPart.Name();
for (auto& r_color : colors) {
for (auto& r_name : r_color.second) {
if (!rModelPart.HasSubModelPart(r_name) && r_main_name != r_name) {
rModelPart.CreateSubModelPart(r_name);
}
}
}
// Some information
MMGMeshInfo<TMMGLibrary> mmg_mesh_info;
mMmmgUtilities.PrintAndGetMmgMeshInfo(mmg_mesh_info);
// Creating auxiliar maps of pointers
std::unordered_map<IndexType,Condition::Pointer> ref_condition; /// Reference condition
std::unordered_map<IndexType,Element::Pointer> ref_element; /// Reference element
// Fill the maps
mMmmgUtilities.WriteReferenceEntitities(rModelPart, mFilename, ref_condition, ref_element);
// Writing the new mesh data on the model part
NodeType::DofsContainerType empty_dofs;
mMmmgUtilities.WriteMeshDataToModelPart(rModelPart, colors, empty_dofs, mmg_mesh_info, ref_condition, ref_element);
// Writing the new solution data on the model part
mMmmgUtilities.WriteSolDataToModelPart(rModelPart);
/* After that we reorder nodes, conditions and elements: */
mMmmgUtilities.ReorderAllIds(rModelPart);
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template<MMGLibrary TMMGLibrary>
void MmgIO<TMMGLibrary>::WriteModelPart(ModelPart& rModelPart)
{
KRATOS_TRY;
// The auxiliar color maps
ColorsMapType aux_ref_cond, aux_ref_elem;
// We initialize the mesh data with the given modelpart
std::unordered_map<IndexType,std::vector<std::string>> colors; /// Where the sub model parts IDs are stored
mMmmgUtilities.GenerateMeshDataFromModelPart(rModelPart, colors, aux_ref_cond, aux_ref_elem);
// Generate the maps of reference
std::unordered_map<IndexType,Element::Pointer> ref_element; /// Reference element
std::unordered_map<IndexType,Condition::Pointer> ref_condition; /// Reference condition
mMmmgUtilities.GenerateReferenceMaps(rModelPart, aux_ref_cond, aux_ref_elem, ref_condition, ref_element);
// We initialize the solution data with the given modelpart
mMmmgUtilities.GenerateSolDataFromModelPart(rModelPart);
// Check if the number of given entities match with mesh size
mMmmgUtilities.CheckMeshData();
// Automatically save the mesh
mMmmgUtilities.OutputMesh(mFilename);
// Automatically save the solution
mMmmgUtilities.OutputSol(mFilename);
// Output the reference files
mMmmgUtilities.OutputReferenceEntitities(mFilename, ref_condition, ref_element);
// Writing the colors to a JSON
AssignUniqueModelPartCollectionTagUtility::WriteTagsToJson(mFilename, colors);
KRATOS_CATCH("");
}
/***********************************************************************************/
/***********************************************************************************/
template class MmgIO<MMGLibrary::MMG2D>;
template class MmgIO<MMGLibrary::MMG3D>;
template class MmgIO<MMGLibrary::MMGS>;
}// namespace Kratos.
| [
"vmataix@cimne.upc.edu"
] | vmataix@cimne.upc.edu |
21c1fcf6a43339de4649e7aadc1154dfc882d6d4 | 37597ac97671d766693a775392ffa617395945b5 | /Demo/Plugins/Example/Plugin.cpp | dce376535947744ca780221537e390713dbfd315 | [] | no_license | Mingun/Ogre-Systems | 9532d368b5cc02fc1786c6254658d7ec1eba2a74 | dc892bd8e651be8cb831ced861d3ee3210b1d519 | refs/heads/master | 2021-01-10T18:46:55.731616 | 2011-09-15T11:23:02 | 2011-09-15T11:23:02 | 2,342,710 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,318 | cpp | // Plugin.cpp : Определение точки входа DLL приложения.
//
#include "stdafx.h"
#include "Plugin.h"
#include "OLS/OgreLogManager.h"
#include "OPS/PluginManager.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch ( ul_reason_for_call )
{
case DLL_PROCESS_ATTACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//Plugin* plugin;
const int PLAGINS_COUNT = 2;
Plugin* plugins[PLAGINS_COUNT];
extern "C" {
PLUGIN_API void dllStartPlugin()
{
for ( int i = 0; i < PLAGINS_COUNT; ++i )
{
plugins[i] = OGRE_NEW Plugin();
Ogre::PluginManager::getSingleton().installPlugin( plugins[i] );
}
}
PLUGIN_API void dllStopPlugin()
{
for ( int i = PLAGINS_COUNT-1; i >=0; --i )
{
Ogre::PluginManager::getSingleton().uninstallPlugin( plugins[i] );
OGRE_DELETE plugins[i];
}
}
}
Ogre::String Plugin::mPluginName( "Example plugin" );
Plugin::Plugin()
{
}
Plugin::~Plugin()
{
}
const Ogre::String& Plugin::getName() const
{
return mPluginName;
}
void Plugin::install()
{
}
void Plugin::initialise()
{
}
void Plugin::shutdown()
{
}
void Plugin::uninstall()
{
}
| [
"alexander_sergey@mail.ru"
] | alexander_sergey@mail.ru |
b55c65b740291e01987f8db31114fd84c89a845f | 80e56bdfceac35462afcb394d1a3e0a2d97b87a2 | /Test/src/IndustryTree.cpp | 36296a342e9d7ed0a71fa3d710989eee0ff86f6d | [] | no_license | dimitarpg13/cpp_testcode | 8c6f338b5a831c35d813f13e5d2c83064accf253 | 9c1a5f2299a8c04cc5cb3dedc8a374063ac65cff | refs/heads/master | 2021-06-06T05:56:10.556943 | 2016-02-27T15:45:57 | 2016-02-27T15:45:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,067 | cpp | /*
* IndustryTree.cpp
*
* Created on: Oct 11, 2014
* Author: root
*/
#include "IndustryTree.h"
namespace Algorithms {
IndustryTree::IndustryTree(string fileName) {
m_pRoot = new IndustryInfo("Classification");
parseIndustries(fileName);
}
IndustryTree::~IndustryTree() {
// delete all IndustryInfo instances
delete m_pRoot;
// delete all companyInfo instances
map<string,CompanyInfo*>::iterator it;
for (it = m_mapCompanies.begin(); it != m_mapCompanies.end(); ++it )
delete it->second;
}
bool IndustryTree::parseIndustries (string fileName)
{
bool res = false;
try
{
ifstream ifs;
ifs.open(fileName);
if (ifs.is_open())
{
string line, val, name, parentName;
IndustryInfo * cur = nullptr, * parent = nullptr;
pair<map<string,IndustryInfo*>::iterator,bool> ret;
map<string,IndustryInfo*>::iterator it;
while (getline(ifs, line, '\n'))
{
//cout << line << '\n';
if (line.substr(0,2)=="//")
continue;
parent = nullptr;
cur = nullptr;
istringstream iss(line);
int i=0;
while (getline(iss, val, '|' ))
{
// cout << '\t' << val << '\n';
if (i==1)
name = val;
else if (i==2)
parentName = val;
else if (i > 2)
break;
i++;
}
it = m_mapIndustries.find(name);
if (it == m_mapIndustries.end())
{
cur = new IndustryInfo(name);
m_mapIndustries[name] = cur;
if (!parentName.empty())
{
it = m_mapIndustries.find(parentName);
if (it == m_mapIndustries.end())
{
parent = new IndustryInfo(parentName);
// since we do not know who is the parent
// of the parent industry insert it at the root
m_pRoot->addChild(parent);
}
else
{
parent = it->second;
}
parent->addChild(cur);
cur->setParent(parent);
}
else
{
// the current industry does not have a parent so
// insert it at the root
m_pRoot->addChild(cur);
}
if (!res)
res = true;
}
else
{
if (!parentName.empty())
{
it = m_mapIndustries.find(parentName);
if (it == m_mapIndustries.end())
{
parent = new IndustryInfo(parentName);
// since we do not know who is the parent
// of the parent industry insert it at the root
m_pRoot->addChild(parent);
}
}
}
}
ifs.close();
}
}
catch (...)
{
cout << "Could not parse file " + fileName << '\n';
}
return res;
}
string IndustryTree::getCompanyKey(string name, float marketCap, float revenue)
{
stringstream sstr;
sstr << name;
sstr << ":";
sstr << setprecision(2) << fixed << marketCap;
sstr << ":";
sstr << setprecision(2) << fixed << revenue;
return sstr.str();
}
bool IndustryTree::addCompanies(string fileName)
{
bool res = false;
try
{
ifstream ifs;
ifs.open(fileName);
if (ifs.is_open())
{
string line, val, compName, industryName, compKey;
float marketCap, revenue;
CompanyInfo * company = nullptr;
IndustryInfo * industry = nullptr;
pair<map<string,IndustryInfo*>::iterator,bool> ret;
map<string,CompanyInfo*>::iterator itComp;
map<string,IndustryInfo*>::iterator itInd;
while (getline(ifs, line, '\n'))
{
//cout << line << '\n';
if (line.substr(0,2)=="//" || line.empty())
continue;
istringstream iss(line);
int i=0;
while (getline(iss, val, '|' ))
{
// cout << '\t' << val << '\n';
if (i==1)
compName = val;
else if (i==2)
industryName = val;
else if (i==3)
marketCap = stof(val);
else if (i==4)
revenue = stof(val);
else if (i>4)
break;
i++;
}
if (compName=="Gemvax & Kael")
{
cout << compName << "'s industry: " << industryName << "\n";
}
compKey = compName;//getCompanyKey(compName,marketCap,revenue);
itComp = m_mapCompanies.find(compKey);
if (itComp == m_mapCompanies.end())
{
company = new CompanyInfo(compName,marketCap,revenue);
itInd = m_mapIndustries.find(industryName);
if (itInd == m_mapIndustries.end())
{
// if the industry is not found in the tree
// then add it to the root
industry = new IndustryInfo(industryName);
m_pRoot->addChild(industry);
}
else
industry = itInd->second;
industry->addCompany(company);
company->addIndustry(industry);
m_mapCompanies[compKey] = company;
}
else
{
company = itComp->second;
itInd = m_mapIndustries.find(industryName);
if (itInd == m_mapIndustries.end())
{
// if the industry is not found in the tree
// then add it to the root
industry = new IndustryInfo(industryName);
m_pRoot->addChild(industry);
}
else
{
industry = itInd->second;
}
industry->addCompany(company);
company->addIndustry(industry);
}
}
ifs.close();
}
}
catch (...)
{
cout << "Could not parse file " + fileName << '\n';
}
return res;
}
bool IndustryTree::addIndustries(string fileName)
{
bool res = parseIndustries(fileName);
return res;
}
void IndustryTree::printIndustries()
{
cout << m_pRoot->getName() << "\n[\n";
printIndustries(m_pRoot, "");
cout << "]\n";
}
void IndustryTree::printIndustries(IndustryInfo * industry, string indent)
{
if (industry != nullptr)
{
if (industry != m_pRoot)
cout << indent << industry->getName() << "\n";
string newIndent = indent + "\t";
vector<IndustryInfo*> industries = industry->getChildren();
for (vector<IndustryInfo*>::iterator it = industries.begin(); it != industries.end(); ++it )
printIndustries(*it,newIndent);
}
}
void IndustryTree::findCompanies(string industryName, string propertyName)
{
string name_lc = propertyName;
name_lc.erase(name_lc.find_last_not_of(" \n\r\t")+1);
transform(name_lc.begin(), name_lc.end(), name_lc.begin(), ::tolower);
IndustryInfo * industry = nullptr;
map<string,IndustryInfo*>::iterator it = m_mapIndustries.find(industryName);
if (it != m_mapIndustries.end())
{
industry = it->second;
set<CompanyInfo*> compSet;
findCompanies(industry,compSet);
vector<CompanyInfo*> companies(compSet.begin(),compSet.end());
if (name_lc=="companyname")
{
sort(companies.begin(), companies.end(), m_foCompNameCmp);
}
else if (name_lc=="marketcap")
{
sort(companies.begin(), companies.end(), m_foCompMrktCapCmp);
}
else if (name_lc=="revenue")
{
sort(companies.begin(), companies.end(), m_foCompRevenueCmp);
}
else
{
throw invalid_argument("findCompanies: invalid property name "+propertyName);
}
cout << "[";
for (vector<CompanyInfo*>::iterator it = companies.begin(); it != companies.end(); ++it )
{
cout << (*it)->getName();
if (it != companies.end() - 1)
cout << ", ";
}
cout << "]" << "\n";
}
else
{
cout << "[" << "]" << "\n";
}
}
void IndustryTree::findCompanies(IndustryInfo * industry, set<CompanyInfo*>& companies)
{
if (industry != nullptr)
{
vector<CompanyInfo*>& curCompanies = industry->getCompanies();
for (vector<CompanyInfo*>::iterator itComp = curCompanies.begin(); itComp != curCompanies.end(); ++itComp )
companies.insert(*itComp);
vector<IndustryInfo*>& children = industry->getChildren();
for (vector<IndustryInfo*>::iterator itInd = children.begin(); itInd != children.end(); ++itInd )
{
findCompanies(*itInd, companies);
}
}
}
void IndustryTree::findIndustries(string companyName)
{
CompanyInfo * company = nullptr;
map<string,CompanyInfo*>::iterator it = m_mapCompanies.find(companyName);
if (it != m_mapCompanies.end())
{
company = it->second;
vector<IndustryInfo*>& industries = company->getIndustries();
cout << "[";
for (vector<IndustryInfo*>::iterator it = industries.begin(); it != industries.end(); ++it )
{
cout << (*it)->getName();
if (it != industries.end() - 1)
cout << ", ";
}
cout << "]\n";
}
}
} /* namespace Algorithms */
| [
"dimitar_pg13@hotmail.com"
] | dimitar_pg13@hotmail.com |
1c1e4b852e313ebaf4a1cf55b5381a47450d2e51 | 5199972c95653ae4b0be104f3960f0685733b487 | /src/net/eventbase.h | b79ceac39585faa258d3ee84e7a3682c0551f57c | [] | no_license | Mahonghui/AmNet | 5d35f5731e6abdf7b015da19735777cc03b0ee50 | 7cd2fed90790b55d63bb6010495aaf8373bf4b94 | refs/heads/master | 2020-04-10T05:35:47.761083 | 2019-02-24T02:25:12 | 2019-02-24T02:25:12 | 160,832,391 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,533 | h | //
// Created by 马宏辉 on 2018-12-08.
//
#ifndef AMNET_EVENTBASE_H
#define AMNET_EVENTBASE_H
#include <sys/epoll.h>
#include <functional>
#include "timestamp.h"
class EventBase{
public:
// 类似闭包函数,包装好的函数赋给一个变量
using callback = std::function<void()>;
using read_callback = std::function<void (TimeStamp)>;
explicit EventBase(int fd);
~EventBase();
// 关联读写事件
void Readable(){
events_ |= (EPOLLIN | EPOLLPRI);
}
void Writeable(){
events_ |= (EPOLLOUT);
}
// 解除事件关联
void unReadble(){
events_ &= ~(EPOLLIN|EPOLLPRI);
}
void unWriteable(){
events_ &= ~(EPOLLOUT);
}
// 定义事件处理函数
void SetReadableCallback(read_callback&& cb){read_callback_ = cb;}
void setWriteableCallback(callback&& cb){write_callback_ = cb;}
void setErrorCallback(callback&& cb){error_callback_ = cb;}
void setCloseCallback(callback&& cb){close_callback_ = cb;}
// 设置活跃事件
void SetRevents(int revent){retevent_ = revent;}
// 事件分发器
void EventHanlder();
// getter
int getFd() const { return fd_;}
int getEvents() const{ return events_;}
bool isWriting() const { return (bool)events_ & EPOLLOUT;}
private:
const int fd_;
int events_;
int retevent_;
read_callback read_callback_;
callback write_callback_;
callback error_callback_;
callback close_callback_;
};
#endif //AMNET_EVENTBASE_H
| [
"amisher@163.com"
] | amisher@163.com |
c74b9839e22b3ae6fd026e9f77f7c56601e7586d | 99c9cc74e9380311edfba3ba5c894d09ec128b32 | /src/session_factory.cpp | 256d571201af96b1c7b4d5402c8dd39f2648216b | [
"MIT"
] | permissive | timothyqiu/http-client | f9f4c76acfc3eb52f48d6e7cf7fbb3bd484ec488 | 8cb001d98dbe959fbb6fa7a1d62675fca376e2d6 | refs/heads/master | 2021-03-03T10:24:30.831186 | 2020-03-21T04:31:23 | 2020-03-21T04:31:23 | 245,954,058 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | #include <ohc/session_factory.hpp>
#include <ohc/session.hpp>
#include "mbedtls/session.hpp"
#include "openssl/session.hpp"
auto SessionFactory::instance() -> SessionFactory&
{
static SessionFactory instance;
return instance;
}
SessionFactory::SessionFactory()
{
registry_["mbedtls"] = MbedTlsSession::create;
registry_["openssl"] = OpenSslSession::create;
}
auto SessionFactory::create(std::string const& name,
SessionConfig const& config) -> SessionPtr
{
auto& registry = SessionFactory::instance().registry_;
if (auto const iter = registry.find(name); iter != std::end(registry)) {
return iter->second(config);
}
return nullptr;
}
| [
"timothyqiu32@gmail.com"
] | timothyqiu32@gmail.com |
2741c58cb6732b0b52f8b1ee4f05e142fbbd0fbc | f84a0ee6bee670736b64427b93d5141061be22ba | /campusp17/d1/fermat.cpp | aea8384d7f632cb854e7e16906a46180275a51c4 | [] | no_license | joseleite19/competitive-programming | eaeb03b6a250619a4490f5da5274da3ba8017b62 | f00e7a6cb84d7b06b09d00fffd7c5ac68a7b99e3 | refs/heads/master | 2020-04-15T14:05:40.261419 | 2017-12-19T18:34:42 | 2017-12-19T18:34:42 | 57,311,825 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,039 | cpp | #include <bits/stdc++.h>
using namespace std;
struct cd{
double r, i;
cd(double r = 0, double i = 0) : r(r), i(i){}
double real() const{ return r; }
void operator*=(double o){ r *= o, i *= o; }
void operator/=(double o){ r /= o, i /= o; }
void operator*=(const cd& o){
double a, b;
a = r*o.r - i*o.i;
b = r*o.i + i*o.r;
r = a, i = b;
}
cd operator*(const cd& o) const{ return cd(r*o.r - i*o.i, r*o.i + i*o.r); }
cd operator+(const cd& o) const{ return cd(r+o.r, i+o.i); }
cd operator-(const cd& o) const{ return cd(r-o.r, i-o.i); }
};
typedef cd base;
const double PI = acos(-1);
void fft (vector<base> & a, bool invert) {
int n = (int) a.size();
for (int i=1, j=0; i<n; ++i) {
int bit = n >> 1;
for (; j>=bit; bit>>=1)
j -= bit;
j += bit;
if (i < j)
swap (a[i], a[j]);
}
for (int len=2; len<=n; len<<=1) {
double ang = 2*PI/len * (invert ? -1 : 1);
base wlen(cos(ang), sin(ang));
for (int i = 0; i < n; i += len) {
base w(1);
for (int j=0; j<len/2; ++j) {
base u = a[i+j], v = a[i+j+len/2] * w;
a[i+j] = u + v;
a[i+j+len/2] = u - v;
w *= wlen;
}
}
}
if (invert)
for (int i=0; i<n; ++i)
a[i] /= n;
}
long long f(long long b, int n, int m){
long long ans = 1;
while(n){
if(n & 1) ans = (ans * b) % m;
b = (b * b) % m;
n >>= 1;
}
return ans;
}
inline long long cast(double x){ return x; }
int main(){
int n, m;
scanf("%d %d", &n, &m);
vector<base> v(1 << (31-__builtin_clz(4*m)));
vector<long long> ori(v.size());
for(int i = 1; i < m; i++){
int x = f(i, n, m);
ori[x]++;
}
for(int i = 0; i < m; i++)
v[i] = base(ori[i], 0);
fft(v, 0);
for(int i = 0; i < v.size(); i++)
v[i] = v[i] * v[i];
fft(v, 1);
long long ans = 0;
for(int i = 1; i < m; i++){
ans += (cast(v[i].real()+0.5) + cast(v[i+m].real()+0.5)) * ori[i];
}
printf("%lld\n", ans);
}
| [
"leite.josemarcos@gmail.com"
] | leite.josemarcos@gmail.com |
314b8afec2ade781c64260c40bcdfb4fbf9efa49 | c9351f8f573c603cfa767956d406bac9bf888b8c | /compile/libbcc/lib/AndroidBitcode/X86/X86ABCCompilerDriver.cpp | e8f01592ebba31bc3bba0fcc7577696e958cf66c | [
"NCSA",
"Apache-2.0",
"BSD-4-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | wangwangheng/Study_Framework-4.3_r1 | 8ea01845b6d9de547f3cdd4ca03578fe7ebf68ab | 3360c234bfb859f3a7c8f01168091d1b83fe9e55 | refs/heads/master | 2021-05-09T21:23:08.669513 | 2018-02-23T08:15:43 | 2018-02-23T08:15:43 | 118,724,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | cpp | /*
* Copyright 2012, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "X86/X86ABCCompilerDriver.h"
#include "bcc/Support/TargetCompilerConfigs.h"
#include "bcc/Support/TargetLinkerConfigs.h"
namespace {
static const char *X86NonPortableList[] = {
"stat",
"fstat",
"lstat",
"fstatat",
"open",
"ioctl",
"fcntl",
"epoll_ctl",
"epoll_wait",
NULL // NUL-terminator
};
} // end anonymous namespace
namespace bcc {
CompilerConfig *X86ABCCompilerDriver::createCompilerConfig() const {
// x86-64 is currently unsupported.
return new (std::nothrow) X86_32CompilerConfig();
}
LinkerConfig *X86ABCCompilerDriver::createLinkerConfig() const {
// x86-64 is currently unsupported.
return new (std::nothrow) X86_32LinkerConfig();
}
const char **X86ABCCompilerDriver::getNonPortableList() const {
return X86NonPortableList;
}
} // end namespace bcc
| [
"wangheng@mobimagic.com"
] | wangheng@mobimagic.com |
603c0f89f2c78aca8c25fc4acc1c0467f7a266fe | 36f022d7d8b1e18055edd86fb301b89e11689256 | /sockets/servidor5.cpp | 9edfc10ba3982cc60e1dafa0bbed7428558d6891 | [] | no_license | lucaspwo/sistemas_de_tempo_real | d44755ff14e6e27ab3a7382ba5a021af7bc0d912 | bf2eb37d9da66b9bd8e4ef6cf0bda43eebf2106a | refs/heads/master | 2023-03-31T11:33:41.494561 | 2021-06-10T13:14:17 | 2021-06-10T13:14:17 | 244,973,909 | 0 | 1 | null | 2022-12-08T07:37:33 | 2020-03-04T18:25:01 | C++ | UTF-8 | C++ | false | false | 1,870 | cpp | //
// servidor5.cpp - Servidor utilizando protocolo UDP
//
//
// Created by Luiz Affonso on 29/11/2020.
//
//
#include "servidor5.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <unistd.h>
#include <stdlib.h>
int main( )
{
int server_sockfd, client_sockfd;
unsigned int server_len;
socklen_t client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
unsigned short porta = 9734;
if ( (server_sockfd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 ) // cria um novo socket
{
printf(" Houve erro na ebertura do socket ");
exit(1);
}
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(porta);
server_len = sizeof(server_address);
if( bind(server_sockfd, (struct sockaddr *) &server_address, server_len) < 0 )
{
perror("Houve error no Bind");
exit(1);
}
//listen(server_sockfd, 5); // No UDP não tem listen()
while(1){
char vetor_ch[4];
printf("Servidor esperando ...\n");
// No UDP não tem accept()
//client_sockfd = accept(server_sockfd, (struct sockaddr *) &client_address, &client_len);
client_len = sizeof(client_address);
if(recvfrom(server_sockfd, vetor_ch, sizeof(vetor_ch),0,
(struct sockaddr *) &client_address, &client_len) < 0 )
{
perror(" erro no RECVFROM( )");
exit(1);
}
for(int i =0; i<4;i++) {
vetor_ch[i]++;
}
sendto(server_sockfd, vetor_ch, sizeof(vetor_ch),0,(struct sockaddr *) &client_address,sizeof(struct sockaddr));
// close(server_sockfd);
}
}
| [
"lucaspwo@gmail.com"
] | lucaspwo@gmail.com |
a33148d61386a9e94396cf9c9be3f89d6e08fe29 | a0846ccad4c0195ab5337697775397cb103c68c7 | /Chapter3/LinkedList.cpp | 3a5cec8c64323deb2e1ae5b6dc844c9ddfd58bc9 | [] | no_license | keyurgolani/DataStructuresAndAlgorithmsWithCPP | 76e6f6d9281de0fcc3468b329fc0b81f9a6e4fce | 902a75c7e444a65e930475d4b1bb7274e7adecd5 | refs/heads/master | 2021-01-20T18:34:24.895541 | 2016-07-01T07:22:50 | 2016-07-01T07:22:50 | 60,823,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,859 | cpp | #include<iostream>
#include<string>
using namespace std;
template <class T>
class ListNode {
private:
T data;
ListNode * nextNode;
public:
ListNode() {
this -> nextNode = NULL;
}
ListNode(T data) {
this -> data = data;
this -> nextNode = NULL;
}
ListNode * getNext() {
return this -> nextNode;
}
void setNext(ListNode * nextNode) {
this -> nextNode = nextNode;
}
T getData() {
return this -> data;
}
void setData(T data) {
this -> data = data;
}
};
template <class U>
class LinkedList {
private:
ListNode<U> * head;
int length;
public:
LinkedList() {
this -> head = NULL;
this -> length = 0;
}
ListNode<U> * getHead() {
return this -> head;
}
ListNode<U> * getLast() {
ListNode<U> * currentNode = this -> getHead();
if(currentNode == NULL) {
return NULL;
}
while(currentNode -> getNext() != NULL) {
currentNode = currentNode -> getNext();
}
return currentNode;
}
void setHead(ListNode<U> * listNode) {
this -> head = listNode;
}
int getLength() {
return this -> length;
}
void setLength(int length) {
this -> length = length;
}
void insertAtBeginning(ListNode<U> * listNode) {
listNode -> setNext(this -> getHead());
this -> head = listNode;
length++;
}
void insertAtEnd(ListNode<U> * listNode) {
if(this -> length > 0 && this -> getHead() != NULL) {
ListNode<U> * currentNode = this -> getHead();
for (int i = 0; i < length - 1; i++) {
currentNode = currentNode -> getNext();
}
currentNode -> setNext(listNode);
} else {
this -> setHead(listNode);
}
length++;
}
void insert(ListNode<U> * listNode, int position) {
if(position > this -> length) {
position = length;
}
if(position > 0 && this -> getHead() != NULL) {
ListNode<U> * currentNode = this -> getHead();
for (int i = 0; i < position - 2; i++) {
currentNode = currentNode -> getNext();
}
listNode -> setNext(currentNode -> getNext());
currentNode -> setNext(listNode);
} else {
this -> setHead(listNode);
}
length++;
}
void print() {
ListNode<U> * currentNode = this -> getHead();
while(currentNode != NULL) {
cout << currentNode -> getData();
if(currentNode -> getNext() != NULL) {
cout << " --> ";
}
currentNode = currentNode -> getNext();
}
cout << endl;
cout << "Size: " << length << endl;
}
bool search(U data) {
ListNode<U> * currentNode = this -> getHead();
while(currentNode != NULL) {
if(currentNode -> getData() == data) {
return true;
}
currentNode = currentNode -> getNext();
}
return false;
}
bool remove(int position) {
if(position > this -> length) {
position = length;
}
if(position == 1) {
this -> removeFromBegin();
}
if(position > 1 && this -> getHead() != NULL) {
ListNode<U> * currentNode = this -> getHead();
for (int i = 0; i < position - 2; i++) {
currentNode = currentNode -> getNext();
}
ListNode<U> * deleteNode = currentNode -> getNext();
currentNode -> setNext(deleteNode -> getNext());
length--;
delete(deleteNode);
}
return false;
}
void removeFromBegin() {
ListNode<U> * deleteNode = this -> getHead();
this -> setHead(this -> getHead() -> getNext());
length--;
delete(deleteNode);
}
void removeFromEnd() {
ListNode<U> * currentNode = this -> getHead();
if(currentNode == NULL) {
return;
}
if(currentNode -> getNext() == NULL) {
this -> setHead(NULL);
delete(currentNode);
}
while(currentNode -> getNext() -> getNext() != NULL) {
currentNode = currentNode -> getNext();
}
ListNode<U> * deleteNode = currentNode -> getNext();
currentNode -> setNext(NULL);
length--;
delete(deleteNode);
}
bool removeMatch(ListNode<U> * listNode) {
ListNode<U> * currentNode = this -> getHead();
ListNode<U> * deleteNode;
if(currentNode == NULL) return false;
if(currentNode == listNode) {
deleteNode = currentNode;
this -> setHead(deleteNode -> getNext());
delete(deleteNode);
length--;
return true;
}
while(currentNode -> getNext() != NULL) {
if(currentNode -> getNext() == listNode) {
deleteNode = currentNode -> getNext();
currentNode -> setNext(deleteNode -> getNext());
delete(deleteNode);
length--;
return true;
}
currentNode = currentNode -> getNext();
}
return false;
}
bool removeMatch(U data) {
ListNode<U> * currentNode = this -> getHead();
ListNode<U> * deleteNode;
if(currentNode == NULL) return false;
if(currentNode -> getData() == data) {
deleteNode = currentNode;
this -> setHead(deleteNode -> getNext());
delete(deleteNode);
length--;
return true;
}
while(currentNode -> getNext() != NULL) {
if(currentNode -> getNext() -> getData() == data) {
deleteNode = currentNode -> getNext();
currentNode -> setNext(deleteNode -> getNext());
delete(deleteNode);
length--;
return true;
}
currentNode = currentNode -> getNext();
}
return false;
}
string toString() {
string listString = "[";
ListNode<U> * currentNode = this -> getHead();
while(currentNode != NULL) {
listString = listString.append(to_string(currentNode -> getData()));
if(currentNode -> getNext() != NULL) {
listString = listString.append(", ");
}
currentNode = currentNode -> getNext();
}
listString = listString.append("]");
return listString;
}
};
int main(int argc, char const *argv[]) {
cout << "Hello World!" << endl;
LinkedList<int> * linkedList = new LinkedList<int>();
ListNode<int> * listNode = new ListNode<int>(25);
linkedList -> insertAtEnd(new ListNode<int>(1));
linkedList -> insertAtBeginning(new ListNode<int>(5));
linkedList -> insertAtEnd(listNode);
linkedList -> insertAtEnd(new ListNode<int>(2));
linkedList -> insertAtEnd(new ListNode<int>(11));
linkedList -> insertAtEnd(new ListNode<int>(15));
linkedList -> insertAtBeginning(new ListNode<int>(55));
linkedList -> insertAtBeginning(new ListNode<int>(21));
linkedList -> insertAtEnd(new ListNode<int>(65));
linkedList -> print();
linkedList -> insert(new ListNode<int>(32), 5);
linkedList -> print();
linkedList -> removeFromBegin();
linkedList -> print();
linkedList -> removeFromEnd();
linkedList -> print();
cout << linkedList -> getLast() -> getData() << endl;
linkedList -> remove(8);
linkedList -> print();
cout << linkedList -> toString() << endl;
return 0;
}
| [
"keyurrgolani@gmail.com"
] | keyurrgolani@gmail.com |
6f9051fa1aac50d919fb6991e636885dd6dbcb99 | e3da8e19e67b7d950e2afc5d3fe71eefea7968e6 | /CPP04/ex03/main.cpp | 157cea593cb6d6dbf31fc599d0f51cb8dfc42c19 | [] | no_license | Mazoise/42-CPP | 8f8a017c3dcf70db594a65a781be792090d46a42 | 7153476a51517273bd855596092c94b71ccc2f33 | refs/heads/master | 2023-03-17T20:32:58.406398 | 2021-03-11T17:56:20 | 2021-03-11T17:56:20 | 339,129,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,712 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mchardin <mchardin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/18 19:09:22 by mchardin #+# #+# */
/* Updated: 2021/02/18 22:50:17 by mchardin ### ########.fr */
/* */
/* ************************************************************************** */
#include "AMateria.hpp"
#include "Ice.hpp"
#include "Cure.hpp"
#include "Character.hpp"
#include "MateriaSource.hpp"
void asked_output()
{
IMateriaSource* src = new MateriaSource();
src->learnMateria(new Ice());
src->learnMateria(new Cure());
ICharacter* me = new Character("me");
AMateria* tmp;
tmp = src->createMateria("ice");
me->equip(tmp);
tmp = src->createMateria("cure");
me->equip(tmp);
ICharacter* bob = new Character("bob");
me->use(0, *bob);
me->use(1, *bob);
delete bob;
delete me;
delete src;
std::cout << std::endl;
}
void more_tests()
{
MateriaSource *src = new MateriaSource();
Character *me = new Character("me");
AMateria *tmp_hello = src->createMateria("hello");
AMateria *tmp_cure = new Cure();
AMateria *tmp_ice = new Ice();
src->learnMateria(new Ice());
src->learnMateria(new Cure());
src->learnMateria(tmp_hello);
src->learnMateria(new Cure());
src->learnMateria(new Cure());
src->learnMateria(tmp_cure);
for (int i = 0; i < 4; i++)
std::cout << "Src slot " << i << " : " << src->getSlots(i)->getType() << std::endl;
me->equip(tmp_cure);
me->equip(tmp_cure);
me->equip(tmp_cure);
me->equip(tmp_cure);
me->equip(new Ice());
me->equip(tmp_hello);
me->equip(new Cure());
me->equip(new Ice());
me->equip(tmp_ice);
for (int i = 0; i < 4; i++)
std::cout << "My slot " << i << " : " << me->getSlots(i)->getType() << std::endl;
me->use(1, *me);
std::cout << "My HP : " << me->getSlots(1)->getXP() << std::endl;
me->use(1, *me);
std::cout << "My HP : " << me->getSlots(1)->getXP() << std::endl;
me->use(1, *me);
std::cout << "My HP : " << me->getSlots(1)->getXP() << std::endl;
me->use(1, *me);
std::cout << "My HP : " << me->getSlots(1)->getXP() << std::endl;
delete tmp_ice;
delete me;
delete src;
}
int main()
{
asked_output();
more_tests();
}
| [
"mchardin@student.42.fr"
] | mchardin@student.42.fr |
50dbd3a2d6d3f09b94dc319ff424eba0f9401c39 | 4b12a93f4ad79a58ae90a8c43ab7f26d3444c19b | /a2/q3cardgame.cc | 73d3faa2e1d154fd07f7ecd58dabf20257049b4b | [] | no_license | sherlockwxl/cs343 | 372a55b809f11a809655b72d4b74e57f93e57b4d | acbbfa82dbc2cdcfc227ba9fca4faa54dc5fc7ca | refs/heads/master | 2020-04-20T03:28:24.377211 | 2019-03-25T22:03:16 | 2019-03-25T22:03:16 | 168,599,255 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,097 | cc |
#include "q3cardgame.h"
#include "PRNG.h"
using namespace std;
int DEATH_DECK_DIVISOR = 7;
extern PRNG *prng;
_Event Schmilblick{};
extern unsigned int Player::totalPlayersLeft;
//methods of printer
Printer::Printer(const unsigned int NoOfPlayers, const unsigned int NoOfCards):
NoOfPlayers(NoOfPlayers), NoOfCards(NoOfCards){
printheader();//print header each time printer is initialized
};
void Printer::flush() {
while(infoqueue.size() != 0){//keep pop the first element in infoqueue and print the element
PlayInfo *tempp = infoqueue.front();
PlayInfo temp = *tempp;
infoqueue.pop_front();
if(temp.cardTook == 0 && !temp.win){//check if empty info
if(!temp.drunk){//empty info
if(infoqueue.size() !=0){//only print tab if element is not last one in queue
cout<<"\t";
}
delete tempp;
continue;
}else{//drunk
cout<<"D";//print D when drunk
if(infoqueue.size() !=0){//only print tab if element is not last one in queue
cout<<"\t";
}
delete tempp;
continue;
}
}
if(temp.win){//if player won, only deal with win when only one player left to avoid duplicate code
if(temp.cardLeft != 0){//player win because no other players
cout<< "#"<<temp.cardLeft<<"#";
if(temp.dead){//handle death and win
cout<<"X";
}
if(infoqueue.size() !=0){
cout<<"\t";
}
delete tempp;
continue;
}
}
//normal output
cout<<temp.cardTook<<":"<<temp.cardLeft;
if(temp.win) {//either print # for win or print </> for direction.
cout << "#";
}else{
cout << (temp.passDirection == 1 ? ">" : "<");
}
if(temp.dead){
cout<<"X";
}
if(infoqueue.size() != 0){
cout<<"\t";
}
delete tempp;
}
cout<<endl;
}
void Printer::printheader() {
cout<<"Players: "<<NoOfPlayers<<" "<<"Cards: "<<NoOfCards<<endl;
for(unsigned int i = 0; i < NoOfPlayers; i++){
cout<<"P"<<i;
if(i != NoOfPlayers - 1){
cout<<'\t';
}
}
cout<<endl;
}
void Printer::prt(unsigned int id, int took, int RemainingPlayers) {
for(PlayInfo* p : infoqueue){//check if the new info will overwrite any of the existing one.
if(p != NULL){
if(p->id == id){
if(p->cardTook != 0){//check if the overwrite one is an empty one
flush();
break;
}
else if(p->cardTook == 0 && p->drunk){//check if the overwrite one is a drunk element
flush();
break;
}
}
}
}
//add new info
//first pad the vector with empty info
while(infoqueue.size() < id){
infoqueue.push_back(new PlayInfo(infoqueue.size(), 0, 0, 0, false, false, false));//MUST use heap to add
// new playinfo into the infoqueue
}
//udpate the existing playinfo
NoOfCards-= took;//update the number of cards
int tempdirection = NoOfCards % 2 == 0 ? 1 : -1; //decide the pass direction
bool isdead = (NoOfCards + took)%DEATH_DECK_DIVISOR == 0 ? true: false;//decide if dead
bool isdrunk = took == 0? true:false; //decide if drunk
bool iswin = (RemainingPlayers == 1 || NoOfCards == 0) ? true: false; //decide if win
if(id == infoqueue.size()){//if the current one should add to the end
PlayInfo *tempinfo = new PlayInfo(id, took, NoOfCards, tempdirection, isdead, isdrunk, iswin);
infoqueue.push_back(tempinfo);
}else{//update existing one
infoqueue[id]->cardTook = took;
infoqueue[id]->cardLeft = NoOfCards;
infoqueue[id]->passDirection = tempdirection;
infoqueue[id]->dead = isdead;
infoqueue[id]->drunk = isdrunk;
infoqueue[id]->win = iswin;
}
if(iswin){//when win flush the buffer
flush();
}
}
//private method of player
void Player::players(unsigned int num){
totalPlayersLeft = num;
}
Player::Player( Printer &printer, unsigned int id ):
id(id),printer(printer), leftplayer(NULL), rightplayer(NULL),deckReceived(0), drunk(false){};
void Player::start( Player &lp, Player &rp ){//link the left and right player
leftplayer = &lp;
rightplayer = &rp;
resume();
}
void Player::play( unsigned int deck ){//update the deck and resume
deckReceived = deck;
resume();
}
void Player::drink(){
resume();
}
void Player::main(){
suspend();//wait for player to be called
try{
_Enable{
for(;;){
if(totalPlayersLeft == 1){//only one left, win this game
printer.prt(id, 0, totalPlayersLeft);
return;
}
//random pick cards and can not more than deck player has
int takeCard = min(deckReceived, (*prng)(1,8));
printer.prt(id, takeCard, totalPlayersLeft);
int cardRemaining = deckReceived - takeCard;
if(cardRemaining == 0){//game end
return;
}
if(deckReceived % DEATH_DECK_DIVISOR == 0){//check if user should be removed from the game
totalPlayersLeft -= 1;
leftplayer->rightplayer = rightplayer; //remove the current player
rightplayer->leftplayer = leftplayer;
}
//alcohol test
if(deckReceived % DEATH_DECK_DIVISOR != 0){//only check when user was not removed
if((*prng)(9) == 0){
printer.prt(id, 0, totalPlayersLeft);
drunk = true;
_Resume Schmilblick() _At *rightplayer;//raise event to let right player know
rightplayer->drink();
}
}
//check pass direction
if(cardRemaining % 2 == 0){
rightplayer->play(cardRemaining);
}else{
leftplayer->play(cardRemaining);
}
}
}
}_CatchResume(Schmilblick& ){//when catch Schmilblick event
if(drunk){//reach start point
drunk = false;//change the boolean back to false
}else{//not the start point
printer.prt(id, 0, totalPlayersLeft);//prt drunk
_Resume Schmilblick() _At *rightplayer;//raise event to right
rightplayer->drink();//resume
}
}
catch(Schmilblick& ){
//do nothing
}
}
| [
"wuxiling@outlook.com"
] | wuxiling@outlook.com |
370c81e18b05b4ea09443f5c6c026f058592a309 | bf10971204ec8d864cd54a93dcb7a41b63cee6ac | /Creation_Crate_Mood_Lamp.ino | 023a9b71100210c84407823cbef798676d027c8e | [] | no_license | rmar72/cc_mood_lamp | 06bc494b5dae9b16559d330fac56334e6f0420cd | abd15330e0184bbe48e728cf3b859a09173bb2b0 | refs/heads/master | 2021-01-19T13:23:50.090776 | 2017-08-20T05:31:08 | 2017-08-20T05:31:08 | 100,840,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,168 | ino | /* Creation Crate Mood Lamp
This lamp smoothly cycles through a colour spectrum.
It only turns on when its surroundings are dark.
Colour equations (we’ll be using these later):
Red = sin(x)
Green = sin(x + PI/3)
Blue = sin(x + 2PI/3)
These equations are how the program will calculate the brightness of
the LEDs.
Step 1: Input User Defined Variables
Think of variables like containers - they’re used to store information. */
int pulseSpeed = 5;
// This value controls how fast the mood lamp runs. You can replace this with any whole number.
int ldrPin = 0; // LDR in Analog Input 0 to read the surrounding light.
int redLed = 11; // red LED in Digital Pin 11.
int greenLed = 10; // green LED in Digital Pin 10.
int blueLed = 9; // blue LED in DIgital Pin 9.
// These are the pins we are using with the UNO R3 (Arduino-compatible). You can see the numbers on the board itself.
int ambientLight;
// This variable stores the value of the light in the room.
int power = 230;
// This variable controls the brightness of the lamp (2-255).
float RGB[3];
// This is an ‘array’. It can hold 3 values: RGB[0], RGB[1], and RGB[2].We’ll use this to store the values of the Red, Blue, and Green LEDs.
float CommonMathVariable = 180/PI;
/* We will be using the value of 180/PI a lot in the main loop, so to
save time, we will calculate it once here in the setup and store it
in CommonMathVariable. Note: it is PI, not P1 */
/* Step 2: Create Setup Loop
This ‘loop’ is not really a loop. It runs once in the beginning to create
the default values for our LEDs. */
void setup () {
pinMode (redLed,OUTPUT);
pinMode (greenLed,OUTPUT);
pinMode (blueLed,OUTPUT);
// This tells the UNO R3 to send data out to the LEDs.
digitalWrite (redLed,LOW);
digitalWrite (greenLed,LOW);
digitalWrite (blueLed,LOW);
// This sets all the outputs (LEDs) to low (as in off), so that they do not turn on during startup.
} // Opening brackets must be accompanied by closing brackets.
/* Step 3: Create Main Loop
The previous sections are where we set up the variables. This section is
where we put them to work! This part of the program is a ‘loop’. It
repeats itself over and over again, making a small change in the
brightness of the LEDs each time - this creates a smooth transition in
colour. */
void loop () {
for (float x = 0; x < PI; x = x + 0.00001) {
RGB[0] = power * abs(sin(x * (CommonMathVariable))); // Red LED.
RGB[1] = power * abs(sin((x + PI/3) * (CommonMathVariable))); // Green LED.
RGB[2] = power * abs(sin((x + (2 * PI) / 3) * (CommonMathVariable))); // Blue LED.
ambientLight = analogRead(ldrPin);
// This reads the light in the room and stores it as a number.
if (ambientLight > 1600) {
// This ‘if statement’ will make the lamp turn on only if it is dark. The darker it is, the higher the number.
analogWrite (redLed,RGB[0]);
analogWrite (greenLed,RGB[1]);
analogWrite (blueLed,RGB[2]);
// These ‘analogWrite’ statements will send the values calculated above to the LEDs.
} // Don’t forget to close this ‘if statement’ with a bracket!
else {
digitalWrite (redLed,LOW);
digitalWrite (greenLed,LOW);
digitalWrite (blueLed,LOW);
}
// This ‘else statement’ will only activate if the ‘if statement’ above does not (ie. If it is too bright in the room). The LEDs will turn off.
for (int i = 0; i < 3; i++) {
// This loop calculates the delay for each colour depending on its current brightness. Brighter LEDs will change colour slower and vice versa.
if (RGB[i] < 1) {
delay (20 * pulseSpeed);
}
else if (RGB[i] < 5) {
delay (10 * pulseSpeed);
}
else if (RGB[i] < 10) {
delay (2 * pulseSpeed);
}
else if (RGB[i] < 100) {
delay (1 * pulseSpeed);
}
// ’else if’ means only one of these conditions can activate at a time.
else {}
// This blank ‘else statement’ is a fail-safe mechanism. It instructs the program to do nothing if the conditions above do not activate. This prevents the program from generating errors when calculating delays.
}
delay(1);
// This delay gives the light dependent resistor time to settle and give accurate readings.
}
} // Don’t forget to close with these brackets!
| [
"rsolm72@gmail.com"
] | rsolm72@gmail.com |
9f9e858397fbcfea99eb93bc0f9e8f724cdb7d8d | c7a586dacf38f5e1cfc9b9f50fed4a1b24244066 | /CodePractice/Main.cpp | 97a051f755d18f804966a7616ccc5bcb473cac64 | [] | no_license | kimdimu/CodePractice | 46b394cef8c1a108f72fd930f1fb4b09dfce0144 | 8f69a357168fd132f68dfa1464fc4a42e717704e | refs/heads/master | 2023-01-01T04:01:31.962802 | 2020-10-25T19:15:14 | 2020-10-25T19:15:14 | 307,156,425 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 715 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int dimu = 0;
int mumu = 0;
// 자 10분안에 만들어야해 구구단 9 x 9 몇단까지 출력할껀지 입력받아서 구구단을 출력하자//
// 숫자 입력받아서 3의배수이나 4의배수가 아닌걸 다 더해라.
//scanf("%d", &dimu);
//
//for (int i = 0; i < dimu; i++)
//{
// if ((dimu-i) % 3 == 0 && (dimu-i)%4 !=0)
// {
// mumu += dimu - i;
// }
//}
//printf("%d\n", mumu);
// *
// **
// ***
// ****
// *****
// 하나 찍고 줄바구기 하나찍고 하나찍고 줄바구기
for (int i = 1; i <= 5; i++)
{
for (int j = 0; j < i; j++)
{
printf("*");
}
printf("\n");
}
return 0;
} | [
"48170768+kimdimu@users.noreply.github.com"
] | 48170768+kimdimu@users.noreply.github.com |
21e41fb87f1d4b2642fb1c0258e0272d015560d9 | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/blink/renderer/platform/graphics/cpu/arm/webgl_image_conversion_neon.h | 1e1d1834bdd2b169c247ad81c592fe79fdbd5a64 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 12,002 | h | /*
* Copyright (C) 2012 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of
* Szeged
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``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 UNIVERSITY OF SZEGED 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 THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_CPU_ARM_WEBGL_IMAGE_CONVERSION_NEON_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_CPU_ARM_WEBGL_IMAGE_CONVERSION_NEON_H_
#if WTF_CPU_ARM_NEON
#include <arm_neon.h>
namespace blink {
namespace SIMD {
ALWAYS_INLINE void UnpackOneRowOfRGBA16LittleToRGBA8(const uint16_t*& source,
uint8_t*& destination,
unsigned& pixels_per_row) {
unsigned components_per_row = pixels_per_row * 4;
unsigned tail_components = components_per_row % 16;
unsigned components_size = components_per_row - tail_components;
const uint8_t* src = reinterpret_cast<const uint8_t*>(source);
for (unsigned i = 0; i < components_size; i += 16) {
uint8x16x2_t components = vld2q_u8(src + i * 2);
vst1q_u8(destination + i, components.val[1]);
}
source += components_size;
destination += components_size;
pixels_per_row = tail_components / 4;
}
ALWAYS_INLINE void UnpackOneRowOfRGB16LittleToRGBA8(const uint16_t*& source,
uint8_t*& destination,
unsigned& pixels_per_row) {
unsigned components_per_row = pixels_per_row * 3;
unsigned tail_components = components_per_row % 24;
unsigned components_size = components_per_row - tail_components;
uint8x8_t component_a = vdup_n_u8(0xFF);
for (unsigned i = 0; i < components_size; i += 24) {
uint16x8x3_t rgb16 = vld3q_u16(source + i);
uint8x8_t component_r = vqmovn_u16(vshrq_n_u16(rgb16.val[0], 8));
uint8x8_t component_g = vqmovn_u16(vshrq_n_u16(rgb16.val[1], 8));
uint8x8_t component_b = vqmovn_u16(vshrq_n_u16(rgb16.val[2], 8));
uint8x8x4_t rgba8 = {{component_r, component_g, component_b, component_a}};
vst4_u8(destination, rgba8);
destination += 32;
}
source += components_size;
pixels_per_row = tail_components / 3;
}
ALWAYS_INLINE void UnpackOneRowOfARGB16LittleToRGBA8(const uint16_t*& source,
uint8_t*& destination,
unsigned& pixels_per_row) {
unsigned components_per_row = pixels_per_row * 4;
unsigned tail_components = components_per_row % 32;
unsigned components_size = components_per_row - tail_components;
for (unsigned i = 0; i < components_size; i += 32) {
uint16x8x4_t argb16 = vld4q_u16(source + i);
uint8x8_t component_a = vqmovn_u16(vshrq_n_u16(argb16.val[0], 8));
uint8x8_t component_r = vqmovn_u16(vshrq_n_u16(argb16.val[1], 8));
uint8x8_t component_g = vqmovn_u16(vshrq_n_u16(argb16.val[2], 8));
uint8x8_t component_b = vqmovn_u16(vshrq_n_u16(argb16.val[3], 8));
uint8x8x4_t rgba8 = {{component_r, component_g, component_b, component_a}};
vst4_u8(destination + i, rgba8);
}
source += components_size;
destination += components_size;
pixels_per_row = tail_components / 4;
}
ALWAYS_INLINE void UnpackOneRowOfBGRA16LittleToRGBA8(const uint16_t*& source,
uint8_t*& destination,
unsigned& pixels_per_row) {
unsigned components_per_row = pixels_per_row * 4;
unsigned tail_components = components_per_row % 32;
unsigned components_size = components_per_row - tail_components;
for (unsigned i = 0; i < components_size; i += 32) {
uint16x8x4_t argb16 = vld4q_u16(source + i);
uint8x8_t component_b = vqmovn_u16(vshrq_n_u16(argb16.val[0], 8));
uint8x8_t component_g = vqmovn_u16(vshrq_n_u16(argb16.val[1], 8));
uint8x8_t component_r = vqmovn_u16(vshrq_n_u16(argb16.val[2], 8));
uint8x8_t component_a = vqmovn_u16(vshrq_n_u16(argb16.val[3], 8));
uint8x8x4_t rgba8 = {{component_r, component_g, component_b, component_a}};
vst4_u8(destination + i, rgba8);
}
source += components_size;
destination += components_size;
pixels_per_row = tail_components / 4;
}
ALWAYS_INLINE void UnpackOneRowOfRGBA4444ToRGBA8(const uint16_t*& source,
uint8_t*& destination,
unsigned& pixels_per_row) {
unsigned tail_pixels = pixels_per_row % 8;
unsigned pixel_size = pixels_per_row - tail_pixels;
uint16x8_t immediate0x0f = vdupq_n_u16(0x0F);
for (unsigned i = 0; i < pixel_size; i += 8) {
uint16x8_t eight_pixels = vld1q_u16(source + i);
uint8x8_t component_r = vqmovn_u16(vshrq_n_u16(eight_pixels, 12));
uint8x8_t component_g =
vqmovn_u16(vandq_u16(vshrq_n_u16(eight_pixels, 8), immediate0x0f));
uint8x8_t component_b =
vqmovn_u16(vandq_u16(vshrq_n_u16(eight_pixels, 4), immediate0x0f));
uint8x8_t component_a = vqmovn_u16(vandq_u16(eight_pixels, immediate0x0f));
component_r = vorr_u8(vshl_n_u8(component_r, 4), component_r);
component_g = vorr_u8(vshl_n_u8(component_g, 4), component_g);
component_b = vorr_u8(vshl_n_u8(component_b, 4), component_b);
component_a = vorr_u8(vshl_n_u8(component_a, 4), component_a);
uint8x8x4_t dest_components = {
{component_r, component_g, component_b, component_a}};
vst4_u8(destination, dest_components);
destination += 32;
}
source += pixel_size;
pixels_per_row = tail_pixels;
}
ALWAYS_INLINE void PackOneRowOfRGBA8ToUnsignedShort4444(
const uint8_t*& source,
uint16_t*& destination,
unsigned& pixels_per_row) {
unsigned components_per_row = pixels_per_row * 4;
unsigned tail_components = components_per_row % 32;
unsigned components_size = components_per_row - tail_components;
uint8_t* dst = reinterpret_cast<uint8_t*>(destination);
uint8x8_t immediate0xf0 = vdup_n_u8(0xF0);
for (unsigned i = 0; i < components_size; i += 32) {
uint8x8x4_t rgba8 = vld4_u8(source + i);
uint8x8_t component_r = vand_u8(rgba8.val[0], immediate0xf0);
uint8x8_t component_g = vshr_n_u8(vand_u8(rgba8.val[1], immediate0xf0), 4);
uint8x8_t component_b = vand_u8(rgba8.val[2], immediate0xf0);
uint8x8_t component_a = vshr_n_u8(vand_u8(rgba8.val[3], immediate0xf0), 4);
uint8x8x2_t rgba4;
rgba4.val[0] = vorr_u8(component_b, component_a);
rgba4.val[1] = vorr_u8(component_r, component_g);
vst2_u8(dst, rgba4);
dst += 16;
}
source += components_size;
destination += components_size / 4;
pixels_per_row = tail_components / 4;
}
ALWAYS_INLINE void UnpackOneRowOfRGBA5551ToRGBA8(const uint16_t*& source,
uint8_t*& destination,
unsigned& pixels_per_row) {
unsigned tail_pixels = pixels_per_row % 8;
unsigned pixel_size = pixels_per_row - tail_pixels;
uint8x8_t immediate0x7 = vdup_n_u8(0x7);
uint8x8_t immediate0xff = vdup_n_u8(0xFF);
uint16x8_t immediate0x1f = vdupq_n_u16(0x1F);
uint16x8_t immediate0x1 = vdupq_n_u16(0x1);
for (unsigned i = 0; i < pixel_size; i += 8) {
uint16x8_t eight_pixels = vld1q_u16(source + i);
uint8x8_t component_r = vqmovn_u16(vshrq_n_u16(eight_pixels, 11));
uint8x8_t component_g =
vqmovn_u16(vandq_u16(vshrq_n_u16(eight_pixels, 6), immediate0x1f));
uint8x8_t component_b =
vqmovn_u16(vandq_u16(vshrq_n_u16(eight_pixels, 1), immediate0x1f));
uint8x8_t component_a = vqmovn_u16(vandq_u16(eight_pixels, immediate0x1));
component_r =
vorr_u8(vshl_n_u8(component_r, 3), vand_u8(component_r, immediate0x7));
component_g =
vorr_u8(vshl_n_u8(component_g, 3), vand_u8(component_g, immediate0x7));
component_b =
vorr_u8(vshl_n_u8(component_b, 3), vand_u8(component_b, immediate0x7));
component_a = vmul_u8(component_a, immediate0xff);
uint8x8x4_t dest_components = {
{component_r, component_g, component_b, component_a}};
vst4_u8(destination, dest_components);
destination += 32;
}
source += pixel_size;
pixels_per_row = tail_pixels;
}
ALWAYS_INLINE void PackOneRowOfRGBA8ToUnsignedShort5551(
const uint8_t*& source,
uint16_t*& destination,
unsigned& pixels_per_row) {
unsigned components_per_row = pixels_per_row * 4;
unsigned tail_components = components_per_row % 32;
unsigned components_size = components_per_row - tail_components;
uint8_t* dst = reinterpret_cast<uint8_t*>(destination);
uint8x8_t immediate0xf8 = vdup_n_u8(0xF8);
uint8x8_t immediate0x18 = vdup_n_u8(0x18);
for (unsigned i = 0; i < components_size; i += 32) {
uint8x8x4_t rgba8 = vld4_u8(source + i);
uint8x8_t component_r = vand_u8(rgba8.val[0], immediate0xf8);
uint8x8_t component_g3bit = vshr_n_u8(rgba8.val[1], 5);
uint8x8_t component_g2bit =
vshl_n_u8(vand_u8(rgba8.val[1], immediate0x18), 3);
uint8x8_t component_b = vshr_n_u8(vand_u8(rgba8.val[2], immediate0xf8), 2);
uint8x8_t component_a = vshr_n_u8(rgba8.val[3], 7);
uint8x8x2_t rgba5551;
rgba5551.val[0] =
vorr_u8(vorr_u8(component_g2bit, component_b), component_a);
rgba5551.val[1] = vorr_u8(component_r, component_g3bit);
vst2_u8(dst, rgba5551);
dst += 16;
}
source += components_size;
destination += components_size / 4;
pixels_per_row = tail_components / 4;
}
ALWAYS_INLINE void PackOneRowOfRGBA8ToUnsignedShort565(
const uint8_t*& source,
uint16_t*& destination,
unsigned& pixels_per_row) {
unsigned components_per_row = pixels_per_row * 4;
unsigned tail_components = components_per_row % 32;
unsigned components_size = components_per_row - tail_components;
uint8_t* dst = reinterpret_cast<uint8_t*>(destination);
uint8x8_t immediate0xf8 = vdup_n_u8(0xF8);
uint8x8_t immediate0x1c = vdup_n_u8(0x1C);
for (unsigned i = 0; i < components_size; i += 32) {
uint8x8x4_t rgba8 = vld4_u8(source + i);
uint8x8_t component_r = vand_u8(rgba8.val[0], immediate0xf8);
uint8x8_t component_g_left = vshr_n_u8(rgba8.val[1], 5);
uint8x8_t component_g_right =
vshl_n_u8(vand_u8(rgba8.val[1], immediate0x1c), 3);
uint8x8_t component_b = vshr_n_u8(vand_u8(rgba8.val[2], immediate0xf8), 3);
uint8x8x2_t rgb565;
rgb565.val[0] = vorr_u8(component_g_right, component_b);
rgb565.val[1] = vorr_u8(component_r, component_g_left);
vst2_u8(dst, rgb565);
dst += 16;
}
source += components_size;
destination += components_size / 4;
pixels_per_row = tail_components / 4;
}
} // namespace SIMD
} // namespace blink
#endif // WTF_CPU_ARM_NEON
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_CPU_ARM_WEBGL_IMAGE_CONVERSION_NEON_H_
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
50f178ea4382a75a7d4a020338bbb501e41e26fc | 79882e9193621a73808c50aa7c2948f9ff7485e5 | /include/cudarrays/detail/utils/env.hpp | 25bc25bb6c76ea0fbd39be2c9b45a19adfce6dc1 | [
"MIT"
] | permissive | cudarrays/cudarrays | 2e28c717c74e56d280fa30910260824c99a809dd | cc4fb82da381b548e1fd3501b8fc6d1c07c8be37 | refs/heads/master | 2020-05-09T16:15:34.716528 | 2016-11-27T07:26:44 | 2016-11-27T07:26:44 | 33,399,232 | 29 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,664 | hpp | /*
* CUDArrays is a library for easy multi-GPU program development.
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2015 Barcelona Supercomputing Center and
* University of Illinois
*
* Developed by: Javier Cabezas <javier.cabezas@gmail.com>
*
* 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
#ifndef CUDARRAYS_DETAIL_UTILS_ENV_HPP_
#define CUDARRAYS_DETAIL_UTILS_ENV_HPP_
#include <cstdlib>
#include <string>
#include <algorithm>
#include <iostream>
namespace detail {
namespace utils {
template <typename T>
class string_to {
public:
static bool convert(std::string name, T &val)
{
val = T(name);
return true;
}
};
template <>
class string_to<bool> {
public:
static bool convert(std::string name, bool &val)
{
std::string tmp = name;
std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);
if (tmp == "y" || tmp == "yes") {
val = true;
return true;
}
if (tmp == "n" || tmp == "no") {
val= false;
return true;
}
long int _val = std::strtol(name.c_str(), NULL, 10);
val = _val != 0;
return true;
}
};
template <>
class string_to<int> {
public:
static bool convert(std::string name, int &val)
{
val = std::strtol(name.c_str(), NULL, 10);
return true;
}
};
template <>
class string_to<unsigned> {
public:
static bool convert(std::string name, unsigned &val)
{
val = std::strtol(name.c_str(), NULL, 10);
return true;
}
};
template <>
class string_to<long int> {
public:
static bool convert(std::string name, long int &val)
{
val = std::strtol(name.c_str(), NULL, 10);
return true;
}
};
template <>
class string_to<long unsigned> {
public:
static bool convert(std::string name, long unsigned &val)
{
val = std::strtoul(name.c_str(), NULL, 10);
return true;
}
};
template <>
class string_to<float> {
public:
static bool convert(std::string name, float &val)
{
val = std::strtof(name.c_str(), NULL);
return true;
}
};
}
}
namespace utils {
template <typename T1>
static T1 getenv(const std::string &name, T1 default_value)
{
char *val = ::getenv(name.c_str());
if (val == NULL) {
return default_value;
}
T1 out;
bool ok = ::detail::utils::string_to<T1>::convert(val, out);
if (ok) return out;
else return T1(0);
}
}
#endif
/* vim:set ft=cpp backspace=2 tabstop=4 shiftwidth=4 textwidth=120 foldmethod=marker expandtab: */
| [
"javier.cabezas@bsc.es"
] | javier.cabezas@bsc.es |
339ade605843eab42a4d6e31867b9f5b9f090122 | 6ce049ad0073d7d5e14efde081c94d9432a15d35 | /SuaMae/contests/Acampinas2016/S01/E02/B/B.cpp | 484f2864f074a37eaba3d8097e545072ffb76009 | [] | no_license | yancouto/maratona-sua-mae | 0f1377c2902375dc3157e6895624e198f52151e0 | 75f5788f981b3baeb6488bbf3483062fa355c394 | refs/heads/master | 2020-05-31T03:26:21.233601 | 2016-08-19T03:28:22 | 2016-08-19T03:28:37 | 38,175,020 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | cpp |
#include <bits/stdc++.h>
using namespace std;
#define fst first
#define snd second
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
#define pb push_back
#define for_tests(t, tt) int t; scanf("%d", &t); for(int tt = 1; tt <= t; tt++)
template<typename T> inline T abs(T t) { return t < 0? -t : t; }
const ll modn = 1000000007;
inline ll mod(ll x) { return x % modn; }
#define xx first
#define yy second.first
#define ori second.second
#define mp make_pair
int n, res;
const int N = 3009;
set < pair<int, pair<int,int> > > xord, yord;
char z[N]; int L[N], D[N], R[N], U[N], Lb[N], Rb[N], Ub[N], Db[N];
vector < pair<int, pair<int,int> > > s;
int dist;
void go(int i){
dist++;
res = max(res,dist);
int l = L[i], r = R[i], u = U[i], d = D[i];
if(l != -1) R[l] = r;
if(r != -1) L[r] = l;
if(u != -1) D[u] = d;
if(d != -1) U[d] = u;
if(z[i] == '^' || z[i] == 'v'){
if(z[i] == '^'){
if(u != -1) go(u);
}
else if(d != -1) go(d);
}
else{
if(z[i] == '<'){
if(l != -1) go(l);
}
else if(r != -1) go(r);
}
}
int main (){
scanf("%d", &n);
for(int a=0;a<n;a++){
int x, y;
scanf("%d %d %c", &x, &y, &z[a]);
xord.insert(mp(x,mp(y,a)));
yord.insert(mp(y,mp(x,a)));
s.pb(mp(x,mp(y,a)));
}
for(int i = 0; i < n; i++) {
L[i] = R[i] = U[i] = D[i] = -1;
auto it = xord.find(s[i]);
if(it != xord.begin() && prev(it)->xx == s[i].xx) U[i] = prev(it)->ori;
if(next(it) != xord.end() && next(it)->xx == s[i].xx) D[i] = next(it)->ori;
it = yord.find(mp(s[i].yy, mp(s[i].xx, i)));
if(it != yord.begin() && prev(it)->xx == s[i].yy) L[i] = prev(it)->ori;
if(next(it) != yord.end() && next(it)->xx == s[i].yy) R[i] = next(it)->ori;
Lb[i] = L[i];
Rb[i] = R[i];
Ub[i] = U[i];
Db[i] = D[i];
}
xord.clear(); yord.clear();
for(int a=0;a<n;a++){
dist = 0;
go(a);
for(int b=0;b<n;b++){
L[b] = Lb[b]; R[b] = Rb[b];
U[b] = Ub[b]; D[b] = Db[b];
}
}
printf("%d\n", res);
}
| [
"obi31@felix.lab.ic.unicamp.br"
] | obi31@felix.lab.ic.unicamp.br |
92be8f2e87b6d09530ed6e5e57a226a99baa239b | a5a7c59b04a1a64fe34653c7970c3cf173f9c1df | /externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_getrf_getrs.cc | 51f38a58ce41a1f7180cf6163d3c432390dc7985 | [
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | siconos/siconos | a7afdba41a2bc1192ad8dcd93ac7266fa281f4cf | 82a8d1338bfc1be0d36b5e8a9f40c1ad5384a641 | refs/heads/master | 2023-08-21T22:22:55.625941 | 2023-07-17T13:07:32 | 2023-07-17T13:07:32 | 37,709,357 | 166 | 33 | Apache-2.0 | 2023-07-17T12:31:16 | 2015-06-19T07:55:53 | C | UTF-8 | C++ | false | false | 2,195 | cc |
// solving A * X = B
// in two steps -- factor (getrf()) and solve (getrs())
//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING
#include <cstddef>
#include <iostream>
#include <boost/numeric/bindings/blas.hpp>
#include <boost/numeric/bindings/lapack/computational/getrf.hpp>
#include <boost/numeric/bindings/lapack/computational/getrs.hpp>
#include <boost/numeric/bindings/ublas/matrix.hpp>
#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>
#include <boost/numeric/bindings/std/vector.hpp>
#include "utils.h"
namespace ublas = boost::numeric::ublas;
namespace blas = boost::numeric::bindings::blas;
namespace lapack = boost::numeric::bindings::lapack;
using std::size_t;
using std::cout;
using std::endl;
#ifndef F_ROW_MAJOR
typedef ublas::matrix<double, ublas::column_major> m_t;
#else
typedef ublas::matrix<double, ublas::row_major> m_t;
#endif
int main() {
cout << endl;
size_t n = 5;
m_t a (n, n); // system matrix
size_t nrhs = 2;
m_t x (n, nrhs);
// b -- right-hand side matrix:
// .. see leading comments for `gesv()' in clapack.hpp
#ifndef F_ROW_MAJOR
m_t b (n, nrhs);
#else
m_t b (nrhs, n);
#endif
init_symm (a);
// [n n-1 n-2 ... 1]
// [n-1 n n-1 ... 2]
// a = [n-2 n-1 n ... 3]
// [ ... ]
// [1 2 ... n-1 n]
ublas::matrix_row<m_t> ar1 (a, 0), ar3 (a, 3);
swap (ar1, ar3); // swap rows to force pivoting
ublas::matrix_column<m_t> xc0 (x, 0), xc1 (x, 1);
blas::set (1., xc0); // x[.,0] = 1
blas::set (2., xc1); // x[.,1] = 2
#ifndef F_ROW_MAJOR
blas::gemm ( 1.0, a, x, 0.0, b); // b = a x, so we know the result ;o)
#else
// see leading comments for `gesv()' in clapack.hpp
ublas::matrix_row<m_t> br0 (b, 0), br1 (b, 1);
blas::gemv (a, xc0, br0); // b[0,.] = a x[.,0]
blas::gemv (a, xc1, br1); // b[1,.] = a x[.,1] => b^T = a x
#endif
print_m (a, "A");
cout << endl;
print_m (b, "B");
cout << endl;
std::vector<int> ipiv (n); // pivot vector
lapack::getrf (a, ipiv); // factor a
lapack::getrs (a, ipiv, b); // solve from factorization
print_m (b, "X");
cout << endl;
print_v (ipiv, "pivots");
cout << endl;
}
| [
"franck.perignon@imag.fr"
] | franck.perignon@imag.fr |
7275ea58d6ea55e588a48467e2ac587497cead92 | f85f1cd1a7bde5d15a7cfe09e78295b04f55e7fa | /lef/clef/xlefiArray.cpp | e9587d06161f6c2ff03c690f6910b9400d29aa00 | [
"Apache-2.0"
] | permissive | kammoh/lefdef | 4a2bb5583b42219ea584c6065deb0ea22fccabcd | 1602f8b3ed81bdc84720d68430140aa4cfb465ed | refs/heads/main | 2023-07-24T00:13:37.140797 | 2021-09-13T19:47:24 | 2021-09-13T19:47:24 | 406,110,365 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,300 | cpp | // *****************************************************************************
// *****************************************************************************
// ATTENTION: THIS IS AN AUTO-GENERATED FILE. DO NOT CHANGE IT!
// *****************************************************************************
// *****************************************************************************
// Copyright 2012, Cadence Design Systems
//
// This file is part of the Cadence LEF/DEF Open Source
// Distribution, Product Version 5.8.
//
// 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 updates, support, or to become part of the LEF/DEF Community,
// check www.openeda.org for details.
//
// $Author: dell $
// $Revision: #1 $
// $Date: 2020/09/29 $
// $State: $
// *****************************************************************************
// *****************************************************************************
#define EXTERN extern "C"
#include "lefiArray.h"
#include "lefiArray.hpp"
// Wrappers definitions.
int lefiArrayFloorPlan_numPatterns (const ::lefiArrayFloorPlan* obj) {
return ((LefDefParser::lefiArrayFloorPlan*)obj)->numPatterns();
}
const ::lefiSitePattern* lefiArrayFloorPlan_pattern (const ::lefiArrayFloorPlan* obj, int index) {
return (const ::lefiSitePattern*) ((LefDefParser::lefiArrayFloorPlan*)obj)->pattern(index);
}
char* lefiArrayFloorPlan_typ (const ::lefiArrayFloorPlan* obj, int index) {
return ((LefDefParser::lefiArrayFloorPlan*)obj)->typ(index);
}
const char* lefiArrayFloorPlan_name (const ::lefiArrayFloorPlan* obj) {
return ((const LefDefParser::lefiArrayFloorPlan*)obj)->name();
}
int lefiArray_numSitePattern (const ::lefiArray* obj) {
return ((LefDefParser::lefiArray*)obj)->numSitePattern();
}
int lefiArray_numCanPlace (const ::lefiArray* obj) {
return ((LefDefParser::lefiArray*)obj)->numCanPlace();
}
int lefiArray_numCannotOccupy (const ::lefiArray* obj) {
return ((LefDefParser::lefiArray*)obj)->numCannotOccupy();
}
int lefiArray_numTrack (const ::lefiArray* obj) {
return ((LefDefParser::lefiArray*)obj)->numTrack();
}
int lefiArray_numGcell (const ::lefiArray* obj) {
return ((LefDefParser::lefiArray*)obj)->numGcell();
}
int lefiArray_hasDefaultCap (const ::lefiArray* obj) {
return ((LefDefParser::lefiArray*)obj)->hasDefaultCap();
}
const char* lefiArray_name (const ::lefiArray* obj) {
return ((const LefDefParser::lefiArray*)obj)->name();
}
const ::lefiSitePattern* lefiArray_sitePattern (const ::lefiArray* obj, int index) {
return (const ::lefiSitePattern*) ((LefDefParser::lefiArray*)obj)->sitePattern(index);
}
const ::lefiSitePattern* lefiArray_canPlace (const ::lefiArray* obj, int index) {
return (const ::lefiSitePattern*) ((LefDefParser::lefiArray*)obj)->canPlace(index);
}
const ::lefiSitePattern* lefiArray_cannotOccupy (const ::lefiArray* obj, int index) {
return (const ::lefiSitePattern*) ((LefDefParser::lefiArray*)obj)->cannotOccupy(index);
}
const ::lefiTrackPattern* lefiArray_track (const ::lefiArray* obj, int index) {
return (const ::lefiTrackPattern*) ((LefDefParser::lefiArray*)obj)->track(index);
}
const ::lefiGcellPattern* lefiArray_gcell (const ::lefiArray* obj, int index) {
return (const ::lefiGcellPattern*) ((LefDefParser::lefiArray*)obj)->gcell(index);
}
int lefiArray_tableSize (const ::lefiArray* obj) {
return ((LefDefParser::lefiArray*)obj)->tableSize();
}
int lefiArray_numDefaultCaps (const ::lefiArray* obj) {
return ((LefDefParser::lefiArray*)obj)->numDefaultCaps();
}
int lefiArray_defaultCapMinPins (const ::lefiArray* obj, int index) {
return ((LefDefParser::lefiArray*)obj)->defaultCapMinPins(index);
}
double lefiArray_defaultCap (const ::lefiArray* obj, int index) {
return ((LefDefParser::lefiArray*)obj)->defaultCap(index);
}
int lefiArray_numFloorPlans (const ::lefiArray* obj) {
return ((LefDefParser::lefiArray*)obj)->numFloorPlans();
}
const char* lefiArray_floorPlanName (const ::lefiArray* obj, int index) {
return ((const LefDefParser::lefiArray*)obj)->floorPlanName(index);
}
int lefiArray_numSites (const ::lefiArray* obj, int index) {
return ((LefDefParser::lefiArray*)obj)->numSites(index);
}
const char* lefiArray_siteType (const ::lefiArray* obj, int floorIndex, int siteIndex) {
return ((const LefDefParser::lefiArray*)obj)->siteType(floorIndex, siteIndex);
}
const ::lefiSitePattern* lefiArray_site (const ::lefiArray* obj, int floorIndex, int siteIndex) {
return (const ::lefiSitePattern*) ((LefDefParser::lefiArray*)obj)->site(floorIndex, siteIndex);
}
void lefiArray_print (const ::lefiArray* obj, FILE* f) {
((LefDefParser::lefiArray*)obj)->print(f);
}
| [
"kammoh@gmail.com"
] | kammoh@gmail.com |
eea8073deff9e2980dfec64b69dd381ee1b2dfab | 54e0ffd2fc7a58dd37966d9ac6ab57860e3bc1ac | /recv/vicente/src/XJBrowser/TreeListCtrl.h | bb34d18f91dd6754feea4199b12cb7d3411aeb7c | [] | no_license | xjsh2017/vicente2018 | 4fef21671771ea55c96f617cf31cfedefca72495 | 414de9d7558c03a8666fc23d7dc080be738e21de | refs/heads/master | 2020-03-23T16:37:45.389992 | 2018-08-28T00:09:37 | 2018-08-28T00:09:37 | 141,820,732 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 26,244 | h | /////////////////////////////////////////////////////////////////////////////
// CTreeListCtrl : Main control class drived from CWnd class
// Writter : TigerX
// Email : idemail@yahoo.com
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_TREELISTCTRL_H__55B6E4E9_1E57_4FEE_AA05_77C052ACE9B5__INCLUDED_)
#define AFX_TREELISTCTRL_H__55B6E4E9_1E57_4FEE_AA05_77C052ACE9B5__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// TreeListCtrl.h : header file
/////////////////////////////////////////////////////////////////////////////
// CTreeListCtrl window
#define TREELISTCTRL_CLASSNAME _T("TurboDLL.TreeListCtrl")
// TreeListCtrl Styles
#define TLC_TREELIST 0x00000001 // TreeList or List
#define TLC_BKGNDIMAGE 0x00000002 // image background
#define TLC_BKGNDCOLOR 0x00000004 // colored background ( not client area )
#define TLC_DOUBLECOLOR 0x00000008 // double color background
#define TLC_MULTIPLESELECT 0x00000010 // single or multiple select
#define TLC_SHOWSELACTIVE 0x00000020 // show active column of selected item
#define TLC_SHOWSELALWAYS 0x00000040 // show selected item always
#define TLC_SHOWSELFULLROWS 0x00000080 // show selected item in fullrow mode
#define TLC_HEADER 0x00000100 // show header
#define TLC_HGRID 0x00000200 // show horizonal grid lines
#define TLC_VGRID 0x00000400 // show vertical grid lines
#define TLC_TGRID 0x00000800 // show tree horizonal grid lines ( when HGRID & VGRID )
#define TLC_HGRID_EXT 0x00001000 // show extention horizonal grid lines
#define TLC_VGRID_EXT 0x00002000 // show extention vertical grid lines
#define TLC_HGRID_FULL 0x00004000 // show full horizonal grid lines
#define TLC_READONLY 0x00008000 // read only
#define TLC_TREELINE 0x00010000 // show tree line
#define TLC_ROOTLINE 0x00020000 // show root line
#define TLC_BUTTON 0x00040000 // show expand/collapse button [+]
#define TLC_CHECKBOX 0x00080000 // show check box
#define TLC_LOCKBOX 0x00100000 // show lock box
#define TLC_IMAGE 0x00200000 // show image
#define TLC_HOTTRACK 0x00400000 // show hover text
#define TLC_DRAG 0x01000000 // drag support
#define TLC_DROP 0x02000000 // drop support
#define TLC_DROPTHIS 0x04000000 // drop on this support
#define TLC_DROPROOT 0x08000000 // drop on root support
#define TLC_HEADDRAGDROP 0x10000000 // head drag drop
#define TLC_HEADFULLDRAG 0x20000000 // head full drag
#define TLC_NOAUTOCHECK 0x40000000 // do NOT auto set checkbox of parent & child
#define TLC_NOAUTOLOCK 0x80000000 // do NOT auto set lockbox of parent & child
// TreeListCtrl State
#define TLS_SUBCLASSFROMCREATE 0x00000001 // subclass when creating
#define TLS_OFFSCREENBUFFER 0x00000002 // use off screen buffer
#define TLS_FOCUS 0x00000004 // focus
#define TLS_CAPTURE 0x00000008 // capture
#define TLS_MODIFY 0x00000010 // modify
#define TLS_MODIFYING 0x00000020 // ending modify
#define TLS_DRAG 0x00000040 // drag
// TreeListItem Consts
#define TLI_ROOT (CTreeListItem*)0xFFFF0001 // root item
#define TLI_LAST (CTreeListItem*)0xFFFF0002 // last child item
#define TLI_FIRST (CTreeListItem*)0xFFFF0003 // first child item
#define TLI_SORT (CTreeListItem*)0xFFFF0004 // sort item
// TreeListCtrl TreeLine Formats
#define TLL_TOP 0x0001 // top line
#define TLL_LEFT 0x0002 // left line
#define TLL_RIGHT 0x0004 // right line
#define TLL_BOTTOM 0x0008 // bottom line
// TreeListCtrl TreeButton Formats
#define TLB_PLUS 0x0001 // plus button
#define TLB_MINUS 0x0002 // minus button
#define TLB_UNKNOW 0x0004 // unknow button
// TreeListCtrl HitTest Position
#define TLHT_ONITEMSPACE 0x0001 // on space
#define TLHT_ONITEMBUTTON 0x0002 // on button
#define TLHT_ONITEMCHECKBOX 0x0004 // on checkbox
#define TLHT_ONITEMLOCKBOX 0x0008 // on lockbox
#define TLHT_ONITEMIMAGE 0x0010 // on icon
#define TLHT_ONITEMTEXT 0x0020 // on item text
#define TLHT_ONITEM ( TLHT_ONITEMSPACE | TLHT_ONITEMBUTTON | TLHT_ONITEMCHECKBOX | TLHT_ONITEMLOCKBOX | TLHT_ONITEMIMAGE | TLHT_ONITEMTEXT )
// TreeListCtrl Given Consts
#define TLGN_ROOT 0x0000
#define TLGN_NEXT 0x0001
#define TLGN_PREVIOUS 0x0002
#define TLGN_PARENT 0x0003
#define TLGN_CHILD 0x0004
#define TLGN_FIRSTVISIBLE 0x0005
#define TLGN_NEXTVISIBLE 0x0006
#define TLGN_PREVIOUSVISIBLE 0x0007
#define TLGN_DROPHILITE 0x0008
#define TLGN_CARET 0x0009
#define TLGN_NEXTSELECT 0x000A
// TreeListCtrl Next Item Consts
#define TLNI_ABOVE 0x0100 // find next item form down to up
#define TLNI_BELOW 0x0200 // find next item form up to down
// TreeListCtrl SetColumnWidth Consts
#define TLSCW_AUTOSIZE -1 // autosize column width by item width
#define TLSCW_AUTOSIZE_USEHEADER -2 // autosize column width by item width and header width
#define TLSCW_AUTOSIZEV -3 // autosize column width by visible item width
#define TLSCW_AUTOSIZEV_USEHEADER -4 // autosize column width by visible item width and header width
// TreeListCtrl Message
#define TLN_SELCHANGING TVN_SELCHANGING // selecting a new item
#define TLN_SELCHANGED TVN_SELCHANGED // selected an item
#define TLN_GETDISPINFO TVN_GETDISPINFO
#define TLN_SETDISPINFO TVN_SETDISPINFO
#define TLN_ITEMEXPANDING TVN_ITEMEXPANDING // expanding an item
#define TLN_ITEMEXPANDED TVN_ITEMEXPANDED // an item was expanded
#define TLN_BEGINDRAG TVN_BEGINDRAG
#define TLN_BEGINRDRAG TVN_BEGINRDRAG
#define TLN_DELETEITEM TVN_DELETEITEM // delete an item
#define TLN_BEGINCONTROL TVN_BEGINLABELEDIT // entry a build in control
#define TLN_ENDCONTROL TVN_ENDLABELEDIT // leave a build in control
#define TLN_ITEMUPDATING (TVN_FIRST-20) // while a column of an item updating
#define TLN_ITEMUPDATED (TVN_FIRST-21) // after a column of an item updated
#define TLN_ITEMFINISHED (TVN_FIRST-22) // after all columns of an item updated
#define TLN_DRAGENTER (TVN_FIRST-23) // drag enter the control
#define TLN_DRAGLEAVE (TVN_FIRST-24) // drag leave the control
#define TLN_DRAGOVER (TVN_FIRST-25) // drag over the control
#define TLN_DROP (TVN_FIRST-26) // drop on the control
#define TLN_ITEMCHECK (TVN_FIRST-27) // check or uncheck an item
#define TLN_ITEMLOCK (TVN_FIRST-28) // lock or unlock an item
#define TLN_ITEMIMAGE (TVN_FIRST-29) // image or unimage an item
// TreeListItem Expand Consts
#define TLE_EXPAND 0 // expand the item
#define TLE_COLLAPSE 1 // collapse the item
#define TLE_TOGGLE 2 // toggle between expand & collapse
#define TLE_COLLAPSERESET 3 // collapse the item then reset it
// TreeListCtrl Consts
#define TLL_HEIGHT 16 // default height of the item
#define TLL_WIDTH 16 // default width of the item
#define TLL_BORDER 2 // border width of the item
#define TLL_BUTTON 4 // button width (half)
#define DROP_NONE 0 // drop on nothing
#define DROP_SELF 1 // drop on drag item or it's child
#define DROP_ITEM 2 // drop on item
#define DROP_ROOT 3 // drop on root
// Draw Consts
#define DEFAULT_HRGN (HRGN)0x0000 // default hrgn
class CTreeListCtrl;
// Struct for Notify
typedef struct _NMTREELIST
{
NMHDR hdr; // default struct
CTreeListItem* pItem; // item pointer
int iCol; // colimn index
} NMTREELIST, FAR* LPNMTREELIST;
typedef struct _NMTREELISTDRAG
{
NMHDR hdr; // default struct
CTreeListCtrl* pSource; // source control
} NMTREELISTDRAG, FAR*LPNMTREELISTDRAG;
typedef struct _NMTREELISTDROP
{
NMHDR hdr; // default struct
CTreeListCtrl* pSource; // source control
CTreeListItem* pItem; // item pointer
} NMTREELISTDROP, FAR* LPNMTREELISTDROP;
typedef BOOL (WINAPI *lpfnUpdateLayeredWindow)( HWND hWnd, HDC hdcDst, POINT *pptDst,
SIZE *psize,HDC hdcSrc, POINT *pptSrc,
COLORREF crKey, BLENDFUNCTION *pblend, DWORD dwFlags );
typedef BOOL (WINAPI *lpfnSetLayeredWindowAttributes)( HWND hwnd, COLORREF crKey, BYTE xAlpha, DWORD dwFlags );
class CTreeListItem;
class CTreeListHeaderCtrl;
class CTreeListTipCtrl;
class CTreeListStaticCtrl;
class CTreeListEditCtrl;
class CTreeListComboCtrl;
class CTreeListCtrl : public CWnd
{
DECLARE_DYNCREATE(CTreeListCtrl)
friend class CTreeListHeaderCtrl;
friend class CTreeListTipCtrl;
friend class CTreeListStaticCtrl;
friend class CTreeListEditCtrl;
friend class CTreeListComboCtrl;
friend class CTLHDragWnd;
friend class CTLCDragWnd;
friend class CTLCDropWnd;
// Construction
public:
CTreeListCtrl();
virtual ~CTreeListCtrl();
BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );
protected:
BOOL Create();
// Members
protected:
// back ground colors of normal status
COLORREF m_crBkColor; // background color ( none client area )
COLORREF m_crBkColor_0; // background color ( single color tree )
COLORREF m_crBkColor_1; // background color ( single color )
COLORREF m_crBkColor_2; // background color ( double color )
// back ground colors of disable status
COLORREF m_crBkDisable; // background color ( none client area )
COLORREF m_crBkDisable_0; // background color ( single color tree )
COLORREF m_crBkDisable_1; // background color ( single color )
COLORREF m_crBkDisable_2; // background color ( double color )
// back ground colors of selected item
COLORREF m_crBkSelected; // background color of selected
COLORREF m_crBkSelectedRow; // background color of current selected row
COLORREF m_crBkSelectedColumn; // background color of current selected column
COLORREF m_crBkSelectedNoFocus; // background color of no focus selected row
// text colors
COLORREF m_crTextSelected; // color of selected text
COLORREF m_crTextSelectedRow; // color of current selected row text
COLORREF m_crTextSelectedColumn; // color of current selected column text
COLORREF m_crTextSelectedNoFocus; // color of no focus selected text
// normal text color
COLORREF m_crText; // color of text
COLORREF m_crTextHover; // color of hover text
// grid colors
COLORREF m_crGrid; // color of grid
COLORREF m_crTreeLine; // color of tree line
// tree list style
DWORD m_dwStyle; // style of tree list control
// font & palette
CFont m_Font; // font of control
CPalette m_Palette; // palette of control
// cursor
HCURSOR m_hButton; // hcursor of button
HCURSOR m_hCheck; // hcursor of checkbox
HCURSOR m_hLock; // hcursor of lockbox
HCURSOR m_hDrop; // hcursor of drop
HCURSOR m_hStop; // hcursor of stop
HCURSOR m_hArrow; // hcursor of arrow
// draw rects
CRect m_rcClient; // rect of control client ( include header )
CRect m_rcHeader; // rect of control header
CRect m_rcTreeList; // rect of treelist
CRect m_rcFocus; // rect of focus item
protected:
// build in controls
CTreeListStaticCtrl m_wndStatic; // Build in Static Control
CTreeListEditCtrl m_wndEdit; // Build in Edit Control
CTreeListComboCtrl m_wndCombo; // Build in ComboBox Control
// objects of control
CTreeListHeaderCtrl m_wndHeader; // TreeList Header Control
CTreeListTipCtrl m_wndTip; // TreeList Tip Control
private:
// image of control
CBitmap m_bmpBkBitmap; // Bitmap of Background ( Default )
CBitmap m_bmpBkDisable; // Bitmap of Disabled Background ( Default )
CImageList m_imgCheck; // CheckBox Image List ( Default )
CImageList m_imgLock; // LockBox Image List ( Default )
CImageList m_imgTree; // Tree Image List ( Default )
CImageList* m_pImageList; // ImageList ( Delault equ &m_imgTree )
DWORD m_dwState; // State of the Control
private:
// column information of control
CPtrArray m_arColumns; // All Columns
CArray<int, int> m_arShows; // All Show Columns
CArray<int, int> m_arSorts; // All Sort Columns
// row information of control
CPtrArray m_arSelects; // Selected Items
int m_iSelCol; // Selected Column
int m_nItemHeight; // Height of
CTreeListItem* m_pRootItem; // Root Item
CTreeListItem* m_pFocusItem; // Focus item
int m_iModifyCol; // Modify col
CTreeListItem* m_pModifyItem; // Modify item
CTreeListItem* m_pUpdateItem; // Update item
// drag drop
CTLCDragWnd* m_pDragWnd; // Drag Window
CTLCDropWnd* m_pDropWnd; // Drop Window
CPoint m_ptBegin; // Point of Begin Drag
CPoint m_ptDelta; // Delta of Drag
CTreeListItem* m_pTargetItem; // Target Item
CTreeListCtrl* m_pTargetWnd; // Target Window
CTreeListItem* m_pHoverItem; // Hover Item
int m_iHoverItem; // Hover Item
// Attributes
public:
// ***************************** CTreeCtrl ******************************
int GetCount();
CImageList* GetImageList(); // retrieve image list of global treelist
void SetImageList( CImageList* pImageList ); // set image list of global treelist
CTreeListItem* GetNextItem( CTreeListItem* pItem, UINT nCode );
BOOL ItemHasChildren( CTreeListItem* pItem );
CTreeListItem* GetChildItem( CTreeListItem* pItem );
CTreeListItem* GetNextSiblingItem( CTreeListItem* pItem );
CTreeListItem* GetPrevSiblingItem( CTreeListItem* pItem );
CTreeListItem* GetParentItem( CTreeListItem* pItem );
CTreeListItem* GetFirstVisibleItem();
CTreeListItem* GetNextVisibleItem( CTreeListItem* pItem );
CTreeListItem* GetPrevVisibleItem( CTreeListItem* pItem );
CTreeListItem* GetSelectedItem();
CTreeListItem* GetNextSelectedItem( CTreeListItem* pItem );
CTreeListItem* GetRootItem();
DWORD GetItemState( CTreeListItem* pItem, DWORD nStateMask = 0xFFFFFFFF );
void SetItemState( CTreeListItem* pItem, DWORD dwAddState, DWORD dwRemoveState = 0 );
void GetItemImage( CTreeListItem* pItem, int& nImage, int& nExpandImage, int& nSelectedImage, int& nExpandSelectedImage );
void SetItemImage( CTreeListItem* pItem, int nImage, int nExpandImage, int nSelectedImage, int nExpandSelectedImage );
LPCTSTR GetItemText( CTreeListItem* pItem, int nSubItem = 0 );
BOOL SetItemText( CTreeListItem* pItem, LPCTSTR lpszText, int nSubItem = 0 );
DWORD GetItemData( CTreeListItem* pItem );
void SetItemData( CTreeListItem* pItem, DWORD dwData );
int GetVisibleCount();
int SetItemHeight( int cyHeight = -1 ); // set height of row ( automatic )
int GetItemHeight(); // retrieve height of row
COLORREF GetBkColor( int nColor = 0 );
COLORREF SetBkColor( COLORREF clr, int nColor = 0 );
COLORREF GetTextColor();
COLORREF SetTextColor( COLORREF clr );
int GetCheck( CTreeListItem* pItem );
void SetCheck( CTreeListItem* pItem, BOOL bCheck = TRUE );
int GetLock( CTreeListItem* pItem );
void SetLock( CTreeListItem* pItem, BOOL bLock = TRUE );
BOOL GetItemRect( CTreeListItem* pItem, LPRECT lpRect );
BOOL GetItemRect( CTreeListItem* pItem, int iSubItem, LPRECT lpRect, BOOL bTextOnly );
BOOL EnsureVisible( CTreeListItem* pItem, int iSubItem );
// ***************************** CListCtrl ******************************
int GetItemCount();
int GetNextItem( int nItem, int nFlags );
POSITION GetFirstSelectedItemPosition();
CTreeListItem* GetNextSelectedItem( POSITION& pos );
int GetStringWidth( LPCTSTR lpsz );
DWORD SetColumnFormat( int nCol, DWORD dwAdd, DWORD dwRemove );
DWORD GetColumnFormat( int nCol, DWORD dwMask = 0xFFFFFFFF );
DWORD SetColumnModify( int nCol, DWORD dwModify );
DWORD GetColumnModify( int nCol );
int SetColumnWidth( int nCol, int nWidth, int nMin = 0, int nMax = 0 );
int GetColumnWidth( int nCol );
int SetColumnImage( int nCol, int iImage );
int GetColumnImage( int nCol );
BOOL SetColumnText( int nCol, LPCTSTR lpszText );
LPCTSTR GetColumnText( int nCol );
BOOL SetColumnDefaultText( int nCol, LPCTSTR lpszText );
LPCTSTR GetColumnDefaultText( int nCol );
DWORD GetItemState( int nItem, DWORD nStateMask = 0xFFFFFFFF );
void SetItemState( int nItem, DWORD dwAddState, DWORD dwRemoveState = 0 );
void GetItemImage( int nItem, int& nImage, int& nExpandImage, int& nSelectedImage, int& nExpandSelectedImage );
void SetItemImage( int nItem, int nImage, int nExpandImage, int nSelectedImage, int nExpandSelectedImage );
LPCTSTR GetItemText( int nItem, int nSubItem = 0 );
BOOL SetItemText( int nItem, int nSubItem, LPCTSTR lpszText );
DWORD GetItemData( int nItem );
void SetItemData( int nItem, DWORD dwData );
BOOL GetViewRect( LPRECT lpRect );
int GetTopIndex();
int GetCountPerPage();
BOOL GetOrigin( LPPOINT lpPoint );
UINT GetSelectedCount();
BOOL SetColumnOrderArray( int iCount, LPINT piArray );
BOOL GetColumnOrderArray( LPINT piArray, int iCount = -1 );
CTreeListHeaderCtrl* GetHeaderCtrl();
int GetSelectionMark();
int SetSelectionMark( int iIndex );
// *************************** CTreeListCtrl ****************************
void SetFont(CFont& font);
CFont* GetFont();
DWORD SetStyle( DWORD dwStyle );
DWORD GetStyle();
DWORD GetState( DWORD nStateMask = 0xFFFFFFFF );
void SetState( DWORD dwAddState, DWORD dwRemoveState = 0 );
int GetSelectColumn();
int GetColumnCount();
void ExchangeItem( CTreeListItem* pItemA, CTreeListItem* pItemB );
void MoveAfterItem( CTreeListItem* pItem, CTreeListItem* pAfter = NULL );
BOOL DragEnter( CTreeListCtrl* pTreeListCtrl );
BOOL DragLeave( CTreeListCtrl* pTreeListCtrl );
int DragOver( CTreeListCtrl* pTreeListCtrl, CPoint point, CTreeListItem** pp = NULL );
int Drop( CTreeListCtrl* pTreeListCtrl, CPoint point );
protected:
int GetWidth(); // retrieve display high of control
int GetHeight(); // retrieve display width of control
int GetColumns(); // retrieve columns
int GetVisibleCount( CTreeListItem* pParent );
BOOL GetItemRectTree( CTreeListItem* pItem, LPRECT lpRect );
BOOL GetItemRectMain( CTreeListItem* pItem, LPRECT lpRect );
private:
void StatChildAdd( CTreeListItem* pItem, int nChild, int nVisibleChild );
void StatChildDel( CTreeListItem* pItem, int nChild, int nVisibleChild );
void StatExpand( CTreeListItem* pItem );
void StatCollapse( CTreeListItem* pItem );
void SetItemParentStatus( CTreeListItem* pItem, DWORD dwMask );
void SetItemChildStatus( CTreeListItem* pItem, DWORD dwAdd, DWORD dwRemove = 0 );
void SetItemCheck( CTreeListItem* pItem, BOOL bAutoCheck = TRUE );
void SetItemLock( CTreeListItem* pItem, BOOL bAutoLock = TRUE );
// Operations
public:
BOOL InsertColumn( LPCTSTR lpszColumnHeading, DWORD dwFormat = TLF_DEFAULT_LEFT, int nWidth = 0, int iImage = -1, int nMin = 0, int nMax = 0);
BOOL DeleteColumn( int iCol );
int InsertItem( int nItem, LPCTSTR lpszItem );
BOOL DeleteItem( int nItem );
CTreeListItem* InsertItem( LPCTSTR lpszItem, CTreeListItem* pParent = TLI_ROOT, CTreeListItem* pInsertAfter = TLI_LAST );
BOOL DeleteItem( CTreeListItem* pItem = TLI_ROOT );
BOOL DeleteAllItems();
BOOL Expand( CTreeListItem* pItem, int nCode );
BOOL Select( CTreeListItem* pItem, int nCode );
CTreeListItem* HitTest( CPoint pt, int* pFlag = NULL, int* pSubItem = NULL, CRect* prcText = NULL );
void SelectItem( CTreeListItem* pItem, int iSubItem = 0, BOOL bClearLastSelected = TRUE );
void ActiveItem( CTreeListItem* pItem, int iSubItem = 0 );
void SetTargetItem( CTreeListItem* pItem = NULL );
void SetHoverItem( CTreeListItem* pItem = NULL );
protected:
CTreeListItem* InsertItemNew ( LPCTSTR lpszItem, CTreeListItem* pParent );
CTreeListItem* InsertItemFirst ( LPCTSTR lpszItem, CTreeListItem* pParent );
CTreeListItem* InsertItemNext ( LPCTSTR lpszItem, CTreeListItem* pParent, CTreeListItem* pInsertAfter );
CTreeListItem* GetLastChildItem( CTreeListItem* pParent = TLI_ROOT );
CTreeListItem* GetSortChildItem( CTreeListItem* pParent = TLI_ROOT );
CTreeListItem* GetValidChildItem( CTreeListItem* pParent, CTreeListItem* pChild);
BOOL Expand( CTreeListItem* pItem, int nCode, int iSubItem );
CTreeListItem* HitTest( CPoint pt, int* pFlag, int* pSubItem, CRect* prcText, CRect rcItem, CTreeListItem* pItem );
private:
CTreeListItem* InsertItemX( CTreeListItem* pParent, CTreeListItem* pNewItem );
BOOL DeleteItemX( CTreeListItem* pItem );
BOOL DeleteItemFast( CTreeListItem* pItem );
CTreeListItem* GetFirstShowItem( int nShowItem );
CTreeListItem* GetNextShowItem( CTreeListItem* pItem, BOOL bChild = TRUE );
CTreeListItem* GetNextVisibleItem( CTreeListItem* pItem, BOOL bChild );
CTreeListItem* GetPrevVisibleItem( CTreeListItem* pItem, BOOL bChild );
CTreeListItem* GetLastVisibleItem( CTreeListItem* pItem );
CTreeListItem* HitTestTree( CPoint pt, int* pFlag, CRect* prcText, CRect rcColumn, CTreeListItem* pItem );
CTreeListItem* HitTestMain( CPoint pt, int* pFlag, CRect* prcText, CRect rcColumn, CTreeListItem* pItem );
CTreeListItem* HitTestList( CPoint pt, int* pFlag, CRect* prcText, CRect rcColumn, CTreeListItem* pItem );
CTreeListItem* GetTreeListItem( int nItem );
int GetTreeListItem( CTreeListItem* pItem );
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTreeListCtrl)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual void PreSubclassWindow();
//}}AFX_VIRTUAL
// Implementation
public:
BOOL SetCtrlFocus( CWnd* pWnd, BOOL bFocus = TRUE );
BOOL BeginModify( CTreeListItem* pItem, int iCol );
BOOL UpdateModify();
BOOL FinishModify();
BOOL CancelModify();
CWnd* GetControl( CTreeListItem* pItem, int iCol );
protected:
LRESULT Notify( DWORD dwMessage, CTreeListItem* pItem, int iCol );
LRESULT NotifyDrop( DWORD dwMessage, CTreeListCtrl* pSource, CTreeListItem* pItem );
void Layout();
void DrawCtrl( CDC* pDC );
void DrawBkgnd( CDC* pDC, CRect rcClip );
void DrawBkgndBmp( CDC* pDC, CRect rcClip, CBitmap* pBkgnd );
void DrawItems( CDC* pDC, CRect rcClip );
void DrawItem( CDC* pDC, CRect rcItem, CTreeListItem* pItem );
void DrawGrid( CDC* pDC, CRect rcItem );
void DrawItemBkgnd( CDC* pDC, CRect rcItem, CTreeListItem* pItem );
void DrawItemExclude( CDC* pDC, CRect rcItem, CTreeListItem* pItem );
void DrawItemTree( CDC* pDC, CRect rcColumn, CTreeListItem* pItem, int iCol );
void DrawItemMain( CDC* pDC, CRect rcColumn, CTreeListItem* pItem, int iCol );
void DrawItemList( CDC* pDC, CRect rcColumn, CTreeListItem* pItem, int iCol );
void DrawItemTreeLine( CDC* pDC, CRect rcColumn, CRect rcTree, DWORD dwFormat );
void DrawItemTreeButton( CDC* pDC, CRect rcColumn, CRect rcTree, DWORD dwFormat );
void DrawItemTreeText( CDC* pDC, CRect rcBkgnd, CTreeListItem* pItem, int iCol );
void DrawItemListText( CDC* pDC, CRect rcBkgnd, CTreeListItem* pItem, int iCol );
void DrawItemText( CDC* pDC, CRect rcBkgnd, CRect rcText, CTreeListItem* pItem, int iCol );
void SetAllScroll();
BOOL PreTranslateKeyDownMessage( MSG* pMsg );
BOOL PreTranslateKeyDownMessage2( MSG* pMsg );
int GetPrevModifyCol();
int GetNextModifyCol();
BOOL UpdateModifyColumn();
BOOL UpdateModifyColumns();
BOOL BeginControl( CTreeListItem* pItem, int iCol );
BOOL CancelControl();
BOOL RestoreControl( CTreeListItem* pItem, int iCol );
BOOL BeginStatic( CTreeListItem* pItem, int iCol, CRect rcText );
BOOL CancelStatic();
BOOL RestoreStatic( CTreeListItem* pItem, int iCol, CRect rcText );
BOOL BeginEdit( CTreeListItem* pItem, int iCol, CRect rcText );
BOOL CancelEdit();
BOOL RestoreEdit( CTreeListItem* pItem, int iCol, CRect rcText );
BOOL BeginCombo( CTreeListItem* pItem, int iCol, CRect rcText );
BOOL CancelCombo();
BOOL RestoreCombo( CTreeListItem* pItem, int iCol, CRect rcText);
BOOL BeginDraging( CPoint point );
BOOL EndDraging( CPoint point );
BOOL DoDraging( CPoint point );
BOOL EndDraging();
private:
void SetHorzScroll( CRect* pPreClient );
void SetVertScroll( CRect* pPreClient );
BOOL IsInSelectsTree( CTreeListItem* pItem );
// Generated message map functions
protected:
//{{AFX_MSG(CTreeListCtrl)
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint();
afx_msg void OnEnable(BOOL bEnable);
afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp);
afx_msg void OnNcPaint();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg void OnDestroy();
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnCancelMode();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_TREELISTCTRL_H__55B6E4E9_1E57_4FEE_AA05_77C052ACE9B5__INCLUDED_)
| [
"benevo.woo@gmail.com"
] | benevo.woo@gmail.com |
05311d1c32ad8210b008a8b2c4d541e7d0e02967 | 3a4645066b2155cd239fdda0b3bea4bd90985aa3 | /Baekjoon/BJ16948.cpp | 681aad75c2144a44ac1b5ecd2e84daca00656c9f | [] | no_license | charmdong/Algorithm_solutions_2019 | ca10553b55e1a3c4c8bc7b602cfcc24c71c7b315 | aa7aa58dc3104954b8b7f62056c0b6656dbef110 | refs/heads/master | 2022-04-04T03:57:51.933185 | 2020-02-24T02:14:46 | 2020-02-24T02:14:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,263 | cpp | /**
* @author : donggun.chung
* @date : 2020.02.15
* @site : BOJ
* @prob_Info : 16948 데스 나이트
* @time : 0ms
* @memory : 2248KB
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int N, srcY, srcX, desY, desX;
int dy[6] = {-2, -2, 0, 0, 2, 2};
int dx[6] = {-1, 1, -2, 2, -1, 1};
vector<vector<int>> board;
int solution();
int main()
{
ios_base ::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N;
board.assign(N, vector<int>(N, 0));
cin >> srcY >> srcX >> desY >> desX;
cout << solution() << endl;
return 0;
}
int solution() {
queue<pair<int, int>> q;
q.push({srcY, srcX});
while(!q.empty()) {
pair<int, int> now = q.front();
q.pop();
if(now == make_pair(desY, desX)) {
return board[desY][desX];
}
for(int dir = 0; dir < 6; dir++) {
int ny = now.first + dy[dir];
int nx = now.second + dx[dir];
if(ny > -1 && ny < N && nx > - 1 && nx < N) {
if(board[ny][nx] == 0) {
q.push({ny, nx});
board[ny][nx] = board[now.first][now.second] + 1;
}
}
}
}
return -1;
} | [
"chungdk1117@gmail.com"
] | chungdk1117@gmail.com |
3c4879aa6deb1385df70fc2ed0395ba4d5466ee7 | 8b114bdb03087ca7b2d144838a697c4c07ef1f61 | /libraries/WireI2C/WireI2C.cpp | 976b0d124af46fea48f612c597109e0d20315e8d | [] | no_license | carrardt/TiPiDuino | 4beecccb701e56c727ac014290ecedc0862dcbc8 | 7bc34539bed44dfeb2e15c6a5676969ffff0929b | refs/heads/master | 2023-08-18T17:48:17.446921 | 2023-08-16T05:56:53 | 2023-08-16T05:56:53 | 30,426,056 | 2 | 0 | null | 2018-08-27T18:53:36 | 2015-02-06T18:12:19 | C++ | UTF-8 | C++ | false | false | 10,648 | cpp | /*
TwoWire.cpp - TWI/I2C library for Wiring & Arduino
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts
Modified 2017 by Chuck Todd (ctodd@cableone.net) to correct Unconfigured Slave Mode reboot
Modified 2020 by Greyson Christoforo (grey@christoforo.net) to implement timeouts
*/
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "twi.h"
#include "WireI2C.h"
// Initialize Class Variables //////////////////////////////////////////////////
uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;
uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;
uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);
// Constructors ////////////////////////////////////////////////////////////////
TwoWire::TwoWire()
{
}
// Public Methods //////////////////////////////////////////////////////////////
void TwoWire::begin(void)
{
rxBufferIndex = 0;
rxBufferLength = 0;
txBufferIndex = 0;
txBufferLength = 0;
twi_init();
twi_attachSlaveTxEvent(onRequestService); // default callback must exist
twi_attachSlaveRxEvent(onReceiveService); // default callback must exist
}
void TwoWire::begin(uint8_t address)
{
begin();
twi_setAddress(address);
}
void TwoWire::begin(int address)
{
begin((uint8_t)address);
}
void TwoWire::end(void)
{
twi_disable();
}
void TwoWire::setClock(uint32_t clock)
{
twi_setFrequency(clock);
}
/***
* Sets the TWI timeout.
*
* This limits the maximum time to wait for the TWI hardware. If more time passes, the bus is assumed
* to have locked up (e.g. due to noise-induced glitches or faulty slaves) and the transaction is aborted.
* Optionally, the TWI hardware is also reset, which can be required to allow subsequent transactions to
* succeed in some cases (in particular when noise has made the TWI hardware think there is a second
* master that has claimed the bus).
*
* When a timeout is triggered, a flag is set that can be queried with `getWireTimeoutFlag()` and is cleared
* when `clearWireTimeoutFlag()` or `setWireTimeoutUs()` is called.
*
* Note that this timeout can also trigger while waiting for clock stretching or waiting for a second master
* to complete its transaction. So make sure to adapt the timeout to accomodate for those cases if needed.
* A typical timeout would be 25ms (which is the maximum clock stretching allowed by the SMBus protocol),
* but (much) shorter values will usually also work.
*
* In the future, a timeout will be enabled by default, so if you require the timeout to be disabled, it is
* recommended you disable it by default using `setWireTimeoutUs(0)`, even though that is currently
* the default.
*
* @param timeout a timeout value in microseconds, if zero then timeout checking is disabled
* @param reset_with_timeout if true then TWI interface will be automatically reset on timeout
* if false then TWI interface will not be reset on timeout
*/
void TwoWire::setWireTimeout(uint32_t timeout, bool reset_with_timeout){
twi_setTimeoutInMicros(timeout, reset_with_timeout);
}
/***
* Returns the TWI timeout flag.
*
* @return true if timeout has occured since the flag was last cleared.
*/
bool TwoWire::getWireTimeoutFlag(void){
return(twi_manageTimeoutFlag(false));
}
/***
* Clears the TWI timeout flag.
*/
void TwoWire::clearWireTimeoutFlag(void){
twi_manageTimeoutFlag(true);
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint32_t iaddress, uint8_t isize, uint8_t sendStop)
{
if (isize > 0) {
// send internal address; this mode allows sending a repeated start to access
// some devices' internal registers. This function is executed by the hardware
// TWI module on other processors (for example Due's TWI_IADR and TWI_MMR registers)
beginTransmission(address);
// the maximum size of internal address is 3 bytes
if (isize > 3){
isize = 3;
}
// write internal register address - most significant byte first
while (isize-- > 0)
write((uint8_t)(iaddress >> (isize*8)));
endTransmission(false);
}
// clamp to buffer length
if(quantity > BUFFER_LENGTH){
quantity = BUFFER_LENGTH;
}
// perform blocking read into buffer
uint8_t read = twi_readFrom(address, rxBuffer, quantity, sendStop);
// set rx buffer iterator vars
rxBufferIndex = 0;
rxBufferLength = read;
return read;
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop) {
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint32_t)0, (uint8_t)0, (uint8_t)sendStop);
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
{
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true);
}
uint8_t TwoWire::requestFrom(int address, int quantity)
{
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true);
}
uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop)
{
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)sendStop);
}
void TwoWire::beginTransmission(uint8_t address)
{
// indicate that we are transmitting
transmitting = 1;
// set address of targeted slave
txAddress = address;
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
}
void TwoWire::beginTransmission(int address)
{
beginTransmission((uint8_t)address);
}
//
// Originally, 'endTransmission' was an f(void) function.
// It has been modified to take one parameter indicating
// whether or not a STOP should be performed on the bus.
// Calling endTransmission(false) allows a sketch to
// perform a repeated start.
//
// WARNING: Nothing in the library keeps track of whether
// the bus tenure has been properly ended with a STOP. It
// is very possible to leave the bus in a hung state if
// no call to endTransmission(true) is made. Some I2C
// devices will behave oddly if they do not see a STOP.
//
uint8_t TwoWire::endTransmission(uint8_t sendStop)
{
// transmit buffer (blocking)
uint8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1, sendStop);
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
// indicate that we are done transmitting
transmitting = 0;
return ret;
}
// This provides backwards compatibility with the original
// definition, and expected behaviour, of endTransmission
//
uint8_t TwoWire::endTransmission(void)
{
return endTransmission(true);
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
size_t TwoWire::write(uint8_t data)
{
if(transmitting){
// in master transmitter mode
// don't bother if buffer is full
if(txBufferLength >= BUFFER_LENGTH){
//setWriteError();
return 0;
}
// put byte in tx buffer
txBuffer[txBufferIndex] = data;
++txBufferIndex;
// update amount in buffer
txBufferLength = txBufferIndex;
}else{
// in slave send mode
// reply to master
twi_transmit(&data, 1);
}
return 1;
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
size_t TwoWire::write(const uint8_t *data, size_t quantity)
{
if(transmitting){
// in master transmitter mode
for(size_t i = 0; i < quantity; ++i){
write(data[i]);
}
}else{
// in slave send mode
// reply to master
twi_transmit(data, quantity);
}
return quantity;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
int TwoWire::available(void)
{
return rxBufferLength - rxBufferIndex;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
int TwoWire::read(void)
{
int value = -1;
// get each successive byte on each call
if(rxBufferIndex < rxBufferLength){
value = rxBuffer[rxBufferIndex];
++rxBufferIndex;
}
return value;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
int TwoWire::peek(void)
{
int value = -1;
if(rxBufferIndex < rxBufferLength){
value = rxBuffer[rxBufferIndex];
}
return value;
}
void TwoWire::flush(void)
{
// XXX: to be implemented.
}
// behind the scenes function that is called when data is received
void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes)
{
// don't bother if user hasn't registered a callback
if(!user_onReceive){
return;
}
// don't bother if rx buffer is in use by a master requestFrom() op
// i know this drops data, but it allows for slight stupidity
// meaning, they may not have read all the master requestFrom() data yet
if(rxBufferIndex < rxBufferLength){
return;
}
// copy twi rx buffer into local read buffer
// this enables new reads to happen in parallel
for(uint8_t i = 0; i < numBytes; ++i){
rxBuffer[i] = inBytes[i];
}
// set rx iterator vars
rxBufferIndex = 0;
rxBufferLength = numBytes;
// alert user program
user_onReceive(numBytes);
}
// behind the scenes function that is called when data is requested
void TwoWire::onRequestService(void)
{
// don't bother if user hasn't registered a callback
if(!user_onRequest){
return;
}
// reset tx buffer iterator vars
// !!! this will kill any pending pre-master sendTo() activity
txBufferIndex = 0;
txBufferLength = 0;
// alert user program
user_onRequest();
}
// sets function called on slave write
void TwoWire::onReceive( void (*function)(int) )
{
user_onReceive = function;
}
// sets function called on slave read
void TwoWire::onRequest( void (*function)(void) )
{
user_onRequest = function;
}
// Preinstantiate Objects //////////////////////////////////////////////////////
TwoWire Wire = TwoWire();
| [
"thierry.carrard@orange.fr"
] | thierry.carrard@orange.fr |
585a02e13ac5933dd2898919d3915185e91c0fd1 | 10ef0192c6a8ad23fa85e43925ff160891e2e54d | /src/converters/ConverterLine.h | 06747ac8a3b417b5d61a7bc54d41cb6eb1eaa1a1 | [
"BSD-3-Clause"
] | permissive | X-Plane/3DsMax-XplnObj | 94f915e922f481dcb164f5f27f3da3b1328f7838 | 92c664493326240ca5565cdf29558c31d6826350 | refs/heads/master | 2021-05-16T15:19:19.245681 | 2017-10-05T16:35:39 | 2017-10-05T16:35:39 | 118,813,327 | 4 | 1 | null | 2018-01-24T19:43:22 | 2018-01-24T19:43:22 | null | UTF-8 | C++ | false | false | 2,712 | h | /*
** Copyright(C) 2017, StepToSky
**
** 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 StepToSky nor the names of its contributors
** may be used to endorse or promote products derived from this software
** without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
** Contacts: www.steptosky.com
*/
#pragma once
#pragma warning(push, 0)
#include <max.h>
#pragma warning(pop)
#include <xpln/obj/ObjLine.h>
/**************************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////////////
/**************************************************************************************************/
class SplineShape;
class ConverterLine {
ConverterLine() = default;
~ConverterLine() = default;
public:
typedef std::vector<xobj::ObjAbstract*> ObjLineList;
static ObjLineList toXpln(INode * inXNode, const Matrix3 & inTargetTm);
static INode * toMax(const xobj::ObjAbstract * /*object*/) {
// TODO Implementation
return nullptr;
}
private:
static SplineShape * getShape(INode * inNode);
};
/**************************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////////////
/**************************************************************************************************/
| [
"pancir3d@steptosky.com"
] | pancir3d@steptosky.com |
4e0a2ba9ea89b3c694842c201f84274a8860f804 | 5552798e3562cad0b615b6141f8ea33214bba861 | /C++/Spoj/bwidow.cpp | de56954358172d24030d66551af7686f5f141a14 | [] | no_license | YashSharma/C-files | 3922994cf7f0f5947173aa2b26a7dc399919267b | 3d7107e16c428ee056814b33ca9b89ab113b0753 | refs/heads/master | 2016-08-12T09:16:25.499792 | 2015-12-20T08:24:47 | 2015-12-20T08:24:47 | 48,312,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | cpp | #include<iostream>
int main()
{ long long t,n,max,i,k;
scanf("%lld",&t);
while(t--)
{ scanf("%lld",&n);
max=0;
unsigned long long a[n][2];
for(i=0;i<n;i++)
{ scanf("%llu %llu",&a[i][0],&a[i][1]);
if(a[i][0]>max)
{ max=a[i][0];
k=i+1; }
}
for(i=0;i<n;i++)
{ if(a[i][1]>=max && k!=(i+1))
{ k=-1;
break;
}
}
printf("%lld\n",k);
}
return 0;
} | [
"Apple@Yash-MacBook-Air.local"
] | Apple@Yash-MacBook-Air.local |
544005ee40f8e9ade076eada9f8d2dd6b01d223f | 5c953e39aab259031bb12046e0e3ab771a076527 | /include/bd/geo/quad.h | 5bb7387c88dc39de3854f6a6a20f0e053521f3ed | [] | no_license | MEC402/cruft | 47cbf1a6f88d1f80c4239cddb72c9b96a0d13216 | 72215b3e92ea32d1ecb257e3d54de41598c864e2 | refs/heads/master | 2021-01-18T10:26:01.738875 | 2016-08-07T01:20:09 | 2016-08-07T01:20:09 | 42,978,274 | 0 | 0 | null | 2015-09-23T04:26:37 | 2015-09-23T04:26:36 | null | UTF-8 | C++ | false | false | 977 | h | #ifndef quad_h__
#define quad_h__
#include <bd/scene/transformable.h>
#include <bd/geo/drawable.h>
#include <glm/glm.hpp>
#include <array>
namespace bd
{
class Quad : public Transformable, public IDrawable
{
public:
static const std::array<glm::vec4, 4> verts_xy; ///< initially in xy-plane
static const std::array<glm::vec4, 4> verts_yz; ///< initially in yz-plane
static const std::array<glm::vec4, 4> verts_xz; ///< initially in xz-plane
static const std::array<glm::vec3, 4> texcoords_xy;
static const std::array<glm::vec3, 4> texcoords_yz;
static const std::array<glm::vec3, 4> texcoords_xz;
static const std::array<unsigned short, 4> elements; ///< Element array indexes for triangle strip.
static const std::array<glm::vec3, 4> colors; ///< Vertex colors.
static const unsigned int vert_element_size = 4; ///< number of elements in single vertex
Quad();
virtual ~Quad();
virtual void draw();
};
} // namespace bd
#endif // !quad_h__
| [
"jimpelton@u.boisestate.edu"
] | jimpelton@u.boisestate.edu |
df44a15040bbe90c5cf2a7981ba692cd96def582 | 575c265b54bbb7f20b74701753174678b1d5ce2c | /lottery/Classes/lottery/bjk8/BJK8ChaseNumBerLayer.cpp | cf2dde0d2b1ec4b09ee5430d03a2ca19a21b5846 | [] | no_license | larryzen/Project3.x | c8c8a0be1874647909fcb1a0eb453c46d6d674f1 | cdc2bf42ea737c317fe747255d2ff955f80dbdae | refs/heads/master | 2020-12-04T21:27:46.777239 | 2019-03-02T06:30:26 | 2019-03-02T06:30:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,729 | cpp | #include "BJK8ChaseNumBerLayer.h"
#include "RoomLayer.h"
#include "ConfigMgr.h"
#include "MovingLabelLayer.h"
#include "PromptBox.h"
#include "LotterySettingView.h"
#include "DBHandler.h"
#include "time.h"
#include "BetLimit.h"
#include "VersionControl.h"
using namespace CocosDenshion;
Scene* BJK8ChaseNumBerLayer::scene()
{
Scene *scene = Scene::create();
BJK8ChaseNumBerLayer *layer = BJK8ChaseNumBerLayer::create();
scene->addChild(layer);
return scene;
}
BJK8ChaseNumBerLayer::BJK8ChaseNumBerLayer()
{
fandianStatus = 0;
ZhuiHaoBool =0;
BeiTouBool = 0;
nMoshiNumber=1;
BaoCunQiShu = 5;
nMoshi=0;
ZhuiHao = 4;
QuanJunBeiShu = 1;
TouZhuJinENumber =0.00;
memset(chaseStatus, 0, sizeof(chaseStatus));
zhuiHaoQiShu = 5;
cellHeight = 20;
betZhuiHaoZhuShu =1;
tempItemInpu = NULL;
for(int index = 0 ; index < zhuiHaoQiShu ; index++)
{
chaseStatus[index]=1;
chaseInputStatus[index] = 1;
chaseInputMonreny[index] = nMoshiNumber*betZhuiHaoZhuShu;
TouZhuJinENumber += chaseInputMonreny[index];
}
NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(BJK8ChaseNumBerLayer::TouZhuZhuiHaoButton), "TouZhuChaseNumBer", NULL);
NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(BJK8ChaseNumBerLayer::changeKind), "GDselectedItemTagNumberCartFailed", NULL);
NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(BJK8ChaseNumBerLayer::touZhuContinueRet), "CQSSCRetZhuiHao", NULL);
NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(BJK8ChaseNumBerLayer::IsFendanHourRet), "IsFendanHourRet", NULL);
}
BJK8ChaseNumBerLayer::~BJK8ChaseNumBerLayer()
{
if(fandianTable != nullptr)
{
fandianTable->release();
}
if(touZhuTable != nullptr)
{
touZhuTable->release();
}
NotificationCenter::getInstance()->removeObserver(this, "TouZhuChaseNumBer");
NotificationCenter::getInstance()->removeObserver(this, "GDselectedItemTagNumberCartFailed");
NotificationCenter::getInstance()->removeObserver(this, "CQSSCRetZhuiHao");
NotificationCenter::getInstance()->removeObserver(this, "IsFendanHourRet");
}
bool BJK8ChaseNumBerLayer::init()
{
if (!Layer::init())
{
return false;
}
ZhuiHaoQiShuBool = false;
this->initData();
this->initView();
setTouchEnabled(true);
this->setKeypadEnabled(true);
return true;
}
void BJK8ChaseNumBerLayer::initData()
{
winSize = Director::getInstance()->getWinSize();
//gameKyTe = NULL;
}
void BJK8ChaseNumBerLayer::initView()
{
LayerColor* layer = LayerColor::create(ccc4(255, 255, 255, 255), SCREEN_WIDTH, SCREEN_HEIGHT);
layer->ignoreAnchorPointForPosition(false);
layer->setPosition(Vec2(winSize.width*0.5,winSize.height*0.5));
this->addChild(layer);
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(false);
listener->onTouchBegan = [=](Touch*, Event*){
if(tempItemInpu != NULL)
{
editBoxEditingDidEnd(tempItemInpu);
tempItemInpu = NULL;
}
return true;
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, layer);
//背景图
Sprite *bk1 = Sprite::createWithSpriteFrame(spriteFrame(HEAD_IMG));
bk1->setAnchorPoint(Vec2(0,1));
bk1->setPosition(Vec2(0, SCREEN_HEIGHT));
bk1->setScaleX(SCREEN_WIDTH / bk1->getContentSize().width);
bk1->setScaleY(162 / bk1->getContentSize().height);
this->addChild(bk1,1);
float fontSize = 38;
//返回按钮
Sprite *pCloseNormalButton = Sprite::createWithSpriteFrame(spriteFrame("regist_04.png"));
Sprite *pCloseSelectButton = Sprite::createWithSpriteFrame(spriteFrame("regist_04.png"));
MenuItemSprite *pCloseItemSprite = MenuItemSprite::create
(pCloseNormalButton,pCloseSelectButton,CC_CALLBACK_1(BJK8ChaseNumBerLayer::back,this));
pCloseButton = Menu::create(pCloseItemSprite,NULL);
//pCloseButton->setPosition(Vec2(32, SCREEN_HEIGHT - 120));
pCloseButton->setPosition(Vec2(34, SCREEN_HEIGHT - 105));
this->addChild(pCloseButton,1);
float menuGap = 10;
//追号字样
LabelTTF *title = LabelTTF::create(ConfigMgr::instance()->text("display_DuangDong.xml", "t175"), "", fontSize);
title->setPosition(Vec2(SCREEN_WIDTH / 2, pCloseButton->getPositionY()));
title->setColor(ccc3(255, 255, 255));
this->addChild(title, 1);
fontSize = 28;
static int fontSize2 = 20;
static int upMove = 20;
char szBuf2[100] = {0};
sprintf(szBuf2, "%.3f ",0.00);
String *TouZhuYuEString = String::createWithFormat("%s %s%s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t3"),szBuf2,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",TouZhuJinENumber);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
//投注金额
TouZhuJinEChaseNumBerLabel = LabelTTF::create(TouZhuJinECherString->getCString(), "", fontSize);
TouZhuJinEChaseNumBerLabel->setPosition(Vec2(winSize.width*0.03,140 + upMove));//
TouZhuJinEChaseNumBerLabel->setAnchorPoint(Vec2(0, 0.5f));
TouZhuJinEChaseNumBerLabel->setColor(ccc3(0,0,0));
this->addChild(TouZhuJinEChaseNumBerLabel, 2);
char szBuf3[100] = {0};
sprintf(szBuf3, "%.3f ", EntityMgr::instance()->getDispatch()->f_qipai_yue);
String *GameYuEString = String::createWithFormat("%s %s%s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t6"),szBuf3,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
//追号期数
haoMaLabel = LabelTTF::create(String::createWithFormat("%s", ConfigMgr::instance()->text("display_DuangDong.xml", "t171"))->getCString(), "", fontSize);
haoMaLabel->setColor(ccc3(0,0,0));
haoMaLabel->setPosition(Vec2(winSize.width*0.1,winSize.height*0.83));
this->addChild(haoMaLabel, 1);
//外框 combobox
Sprite *beilvBk = Sprite::createWithSpriteFrame(spriteFrame("home_11.png"));
beilvBk->setAnchorPoint(Vec2(0,0.5f));
beilvBk->setPosition(Vec2(winSize.width*0.2+1,winSize.height*0.83));
this->addChild(beilvBk,2);
//下拉
Sprite *ButtonCodedImage = Sprite::createWithSpriteFrame(spriteFrame("beting17.png"));
Sprite *ButtonCodeNormalImage = Sprite::createWithSpriteFrame(spriteFrame("beting18.png"));
ButtonCodeRecordItem = MenuItemSprite::create(ButtonCodedImage,ButtonCodeNormalImage,CC_CALLBACK_1(BJK8ChaseNumBerLayer::XuanZeZhuiHaoQiShu,this));
Menu *ButtonCodeMenu = Menu::create(ButtonCodeRecordItem,NULL);
ButtonCodeMenu->setPosition(Vec2(winSize.width*0.45-22,winSize.height*0.83)); //向左移动20个像素
this->addChild(ButtonCodeMenu,2);
beilvBk->setScaleX((ButtonCodeMenu->getPositionX()-beilvBk->getPositionX() + ButtonCodedImage->getContentSize().width / 2) / beilvBk->getContentSize().width); //框缩短1/4
//追号输入框
beilvInput = EditBox::create(cocos2d::Size(120,32), "blank.png");
float beilvInputMidX = winSize.width*0.2;
beilvInput->setPosition(Vec2(winSize.width*0.2, beilvBk->getPositionY()));
beilvInput->setInputFlag(ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE);
beilvInput->setReturnType(ui::EditBox::KeyboardReturnType::DONE);
beilvInput->setInputMode(ui::EditBox::InputMode::NUMERIC);
beilvInput->setAnchorPoint(Vec2(0,0.5f));
beilvInput->setFontColor(ccc3(0,0,0));
beilvInput->setFontName("");
beilvInput->setFontSize(fontSize);
beilvInput->setDelegate(this);
beilvInput->setText("5");
beilvInput->setColor(ccc3(112,112,112));
beilvInput->setMaxLength(20);
this->addChild(beilvInput, 2);
//追号倍数
timeLabel = LabelTTF::create(String::createWithFormat("%s", ConfigMgr::instance()->text("display_DuangDong.xml", "t172"))->getCString(), "", fontSize);
timeLabel->setColor(ccc3(0,0,0));
timeLabel->setPosition(Vec2(winSize.width*0.7 + 20,haoMaLabel->getPositionY()));//右移20
this->addChild(timeLabel, 1);
//追号输入 外框
Sprite *beilvBk2 = Sprite::createWithSpriteFrame(spriteFrame("home_11_2.png"));
beilvBk2->setAnchorPoint(Vec2(0,0.5f));
beilvBk2->setScaleX(0.8f);
beilvBk2->setPosition(Vec2(winSize.width*0.8 + 20,beilvBk->getPositionY())); //右移20
this->addChild(beilvBk2,2);
CtratebeilvInput = EditBox::create(cocos2d::Size(80,32), "blank.png");
float CtratebeilvInputMidX = beilvBk2->getPositionX();
CtratebeilvInput->setPosition(Vec2(CtratebeilvInputMidX, beilvBk->getPositionY()));
CtratebeilvInput->setInputFlag(ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE);
CtratebeilvInput->setReturnType(ui::EditBox::KeyboardReturnType::DONE);
CtratebeilvInput->setAnchorPoint(Vec2(0,0.5f));
CtratebeilvInput->setFontColor(ccc3(0,0,0));
CtratebeilvInput->setFontName("");CtratebeilvInput->setFontSize(fontSize);
CtratebeilvInput->setColor(ccc3(112,112,112));
CtratebeilvInput->setDelegate(this);
CtratebeilvInput->setText("1");
CtratebeilvInput->setInputMode(ui::EditBox::InputMode::NUMERIC);
CtratebeilvInput->setMaxLength(20);
this->addChild(CtratebeilvInput, 2);
/*********************************/
m_TableNode = Node::create();
m_TableNode->setPosition(1000,1000);
this->addChild(m_TableNode, 3);
//白色背景 带边框
tableCellWidth = 185;//216 //减少30
fandianTableBk = Sprite::createWithSpriteFrame(spriteFrame("lottery_record_01.png"));
fandianTableBk->setAnchorPoint(Vec2(0,0));
fandianTableBk->setPosition(Vec2::ZERO);
fandianTableBk->setScaleX(tableCellWidth / fandianTableBk->getContentSize().width);
m_TableNode->addChild(fandianTableBk,3);
tableViewSize.width = tableCellWidth;
tableViewSize.height = fandianTableBk->getContentSize().height;
//追号列表
fandianTable = TableView::create(this, tableViewSize);
fandianTable->setDelegate(this);
fandianTable->setAnchorPoint(Vec2(0.5, 0.5));
fandianTable->setPosition(Vec2::ZERO);
fandianTable->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN);
fandianTable->setDirection(ScrollView::Direction::VERTICAL);
fandianTable->retain();
fandianTable->setTag(1111);
m_TableNode->addChild(fandianTable, 3);
//是否倍投
LabelTTF* BeiNumberLabel = LabelTTF::create(String::createWithFormat("%s",ConfigMgr::instance()->text("display_DuangDong.xml","t173"))->getCString(), "",fontSize);
BeiNumberLabel->setColor(ccc3(0,0,0));
BeiNumberLabel->setPosition(Vec2(winSize.width*0.1,winSize.height*0.75 + upMove));
this->addChild(BeiNumberLabel, 2);
//倍投开关
Sprite *winningRecordSelectedImage = Sprite::createWithSpriteFrame(spriteFrame("beting16.png"));
Sprite *contiRecordNormalImage = Sprite::createWithSpriteFrame(spriteFrame("beting16.png"));
betRecordItem = MenuItemSprite::create(winningRecordSelectedImage,contiRecordNormalImage,CC_CALLBACK_1(BJK8ChaseNumBerLayer::IsEndeBeiTou,this));
recordMenu = Menu::create(betRecordItem,NULL);
recordMenu->setPosition(Vec2(winSize.width*0.3 - 20,winSize.height*0.75 + upMove));
this->addChild(recordMenu,2);
//中奖后停止追号
LabelTTF* BeiNumberLabe2 = LabelTTF::create(String::createWithFormat("%s",ConfigMgr::instance()->text("display_DuangDong.xml","t174"))->getCString(), "",fontSize);
BeiNumberLabe2->setColor(ccc3(0,0,0));
BeiNumberLabe2->setPosition(Vec2(winSize.width*0.62 + 35,winSize.height*0.75 + upMove));//右移40
this->addChild(BeiNumberLabe2,2);
//追号开关
Sprite *betRecordNormalImage = Sprite::createWithSpriteFrame(spriteFrame("beting15.png"));
Sprite *betRecordSelectedImage = Sprite::createWithSpriteFrame(spriteFrame("beting15.png"));
GetRecordItem = MenuItemSprite::create(betRecordNormalImage,betRecordSelectedImage,CC_CALLBACK_1(BJK8ChaseNumBerLayer::IsEndeZhuiHao,this));
recordMenu2 = Menu::create(GetRecordItem,NULL);
recordMenu2->setPosition(Vec2(winSize.width*0.9,winSize.height*0.75 + upMove));
this->addChild(recordMenu2,2);
//表格头
Sprite *gapTagSprite = Sprite::createWithSpriteFrame(spriteFrame("beting19.png"));
gapTagSprite->setAnchorPoint(Vec2(0.5f,0.5f));
//gapTagSprite->setScaleX(0.98f);
gapTagSprite->setPosition(Vec2(SCREEN_WIDTH / 2,winSize.height*0.65f + 40 + upMove));//上移40
this->addChild(gapTagSprite,1);
//线
//Sprite *gap1 = Sprite::createWithSpriteFrame(spriteFrame("room_12.png"));
//gap1->setAnchorPoint(Vec2(0, 1));
//gap1->setPosition(Vec2(0, gapTagSprite->getPositionY() - gapTagSprite->getContentSize().height - 15));
//this->addChild(gap1, 1);
//增加外框
Scale9Sprite *sptTableBack = Scale9Sprite::createWithSpriteFrame(spriteFrame("beting03.png"));
sptTableBack->setAnchorPoint(Vec2(0.5f, 0.5f));
sptTableBack->setPosition(Vec2(SCREEN_WIDTH / 2, (gapTagSprite->getPositionY() + 120 + gapTagSprite->getContentSize().height) / 2)); //设置位置
sptTableBack->setScaleX((gapTagSprite->getContentSize().width + 20) / sptTableBack->getContentSize().width);
sptTableBack->setScaleY((gapTagSprite->getPositionY() - 120 + 20) / sptTableBack->getContentSize().height);
this->addChild(sptTableBack, 0);
//追号表格
cocos2d::Size tableViewSize;
tableViewSize.width = gapTagSprite->getContentSize().width + 10;
tableViewSize.height = gapTagSprite->getPositionY() - 50 - 120 - 4 - gapTagSprite->getContentSize().height;//tableViewSize.height = winSize.height*0.65 - 170;;
touZhuTable = TableView::create(this, tableViewSize); //设置可显区域
touZhuTable->setDelegate(this);
touZhuTable->setAnchorPoint(Vec2(0, 0));
touZhuTable->setPosition(Vec2(12, 120 + upMove + 50)); //设置位置
//touZhuTable->setPosition(sptTableBack->getPosition());//校正位置
touZhuTable->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN);
touZhuTable->setDirection(ScrollView::Direction::VERTICAL);
touZhuTable->retain();
this->addChild(touZhuTable, 1);
//touZhuTable->setVisible(false);
#ifndef VER_369
//底部背景
Sprite *bottomBk = Sprite::createWithSpriteFrame(spriteFrame("room_12_2.png"));
bottomBk->setPosition(Vec2(SCREEN_WIDTH/2, 60));
bottomBk->setScaleX(SCREEN_WIDTH / bottomBk->getContentSize().width);
bottomBk->setScaleY(120/bottomBk->getContentSize().height);
//bottomBk->setColor(ccc3(50,50,50));
this->addChild(bottomBk,2);
#endif
//确定 取消
Sprite *StramNormalImage_1 = Sprite::createWithSpriteFrame(spriteFrame("beting22.png"));
Sprite *StramNormalImage_2 = Sprite::createWithSpriteFrame(spriteFrame("beting23.png"));
Sprite *CloseNormalImage_1 = Sprite::createWithSpriteFrame(spriteFrame("beting24.png"));
Sprite *CloseNormalImage_2 = Sprite::createWithSpriteFrame(spriteFrame("beting25.png"));
StramItem = MenuItemSprite::create(StramNormalImage_1,StramNormalImage_2,CC_CALLBACK_1(BJK8ChaseNumBerLayer::betRecord,this));
CloseItem = MenuItemSprite::create(CloseNormalImage_1,CloseNormalImage_2,CC_CALLBACK_1(BJK8ChaseNumBerLayer::ZhuiHaoCloseButton,this));
StramMenu2 = Menu::create(CloseItem,StramItem,NULL);
StramMenu2->setPosition(Vec2(winSize.width*0.5,60));
StramMenu2->alignItemsHorizontallyWithPadding(150);
this->addChild(StramMenu2,2);
}
//top menu
void BJK8ChaseNumBerLayer::setting(Object* obj)
{
playButtonSound();
LotterySettingView *layer = LotterySettingView::create();
Scene *scene = Scene::create();
scene->addChild(layer);
Director::getInstance()->replaceScene(scene);
}
void BJK8ChaseNumBerLayer::back(Object *obj)
{
playButtonSound();
this->setPositionY(2000);
NotificationCenter::getInstance()->postNotification("ChaseNumBerItem");
}
//transaction menu
void BJK8ChaseNumBerLayer::recharge(Object* obj)
{
}
void BJK8ChaseNumBerLayer::withdraw(Object *obj)
{
}
void BJK8ChaseNumBerLayer::ZhuiHaoCloseButton(Object *obj)
{
this->setPositionY(2000);
NotificationCenter::getInstance()->postNotification("ChaseNumBerItem");
}
//record menu
void BJK8ChaseNumBerLayer::changeKind(Object *obj)
{
String *GDselectQiShuString = (String *)obj;
GDselectedItemTagNumber = atof(GDselectQiShuString->getCString());
//touZhuTable->reloadData();
}
void BJK8ChaseNumBerLayer::ShowZhuiHaoMen()
{
pCloseButton->setEnabled(true);
CtratebeilvInput->setEnabled(true);
recordMenu->setEnabled(true);
recordMenu2->setEnabled(true);
StramMenu2->setEnabled(true);
//tempItemInpu->setEnabled(true);
middleMenu->setEnabled(true);
}
void BJK8ChaseNumBerLayer::dissZhuiHaoMen()
{
pCloseButton->setEnabled(false);
CtratebeilvInput->setEnabled(false);
recordMenu->setEnabled(false);
recordMenu2->setEnabled(false);
StramMenu2->setEnabled(false);
//tempItemInpu->setEnabled(false);
middleMenu->setEnabled(false);
}
void BJK8ChaseNumBerLayer::TouZhuZhuiHaoButton(Object *obj)
{
if(MyBetNumber::getInstance()->size() == 0) return;
nMoshiNumber = 0.0f;
for(int i = 0;i < MyBetNumber::getInstance()->size();i ++)
nMoshiNumber += MyBetNumber::getInstance()->getItem(i).getBetMoney();
float ZhangHuYuENumber = EntityMgr::instance()->getDispatch()->f_yue;
char szBuf2[100] = {0};
sprintf(szBuf2, "%.3f ",ZhangHuYuENumber);
String *TouZhuYuEString = String::createWithFormat("%s %s%s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t3"),szBuf2,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
string nMoshiString = CtratebeilvInput->getText();
int nBeiShu = atoi(nMoshiString.c_str());
//总共金额
float temp=0;
for(int index = 0 ; index < zhuiHaoQiShu ; index++)
{
if( chaseStatus[index]==1){
if(BeiTouBool ==0){
chaseInputStatus[index] = nBeiShu;
}else{
chaseInputStatus[index+1]= chaseInputStatus[index]*2;
if(chaseInputStatus[index+1]>MAX_ZHUIHAO_BEISHU)
{
chaseInputStatus[index+1] = MAX_ZHUIHAO_BEISHU;
}}
chaseStatus[index]=1;
chaseInputMonreny[index] = nMoshiNumber*chaseInputStatus[index];
temp += chaseInputMonreny[index];
}}
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",temp);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
TouZhuJinEChaseNumBerLabel->setString(TouZhuJinECherString->getCString());
touZhuTable->reloadData();
}
void BJK8ChaseNumBerLayer::betRecord(Object *obj)
{
playButtonSound();
if (MyBetNumber::getInstance()->size() == 0) return;
bool bRet = EntityMgr::instance()->getDispatch()->connectLoginServer();
if(!bRet)
{
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(ConfigMgr::instance()->text("display_DuangDong.xml", "t167"),
Vec2(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
}else{
//判断是否在封单
NotificationCenter::getInstance()->postNotification("IsFendanHour");
}
}
void BJK8ChaseNumBerLayer::IsFendanHourRet(Object *obj)
{
Bool* isFendan = (Bool *)obj;
//封单
if(isFendan->getValue())
{
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(ConfigMgr::instance()->text("display_DuangDong.xml", "t8"),
Vec2(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
return;
}
float TouZhuJinE =0;
char qiShu[MAX_QIHAO][20] = {0};
int beiShu[MAX_QIHAO]={0};
int totalQiShu = 0;
string nMoshiString = CtratebeilvInput->getText();
int nbeiShu = atoi(nMoshiString.c_str());
if(nbeiShu < 1) nbeiShu = 1;
if(ZhuiHao != 2)
{
MyBetNumber::addRandSeed();
ZhuiHao = rand() % 6000 + 4;
}
MyBetNumber::getInstance()->betReady();
//追号投注开始
for(int id = 0;id < MyBetNumber::getInstance()->size();id ++)
{
Bet_Info tempInfo = MyBetNumber::getInstance()->getItem(id);
for(int i = 0 ; i < zhuiHaoQiShu ; i++){
if(chaseStatus[i] == 1){
totalQiShu++;
beiShu[i] = chaseInputStatus[i] * tempInfo.m_betPlus->getValue();
sprintf(qiShu[i], "%lld",BetLimit::getRealQihao(GDselectedItemTagNumber+i, tempInfo.m_gameKind->getValue(),GDselectedItemTagNumber));
TouZhuJinE+=chaseInputMonreny[i];
}
}
if(TouZhuJinE == 0) return;
EntityMgr::instance()->getDispatch()->SendPacketWithTouZhuCQSSC_ZhioHao(zhuiHaoQiShu, qiShu, tempInfo.m_gameKind->getValue(), BetLimit::GetWanfaIdFromId(tempInfo.m_wanFaKind->getValue(),5),
tempInfo.m_betNumber->getCString(), tempInfo.m_betCount->getValue(), beiShu, tempInfo.m_mode->getValue(), nbeiShu, 0, ZhuiHao, 0);
}
this->setPositionY(2000);
NotificationCenter::getInstance()->postNotification("ZhuiHaobackCHongQIN");
NotificationCenter::getInstance()->postNotification("ZhuiHaoTouZhuJinENumber",Float::create(TouZhuJinE));
}
void BJK8ChaseNumBerLayer::touZhuContinueRet(Object *obj)
{
Array *data = (Array *)obj;
Integer *lResult = (Integer *)data->objectAtIndex(0);
String *resultDesc = (String *)data->objectAtIndex(1);
Integer *nSign = (Integer *)data->objectAtIndex(2);
//计数
MyBetNumber::getInstance()->setRetType(lResult->getValue());
if(!MyBetNumber::getInstance()->isEndBet()) return;
int returnType = MyBetNumber::getInstance()->getRetType();
playButtonSound();
if(returnType == 0){
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(ConfigMgr::instance()->text("display_text.xml", "t180"),
Vec2(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
}
else if(returnType > 0 && returnType <= 18)
{
int nTempType=returnType;
//from T200 to T208
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(ConfigMgr::instance()->text("display_text.xml", String::createWithFormat("t%ld", 200+ nTempType)->getCString()),
Vec2(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
}
else if(returnType == 111)
{
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(ConfigMgr::instance()->text("display_text.xml", "t717"),
Vec2(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
}else if(returnType > 18){
int temp = 1900 + lResult->getValue() * 2;
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(String::createWithFormat("%s%d%s",
ConfigMgr::instance()->text("display_text.xml", "t718"),
temp,
ConfigMgr::instance()->text("display_text.xml", "t719"))->getCString(),
ccp(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
}else{
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(ConfigMgr::instance()->text("display_text.xml", "t182"),
Vec2(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
}
this->setPositionY(2000);
NotificationCenter::getInstance()->postNotification("RemoveCurrentLayer");
EntityMgr::instance()->getDispatch()->SendPacketWithGetLastYue();
}
void BJK8ChaseNumBerLayer::ZhuiHaoQiShuRecord(Object *obj)
{
}
void BJK8ChaseNumBerLayer::contiRecord(Object *obj)
{
}
void BJK8ChaseNumBerLayer::onEnter()
{
Layer::onEnter();
}
void BJK8ChaseNumBerLayer::onExit()
{
Layer::onExit();
}
void BJK8ChaseNumBerLayer::onKeyReleased(EventKeyboard::KeyCode keycode, Event *event)
{
//if (keycode == EventKeyboard::KeyCode::KEY_BACK) //返回
//{
// back(NULL);
// event->stopPropagation();
//}
}
cocos2d::Size BJK8ChaseNumBerLayer::cellSizeForTable(TableView *table)
{
cocos2d::Size size;
size.width = winSize.width;
int tag = dynamic_cast<Node*>(table)->getTag();
if(tag == 1111){size.height = 50;}
else{size.height = 50;}
return size;
}
ssize_t BJK8ChaseNumBerLayer::numberOfCellsInTableView(TableView *table)
{
int tag = dynamic_cast<Node*>(table)->getTag();
if(tag == 1111){return 5;}
else{return zhuiHaoQiShu;}
}
TableViewCell *BJK8ChaseNumBerLayer::tableCellAtIndex(TableView *table,ssize_t index)
{
static const char * cellIdentifier = "cell-identifier";
TableViewCell *cell = new TableViewCell();
cell->autorelease();
//没有值
if(MyBetNumber::getInstance()->size() == 0) return cell;
ZhuiHao11Xuan5KIsShowQiShu = false;
int tag = dynamic_cast<Node*>(table)->getTag();
if(tag == 1111){
cell->setTag(index);
int value = 5.0;
value+=5*index;
char str[4] = {0};
sprintf(str, "%d", value);
LabelTTF *label = LabelTTF::create(str, "", 22);
label->setAnchorPoint(Vec2(0,0.5f));
label->setPosition(Vec2(10, cellHeight*2/3));
label->setColor(ccc3(0,0,0));
cell->addChild(label, 3);
return cell;
}else {
float gap = 15;
float textWidth = 600;
float fontSize = 27;
string nMoshiString = CtratebeilvInput->getText();
int nBeiShu = atoi(nMoshiString.c_str());
QuanJunBeiShu =nBeiShu;
ccColor3B redColor = ccc3(61,8,40);
ccColor3B blackColor = ccc3(0,0,0);
LabelTTF *normalttf;
CCMenuItem *betemRecordItem;
Sprite *betRecordNormalImage_1;
Sprite *betRecordNormalImage_2;
auto tempItemInpu1 = EditBox::create(cocos2d::Size(80, 32), "beting26.png");
tempItemInpu1->setPosition(Vec2(gap,cellHeight/2));
tempItemInpu1->setInputFlag(ui::EditBox::InputFlag::INITIAL_CAPS_SENTENCE);
tempItemInpu1->setReturnType(ui::EditBox::KeyboardReturnType::DONE);
tempItemInpu1->setAnchorPoint(Vec2(0,0.5f));
tempItemInpu1->setFontColor(ccc3(0,0,0));
tempItemInpu1->setFontName("");tempItemInpu1->setFontSize(fontSize);
tempItemInpu1->setColor(ccc3(112,112,112));
tempItemInpu1->setMaxLength(30);
tempItemInpu1->setTag(index);
tempItemInpu1->setInputMode(ui::EditBox::InputMode::NUMERIC);
tempItemInpu1->setText(String::createWithFormat("%d", chaseInputStatus[index])->getCString());
//tempItemInpu1->setDelegate(this);
cell->addChild(tempItemInpu1, 2);
tempItemInpu1->addClickEventListener([=](Ref *){tempItemInpu = tempItemInpu1;});
//期号
normalttf = LabelTTF::create(String::createWithFormat("%lld",BetLimit::getRealQihao(GDselectedItemTagNumber+index,MyBetNumber::getInstance()->getItem(0).m_gameKind->getValue(),GDselectedItemTagNumber))->getCString(),"",fontSize);
normalttf->setColor(blackColor);
normalttf->setAnchorPoint(Vec2(1,0.5f));
normalttf->setPosition(Vec2(320, cellHeight/2));//280
cell->addChild(normalttf, 2);
//金额
tempIttf = LabelTTF::create(String::createWithFormat("%.3f",chaseInputMonreny[index])->getCString(),"",fontSize);
tempIttf->setColor(blackColor);
tempIttf->setAnchorPoint(Vec2(1,0.5f));
tempIttf->setPosition(Vec2(470,cellHeight/2));
cell->addChild(tempIttf, 2);
//选择期数
Sprite *XuanZeQiShuNormalImage;
Sprite *XuanZeQiShuSelectedImage;
if(chaseStatus[index] == 0){
XuanZeQiShuNormalImage = Sprite::createWithSpriteFrame(spriteFrame("beting27.png"));
XuanZeQiShuSelectedImage = Sprite::createWithSpriteFrame(spriteFrame("beting27.png"));
}else{
XuanZeQiShuNormalImage = Sprite::createWithSpriteFrame(spriteFrame("beting28.png"));
XuanZeQiShuSelectedImage = Sprite::createWithSpriteFrame(spriteFrame("beting28.png"));
}
XuanZeQiShuItem = MenuItemSprite::create(XuanZeQiShuNormalImage,XuanZeQiShuSelectedImage,CC_CALLBACK_1(BJK8ChaseNumBerLayer::XuanZeQiShu,this));
XuanZeQiShuItem->setTag(index);
middleMenu = Menu::create(XuanZeQiShuItem,NULL);
middleMenu->setPosition(Vec2(640,cellHeight/2)); //600
cell->addChild(middleMenu,2);
//较正位置
#ifdef VER_369
tempItemInpu1->setPositionY(tempItemInpu1->getPositionY() + 10);
normalttf->setPositionY(normalttf->getPositionY() + 10);
tempIttf->setPositionY(tempIttf->getPositionY() + 10);
middleMenu->setPositionY(middleMenu->getPositionY() + 10);
#endif
//增加背景色
if (index % 2 == 0)
{
Sprite *cellBack = Sprite::createWithSpriteFrame(spriteFrame("room_12_2.png"));
cellBack->setAnchorPoint(Vec2(0,0.5));
cellBack->setPosition(Vec2(10,cellHeight/2));
cellBack->setOpacity(100);
cellBack->setScaleX(SCREEN_WIDTH / cellBack->getContentSize().width);
cellBack->setScaleY(50 / cellBack->getContentSize().height);
cell->addChild(cellBack,1);
#ifdef VER_369
cellBack->setVisible(false);
//新的背景
Sprite *cellBack1 = Sprite::createWithSpriteFrame(spriteFrame("beting19_3.png"));
cellBack1->setAnchorPoint(Vec2(0,0.5));
cellBack1->setPosition(Vec2(10,cellHeight/2 + 10));
cellBack1->setScaleY(45 / cellBack1->getContentSize().height);
cell->addChild(cellBack1,1);
#endif
} else
{
#ifdef VER_369
Sprite *cellBack = Sprite::createWithSpriteFrame(spriteFrame("beting19_2.png"));
cellBack->setAnchorPoint(Vec2(0,0.5));
cellBack->setPosition(Vec2(10,cellHeight/2 + 10));
cellBack->setScaleY(45 / cellBack->getContentSize().height);
cell->addChild(cellBack,1);
#endif
}
return cell;
}
}
void BJK8ChaseNumBerLayer::tableCellTouched(TableView *table, TableViewCell *cell)
{
if(table->getTag() != 1111) return;
//点击
XuanZeZhuiHaoQiShu(nullptr);
int cellTag = cell->getTag();
int value = 5.0;
if(cellTag <0)
{
string beilvInputString = beilvInput->getText();
value = atoi(beilvInputString.c_str());
}else{
value+=5*cellTag;
}
char valueStr[10] = {0};
sprintf(valueStr, "%d", value);
beilvInput->setText(valueStr);
m_TableNode->setPosition(Vec2(1000,1000));
this->ShowZhuiHaoMen();
zhuiHaoQiShu = value;
string nMoshiString = CtratebeilvInput->getText();
int nBeiShu = atoi(nMoshiString.c_str());
float temp =0;
for(int index =0;index<zhuiHaoQiShu;index++)
{
chaseInputStatus[index]=nBeiShu;
chaseInputMonreny[index] =chaseInputStatus[index]*nMoshiNumber*betZhuiHaoZhuShu;
temp += chaseInputMonreny[index];
chaseStatus[index] =1;
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",temp);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
TouZhuJinEChaseNumBerLabel->setString(TouZhuJinECherString->getCString());
}
if(BeiTouBool ==1)
{
float tempBUn =0;
if(nBeiShu !=1)
{
chaseInputStatus[0] = nBeiShu;
}
for(int i = 0 ; i < zhuiHaoQiShu ; i++)
{
if(nBeiShu !=1)
{
chaseInputStatus[i+1]= chaseInputStatus[i]*2;
}else
{
chaseInputStatus[i+1]= chaseInputStatus[i]*2;
CCLOG("%d",chaseInputStatus[i+1]);
}
if(chaseInputStatus[i+1]>MAX_ZHUIHAO_BEISHU)
{
chaseInputStatus[i+1] = MAX_ZHUIHAO_BEISHU;
}
chaseStatus[i]=1;
chaseInputMonreny[i] = chaseInputStatus[i]*nMoshiNumber*betZhuiHaoZhuShu;
CCLOG("MonENy == %d",chaseInputMonreny[i]);
tempIttf ->setString(String::createWithFormat("%.3f",chaseInputMonreny[i])->getCString());
temp += chaseInputMonreny[i];
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",temp);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
TouZhuJinEChaseNumBerLabel->setString(TouZhuJinECherString->getCString());
}
}
ZhuiHaoQiShuBool = false;
touZhuTable->reloadData();
}
void BJK8ChaseNumBerLayer::scrollViewDidScroll(ScrollView* view)
{
}
void BJK8ChaseNumBerLayer::scrollViewDidZoom(ScrollView* view)
{
}
void BJK8ChaseNumBerLayer::XuanZeQiShu(Object *obj)
{
playButtonSound();
MenuItemSprite *XuanZeQiShuItem = (MenuItemSprite *)obj;
int itemTag = XuanZeQiShuItem->getTag();
if(chaseStatus[itemTag] == 0)
{
chaseStatus[itemTag] = 1;
Sprite *XuanZeQiShuNormalImage = Sprite::createWithSpriteFrame(spriteFrame("beting28.png"));
Sprite *XuanZeQiShuSelectedImage = Sprite::createWithSpriteFrame(spriteFrame("beting28.png"));
XuanZeQiShuItem->setNormalImage(XuanZeQiShuNormalImage);
XuanZeQiShuItem->setSelectedImage(XuanZeQiShuSelectedImage);
}else
{
chaseStatus[itemTag] = 0;
Sprite *XuanZeQiShuNormalImage = Sprite::createWithSpriteFrame(spriteFrame("beting27.png"));
Sprite *XuanZeQiShuSelectedImage = Sprite::createWithSpriteFrame(spriteFrame("beting27.png"));
XuanZeQiShuItem->setNormalImage(XuanZeQiShuNormalImage);
XuanZeQiShuItem->setSelectedImage(XuanZeQiShuSelectedImage);
}
float temp=0;
int temp2 =0;
//计算追号
for(int i =0;i<zhuiHaoQiShu;i++)
{
if(chaseStatus[i]==1)
{
chaseInputMonreny[i] =chaseInputStatus[i]*nMoshiNumber*betZhuiHaoZhuShu;
temp += chaseInputMonreny[i];
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",temp);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
TouZhuJinEChaseNumBerLabel->setString(TouZhuJinECherString->getCString());
}
temp2 +=chaseStatus[i];
if(temp2 ==0)
{
temp =0;
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",temp);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
TouZhuJinEChaseNumBerLabel->setString(TouZhuJinECherString->getCString());
}
}
}
void BJK8ChaseNumBerLayer::XuanZeZhuiHaoQiShu(Object *obj)
{
playButtonSound();
//MenuItemSprite *ButtonCodeRecordItem = (MenuItemSprite *)obj;
if (fandianStatus != 0)
{
fandianStatus = 0;
//ButtonCodeRecordItem->unselected();
m_TableNode->setPosition(Vec2(1000,1000));
this->ShowZhuiHaoMen();
betRecordItem->setEnabled(true);
touZhuTable->setTouchEnabled(true);
return;
}
//ButtonCodeRecordItem->selected();
fandianStatus = 2;
m_TableNode->setPosition(Vec2(winSize.width*0.2+2,winSize.height*0.6-3));
this->dissZhuiHaoMen();
betRecordItem->setEnabled(false);
touZhuTable->setTouchEnabled(false);
fandianTable->reloadData();
}
void BJK8ChaseNumBerLayer::IsEndeBeiTou(Object *obj)
{
playButtonSound();
MenuItemSprite *betRecordItem = (MenuItemSprite *)obj;
string nMoshiString = CtratebeilvInput->getText();
int nBeiShu = atoi(nMoshiString.c_str());
float temp = 0;
if(BeiTouBool==0)
{
BeiTouBool = 1;
Sprite *StramNormalImage_1 = Sprite::createWithSpriteFrame(spriteFrame("beting15.png"));
Sprite *StramNormalImage_2 = Sprite::createWithSpriteFrame(spriteFrame("beting15.png"));
betRecordItem->setNormalImage(StramNormalImage_1);
betRecordItem->setSelectedImage(StramNormalImage_2);
if(nBeiShu !=1)
{
chaseInputStatus[0] = nBeiShu;
}
for(int i = 0 ; i < zhuiHaoQiShu ; i++)
{
if(nBeiShu !=1)
{
chaseInputStatus[i+1]= chaseInputStatus[i]*2;
}else
{
chaseInputStatus[i+1]= chaseInputStatus[i]*2;
}
if(chaseInputStatus[i+1]>MAX_ZHUIHAO_BEISHU)
{
chaseInputStatus[i+1] = MAX_ZHUIHAO_BEISHU;
}
if(chaseStatus[i]==1){
chaseInputMonreny[i] = chaseInputStatus[i]*nMoshiNumber*betZhuiHaoZhuShu;
tempIttf ->setString(String::createWithFormat("%.3f",chaseInputMonreny[i])->getCString());
temp += chaseInputMonreny[i];
}
}
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",temp);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
TouZhuJinEChaseNumBerLabel->setString(TouZhuJinECherString->getCString());
touZhuTable->reloadData();
}else
{
BeiTouBool = 0;
Sprite *StramNormalImage_1 = Sprite::createWithSpriteFrame(spriteFrame("beting16.png"));
Sprite *StramNormalImage_2 = Sprite::createWithSpriteFrame(spriteFrame("beting16.png"));
betRecordItem->setNormalImage(StramNormalImage_1);
betRecordItem->setSelectedImage(StramNormalImage_2);
for(int i = 0 ; i < zhuiHaoQiShu ; i++)
{
if(nBeiShu !=1)
{
chaseInputStatus[i]= nBeiShu;
}else
{chaseInputStatus[i+1]= 1;
}
if(chaseStatus[i]==1){
chaseInputMonreny[i] = chaseInputStatus[i]*nMoshiNumber*betZhuiHaoZhuShu;
tempIttf ->setString(String::createWithFormat("%.3f",chaseInputMonreny[i])->getCString());
temp += chaseInputMonreny[i];
}
}
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",temp);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
TouZhuJinEChaseNumBerLabel->setString(TouZhuJinECherString->getCString());
touZhuTable->reloadData();
}
}
void BJK8ChaseNumBerLayer::IsEndeZhuiHao(Object *obj)
{
playButtonSound();
MenuItemSprite *GetRecordItem = (MenuItemSprite *)obj;
if(ZhuiHaoBool == 0)
{
ZhuiHaoBool = 1;
ZhuiHao =2;
Sprite *CloseNormalImage_1 = Sprite::createWithSpriteFrame(spriteFrame("beting16.png"));
Sprite *CloseNormalImage_2 = Sprite::createWithSpriteFrame(spriteFrame("beting16.png"));
GetRecordItem->setNormalImage(CloseNormalImage_1);
GetRecordItem->setSelectedImage(CloseNormalImage_2);
}else
{
ZhuiHaoBool = 0;
ZhuiHao = 4;
Sprite *CloseNormalImage_1 = Sprite::createWithSpriteFrame(spriteFrame("beting15.png"));
Sprite *CloseNormalImage_2 = Sprite::createWithSpriteFrame(spriteFrame("beting15.png"));
GetRecordItem->setNormalImage(CloseNormalImage_1);
GetRecordItem->setSelectedImage(CloseNormalImage_2);
}
}
void BJK8ChaseNumBerLayer::editBoxEditingDidEnd(EditBox* editBox)
{
string nMoshiString = CtratebeilvInput->getText();
int nBeiShu = atoi(nMoshiString.c_str());
if(nBeiShu < 1)
{
nBeiShu = 1;
CtratebeilvInput->setText("1");
}
int boxTag = editBox->getTag();
string beilvInputString = beilvInput->getText();
int nbeilvIn = atoi(beilvInputString.c_str());
zhuiHaoQiShu =nbeilvIn;
if(zhuiHaoQiShu > MAX_QIHAO)
{
String* displayStr = String::createWithFormat("%s%d%s",ConfigMgr::instance()->text("display_text.xml", "t994"),MAX_QIHAO,ConfigMgr::instance()->text("display_text.xml", "t71"));
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(displayStr->getCString(),
Vec2(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
beilvInput->setText("50");
zhuiHaoQiShu = MAX_QIHAO;
}
if(nBeiShu > MAX_ZHUIHAO_BEISHU)
{
nBeiShu = MAX_ZHUIHAO_BEISHU;
CtratebeilvInput->setText("999");
}
if(QuanJunBeiShu !=nBeiShu)
{
if(nBeiShu !=1)
{
chaseInputStatus[0] = nBeiShu;
}
for(int i =0;i<zhuiHaoQiShu;i++)
{
if(BeiTouBool ==0)
{
chaseInputStatus[i] = nBeiShu;
}else{
chaseInputStatus[i+1]= chaseInputStatus[i]*2;
if(chaseInputStatus[i+1]>MAX_ZHUIHAO_BEISHU)
{
chaseInputStatus[i+1] = MAX_ZHUIHAO_BEISHU;
}
}
chaseStatus[i]=1;
}
}else if(boxTag < 0&&BeiTouBool==0)
{
for(int index =0;index<zhuiHaoQiShu;index++){
chaseStatus[index]=1;
chaseInputStatus[index]=nBeiShu;
}
}
else{
chaseInputStatus[boxTag] = (atoi(editBox->getText()));
if(chaseInputStatus[boxTag] <=0){
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(ConfigMgr::instance()->text("display_DuangDong.xml", "t169"),
Vec2(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
chaseInputStatus[boxTag] = 1;
return;
}else if(chaseInputStatus[boxTag]>MAX_ZHUIHAO_BEISHU){
MovingLabelLayer* layer = MovingLabelLayer::MovingLabelLayerWith(
String::createWithFormat("%s%d%s",ConfigMgr::instance()->text("display_DuangDong.xml", "t170"),MAX_ZHUIHAO_BEISHU,ConfigMgr::instance()->text("display_DuangDong.xml", "t199"))->getCString(),
Vec2(winSize.width * 0.5,winSize.height * 0.5));
this->addChild(layer, 255);
chaseInputStatus[boxTag] = 1;
editBox->setText("1");
return;
}
}
float temp=0;
for(int i =0;i<zhuiHaoQiShu;i++)
{
if(chaseStatus[i]==1){
chaseInputMonreny[i] =chaseInputStatus[i]*nMoshiNumber*betZhuiHaoZhuShu;
tempIttf ->setString(String::createWithFormat("%.3f",chaseInputMonreny[i])->getCString());
temp += chaseInputMonreny[i];
}
}
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",temp);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
TouZhuJinEChaseNumBerLabel->setString(TouZhuJinECherString->getCString());
if(BaoCunQiShu != nbeilvIn&&BeiTouBool==1)
{
BaoCunQiShu = nbeilvIn;
zhuiHaoQiShu = nbeilvIn;
float tempBUn =0;
if(nBeiShu !=1)
{
chaseInputStatus[0] = nBeiShu;
}
for(int i = 0 ; i < zhuiHaoQiShu ; i++)
{
if(nBeiShu !=1)
{
chaseInputStatus[i+1]= chaseInputStatus[i]*2;
}else
{
chaseInputStatus[i+1]= chaseInputStatus[i]*2;
CCLOG("%d",chaseInputStatus[i+1]);
}
if(chaseInputStatus[i+1]>MAX_ZHUIHAO_BEISHU)
{
chaseInputStatus[i+1] = MAX_ZHUIHAO_BEISHU;
}
chaseStatus[i]=1;
chaseInputMonreny[i] = chaseInputStatus[i]*nMoshiNumber*betZhuiHaoZhuShu;
CCLOG("MonENy == %d",chaseInputMonreny[i]);
tempIttf ->setString(String::createWithFormat("%.3f",chaseInputMonreny[i])->getCString());
temp += chaseInputMonreny[i];
char szBuf[100] = {0};
sprintf(szBuf, "%.3f ",temp);
String *TouZhuJinECherString = String::createWithFormat("%s %s %s",
ConfigMgr::instance()->text("display_DuangDong.xml", "t1"),szBuf,
ConfigMgr::instance()->text("display_DuangDong.xml", "t2"));
TouZhuJinEChaseNumBerLabel->setString(TouZhuJinECherString->getCString());
}
}
touZhuTable->reloadData();
} | [
"hanshouqing85@163.com"
] | hanshouqing85@163.com |
93405aabf5d7d2f92a132b7272fdfccd546043bb | 7e5be101928eb7ea43bc1a335d3475536f8a5bb2 | /2016 Training/3.30/A.cpp | 7a035319c2f72a45fded76f6ad4f7ab3951ae34f | [] | no_license | TaoSama/ICPC-Code-Library | f94d4df0786a8a1c175da02de0a3033f9bd103ec | ec80ec66a94a5ea1d560c54fe08be0ecfcfc025e | refs/heads/master | 2020-04-04T06:19:21.023777 | 2018-11-05T18:22:32 | 2018-11-05T18:22:32 | 54,618,194 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 866 | cpp | //
// Created by TaoSama on 2016-03-30
// Copyright (c) 2016 TaoSama. All rights reserved.
//
#pragma comment(linker, "/STACK:102400000,102400000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
int main() {
#ifdef LOCAL
freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
// freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
long long x;
while(scanf("%lld", &x) == 1) {
printf("%lld\n", x - 1);
}
return 0;
}
| [
"lwt1367@gmail.com"
] | lwt1367@gmail.com |
673c75dbb74c2f6861c556ad3e3e0465bda9f0cf | e51d009c6c6a1633c2c11ea4e89f289ea294ec7e | /xr2-dsgn/sources/xray/editor/world/sources/tool_particle.h | f8aee8bbd637463cdd919a230e880f267e41e216 | [] | no_license | avmal0-Cor/xr2-dsgn | a0c726a4d54a2ac8147a36549bc79620fead0090 | 14e9203ee26be7a3cb5ca5da7056ecb53c558c72 | refs/heads/master | 2023-07-03T02:05:00.566892 | 2021-08-06T03:10:53 | 2021-08-06T03:10:53 | 389,939,196 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | h | ////////////////////////////////////////////////////////////////////////////
// Created : 19.08.2010
// Author : Andrew Kolomiets
// Copyright (C) GSC Game World - 2010
////////////////////////////////////////////////////////////////////////////
#ifndef TOOL_PATRICLE_H_INCLUDED
#define TOOL_PATRICLE_H_INCLUDED
#include "tool_base.h"
namespace xray {
namespace editor {
ref class solid_visual_tool_tab;
public ref class tool_particle :public tool_base
{
typedef tool_base super;
public:
tool_particle ( level_editor^ le );
virtual ~tool_particle ( );
virtual object_base^ load_object ( configs::lua_config_value const& t, render::scene_ptr const& scene, render::scene_view_ptr const& scene_view ) override;
virtual object_base^ create_library_object_instance ( System::String^ name, render::scene_ptr const& scene, render::scene_view_ptr const& scene_view ) override;
virtual void destroy_object ( object_base^ o ) override;
virtual tool_tab^ ui ( ) override;
void load_library ( );
virtual void initialize ( ) override;
private:
object_base^ create_raw_object ( System::String^ id, render::scene_ptr const& scene );
void process_recursive_names ( vfs::vfs_iterator const & it, System::String^ path );
void on_library_fs_iterator_ready( vfs::vfs_locked_iterator const & fs_it );
solid_visual_tool_tab^ m_tool_tab;
}; // class tool_solid_visual
} // namespace editor
} // namespace xray
#endif // #ifndef TOOL_PATRICLE_H_INCLUDED | [
"youalexandrov@icloud.com"
] | youalexandrov@icloud.com |
8bab03f86e85bc80eabe13c10b9f6c8759eb1ab1 | 45d300db6d241ecc7ee0bda2d73afd011e97cf28 | /OTCDerivativesCalculatorModule/Project_Cpp/lib_static/xmlFactory/GenClass/RiskMonitor-0-1/OrEventCal.cpp | 91de95f92d8bec1e61829347a4f498d7af7efec7 | [] | no_license | fagan2888/OTCDerivativesCalculatorModule | 50076076f5634ffc3b88c52ef68329415725e22d | e698e12660c0c2c0d6899eae55204d618d315532 | refs/heads/master | 2021-05-30T03:52:28.667409 | 2015-11-27T06:57:45 | 2015-11-27T06:57:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,273 | cpp | // OrEventCal.cpp
#include "OrEventCal.hpp"
#ifdef ConsolePrint
#include <iostream>
#endif
namespace FpmlSerialized {
OrEventCal::OrEventCal(TiXmlNode* xmlNode)
: ISerialized(xmlNode)
{
#ifdef ConsolePrint
std::string initialtap_ = FileManager::instance().tap_;
FileManager::instance().tap_.append(" ");
#endif
//eventCalculationListNode ----------------------------------------------------------------------------------------------------------------------
TiXmlElement* eventCalculationListNode = xmlNode->FirstChildElement("eventCalculationList");
if(eventCalculationListNode){eventCalculationListIsNull_ = false;}
else{eventCalculationListIsNull_ = true;}
#ifdef ConsolePrint
FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- eventCalculationListNode , address : " << eventCalculationListNode << std::endl;
#endif
if(eventCalculationListNode)
{
eventCalculationList_ = boost::shared_ptr<EventCalculationList>(new EventCalculationList(eventCalculationListNode));
}
//complementNode ----------------------------------------------------------------------------------------------------------------------
TiXmlElement* complementNode = xmlNode->FirstChildElement("complement");
if(complementNode){complementIsNull_ = false;}
else{complementIsNull_ = true;}
#ifdef ConsolePrint
FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- complementNode , address : " << complementNode << std::endl;
#endif
if(complementNode)
{
complement_ = boost::shared_ptr<XsdTypeBoolean>(new XsdTypeBoolean(complementNode));
}
#ifdef ConsolePrint
FileManager::instance().tap_ = initialtap_;
#endif
}
boost::shared_ptr<EventCalculationList> OrEventCal::getEventCalculationList()
{
if(!this->eventCalculationListIsNull_){
return this->eventCalculationList_;
}else
{
QL_FAIL("null Ptr");
return boost::shared_ptr<EventCalculationList>();
}
}
boost::shared_ptr<XsdTypeBoolean> OrEventCal::getComplement()
{
if(!this->complementIsNull_){
return this->complement_;
}else
{
QL_FAIL("null Ptr");
return boost::shared_ptr<XsdTypeBoolean>();
}
}
}
| [
"math.ansang@gmail.com"
] | math.ansang@gmail.com |
701e949648446c9a324fab3bd57965196167a9e7 | 295761bc19ac68ca9c111c25d8f867dbcca49fa9 | /src/partitioner/implementation/source/PartitionerParmetisConfigSourceJSON.cpp | 1312865517aa2536ac5a4070cea255597e5bee38 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | warwick-hpsc/CUP-CFD | 2ad95dd291bb5c8dff6080e6df70f4d2b7ebdaa0 | b83b5675eb64a3806bee9096267321840a757790 | refs/heads/master | 2021-12-21T20:09:18.696865 | 2021-12-19T23:37:03 | 2021-12-19T23:37:03 | 241,870,858 | 3 | 1 | MIT | 2021-12-19T23:37:04 | 2020-02-20T11:48:36 | C++ | UTF-8 | C++ | false | false | 1,560 | cpp | /**
* @file
* @author University of Warwick
* @version 1.0
*
* @section LICENSE
*
* @section DESCRIPTION
*
* Class Definition for the PartitionerParmetisConfigSourceJSON class.
*/
// Header for this class
#include "PartitionerParmetisConfigSourceJSON.h"
#include "PartitionerParmetisConfig.h"
// File access for reading into JSON structures
#include <fstream>
namespace cupcfd
{
namespace partitioner
{
// === Constructors/Deconstructors ===
template <class I, class T>
PartitionerParmetisConfigSourceJSON<I,T>::PartitionerParmetisConfigSourceJSON(Json::Value& parseJSON)
{
this->configData = parseJSON;
}
template <class I, class T>
PartitionerParmetisConfigSourceJSON<I,T>::~PartitionerParmetisConfigSourceJSON()
{
// Nothing to do currently
}
// === Concrete Methods ===
template <class I, class T>
cupcfd::error::eCodes PartitionerParmetisConfigSourceJSON<I,T>::buildPartitionerConfig(PartitionerConfig<I,T> ** config)
{
// Since we don't currently load any other options, we can only match on the top level name
// This can be included as a workaround for now in lieu of missing options checks to verify if a valid top level
// name was found (and thus a correct configuration match)
if(this->configData == Json::Value::null)
{
return cupcfd::error::E_CONFIG_OPT_NOT_FOUND;
}
*config = new PartitionerParmetisConfig<I,T>();
return cupcfd::error::E_SUCCESS;
}
}
}
// Explicit Instantiation
template class cupcfd::partitioner::PartitionerParmetisConfigSourceJSON<int,int>;
| [
"a.m.b.owenson@warwick.ac.uk"
] | a.m.b.owenson@warwick.ac.uk |
c486bd63d12e0dba7a3a68359170fd855712dbd8 | b1bf17201149ba0a8b865e425fef5e3369b04260 | /llvm/lib/DebugInfo/PDB/PDBSymbolTypeEnum.cpp | d0e9b0e5825c674b152e72120376d5e1856a577c | [
"NCSA"
] | permissive | cya410/llvm | 788288b9989de58e1b7a05c5ab9490099c7c3920 | a6a751eb63eaea13a427ea33365dade739842453 | refs/heads/master | 2016-09-06T12:38:02.151281 | 2015-03-16T16:09:18 | 2015-03-16T16:09:18 | 30,787,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,131 | cpp | //===- PDBSymbolTypeEnum.cpp - --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeEnum::PDBSymbolTypeEnum(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeEnum::dump(raw_ostream &OS, int Indent,
PDB_DumpLevel Level) const {
OS << stream_indent(Indent);
if (Level >= PDB_DumpLevel::Normal)
OS << "enum ";
uint32_t ClassId = getClassParentId();
if (ClassId != 0) {
if (auto ClassParent = Session.getSymbolById(ClassId)) {
ClassParent->dump(OS, 0, Level);
OS << "::";
}
}
OS << getName();
}
| [
"yanchao2012@gmail.com"
] | yanchao2012@gmail.com |
3f521bc7c1e4aacb3a4cf98cb4de187b6e688f14 | 144ae1682c29661952b8554205b63d22e1c9efad | /include/summer/http/basic.h | a81e0a8682b7f10a6ef977af4836946d57c144c6 | [] | no_license | iceseyes/Summer | a4c832feb77d087c612285b27f03ccb5bf59dd31 | 95b90fac0751e9266d40037e2d9832da145e5db3 | refs/heads/master | 2020-05-19T11:53:53.207687 | 2014-09-05T12:57:08 | 2014-09-05T12:57:08 | 22,332,728 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,811 | h | /*
* summer - summer/http/basic.h
* Author: Massimo Bianchi 2014
*
* Defines basic HTTP entities
*/
#ifndef SUMMER_HTTP_BASIC_HTPP
#define SUMMER_HTTP_BASIC_HTPP
#include <summer/net/URI.h>
#include <boost/asio.hpp>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
/** \namespace summer::http
* \brief summer::http namespace is the module of summer library which defines HTTP protocol.
*
* This module contains all the structure to define the Summer HTTP server.
* To achive this
* 1. Specialize summer::server::Server to handle http::Request and http::Reply.
* 2. Defines basic HTTP RootDispatcher used by generic protocol to dispatch client requests.
* 3. Implements Http Header, Request and Reply and algorithms to parsing Http Request (RequestParser).
*/
namespace summer { namespace http {
struct RequestParser;
/// An HTTP Header.
struct Header {
std::string name; //!< name of header
std::string value; //!< value (as string) of header
/// Default constructor
Header() {}
/// Convert a std::pair<string, string> into a Header
Header(const std::pair<std::string, std::string> &p) : name(p.first), value(p.second) {}
/// An Header is checked by name
bool operator==(const std::string &name) const;
/// Convert a std::pair<string, string> into a Header
Header &operator=(const std::pair<std::string, std::string> &p);
/// A Header can be casted to a std::pair
operator std::pair<std::string, std::string>() const;
};
/// An HTTP Request.
struct Request {
using Headers = std::vector<Header>; //!< a set of Header
using URI = net::URI; //!< URI class
using RequestParser = summer::http::RequestParser; //!< Parser to use.
std::string method; //!< HTTP Method for request
URI uri; //!< URI of request
int http_version_major; //!< HTTP Version
int http_version_minor; //!< HTTP Version
Headers headers; //!< Headers
std::string body; //!< Request body
/// Access to header by name. If header doesn't exist create a new one.
/// @param header [in] header name.
/// @return the corresponding header value
std::string &operator[](const std::string &header);
/// Access to header by name.
/// @param header [in] header name.
/// @return the corresponding header value, if header exist. Empty otherwise.
std::string operator[](const std::string &header) const;
/// Return the string value of name-parameter.
/// @return The string value of parameter name if exist, or an empty string otherwise.
std::string parameter(const std::string &name) const;
private:
using Parameters = std::map<std::string, std::string>;
Parameters ¶ms() const;
mutable Parameters _params;
};
/// An HTTP Reply
struct Reply {
/// HTTP Status
enum status_type {
ok = 200,
created = 201,
accepted = 202,
no_content = 204,
multiple_choices = 300,
moved_permanently = 301,
moved_temporarily = 302,
not_modified = 304,
bad_request = 400,
unauthorized = 401,
forbidden = 403,
not_found = 404,
internal_server_error = 500,
not_implemented = 501,
bad_gateway = 502,
service_unavailable = 503
} status; //!< Http Status of the reply
std::vector<Header> headers; //!< The headers to be included in the reply.
std::string content; //!< The content
/// makes reply a buffer
/// @return reply as an ASIO buffer
std::vector<boost::asio::const_buffer> to_buffers();
/// Prepare a Stock Reply by type
/// @param status [in] status to create a reply
/// @return a reply of status type.
static Reply stock_reply(status_type status);
};
/// Inject headers passed in reply.
template<class Headers> Reply &operator<<(Reply &reply, const Headers &headers) {
for(auto h : headers) { reply.headers.push_back(Header(h)); }
return reply;
}
}}
#endif // SUMMER_HTTP_BASIC_HTPP
| [
"bianchi.massimo@gmail.com"
] | bianchi.massimo@gmail.com |
2bd70f37d938a4e1e5a8a399f7438bea7cb0058b | 8b4641d4e42a21b58a8f817ecf271c054bf31f0d | /src/test/reverselock_tests.cpp | 09b50fdc81b626909a821cd9394974dc79d2c68c | [
"MIT"
] | permissive | casterminator/zcore-source | 6a7e4d38b961e4fda778d815a38a670bfdb2febd | 4d9dab5e31e6f45f123b32bca8cefd99963424c7 | refs/heads/master | 2020-04-03T18:21:49.942860 | 2019-04-05T00:43:19 | 2019-04-05T00:43:19 | 155,480,879 | 0 | 0 | MIT | 2019-04-05T00:43:20 | 2018-10-31T01:37:26 | C++ | UTF-8 | C++ | false | false | 1,561 | cpp | // Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "reverselock.h"
#include "test/test_zcore.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(reverselock_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(reverselock_basics)
{
boost::mutex mutex;
boost::unique_lock<boost::mutex> lock(mutex);
BOOST_CHECK(lock.owns_lock());
{
reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
BOOST_CHECK(!lock.owns_lock());
}
BOOST_CHECK(lock.owns_lock());
}
BOOST_AUTO_TEST_CASE(reverselock_errors)
{
boost::mutex mutex;
boost::unique_lock<boost::mutex> lock(mutex);
// Make sure trying to reverse lock an unlocked lock fails
lock.unlock();
BOOST_CHECK(!lock.owns_lock());
bool failed = false;
try {
reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
} catch(...) {
failed = true;
}
BOOST_CHECK(failed);
BOOST_CHECK(!lock.owns_lock());
// Make sure trying to lock a lock after it has been reverse locked fails
failed = false;
bool locked = false;
lock.lock();
BOOST_CHECK(lock.owns_lock());
try {
reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
lock.lock();
locked = true;
} catch(...) {
failed = true;
}
BOOST_CHECK(locked && failed);
BOOST_CHECK(lock.owns_lock());
}
BOOST_AUTO_TEST_SUITE_END()
| [
"erickcosta2010@gmail.com"
] | erickcosta2010@gmail.com |
b38dfa5a5341dea3acbe4cbb1b8b27d67ddb95f6 | 9e79b322867bcf881a02ccdbafb82c4a4e2dc140 | /rclcpp/include/rclcpp/executors/executor_entities_collector.hpp | ad9bc84faded943b1e45180f5b186a91a2ff2130 | [
"Apache-2.0"
] | permissive | ros2/rclcpp | 087aefd7d412b8ac5ad11614bd98978206fa3c9b | 65f0b70d4aa4d1a3b8dc4c08aae26151ca00ca55 | refs/heads/rolling | 2023-08-16T23:02:41.840776 | 2023-08-15T22:21:33 | 2023-08-15T22:21:33 | 22,737,333 | 439 | 443 | Apache-2.0 | 2023-09-14T14:53:05 | 2014-08-07T21:36:38 | C++ | UTF-8 | C++ | false | false | 9,873 | hpp | // Copyright 2023 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP__EXECUTORS__EXECUTOR_ENTITIES_COLLECTOR_HPP_
#define RCLCPP__EXECUTORS__EXECUTOR_ENTITIES_COLLECTOR_HPP_
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <vector>
#include "rcpputils/thread_safety_annotations.hpp"
#include <rclcpp/any_executable.hpp>
#include <rclcpp/node_interfaces/node_base.hpp>
#include <rclcpp/callback_group.hpp>
#include <rclcpp/executors/executor_notify_waitable.hpp>
#include <rclcpp/visibility_control.hpp>
#include <rclcpp/wait_set.hpp>
#include <rclcpp/wait_result.hpp>
namespace rclcpp
{
namespace executors
{
/// Class to monitor a set of nodes and callback groups for changes in entity membership
/**
* This is to be used with an executor to track the membership of various nodes, groups,
* and entities (timers, subscriptions, clients, services, etc) and report status to the
* executor.
*
* In general, users will add either nodes or callback groups to an executor.
* Each node may have callback groups that are automatically associated with executors,
* or callback groups that must be manually associated with an executor.
*
* This object tracks both types of callback groups as well as nodes that have been
* previously added to the executor.
* When a new callback group is added/removed or new entities are added/removed, the
* corresponding node or callback group will signal this to the executor so that the
* entity collection may be rebuilt according to that executor's implementation.
*
*/
class ExecutorEntitiesCollector
{
public:
/// Constructor
/**
* \param[in] notify_waitable Waitable that is used to signal to the executor
* when nodes or callback groups have been added or removed.
*/
RCLCPP_PUBLIC
explicit ExecutorEntitiesCollector(
std::shared_ptr<ExecutorNotifyWaitable> notify_waitable);
/// Destructor
RCLCPP_PUBLIC
~ExecutorEntitiesCollector();
/// Indicate if the entities collector has pending additions or removals.
/**
* \return true if there are pending additions or removals
*/
bool has_pending() const;
/// Add a node to the entity collector
/**
* \param[in] node_ptr a shared pointer that points to a node base interface
* \throw std::runtime_error if the node is associated with an executor
*/
RCLCPP_PUBLIC
void
add_node(rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_ptr);
/// Remove a node from the entity collector
/**
* \param[in] node_ptr a shared pointer that points to a node base interface
* \throw std::runtime_error if the node is associated with an executor
* \throw std::runtime_error if the node is associated with this executor
*/
RCLCPP_PUBLIC
void
remove_node(rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_ptr);
/// Add a callback group to the entity collector
/**
* \param[in] group_ptr a shared pointer that points to a callback group
* \throw std::runtime_error if the callback_group is associated with an executor
*/
RCLCPP_PUBLIC
void
add_callback_group(rclcpp::CallbackGroup::SharedPtr group_ptr);
/// Remove a callback group from the entity collector
/**
* \param[in] group_ptr a shared pointer that points to a callback group
* \throw std::runtime_error if the callback_group is not associated with an executor
* \throw std::runtime_error if the callback_group is not associated with this executor
*/
RCLCPP_PUBLIC
void
remove_callback_group(rclcpp::CallbackGroup::SharedPtr group_ptr);
/// Get all callback groups known to this entity collector
/**
* This will include manually added and automatically added (node associated) groups
* \return vector of all callback groups
*/
RCLCPP_PUBLIC
std::vector<rclcpp::CallbackGroup::WeakPtr>
get_all_callback_groups() const;
/// Get manually-added callback groups known to this entity collector
/**
* This will include callback groups that have been added via add_callback_group
* \return vector of manually-added callback groups
*/
RCLCPP_PUBLIC
std::vector<rclcpp::CallbackGroup::WeakPtr>
get_manually_added_callback_groups() const;
/// Get automatically-added callback groups known to this entity collector
/**
* This will include callback groups that are associated with nodes added via add_node
* \return vector of automatically-added callback groups
*/
RCLCPP_PUBLIC
std::vector<rclcpp::CallbackGroup::WeakPtr>
get_automatically_added_callback_groups() const;
/// Update the underlying collections
/**
* This will prune nodes and callback groups that are no longer valid as well
* as add new callback groups from any associated nodes.
*/
RCLCPP_PUBLIC
void
update_collections();
protected:
using NodeCollection = std::set<
rclcpp::node_interfaces::NodeBaseInterface::WeakPtr,
std::owner_less<rclcpp::node_interfaces::NodeBaseInterface::WeakPtr>>;
using CallbackGroupCollection = std::set<
rclcpp::CallbackGroup::WeakPtr,
std::owner_less<rclcpp::CallbackGroup::WeakPtr>>;
using WeakNodesToGuardConditionsMap = std::map<
rclcpp::node_interfaces::NodeBaseInterface::WeakPtr,
rclcpp::GuardCondition::WeakPtr,
std::owner_less<rclcpp::node_interfaces::NodeBaseInterface::WeakPtr>>;
using WeakGroupsToGuardConditionsMap = std::map<
rclcpp::CallbackGroup::WeakPtr,
rclcpp::GuardCondition::WeakPtr,
std::owner_less<rclcpp::CallbackGroup::WeakPtr>>;
/// Implementation of removing a node from the collector.
/**
* This will disassociate the node from the collector and remove any
* automatically-added callback groups
*
* This takes and returns an iterator so it may be used as:
*
* it = remove_weak_node(it);
*
* \param[in] weak_node iterator to the weak node to be removed
* \return Valid updated iterator in the same collection
*/
RCLCPP_PUBLIC
NodeCollection::iterator
remove_weak_node(NodeCollection::iterator weak_node) RCPPUTILS_TSA_REQUIRES(mutex_);
/// Implementation of removing a callback group from the collector.
/**
* This will disassociate the callback group from the collector
*
* This takes and returns an iterator so it may be used as:
*
* it = remove_weak_callback_group(it);
*
* \param[in] weak_group_it iterator to the weak group to be removed
* \param[in] collection the collection to remove the group from
* (manually or automatically added)
* \return Valid updated iterator in the same collection
*/
RCLCPP_PUBLIC
CallbackGroupCollection::iterator
remove_weak_callback_group(
CallbackGroupCollection::iterator weak_group_it,
CallbackGroupCollection & collection) RCPPUTILS_TSA_REQUIRES(mutex_);
/// Implementation of adding a callback group
/**
* \param[in] group_ptr the group to add
* \param[in] collection the collection to add the group to
*/
RCLCPP_PUBLIC
void
add_callback_group_to_collection(
rclcpp::CallbackGroup::SharedPtr group_ptr,
CallbackGroupCollection & collection) RCPPUTILS_TSA_REQUIRES(mutex_);
/// Iterate over queued added/remove nodes and callback_groups
RCLCPP_PUBLIC
void
process_queues() RCPPUTILS_TSA_REQUIRES(mutex_);
/// Check a collection of nodes and add any new callback_groups that
/// are set to be automatically associated via the node.
RCLCPP_PUBLIC
void
add_automatically_associated_callback_groups(
const NodeCollection & nodes_to_check) RCPPUTILS_TSA_REQUIRES(mutex_);
/// Check all nodes and group for expired weak pointers and remove them.
RCLCPP_PUBLIC
void
prune_invalid_nodes_and_groups() RCPPUTILS_TSA_REQUIRES(mutex_);
/// mutex to protect collections and pending queues
mutable std::mutex mutex_;
/// Callback groups that were added via `add_callback_group`
CallbackGroupCollection manually_added_groups_ RCPPUTILS_TSA_GUARDED_BY(mutex_);
/// Callback groups that were added by their association with added nodes
CallbackGroupCollection automatically_added_groups_ RCPPUTILS_TSA_GUARDED_BY(mutex_);
/// nodes that are associated with the executor
NodeCollection weak_nodes_ RCPPUTILS_TSA_GUARDED_BY(mutex_);
/// Track guard conditions associated with added nodes
WeakNodesToGuardConditionsMap weak_nodes_to_guard_conditions_ RCPPUTILS_TSA_GUARDED_BY(mutex_);
/// Track guard conditions associated with added callback groups
WeakGroupsToGuardConditionsMap weak_groups_to_guard_conditions_ RCPPUTILS_TSA_GUARDED_BY(mutex_);
/// nodes that have been added since the last update.
NodeCollection pending_added_nodes_ RCPPUTILS_TSA_GUARDED_BY(mutex_);
/// nodes that have been removed since the last update.
NodeCollection pending_removed_nodes_ RCPPUTILS_TSA_GUARDED_BY(mutex_);
/// callback groups that have been added since the last update.
CallbackGroupCollection pending_manually_added_groups_ RCPPUTILS_TSA_GUARDED_BY(mutex_);
/// callback groups that have been removed since the last update.
CallbackGroupCollection pending_manually_removed_groups_ RCPPUTILS_TSA_GUARDED_BY(mutex_);
/// Waitable to add guard conditions to
std::shared_ptr<ExecutorNotifyWaitable> notify_waitable_;
};
} // namespace executors
} // namespace rclcpp
//
#endif // RCLCPP__EXECUTORS__EXECUTOR_ENTITIES_COLLECTOR_HPP_
| [
"noreply@github.com"
] | noreply@github.com |
3965b7b5781765b7ef388d93670df0ec3dee4afe | 25c3e1d01a55992a7fa2afa0907943e86ef34966 | /Tera Emulator v1xxx VS Project [SRC]/TERA_C++_EMULATOR_1/RDungeonCoolTImeList.cpp | c9d598ea5efecb70be2b667e054e797db28472b2 | [] | no_license | highattack30/Tera_Emulator_v1xxx-1 | 6daba31ca976f61658481a4c8aca98f8bdf9759c | 0c926ac903921912e69d9bb7e5cdc4022b0236f3 | refs/heads/master | 2021-01-21T19:01:50.117483 | 2016-08-22T09:17:14 | 2016-08-22T09:17:14 | 66,280,083 | 1 | 1 | null | 2016-08-22T14:33:30 | 2016-08-22T14:33:30 | null | UTF-8 | C++ | false | false | 365 | cpp | #include "RDungeonCoolTimeList.h"
RDungeonCoolTimeList::RDungeonCoolTimeList() : SendPacket(C_DUNGEON_COOL_TIME_LIST )
{
}
void RDungeonCoolTimeList::Process(OpCode opCode, Stream * data, Client * caller)
{
data->Clear();
data->WriteInt16(8);
data->WriteInt16(S_DUNGEON_COOL_TIME_LIST);
data->WriteInt32(0);
BroadcastSystem::Broadcast(caller, data, ME, 0);
} | [
"Narcis@NARCIS-PC"
] | Narcis@NARCIS-PC |
21580da8898fed1bdde949b91ab7691f70d8b7ce | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14421/function14421_schedule_20/function14421_schedule_20_wrapper.cpp | 01824201bc4c689ccb2eb257dae5bc2da9be5240 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,547 | cpp | #include "Halide.h"
#include "function14421_schedule_20_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(512, 64);
Halide::Buffer<int32_t> buf01(512, 2048);
Halide::Buffer<int32_t> buf02(512, 2048);
Halide::Buffer<int32_t> buf03(64);
Halide::Buffer<int32_t> buf04(512, 2048);
Halide::Buffer<int32_t> buf05(512);
Halide::Buffer<int32_t> buf06(512);
Halide::Buffer<int32_t> buf07(512, 64);
Halide::Buffer<int32_t> buf08(512);
Halide::Buffer<int32_t> buf09(64, 2048);
Halide::Buffer<int32_t> buf0(512, 64, 2048);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14421_schedule_20(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf07.raw_buffer(), buf08.raw_buffer(), buf09.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14421/function14421_schedule_20/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
1562fef246e5c90cc5bb8d5d1df05e5cab4fdd8e | a0c4ed3070ddff4503acf0593e4722140ea68026 | /source/UTILS/UNTFS/INC/FRS.HXX | 1f7bf6f9f55bb71ef8cf5cd8dc62d3f0ed94a253 | [] | no_license | cjacker/windows.xp.whistler | a88e464c820fbfafa64fbc66c7f359bbc43038d7 | 9f43e5fef59b44e47ba1da8c2b4197f8be4d4bc8 | refs/heads/master | 2022-12-10T06:47:33.086704 | 2020-09-19T15:06:48 | 2020-09-19T15:06:48 | 299,932,617 | 0 | 1 | null | 2020-09-30T13:43:42 | 2020-09-30T13:43:41 | null | UTF-8 | C++ | false | false | 13,767 | hxx | /*++
Copyright (c) 2000 Microsoft Corporation
Module Name:
frs.hxx
Abstract:
This module contains the declarations for the
NTFS_FILE_RECORD_SEGMENT class. This class models File
Record Segments in the NTFS Master File Table; it is the
object through which a file's attributes may be accessed.
Author:
Bill McJohn (billmc) 13-June-91
Environment:
ULIB, User Mode
--*/
#if !defined( _NTFS_FILE_RECORD_SEGMENT_DEFN_ )
#define _NTFS_FILE_RECORD_SEGMENT_DEFN_
#include "frsstruc.hxx"
#include "cannedsd.hxx"
#include "clusrun.hxx"
#include "array.hxx"
#include "hmem.hxx"
#include "list.hxx"
#include "iterator.hxx"
// Possible return codes for SortIndex:
//
// NTFS_SORT_INDEX_NOT_FOUND -- this FRS does not contain an
// index with the specified name.
// NTFS_SORT_INDEX_WELL_ORDERED -- the index was not sorted because
// it was found to be well-ordered.
// NTFS_SORT_INDEX_BADLY_ORDERED -- The index was found to be badly
// ordered, and it was not sorted.
// NTFS_SORT_INDEX_SORTED -- The index was sorted and new
// attributes were inserted into
// the FRS.
// NTFS_INSERT_FAILED -- An insertion of an index entry
// into the new tree failed.
// (Probable cause: out of space.)
// NTFS_SORT_ERROR -- Sort failed because of an error.
//
//
typedef enum NTFS_SORT_CODE {
NTFS_SORT_INDEX_NOT_FOUND,
NTFS_SORT_INDEX_WELL_ORDERED,
NTFS_SORT_INDEX_BADLY_ORDERED,
NTFS_SORT_INDEX_SORTED,
NTFS_SORT_INSERT_FAILED,
NTFS_SORT_ERROR
};
// Forward references
DECLARE_CLASS( IO_DP_DRIVE );
DECLARE_CLASS( NTFS_MASTER_FILE_TABLE );
DECLARE_CLASS( NTFS_MFT_FILE );
DECLARE_CLASS( NTFS_ATTRIBUTE );
DECLARE_CLASS( WSTRING );
DECLARE_CLASS( NTFS_ATTRIBUTE_RECORD );
DECLARE_CLASS( NTFS_ATTRIBUTE_RECORD_LIST );
DECLARE_CLASS( NTFS_FILE_RECORD_SEGMENT );
DECLARE_CLASS( NTFS_ATTRIBUTE_LIST );
DECLARE_CLASS( NTFS_BITMAP );
DECLARE_CLASS( NTFS_BAD_CLUSTER_FILE );
class NTFS_FILE_RECORD_SEGMENT : public NTFS_FRS_STRUCTURE {
public:
UNTFS_EXPORT
DECLARE_CONSTRUCTOR( NTFS_FILE_RECORD_SEGMENT );
VIRTUAL
UNTFS_EXPORT
~NTFS_FILE_RECORD_SEGMENT (
);
NONVIRTUAL
UNTFS_EXPORT
BOOLEAN
Initialize (
IN VCN FileNumber,
IN OUT PNTFS_MFT_FILE MftFile
);
NONVIRTUAL
UNTFS_EXPORT
BOOLEAN
Initialize (
IN VCN FileNumber,
IN OUT PNTFS_MASTER_FILE_TABLE Mft
);
NONVIRTUAL
UNTFS_EXPORT
BOOLEAN
Create (
IN PCSTANDARD_INFORMATION StandardInformation,
IN USHORT Flags DEFAULT 0
);
NONVIRTUAL
BOOLEAN
Create (
IN PCMFT_SEGMENT_REFERENCE BaseSegment,
IN USHORT Flags DEFAULT 0
);
NONVIRTUAL
BOOLEAN
CreateSystemFile(
);
NONVIRTUAL
BOOLEAN
VerifyAndFixFileNames(
IN OUT PNTFS_BITMAP VolumeBitmap,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN DiskErrorsFound DEFAULT NULL,
IN BOOLEAN FixDupInfo DEFAULT TRUE
);
VIRTUAL
UNTFS_EXPORT
BOOLEAN
Write(
);
NONVIRTUAL
UNTFS_EXPORT
BOOLEAN
Flush(
IN OUT PNTFS_BITMAP VolumeBitmap OPTIONAL,
IN OUT PNTFS_INDEX_TREE ParentIndex DEFAULT NULL
);
NONVIRTUAL
BOOLEAN
AddDataAttribute(
IN ULONG InitialSize,
IN OUT PNTFS_BITMAP VolumeBitmap,
IN BOOLEAN Fill DEFAULT FALSE,
IN CHAR FillCharacter DEFAULT 0
);
NONVIRTUAL
UNTFS_EXPORT
BOOLEAN
AddFileNameAttribute(
IN PFILE_NAME FileNameAttributeValue
);
NONVIRTUAL
BOOLEAN
AddAttribute(
IN ATTRIBUTE_TYPE_CODE Type,
IN PCWSTRING Name OPTIONAL,
IN PCVOID Value OPTIONAL,
IN ULONG Length,
IN OUT PNTFS_BITMAP Bitmap OPTIONAL,
IN BOOLEAN IsIndexed DEFAULT FALSE
);
NONVIRTUAL
UNTFS_EXPORT
BOOLEAN
AddSecurityDescriptor(
IN CANNED_SECURITY_TYPE SecurityType,
IN OUT PNTFS_BITMAP Bitmap
);
NONVIRTUAL
BOOLEAN
AddEmptyAttribute(
IN ATTRIBUTE_TYPE_CODE Type,
IN PCWSTRING Name DEFAULT NULL
);
NONVIRTUAL
UNTFS_EXPORT
BOOLEAN
IsAttributePresent (
IN ATTRIBUTE_TYPE_CODE Type,
IN PCWSTRING Name DEFAULT NULL,
IN BOOLEAN IgnoreExternal DEFAULT FALSE
);
NONVIRTUAL
BOOLEAN
QueryAttributeRecord (
OUT PNTFS_ATTRIBUTE_RECORD AttributeRecord,
IN ATTRIBUTE_TYPE_CODE Type,
IN PCWSTRING Name DEFAULT NULL
) CONST;
NONVIRTUAL
UNTFS_EXPORT
BOOLEAN
QueryAttribute (
OUT PNTFS_ATTRIBUTE Attribute,
OUT PBOOLEAN Error,
IN ATTRIBUTE_TYPE_CODE Type,
IN PCWSTRING Name DEFAULT NULL
);
NONVIRTUAL
BOOLEAN
QueryResidentAttribute (
OUT PNTFS_ATTRIBUTE Attribute,
OUT PBOOLEAN Error,
IN ATTRIBUTE_TYPE_CODE Type,
IN PCVOID Value,
IN ULONG ValueLength,
IN COLLATION_RULE CollationRule DEFAULT COLLATION_BINARY
);
NONVIRTUAL
BOOLEAN
QueryAttributeByOrdinal (
OUT PNTFS_ATTRIBUTE Attribute,
OUT PBOOLEAN Error,
IN ATTRIBUTE_TYPE_CODE Type,
IN ULONG Ordinal
);
NONVIRTUAL
BOOLEAN
QueryAttributeByTag (
OUT PNTFS_ATTRIBUTE Attribute,
OUT PBOOLEAN Error,
IN ULONG Tag
);
NONVIRTUAL
BOOLEAN
PurgeAttribute (
IN ATTRIBUTE_TYPE_CODE Type,
IN PCWSTRING Name DEFAULT NULL,
IN BOOLEAN IgnoreExternal DEFAULT FALSE
);
NONVIRTUAL
BOOLEAN
DeleteResidentAttribute(
IN ATTRIBUTE_TYPE_CODE Type,
IN PCWSTRING Name OPTIONAL,
IN PCVOID Value,
IN ULONG ValueLength,
OUT PBOOLEAN Deleted,
IN BOOLEAN IgnoreExternal DEFAULT FALSE
);
NONVIRTUAL
BOOLEAN
DeleteResidentAttributeLocal(
IN ATTRIBUTE_TYPE_CODE Type,
IN PCWSTRING Name OPTIONAL,
IN PCVOID Value,
IN ULONG ValueLength,
OUT PBOOLEAN Deleted,
OUT PBOOLEAN IsIndexed,
OUT PUSHORT InstanceTag
);
VIRTUAL
BOOLEAN
InsertAttributeRecord (
IN OUT PNTFS_ATTRIBUTE_RECORD NewRecord,
IN BOOLEAN ForceExternal DEFAULT FALSE
);
NONVIRTUAL
USHORT
QueryNextInstance(
);
NONVIRTUAL
VOID
IncrementNextInstance(
);
NONVIRTUAL
ULONG
QueryFreeSpace(
);
NONVIRTUAL
ULONG
QueryMaximumAttributeRecordSize (
) CONST;
NONVIRTUAL
BOOLEAN
QueryNextAttribute(
IN OUT PATTRIBUTE_TYPE_CODE TypeCode,
IN OUT PWSTRING Name
);
NONVIRTUAL
BOOLEAN
RecoverFile(
IN OUT PNTFS_BITMAP VolumeBitmap,
IN OUT PNUMBER_SET BadClusterList,
OUT PULONG BadClusters,
OUT PBIG_INT BytesRecovered,
OUT PBIG_INT TotalBytes
);
NONVIRTUAL
NTFS_SORT_CODE
SortIndex(
IN PCWSTRING IndexName,
IN OUT PNTFS_BITMAP VolumeBitmap,
IN BOOLEAN DuplicatesAllowed,
IN BOOLEAN CheckOnly DEFAULT FALSE
);
NONVIRTUAL
BOOLEAN
QueryDuplicatedInformation(
OUT PDUPLICATED_INFORMATION DuplicatedInformation
);
NONVIRTUAL
BOOLEAN
UpdateFileNames(
IN PDUPLICATED_INFORMATION DuplicatedInformation,
IN OUT PNTFS_INDEX_TREE Index OPTIONAL,
IN BOOLEAN IgnoreExternal
);
NONVIRTUAL
BOOLEAN
Backtrack(
OUT PWSTRING Path
);
NONVIRTUAL
VOID
SetLsn(
IN BIG_INT NewLsn
);
protected:
NONVIRTUAL
BOOLEAN
Initialize(
IN OUT PLOG_IO_DP_DRIVE Drive,
IN LCN StartOfMft,
IN PNTFS_MASTER_FILE_TABLE Mft
);
private:
NONVIRTUAL
VOID
Construct (
);
NONVIRTUAL
VOID
Destroy (
);
NONVIRTUAL
BOOLEAN
Create (
IN USHORT Flags DEFAULT 0
);
NONVIRTUAL
BOOLEAN
SetupAttributeList(
);
NONVIRTUAL
BOOLEAN
CreateAttributeList(
OUT PNTFS_ATTRIBUTE_LIST AttributeList
);
NONVIRTUAL
BOOLEAN
SaveAttributeList(
PNTFS_BITMAP VolumeBitmap
);
NONVIRTUAL
BOOLEAN
InsertExternalAttributeRecord(
IN PNTFS_ATTRIBUTE_RECORD NewRecord
);
NONVIRTUAL
BOOLEAN
BacktrackWorker(
IN OUT PWSTRING Path
);
NONVIRTUAL
PNTFS_FILE_RECORD_SEGMENT
SetupChild(
IN VCN FileNumber
);
NONVIRTUAL
BOOLEAN
AddChild(
PNTFS_FILE_RECORD_SEGMENT ChildFrs
);
NONVIRTUAL
PNTFS_FILE_RECORD_SEGMENT
GetChild(
VCN FileNumber
);
NONVIRTUAL
VOID
DeleteChild(
VCN FileNumber
);
HMEM _Mem;
LIST _Children;
PITERATOR _ChildIterator;
PNTFS_MASTER_FILE_TABLE _Mft;
PNTFS_ATTRIBUTE_LIST _AttributeList;
};
INLINE
USHORT
NTFS_FILE_RECORD_SEGMENT::QueryNextInstance(
)
/*++
Routine Description:
This method fetches the current value of the FRS'
NextAttributeInstance field.
Arguments:
None.
Return Value:
The current value of the FRS' NextAttributeInstance field.
--*/
{
return _FrsData->NextAttributeInstance;
}
INLINE
VOID
NTFS_FILE_RECORD_SEGMENT::IncrementNextInstance(
)
/*++
Routine Description:
This method increments the NextAttributeInstance field of
the File Record Segment.
Arguments:
None.
Return Value:
None.
--*/
{
_FrsData->NextAttributeInstance++;
}
INLINE
ULONG
NTFS_FILE_RECORD_SEGMENT::QueryFreeSpace(
)
/*++
Routine Description:
This method returns the amount of free space following the
last Attribute Record in the File Record Segment.
Arguments:
None.
Return Value:
The amount of free space.
Notes:
This method assumes that the FRS is consistent.
--*/
{
return _FrsData->BytesAvailable - _FrsData->FirstFreeByte;
}
INLINE
ULONG
NTFS_FILE_RECORD_SEGMENT::QueryMaximumAttributeRecordSize (
) CONST
/*++
Routine Description:
This method returns the size of the largest attribute record
the File Record Segment will accept. Note that this is the
largest record it will ever accept, not what it can currently
accept.
Arguments:
None.
Return Value:
The size of the largest attribute record a File Record Segment
of this size can accept.
--*/
{
return QuerySize() - (_FrsData->FirstAttributeOffset +
QuadAlign(sizeof(ATTRIBUTE_TYPE_CODE)));
}
INLINE
BOOLEAN
NTFS_FILE_RECORD_SEGMENT::AddEmptyAttribute(
IN ATTRIBUTE_TYPE_CODE Type,
IN PCWSTRING Name
)
/*++
Routine Description:
This method adds an empty, non-indexed, resident attribute of
the specified type to the FRS.
Arguments:
Type -- Supplies the attribute's type code.
Name -- Supplies the attribute's name. May be NULL, in which
case the attribute has no name.
Return Value:
TRUE upon successful completion.
--*/
{
NTFS_ATTRIBUTE Attribute;
return( Attribute.Initialize( GetDrive(),
QueryClusterFactor(),
NULL,
0,
Type,
Name,
0 ) &&
Attribute.InsertIntoFile( this, NULL ) );
}
#endif
| [
"71558585+window-chicken@users.noreply.github.com"
] | 71558585+window-chicken@users.noreply.github.com |
0ee22e10cdb52e8f67a5cbe17d938f3feb6d3f1c | 3f9a7bf11506b16170a632aa3dc99b31fae5dc44 | /testexecmgmt/ucc/Source/Uccs.v2/ServiceStubs/GPSSimulator/CCGpssimulator.cpp | 788519e89295aa16240ea66384e94063e4f2ba5f | [] | no_license | fedor4ever/testexec | a5b85726b54384feeedb74e76a7ead12b87a8d37 | 2a6185d3922dbf95b86eb6a7701f737a646f9e58 | refs/heads/master | 2019-01-02T09:10:59.426200 | 2015-04-12T12:06:41 | 2015-04-12T12:06:41 | 33,688,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,625 | cpp | /*
* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
* System Includes
*
*/
#include <stdio.h>
#include <assert.h>
#include <rpc/types.h>
/****************************************************************************************
*
* Local Includes
*
***************************************************************************************/
#include "CCGpssimulator.h"
/****************************************************************************************
*
* Implementation
*
***************************************************************************************/
CCGpssimulator::CCGpssimulator()
{
cl = NULL;
iLastRPCError.re_status = RPC_SUCCESS;
}
CCGpssimulator::~CCGpssimulator()
{
assert( cl == NULL );
}
char *CCGpssimulator::GetLastRPCError( int *aIntErr )
{
struct rpc_err rpcerr;
// check that the handle is valid
if( cl == NULL ) {
return NULL;
}
// pass the aIntErr
if( aIntErr != NULL ) {
clnt_geterr( cl, &rpcerr );
*aIntErr = rpcerr.re_status;
}
// return the errorstring
return clnt_sperror( cl, NULL );
}
int CCGpssimulator::Connect( string aRemoteHost )
{
// check that we are not already connected
if( cl != NULL ) {
return ERR_STUB_ALREADY_CONNECTED;
}
// start the rpc library
rpc_nt_init();
// connect to the service
cl = clnt_create( aRemoteHost.c_str(), GPSSIMULATOR, GPSSIMULATOR_VERSION, "tcp" );
if( cl == NULL ) {
rpc_nt_exit();
return ERR_FAILED_TO_CONNECT;
}
// done
return ERR_NONE;
}
int CCGpssimulator::Disconnect( )
{
// check that we are connected
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// cleanup the client handle
clnt_destroy( cl );
cl = NULL;
rpc_nt_exit();
// done
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: ss_startuprpcservice
*
***************************************************************************************/
int CCGpssimulator::ss_startuprpcservice( TStartupInfo aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *ss_startuprpcservice_10( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: sc_shutdownrpcservice
*
***************************************************************************************/
int CCGpssimulator::sc_shutdownrpcservice( int aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *sc_shutdownrpcservice_10( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: list_connections
*
***************************************************************************************/
int CCGpssimulator::list_connections( TComponentList *rv )
{
struct rpc_err rerr;
int aArgs = 0;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *list_connections_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: cstr_startprocess
*
***************************************************************************************/
int CCGpssimulator::cstr_startprocess( char *aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *cstr_startprocess_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: dstr_removeprocess
*
***************************************************************************************/
int CCGpssimulator::dstr_removeprocess( int aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *dstr_removeprocess_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: startsimulator
*
***************************************************************************************/
int CCGpssimulator::startsimulator( int *rv )
{
struct rpc_err rerr;
int aArgs = 0;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *startsimulator_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: stopsimulator
*
***************************************************************************************/
int CCGpssimulator::stopsimulator( int *rv )
{
struct rpc_err rerr;
int aArgs = 0;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *stopsimulator_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: setfielddefault
*
***************************************************************************************/
int CCGpssimulator::setfielddefault( TField aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *setfielddefault_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: setsatellitedefault
*
***************************************************************************************/
int CCGpssimulator::setsatellitedefault( TSatellite aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *setsatellitedefault_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: positionset
*
***************************************************************************************/
int CCGpssimulator::positionset( TPositionInfo aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *positionset_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: courseset
*
***************************************************************************************/
int CCGpssimulator::courseset( TCourse aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *courseset_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: accuracyset
*
***************************************************************************************/
int CCGpssimulator::accuracyset( TAccuracy aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *accuracyset_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: satelliteset
*
***************************************************************************************/
int CCGpssimulator::satelliteset( TSatellite aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *satelliteset_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: batchappendsentence
*
***************************************************************************************/
int CCGpssimulator::batchappendsentence( TAppendSentence aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *batchappendsentence_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: batchappendusersentence
*
***************************************************************************************/
int CCGpssimulator::batchappendusersentence( TAppendUserSentence aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *batchappendusersentence_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: batchsetdelay
*
***************************************************************************************/
int CCGpssimulator::batchsetdelay( int aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *batchsetdelay_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: batchreset
*
***************************************************************************************/
int CCGpssimulator::batchreset( int *rv )
{
struct rpc_err rerr;
int aArgs = 0;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *batchreset_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: setcomport
*
***************************************************************************************/
int CCGpssimulator::setcomport( char *aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *setcomport_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: setchunkmode
*
***************************************************************************************/
int CCGpssimulator::setchunkmode( bool_t aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *setchunkmode_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: setchunksize
*
***************************************************************************************/
int CCGpssimulator::setchunksize( int aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *setchunksize_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: setchunkdelay
*
***************************************************************************************/
int CCGpssimulator::setchunkdelay( int aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *setchunkdelay_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: startcomms
*
***************************************************************************************/
int CCGpssimulator::startcomms( int *rv )
{
struct rpc_err rerr;
int aArgs = 0;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *startcomms_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: stopcomms
*
***************************************************************************************/
int CCGpssimulator::stopcomms( int *rv )
{
struct rpc_err rerr;
int aArgs = 0;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *stopcomms_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
/****************************************************************************************
*
* PUBLIC FUNCTION: batchappenduserstring
*
***************************************************************************************/
int CCGpssimulator::batchappenduserstring( TAppendString aArgs, int *rv )
{
struct rpc_err rerr;
// check the rv pointer
if( rv == NULL ) {
return ERR_INVALID_RV_POINTER;
}
// check that we have a connection
if( cl == NULL ) {
return ERR_STUB_NOT_CONNECTED;
}
// do the call
*rv = *batchappenduserstring_1( &aArgs, cl );
// check for rpc errors and return the result
clnt_geterr( cl, &rerr );
if( rerr.re_status != RPC_SUCCESS ) {
iLastRPCError = rerr;
return ERR_RPC_ERROR;
}
return ERR_NONE;
}
| [
"johnson.ma@nokia.com"
] | johnson.ma@nokia.com |
5c31950c0d5e60cbae970ad4968507147a3f83df | b4d572c75b0268af2007a5350432c616118828cd | /Contents/src/SnowMan/drawable.cpp | 0420eb887b224ee83fa25312f09f0f03c4bf7a64 | [] | no_license | Jiaww/D3D11-SnowMan | 56bb75e07da4f30db0ef97a790afdb2eabbeda90 | f695ff46dc6f2511c5e1c353c4d058a0e7e478ff | refs/heads/master | 2021-05-08T16:13:01.065413 | 2018-02-21T02:01:48 | 2018-02-21T02:01:48 | 120,145,618 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 94 | cpp | #include "pch.h"
#include "drawable.h"
drawable::drawable()
{
}
drawable::~drawable()
{
}
| [
"jiaww@seas.upenn.edu"
] | jiaww@seas.upenn.edu |
cca9fcef76dfca149fe18f74cd07b7bc793aa21e | 3970f1a70df104f46443480d1ba86e246d8f3b22 | /vimrid/src/types/VPoint2f.cpp | 67c3176e3fd00c0b033b72e6a7979cb06ca38153 | [] | no_license | zhan2016/vimrid | 9f8ea8a6eb98153300e6f8c1264b2c042c23ee22 | 28ae31d57b77df883be3b869f6b64695df441edb | refs/heads/master | 2021-01-20T16:24:36.247136 | 2009-07-28T18:32:31 | 2009-07-28T18:32:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,594 | cpp | /* TODO: Short description of file.
*
* TODO: Write detailed information.
*
* Created: 07-Apr-2009
* Author: Nick Bolton (njb4@aber.ac.uk)
*/
#include "VPoint2f.h"
#include <sstream>
using namespace std;
namespace vimrid
{
VPoint2f::VPoint2f()
:
X(0), Y(0)
{
}
VPoint2f::VPoint2f(VFloat x, VFloat y)
:
X(x), Y(y)
{
}
VPoint2f::VPoint2f(const VPoint3f &p)
:
X(p.X), Y(p.Y)
{
}
VPoint2f::~VPoint2f()
{
}
VPoint2f &VPoint2f::operator=(const VPoint3f &rhs)
{
X = rhs.X;
Y = rhs.Y;
return *this;
}
VPoint2f VPoint2f::operator+(const VPoint2f &rhs) const
{
VPoint2f value;
const VPoint2f &lhs = *this;
value.X = lhs.X + rhs.X;
value.Y = lhs.Y + rhs.Y;
return value;
}
VPoint2f VPoint2f::operator-(const VPoint2f &rhs) const
{
VPoint2f value;
const VPoint2f &lhs = *this;
value.X = lhs.X - rhs.X;
value.Y = lhs.Y - rhs.Y;
return value;
}
VPoint2f VPoint2f::operator+(const VPoint3f &rhs) const
{
VPoint2f value;
const VPoint2f &lhs = *this;
value.X = lhs.X + rhs.X;
value.Y = lhs.Y + rhs.Y;
return value;
}
VPoint2f VPoint2f::operator-(const VPoint3f &rhs) const
{
VPoint2f value;
const VPoint2f &lhs = *this;
value.X = lhs.X - rhs.X;
value.Y = lhs.Y - rhs.Y;
return value;
}
VPoint2f VPoint2f::operator+(const VSize3F &rhs) const
{
VPoint2f value;
const VPoint2f &lhs = *this;
value.X = lhs.X + rhs.Width;
value.Y = lhs.Y + rhs.Height;
return value;
}
VPoint2f VPoint2f::operator+(const VFloat &rhs) const
{
VPoint2f value;
const VPoint2f &lhs = *this;
value.X = lhs.X + rhs;
value.Y = lhs.Y + rhs;
return value;
}
VPoint2f VPoint2f::operator-(const VFloat &rhs) const
{
VPoint2f value;
const VPoint2f &lhs = *this;
value.X = lhs.X - rhs;
value.Y = lhs.Y - rhs;
return value;
}
VPoint2f &VPoint2f::operator+=(const VFloat &rhs)
{
X += rhs;
Y += rhs;
return *this;
}
VPoint2f &Point2f::operator-=(const VFloat &rhs)
{
X -= rhs;
Y -= rhs;
return *this;
}
VPoint2f Point2f::operator*(const VFloat &rhs) const
{
VPoint2f value;
const VPoint2f &lhs = *this;
value.X = lhs.X * rhs;
value.Y = lhs.Y * rhs;
return value;
}
VBool VPoint2f::operator>(const VPoint2f &rhs) const
{
return (X > rhs.X) && (Y > rhs.Y);
}
VBool VPoint2f::operator<(const VPoint2f &rhs) const
{
return (X < rhs.X) && (Y < rhs.Y);
}
VBool VPoint2f::operator>(const VPoint3f &rhs) const
{
return (X > rhs.X) && (Y > rhs.Y);
}
VBool VPoint2f::operator<(const VPoint3f &rhs) const
{
return (X < rhs.X) && (Y < rhs.Y);
}
ostream &operator<<(ostream& os, const VPoint2f &point)
{
os << "X: " << point.X << " ";
os << "Y: " << point.Y;
return os;
}
}
| [
"nick@synergy-project.org"
] | nick@synergy-project.org |
f933f5503b1a0f461d8aebd0220b9065529c9690 | 22c07eb77d6087103a982877c345d16d52e5b90a | /IrRemote/IrRemote.ino | 63307c8eff6de6db0f938c5a43c069ab43114f68 | [] | no_license | Bhacaz/ArduinoInfraRedRemote | 7e9134011bf6f6af5bf990a015bb2b36a3a0a9ef | 9e06c9ffe04b17b2d2b9518bcad3bb36951a6c65 | refs/heads/master | 2021-01-10T21:01:39.084059 | 2014-10-28T11:33:35 | 2014-10-28T11:33:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,562 | ino | /*
* IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
*/
#include <IRremote.h>
int RECV_PIN = 10;
int led1 = 13;
int led2 = 12;
int led3 = 11;
int brightess = 255;
boolean on = false;
int fadeAmount = 10;
unsigned long remote_receive = 0;
int led_number = 1;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
}
void loop() {
if (irrecv.decode(&results)) {
remote_receive = results.value;
Serial.println(remote_receive, HEX);
switch(remote_receive)
{
case 0x540A:
on = (!on);
if(on == true){ onLed(led_number);}
else{ allOff();}
break;
case 0xDE108:
led_number++;
if (led_number == 8)
{
led_number = 1;
}
onLed(led_number);
break;
case 0x5E108:
led_number--;
if (led_number == 0)
{
led_number = 7;
}
onLed(led_number);
break;
case 0x1E108:
brightess = brightess + fadeAmount;
if(brightess > 255){brightess = 255;};
onLed(led_number);
break;
case 0x9E108:
brightess = brightess - fadeAmount;
if(brightess < 0){brightess = 0;};
onLed(led_number);
break;
case 0x3E108:
brightess = 255;
led_number = 1;
onLed(led_number);
}
irrecv.resume(); // Receive the next value
}
delay(100);
}
void allOff()
{
analogWrite(led1, 0);
analogWrite(led2, 0);
analogWrite(led3, 0);
}
void onLed(int nb)
{
allOff();
switch (nb)
{
case 1:
analogWrite(led1, brightess);
break;
case 2:
analogWrite(led2, brightess);
break;
case 3:
analogWrite(led3, brightess);
break;
case 4:
analogWrite(led1, brightess);
analogWrite(led2, brightess);
break;
case 5:
analogWrite(led1, brightess);
analogWrite(led3, brightess);
break;
case 6:
analogWrite(led2, brightess);
analogWrite(led3, brightess);
break;
case 7:
analogWrite(led1, brightess);
analogWrite(led2, brightess);
analogWrite(led3, brightess);
break;
}
}
| [
"bhacaz@Helix-Ubuntu"
] | bhacaz@Helix-Ubuntu |
ca4bc652f34d8efe85901c53134bac019b74729c | 20c74d83255427dd548def97f9a42112c1b9249a | /src/roadfighter/truck.cpp | a40ec2f7ef6c9d80922a3391fb4f38722053fef8 | [] | no_license | jonyzp/roadfighter | 70f5c7ff6b633243c4ac73085685595189617650 | d02cbcdcfda1555df836379487953ae6206c0703 | refs/heads/master | 2016-08-10T15:39:09.671015 | 2011-05-05T12:00:34 | 2011-05-05T12:00:34 | 54,320,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | #include "truck.h"
Truck::Truck()
{
}
Truck::Truck(char *name)
:NonRivalCar(name)
{
addImage(ImageInfo("truck", ROADFIGHTER_IMAGES_DIR, "truck.bmp", 4, 32, 64));
myType = TRUCK_CAR;
init();
setWidth(32);
setHeight(64);
setStretchedWidth(20);
setStretchedHeight(64);
initMe();
setSpeed(200);
initImages();
}
Truck::~Truck()
{
}
void Truck::initMe()
{
active = yes;
state = ALIVE;
currentFrame = frames[CAR_ALIVE_FRAME];
}
void Truck::bumpAction()
{
}
| [
"vickyrare@yahoo.com"
] | vickyrare@yahoo.com |
709c65d31f847bed0db917f82e3b50f9757ab820 | e9a257e0e57acb2a904165c3f554deb716d44f62 | /CinderGraphicsLib/include/SpriteDataParser.h | b13bbb908d8e09d0a06c5aa5227262f8e8493a1e | [] | no_license | ViktorFagerlind/CinderProjects | 931f13e4e28b25d9d5bef4c2402fc9075e1596fc | a8a3f7ce7a49a6b4ca332388eca66b5147fcc5f9 | refs/heads/master | 2021-06-26T16:45:13.357434 | 2016-10-10T20:10:50 | 2016-10-10T20:10:50 | 23,731,340 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | h | #pragma once
#include "cinder/Cinder.h"
#include "cinder/app/App.h"
#include "cinder/Xml.h"
#include "cinder/DataSource.h"
#include "SpriteData.h"
#include "SpriteSheet.h"
class SpriteDataParser{
public:
static std::vector<SpriteData> parseSpriteData (ci::DataSourceRef dataSource, int format);
private:
static ci::XmlTree spriteXml;
static std::vector<SpriteData> sprites;
};
| [
"viktor_fagerlind@hotmail.com@912f2d48-f3f0-11de-99d0-77da0b7ae2c6"
] | viktor_fagerlind@hotmail.com@912f2d48-f3f0-11de-99d0-77da0b7ae2c6 |
5ccdb031ab9310c53d68b23f56a7b135c91cc3c4 | 8cfed525d7412a300081aa39ca808da9fc58c9bd | /Source Code/Engineering Code/code/GenderPrediction/GenderPrediction/stdafx.cpp | 9456d14085fa43d8bdc1dcd46687b35407d9503f | [] | no_license | lanouyu/Age-and-Gender-Recognition-Software | 082d7f1998bb178e6de88073e2dcfa66c9da7059 | 21504447f9d80743fa8763dd1fdaaeab8d3ae690 | refs/heads/master | 2021-08-14T10:01:39.244057 | 2017-11-15T09:54:30 | 2017-11-15T09:54:30 | 110,646,030 | 2 | 3 | null | null | null | null | GB18030 | C++ | false | false | 277 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// GenderPrediction.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"lanouyu@gmail.com"
] | lanouyu@gmail.com |
0317797d383f4e1f937232662d798978db6cbb40 | 47a84a8760ff5f41eadf61eaf11d36fb80ea0551 | /week2/siren/siren.ino | 40d9f0417a4febeef336d6e47cdc1b9ef1d12e68 | [] | no_license | sok98/arduino_basic | 2af8500d1e150b79e33a41f66dd1c785953a4bc2 | 28b82c08e5feee30c2635e55af26ad1649a0a30b | refs/heads/master | 2023-01-07T10:47:44.627139 | 2020-10-27T11:02:13 | 2020-10-27T11:02:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | ino | void setup() {
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
}
void loop() {
tone(10,500,100);
digitalWrite(9, HIGH); //파란불 켜기
digitalWrite(8, LOW); //빨간불 끄기
delay(200);
tone(10, 1000, 100);
digitalWrite(9, LOW); //파란불 끄기
digitalWrite(8, HIGH); //빨간불 켜기
delay(200);
}
| [
"hj970219@naver.com"
] | hj970219@naver.com |
b8565eca83c72fdf050ed22250198040ac7c5fd6 | 0229e748533018d57c16c9666610e29ff758935d | /errorcheck_model_public.h | 83239524d1866b2191aa51c9ea61969468ad1474 | [] | no_license | jamesr66a/EmbeddedCapstonePiSoftware | e0e6e93fff5489044fa36c7fad2eeff5cfabe82d | 2c033986d8b0dc3a39d530f77cff7abbad6944cf | refs/heads/master | 2021-01-01T04:11:25.926604 | 2016-04-28T16:33:15 | 2016-04-28T16:33:15 | 58,290,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 374 | h | #ifndef _ERRORCHECK_MODEL_PUBLIC_H_
#define _ERRORCHECK_MODEL_PUBLIC_H_
#include "generated/DebugInfo.pbo.h"
#include <vector>
int errorcheck_aggregate_debug_info_count();
float errorcheck_debug_info_rate_per_minute();
void sendToErrorCheckModelQueue(DebugInfo *info);
std::vector<DebugInfo> errorcheck_aggregate_info_vector();
#endif /* _ERRORCHECK_MODEL_PUBLIC_H_ */
| [
"jamesr66@vt.edu"
] | jamesr66@vt.edu |
5b1a48b4897e50be21f82ea279a1ccc994da11c0 | e380c7ba3db647b8d0186afd60717478dc8f2f4b | /src/kinematica/al5d_pckg/src/Color.cpp | 4034328bb696a73483e2eea560a3ee2b89931986 | [
"MIT"
] | permissive | steinzwerink/kinematica | 8096eb6d7191ca9fc82f1a137d95bef0d95f617b | 35138025ab5237ff24812d4ce9d8cbbeabdb2ee4 | refs/heads/master | 2020-07-22T17:55:20.110245 | 2019-10-22T11:27:01 | 2019-10-22T11:27:01 | 195,205,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,685 | cpp | #include "al5d_pckg/Color.hpp"
//Color
Color::Color(const std::string &filter_type, const cv::Mat &input_image)
: Filter(filter_type), input_image(input_image)
{
}
Color::~Color()
{
}
//Red
Red::Red(const std::string &filter_type, const cv::Mat &input_image)
: Color(filter_type, input_image)
{
}
cv::Mat Red::pipeline(int h_low, int s_low, int v_low, int h_upper, int s_upper, int v_upper, int h_low_max, int h_upper_max)
{
cv::Mat hsv_image, lower_range, upper_range, hue_image;
hsv_image = this->get_HSV(input_image);
cv::inRange(hsv_image, cv::Scalar(h_low, s_low, v_low), cv::Scalar(h_low_max, 255, 255), lower_range);
cv::inRange(hsv_image, cv::Scalar(h_upper, s_upper, v_upper), cv::Scalar(h_upper_max, 255, 255), upper_range);
cv::addWeighted(lower_range, 1.0, upper_range, 1.0, 0.0, hue_image);
return hue_image;
}
Red::~Red()
{
}
//Green
Green::Green(const std::string &filter_type, const cv::Mat &input_image)
: Color(filter_type, input_image)
{
}
cv::Mat Green::pipeline(int h_low, int s_low, int v_low, int h_upper, int s_upper, int v_upper, int h_low_max, int h_upper_max)
{
cv::Mat hsv_image, lower_range, upper_range, hue_image;
hsv_image = this->get_HSV(input_image);
cv::inRange(hsv_image, cv::Scalar(h_low, s_low, v_low), cv::Scalar(h_low_max, 255, 255), lower_range);
cv::inRange(hsv_image, cv::Scalar(h_upper, s_upper, v_upper), cv::Scalar(h_upper_max, 255, 255), upper_range);
cv::addWeighted(lower_range, 1.0, upper_range, 1.0, 0.0, hue_image);
return hue_image;
}
Green::~Green()
{
}
//Blue
Blue::Blue(const std::string &filter_type, const cv::Mat &input_image)
: Color(filter_type, input_image)
{
}
cv::Mat Blue::pipeline(int h_low, int s_low, int v_low, int h_upper, int s_upper, int v_upper, int h_low_max, int h_upper_max)
{
cv::Mat hsv_image, lower_range, upper_range, hue_image;
hsv_image = this->get_HSV(input_image);
cv::inRange(hsv_image, cv::Scalar(h_low, s_low, v_low), cv::Scalar(h_low_max, 255, 255), lower_range);
cv::inRange(hsv_image, cv::Scalar(h_upper, s_upper, v_upper), cv::Scalar(h_upper_max, 255, 255), upper_range);
cv::addWeighted(lower_range, 1.0, upper_range, 1.0, 0.0, hue_image);
return hue_image;
}
Blue::~Blue()
{
}
//Yellow
Yellow::Yellow(const std::string &filter_type, const cv::Mat &input_image)
: Color(filter_type, input_image)
{
}
cv::Mat Yellow::pipeline(int h_low, int s_low, int v_low, int h_upper, int s_upper, int v_upper, int h_low_max, int h_upper_max)
{
cv::Mat hsv_image, lower_range, upper_range, hue_image;
hsv_image = this->get_HSV(input_image);
cv::inRange(hsv_image, cv::Scalar(h_low, s_low, v_low), cv::Scalar(h_low_max, 255, 255), lower_range);
cv::inRange(hsv_image, cv::Scalar(h_upper, s_upper, v_upper), cv::Scalar(h_upper_max, 255, 255), upper_range);
cv::addWeighted(lower_range, 1.0, upper_range, 1.0, 0.0, hue_image);
return hue_image;
}
Yellow::~Yellow()
{
}
//White
White::White(const std::string &filter_type, const cv::Mat &input_image)
: Color(filter_type, input_image)
{
}
cv::Mat White::pipeline(int h_low, int s_low, int v_low, int h_upper, int s_upper, int v_upper, int h_low_max, int h_upper_max)
{
cv::Mat hsv_image, lower_range, upper_range, hue_image;
hsv_image = this->get_HSV(input_image);
cv::inRange(hsv_image, cv::Scalar(h_low, s_low, v_low), cv::Scalar(h_low_max, 255, 255), lower_range);
cv::inRange(hsv_image, cv::Scalar(h_upper, s_upper, v_upper), cv::Scalar(h_upper_max, 255, 255), upper_range);
cv::addWeighted(lower_range, 1.0, upper_range, 1.0, 0.0, hue_image);
return hue_image;
}
White::~White()
{
}
| [
"TDJ.deWinkel@student.han.nl"
] | TDJ.deWinkel@student.han.nl |
1a05be55a21568b293d691e6d732ad102f3d5dd8 | 6ea733425583c44cd9741acf2baa3ed9649d7ae5 | /constants/constants.inc | 18ae5867d9ad2f2a228c8542c03e54a4c418ab68 | [] | no_license | PikalaxALT/pokemdred | 3164e29c84202ea21bd00690f86506e4494032f8 | 7b793f24ce062cfd5c814fb78332cff86559b36b | refs/heads/master | 2021-08-28T07:56:56.257762 | 2017-12-11T15:49:15 | 2017-12-11T15:49:15 | 113,768,385 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40 | inc | .include "constants/gba_constants.inc"
| [
"scnorton@biociphers.org"
] | scnorton@biociphers.org |
1e4e11b7b9de54f98470ec0cbeb325ee1137d843 | 6e8681a0d9195923130f6aaaec592086e9a784f9 | /Trunk/2017_fall/Resources/CppBook-SourceCode/Chap21/setops.cpp | 8113d7e6ba013649d73e6a79973dc8c3983c0ce7 | [] | no_license | rugbyprof/1063-Data-Structures | a7faa4b855f3ae18f62c654703234e786d5d7f68 | e41697c60e2ad113105634348d5211c454bcd900 | refs/heads/master | 2021-10-23T02:25:32.756031 | 2021-10-15T16:22:23 | 2021-10-15T16:22:23 | 17,293,996 | 24 | 42 | null | 2019-10-01T16:23:48 | 2014-02-28T17:30:57 | C++ | UTF-8 | C++ | false | false | 1,053 | cpp | #include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include "setoutput.h"
// Computes the intersection of sets s1 and s2
template<typename T>
std::set<T> operator&(const std::set<T>& s1, const std::set<T>& s2) {
std::set<T> result;
std::set_intersection(std::begin(s1), std::end(s1),
std::begin(s2), std::end(s2),
std::inserter(result, std::end(result)));
return result;
}
// Computes the union of sets s1 and s2
template<typename T>
std::set<T> operator|(const std::set<T>& s1, const std::set<T>& s2) {
std::set<T> result;
std::set_union(std::begin(s1), std::end(s1), std::begin(s2), std::end(s2),
std::inserter(result, std::end(result)));
return result;
}
int main() {
std::set<int> s1 {1, 2, 3, 4, 5, 6, 7, 8};
std::set<int> s2 {2, 5, 7, 9, 10};
std::cout << s1 << " & " << s2 << " = " << (s1 & s2) << '\n';
std::cout << s1 << " | " << s2 << " = " << (s1 | s2) << '\n';
}
| [
"griffin@Terrys-MBP.att.net"
] | griffin@Terrys-MBP.att.net |
3e1e85efc654409635b155aed6b2ee9db68f8e16 | 23f988531f6b59d5e2639d14d7c3183a94360cef | /net/netgame.h | cb6d1a02fdabc513ef104c01b5cc6caf826bce39 | [] | no_license | AthallahDzaki/SAMPMobile | 0f883ed25396dca6841f3c2002500c2824efb33c | 165673b0d853ede42a94ec0f09180869809aaa6e | refs/heads/master | 2023-08-01T19:41:05.482866 | 2021-10-01T00:38:32 | 2021-10-01T00:38:32 | 267,602,721 | 20 | 16 | null | null | null | null | UTF-8 | C++ | false | false | 3,868 | h | #pragma once
// raknet
#include "../vendor/RakNet/RakClientInterface.h"
#include "../vendor/RakNet/RakNetworkFactory.h"
#include "../vendor/RakNet/PacketEnumerations.h"
#include "../vendor/RakNet/StringCompressor.h"
#include "localplayer.h"
#include "remoteplayer.h"
#include "playerpool.h"
#include "vehiclepool.h"
#include "gangzonepool.h"
#include "objectpool.h"
#include "pickuppool.h"
#include "textlabelpool.h"
#include "textdrawpool.h"
#include "playerbubblepool.h"
#include "actorpool.h"
#define GAMESTATE_WAIT_CONNECT 9
#define GAMESTATE_CONNECTING 13
#define GAMESTATE_AWAIT_JOIN 15
#define GAMESTATE_CONNECTED 14
#define GAMESTATE_RESTARTING 18
#define GAMESTATE_NONE 0
#define GAMESTATE_DISCONNECTED 4
#define NETMODE_ONFOOT_SENDRATE 30
#define NETMODE_INCAR_SENDRATE 30
#define NETMODE_FIRING_SENDRATE 30
#define NETMODE_SEND_MULTIPLIER 2
#define INVALID_PLAYER_ID 0xFFFF
#define INVALID_VEHICLE_ID 0xFFFF
class CNetGame
{
public:
CNetGame(const char* szHostOrIp, int iPort, const char* szPlayerName, const char* szPass);
~CNetGame();
void Process();
CPlayerPool* GetPlayerPool() { return m_pPlayerPool; }
CVehiclePool* GetVehiclePool() { return m_pVehiclePool; }
CObjectPool* GetObjectPool() { return m_pObjectPool; }
CPickupPool* GetPickupPool() { return m_pPickupPool; }
CGangZonePool* GetGangZonePool() { return m_pGangZonePool; }
CText3DLabelsPool* GetLabelPool() { return m_pLabelPool; }
RakClientInterface* GetRakClient() { return m_pRakClient; };
CTextDrawPool* GetTextDrawPool() { return m_pTextDrawPool; }
CPlayerBubblePool* GetPlayerBubblePool() { return m_pPlayerBubblePool; }
CActorPool* GetActorPool() { return m_pActorPool; }
int GetGameState() { return m_iGameState; }
void SetGameState(int iGameState) { m_iGameState = iGameState; }
void ResetVehiclePool();
void ResetObjectPool();
void ResetPickupPool();
void ResetGangZonePool();
void ResetLabelPool();
void ShutDownForGameRestart();
void SendChatMessage(const char* szMsg);
void SendChatCommand(const char* szMsg);
void SendDialogResponse(uint16_t wDialogID, uint8_t byteButtonID, uint16_t wListboxItem, char* szInput);
void SetMapIcon(uint8_t byteIndex, float fX, float fY, float fZ, uint8_t byteIcon, int iColor, int style);
void DisableMapIcon(uint8_t byteIndex);
void UpdatePlayerScoresAndPings();
bool GetHeadMoveState();
private:
RakClientInterface* m_pRakClient;
CPlayerPool* m_pPlayerPool;
CVehiclePool* m_pVehiclePool;
CObjectPool* m_pObjectPool;
CPickupPool* m_pPickupPool;
CGangZonePool* m_pGangZonePool;
CText3DLabelsPool* m_pLabelPool;
CTextDrawPool* m_pTextDrawPool;
CPlayerBubblePool* m_pPlayerBubblePool;
CActorPool* m_pActorPool;
int m_iGameState;
uint32_t m_dwLastConnectAttempt;
uint32_t m_dwMapIcons[100];
void UpdateNetwork();
void Packet_AuthKey(Packet *p);
void Packet_DisconnectionNotification(Packet *p);
void Packet_ConnectionLost(Packet *p);
void Packet_ConnectionSucceeded(Packet *p);
void Packet_PlayerSync(Packet* pkt);
void Packet_VehicleSync(Packet* pkt);
void Packet_PassengerSync(Packet* pkt);
void Packet_MarkersSync(Packet* pkt);
void Packet_AimSync(Packet* p);
void Packet_BulletSync(Packet* pkt);
public:
char m_szHostName[0xFF];
char m_szHostOrIp[0x7F];
int m_iPort;
bool m_bZoneNames;
bool m_bUseCJWalk;
bool m_bAllowWeapons;
bool m_bHeadMove;
bool m_bLimitGlobalChatRadius;
float m_fGlobalChatRadius;
float m_fNameTagDrawDistance;
bool m_bDisableEnterExits;
bool m_bNameTagLOS;
bool m_bManualVehicleEngineAndLight;
int m_iSpawnsAvailable;
bool m_bShowPlayerTags;
int m_iShowPlayerMarkers;
bool m_bHoldTime;
uint8_t m_byteWorldTime;
uint8_t m_byteWorldMinute;
uint8_t m_byteWeather;
float m_fGravity;
int m_iDeathDropMoney;
bool m_bInstagib;
int m_iLagCompensation;
int m_iVehicleFriendlyFire;
}; | [
"discordgg5@gmail.com"
] | discordgg5@gmail.com |
fb979d41b659eb1e4b49885df18880a831e88495 | b933738dbdc36c48d7560dd980204f4aa00e68ed | /activityselection.cpp | 69c1585565795a9e82efddb625c059482cb8bbda | [] | no_license | RishyaniBhattacharya/DAA | 3d610f2dfa5534ab590a8dcc10e34c4d23ebff02 | ce59ec0fc5abc414257a51bf9c28ae76bce73ad7 | refs/heads/main | 2023-07-30T23:30:00.341300 | 2021-10-02T12:39:03 | 2021-10-02T12:39:03 | 412,326,360 | 1 | 10 | null | 2021-10-03T10:31:37 | 2021-10-01T04:31:26 | C++ | UTF-8 | C++ | false | false | 1,144 | cpp | // C++ program for activity selection problem.
// The following implementation assumes that the activities
// are already sorted according to their finish time
#include <bits/stdc++.h>
using namespace std;
// Prints a maximum set of activities that can be done by a single
// person, one at a time.
// n --> Total number of activities
// s[] --> An array that contains start time of all activities
// f[] --> An array that contains finish time of all activities
void printMaxActivities(int s[], int f[], int n)
{
int i, j;
cout <<"Following activities are selected "<< endl;
// The first activity always gets selected
i = 0;
cout <<" "<< i;
// Consider rest of the activities
for (j = 1; j < n; j++)
{
// If this activity has start time greater than or
// equal to the finish time of previously selected
// activity, then select it
if (s[j] >= f[i])
{
cout <<" " << j;
i = j;
}
}
}
// driver program to test above function
int main()
{
int s[] = {1, 3, 0, 5, 8, 5};
int f[] = {2, 4, 6, 7, 9, 9};
int n = sizeof(s)/sizeof(s[0]);
printMaxActivities(s, f, n);
return 0;
}
//this code contributed by shivanisinghss2110
| [
"noreply@github.com"
] | noreply@github.com |
686f63469e03d24c5299b631c197dafeb5903976 | 7539be0b8c84db96d2ee22d0f1a625d669926342 | /lab7.cpp | 3a95a462c31f1d64d00f3b19557ba7e4990d3c52 | [] | no_license | Brogin/semestr-1 | 484698d6f8a25efcf3582c04cee9ec52b3dcc9e0 | 078342ba1fbe30e98a70f8013163280a3a378ff1 | refs/heads/master | 2016-09-14T18:25:25.782295 | 2016-05-24T09:05:44 | 2016-05-24T09:05:44 | 59,516,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 887 | cpp | #include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void main()
{
system("color F0");
srand(time(NULL));
int size, i, oddmin, oddmax, evenmin, evenmax;
cout << "Enter size of array: ";
cin >> size;
int *arr = new int[size];
for(i=0;i<size;i++)
{
arr[i] = rand() % 10 + 1;
cout << arr[i] << " ";
}
cout << "\n";
oddmin = oddmax = evenmin = evenmax = arr[0];
for(i=1;i<size;i++)
{
if(i%2)
{
if(evenmin > arr[i])
evenmin = arr[i];
if(evenmax < arr[i])
evenmax = arr[i];
}
else
{
if(oddmin > arr[i])
oddmin = arr[i];
if(oddmax < arr[i])
oddmax = arr[i];
}
}
cout << "Odd min value: " << oddmin << "\t" << "Odd max value: " << oddmax << "\n" << "Even min value: " << evenmin << "\t" << "Even max value: " << evenmax << "\n";
delete []arr;
system("pause");
} | [
"qualintoron@gmail.com"
] | qualintoron@gmail.com |
eef003aca9be2caf6fcbcf79d366dc67267220d0 | f0b7bcc41298354b471a72a7eeafe349aa8655bf | /codebase/apps/didss/src/Dsr2Vol/Beam.cc | 8372c1711f8b838f548d144c98b036c42edbc863 | [
"BSD-3-Clause"
] | permissive | NCAR/lrose-core | 23abeb4e4f1b287725dc659fb566a293aba70069 | be0d059240ca442883ae2993b6aa112011755688 | refs/heads/master | 2023-09-01T04:01:36.030960 | 2023-08-25T00:41:16 | 2023-08-25T00:41:16 | 51,408,988 | 90 | 53 | NOASSERTION | 2023-08-18T21:59:40 | 2016-02-09T23:36:25 | C++ | UTF-8 | C++ | false | false | 6,608 | cc | // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
// ** Copyright UCAR (c) 1990 - 2016
// ** University Corporation for Atmospheric Research (UCAR)
// ** National Center for Atmospheric Research (NCAR)
// ** Boulder, Colorado, USA
// ** BSD licence applies - redistribution and use in source and binary
// ** forms, with or without modification, are permitted provided that
// ** the following conditions are met:
// ** 1) If the software is modified to produce derivative works,
// ** such modified software should be clearly marked, so as not
// ** to confuse it with the version available from UCAR.
// ** 2) Redistributions of source code must retain the above copyright
// ** notice, this list of conditions and the following disclaimer.
// ** 3) 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.
// ** 4) Neither the name of UCAR nor the names of its contributors,
// ** if any, may be used to endorse or promote products derived from
// ** this software without specific prior written permission.
// ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS
// ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
// ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
/////////////////////////////////////////////////////////////
// Beam.cc
//
// Mike Dixon, RAP, NCAR
// P.O.Box 3000, Boulder, CO, 80307-3000, USA
//
// Dec 2003
//
///////////////////////////////////////////////////////////////
#include "Beam.hh"
#include "Transform.hh"
#include <toolsa/toolsa_macros.h>
#include <toolsa/mem.h>
#include <iostream>
using namespace std;
const double Beam::missFl32 = -9999.0;
/////////////////////////////////////////////////
// construct from radarMsg
Beam::Beam(DsRadarMsg &radarMsg,
const Params ¶ms,
const vector<FieldInfo> &fields,
double nyquist_vel) :
_fields(fields),
nyquistVel(nyquist_vel),
fieldData(NULL),
censorFlag(NULL)
{
const DsRadarBeam &rbeam = radarMsg.getRadarBeam();
const DsRadarParams &rparams = radarMsg.getRadarParams();
vector<DsFieldParams *> &fparams = radarMsg.getFieldParams();
time = rbeam.dataTime;
elev = rbeam.elevation;
if (params.use_target_elev) {
elev = rbeam.targetElev;
}
if (elev > 180) {
elev -= 360.0;
}
az = rbeam.azimuth;
targetAz = rbeam.targetAz;
targetEl = rbeam.targetElev;
if (rbeam.scanMode > 0) {
scanMode = rbeam.scanMode;
} else {
scanMode = rparams.scanMode;
}
tiltNum = rbeam.tiltNum;
volNum = rbeam.volumeNum;
isIndexed = rbeam.beamIsIndexed;
angularResolution = rbeam.angularResolution;
antennaTransition = rbeam.antennaTransition;
prf = rparams.pulseRepFreq;
nyquistVel = rparams.unambigVelocity;
nGates = rparams.numGates;
if (params.remove_test_pulse) {
nGates -= params.ngates_test_pulse;
}
startRange = rparams.startRange;
gateSpacing = rparams.gateSpacing;
accept = true;
byteWidth = rbeam.byteWidth;
missing = 1;
fieldData = ucalloc2(_fields.size(), nGates, byteWidth);
censorFlag = (int *) ucalloc(nGates, sizeof(int));
// copy in the field data
// order changes from gate-by-gate to field-by-field
for (size_t ifield = 0; ifield < _fields.size(); ifield++) {
for (size_t ii = 0; ii < fparams.size(); ii++) {
if (_fields[ifield].dsrName == fparams[ii]->name) {
if (byteWidth == 4) {
fl32 *inData = (fl32 *) rbeam.data() + ii;
fl32 *outData = (fl32 *) fieldData[ifield];
for (int igate = 0; igate < nGates;
igate++, inData += fparams.size(), outData++) {
*outData = *inData;
} // igate
} else if (byteWidth == 2) {
ui16 *inData = (ui16 *) rbeam.data() + ii;
ui16 *outData = (ui16 *) fieldData[ifield];
for (int igate = 0; igate < nGates;
igate++, inData += fparams.size(), outData++) {
*outData = *inData;
} // igate
} else {
// byte width 1
ui08 *inData = (ui08 *) rbeam.data() + ii;
ui08 *outData = (ui08 *) fieldData[ifield];
for (int igate = 0; igate < nGates;
igate++, inData += fparams.size(), outData++) {
*outData = *inData;
} // igate
}
break;
} // if (!strcmp ...
} // ii
} // ifield
}
/////////////////////////////////////////////////
// construct by interpolating bewteen 2 beams
// Interpolated beam has (weight1) from beam1,
// (1.0 - weight1) from beam2
Beam::Beam(const Beam &beam1, const Beam &beam2, double weight1) :
_fields(beam1._fields),
fieldData(NULL),
censorFlag(NULL)
{
// compute the min number of gates in the beams
int minGates;
if (beam1.nGates < beam2.nGates) {
minGates = beam1.nGates;
} else {
minGates = beam2.nGates;
}
// create the missing beam
time = beam1.time + (beam2.time - beam1.time) / 2;
double weight2 = 1.0 - weight1;
az = beam1.az * weight1 + beam2.az * weight2;
elev = beam1.elev * weight1 + beam2.elev * weight2;
startRange = beam1.startRange;
gateSpacing = beam1.gateSpacing;
nGates = minGates;
byteWidth = beam1.byteWidth;
missing = beam1.missing;
fmissing = beam1.fmissing;
nyquistVel = beam1.nyquistVel;
fieldData =
ucalloc2(beam1._fields.size(), nGates, byteWidth);
censorFlag = (int *) ucalloc(nGates, sizeof(int));
for (size_t ifield = 0; ifield < beam1._fields.size(); ifield++) {
const FieldInfo &fld = beam1._fields[ifield];
bool interpDbAsPower = fld.interpDbAsPower;
bool isVel = fld.isVel;
bool allowInterp = fld.allowInterp;
for (int igate = 0; igate < nGates; igate++) {
fl32 val1 = beam1.getValue(ifield, igate);
fl32 val2 = beam2.getValue(ifield, igate);
fl32 val = Transform::interp(val1, val2, weight1, interpDbAsPower,
isVel, nyquistVel, allowInterp);
setValue(ifield, igate, val);
}
} // ifield
}
/////////////////////////////////////////////////
// destructor
Beam::~Beam()
{
if (fieldData != NULL) {
ufree2((void **) fieldData);
}
if (censorFlag != NULL) {
ufree(censorFlag);
}
}
| [
"dixon@ucar.edu"
] | dixon@ucar.edu |
c3a289f52a7d90d8472fcafd7cbe3e12f37fca7e | 370531e231033683e63848c68e062c4c2c3bd6d3 | /superSingleCell-c3dEngine/c3dEngine/core/c3dALSource.cpp | 9ed57b51dcbd62cdf026dcd79a34c10ce50dfaa8 | [] | no_license | andrew889/superSingleCell-c3dEngine | 2488689026d72d6e0a970a35584c06fe4453086a | 7df9c32b7f4fa15bfb71bc10609e5e49d4b85f04 | refs/heads/master | 2020-12-29T00:55:42.588120 | 2014-04-12T11:25:48 | 2014-04-12T11:25:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | cpp | //
// c3dALSource.cpp
// HelloOpenGL
//
// Created by wantnon (yang chao) on 14-2-23.
//
//
#include "c3dALSource.h"
void Cc3dALSource::initSource(Cc3dALBuffer*buffer){
assert(buffer);
setBuffer(buffer);
// //记录buffer和isPermanent
// m_buffer=(Cc3dALBuffer*)pBuffer;
//创建source
ALenum error;
alGenSources(1, &m_source);
if(alGetError() != AL_NO_ERROR)
{
printf("Error generating sources! %x\n", error);
C3DCHECK_AL_ERROR_DEBUG();
}
//初始化source
alSourcei(m_source, AL_BUFFER, buffer->getBuffer());
alSourcef(m_source, AL_PITCH, 1.0f);
alSourcef(m_source, AL_GAIN, 1.0f);
alSourcei(m_source, AL_LOOPING, AL_FALSE);
// 设定距离模型参数
alSourcef(m_source, AL_REFERENCE_DISTANCE, 30);
alSourcef(m_source, AL_ROLLOFF_FACTOR,0.25);
}
| [
"yangchao1@chukong-inc.com"
] | yangchao1@chukong-inc.com |
f89fa44680c6434e406f342abc271fa7053d1947 | 5ae8bbfda3174d232d8c64a888223a798245c02b | /GrandpaGetsHisGroove/Source/GrandpaGetsHisGroove/Interfaces/DanceInterface.cpp | 7b8e5ad71009b3f17cfbad3c4c01e4b0183df837 | [
"MIT"
] | permissive | Broar/sa-gamedev-2016 | 76add5f2dc88f46f8acb2629f8554ce40cb9e7c6 | dae257f8f90c5950fae98cd66bde5af17da4b84a | refs/heads/master | 2021-01-18T05:28:54.821037 | 2016-08-01T05:01:11 | 2016-08-01T05:01:11 | 63,302,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | // Copyright 2016 Team Axe Lasers
#include "GrandpaGetsHisGroove.h"
#include "DanceInterface.h"
UDanceInterface::UDanceInterface(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
| [
"broham113@gmail.com"
] | broham113@gmail.com |
fdde524f2ccfd704fd4d3e5dafbacb2774e61684 | e5d1ca5d3bb724a2c4b7add53d7ae464fa775fba | /sleuthkit/framework/tsk/framework/pipeline/TskFileAnalysisPipeline.cpp | 694d08aed1f3de40ab8a2a0dc58d5d063b496390 | [
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-free-unknown",
"LGPL-2.0-or-later",
"Zlib",
"Apache-2.0"
] | permissive | myselfanuj/OpenDF | 6a64d663d08f74fa5b01e08d581a0b1271d22cbf | 47b16f364ffd137ed300c8448f98f9d494003849 | refs/heads/master | 2020-08-11T06:57:24.768256 | 2019-10-11T20:09:28 | 2019-10-11T20:09:28 | 214,513,339 | 0 | 0 | Apache-2.0 | 2019-10-11T19:22:46 | 2019-10-11T19:22:46 | null | UTF-8 | C++ | false | false | 5,348 | cpp | /*
* The Sleuth Kit
*
* Contact: Brian Carrier [carrier <at> sleuthkit [dot] org]
* Copyright (c) 2010-2012 Basis Technology Corporation. All Rights
* reserved.
*
* This software is distributed under the Common Public License 1.0
*/
/**
* \file TskFileAnalysisPipeline.cpp
* Contains the implementation for the TskFileAnalysisPipeline class.
*/
// Include the class definition first to ensure it does not depend on subsequent includes in this file.
#include "TskFileAnalysisPipeline.h"
// TSK Framework includes
#include "tsk/framework/file/TskFileManagerImpl.h"
#include "tsk/framework/services/TskServices.h"
// Poco includes
#include "Poco/AutoPtr.h"
#include "Poco/Stopwatch.h"
// C/C++ library includes
#include <sstream>
#include <memory>
void TskFileAnalysisPipeline::run(const uint64_t fileId)
{
// Get a file object for the given fileId
std::auto_ptr<TskFile> file(TskFileManagerImpl::instance().getFile(fileId));
if (m_modules.size() == 0){
file->setStatus(TskImgDB::IMGDB_FILES_STATUS_ANALYSIS_COMPLETE);
return;
}
// Run the file object through the pipeline.
run(file.get());
}
void TskFileAnalysisPipeline::run(TskFile* file)
{
const std::string MSG_PREFIX = "TskFileAnalysisPipeline::run : ";
if (m_modules.size() == 0)
return;
if (file == NULL)
{
LOGERROR(MSG_PREFIX + "passed NULL file pointer");
throw TskNullPointerException();
}
TskImgDB& imgDB = TskServices::Instance().getImgDB();
try
{
// If this is an excluded file or the file is not ready for analysis
// we return without processing.
if (excludeFile(file))
{
std::stringstream msg;
msg << MSG_PREFIX << "skipping file (excluded) " << file->getName() << "(" << file->getId() << ")";
LOGINFO(msg.str());
file->setStatus(TskImgDB::IMGDB_FILES_STATUS_ANALYSIS_SKIPPED);
return;
}
if (file->getStatus() != TskImgDB::IMGDB_FILES_STATUS_READY_FOR_ANALYSIS)
{
std::stringstream msg;
msg << MSG_PREFIX << "skipping file (not ready) " << file->getName() << "(" << file->getId() << ")";
LOGINFO(msg.str());
return;
}
// Update status to indicate analysis is in progress.
file->setStatus(TskImgDB::IMGDB_FILES_STATUS_ANALYSIS_IN_PROGRESS);
std::stringstream msg;
msg << MSG_PREFIX << "analyzing " << file->getName() << "(" << file->getId() << ")";
LOGINFO(msg.str());
imgDB.begin();
// If there is an Executable module in the pipeline we must
// ensure that the file exists on disk.
if (m_hasExeModule && !file->exists())
{
TskFileManagerImpl::instance().saveFile(file);
}
bool bModuleFailed = false;
Poco::Stopwatch stopWatch;
for (size_t i = 0; i < m_modules.size(); i++)
{
// we have no way of knowing if the file was closed by a module,
// so always make sure it is open
file->open();
// Reset the file offset to the beginning of the file.
file->seek(0);
stopWatch.restart();
TskModule::Status status = m_modules[i]->run(file);
stopWatch.stop();
updateModuleExecutionTime(m_modules[i]->getModuleId(), stopWatch.elapsed());
imgDB.setModuleStatus(file->getId(), m_modules[i]->getModuleId(), (int)status);
// If any module encounters a failure while processing a file
// we will set the file status to failed once the pipeline is complete.
if (status == TskModule::FAIL)
bModuleFailed = true;
// Stop processing the file when a module tells us to.
else if (status == TskModule::STOP)
break;
}
// Delete the file if it exists. The file may have been created by us
// above or by a module that required it to exist on disk.
// Carved and derived files should not be deleted since the content is
// typically created by external tools.
if (file->getTypeId() != TskImgDB::IMGDB_FILES_TYPE_CARVED &&
file->getTypeId() != TskImgDB::IMGDB_FILES_TYPE_DERIVED &&
file->exists())
{
TskFileManagerImpl::instance().deleteFile(file);
}
// We allow modules to set status on the file so we only update it
// if the modules haven't.
if (file->getStatus() == TskImgDB::IMGDB_FILES_STATUS_ANALYSIS_IN_PROGRESS)
{
if (bModuleFailed)
{
file->setStatus(TskImgDB::IMGDB_FILES_STATUS_ANALYSIS_FAILED);
}
else
{
file->setStatus(TskImgDB::IMGDB_FILES_STATUS_ANALYSIS_COMPLETE);
}
}
imgDB.commit();
}
catch (std::exception& ex)
{
std::stringstream msg;
msg << MSG_PREFIX << "error while processing file id (" << file->getId() << ") : " << ex.what();
LOGERROR(msg.str());
imgDB.updateFileStatus(file->getId(), TskImgDB::IMGDB_FILES_STATUS_ANALYSIS_FAILED);
imgDB.commit();
// Rethrow the exception
throw;
}
}
| [
"agentmilindu@gmail.com"
] | agentmilindu@gmail.com |
372274668faa17138a18e849ea43c9fb22df7285 | 1250f85f2d17c1bd7a554bd9b7a1c76914223efa | /src/interfaces/wireless_commands/CalibrateAccelerometerCommand.cpp | df64c435b5ad8b9bd0d77678812d3401e1a3b861 | [] | no_license | HBuczynski/AHRS | 0cf015ccb5978fd7ddf1aeccbdd0b9b943c6d31c | 324169c7869b9d69343f6120739ec8e0b9901d4a | refs/heads/master | 2022-02-22T08:22:37.208745 | 2019-09-10T19:36:34 | 2019-09-10T19:36:34 | 111,209,994 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,460 | cpp | #include "CalibrateAccelerometerCommand.h"
#include "CommandVisitor.h"
using namespace std;
using namespace communication;
CalibrateAccelerometerCommand::CalibrateAccelerometerCommand(uint8_t axis, AccelAction action)
: Command(10,CommandType::CALIBRATE_ACCELEROMETER),
axis_(axis),
action_(action)
{}
CalibrateAccelerometerCommand::~CalibrateAccelerometerCommand()
{}
vector<uint8_t > CalibrateAccelerometerCommand::getFrameBytes()
{
initializeDataSize();
vector<uint8_t > frame = getHeader();
frame.push_back(static_cast<uint8_t>(commandType_));
frame.push_back(axis_);
frame.push_back(static_cast<uint8_t>(action_));
return frame;
}
string CalibrateAccelerometerCommand::getName()
{
return string("CalibrateAccelerometerCommand");
}
void CalibrateAccelerometerCommand::accept(CommandVisitor& visitor)
{
visitor.visit(*this);
}
uint8_t CalibrateAccelerometerCommand::getAxis() const noexcept
{
return axis_;
}
void CalibrateAccelerometerCommand::setAxis(uint8_t axis) noexcept
{
axis_ = axis;
}
void CalibrateAccelerometerCommand::setAction(AccelAction action) noexcept
{
action_ = action;
}
AccelAction CalibrateAccelerometerCommand::getAction() const noexcept
{
return action_;
}
void CalibrateAccelerometerCommand::initializeDataSize()
{
uint16_t dataSize = sizeof(commandType_);
dataSize += sizeof(axis_);
dataSize += sizeof(action_);
setDataSize(dataSize);
}
| [
"hubert.buczynski94@gmail.com"
] | hubert.buczynski94@gmail.com |
4e63000c3cb1b2cff79bb878d0d35046c7d4a820 | cd484c21d9d412d81ee3039072365fbb32947fce | /WBoard/Source/adaptors/WBCFFAdaptor.cpp | 8920904a00a700033eaf17dc6813dde4e047cd63 | [] | no_license | drivestudy/WBoard | 8c97fc4f01f58540718cd2c082562f9eab5761de | 18959203a234944fb402b444462db76c6dd5b3c6 | refs/heads/main | 2023-08-01T01:41:04.303780 | 2021-09-09T04:56:46 | 2021-09-09T04:56:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 64,645 | cpp | #include "WBCFFAdaptor.h"
#include <QtCore>
#include <QtXml>
#include <QTransform>
#include <QGraphicsItem>
#include <QSvgRenderer>
#include <QPainter>
#include "WBCFFConstants.h"
#include "globals/WBGlobals.h"
THIRD_PARTY_WARNINGS_DISABLE
#include "quazip.h"
#include "quazipfile.h"
#include "quazipfileinfo.h"
THIRD_PARTY_WARNINGS_ENABLE
WBCFFAdaptor::WBCFFAdaptor()
{
}
bool WBCFFAdaptor::convertWBZToIWB(const QString &from, const QString &to)
{
qDebug() << "starting converion from" << from << "to" << to;
QString source = QString();
if (QFileInfo(from).isDir() && QFile::exists(from)) {
qDebug() << "File specified is dir, continuing convertion";
source = from;
} else {
source = uncompressZip(from);
if (!source.isNull()) qDebug() << "File specified is zip file. Uncompressed to tmp dir, continuing convertion";
}
if (source.isNull()) {
qDebug() << "File specified is not a dir or a zip file, stopping covretion";
return false;
}
QString tmpDestination = createNewTmpDir();
if (tmpDestination.isNull()) {
qDebug() << "can't create temp destination folder. Stopping parsing...";
return false;
}
WBToCFFConverter tmpConvertrer(source, tmpDestination);
if (!tmpConvertrer) {
qDebug() << "The convertrer class is invalid, stopping conversion. Error message" << tmpConvertrer.lastErrStr();
return false;
}
bool bParceRes = tmpConvertrer.parse();
mConversionMessages << tmpConvertrer.getMessages();
if (!bParceRes) {
return false;
}
if (!compressZip(tmpDestination, to))
qDebug() << "error in compression";
//Cleanning tmp souces in filesystem
if (!QFileInfo(from).isDir())
if (!freeDir(source))
qDebug() << "can't delete tmp directory" << QDir(source).absolutePath() << "try to delete them manually";
if (!freeDir(tmpDestination))
qDebug() << "can't delete tmp directory" << QDir(tmpDestination).absolutePath() << "try to delete them manually";
return true;
}
QString WBCFFAdaptor::uncompressZip(const QString &zipFile)
{
QuaZip zip(zipFile);
if(!zip.open(QuaZip::mdUnzip)) {
qWarning() << "Import failed. Cause zip.open(): " << zip.getZipError();
return QString();
}
zip.setFileNameCodec("UTF-8");
QuaZipFileInfo info;
QuaZipFile file(&zip);
QString documentRootFolder = createNewTmpDir();
if (documentRootFolder.isNull()) {
qDebug() << "can't create tmp directory for zip file" << zipFile;
return QString();
}
QDir rootDir(documentRootFolder);
QFile out;
char c;
bool allOk = true;
for(bool more = zip.goToFirstFile(); more; more=zip.goToNextFile()) {
if(!zip.getCurrentFileInfo(&info)) {
qWarning() << "Import failed. Cause: getCurrentFileInfo(): " << zip.getZipError();
allOk = false;
break;
}
if(!file.open(QIODevice::ReadOnly)) {
allOk = false;
break;
}
if(file.getZipError()!= UNZ_OK) {
qWarning() << "Import failed. Cause: file.getFileName(): " << zip.getZipError();
allOk = false;
break;
}
QString newFileName = documentRootFolder + "/" + file.getActualFileName();
QFileInfo newFileInfo(newFileName);
rootDir.mkpath(newFileInfo.absolutePath());
out.setFileName(newFileName);
out.open(QIODevice::WriteOnly);
while(file.getChar(&c))
out.putChar(c);
out.close();
if(file.getZipError()!=UNZ_OK) {
qWarning() << "Import failed. Cause: " << zip.getZipError();
allOk = false;
break;
}
if(!file.atEnd()) {
qWarning() << "Import failed. Cause: read all but not EOF";
allOk = false;
break;
}
file.close();
if(file.getZipError()!=UNZ_OK) {
qWarning() << "Import failed. Cause: file.close(): " << file.getZipError();
allOk = false;
break;
}
}
if (!allOk) {
out.close();
file.close();
zip.close();
return QString();
}
if(zip.getZipError()!=UNZ_OK) {
qWarning() << "Import failed. Cause: zip.close(): " << zip.getZipError();
return QString();
}
return documentRootFolder;
}
bool WBCFFAdaptor::compressZip(const QString &source, const QString &destination)
{
QDir toDir = QFileInfo(destination).dir();
if (!toDir.exists())
if (!QDir().mkpath(toDir.absolutePath())) {
qDebug() << "can't create destination folder to uncompress file";
return false;
}
QuaZip zip(destination);
zip.setFileNameCodec("UTF-8");
if(!zip.open(QuaZip::mdCreate)) {
qDebug("Export failed. Cause: zip.open(): %d", zip.getZipError());
return false;
}
QuaZipFile outZip(&zip);
QFileInfo sourceInfo(source);
if (sourceInfo.isDir()) {
if (!compressDir(QFileInfo(source).absoluteFilePath(), "", &outZip))
return false;
} else if (sourceInfo.isFile()) {
if (!compressFile(QFileInfo(source).absoluteFilePath(), "", &outZip))
return false;
}
return true;
}
bool WBCFFAdaptor::compressDir(const QString &dirName, const QString &parentDir, QuaZipFile *outZip)
{
QFileInfoList dirFiles = QDir(dirName).entryInfoList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
QListIterator<QFileInfo> iter(dirFiles);
while (iter.hasNext()) {
QFileInfo curFile = iter.next();
if (curFile.isDir()) {
if (!compressDir(curFile.absoluteFilePath(), parentDir + curFile.fileName() + "/", outZip)) {
qDebug() << "error at compressing dir" << curFile.absoluteFilePath();
return false;
}
} else if (curFile.isFile()) {
if (!compressFile(curFile.absoluteFilePath(), parentDir, outZip)) {
return false;
}
}
}
return true;
}
bool WBCFFAdaptor::compressFile(const QString &fileName, const QString &parentDir, QuaZipFile *outZip)
{
QFile sourceFile(fileName);
if(!sourceFile.open(QIODevice::ReadOnly)) {
qDebug() << "Compression of file" << sourceFile.fileName() << " failed. Cause: inFile.open(): " << sourceFile.errorString();
return false;
}
if(!outZip->open(QIODevice::WriteOnly, QuaZipNewInfo(parentDir + QFileInfo(fileName).fileName(), sourceFile.fileName()))) {
qDebug() << "Compression of file" << sourceFile.fileName() << " failed. Cause: outFile.open(): " << outZip->getZipError();
sourceFile.close();
return false;
}
outZip->write(sourceFile.readAll());
if(outZip->getZipError() != UNZ_OK) {
qDebug() << "Compression of file" << sourceFile.fileName() << " failed. Cause: outFile.write(): " << outZip->getZipError();
sourceFile.close();
outZip->close();
return false;
}
if(outZip->getZipError() != UNZ_OK)
{
qWarning() << "Compression of file" << sourceFile.fileName() << " failed. Cause: outFile.close(): " << outZip->getZipError();
sourceFile.close();
outZip->close();
return false;
}
outZip->close();
sourceFile.close();
return true;
}
QString WBCFFAdaptor::createNewTmpDir()
{
int tmpNumber = 0;
QDir systemTmp = QDir::temp();
while (true) {
QString dirName = QString("CFF_adaptor_filedata_store%1.%2")
.arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm"))
.arg(tmpNumber++);
if (!systemTmp.exists(dirName)) {
if (systemTmp.mkdir(dirName)) {
QString result = systemTmp.absolutePath() + "/" + dirName;
tmpDirs.append(result);
return result;
} else {
qDebug() << "Can't create temporary dir maybe due to permissions";
return QString();
}
} else if (tmpNumber == 10) {
qWarning() << "Import failed. Failed to create temporary file ";
return QString();
}
tmpNumber++;
}
return QString();
}
bool WBCFFAdaptor::deleteDir(const QString& pDirPath) const
{
if (pDirPath == "" || pDirPath == "." || pDirPath == "..")
return false;
QDir dir(pDirPath);
if (dir.exists())
{
foreach(QFileInfo dirContent, dir.entryInfoList(QDir::Files | QDir::Dirs
| QDir::NoDotAndDotDot | QDir::Hidden | QDir::System, QDir::Name))
{
if (dirContent.isDir())
{
deleteDir(dirContent.absoluteFilePath());
}
else
{
if (!dirContent.dir().remove(dirContent.fileName()))
{
return false;
}
}
}
}
return dir.rmdir(pDirPath);
}
QList<QString> WBCFFAdaptor::getConversionMessages()
{
return mConversionMessages;
}
bool WBCFFAdaptor::freeDir(const QString &dir)
{
bool result = true;
if (!deleteDir(dir))
result = false;
tmpDirs.removeAll(QDir(dir).absolutePath());
return result;
}
void WBCFFAdaptor::freeTmpDirs()
{
foreach (QString dir, tmpDirs)
freeDir(dir);
}
WBCFFAdaptor::~WBCFFAdaptor()
{
freeTmpDirs();
}
WBCFFAdaptor::WBToCFFConverter::WBToCFFConverter(const QString &source, const QString &destination)
{
sourcePath = source;
destinationPath = destination;
errorStr = noErrorMsg;
mDataModel = new QDomDocument;
mDocumentToWrite = new QDomDocument;
mDocumentToWrite->setContent(QString("<doc></doc>"));
mIWBContentWriter = new QXmlStreamWriter;
mIWBContentWriter->setAutoFormatting(true);
iwbSVGItemsAttributes.insert(tIWBImage, iwbSVGImageAttributes);
iwbSVGItemsAttributes.insert(tIWBVideo, iwbSVGVideoAttributes);
iwbSVGItemsAttributes.insert(tIWBText, iwbSVGTextAttributes);
iwbSVGItemsAttributes.insert(tIWBTextArea, iwbSVGTextAreaAttributes);
iwbSVGItemsAttributes.insert(tIWBPolyLine, iwbSVGPolyLineAttributes);
iwbSVGItemsAttributes.insert(tIWBPolygon, iwbSVGPolygonAttributes);
iwbSVGItemsAttributes.insert(tIWBRect, iwbSVGRectAttributes);
iwbSVGItemsAttributes.insert(tIWBLine, iwbSVGLineAttributes);
iwbSVGItemsAttributes.insert(tIWBTspan, iwbSVGTspanAttributes);
}
bool WBCFFAdaptor::WBToCFFConverter::parse()
{
if(!isValid()) {
qDebug() << "document metadata is not valid. Can't parse";
return false;
}
qDebug() << "begin parsing ubz";
QFile outFile(contentIWBFileName());
if (!outFile.open(QIODevice::WriteOnly| QIODevice::Text)) {
qDebug() << "can't open output file for writing";
errorStr = "createXMLOutputPatternError";
return false;
}
mIWBContentWriter->setDevice(&outFile);
mIWBContentWriter->writeStartDocument();
mIWBContentWriter->writeStartElement(tIWBRoot);
fillNamespaces();
mIWBContentWriter->writeAttribute(aIWBVersion, avIWBVersionNo);
if (!parseMetadata()) {
if (errorStr == noErrorMsg)
errorStr = "MetadataParsingError";
outFile.close();
return false;
}
if (!parseContent()) {
if (errorStr == noErrorMsg)
errorStr = "ContentParsingError";
outFile.close();
return false;
}
mIWBContentWriter->writeEndElement();
mIWBContentWriter->writeEndDocument();
outFile.close();
qDebug() << "finished with success";
return true;
}
bool WBCFFAdaptor::WBToCFFConverter::parseMetadata()
{
int errorLine, errorColumn;
QFile metaDataFile(sourcePath + "/" + fMetadata);
if (!metaDataFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
errorStr = "can't open" + QFileInfo(sourcePath + "/" + fMetadata).absoluteFilePath();
qDebug() << errorStr;
return false;
} else if (!mDataModel->setContent(metaDataFile.readAll(), true, &errorStr, &errorLine, &errorColumn)) {
qWarning() << "Error:Parseerroratline" << errorLine << ","
<< "column" << errorColumn << ":" << errorStr;
return false;
}
QDomElement nextInElement = mDataModel->documentElement();
nextInElement = nextInElement.firstChildElement(tDescription);
if (!nextInElement.isNull()) {
mIWBContentWriter->writeStartElement(iwbNS, tIWBMeta);
mIWBContentWriter->writeAttribute(aIWBName, aCreator);
mIWBContentWriter->writeAttribute(aIWBContent, avCreator);
mIWBContentWriter->writeEndElement();
mIWBContentWriter->writeStartElement(iwbNS, tIWBMeta);
mIWBContentWriter->writeAttribute(aIWBName, aOwner);
mIWBContentWriter->writeAttribute(aIWBContent, avOwner);
mIWBContentWriter->writeEndElement();
mIWBContentWriter->writeStartElement(iwbNS, tIWBMeta);
mIWBContentWriter->writeAttribute(aIWBName, aDescription);
mIWBContentWriter->writeAttribute(aIWBContent, avDescription);
mIWBContentWriter->writeEndElement();
mIWBContentWriter->writeStartElement(iwbNS, tIWBMeta);
mIWBContentWriter->writeAttribute(aIWBName, aAbout);
mIWBContentWriter->writeAttribute(aIWBContent, nextInElement.attribute(aAbout));
mIWBContentWriter->writeEndElement();
nextInElement = nextInElement.firstChildElement();
while (!nextInElement.isNull()) {
QString textContent = nextInElement.text();
if (!textContent.trimmed().isEmpty()) {
if (nextInElement.tagName() == tWBZSize) {
QSize tmpSize = getSVGDimentions(nextInElement.text());
if (!tmpSize.isNull()) {
mSVGSize = tmpSize;
} else {
qDebug() << "can't interpret svg section size";
errorStr = "InterpretSvgSizeError";
return false;
}
} else {
mIWBContentWriter->writeStartElement(iwbNS, tIWBMeta);
mIWBContentWriter->writeAttribute(aIWBName, nextInElement.tagName());
mIWBContentWriter->writeAttribute(aIWBContent, textContent);
mIWBContentWriter->writeEndElement();
}
}
nextInElement = nextInElement.nextSiblingElement();
}
}
metaDataFile.close();
return true;
}
bool WBCFFAdaptor::WBToCFFConverter::parseContent() {
QDir sourceDir(sourcePath);
QStringList fileFilters;
fileFilters << QString(pageAlias + "???." + pageFileExtentionUBZ);
QStringList pageList = sourceDir.entryList(fileFilters, QDir::Files, QDir::Name | QDir::IgnoreCase);
QDomElement svgDocumentSection = mDataModel->createElementNS(svgIWBNS, ":"+tSvg);
if (!pageList.count()) {
qDebug() << "can't find any content file";
errorStr = "ErrorContentFile";
return false;
} else
{
QDomElement pageset = parsePageset(pageList);
if (pageset.isNull())
return false;
else
svgDocumentSection.appendChild(pageset);
}
if (QRect() == mViewbox)
{
mViewbox.setRect(0,0, mSVGSize.width(), mSVGSize.height());
}
svgDocumentSection.setAttribute(aIWBViewBox, rectToIWBAttr(mViewbox));
svgDocumentSection.setAttribute(aWidth, QString("%1").arg(mViewbox.width()));
svgDocumentSection.setAttribute(aHeight, QString("%1").arg(mViewbox.height()));
writeQDomElementToXML(svgDocumentSection);
if (!writeExtendedIwbSection()) {
if (errorStr == noErrorMsg)
errorStr = "writeExtendedIwbSectionError";
return false;
}
return true;
}
QDomElement WBCFFAdaptor::WBToCFFConverter::parsePage(const QString &pageFileName)
{
qDebug() << "begin parsing page" + pageFileName;
mSvgElements.clear();
int errorLine, errorColumn;
QFile pageFile(sourcePath + "/" + pageFileName);
if (!pageFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "can't open file" << pageFileName << "for reading";
return QDomElement();
} else if (!mDataModel->setContent(pageFile.readAll(), true, &errorStr, &errorLine, &errorColumn)) {
qWarning() << "Error:Parseerroratline" << errorLine << ","
<< "column" << errorColumn << ":" << errorStr;
pageFile.close();
return QDomElement();
}
QDomElement page;
QDomElement group;
QDomElement nextTopElement = mDataModel->firstChildElement();
while (!nextTopElement.isNull()) {
QString tagname = nextTopElement.tagName();
if (tagname == tSvg) {
page = parseSvgPageSection(nextTopElement);
if (page.isNull()) {
qDebug() << "The page is empty.";
pageFile.close();
return QDomElement();
}
} else if (tagname == tWBZGroups) {
group = parseGroupsPageSection(nextTopElement);
if (group.isNull()) {
qDebug() << "Page doesn't contains any groups.";
pageFile.close();
return QDomElement();
}
}
nextTopElement = nextTopElement.nextSiblingElement();
}
pageFile.close();
return page.hasChildNodes() ? page : QDomElement();
}
QDomElement WBCFFAdaptor::WBToCFFConverter::parsePageset(const QStringList &pageFileNames)
{
QMultiMap<int, QDomElement> pageList;
int iPageNo = 1;
QStringListIterator curPage(pageFileNames);
while (curPage.hasNext()) {
QString curPageFile = curPage.next();
QDomElement iterElement = parsePage(curPageFile);
if (!iterElement.isNull())
{
iterElement.setAttribute(tId, iPageNo);
addSVGElementToResultModel(iterElement, pageList, iPageNo);
iPageNo++;
}
else
return QDomElement();
}
if (!pageList.count())
return QDomElement();
QDomElement svgPagesetElement = mDocumentToWrite->createElementNS(svgIWBNS,":"+ tIWBPageSet);
QMapIterator<int, QDomElement> nextSVGElement(pageList);
nextSVGElement.toFront();
while (nextSVGElement.hasNext())
svgPagesetElement.appendChild(nextSVGElement.next().value());
return svgPagesetElement.hasChildNodes() ? svgPagesetElement : QDomElement();
}
QDomElement WBCFFAdaptor::WBToCFFConverter::parseSvgPageSection(const QDomElement &element)
{
if (element.hasAttribute(aWBZViewBox)) {
setViewBox(getViewboxRect(element.attribute(aWBZViewBox)));
}
QMultiMap<int, QDomElement> svgElements;
QDomElement svgElementPart = mDocumentToWrite->createElementNS(svgIWBNS,":"+ tIWBPage);
if (element.hasAttribute(aDarkBackground)) {
createBackground(element, svgElements);
}
QDomElement nextElement = element.firstChildElement();
while (!nextElement.isNull()) {
QString tagName = nextElement.tagName();
if (tagName == tUBZG)
parseSVGGGroup(nextElement, svgElements);
else if (tagName == tWBZImage)
parseWBZImage(nextElement, svgElements);
else if (tagName == tWBZVideo)
parseWBZVideo(nextElement, svgElements);
else if (tagName == tWBZAudio)
parseWBZAudio(nextElement, svgElements);
else if (tagName == tWBZForeignObject)
parseForeignObject(nextElement, svgElements);
else if (tagName == tWBZLine)
parseWBZLine(nextElement, svgElements);
else if (tagName == tWBZPolygon)
parseWBZPolygon(nextElement, svgElements);
else if (tagName == tWBZPolyline)
parseWBZPolyline(nextElement, svgElements);
else if (tagName == tWBZGroups)
parseGroupsPageSection(nextElement);
nextElement = nextElement.nextSiblingElement();
}
if (0 == svgElements.count())
return QDomElement();
QMapIterator<int, QDomElement> nextSVGElement(svgElements);
nextSVGElement.toFront();
while (nextSVGElement.hasNext())
svgElementPart.appendChild(nextSVGElement.next().value());
return svgElementPart.hasChildNodes() ? svgElementPart : QDomElement();
}
void WBCFFAdaptor::WBToCFFConverter::writeQDomElementToXML(const QDomNode &node)
{
if (!node.isNull()) {
if (node.isText())
mIWBContentWriter->writeCharacters(node.nodeValue());
else {
mIWBContentWriter->writeStartElement(node.namespaceURI(), node.toElement().tagName());
for (int i = 0; i < node.toElement().attributes().count(); i++) {
QDomAttr attr = node.toElement().attributes().item(i).toAttr();
mIWBContentWriter->writeAttribute(attr.name(), attr.value());
}
QDomNode child = node.firstChild();
while(!child.isNull()) {
writeQDomElementToXML(child);
child = child.nextSibling();
}
mIWBContentWriter->writeEndElement();
}
}
}
bool WBCFFAdaptor::WBToCFFConverter::writeExtendedIwbSection()
{
if (!mExtendedElements.count()) {
qDebug() << "extended iwb content list is empty";
errorStr = "EmptyExtendedIwbSectionContentError";
return false;
}
QListIterator<QDomElement> nextExtendedIwbElement(mExtendedElements);
while (nextExtendedIwbElement.hasNext()) {
writeQDomElementToXML(nextExtendedIwbElement.next());
}
return true;
}
QDomElement WBCFFAdaptor::WBToCFFConverter::parseGroupsPageSection(const QDomElement &groupRoot)
{
if (!groupRoot.hasChildNodes()) {
qDebug() << "Group root is empty";
return QDomElement();
}
QDomElement groupElement = groupRoot.firstChildElement();
while (!groupElement.isNull()) {
QDomElement extendedElement = mDataModel->createElementNS(iwbNS, groupElement.tagName());
QDomElement groupChildElement = groupElement.firstChildElement();
while (!groupChildElement.isNull()) {
QDomElement extSubElement = mDataModel->createElementNS(iwbNS, groupChildElement.tagName());
extSubElement.setAttribute(aRef, groupChildElement.attribute(aID, QUuid().toString()));
extendedElement.appendChild(extSubElement);
groupChildElement = groupChildElement.nextSiblingElement();
}
mExtendedElements.append(extendedElement);
groupElement = groupElement.nextSiblingElement();
}
qDebug() << "parsing ubz group section";
return groupRoot;
}
QString WBCFFAdaptor::WBToCFFConverter::getDstContentFolderName(const QString &elementType)
{
QString sRet;
QString sDstContentFolderName;
// widgets must be saved as .png images.
if ((tIWBImage == elementType) || (tWBZForeignObject == elementType))
sDstContentFolderName = cfImages;
else
if (tIWBVideo == elementType)
sDstContentFolderName = cfVideos;
else
if (tIWBAudio == elementType)
sDstContentFolderName = cfAudios;
sRet = sDstContentFolderName;
return sRet;
}
QString WBCFFAdaptor::WBToCFFConverter::getSrcContentFolderName(QString href)
{
QString sRet;
QStringList ls = href.split("/");
for (int i = 0; i < ls.count()-1; i++)
{
QString sPart = ls.at(i);
if (wbzContentFolders.contains(sPart))
{
sRet = sPart;
}
}
// if (0 < ls.count())
// sRet = ls.at(ls.count()-1);
//
// sRet = href.remove(sRet);
//
// if (sRet.endsWith("/"))
// sRet.remove("/");
return sRet;
}
QString WBCFFAdaptor::WBToCFFConverter::getFileNameFromPath(const QString sPath)
{
QString sRet;
QStringList sl = sPath.split("/",QString::SkipEmptyParts);
if (0 < sl.count())
{
QString name = sl.at(sl.count()-1);
QString extention = getExtentionFromFileName(name);
if (feWgt == extention)
{
name.remove("{");
name.remove("}");
}
name.remove(name.length()-extention.length(), extention.length());
name += convertExtention(extention);
sRet = name;
}
return sRet;
}
QString WBCFFAdaptor::WBToCFFConverter::getExtentionFromFileName(const QString &filename)
{
QStringList sl = filename.split("/",QString::SkipEmptyParts);
if (0 < sl.count())
{
QString name = sl.at(sl.count()-1);
QStringList tl = name.split(".");
return tl.at(tl.count()-1);
}
return QString();
}
QString WBCFFAdaptor::WBToCFFConverter::convertExtention(const QString &ext)
{
QString sRet;
if (feSvg == ext)
sRet = fePng;
else
if (feWgt == ext)
sRet = fePng;
else
sRet = ext;
return sRet;
}
QString WBCFFAdaptor::WBToCFFConverter::getElementTypeFromUBZ(const QDomElement &element)
{
QString sRet;
if (tWBZForeignObject == element.tagName())
{
QString sPath;
if (element.hasAttribute(aWBZType))
{
if (avWBZText == element.attribute(aWBZType))
sRet = tIWBTextArea;
else
sRet = element.attribute(aWBZType);
}
else
{
if (element.hasAttribute(aSrc))
sPath = element.attribute(aSrc);
else
if (element.hasAttribute(aWBZHref))
sPath = element.attribute(aWBZHref);
QStringList tsl = sPath.split(".", QString::SkipEmptyParts);
if (0 < tsl.count())
{
QString elementType = tsl.at(tsl.count()-1);
if (iwbElementImage.contains(elementType))
sRet = tIWBImage;
else
if (iwbElementAudio.contains(elementType))
sRet = tIWBAudio;
else
if (iwbElementVideo.contains(elementType))
sRet = tIWBVideo;
}
}
}
else
sRet = element.tagName();
return sRet;
}
int WBCFFAdaptor::WBToCFFConverter::getElementLayer(const QDomElement &element)
{
int iRetLayer = 0;
if (element.hasAttribute(aZLayer))
iRetLayer = (int)element.attribute(aZLayer).toDouble();
else
iRetLayer = DEFAULT_LAYER;
return iRetLayer;
}
bool WBCFFAdaptor::WBToCFFConverter::itIsSupportedFormat(const QString &format) const
{
bool bRet;
QStringList tsl = format.split(".", QString::SkipEmptyParts);
if (0 < tsl.count())
bRet = cffSupportedFileFormats.contains(tsl.at(tsl.count()-1).toLower());
else
bRet = false;
return bRet;
}
bool WBCFFAdaptor::WBToCFFConverter::itIsFormatToConvert(const QString &format) const
{
foreach (QString f, wbzFormatsToConvert.split(","))
{
if (format == f)
return true;
}
return false;
}
bool WBCFFAdaptor::WBToCFFConverter::itIsSVGElementAttribute(const QString ItemType, const QString &AttrName)
{
QString allowedElementAttributes = iwbSVGItemsAttributes[ItemType];
allowedElementAttributes.remove("/t");
allowedElementAttributes.remove(" ");
foreach(QString attr, allowedElementAttributes.split(","))
{
if (AttrName == attr.trimmed())
return true;
}
return false;
}
bool WBCFFAdaptor::WBToCFFConverter::itIsIWBAttribute(const QString &attribute) const
{
foreach (QString attr, iwbElementAttributes.split(","))
{
if (attribute == attr.trimmed())
return true;
}
return false;
}
bool WBCFFAdaptor::WBToCFFConverter::itIsWBZAttributeToConvert(const QString &attribute) const
{
foreach (QString attr, wbzElementAttributesToConvert.split(","))
{
if (attribute == attr.trimmed())
return true;
}
return false;
}
bool WBCFFAdaptor::WBToCFFConverter::ibwAddLine(int x1, int y1, int x2, int y2, QString color, int width, bool isBackground)
{
bool bRet = true;
QDomDocument doc;
QDomElement svgBackgroundCrossPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":line");
QDomElement iwbBackgroundCrossPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
QString sUUID = QUuid::createUuid().toString();
svgBackgroundCrossPart.setTagName(tIWBLine);
svgBackgroundCrossPart.setAttribute(aX+"1", x1);
svgBackgroundCrossPart.setAttribute(aY+"1", y1);
svgBackgroundCrossPart.setAttribute(aX+"2", x2);
svgBackgroundCrossPart.setAttribute(aY+"2", y2);
svgBackgroundCrossPart.setAttribute(aStroke, color);
svgBackgroundCrossPart.setAttribute(aStrokeWidth, width);
svgBackgroundCrossPart.setAttribute(aID, sUUID);
if (isBackground)
{
iwbBackgroundCrossPart.setAttribute(aRef, sUUID);
iwbBackgroundCrossPart.setAttribute(aLocked, avTrue);
addIWBElementToResultModel(iwbBackgroundCrossPart);
}
addSVGElementToResultModel(svgBackgroundCrossPart, mSvgElements, DEFAULT_BACKGROUND_CROSS_LAYER);
if (!bRet)
{
qDebug() << "|error at creating crosses on background";
errorStr = "CreatingCrossedBackgroundParsingError.";
}
return bRet;
}
QTransform WBCFFAdaptor::WBToCFFConverter::getTransformFromWBZ(const QDomElement &ubzElement)
{
QTransform trRet;
QStringList transformParameters;
QString ubzTransform = ubzElement.attribute(aTransform);
ubzTransform.remove("matrix");
ubzTransform.remove("(");
ubzTransform.remove(")");
transformParameters = ubzTransform.split(",", QString::SkipEmptyParts);
if (6 <= transformParameters.count())
{
QTransform *tr = NULL;
tr = new QTransform(transformParameters.at(0).toDouble(),
transformParameters.at(1).toDouble(),
transformParameters.at(2).toDouble(),
transformParameters.at(3).toDouble(),
transformParameters.at(4).toDouble(),
transformParameters.at(5).toDouble());
trRet = *tr;
delete tr;
}
if (6 <= transformParameters.count())
{
QTransform *tr = NULL;
tr = new QTransform(transformParameters.at(0).toDouble(),
transformParameters.at(1).toDouble(),
transformParameters.at(2).toDouble(),
transformParameters.at(3).toDouble(),
transformParameters.at(4).toDouble(),
transformParameters.at(5).toDouble());
trRet = *tr;
delete tr;
}
return trRet;
}
qreal WBCFFAdaptor::WBToCFFConverter::getAngleFromTransform(const QTransform &tr)
{
qreal angle = -(atan(tr.m21()/tr.m11())*180/PI);
if (tr.m21() > 0 && tr.m11() < 0)
angle += 180;
else
if (tr.m21() < 0 && tr.m11() < 0)
angle += 180;
return angle;
}
void WBCFFAdaptor::WBToCFFConverter::setGeometryFromWBZ(const QDomElement &ubzElement, QDomElement &iwbElement)
{
setCoordinatesFromWBZ(ubzElement,iwbElement);
}
void WBCFFAdaptor::WBToCFFConverter::setCoordinatesFromWBZ(const QDomElement &ubzElement, QDomElement &iwbElement)
{
QTransform tr;
if (QString() != ubzElement.attribute(aTransform))
tr = getTransformFromWBZ(ubzElement);
qreal x = ubzElement.attribute(aX).toDouble();
qreal y = ubzElement.attribute(aY).toDouble();
qreal height = ubzElement.attribute(aHeight).toDouble();
qreal width = ubzElement.attribute(aWidth).toDouble();
qreal alpha = getAngleFromTransform(tr);
QRectF itemRect;
QGraphicsRectItem item;
item.setRect(0,0, width, height);
item.setTransform(tr);
item.setRotation(-alpha);
QMatrix sceneMatrix = item.sceneMatrix();
iwbElement.setAttribute(aX, x);
iwbElement.setAttribute(aY, y);
iwbElement.setAttribute(aHeight, height*sceneMatrix.m22());
iwbElement.setAttribute(aWidth, width*sceneMatrix.m11());
iwbElement.setAttribute(aTransform, QString("rotate(%1) translate(%2,%3)").arg(alpha)
.arg(sceneMatrix.dx())
.arg(sceneMatrix.dy()));
}
bool WBCFFAdaptor::WBToCFFConverter::setContentFromWBZ(const QDomElement &ubzElement, QDomElement &svgElement)
{
bool bRet = true;
QString srcPath;
if (tWBZForeignObject != ubzElement.tagName())
srcPath = ubzElement.attribute(aWBZHref);
else
srcPath = ubzElement.attribute(aSrc);
QString sSrcContentFolder = getSrcContentFolderName(srcPath);
QString sSrcFileName = sourcePath + "/" + srcPath ;
QString fileExtention = getExtentionFromFileName(sSrcFileName);
QString sDstContentFolder = getDstContentFolderName(ubzElement.tagName());
QString sDstFileName(QString(QUuid::createUuid().toString()+"."+convertExtention(fileExtention)));
if (itIsSupportedFormat(fileExtention))
{
sSrcFileName = sourcePath + "/" + sSrcContentFolder + "/" + getFileNameFromPath(srcPath);
QFile srcFile;
srcFile.setFileName(sSrcFileName);
QDir dstDocFolder(destinationPath);
if (!dstDocFolder.exists(sDstContentFolder))
bRet &= dstDocFolder.mkdir(sDstContentFolder);
if (bRet)
{
QString dstFilePath = destinationPath+"/"+sDstContentFolder+"/"+sDstFileName;
bRet &= srcFile.copy(dstFilePath);
}
if (bRet)
{
svgElement.setAttribute(aSVGHref, sDstContentFolder+"/"+sDstFileName);
}
}
else if (itIsFormatToConvert(fileExtention))
{
if (feSvg == fileExtention)
{
QDir dstDocFolder(destinationPath);
if (!dstDocFolder.exists(sDstContentFolder))
bRet &= dstDocFolder.mkdir(sDstContentFolder);
if (bRet)
{
if (feSvg == fileExtention)
{
QString dstFilePath = destinationPath+"/"+sDstContentFolder+"/"+sDstFileName;
bRet &= createPngFromSvg(sSrcFileName, dstFilePath, getTransformFromWBZ(ubzElement));
}
else
bRet = false;
}
if (bRet)
{
svgElement.setAttribute(aSVGHref, sDstContentFolder+"/"+sDstFileName);
}
}
}
else
{
addLastExportError(QObject::tr("Element ID = ") + QString("%1 \r\n").arg(ubzElement.attribute(aWBZUuid))
+ QString("Source file = ") + QString("%1 \r\n").arg(ubzElement.attribute(aWBZSource))
+ QObject::tr("Content is not supported in destination format."));
bRet = false;
}
if (!bRet)
{
qDebug() << "format is not supported by CFF";
}
return bRet;
}
void WBCFFAdaptor::WBToCFFConverter::setCFFTextFromHTMLTextNode(const QDomElement htmlTextNode, QDomElement &iwbElement)
{
QDomDocument textDoc;
QDomElement textParentElement = iwbElement;
QString textString;
QDomNode htmlPNode = htmlTextNode.firstChild();
bool bTbreak = false;
while(!htmlPNode.isNull())
{
if (bTbreak)
{
bTbreak = false;
QDomElement tbreakNode = textDoc.createElementNS(svgIWBNS, svgIWBNSPrefix+":"+tIWBTbreak);
textParentElement.appendChild(tbreakNode.cloneNode(true));
}
QDomNode spanNode = htmlPNode.firstChild();
while (!spanNode.isNull())
{
if (spanNode.isText())
{
QDomText nodeText = textDoc.createTextNode(spanNode.nodeValue());
textParentElement.appendChild(nodeText.cloneNode(true));
}
else
if (spanNode.isElement())
{
QDomElement pElementIwb;
QDomElement spanElement = textDoc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + tIWBTspan);
setCommonAttributesFromUBZ(htmlPNode.toElement(), pElementIwb, spanElement);
if (spanNode.hasAttributes())
{
int attrCount = spanNode.attributes().count();
if (0 < attrCount)
{
for (int i = 0; i < attrCount; i++)
{
QStringList cffAttributes = spanNode.attributes().item(i).nodeValue().split(";", QString::SkipEmptyParts);
{
for (int i = 0; i < cffAttributes.count(); i++)
{
QString attr = cffAttributes.at(i).trimmed();
QStringList AttrVal = attr.split(":", QString::SkipEmptyParts);
if(1 < AttrVal.count())
{
QString sAttr = ubzAttrNameToCFFAttrName(AttrVal.at(0));
if (itIsSVGElementAttribute(spanElement.tagName(), sAttr))
spanElement.setAttribute(sAttr, ubzAttrValueToCFFAttrName(AttrVal.at(1)));
}
}
}
}
}
}
QDomText nodeText = textDoc.createTextNode(spanNode.firstChild().nodeValue());
spanElement.appendChild(nodeText);
textParentElement.appendChild(spanElement.cloneNode(true));
}
spanNode = spanNode.nextSibling();
}
bTbreak = true;
htmlPNode = htmlPNode.nextSibling();
}
}
QString WBCFFAdaptor::WBToCFFConverter::ubzAttrNameToCFFAttrName(QString cffAttrName)
{
QString sRet = cffAttrName;
if (QString("color") == cffAttrName)
sRet = QString("fill");
if (QString("align") == cffAttrName)
sRet = QString("text-align");
return sRet;
}
QString WBCFFAdaptor::WBToCFFConverter::ubzAttrValueToCFFAttrName(QString cffValue)
{
QString sRet = cffValue;
if (QString("text") == cffValue)
sRet = QString("normal");
return sRet;
}
bool WBCFFAdaptor::WBToCFFConverter::setCFFAttribute(const QString &attributeName, const QString &attributeValue, const QDomElement &ubzElement, QDomElement &iwbElement, QDomElement &svgElement)
{
bool bRet = true;
bool bNeedsIWBSection = false;
if (itIsIWBAttribute(attributeName))
{
if (!((aBackground == attributeName) && (avFalse == attributeValue)))
{
iwbElement.setAttribute(attributeName, attributeValue);
bNeedsIWBSection = true;
}
}
else
if (itIsWBZAttributeToConvert(attributeName))
{
if (aTransform == attributeName)
{
setGeometryFromWBZ(ubzElement, svgElement);
}
else
if (attributeName.contains(aWBZUuid))
{
QString parentId = ubzElement.attribute(aWBZParent);
QString id;
if (!parentId.isEmpty())
id = "{" + parentId + "}" + "{" + ubzElement.attribute(aWBZUuid)+"}";
else
id = "{" + ubzElement.attribute(aWBZUuid)+"}";
svgElement.setAttribute(aID, id);
}
else
if (attributeName.contains(aWBZHref)||attributeName.contains(aSrc))
{
bRet &= setContentFromWBZ(ubzElement, svgElement);
bNeedsIWBSection = bRet||bNeedsIWBSection;
}
}
else
if (itIsSVGElementAttribute(svgElement.tagName(),attributeName))
{
svgElement.setAttribute(attributeName, attributeValue);
}
if (bNeedsIWBSection)
{
if (0 < iwbElement.attributes().count())
{
QStringList tl = ubzElement.attribute(aSVGHref).split("/");
QString id = tl.at(tl.count()-1);
// if element already have an ID, we use it. Else we create new id for element.
if (QString() == id)
id = QUuid::createUuid().toString();
svgElement.setAttribute(aID, id);
iwbElement.setAttribute(aRef, id);
}
}
return bRet;
}
bool WBCFFAdaptor::WBToCFFConverter::setCommonAttributesFromUBZ(const QDomElement &ubzElement, QDomElement &iwbElement, QDomElement &svgElement)
{
bool bRet = true;
for (int i = 0; i < ubzElement.attributes().count(); i++)
{
QDomNode attribute = ubzElement.attributes().item(i);
QString attributeName = ubzAttrNameToCFFAttrName(attribute.nodeName().remove("ub:"));
bRet &= setCFFAttribute(attributeName, ubzAttrValueToCFFAttrName(attribute.nodeValue()), ubzElement, iwbElement, svgElement);
if (!bRet) break;
}
return bRet;
}
void WBCFFAdaptor::WBToCFFConverter::setViewBox(QRect viewbox)
{
mViewbox |= viewbox;
}
QDomNode WBCFFAdaptor::WBToCFFConverter::findTextNode(const QDomNode &node)
{
QDomNode iterNode = node;
while (!iterNode.isNull())
{
if (iterNode.isText())
{
if (!iterNode.isNull())
return iterNode;
}
else
{
if (!iterNode.firstChild().isNull())
{
QDomNode foundNode = findTextNode(iterNode.firstChild());
if (!foundNode.isNull())
if (foundNode.isText())
return foundNode;
}
}
if (!iterNode.nextSibling().isNull())
iterNode = iterNode.nextSibling();
else
break;
}
return iterNode;
}
QDomNode WBCFFAdaptor::WBToCFFConverter::findNodeByTagName(const QDomNode &node, QString tagName)
{
QDomNode iterNode = node;
while (!iterNode.isNull())
{
QString t = iterNode.toElement().tagName();
if (tagName == t)
return iterNode;
else
{
if (!iterNode.firstChildElement().isNull())
{
QDomNode foundNode = findNodeByTagName(iterNode.firstChildElement(), tagName);
if (!foundNode.isNull()){
if (foundNode.isElement())
{
if (tagName == foundNode.toElement().tagName())
return foundNode;
}
else
break;
}
}
}
if (!iterNode.nextSibling().isNull())
iterNode = iterNode.nextSibling();
else
break;
}
return QDomNode();
}
bool WBCFFAdaptor::WBToCFFConverter::createBackground(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
qDebug() << "|creating element background";
QDomDocument doc;
//QDomElement svgBackgroundElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + tWBZImage);
QDomElement svgBackgroundElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + tIWBRect);
QDomElement iwbBackgroundElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
QRect bckRect(mViewbox);
if (0 <= mViewbox.topLeft().x())
bckRect.topLeft().setX(0);
if (0 <= mViewbox.topLeft().y())
bckRect.topLeft().setY(0);
if (QRect() != bckRect)
{
QString sElementID = QUuid::createUuid().toString();
bool darkBackground = (avTrue == element.attribute(aDarkBackground));
svgBackgroundElementPart.setAttribute(aFill, darkBackground ? "black" : "white");
svgBackgroundElementPart.setAttribute(aID, sElementID);
svgBackgroundElementPart.setAttribute(aX, bckRect.x());
svgBackgroundElementPart.setAttribute(aY, bckRect.y());
svgBackgroundElementPart.setAttribute(aHeight, bckRect.height());
svgBackgroundElementPart.setAttribute(aWidth, bckRect.width());
//svgBackgroundElementPart.setAttribute(aSVGHref, backgroundImagePath);
iwbBackgroundElementPart.setAttribute(aRef, sElementID);
iwbBackgroundElementPart.setAttribute(aBackground, avTrue);
//iwbBackgroundElementPart.setAttribute(aLocked, avTrue);
addSVGElementToResultModel(svgBackgroundElementPart, dstSvgList, DEFAULT_BACKGROUND_LAYER);
addIWBElementToResultModel(iwbBackgroundElementPart);
return true;
}
else
{
qDebug() << "|error at creating element background";
errorStr = "CreatingElementBackgroundParsingError.";
return false;
}
}
QString WBCFFAdaptor::WBToCFFConverter::createBackgroundImage(const QDomElement &element, QSize size)
{
QString sRet;
QString sDstFileName(fIWBBackground);
bool bDirExists = true;
QDir dstDocFolder(destinationPath);
if (!dstDocFolder.exists(cfImages))
bDirExists &= dstDocFolder.mkdir(cfImages);
QString dstFilePath;
if (bDirExists)
dstFilePath = destinationPath+"/"+cfImages+"/"+sDstFileName;
if (!QFile().exists(dstFilePath))
{
QRect rect(0,0, size.width(), size.height());
QImage *bckImage = new QImage(size, QImage::Format_RGB888);
QPainter *painter = new QPainter(bckImage);
bool darkBackground = (avTrue == element.attribute(aDarkBackground));
QColor bCrossColor;
bCrossColor = darkBackground?QColor(Qt::white):QColor(Qt::blue);
int penAlpha = (int)(255/2);
bCrossColor.setAlpha(penAlpha);
painter->setPen(bCrossColor);
painter->setBrush(darkBackground?QColor(Qt::black):QColor(Qt::white));
painter->drawRect(rect);
if (avTrue == element.attribute(aCrossedBackground))
{
qreal firstY = ((int) (rect.y () / iCrossSize)) * iCrossSize;
for (qreal yPos = firstY; yPos <= rect.y () + rect.height (); yPos += iCrossSize)
{
painter->drawLine (rect.x (), yPos, rect.x () + rect.width (), yPos);
}
qreal firstX = ((int) (rect.x () / iCrossSize)) * iCrossSize;
for (qreal xPos = firstX; xPos <= rect.x () + rect.width (); xPos += iCrossSize)
{
painter->drawLine (xPos, rect.y (), xPos, rect.y () + rect.height ());
}
}
painter->end();
painter->save();
if (QString() != dstFilePath)
if (bckImage->save(dstFilePath))
sRet = cfImages+"/"+sDstFileName;
delete bckImage;
delete painter;
}
else
sRet = cfImages+"/"+sDstFileName;
return sRet;
}
bool WBCFFAdaptor::WBToCFFConverter::createPngFromSvg(QString &svgPath, QString &dstPath, QTransform transformation, QSize size)
{
if (QFile().exists(svgPath))
{
QImage i(svgPath);
QSize iSize = (QSize() == size)?QSize(i.size().width()*transformation.m11(), i.size().height()*transformation.m22()):size;
QImage image(iSize, QImage::Format_ARGB32_Premultiplied);
image.fill(0);
QPainter imagePainter(&image);
QSvgRenderer renderer(svgPath);
renderer.render(&imagePainter);
return image.save(dstPath);
}
else
return false;
}
bool WBCFFAdaptor::WBToCFFConverter::parseSVGGGroup(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
qDebug() << "|parsing g section";
QDomElement nextElement = element.firstChildElement();
if (nextElement.isNull()) {
qDebug() << "Empty g element";
errorStr = "EmptyGSection";
return false;
}
QMultiMap<int, QDomElement> svgElements;
QDomDocument doc;
QDomElement svgElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + tIWBG);
QDomElement iwbElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
// Elements can know about its layer, so it must add result QDomElements to ordrered list.
while (!nextElement.isNull()) {
QString tagName = nextElement.tagName();
if (tagName == tWBZLine) parseWBZLine(nextElement, svgElements);
else if (tagName == tWBZPolygon) parseWBZPolygon(nextElement, svgElements);
else if (tagName == tWBZPolyline) parseWBZPolyline(nextElement, svgElements);
nextElement = nextElement.nextSiblingElement();
}
QList<int> layers;
QMapIterator<int, QDomElement> nextSVGElement(svgElements);
while (nextSVGElement.hasNext())
layers << nextSVGElement.next().key();
qSort(layers);
int layer = layers.at(0);
nextSVGElement.toFront();
while (nextSVGElement.hasNext())
svgElementPart.appendChild(nextSVGElement.next().value());
addSVGElementToResultModel(svgElementPart, dstSvgList, layer);
return true;
}
bool WBCFFAdaptor::WBToCFFConverter::parseWBZImage(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
qDebug() << "|parsing image";
QDomDocument doc;
QDomElement svgElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + getElementTypeFromUBZ(element));
QDomElement iwbElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
if (setCommonAttributesFromUBZ(element, iwbElementPart, svgElementPart))
{
addSVGElementToResultModel(svgElementPart, dstSvgList, getElementLayer(element));
if (0 < iwbElementPart.attributes().count())
addIWBElementToResultModel(iwbElementPart);
return true;
}
else
{
qDebug() << "|error at image parsing";
errorStr = "ImageParsingError";
return false;
}
}
bool WBCFFAdaptor::WBToCFFConverter::parseWBZVideo(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
qDebug() << "|parsing video";
QDomDocument doc;
QDomElement svgElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + getElementTypeFromUBZ(element));
QDomElement iwbElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
if (setCommonAttributesFromUBZ(element, iwbElementPart, svgElementPart))
{
QDomElement svgSwitchSection = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + tIWBSwitch);
svgSwitchSection.appendChild(svgElementPart);
QDomElement svgText = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + tIWBTextArea);
svgText.setAttribute(aX, svgElementPart.attribute(aX));
svgText.setAttribute(aY, svgElementPart.attribute(aY));
svgText.setAttribute(aWidth, svgElementPart.attribute(aWidth));
svgText.setAttribute(aHeight, svgElementPart.attribute(aHeight));
svgText.setAttribute(aTransform, svgElementPart.attribute(aTransform));
QDomText text = doc.createTextNode("Cannot Open Content");
svgText.appendChild(text);
svgSwitchSection.appendChild(svgText);
addSVGElementToResultModel(svgSwitchSection, dstSvgList, getElementLayer(element));
if (0 < iwbElementPart.attributes().count())
addIWBElementToResultModel(iwbElementPart);
return true;
}
else
{
qDebug() << "|error at video parsing";
errorStr = "VideoParsingError";
return false;
}
}
bool WBCFFAdaptor::WBToCFFConverter::parseWBZAudio(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
qDebug() << "|parsing audio";
QDomDocument doc;
QDomElement svgElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + getElementTypeFromUBZ(element));
QDomElement iwbElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
if (setCommonAttributesFromUBZ(element, iwbElementPart, svgElementPart))
{
//we must create image-containers for audio files
int audioImageDimention = qMin(svgElementPart.attribute(aWidth).toInt(), svgElementPart.attribute(aHeight).toInt());
QString srcAudioImageFile(sAudioElementImage);
QString elementId = QString(QUuid::createUuid().toString());
QString sDstAudioImageFileName = elementId+"."+fePng;
QString dstAudioImageFilePath = destinationPath+"/"+cfImages+"/"+sDstAudioImageFileName;
QString dstAudioImageRelativePath = cfImages+"/"+sDstAudioImageFileName;
QFile srcFile(srcAudioImageFile);
//creating folder for audioImage
QDir dstDocFolder(destinationPath);
bool bRes = true;
if (!dstDocFolder.exists(cfImages))
bRes &= dstDocFolder.mkdir(cfImages);
if (bRes && createPngFromSvg(srcAudioImageFile, dstAudioImageFilePath, getTransformFromWBZ(element), QSize(audioImageDimention, audioImageDimention)))
{
// first we place content
QDomElement svgASection = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + tIWBA);
svgASection.setAttribute(aSVGHref, svgElementPart.attribute(aSVGHref));
svgElementPart.setTagName(tIWBImage);
svgElementPart.setAttribute(aSVGHref, dstAudioImageRelativePath);
svgElementPart.setAttribute(aHeight, audioImageDimention);
svgElementPart.setAttribute(aWidth, audioImageDimention);
svgASection.appendChild(svgElementPart);
QDomElement svgText = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + tIWBTextArea);
svgText.setAttribute(aX, svgElementPart.attribute(aX));
svgText.setAttribute(aY, svgElementPart.attribute(aY));
svgText.setAttribute(aWidth, svgElementPart.attribute(aWidth));
svgText.setAttribute(aHeight, svgElementPart.attribute(aHeight));
svgText.setAttribute(aTransform, svgElementPart.attribute(aTransform));
QDomText text = doc.createTextNode("Cannot Open Content");
svgText.appendChild(text);
addSVGElementToResultModel(svgASection/*svgSwitchSection*/, dstSvgList, getElementLayer(element));
if (0 < iwbElementPart.attributes().count())
addIWBElementToResultModel(iwbElementPart);
return true;
}
return false;
}
else
{
qDebug() << "|error at audio parsing";
errorStr = "AudioParsingError";
return false;
}
}
bool WBCFFAdaptor::WBToCFFConverter::parseForeignObject(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
if (element.attribute(aWBZType) == avWBZText) {
return parseWBZText(element, dstSvgList);
}
qDebug() << "|parsing foreign object";
QDomDocument doc;
QDomElement svgElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + getElementTypeFromUBZ(element));
QDomElement iwbElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
if (setCommonAttributesFromUBZ(element, iwbElementPart, svgElementPart))
{
addSVGElementToResultModel(svgElementPart, dstSvgList, getElementLayer(element));
if (0 < iwbElementPart.attributes().count())
addIWBElementToResultModel(iwbElementPart);
return true;
}
else
{
qDebug() << "|error at parsing foreign object";
errorStr = "ForeignObjectParsingError";
return false;
}
}
bool WBCFFAdaptor::WBToCFFConverter::parseWBZText(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
qDebug() << "|parsing text";
QDomDocument doc;
QDomElement svgElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + getElementTypeFromUBZ(element));
QDomElement iwbElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
if (element.hasChildNodes())
{
QDomDocument htmlDoc;
htmlDoc.setContent(findTextNode(element).nodeValue());
QDomNode bodyNode = findNodeByTagName(htmlDoc.firstChildElement(), "body");
setCFFTextFromHTMLTextNode(bodyNode.toElement(), svgElementPart);
if (setCommonAttributesFromUBZ(element, iwbElementPart, svgElementPart))
{
QString commonParams;
for (int i = 0; i < bodyNode.attributes().count(); i++)
{
commonParams += " " + bodyNode.attributes().item(i).nodeValue();
}
commonParams.remove(" ");
commonParams.remove("'");
QStringList commonAttributes = commonParams.split(";", QString::SkipEmptyParts);
for (int i = 0; i < commonAttributes.count(); i++)
{
QStringList AttrVal = commonAttributes.at(i).split(":", QString::SkipEmptyParts);
if (1 < AttrVal.count())
{
QString sAttr = ubzAttrNameToCFFAttrName(AttrVal.at(0));
QString sVal = ubzAttrValueToCFFAttrName(AttrVal.at(1));
setCFFAttribute(sAttr, sVal, element, iwbElementPart, svgElementPart);
}
}
addSVGElementToResultModel(svgElementPart, dstSvgList, getElementLayer(element));
if (0 < iwbElementPart.attributes().count())
addIWBElementToResultModel(iwbElementPart);
return true;
}
return false;
}
else
{
qDebug() << "|error at text parsing";
errorStr = "TextParsingError";
return false;
}
}
bool WBCFFAdaptor::WBToCFFConverter::parseWBZPolygon(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
qDebug() << "||parsing polygon";
QDomDocument doc;
QDomElement svgElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + getElementTypeFromUBZ(element));
QDomElement iwbElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
if (setCommonAttributesFromUBZ(element, iwbElementPart, svgElementPart))
{
svgElementPart.setAttribute(aStroke, svgElementPart.attribute(aFill));
addSVGElementToResultModel(svgElementPart, dstSvgList, getElementLayer(element));
if (0 < iwbElementPart.attributes().count())
{
QString id = svgElementPart.attribute(aWBZUuid);
if (id.isEmpty())
id = QUuid::createUuid().toString();
svgElementPart.setAttribute(aID, id);
iwbElementPart.setAttribute(aRef, id);
addIWBElementToResultModel(iwbElementPart);
}
return true;
}
else
{
qDebug() << "||error at parsing polygon";
errorStr = "PolygonParsingError";
return false;
}
}
bool WBCFFAdaptor::WBToCFFConverter::parseWBZPolyline(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
qDebug() << "||parsing polyline";
QDomElement resElement;
QDomDocument doc;
QDomElement svgElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + getElementTypeFromUBZ(element));
QDomElement iwbElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
if (setCommonAttributesFromUBZ(element, iwbElementPart, svgElementPart))
{
svgElementPart.setAttribute(aStroke, svgElementPart.attribute(aFill));
addSVGElementToResultModel(svgElementPart, dstSvgList, getElementLayer(element));
if (0 < iwbElementPart.attributes().count())
{
QString id = QUuid::createUuid().toString();
svgElementPart.setAttribute(aID, id);
iwbElementPart.setAttribute(aRef, id);
addIWBElementToResultModel(iwbElementPart);
}
return true;
}
else
{
qDebug() << "||error at parsing polygon";
errorStr = "PolylineParsingError";
return false;
}
}
bool WBCFFAdaptor::WBToCFFConverter::parseWBZLine(const QDomElement &element, QMultiMap<int, QDomElement> &dstSvgList)
{
qDebug() << "||parsing line";
QDomElement resElement;
QDomDocument doc;
QDomElement svgElementPart = doc.createElementNS(svgIWBNS,svgIWBNSPrefix + ":" + getElementTypeFromUBZ(element));
QDomElement iwbElementPart = doc.createElementNS(iwbNS,iwbNsPrefix + ":" + tElement);
if (setCommonAttributesFromUBZ(element, iwbElementPart, svgElementPart))
{
svgElementPart.setAttribute(aStroke, svgElementPart.attribute(aFill));
addSVGElementToResultModel(svgElementPart, dstSvgList, getElementLayer(element));
if (0 < iwbElementPart.attributes().count())
{
QString id = QUuid::createUuid().toString();
svgElementPart.setAttribute(aID, id);
iwbElementPart.setAttribute(aRef, id);
addIWBElementToResultModel(iwbElementPart);
}
}
else
{
qDebug() << "||error at parsing polygon";
errorStr = "LineParsingError";
return false;
}
return true;
}
void WBCFFAdaptor::WBToCFFConverter::addSVGElementToResultModel(const QDomElement &element, QMultiMap<int, QDomElement> &dstList, int layer)
{
int elementLayer = (DEFAULT_LAYER == layer) ? DEFAULT_LAYER : layer;
QDomElement rootElement = element.cloneNode(true).toElement();
mDocumentToWrite->firstChildElement().appendChild(rootElement);
dstList.insert(elementLayer, rootElement);
}
void WBCFFAdaptor::WBToCFFConverter::addIWBElementToResultModel(const QDomElement &element)
{
QDomElement rootElement = element.cloneNode(true).toElement();
mDocumentToWrite->firstChildElement().appendChild(rootElement);
mExtendedElements.append(rootElement);
}
WBCFFAdaptor::WBToCFFConverter::~WBToCFFConverter()
{
if (mDataModel)
delete mDataModel;
if (mIWBContentWriter)
delete mIWBContentWriter;
if (mDocumentToWrite)
delete mDocumentToWrite;
}
bool WBCFFAdaptor::WBToCFFConverter::isValid() const
{
bool result = QFileInfo(sourcePath).exists()
&& QFileInfo(sourcePath).isDir()
&& errorStr == noErrorMsg;
if (!result) {
qDebug() << "specified data is not valid";
errorStr = "ValidateDataError";
}
return result;
}
void WBCFFAdaptor::WBToCFFConverter::fillNamespaces()
{
mIWBContentWriter->writeDefaultNamespace(svgWBZNS);
mIWBContentWriter->writeNamespace(iwbNS, iwbNsPrefix);
mIWBContentWriter->writeNamespace(svgIWBNS, svgIWBNSPrefix);
mIWBContentWriter->writeNamespace(xlinkNS, xlinkNSPrefix);
}
QString WBCFFAdaptor::WBToCFFConverter::digitFileFormat(int digit) const
{
return QString("%1").arg(digit, 3, 10, QLatin1Char('0'));
}
QString WBCFFAdaptor::WBToCFFConverter::contentIWBFileName() const
{
return destinationPath + "/" + fIWBContent;
}
//setting SVG dimenitons
QSize WBCFFAdaptor::WBToCFFConverter::getSVGDimentions(const QString &element)
{
QStringList dimList;
dimList = element.split(dimensionsDelimiter1, QString::KeepEmptyParts);
if (dimList.count() != 2)
return QSize();
bool ok;
int width = dimList.takeFirst().toInt(&ok);
if (!ok || !width)
return QSize();
int height = dimList.takeFirst().toInt(&ok);
if (!ok || !height)
return QSize();
return QSize(width, height);
}
QRect WBCFFAdaptor::WBToCFFConverter::getViewboxRect(const QString &element) const
{
QStringList dimList;
dimList = element.split(dimensionsDelimiter2, QString::KeepEmptyParts);
if (dimList.count() != 4)
return QRect();
bool ok = false;
int x = dimList.takeFirst().toInt(&ok);
if (!ok || !x)
return QRect();
int y = dimList.takeFirst().toInt(&ok);
if (!ok || !y)
return QRect();
int width = dimList.takeFirst().toInt(&ok);
if (!ok || !width)
return QRect();
int height = dimList.takeFirst().toInt(&ok);
if (!ok || !height)
return QRect();
return QRect(x, y, width, height);
}
QString WBCFFAdaptor::WBToCFFConverter::rectToIWBAttr(const QRect &rect) const
{
if (rect.isNull()) return QString();
return QString("%1 %2 %3 %4").arg(rect.topLeft().x())
.arg(rect.topLeft().y())
.arg(rect.width())
.arg(rect.height());
}
| [
"574226409@qq.com"
] | 574226409@qq.com |
954b6ce72e12ed5ba0c4e9c8d88dee4f7cd2cf87 | 0995654f992db7fec8d607d19d323e766ff373cb | /cutSphere.hpp | 133b879515b15a495d4b79eaa29eb2ba466914c1 | [] | no_license | arthurMachad0/EscultorDigital | c217857d7fbd524e8d77ddd7c2eb0b83c38aeb2c | 663b3e813519c41e51eccb0b3be4420a4997bc70 | refs/heads/main | 2023-07-28T02:30:35.394848 | 2021-09-14T22:17:26 | 2021-09-14T22:17:26 | 406,535,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | hpp | #ifndef CUTSPHERE_H
#define CUTSPHERE_H
#include "FiguraGeometrica.hpp"
#include "Sculptor.hpp"
class cutSphere : public FiguraGeometrica{
int xc, yc, zc, e;
public:
cutSphere ( int xc, int yc, int zc, int e);
~cutSphere(){}
void draw (Sculptor &s);
};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
746bb866e916e21354c0127b50da3f9a6fccd3b4 | ab1222d1218b588e97fb9136af391a3c023d7040 | /src/Baralho.h | 7218077d2af890dadb6ff33471259ad17c2b14b3 | [] | no_license | levelgigio/truco_allegro | bb408eab60549b472a57d6413a1f7303943c5f16 | d5162440863a6869112105b000e569b5680899ff | refs/heads/master | 2020-03-24T20:10:37.996009 | 2018-07-31T04:51:41 | 2018-07-31T04:51:41 | 142,963,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | h | #pragma once
#include "CartaTruco.h"
#include <vector>
#include <iostream>
#include <time.h>
using namespace std;
class Baralho
{
private:
vector<CartaTruco*> todasCartas;
vector<CartaTruco*> cartasUsadas;
vector<CartaTruco*> cartasBaralho;
vector<CartaTruco*> cartasDescarte;
vector<CartaTruco*>::iterator it;
CartaTruco* cartaVirada;
int numZap;
public:
Baralho();
~Baralho();
void baralhoParaUsada(CartaTruco* const pCarta);
void usadaParaBaralho(CartaTruco* const pCarta);
void usadaParaDescarte(CartaTruco* const pCarta);
void descarteParaBaralho(CartaTruco* const pCarta);
CartaTruco* const cartaBaralhoParaUsada();
void resetaBaralho();
void devolveUsadas();
void devolveDescartes();
void resetaValores();
void embaralha();
void atualizaValores();
void setNumZap(const int aNum);
const int getNumZap();
CartaTruco* const virarCarta();
CartaTruco* const getCartaVirada();
vector<CartaTruco*> get_cartas_descarte();
void desvirarCarta();
};
| [
"gigio.forastieri@gmail.com"
] | gigio.forastieri@gmail.com |
7b62ce1b8a627f7a58d9861dfb942e1ba9330c13 | 201f4594c419e194069c893be70ce3920ba237fe | /pokemon-Antoine-Erine/Pokemon.cpp | 8537ab008cf58746911ea9b83327534d6c3ac33d | [] | no_license | Erine-Berard/Pokemon | d299df92d7f1b412085c04a81daed918bcd9f5d0 | 096a28b8b5d6a14f5ec72cc20fb5bbcd6a7fb730 | refs/heads/main | 2023-03-22T20:17:47.618783 | 2021-03-16T09:32:53 | 2021-03-16T09:32:53 | 345,586,538 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,031 | cpp | #include "Pokemon.h"
//#include "Objet.h"
#include "Attaques.h"
using namespace std;
Pokemon::Pokemon(string Nom, int Prix, vector <string> type, long double PV, int Niveau, long double Attaque, long double Attaquespe, long double Defense, long double Defensespe, int Vitesse, vector <Attaques> VectorAttaques ,Objet objet)
: Nom(Nom), Prix(Prix), type(type), PV(PV), Niveau(Niveau), Attaque(Attaque), Attaquespe(Attaquespe), Defense(Defense), Defensespe(Defensespe), Vitesse(Vitesse), VectorAttaques(VectorAttaques),objet(objet)
{
for (int i = 0; i < VectorAttaques.size(); i++) {
Attaques* ptr = &VectorAttaques[i];
VectorPtrAttaques.push_back(ptr);
}
}
Pokemon::~Pokemon() {}
string Pokemon::GetNom(){
return Nom;
}
int Pokemon::GetPrix(){
return Prix;
}
vector<string> Pokemon::GetTypes(){
return type;
}
double Pokemon::GetPV(){
return PV;
}
int Pokemon::GetNiveau(){
return Niveau;
}
long double Pokemon::GetAttaque(){
return Attaque;
}
long double Pokemon::GetAttaquespe(){
return Attaquespe;
}
long double Pokemon::GetDefense(){
return Defense;
}
long double Pokemon::GetDefensespe(){
return Defensespe;
}
int Pokemon::GetVitesse(){
return Vitesse;
}
vector <Attaques> Pokemon::GetAttaques(){
return VectorAttaques;
}
std::vector<Attaques*> Pokemon::GetBisAttaques(){
return VectorPtrAttaques;
}
void Pokemon::SetPV(double pv){
this->PV = pv;
return;
}
void Pokemon::AjouterAttaque(Attaques attaques){
this->VectorAttaques.push_back(attaques);
return;
}
void Pokemon::Attaquer(Pokemon& pokemon, Attaques attaques){
long double degats = attaques.Calculerdegats(*this, pokemon);
if (pokemon.PV <= degats) {
pokemon.PV = 0;
}
else {
pokemon.PV -= degats;
}
return;
}
void Pokemon::UtiliserObjet(){
objet.Action(*this);
return;
}
bool Pokemon::EstKO(){
if (PV > 0) {
return false;
}
else {
return true;
}
}
void Pokemon::AfficherAttaques(){
int tail (VectorAttaques.size());
for (int i = 0; i < tail; ++i) {
VectorAttaques[i].Afficher();
}
return;
}
void Pokemon::Afficherbis(){
cout << " Nom :" << GetNom() << endl;
cout << " Prix :" << GetPrix() << endl;
cout << " Type :";
int tail(type.size());
for (int i = 0; i < tail; ++i) {
cout << type[i] << ", ";
}
cout << endl << endl ;
}
void Pokemon::Afficher(){
cout << " Son Nom : " << Nom << endl
<< " Son prix : " << Prix << endl
<< " Son/ses type/s : ";
int tail(type.size());
for (int i = 0; i < tail; ++i) {
cout << type[i] << ", ";
}
cout << endl << " Son nombre de PV : " << PV << endl
<< " Son niveau : " << Niveau << endl
<< " Sa valeur d'attaque : " << Attaque << endl
<< " Sa valeur d'attaque special : " << Attaquespe << endl
<< " Sa valeur de defense : " << Defense << endl
<< " Sa valeur de defense special : " << Defensespe << endl
<< " Sa vitesse d'attaque : " << Vitesse << endl
<< " Ses attaques :" << endl;
this->AfficherAttaques();
objet.Afficher();
return;
}
| [
"berard.erine@gmail.com"
] | berard.erine@gmail.com |
c337956bf01a32f0d2e4bcc46ae9e02496b8f746 | fb66a5cc43d27f33c85320a6dba8b9a8ff4765a9 | /gapputils/gml.imageprocessing/Resample.h | 4e0229df6a2edf987176e15247a3994bb850f0d3 | [] | no_license | e-thereal/gapputils | 7a211c7d92fd2891703cb16bf94e6e05f0fb3b8a | a9eca31373c820c12f4f5f308c0e2005e4672fd0 | refs/heads/master | 2021-04-26T16:42:58.303603 | 2015-09-02T21:32:45 | 2015-09-02T21:32:45 | 38,838,767 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 856 | h | /*
* Resample.h
*
* Created on: Feb 5, 2015
* Author: tombr
*/
#ifndef GML_RESAMPLE_H_
#define GML_RESAMPLE_H_
#include <gapputils/DefaultWorkflowElement.h>
#include <gapputils/Image.h>
#include <gapputils/namespaces.h>
#include <tbblas/tensor.hpp>
namespace gml {
namespace imageprocessing {
struct ResampleChecker { ResampleChecker(); };
class Resample : public DefaultWorkflowElement<Resample> {
typedef tbblas::sequence<int, 3> dim_t;
InitReflectableClass(Resample)
friend class ResampleChecker;
Property(Input, boost::shared_ptr<image_t>)
Property(Size, dim_t)
Property(PixelSize, dim_t)
Property(Output, boost::shared_ptr<image_t>)
public:
Resample();
protected:
virtual void update(IProgressMonitor* monitor) const;
};
} /* namespace imageprocessing */
} /* namespace gml */
#endif /* GML_RESAMPLE_H_ */
| [
"brosch.tom@gmail.com"
] | brosch.tom@gmail.com |
7cd0013cc813e5f18212a9c6fa54beebf99c6916 | ad8271700e52ec93bc62a6fa3ee52ef080e320f2 | /CatalystRichPresence/CatalystSDK/UIWidgetBlueprint.h | f24b9b9a3c42202194ded29990bacd6a5a9b3410 | [] | no_license | RubberDuckShobe/CatalystRPC | 6b0cd4482d514a8be3b992b55ec143273b3ada7b | 92d0e2723e600d03c33f9f027c3980d0f087c6bf | refs/heads/master | 2022-07-29T20:50:50.640653 | 2021-03-25T06:21:35 | 2021-03-25T06:21:35 | 351,097,185 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | h | //
// Generated with FrostbiteGen by Chod
// File: SDK\UIWidgetBlueprint.h
// Created: Wed Mar 10 18:59:45 2021
//
#ifndef FBGEN_UIWidgetBlueprint_H
#define FBGEN_UIWidgetBlueprint_H
#include "ObjectBlueprint.h"
class UIWidgetBlueprint :
public ObjectBlueprint // size = 0x48
{
public:
static void* GetTypeInfo()
{
return (void*)0x000000014281F3B0;
}
}; // size = 0x48
#endif // FBGEN_UIWidgetBlueprint_H
| [
"dog@dog.dog"
] | dog@dog.dog |
c4d51f7ad08b0671c0bb5e9d8ef86af91e0720d7 | fe739acd76bba1028e38c67607424ee1b4bd0c05 | /CursoCppATS/video011.cpp | 28165d626482e4e0071b5dd21bce3ade2d4398c3 | [] | no_license | vtsartas/EJCpp | ad57f3f21c9d198d0685023356feeeb2f939bc25 | d340b3d7a74e6d96b559720269fa88da8f195318 | refs/heads/master | 2020-12-09T18:30:17.892969 | 2020-01-16T20:51:46 | 2020-01-16T20:51:46 | 233,383,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | cpp | // 011 - condicionales
#include <iostream>
#include <stdlib.h> // COMPROBAR si era lo necesario para que funcionase en 'spanish'
#include <clocale> // necesaria para la localización y codificación en español
#include <windows.h> // necesaria para la codificación de caracteres en español en Windows
using namespace std;
int main(){
setlocale(LC_CTYPE,"spanish");
SetConsoleCP(1252); // Cambiar STDIN - Necesario para máquinas Windows
SetConsoleOutputCP(65001); // Cambiar STDOUT - Necesario para máquinas Windows
int numero,dato=5;
cout<<"Introduce un valor que se comparará a "<<dato<<": "; cin>>numero;
cout<<"El valor dado "<<((numero==dato)?"es igual a ":"no es igual a ")<<dato<<".";
return 0;
} // fin del main | [
"vtsartas@gmail.com"
] | vtsartas@gmail.com |
eb1ed252de3b572ec7de9f8854e18f7760d9f57d | 04230fbf25fdea36a2d473233e45df21b6ff6fff | /1348-A.cpp | 132bf7dcb96d540bda5324f1fe83db88825620a8 | [
"MIT"
] | permissive | ankiiitraj/questionsSolved | 48074d674bd39fe67da1f1dc7c944b95a3ceac34 | 8452b120935a9c3d808b45f27dcdc05700d902fc | refs/heads/master | 2021-07-22T10:16:13.538256 | 2021-02-12T11:51:47 | 2021-02-12T11:51:47 | 241,689,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,047 | cpp | #include <bits/stdc++.h>
#define int long long int
#define pb push_back
#define all(a) a.begin(), a.end()
#define scnarr(a, n) for (int i = 0; i < n; ++i) cin >> a[i]
#define vi vector<int>
#define pii pair <int, int>
#define mii map <int, int>
#define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
using namespace std;
//Constants
const int MOD = 1000000007; // 1e9 + 7
const int N = 1000005; // 1e6 +5
/* -------------------------------Solution Sarted--------------------------------------*/
int32_t main()
{
faster;
#ifndef ONLINE_JUDGE
freopen("ip.txt", "r", stdin);
freopen("op.txt", "w", stdout);
#endif
int t; cin >> t; while(t--)
{
int n;
cin >> n;
int first = 0, second = 0;
if(n == 2){
cout << 2 << endl;
continue;
}
for(int i = 1; i <= n/2 -1; ++i){
first += pow(2, i);
}
for(int i = n/2; i <= n -1; ++i){
second += pow(2, i);
}
first += pow(2, n);
cout << abs(first - second) << endl;
}
return 0;
}
//Author : Ankit Raj
//InSearchForMeanings
//Problem Link :
| [
"ankitatiiitr@gmail.com"
] | ankitatiiitr@gmail.com |
e75fd26b9943af28a61ec7cec82ce0b087693e0b | 84f3a4a858afa1a1f494556643b29aa706292261 | /OpenMoCap/src/Gui/Widgets/ImageWidget.h | 4cf3001a52093a6350c35e314e106357f6fcd535 | [] | no_license | jamieforth/OpenMoCap | ac44a86554983030ed0448855720084e4488d73b | 45eaa1347d3160719147e52a20279937cc199837 | refs/heads/master | 2020-03-07T00:12:16.479130 | 2014-08-02T21:50:53 | 2014-08-02T21:50:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,446 | h | #ifndef IMAGEWIDGET_H_
#define IMAGEWIDGET_H_
#include "../../Utils/Image.h"
#include <opencv2/opencv.hpp>
#include <GL/gl.h>
#include <GL/glext.h>
#include <GL/glu.h>
#include <QObject>
#include <QtOpenGL>
class ImageWidget : public QGLWidget {
Q_OBJECT
public:
/*!
* ImageWidget constructor.
*
* @param parent The parent widget.
* @param width Image width.
* @param height Image height.
*/
ImageWidget(QWidget* parent = 0, int width = 320, int height = 240);
/*!
* Refreshes the image.
*
* @param image The image to be refreshed.
*/
virtual void refreshImage(IplImage* image);
/*!
* Returns current image
*/
IplImage* getImage() {
return _imageRef;
}
protected:
//Initialized with NULL on constructor's initialization list.
//! Image reference.
IplImage *_imageRef;
/*!
* Resizes the viewport.
*
* @param width Viewport width.
* @param height Viewport height.
*/
void resizeGL(int width, int height);
/*!
* Image widget paint event handler.
*
* @param paintEvent The event to be handled.
*/
virtual void paintEvent(QPaintEvent *paintEvent);
/*!
* Sets the viewport up.
*
* @param width Viewport width.
* @param height Viewport height.
*/
void setupViewPort(int width, int height);
/*!
* Draws the background image.
*/
void drawBackgroundImage();
};
#endif /* IMAGEWIDGET_H_ */
| [
"davidflam@gmail.com@1b195e6b-c8d0-be63-1615-5224d025ebd8"
] | davidflam@gmail.com@1b195e6b-c8d0-be63-1615-5224d025ebd8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.