hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
abb67a710058c771ece4227facb9d97f4c223d47 | 15,580 | cpp | C++ | sdl1/f1spirit/F1Spirit-auxiliar.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/f1spirit/F1Spirit-auxiliar.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/f1spirit/F1Spirit-auxiliar.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | #ifdef _WIN32
#include <windows.h>
#include <windowsx.h>
#else
#include <sys/time.h>
#include <time.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "ctype.h"
#include "string.h"
#include "math.h"
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_mixer.h"
#include "auxiliar.h"
#include "List.h"
#include "sound.h"
#include "F1Spirit-auxiliar.h"
#ifdef KITSCHY_DEBUG_MEMORY
#include "debug_memorymanager.h"
#endif
SDL_Surface *frame_corner[4] = {0, 0, 0, 0};
SDL_Surface *frame_h[2] = {0, 0}, *frame_v[2] = {0, 0};
int linear_base [ 16] = {0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2};
int corner_base1[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 2, 2,
0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2
};
int corner_base2[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2
};
void free_auxiliar_menu_surfaces(void)
{
int i;
for (i = 0;i < 4;i++) {
if (frame_corner[i] != 0)
SDL_FreeSurface(frame_corner[i]);
frame_corner[i] = 0;
}
if (frame_h[0] != 0)
SDL_FreeSurface(frame_h[0]);
frame_h[0] = 0;
if (frame_h[1] != 0)
SDL_FreeSurface(frame_h[1]);
frame_h[1] = 0;
if (frame_v[0] != 0)
SDL_FreeSurface(frame_v[0]);
frame_v[0] = 0;
if (frame_v[1] != 0)
SDL_FreeSurface(frame_v[1]);
frame_v[1] = 0;
} /* free_auxiliar_menu_surfaces */
SDL_Surface *load_bmp_font(char *filename, int first, int last)
{
SDL_Surface *bitmap_font = 0;
SDL_Surface *sfc = IMG_Load(filename);
if (sfc != 0) {
int w = (sfc->w / (last - first));
bitmap_font = SDL_CreateRGBSurface(SDL_SWSURFACE, w * 256, sfc->h, 32, RMASK, GMASK, BMASK, AMASK);
SDL_SetAlpha(bitmap_font, 0, 0);
SDL_FillRect(bitmap_font, 0, 0);
}
if (bitmap_font != 0) {
int i, j, k, s;
Uint32 color;
s = sfc->w / (last - first);
for (k = 0;k < 256;k++) {
if (k >= first && k < last) {
for (i = 0;i < s;i++) {
for (j = 0;j < sfc->h;j++) {
SDL_LockSurface(sfc);
color = getpixel(sfc, (k - first) * s + i, j);
SDL_UnlockSurface(sfc);
SDL_LockSurface(bitmap_font);
putpixel(bitmap_font, k*s + i, j, color);
SDL_UnlockSurface(bitmap_font);
}
}
}
}
}
return bitmap_font;
} /* load_bmp_font */
SDL_Surface *draw_menu(int MAX_OPTIONS, char *title, char *options, int *option_type, int selected, float sel_factor, float enter_factor, SDL_Surface *font, int *first_option)
{
SDL_Surface *sfc;
int w = 0, h = 0;
int title_w = 0, title_h = 0;
int options_w = 0, options_h = 0;
int n_options = 0;
/* Compute the number of options: */
{
int i;
i = 0;
while (options != 0 && options[i] != 0) {
if (options[i] == '\n')
n_options++;
i++;
}
}
if (selected < *first_option) {
*first_option = selected;
}
if ((*first_option) + (MAX_OPTIONS - 1) < selected) {
*first_option = selected - (MAX_OPTIONS - 1);
}
/* Compute the size of the surface: */
/* title + options + frame */
if (title != 0) {
title_w = get_text_width_bmp((unsigned char *)title, font, 0);
title_h = font->h + 8;
}
{
int count = 0;
int i, j, s;
char text_tmp[256];
i = j = 0;
s = font->w / 256;
while (options != 0 && options[i] != 0) {
text_tmp[j] = options[i];
if (options[i] == '\n') {
text_tmp[j] = 0;
if (option_type != 0 && (option_type[count] == 11)) {
if (int(strlen(text_tmp))*s + 7 > options_w)
options_w = strlen(text_tmp) * s + 7;
} else {
if (int(strlen(text_tmp))*s > options_w)
options_w = strlen(text_tmp) * s;
}
if (count >= *first_option &&
count < (*first_option + MAX_OPTIONS)) {
options_h += font->h - 2;
}
count++;
j = 0;
} else {
j++;
}
i++;
}
options_h += 2;
}
if (options != 0) {
options_w += 32; /* 8*2 : frame + 8*2 : gap between text and frame */
options_h += 32; /* 8*2 : frame + 8*2 : gap between text and frame */
}
w = max(title_w, options_w);
h = title_h + options_h;
if (w > 0 && h > 0) {
int y = 0;
int max_y = h;
if (title != 0)
max_y -= font->h + 8;
max_y -= 32;
max_y = int(max_y * enter_factor);
max_y += 32;
if (title != 0)
max_y += font->h + 8;
sfc = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, RMASK, GMASK, BMASK, AMASK);
SDL_SetAlpha(sfc, 0, 0);
SDL_FillRect(sfc, 0, 0);
/* Draw the elements of the menu: */
/* title: */
if (title != 0) {
SDL_Rect r;
print_left_bmp((unsigned char *)title, font, sfc, 0, 0, 0);
r.x = 0;
r.y = 0;
r.w = get_text_width_bmp((unsigned char *)title, font, 0);
r.h = font->h;
surface_fader(sfc, 1, 1, 1, enter_factor, &r);
y += font->h + 8;
} else {
y++;
}
y = y + 16;
/* options: */
{
int i, j, count = 0, s, sel = 0;
char text_tmp[256];
i = j = 0;
s = font->w / 256;
while (options != 0 && options[i] != 0 && y < max_y) {
text_tmp[j] = options[i];
if (options[i] == '\n') {
if (sel >= *first_option &&
sel < (*first_option + MAX_OPTIONS)) {
text_tmp[j] = 0;
print_left_bmp((unsigned char *)text_tmp, font, sfc, 16, y, 0);
if (option_type != 0 && (option_type[count] == 11)) {
int w = get_text_width_bmp((unsigned char *)text_tmp, font, 0);
Uint32 color = SDL_MapRGB(sfc->format, 255, 255, 255);
Uint32 color2 = SDL_MapRGB(sfc->format, 0, 0, 0);
/* Draw triangle that denotes that the option leads to a submenu: */
putpixel(sfc, 16 + w + 4, y + 6, color);
putpixel(sfc, 16 + w + 4, y + 7, color);
putpixel(sfc, 16 + w + 4, y + 8, color);
putpixel(sfc, 16 + w + 4, y + 9, color);
putpixel(sfc, 16 + w + 4, y + 10, color);
putpixel(sfc, 16 + w + 5, y + 7, color);
putpixel(sfc, 16 + w + 5, y + 8, color);
putpixel(sfc, 16 + w + 5, y + 9, color);
putpixel(sfc, 16 + w + 6, y + 8, color);
/* bloack outline: */
putpixel(sfc, 16 + w + 3, y + 6, color2);
putpixel(sfc, 16 + w + 3, y + 7, color2);
putpixel(sfc, 16 + w + 3, y + 8, color2);
putpixel(sfc, 16 + w + 3, y + 9, color2);
putpixel(sfc, 16 + w + 3, y + 10, color2);
putpixel(sfc, 16 + w + 4, y + 5, color2);
putpixel(sfc, 16 + w + 4, y + 11, color2);
putpixel(sfc, 16 + w + 5, y + 6, color2);
putpixel(sfc, 16 + w + 5, y + 10, color2);
putpixel(sfc, 16 + w + 6, y + 7, color2);
putpixel(sfc, 16 + w + 6, y + 9, color2);
putpixel(sfc, 16 + w + 7, y + 8, color2);
}
/* Selected option: */
if (sel == selected) {
SDL_Rect r;
r.x = 16;
r.y = y;
r.w = get_text_width_bmp((unsigned char *)text_tmp, font, 0);
r.h = font->h;
if (option_type != 0 && (option_type[count] == 11))
r.w += 7;
surface_fader(sfc, sel_factor, sel_factor, sel_factor, 1, &r);
}
if (option_type != 0 && (option_type[count] < 0)) {
SDL_Rect r;
r.x = 16;
r.y = y;
r.w = get_text_width_bmp((unsigned char *)text_tmp, font, 0);
r.h = font->h;
surface_fader(sfc, 0.5F, 0.5F, 0.5F, 1, &r);
}
y += font->h - 2;
}
count++;
j = 0;
sel++;
} else {
j++;
}
i++;
}
y += 2;
}
{
/* Delete the options that have been drawn and shouldn't: */
SDL_Rect r;
r.x = 0;
r.y = max_y - 16;
r.w = w;
r.h = y - (max_y - 16);
SDL_FillRect(sfc, &r, 0);
}
/* frame: */
if (title != 0)
y = font->h + 8;
else
y = 2;
draw_menu_frame(sfc, 0, y, w, max_y - y);
/* flechas de scroll: */
if (enter_factor == 1) {
if (*first_option > 0) {
Uint32 color = SDL_MapRGB(sfc->format, 255, 255, 255);
putpixel(sfc, w / 2, y + 13, color);
putpixel(sfc, (w / 2) - 1, y + 14, color);
putpixel(sfc, (w / 2), y + 14, color);
putpixel(sfc, (w / 2) + 1, y + 14, color);
putpixel(sfc, (w / 2) - 2, y + 15, color);
putpixel(sfc, (w / 2) - 1, y + 15, color);
putpixel(sfc, (w / 2), y + 15, color);
putpixel(sfc, (w / 2) + 1, y + 15, color);
putpixel(sfc, (w / 2) + 2, y + 15, color);
}
if ((*first_option + (MAX_OPTIONS)) < n_options) {
Uint32 color = SDL_MapRGB(sfc->format, 255, 255, 255);
putpixel(sfc, w / 2, max_y - 13, color);
putpixel(sfc, (w / 2) - 1, max_y - 14, color);
putpixel(sfc, (w / 2), max_y - 14, color);
putpixel(sfc, (w / 2) + 1, max_y - 14, color);
putpixel(sfc, (w / 2) - 2, max_y - 15, color);
putpixel(sfc, (w / 2) - 1, max_y - 15, color);
putpixel(sfc, (w / 2), max_y - 15, color);
putpixel(sfc, (w / 2) + 1, max_y - 15, color);
putpixel(sfc, (w / 2) + 2, max_y - 15, color);
}
}
if (enter_factor < 0.510)
surface_fader(sfc, 1, 1, 1, enter_factor*2, 0);
return sfc;
}
return 0;
} /* draw_menu */
void draw_menu_frame(SDL_Surface *sfc, int x, int y, int dx, int dy, int a)
{
if (frame_corner[0] == 0) {
int i, j;
// float /*d,x,y,*/c;
Uint32 color;
/* Compute the frame graphics: */
frame_corner[0] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 16, 32, RMASK, GMASK, BMASK, AMASK);
frame_corner[1] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 16, 32, RMASK, GMASK, BMASK, AMASK);
frame_corner[2] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 16, 32, RMASK, GMASK, BMASK, AMASK);
frame_corner[3] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 16, 32, RMASK, GMASK, BMASK, AMASK);
frame_v[0] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 1, 32, RMASK, GMASK, BMASK, AMASK);
frame_h[0] = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, 16, 32, RMASK, GMASK, BMASK, AMASK);
frame_v[1] = SDL_CreateRGBSurface(SDL_SWSURFACE, 16, 1, 32, RMASK, GMASK, BMASK, AMASK);
frame_h[1] = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, 16, 32, RMASK, GMASK, BMASK, AMASK);
SDL_SetAlpha(frame_corner[0], 0, 0);
SDL_SetAlpha(frame_corner[1], 0, 0);
SDL_SetAlpha(frame_corner[2], 0, 0);
SDL_SetAlpha(frame_corner[3], 0, 0);
SDL_SetAlpha(frame_v[0], 0, 0);
SDL_SetAlpha(frame_v[1], 0, 0);
SDL_SetAlpha(frame_h[0], 0, 0);
SDL_SetAlpha(frame_h[1], 0, 0);
for (i = 0;i < 16;i++) {
if (linear_base[i] == 0)
color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, 0);
if (linear_base[i] == 1)
color = SDL_MapRGBA(frame_corner[0]->format, 255, 255, 255, 255);
if (linear_base[i] == 2)
color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, a);
putpixel(frame_v[0], i, 0, color);
putpixel(frame_h[0], 0, i, color);
putpixel(frame_v[1], 15 - i, 0, color);
putpixel(frame_h[1], 0, 15 - i, color);
} // for
for (i = 0;i < 16;i++) {
for (j = 0;j < 16;j++) {
if (corner_base1[j + i*16] == 0)
color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, 0);
if (corner_base1[j + i*16] == 1)
color = SDL_MapRGBA(frame_corner[0]->format, 255, 255, 255, 255);
if (corner_base1[j + i*16] == 2)
color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, a);
putpixel(frame_corner[0], i, j, color);
putpixel(frame_corner[3], 15 - i, 15 - j, color);
if (corner_base2[j + i*16] == 0)
color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, 0);
if (corner_base2[j + i*16] == 1)
color = SDL_MapRGBA(frame_corner[0]->format, 255, 255, 255, 255);
if (corner_base2[j + i*16] == 2)
color = SDL_MapRGBA(frame_corner[0]->format, 0, 0, 0, a);
putpixel(frame_corner[2], i, 15 - j, color);
putpixel(frame_corner[1], 15 - i, j, color);
} // for
} // for
}
SDL_Rect r;
int i, j;
r.x = x;
r.y = y;
SDL_BlitSurface(frame_corner[0], 0, sfc, &r);
r.x = x + dx - 16;
r.y = y;
SDL_BlitSurface(frame_corner[1], 0, sfc, &r);
r.x = x;
r.y = y + dy - 16;
SDL_BlitSurface(frame_corner[2], 0, sfc, &r);
r.x = x + dx - 16;
r.y = y + dy - 16;
SDL_BlitSurface(frame_corner[3], 0, sfc, &r);
for (i = y + 16;i < y + dy - 16;i++) {
r.x = x;
r.y = i;
SDL_BlitSurface(frame_v[0], 0, sfc, &r);
r.x = x + dx - 16;
r.y = i;
SDL_BlitSurface(frame_v[1], 0, sfc, &r);
}
for (i = x + 16;i < x + dx - 16;i++) {
r.x = i;
r.y = y;
SDL_BlitSurface(frame_h[0], 0, sfc, &r);
r.x = i;
r.y = y + dy - 16;
SDL_BlitSurface(frame_h[1], 0, sfc, &r);
}
{
Uint8 *p;
for (j = 10;j < dy - 10;j++) {
p = (Uint8 *)sfc->pixels + (y + j) * sfc->pitch + (x + 10) * 4;
for (i = 10;i < dx - 10;i++, p += 4) {
/*
FIXME:
for some weird reason, changing the AOFFSET here doesn't work
instead on alpha it uses red (ROFFSET)...
probably has something to do with bitshifting and endianness
this works, but should be fixed!
*/
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
*((Uint32 *)p) = ((*(Uint32 *)p) | ((Uint32)a << (ROFFSET * 8)));
#else
*((Uint32 *)p) = ((*(Uint32 *)p) | ((Uint32)a << (AOFFSET * 8)));
#endif
}
}
}
}
void draw_menu_frame(SDL_Surface *sfc, int x, int y, int dx, int dy)
{
draw_menu_frame(sfc, x, y, dx, dy, 192);
}
SOUNDT load_sfx(char *folder, char *default_folder, char *sample)
{
char tmp[256];
SOUNDT stmp;
sprintf(tmp, "%s%s", folder, sample);
if (Sound_file_test(tmp)) {
stmp = Sound_create_sound(tmp);
#ifdef F1SPIRIT_DEBUG_MESSAGES
output_debug_message("%s: %p\n", tmp, stmp);
#endif
return stmp;
}
sprintf(tmp, "%s%s", default_folder, sample);
stmp = Sound_create_sound(tmp);
#ifdef F1SPIRIT_DEBUG_MESSAGES
output_debug_message("%s: %p\n", tmp, stmp);
#endif
return stmp;
} /* load_sfx */
| 25.625 | 175 | 0.508023 | pdpdds |
abb7de1094601dbf1560777070d4c17f69bae869 | 3,767 | cpp | C++ | tf2_src/hammer/replacetexdlg.cpp | IamIndeedGamingAsHardAsICan03489/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | src/hammer/replacetexdlg.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | null | null | null | src/hammer/replacetexdlg.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#include "stdafx.h"
#include "hammer.h"
#include "ReplaceTexDlg.h"
#include "MainFrm.h"
#include "GlobalFunctions.h"
#include "TextureBrowser.h"
#include "TextureSystem.h"
#include "mapdoc.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
CReplaceTexDlg::CReplaceTexDlg(int nSelected, CWnd* pParent /*=NULL*/)
: CDialog(CReplaceTexDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CReplaceTexDlg)
m_iSearchAll = nSelected ? FALSE : TRUE;
m_strFind = _T("");
m_strReplace = _T("");
m_iAction = 0;
m_bMarkOnly = FALSE;
m_bHidden = FALSE;
m_bRescaleTextureCoordinates = false;
//}}AFX_DATA_INIT
m_nSelected = nSelected;
}
void CReplaceTexDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CReplaceTexDlg)
DDX_Control(pDX, IDC_FIND, m_cFind);
DDX_Control(pDX, IDC_REPLACE, m_cReplace);
DDX_Control(pDX, IDC_REPLACEPIC, m_cReplacePic);
DDX_Control(pDX, IDC_FINDPIC, m_cFindPic);
DDX_Radio(pDX, IDC_INMARKED, m_iSearchAll);
DDX_Text(pDX, IDC_FIND, m_strFind);
DDX_Text(pDX, IDC_REPLACE, m_strReplace);
DDX_Radio(pDX, IDC_ACTION, m_iAction);
DDX_Check(pDX, IDC_MARKONLY, m_bMarkOnly);
DDX_Check(pDX, IDC_HIDDEN, m_bHidden);
DDX_Check(pDX, IDC_RESCALETEXTURECOORDINATES, m_bRescaleTextureCoordinates);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CReplaceTexDlg, CDialog)
//{{AFX_MSG_MAP(CReplaceTexDlg)
ON_BN_CLICKED(IDC_BROWSEREPLACE, OnBrowsereplace)
ON_BN_CLICKED(IDC_BROWSEFIND, OnBrowsefind)
ON_EN_UPDATE(IDC_FIND, OnUpdateFind)
ON_EN_UPDATE(IDC_REPLACE, OnUpdateReplace)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CReplaceTexDlg message handlers
void CReplaceTexDlg::BrowseTex(int iEdit)
{
CString strTex;
CWnd *pWnd = GetDlgItem(iEdit);
pWnd->GetWindowText(strTex);
CTextureBrowser *pBrowser = new CTextureBrowser(GetMainWnd());
pBrowser->SetUsed(iEdit == IDC_FIND);
pBrowser->SetInitialTexture(strTex);
if (pBrowser->DoModal() == IDOK)
{
IEditorTexture *pTex = g_Textures.FindActiveTexture(pBrowser->m_cTextureWindow.szCurTexture);
char szName[MAX_PATH];
if (pTex != NULL)
{
pTex->GetShortName(szName);
}
else
{
szName[0] = '\0';
}
pWnd->SetWindowText(szName);
}
delete pBrowser;
}
void CReplaceTexDlg::OnBrowsereplace()
{
BrowseTex(IDC_REPLACE);
}
void CReplaceTexDlg::OnBrowsefind()
{
BrowseTex(IDC_FIND);
}
//
// find/replace text string updates:
//
void CReplaceTexDlg::OnUpdateFind()
{
// get texture window and set texture in there
CString strTex;
m_cFind.GetWindowText(strTex);
IEditorTexture *pTex = g_Textures.FindActiveTexture(strTex);
m_cFindPic.SetTexture(pTex);
}
void CReplaceTexDlg::OnUpdateReplace()
{
// get texture window and set texture in there
CString strTex;
m_cReplace.GetWindowText(strTex);
IEditorTexture *pTex = g_Textures.FindActiveTexture(strTex);
m_cReplacePic.SetTexture(pTex);
}
BOOL CReplaceTexDlg::OnInitDialog()
{
CDialog::OnInitDialog();
if(!m_nSelected)
{
CWnd *pWnd = GetDlgItem(IDC_INMARKED);
pWnd->EnableWindow(FALSE);
}
OnUpdateFind();
return TRUE;
}
void CReplaceTexDlg::DoReplaceTextures()
{
CMapDoc *pDoc = CMapDoc::GetActiveMapDoc();
if ( pDoc )
{
pDoc->ReplaceTextures(
m_strFind,
m_strReplace,
m_iSearchAll,
m_iAction | ( m_bMarkOnly ? 0x100 : 0 ),
m_bHidden,
(m_bRescaleTextureCoordinates != 0)
);
}
}
| 22.289941 | 95 | 0.68171 | IamIndeedGamingAsHardAsICan03489 |
abb97809b15e472a71455984755df19149e3935a | 13,581 | hxx | C++ | main/svtools/inc/svtools/fmtfield.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/svtools/inc/svtools/fmtfield.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/svtools/inc/svtools/fmtfield.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _FMTFIELD_HXX_
#define _FMTFIELD_HXX_
#include "svtools/svtdllapi.h"
#include <vcl/spinfld.hxx>
#include <svl/zforlist.hxx>
//#define REGEXP_SUPPORT
#ifdef REGEXP_SUPPORT
#ifndef _UNOTOOLS_TEXTSEARCH_HXX
#include <unotools/textsearch.hxx>
#endif
#else
// use a hand-made regular expression parsing for the small expression we're interested in
// as soon as OOo does have regular expression support, we can switch on the REGEXP_SUPPORT define
namespace validation { class NumberValidator; }
#endif
typedef sal_uInt16 FORMAT_CHANGE_TYPE;
#define FCT_KEYONLY 0x00 // only a new key was set
#define FCT_FORMATTER 0x01 // a new formatter was set, usually implies a change of the key, too
#define FCT_PRECISION 0x02 // a new precision was set
#define FCT_THOUSANDSSEP 0x03 // the thousands separator setting changed
//------------------------------------------------------------------------------
class SVT_DLLPUBLIC FormattedField : public SpinField
{
private:
// Da ein SvNumberFormatter eine ziemlich teure (sowohl zeit- als auch platz-maessig) Angelegenheit ist,
// haelt sich nicht jedes Field, an dem kein Formatter gesetzt wurde, eine eigenen Instanz, sondern es gibt nur eine
// einzige statische.
class StaticFormatter
{
static SvNumberFormatter* s_cFormatter;
static sal_uLong s_nReferences;
public:
StaticFormatter();
~StaticFormatter();
operator SvNumberFormatter* () { return GetFormatter(); }
SVT_DLLPUBLIC SvNumberFormatter* GetFormatter();
};
protected:
String m_sLastValidText;
// hat nichts mit dem current value zu tun, ist der letzte Text, der waehrend einer Eingabe als gueltig erkannt
// wurde (also durch CheckText geprueft, nicht durch den Formatter gejagt)
Selection m_aLastSelection;
double m_dMinValue;
double m_dMaxValue;
sal_Bool m_bHasMin : 1;
sal_Bool m_bHasMax : 1;
sal_Bool m_bStrictFormat : 1;
sal_Bool m_bValueDirty : 1;
sal_Bool m_bEnableEmptyField : 1;
sal_Bool m_bAutoColor : 1;
sal_Bool m_bEnableNaN : 1;
double m_dCurrentValue;
double m_dDefaultValue;
sal_uLong m_nFormatKey;
SvNumberFormatter* m_pFormatter;
StaticFormatter m_aStaticFormatter;
double m_dSpinSize;
double m_dSpinFirst;
double m_dSpinLast;
// es macht einen Unterschied, ob man bei eingestellter Textformatierung beim LostFocus den aktuellen String durch
// den Formatter jagt und das Ergebnis anzeigt oder erst aus dem String ein double macht, das formatiert und dann
// ausgibt
sal_Bool m_bTreatAsNumber;
// und mit den folgenden Members koennen wir das Ganze hier auch zur formatierten Text-Ausgabe benutzen ...
String m_sCurrentTextValue;
String m_sDefaultText;
// die bei der letzten Ausgabe-Operation vom Formatter gelieferte Farbe (nicht dass wir sie beachten wuerden, aber
// man kann sie von aussen abfragen)
Color* m_pLastOutputColor;
bool m_bUseInputStringForFormatting;
public:
FormattedField(Window* pParent, WinBits nStyle = 0, SvNumberFormatter* pInitialFormatter = NULL, sal_Int32 nFormatKey = 0);
FormattedField(Window* pParent, const ResId& rResId, SvNumberFormatter* pInitialFormatter = NULL, sal_Int32 nFormatKey = 0);
virtual ~FormattedField();
// Min-/Max-Verwaltung
sal_Bool HasMinValue() const { return m_bHasMin; }
void ClearMinValue() { m_bHasMin = sal_False; }
void SetMinValue(double dMin);
double GetMinValue() const { return m_dMinValue; }
sal_Bool HasMaxValue() const { return m_bHasMax; }
void ClearMaxValue() { m_bHasMax = sal_False; }
void SetMaxValue(double dMax);
double GetMaxValue() const { return m_dMaxValue; }
// aktueller Wert
virtual void SetValue(double dVal);
virtual double GetValue();
// die Standard-Implementierung jagt die Eingabe jeweils durch den Formatter, so einer vorhanden ist
void GetColor() const;
void SetTextValue(const XubString& rText);
// der String wird in ein double umgewandelt (durch den Formatter) und anschliessen in SetValue gesteckt
sal_Bool IsEmptyFieldEnabled() const { return m_bEnableEmptyField; }
void EnableEmptyField(sal_Bool bEnable);
// wenn nicht enabled, wird beim Verlassen des Feldes der Text auf den letzten gueltigen zurueckgesetzt
void SetDefaultValue(double dDefault) { m_dDefaultValue = dDefault; m_bValueDirty = sal_True; }
// wenn der aktuelle String ungueltig ist, liefert GetValue() diesen Default-Wert
double GetDefaultValue() const { return m_dDefaultValue; }
// Einstellungen fuer das Format
sal_uLong GetFormatKey() const { return m_nFormatKey; }
void SetFormatKey(sal_uLong nFormatKey);
SvNumberFormatter* GetFormatter() const { return m_pFormatter; }
void SetFormatter(SvNumberFormatter* pFormatter, sal_Bool bResetFormat = sal_True);
// wenn bResetFormat sal_False ist, wird versucht, das alte eingestellte Format mit 'hinueberzuretten' (teuer, wenn es sich nicht
// um eines der Standard-Formate handelt, die in allen Formattern gleich sind)
// wenn sal_True, wird als neuer FormatKey 0 gesetzt
sal_Bool GetThousandsSep() const;
void SetThousandsSep(sal_Bool _bUseSeparator);
// the is no check if the current format is numeric, so be cautious when calling these functions
sal_uInt16 GetDecimalDigits() const;
void SetDecimalDigits(sal_uInt16 _nPrecision);
// the is no check if the current format is numeric, so be cautious when calling these functions
SvNumberFormatter* StandardFormatter() { return m_aStaticFormatter; }
// Wenn man keinen eigenen Formatter explizit anlegen will, kann man diesen hier in SetFormatter stecken ...
// Das hier gelieferte Objekt wird allerdings zwischen allen Instanzen der Klasse geteilt (aus Zeit- und Platzgruenden),
// also ist etwas Vorsicht angebracht ...
void GetFormat(XubString& rFormatString, LanguageType& eLang) const;
sal_Bool SetFormat(const XubString& rFormatString, LanguageType eLang);
// sal_False, wenn der FormatString nicht gesetzt werden konnte (also wahrscheinlich ungueltig ist)
sal_Bool IsStrictFormat() const { return m_bStrictFormat; }
void SetStrictFormat(sal_Bool bEnable) { m_bStrictFormat = bEnable; }
// Formatueberpruefung waehrend der Eingabe ?
// Spin-Handling
virtual void Up();
virtual void Down();
// Standard-Implementierung : hoch- oder runterzaehlen des aktuellen double einfach um die gesetzte SpinSize
virtual void First();
virtual void Last();
// Standard-Implementierung : aktuelles double setzen auf eingestellten first respektive last value
void SetSpinSize(double dStep) { m_dSpinSize = dStep; }
double GetSpinSize() const { return m_dSpinSize; }
void SetSpinFirst(double dFirst) { m_dSpinFirst = dFirst; }
double GetSpinFirst() const { return m_dSpinFirst; }
void SetSpinLast(double dLast) { m_dSpinLast = dLast; }
double GetSpinLast() const { return m_dSpinLast; }
sal_Bool TreatingAsNumber() const { return m_bTreatAsNumber; }
void TreatAsNumber(sal_Bool bDoSo) { m_bTreatAsNumber = bDoSo; }
public:
virtual void SetText( const XubString& rStr );
virtual void SetText( const XubString& rStr, const Selection& rNewSelection );
void SetValidateText(const XubString& rText, const String* pErrorText = NULL);
// die folgenden Methoden sind interesant, wenn m_bTreatAsNumber auf sal_False sitzt
/** nehmen wir mal an, irgendjemand will das ganze schoene double-Handling gar nicht haben, sondern
einfach den Text formatiert ausgeben ...
(der Text wird einfach nur durch den Formatter gejagt und dann gesetzt)
*/
void SetTextFormatted(const XubString& rText);
String GetTextValue() const;
void SetDefaultText(const XubString& rDefault) { m_sDefaultText = rDefault; }
String GetDefaultText() const { return m_sDefaultText; }
// die bei der letzten Ausgabe-Operation vom Formatter gelieferte Farbe (Ausgabe-Operationen werden getriggert durch
// SetValue, SetTextValue, SetTextFormatted, also indirekt eventuell auch durch SetMin-/-MaxValue)
Color* GetLastOutputColor() const { return m_pLastOutputColor; }
/** reformats the current text. Interesting if the user entered some text in an "input format", and
this should be formatted in the "output format" (which may differ, e.g. by additional numeric
digits or such).
*/
void Commit();
// enable automatic coloring. if set to sal_True, and the format the field is working with for any current value
// says that it has to be painted in a special color (e.g. a format where negative numbers should be printed
// red), the text is painted with that color automatically.
// The color used is the same as returned by GetLastOutputColor()
void SetAutoColor(sal_Bool _bAutomatic);
sal_Bool GetAutoColor() const { return m_bAutoColor; }
/** enables handling of not-a-number value.
When this is set to <FALSE/> (the default), then invalid inputs (i.e. text which cannot be
intepreted, according to the current formatting) will be handled as if the default value
has been entered. GetValue the will return this default value.
When set to <TRUE/>, then GetValue will return NaN (not a number, see <method scope="rtl::math">isNan</method>)
when the current input is invalid.
Note that setting this to <TRUE/> implies that upon leaving the control, the input
will *not* be corrected to a valid value. For example, if the user enters "foo" in the
control, and then tabs out of it, the text "foo" will persist, and GetValue will
return NaN in subsequent calls.
*/
void EnableNotANumber( sal_Bool _bEnable );
sal_Bool IsNotANumberEnabled( ) const { return m_bEnableNaN; }
/** When being set to true, the strings in the field are formatted using the
InputLine format. That's also what you get in Calc when you edit a cell
using F2
*/
void UseInputStringForFormatting( bool bUseInputStr = true );
bool IsUsingInputStringForFormatting() const;
protected:
virtual long Notify(NotifyEvent& rNEvt);
virtual void Modify();
// CheckText ueberschreiben fuer Ueberpruefung zur Eingabezeit
virtual sal_Bool CheckText(const XubString&) const { return sal_True; }
// any aspect of the current format has changed
virtual void FormatChanged(FORMAT_CHANGE_TYPE nWhat);
void ImplSetTextImpl(const XubString& rNew, Selection* pNewSel);
void ImplSetValue(double dValue, sal_Bool bForce);
sal_Bool ImplGetValue(double& dNewVal);
void ImplSetFormatKey(sal_uLong nFormatKey);
// SetFormatKey without FormatChanged notification
virtual SvNumberFormatter* CreateFormatter() { SetFormatter(StandardFormatter()); return m_pFormatter; }
SvNumberFormatter* ImplGetFormatter() const { return m_pFormatter ? m_pFormatter : ((FormattedField*)this)->CreateFormatter(); }
long PreNotify(NotifyEvent& rNEvt);
virtual void ReFormat();
};
//------------------------------------------------------------------------------
class SVT_DLLPUBLIC DoubleNumericField : public FormattedField
{
protected:
#ifdef REGEXP_SUPPORT
::utl::TextSearch* m_pConformanceTester;
#else
validation::NumberValidator* m_pNumberValidator;
#endif
public:
DoubleNumericField(Window* pParent, WinBits nStyle = 0)
:FormattedField(pParent, nStyle)
#ifdef REGEXP_SUPPORT
,m_pConformanceTester( NULL )
#else
,m_pNumberValidator( NULL )
#endif
{
ResetConformanceTester();
}
DoubleNumericField(Window* pParent, const ResId& rResId)
:FormattedField(pParent, rResId)
#ifdef REGEXP_SUPPORT
,m_pConformanceTester( NULL )
#else
,m_pNumberValidator( NULL )
#endif
{
ResetConformanceTester();
}
virtual ~DoubleNumericField();
protected:
virtual sal_Bool CheckText(const XubString& sText) const;
virtual void FormatChanged(FORMAT_CHANGE_TYPE nWhat);
void ResetConformanceTester();
};
//==============================================================================
#define FCT_CURRENCY_SYMBOL 0x10
#define FCT_CURRSYM_POSITION 0x20
//------------------------------------------------------------------------------
class DoubleCurrencyField : public FormattedField
{
XubString m_sCurrencySymbol;
sal_Bool m_bPrependCurrSym;
sal_Bool m_bChangingFormat;
public:
DoubleCurrencyField(Window* pParent, WinBits nStyle = 0);
DoubleCurrencyField(Window* pParent, const ResId& rResId);
XubString getCurrencySymbol() const { return m_sCurrencySymbol; }
void setCurrencySymbol(const XubString& _sSymbol);
sal_Bool getPrependCurrSym() const { return m_bPrependCurrSym; }
void setPrependCurrSym(sal_Bool _bPrepend);
protected:
virtual void FormatChanged(FORMAT_CHANGE_TYPE nWhat);
void UpdateCurrencyFormat();
};
#endif // _FMTFIELD_HXX_
| 39.138329 | 131 | 0.737206 | Grosskopf |
abc0c946edd3d6dfabe817ff8e86c87b3aecf71c | 7,107 | cpp | C++ | BCG/BCGPToolbarSystemMenuButton.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 2 | 2018-03-30T06:40:08.000Z | 2022-02-23T12:40:13.000Z | BCG/BCGPToolbarSystemMenuButton.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | null | null | null | BCG/BCGPToolbarSystemMenuButton.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 1 | 2020-08-11T05:48:02.000Z | 2020-08-11T05:48:02.000Z | //*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of the BCGControlBar Library
// Copyright (C) 1998-2014 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
// BCGToolbarSystemMenuButton.cpp: implementation of the CBCGPToolbarSystemMenuButton class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <afxpriv.h>
#include "BCGPToolBar.h"
#include "BCGPToolbarSystemMenuButton.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
IMPLEMENT_SERIAL(CBCGPToolbarSystemMenuButton, CBCGPToolbarMenuButton, VERSIONABLE_SCHEMA | 1)
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CBCGPToolbarSystemMenuButton::CBCGPToolbarSystemMenuButton()
{
m_hSysMenuIcon = NULL;
m_hSystemMenu = NULL;
}
//****************************************************************************************
CBCGPToolbarSystemMenuButton::CBCGPToolbarSystemMenuButton (HMENU hSystemMenu, HICON hSystemIcon) :
CBCGPToolbarMenuButton (0, hSystemMenu, -1)
{
m_hSysMenuIcon = hSystemIcon;
m_hSystemMenu = hSystemMenu;
if (m_hSysMenuIcon == NULL)
{
m_hSysMenuIcon = globalData.m_hiconApp;
}
}
//****************************************************************************************
CBCGPToolbarSystemMenuButton::~CBCGPToolbarSystemMenuButton()
{
}
//****************************************************************************************
void CBCGPToolbarSystemMenuButton::CopyFrom (const CBCGPToolbarButton& s)
{
CBCGPToolbarMenuButton::CopyFrom (s);
const CBCGPToolbarSystemMenuButton& src = (const CBCGPToolbarSystemMenuButton&) s;
m_hSysMenuIcon = src.m_hSysMenuIcon;
m_hSystemMenu = src.m_hSystemMenu;
}
//****************************************************************************************
SIZE CBCGPToolbarSystemMenuButton::OnCalculateSize (CDC* /*pDC*/, const CSize& sizeDefault,
BOOL /*bHorz*/)
{
return CSize (::GetSystemMetrics (SM_CXMENUSIZE), sizeDefault.cy);
}
//****************************************************************************************
void CBCGPToolbarSystemMenuButton::OnDraw (CDC* pDC, const CRect& rect,
CBCGPToolBarImages* /*pImages*/,
BOOL /*bHorz*/, BOOL /*bCustomizeMode*/,
BOOL /*bHighlight*/,
BOOL /*bDrawBorder*/, BOOL /*bGrayDisabledButtons*/)
{
if (m_hSysMenuIcon != NULL)
{
CSize size (min (::GetSystemMetrics (SM_CXSMICON), ::GetSystemMetrics (SM_CXMENUSIZE)),
min (::GetSystemMetrics (SM_CYSMICON), ::GetSystemMetrics (SM_CYMENUSIZE)));
int iOffset = (rect.Height () - size.cy) / 2;
::DrawIconEx (*pDC, rect.left, rect.top + iOffset, m_hSysMenuIcon,
size.cx, size.cy,
0, NULL, DI_NORMAL);
}
else
{
pDC->FillSolidRect(rect, RGB(255, 0, 0));
}
}
//****************************************************************************************
void CBCGPToolbarSystemMenuButton::OnDblClick (CWnd* pWnd)
{
if (CBCGPToolBar::IsCustomizeMode ())
{
return;
}
ASSERT (pWnd != NULL);
//////////////////////////////////////////////
// Make sure to close the popup menu and
// find the MDI frame correctly.
//--------------------------------------------
OnCancelMode ();
CFrameWnd* pParentFrame = BCGPGetParentFrame (pWnd);
if(pParentFrame != NULL && pParentFrame->IsKindOf (RUNTIME_CLASS (CMiniDockFrameWnd)))
{
pParentFrame = (CFrameWnd*) pParentFrame->GetParent ();
}
CMDIFrameWnd* pMDIFrame =
DYNAMIC_DOWNCAST (CMDIFrameWnd, pParentFrame);
if (pMDIFrame != NULL)
{
CMDIChildWnd* pChild = pMDIFrame->MDIGetActive ();
ASSERT_VALID (pChild);
BOOL bCloseIsDisabled = FALSE;
CMenu* pSysMenu = pChild->GetSystemMenu (FALSE);
if (pSysMenu != NULL)
{
MENUITEMINFO menuInfo;
ZeroMemory(&menuInfo,sizeof(MENUITEMINFO));
menuInfo.cbSize = sizeof(MENUITEMINFO);
menuInfo.fMask = MIIM_STATE;
pSysMenu->GetMenuItemInfo (SC_CLOSE, &menuInfo);
bCloseIsDisabled = ((menuInfo.fState & MFS_GRAYED) ||
(menuInfo.fState & MFS_DISABLED));
}
if (!bCloseIsDisabled)
{
pChild->SendMessage (WM_SYSCOMMAND, SC_CLOSE);
}
}
//--------------------------------------------
//////////////////////////////////////////////
}
//****************************************************************************************
void CBCGPToolbarSystemMenuButton::CreateFromMenu (HMENU hMenu)
{
m_hSystemMenu = hMenu;
}
//****************************************************************************************
HMENU CBCGPToolbarSystemMenuButton::CreateMenu () const
{
ASSERT (m_hSystemMenu != NULL);
HMENU hMenu = CBCGPToolbarMenuButton::CreateMenu ();
if (hMenu == NULL)
{
return NULL;
}
//---------------------------------------------------------------------
// System menu don't produce updating command statuses via the
// standard MFC idle command targeting. So, we should enable/disable
// system menu items according to the standard system menu status:
//---------------------------------------------------------------------
CMenu* pMenu = CMenu::FromHandle (hMenu);
ASSERT_VALID (pMenu);
CMenu* pSysMenu = CMenu::FromHandle (m_hSystemMenu);
ASSERT_VALID (pSysMenu);
int iCount = (int) pSysMenu->GetMenuItemCount ();
for (int i = 0; i < iCount; i ++)
{
UINT uiState = pSysMenu->GetMenuState (i, MF_BYPOSITION);
UINT uiCmd = pSysMenu->GetMenuItemID (i);
if (uiState & MF_CHECKED)
{
pMenu->CheckMenuItem (uiCmd, MF_CHECKED);
}
if (uiState & MF_DISABLED)
{
pMenu->EnableMenuItem (uiCmd, MF_DISABLED);
}
if (uiState & MF_GRAYED)
{
pMenu->EnableMenuItem (uiCmd, MF_GRAYED);
}
}
return hMenu;
}
//****************************************************************************************
void CBCGPToolbarSystemMenuButton::OnCancelMode ()
{
if (m_pPopupMenu != NULL && ::IsWindow (m_pPopupMenu->m_hWnd))
{
if (m_pPopupMenu->InCommand ())
{
return;
}
m_pPopupMenu->SaveState ();
m_pPopupMenu->m_bAutoDestroyParent = FALSE;
m_pPopupMenu->CloseMenu ();
}
m_pPopupMenu = NULL;
m_bToBeClosed = FALSE;
}
//****************************************************************************************
void CBCGPToolbarSystemMenuButton::OnAfterCreatePopupMenu ()
{
if (m_pPopupMenu != NULL && ::IsWindow (m_pPopupMenu->m_hWnd))
{
CFrameWnd* pParentFrame = BCGCBProGetTopLevelFrame (m_pPopupMenu);
if(pParentFrame != NULL && pParentFrame->IsKindOf (RUNTIME_CLASS (CMiniDockFrameWnd)))
{
pParentFrame = (CFrameWnd*) pParentFrame->GetParent ();
}
CMDIFrameWnd* pMDIFrame =
DYNAMIC_DOWNCAST (CMDIFrameWnd, pParentFrame);
if (pMDIFrame != NULL)
{
CMDIChildWnd* pChild = pMDIFrame->MDIGetActive ();
ASSERT_VALID (pChild);
m_pPopupMenu->SetMessageWnd (pChild);
}
}
}
| 29.736402 | 99 | 0.556071 | 11Zero |
abc4fb0ba91b9695df580ed90da3745bd7cf5ba4 | 1,454 | cpp | C++ | Leetcode/L1510.cpp | yanjinbin/Foxconn | d8340d228deb35bd8ec244f6156374da8a1f0aa0 | [
"CC0-1.0"
] | 8 | 2021-02-14T01:48:09.000Z | 2022-01-29T09:12:55.000Z | Leetcode/L1510.cpp | yanjinbin/Foxconn | d8340d228deb35bd8ec244f6156374da8a1f0aa0 | [
"CC0-1.0"
] | null | null | null | Leetcode/L1510.cpp | yanjinbin/Foxconn | d8340d228deb35bd8ec244f6156374da8a1f0aa0 | [
"CC0-1.0"
] | null | null | null |
#include <vector>
#include <iostream>
#include <queue>
#include <map>
#include <algorithm>
#include <functional>
#include <stack>
using namespace std;
const int INF = 0x3F3F3F3F;
const int MOD = 1E9 + 7;
#define ready ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define debug puts("pigtoria bling bling ⚡️⚡️");
#define FOR(i, a, b) for (int i = a; i < b; i++)
#define pii pair<int, int>
#define LL long long
#define LD long double
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define FI first
#define SE second
// 石子游戏IV
class Solution {
public:
vector<int> dp;
bool winnerSquareGame(int n) {
dp.resize(n + 1, -1);
dp[0] = 0;// 0 lose 1 win -1 unknown
return dfs(n);
}
// top-down
bool dfs(int n) {
if (dp[n] != -1) {
return dp[n];
}
for (int i = 1; i * i <= n; i++) {
if (dfs(n - i * i) == 0) { // 如果对方会输,则你有赢得机会
dp[n] = 1;
return true;
}
}
dp[n] = 0;
return false;
}
// bottom-up
bool winnerSquareGame_(int n) {
vector<bool> dp(n + 1, false);
for (int i = 1; i <= n; i++) {
for (int j = 1; j * j <= i; ++j) {
if (!dp[i - j * j]) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
};
int main() {
return 0;
} | 21.382353 | 72 | 0.486245 | yanjinbin |
abc72cde4ceb89ad6ce76afd70301195b5a726ec | 1,362 | cpp | C++ | src/get_coords.cpp | ropensci/geoops | e83b0e98a3d532f9081f3adab787f8f719c9ffc1 | [
"MIT"
] | 11 | 2018-05-19T08:37:37.000Z | 2020-09-14T05:36:52.000Z | src/get_coords.cpp | cran/geoops | ec6c9300b7a48a4a604ba3a4243da7d0360e85a3 | [
"MIT"
] | 3 | 2018-03-19T18:37:19.000Z | 2020-05-15T21:49:48.000Z | src/get_coords.cpp | cran/geoops | ec6c9300b7a48a4a604ba3a4243da7d0360e85a3 | [
"MIT"
] | 2 | 2018-09-01T12:26:15.000Z | 2019-10-14T14:18:34.000Z | #include <Rcpp.h>
#include "json.h"
using json = nlohmann::json;
// Checks if coordinates contains a number
bool contains_number(std::string coordinates) {
auto jj = json::parse(coordinates);
if (jj.size() > 1 && jj[0].is_number() && jj[1].is_number()) {
return true;
}
if (jj[0].is_array() && jj[0].size()) {
return contains_number(jj[0].dump());
}
throw std::runtime_error("coordinates must only contain numbers");
}
// Checks if coordinates contains a number
std::string check_contain(std::string x) {
if (contains_number(x)) {
return x;
} else {
throw std::runtime_error("No valid coordinates");
};
};
// [[Rcpp::export]]
std::string get_coords(std::string x) {
std::string z = x;
auto j = json::parse(z);
std::string out;
if (j.is_array()) {
// array
std::string out = z;
std::string res = check_contain(out);
return res;
// return out;
} else if (j["coordinates"].is_array()) {
// geometry object
std::string out = j["coordinates"].dump();
std::string res = check_contain(out);
return res;
} else if (j["geometry"]["coordinates"].is_array()) {
// feature
std::string out = j["geometry"]["coordinates"].dump();
// return out;
std::string res = check_contain(out);
return res;
} else {
throw std::runtime_error("No valid coordinates");
};
};
| 24.763636 | 68 | 0.621145 | ropensci |
abc9a270e4277476603cc7bd056e38800650c461 | 9,347 | cpp | C++ | node/main.cpp | quepas/pep-talk | 73a7e471517aee5595ca63bd007b1aae433fbc39 | [
"MIT"
] | 3 | 2020-12-15T13:41:46.000Z | 2021-09-06T10:26:42.000Z | main.cpp | quepas/peptalk-node | 0ee869abcdc58aeaca756a867b407e179ba655db | [
"MIT"
] | 6 | 2020-04-07T10:28:03.000Z | 2020-06-19T20:34:15.000Z | node/main.cpp | quepas/peptalk | 73a7e471517aee5595ca63bd007b1aae433fbc39 | [
"MIT"
] | null | null | null | #include <napi.h>
#include <timing.hpp>
#include <counting.hpp>
#include <profiling.hpp>
using namespace peptalk;
using std::function;
using std::string;
using std::vector;
function<void(string, string)> OnErrorOrWarning(Napi::Env& env) {
return [&env](string peptalk_msg, string papi_msg) {
Napi::Error::New(env, peptalk_msg + " : " + papi_msg).ThrowAsJavaScriptException();
};
}
vector<string> ExtractArrayOfStrings(const Napi::Array &array) {
vector<string> result;
result.reserve(array.Length());
for (size_t idx = 0; idx < array.Length(); ++idx) {
// TODO: check if each array element is a string
result.push_back(array.Get(idx).As<Napi::String>().Utf8Value());
}
return result;
}
/*
* Timing
*/
void TimingInit(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
if (info.Length() < 3) {
Napi::TypeError::New(env, "Wrong arguments. Expected: "
"(result_file: string, parameters: string[], num_measurements: number)")
.ThrowAsJavaScriptException();
return;
}
if (!info[0].IsString()) {
Napi::TypeError::New(env, "First argument must be a string").ThrowAsJavaScriptException();
return;
}
if (!info[1].IsArray()) {
Napi::TypeError::New(env, "Second argument must be of type string[]").ThrowAsJavaScriptException();
return;
}
if (!info[2].IsNumber()) {
Napi::TypeError::New(env, "Third argument must be a number").ThrowAsJavaScriptException();
return;
}
auto result_file = info[0].As<Napi::String>().Utf8Value();
auto parameter_names = info[1].As<Napi::Array>();
auto num_measurements = info[2].As<Napi::Number>().Uint32Value();
timing::Init(result_file, ExtractArrayOfStrings(parameter_names), num_measurements, OnErrorOrWarning(env));
}
void TimingStart(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
if (info.Length() < 1) {
Napi::TypeError::New(env,
"Wrong arguments. Expected: (parameters: string[])").ThrowAsJavaScriptException();
return;
}
if (!info[0].IsArray()) {
Napi::TypeError::New(env, "First argument must be of type string[]").ThrowAsJavaScriptException();
return;
}
auto parameter_names = info[0].As<Napi::Array>();
timing::Start(ExtractArrayOfStrings(parameter_names), OnErrorOrWarning(env));
}
void TimingStop(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
timing::Stop(OnErrorOrWarning(env));
}
void TimingClose(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
timing::Close(OnErrorOrWarning(env));
}
/*
* Counting
*/
void CountingInit(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
if (info.Length() < 4) {
Napi::TypeError::New(env, "Wrong arguments. Expected: "
"(result_file: string, parameters: string[],"
" performance_events: string[], num_measurements: number)")
.ThrowAsJavaScriptException();
return;
}
if (!info[0].IsString()) {
Napi::TypeError::New(env, "First argument must be a string").ThrowAsJavaScriptException();
return;
}
if (!info[1].IsArray()) {
Napi::TypeError::New(env, "Second argument must be of type string[]").ThrowAsJavaScriptException();
return;
}
if (!info[2].IsArray()) {
Napi::TypeError::New(env, "Third argument must be of type string[]").ThrowAsJavaScriptException();
return;
}
if (!info[3].IsNumber()) {
Napi::TypeError::New(env, "Fourth argument must be a number").ThrowAsJavaScriptException();
return;
}
auto result_file = info[0].As<Napi::String>().Utf8Value();
auto parameter_names = info[1].As<Napi::Array>();
auto performance_events = info[2].As<Napi::Array>();
auto num_measurements = info[3].As<Napi::Number>().Uint32Value();
counting::Init(result_file,
ExtractArrayOfStrings(parameter_names),
ExtractArrayOfStrings(performance_events),
num_measurements,
OnErrorOrWarning(env));
}
void CountingStart(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
if (info.Length() < 1) {
Napi::TypeError::New(env, "Wrong arguments. Expected: (parameters: string[])")
.ThrowAsJavaScriptException();
return;
}
if (!info[0].IsArray()) {
Napi::TypeError::New(env, "First argument must be of type string[]").ThrowAsJavaScriptException();
return;
}
auto parameter_names = info[0].As<Napi::Array>();
counting::Start(ExtractArrayOfStrings(parameter_names), OnErrorOrWarning(env));
}
void CountingStop(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
counting::Stop(OnErrorOrWarning(env));
}
void CountingClose(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
counting::Close(OnErrorOrWarning(env));
}
/*
* Profiling
*/
void ProfilingInit(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
if (info.Length() < 5) {
Napi::TypeError::New(env, "Wrong arguments. Expected: "
"(result_file: string, overflow_event: string,"
" overflow_threshold: number, performance_events: string[],"
" include_inst_address: bool)")
.ThrowAsJavaScriptException();
return;
}
if (!info[0].IsString()) {
Napi::TypeError::New(env, "First argument must be a string").ThrowAsJavaScriptException();
return;
}
if (!info[1].IsString()) {
Napi::TypeError::New(env, "Second argument must be a string").ThrowAsJavaScriptException();
return;
}
if (!info[2].IsNumber()) {
Napi::TypeError::New(env, "Third argument must be a number").ThrowAsJavaScriptException();
return;
}
if (!info[3].IsArray()) {
Napi::TypeError::New(env, "Fourth argument must be of type string[]").ThrowAsJavaScriptException();
return;
}
if (!info[4].IsBoolean()) {
Napi::TypeError::New(env, "Fifth argument must be a boolean").ThrowAsJavaScriptException();
return;
}
auto result_file = info[0].As<Napi::String>().Utf8Value();
auto overflow_event = info[1].As<Napi::String>().Utf8Value();
auto overflow_threshold = info[2].As<Napi::Number>().Uint32Value();
auto performance_events = info[3].As<Napi::Array>();
bool include_inst_address = info[4].As<Napi::Boolean>();
profiling::Init(result_file,
overflow_event,
overflow_threshold,
ExtractArrayOfStrings(performance_events),
include_inst_address,
OnErrorOrWarning(env));
}
void ProfilingStart(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
if (info.Length() < 1) {
Napi::TypeError::New(env, "Wrong arguments. Expected: (trace_header: string)")
.ThrowAsJavaScriptException();
return;
}
if (!info[0].IsString()) {
Napi::TypeError::New(env, "First argument must be a string").ThrowAsJavaScriptException();
return;
}
auto trace_header = info[0].As<Napi::String>().Utf8Value();
profiling::Start(trace_header, OnErrorOrWarning(env));
}
void ProfilingStop(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
profiling::Stop(OnErrorOrWarning(env));
}
void ProfilingClose(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
profiling::Close(OnErrorOrWarning(env));
}
static Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
/*
* Timing
*/
exports.Set(Napi::String::New(env, "timingInit"),
Napi::Function::New(env, TimingInit));
exports.Set(Napi::String::New(env, "timingStart"),
Napi::Function::New(env, TimingStart));
exports.Set(Napi::String::New(env, "timingStop"),
Napi::Function::New(env, TimingStop));
exports.Set(Napi::String::New(env, "timingClose"),
Napi::Function::New(env, TimingClose));
/*
* Counting
*/
exports.Set(Napi::String::New(env, "countingInit"),
Napi::Function::New(env, CountingInit));
exports.Set(Napi::String::New(env, "countingStart"),
Napi::Function::New(env, CountingStart));
exports.Set(Napi::String::New(env, "countingStop"),
Napi::Function::New(env, CountingStop));
exports.Set(Napi::String::New(env, "countingClose"),
Napi::Function::New(env, CountingClose));
/*
* Profiling
*/
exports.Set(Napi::String::New(env, "profilingInit"),
Napi::Function::New(env, ProfilingInit));
exports.Set(Napi::String::New(env, "profilingStart"),
Napi::Function::New(env, ProfilingStart));
exports.Set(Napi::String::New(env, "profilingStop"),
Napi::Function::New(env, ProfilingStop));
exports.Set(Napi::String::New(env, "profilingClose"),
Napi::Function::New(env, ProfilingClose));
return exports;
}
NODE_API_MODULE(pep_talk_node, InitAll)
| 35.95 | 111 | 0.611854 | quepas |
abca2b38f15a78dd26c059d92b69175c083018ae | 369 | cpp | C++ | Engine/EngineProject/DiceGameObject.cpp | joshuaRMS/BoardChampions- | b1146f721dd4e49b3fecba8243182efce64249f9 | [
"MIT"
] | 1 | 2019-12-09T13:53:40.000Z | 2019-12-09T13:53:40.000Z | Engine/EngineProject/DiceGameObject.cpp | joshuaRMS/BoardChampions- | b1146f721dd4e49b3fecba8243182efce64249f9 | [
"MIT"
] | null | null | null | Engine/EngineProject/DiceGameObject.cpp | joshuaRMS/BoardChampions- | b1146f721dd4e49b3fecba8243182efce64249f9 | [
"MIT"
] | null | null | null | #include "DiceGameObject.h"
void DiceGameObject::rollDices()
{
Dice1 = rand() % 6 + 1;
Dice2 = rand() % 6 + 1;
std::cout << Dice1 << std::endl;
}
void DiceGameObject::DrawDices()
{
}
void DiceGameObject::init()
{
rollDices();
}
void DiceGameObject::update(float elapsedTime)
{
}
DiceGameObject::DiceGameObject()
{
}
DiceGameObject::~DiceGameObject()
{
}
| 10.542857 | 46 | 0.661247 | joshuaRMS |
abcbb26b1b2bdd7ef7356308bc5fdb0b8aa510cb | 1,064 | cpp | C++ | NestedRangesCheck.cpp | zuhaib786/CSES_SOLUTIONS | d506d25919b9ebc9b2b809e1cd5327c14872e4a9 | [
"MIT"
] | 1 | 2021-06-18T01:48:37.000Z | 2021-06-18T01:48:37.000Z | NestedRangesCheck.cpp | zuhaib786/CSES_SOLUTIONS | d506d25919b9ebc9b2b809e1cd5327c14872e4a9 | [
"MIT"
] | null | null | null | NestedRangesCheck.cpp | zuhaib786/CSES_SOLUTIONS | d506d25919b9ebc9b2b809e1cd5327c14872e4a9 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct range
{
int first;
int second;
int index;
};
bool compare(range range1, range range2)
{
if (range1.first== range2.first)
{
return range1.second > range2.second;
}
return range1.first < range2.first;
}
int main() {
int n;
cin>>n;
vector<range> v(n);
vector<int> contains(n, 0);
vector<int> is_contained(n, 0);
for(int i = 0; i<n;i++)
{
int a, b;
cin>>a>>b;
v[i] = {a, b, i};
}
sort(v.begin(), v.end(), compare);
int max_range = 0, min_range = 1e9+7, i = 0, j = n-1;
for(; i<n && j>=0; i++, j--)
{
range r1 = v[i];
if (r1.second <= max_range)
{
is_contained[v[i].index] = 1;
}
max_range = max(max_range, r1.second);
range r2 = v[j];
if (r2.second >= min_range)
{
contains[v[j].index] = 1;
}
min_range = min(min_range, r2.second);
}
for(int i = 0; i<n;i++)
{
cout<< contains[i]<<" ";
}
cout<<endl;
for(int i = 0; i<n;i++)
{
cout<< is_contained[i]<<" ";
}
cout<<endl;
return 0;
} | 18.033898 | 55 | 0.531955 | zuhaib786 |
abcec6dfcedef9a428b6ad69cd6fb01a057be837 | 268 | cpp | C++ | libs/core/render/src/detail/bksge_core_render_detail_index_array_base.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/render/src/detail/bksge_core_render_detail_index_array_base.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/render/src/detail/bksge_core_render_detail_index_array_base.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file bksge_core_render_detail_index_array_base.cpp
*
* @brief IndexArrayBase の実装
*
* @author myoukaku
*/
#include <bksge/fnd/config.hpp>
#if !defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/detail/inl/index_array_base_inl.hpp>
#endif
| 20.615385 | 65 | 0.720149 | myoukaku |
abcef9e5bb12963e0c452adfd5bbb7a0b82903dd | 4,634 | cpp | C++ | gtsam/geometry/tests/testCyclic.cpp | kvmanohar22/gtsam | 8194b931fe07fb1bd346cdcf116a35f9c4e208ba | [
"BSD-3-Clause"
] | 1,402 | 2017-03-28T00:18:11.000Z | 2022-03-30T10:28:32.000Z | gtsam/geometry/tests/testCyclic.cpp | kvmanohar22/gtsam | 8194b931fe07fb1bd346cdcf116a35f9c4e208ba | [
"BSD-3-Clause"
] | 851 | 2017-11-27T15:09:56.000Z | 2022-03-31T22:26:38.000Z | gtsam/geometry/tests/testCyclic.cpp | kvmanohar22/gtsam | 8194b931fe07fb1bd346cdcf116a35f9c4e208ba | [
"BSD-3-Clause"
] | 565 | 2017-11-30T16:15:59.000Z | 2022-03-31T02:53:04.000Z | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file testCyclic.cpp
* @brief Unit tests for cyclic group
* @author Frank Dellaert
**/
#include <gtsam/geometry/Cyclic.h>
#include <gtsam/base/Testable.h>
#include <CppUnitLite/TestHarness.h>
using namespace std;
using namespace gtsam;
typedef Cyclic<3> Z3; // Let's use the cyclic group of order 3
typedef Cyclic<2> Z2;
//******************************************************************************
TEST(Cyclic, Concept) {
BOOST_CONCEPT_ASSERT((IsGroup<Z3>));
EXPECT_LONGS_EQUAL(0, traits<Z3>::Identity());
}
//******************************************************************************
TEST(Cyclic, Constructor) {
Z3 g(0);
}
//******************************************************************************
TEST(Cyclic, Compose) {
EXPECT_LONGS_EQUAL(0, traits<Z3>::Compose(Z3(0),Z3(0)));
EXPECT_LONGS_EQUAL(1, traits<Z3>::Compose(Z3(0),Z3(1)));
EXPECT_LONGS_EQUAL(2, traits<Z3>::Compose(Z3(0),Z3(2)));
EXPECT_LONGS_EQUAL(2, traits<Z3>::Compose(Z3(2),Z3(0)));
EXPECT_LONGS_EQUAL(0, traits<Z3>::Compose(Z3(2),Z3(1)));
EXPECT_LONGS_EQUAL(1, traits<Z3>::Compose(Z3(2),Z3(2)));
}
//******************************************************************************
TEST(Cyclic, Between) {
EXPECT_LONGS_EQUAL(0, traits<Z3>::Between(Z3(0),Z3(0)));
EXPECT_LONGS_EQUAL(1, traits<Z3>::Between(Z3(0),Z3(1)));
EXPECT_LONGS_EQUAL(2, traits<Z3>::Between(Z3(0),Z3(2)));
EXPECT_LONGS_EQUAL(1, traits<Z3>::Between(Z3(2),Z3(0)));
EXPECT_LONGS_EQUAL(2, traits<Z3>::Between(Z3(2),Z3(1)));
EXPECT_LONGS_EQUAL(0, traits<Z3>::Between(Z3(2),Z3(2)));
}
//******************************************************************************
TEST(Cyclic, Inverse) {
EXPECT_LONGS_EQUAL(0, traits<Z3>::Inverse(Z3(0)));
EXPECT_LONGS_EQUAL(2, traits<Z3>::Inverse(Z3(1)));
EXPECT_LONGS_EQUAL(1, traits<Z3>::Inverse(Z3(2)));
}
//******************************************************************************
TEST(Cyclic, Negation) {
EXPECT_LONGS_EQUAL(0, -Z3(0));
EXPECT_LONGS_EQUAL(2, -Z3(1));
EXPECT_LONGS_EQUAL(1, -Z3(2));
}
//******************************************************************************
TEST(Cyclic, Negation2) {
EXPECT_LONGS_EQUAL(0, -Z2(0));
EXPECT_LONGS_EQUAL(1, -Z2(1));
}
//******************************************************************************
TEST(Cyclic , Invariants) {
Z3 g(2), h(1);
EXPECT(check_group_invariants(g,h));
}
//******************************************************************************
// The Direct sum of Z2 and Z2 is *not* Cyclic<4>, but the
// smallest non-cyclic group called the Klein four-group:
typedef DirectSum<Z2, Z2> K4;
namespace gtsam {
/// Define K4 to be a model of the Additive Group concept, and provide Testable
template<>
struct traits<K4> : internal::AdditiveGroupTraits<K4> {
static void Print(const K4& m, const string& s = "") {
cout << s << "(" << m.first << "," << m.second << ")" << endl;
}
static bool Equals(const K4& m1, const K4& m2, double tol = 1e-8) {
return m1 == m2;
}
};
} // namespace gtsam
TEST(Cyclic , DirectSum) {
// The Direct sum of Z2 and Z2 is *not* Cyclic<4>, but the
// smallest non-cyclic group called the Klein four-group:
BOOST_CONCEPT_ASSERT((IsGroup<K4>));
BOOST_CONCEPT_ASSERT((IsTestable<K4>));
// Refer to http://en.wikipedia.org/wiki/Klein_four-group
K4 e(0,0), a(0, 1), b(1, 0), c(1, 1);
EXPECT(assert_equal(a, - a));
EXPECT(assert_equal(b, - b));
EXPECT(assert_equal(c, - c));
EXPECT(assert_equal(a, a + e));
EXPECT(assert_equal(b, b + e));
EXPECT(assert_equal(c, c + e));
EXPECT(assert_equal(e, a + a));
EXPECT(assert_equal(e, b + b));
EXPECT(assert_equal(e, c + c));
EXPECT(assert_equal(c, a + b));
EXPECT(assert_equal(b, a + c));
EXPECT(assert_equal(a, b + c));
EXPECT(assert_equal(c, a - b));
EXPECT(assert_equal(a, b - c));
EXPECT(assert_equal(b, c - a));
EXPECT(check_group_invariants(a, b));
EXPECT(check_group_invariants(b, c));
EXPECT(check_group_invariants(c, a));
}
//******************************************************************************
int main() {
TestResult tr;
return TestRegistry::runAllTests(tr);
}
//******************************************************************************
| 32.633803 | 80 | 0.518343 | kvmanohar22 |
abd4da0a61e24c5dfb3f3c38d60cbafc05a0a009 | 2,419 | cc | C++ | src/q_151_200/q0200.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | 2 | 2021-09-28T18:41:03.000Z | 2021-09-28T18:42:57.000Z | src/q_151_200/q0200.cc | vNaonLu/Daily_LeetCode | 30024b561611d390931cef1b22afd6a5060cf586 | [
"MIT"
] | 16 | 2021-09-26T11:44:20.000Z | 2021-11-28T06:44:02.000Z | src/q_151_200/q0200.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | 1 | 2021-11-22T09:11:36.000Z | 2021-11-22T09:11:36.000Z | #include <gtest/gtest.h>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
/**
* This file is generated by leetcode_add.py v1.0
*
* 200.
* Number of Islands
*
* ––––––––––––––––––––––––––––– Description –––––––––––––––––––––––––––––
*
* Given an ‘m x n’ 2D binary grid ‘grid’ which represents a map of ‘'1'’
* s (land) and ‘'0'’ s (water), return “the number of islands”
* An “island” is surrounded by water and is formed by connecting
* adjacent lands horizontally or vertically. You may assume all four
* edges of the grid are all surrounded by water.
*
* ––––––––––––––––––––––––––––– Constraints –––––––––––––––––––––––––––––
*
* • ‘m = grid.length’
* • ‘n = grid[i].length’
* • ‘1 ≤ m, n ≤ 300’
* • ‘grid[i][j]’ is ‘'0'’ or ‘'1'’ .
*
*/
struct q200 : public ::testing::Test {
// Leetcode answer here
class Solution {
private:
vector<int> dir = {-1, 0, 1, 0, 0, 1, 0, -1};
public:
int numIslands(vector<vector<char>>& grid) {
int res = 0;
int m = grid.size(), n = grid[0].size();
queue<pair<int, int>> island;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
island.push({i, j});
grid[i][j] = '0';
while (!island.empty()) {
auto& p = island.front();
for (int k = 0; k < dir.size(); ++k) {
int x = p.first + dir[k],
y = p.second + dir[++k];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') {
grid[x][y] = '0';
island.emplace(x, y);
}
}
island.pop();
}
++res;
}
}
}
return res;
}
};
class Solution *solution;
};
TEST_F(q200, sample_input01) {
solution = new Solution();
vector<vector<char>> grid = {{'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}};
int exp = 1;
EXPECT_EQ(solution->numIslands(grid), exp);
delete solution;
}
TEST_F(q200, sample_input02) {
solution = new Solution();
vector<vector<char>> grid = {{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}};
int exp = 3;
EXPECT_EQ(solution->numIslands(grid), exp);
delete solution;
} | 29.144578 | 139 | 0.446465 | vNaonLu |
abd9de720def75125a9f45c56f58d0dbe5d584b1 | 1,215 | cpp | C++ | src/Graphics/TextureCPU.cpp | StarNuik/poi.Graphics | 551ef5eeb8f1576c4d7ac0d5dee4ff8faee8cc3c | [
"MIT"
] | null | null | null | src/Graphics/TextureCPU.cpp | StarNuik/poi.Graphics | 551ef5eeb8f1576c4d7ac0d5dee4ff8faee8cc3c | [
"MIT"
] | null | null | null | src/Graphics/TextureCPU.cpp | StarNuik/poi.Graphics | 551ef5eeb8f1576c4d7ac0d5dee4ff8faee8cc3c | [
"MIT"
] | null | null | null | #include <stb_image.h>
#include <string>
#include <GL/glew.h>
#include "Graphics/TextureCPU.hpp"
#include "Graphics/Enums/TextureFormatGPU.hpp"
#include "Graphics/Enums/TextureFormatCPU.hpp"
using namespace poi::Graphics;
namespace /* Project constants */
{
using namespace poi;
const int32 InternalChannelsCount = 4;
// const TextureFormatGPU InternalTextureFormat = TextureFormatGPU::RGBA;
const TexturePixelType InternalPixelType = TexturePixelType::UnsignedByte;
// inline uint8 FormatToChannels(TextureFormatCPU f)
// {
// return (f == TextureFormatCPU::RGB ? 3 : 4);
// }
}
TextureCPU::TextureCPU(const uint16 width, const uint16 height, const TextureFormatCPU format)
{
this->width = width;
this->height = height;
this->format = format;
this->channels = (uint8)format;
const uint32 arraySize = sizeof(uint8) * width * height * channels;
pixels = new uint8[arraySize];
}
TextureCPU::~TextureCPU()
{
delete[] pixels;
}
TextureFormatGPU TextureCPU::GetCPUFormat()
{
return (format == TextureFormatCPU::RGB ? TextureFormatGPU::RGB : TextureFormatGPU::RGBA);
}
TexturePixelType TextureCPU::GetCPUPixelType()
{
return InternalPixelType;
} | 24.795918 | 95 | 0.720165 | StarNuik |
abdb21f77748c08b2564dccc8027c0ec9f9143ca | 1,693 | cc | C++ | bend_mnbrak.cc | lehoangha/tomo2d_HeriotWatt | 48477115ed2455a8255521570e4e81ffe754be08 | [
"MIT"
] | 3 | 2018-05-03T14:42:29.000Z | 2021-11-03T06:59:54.000Z | bend_mnbrak.cc | lehoangha/tomo2d_HeriotWatt | 48477115ed2455a8255521570e4e81ffe754be08 | [
"MIT"
] | 1 | 2015-10-07T03:23:17.000Z | 2015-10-07T03:23:17.000Z | bend_mnbrak.cc | lehoangha/tomo2d_HeriotWatt | 48477115ed2455a8255521570e4e81ffe754be08 | [
"MIT"
] | 2 | 2018-09-19T13:17:25.000Z | 2021-07-28T07:37:34.000Z | /*
* bend_mnbrak.cc - initial bracket search for bending solver
* (taken from Numerical Recipe's mnbrak.cc)
*
* Jun Korenaga, MIT/WHOI
* January 1999
*/
#include "bend.h"
#include <math.h>
#define GOLD 1.618034
#define GLIMIT 100.0
#define TINY 1.0e-20
#define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
static double maxarg1,maxarg2;
#define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ?\
(maxarg1) : (maxarg2))
void BendingSolver2d::mnbrak(double *ax, double *bx, double *cx,
double *fa, double *fb, double *fc,
PF1DIM pfunc)
{
double ulim,u,r,q,fu,dum;
*fa=(this->*pfunc)(*ax);
*fb=(this->*pfunc)(*bx);
if (*fb > *fa) {
SHFT(dum,*ax,*bx,dum)
SHFT(dum,*fb,*fa,dum)
}
*cx=(*bx)+GOLD*(*bx-*ax);
*fc=(this->*pfunc)(*cx);
while (*fb > *fc) {
r=(*bx-*ax)*(*fb-*fc);
q=(*bx-*cx)*(*fb-*fa);
u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
(2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
ulim=(*bx)+GLIMIT*(*cx-*bx);
if ((*bx-u)*(u-*cx) > 0.0) {
fu=(this->*pfunc)(u);
if (fu < *fc) {
*ax=(*bx);
*bx=u;
*fa=(*fb);
*fb=fu;
return;
} else if (fu > *fb) {
*cx=u;
*fc=fu;
return;
}
u=(*cx)+GOLD*(*cx-*bx);
fu=(this->*pfunc)(u);
} else if ((*cx-u)*(u-ulim) > 0.0) {
fu=(this->*pfunc)(u);
if (fu < *fc) {
SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
SHFT(*fb,*fc,fu,(this->*pfunc)(u))
}
} else if ((u-ulim)*(ulim-*cx) >= 0.0) {
u=ulim;
fu=(this->*pfunc)(u);
} else {
u=(*cx)+GOLD*(*cx-*bx);
fu=(this->*pfunc)(u);
}
SHFT(*ax,*bx,*cx,u)
SHFT(*fa,*fb,*fc,fu)
}
}
#undef GOLD
#undef GLIMIT
#undef TINY
#undef SHFT
| 22.276316 | 67 | 0.512109 | lehoangha |
abdd36d00280f356be581d89281511a8973376b7 | 1,275 | cpp | C++ | chapter16/Mammal2.cpp | UncleCShark/CppIn24HoursWithCmake | 7d1f30906fed2c7d144e5495ad42a3a9a59d2dce | [
"MIT"
] | null | null | null | chapter16/Mammal2.cpp | UncleCShark/CppIn24HoursWithCmake | 7d1f30906fed2c7d144e5495ad42a3a9a59d2dce | [
"MIT"
] | null | null | null | chapter16/Mammal2.cpp | UncleCShark/CppIn24HoursWithCmake | 7d1f30906fed2c7d144e5495ad42a3a9a59d2dce | [
"MIT"
] | null | null | null | #include <iostream>
enum BREED {
YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB
};
class Mammal {
public:
// constructors
Mammal() : age(2), weight(5) {
}
~Mammal() {
}
// accessors
int getAge() const {
return age;
}
void setAge(int newAge) {
age = newAge;
}
int getWeight() const {
return weight;
}
void setWeight(int newWeight) {
weight = newWeight;
}
// other methods
void speak() const {
std::cout << "Mammal sound!\n";
}
void sleep() const {
std::cout << "Shhh. I'm sleeping.\n";
}
protected:
int age;
int weight;
};
class Dog : public Mammal {
public:
// constructors
Dog() : breed(YORKIE) {
}
~Dog() {
}
// accessors
BREED getBreed() const {
return breed;
}
void setBreed(BREED newBreed) {
breed = newBreed;
}
// other methods
void wagTail() {
std::cout << "Tail wagging ...\n";
}
void begForFood() {
std::cout << "Begging for food ...\n";
}
private:
BREED breed;
};
int main() {
Dog fido;
fido.speak();
fido.wagTail();
std::cout << "Fido is " << fido.getAge() << " years old\n";
return 0;
}
| 14.010989 | 63 | 0.505882 | UncleCShark |
abdd99bdb841232280a77408c20ced5bc6bf9c8f | 840 | cpp | C++ | problems/leet/92-reverse-linked-list-ii/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/leet/92-reverse-linked-list-ii/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/leet/92-reverse-linked-list-ii/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// *****
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
if (m == n)
return head;
ListNode pre_head(0, head);
head = &pre_head;
while (m > 1) {
--m, --n;
head = head->next;
}
ListNode *tail = head->next;
ListNode *ntail = head->next->next;
while (n > 1) {
--n;
ListNode *next_ntail = ntail->next;
ntail->next = tail;
tail = ntail;
ntail = next_ntail;
}
head->next->next = ntail;
head->next = tail;
return pre_head.next;
}
};
// *****
int main() {
return 0;
}
| 18.26087 | 58 | 0.545238 | brunodccarvalho |
abdf41741f09be06393ad86892a1bba03b4076b7 | 5,440 | cc | C++ | tls/src/internal.cc | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | tls/src/internal.cc | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | tls/src/internal.cc | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | /*
** Copyright 2009-2013,2017 Centreon
**
** 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 more information : contact@centreon.com
*/
#include <cstring>
#include <gnutls/gnutls.h>
#if GNUTLS_VERSION_NUMBER < 0x030000
# include <cerrno>
# include <pthread.h>
# include <gcrypt.h>
#endif // GNU TLS < 3.0.0
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/io/raw.hh"
#include "com/centreon/broker/io/stream.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/tls/internal.hh"
#include "com/centreon/broker/tls/stream.hh"
using namespace com::centreon::broker;
/**************************************
* *
* Global Objects *
* *
**************************************/
/**
* Those 2048-bits wide Diffie-Hellman parameters were generated the
* 30/07/2009 on Ubuntu 9.04 x86 using OpenSSL 0.9.8g with generator 2.
*/
unsigned char const tls::dh_params_2048[] =
"-----BEGIN DH PARAMETERS-----\n" \
"MIIBCAKCAQEA93F3CN41kJooLbqcOdWHJPb+/zPV+mMs5Svb6PVH/XS3BK/tuuVu\n" \
"r9okkOzGr07KLPiKf+3MJSgHs9N91wPG6JcMcRys3fH1Tszh1i1317tE54o+oLPv\n" \
"jcs9P13lFlZm4gB7sjkR5If/ZtudoVwv7JS5WHIXrzew7iW+kT/QXCp+jkO1Vusc\n" \
"mQHlq4Fqt/p7zxOHVc8GBttE6/vEYipm2pdym1kBy62Z6rZLowkukngI5uzdQvB4\n" \
"Pmq5BmeRzGRClSkmRW4pUXiBac8SMAgMBl7cgAEaURR2D8Y4XltyXW51xzO1x1QM\n" \
"bOl9nneRY2Y8X3FOR1+Mzt+x44F+cWtqIwIBAg==\n" \
"-----END DH PARAMETERS-----\n";
gnutls_dh_params_t tls::dh_params;
#if GNUTLS_VERSION_NUMBER < 0x030000
GCRY_THREAD_OPTION_PTHREAD_IMPL;
#endif // GNU TLS < 3.0.0
/**************************************
* *
* Static Functions *
* *
**************************************/
// Might be used below, when library logging is enabled.
// static void log_gnutls_message(int level, char const* message) {
// (void)level;
// logging::debug(logging::low)
// << "TLS: GNU TLS debug: " << message;
// return ;
// }
/**************************************
* *
* Global Functions *
* *
**************************************/
/**
* Deinit the TLS library.
*/
void tls::destroy() {
// Unload Diffie-Hellman parameters.
gnutls_dh_params_deinit(dh_params);
// Unload GNU TLS library
gnutls_global_deinit();
return ;
}
/**
* @brief TLS initialization function.
*
* Prepare all necessary ressources for TLS use.
*/
void tls::initialize() {
gnutls_datum_t const dhp =
{ const_cast<unsigned char*>(dh_params_2048),
sizeof(dh_params_2048) };
int ret;
// Eventually initialize libgcrypt.
#if GNUTLS_VERSION_NUMBER < 0x030000
logging::info(logging::high)
<< "TLS: initializing libgcrypt (GNU TLS <= 2.11.0)";
gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
#endif // GNU TLS < 3.0.0
// Initialize GNU TLS library.
if (gnutls_global_init() != GNUTLS_E_SUCCESS)
throw (exceptions::msg()
<< "TLS: GNU TLS library initialization failed");
// Log GNU TLS version.
{
logging::info(logging::medium)
<< "TLS: compiled with GNU TLS version " << GNUTLS_VERSION;
char const* v(gnutls_check_version(GNUTLS_VERSION));
if (!v)
throw (exceptions::msg() << "TLS: GNU TLS run-time version is "
<< "incompatible with the compile-time version ("
<< GNUTLS_VERSION
<< "): please update your GNU TLS library");
logging::info(logging::high)
<< "TLS: loading GNU TLS version " << v;
// gnutls_global_set_log_function(log_gnutls_message);
// gnutls_global_set_log_level(11);
}
// Load Diffie-Hellman parameters.
ret = gnutls_dh_params_init(&dh_params);
if (ret != GNUTLS_E_SUCCESS)
throw (exceptions::msg()
<< "TLS: could not load TLS Diffie-Hellman parameters: "
<< gnutls_strerror(ret));
ret = gnutls_dh_params_import_pkcs3(
dh_params,
&dhp,
GNUTLS_X509_FMT_PEM);
if (ret != GNUTLS_E_SUCCESS)
throw (exceptions::msg()
<< "TLS: could not import PKCS #3 parameters: "
<< gnutls_strerror(ret));
return ;
}
/**
* The following static function is used to receive data from the lower
* layer and give it to TLS for decoding.
*/
ssize_t tls::pull_helper(
gnutls_transport_ptr_t ptr,
void* data,
size_t size) {
return (static_cast<tls::stream*>(ptr)->read_encrypted(data, size));
}
/**
* The following static function is used to send data from TLS to the lower
* layer.
*/
ssize_t tls::push_helper(
gnutls_transport_ptr_t ptr,
void const* data,
size_t size) {
return (static_cast<tls::stream*>(ptr)->write_encrypted(data, size));
}
| 31.627907 | 76 | 0.617279 | sdelafond |
abe1d57fa229bbcefbda3b3fb5e52d4b6be8f7e9 | 2,578 | hpp | C++ | third_party/boost/simd/arch/common/scalar/function/reversebits.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 6 | 2018-02-25T22:23:33.000Z | 2021-01-15T15:13:12.000Z | third_party/boost/simd/arch/common/scalar/function/reversebits.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/arch/common/scalar/function/reversebits.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 7 | 2017-12-12T12:36:31.000Z | 2020-02-10T14:27:07.000Z | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REVERSEBITS_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REVERSEBITS_HPP_INCLUDED
#include <boost/simd/detail/dispatch/function/overload.hpp>
#include <boost/config.hpp>
namespace boost { namespace simd { namespace ext
{
namespace bd = boost::dispatch;
BOOST_DISPATCH_OVERLOAD ( reversebits_
, (typename A0)
, bd::cpu_
, bd::scalar_< bd::ints8_<A0> >
)
{
BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT
{
return std::uint8_t(
((uint8_t(a0) * 0x0802LU & 0x22110LU)
| (uint8_t(a0) * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16
);
}
};
BOOST_DISPATCH_OVERLOAD ( reversebits_
, (typename A0)
, bd::cpu_
, bd::scalar_< bd::ints64_<A0> >
)
{
BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT
{
union { A0 a; std::uint32_t b[2]; } z = {a0};
z.b[0] = reversebits(z.b[0]);
z.b[1] = reversebits(z.b[1]);
std::swap(z.b[0], z.b[1]);
return z.a;
}
};
BOOST_DISPATCH_OVERLOAD ( reversebits_
, (typename A0)
, bd::cpu_
, bd::scalar_< bd::ints16_<A0> >
)
{
BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT
{
union { A0 a; std::uint8_t b[2]; } z = {a0};
z.b[0] = reversebits(z.b[0]);
z.b[1] = reversebits(z.b[1]);
std::swap(z.b[0], z.b[1]);
return z.a;
}
};
BOOST_DISPATCH_OVERLOAD ( reversebits_
, (typename A0)
, bd::cpu_
, bd::scalar_< bd::ints32_<A0> >
)
{
BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT
{
union { A0 a; std::uint16_t b[2]; } z = {a0};
z.b[0] = reversebits(z.b[0]);
z.b[1] = reversebits(z.b[1]);
std::swap(z.b[0], z.b[1]);
return z.a;
}
};
} } }
#endif
| 29.976744 | 100 | 0.470132 | SylvainCorlay |
abe2a63ef55c0637ba4fb6d4a27fb557ddd39bd9 | 5,461 | cpp | C++ | Code/Motor2D/Menu.cpp | isaaccalvis/DevGame | e972f4fd2ce756cb2ea00411d04a2ad99bce51c0 | [
"Unlicense"
] | null | null | null | Code/Motor2D/Menu.cpp | isaaccalvis/DevGame | e972f4fd2ce756cb2ea00411d04a2ad99bce51c0 | [
"Unlicense"
] | null | null | null | Code/Motor2D/Menu.cpp | isaaccalvis/DevGame | e972f4fd2ce756cb2ea00411d04a2ad99bce51c0 | [
"Unlicense"
] | null | null | null | #include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Map.h"
#include "j1Scene.h"
#include "Menu.h"
#include "ModulePlayer.h"
#include "ModuleEnemies.h"
#include "j1FadeToBlack.h"
#include "ModuleGui.h"
#include "gui_image.h"
#include "SDL_mixer\include\SDL_mixer.h"
Menu::Menu() : j1Module(){
name.create("scene");
}
Menu::~Menu(){}
bool Menu::Awake(pugi::xml_node& config){
return true;
}
bool Menu::Start(){
back = App->tex->Load("textures/menu_background.png");
App->gui->atlas = App->tex->Load("textures/Game_Gui_Buttons.png");
background = App->gui->addImage(0, 0, { 0, 0, 1024, 640 }, back, nullptr, nullptr, false);
new_game = App->gui->addButton(170, 330, { 50, 25, 250, 70 }, App->gui->atlas, nullptr, nullptr, { 50, 212, 250, 70 }, { 49, 392, 250, 70 }, this);
settings = App->gui->addButton(630, 160, { 50, 120, 250, 70 }, App->gui->atlas, nullptr, nullptr, { 50, 298, 250, 70 }, { 50, 487, 250, 70 }, this);
credits = App->gui->addButton(630, 330, { 435, 122, 255, 75 }, App->gui->atlas, nullptr, nullptr, { 435, 300, 255, 75 }, { 435, 489, 255, 70 }, this);
quit = App->gui->addButton(630, 500, { 435, 25, 255, 75 }, App->gui->atlas, nullptr, nullptr, { 435, 213, 255, 75 }, { 435, 392, 255, 75 }, this);
load_button = App->gui->addButton(170, 500, { 735, 25, 250, 70 }, App->gui->atlas, nullptr, nullptr, { 735, 121, 250, 70 }, { 735, 212, 250, 70 }, this);
return true;
}
bool Menu::PreUpdate(){
return true;
}
bool Menu::Update(float dt){
return true;
}
bool Menu::PostUpdate(){
bool ret = true;
if (start_game) {
App->render->cam.x = 0;
App->map->Start();
App->fade->FadeToBlack(this, (j1Module*)App->scene, 1.0f);
start_game = false;
}
else if (exit_game) {
ret = false;
exit_game = false;
}
else if (opt) {
for (p2List_item<GUI_object*>* it = App->gui->gui_objects.start; it != nullptr; it = it->next)
{
it->data->CleanUp();
}
back = App->tex->Load("textures/menu_background.png");
App->gui->atlas = App->tex->Load("textures/Game_Gui_Buttons.png");
App->gui->gui_objects.clear();
background = App->gui->addImage(0, 0, { 0, 0, 1024, 640 }, back, nullptr, nullptr, false);
sound_bar = App->gui->addScrollBar(200, 500, { 1034, 490, 306, 70 }, App->gui->atlas, App->gui->atlas, { 1372, 480, 66, 66 }, 10, 10, false, this, nullptr, false);
back_button = App->gui->addButton(630, 500, { 1220, 27, 255, 70 }, App->gui->atlas, nullptr, nullptr, { 1220, 123, 255, 70 }, { 1220, 214, 255, 70 }, this);
opt = false;
}
else if (cred) {
for (p2List_item<GUI_object*>* it = App->gui->gui_objects.start; it != nullptr; it = it->next)
{
it->data->CleanUp();
}
App->gui->gui_objects.clear();
cred = false;
}
else if (loadGame) {
for (p2List_item<GUI_object*>* it = App->gui->gui_objects.start; it != nullptr; it = it->next)
{
it->data->CleanUp();
}
App->gui->gui_objects.clear();
App->enemies->active = true;
App->scene->active = true;
App->map->active = true;
App->player->active = true;
need_load = true;
loadGame = false;
}
else if (go_back) {
for (p2List_item<GUI_object*>* it = App->gui->gui_objects.start; it != nullptr; it = it->next)
{
it->data->CleanUp();
}
App->gui->gui_objects.clear();
back = App->tex->Load("textures/menu_background.png");
App->gui->atlas = App->tex->Load("textures/Game_Gui_Buttons.png");
background = App->gui->addImage(0, 0, { 0, 0, 1024, 640 }, back, nullptr, nullptr, false);
new_game = App->gui->addButton(170, 330, { 50, 25, 250, 70 }, App->gui->atlas, nullptr, nullptr, { 50, 212, 250, 70 }, { 49, 392, 250, 70 }, this);
settings = App->gui->addButton(630, 160, { 50, 120, 250, 70 }, App->gui->atlas, nullptr, nullptr, { 50, 298, 250, 70 }, { 50, 487, 250, 70 }, this);
credits = App->gui->addButton(630, 330, { 435, 122, 255, 75 }, App->gui->atlas, nullptr, nullptr, { 435, 300, 255, 75 }, { 435, 489, 255, 70 }, this);
quit = App->gui->addButton(630, 500, { 435, 25, 255, 75 }, App->gui->atlas, nullptr, nullptr, { 435, 213, 255, 75 }, { 435, 392, 255, 75 }, this);
load_button = App->gui->addButton(170, 500, { 735, 25, 250, 70 }, App->gui->atlas, nullptr, nullptr, { 735, 121, 250, 70 }, { 735, 212, 250, 70 }, this);
go_back = false;
}
return ret;
}
bool Menu::CleanUp()
{
LOG("Freeing menu");
for (p2List_item<GUI_object*>* it = App->gui->gui_objects.start; it != nullptr; it = it->next)
{
it->data->CleanUp();
}
App->gui->gui_objects.clear();
if (active) {
App->enemies->Start();
App->player->Start();
App->enemies->active = true;
App->scene->active = true;
App->map->active = true;
App->player->active = true;
active = false;
}
return true;
}
void Menu::CallBack(GUI_object* object, GUI_OBJECT_STATE state)
{
switch (state) {
case GUI_OBJECT_STATE::MOUSE_IN:
break;
case GUI_OBJECT_STATE::MOUSE_OUT:
break;
case GUI_OBJECT_STATE::MOUSE_ON_CLICK:
break;
case GUI_OBJECT_STATE::MOUSE_OFF_CLICK:
if (object == new_game)
start_game = true;
else if (object == load_button)
loadGame = true;
else if (object == settings)
opt = true;
else if (object == credits)
cred = true;
else if (object == quit)
exit_game = true;
else if (object == back_button)
go_back = true;
else if (object == sound_bar)
Mix_VolumeMusic(sound_bar->returnNumer0to100());
break;
}
} | 26.004762 | 165 | 0.625343 | isaaccalvis |
abe2a86acd090a95c83715fa8121aed1195bb1bc | 1,852 | cpp | C++ | 04_coding_tasks/lib/004_Median_of_Two_Sorted_Arrays.cpp | JWidder/CodingCPP | 00dbf5b0b201299597dfca5c4566d160f780db4f | [
"MIT"
] | null | null | null | 04_coding_tasks/lib/004_Median_of_Two_Sorted_Arrays.cpp | JWidder/CodingCPP | 00dbf5b0b201299597dfca5c4566d160f780db4f | [
"MIT"
] | 2 | 2021-09-27T04:15:22.000Z | 2021-10-09T04:53:33.000Z | 04_coding_tasks/lib/004_Median_of_Two_Sorted_Arrays.cpp | JWidder/CodingCPP | 00dbf5b0b201299597dfca5c4566d160f780db4f | [
"MIT"
] | 1 | 2021-09-08T14:18:28.000Z | 2021-09-08T14:18:28.000Z | #include <string>
#include "LibSolution.h"
using namespace std;
/*
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Task:
https://leetcode.com/problems/median-of-two-sorted-arrays/
Solution:
- add the total number of elements in the both vectors
- finde median
- if number is even median is the average of the inner elements
- if number if odd: median is the middle element.
*/
namespace leetcode {
double find_median_vector(vector<int>& nums) {
int size = nums.size();
if (size % 2 == 0) {
int wert1 = nums[(size / 2) - 1];
int wert2 = nums[(size / 2)];
return (double)(wert1 + wert2) / 2.0;
}
else {
return (nums[size / 2]);
}
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int size1 = nums1.size();
int size2 = nums2.size();
int size = nums1.size() + nums2.size();
int count = 0;
// Get iterator
std::vector<int>::iterator it1 = nums1.begin();
std::vector<int>::iterator it2 = nums2.begin();
double result = -1.0;
int wert1;
int wert2;
if (size1 == 0){
result = find_median_vector(nums2);
}
else if (size2 == 0) {
result = find_median_vector(nums1);
}
else {
if (size % 2 == 0) {
for (count = 0; count <= size / 2; count++) {
if (it2 != std::end(nums2)) {
if (*it1 < *it2) {
wert1 = *it1;
it1++;
}
else {
wert2 = *it2;
it2++;
}
}
else {
wert1 = wert2;
break;
}
}
result = (double)(wert1 + wert2) / 2.0;
}
else {
for (count = 0; count <= size / 2; count++) {
if (*it1 < *it2) {
result = *it1;
it1++;
}
else {
result = *it2;
it2++;
}
}
}
}
return result;
}
} | 20.808989 | 113 | 0.566955 | JWidder |
abe340e5b56f05307e231dbacb5b9579f72d26d4 | 185 | cpp | C++ | Category.cpp | UgurIpekduzen/Storage-Algorithms-and-Programming-2-Project-1- | 1740a823aee350da7ad7115342fef2f675495306 | [
"MIT"
] | null | null | null | Category.cpp | UgurIpekduzen/Storage-Algorithms-and-Programming-2-Project-1- | 1740a823aee350da7ad7115342fef2f675495306 | [
"MIT"
] | null | null | null | Category.cpp | UgurIpekduzen/Storage-Algorithms-and-Programming-2-Project-1- | 1740a823aee350da7ad7115342fef2f675495306 | [
"MIT"
] | null | null | null | #include "Category.h"
Category::Category(int catID, string catName, string desc)
{
CatID = catID;
CategoryName = catName;
Description = desc;
}
Category::~Category()
{
} | 15.416667 | 59 | 0.664865 | UgurIpekduzen |
abe77c00f55ce8999bcad7f15296e3fc6f8b1ad9 | 789 | cpp | C++ | uhk/acm3853.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm3853.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm3853.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
using namespace std;
struct node
{
double stay;
double right;
double below;
};
node ar[1010][1010];
double sa[1010][1010];
int N, M;
int main()
{
int i, j, k, u, n, m, a, b;
while (scanf("%d %d", &N, &M) != EOF)
{
for (i = 1; i <= N; i++)
{
for (j = 1; j <= M; j++)
{
scanf("%lf %lf %lf", &ar[i][j].stay, &ar[i][j].right, &ar[i][j].below);
}
}
memset(sa, 0, sizeof(sa));
for (i = N; i >= 1; i--)
{
for (j = M; j >= 1; j--)
{
if (i == N && j == M)
continue;
if (1.0 - ar[i][j].stay < 1.0e-9)
continue;
sa[i][j] = (ar[i][j].right*sa[i][j + 1] + ar[i][j].below*sa[i + 1][j] + 2.0) / (1.0 - ar[i][j].stay);
}
}
printf("%.3f\n", sa[1][1]);
}
return 0;
}
| 18.348837 | 105 | 0.467681 | Hyyyyyyyyyy |
abec65cc0db0fb3cf4e8e03fb6ee8b6ffd42af41 | 12,227 | cpp | C++ | code/2D/lib/mex/precompute_mex.cpp | ErisZhang/BCQN | 6c103e0e173bb825e4207b282a0cba2ce5d10e24 | [
"MIT"
] | 15 | 2021-07-16T11:03:01.000Z | 2022-01-15T00:58:26.000Z | code/2D/lib/mex/precompute_mex.cpp | ErisZhang/BCQN | 6c103e0e173bb825e4207b282a0cba2ce5d10e24 | [
"MIT"
] | 1 | 2019-07-10T12:12:18.000Z | 2019-07-10T12:12:18.000Z | code/2D/lib/mex/precompute_mex.cpp | ErisZhang/BCQN | 6c103e0e173bb825e4207b282a0cba2ce5d10e24 | [
"MIT"
] | 4 | 2019-02-21T06:12:40.000Z | 2020-09-27T09:58:32.000Z | #include <mex.h>
#include <math.h>
#include <Eigen/Dense>
#include <iostream>
#include <vector>
using namespace Eigen;
using namespace std;
double get_tri_area(Vector2d p0, Vector2d p1, Vector2d p2)
{
Vector2d u = p1 - p0;
Vector2d v = p2 - p0;
return 0.5 * sqrt(u.dot(u) * v.dot(v) - u.dot(v) * u.dot(v));
}
double get_tri_area(Vector3d p0, Vector3d p1, Vector3d p2)
{
Vector3d u = p1 - p0;
Vector3d v = p2 - p0;
return 0.5 * sqrt(u.dot(u) * v.dot(v) - u.dot(v) * u.dot(v));
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mxArray *X_g_inv_mex, *tri_areas_mex, *F_dot_mex, *row_mex, *col_mex, *val_mex, *x2u_mex, *J_mex, *J_info_mex, *JT_mex, *JT_info_mex, *perimeter_mex;
double *tri_num, *tri_list, *ver_num, *ver_list, *uv_mesh, *dirichlet;
double *X_g_inv, *tri_areas, *F_dot, *row, *col, *val, *x2u, *J, *J_info, *JT, *JT_info, *perimeter;
tri_num = mxGetPr(prhs[0]);
tri_list = mxGetPr(prhs[1]);
ver_num = mxGetPr(prhs[2]);
ver_list = mxGetPr(prhs[3]);
uv_mesh = mxGetPr(prhs[4]);
dirichlet = mxGetPr(prhs[5]);
int tri_n = tri_num[0];
int ver_n = ver_num[0];
int is_uv_mesh = uv_mesh[0];
X_g_inv_mex = plhs[0] = mxCreateDoubleMatrix(4 * tri_n, 1, mxREAL);
tri_areas_mex = plhs[1] = mxCreateDoubleMatrix(tri_n, 1, mxREAL);
F_dot_mex = plhs[2] = mxCreateDoubleMatrix(24 * tri_n, 1, mxREAL);
row_mex = plhs[3] = mxCreateDoubleMatrix(18 * tri_n, 1, mxREAL);
col_mex = plhs[4] = mxCreateDoubleMatrix(18 * tri_n, 1, mxREAL);
val_mex = plhs[5] = mxCreateDoubleMatrix(18 * tri_n, 1, mxREAL);
x2u_mex = plhs[6] = mxCreateDoubleMatrix(2 * ver_n, 1, mxREAL);
X_g_inv = mxGetPr(X_g_inv_mex);
tri_areas = mxGetPr(tri_areas_mex);
F_dot = mxGetPr(F_dot_mex);
row = mxGetPr(row_mex);
col = mxGetPr(col_mex);
val = mxGetPr(val_mex);
x2u = mxGetPr(x2u_mex);
int count = 1;
int fixed_num = 0;
int tri[3];
for(int i = 0; i < 2 * ver_n; i++)
{
if(dirichlet[i] == 0)
{
x2u[i] = count;
count++;
}else
{
fixed_num++;
x2u[i] = 0;
}
}
//mexPrintf("check 1\n");
vector<vector<int>*> ver_tri_map;
for(int i = 0; i < ver_n; i++)
{
vector<int>* tris = new vector<int>();
ver_tri_map.push_back(tris);
}
for(int i = 0; i < tri_n; i++)
{
tri[0] = tri_list[i] - 1;
tri[1] = tri_list[i + tri_n] - 1;
tri[2] = tri_list[i + 2 * tri_n] - 1;
ver_tri_map[tri[0]]->push_back(i);
ver_tri_map[tri[1]]->push_back(i);
ver_tri_map[tri[2]]->push_back(i);
}
int max_valence = 0;
for(int i = 0; i < ver_n; i++)
{
if(max_valence < ver_tri_map[i]->size())
{
max_valence = ver_tri_map[i]->size();
}
}
J_mex = plhs[7] = mxCreateDoubleMatrix((2 * ver_n - fixed_num) * max_valence, 1, mxREAL);
J_info_mex = plhs[8] = mxCreateDoubleMatrix(2, 1, mxREAL);
JT_mex = plhs[9] = mxCreateDoubleMatrix(tri_n * 3 * 2, 1, mxREAL);
JT_info_mex = plhs[10] = mxCreateDoubleMatrix(2, 1, mxREAL);
perimeter_mex = plhs[11] = mxCreateDoubleMatrix(ver_n, 1, mxREAL);
J = mxGetPr(J_mex);
J_info = mxGetPr(J_info_mex);
JT = mxGetPr(JT_mex);
JT_info = mxGetPr(JT_info_mex);
perimeter = mxGetPr(perimeter_mex);
count = 0;
J_info[0] = 2 * ver_n - fixed_num;
J_info[1] = max_valence;
for(int i = 0; i < ver_n; i++)
{
perimeter[i] = 0;
if(dirichlet[2 * i] == 0)
{
for(int j = 0; j < max_valence; j++)
{
if(j < ver_tri_map[i]->size())
{
J[count * max_valence + j] = ver_tri_map[i]->at(j);
}else{
J[count * max_valence + j] = -1;
}
}
count++;
for(int j = 0; j < max_valence; j++)
{
if(j < ver_tri_map[i]->size())
{
J[count * max_valence + j] = ver_tri_map[i]->at(j);
}else{
J[count * max_valence + j] = -1;
}
}
count++;
}
}
JT_info[0] = tri_n;
JT_info[1] = 3 * 2;
for(int i = 0; i < tri_n; i++)
{
tri[0] = tri_list[i] - 1;
tri[1] = tri_list[i + tri_n] - 1;
tri[2] = tri_list[i + 2 * tri_n] - 1;
for(int j = 0; j < 3; j++)
{
if(x2u[2 * tri[j]] > 0)
{
JT[i * 2 * 3 + 2 * j + 0] = x2u[2 * tri[j] + 0] - 1;
JT[i * 2 * 3 + 2 * j + 1] = x2u[2 * tri[j] + 1] - 1;
}else{
JT[i * 2 * 3 + 2 * j + 0] = -1;
JT[i * 2 * 3 + 2 * j + 1] = -1;
}
}
}
for(int i = 0; i < ver_n; i++)
{
ver_tri_map[i]->clear();
delete ver_tri_map[i];
}
ver_tri_map.clear();
///////////////////////////////////////////////////////////////////////
Matrix2d X_g, B;
double C_sub[4][6];
double tri_area;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 6; j++)
{
C_sub[i][j] = 0;
}
}
for(int i = 0; i < tri_n; i++)
{
tri[0] = tri_list[i] - 1;
tri[1] = tri_list[i + tri_n] - 1;
tri[2] = tri_list[i + 2 * tri_n] - 1;
/////////////////////////////////////////////////////////////
if(is_uv_mesh)
{
Vector3d p0(ver_list[3 * tri[0]], ver_list[3 * tri[0] + 1], ver_list[3 * tri[0] + 2]);
Vector3d p1(ver_list[3 * tri[1]], ver_list[3 * tri[1] + 1], ver_list[3 * tri[1] + 2]);
Vector3d p2(ver_list[3 * tri[2]], ver_list[3 * tri[2] + 1], ver_list[3 * tri[2] + 2]);
perimeter[tri[0]] += (p1 - p2).norm();
perimeter[tri[1]] += (p2 - p0).norm();
perimeter[tri[2]] += (p0 - p1).norm();
tri_area = tri_areas[i] = get_tri_area(p0, p1, p2);
Vector3d bx = p1 - p0;
Vector3d cx = p2 - p0;
Vector3d Ux = bx;
Ux.normalize();
Vector3d w = Ux.cross(cx);
Vector3d Wx = w;
Wx.normalize();
Vector3d Vx = Ux.cross(Wx);
Matrix3d R;
R.col(0) = Ux;
R.col(1) = Vx;
R.col(2) = Wx;
Vector3d vb = R.transpose() * bx;
Vector3d vc = R.transpose() * cx;
X_g << vb[0], vc[0], vb[1], vc[1];
if(X_g.determinant() < 0)
{
X_g.row(1) = -1.0 * X_g.row(1);
}
}else{
Vector2d p0(ver_list[2 * tri[0]], ver_list[2 * tri[0] + 1]);
Vector2d p1(ver_list[2 * tri[1]], ver_list[2 * tri[1] + 1]);
Vector2d p2(ver_list[2 * tri[2]], ver_list[2 * tri[2] + 1]);
perimeter[tri[0]] += (p1 - p2).norm();
perimeter[tri[1]] += (p2 - p0).norm();
perimeter[tri[2]] += (p0 - p1).norm();
tri_area = tri_areas[i] = get_tri_area(p0, p1, p2);
Vector2d e0 = p1 - p0;
Vector2d e1 = p2 - p0;
X_g << e0[0], e1[0], e0[1], e1[1];
}
///////////////////////////////////////////////////////////////
B = X_g.inverse();
X_g_inv[i] = B(0, 0);
X_g_inv[tri_n + i] = B(1, 0);
X_g_inv[2 * tri_n + i] = B(0, 1);
X_g_inv[3 * tri_n + i] = B(1, 1);
C_sub[0][0] = -(B(0, 0) + B(1, 0));
C_sub[1][1] = -(B(0, 0) + B(1, 0));
C_sub[0][2] = B(0, 0);
C_sub[1][3] = B(0, 0);
C_sub[0][4] = B(1, 0);
C_sub[1][5] = B(1, 0);
C_sub[2][0] = -(B(0, 1) + B(1, 1));
C_sub[3][1] = -(B(0, 1) + B(1, 1));
C_sub[2][2] = B(0, 1);
C_sub[3][3] = B(0, 1);
C_sub[2][4] = B(1, 1);
C_sub[3][5] = B(1, 1);
for(int j = 0; j < 6; j++)
{
F_dot[0 * tri_n * 6 + j * tri_n + i] = C_sub[0][j];
F_dot[1 * tri_n * 6 + j * tri_n + i] = C_sub[1][j];
F_dot[2 * tri_n * 6 + j * tri_n + i] = C_sub[2][j];
F_dot[3 * tri_n * 6 + j * tri_n + i] = C_sub[3][j];
}
//////////////////////////////////////////////////////////////////////
Matrix2d A0;
A0 << -1.0 * (B(0, 0) + B(1, 0)), 0, 0, -1.0 * (B(0, 0) + B(1, 0));
Matrix2d A1;
A1 << -1.0 * (B(0, 1) + B(1, 1)), 0, 0, -1.0 * (B(0, 1) + B(1, 1));
Matrix2d B0;
B0 << B(0, 0), 0, 0, B(0, 0);
Matrix2d B1;
B1 << B(0, 1), 0, 0, B(0, 1);
Matrix2d C0;
C0 << B(1, 0), 0, 0, B(1, 0);
Matrix2d C1;
C1 << B(1, 1), 0, 0, B(1, 1);
Matrix2d AA = A0 * A0 + A1 * A1;
Matrix2d AB = A0 * B0 + A1 * B1;
Matrix2d AC = A0 * C0 + A1 * C1;
Matrix2d BA = B0 * A0 + B1 * A1;
Matrix2d BB = B0 * B0 + B1 * B1;
Matrix2d BC = B0 * C0 + B1 * C1;
Matrix2d CA = C0 * A0 + C1 * A1;
Matrix2d CB = C0 * B0 + C1 * B1;
Matrix2d CC = C0 * C0 + C1 * C1;
row[18 * i + 0] = 2 * tri[0];
col[18 * i + 0] = 2 * tri[0];
val[18 * i + 0] = AA(0, 0) * tri_area;
row[18 * i + 1] = 2 * tri[0] + 1;
col[18 * i + 1] = 2 * tri[0] + 1;
val[18 * i + 1] = AA(1, 1) * tri_area;
row[18 * i + 2] = 2 * tri[0];
col[18 * i + 2] = 2 * tri[1];
val[18 * i + 2] = AB(0, 0) * tri_area;
row[18 * i + 3] = 2 * tri[0] + 1;
col[18 * i + 3] = 2 * tri[1] + 1;
val[18 * i + 3] = AB(1, 1) * tri_area;
row[18 * i + 4] = 2 * tri[0];
col[18 * i + 4] = 2 * tri[2];
val[18 * i + 4] = AC(0, 0) * tri_area;
row[18 * i + 5] = 2 * tri[0] + 1;
col[18 * i + 5] = 2 * tri[2] + 1;
val[18 * i + 5] = AC(1, 1) * tri_area;
row[18 * i + 6] = 2 * tri[1];
col[18 * i + 6] = 2 * tri[0];
val[18 * i + 6] = BA(0, 0) * tri_area;
row[18 * i + 7] = 2 * tri[1] + 1;
col[18 * i + 7] = 2 * tri[0] + 1;
val[18 * i + 7] = BA(1, 1) * tri_area;
row[18 * i + 8] = 2 * tri[1];
col[18 * i + 8] = 2 * tri[1];
val[18 * i + 8] = BB(0, 0) * tri_area;
row[18 * i + 9] = 2 * tri[1] + 1;
col[18 * i + 9] = 2 * tri[1] + 1;
val[18 * i + 9] = BB(1, 1) * tri_area;
row[18 * i + 10] = 2 * tri[1];
col[18 * i + 10] = 2 * tri[2];
val[18 * i + 10] = BC(0, 0) * tri_area;
row[18 * i + 11] = 2 * tri[1] + 1;
col[18 * i + 11] = 2 * tri[2] + 1;
val[18 * i + 11] = BC(1, 1) * tri_area;
row[18 * i + 12] = 2 * tri[2];
col[18 * i + 12] = 2 * tri[0];
val[18 * i + 12] = CA(0, 0) * tri_area;
row[18 * i + 13] = 2 * tri[2] + 1;
col[18 * i + 13] = 2 * tri[0] + 1;
val[18 * i + 13] = CA(1, 1) * tri_area;
row[18 * i + 14] = 2 * tri[2];
col[18 * i + 14] = 2 * tri[1];
val[18 * i + 14] = CB(0, 0) * tri_area;
row[18 * i + 15] = 2 * tri[2] + 1;
col[18 * i + 15] = 2 * tri[1] + 1;
val[18 * i + 15] = CB(1, 1) * tri_area;
row[18 * i + 16] = 2 * tri[2];
col[18 * i + 16] = 2 * tri[2];
val[18 * i + 16] = CC(0, 0) * tri_area;
row[18 * i + 17] = 2 * tri[2] + 1;
col[18 * i + 17] = 2 * tri[2] + 1;
val[18 * i + 17] = CC(1, 1) * tri_area;
}
return;
} | 29.605327 | 153 | 0.399117 | ErisZhang |
74387bd503d654fadb158d57e5a9322d848274f3 | 4,522 | cpp | C++ | src/input/linux/linux_gpio.cpp | lii-enac/djnn-cpp | f27c5ba3186186ee22c93ae91c16063556e929b6 | [
"BSD-2-Clause"
] | 4 | 2018-09-11T14:27:57.000Z | 2019-12-16T21:06:26.000Z | src/input/linux/linux_gpio.cpp | lii-enac/djnn-cpp | f27c5ba3186186ee22c93ae91c16063556e929b6 | [
"BSD-2-Clause"
] | null | null | null | src/input/linux/linux_gpio.cpp | lii-enac/djnn-cpp | f27c5ba3186186ee22c93ae91c16063556e929b6 | [
"BSD-2-Clause"
] | 2 | 2018-06-11T14:15:30.000Z | 2019-01-09T12:23:35.000Z | /*
* djnn v2
*
* The copyright holders for the contents of this file are:
* Ecole Nationale de l'Aviation Civile, France (2019)
* See file "license.terms" for the rights and conditions
* defined by copyright holders.
*
*
* Contributors:
* Stéphane Chatty <chatty@djnn.net>
* Mathieu Magnaudet <mathieu.magnaudet@enac.fr>
*
*/
#include <stdexcept>
#include "core/utils/error.h"
#include "core/core-dev.h" // graph add/remove edge
#include "core/utils/to_string.h"
#include "core/utils/utils-dev.h"
#include "linux_input.h"
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
namespace djnn {
static int num_gpios = 0;
static map<int,GPIOLine*> gpio_lines;
void
p_init_gpios ()
{
int num = 0;
/* iterate on all controllers to determine the total number of GPIOs */
while (1) {
char filename[64];
int fd;
char buf[10];
const char* p;
int numgpio = 0;
/* attempt to read the information file for the next controller */
snprintf (filename, 64, "/sys/class/gpio/gpiochip%d/ngpio", num);
fd = open (filename, O_RDONLY);
if (fd < 0)
break;
/* read the number of GPIOs in this controller */
read (fd, buf, 10);
for (p = buf; *p != '\n'; ++p)
numgpio = 10*numgpio + *p - '0';
close (fd);
/* update the total number of GPIOs */
num += numgpio;
}
num_gpios = num-1;
if (num_gpios < 0)
fprintf (stderr, "djnn warning: no GPIO\n");
}
CoreProcess*
p_find_gpio (const string& path, direction_e dir)
{
try {
string::size_type sz;
size_t index = std::stoi (path, &sz);
map<int, GPIOLine*>::iterator it = gpio_lines.find (index);
GPIOLine* line = nullptr;
if (it != gpio_lines.end ()) {
line = it->second;
} else {
line = new GPIOLine (nullptr, "line" + djnn::to_string (index), index, dir);
line->activate ();
}
if (path.length() > (sz + 1))
return line->find_child_impl (path.substr ((sz + 1)));
else
return line;
}
catch (std::invalid_argument& arg) {
warning (nullptr, "invalid gpio path specification: " + path);
}
return nullptr;
}
GPIOLine::GPIOLine (ParentProcess* parent, const string& name, int pin, direction_e dir)
: FatProcess (name),
_pin (pin),
_dir (dir),
_iofd (nullptr),
_action (nullptr),
_c_action (nullptr)
{
if (pin < 0 || pin > num_gpios)
error (this, "no gpio " + __to_string (pin));
_value = new BoolProperty (this, "value", true);
/* activate the GPIO interface */
_fd = open ("/sys/class/gpio/export", O_WRONLY);
char buf[64];
const char* direction = _dir == IN ? "in" : "out";
const int dirlen = _dir == IN ? 2 : 3;
if (_fd < 0)
error (this, "unable to open gpio");
write (_fd, buf, snprintf (buf, 64, "%d", _pin));
close (_fd);
/* set it to the desired direction */
snprintf (buf, 64, "/sys/class/gpio/gpio%d/direction", pin);
_fd = open (buf, O_WRONLY);
if (_fd < 0) {
error (this, "cannot set direction of GPIO " + __to_string (pin));
}
write (_fd, direction, dirlen);
close (_fd);
/* open the value file */
snprintf (buf, 64, "/sys/class/gpio/gpio%d/value", pin);
_fd = open (buf, _dir == IN ? O_RDONLY : O_WRONLY);
if (_fd < 0) {
error (this, "cannot open GPIO " + __to_string (pin));
}
if (dir == IN) {
_iofd = new IOFD (nullptr, "gpiofd", _fd);
_iofd->activate ();
_action = new GPIOLineReadAction (this, "read");
_c_action = new Coupling (_iofd->find_child_impl ("readable"), ACTIVATION, _action, ACTIVATION);
} else {
_action = new GPIOLineWriteAction (this, "write");
_c_action = new Coupling (_value, ACTIVATION, _action, ACTIVATION);
}
finalize_construction (parent, name);
}
GPIOLine::~GPIOLine()
{
if (_dir == IN) {
_iofd->deactivate ();
delete _c_action;
delete _action;
delete _iofd;
} else {
delete _c_action;
delete _action;
}
close (_fd);
delete _value;
}
void
GPIOLine::read_value ()
{
char buf[10];
lseek (_fd, 0, SEEK_SET);
if (read (_fd, buf, 10) > 0)
_value->set_value (buf[0] - '0', true);
}
void
GPIOLine::write_value ()
{
char buf[4];
int value = _value->get_value ();
snprintf (buf, 4, "%d", value);
write (_fd, buf, strlen (buf) + 1);
}
}
| 25.693182 | 102 | 0.582043 | lii-enac |
743a96d9c7794f785b2e6b1eb97176ea1b188707 | 4,469 | cpp | C++ | Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheTrack.cpp | greenrainstudios/AlembicUtilities | 3970988065aef6861898a5185495e784a0c43ecb | [
"MIT"
] | null | null | null | Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheTrack.cpp | greenrainstudios/AlembicUtilities | 3970988065aef6861898a5185495e784a0c43ecb | [
"MIT"
] | null | null | null | Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheTrack.cpp | greenrainstudios/AlembicUtilities | 3970988065aef6861898a5185495e784a0c43ecb | [
"MIT"
] | 1 | 2021-01-22T09:11:51.000Z | 2021-01-22T09:11:51.000Z | // Copyright Epic Games, Inc. All Rights Reserved.
#include "GeometryCacheTrack.h"
#include "GeometryCacheHelpers.h"
#include "UObject/AnimPhysObjectVersion.h"
const FGeometryCacheTrackSampleInfo FGeometryCacheTrackSampleInfo::EmptySampleInfo;
const FVisibilitySample FVisibilitySample::VisibleSample(true);
const FVisibilitySample FVisibilitySample::InvisibleSample(false);
UGeometryCacheTrack::UGeometryCacheTrack(const FObjectInitializer& ObjectInitializer /*= FObjectInitializer::Get()*/) : UObject(ObjectInitializer)
{
NumMaterials = 0;
Duration = 0;
}
const bool UGeometryCacheTrack::UpdateMeshData(const float Time, const bool bLooping, int32& InOutMeshSampleIndex, FGeometryCacheMeshData*& OutMeshData)
{
return false;
}
const bool UGeometryCacheTrack::UpdateMatrixData(const float Time, const bool bLooping, int32& InOutMatrixSampleIndex, FMatrix& OutWorldMatrix)
{
// Retrieve sample index from Time
const uint32 MatrixSampleIndex = FindSampleIndexFromTime(MatrixSampleTimes, Time, bLooping);
// Update the Matrix and Index if MatrixSampleIndex is different from the stored InOutMatrixSampleIndex
if (MatrixSampleIndex != InOutMatrixSampleIndex)
{
InOutMatrixSampleIndex = MatrixSampleIndex;
OutWorldMatrix = MatrixSamples[MatrixSampleIndex];
return true;
}
return false;
}
const bool UGeometryCacheTrack::UpdateBoundsData(const float Time, const bool bLooping, const bool bIsPlayingBackward, int32& InOutBoundsSampleIndex, FBox& OutBounds)
{
// Fixme implement bounds in derived classes, should we make this abstract?
check(false);
return false;
}
UGeometryCacheTrack::~UGeometryCacheTrack()
{
MatrixSamples.Empty();
MatrixSampleTimes.Empty();
}
void UGeometryCacheTrack::Serialize(FArchive& Ar)
{
Ar.UsingCustomVersion(FAnimPhysObjectVersion::GUID);
if (Ar.CustomVer(FAnimPhysObjectVersion::GUID) >= FAnimPhysObjectVersion::GeometryCacheAssetDeprecation)
{
Super::Serialize(Ar);
}
Ar << MatrixSamples;
Ar << MatrixSampleTimes;
Ar << NumMaterials;
}
void UGeometryCacheTrack::SetMatrixSamples(const TArray<FMatrix>& Matrices, const TArray<float>& SampleTimes)
{
// Copy Matrix samples and sample-times
MatrixSamples.Append(Matrices);
MatrixSampleTimes.Append(SampleTimes);
}
void UGeometryCacheTrack::AddMatrixSample(const FMatrix& Matrix, const float SampleTime)
{
MatrixSamples.Add(Matrix);
MatrixSampleTimes.Add(SampleTime);
Duration = FMath::Max(Duration, SampleTime);
}
void UGeometryCacheTrack::SetDuration(float NewDuration)
{
Duration = NewDuration;
}
float UGeometryCacheTrack::GetDuration()
{
return Duration;
}
const float UGeometryCacheTrack::GetMaxSampleTime() const
{
// If there are sample-times available return the (maximal) time from the last sample
if ( MatrixSampleTimes.Num() > 0 )
{
return MatrixSampleTimes.Last();
}
// Otherwise no data/times available
return 0.0f;
}
const uint32 UGeometryCacheTrack::FindSampleIndexFromTime(const TArray<float>& SampleTimes, const float Time, const bool bLooping)
{
// No index possible
if (SampleTimes.Num() == 0 || SampleTimes.Num() == 1)
{
return 0;
}
// Modulo the incoming Time if the animation is played on a loop
float SampleTime = Time;
if (bLooping)
{
SampleTime = GeometyCacheHelpers::WrapAnimationTime(Time, Duration);
}
// Binary searching for closest (floored) SampleIndex
uint32 MinIndex = 0;
uint32 MaxIndex = SampleTimes.Num() - 1;
if (SampleTime >= SampleTimes[MaxIndex])
{
return MaxIndex;
}
else if (SampleTime <= SampleTimes[MinIndex])
{
return MinIndex;
}
while (MaxIndex > 0 && MaxIndex >= MinIndex)
{
uint32 Mid = (MinIndex + MaxIndex) / 2;
if (SampleTime > SampleTimes[Mid])
{
MinIndex = Mid + 1;
}
else
{
MaxIndex = Mid - 1;
}
}
return MinIndex;
}
void UGeometryCacheTrack::GetResourceSizeEx(FResourceSizeEx& CumulativeResourceSize)
{
Super::GetResourceSizeEx(CumulativeResourceSize);
// Determine resource size from data that is serialized
CumulativeResourceSize.AddDedicatedSystemMemoryBytes(MatrixSamples.Num() * sizeof(FMatrix));
CumulativeResourceSize.AddDedicatedSystemMemoryBytes(MatrixSampleTimes.Num() * sizeof(float));
}
const FGeometryCacheTrackSampleInfo& UGeometryCacheTrack::GetSampleInfo(float Time, bool bLooping)
{
return FGeometryCacheTrackSampleInfo::EmptySampleInfo;
}
| 28.464968 | 167 | 0.750727 | greenrainstudios |
743c89ecec5979c250c222952bd2bcb9c8b506d9 | 46 | cpp | C++ | src/scanContext.cpp | softdream/Slam-Project-Of-MyOwn | 6d6db8a5761e8530971b203983ea2215620aa5c2 | [
"Apache-2.0"
] | 21 | 2021-07-19T08:15:53.000Z | 2022-03-31T07:07:55.000Z | src/scanContext.cpp | Forrest-Z/Slam-Project-Of-MyOwn | 6d6db8a5761e8530971b203983ea2215620aa5c2 | [
"Apache-2.0"
] | 3 | 2022-03-02T12:55:37.000Z | 2022-03-07T12:12:57.000Z | src/scanContext.cpp | softdream/Slam-Project-Of-MyOwn | 6d6db8a5761e8530971b203983ea2215620aa5c2 | [
"Apache-2.0"
] | 4 | 2021-08-12T15:11:09.000Z | 2022-01-08T14:20:36.000Z | #include "scanContext.h"
namespace slam{
}
| 6.571429 | 24 | 0.695652 | softdream |
743da00a0b4f398d3f50d79a19d301aefc9cc8e0 | 10,636 | cpp | C++ | third_party/skia_m79/third_party/externals/angle2/src/gpu_info_util/SystemInfo_android.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 20 | 2019-04-18T07:37:34.000Z | 2022-02-02T21:43:47.000Z | third_party/skia_m79/third_party/externals/angle2/src/gpu_info_util/SystemInfo_android.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 11 | 2019-10-21T13:39:41.000Z | 2021-11-05T08:11:54.000Z | third_party/skia_m79/third_party/externals/angle2/src/gpu_info_util/SystemInfo_android.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 9 | 2018-10-31T03:07:11.000Z | 2021-08-06T08:53:21.000Z | //
// Copyright 2018 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SystemInfo_android.cpp: implementation of the Android-specific parts of SystemInfo.h
#include <dlfcn.h>
#include <vulkan/vulkan.h>
#include "gpu_info_util/SystemInfo_internal.h"
#include <sys/system_properties.h>
#include <cstring>
#include <fstream>
#include "common/angleutils.h"
#include "common/debug.h"
namespace angle
{
class VulkanLibrary final : NonCopyable
{
public:
VulkanLibrary() {}
~VulkanLibrary()
{
if (mInstance != VK_NULL_HANDLE)
{
PFN_vkDestroyInstance pfnDestroyInstance =
reinterpret_cast<PFN_vkDestroyInstance>(dlsym(mLibVulkan, "vkDestroyInstance"));
if (pfnDestroyInstance)
{
pfnDestroyInstance(mInstance, nullptr);
}
}
if (mLibVulkan)
dlclose(mLibVulkan);
}
VkInstance getVulkanInstance()
{
// Find the system's Vulkan library and open it:
mLibVulkan = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
if (!mLibVulkan)
{
// If Vulkan doesn't exist, bail-out early:
return VK_NULL_HANDLE;
}
// Determine the available Vulkan instance version:
uint32_t instanceVersion = VK_API_VERSION_1_0;
#if defined(VK_VERSION_1_1)
PFN_vkEnumerateInstanceVersion pfnEnumerateInstanceVersion =
reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
dlsym(mLibVulkan, "vkEnumerateInstanceVersion"));
if (!pfnEnumerateInstanceVersion ||
pfnEnumerateInstanceVersion(&instanceVersion) != VK_SUCCESS)
{
instanceVersion = VK_API_VERSION_1_0;
}
#endif // VK_VERSION_1_1
// Create a Vulkan instance:
VkApplicationInfo appInfo;
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pNext = nullptr;
appInfo.pApplicationName = "";
appInfo.applicationVersion = 1;
appInfo.pEngineName = "";
appInfo.engineVersion = 1;
appInfo.apiVersion = instanceVersion;
VkInstanceCreateInfo createInstanceInfo;
createInstanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInstanceInfo.pNext = nullptr;
createInstanceInfo.flags = 0;
createInstanceInfo.pApplicationInfo = &appInfo;
createInstanceInfo.enabledLayerCount = 0;
createInstanceInfo.ppEnabledLayerNames = nullptr;
createInstanceInfo.enabledExtensionCount = 0;
createInstanceInfo.ppEnabledExtensionNames = nullptr;
PFN_vkCreateInstance pfnCreateInstance =
reinterpret_cast<PFN_vkCreateInstance>(dlsym(mLibVulkan, "vkCreateInstance"));
if (!pfnCreateInstance ||
pfnCreateInstance(&createInstanceInfo, nullptr, &mInstance) != VK_SUCCESS)
{
return VK_NULL_HANDLE;
}
return mInstance;
}
void *gpa(std::string fn) { return dlsym(mLibVulkan, fn.c_str()); }
#define GPA(ob, type, fn) reinterpret_cast<type>(ob.gpa(fn))
private:
void *mLibVulkan = nullptr;
VkInstance mInstance = VK_NULL_HANDLE;
};
ANGLE_FORMAT_PRINTF(1, 2)
std::string FormatString(const char *fmt, ...)
{
va_list vararg;
va_start(vararg, fmt);
std::vector<char> buffer(512);
size_t len = FormatStringIntoVector(fmt, vararg, buffer);
va_end(vararg);
return std::string(&buffer[0], len);
}
bool GetAndroidSystemProperty(const std::string &propertyName, std::string *value)
{
// PROP_VALUE_MAX from <sys/system_properties.h>
std::vector<char> propertyBuf(PROP_VALUE_MAX);
int len = __system_property_get(propertyName.c_str(), propertyBuf.data());
if (len <= 0)
{
return false;
}
*value = std::string(propertyBuf.data());
return true;
}
bool GetSystemInfo(SystemInfo *info)
{
bool isFullyPopulated = true;
isFullyPopulated =
GetAndroidSystemProperty("ro.product.manufacturer", &info->machineManufacturer) &&
isFullyPopulated;
isFullyPopulated =
GetAndroidSystemProperty("ro.product.model", &info->machineModelName) && isFullyPopulated;
// This implementation builds on top of the Vulkan API, but cannot assume the existence of the
// Vulkan library. ANGLE can be installed on versions of Android as old as Ice Cream Sandwich.
// Therefore, we need to use dlopen()/dlsym() in order to see if Vulkan is installed on the
// system, and if so, to use it:
VulkanLibrary vkLibrary;
VkInstance instance = vkLibrary.getVulkanInstance();
if (instance == VK_NULL_HANDLE)
{
// If Vulkan doesn't exist, bail-out early:
return false;
}
// Enumerate the Vulkan physical devices, which are ANGLE gpus:
PFN_vkEnumeratePhysicalDevices pfnEnumeratePhysicalDevices =
GPA(vkLibrary, PFN_vkEnumeratePhysicalDevices, "vkEnumeratePhysicalDevices");
PFN_vkGetPhysicalDeviceProperties pfnGetPhysicalDeviceProperties =
GPA(vkLibrary, PFN_vkGetPhysicalDeviceProperties, "vkGetPhysicalDeviceProperties");
uint32_t physicalDeviceCount = 0;
if (!pfnEnumeratePhysicalDevices ||
pfnEnumeratePhysicalDevices(instance, &physicalDeviceCount, nullptr) != VK_SUCCESS)
{
return false;
}
std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
if (pfnEnumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices.data()) !=
VK_SUCCESS)
{
return false;
}
// If we get to here, we will likely provide a valid answer (unless an unknown vendorID):
info->gpus.resize(physicalDeviceCount);
for (uint32_t i = 0; i < physicalDeviceCount; i++)
{
VkPhysicalDeviceProperties properties;
pfnGetPhysicalDeviceProperties(physicalDevices[i], &properties);
// Fill in data for a given physical device (a.k.a. gpu):
GPUDeviceInfo &gpu = info->gpus[i];
gpu.vendorId = properties.vendorID;
gpu.deviceId = properties.deviceID;
// Need to parse/re-format properties.driverVersion.
//
// TODO(ianelliott): Determine the formatting used for each vendor
// (http://anglebug.com/2677)
switch (properties.vendorID)
{
case kVendorID_AMD:
gpu.driverVendor = "Advanced Micro Devices, Inc";
gpu.driverVersion = FormatString("0x%x", properties.driverVersion);
gpu.detailedDriverVersion.major = properties.driverVersion;
break;
case kVendorID_ARM:
gpu.driverVendor = "Arm Holdings";
gpu.driverVersion = FormatString("0x%x", properties.driverVersion);
gpu.detailedDriverVersion.major = properties.driverVersion;
break;
case kVendorID_ImgTec:
gpu.driverVendor = "Imagination Technologies Limited";
gpu.driverVersion = FormatString("0x%x", properties.driverVersion);
gpu.detailedDriverVersion.major = properties.driverVersion;
break;
case kVendorID_Intel:
gpu.driverVendor = "Intel Corporation";
gpu.driverVersion = FormatString("0x%x", properties.driverVersion);
gpu.detailedDriverVersion.major = properties.driverVersion;
break;
case kVendorID_NVIDIA:
gpu.driverVendor = "NVIDIA Corporation";
gpu.driverVersion = FormatString("%d.%d.%d.%d", properties.driverVersion >> 22,
(properties.driverVersion >> 14) & 0XFF,
(properties.driverVersion >> 6) & 0XFF,
properties.driverVersion & 0x3F);
gpu.detailedDriverVersion.major = properties.driverVersion >> 22;
gpu.detailedDriverVersion.minor = (properties.driverVersion >> 14) & 0xFF;
gpu.detailedDriverVersion.subMinor = (properties.driverVersion >> 6) & 0xFF;
gpu.detailedDriverVersion.patch = properties.driverVersion & 0x3F;
break;
case kVendorID_Qualcomm:
gpu.driverVendor = "Qualcomm Technologies, Inc";
if (properties.driverVersion & 0x80000000)
{
gpu.driverVersion = FormatString("%d.%d.%d", properties.driverVersion >> 22,
(properties.driverVersion >> 12) & 0X3FF,
properties.driverVersion & 0xFFF);
gpu.detailedDriverVersion.major = properties.driverVersion >> 22;
gpu.detailedDriverVersion.minor = (properties.driverVersion >> 12) & 0x3FF;
gpu.detailedDriverVersion.subMinor = properties.driverVersion & 0xFFF;
}
else
{
gpu.driverVersion = FormatString("0x%x", properties.driverVersion);
gpu.detailedDriverVersion.major = properties.driverVersion;
}
break;
case kVendorID_Vivante:
gpu.driverVendor = "Vivante";
gpu.driverVersion = FormatString("0x%x", properties.driverVersion);
gpu.detailedDriverVersion.major = properties.driverVersion;
break;
case kVendorID_VeriSilicon:
gpu.driverVendor = "VeriSilicon";
gpu.driverVersion = FormatString("0x%x", properties.driverVersion);
gpu.detailedDriverVersion.major = properties.driverVersion;
break;
case kVendorID_Kazan:
gpu.driverVendor = "Kazan Software";
gpu.driverVersion = FormatString("0x%x", properties.driverVersion);
gpu.detailedDriverVersion.major = properties.driverVersion;
break;
default:
return false;
}
gpu.driverDate = "";
}
return isFullyPopulated;
}
} // namespace angle
| 41.385214 | 99 | 0.607465 | kniefliu |
743ef6c22393b0253455521701b967fcfe56e1b7 | 47,041 | cpp | C++ | ackermann_drive_controller/src/ackermann_drive_controller.cpp | Jenifen/curio | fa08e5abba54622170ca3f4c1f5933e97f51a022 | [
"BSD-3-Clause"
] | 34 | 2020-02-05T07:26:27.000Z | 2022-03-12T09:38:56.000Z | ackermann_drive_controller/src/ackermann_drive_controller.cpp | Jenifen/curio | fa08e5abba54622170ca3f4c1f5933e97f51a022 | [
"BSD-3-Clause"
] | 10 | 2020-01-28T13:14:52.000Z | 2022-03-12T11:07:08.000Z | ackermann_drive_controller/src/ackermann_drive_controller.cpp | Jenifen/curio | fa08e5abba54622170ca3f4c1f5933e97f51a022 | [
"BSD-3-Clause"
] | 16 | 2020-04-10T05:03:51.000Z | 2022-02-21T05:04:49.000Z | //
// Software License Agreement (BSD-3-Clause)
//
// Copyright (c) 2019 Rhys Mainwaring
// All rights reserved
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
/*
* Author: Rhys Mainwaring
*/
// Adapted from the original source code for diff_drive_controller
// and ackermann_steering_controller from the ros_controllers
// package: https://github.com/ros-controls/ros_controllers
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, PAL Robotics, S.L.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the PAL Robotics nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/*
* Author: Bence Magyar, Enrique Fernández
*/
#include "ackermann_drive_controller/ackermann_drive_controller.h"
#include "ackermann_drive_controller/ackermann_drive_enums.h"
#include <tf/transform_datatypes.h>
#include <urdf/urdfdom_compatibility.h>
#include <urdf_parser/urdf_parser.h>
#include <cmath>
#include <limits>
/*
static double euclideanOfVectors(const urdf::Vector3& vec1, const urdf::Vector3& vec2)
{
return std::sqrt(std::pow(vec1.x-vec2.x,2) +
std::pow(vec1.y-vec2.y,2) +
std::pow(vec1.z-vec2.z,2));
}
*/
/*
* \brief Check that a link exists and has a geometry collision.
* \param link The link
* \return true if the link has a collision element with geometry
*/
/*
static bool hasCollisionGeometry(const urdf::LinkConstSharedPtr& link)
{
if (!link)
{
ROS_ERROR("Link == NULL.");
return false;
}
if (!link->collision)
{
ROS_ERROR_STREAM("Link " << link->name << " does not have collision description. Add collision description for link to urdf.");
return false;
}
if (!link->collision->geometry)
{
ROS_ERROR_STREAM("Link " << link->name << " does not have collision geometry description. Add collision geometry description for link to urdf.");
return false;
}
return true;
}
*/
/*
* \brief Check if the link is modeled as a cylinder
* \param link Link
* \return true if the link is modeled as a Cylinder; false otherwise
*/
/*
static bool isCylinder(const urdf::LinkConstSharedPtr& link)
{
if (!hasCollisionGeometry(link))
{
return false;
}
if (link->collision->geometry->type != urdf::Geometry::CYLINDER)
{
ROS_DEBUG_STREAM("Link " << link->name << " does not have cylinder geometry");
return false;
}
return true;
}
*/
/*
* \brief Check if the link is modeled as a sphere
* \param link Link
* \return true if the link is modeled as a Sphere; false otherwise
*/
/*
static bool isSphere(const urdf::LinkConstSharedPtr& link)
{
if (!hasCollisionGeometry(link))
{
return false;
}
if (link->collision->geometry->type != urdf::Geometry::SPHERE)
{
ROS_DEBUG_STREAM("Link " << link->name << " does not have sphere geometry");
return false;
}
return true;
}
*/
/*
* \brief Get the wheel radius
* \param [in] wheel_link Wheel link
* \param [out] wheel_radius Wheel radius [m]
* \return true if the wheel radius was found; false otherwise
*/
/*
static bool getWheelRadius(const urdf::LinkConstSharedPtr& wheel_link, double& wheel_radius)
{
if (isCylinder(wheel_link))
{
wheel_radius = (static_cast<urdf::Cylinder*>(wheel_link->collision->geometry.get()))->radius;
return true;
}
else if (isSphere(wheel_link))
{
wheel_radius = (static_cast<urdf::Sphere*>(wheel_link->collision->geometry.get()))->radius;
return true;
}
ROS_ERROR_STREAM("Wheel link " << wheel_link->name << " is NOT modeled as a cylinder or sphere!");
return false;
}
*/
/// \brief Calculate the turning radius and rate of turn.
///
/// Conventions are specifiied according to ROS REP 103:
/// Standard Units of Measure and Coordinate Conventions
/// https://www.ros.org/reps/rep-0103.html.
///
/// x forward
/// y left
/// z up
///
/// Example:
/// v_b >= 0, omega_b > 0 => r_p > 0 the turn is positive (anti-clockwise),
/// v_b >= 0, omega_b < 0 => r_p < 0 the turn is negative (clockwise),
/// v_b >= 0, omega_b = 0 => r_p = inf there is no turn.
///
/// \param[in] v_b linear velocity of the base [m/s].
/// \param[in] omega_b angular velocity of the base [rad/s].
/// \param[in] d distance between the fixed wheels [m].
/// \param[out] r_p turning radius [m]
/// \param[out] omega_p turning rate [rad/s]
void turningRadiusAndRate(double v_b, double omega_b, double d, double &r_p, double &omega_p)
{
double vl = v_b - d * omega_b / 2.0;
double vr = v_b + d * omega_b / 2.0;
if (vl == vr)
{
r_p = std::numeric_limits<double>::infinity();
omega_p = 0.0;
}
else
{
r_p = d * (vr + vl) / (vr - vl) / 2.0;
omega_p = (vr - vl) / d;
}
}
namespace ackermann_drive_controller
{
AckermannDriveController::AckermannDriveController():
open_loop_(false),
command_struct_(),
wheel_radius_(0.0),
mid_wheel_lat_separation_(0.0),
front_wheel_lat_separation_(0.0),
front_wheel_lon_separation_(0.0),
back_wheel_lat_separation_(0.0),
back_wheel_lon_separation_(0.0),
// wheel_separation_multiplier_(1.0),
// left_wheel_radius_multiplier_(1.0),
// right_wheel_radius_multiplier_(1.0),
cmd_vel_timeout_(0.5),
allow_multiple_cmd_vel_publishers_(true),
base_frame_id_("base_link"),
odom_frame_id_("odom"),
enable_odom_tf_(true),
wheel_joints_size_(0),
steer_joints_size_(0),
publish_cmd_(false)
// publish_wheel_joint_controller_state_(false)
{
}
// @TODO: CHANGE
bool AckermannDriveController::init(
hardware_interface::RobotHW* robot_hw,
// hardware_interface::VelocityJointInterface* hw,
ros::NodeHandle& root_nh,
ros::NodeHandle &controller_nh)
{
typedef hardware_interface::VelocityJointInterface VelIface;
typedef hardware_interface::PositionJointInterface PosIface;
// Get the velocity and position and hardware_interfaces
VelIface *vel_joint_if = robot_hw->get<VelIface>(); // vel for wheels
PosIface *pos_joint_if = robot_hw->get<PosIface>(); // pos for steers
const std::string complete_ns = controller_nh.getNamespace();
std::size_t id = complete_ns.find_last_of("/");
name_ = complete_ns.substr(id + 1);
// Get joint names from the parameter server
wheel_joints_size_ = 6;
steer_joints_size_ = 4;
std::vector<std::string> wheel_names(wheel_joints_size_), steer_names(steer_joints_size_);
controller_nh.param("front_left_wheel", wheel_names[WHEEL_INDEX_FRONT_LEFT], std::string("front_left_wheel_joint"));
controller_nh.param("front_right_wheel", wheel_names[WHEEL_INDEX_FRONT_RIGHT], std::string("front_right_wheel_joint"));
controller_nh.param("mid_left_wheel", wheel_names[WHEEL_INDEX_MID_LEFT], std::string("mid_left_wheel_joint"));
controller_nh.param("mid_right_wheel", wheel_names[WHEEL_INDEX_MID_RIGHT], std::string("mid_right_wheel_joint"));
controller_nh.param("back_left_wheel", wheel_names[WHEEL_INDEX_BACK_LEFT], std::string("back_left_wheel_joint"));
controller_nh.param("back_right_wheel", wheel_names[WHEEL_INDEX_BACK_RIGHT], std::string("back_right_wheel_joint"));
controller_nh.param("front_left_steer", steer_names[STEER_INDEX_FRONT_LEFT], std::string("front_left_steer_joint"));
controller_nh.param("front_right_steer", steer_names[STEER_INDEX_FRONT_RIGHT], std::string("front_right_steer_joint"));
controller_nh.param("back_left_steer", steer_names[STEER_INDEX_BACK_LEFT], std::string("back_left_steer_joint"));
controller_nh.param("back_right_steer", steer_names[STEER_INDEX_BACK_RIGHT], std::string("back_right_steer_joint"));
// Resize joint vectors
wheel_joints_.resize(wheel_joints_size_);
steer_joints_.resize(steer_joints_size_);
// Odometry related:
double publish_rate;
controller_nh.param("publish_rate", publish_rate, 50.0);
ROS_INFO_STREAM_NAMED(name_, "Controller state will be published at "
<< publish_rate << "Hz.");
publish_period_ = ros::Duration(1.0 / publish_rate);
controller_nh.param("open_loop", open_loop_, open_loop_);
// controller_nh.param("wheel_separation_multiplier", wheel_separation_multiplier_, wheel_separation_multiplier_);
// ROS_INFO_STREAM_NAMED(name_, "Wheel separation will be multiplied by "
// << wheel_separation_multiplier_ << ".");
// if (controller_nh.hasParam("wheel_radius_multiplier"))
// {
// double wheel_radius_multiplier;
// controller_nh.getParam("wheel_radius_multiplier", wheel_radius_multiplier);
// left_wheel_radius_multiplier_ = wheel_radius_multiplier;
// right_wheel_radius_multiplier_ = wheel_radius_multiplier;
// }
// else
// {
// controller_nh.param("left_wheel_radius_multiplier", left_wheel_radius_multiplier_, left_wheel_radius_multiplier_);
// controller_nh.param("right_wheel_radius_multiplier", right_wheel_radius_multiplier_, right_wheel_radius_multiplier_);
// }
// ROS_INFO_STREAM_NAMED(name_, "Left wheel radius will be multiplied by "
// << left_wheel_radius_multiplier_ << ".");
// ROS_INFO_STREAM_NAMED(name_, "Right wheel radius will be multiplied by "
// << right_wheel_radius_multiplier_ << ".");
int velocity_rolling_window_size = 10;
controller_nh.param("velocity_rolling_window_size", velocity_rolling_window_size, velocity_rolling_window_size);
ROS_INFO_STREAM_NAMED(name_, "Velocity rolling window size of "
<< velocity_rolling_window_size << ".");
odometry_.setVelocityRollingWindowSize(velocity_rolling_window_size);
// Twist command related:
controller_nh.param("cmd_vel_timeout", cmd_vel_timeout_, cmd_vel_timeout_);
ROS_INFO_STREAM_NAMED(name_, "Velocity commands will be considered old if they are older than "
<< cmd_vel_timeout_ << "s.");
controller_nh.param("allow_multiple_cmd_vel_publishers", allow_multiple_cmd_vel_publishers_, allow_multiple_cmd_vel_publishers_);
ROS_INFO_STREAM_NAMED(name_, "Allow mutiple cmd_vel publishers is "
<< (allow_multiple_cmd_vel_publishers_?"enabled":"disabled"));
controller_nh.param("base_frame_id", base_frame_id_, base_frame_id_);
ROS_INFO_STREAM_NAMED(name_, "Base frame_id set to " << base_frame_id_);
controller_nh.param("odom_frame_id", odom_frame_id_, odom_frame_id_);
ROS_INFO_STREAM_NAMED(name_, "Odometry frame_id set to " << odom_frame_id_);
controller_nh.param("enable_odom_tf", enable_odom_tf_, enable_odom_tf_);
ROS_INFO_STREAM_NAMED(name_, "Publishing to tf is " << (enable_odom_tf_?"enabled":"disabled"));
// Velocity and acceleration limits:
controller_nh.param("linear/x/has_velocity_limits" , limiter_lin_.has_velocity_limits , limiter_lin_.has_velocity_limits );
controller_nh.param("linear/x/has_acceleration_limits", limiter_lin_.has_acceleration_limits, limiter_lin_.has_acceleration_limits);
controller_nh.param("linear/x/has_jerk_limits" , limiter_lin_.has_jerk_limits , limiter_lin_.has_jerk_limits );
controller_nh.param("linear/x/max_velocity" , limiter_lin_.max_velocity , limiter_lin_.max_velocity );
controller_nh.param("linear/x/min_velocity" , limiter_lin_.min_velocity , -limiter_lin_.max_velocity );
controller_nh.param("linear/x/max_acceleration" , limiter_lin_.max_acceleration , limiter_lin_.max_acceleration );
controller_nh.param("linear/x/min_acceleration" , limiter_lin_.min_acceleration , -limiter_lin_.max_acceleration );
controller_nh.param("linear/x/max_jerk" , limiter_lin_.max_jerk , limiter_lin_.max_jerk );
controller_nh.param("linear/x/min_jerk" , limiter_lin_.min_jerk , -limiter_lin_.max_jerk );
controller_nh.param("angular/z/has_velocity_limits" , limiter_ang_.has_velocity_limits , limiter_ang_.has_velocity_limits );
controller_nh.param("angular/z/has_acceleration_limits", limiter_ang_.has_acceleration_limits, limiter_ang_.has_acceleration_limits);
controller_nh.param("angular/z/has_jerk_limits" , limiter_ang_.has_jerk_limits , limiter_ang_.has_jerk_limits );
controller_nh.param("angular/z/max_velocity" , limiter_ang_.max_velocity , limiter_ang_.max_velocity );
controller_nh.param("angular/z/min_velocity" , limiter_ang_.min_velocity , -limiter_ang_.max_velocity );
controller_nh.param("angular/z/max_acceleration" , limiter_ang_.max_acceleration , limiter_ang_.max_acceleration );
controller_nh.param("angular/z/min_acceleration" , limiter_ang_.min_acceleration , -limiter_ang_.max_acceleration );
controller_nh.param("angular/z/max_jerk" , limiter_ang_.max_jerk , limiter_ang_.max_jerk );
controller_nh.param("angular/z/min_jerk" , limiter_ang_.min_jerk , -limiter_ang_.max_jerk );
// Publish limited velocity:
controller_nh.param("publish_cmd", publish_cmd_, publish_cmd_);
// Publish wheel data:
// controller_nh.param("publish_wheel_joint_controller_state", publish_wheel_joint_controller_state_, publish_wheel_joint_controller_state_);
// If either parameter is not available, we need to look up the value in the URDF
// bool lookup_wheel_separation = !controller_nh.getParam("wheel_separation", wheel_separation_);
// bool lookup_wheel_radius = !controller_nh.getParam("wheel_radius", wheel_radius_);
controller_nh.param("wheel_radius", wheel_radius_, wheel_radius_);
controller_nh.param("mid_wheel_lat_separation", mid_wheel_lat_separation_, mid_wheel_lat_separation_);
controller_nh.param("front_wheel_lat_separation", front_wheel_lat_separation_, front_wheel_lat_separation_);
controller_nh.param("front_wheel_lon_separation", front_wheel_lon_separation_, front_wheel_lon_separation_);
controller_nh.param("back_wheel_lat_separation", back_wheel_lat_separation_, back_wheel_lat_separation_);
controller_nh.param("back_wheel_lon_separation", back_wheel_lon_separation_, back_wheel_lon_separation_);
// Set up positions of wheels and steering joints
wheel_positions_.resize(wheel_joints_size_);
steer_positions_.resize(steer_joints_size_);
wheel_positions_[WHEEL_INDEX_FRONT_LEFT] = Pos(front_wheel_lon_separation_, front_wheel_lat_separation_/2.0);
wheel_positions_[WHEEL_INDEX_FRONT_RIGHT] = Pos(front_wheel_lon_separation_, -front_wheel_lat_separation_/2.0);
wheel_positions_[WHEEL_INDEX_MID_LEFT] = Pos(0.0, mid_wheel_lat_separation_/2.0);
wheel_positions_[WHEEL_INDEX_MID_RIGHT] = Pos(0.0, -mid_wheel_lat_separation_/2.0);
wheel_positions_[WHEEL_INDEX_BACK_LEFT] = Pos(-back_wheel_lon_separation_, back_wheel_lat_separation_/2.0);
wheel_positions_[WHEEL_INDEX_BACK_RIGHT] = Pos(-back_wheel_lon_separation_, -back_wheel_lat_separation_/2.0);
steer_positions_[STEER_INDEX_FRONT_LEFT] = Pos(front_wheel_lon_separation_, front_wheel_lat_separation_/2.0);
steer_positions_[STEER_INDEX_FRONT_RIGHT] = Pos(front_wheel_lon_separation_, -front_wheel_lat_separation_/2.0);
steer_positions_[STEER_INDEX_BACK_LEFT] = Pos(-back_wheel_lon_separation_, back_wheel_lat_separation_/2.0);
steer_positions_[STEER_INDEX_BACK_RIGHT] = Pos(-back_wheel_lon_separation_, -back_wheel_lat_separation_/2.0);
// Velocity and angle calculation workspace.
wheel_vel_.resize(wheel_joints_size_);
steer_ang_.resize(steer_joints_size_);
// @TODO: enable setting params from URDF
/*
if (!setOdomParamsFromUrdf(
root_nh,
left_wheel_names[0],
right_wheel_names[0],
lookup_wheel_separation,
lookup_wheel_radius))
{
return false;
}
*/
// @TODO: enable odometry
// Regardless of how we got the separation and radius, use them
// to set the odometry parameters
/*
const double ws = wheel_separation_multiplier_ * wheel_separation_;
const double lwr = left_wheel_radius_multiplier_ * wheel_radius_;
const double rwr = right_wheel_radius_multiplier_ * wheel_radius_;
odometry_.setWheelParams(ws, lwr, rwr);
ROS_INFO_STREAM_NAMED(name_,
"Odometry params : wheel separation " << ws
<< ", left wheel radius " << lwr
<< ", right wheel radius " << rwr);
*/
// Odometry workspace
wheel_joints_pos_.resize(wheel_joints_size_);
steer_joints_pos_.resize(steer_joints_size_);
// Set odometry parameters
odometry_.setWheelParams(
wheel_radius_,
mid_wheel_lat_separation_,
front_wheel_lat_separation_,
front_wheel_lon_separation_,
back_wheel_lat_separation_,
back_wheel_lon_separation_);
setOdomPubFields(root_nh, controller_nh);
if (publish_cmd_)
{
cmd_vel_pub_.reset(new realtime_tools::RealtimePublisher<geometry_msgs::TwistStamped>(controller_nh, "cmd_vel_out", 100));
}
// @TODO: enable publishing wheel and steer joint info.
// Wheel joint controller state:
/*
if (publish_wheel_joint_controller_state_)
{
controller_state_pub_.reset(new realtime_tools::RealtimePublisher<control_msgs::JointTrajectoryControllerState>(controller_nh, "wheel_joint_controller_state", 100));
const size_t num_wheels = wheel_joints_size_ * 2;
controller_state_pub_->msg_.joint_names.resize(num_wheels);
controller_state_pub_->msg_.desired.positions.resize(num_wheels);
controller_state_pub_->msg_.desired.velocities.resize(num_wheels);
controller_state_pub_->msg_.desired.accelerations.resize(num_wheels);
controller_state_pub_->msg_.desired.effort.resize(num_wheels);
controller_state_pub_->msg_.actual.positions.resize(num_wheels);
controller_state_pub_->msg_.actual.velocities.resize(num_wheels);
controller_state_pub_->msg_.actual.accelerations.resize(num_wheels);
controller_state_pub_->msg_.actual.effort.resize(num_wheels);
controller_state_pub_->msg_.error.positions.resize(num_wheels);
controller_state_pub_->msg_.error.velocities.resize(num_wheels);
controller_state_pub_->msg_.error.accelerations.resize(num_wheels);
controller_state_pub_->msg_.error.effort.resize(num_wheels);
for (size_t i = 0; i < wheel_joints_size_; ++i)
{
controller_state_pub_->msg_.joint_names[i] = left_wheel_names[i];
controller_state_pub_->msg_.joint_names[i + wheel_joints_size_] = right_wheel_names[i];
}
vel_left_previous_.resize(wheel_joints_size_, 0.0);
vel_right_previous_.resize(wheel_joints_size_, 0.0);
}
*/
// Get the joint object to use in the realtime loop
for (size_t i = 0; i < wheel_joints_size_; ++i)
{
ROS_INFO_STREAM_NAMED(name_, "Adding wheel with joint name: " << wheel_names[i]);
wheel_joints_[i] = vel_joint_if->getHandle(wheel_names[i]); // throws on failure
}
for (size_t i = 0; i < steer_joints_size_; ++i)
{
ROS_INFO_STREAM_NAMED(name_, "Adding steer with joint name: " << steer_names[i]);
steer_joints_[i] = pos_joint_if->getHandle(steer_names[i]); // throws on failure
}
sub_command_ = controller_nh.subscribe("cmd_vel", 1, &AckermannDriveController::cmdVelCallback, this);
// @TODO: enable dynamic reconfig
/*
// Initialize dynamic parameters
DynamicParams dynamic_params;
dynamic_params.left_wheel_radius_multiplier = left_wheel_radius_multiplier_;
dynamic_params.right_wheel_radius_multiplier = right_wheel_radius_multiplier_;
dynamic_params.wheel_separation_multiplier = wheel_separation_multiplier_;
dynamic_params.publish_rate = publish_rate;
dynamic_params.enable_odom_tf = enable_odom_tf_;
dynamic_params_.writeFromNonRT(dynamic_params);
// Initialize dynamic_reconfigure server
AckermannDriveControllerConfig config;
config.left_wheel_radius_multiplier = left_wheel_radius_multiplier_;
config.right_wheel_radius_multiplier = right_wheel_radius_multiplier_;
config.wheel_separation_multiplier = wheel_separation_multiplier_;
config.publish_rate = publish_rate;
config.enable_odom_tf = enable_odom_tf_;
dyn_reconf_server_ = std::make_shared<ReconfigureServer>(controller_nh);
dyn_reconf_server_->updateConfig(config);
dyn_reconf_server_->setCallback(boost::bind(&AckermannDriveController::reconfCallback, this, _1, _2));
*/
return true;
}
// @TODO: CHANGE
void AckermannDriveController::update(const ros::Time& time, const ros::Duration& period)
{
// @TODO: enable dynamic reconfig
// update parameter from dynamic reconf
// updateDynamicParams();
// @TODO: enable odometry
// Apply (possibly new) multipliers:
/*
const double ws = wheel_separation_multiplier_ * wheel_separation_;
const double lwr = left_wheel_radius_multiplier_ * wheel_radius_;
const double rwr = right_wheel_radius_multiplier_ * wheel_radius_;
odometry_.setWheelParams(ws, lwr, rwr);
*/
// COMPUTE AND PUBLISH ODOMETRY
if (open_loop_)
{
odometry_.updateOpenLoop(last0_cmd_.lin, last0_cmd_.ang, time);
}
else
{
for (size_t i=0; i<wheel_joints_size_; ++i)
{
wheel_joints_pos_[i] = wheel_joints_[i].getPosition();
}
for (size_t i=0; i<steer_joints_size_; ++i)
{
steer_joints_pos_[i] = steer_joints_[i].getPosition();
}
// Estimate linear and angular velocity using joint information
odometry_.update(wheel_joints_pos_, steer_joints_pos_, time);
}
// Publish odometry message
if (last_state_publish_time_ + publish_period_ < time)
{
last_state_publish_time_ += publish_period_;
// Compute and store orientation info
const geometry_msgs::Quaternion orientation(
tf::createQuaternionMsgFromYaw(odometry_.getHeading()));
// Populate odom message and publish
if (odom_pub_->trylock())
{
odom_pub_->msg_.header.stamp = time;
odom_pub_->msg_.pose.pose.position.x = odometry_.getX();
odom_pub_->msg_.pose.pose.position.y = odometry_.getY();
odom_pub_->msg_.pose.pose.orientation = orientation;
odom_pub_->msg_.twist.twist.linear.x = odometry_.getLinear();
odom_pub_->msg_.twist.twist.angular.z = odometry_.getAngular();
odom_pub_->unlockAndPublish();
}
// Publish tf /odom frame
if (enable_odom_tf_ && tf_odom_pub_->trylock())
{
geometry_msgs::TransformStamped& odom_frame = tf_odom_pub_->msg_.transforms[0];
odom_frame.header.stamp = time;
odom_frame.transform.translation.x = odometry_.getX();
odom_frame.transform.translation.y = odometry_.getY();
odom_frame.transform.rotation = orientation;
tf_odom_pub_->unlockAndPublish();
}
}
// MOVE ROBOT
// Retreive current velocity command and time step:
Commands curr_cmd = *(command_.readFromRT());
const double dt = (time - curr_cmd.stamp).toSec();
// Brake if cmd_vel has timeout:
if (dt > cmd_vel_timeout_)
{
curr_cmd.lin = 0.0;
curr_cmd.ang = 0.0;
}
// Limit velocities and accelerations:
const double cmd_dt(period.toSec());
limiter_lin_.limit(curr_cmd.lin, last0_cmd_.lin, last1_cmd_.lin, cmd_dt);
limiter_ang_.limit(curr_cmd.ang, last0_cmd_.ang, last1_cmd_.ang, cmd_dt);
last1_cmd_ = last0_cmd_;
last0_cmd_ = curr_cmd;
// Publish limited velocity:
if (publish_cmd_ && cmd_vel_pub_ && cmd_vel_pub_->trylock())
{
cmd_vel_pub_->msg_.header.stamp = time;
cmd_vel_pub_->msg_.twist.linear.x = curr_cmd.lin;
cmd_vel_pub_->msg_.twist.angular.z = curr_cmd.ang;
cmd_vel_pub_->unlockAndPublish();
}
// ACKERMAN DRIVE / STEERING
// Note the output velocity command for this controller is the angular velocity
// for the wheel (not the linear velocity of the wheel rim).
// This is the same behaviour as the diff_drive_controller.
// Calculate the turning radius and rate
double r_p, omega_p;
turningRadiusAndRate(curr_cmd.lin, curr_cmd.ang, mid_wheel_lat_separation_, r_p, omega_p);
ROS_DEBUG_STREAM_NAMED(name_, "r_p: " << r_p << ": omega_p: " << omega_p);
// Calculate velocity and steering angle for each wheel
if (omega_p == 0)
{
// No rotation - set wheel velocity directly
for (int i=0; i<wheel_joints_size_; ++i)
{
wheel_vel_[i] = curr_cmd.lin / wheel_radius_;
}
for (int i=0; i<steer_joints_size_; ++i)
{
steer_ang_[i] = 0.0;
}
}
else
{
for (int i=0; i<wheel_joints_size_; ++i)
{
// Wheel position
auto pos = wheel_positions_[i];
double x = pos.x;
double y = pos.y;
// Wheel turn radius
double r = std::sqrt(x*x + (r_p - y)*(r_p - y));
// Wheel velocity
double sgn = (r_p - y) < 0.0 ? -1.0 : 1.0;
double vel = sgn * r * omega_p;
wheel_vel_[i] = vel / wheel_radius_;
ROS_DEBUG_STREAM_NAMED(name_, "wheel[" << i << "]: r: " << r << ": vel: " << vel);
}
for (int i=0; i<steer_joints_size_; ++i)
{
auto pos = steer_positions_[i];
double x = pos.x;
double y = pos.y;
// Wheel angle
double angle = std::atan2(x, (r_p - y));
// Flip wheel angle by 180 deg if steering rotation is past 90 deg
// (i.e. turning radius < robot base footprint radius).
if (angle > M_PI/2.0)
angle -= M_PI;
if (angle < -M_PI/2.0)
angle += M_PI;
steer_ang_[i] = angle;
ROS_DEBUG_STREAM_NAMED(name_, "steer[" << i << "]: angle: " << angle);
}
}
// Set velocities.
for (size_t i = 0; i < wheel_joints_size_; ++i)
{
wheel_joints_[i].setCommand(wheel_vel_[i]);
}
// Set positions.
for (size_t i = 0; i < steer_joints_size_; ++i)
{
steer_joints_[i].setCommand(steer_ang_[i]);
}
// @TODO: enable publishing wheel and steer joint info.
// publishWheelData(time, period, curr_cmd, ws, lwr, rwr);
time_previous_ = time;
}
void AckermannDriveController::starting(const ros::Time& time)
{
brake();
// Register starting time used to keep fixed rate
last_state_publish_time_ = time;
time_previous_ = time;
odometry_.init(time);
}
void AckermannDriveController::stopping(const ros::Time& /*time*/)
{
brake();
}
void AckermannDriveController::brake()
{
const double vel = 0.0;
for (size_t i = 0; i < wheel_joints_size_; ++i)
{
wheel_joints_[i].setCommand(vel);
}
const double ang = 0.0;
for (size_t i = 0; i < steer_joints_size_; ++i)
{
steer_joints_[i].setCommand(ang);
}
}
void AckermannDriveController::cmdVelCallback(const geometry_msgs::Twist& command)
{
if (isRunning())
{
// check that we don't have multiple publishers on the command topic
if (!allow_multiple_cmd_vel_publishers_ && sub_command_.getNumPublishers() > 1)
{
ROS_ERROR_STREAM_THROTTLE_NAMED(1.0, name_, "Detected " << sub_command_.getNumPublishers()
<< " publishers. Only 1 publisher is allowed. Going to brake.");
brake();
return;
}
command_struct_.ang = command.angular.z;
command_struct_.lin = command.linear.x;
command_struct_.stamp = ros::Time::now();
command_.writeFromNonRT (command_struct_);
ROS_DEBUG_STREAM_NAMED(name_,
"Added values to command. "
<< "Ang: " << command_struct_.ang << ", "
<< "Lin: " << command_struct_.lin << ", "
<< "Stamp: " << command_struct_.stamp);
}
else
{
ROS_ERROR_NAMED(name_, "Can't accept new commands. Controller is not running.");
}
}
// @TODO: enable setting params from URDF
/*
bool AckermannDriveController::setOdomParamsFromUrdf(ros::NodeHandle& root_nh,
const std::string& left_wheel_name,
const std::string& right_wheel_name,
bool lookup_wheel_separation,
bool lookup_wheel_radius)
{
if (!(lookup_wheel_separation || lookup_wheel_radius))
{
// Short-circuit in case we don't need to look up anything, so we don't have to parse the URDF
return true;
}
// Parse robot description
const std::string model_param_name = "robot_description";
bool res = root_nh.hasParam(model_param_name);
std::string robot_model_str="";
if (!res || !root_nh.getParam(model_param_name,robot_model_str))
{
ROS_ERROR_NAMED(name_, "Robot description couldn't be retrieved from param server.");
return false;
}
urdf::ModelInterfaceSharedPtr model(urdf::parseURDF(robot_model_str));
urdf::JointConstSharedPtr left_wheel_joint(model->getJoint(left_wheel_name));
urdf::JointConstSharedPtr right_wheel_joint(model->getJoint(right_wheel_name));
if (lookup_wheel_separation)
{
// Get wheel separation
if (!left_wheel_joint)
{
ROS_ERROR_STREAM_NAMED(name_, left_wheel_name
<< " couldn't be retrieved from model description");
return false;
}
if (!right_wheel_joint)
{
ROS_ERROR_STREAM_NAMED(name_, right_wheel_name
<< " couldn't be retrieved from model description");
return false;
}
ROS_INFO_STREAM("left wheel to origin: " << left_wheel_joint->parent_to_joint_origin_transform.position.x << ","
<< left_wheel_joint->parent_to_joint_origin_transform.position.y << ", "
<< left_wheel_joint->parent_to_joint_origin_transform.position.z);
ROS_INFO_STREAM("right wheel to origin: " << right_wheel_joint->parent_to_joint_origin_transform.position.x << ","
<< right_wheel_joint->parent_to_joint_origin_transform.position.y << ", "
<< right_wheel_joint->parent_to_joint_origin_transform.position.z);
wheel_separation_ = euclideanOfVectors(left_wheel_joint->parent_to_joint_origin_transform.position,
right_wheel_joint->parent_to_joint_origin_transform.position);
}
if (lookup_wheel_radius)
{
// Get wheel radius
if (!getWheelRadius(model->getLink(left_wheel_joint->child_link_name), wheel_radius_))
{
ROS_ERROR_STREAM_NAMED(name_, "Couldn't retrieve " << left_wheel_name << " wheel radius");
return false;
}
}
return true;
}
*/
void AckermannDriveController::setOdomPubFields(ros::NodeHandle& root_nh, ros::NodeHandle& controller_nh)
{
// Get and check params for covariances
XmlRpc::XmlRpcValue pose_cov_list;
controller_nh.getParam("pose_covariance_diagonal", pose_cov_list);
ROS_ASSERT(pose_cov_list.getType() == XmlRpc::XmlRpcValue::TypeArray);
ROS_ASSERT(pose_cov_list.size() == 6);
for (int i = 0; i < pose_cov_list.size(); ++i)
ROS_ASSERT(pose_cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);
XmlRpc::XmlRpcValue twist_cov_list;
controller_nh.getParam("twist_covariance_diagonal", twist_cov_list);
ROS_ASSERT(twist_cov_list.getType() == XmlRpc::XmlRpcValue::TypeArray);
ROS_ASSERT(twist_cov_list.size() == 6);
for (int i = 0; i < twist_cov_list.size(); ++i)
ROS_ASSERT(twist_cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);
// Setup odometry realtime publisher + odom message constant fields
odom_pub_.reset(new realtime_tools::RealtimePublisher<nav_msgs::Odometry>(controller_nh, "odom", 100));
odom_pub_->msg_.header.frame_id = odom_frame_id_;
odom_pub_->msg_.child_frame_id = base_frame_id_;
odom_pub_->msg_.pose.pose.position.z = 0;
odom_pub_->msg_.pose.covariance = {
static_cast<double>(pose_cov_list[0]), 0., 0., 0., 0., 0.,
0., static_cast<double>(pose_cov_list[1]), 0., 0., 0., 0.,
0., 0., static_cast<double>(pose_cov_list[2]), 0., 0., 0.,
0., 0., 0., static_cast<double>(pose_cov_list[3]), 0., 0.,
0., 0., 0., 0., static_cast<double>(pose_cov_list[4]), 0.,
0., 0., 0., 0., 0., static_cast<double>(pose_cov_list[5]) };
odom_pub_->msg_.twist.twist.linear.y = 0;
odom_pub_->msg_.twist.twist.linear.z = 0;
odom_pub_->msg_.twist.twist.angular.x = 0;
odom_pub_->msg_.twist.twist.angular.y = 0;
odom_pub_->msg_.twist.covariance = {
static_cast<double>(twist_cov_list[0]), 0., 0., 0., 0., 0.,
0., static_cast<double>(twist_cov_list[1]), 0., 0., 0., 0.,
0., 0., static_cast<double>(twist_cov_list[2]), 0., 0., 0.,
0., 0., 0., static_cast<double>(twist_cov_list[3]), 0., 0.,
0., 0., 0., 0., static_cast<double>(twist_cov_list[4]), 0.,
0., 0., 0., 0., 0., static_cast<double>(twist_cov_list[5]) };
tf_odom_pub_.reset(new realtime_tools::RealtimePublisher<tf::tfMessage>(root_nh, "/tf", 100));
tf_odom_pub_->msg_.transforms.resize(1);
tf_odom_pub_->msg_.transforms[0].transform.translation.z = 0.0;
tf_odom_pub_->msg_.transforms[0].child_frame_id = base_frame_id_;
tf_odom_pub_->msg_.transforms[0].header.frame_id = odom_frame_id_;
}
// @TODO: enable dynamic reconfig
/*
void AckermannDriveController::reconfCallback(AckermannDriveControllerConfig& config, uint32_t level)
{
DynamicParams dynamic_params;
dynamic_params.left_wheel_radius_multiplier = config.left_wheel_radius_multiplier;
dynamic_params.right_wheel_radius_multiplier = config.right_wheel_radius_multiplier;
dynamic_params.wheel_separation_multiplier = config.wheel_separation_multiplier;
dynamic_params.publish_rate = config.publish_rate;
dynamic_params.enable_odom_tf = config.enable_odom_tf;
dynamic_params_.writeFromNonRT(dynamic_params);
ROS_INFO_STREAM_NAMED(name_, "Dynamic Reconfigure:\n" << dynamic_params);
}
void AckermannDriveController::updateDynamicParams()
{
// Retreive dynamic params:
const DynamicParams dynamic_params = *(dynamic_params_.readFromRT());
left_wheel_radius_multiplier_ = dynamic_params.left_wheel_radius_multiplier;
right_wheel_radius_multiplier_ = dynamic_params.right_wheel_radius_multiplier;
wheel_separation_multiplier_ = dynamic_params.wheel_separation_multiplier;
publish_period_ = ros::Duration(1.0 / dynamic_params.publish_rate);
enable_odom_tf_ = dynamic_params.enable_odom_tf;
}
*/
// @TODO: enable publishing wheel and steer joint info.
/*
void AckermannDriveController::publishWheelData(const ros::Time& time, const ros::Duration& period, Commands& curr_cmd,
double wheel_separation, double left_wheel_radius, double right_wheel_radius)
{
if (publish_wheel_joint_controller_state_ && controller_state_pub_->trylock())
{
const double cmd_dt(period.toSec());
// Compute desired wheels velocities, that is before applying limits:
const double vel_left_desired = (curr_cmd.lin - curr_cmd.ang * wheel_separation / 2.0) / left_wheel_radius;
const double vel_right_desired = (curr_cmd.lin + curr_cmd.ang * wheel_separation / 2.0) / right_wheel_radius;
controller_state_pub_->msg_.header.stamp = time;
for (size_t i = 0; i < wheel_joints_size_; ++i)
{
const double control_duration = (time - time_previous_).toSec();
const double left_wheel_acc = (left_wheel_joints_[i].getVelocity() - vel_left_previous_[i]) / control_duration;
const double right_wheel_acc = (right_wheel_joints_[i].getVelocity() - vel_right_previous_[i]) / control_duration;
// Actual
controller_state_pub_->msg_.actual.positions[i] = left_wheel_joints_[i].getPosition();
controller_state_pub_->msg_.actual.velocities[i] = left_wheel_joints_[i].getVelocity();
controller_state_pub_->msg_.actual.accelerations[i] = left_wheel_acc;
controller_state_pub_->msg_.actual.effort[i] = left_wheel_joints_[i].getEffort();
controller_state_pub_->msg_.actual.positions[i + wheel_joints_size_] = right_wheel_joints_[i].getPosition();
controller_state_pub_->msg_.actual.velocities[i + wheel_joints_size_] = right_wheel_joints_[i].getVelocity();
controller_state_pub_->msg_.actual.accelerations[i + wheel_joints_size_] = right_wheel_acc;
controller_state_pub_->msg_.actual.effort[i+ wheel_joints_size_] = right_wheel_joints_[i].getEffort();
// Desired
controller_state_pub_->msg_.desired.positions[i] += vel_left_desired * cmd_dt;
controller_state_pub_->msg_.desired.velocities[i] = vel_left_desired;
controller_state_pub_->msg_.desired.accelerations[i] = (vel_left_desired - vel_left_desired_previous_) * cmd_dt;
controller_state_pub_->msg_.desired.effort[i] = std::numeric_limits<double>::quiet_NaN();
controller_state_pub_->msg_.desired.positions[i + wheel_joints_size_] += vel_right_desired * cmd_dt;
controller_state_pub_->msg_.desired.velocities[i + wheel_joints_size_] = vel_right_desired;
controller_state_pub_->msg_.desired.accelerations[i + wheel_joints_size_] = (vel_right_desired - vel_right_desired_previous_) * cmd_dt;
controller_state_pub_->msg_.desired.effort[i+ wheel_joints_size_] = std::numeric_limits<double>::quiet_NaN();
// Error
controller_state_pub_->msg_.error.positions[i] = controller_state_pub_->msg_.desired.positions[i] -
controller_state_pub_->msg_.actual.positions[i];
controller_state_pub_->msg_.error.velocities[i] = controller_state_pub_->msg_.desired.velocities[i] -
controller_state_pub_->msg_.actual.velocities[i];
controller_state_pub_->msg_.error.accelerations[i] = controller_state_pub_->msg_.desired.accelerations[i] -
controller_state_pub_->msg_.actual.accelerations[i];
controller_state_pub_->msg_.error.effort[i] = controller_state_pub_->msg_.desired.effort[i] -
controller_state_pub_->msg_.actual.effort[i];
controller_state_pub_->msg_.error.positions[i + wheel_joints_size_] = controller_state_pub_->msg_.desired.positions[i + wheel_joints_size_] -
controller_state_pub_->msg_.actual.positions[i + wheel_joints_size_];
controller_state_pub_->msg_.error.velocities[i + wheel_joints_size_] = controller_state_pub_->msg_.desired.velocities[i + wheel_joints_size_] -
controller_state_pub_->msg_.actual.velocities[i + wheel_joints_size_];
controller_state_pub_->msg_.error.accelerations[i + wheel_joints_size_] = controller_state_pub_->msg_.desired.accelerations[i + wheel_joints_size_] -
controller_state_pub_->msg_.actual.accelerations[i + wheel_joints_size_];
controller_state_pub_->msg_.error.effort[i+ wheel_joints_size_] = controller_state_pub_->msg_.desired.effort[i + wheel_joints_size_] -
controller_state_pub_->msg_.actual.effort[i + wheel_joints_size_];
// Save previous velocities to compute acceleration
vel_left_previous_[i] = left_wheel_joints_[i].getVelocity();
vel_right_previous_[i] = right_wheel_joints_[i].getVelocity();
vel_left_desired_previous_ = vel_left_desired;
vel_right_desired_previous_ = vel_right_desired;
}
controller_state_pub_->unlockAndPublish();
}
}
*/
PLUGINLIB_EXPORT_CLASS(ackermann_drive_controller::AckermannDriveController, controller_interface::ControllerBase);
} // namespace ackermann_drive_controller
| 46.529179 | 181 | 0.639995 | Jenifen |
74411e2d6c418ea359b615812efe8c0dc7ba060d | 7,079 | cc | C++ | chrome/chrome_cleaner/http/mock_http_agent_factory.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/chrome_cleaner/http/mock_http_agent_factory.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/chrome_cleaner/http/mock_http_agent_factory.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/chrome_cleaner/http/mock_http_agent_factory.h"
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "base/logging.h"
#include "chrome/chrome_cleaner/http/http_agent.h"
#include "chrome/chrome_cleaner/http/http_agent_factory.h"
#include "chrome/chrome_cleaner/http/http_response.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chrome_cleaner {
namespace {
// Class that provides a response based on how the MockHttpAgentConfig is
// configured.
class MockHttpResponse : public chrome_cleaner::HttpResponse {
public:
explicit MockHttpResponse(MockHttpAgentConfig* config) : config_(config) {
DCHECK(config);
}
~MockHttpResponse() override = default;
// chrome_cleaner::HttpResponse:
bool GetStatusCode(uint16_t* status_code) override {
if (config_->GetCurrentCalls().get_status_code_succeeds) {
*status_code = static_cast<uint16_t>(
config_->GetCurrentCalls().get_status_code_result);
}
return config_->GetCurrentCalls().get_status_code_succeeds;
}
bool GetContentLength(bool* has_content_length,
uint32_t* content_length) override {
ADD_FAILURE() << "This method should not be called.";
return false;
}
bool GetContentType(bool* has_content_type,
base::string16* content_type) override {
ADD_FAILURE() << "This method should not be called.";
return false;
}
bool HasData(bool* has_data) override {
if (config_->GetCurrentCalls().has_data_succeeds)
*has_data = !config_->GetCurrentCalls().read_data_result.empty();
return config_->GetCurrentCalls().has_data_succeeds;
}
bool ReadData(char* buffer, uint32_t* count) override {
MockHttpAgentConfig::Calls& calls = config_->GetCurrentCalls();
bool succeeds = calls.read_data_succeeds_by_default;
if (!calls.read_data_success_sequence.empty()) {
succeeds = calls.read_data_success_sequence[0];
calls.read_data_success_sequence.erase(
calls.read_data_success_sequence.begin());
}
if (succeeds)
config_->ReadData(buffer, count);
return succeeds;
}
private:
MockHttpAgentConfig* config_{nullptr};
DISALLOW_COPY_AND_ASSIGN(MockHttpResponse);
};
// Class that acts as an HttpAgent based on how the MockHttpAgentConfig is
// configured.
class MockHttpAgent : public chrome_cleaner::HttpAgent {
public:
explicit MockHttpAgent(MockHttpAgentConfig* config) : config_(config) {
DCHECK(config);
}
~MockHttpAgent() override = default;
// chrome_cleaner::HttpAgent:
std::unique_ptr<chrome_cleaner::HttpResponse> Post(
const base::string16& host,
uint16_t port,
const base::string16& path,
bool secure,
const base::string16& extra_headers,
const std::string& body,
const net::NetworkTrafficAnnotationTag& /*traffic_annotation*/) override {
const bool post_succeeds = config_->GetCurrentCalls().request_succeeds;
MockHttpAgentConfig::RequestData post_data;
post_data.host = host;
post_data.port = port;
post_data.path = path;
post_data.secure = secure;
post_data.extra_headers = extra_headers;
post_data.body = body;
config_->AddRequestData(post_data);
if (post_succeeds)
return std::make_unique<MockHttpResponse>(config_);
return std::unique_ptr<MockHttpResponse>();
}
// chrome_cleaner::HttpAgent:
std::unique_ptr<chrome_cleaner::HttpResponse> Get(
const base::string16& host,
uint16_t port,
const base::string16& path,
bool secure,
const base::string16& extra_headers,
const net::NetworkTrafficAnnotationTag& /*traffic_annotation*/) override {
const bool get_succeeds = config_->GetCurrentCalls().request_succeeds;
MockHttpAgentConfig::RequestData get_data;
get_data.host = host;
get_data.port = port;
get_data.path = path;
get_data.secure = secure;
get_data.extra_headers = extra_headers;
config_->AddRequestData(get_data);
if (get_succeeds)
return std::make_unique<MockHttpResponse>(config_);
return std::unique_ptr<MockHttpResponse>();
}
private:
MockHttpAgentConfig* config_{nullptr};
DISALLOW_COPY_AND_ASSIGN(MockHttpAgent);
};
} // namespace
MockHttpAgentConfig::Calls::Calls(HttpStatus status)
: get_status_code_result(status) {}
MockHttpAgentConfig::Calls::Calls(const Calls& other) = default;
MockHttpAgentConfig::Calls::~Calls() = default;
MockHttpAgentConfig::Calls& MockHttpAgentConfig::Calls::operator=(
const MockHttpAgentConfig::Calls& other) = default;
MockHttpAgentConfig::RequestData::RequestData() = default;
MockHttpAgentConfig::RequestData::RequestData(const RequestData& other) =
default;
MockHttpAgentConfig::RequestData::~RequestData() = default;
MockHttpAgentConfig::RequestData& MockHttpAgentConfig::RequestData::operator=(
const MockHttpAgentConfig::RequestData& other) = default;
MockHttpAgentConfig::MockHttpAgentConfig() = default;
MockHttpAgentConfig::~MockHttpAgentConfig() = default;
size_t MockHttpAgentConfig::AddCalls(const Calls& calls) {
calls_.push_back(calls);
return calls_.size() - 1;
}
MockHttpAgentConfig::Calls& MockHttpAgentConfig::GetCurrentCalls() {
if (current_index_ >= calls_.size()) {
static Calls default_calls(HttpStatus::kOk);
ADD_FAILURE() << "Did not expect more than " << calls_.size() << " tries";
return default_calls;
}
return calls_[current_index_];
}
void MockHttpAgentConfig::ReadData(char* buffer, uint32_t* count) {
if (current_index_ >= calls_.size()) {
ADD_FAILURE() << "Reading data for an unexpected call";
*count = 0;
return;
}
Calls& calls = calls_[current_index_];
*count =
std::min(*count, static_cast<uint32_t>(calls.read_data_result.size()));
memcpy(buffer, calls.read_data_result.c_str(), *count);
calls.read_data_result = calls.read_data_result.substr(*count);
}
void MockHttpAgentConfig::AddRequestData(const RequestData& request_data) {
ASSERT_EQ(request_data_.size(), current_index_)
<< "MockHttpAgentConfig does not support creating multiple agents "
<< "without calling Post or Get on each before creating the next one. "
<< "Suggest adding support to MockHttpAgentConfig for that if necessary, "
<< "or updating your code to avoid this.";
request_data_.push_back(request_data);
}
MockHttpAgentFactory::MockHttpAgentFactory(MockHttpAgentConfig* config)
: config_(config) {
DCHECK(config);
}
std::unique_ptr<chrome_cleaner::HttpAgent>
MockHttpAgentFactory::CreateHttpAgent() const {
// Set the configuration index to the next one (one per HttpAgent).
if (config_->current_index_ == MockHttpAgentConfig::kInvalidIndex)
config_->current_index_ = 0;
else
++config_->current_index_;
return std::make_unique<MockHttpAgent>(config_);
}
} // namespace chrome_cleaner
| 31.744395 | 80 | 0.730753 | sarang-apps |
744127979977c33452dbd4f3f80463078c2ba9df | 1,059 | cpp | C++ | pt07z.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 264 | 2015-01-08T10:07:01.000Z | 2022-03-26T04:11:51.000Z | pt07z.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 17 | 2016-04-15T03:38:07.000Z | 2020-10-30T00:33:57.000Z | pt07z.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 127 | 2015-01-08T04:56:44.000Z | 2022-02-25T18:40:37.000Z | // 2008-07-29
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <list>
using namespace std;
int main()
{
int N,i,u,v;
scanf("%d",&N);
list<int> L[10000];
for (i=0; i<N-1; i++)
{
scanf("%d %d",&u,&v); u--,v--;
L[u].push_back(v);
L[v].push_back(u);
}
int size=1;
int p[20000];
int n[20000];
int d[20000];
int maxdist=0;
int node;
p[0]=-1;
n[0]=0;
d[0]=0;
while (size)
{
size--;
int _n=n[size];
int _d=d[size];
int _p=p[size];
if (maxdist<_d)
{
maxdist=_d;
node=_n;
}
list<int>::iterator I;
for (I=L[_n].begin();I!=L[_n].end();I++)
if (*I!=_p)
{
p[size]=_n;
n[size]=*I;
d[size]=_d+1;
size++;
}
}
size=1;
maxdist=0;
p[0]=-1;
n[0]=node;
d[0]=0;
while (size)
{
size--;
int _n=n[size];
int _d=d[size];
int _p=p[size];
if (maxdist<_d)
{
maxdist=_d;
node=_n;
}
list<int>::iterator I;
for (I=L[_n].begin();I!=L[_n].end();I++)
if (*I!=_p)
{
p[size]=_n;
n[size]=*I;
d[size]=_d+1;
size++;
}
}
printf("%d\n",maxdist);
return 0;
}
| 13.934211 | 42 | 0.507082 | ohmyjons |
74440b1c5c4417fae1efdb360ec982198c4b4949 | 3,775 | cpp | C++ | 7952603892_basic.cpp | sehgal-aamulya/SequenceAlignmentAlgorithms | 35ce3c9a35c1a681f03c5b605b6152a1a30c014f | [
"MIT"
] | null | null | null | 7952603892_basic.cpp | sehgal-aamulya/SequenceAlignmentAlgorithms | 35ce3c9a35c1a681f03c5b605b6152a1a30c014f | [
"MIT"
] | null | null | null | 7952603892_basic.cpp | sehgal-aamulya/SequenceAlignmentAlgorithms | 35ce3c9a35c1a681f03c5b605b6152a1a30c014f | [
"MIT"
] | null | null | null | //
// Created by Aamulya Sehgal on 12/4/21.
//
#include <string>
#include <iostream>
#include <fstream>
#include <sys/resource.h>
#include "SequenceAlignment.hpp"
#include "StringGenerator.hpp"
#include "StringTrim.hpp"
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cout << "Please include an input file name (./7952603892_basic input.txt)" << std::endl;
std::cout << "You can also include an output file name (defaults to output.txt) "
"(./7952603892_basic input.txt output.txt)" << std::endl;
return EXIT_FAILURE;
}
constexpr std::array<std::array<int, 4>, 4> mismatchPenalty = {
0, 110, 48, 94,
110, 0, 118, 48,
48, 118, 0, 110,
94, 48, 110, 0
};
constexpr int gapPenalty = 30;
constexpr char gapSymbol = '_';
const std::string_view inputFileName{argv[1]};
const std::string_view outputFileName{(argc >= 3) ? argv[2] : "output.txt"};
std::ifstream fin{inputFileName.data()};
std::string strOne, strTwo;
std::vector<size_t> j;
std::vector<size_t> k;
std::getline(fin, strOne);
trim(strOne);
size_t value;
while (fin >> value) {
j.push_back(value);
}
fin.clear();
std::getline(fin, strTwo);
trim(strTwo);
while (fin >> value) {
k.push_back(value);
}
const auto[stringOne, stringTwo] = inputStringGenerator(strOne, strTwo, j, k);
std::ofstream fout{outputFileName.data()};
rusage start, end;
const int startReturn = getrusage(RUSAGE_SELF, &start);
if (startReturn) return startReturn;
const SequenceAlignment sequenceAlignment(stringOne, stringTwo, gapSymbol, gapPenalty, mismatchPenalty);
const size_t alignmentCost = sequenceAlignment.align();
const auto[sequenceOne, sequenceTwo] = sequenceAlignment.sequence();
const int endReturn = getrusage(RUSAGE_SELF, &end);
if (endReturn) return endReturn;
const double diffTime = (end.ru_utime.tv_sec * 1000000.0 + end.ru_utime.tv_usec +
end.ru_stime.tv_sec * 1000000.0 + end.ru_stime.tv_usec -
start.ru_utime.tv_sec * 1000000.0 - start.ru_utime.tv_usec -
start.ru_stime.tv_sec * 1000000.0 - start.ru_stime.tv_usec) /
1000000.0;
double diffMemory = end.ru_maxrss - start.ru_maxrss;
if (diffMemory == 0.0) diffMemory = end.ru_maxrss;
#ifdef __APPLE__
diffMemory /= 1024.0;
#endif
#ifndef NDEBUG
std::cout << "Basic Version:" << std::endl;
std::cout << "StringOne: " << stringOne << std::endl;
std::cout << "StringTwo: " << stringTwo << std::endl;
std::cout << std::endl;
std::cout << "Problem Size (sum of string sizes): " << stringOne.size() + stringTwo.size() << std::endl;
std::cout << std::endl;
#endif
if (sequenceOne.size() <= 50) {
#ifndef NDEBUG
std::cout << sequenceOne << std::endl;
std::cout << sequenceTwo << std::endl;
#endif
fout << sequenceOne << std::endl;
fout << sequenceTwo << std::endl;
}
else {
#ifndef NDEBUG
std::cout << sequenceOne.substr(0, 50) << " "
<< sequenceOne.substr(sequenceOne.size() - 50)
<< std::endl;
std::cout << sequenceTwo.substr(0, 50) << " "
<< sequenceTwo.substr(sequenceTwo.size() - 50)
<< std::endl;
#endif
fout << sequenceOne.substr(0, 50) << " "
<< sequenceOne.substr(sequenceOne.size() - 50)
<< std::endl;
fout << sequenceTwo.substr(0, 50) << " "
<< sequenceTwo.substr(sequenceTwo.size() - 50)
<< std::endl;
}
#ifndef NDEBUG
std::cout << alignmentCost << std::endl;
std::cout << std::fixed << diffTime << std::endl;
std::cout << std::fixed << diffMemory << std::endl;
#endif
fout << alignmentCost << std::endl;
fout << std::fixed << diffTime << std::endl;
fout << std::fixed << diffMemory << std::endl;
return 0;
}
| 27.355072 | 106 | 0.629934 | sehgal-aamulya |
74446f5b5c586514152365f900623f91b62bf0a6 | 36,537 | hh | C++ | software/protoDUNE/protoDUNE/Headers.hh | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | null | null | null | software/protoDUNE/protoDUNE/Headers.hh | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | 2 | 2017-05-11T04:22:27.000Z | 2018-09-18T16:10:29.000Z | software/protoDUNE/protoDUNE/Headers.hh | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | 2 | 2017-04-03T21:59:53.000Z | 2020-12-13T00:14:20.000Z | // -*-Mode: C++;-*-
#ifndef PDD_HEADER_HH
#define PDD_HEADER_HH
/* ---------------------------------------------------------------------- *//*!
*
* @file Header.hh
* @brief Proto-Dune Data Header
* @verbatim
* Copyright 2013
* by
*
* The Board of Trustees of the
* Leland Stanford Junior University.
* All rights reserved.
*
* @endverbatim
*
* @par Facility:
* pdd
*
* @author
* <russell@slac.stanford.edu>
*
* @par Date created:
* <2017/06/19>
*
* @par Credits:
* SLAC
*
\* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *\
HISTORY
-------
DATE WHO WHAT
---------- --- ---------------------------------------------------------
2018.07.18 jjr Added a const to the n64() methods
2018.02.06 jjr Added methods to add the source specifiers (i.e. the WIB
2017.08.28 jjr Fix position of trigger type in auxilliary block to
match the documentation
2017.08.29 jjr Stripped debugging print statements.
2017.06.19 jjr Created
\* ---------------------------------------------------------------------- */
namespace pdd {
#define PDD_DEBUG(_mask, _offset, _val) \
fprintf (stderr, \
"Mask: %8.8" PRIx32 " Offset: %8.8x Value: %8.8" PRIx32 "\n", \
static_cast<uint32_t>( _mask), \
static_cast< int>(_offset), \
static_cast<uint32_t>( _val)), \
#define PDD_INSERT(_type, _mask, _offset, _val) \
( \
((static_cast<_type>((_val) & static_cast<uint32_t>( _mask))) \
<< static_cast< int>(_offset)) \
)
#define PDD_INSERTC(_type, _mask, _offset, _val) \
((~(static_cast<_type>(_val) & static_cast<uint32_t>( _mask))) \
<< (64 - static_cast< int>(_offset)))
#define PDD_INSERT64(_mask, _offset, _val) \
PDD_INSERT(uint64_t, _mask, _offset, _val)
#define PDD_INSERT64C(_mask, _offset, _val) \
PDD_INSERTC(uint64_t, _mask, _offset, _val)
#define PDD_INSERT32(_mask, _offset, _val) \
PDD_INSERT(uint32_t, _mask, _offset, _val)
#define PDD_INSERT32C(_mask, _offset, _val) \
PDD_INSERTC(uint32_t, _mask, _offset, _val)
#define PDD_EXTRACT(_type, _val, _mask, _offset) \
(((_val) >> static_cast<int>(_offset)) & static_cast<uint32_t>(_mask))
#define PDD_EXTRACT64(_val, _mask, _offset) \
PDD_EXTRACT(uint64_t, _val, _mask, _offset)
#define PDD_EXTRACT32(_val, _mask, _offset) \
PDD_EXTRACT(uint64_t, _val, _mask, _offset)
/* ---------------------------------------------------------------------- *//*!
\class Header 0
\brief Generic format = 0 header
*/
/* ---------------------------------------------------------------------- */
class Header0
{
public:
Header0 (int type,
uint8_t subtype,
uint32_t bridge,
int naux64,
uint32_t n64) :
m_w64 (compose (type, subtype, bridge, naux64, n64))
{
return;
}
/* ------------------------------------------------------------------- *//*!
\enum class Size
\brief Enumerates the sizes of the Header bit fields.
*/
/* ------------------------------------------------------------------ */
enum class Size: int
{
Format = 4, /*!< Size of the format field */
Type = 4, /*!< Size of the frame type field */
Length = 24, /*!< Size of the length field */
NAux64 = 4, /*!< Size of the auxillary length field */
SubType = 4, /*!< Size of the record's subtype field */
Specific1 = 24 /*!< Size of the first type specific field */
};
/* ------------------------------------------------------------------ */
/* ------------------------------------------------------------------- *//*!
\enum class Offset
\brief Enumerates the right justified offsets of the header bit
fields.
*/
/* ------------------------------------------------------------------ */
enum class Offset: int
{
Format = 0, /*!< Offset to the format field */
Type = 4, /*!< Offset to the frame type field */
Length = 8, /*!< Offset to the length field */
NAux64 = 32, /*!< Offset to the auxillary length field */
SubType = 36, /*!< Offset to the record's subtype field */
Bridge = 40 /*!< Offset to the bridge word */
};
/* ------------------------------------------------------------------ */
/* ------------------------------------------------------------------- *//*!
\enum class Offset
\brief Enumerates the right justified masks of the header bit fields.
*/
/* ------------------------------------------------------------------ */
enum class Mask: uint32_t
{
Format = 0x0000000f,
Type = 0x0000000f,
Length = 0x00ffffff,
NAux64 = 0x0000000f,
SubType = 0x0000000f,
Bridge = 0x00ffffff
};
/* ------------------------------------------------------------------ */
public:
static uint64_t compose (int type,
uint8_t subtype,
uint32_t bridge,
int naux64,
uint32_t n64);
void construct (int type,
uint8_t subtype,
uint32_t bridge,
int naux64,
uint32_t n64)
{
m_w64 = compose (type, subtype, bridge, n64, naux64);
}
uint64_t retrieve () const
{
return m_w64;
}
static uint32_t format (uint64_t w64)
{
return PDD_EXTRACT64 (w64, Mask::Format, Offset::Format);
}
static uint32_t type (uint64_t w64)
{
return PDD_EXTRACT64 (w64, Mask::Type, Offset::Type);
}
static uint32_t length (uint64_t w64)
{
return PDD_EXTRACT64 (w64, Mask::Length, Offset::Length);
}
static uint32_t subtype (uint64_t w64)
{
return PDD_EXTRACT64 (w64, Mask::SubType, Offset::SubType);
}
static uint32_t naux64 (uint64_t w64)
{
return PDD_EXTRACT64 (w64, Mask::NAux64, Offset::NAux64);
}
static uint32_t bridge (uint64_t w64)
{
return PDD_EXTRACT64 (w64, Mask::Bridge, Offset::Bridge);
}
public:
uint64_t m_w64;
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\brief Method to compose a generic Header0
\param[in] type The fragment type
\param[in] subtype The 4-bit record subtype
\param[in] naux64 The number of 64 bit auxillary words
\param[in] spec1 The 24-bit type specific word
\param[in] n64 The length of this fragment in units of 64-bit words
*/
/* ---------------------------------------------------------------------- */
inline uint64_t Header0::compose (int type,
uint8_t subtype,
uint32_t bridge,
int naux64,
uint32_t n64)
{
/*
fprintf (stderr,
"Header0::compose type=%d subtype=%d bridge=%8.8" PRIx32 " "
"naux64=%d n64=%8.8" PRIx32 "\n",
type, subtype, bridge, naux64, n64);
*/
uint64_t w64 = PDD_INSERT64 (Mask::Format, Offset::Format, 0)
| PDD_INSERT64 (Mask::Type, Offset::Type, type)
| PDD_INSERT64 (Mask::Length, Offset::Length, n64)
| PDD_INSERT64 (Mask::SubType, Offset::SubType, subtype)
| PDD_INSERT64 (Mask::NAux64, Offset::NAux64, naux64)
| PDD_INSERT64 (Mask::Bridge, Offset::Bridge, bridge);
return w64;
};
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\class Header 1
\brief Generic format = 1 header
*/
/* ---------------------------------------------------------------------- */
class Header1
{
public:
Header1 () { return; }
Header1 (int type,
uint32_t n64,
uint32_t bridge) :
m_w64 (compose (type, n64, bridge))
{
return;
}
int n64 () const { return (m_w64 >> static_cast< int>(Offset::Length))
& static_cast<uint32_t>( Mask::Length); }
/* ------------------------------------------------------------------- *//*!
\enum class Size
\brief Enumerates the sizes of the Header bit fields.
*/
/* ------------------------------------------------------------------ */
enum class Size: int
{
Format = 4, /*!< Size of the format field */
Type = 4, /*!< Size of the record/frame type field */
Length = 24, /*!< Size of the length field */
Bridge = 32 /*!< Size of the bridge field */
};
/* ------------------------------------------------------------------ */
/* ------------------------------------------------------------------- *//*!
\enum class Offset
\brief Enumerates the right justified offsets of the header bit
fields.
*/
/* ------------------------------------------------------------------ */
enum class Offset: int
{
Format = 0, /*!< Offset of the format field */
Type = 4, /*!< Offset of the frame type field */
Length = 8, /*!< Offset of the length field */
Bridge = 32 /*!< Offset of the bridge field */
};
/* ------------------------------------------------------------------ */
/* ------------------------------------------------------------------- *//*!
\enum class Offset
\brief Enumerates the right justified masks of the header bit fields.
*/
/* ------------------------------------------------------------------ */
enum class Mask: uint32_t
{
Format = 0x0000000f,
Type = 0x0000000f,
Version = 0x0000000f,
Length = 0x00ffffff,
Bridge = 0xffffffff
};
/* ------------------------------------------------------------------ */
public:
static uint64_t compose (int type,
uint32_t n64,
uint32_t bridge);
void construct (int type,
uint32_t n64,
uint32_t bridge)
{
Header1::m_w64 = Header1::compose (type, n64, bridge);
return;
}
uint64_t retrieve () const
{
return m_w64;
}
static uint32_t type (uint64_t w64)
{
return PDD_EXTRACT64 (w64, Mask::Type, Offset::Type);
}
static uint32_t n64 (uint64_t w64)
{
return PDD_EXTRACT64 (w64, Mask::Length, Offset::Length);
}
static uint32_t bridge (uint64_t w64)
{
return PDD_EXTRACT64 (w64, Mask::Bridge, Offset::Bridge);
}
public:
uint64_t m_w64;
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\brief Method to compose a generic Header1
\param[in] type The record type
\param[in] n64 The length of this fragment in units of 64-bit words
\param[in] bridge An arbitrary 32-bit bridge word. Its meaning is
record \a type specific
*/
/* ---------------------------------------------------------------------- */
inline uint64_t Header1::compose (int type,
uint32_t n64,
uint32_t bridge)
{
/*
fprintf (stderr,
"Header1::compose Format:%d Type:%d N64:%8.8" PRIx32 ""
" Bridge:%8.8" PRIx32 "\n",
1, type, n64, bridge);
*/
uint64_t w64 = PDD_INSERT64 (Mask::Format, Offset::Format, 1)
| PDD_INSERT64 (Mask::Type, Offset::Type, type)
| PDD_INSERT64 (Mask::Length, Offset::Length, n64)
| PDD_INSERT64 (Mask::Bridge, Offset::Bridge, bridge);
return w64;
};
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\class Header 2
\brief Generic format = 1 header
*/
/* ---------------------------------------------------------------------- */
class Header2
{
public:
Header2 () { return; }
Header2 (int type,
unsigned int n64,
unsigned int bridge) :
m_w32 (compose (type, n64, bridge))
{
return;
}
int n64 () const { return (m_w32 >> static_cast< int>(Offset::Length))
& static_cast<uint32_t>( Mask::Length); }
/* ------------------------------------------------------------------- *//*!
\enum class Size
\brief Enumerates the sizes of the Header bit fields.
*/
/* ------------------------------------------------------------------ */
enum class Size: int
{
Format = 4, /*!< Size of the format field */
Type = 4, /*!< Size of the record/frame type field */
Length = 12, /*!< Size of the length field */
Bridge = 12 /*!< Size of the bridge word field */
};
/* ------------------------------------------------------------------ */
/* ------------------------------------------------------------------- *//*!
\enum class Offset
\brief Enumerates the right justified offsets of the header bit
fields.
*/
/* ------------------------------------------------------------------ */
enum class Offset: int
{
Format = 0, /*!< Offset of the format field */
Type = 4, /*!< Offset of the frame type field */
Length = 8, /*!< Offset of the length field */
Bridge = 20, /*!< Offset of the bridge word field */
};
/* ------------------------------------------------------------------ */
/* ------------------------------------------------------------------- *//*!
\enum class Offset
\brief Enumerates the right justified masks of the header bit fields.
*/
/* ------------------------------------------------------------------ */
enum class Mask: uint32_t
{
Format = 0x0000000f,
Type = 0x0000000f,
Length = 0x00000fff,
Bridge = 0x00000fff,
};
/* ------------------------------------------------------------------ */
public:
static uint32_t compose (unsigned int type,
unsigned int n64,
unsigned int bridge);
void construct (unsigned int type,
unsigned int n64,
unsigned int bridge)
{
/*
printf ("Header2::construct type = %u n64 = %u bridge = %8.8x\n",
type, n64, bridge);
*/
Header2::m_w32 = Header2::compose (type, n64, bridge);
return;
}
uint32_t retrieve () const
{
return m_w32;
}
static uint32_t type (uint64_t w32)
{
return PDD_EXTRACT32 (w32, Mask::Type, Offset::Type);
}
static uint32_t n64 (uint32_t w32)
{
return PDD_EXTRACT32 (w32, Mask::Length, Offset::Length);
}
static uint32_t bridge (uint32_t w32)
{
return PDD_EXTRACT32 (w32, Mask::Bridge, Offset::Bridge);
}
public:
uint32_t m_w32;
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\brief Method to compose a generic Header2
\param[in] type The record type
\param[in] n64 The length of this fragment in units of 64-bit words
\param[in bridge An 12-bit type specific bridge field
*/
/* ---------------------------------------------------------------------- */
inline uint32_t Header2::compose (unsigned int type,
unsigned int n64,
unsigned int bridge)
{
/*
fprintf (stderr,
"Header2::compose Format:%d Type:%d N64:%3.3x Bridge:%3.3x\n",
1, type, n64, bridge);
*/
uint32_t w32 = PDD_INSERT64 (Mask::Format, Offset::Format, 2)
| PDD_INSERT64 (Mask::Type, Offset::Type, type)
| PDD_INSERT64 (Mask::Length, Offset::Length, n64)
| PDD_INSERT64 (Mask::Bridge, Offset::Bridge, bridge);
return w32;
};
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\class Trailer
\brief Generic trailers. Trailers are always the complemented value
of its corresponding Header. As such, they are not actually
filled on a field by field basis.
*/
/* ---------------------------------------------------------------------- */
class Trailer
{
public:
explicit Trailer () { return; }
public:
Trailer (uint64_t header) : m_w64 (~header) { return; }
static uint64_t compose (uint64_t header) { return ~header; }
void construct (uint64_t header)
{
m_w64 = ~header;
/*
fprintf (stderr, "Trailer: %16.16" PRIx64 " -> %16.16" PRIx64 "\n",
header, m_w64);
*/
}
public:
uint64_t m_w64;
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
namespace fragment
{
/* ---------------------------------------------------------------------- *//*!
\enum class Type
\brief Enumerates the type of fragment. A fragment is the largest
self-contained piece of data that originates from 1 contributor.
*/
/* ---------------------------------------------------------------------- */
enum class Type
{
Reserved_0 = 0, /*!< Reserved for future use */
Control = 1, /*!< Control, \e e.g. Begin/Pause/Resume/Stop/etc */
Data = 2, /*!< Detector data of some variety */
MonitorSync = 3, /*!< Statistics synchronized across contributors */
MonitorUnSync = 4 /*!< Statistics for a single contributor */
};
/* ---------------------------------------------------------------------- */
static const uint32_t Pattern = 0x8b309e;
/* ---------------------------------------------------------------------- *//*!
*/
/* ---------------------------------------------------------------------- */
class Identifier
{
/* ------------------------------------------------------------------- *//*!
\enum class FormatType
\brief This enumerates the identifier formats. It is really more
for documentation than usage
*/
/* ------------------------------------------------------------------- */
enum class FormatType
{
_0 = 0, /*!< Only 1 source identifier */
_1 = 1 /*!< Two source identifiers */
};
/* ------------------------------------------------------------------- */
public:
Identifier () { return; }
Identifier (uint8_t type,
uint16_t src,
uint32_t sequence,
uint64_t timestamp) :
Identifier (FormatType::_0, type, src, 0, sequence, timestamp) { return; }
Identifier (uint16_t type,
uint16_t src0,
uint16_t src1,
uint32_t sequence,
uint64_t timestamp) :
Identifier (FormatType::_1, type, src0, src1, sequence, timestamp) { return; }
Identifier (enum FormatType format,
uint8_t type,
uint16_t src0,
uint16_t src1,
uint32_t sequence,
uint64_t timestamp) :
m_w64 (compose (static_cast<int>(format), type, src0, src1, sequence)),
m_timestamp (timestamp)
{
return;
}
Identifier (Identifier const &identifier)
{
*this = identifier;
}
enum class Size
{
Format = 4, /*!< Size of the format field */
Type = 4, /*!< Trigger Type */
Src0 = 12, /*!< Channel bundle 0 source identifier (from WIB) */
Src1 = 12, /*!< Channel bundle 1 source identified (from WIB) */
Sequence = 32 /*!< Overall sequence number */
};
enum class Mask : uint32_t
{
Format = 0x0000000f,
Type = 0x0000000f,
Src0 = 0x00000fff,
Src1 = 0x00000fff,
Sequence = 0xffffffff
};
enum Offset
{
Format = 0,
Type = 4,
Src0 = 8,
Src1 = 20,
Sequence = 32
};
void construct (uint8_t type,
uint16_t src0,
uint16_t src1,
uint32_t sequence,
uint64_t timestamp)
{
m_w64 = compose (static_cast<int>(FormatType::_1),
type,
src0,
src1,
sequence);
m_timestamp = timestamp;
/*
fprintf (stderr,
"Identifier.m_64 = %16.16" PRIx64 " ts = %16.16" PRIx64 "\n",
m_w64,
m_timestamp);
*/
}
static uint64_t compose (int format,
uint8_t type,
uint16_t src0,
uint16_t src1,
uint32_t sequence)
{
uint64_t w64 =
PDD_INSERT64 (Mask::Format, Offset::Format, format)
| PDD_INSERT64 (Mask::Type, Offset::Type, type)
| PDD_INSERT64 (Mask::Src0, Offset::Src0, src0)
| PDD_INSERT64 (Mask::Src1, Offset::Src1, src1)
| PDD_INSERT64 (Mask::Sequence, Offset::Sequence, sequence);
return w64;
}
void construct (uint16_t src0, uint16_t src1)
{
m_w64 &= ~static_cast<uint64_t>(Mask ::Src0)
<< static_cast<uint64_t>(Offset::Src0);
m_w64 &= ~static_cast<uint64_t>(Mask ::Src1)
<< static_cast<uint64_t>(Offset::Src1);
m_w64 = PDD_INSERT64 (Mask::Src0, Offset::Src0, src0)
| PDD_INSERT64 (Mask::Src1, Offset::Src1, src1);
return;
}
public:
uint64_t m_w64; /*!< 64-bit packed word of format,srcs, sequence */
uint64_t m_timestamp; /*!< The identifying timestamp */
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\brief Template class for Fragment Headers
This class is specialized for the various types of fragment headers
*/
/* ---------------------------------------------------------------------- */
template<enum fragment::Type TYPE>
class Header : public Header0
{
public:
Header (uint8_t subtype,
uint32_t bridge,
int naux64,
uint32_t n64) :
Header0 (static_cast<int>(TYPE), subtype, bridge, naux64, n64)
{
return;
}
static uint64_t compose (uint8_t subtype,
uint8_t naux64,
uint32_t n64);
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\brief Template class for Fragment Trailers
*/
/* ---------------------------------------------------------------------- */
template<enum fragment::Type TYPE>
class Trailer
{
public:
static uint64_t compose (uint8_t subtype,
int naxu64,
uint32_t n64);
public:
uint64_t m_w64;
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\brief Specialized fragment header for Data
*/
/* ---------------------------------------------------------------------- */
template<>
class Header<fragment::Type::Data> : public Header0
{
public:
enum class RecType
{
Reserved_0 = 0, /*!< Reserved for future use */
Originator = 1, /*!< Originator record type */
TpcNormal = 2, /*!< Normal TPC data, \e i.e. no errors */
TpcDamaged = 3 /*!< Damaged TPC data, \e i.e. has errors */
};
public:
Header<fragment::Type::Data> (RecType rectype,
Identifier const &identifier,
uint32_t n64) :
Header0 (static_cast<int>(fragment::Type::Data),
static_cast<uint8_t>(rectype),
fragment::Pattern,
(sizeof (identifier))/ sizeof (uint64_t),
n64),
m_identifier (identifier)
{
return;
}
Header<fragment::Type::Data> (RecType rectype) :
Header0 (static_cast<int>(fragment::Type::Data),
static_cast<uint8_t>(rectype),
fragment::Pattern,
sizeof (struct Identifier) / sizeof (uint64_t),
0),
m_identifier ()
{
return;
}
Header<fragment::Type::Data> () :
Header0 (static_cast<int>(fragment::Type::Data),
sizeof (struct Identifier) / sizeof (uint64_t),
0,
fragment::Pattern,
0),
m_identifier ()
{
return;
}
void construct (RecType rectype,
Identifier const &identifier,
uint32_t n64)
{
m_w64 = Header0::compose (static_cast<int>(fragment::Type::Data),
static_cast<uint8_t>(rectype),
fragment::Pattern,
sizeof (m_identifier) / sizeof (uint64_t),
n64);
m_identifier = identifier;
return;
}
void construct (uint16_t src0,
uint16_t src1)
{
m_identifier.construct (src0, src1);
return;
}
void construct (RecType rectype,
uint8_t type,
uint16_t src0,
uint16_t src1,
uint32_t sequence,
uint64_t timestamp,
uint32_t n64)
{
m_w64 = Header0::compose (static_cast<int>(fragment::Type::Data),
static_cast<uint8_t>(rectype),
fragment::Pattern,
sizeof (m_identifier) / sizeof (uint64_t),
n64);
//fprintf (stderr, "Header.m_64 %16.16" PRIx64 "\n", m_w64);
m_identifier.construct (type, src0, src1, sequence, timestamp);
return;
}
public:
Identifier m_identifier;
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- */
class Version
{
public:
Version () { return; }
Version (uint32_t firmware,
uint32_t software) :
m_w64 (compose (firmware, software))
{
return;
}
static uint64_t compose (uint32_t firmware, uint32_t software)
{
uint64_t version = software;
version <<= 32;
version |= firmware;
//fprintf (stderr, "Version %16.16" PRIx64 "\n", version);
return version;
}
void construct (uint32_t firmware, uint32_t software)
{
m_w64 = compose (firmware, software);
return;
}
static uint32_t firmware (uint64_t m_64) { return m_64 >> 0; }
static uint32_t software (uint64_t m_64) { return m_64 >> 32; }
uint32_t software () const { return software (m_w64); }
uint32_t firmware () const { return firmware (m_w64); }
public:
uint64_t m_w64;
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\class OriginatorBody
\brief The hardware, software and geographic information about this
datas orginator
*/
/* ---------------------------------------------------------------------- */
class OriginatorBody
{
public:
OriginatorBody () { return; }
int construct (uint32_t fw_version,
uint32_t sw_version,
char const *rptSwTag,
uint8_t nrptSwTag,
uint64_t serialNumber,
uint32_t location,
char const *groupName,
uint8_t ngroupName)
{
m_location = location;
m_version.construct (fw_version, sw_version);
m_serialNumber = serialNumber;
strncpy (m_strings, rptSwTag, nrptSwTag + 1);
strncpy (m_strings + nrptSwTag + 1, groupName, ngroupName + 1);
int size = sizeof (OriginatorBody)
- sizeof (m_strings) + nrptSwTag + ngroupName + 2;
return size;
}
uint32_t location () const { return m_location; }
uint64_t serialNumber () const { return m_serialNumber; }
Version const &version () const { return m_version; }
char const *rptSwTag () const { return m_strings; }
char const *groupName () const { return &m_strings [strlen(rptSwTag()) + 1]; }
public:
uint32_t m_location;
uint64_t m_serialNumber;
Version m_version;
char m_strings[32+32];
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\class Originator
\brief Information about the physical entity (RCE) producing the data
and the software and firmware running on it
*/
/* ---------------------------------------------------------------------- */
class Originator : public Header2
{
static const int Version = 0;
public:
Originator () { return; }
int construct (uint32_t fw_version,
uint32_t sw_version,
char const *rptSwTag,
uint8_t nrptSwTag,
uint64_t serialNumber,
uint32_t location,
char const *groupName,
uint8_t ngroupName)
{
//fprintf (stderr, "Fw/Sw = %8.8" PRIx32 " %8.8" PRIx32 "\n", fw_version, sw_version);
int size = m_body.construct (fw_version,
sw_version,
rptSwTag,
nrptSwTag,
serialNumber,
location,
groupName,
ngroupName);
size += sizeof (Header2);
Header2::construct (static_cast<int>
(Header<fragment::Type::Data>::RecType::Originator),
(size + sizeof (uint64_t) - 1) / sizeof (uint64_t),
Version);
return size;
}
public:
OriginatorBody m_body;
} __attribute__ ((packed));
/* ---------------------------------------------------------------------- */
}
template<enum fragment::Type TYPE>
inline uint64_t fragment::Header<TYPE>:: compose (uint8_t subtype,
uint8_t naux64,
uint32_t n64)
{
uint64_t w64 = Header0::compose (static_cast<int>(TYPE),
subtype,
fragment::Pattern,
naux64,
n64);
return w64;
}
template<enum fragment::Type TYPE>
inline uint64_t fragment::Trailer<TYPE>::compose (uint8_t subtype,
int naux64,
uint32_t n64)
{
uint32_t bridge = fragment::Pattern;
uint64_t w64 =
PDD_INSERT64C (Header0::Mask::Format, Header0::Offset::Format, 0)
| PDD_INSERT64C (Header0::Mask::Type, Header0::Offset::Type, TYPE)
| PDD_INSERT64C (Header0::Mask::NAux64, Header0::Offset::NAux64, naux64)
| PDD_INSERT64C (Header0::Mask::SubType, Header0::Offset::SubType, subtype)
| PDD_INSERT64C (Header0::Mask::Bridge, Header0::Offset::Bridge, bridge)
| PDD_INSERT64C (Header0::Mask::Length, Header0::Offset::Length, n64);
return w64;
}
/*
#undef PDD_INSERT
#undef PDD_INSERTC
#undef PDD_INSERT32
#undef PDD_INSERT32C
#undef PDD_INSERT64
#undef PDD_INSERT64C
*/
}
#endif
| 32.739247 | 92 | 0.396393 | slaclab |
744480da91eb8d6f0692e774d08cee2a0fe4b699 | 1,590 | hpp | C++ | src/whiteboard/validate_visitor.hpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | 12 | 2015-03-04T15:07:00.000Z | 2019-09-13T16:31:06.000Z | src/whiteboard/validate_visitor.hpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | null | null | null | src/whiteboard/validate_visitor.hpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | 5 | 2017-04-22T08:16:48.000Z | 2020-07-12T03:35:16.000Z | /* $Id: validate_visitor.hpp 49264 2011-04-17 22:56:44Z gabba $ */
/*
Copyright (C) 2010 - 2011 by Gabriel Morin <gabrielmorin (at) gmail (dot) com>
Part of the Battle for Wesnoth Project http://www.wesnoth.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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.
See the COPYING file for more details.
*/
/**
* @file
*/
#ifndef WB_VALIDATE_VISITOR_HPP_
#define WB_VALIDATE_VISITOR_HPP_
#include "mapbuilder_visitor.hpp"
#include <set>
namespace wb
{
/**
* Visits all the actions in the given side_actions, building a future unit map as it goes,
* and checking the validity of each action.
*/
class validate_visitor: public mapbuilder_visitor
{
public:
validate_visitor(unit_map& unit_map, side_actions_ptr side_actions);
virtual ~validate_visitor();
/// @return false some actions had to be deleted during validation,
/// which may warrant a second validation
bool validate_actions();
virtual void visit_move(move_ptr move);
virtual void visit_attack(attack_ptr attack);
virtual void visit_recruit(recruit_ptr recruit);
virtual void visit_recall(recall_ptr recall);
virtual void visit_suppose_dead(suppose_dead_ptr sup_d);
private:
std::set<action_ptr> actions_to_erase_;
};
}
#endif /* WB_VALIDATE_VISITOR_HPP_ */
| 27.894737 | 92 | 0.738994 | blackberry |
74450473b1fb8489b94dd3ed8ea8f84c0f64af17 | 3,613 | cc | C++ | cpp/hackranker/h30.cc | staugust/leetcode | 0ddd0b0941e596d3c6a21b6717d0dd193025f580 | [
"Apache-2.0"
] | null | null | null | cpp/hackranker/h30.cc | staugust/leetcode | 0ddd0b0941e596d3c6a21b6717d0dd193025f580 | [
"Apache-2.0"
] | null | null | null | cpp/hackranker/h30.cc | staugust/leetcode | 0ddd0b0941e596d3c6a21b6717d0dd193025f580 | [
"Apache-2.0"
] | null | null | null | /*
*
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <cstdio>
#include <map>
#include <set>
#include <deque>
#include <queue>
using namespace std;
vector<int> closestNumbers(vector<int> arr) {
int diff = 0x3f3f3f3f;
std::sort(arr.begin(), arr.end());
std::vector<int> res;
for (int i = 1; i < arr.size(); i++) {
diff = diff < arr[i] - arr[i - 1] ? diff : arr[i] - arr[i - 1];
}
for (int i = 1; i < arr.size(); i++) {
if (arr[i] - arr[i - 1] == diff) {
res.push_back(arr[i - 1]);
res.push_back(arr[i]);
}
}
return res;
}
string gameOfThrones(string s) {
vector<int> vec(26, 0);
for (auto c : s) {
vec[c - 'a'] += 1;
}
int odd = 0;
for (auto k : vec) {
odd += (k % 2);
}
if (odd == 0 || odd == 1)
{
return "YES";
}
return "NO";
}
string twoStrings(string s1, string s2) {
vector<int> vec(26, 0);
for (auto c : s1) {
vec[c - 'a'] = 1;
}
for (auto c : s2) {
if (vec[c - 'a'] == 1) {
return "YES";
}
}
return "NO";
}
int stringConstruction(string s) {
vector<int> vec(26, 0);
int cnt = 0;
for (auto c : s) {
if (vec[c - 'a'] == 0) {
cnt += 1;
vec[c - 'a'] = 1;
}
}
return cnt;
}
vector<int> icecreamParlor(int m, vector<int> arr) {
map<int, pair<int, int> > mp;
for (int i = 0; i < arr.size() ; i++) {
for (int j = i+1; j < arr.size(); j++) {
if ((arr[i] + arr[j]) == m) {
return { i + 1, j + 1 };
}
}
}
for (int i = 0; i < arr.size(); i++) {
if (arr[i] * 2 == m) {
return { i + 1, i + 1 };
}
}
return { 0, 0 };
}
string balancedSums(vector<int> arr) {
int right = 0;
for (auto k : arr) {
right += k;
}
int left = 0;
for (int i = 0; i < arr.size(); i++) {
if ( left == (right - arr[i])) {
return "YES";
}
left += arr[i];
right -= arr[i];
}
return "NO";
}
int minimumAbsoluteDifference(vector<int> arr) {
sort(arr.begin(), arr.end());
int mn = 0x3f3f3f3f;
for (int i = 1; i < arr.size(); i++) {
mn = mn < (arr[i] - arr[i - 1]) ? mn : arr[i] - arr[i - 1];
}
return mn;
}
long marcsCakewalk(vector<int> calorie) {
sort(calorie.begin(), calorie.end());
long cnt = 0;
long base = 1;
for (auto i = calorie.rbegin(); i != calorie.rend(); i++) {
cnt += base * *i;
base *= 2;
}
return cnt;
}
string gridChallenge(vector<string> grid) {
for (int i = 0; i < grid.size(); i++) {
sort(grid[i].begin(), grid[i].end());
}
int m = grid.size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < m -1; j++) {
if (grid[j + 1][i] < grid[j][i]) {
return "NO";
}
}
}
return "YES";
}
int luckBalance(int k, vector<vector<int>> contests) {
vector<int> imp;
int luck = 0;
for (auto & v : contests) {
if (v[1] == 1) {
imp.push_back(v[0]);
}
else {
luck += v[0];
}
}
if (imp.size() <= k) {
for (int i = 0; i < imp.size(); i++) {
luck += imp[i];
}
}
else {
sort(imp.begin(), imp.end());
int t = imp.size() - k;
for (int i = 0; i < t; i++) {
luck -= imp[i];
}
for (int i = t; i < imp.size(); i++) {
luck += imp[i];
}
}
return luck;
}
vector<int> maximumPerimeterTriangle(vector<int> sticks) {
sort(sticks.begin(), sticks.end());
int k = sticks.size() - 1;
for (; k - 1 > 0; k--) {
if (sticks[k] < (sticks[k - 1] + sticks[k - 2])) {
return { sticks[k - 2] , sticks[k - 1] , sticks[k] };
}
}
return { -1 };
}
int main_h30() {
string s = "abcdefghijklmn";
reverse(s.begin(), s.end());
std::cout << s << std::endl;
auto k = closestNumbers({ -5, 15, 25, 71, 63
}) ;
for (auto i : k) {
std::cout << i << std::endl;
}
return 0;
} | 18.065 | 65 | 0.51121 | staugust |
74475242e369b0e9625b44109b4a69ee8a647456 | 1,992 | cpp | C++ | RiocArduino/RORudderServo.cpp | robinz-labs/rioc-arduino | 37e752cfc5cf13a61dd03b4556cf33aa18d24814 | [
"Apache-2.0"
] | null | null | null | RiocArduino/RORudderServo.cpp | robinz-labs/rioc-arduino | 37e752cfc5cf13a61dd03b4556cf33aa18d24814 | [
"Apache-2.0"
] | null | null | null | RiocArduino/RORudderServo.cpp | robinz-labs/rioc-arduino | 37e752cfc5cf13a61dd03b4556cf33aa18d24814 | [
"Apache-2.0"
] | null | null | null | #include "RORudderServo.h"
#include "RiocMessager.h"
#include <Servo.h>
RORudderServo::RORudderServo()
{
_pin = -1;
_mode = -1;
_enabled = false;
_servo = NULL;
}
RORudderServo::~RORudderServo()
{
}
bool RORudderServo::setup(byte msg[8], byte address_from)
{
if (_pin != -1) return false;
int pin = msg[2];
int mode = msg[3];
if (pin<=DO_PIN_MAX_NUMBER) {
_pin = pin;
_mode = mode;
_enabled = false;
_servo = new Servo();
return true;
}
return false;
}
void RORudderServo::execute(byte msg[8], byte address_from)
{
if (_pin == -1) return;
int cmd = msg[1];
if (cmd==0x01) {
// SET ANGLE
int angle = msg[3];
if (angle > 180) angle = 180;
_servo->write(angle);
// enable the servo as soon as write the first angle
if (!_enabled) setEnabled(true);
if (!isSilent()) {
byte rsp[] = {0x13, 0x81, _pin, angle, 0, 0, 0, 0};
if (_messager!=NULL) _messager->sendMessage(rsp, address_from);
}
} else if (cmd==0x02) {
// GET ANGLE
int angle = _servo->read();
byte rsp[] = {0x13, 0x82, _pin, angle, 0, 0, 0, 0};
if (_messager!=NULL) _messager->sendMessage(rsp, address_from);
} else if (cmd==0x03) {
// SET ENABLE
bool enabled = msg[3];
setEnabled(enabled);
if (!isSilent()) {
byte rsp[] = {0x13, 0x83, _pin, enabled, 0, 0, 0, 0};
if (_messager!=NULL) _messager->sendMessage(rsp, address_from);
}
} else if (cmd==0x04) {
// GET ENABLE
bool enabled = _enabled; //_servo->attached();
byte rsp[] = {0x13, 0x84, _pin, enabled, 0, 0, 0, 0};
if (_messager!=NULL) _messager->sendMessage(rsp, address_from);
}
}
void RORudderServo::process()
{
}
void RORudderServo::setAngle(int angle)
{
_servo->write(angle);
}
void RORudderServo::setEnabled(bool enabled)
{
if (enabled == _enabled) return;
if (enabled) {
_servo->attach(_pin);
} else {
_servo->detach();
}
_enabled = enabled;
}
| 17.628319 | 69 | 0.593876 | robinz-labs |
74485ee42af47b6f7f1fa36e60760bd3cbf9a4ad | 4,787 | cpp | C++ | BossAttack1_DomJudge/BA1_B_html lexer.cpp | Ping6666/Compiler-Projects | 31c7c437a2fad66b7b7424d9b2a468b61d94fdd3 | [
"MIT"
] | 1 | 2021-11-21T15:52:23.000Z | 2021-11-21T15:52:23.000Z | BossAttack1_DomJudge/BA1_B_html lexer.cpp | Ping6666/Compiler-Projects | 31c7c437a2fad66b7b7424d9b2a468b61d94fdd3 | [
"MIT"
] | null | null | null | BossAttack1_DomJudge/BA1_B_html lexer.cpp | Ping6666/Compiler-Projects | 31c7c437a2fad66b7b7424d9b2a468b61d94fdd3 | [
"MIT"
] | null | null | null | #include <iostream>
// all test case will be legal
std::string inputString;
void stringManipulate()
{
bool set = false;
for (int i = 0; i < (int)inputString.length(); i++)
{
if (set)
{
if (inputString[i] == ' ')
{
inputString.erase(inputString.begin() + i);
i--;
}
else
{
set = false;
}
}
else
{
if (inputString[i] == ' ')
{
set = true;
}
}
}
return;
}
int main()
{
inputString.clear();
while (true)
{
char ch = getchar();
if (ch == EOF)
{
break;
}
else if (ch == '\n')
{
inputString += " ";
}
else
{
inputString += ch;
}
}
stringManipulate();
bool inTagDef = false;
int id_now = 0;
bool firstPrint = false;
bool QUOTE_STRING = false;
while (true)
{
if (id_now >= inputString.length())
{
break;
}
if ((id_now + 1 < inputString.length()) && (inputString[id_now] == '<') && (inputString[id_now + 1] == '/'))
{
inTagDef = true;
if (firstPrint)
{
std::cout << "\n";
firstPrint = false;
}
std::cout << "TAG_OPEN_SLASH </\n";
id_now += 1;
}
else if (inputString[id_now] == '<')
{
inTagDef = true;
if (firstPrint)
{
std::cout << "\n";
firstPrint = false;
}
std::cout << "TAG_OPEN <\n";
}
else if (inputString[id_now] == '>')
{
inTagDef = false;
if (firstPrint)
{
std::cout << "\n";
firstPrint = false;
}
std::cout << "TAG_CLOSE >\n";
}
else if (inputString[id_now] == '=')
{
if (firstPrint)
{
std::cout << "\n";
firstPrint = false;
}
std::cout << "TAG_EQUALS =\n";
}
else if (inputString[id_now] == '\'' && inTagDef == true) // 1
{
inTagDef = false;
QUOTE_STRING = true;
if (firstPrint)
{
std::cout << "\n";
firstPrint = false;
}
// firstPrint = false;
std::cout << "SINGLE_QUOTE_STRING ";
}
else if (inputString[id_now] == '\'' && inTagDef == false && QUOTE_STRING == true) // 2
{
inTagDef = true;
QUOTE_STRING = false;
}
else if (inputString[id_now] == '"' && inTagDef == true) // 1
{
inTagDef = false;
QUOTE_STRING = true;
if (firstPrint)
{
std::cout << "\n";
firstPrint = false;
}
// firstPrint = false;
std::cout << "DOUBLE_QUOTE_STRING ";
}
else if (inputString[id_now] == '"' && inTagDef == false && QUOTE_STRING == true) // 2
{
inTagDef = true;
QUOTE_STRING = false;
}
else if (inputString[id_now] == ' ')
{
// continue;
if (inTagDef)
{
std::cout << "\n";
// inTagDef = false;
firstPrint = false;
}
else if (firstPrint)
{
std::cout << " ";
}
}
else if (inTagDef) // generate TAG_NAME token
{
if (!firstPrint)
{
firstPrint = true;
std::cout << "TAG_NAME ";
}
std::cout << inputString[id_now];
}
else // generate HTML_TEXT token
{
if ((QUOTE_STRING) && (inputString[id_now] == '\'' || inputString[id_now] == '"'))
{
QUOTE_STRING = false;
}
else
{
if (QUOTE_STRING)
{
firstPrint = true;
}
if ((!firstPrint) && (!QUOTE_STRING))
{
firstPrint = true;
std::cout << "HTML_TEXT ";
}
std::cout << inputString[id_now];
}
}
id_now += 1;
}
return 0;
}
| 25.328042 | 117 | 0.350742 | Ping6666 |
7449afbe93d4d2665437c7985ae6933b724e1722 | 75 | cc | C++ | project2/kernels/grad_case9.cc | beizai/CompilerProject2 | 07c99fd0ff0a0f66ac470ded5d11470b1c473b97 | [
"MIT"
] | 26 | 2020-05-11T09:00:41.000Z | 2021-08-25T16:58:42.000Z | project2/kernels/grad_case9.cc | beizai/CompilerProject2 | 07c99fd0ff0a0f66ac470ded5d11470b1c473b97 | [
"MIT"
] | 2 | 2020-05-10T12:23:30.000Z | 2020-06-12T03:20:41.000Z | project2/kernels/grad_case9.cc | beizai/CompilerProject2 | 07c99fd0ff0a0f66ac470ded5d11470b1c473b97 | [
"MIT"
] | 30 | 2020-05-10T05:45:23.000Z | 2022-03-10T16:18:33.000Z | #include "../run2.h"
void grad_case9(float (&dB)[4][6], float (&dA)[4]) {} | 25 | 53 | 0.573333 | beizai |
744a5e4308eec88c6cb7e9e2fd2180a177630fb5 | 564 | cpp | C++ | src/FileManager.cpp | Crupette/decent-engine | 9934df33e8f1e87adf7298baa731c48eee2b2b5b | [
"Apache-2.0"
] | null | null | null | src/FileManager.cpp | Crupette/decent-engine | 9934df33e8f1e87adf7298baa731c48eee2b2b5b | [
"Apache-2.0"
] | null | null | null | src/FileManager.cpp | Crupette/decent-engine | 9934df33e8f1e87adf7298baa731c48eee2b2b5b | [
"Apache-2.0"
] | null | null | null | #include "FileManager.h"
#include <fstream>
namespace DecentEngine {
void FileManager::dumpFile(const std::string& filePath, std::vector<unsigned char>& contents){
std::ifstream file(filePath, std::ios::binary);
if(file.fail()){
//TODO: Add logger message with [WARN] tag
printf("Failed to dump file contents into vector.\nError is as follows:\n404 FILE NOT FOUND");
return;
}
file.seekg(0, std::ios::end);
size_t len = file.tellg();
file.seekg(0, std::ios::beg);
contents.resize(len);
file.read((char*)(&contents[0]), len);
file.close();
}
}
| 20.888889 | 95 | 0.689716 | Crupette |
744d0e53844aa1c5688e86825db28154e7cbf751 | 2,909 | cpp | C++ | fucapi2Bimestre/teste2.cpp | taynarodrigues/OpenGL | c1309835313f2a00b07668cfddbea21a26c5b21f | [
"MIT"
] | 2 | 2020-04-05T02:38:14.000Z | 2020-04-05T02:48:18.000Z | fucapi2Bimestre/teste2.cpp | taynarodrigues/OpenGL--Computacao-Grafica | c1309835313f2a00b07668cfddbea21a26c5b21f | [
"MIT"
] | null | null | null | fucapi2Bimestre/teste2.cpp | taynarodrigues/OpenGL--Computacao-Grafica | c1309835313f2a00b07668cfddbea21a26c5b21f | [
"MIT"
] | null | null | null | // Fazer código OpenGL para gerar pelo menos duas das seguintes curvas de Bezier (ver imagem).
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdlib.h>
#include <GL/glut.h>
GLfloat ctrlpoints2[4][3]={
{ 0.0, 0.0, 0.0},
{-2.0, 0.3, 0.0},
{-3.0,-1.0, 0.0},
{-4.0, 4.0, 0.0}
};
GLfloat ctrlpoints6[4][3]={
{ 0.0, 0.0, 0.0},
{-2.0,-0.3, 0.0},
{-3.0, 1.0, 0.0},
{-4.0,-4.0, 0.0}
};
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
/*A forma de trabalhar com curvas por partes de forma geral é a seguinte
1. Você define os pontos de controle
2. Define as funções paramétricas da curva usando glMap1f()
3. Desenha a curva usando glEvalCoord1f() para avaliar os parâmetros nas funções paramétricas previamente criadas com glMap1f()
Este processo se deve repetir para cada curva, primeiro glMap1f() depois glEvalCoord1f() para a primeira curva, depois glMap1f() e
glEvalCoord1f() para a segunda e assim
*/
glEnable(GL_MAP1_VERTEX_3);
}
void display(void)
{
int i;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glMap1f(GL_MAP1_VERTEX_3, 0.0,1.0,3,4, &ctrlpoints2[0][0]);
glEnable(GL_MAP1_VERTEX_3);//
glBegin(GL_LINE_STRIP);
for (i = 0; i <= 30; i++)
glEvalCoord1f((GLfloat) i/30.0);
glEnd();
glPointSize(6.0f); //tamanho do ponto verde O código a seguir exibe os pontos de controle como pontos /
// glColor3f(0.0, 1.0, 0.0);
glBegin(GL_POINTS);
for (i = 0; i < 4; i++)
glVertex3fv(&ctrlpoints2[i][0]);
glEnd();
//CURVA 2
//O grau da curva têm que ser 3, pelo que a quantidade de pontos de controle é 4.
glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, &ctrlpoints6[0][0]);
glColor3f(0.0, 1.0, 0.0); //COR VERDE
glBegin(GL_LINE_STRIP);
for (int j = 0; j <= 30; j++) {
glEvalCoord1f((GLfloat)j / 30.0);
}
glEnd();
glBegin(GL_POINTS);
for (int i = 0; i < 6; i++) {
glVertex3fv(&ctrlpoints6[i][0]);
}
glEnd();
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-5.0, 5.0, -5.0*(GLfloat)h/(GLfloat)w,
5.0*(GLfloat)h/(GLfloat)w, -5.0, 5.0);
else
glOrtho(-5.0*(GLfloat)w/(GLfloat)h,
5.0*(GLfloat)w/(GLfloat)h, -5.0, 5.0, -5.0, 5.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow("Curva de Bezier "); //cria a janela
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
// g++ teste2.cpp -o firstOpenGlApp -lglut -lGLU -lGL
// ./firstOpenGlApp | 26.688073 | 131 | 0.609144 | taynarodrigues |
744d653f35c31e92367a03887fa714945000de7b | 9,781 | cpp | C++ | 11_learning_materials/stanford_self_driving_car/perception/descriptors_3d/src/shared/spectral_analysis.cpp | EatAllBugs/autonomous_learning | 02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47 | [
"MIT"
] | 14 | 2021-09-01T14:25:45.000Z | 2022-02-21T08:49:57.000Z | 11_learning_materials/stanford_self_driving_car/perception/descriptors_3d/src/shared/spectral_analysis.cpp | yinflight/autonomous_learning | 02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47 | [
"MIT"
] | null | null | null | 11_learning_materials/stanford_self_driving_car/perception/descriptors_3d/src/shared/spectral_analysis.cpp | yinflight/autonomous_learning | 02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47 | [
"MIT"
] | 3 | 2021-10-10T00:58:29.000Z | 2022-01-23T13:16:09.000Z | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <descriptors_3d/shared/spectral_analysis.h>
using namespace std;
// --------------------------------------------------------------
/* See function definition */
// --------------------------------------------------------------
SpectralAnalysis::SpectralAnalysis(double support_radius)
{
support_radius_ = support_radius;
spectral_computed_ = false;
}
// --------------------------------------------------------------
/* See function definition */
// --------------------------------------------------------------
SpectralAnalysis::~SpectralAnalysis()
{
clearSpectral();
}
// --------------------------------------------------------------
/* See function definition */
// --------------------------------------------------------------
void SpectralAnalysis::clearSpectral()
{
unsigned int nbr_data = normals_.size();
for (unsigned int i = 0 ; i < nbr_data ; i++)
{
if (normals_[i] != NULL)
{
delete normals_[i];
delete middle_eig_vecs_[i];
delete tangents_[i];
delete eigenvalues_[i];
}
}
normals_.clear();
middle_eig_vecs_.clear();
tangents_.clear();
eigenvalues_.clear();
spectral_computed_ = false;
}
// --------------------------------------------------------------
/* See function definition */
// --------------------------------------------------------------
int SpectralAnalysis::analyzeInterestPoints(const sensor_msgs::PointCloud& data,
cloud_kdtree::KdTree& data_kdtree,
const vector<const geometry_msgs::Point32*>& interest_pts)
{
if (spectral_computed_)
{
ROS_ERROR("SpectralAnalysis::analyzeInterestPoints() spectral info already exists");
return -1;
}
// ----------------------------------------
// Ensure some regions are provided
unsigned int nbr_interest_pts = interest_pts.size();
// ----------------------------------------
// Ensure radius is valid
if (support_radius_ < 1e-6)
{
ROS_ERROR("SpectralAnalysis::analyzeInterestPoints() support radius must be set to a positive value");
return -1;
}
// ----------------------------------------
// Allocate accordingly
normals_.assign(nbr_interest_pts, NULL);
middle_eig_vecs_.assign(nbr_interest_pts, NULL);
tangents_.assign(nbr_interest_pts, NULL);
eigenvalues_.assign(nbr_interest_pts, NULL);
// ----------------------------------------
// Find neighboring points within radius for each interest point
int int_nbr_interest_pts = static_cast<int> (nbr_interest_pts);
#pragma omp parallel for schedule(dynamic)
for (int i = 0 ; i < int_nbr_interest_pts ; i++)
{
// ---------------------
// Retrieve next interest point
const geometry_msgs::Point32* curr_interest_pt = interest_pts[static_cast<size_t> (i)];
if (curr_interest_pt == NULL)
{
ROS_WARN("SpectralAnalysis::analyzeInterestPoints() passed NULL interest point");
}
else
{
// ---------------------
// Retrieve neighboring points around the interest point
vector<int> neighbor_indices;
vector<float> neighbor_distances; // unused
// radiusSearch returning false (0 neighbors) is okay
data_kdtree.radiusSearch(*curr_interest_pt, support_radius_, neighbor_indices, neighbor_distances);
// ---------------------
// Compute spectral information for interest point
computeSpectralInfo(data, neighbor_indices, static_cast<size_t> (i));
}
}
spectral_computed_ = true;
return 0;
}
// --------------------------------------------------------------
/* See function definition */
// --------------------------------------------------------------
int SpectralAnalysis::analyzeInterestRegions(const sensor_msgs::PointCloud& data,
cloud_kdtree::KdTree& data_kdtree,
const vector<const vector<int>*>& interest_region_indices)
{
if (spectral_computed_)
{
ROS_ERROR("SpectralAnalysis::analyzeInterestRegions() spectral info already exists");
return -1;
}
// ----------------------------------------
// Ensure some regions are provided
unsigned int nbr_regions = interest_region_indices.size();
// ----------------------------------------
// Allocate accordingly
normals_.assign(nbr_regions, NULL);
middle_eig_vecs_.assign(nbr_regions, NULL);
tangents_.assign(nbr_regions, NULL);
eigenvalues_.assign(nbr_regions, NULL);
// ----------------------------------------
// For each interest region, either:
// Use the region itself as the support volume
// Find a support volume within a radius from the region's centroid
int int_nbr_regions = static_cast<int> (nbr_regions);
#pragma omp parallel for schedule(dynamic)
for (int i = 0 ; i < int_nbr_regions ; i++)
{
// ---------------------
// Retrieve next interest region
// (By default, use the interest region as the support volume)
const vector<int>* curr_interest_region = interest_region_indices[static_cast<size_t> (i)];
if (curr_interest_region == NULL)
{
ROS_WARN("SpectralAnalysis::analyzeInterestRegions() passed NULL interest region");
}
else
{
// Do a range search around the interest region's CENTROID if indicated
vector<int> neighbor_indices;
if (support_radius_ > 1e-6)
{
// Compute centroid of interest region
geometry_msgs::Point32 region_centroid;
cloud_geometry::nearest::computeCentroid(data, *curr_interest_region, region_centroid);
vector<float> neighbor_distances; // unused
// radiusSearch returning false (0 neighbors) is okay
data_kdtree.radiusSearch(region_centroid, support_radius_, neighbor_indices, neighbor_distances);
// Now point to the neighboring points from radiusSearch
curr_interest_region = &neighbor_indices;
}
// ---------------------
// Compute spectral information for interest region
computeSpectralInfo(data, *curr_interest_region, static_cast<size_t> (i));
}
}
// ----------------------------------------
spectral_computed_ = true;
return 0;
}
// --------------------------------------------------------------
/* See function definition */
// --------------------------------------------------------------
void SpectralAnalysis::computeSpectralInfo(const sensor_msgs::PointCloud& data,
const vector<int>& support_volume_indices,
const size_t idx)
{
// ----------------------------------------
// Need 3-by-3 matrix to have full rank
if (support_volume_indices.size() < 3)
{
ROS_DEBUG("SpectralAnalysis::computeSpectralInfo() not enough neighbors for interest sample %u", idx);
return;
}
// ----------------------------------------
// Allocate for new data
Eigen::Vector3d* new_normal = new Eigen::Vector3d();
Eigen::Vector3d* new_middle_eigvec = new Eigen::Vector3d();
Eigen::Vector3d* new_tangent = new Eigen::Vector3d();
Eigen::Vector3d* new_eig_vals = new Eigen::Vector3d();
// ----------------------------------------
// Eigen-analysis of support volume
// smallest eigenvalue = index 0
geometry_msgs::Point32 centroid;
Eigen::Matrix3d eigen_vectors;
cloud_geometry::nearest::computePatchEigenNormalized(data, support_volume_indices, eigen_vectors,
*(new_eig_vals), centroid);
// ----------------------------------------
// Populate containers
for (unsigned int j = 0 ; j < 3 ; j++)
{
(*(new_normal))[j] = eigen_vectors(j, 0);
(*(new_middle_eigvec))[j] = eigen_vectors(j, 1);
(*(new_tangent))[j] = eigen_vectors(j, 2);
}
// Make unit length
new_normal->normalize();
new_middle_eigvec->normalize();
new_tangent->normalize();
normals_[idx] = new_normal;
middle_eig_vecs_[idx] = new_middle_eigvec;
tangents_[idx] = new_tangent;
eigenvalues_[idx] = new_eig_vals;
}
| 37.190114 | 106 | 0.584296 | EatAllBugs |
744eaa921b450ff9971fcd7e445a537ecab85873 | 4,401 | cpp | C++ | src/game/server/gamemodes/fastcap.cpp | Laxa/teeworlds-race | e206a053bb8396f59792bb5de9e3c53674f6a702 | [
"Zlib"
] | null | null | null | src/game/server/gamemodes/fastcap.cpp | Laxa/teeworlds-race | e206a053bb8396f59792bb5de9e3c53674f6a702 | [
"Zlib"
] | null | null | null | src/game/server/gamemodes/fastcap.cpp | Laxa/teeworlds-race | e206a053bb8396f59792bb5de9e3c53674f6a702 | [
"Zlib"
] | null | null | null | // copyright (c) 2007 magnus auvinen, see licence.txt for more info
#include <engine/shared/config.h>
#include <game/mapitems.h>
#include <game/server/entities/character.h>
#include <game/server/entities/flag.h>
#include <game/server/player.h>
#include <game/server/gamecontext.h>
#include "fastcap.h"
CGameControllerFC::CGameControllerFC(class CGameContext *pGameServer)
: CGameControllerRACE(pGameServer)
{
m_apFlags[0] = 0;
m_apFlags[1] = 0;
for(int i = 0; i < MAX_CLIENTS; i++)
m_apPlFlags[i] = 0;
m_pGameType = "FastCap";
m_GameFlags = GAMEFLAG_TEAMS|GAMEFLAG_FLAGS;
}
bool CGameControllerFC::OnEntity(int Index, vec2 Pos)
{
if(IGameController::OnEntity(Index, Pos))
return true;
int Team = -1;
if(Index == ENTITY_FLAGSTAND_RED) Team = TEAM_RED;
if(Index == ENTITY_FLAGSTAND_BLUE) Team = TEAM_BLUE;
if(Team == -1)
return false;
CFlag *F = new CFlag(&GameServer()->m_World, Team, Pos, 0x0);
m_apFlags[Team] = F;
return true;
}
bool CGameControllerFC::IsOwnFlagStand(vec2 Pos, int Team)
{
for(int fi = 0; fi < 2; fi++)
{
CFlag *F = m_apFlags[fi];
if(F && F->m_Team == Team && distance(F->m_Pos, Pos) < 32)
return true;
}
return false;
}
bool CGameControllerFC::IsEnemyFlagStand(vec2 Pos, int Team)
{
for(int fi = 0; fi < 2; fi++)
{
CFlag *F = m_apFlags[fi];
if(F && F->m_Team != Team && distance(F->m_Pos, Pos) < 32)
return true;
}
return false;
}
int CGameControllerFC::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon)
{
int ID = pVictim->GetPlayer()->GetCID();
if(m_apPlFlags[ID])
{
m_apPlFlags[ID]->Reset();
m_apPlFlags[ID] = 0;
}
return CGameControllerRACE::OnCharacterDeath(pVictim, pKiller, Weapon);
}
void CGameControllerFC::OnCharacterSpawn(class CCharacter *pChr)
{
IGameController::OnCharacterSpawn(pChr);
//full armor
pChr->IncreaseArmor(10);
// give nades
if(!g_Config.m_SvNoItems)
pChr->GiveWeapon(WEAPON_GRENADE, 10);
}
bool CGameControllerFC::CanSpawn(CPlayer *pPlayer, vec2 *pOutPos)
{
CSpawnEval Eval;
// spectators can't spawn
if(pPlayer->GetTeam() == -1)
return false;
Eval.m_FriendlyTeam = pPlayer->GetTeam();
// try first enemy spawns, than normal, than own
EvaluateSpawnType(&Eval, 1+((pPlayer->GetTeam()+1)&1));
if(!Eval.m_Got)
{
EvaluateSpawnType(&Eval, 0);
if(!Eval.m_Got)
EvaluateSpawnType(&Eval, 1+(pPlayer->GetTeam()&1));
}
*pOutPos = Eval.m_Pos;
return Eval.m_Got;
}
bool CGameControllerFC::CanBeMovedOnBalance(int Cid)
{
CCharacter* Character = GameServer()->m_apPlayers[Cid]->GetCharacter();
if(Character)
{
for(int fi = 0; fi < 2; fi++)
{
CFlag *F = m_apFlags[fi];
if(F->m_pCarryingCharacter == Character)
return false;
}
}
return true;
}
bool CGameControllerFC::OnRaceStart(int ID, float StartAddTime, bool Check)
{
CRaceData *p = &m_aRace[ID];
if(p->m_RaceState == RACE_STARTED)
return false;
CGameControllerRACE::OnRaceStart(ID, StartAddTime, false);
m_apPlFlags[ID] = new CFlag(&GameServer()->m_World, GameServer()->m_apPlayers[ID]->GetTeam()^1, GameServer()->GetPlayerChar(ID)->m_Pos, GameServer()->GetPlayerChar(ID));
GameServer()->CreateSoundGlobal(SOUND_CTF_GRAB_EN, ID);
return true;
}
bool CGameControllerFC::OnRaceEnd(int ID, float FinishTime)
{
if(!CGameControllerRACE::OnRaceEnd(ID, FinishTime))
return false;
if(m_apPlFlags[ID])
{
m_apPlFlags[ID]->Reset();
m_apPlFlags[ID] = 0;
// reset pickups
GameServer()->m_apPlayers[ID]->m_ResetPickups = true;
// sound \o/
GameServer()->CreateSoundGlobal(SOUND_CTF_CAPTURE, ID);
}
return true;
}
void CGameControllerFC::Snap(int SnappingClient)
{
IGameController::Snap(SnappingClient);
CNetObj_GameData *pGameDataObj = (CNetObj_GameData *)Server()->SnapNewItem(NETOBJTYPE_GAMEDATA, 0, sizeof(CNetObj_GameData));
if(!pGameDataObj)
return;
pGameDataObj->m_TeamscoreRed = 0;
pGameDataObj->m_TeamscoreBlue = 0;
if(m_apPlFlags[SnappingClient])
{
if(m_apPlFlags[SnappingClient]->m_Team == TEAM_RED)
{
pGameDataObj->m_FlagCarrierRed = SnappingClient;
pGameDataObj->m_FlagCarrierBlue = FLAG_MISSING;
}
else if(m_apPlFlags[SnappingClient]->m_Team == TEAM_BLUE)
{
pGameDataObj->m_FlagCarrierBlue = SnappingClient;
pGameDataObj->m_FlagCarrierRed = FLAG_MISSING;
}
}
else
{
pGameDataObj->m_FlagCarrierRed = FLAG_MISSING;
pGameDataObj->m_FlagCarrierBlue = FLAG_MISSING;
}
}
| 23.163158 | 170 | 0.709611 | Laxa |
744f12933dbb03e1ceacea733c451b8287ce1b12 | 3,026 | hpp | C++ | Chapter 8/Abbrevia/source/hpp/Win32/Debug/AbbreviaD.hpp | PacktPublishing/Delphi-High-Performance | bcb84190e8660a28cbc0caada2e1bed3b8adfe42 | [
"MIT"
] | 45 | 2018-04-08T07:01:13.000Z | 2022-02-18T17:28:10.000Z | Chapter 8/Abbrevia/source/hpp/Win32/Release/AbbreviaD.hpp | anomous/Delphi-High-Performance | 051a8f7d7460345b60cb8d2a10a974ea8179ea41 | [
"MIT"
] | null | null | null | Chapter 8/Abbrevia/source/hpp/Win32/Release/AbbreviaD.hpp | anomous/Delphi-High-Performance | 051a8f7d7460345b60cb8d2a10a974ea8179ea41 | [
"MIT"
] | 17 | 2018-03-21T11:22:15.000Z | 2022-03-16T05:55:54.000Z | // CodeGear C++Builder
// Copyright (c) 1995, 2016 by Embarcadero Technologies, Inc.
// All rights reserved
// (DO NOT EDIT: machine generated header) 'AbbreviaD.dpk' rev: 31.00 (Windows)
#ifndef AbbreviadHPP
#define AbbreviadHPP
#pragma delphiheader begin
#pragma option push
#pragma option -w- // All warnings off
#pragma option -Vx // Zero-length empty class member
#pragma pack(push,8)
#include <System.hpp> // (rtl)
#include <SysInit.hpp>
#include <AbArcTyp.hpp>
#include <AbBase.hpp>
#include <AbBitBkt.hpp>
#include <AbBrowse.hpp>
#include <AbBzip2.hpp>
#include <AbBzip2Typ.hpp>
#include <AbCabExt.hpp>
#include <AbCabKit.hpp>
#include <AbCabMak.hpp>
#include <AbCabTyp.hpp>
#include <AbCBrows.hpp>
#include <AbCharset.hpp>
#include <AbConst.hpp>
#include <AbCrtl.hpp>
#include <AbDfBase.hpp>
#include <AbDfCryS.hpp>
#include <AbDfDec.hpp>
#include <AbDfEnc.hpp>
#include <AbDfHufD.hpp>
#include <AbDfInW.hpp>
#include <AbDfOutW.hpp>
#include <AbDfPkMg.hpp>
#include <AbDfStrm.hpp>
#include <AbDfXlat.hpp>
#include <AbExcept.hpp>
#include <AbFciFdi.hpp>
#include <AbGzTyp.hpp>
#include <AbLZMA.hpp>
#include <AbPPMd.hpp>
#include <AbResString.hpp>
#include <AbSelfEx.hpp>
#include <AbSpanSt.hpp>
#include <AbSWStm.hpp>
#include <AbTarTyp.hpp>
#include <AbUnzOutStm.hpp>
#include <AbUnzper.hpp>
#include <AbUnzPrc.hpp>
#include <AbUtils.hpp>
#include <AbVMStrm.hpp>
#include <AbWavPack.hpp>
#include <AbZBrows.hpp>
#include <AbZipExt.hpp>
#include <AbZipKit.hpp>
#include <AbZipper.hpp>
#include <AbZipPrc.hpp>
#include <AbZipTyp.hpp>
#include <AbZLTyp.hpp>
#include <AbLZMAStream.hpp>
#include <AbBytes.hpp>
#include <Winapi.Windows.hpp> // (rtl)
#include <Winapi.PsAPI.hpp> // (rtl)
#include <System.Character.hpp> // (rtl)
#include <System.Internal.ExcUtils.hpp> // (rtl)
#include <System.SysUtils.hpp> // (rtl)
#include <System.VarUtils.hpp> // (rtl)
#include <System.Variants.hpp> // (rtl)
#include <System.Rtti.hpp> // (rtl)
#include <System.TypInfo.hpp> // (rtl)
#include <System.Math.hpp> // (rtl)
#include <System.Generics.Defaults.hpp> // (rtl)
#include <System.Classes.hpp> // (rtl)
#include <System.TimeSpan.hpp> // (rtl)
#include <System.DateUtils.hpp> // (rtl)
#include <System.IOUtils.hpp> // (rtl)
#include <System.AnsiStrings.hpp> // (rtl)
#include <System.Win.Registry.hpp> // (rtl)
#include <Winapi.ShellAPI.hpp> // (rtl)
//-- user supplied -----------------------------------------------------------
namespace Abbreviad
{
//-- forward type declarations -----------------------------------------------
//-- type declarations -------------------------------------------------------
//-- var, const, procedure ---------------------------------------------------
} /* namespace Abbreviad */
#if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_ABBREVIAD)
using namespace Abbreviad;
#endif
#pragma pack(pop)
#pragma option pop
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // AbbreviadHPP
| 29.666667 | 94 | 0.657303 | PacktPublishing |
744f55bb19e02078fff95f271bb9ebe265ffa084 | 22,099 | cpp | C++ | src/core/models/error/error_model_factory.cpp | gunjanbaid/octopus | b19e825d10c16bc14565338aadf4aee63c8fe816 | [
"MIT"
] | null | null | null | src/core/models/error/error_model_factory.cpp | gunjanbaid/octopus | b19e825d10c16bc14565338aadf4aee63c8fe816 | [
"MIT"
] | null | null | null | src/core/models/error/error_model_factory.cpp | gunjanbaid/octopus | b19e825d10c16bc14565338aadf4aee63c8fe816 | [
"MIT"
] | null | null | null | // Copyright (c) 2015-2019 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#include "error_model_factory.hpp"
#include <array>
#include <unordered_map>
#include <fstream>
#include <sstream>
#include <iostream>
#include <boost/optional.hpp>
#include <boost/functional/hash.hpp>
#include "utils/string_utils.hpp"
#include "exceptions/user_error.hpp"
#include "exceptions/malformed_file_error.hpp"
#include "basic_repeat_based_indel_error_model.hpp"
#include "repeat_based_snv_error_model.hpp"
#include "custom_repeat_based_indel_error_model.hpp"
namespace octopus {
static constexpr std::array<LibraryPreparation, 3> libraries {
LibraryPreparation::pcr, LibraryPreparation::pcr_free, LibraryPreparation::tenx
};
static constexpr std::array<Sequencer, 8> sequencers {
Sequencer::hiseq_2000, Sequencer::hiseq_2500, Sequencer::hiseq_4000,
Sequencer::xten, Sequencer::novaseq, Sequencer::bgiseq_500,
Sequencer::pacbio, Sequencer::pacbio_css
};
std::ostream& operator<<(std::ostream& out, const LibraryPreparation& library)
{
switch (library) {
case LibraryPreparation::pcr:
out << "PCR";
break;
case LibraryPreparation::pcr_free:
out << "PCR-free";
break;
case LibraryPreparation::tenx:
out << "10X";
break;
}
return out;
}
template <typename Range>
std::ostream& join(const Range& range, std::ostream& os, const std::string& delim = " ")
{
if (std::cbegin(range) != std::cend(range)) {
using T = typename std::iterator_traits<decltype(std::cbegin(range))>::value_type;
std::copy(std::cbegin(range), std::prev(std::cend(range)), std::ostream_iterator<T> {os, delim.c_str()});
os << *std::prev(std::cend(range));
}
return os;
}
class UnknownLibraryPreparation : public UserError
{
std::string name_;
std::string do_where() const override
{
return "operator>>(std::istream&, LibraryPreparation&)";
}
std::string do_why() const override
{
return "The library preparation name " + name_ + " is unknown";
}
std::string do_help() const override
{
std::ostringstream ss {};
ss << "Choose a valid library preparation name [";
join(libraries, ss, ", ");
ss << "]";
return ss.str();
}
public:
UnknownLibraryPreparation(std::string name) : name_ {std::move(name)} {}
};
std::istream& operator>>(std::istream& in, LibraryPreparation& result)
{
std::string token;
in >> token;
utils::capitalise(token);
if (token == "PCR")
result = LibraryPreparation::pcr;
else if (token == "PCR-FREE" || token == "PCRF")
result = LibraryPreparation::pcr_free;
else if (token == "10X")
result = LibraryPreparation::tenx;
else throw UnknownLibraryPreparation {token};
return in;
}
std::ostream& operator<<(std::ostream& out, const Sequencer& sequencer)
{
switch (sequencer) {
case Sequencer::hiseq_2000:
out << "HiSeq-2000";
break;
case Sequencer::hiseq_2500:
out << "HiSeq-2500";
break;
case Sequencer::hiseq_4000:
out << "HiSeq-4000";
break;
case Sequencer::xten:
out << "X10";
break;
case Sequencer::novaseq:
out << "NovaSeq";
break;
case Sequencer::bgiseq_500:
out << "BGISEQ-500";
break;
case Sequencer::pacbio:
out << "PacBio";
break;
case Sequencer::pacbio_css:
out << "PacBioCSS";
break;
}
return out;
}
class UnknownSequencer : public UserError
{
std::string name_;
std::string do_where() const override
{
return "operator>>(std::istream&, Sequencer&)";
}
std::string do_why() const override
{
return "The sequencer name " + name_ + " is unknown";
}
std::string do_help() const override
{
std::ostringstream ss {};
ss << "Choose a valid sequencer name [";
join(sequencers, ss, ", ");
ss << "]";
return ss.str();
}
public:
UnknownSequencer(std::string name) : name_ {std::move(name)} {}
};
std::istream& operator>>(std::istream& in, Sequencer& result)
{
std::string token;
in >> token;
utils::capitalise(token);
if (token == "HISEQ-2000")
result = Sequencer::hiseq_2000;
else if (token == "HISEQ-2500")
result = Sequencer::hiseq_2500;
else if (token == "HISEQ-4000")
result = Sequencer::hiseq_4000;
else if (token == "X10")
result = Sequencer::xten;
else if (token == "NOVASEQ")
result = Sequencer::novaseq;
else if (token == "BGISEQ-500")
result = Sequencer::bgiseq_500;
else if (token == "PACBIO")
result = Sequencer::pacbio;
else if (token == "PACBIOCSS")
result = Sequencer::pacbio_css;
else throw UnknownSequencer {token};
return in;
}
LibraryPreparation to_library(const std::string& name)
{
LibraryPreparation result;
std::istringstream ss {name};
ss >> result;
return result;
}
Sequencer to_sequencer(const std::string& name)
{
Sequencer result;
std::istringstream ss {name};
ss >> result;
return result;
}
struct ModelConfigHash
{
std::size_t operator()(const ModelConfig& config) const
{
using boost::hash_combine;
std::size_t seed {};
hash_combine(seed, config.library);
hash_combine(seed, config.sequencer);
return seed;
}
};
bool operator==(const ModelConfig& lhs, const ModelConfig& rhs) noexcept
{
return lhs.library == rhs.library && lhs.sequencer == rhs.sequencer;
}
using RepeatBasedIndelModelParameterMap = std::unordered_map<ModelConfig, BasicRepeatBasedIndelErrorModel::Parameters, ModelConfigHash>;
static const RepeatBasedIndelModelParameterMap builtin_indel_models {{
{
{LibraryPreparation::pcr_free, Sequencer::hiseq_2000},
{
{45,45,43,43,41,38,35,32,29,25,21,20,19,18,17,17,16,16,15,14,14,13,12,12,11,10,9,9,8,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5},
{45,45,45,41,39,34,30,24,21,18,15,13,12,10,8,7,7,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3},
{45,45,42,40,35,29,26,24,22,21,20,19,18,18,17,17,16,16,15,15,15,14,13,13,12,12,11,11,10,10,9,9,9,7,7,7,6,6,5,4,4,4,4,4,4,4,4,4,3},
{45,45,40,36,30,28,26,25,23,22,22,22,21,21,20,20,20,18,17,16,14,14,14,14,12,11,11,11,10,10,10,7,7,7,4,4,4,4,4,4,4,3}
}
},
{
{LibraryPreparation::pcr_free, Sequencer::hiseq_2500},
{
{45,45,43,43,41,38,35,32,29,25,21,20,19,18,17,17,16,16,15,14,14,13,12,12,11,10,9,9,8,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5},
{45,45,45,41,39,34,30,24,21,18,15,13,12,10,8,7,7,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3},
{45,45,42,40,35,29,26,24,22,21,20,19,18,18,17,17,16,16,15,15,15,14,13,13,12,12,11,11,10,10,9,9,9,7,7,7,6,6,5,4,4,4,4,4,4,4,4,4,3},
{45,45,40,36,30,28,26,25,23,22,22,22,21,21,20,20,20,18,17,16,14,14,14,14,12,11,11,11,10,10,10,7,7,7,4,4,4,4,4,4,4,3}
}
},
{
{LibraryPreparation::pcr_free, Sequencer::hiseq_4000},
{
{45,45,43,43,41,38,35,32,29,25,21,20,19,18,17,17,16,16,15,14,14,13,12,12,11,10,9,9,8,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5},
{45,45,45,41,39,34,30,24,21,18,15,13,12,10,8,7,7,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3},
{45,45,42,40,35,29,26,24,22,21,20,19,18,18,17,17,16,16,15,15,15,14,13,13,12,12,11,11,10,10,9,9,9,7,7,7,6,6,5,4,4,4,4,4,4,4,4,4,3},
{45,45,40,36,30,28,26,25,23,22,22,22,21,21,20,20,20,18,17,16,14,14,14,14,12,11,11,11,10,10,10,7,7,7,4,4,4,4,4,4,4,3}
}
},
{
{LibraryPreparation::pcr_free, Sequencer::xten},
{
{45,45,47,44,43,39,37,33,29,26,24,22,21,21,20,19,18,18,17,16,15,14,14,13,13,13,12,12,11,11,10,10,10,9,9,9,9,9,9,9,9,9,9,9,8},
{45,45,47,45,42,38,33,28,24,21,19,18,16,15,13,12,11,11,11,10,10,9,9,9,9,9,9,9,8,8,8,8,8,8,8,6},
{45,45,43,40,35,31,28,26,24,23,22,21,20,20,19,19,18,17,17,17,16,15,15,14,13,13,12,11,11,11,10,10,10,8,8,8,6,6,5},
{45,45,42,36,32,29,27,26,24,23,23,22,21,21,20,19,18,17,15,14,13,13,13,11,11,11,11,10,7,7,7,5,5,5,5,5,4}
}
},
{
{LibraryPreparation::pcr_free, Sequencer::novaseq},
{
{45,45,43,42,41,38,35,32,29,26,24,22,21,21,20,19,18,17,16,16,15,14,13,12,11,11,10,9,8,7,7,6,6,5,5,5,5,4,4,4,4,4,4,4,4,3},
{45,45,43,40,37,33,28,21,19,17,15,13,12,11,8,7,7,6,6,6,5,5,5,5,3},
{45,45,39,38,33,29,26,25,23,22,21,20,20,19,18,18,17,17,16,15,15,14,14,13,12,11,10,9,9,9,8,8,8,8,8,6,5,5,5,4,4,4,4,4,4,3},
{45,45,39,34,30,27,25,25,22,22,21,21,21,21,19,19,19,16,13,13,13,11,11,11,11,11,10,9,8,7,6,4,4,4,4,4,4,4,3}
}
},
{
{LibraryPreparation::pcr_free, Sequencer::bgiseq_500},
{
{45,45,47,44,43,39,37,33,29,26,24,22,21,21,20,19,18,18,17,16,15,14,14,13,13,13,12,12,11,11,10,10,10,9,9,9,9,9,9,9,9,9,9,9,8},
{45,45,47,45,42,38,33,28,24,21,19,18,16,15,13,12,11,11,11,10,10,9,9,9,9,9,9,9,8,8,8,8,8,8,8,6},
{45,45,43,40,35,31,28,26,24,23,22,21,20,20,19,19,18,17,17,17,16,15,15,14,13,13,12,11,11,11,10,10,10,8,8,8,6,6,5},
{45,45,42,36,32,29,27,26,24,23,23,22,21,21,20,19,18,17,15,14,13,13,13,11,11,11,11,10,7,7,7,5,5,5,5,5,4}
}
},
{
{LibraryPreparation::pcr_free, Sequencer::pacbio},
{
{13,13,11,10,9,8,7,7,7,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4},
{13,13,10,8,7,7,7,7,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4},
{13,13,8,7,6,6,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3},
{13,13,7,6,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4}
}
},
{
{LibraryPreparation::pcr_free, Sequencer::pacbio_css},
{
{31,31,27,24,21,18,16,14,13,12,11,10,10,9,9,8,8,8,8,7,7,7,7,7,7,7,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5},
{31,31,25,21,18,16,14,12,10,9,8,8,6,6,6,6,6,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4},
{31,31,24,22,20,17,15,14,12,11,10,10,9,9,9,8,8,8,8,7,7,7,7,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,3,3,3,3},
{31,31,22,19,17,15,14,13,11,11,10,10,9,9,8,8,7,7,6,6,6,6,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,3}
}
},
{
{LibraryPreparation::pcr, Sequencer::hiseq_2000},
{
{45,45,43,41,40,36,34,30,24,20,16,13,12,11,10,10,9,9,8,8,7,7,7,6,6,6,6,5,5,5,4,4,4,4,4,4,4,4,4,4,3},
{45,45,42,40,37,33,27,21,17,15,12,10,9,7,6,6,5,5,4,4,4,4,4,4,4,3},
{45,45,38,37,32,26,21,18,16,14,14,13,13,12,12,11,11,11,10,10,10,9,9,9,8,8,7,7,7,7,6,6,6,5,5,4,4,4,4,4,4,4,3},
{45,45,37,32,26,22,20,19,18,17,17,16,15,15,14,13,13,12,12,12,12,10,10,10,9,9,7,7,7,7,6,6,6,6,4,3}
}
},
{
{LibraryPreparation::pcr, Sequencer::hiseq_2500},
{
{45,45,43,41,40,36,34,30,24,20,16,13,12,11,10,10,9,9,8,8,7,7,7,6,6,6,6,5,5,5,4,4,4,4,4,4,4,4,4,4,3},
{45,45,42,40,37,33,27,21,17,15,12,10,9,7,6,6,5,5,4,4,4,4,4,4,4,3},
{45,45,38,37,32,26,21,18,16,14,14,13,13,12,12,11,11,11,10,10,10,9,9,9,8,8,7,7,7,7,6,6,6,5,5,4,4,4,4,4,4,4,3},
{45,45,37,32,26,22,20,19,18,17,17,16,15,15,14,13,13,12,12,12,12,10,10,10,9,9,7,7,7,7,6,6,6,6,4,3}
}
},
{
{LibraryPreparation::pcr, Sequencer::hiseq_4000},
{
{45,45,43,41,40,36,34,30,24,20,16,13,12,11,10,10,9,9,8,8,7,7,7,6,6,6,6,5,5,5,4,4,4,4,4,4,4,4,4,4,3},
{45,45,42,40,37,33,27,21,17,15,12,10,9,7,6,6,5,5,4,4,4,4,4,4,4,3},
{45,45,38,37,32,26,21,18,16,14,14,13,13,12,12,11,11,11,10,10,10,9,9,9,8,8,7,7,7,7,6,6,6,5,5,4,4,4,4,4,4,4,3},
{45,45,37,32,26,22,20,19,18,17,17,16,15,15,14,13,13,12,12,12,12,10,10,10,9,9,7,7,7,7,6,6,6,6,4,3}
}
},
{
{LibraryPreparation::pcr, Sequencer::xten},
{
{60,60,44,42,40,36,34,30,24,20,16,13,12,11,10,9,9,8,8,8,7,7,7,6,6,6,5,5,5,5,5,5,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3},
{60,60,42,40,37,35,28,22,18,15,12,10,9,7,6,4,4,5,5,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3},
{60,60,38,37,33,27,21,18,16,15,14,13,13,12,12,12,11,11,10,10,9,9,9,9,8,7,7,6,6,6,5,5,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3},
{60,60,38,33,26,22,20,19,18,18,17,16,17,15,14,14,14,14,13,12,12,11,10,10,8,7,7,6,6,5,5,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3}
}
},
{
{LibraryPreparation::pcr, Sequencer::novaseq},
{
{45,45,43,41,40,36,34,30,24,20,16,13,12,11,10,10,9,9,8,8,7,7,7,6,6,6,6,5,5,5,4,4,4,4,4,4,4,4,4,4,3},
{45,45,42,40,37,33,27,21,17,15,12,10,9,7,6,6,5,5,4,4,4,4,4,4,4,3},
{45,45,38,37,32,26,21,18,16,14,14,13,13,12,12,11,11,11,10,10,10,9,9,9,8,8,7,7,7,7,6,6,6,5,5,4,4,4,4,4,4,4,3},
{45,45,37,32,26,22,20,19,18,17,17,16,15,15,14,13,13,12,12,12,12,10,10,10,9,9,7,7,7,7,6,6,6,6,4,3}
}
},
{
{LibraryPreparation::pcr, Sequencer::bgiseq_500},
{
{60,60,49,47,43,39,35,31,25,21,17,14,13,12,11,11,10,10,9,9,9,8,8,8,8,8,7,7,7,7,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,4},
{60,60,48,45,42,38,32,26,22,17,14,12,10,9,8,7,6,6,6,5,5,5,5,5,4,4,4,4,4,4,4,4,3},
{60,60,44,42,36,29,22,19,17,15,15,14,14,13,13,13,12,12,12,11, 11,10,10,10,9,9,9,8,8,8,8,8,8,7,7,6,6,6,5,4,4,4,4,3},
{60,60,41,36,28,23,21,20,19,18,18,17,17,16,15,15,14,13,12,12,12,12,10,9,9,9,9,8,8,7,7,7,7,6,6,6,6,5,5,5,5,4,4,4,4,4,4,4,3}
}
},
{
{LibraryPreparation::pcr, Sequencer::pacbio},
{
{13,13,11,10,9,8,7,7,7,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4},
{13,13,10,8,7,7,7,7,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4},
{13,13,8,7,6,6,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3},
{13,13,7,6,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4}
}
},
{
{LibraryPreparation::pcr, Sequencer::pacbio_css},
{
{40,40,31,29,28,24,21,19,17,15,13,12,11,10,10,9,9,8,8,8,7,7,6,6,6,6,5,5,5,5,4},
{40,40,33,31,28,22,17,13,12,10,9,8,7,6,5,5,5,4,4,4,4,4,4,4,4,4,4,3},
{40,40,30,27,22,18,16,15,13,13,12,12,11,11,11,10,10,10,9,9,9,8,8,8,7,7,6,6,6,6,5,5,5,4},
{40,40,28,25,19,16,15,14,12,12,12,12,11,11,10,10,10,9,9,9,8,7,7,7,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,3}
}
},
{
{LibraryPreparation::tenx, Sequencer::hiseq_2000},
{
{45,45,36,34,30,27,26,24,20,16,13,12,11,10,9,8,8,7,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4},
{45,45,34,31,28,24,21,18,16,14,12,10,9,8,8,8,7,7,7,7,7,7,7,7,7,7,6,3},
{45,45,34,33,29,23,18,15,14,13,12,12,11,11,10,10,10,9,9,9,9,8,8,8,8,7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5},
{45,45,32,29,23,19,17,16,15,14,14,13,12,12,11,11,11,11,11,9,9,9,7,7,7,7,6}
}
},
{
{LibraryPreparation::tenx, Sequencer::hiseq_2500},
{
{45,45,37,35,30,28,26,25,21,17,14,12,11,11,10,10,9,9,8,8,8,7,7,7,7,7,7,7,6},
{45,45,36,33,29,26,22,20,17,15,13,11,10,9,9,9,9,8},
{45,45,33,32,28,23,18,15,13,12,12,11,11,10,10,9,9,9,8,8,8,8,7,7,7,6,6,6,6,6,5},
{45,45,31,28,23,19,16,15,14,13,12,12,11,10,10,10,10,10,10,9,9,7,7,6,6,6,5}
}
},
{
{LibraryPreparation::tenx, Sequencer::hiseq_4000},
{
{45,45,37,35,30,28,26,25,21,17,14,12,11,11,10,10,9,9,8,8,8,7,7,7,7,7,7,7,6},
{45,45,36,33,29,26,22,20,17,15,13,11,10,9,9,9,9,8},
{45,45,33,32,28,23,18,15,13,12,12,11,11,10,10,9,9,9,8,8,8,8,7,7,7,6,6,6,6,6,5},
{45,45,31,28,23,19,16,15,14,13,12,12,11,10,10,10,10,10,10,9,9,7,7,6,6,6,5}
}
},
{
{LibraryPreparation::tenx, Sequencer::xten},
{
{45,45,31,29,28,24,21,19,17,15,13,12,11,10,10,9,9,8,8,8,7,7,6,6,6,6,5,5,5,5,4},
{45,45,33,31,28,22,17,13,12,10,9,8,7,6,5,5,5,4,4,4,4,4,4,4,4,4,4,3},
{45,45,30,27,22,18,16,15,13,13,12,12,11,11,11,10,10,10,9,9,9,8,8,8,7,7,6,6,6,6,5,5,5,4},
{45,45,28,25,19,16,15,14,12,12,12,12,11,11,10,10,10,9,9,9,8,7,7,7,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,3}
}
},
{
{LibraryPreparation::tenx, Sequencer::novaseq},
{
{45,45,31,29,28,24,21,19,17,15,13,12,11,10,10,9,9,8,8,8,7,7,6,6,6,6,5,5,5,5,4},
{45,45,33,31,28,22,17,13,12,10,9,8,7,6,5,5,5,4,4,4,4,4,4,4,4,4,4,3},
{45,45,30,27,22,18,16,15,13,13,12,12,11,11,11,10,10,10,9,9,9,8,8,8,7,7,6,6,6,6,5,5,5,4},
{45,45,28,25,19,16,15,14,12,12,12,12,11,11,10,10,10,9,9,9,8,7,7,7,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,3}
}
},
{
{LibraryPreparation::tenx, Sequencer::bgiseq_500},
{
{45,45,37,35,30,28,26,25,21,17,14,12,11,11,10,10,9,9,8,8,8,7,7,7,7,7,7,7,6},
{45,45,36,33,29,26,22,20,17,15,13,11,10,9,9,9,9,8},
{45,45,34,33,29,23,18,15,14,13,12,12,11,11,10,10,10,9,9,9,9,8,8,8,8,7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5},
{45,45,32,29,23,19,17,16,15,14,14,13,12,12,11,11,11,11,11,9,9,9,7,7,7,7,6}
}
}
}};
BasicRepeatBasedIndelErrorModel::Parameters lookup_builtin_indel_model(const ModelConfig config)
{
return builtin_indel_models.at(config);
}
bool use_snv_error_model(const ModelConfig config)
{
return config.sequencer != Sequencer::pacbio && config.sequencer != Sequencer::pacbio_css;
}
using RepeatBasedSnvModelParameterMap = std::unordered_map<LibraryPreparation, BasicRepeatBasedSNVErrorModel::Parameters>;
static const RepeatBasedSnvModelParameterMap builtin_snv_models {{
{
LibraryPreparation::pcr_free,
{
{125,125,60,55,50,30,20,15,12,12,10,10,10,10,8,7,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1},
{125,125,60,60,52,52,38,38,22,22,17,17,15,15,13,13,10,10,10,10,8,8,7,6,6,6,6,6,6,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1},
{125,125,125,55,55,55,40,40,40,25,25,25,19,19,19,11,11,11,9,9,9,7,7,6,6,6,6,6,6,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1}
}
},
{
LibraryPreparation::pcr,
{
{125,125,60,55,38,23,16,14,11,10,9,8,7,7,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1},
{125,125,60,60,52,52,38,38,22,22,17,17,15,15,13,13,10,10,10,10,8,8,7,6,6,6,6,6,6,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1},
{125,125,125,55,55,55,40,40,40,25,25,25,19,19,19,11,11,11,9,9,9,7,7,6,6,6,6,6,6,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1}
}},
{
LibraryPreparation::tenx,
{
{125,125,60,55,38,23,16,14,11,10,9,8,7,7,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1},
{125,125,60,60,52,52,38,38,22,22,17,17,15,15,13,13,10,10,10,10,8,8,7,6,6,6,6,6,6,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1},
{125,125,125,55,55,55,40,40,40,25,25,25,19,19,19,11,11,11,9,9,9,7,7,6,6,6,6,6,6,5,5,5,5,4,4,4,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1}
}}
}};
boost::optional<BasicRepeatBasedSNVErrorModel::Parameters> lookup_builtin_snv_model(const ModelConfig config)
{
if (use_snv_error_model(config)) {
return builtin_snv_models.at(config.library);
} else {
return boost::none;
}
}
class MalformedErrorModelFile : public MalformedFileError
{
std::string do_where() const override { return "make_indel_error_model"; }
std::string do_help() const override { return "refer to documentation on custom error models or use provided Python script"; }
public:
MalformedErrorModelFile(boost::filesystem::path file) : MalformedFileError {std::move(file), "model"} {}
};
std::unique_ptr<SnvErrorModel> make_snv_error_model(const ModelConfig config)
{
auto model = lookup_builtin_snv_model(config);
if (model) {
return std::make_unique<BasicRepeatBasedSNVErrorModel>(std::move(*model));
} else {
return nullptr;
}
}
std::unique_ptr<IndelErrorModel> make_indel_error_model(const ModelConfig config)
{
return std::make_unique<BasicRepeatBasedIndelErrorModel>(lookup_builtin_indel_model(config));
}
ModelConfig parse_model_config(const std::string& label)
{
auto result = default_model_config;
const auto library_end_pos = label.find('.');
const auto library_name = label.substr(0, library_end_pos);
if (!library_name.empty()) {
result.library = to_library(library_name);
}
if (library_end_pos != std::string::npos) {
const auto sequencer_name = label.substr(library_end_pos + 1);
if (!sequencer_name.empty()) {
result.sequencer = to_sequencer(sequencer_name);
}
}
return result;
}
ErrorModel make_error_model(const std::string& label)
{
const auto config = parse_model_config(label);
return {make_indel_error_model(config), make_snv_error_model(config)};
}
ErrorModel make_error_model(const boost::filesystem::path& model_filename)
{
std::ifstream model_file {model_filename.string()};
std::string model_str {static_cast<std::stringstream const&>(std::stringstream() << model_file.rdbuf()).str()};
auto params = make_penalty_map(std::move(model_str));
if (!params.open) {
throw MalformedErrorModelFile {model_filename};
}
ErrorModel result {};
if (params.extend) {
result.indel = std::make_unique<CustomRepeatBasedIndelErrorModel>(std::move(*params.open), std::move(*params.extend));
} else {
result.indel = std::make_unique<CustomRepeatBasedIndelErrorModel>(std::move(*params.open));
}
result.snv = make_snv_error_model(default_model_config);
return result;
}
} // namespace octopus
| 41.933586 | 142 | 0.569257 | gunjanbaid |
745159242d81163b2eea766e92221cfc1cf268c7 | 5,741 | hpp | C++ | src/webots/nodes/WbIndexedFaceSet.hpp | awesome-archive/webots | 8e74fb8393d1e3a6540749afc492635c43f1b30f | [
"Apache-2.0"
] | 2 | 2019-07-12T13:47:44.000Z | 2019-08-17T02:53:54.000Z | src/webots/nodes/WbIndexedFaceSet.hpp | golbh/webots | 8e74fb8393d1e3a6540749afc492635c43f1b30f | [
"Apache-2.0"
] | null | null | null | src/webots/nodes/WbIndexedFaceSet.hpp | golbh/webots | 8e74fb8393d1e3a6540749afc492635c43f1b30f | [
"Apache-2.0"
] | 1 | 2019-07-13T17:58:04.000Z | 2019-07-13T17:58:04.000Z | // Copyright 1996-2018 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef WB_INDEXED_FACE_SET_HPP
#define WB_INDEXED_FACE_SET_HPP
#include "WbGeometry.hpp"
#include "WbTriangleMeshCache.hpp"
#include <unordered_map>
class WbCoordinate;
class WbTextureCoordinate;
class WbTriangleMesh;
class WbVector3;
typedef struct dxTriMeshData *dTriMeshDataID;
typedef std::unordered_map<WbTriangleMeshCache::IndexedFaceSetKey, WbTriangleMeshCache::TriangleMeshInfo,
WbTriangleMeshCache::IndexedFaceSetKeyHasher>
WbTriangleMeshMap;
class WbIndexedFaceSet : public WbGeometry {
Q_OBJECT
public:
// constructors and destructor
explicit WbIndexedFaceSet(WbTokenizer *tokenizer = NULL);
WbIndexedFaceSet(const WbIndexedFaceSet &other);
explicit WbIndexedFaceSet(const WbNode &other);
virtual ~WbIndexedFaceSet();
// reimplemented public functions
int nodeType() const override { return WB_NODE_INDEXED_FACE_SET; }
void preFinalize() override;
void postFinalize() override;
void createWrenObjects() override;
void setScaleNeedUpdate() override;
dGeomID createOdeGeom(dSpaceID space) override;
void createResizeManipulator() override;
void attachResizeManipulator() override;
bool isAValidBoundingObject(bool checkOde = false, bool warning = true) const override;
bool isSuitableForInsertionInBoundingObject(bool warning = false) const override;
void buildGeomIntoBuffers(WbWrenMeshBuffers *buffers, const WbMatrix4 &m, bool generateUserTexCoords = true) const override;
void reset() override;
// field accessors
WbCoordinate *coord() const;
WbTextureCoordinate *texCoord() const;
const WbMFInt *coordIndex() const { return static_cast<const WbMFInt *>(mCoordIndex); }
const WbMFInt *texCoordIndex() const { return static_cast<const WbMFInt *>(mTexCoordIndex); }
const WbSFDouble *creaseAngle() const { return static_cast<const WbSFDouble *>(mCreaseAngle); }
const WbSFBool *ccw() const { return static_cast<const WbSFBool *>(mCcw); }
// Rescaling and translating
void rescale(const WbVector3 &v) override;
void rescaleAndTranslate(int coordinate, double scale, double translation);
void rescaleAndTranslate(double factor, const WbVector3 &t);
void rescaleAndTranslate(const WbVector3 &scale, const WbVector3 &translation);
void translate(const WbVector3 &v);
double max(int coordinate) const;
double min(int coordinate) const;
double range(int coordinate) const { return max(coordinate) - min(coordinate); }
void updateTriangleMesh(bool issueWarnings = true);
// ray tracing
void recomputeBoundingSphere() const override;
bool pickUVCoordinate(WbVector2 &uv, const WbRay &ray, int textureCoordSet = 0) const override;
double computeDistance(const WbRay &ray) const override;
// friction
WbVector3 computeFrictionDirection(const WbVector3 &normal) const override;
// Non-recursive texture mapping
WbVector2 nonRecursiveTextureSizeFactor() const override;
// resize manipulator
void setResizeManipulatorDimensions() override;
// WbTriangleMesh management (see WbTriangleMeshCache.hpp)
WbTriangleMeshCache::TriangleMeshInfo createTriangleMesh();
virtual void setTriangleMesh(WbTriangleMesh *triangleMesh) { mTriangleMesh = triangleMesh; }
virtual void updateOdeData();
WbTriangleMeshMap &getTriangleMeshMap() { return cTriangleMeshMap; }
WbTriangleMeshCache::IndexedFaceSetKey &getMeshKey() { return mMeshKey; }
signals:
void validIndexedFaceSetInserted();
protected:
virtual int indexSize() const { return 0; }
bool areSizeFieldsVisibleAndNotRegenerator() const override;
void exportNodeContents(WbVrmlWriter &writer) const override;
bool exportNodeHeader(WbVrmlWriter &writer) const override;
private:
WbIndexedFaceSet &operator=(const WbIndexedFaceSet &); // non copyable
WbNode *clone() const override { return new WbIndexedFaceSet(*this); }
void init();
// user accessible fields
WbSFNode *mCoord;
WbSFNode *mTexCoord;
WbSFBool *mCcw;
WbMFInt *mCoordIndex;
WbMFInt *mTexCoordIndex;
WbSFDouble *mCreaseAngle;
// other variables
WbTriangleMesh *mTriangleMesh;
QString mTriangleMeshError;
dTriMeshDataID mTrimeshData;
// WREN
void buildWrenMesh(bool updateCache);
int estimateVertexCount(bool isOutlineMesh = false) const;
int estimateIndexCount(bool isOutlineMesh = false) const;
// ODE
void applyToOdeData(bool correctSolidMass = true) override;
void setOdeTrimeshData();
void clearTrimeshResources();
bool mCorrectSolidMass;
bool mIsOdeDataApplied;
// ray tracing
// compute local collision point and return the distance
enum { X, Y, Z };
double computeLocalCollisionPoint(WbVector3 &point, int &triangleIndex, const WbRay &ray) const;
void updateScaledVertices() const;
mutable bool mScaledVerticesNeedUpdate;
// Hashmap key for this instance's mesh
WbTriangleMeshCache::IndexedFaceSetKey mMeshKey;
// Hashmap containing triangle meshes, shared by all instances
static WbTriangleMeshMap cTriangleMeshMap;
private slots:
void updateCoord();
void updateTexCoord();
void updateCcw();
void updateCoordIndex();
void updateTexCoordIndex();
void updateCreaseAngle();
};
#endif
| 35.438272 | 126 | 0.774604 | awesome-archive |
74523286fde903feac0517ed6f46f645a50ac715 | 9,472 | cpp | C++ | animer/main.cpp | Benjins/GBADev | 0a968a1aa1ee38b57644a1bb8d27f2c5332e3c90 | [
"MIT"
] | null | null | null | animer/main.cpp | Benjins/GBADev | 0a968a1aa1ee38b57644a1bb8d27f2c5332e3c90 | [
"MIT"
] | null | null | null | animer/main.cpp | Benjins/GBADev | 0a968a1aa1ee38b57644a1bb8d27f2c5332e3c90 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "../toolsCode/Renderer.h"
#include "../toolsCode/Timer.h"
#include "../toolsCode/openfile.h"
#define TILE_INDEX_MULTIPLIER 24
void* bitmapData = NULL;
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define ARRAY_COUNT(x) (sizeof(x) / sizeof((x)[0]))
#define SAFE_FREE(x) {if(x){free(x); (x) = nullptr;}}
typedef struct {
char* start;
int length;
}Token;
inline float clamp(float val, float min, float max) {
return MIN(max, MAX(min, val));
}
inline int clamp(int val, int min, int max) {
return MIN(max, MAX(min, val));
}
inline bool RangeCheck(int a, int b, int c) {
return (a < b) && (b < c);
}
enum KeyState {
OFF = 0,
RELEASE = 1,
PRESS = 2,
HOLD = 3
};
KeyState keyStates[256] = {};
inline KeyState StateFromBools(bool wasDown, bool isDown) {
return (KeyState)((wasDown ? 1 : 0) | (isDown ? 2 : 0));
}
struct WindowObj;
const char* arg1Str;
int arg1Length;
WindowObj* windowObj;
int frameWidth = 0;
int frameHeight = 0;
float zoomLevel = 1.0f;
int xOffset = 0;
int yOffset = 0;
int currentPaintIndex = 0;
int currMouseX = 0;
int currMouseY = 0;
int mouseState = 0;
#include "AnimAsset.h"
AnimAsset animAsset = {};
int animClipIndex = 0;
float animTime = 0.0f;
bool isPlaying = true;
int white = 0xFFFFFFFF;
BitmapData whiteCol = {&white, 1, 1};
int circleData[256] = {};
BitmapData cyanCircle = {circleData, 16, 16};
int plusData[256] = {};
BitmapData plusSign = {plusData, 16, 16};
int crossData[256] = {};
BitmapData crossSign = {crossData, 16, 16};
Timer timer;
void Init(){
ReadAnimAssetFile(&animAsset, "anim.txt", arg1Str, arg1Length);
for(int i = 0; i < 16; i++){
crossData[17*i] = 0xEE2222;
crossData[16*i+16-i] = 0xEE2222;
}
for(int i = 0; i < 16; i++){
plusData[128+i] = 0xFFFFFF;
plusData[i*16+8] = 0xFFFFFF;
}
for(int j = 0; j < 16; j++){
float rSqr = 64;
float heightSqr = (8 - j)*(8 - j);
float width = sqrt(rSqr - heightSqr);
for(int i = 0; i < 16; i++){
int idx = j*16+i;
if(abs(8 - i) < (int)width){
circleData[idx] = 0xFFFFFF;
}
else if(abs(8 - i) < width){
float widthFrac = width - (int)width;
unsigned char amt = (unsigned char)(width * 255);
circleData[idx] = amt | (amt << 8) | (amt << 16);
}
}
}
}
char textBuffer[256] = {};
char textBuffer2[256] = {};
void RunFrame(){
float deltaTime = (float)timer.GetTimeSince();
timer.Reset();
if(isPlaying){
animTime += deltaTime;
}
if (keyStates['W'] > 1) {
char fullAssetFileName[256] = {};
sprintf(fullAssetFileName, "%.*s/%s", arg1Length, arg1Str, "anim.txt");
SaveAnimAssetFile(&animAsset, fullAssetFileName);
}
BitmapData frameBuffer = { (int*)bitmapData, frameWidth, frameHeight };
memset(bitmapData, 0, frameBuffer.width*frameBuffer.height * 4);
for(int i = 0; i < animAsset.animClipCount; i++){
DrawText(frameBuffer, animAsset.animClips[i].name, frameBuffer.width - 180, 100*i+40, 150, 40);
if(Button(frameBuffer, frameBuffer.width - 180, 100*i+50, 50, 30, 0x777777, 0xEEEEEE, 0xDDDDDD, "")){
animClipIndex = i;
animTime = 0;
}
}
//Useful for seeing performance
//DrawText(frameBuffer, timeStr, 400, 400, 500, 100);
DrawBox(frameBuffer, 20, frameBuffer.height - 40, frameBuffer.width - 220, 30, white);
int textBox = 0;
if(TextBox(frameBuffer, textBuffer, sizeof(textBuffer), 500, 200, 100, 30)){
textBox = 1;
}
if(TextBox(frameBuffer, textBuffer2, sizeof(textBuffer2), 500, 260, 100, 30)){
textBox = 1;
}
int frameLength = 0;
for(int i = 0; i < animAsset.animClips[animClipIndex].keyFrameCount; i++){
frameLength += animAsset.animClips[animClipIndex].keyFrames[i].duration;
}
float animLengthInSeconds = ((float)frameLength)/60.0f;
while(animTime > animLengthInSeconds){
animTime -= animLengthInSeconds;
}
int secondLength = (frameLength+59)/60;
int timelinePixelWidth = frameBuffer.width - 240;
for(int i = 0; i <= secondLength; i++){
int x = 20 + (timelinePixelWidth/secondLength)*i;
DrawBox(frameBuffer, x, frameBuffer.height - 80, 20, 70, white);
}
int animTickX = (animTime/animLengthInSeconds)*timelinePixelWidth;
DrawBox(frameBuffer, animTickX, frameBuffer.height - 90, 20, 80, 0xFF7777FF);
DrawText(frameBuffer, (isPlaying ? "Pause" : "Play"), frameBuffer.width - 180, frameBuffer.height - 90, 150, 40);
if(Button(frameBuffer, frameBuffer.width - 180, frameBuffer.height - 80, 100, 50, 0x777777, 0xEEEEEE, 0xDDDDDD, "")){
isPlaying = !isPlaying;
}
if(mouseState == HOLD && currMouseX > 20 && currMouseX < frameBuffer.width - 220
&& currMouseY > frameBuffer.height - 100 && currMouseY < frameBuffer.height){
float projectedAnimTime = ((float)currMouseX - 10)/timelinePixelWidth * animLengthInSeconds;
animTime = clamp(projectedAnimTime, 0.0f, animLengthInSeconds);
}
else if(mouseState == HOLD && currMouseY < frameBuffer.height - 150
&& currMouseY > frameBuffer.height - 200){
int frameLength = 0;
for(int i = 0; i < animAsset.animClips[animClipIndex].keyFrameCount; i++){
float pixelX = (float(frameLength))/60 / animLengthInSeconds * timelinePixelWidth;
if(currMouseX > pixelX && currMouseX < pixelX + 50){
float pixelOffset = pixelX + 25 - currMouseX;
float frameOffset = pixelOffset / timelinePixelWidth * animLengthInSeconds * 60;
int offsetInt = (frameOffset < 0 ? -1 : 1) * (int)((frameOffset < 0 ? -frameOffset : frameOffset));
if(i != 0){
animAsset.animClips[animClipIndex].keyFrames[i-1].duration -= offsetInt;
if (i != animAsset.animClips[animClipIndex].keyFrameCount - 1) {
animAsset.animClips[animClipIndex].keyFrames[i].duration += offsetInt;
}
}
break;
}
frameLength += animAsset.animClips[animClipIndex].keyFrames[i].duration;
}
}
else if(mouseState == RELEASE && currMouseY < frameBuffer.height - 100
&& currMouseY > frameBuffer.height - 150){
int startTime = 0;
for(int i = 0; i < animAsset.animClips[animClipIndex].keyFrameCount; i++){
float pixelX = ((float)startTime)/60/animLengthInSeconds * timelinePixelWidth;
if(currMouseX > pixelX && currMouseX < pixelX + 50){
char fileName[256] = {};
if(OpenFile(fileName, windowObj, "bmp", "BMP files(*.bmp)", arg1Str, arg1Length)){
free(animAsset.animClips[animClipIndex].keyFrames[i].spriteData.data);
free(animAsset.animClips[animClipIndex].keyFrames[i].fileName);
int newFileNameLength = strlen(fileName);
char* newFileName = (char*)malloc(newFileNameLength+1);
memcpy(newFileName, fileName, newFileNameLength);
newFileName[newFileNameLength] = '\0';
animAsset.animClips[animClipIndex].keyFrames[i].fileName = newFileName;
char fullNewFileName[256] = {};
sprintf(fullNewFileName, "%.*s/%s", arg1Length, arg1Str, newFileName);
animAsset.animClips[animClipIndex].keyFrames[i].spriteData = LoadBMPFile(fullNewFileName);
}
}
startTime += animAsset.animClips[animClipIndex].keyFrames[i].duration;
}
}
int currentFrames = (int)(animTime*60);
if(Button(frameBuffer, frameBuffer.width - 150, frameBuffer.height - 250, 100, 50, 0x777777, 0xEEEEEE, 0xDDDDDD, "")){
char fileName[256] = {};
if(OpenFile(fileName, windowObj, "bmp", "BMP files(*.bmp)", arg1Str, arg1Length)){
int newFileNameLength = strlen(fileName);
char* newFileName = (char*)malloc(newFileNameLength+1);
memcpy(newFileName, fileName, newFileNameLength);
newFileName[newFileNameLength] = '\0';
char fullNewFileName[256] = {};
sprintf(fullNewFileName, "%.*s/%s", arg1Length, arg1Str, newFileName);
AnimKeyFrame newKeyFrame = {newFileName, LoadBMPFile(fullNewFileName), 20};
AddKeyFrame(&animAsset.animClips[animClipIndex], newKeyFrame);
}
}
DrawBitmap(frameBuffer, frameBuffer.width - 149, frameBuffer.height - 299, 48, 48, plusSign);
int frames = 0;
int currKeyFrame = 0;
for(int i = 0; i < animAsset.animClips[animClipIndex].keyFrameCount; i++){
frames += animAsset.animClips[animClipIndex].keyFrames[i].duration;
if(frames > currentFrames){
currKeyFrame = i;
break;
}
}
int startTime = 0;
for(int i = 0; i < animAsset.animClips[animClipIndex].keyFrameCount; i++){
float startPixels = ((float)startTime)/60/animLengthInSeconds * timelinePixelWidth;
DrawBitmap(frameBuffer, (int)startPixels, frameBuffer.height - 200, 50, 50, cyanCircle);
DrawBitmap(frameBuffer, (int)startPixels, frameBuffer.height - 150, 50, 50, animAsset.animClips[animClipIndex].keyFrames[i].spriteData);
int duration = animAsset.animClips[animClipIndex].keyFrames[i].duration;
if(Button(frameBuffer, (int)startPixels, frameBuffer.height - 250, 30, 30, 0x777777, 0xEEEEEE, 0xDDDDDD, "")){
RemoveAnimKeyFrame(&animAsset.animClips[animClipIndex], i);
}
DrawBitmap(frameBuffer, startPixels, frameBuffer.height - 250, 30, 30, crossSign);
startTime += duration;
}
NoramlizeAnimClip(&animAsset.animClips[animClipIndex]);
DrawBitmap(frameBuffer, 50, 50, 250, 250, animAsset.animClips[animClipIndex].keyFrames[currKeyFrame].spriteData);
if(mouseState == PRESS){
mouseState = HOLD;
}
if(mouseState == RELEASE){
mouseState = OFF;
}
for(int i = 0; i < 256; i++){
if(keyStates[i] == PRESS){
keyStates[i] = HOLD;
}
if(keyStates[i] == RELEASE){
keyStates[i] = OFF;
}
}
zoomLevel = clamp(zoomLevel, 0.25f, 2.0f);
} | 29.325077 | 138 | 0.676626 | Benjins |
74539fd3a437ada34e33972f54afa3905e6283f1 | 1,970 | cpp | C++ | training/1-3-7-wormhole/cpp11/main.cpp | hsun324/usaco-solutions | 27f77911971513a4d2b1b820eaa09802acadfefa | [
"MIT"
] | 2 | 2015-12-26T21:20:12.000Z | 2017-12-19T00:11:45.000Z | training/1-3-7-wormhole/cpp11/main.cpp | hsun324/usaco-solutions | 27f77911971513a4d2b1b820eaa09802acadfefa | [
"MIT"
] | null | null | null | training/1-3-7-wormhole/cpp11/main.cpp | hsun324/usaco-solutions | 27f77911971513a4d2b1b820eaa09802acadfefa | [
"MIT"
] | null | null | null | /*
ID: <ID HERE>
LANG: C++11
TASK: wormhole
*/
#include <algorithm>
#include <fstream>
#include <map>
#include <set>
#include <utility>
#include <vector>
using namespace std;
bool check_cycle(vector<int> &pairs, map<int, int> &transitions) {
vector<bool> visited(pairs.size());
for (int i = 0; i < pairs.size(); i++) {
if (visited[i]) continue;
int current = i;
do {
visited[current] = true;
int exit = pairs[current], next = -1;
auto transition = transitions.find(exit);
if (transition != transitions.end())
next = transition->second;
if (next == i)
break;
current = next;
} while (current >= 0);
if (current >= 0) return true;
}
return false;
}
int construct_permutations_and_check(vector<int> &permutation, map<int, int> &transitions) {
auto first_unassigned = find(permutation.begin(), permutation.end(), -1);
if (first_unassigned == permutation.end())
return check_cycle(permutation, transitions) ? 1 : 0;
int count = 0;
int unassigned_index = first_unassigned - permutation.begin();
for (int i = unassigned_index + 1; i < permutation.size(); i++) {
if (permutation[i] == -1) {
vector<int> current(permutation);
current[i] = unassigned_index;
current[unassigned_index] = i;
count += construct_permutations_and_check(current, transitions);
}
}
return count;
}
int main() {
ifstream cin("wormhole.in");
ofstream cout("wormhole.out");
int count;
cin >> count;
map<int, set<pair<int, int>>> wormholes;
for (int i = 0, x, y; i < count; i++) {
cin >> x >> y;
wormholes[y].emplace(x, i);
}
map<int, int> transitions;
for (auto &wormhole_set : wormholes) {
int last_index = -1;
for (auto &index : wormhole_set.second) {
if (last_index >= 0) transitions[last_index] = index.second;
last_index = index.second;
}
}
vector<int> permutation(count, -1);
int cycles = construct_permutations_and_check(permutation, transitions);
cout << cycles << endl;
return 0;
}
| 21.413043 | 92 | 0.658883 | hsun324 |
74565efae85b7a46bd23d0d9746594bd2c06569f | 29,181 | cpp | C++ | Source/Runtime/Private/Components/ComParticleSystem.cpp | redchew-fork/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | [
"Apache-2.0"
] | 410 | 2017-03-03T08:56:54.000Z | 2022-03-29T07:18:46.000Z | Source/Runtime/Private/Components/ComParticleSystem.cpp | redchew-fork/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | [
"Apache-2.0"
] | 31 | 2017-03-05T11:37:44.000Z | 2021-09-15T21:28:34.000Z | Source/Runtime/Private/Components/ComParticleSystem.cpp | redchew-fork/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | [
"Apache-2.0"
] | 48 | 2017-03-18T05:28:21.000Z | 2022-03-05T12:27:17.000Z | // Copyright(c) 2017 POLYGONTEK
//
// 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 "Precompiled.h"
#include "Render/Render.h"
#include "Asset/Asset.h"
#include "Asset/Resource.h"
#include "Asset/GuidMapper.h"
#include "Components/ComTransform.h"
#include "Components/ComParticleSystem.h"
#include "Game/GameWorld.h"
#include "Game/TagLayerSettings.h"
BE_NAMESPACE_BEGIN
OBJECT_DECLARATION("Particle System", ComParticleSystem, ComRenderable)
BEGIN_EVENTS(ComParticleSystem)
END_EVENTS
void ComParticleSystem::RegisterProperties() {
REGISTER_MIXED_ACCESSOR_PROPERTY("particleSystem", "Particle System", Guid, GetParticleSystemGuid, SetParticleSystemGuid, GuidMapper::defaultParticleSystemGuid,
"", PropertyInfo::Flag::Editor).SetMetaObject(&ParticleSystemResource::metaObject);
REGISTER_PROPERTY("playOnAwake", "Play On Awake", bool, playOnAwake, true,
"", PropertyInfo::Flag::Editor);
}
ComParticleSystem::ComParticleSystem() {
particleSystemAsset = nullptr;
#if WITH_EDITOR
spriteHandle = -1;
spriteReferenceMesh = nullptr;
#endif
}
ComParticleSystem::~ComParticleSystem() {
Purge(false);
}
void ComParticleSystem::Purge(bool chainPurge) {
#if WITH_EDITOR
if (spriteDef.mesh) {
meshManager.ReleaseMesh(spriteDef.mesh);
spriteDef.mesh = nullptr;
}
if (spriteReferenceMesh) {
meshManager.ReleaseMesh(spriteReferenceMesh);
spriteReferenceMesh = nullptr;
}
if (spriteHandle != -1) {
renderWorld->RemoveRenderObject(spriteHandle);
spriteHandle = -1;
}
#endif
if (renderObjectDef.particleSystem) {
particleSystemManager.ReleaseParticleSystem(renderObjectDef.particleSystem);
renderObjectDef.particleSystem = nullptr;
}
if (renderObjectDef.stageParticles.Count() > 0) {
for (int stageIndex = 0; stageIndex < renderObjectDef.stageParticles.Count(); stageIndex++) {
Mem_Free(renderObjectDef.stageParticles[stageIndex]);
}
renderObjectDef.stageParticles.Clear();
}
if (chainPurge) {
ComRenderable::Purge();
}
}
void ComParticleSystem::Init() {
ComRenderable::Init();
currentTime = 0;
stopTime = 0;
simulationStarted = false;
ComTransform *transform = GetEntity()->GetTransform();
#if WITH_EDITOR
// 3d spriteDef
spriteReferenceMesh = meshManager.GetMesh("_defaultQuadMesh");
spriteDef.flags = RenderObject::Flag::Billboard;
spriteDef.layer = TagLayerSettings::BuiltInLayer::Editor;
spriteDef.maxVisDist = MeterToUnit(50.0f);
Texture *spriteTexture = textureManager.GetTextureWithoutTextureInfo("Data/EditorUI/ParticleSystem.png", Texture::Flag::Clamp | Texture::Flag::HighQuality);
spriteDef.materials.SetCount(1);
spriteDef.materials[0] = materialManager.GetSingleTextureMaterial(spriteTexture, Material::TextureHint::Sprite);
textureManager.ReleaseTexture(spriteTexture);
spriteDef.mesh = spriteReferenceMesh->InstantiateMesh(Mesh::Type::Static);
spriteDef.aabb = spriteReferenceMesh->GetAABB();
spriteDef.worldMatrix = transform->GetMatrixNoScale();
spriteDef.materialParms[RenderObject::MaterialParm::Red] = 1.0f;
spriteDef.materialParms[RenderObject::MaterialParm::Green] = 1.0f;
spriteDef.materialParms[RenderObject::MaterialParm::Blue] = 1.0f;
spriteDef.materialParms[RenderObject::MaterialParm::Alpha] = 1.0f;
spriteDef.materialParms[RenderObject::MaterialParm::TimeOffset] = 0.0f;
spriteDef.materialParms[RenderObject::MaterialParm::TimeScale] = 1.0f;
#endif
transform->Connect(&ComTransform::SIG_TransformUpdated, this, (SignalCallback)&ComParticleSystem::TransformUpdated, SignalObject::ConnectionType::Unique);
// Mark as initialized.
SetInitialized(true);
UpdateVisuals();
}
void ComParticleSystem::ChangeParticleSystem(const Guid &particleSystemGuid) {
#if WITH_EDITOR
// Disconnect with previously connected particleSystem asset.
if (particleSystemAsset) {
particleSystemAsset->Disconnect(&Asset::SIG_Reloaded, this);
particleSystemAsset = nullptr;
}
#endif
// Release the previously used particleSystem.
if (renderObjectDef.particleSystem) {
particleSystemManager.ReleaseParticleSystem(renderObjectDef.particleSystem);
renderObjectDef.particleSystem = nullptr;
}
// Get the new particleSystem.
const Str particleSystemPath = resourceGuidMapper.Get(particleSystemGuid);
renderObjectDef.particleSystem = particleSystemManager.GetParticleSystem(particleSystemPath);
ResetParticles();
#if WITH_EDITOR
// Need to particleSystem asset to be reloaded in editor.
particleSystemAsset = (Asset *)Asset::FindInstance(particleSystemGuid);
if (particleSystemAsset) {
particleSystemAsset->Connect(&Asset::SIG_Reloaded, this, (SignalCallback)&ComParticleSystem::ParticleSystemReloaded, SignalObject::ConnectionType::Queued);
}
#endif
}
void ComParticleSystem::ResetParticles() {
renderObjectDef.stageStartDelay.SetCount(renderObjectDef.particleSystem->NumStages());
// Free memory used for particles.
if (renderObjectDef.stageParticles.Count() > 0) {
for (int stageIndex = 0; stageIndex < renderObjectDef.stageParticles.Count(); stageIndex++) {
Mem_Free(renderObjectDef.stageParticles[stageIndex]);
}
renderObjectDef.stageParticles.Clear();
}
renderObjectDef.stageParticles.SetCount(renderObjectDef.particleSystem->NumStages());
for (int stageIndex = 0; stageIndex < renderObjectDef.particleSystem->NumStages(); stageIndex++) {
const ParticleSystem::Stage *stage = renderObjectDef.particleSystem->GetStage(stageIndex);
renderObjectDef.stageStartDelay[stageIndex] = stage->standardModule.startDelay.Evaluate(RANDOM_FLOAT(0, 1), 0);
int trailCount = (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::Trails)) ? stage->trailsModule.count : 0;
int particleSize = sizeof(Particle) + sizeof(Particle::Trail) * trailCount;
int size = stage->standardModule.count * particleSize;
renderObjectDef.stageParticles[stageIndex] = (Particle *)Mem_Alloc(size);
memset(renderObjectDef.stageParticles[stageIndex], 0, size);
}
}
void ComParticleSystem::Awake() {
if (playOnAwake) {
simulationStarted = true;
}
}
void ComParticleSystem::OnActive() {
ResetParticles();
ComRenderable::OnActive();
}
void ComParticleSystem::OnInactive() {
#if WITH_EDITOR
if (spriteHandle != -1) {
renderWorld->RemoveRenderObject(spriteHandle);
spriteHandle = -1;
}
#endif
ComRenderable::OnInactive();
}
bool ComParticleSystem::HasRenderObject(int renderObjectHandle) const {
#if WITH_EDITOR
if (this->spriteHandle == renderObjectHandle) {
return true;
}
#endif
return ComRenderable::HasRenderObject(renderObjectHandle);
}
int ComParticleSystem::GetAliveParticleCount() const {
int aliveCount = 0;
for (int stageIndex = 0; stageIndex < renderObjectDef.particleSystem->NumStages(); stageIndex++) {
const ParticleSystem::Stage *stage = renderObjectDef.particleSystem->GetStage(stageIndex);
const ParticleSystem::StandardModule &standardModule = stage->standardModule;
int trailCount = (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::Trails)) ? stage->trailsModule.count : 0;
for (int particleIndex = 0; particleIndex < standardModule.count; particleIndex++) {
int particleSize = sizeof(Particle) + sizeof(Particle::Trail) * trailCount;
// Get the particle pointer with the given particle index.
Particle *particle = (Particle *)((byte *)renderObjectDef.stageParticles[stageIndex] + particleIndex * particleSize);
if (particle->alive) {
aliveCount++;
}
}
}
return aliveCount;
}
void ComParticleSystem::Update() {
if (!IsActiveInHierarchy()) {
return;
}
if (!simulationStarted) {
return;
}
int elapsedTime = GetGameWorld()->GetTime() - GetGameWorld()->GetPrevTime();
currentTime += elapsedTime;
UpdateSimulation(currentTime);
}
void ComParticleSystem::UpdateSimulation(int currentTime) {
renderObjectDef.time = currentTime;
renderObjectDef.aabb.SetZero();
const Mat3x4 worldMatrix = GetEntity()->GetTransform()->GetMatrix();
bool simulationEnded = true;
for (int stageIndex = 0; stageIndex < renderObjectDef.particleSystem->NumStages(); stageIndex++) {
const ParticleSystem::Stage *stage = renderObjectDef.particleSystem->GetStage(stageIndex);
// Standard module
const ParticleSystem::StandardModule &standardModule = stage->standardModule;
// Is in delay time ?
int simulationTime = standardModule.simulationSpeed * currentTime - SEC2MILLI(renderObjectDef.stageStartDelay[stageIndex]);
if (simulationTime < 0) {
simulationEnded = false;
continue;
}
int cycleDuration = standardModule.lifeTime + standardModule.deadTime;
int curCycles = simulationTime / cycleDuration;
if (!standardModule.looping) {
if (curCycles > standardModule.maxCycles) {
continue;
}
}
if (stopTime != 0) {
if (currentTime > stopTime + cycleDuration) {
continue;
}
}
simulationEnded = false;
int inCycleTime = simulationTime - curCycles * cycleDuration;
int trailCount = (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::Trails)) ? stage->trailsModule.count : 0;
for (int particleIndex = 0; particleIndex < standardModule.count; particleIndex++) {
int particleGenTime = standardModule.lifeTime * standardModule.spawnBunching * particleIndex / standardModule.count;
int particleAge = inCycleTime - particleGenTime;
// Wrap elapsed time of this particle if it is needed
if (particleAge <= 0) {
if (standardModule.prewarm || curCycles > 0) {
particleAge += cycleDuration;
}
}
int particleSize = sizeof(Particle) + sizeof(Particle::Trail) * trailCount;
// Get the particle pointer with the given particle index
Particle *particle = (Particle *)((byte *)renderObjectDef.stageParticles[stageIndex] + particleIndex * particleSize);
// Check this particle is alive now
if (particleAge >= 0 && particleAge < standardModule.lifeTime) {
// Generate if this particle is not generated yet.
bool regenerate = !particle->generated;
if (curCycles > particle->cycle) {
if (inCycleTime > particleGenTime) {
if (!standardModule.looping) {
if (curCycles >= standardModule.maxCycles) {
particle->alive = false;
continue;
}
}
particle->cycle = curCycles;
regenerate = true;
}
if (curCycles - particle->cycle > 1) {
particle->cycle = curCycles - 1;
regenerate = true;
}
}
if (stopTime > 0) {
if (particleGenTime + particle->cycle * cycleDuration > stopTime) {
continue;
}
}
particle->alive = true;
if (regenerate) {
if (standardModule.simulationSpace == ParticleSystem::StandardModule::SimulationSpace::Global) {
particle->worldMatrix = worldMatrix;
}
InitializeParticle(particle, stage, (float)inCycleTime / cycleDuration);
}
ProcessTrail(particle, stage, particleAge);
} else {
particle->alive = false;
particle->generated = false;
particle->cycle = 0;
}
}
}
if (simulationEnded) {
simulationStarted = false;
stopTime = 0;
return;
}
ComRenderable::UpdateVisuals();
}
void ComParticleSystem::InitializeParticle(Particle *particle, const ParticleSystem::Stage *stage, float inCycleFrac) const {
particle->generated = true;
particle->initialSpeed = MeterToUnit(stage->standardModule.startSpeed.Evaluate(RANDOM_FLOAT(0, 1), inCycleFrac));
particle->initialSize = MeterToUnit(stage->standardModule.startSize.Evaluate(RANDOM_FLOAT(0, 1), inCycleFrac));
particle->initialAspectRatio = stage->standardModule.startAspectRatio.Evaluate(RANDOM_FLOAT(0, 1), inCycleFrac);
particle->initialAngle = stage->standardModule.startRotation.Evaluate(RANDOM_FLOAT(0, 1), inCycleFrac);
particle->initialAngle += RANDOM_FLOAT(-180, 180) * stage->standardModule.randomizeRotation;
particle->initialColor = stage->standardModule.startColor; //
if (stage->moduleFlags & (BIT(ParticleSystem::ModuleBit::LTSize) | BIT(ParticleSystem::ModuleBit::SizeBySpeed))) {
particle->randomSize = RANDOM_FLOAT(0, 1);
}
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTAspectRatio)) {
particle->randomAspectRatio = RANDOM_FLOAT(0, 1);
}
if (stage->moduleFlags & (BIT(ParticleSystem::ModuleBit::LTRotation) | BIT(ParticleSystem::ModuleBit::RotationBySpeed))) {
particle->randomAngularVelocity = RANDOM_FLOAT(0, 1);
}
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTSpeed)) {
particle->randomSpeed = RANDOM_FLOAT(0, 1);
}
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTForce)) {
particle->randomForce.x = RANDOM_FLOAT(0, 1);
particle->randomForce.y = RANDOM_FLOAT(0, 1);
particle->randomForce.z = RANDOM_FLOAT(0, 1);
}
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::Shape)) {
const ParticleSystem::ShapeModule &shapeModule = stage->shapeModule;
if (shapeModule.shape == ParticleSystem::ShapeModule::Shape::Box) {
particle->initialPosition.x = MeterToUnit(RANDOM_FLOAT(-shapeModule.extents.x, shapeModule.extents.x));
particle->initialPosition.y = MeterToUnit(RANDOM_FLOAT(-shapeModule.extents.y, shapeModule.extents.y));
particle->initialPosition.z = MeterToUnit(RANDOM_FLOAT(-shapeModule.extents.z, shapeModule.extents.z));
if (shapeModule.randomizeDir == 0) {
particle->direction = Vec3::unitZ;
} else {
Vec3 randomDir = Vec3::FromUniformSampleSphere(RANDOM_FLOAT(0, 1), RANDOM_FLOAT(0, 1));
particle->direction = Math::Lerp(Vec3::unitZ, randomDir, shapeModule.randomizeDir);
}
} else if (shapeModule.shape == ParticleSystem::ShapeModule::Shape::Sphere) {
float r = MeterToUnit(shapeModule.radius);
if (shapeModule.thickness > 0) {
r = RANDOM_FLOAT(r * (1.0f - shapeModule.thickness), r);
}
particle->initialPosition = Vec3::FromUniformSampleSphere(RANDOM_FLOAT(0, 1), RANDOM_FLOAT(0, 1));
particle->initialPosition *= r;
if (shapeModule.randomizeDir == 0) {
particle->direction = Vec3::unitZ;
} else {
Vec3 randomDir = Vec3::FromUniformSampleSphere(RANDOM_FLOAT(0, 1), RANDOM_FLOAT(0, 1));
particle->direction = Math::Lerp(Vec3::unitZ, randomDir, shapeModule.randomizeDir);
}
} else if (shapeModule.shape == ParticleSystem::ShapeModule::Shape::Circle) {
float r = MeterToUnit(shapeModule.radius);
if (shapeModule.thickness > 0) {
r = RANDOM_FLOAT(r * (1.0f - shapeModule.thickness), r);
}
particle->initialPosition.ToVec2() = Vec2::FromUniformSampleCircle(RANDOM_FLOAT(0, 1));
particle->initialPosition.z = 0;
particle->initialPosition *= r;
if (shapeModule.randomizeDir == 0) {
particle->direction = Vec3::unitZ;
} else {
Vec3 randomDir = Vec3::FromUniformSampleSphere(RANDOM_FLOAT(0, 1), RANDOM_FLOAT(0, 1));
particle->direction = Math::Lerp(Vec3::unitZ, randomDir, shapeModule.randomizeDir);
}
} else if (shapeModule.shape == ParticleSystem::ShapeModule::Shape::Cone) {
float r = MeterToUnit(shapeModule.radius);
if (shapeModule.thickness > 0) {
r = RANDOM_FLOAT(r * (1.0f - shapeModule.thickness), r);
}
Vec2 p = Vec2::FromUniformSampleCircle(RANDOM_FLOAT(0, 1));
particle->initialPosition.ToVec2() = p;
particle->initialPosition.z = 0;
particle->initialPosition *= r;
particle->direction = Vec3::unitZ;
if (r > FLT_EPSILON) {
float l2 = particle->initialPosition.LengthSqr();
if (l2 > FLT_EPSILON) {
float angleScale = l2 / (r * r);
if (shapeModule.randomizeDir > 0) {
angleScale = Math::Lerp(angleScale, RANDOM_FLOAT(-1.f, 1.f), shapeModule.randomizeDir);
}
float rotAngle = shapeModule.angle * angleScale;
Vec3 rotDir = Vec3(-p.y, p.x, 0);
Rotation rotation(Vec3::origin, rotDir, rotAngle);
particle->direction = rotation.RotatePoint(particle->direction);
}
}
}
} else {
particle->initialPosition.Set(0, 0, 0);
particle->direction.Set(0, 0, 0);
}
}
void ComParticleSystem::ProcessTrail(Particle *particle, const ParticleSystem::Stage *stage, int particleAge) {
ALIGN_AS32 Mat3x4 offsetMatrix;
if (stage->standardModule.simulationSpace == ParticleSystem::StandardModule::SimulationSpace::Global) {
offsetMatrix = GetEntity()->GetTransform()->GetMatrix().Inverse() * particle->worldMatrix;
}
int trailCount = (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::Trails)) ? stage->trailsModule.count : 0;
int pivotCount = 1 + trailCount;
for (int pivotIndex = 0; pivotIndex < pivotCount; pivotIndex++) {
Particle::Trail *trail = &particle->trails[pivotIndex];
float trailAge = particleAge;
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::Trails)) {
trailAge -= (stage->standardModule.lifeTime * stage->trailsModule.length) * pivotIndex / trailCount;
if (stage->trailsModule.trailCut) {
if (trailAge < 0) {
trailAge = 0;
}
}
}
float trailFrac = trailAge / stage->standardModule.lifeTime;
float trailSpeed;
if (stage->moduleFlags & (BIT(ParticleSystem::ModuleBit::SizeBySpeed) | BIT(ParticleSystem::ModuleBit::RotationBySpeed))) {
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::CustomPath)) {
trailSpeed = 0;
} else if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTSpeed)) {
trailSpeed = particle->initialSpeed + MeterToUnit(stage->speedOverLifetimeModule.speed.Evaluate(particle->randomSpeed, trailFrac));
} else {
trailSpeed = particle->initialSpeed;
}
}
// Compute size.
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTSize)) {
trail->size = particle->initialSize * stage->sizeOverLifetimeModule.size.Evaluate(particle->randomSize, trailFrac);
} else if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::SizeBySpeed)) {
float l = Math::Fabs(stage->sizeBySpeedModule.speedRange[1] - stage->sizeBySpeedModule.speedRange[0]);
float speedFrac = (UnitToMeter(trailSpeed) - stage->sizeBySpeedModule.speedRange[0]) / l;
trail->size = particle->initialSize * stage->sizeBySpeedModule.size.Evaluate(particle->randomSize, speedFrac);
} else {
trail->size = particle->initialSize;
}
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::Trails)) {
trail->size *= Math::Lerp(1.0f, stage->trailsModule.trailScale, (float)pivotIndex / trailCount);
}
// Compute aspect ratio.
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTAspectRatio)) {
trail->aspectRatio = particle->initialAspectRatio * stage->aspectRatioOverLifetimeModule.aspectRatio.Evaluate(particle->randomAspectRatio, trailFrac);
} else {
trail->aspectRatio = particle->initialAspectRatio;
}
// Compute rotation angle.
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTRotation)) {
float angularVelocity = stage->rotationOverLifetimeModule.rotation.Evaluate(particle->randomAngularVelocity, trailFrac);
trail->angle = particle->initialAngle + MILLI2SEC(trailAge) * angularVelocity;
} else if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::RotationBySpeed)) {
float l = Math::Fabs(stage->rotationBySpeedModule.speedRange[1] - stage->rotationBySpeedModule.speedRange[0]);
float speedFrac = (UnitToMeter(trailSpeed) - stage->rotationBySpeedModule.speedRange[0]) / l;
float angularVelocity = stage->rotationBySpeedModule.rotation.Evaluate(particle->randomSize, speedFrac);
trail->angle = particle->initialAngle + MILLI2SEC(trailAge) * angularVelocity;
} else {
trail->angle = particle->initialAngle;
}
// Compute color.
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTColor)) {
if (trailFrac < stage->colorOverLifetimeModule.fadeLocation) {
// fade in.
float f = trailFrac / stage->colorOverLifetimeModule.fadeLocation;
trail->color = Math::Lerp(stage->colorOverLifetimeModule.targetColor, particle->initialColor, f);
} else {
// fade out.
float f = (trailFrac - stage->colorOverLifetimeModule.fadeLocation) / (1.f - stage->colorOverLifetimeModule.fadeLocation);
trail->color = Math::Lerp(particle->initialColor, stage->colorOverLifetimeModule.targetColor, f);
}
} else {
trail->color = particle->initialColor;
}
// Compute position.
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::CustomPath)) {
ComputeTrailPositionFromCustomPath(stage->customPathModule, particle, trailFrac, trail);
} else if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTSpeed)) {
float dist = particle->initialSpeed * trailFrac + MeterToUnit(stage->speedOverLifetimeModule.speed.Integrate(particle->randomSpeed, trailFrac));
trail->position = particle->initialPosition + particle->direction * dist;
} else {
float dist = particle->initialSpeed * trailFrac;
trail->position = particle->initialPosition + particle->direction * dist;
}
// Apply force.
if (stage->moduleFlags & BIT(ParticleSystem::ModuleBit::LTForce)) {
Vec3 force(
MeterToUnit(stage->forceOverLifetimeModule.force[0].Evaluate(particle->randomForce.x, trailFrac)),
MeterToUnit(stage->forceOverLifetimeModule.force[1].Evaluate(particle->randomForce.y, trailFrac)),
MeterToUnit(stage->forceOverLifetimeModule.force[2].Evaluate(particle->randomForce.z, trailFrac)));
trail->position += force * 0.5f * trailFrac * trailFrac;
}
// Apply gravity.
trail->position.z -= MeterToUnit(stage->standardModule.gravity) * 0.5f * trailFrac * trailFrac;
if (stage->standardModule.simulationSpace == ParticleSystem::StandardModule::SimulationSpace::Global) {
trail->position = offsetMatrix * trail->position;
}
// Add trail bounds to the entity bounds.
float radius;
if (stage->standardModule.orientation == ParticleSystem::StandardModule::Orientation::Aimed ||
stage->standardModule.orientation == ParticleSystem::StandardModule::Orientation::AimedZ) {
radius = trail->size * 0.5f * 2.0f;
} else {
radius = trail->size * 0.5f;
}
renderObjectDef.aabb.AddAABB(Sphere(trail->position, radius).ToAABB());
}
}
void ComParticleSystem::ComputeTrailPositionFromCustomPath(const ParticleSystem::CustomPathModule &customPathModule, const Particle *particle, float t, Particle::Trail *trail) const {
if (customPathModule.customPath == ParticleSystem::CustomPathModule::CustomPath::Cone) {
float radialTheta = t * DEG2RAD(customPathModule.radialSpeed);
float s, c;
Math::SinCos(radialTheta, s, c);
c = c * (1.0f - t);
s = s * (1.0f - t);
trail->position.x = particle->initialPosition.x * c + particle->initialPosition.y * s;
trail->position.y = particle->initialPosition.y * c - particle->initialPosition.x * s;
trail->position.z = 0;
return;
}
if (customPathModule.customPath == ParticleSystem::CustomPathModule::CustomPath::Helix) {
float radialTheta = t * DEG2RAD(customPathModule.radialSpeed);
float s, c;
Math::SinCos(radialTheta, s, c);
trail->position.x = particle->initialPosition.x * c + particle->initialPosition.y * s;
trail->position.y = particle->initialPosition.y * c - particle->initialPosition.x * s;
trail->position.z = particle->initialPosition.z + t * particle->direction.z;
return;
}
if (customPathModule.customPath == ParticleSystem::CustomPathModule::CustomPath::Spherical) {
float radialTheta = t * DEG2RAD(customPathModule.radialSpeed);
float axialTheta = t * customPathModule.axialSpeed;
float s, c;
Math::SinCos(radialTheta, s, c);
Vec3 tmp = particle->initialPosition;
tmp.Normalize();
Vec3 rotDir = Vec3::unitZ.Cross(tmp);
Rotation rotation(Vec3::origin, rotDir, axialTheta);
Vec3 vec = rotation.RotatePoint(particle->initialPosition);
trail->position.x = vec.x * c + vec.y * s;
trail->position.y = vec.y * c - vec.x * s;
trail->position.z = vec.z;
return;
}
assert(0);
}
#if WITH_EDITOR
void ComParticleSystem::DrawGizmos(const RenderCamera *camera, bool selected, bool selectedByParent) {
// Fade icon alpha in near distance
float alpha = Clamp(spriteDef.worldMatrix.ToTranslationVec3().Distance(camera->GetState().origin) / MeterToUnit(8.0f), 0.01f, 1.0f);
spriteDef.materials[0]->GetPass()->constantColor[3] = alpha;
}
#endif
bool ComParticleSystem::IsAlive() const {
return simulationStarted;
}
void ComParticleSystem::Play() {
simulationStarted = true;
currentTime = 0;
stopTime = 0;
}
void ComParticleSystem::Stop() {
if (stopTime == 0) {
stopTime = currentTime;
}
}
void ComParticleSystem::Resume() {
simulationStarted = true;
}
void ComParticleSystem::Pause() {
simulationStarted = false;
}
void ComParticleSystem::UpdateVisuals() {
if (!IsInitialized() || !IsActiveInHierarchy()) {
return;
}
#if WITH_EDITOR
if (spriteHandle == -1) {
spriteHandle = renderWorld->AddRenderObject(&spriteDef);
} else {
renderWorld->UpdateRenderObject(spriteHandle, &spriteDef);
}
#endif
ComRenderable::UpdateVisuals();
}
void ComParticleSystem::TransformUpdated(const ComTransform *transform) {
#if WITH_EDITOR
spriteDef.worldMatrix.SetTranslation(transform->GetOrigin());
#endif
UpdateVisuals();
}
void ComParticleSystem::ParticleSystemReloaded() {
SetParticleSystemGuid(GetProperty("particleSystem").As<Guid>());
}
Guid ComParticleSystem::GetParticleSystemGuid() const {
if (renderObjectDef.particleSystem) {
const Str particleSystemPath = renderObjectDef.particleSystem->GetHashName();
return resourceGuidMapper.Get(particleSystemPath);
}
return Guid();
}
void ComParticleSystem::SetParticleSystemGuid(const Guid &guid) {
ChangeParticleSystem(guid);
UpdateVisuals();
}
BE_NAMESPACE_END
| 38.701592 | 183 | 0.649498 | redchew-fork |
745999a25b480d74ca6a1b28c68a70a257dccc3b | 8,465 | cc | C++ | tools/embedding_plugin/cc/kernels/v1/embedding_wrapper_fprop_v4.cc | quinnrong94/HugeCTR | 1068dc48b05a1219b393144dd3b61a1749f232df | [
"Apache-2.0"
] | 1 | 2021-06-04T04:03:54.000Z | 2021-06-04T04:03:54.000Z | tools/embedding_plugin/cc/kernels/v1/embedding_wrapper_fprop_v4.cc | quinnrong94/HugeCTR | 1068dc48b05a1219b393144dd3b61a1749f232df | [
"Apache-2.0"
] | null | null | null | tools/embedding_plugin/cc/kernels/v1/embedding_wrapper_fprop_v4.cc | quinnrong94/HugeCTR | 1068dc48b05a1219b393144dd3b61a1749f232df | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "embedding_wrapper.h"
#include "HugeCTR/include/embeddings/distributed_slot_sparse_embedding_hash.hpp"
#include "HugeCTR/include/embeddings/localized_slot_sparse_embedding_hash.hpp"
#include "HugeCTR/include/embeddings/localized_slot_sparse_embedding_one_hot.hpp"
#include "embedding_utils.hpp"
namespace HugeCTR {
namespace Version1 {
/** This function get input as a single tensor, rather that a list of tensors.
* Its inputs: row_offsets, value_tensors both are single tensors (stack from list of tensor.)
* TODO: Use NCCL to do memory transfer.
*/
template <typename TypeKey, typename TypeFP>
tensorflow::Status EmbeddingWrapper<TypeKey, TypeFP>::fprop_v4(
const tensorflow::Tensor* row_indices,
const tensorflow::Tensor* values,
const std::string& embedding_name,
const bool is_training,
const cudaStream_t& tf_stream,
tensorflow::Tensor* const forward_result) {
/*get input space*/
std::string input_space_name = embedding_name;
input_space_name += (is_training ? "_train" : "_eval");
std::shared_ptr<InputSpace> space = get_input_space(input_space_name);
if (!space) return tensorflow::errors::NotFound(__FILE__, ": ", __LINE__, ", Did not find ",
input_space_name, " in input_spaces.");
/*do distribute keys*/
const auto distribute_keys_func = get_item_from_map(distribute_keys_on_gpu_func_, embedding_name);
WRAPPER_REQUIRE_OK((this->*distribute_keys_func)(row_indices, values, embedding_name, is_training, space));
#ifndef NDEBUG
/*need synchronize streams? wait stream to finish distribute keys on GPU?*/
HugeCTR::CudaDeviceContext context;
for (size_t dev_id = 0; dev_id < resource_manager_->get_local_gpu_count(); ++dev_id) {
const auto& local_gpu = resource_manager_->get_local_gpu(dev_id);
context.set_device(local_gpu->get_device_id());
WRAPPER_CUDA_CHECK(cudaStreamSynchronize(local_gpu->get_stream()));
// check CSR results
std::unique_ptr<TypeKey []> host_row_offsets(new TypeKey[space->row_offsets_tensors_[dev_id].get_num_elements()]());
WRAPPER_CUDA_CHECK(cudaMemcpyAsync(host_row_offsets.get(),
space->row_offsets_tensors_[dev_id].get_ptr(),
space->row_offsets_tensors_[dev_id].get_size_in_bytes(),
cudaMemcpyDeviceToHost,
local_gpu->get_stream()));
std::unique_ptr<TypeKey []> host_values(new TypeKey[space->value_tensors_[dev_id].get_num_elements()]());
WRAPPER_CUDA_CHECK(cudaMemcpyAsync(host_values.get(),
space->value_tensors_[dev_id].get_ptr(),
space->value_tensors_[dev_id].get_size_in_bytes(),
cudaMemcpyDeviceToHost,
local_gpu->get_stream()));
WRAPPER_CUDA_CHECK(cudaStreamSynchronize(local_gpu->get_stream()));
std::cout << "dev_id = " << dev_id << ", row_offsets = ";
for (size_t i = 0; i < space->row_offsets_tensors_[dev_id].get_num_elements(); ++i) {
std::cout << host_row_offsets[i] << ", ";
}
std::cout << std::endl;
std::cout << "dev_id = " << dev_id << ", values = ";
for (size_t i = 0; i < space->value_tensors_[dev_id].get_num_elements(); ++i){
std::cout << host_values[i] << ", ";
}
std::cout << std::endl;
} // for dev_id
#endif
try {
/*do forward propagation*/
std::shared_ptr<IEmbedding> embedding = get_embedding(embedding_name);
if (!embedding) return tensorflow::errors::NotFound(__FILE__, ":", __LINE__, " ",
"Not found ", embedding_name);
embedding->forward(is_training);
/*get forward results*/
if (std::is_same<TypeFP, float>::value) {
embedding->get_forward_results_tf(is_training, true, reinterpret_cast<void*>(forward_result->flat<float>().data()));
} else if (std::is_same<TypeFP, __half>::value) {
embedding->get_forward_results_tf(is_training, true, reinterpret_cast<void*>(forward_result->flat<Eigen::half>().data()));
} else {
return tensorflow::errors::Unimplemented(__FILE__, ":", __LINE__, " TypeFP should be {float, __half}.");
}
} catch (const HugeCTR::internal_runtime_error& rt_error) {
return tensorflow::errors::Aborted(__FILE__, ":", __LINE__, " ", rt_error.what());
}
/*record cudaEvent on each stream*/
std::vector<cudaEvent_t> fprop_events = get_item_from_map(fprop_events_, embedding_name);
if (fprop_events.empty()) return tensorflow::errors::Aborted(__FILE__, ":", __LINE__, " ",
"Cannot find fprop cudaEvent_t for embedding: ", embedding_name);
for (size_t dev_id = 0; dev_id < resource_manager_->get_local_gpu_count(); ++dev_id){
CudaDeviceContext context;
const auto& local_gpu = resource_manager_->get_local_gpu(dev_id);
context.set_device(local_gpu->get_device_id());
WRAPPER_CUDA_CHECK(cudaEventRecord(fprop_events[dev_id], local_gpu->get_stream()));
}
/*synchronize tf stream with cuda stream*/
for (size_t dev_id = 0; dev_id < resource_manager_->get_local_gpu_count(); ++dev_id){
CudaDeviceContext context;
const auto& local_gpu = resource_manager_->get_local_gpu(dev_id);
context.set_device(local_gpu->get_device_id());
WRAPPER_CUDA_CHECK(cudaStreamWaitEvent(tf_stream, fprop_events[dev_id], 0));
}
return tensorflow::Status::OK();
}
template tensorflow::Status EmbeddingWrapper<long long, float>::fprop_v4(
const tensorflow::Tensor* row_indices,
const tensorflow::Tensor* values,
const std::string& embedding_name,
const bool is_training,
const cudaStream_t& tf_stream,
tensorflow::Tensor* const forward_result);
template tensorflow::Status EmbeddingWrapper<long long, __half>::fprop_v4(
const tensorflow::Tensor* row_indices,
const tensorflow::Tensor* values,
const std::string& embedding_name,
const bool is_training,
const cudaStream_t& tf_stream,
tensorflow::Tensor* const forward_result);
template tensorflow::Status EmbeddingWrapper<unsigned int, float>::fprop_v4(
const tensorflow::Tensor* row_indices,
const tensorflow::Tensor* values,
const std::string& embedding_name,
const bool is_training,
const cudaStream_t& tf_stream,
tensorflow::Tensor* const forward_result);
template tensorflow::Status EmbeddingWrapper<unsigned int, __half>::fprop_v4(
const tensorflow::Tensor* row_indices,
const tensorflow::Tensor* values,
const std::string& embedding_name,
const bool is_training,
const cudaStream_t& tf_stream,
tensorflow::Tensor* const forward_result);
} // namespace Version1
} // namespace HugeCTR | 50.993976 | 134 | 0.606025 | quinnrong94 |
745a0ee3bceb377b67e7d65d5daea7386e7644af | 3,671 | cc | C++ | tests/unit/base/Serialization_unittest.cc | cloner1984/shogun | 901c04b2c6550918acf0594ef8afeb5dcd840a7d | [
"BSD-3-Clause"
] | 2 | 2015-01-13T15:18:27.000Z | 2015-05-01T13:28:48.000Z | tests/unit/base/Serialization_unittest.cc | cloner1984/shogun | 901c04b2c6550918acf0594ef8afeb5dcd840a7d | [
"BSD-3-Clause"
] | null | null | null | tests/unit/base/Serialization_unittest.cc | cloner1984/shogun | 901c04b2c6550918acf0594ef8afeb5dcd840a7d | [
"BSD-3-Clause"
] | null | null | null | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Viktor Gal, Thoralf Klein, Evgeniy Andreev, Soeren Sonnenburg,
* Heiko Strathmann
*/
#include <gtest/gtest.h>
#include <shogun/labels/BinaryLabels.h>
#include <shogun/labels/MulticlassLabels.h>
#include <shogun/io/SerializableAsciiFile.h>
#include <shogun/classifier/svm/LibLinear.h>
#include <shogun/features/DataGenerator.h>
#include <shogun/features/DenseFeatures.h>
using namespace shogun;
TEST(Serialization,multiclass_labels)
{
index_t n=10;
index_t n_class=3;
CMulticlassLabels* labels=new CMulticlassLabels();
SGVector<float64_t> lab(n);
for (index_t i=0; i<n; ++i)
lab[i]=i%n_class;
labels->set_labels(lab);
labels->allocate_confidences_for(n_class);
SGVector<float64_t> conf(n_class);
for (index_t i=0; i<n_class; ++i)
conf[i]=CMath::randn_double();
for (index_t i=0; i<n; ++i)
labels->set_multiclass_confidences(i, conf);
/* create serialized copy */
const char* filename="multiclass_labels.txt";
CSerializableAsciiFile* file=new CSerializableAsciiFile(filename, 'w');
labels->save_serializable(file);
file->close();
SG_UNREF(file);
file=new CSerializableAsciiFile(filename, 'r');
CMulticlassLabels* labels_loaded=new CMulticlassLabels();
labels_loaded->load_serializable(file);
file->close();
SG_UNREF(file);
/* compare */
for (index_t i=0; i<n; ++i)
ASSERT(labels_loaded->get_labels()[i]==labels->get_labels()[i]);
for (index_t i=0; i<n; ++i)
{
for (index_t j=0; j<n_class; ++j)
{
//float64_t a=labels->get_multiclass_confidences(i)[j];
//float64_t b=labels_loaded->get_multiclass_confidences(i)[j];
// Add one multiclass serialization works
//float64_t diff=CMath::abs(a-b);
//EXPECT_LE(diff, 10E-15);
}
}
SG_UNREF(labels_loaded);
SG_UNREF(labels);
}
#ifdef HAVE_LAPACK
TEST(Serialization, liblinear)
{
index_t num_samples = 50;
CMath::init_random(13);
SGMatrix<float64_t> data =
CDataGenerator::generate_gaussians(num_samples, 2, 2);
CDenseFeatures<float64_t> features(data);
SGVector<index_t> train_idx(num_samples), test_idx(num_samples);
SGVector<float64_t> labels(num_samples);
for (index_t i = 0, j = 0; i < data.num_cols; ++i)
{
if (i % 2 == 0)
train_idx[j] = i;
else
test_idx[j++] = i;
labels[i/2] = (i < data.num_cols/2) ? 1.0 : -1.0;
}
CDenseFeatures<float64_t>* train_feats = (CDenseFeatures<float64_t>*)features.copy_subset(train_idx);
CDenseFeatures<float64_t>* test_feats = (CDenseFeatures<float64_t>*)features.copy_subset(test_idx);
CBinaryLabels* ground_truth = new CBinaryLabels(labels);
CLibLinear* liblin = new CLibLinear(1.0, train_feats, ground_truth);
liblin->set_epsilon(1e-5);
liblin->train();
CBinaryLabels* pred = liblin->apply(test_feats)->as<CBinaryLabels>();
for (int i = 0; i < num_samples; ++i)
EXPECT_EQ(ground_truth->get_int_label(i), pred->get_int_label(i));
SG_UNREF(pred);
/* save liblin */
const char* filename="trained_liblin.txt";
CSerializableAsciiFile* file=new CSerializableAsciiFile(filename, 'w');
liblin->save_serializable(file);
file->close();
SG_UNREF(file);
/* load liblin */
file=new CSerializableAsciiFile(filename, 'r');
CLibLinear* liblin_loaded=new CLibLinear();
liblin_loaded->load_serializable(file);
file->close();
SG_UNREF(file);
/* classify with the deserialized model */
pred = liblin_loaded->apply(test_feats)->as<CBinaryLabels>();
for (int i = 0; i < num_samples; ++i)
EXPECT_EQ(ground_truth->get_int_label(i), pred->get_int_label(i));
SG_UNREF(liblin_loaded);
SG_UNREF(liblin);
SG_UNREF(train_feats);
SG_UNREF(test_feats);
SG_UNREF(pred);
}
#endif
| 27.601504 | 102 | 0.723236 | cloner1984 |
745b3b103a8485a1a1ce73065ae3893fa8b5ab87 | 2,812 | cpp | C++ | Core/rt/vm/rt/android/libcore/luni/src/main/native/ZipUtilities.cpp | bugvm/robovm | 430cbeb4a9f49f48b982821b40741fad110efe57 | [
"MIT"
] | 29 | 2018-06-04T21:34:00.000Z | 2022-02-21T16:34:44.000Z | Core/rt/vm/rt/android/libcore/luni/src/main/native/ZipUtilities.cpp | bugvm/robovm | 430cbeb4a9f49f48b982821b40741fad110efe57 | [
"MIT"
] | 15 | 2018-03-02T03:38:56.000Z | 2021-03-22T02:06:14.000Z | Core/rt/vm/rt/android/libcore/luni/src/main/native/ZipUtilities.cpp | bugvm/robovm | 430cbeb4a9f49f48b982821b40741fad110efe57 | [
"MIT"
] | 6 | 2018-10-17T02:28:28.000Z | 2020-11-27T04:47:50.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "JniConstants.h"
#include "JniException.h"
#include "UniquePtr.h"
#include "ZipUtilities.h"
void throwExceptionForZlibError(JNIEnv* env, const char* exceptionClassName, int error,
NativeZipStream* stream) {
if (error == Z_MEM_ERROR) {
jniThrowOutOfMemoryError(env, NULL);
} else if (stream != NULL && stream->stream.msg != NULL) {
jniThrowException(env, exceptionClassName, stream->stream.msg);
} else {
jniThrowException(env, exceptionClassName, zError(error));
}
}
NativeZipStream::NativeZipStream() : input(NULL), inCap(0), mDict(NULL) {
// Let zlib use its default allocator.
stream.opaque = Z_NULL;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
}
NativeZipStream::~NativeZipStream() {
}
void NativeZipStream::setDictionary(JNIEnv* env, jbyteArray javaDictionary, int off, int len,
bool inflate) {
UniquePtr<jbyte[]> dictionaryBytes(new jbyte[len]);
if (dictionaryBytes.get() == NULL) {
jniThrowOutOfMemoryError(env, NULL);
return;
}
env->GetByteArrayRegion(javaDictionary, off, len, &dictionaryBytes[0]);
const Bytef* dictionary = reinterpret_cast<const Bytef*>(&dictionaryBytes[0]);
int err;
if (inflate) {
err = inflateSetDictionary(&stream, dictionary, len);
} else {
err = deflateSetDictionary(&stream, dictionary, len);
}
if (err != Z_OK) {
throwExceptionForZlibError(env, "java/lang/IllegalArgumentException", err, NULL);
return;
}
mDict.reset(dictionaryBytes.release());
}
void NativeZipStream::setInput(JNIEnv* env, jbyteArray buf, jint off, jint len) {
input.reset(new jbyte[len]);
if (input.get() == NULL) {
inCap = 0;
jniThrowOutOfMemoryError(env, NULL);
return;
}
inCap = len;
if (buf != NULL) {
env->GetByteArrayRegion(buf, off, len, &input[0]);
}
stream.next_in = reinterpret_cast<Bytef*>(&input[0]);
stream.avail_in = len;
}
NativeZipStream* toNativeZipStream(jlong address) {
return reinterpret_cast<NativeZipStream*>(static_cast<uintptr_t>(address));
}
| 33.47619 | 93 | 0.71835 | bugvm |
745d3eded819b3028db70cea94fa5983030c9704 | 8,994 | hxx | C++ | main/sw/source/filter/inc/wwstyles.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sw/source/filter/inc/wwstyles.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sw/source/filter/inc/wwstyles.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
/// @HTML
#ifndef WW_WWSTYLES_HXX
#define WW_WWSTYLES_HXX
class String; //yuck...
#include <sal/types.h>
namespace ww
{
enum sti
{
stiNormal = 0, // 0x0000
stiLev1 = 1, // 0x0001
stiLev2 = 2, // 0x0002
stiLev3 = 3, // 0x0003
stiLev4 = 4, // 0x0004
stiLev5 = 5, // 0x0005
stiLev6 = 6, // 0x0006
stiLev7 = 7, // 0x0007
stiLev8 = 8, // 0x0008
stiLev9 = 9, // 0x0009
stiLevFirst = stiLev1,
stiLevLast = stiLev9,
stiIndex1 = 10, // 0x000A
stiIndex2 = 11, // 0x000B
stiIndex3 = 12, // 0x000C
stiIndex4 = 13, // 0x000D
stiIndex5 = 14, // 0x000E
stiIndex6 = 15, // 0x000F
stiIndex7 = 16, // 0x0010
stiIndex8 = 17, // 0x0011
stiIndex9 = 18, // 0x0012
stiIndexFirst = stiIndex1,
stiIndexLast = stiIndex9,
stiToc1 = 19, // 0x0013
stiToc2 = 20, // 0x0014
stiToc3 = 21, // 0x0015
stiToc4 = 22, // 0x0016
stiToc5 = 23, // 0x0017
stiToc6 = 24, // 0x0018
stiToc7 = 25, // 0x0019
stiToc8 = 26, // 0x001A
stiToc9 = 27, // 0x001B
stiTocFirst = stiToc1,
stiTocLast = stiToc9,
stiNormIndent = 28, // 0x001C
stiFtnText = 29, // 0x001D
stiAtnText = 30, // 0x001E
stiHeader = 31, // 0x001F
stiFooter = 32, // 0x0020
stiIndexHeading = 33, // 0x0021
stiCaption = 34, // 0x0022
stiToCaption = 35, // 0x0023
stiEnvAddr = 36, // 0x0024
stiEnvRet = 37, // 0x0025
stiFtnRef = 38, // 0x0026 char style
stiAtnRef = 39, // 0x0027 char style
stiLnn = 40, // 0x0028 char style
stiPgn = 41, // 0x0029 char style
stiEdnRef = 42, // 0x002A char style
stiEdnText = 43, // 0x002B
stiToa = 44, // 0x002C
stiMacro = 45, // 0x002D
stiToaHeading = 46, // 0x002E
stiList = 47, // 0x002F
stiListBullet = 48, // 0x0030
stiListNumber = 49, // 0x0031
stiList2 = 50, // 0x0032
stiList3 = 51, // 0x0033
stiList4 = 52, // 0x0034
stiList5 = 53, // 0x0035
stiListBullet2 = 54, // 0x0036
stiListBullet3 = 55, // 0x0037
stiListBullet4 = 56, // 0x0038
stiListBullet5 = 57, // 0x0039
stiListNumber2 = 58, // 0x003A
stiListNumber3 = 59, // 0x003B
stiListNumber4 = 60, // 0x003C
stiListNumber5 = 61, // 0x003D
stiTitle = 62, // 0x003E
stiClosing = 63, // 0x003F
stiSignature = 64, // 0x0040
stiNormalChar = 65, // 0x0041 char style
stiBodyText = 66, // 0x0042
/*
stiBodyTextInd1 was orig stiBodyText2 in documentation, but that
collides with the other stiBodyText2 and this seems more reasonable.
cmc@openoffice.org
*/
stiBodyTextInd1 = 67, // 0x0043
stiListCont = 68, // 0x0044
stiListCont2 = 69, // 0x0045
stiListCont3 = 70, // 0x0046
stiListCont4 = 71, // 0x0047
stiListCont5 = 72, // 0x0048
stiMsgHeader = 73, // 0x0049
stiSubtitle = 74, // 0x004A
stiSalutation = 75, // 0x004B
stiDate = 76, // 0X004C
stiBodyText1I = 77, // 0x004D
stiBodyText1I2 = 78, // 0x004E
stiNoteHeading = 79, // 0x004F
stiBodyText2 = 80, // 0x0050
stiBodyText3 = 81, // 0x0051
stiBodyTextInd2 = 82, // 0x0052
stiBodyTextInd3 = 83, // 0x0053
stiBlockQuote = 84, // 0x0054
stiHyperlink = 85, // 0x0055 char style
stiHyperlinkFollowed = 86, // 0x0056 char style
stiStrong = 87, // 0x0057 char style
stiEmphasis = 88, // 0x0058 char style
stiNavPane = 89, // 0x0059 char style
stiPlainText = 90, // 0x005A
stiMax = 91, // number of defined sti's
stiUser = 0x0ffe, // user styles are distinguished by name
stiNil = 0x0fff // max for 12 bits
};
/** Find the WinWord sti index of an english style name.
When importing a RTF document we would like to treat styles as similar
to how word does as possible, to this end word will treat some styles
with special names as inbuilt styles, and some as user defined styles.
See OpenOffice.org issue 21881
(http://www.openoffice.org/issues/show_bug.cgi?id=21881)
and OpenOffice.org issue 17503
(http://www.openoffice.org/issues/show_bug.cgi?id=17503)
@param
rSting the Style name to test to see what winword sti word would give
such a name if it has no other information to work with (e.g. importing
a RTF document)
@return the sti that word would give it. stiUser if word would treat
it as a user defined style.
@author
<a href="mailto:cmc@openoffice.org">Caolán McNamara</a>
<a href="mailto:tono@openoffice.org">Takashi Ono</a>
*/
sti GetCanonicalStiFromEnglishName(const String &rString) throw();
/** Find the WinWord sti index of an old <= Word2 stc (style code)
When importing a Word 2 document we would like to treat styles as
similar to how word 8 does as possible, to this end word will treat
some styles with special codes as inbuilt styles, and some as user
defined styles.
@param
stc the Style code to test to see what winword sti word would give
such a code
@return the sti that word would give it. stiUser if word would treat
it as a user defined style.
@author
<a href="mailto:cmc@openoffice.org">Caolán McNamara</a>
*/
sti GetCanonicalStiFromStc(sal_uInt8 stc) throw();
/** Find the WinWord english name from a sti index
Map the word style index to it's english name
@param
sti the Style index
@return the name word would give it if it's an inbuilt name, otherwise
NULL
@author
<a href="mailto:cmc@openoffice.org">Caolán McNamara</a>
*/
const sal_Char* GetEnglishNameFromSti(sti eSti) throw();
/** Determine if the WinWord sti is standard Character Style
@param
sti the Style index
@return true if a known inbuild character style
@author
<a href="mailto:cmc@openoffice.org">Caolán McNamara</a>
*/
bool StandardStiIsCharStyle(sti eSti) throw();
} // namespace ww
#endif
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
| 41.256881 | 80 | 0.497887 | Grosskopf |
7460861f64eaebd73d4011f9b7508f67d6208ce8 | 3,706 | cc | C++ | src/plugin_environment.cc | blockspacer/flextool | d6594c7b2d4ce122a704075f68c7fab17d8bc737 | [
"Apache-2.0",
"MIT"
] | 22 | 2020-05-20T13:49:54.000Z | 2021-12-21T12:20:05.000Z | src/plugin_environment.cc | blockspacer/flextool | d6594c7b2d4ce122a704075f68c7fab17d8bc737 | [
"Apache-2.0",
"MIT"
] | 2 | 2020-05-12T20:19:21.000Z | 2020-10-12T15:40:27.000Z | src/plugin_environment.cc | blockspacer/flextool | d6594c7b2d4ce122a704075f68c7fab17d8bc737 | [
"Apache-2.0",
"MIT"
] | 3 | 2020-05-19T01:00:39.000Z | 2021-07-15T05:44:17.000Z | #include "flextool/plugin_environment.hpp" // IWYU pragma: associated
#include <base/files/file_path.h>
#include <base/base_paths.h>
#include <base/files/file_util.h>
#include <base/logging.h>
#include <base/path_service.h>
#include <base/check.h>
#include <base/notreached.h>
#include <base/threading/thread_task_runner_handle.h>
#include <base/sequence_checker.h>
#include <entt/signal/dispatcher.hpp>
#include <Corrade/PluginManager/AbstractManager.h>
#include <flexlib/ToolPlugin.hpp>
#include <basis/plugin_manager.h>
#include <sstream>
#include <algorithm>
namespace flextool {
ScopedPluginEnvironment::ScopedPluginEnvironment()
: main_events_dispatcher(std::make_unique<entt::dispatcher>())
{
DCHECK(base::ThreadTaskRunnerHandle::Get());
DETACH_FROM_SEQUENCE(sequence_checker_);
}
/// \note destroy dispatcher before plugin manager
/// see https://github.com/skypjack/entt/issues/103
ScopedPluginEnvironment::~ScopedPluginEnvironment()
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(main_events_dispatcher);
VLOG(9)
<< "PluginManager shutdown...";
using Shutdown
= backend::PluginManagerEvents::Shutdown;
main_events_dispatcher->trigger<Shutdown>();
}
/// \todo refactor long method
bool ScopedPluginEnvironment::init(
int argc
, char* argv[]
, const base::FilePath& pathToDirWithPlugins
, const base::FilePath& pathToPluginsConfFile
, const std::vector<base::FilePath>& pathsToExtraPluginFiles
, const base::FilePath& outDir)
{
DCHECK(argc > 0);
if (!base::PathService::Get(base::DIR_EXE, &dir_exe_)) {
NOTREACHED();
// stop app execution with EXIT_FAILURE
return
false;
}
{
DCHECK(main_events_dispatcher);
plug_mgr.connect_to_dispatcher(*main_events_dispatcher);
}
{
VLOG(9)
<< "creating"
" plugin::ToolPlugin::Events::Init";
DCHECK(main_events_dispatcher);
using Init
= plugin::ToolPlugin::Events::Init;
Init eventData{
argc
, argv
};
main_events_dispatcher->trigger<Init>(
std::move(eventData)
);
}
// sanity check
{
base::FilePath curDir;
base::GetCurrentDirectory(&curDir);
CHECK(curDir == outDir);
}
{
VLOG(9)
<< "running"
" backend::PluginManager::Events::Startup";
DCHECK(main_events_dispatcher);
// must have default value
DCHECK(!pathToDirWithPlugins.empty());
// must have default value
DCHECK(!pathToPluginsConfFile.empty());
using Startup
= backend::PluginManagerEvents::Startup;
Startup eventData{
pathToDirWithPlugins
, pathToPluginsConfFile
, pathsToExtraPluginFiles
};
main_events_dispatcher->trigger<
Startup
>(std::move(eventData));
}
/// \todo allow plugins to notify other plugins about
/// their startup with custom data
/// all you need is to store main_events_dispatcher in plugin
/// and send startup event via that main_events_dispatcher
/// other plugins must load special library or headers
/// to process that startup event with same main_events_dispatcher
// each loaded plugin must receive |connect_plugins_to_dispatcher|
if(!plug_mgr.countLoadedPlugins()) {
LOG(WARNING)
<< "unable to find plugins in plugins directory: "
<< pathToDirWithPlugins;
}
{
VLOG(9)
<< "running"
" plug_mgr.connect_plugins_to_dispatcher";
DCHECK(main_events_dispatcher);
plug_mgr.connect_plugins_to_dispatcher(
*main_events_dispatcher);
}
return
true;
}
} // flextool
| 24.706667 | 70 | 0.675121 | blockspacer |
7462bd0a41b5e3a56b50f3eee4a2baa4d171ee38 | 26,745 | inl | C++ | applications/plugins/InvertibleFVM/InvertibleFVMForceField.inl | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | applications/plugins/InvertibleFVM/InvertibleFVMForceField.inl | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | applications/plugins/InvertibleFVM/InvertibleFVMForceField.inl | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program 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 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_COMPONENT_FORCEFIELD_TETRAHEDRONFEMFORCEFIELD_INL
#define SOFA_COMPONENT_FORCEFIELD_TETRAHEDRONFEMFORCEFIELD_INL
#include "InvertibleFVMForceField.h"
#include <sofa/core/behavior/ForceField.inl>
#include <sofa/core/visual/VisualParams.h>
#include <SofaBaseTopology/GridTopology.h>
#include <sofa/simulation/Simulation.h>
#include <sofa/helper/decompose.h>
#include <sofa/helper/gl/template.h>
#include <assert.h>
#include <iostream>
#include <set>
//#include <SofaBaseLinearSolver/CompressedRowSparseMatrix.h>
namespace sofa
{
namespace component
{
namespace forcefield
{
using std::set;
using namespace sofa::defaulttype;
template <class DataTypes>
void InvertibleFVMForceField<DataTypes>::reset()
{
//serr<<"InvertibleFVMForceField<DataTypes>::reset"<<sendl;
}
template <class DataTypes>
void InvertibleFVMForceField<DataTypes>::init()
{
const VecReal& youngModulus = _youngModulus.getValue();
minYoung=youngModulus[0];
maxYoung=youngModulus[0];
for (unsigned i=0; i<youngModulus.size(); i++)
{
if (youngModulus[i]<minYoung) minYoung=youngModulus[i];
if (youngModulus[i]>maxYoung) maxYoung=youngModulus[i];
}
// ParallelDataThrd is used to build the matrix asynchronusly (when listening = true)
// This feature is activated when callin handleEvent with ParallelizeBuildEvent
// At init parallelDataSimu == parallelDataThrd (and it's the case since handleEvent is called)
this->core::behavior::ForceField<DataTypes>::init();
_mesh = this->getContext()->getMeshTopology();
if (_mesh==NULL)
{
serr << "ERROR(InvertibleFVMForceField): object must have a BaseMeshTopology."<<sendl;
return;
}
#ifdef SOFA_NEW_HEXA
if (_mesh==NULL || (_mesh->getNbTetrahedra()<=0 && _mesh->getNbHexahedra()<=0))
#else
if (_mesh==NULL || (_mesh->getNbTetrahedra()<=0 && _mesh->getNbCubes()<=0))
#endif
{
serr << "ERROR(InvertibleFVMForceField): object must have a tetrahedric BaseMeshTopology."<<sendl;
return;
}
if (!_mesh->getTetrahedra().empty())
{
_indexedTetra = & (_mesh->getTetrahedra());
}
else
{
core::topology::BaseMeshTopology::SeqTetrahedra* tetrahedra = new core::topology::BaseMeshTopology::SeqTetrahedra;
#ifdef SOFA_NEW_HEXA
int nbcubes = _mesh->getNbHexahedra();
#else
int nbcubes = _mesh->getNbCubes();
#endif
// These values are only correct if the mesh is a grid topology
int nx = 2;
int ny = 1;
// int nz = 1;
{
topology::GridTopology* grid = dynamic_cast<topology::GridTopology*>(_mesh);
if (grid != NULL)
{
nx = grid->getNx()-1;
ny = grid->getNy()-1;
// nz = grid->getNz()-1;
}
}
// Tesselation of each cube into 6 tetrahedra
tetrahedra->reserve(nbcubes*6);
for (int i=0; i<nbcubes; i++)
{
// if (flags && !flags->isCubeActive(i)) continue;
#ifdef SOFA_NEW_HEXA
core::topology::BaseMeshTopology::Hexa c = _mesh->getHexahedron(i);
#define swap(a,b) { int t = a; a = b; b = t; }
if (!((i%nx)&1))
{
// swap all points on the X edges
swap(c[0],c[1]);
swap(c[3],c[2]);
swap(c[4],c[5]);
swap(c[7],c[6]);
}
if (((i/nx)%ny)&1)
{
// swap all points on the Y edges
swap(c[0],c[3]);
swap(c[1],c[2]);
swap(c[4],c[7]);
swap(c[5],c[6]);
}
if ((i/(nx*ny))&1)
{
// swap all points on the Z edges
swap(c[0],c[4]);
swap(c[1],c[5]);
swap(c[2],c[6]);
swap(c[3],c[7]);
}
#undef swap
typedef core::topology::BaseMeshTopology::Tetra Tetra;
tetrahedra->push_back(Tetra(c[0],c[5],c[1],c[6]));
tetrahedra->push_back(Tetra(c[0],c[1],c[3],c[6]));
tetrahedra->push_back(Tetra(c[1],c[3],c[6],c[2]));
tetrahedra->push_back(Tetra(c[6],c[3],c[0],c[7]));
tetrahedra->push_back(Tetra(c[6],c[7],c[0],c[5]));
tetrahedra->push_back(Tetra(c[7],c[5],c[4],c[0]));
#else
core::topology::BaseMeshTopology::Cube c = _mesh->getCube(i);
int sym = 0;
if (!((i%nx)&1)) sym+=1;
if (((i/nx)%ny)&1) sym+=2;
if ((i/(nx*ny))&1) sym+=4;
typedef core::topology::BaseMeshTopology::Tetra Tetra;
tetrahedra->push_back(Tetra(c[0^sym],c[5^sym],c[1^sym],c[7^sym]));
tetrahedra->push_back(Tetra(c[0^sym],c[1^sym],c[2^sym],c[7^sym]));
tetrahedra->push_back(Tetra(c[1^sym],c[2^sym],c[7^sym],c[3^sym]));
tetrahedra->push_back(Tetra(c[7^sym],c[2^sym],c[0^sym],c[6^sym]));
tetrahedra->push_back(Tetra(c[7^sym],c[6^sym],c[0^sym],c[5^sym]));
tetrahedra->push_back(Tetra(c[6^sym],c[5^sym],c[4^sym],c[0^sym]));
#endif
}
_indexedTetra = tetrahedra;
}
reinit(); // compute per-element stiffness matrices and other precomputed values
// sout << "InvertibleFVMForceField: init OK, "<<_indexedTetra->size()<<" tetra."<<sendl;
}
template <class DataTypes>
inline void InvertibleFVMForceField<DataTypes>::reinit()
{
if (!this->mstate) return;
if (!_mesh->getTetrahedra().empty())
{
_indexedTetra = & (_mesh->getTetrahedra());
}
//serr<<"InvertibleFVMForceField<DataTypes>::reinit"<<sendl;
const VecCoord& p = this->mstate->read(core::ConstVecCoordId::restPosition())->getValue();
_initialPoints.setValue(p);
_initialTransformation.resize( _indexedTetra->size() );
_initialRotation.resize( _indexedTetra->size() );
_U.resize( _indexedTetra->size() );
_V.resize( _indexedTetra->size() );
_b.resize( _indexedTetra->size() );
unsigned int i=0;
typename VecTetra::const_iterator it;
for( it = _indexedTetra->begin(), i = 0 ; it != _indexedTetra->end() ; ++it, ++i )
{
const Index &a = (*it)[0];
const Index &b = (*it)[1];
const Index &c = (*it)[2];
const Index &d = (*it)[3];
const VecCoord &initialPoints=_initialPoints.getValue();
// edges
Coord ab = initialPoints[b]-initialPoints[a];
Coord ac = initialPoints[c]-initialPoints[a];
Coord ad = initialPoints[d]-initialPoints[a];
Coord bc = initialPoints[c]-initialPoints[b];
Coord bd = initialPoints[d]-initialPoints[b];
//Coord cd = initialPoints[d]-initialPoints[c];
// the initial edge matrix
Transformation A;
A[0] = ab;
A[1] = ac;
A[2] = ad;
serr<<"A"<< A<<sendl;
//Transformation R_0_1;
helper::Decompose<Real>::polarDecomposition( A, _initialRotation[i] );
_initialRotation[i].transpose();
//_initialRotation[i] = R_0_1;
if( _verbose.getValue() ) serr<<"InvertibleFVMForceField initialRotation "<<_initialRotation[i]<<sendl;
_initialTransformation[i].invert( _initialRotation[i] * A );
/*serr<<"R_0_1 * A "<<R_0_1 * A<<sendl;
serr<<"R_0_1.transposed() * A "<<R_0_1.transposed() * A<<sendl;
serr<<" A * R_0_1 "<< A*R_0_1<<sendl;
serr<<" A * R_0_1.transposed() "<< A*R_0_1.transposed()<<sendl;
ab = R_0_1.transposed() * ab;
ac = R_0_1.transposed() * ac;
ad = R_0_1.transposed() * ad;
bc = R_0_1.transposed() * bc;
bd = R_0_1.transposed() * bd;
A[0] = ab;
A[1] = ac;
A[2] = ad;
serr<<"R_0_1 * edges "<<A<<sendl;
Coord rotateda = R_0_1.transposed() * initialPoints[a];
Coord rotatedb = R_0_1.transposed() * initialPoints[b];
Coord rotatedc = R_0_1.transposed() * initialPoints[c];
Coord rotatedd = R_0_1.transposed() * initialPoints[d];
serr<<"rotateda "<<rotateda<<sendl;
serr<<"rotatedb "<<rotatedb<<sendl;
serr<<"rotatedc "<<rotatedc<<sendl;
serr<<"rotatedd "<<rotatedd<<sendl;
ab = rotatedb-rotateda;
ac = rotatedc-rotateda;
ad = rotatedd-rotateda;
bc = rotatedc-rotatedb;
bd = rotatedd-rotatedb;
A[0] = ab;
A[1] = ac;
A[2] = ad;
serr<<"rotated A"<< A<<sendl;*/
/* ab = R_0_1 * ab;
ac = R_0_1 * ac;
ad = R_0_1 * ad;
bc = R_0_1 * bc;
bd = R_0_1 * bd;*/
if( _verbose.getValue() ) serr<<"InvertibleFVMForceField _initialTransformation "<<A<<" "<<_initialTransformation[i]<<sendl;
// the normals (warning: the cross product gives a normal weighted by 2 times the area of the triangle)
Coord N3 = cross( ab, ac ); // face (a,b,c)
Coord N2 = cross( ad, ab ); // face (a,d,b)
Coord N1 = cross( ac, ad ); // face (a,c,d)
Coord N0 = cross( bd, bc ); // face (b,c,d)
// the node ordering changes the normal directions
Real coef = determinant(A)>0 ? (Real)(1/6.0) : (Real)(-1/6.0);
//_initialRotation[i].transpose();
////// compute b_i = -(Nj+Nk+Nl)/3 where N_j are the area-weighted normals of the triangles incident to the node i
_b[i][0] = /*_initialRotation[i] **/ ( N1 + N2 + N3 ) * coef;
_b[i][1] = /*_initialRotation[i] **/ ( N0 + N2 + N3 ) * coef;
_b[i][2] = /*_initialRotation[i] **/ ( N0 + N1 + N3 ) * coef;
//_b[i][3] = ( N0 + N1 + N2 ) * coef;
if( _verbose.getValue() && determinant(A) < 0 ) serr<<"detA "<<determinant(A)<<sendl;
serr<<"InvertibleFVMForceField b "<<sendl;
serr<<_b[i][0]<<sendl;
serr<<_b[i][1]<<sendl;
serr<<_b[i][2]<<sendl;
}
}
template<class DataTypes>
inline void InvertibleFVMForceField<DataTypes>::addForce (const core::MechanicalParams* /*mparams*/ /* PARAMS FIRST */, DataVecDeriv& d_f, const DataVecCoord& d_x, const DataVecDeriv& /* d_v */)
{
VecDeriv& f = *d_f.beginEdit();
const VecCoord& p = d_x.getValue();
f.resize(p.size());
unsigned int elementIndex;
typename VecTetra::const_iterator it;
for( it=_indexedTetra->begin(), elementIndex=0 ; it!=_indexedTetra->end() ; ++it,++elementIndex )
{
const Index &a = (*it)[0];
const Index &b = (*it)[1];
const Index &c = (*it)[2];
const Index &d = (*it)[3];
Transformation A;
A[0] = p[b]-p[a];
A[1] = p[c]-p[a];
A[2] = p[d]-p[a];
// tests
//A[0] = Coord(2,0,0)-p[a];
//A[1] = Coord(0,2,0)-p[a];
//A[2] = Coord(0,0,-2)-p[a];
//A[0] = Coord(1,1,0)-p[a];
//A[0] = Coord(1,0,-1)-p[a];
//A[0] = Coord(0.5,0,0)-p[a];
//A[0] = Coord(1,2,0)-p[a];
//A[1] = Coord(0.5,0,0)-p[a];
//A[2] = Coord(1,0,2)-p[a];
if( _verbose.getValue() ) serr<<"InvertibleFVMForceField currentTransf "<<A<<sendl;
Mat<3,3,Real> F = /*_initialRotation[elementIndex] **/ A * _initialTransformation[elementIndex];
if( _verbose.getValue() ) serr<<"InvertibleFVMForceField F "<<F<<" (det= "<<determinant(F)<<")"<<sendl;
Mat<3,3,Real> U, V; // the two rotations
Vec<3,Real> F_diagonal, P_diagonal; // diagonalized strain, diagonalized stress
helper::Decompose<Real>::SVD_stable( F, U, F_diagonal, V );
// isotrope hookean material defined by P_diag = 2*mu*(F_diag-Id)+lambda*tr(F_diag-Id)*Id
const VecReal& localStiffnessFactor = _localStiffnessFactor.getValue();
Real youngModulusElement;
if (_youngModulus.getValue().size() == _indexedTetra->size()) youngModulusElement = _youngModulus.getValue()[elementIndex];
else if (_youngModulus.getValue().size() > 0) youngModulusElement = _youngModulus.getValue()[0];
else
{
setYoungModulus(500.0f);
youngModulusElement = _youngModulus.getValue()[0];
}
const Real youngModulus = (localStiffnessFactor.empty() ? 1.0f : localStiffnessFactor[elementIndex*localStiffnessFactor.size()/_indexedTetra->size()])*youngModulusElement;
const Real poissonRatio = _poissonRatio.getValue();
Real lambda = (youngModulus*poissonRatio) / ((1+poissonRatio)*(1-2*poissonRatio));
Real mu = youngModulus / (/*2**/(1+poissonRatio));
//Real volume = helper::rabs( determinant( A ) ) / (Real)6.;
//lambda *= volume;
//mu *= volume;
//serr<<F_diagonal<<sendl;
F_diagonal[0] -= 1;
F_diagonal[1] -= 1;
F_diagonal[2] -= 1;
P_diagonal = F_diagonal* /*2**/ mu;
Real tmp = lambda*(F_diagonal[0]+F_diagonal[1]+F_diagonal[2]);
P_diagonal[0] += tmp;
P_diagonal[1] += tmp;
P_diagonal[2] += tmp;
/*for( int i = 0 ; i<3; ++i )
if( fabs(P_diagonal[i]) < 1e-6 )
P_diagonal[i] = 0;*/
if( _verbose.getValue() ) serr<<"InvertibleFVMForceField P_diagonal "<<P_diagonal<<sendl;
// TODO optimize this computation without having to use a 3x3 matrix
Mat<3,3,Real> P; //P_diag_M.clear();
P[0][0] = P_diagonal[0];
P[1][1] = P_diagonal[1];
P[2][2] = P_diagonal[2];
//if( _verbose.getValue() ) serr<<"InvertibleFVMForceField P "<<P<<sendl;
P = _initialRotation[elementIndex] * U * P * V.transposed();
_U[elementIndex].transpose( U );
_V[elementIndex] = V;
//serr<<F<<sendl;
// //F.invert(F);
// F[0][0] -= 1;
// F[1][1] -= 1;
// F[2][2] -= 1;
// P = F*/*2**/mu;
// tmp = lambda*(F[0][0]+F[1][1]+F[2][2]);
// P[0][0] += tmp;
// P[1][1] += tmp;
// P[2][2] += tmp;
// P = _initialRotation[elementIndex].transposed() * P;
Deriv G0 = P * _b[elementIndex][0];
Deriv G1 = P * _b[elementIndex][1];
Deriv G2 = P * _b[elementIndex][2];
//Deriv G3 = P * _b[elementIndex][3];
if( _verbose.getValue() )
{
serr<<"InvertibleFVMForceField forcesG "<<sendl;
serr<<G0<<sendl;
serr<<G1<<sendl;
serr<<G2<<sendl;
serr<<(-G0-G1-G2)<<sendl;
}
f[a] += G0;
f[b] += G1;
f[c] += G2;
f[d] += (-G0-G1-G2); // null force sum
//f[d] += G3;
//if( (G3 +G0+G1+G2).norm() > 1e-5 ) serr<<"force sum not null "<<G3<<" "<<(-(G0+G1+G2))<<sendl;
}
d_f.endEdit();
}
template<class DataTypes>
inline void InvertibleFVMForceField<DataTypes>::addDForce(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& d_df, const DataVecDeriv& d_dx)
{
return;
//serr<<"InvertibleFVMForceField::addDForce is not implemented\n";
VecDeriv& df = *d_df.beginEdit();
const VecDeriv& dx = d_dx.getValue();
Real kFactor = (Real)mparams->kFactorIncludingRayleighDamping(this->rayleighStiffness.getValue());
df.resize(dx.size());
unsigned int i;
typename VecTetra::const_iterator it;
for(it = _indexedTetra->begin(), i = 0 ; it != _indexedTetra->end() ; ++it, ++i)
{
Index a = (*it)[0];
Index b = (*it)[1];
Index c = (*it)[2];
Index d = (*it)[3];
// edges
//const VecCoord &initialPoints=_initialPoints.getValue();
/*Coord ab = initialPoints[b]+dx[b]-(initialPoints[a]+dx[a]);
Coord ac = initialPoints[c]+dx[c]-(initialPoints[a]+dx[a]);
Coord ad = initialPoints[d]+dx[d]-(initialPoints[a]+dx[a]);*/
Coord ab = dx[b]-(dx[a]);
Coord ac = dx[c]-(dx[a]);
Coord ad = dx[d]-(dx[a]);
// the initial edge matrix
Transformation A;
A[0] = ab;
A[1] = ac;
A[2] = ad;
Mat<3,3,Real> F = A * _initialTransformation[i];
//serr<<"addDForce F "<<F<<sendl;
Mat<3,3,Real> F_diagonal = _U[i] * F * _V[i];
const VecReal& localStiffnessFactor = _localStiffnessFactor.getValue();
Real youngModulusElement;
if (_youngModulus.getValue().size() == _indexedTetra->size()) youngModulusElement = _youngModulus.getValue()[i];
else if (_youngModulus.getValue().size() > 0) youngModulusElement = _youngModulus.getValue()[0];
else
{
setYoungModulus(500.0f);
youngModulusElement = _youngModulus.getValue()[0];
}
const Real youngModulus = (localStiffnessFactor.empty() ? 1.0f : localStiffnessFactor[i*localStiffnessFactor.size()/_indexedTetra->size()])*youngModulusElement;
const Real poissonRatio = _poissonRatio.getValue();
Real lambda = (youngModulus*poissonRatio) / ((1+poissonRatio)*(1-2*poissonRatio));
Real mu = youngModulus / (/*2**/(1+poissonRatio));
//serr<<F_diagonal<<sendl;
Mat<3,3,Real> P_diagonal;
F_diagonal[0][0] -= 1;
F_diagonal[1][1] -= 1;
F_diagonal[2][2] -= 1;
P_diagonal = F_diagonal* /*2**/ mu;
Real tmp = lambda*(F_diagonal[0][0]+F_diagonal[1][1]+F_diagonal[2][2]);
P_diagonal[0][0] += tmp;
P_diagonal[1][1] += tmp;
P_diagonal[2][2] += tmp;
//serr<<"addDForce F_diagonal "<<F_diagonal<<sendl;
//serr<<"addDForce P_diagonal "<<P_diagonal<<sendl;
//serr<<"InvertibleFVMForceField P_diagonal "<<P_diagonal<<sendl;
Mat<3,3,Real> P = _initialRotation[i] * _U[i].transposed() * P_diagonal * _V[i] * kFactor;
Deriv G0 = P * _b[i][0];
Deriv G1 = P * _b[i][1];
Deriv G2 = P * _b[i][2];
//Deriv G3 = forceTmp * _b[elementIndex][3];
df[a] += G0;
df[b] += G1;
df[c] += G2;
df[d] += (-G0-G1-G2);
}
d_df.endEdit();
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
template<class DataTypes>
void InvertibleFVMForceField<DataTypes>::draw(const core::visual::VisualParams* vparams)
{
if (!vparams->displayFlags().getShowForceFields()) return;
if (!this->mstate) return;
const VecCoord& x = this->mstate->read(core::ConstVecCoordId::position())->getValue();
const bool edges = (drawAsEdges.getValue() || vparams->displayFlags().getShowWireFrame());
const bool heterogeneous = (drawHeterogeneousTetra.getValue() && minYoung!=maxYoung);
const VecReal & youngModulus = _youngModulus.getValue();
vparams->drawTool()->setLightingEnabled(false);
if (edges)
{
std::vector< Vector3 > points[3];
typename VecTetra::const_iterator it;
int i;
for(it = _indexedTetra->begin(), i = 0 ; it != _indexedTetra->end() ; ++it, ++i)
{
Index a = (*it)[0];
Index b = (*it)[1];
Index c = (*it)[2];
Index d = (*it)[3];
Coord pa = x[a];
Coord pb = x[b];
Coord pc = x[c];
Coord pd = x[d];
// glColor4f(0,0,1,1);
points[0].push_back(pa);
points[0].push_back(pb);
points[0].push_back(pc);
points[0].push_back(pd);
// glColor4f(0,0.5,1,1);
points[1].push_back(pa);
points[1].push_back(pc);
points[1].push_back(pb);
points[1].push_back(pd);
// glColor4f(0,1,1,1);
points[2].push_back(pa);
points[2].push_back(pd);
points[2].push_back(pb);
points[2].push_back(pc);
if(heterogeneous)
{
float col = (float)((youngModulus[i]-minYoung) / (maxYoung-minYoung));
float fac = col * 0.5f;
Vec<4,float> color2 = Vec<4,float>(col , 0.5f - fac , 1.0f-col,1.0f);
Vec<4,float> color3 = Vec<4,float>(col , 1.0f - fac , 1.0f-col,1.0f);
Vec<4,float> color4 = Vec<4,float>(col+0.5f , 1.0f - fac , 1.0f-col,1.0f);
vparams->drawTool()->drawLines(points[0],1,color2 );
vparams->drawTool()->drawLines(points[1],1,color3 );
vparams->drawTool()->drawLines(points[2],1,color4 );
for(unsigned int i=0 ; i<3 ; i++) points[i].clear();
}
}
if(!heterogeneous)
{
vparams->drawTool()->drawLines(points[0], 1, Vec<4,float>(0.0,0.5,1.0,1.0));
vparams->drawTool()->drawLines(points[1], 1, Vec<4,float>(0.0,1.0,1.0,1.0));
vparams->drawTool()->drawLines(points[2], 1, Vec<4,float>(0.5,1.0,1.0,1.0));
}
}
else
{
std::vector< Vector3 > points[4];
typename VecTetra::const_iterator it;
int i;
for(it = _indexedTetra->begin(), i = 0 ; it != _indexedTetra->end() ; ++it, ++i)
{
Index a = (*it)[0];
Index b = (*it)[1];
Index c = (*it)[2];
Index d = (*it)[3];
//Coord center = (x[a]+x[b]+x[c]+x[d])*0.125;
// Coord pa = (x[a]+center)*(Real)0.666667;
// Coord pb = (x[b]+center)*(Real)0.666667;
// Coord pc = (x[c]+center)*(Real)0.666667;
// Coord pd = (x[d]+center)*(Real)0.666667;
Coord pa = x[a];
Coord pb = x[b];
Coord pc = x[c];
Coord pd = x[d];
// glColor4f(0,0,1,1);
points[0].push_back(pa);
points[0].push_back(pb);
points[0].push_back(pc);
// glColor4f(0,0.5,1,1);
points[1].push_back(pb);
points[1].push_back(pc);
points[1].push_back(pd);
// glColor4f(0,1,1,1);
points[2].push_back(pc);
points[2].push_back(pd);
points[2].push_back(pa);
// glColor4f(0.5,1,1,1);
points[3].push_back(pd);
points[3].push_back(pa);
points[3].push_back(pb);
if(heterogeneous)
{
float col = (float)((youngModulus[i]-minYoung) / (maxYoung-minYoung));
float fac = col * 0.5f;
Vec<4,float> color1 = Vec<4,float>(col , 0.0f - fac , 1.0f-col,1.0f);
Vec<4,float> color2 = Vec<4,float>(col , 0.5f - fac , 1.0f-col,1.0f);
Vec<4,float> color3 = Vec<4,float>(col , 1.0f - fac , 1.0f-col,1.0f);
Vec<4,float> color4 = Vec<4,float>(col+0.5f , 1.0f - fac , 1.0f-col,1.0f);
vparams->drawTool()->drawTriangles(points[0],color1 );
vparams->drawTool()->drawTriangles(points[1],color2 );
vparams->drawTool()->drawTriangles(points[2],color3 );
vparams->drawTool()->drawTriangles(points[3],color4 );
for(unsigned int i=0 ; i<4 ; i++) points[i].clear();
}
std::vector< Vector3 > pointsl(2);
pointsl[0] = x[a];
pointsl[1] = x[a] - _b[i][0];
vparams->drawTool()->drawLines( pointsl, 5, Vec<4,float>(1,1,1,1.0f) );
pointsl[0] = x[b];
pointsl[1] = x[b] - _b[i][1];
vparams->drawTool()->drawLines( pointsl, 5, Vec<4,float>(1,1,1,1.0f) );
pointsl[0] = x[c];
pointsl[1] = x[c] - _b[i][2];
vparams->drawTool()->drawLines( pointsl, 5, Vec<4,float>(1,1,1,1.0f) );
pointsl[0] = x[d];
pointsl[1] = x[d] + (_b[i][0]+_b[i][1]+_b[i][2]);
vparams->drawTool()->drawLines( pointsl, 5, Vec<4,float>(1,1,1,1.0f) );
std::vector< Vector3 > pointsp(1);
pointsp[0] = x[a];
vparams->drawTool()->drawPoints( pointsp, 20, Vec<4,float>(1,0,0,1.0f) );
pointsp[0] = x[b];
vparams->drawTool()->drawPoints( pointsp, 20, Vec<4,float>(0,1,0,1.0f) );
pointsp[0] = x[c];
vparams->drawTool()->drawPoints( pointsp, 20, Vec<4,float>(0,0,1,1.0f) );
pointsp[0] = x[d];
vparams->drawTool()->drawPoints( pointsp, 20, Vec<4,float>(1,1,0,1.0f) );
}
if(!heterogeneous)
{
vparams->drawTool()->drawTriangles(points[0], Vec<4,float>(0.0,0.0,1.0,1.0));
vparams->drawTool()->drawTriangles(points[1], Vec<4,float>(0.0,0.5,1.0,1.0));
vparams->drawTool()->drawTriangles(points[2], Vec<4,float>(0.0,1.0,1.0,1.0));
vparams->drawTool()->drawTriangles(points[3], Vec<4,float>(0.5,1.0,1.0,1.0));
}
}
}
template<class DataTypes>
void InvertibleFVMForceField<DataTypes>::addKToMatrix(sofa::defaulttype::BaseMatrix * /*mat*/, SReal /*k*/, unsigned int &/*offset*/)
{
serr<<"InvertibleFVMForceField::addKToMatrix is not implemented\n";
}
} // namespace forcefield
} // namespace component
} // namespace sofa
#endif // SOFA_COMPONENT_FORCEFIELD_TETRAHEDRONFEMFORCEFIELD_INL
| 34.157088 | 194 | 0.532025 | sofa-framework |
7464e2488c1cca3a52195c79b57be576b0151637 | 1,848 | cc | C++ | chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.h"
namespace policy {
DlpContentRestrictionSet::DlpContentRestrictionSet() = default;
DlpContentRestrictionSet::DlpContentRestrictionSet(
DlpContentRestriction restriction)
: restriction_mask_(restriction) {}
DlpContentRestrictionSet::DlpContentRestrictionSet(
const DlpContentRestrictionSet& restriction_set) = default;
DlpContentRestrictionSet& DlpContentRestrictionSet::operator=(
const DlpContentRestrictionSet&) = default;
DlpContentRestrictionSet::~DlpContentRestrictionSet() = default;
bool DlpContentRestrictionSet::operator==(
const DlpContentRestrictionSet& other) const {
return restriction_mask_ == other.restriction_mask_;
}
bool DlpContentRestrictionSet::operator!=(
const DlpContentRestrictionSet& other) const {
return !(*this == other);
}
void DlpContentRestrictionSet::SetRestriction(
DlpContentRestriction restriction) {
restriction_mask_ |= restriction;
}
bool DlpContentRestrictionSet::HasRestriction(
DlpContentRestriction restriction) const {
return (restriction_mask_ & restriction) != 0;
}
void DlpContentRestrictionSet::UnionWith(
const DlpContentRestrictionSet& other) {
restriction_mask_ |= other.restriction_mask_;
}
DlpContentRestrictionSet DlpContentRestrictionSet::DifferenceWith(
const DlpContentRestrictionSet& other) const {
// Leave only the restrictions that are present in |this|, but not in |other|.
return DlpContentRestrictionSet(restriction_mask_ & ~other.restriction_mask_);
}
DlpContentRestrictionSet::DlpContentRestrictionSet(uint8_t mask)
: restriction_mask_(mask) {}
} // namespace policy
| 31.862069 | 80 | 0.796537 | mghgroup |
746522538f59aec89779423d49f757dc0e4aa787 | 1,705 | cpp | C++ | tests/ondemand/ondemand_assert_out_of_order_values.cpp | friendlyanon/simdjson | 7ed9554280802ccadfba6f69761ef197114e5593 | [
"Apache-2.0"
] | 1 | 2020-12-20T16:32:24.000Z | 2020-12-20T16:32:24.000Z | tests/ondemand/ondemand_assert_out_of_order_values.cpp | c3358/simdjson | 85001c55fb678415922960171b27e4bd4cfa4ef5 | [
"Apache-2.0"
] | null | null | null | tests/ondemand/ondemand_assert_out_of_order_values.cpp | c3358/simdjson | 85001c55fb678415922960171b27e4bd4cfa4ef5 | [
"Apache-2.0"
] | 1 | 2021-08-06T10:16:23.000Z | 2021-08-06T10:16:23.000Z | #include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "simdjson.h"
using namespace simdjson;
using namespace simdjson::builtin;
// This ensures the compiler can't rearrange them into the proper order (which causes it to work!)
simdjson_never_inline int check_point(simdjson_result<ondemand::value> xval, simdjson_result<ondemand::value> yval) {
// Verify the expected release behavior
error_code error;
uint64_t x = 0;
if ((error = xval.get(x))) { std::cerr << "error getting x: " << error << std::endl; }
else if (x != 2) { std::cerr << "expected x to (wrongly) be 2, was " << x << std::endl; }
uint64_t y = 0;
if ((error = yval.get(y))) { std::cerr << "error getting y: " << error << std::endl; }
else if (y != 3) { std::cerr << "expected y to (wrongly) be 3, was " << y << std::endl; }
return 0;
}
int test_check_point() {
auto json = R"(
{
"x": 1,
"y": 2 3
)"_padded;
ondemand::parser parser;
auto doc = parser.iterate(json);
return check_point(doc["x"], doc["y"]);
}
bool fork_failed_with_assert() {
int status = 0;
wait(&status);
return WIFSIGNALED(status);
}
int main(void) {
// To verify that the program asserts (which sends a signal), we fork a new process and use wait()
// to check the resulting error code. If it's a signal error code, we consider the
// test to have passed.
// From https://stackoverflow.com/a/33694733
pid_t pid = fork();
if (pid == -1) { std::cerr << "fork failed" << std::endl; return 1; }
if (pid) {
// Parent - wait child and interpret its result
return fork_failed_with_assert() ? 0 : 1;
} else {
test_check_point();
}
}
| 29.912281 | 117 | 0.641642 | friendlyanon |
7465ff9f1b9725685726c0c4c6e2c2c59d760f05 | 823 | cpp | C++ | ui/widget/toolbar/AdjustPanelToolBar.cpp | shinehanx/openphoto | e4466e5e80829385d2aa84813f2d5a8960053845 | [
"Apache-2.0"
] | 5 | 2021-03-11T00:30:25.000Z | 2021-07-28T00:31:20.000Z | ui/widget/toolbar/AdjustPanelToolBar.cpp | shinehanx/openphoto | e4466e5e80829385d2aa84813f2d5a8960053845 | [
"Apache-2.0"
] | null | null | null | ui/widget/toolbar/AdjustPanelToolBar.cpp | shinehanx/openphoto | e4466e5e80829385d2aa84813f2d5a8960053845 | [
"Apache-2.0"
] | 1 | 2021-09-14T16:28:26.000Z | 2021-09-14T16:28:26.000Z | #include "AdjustPanelToolBar.h"
#include <QIcon>
AdjustPanelToolBar::AdjustPanelToolBar(QWidget *parent) : QToolBar(parent)
{
}
AdjustPanelToolBar::AdjustPanelToolBar(ToolButtonData *datas, int size, QWidget *parent) : QToolBar(parent)
{
toolButtonDatas = datas;
toolButtonSize = size;
}
void AdjustPanelToolBar::setup()
{
this->setStyleSheet(qssToolBar);
this->setOrientation(Qt::Horizontal);
this->setMovable(false);
if (toolButtonDatas == nullptr) {
return ;
}
int i = 0;
for(ToolButtonData * data=toolButtonDatas; i<toolButtonSize; data++){
QAction * action = new QAction(this);
action->setIcon(QIcon(data->icon));
action->setToolTip(data->tip);
action->setData(QVariant(data->name));
this->addAction(action);
i++;
}
}
| 24.939394 | 107 | 0.663426 | shinehanx |
7466b0e0ac71ab7eb83d9e4f513a021ac1d5a4f5 | 4,388 | cpp | C++ | plugins/mdaRoundPan.cpp | elk-audio/mda-vst2 | 8ea6ef97946a617d73e48d245777e57fb984357f | [
"MIT"
] | 2 | 2020-05-01T20:57:56.000Z | 2021-05-20T13:59:20.000Z | plugins/mdaRoundPan.cpp | elk-audio/mda-vst2 | 8ea6ef97946a617d73e48d245777e57fb984357f | [
"MIT"
] | null | null | null | plugins/mdaRoundPan.cpp | elk-audio/mda-vst2 | 8ea6ef97946a617d73e48d245777e57fb984357f | [
"MIT"
] | null | null | null | #include "mdaRoundPan.h"
#include <math.h>
#include <float.h>
AudioEffect *createEffectInstance(audioMasterCallback audioMaster)
{
return new mdaRoundPan(audioMaster);
}
mdaRoundPan::mdaRoundPan(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, 1, 2) // programs, parameters
{
//inits here!
fParam1 = (float)0.5; //pan
fParam2 = (float)0.8; //auto
//size = 1500;
//bufpos = 0;
//buffer = new float[size];
//buffer2 = new float[size];
setNumInputs(2);
setNumOutputs(2);
setUniqueID('mdaP'); // identify here
DECLARE_VST_DEPRECATED(canMono) ();
canProcessReplacing();
strcpy(programName, "Round Panner");
suspend(); // flush buffer
//calcs here!
phi = 0.0;
dphi = (float)(5.0 / getSampleRate());
}
bool mdaRoundPan::getProductString(char* text) { strcpy(text, "mda RoundPan"); return true; }
bool mdaRoundPan::getVendorString(char* text) { strcpy(text, "mda"); return true; }
bool mdaRoundPan::getEffectName(char* name) { strcpy(name, "RoundPan"); return true; }
void mdaRoundPan::setParameter(VstInt32 index, float value)
{
switch(index)
{
case 0: fParam1 = value; phi = (float)(6.2831853 * (fParam1 - 0.5)); break;
case 1: fParam2 = value; break;
}
//calcs here
if (fParam2>0.55)
{
dphi = (float)(20.0 * (fParam2 - 0.55) / getSampleRate());
}
else
{
if (fParam2<0.45)
{
dphi = (float)(-20.0 * (0.45 - fParam2) / getSampleRate());
}
else
{
dphi = 0.0;
}
}
}
mdaRoundPan::~mdaRoundPan()
{
//if(buffer) delete buffer;
//if(buffer2) delete buffer2;
}
void mdaRoundPan::suspend()
{
//memset(buffer, 0, size * sizeof(float));
//memset(buffer2, 0, size * sizeof(float));
}
void mdaRoundPan::setProgramName(char *name)
{
strcpy(programName, name);
}
void mdaRoundPan::getProgramName(char *name)
{
strcpy(name, programName);
}
bool mdaRoundPan::getProgramNameIndexed (VstInt32 category, VstInt32 index, char* name)
{
if (index == 0)
{
strcpy(name, programName);
return true;
}
return false;
}
float mdaRoundPan::getParameter(VstInt32 index)
{
float v=0;
switch(index)
{
case 0: v = fParam1; break;
case 1: v = fParam2; break;
}
return v;
}
void mdaRoundPan::getParameterName(VstInt32 index, char *label)
{
switch(index)
{
case 0: strcpy(label, "Pan"); break;
case 1: strcpy(label, "Auto"); break;
}
}
#include <stdio.h>
void int2strng(VstInt32 value, char *string) { sprintf(string, "%d", value); }
void mdaRoundPan::getParameterDisplay(VstInt32 index, char *text)
{
switch(index)
{
case 0: int2strng((VstInt32)(360.0 * (fParam1 - 0.5)), text); break;
case 1: int2strng((VstInt32)(57.296 * dphi * getSampleRate()), text); break;
}
}
void mdaRoundPan::getParameterLabel(VstInt32 index, char *label)
{
switch(index)
{
case 0: strcpy(label, "deg"); break;
case 1: strcpy(label, "deg/sec"); break;
}
}
//--------------------------------------------------------------------------------
// process
void mdaRoundPan::process(float **inputs, float **outputs, VstInt32 sampleFrames)
{
float *in1 = inputs[0];
float *in2 = inputs[1];
float *out1 = outputs[0];
float *out2 = outputs[1];
float a, c, d, x=0.5, y=(float)0.7854;
float ph, dph, fourpi=(float)12.566371;
ph = phi;
dph = dphi;
--in1;
--in2;
--out1;
--out2;
while(--sampleFrames >= 0)
{
a = x * (*++in1 + *++in2);
c = out1[1];
d = out2[1]; //process from here...
c += (float)(a * -sin((x * ph) - y)); // output
d += (float)(a * sin((x * ph) + y));
ph = ph + dph;
*++out1 = c;
*++out2 = d;
}
if(ph<0.0) ph = ph + fourpi; else if(ph>fourpi) ph = ph - fourpi;
phi = ph;
}
void mdaRoundPan::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames)
{
float *in1 = inputs[0];
float *in2 = inputs[1];
float *out1 = outputs[0];
float *out2 = outputs[1];
float a, c, d, x=0.5, y=(float)0.7854;
float ph, dph, fourpi=(float)12.566371;
ph = phi;
dph = dphi;
--in1;
--in2;
--out1;
--out2;
while(--sampleFrames >= 0)
{
a = x * (*++in1 + *++in2); //process from here...
c = (float)(a * -sin((x * ph) - y)); // output
d = (float)(a * sin((x * ph) + y));
ph = ph + dph;
*++out1 = c;
*++out2 = d;
}
if(ph<0.0) ph = ph + fourpi; else if(ph>fourpi) ph = ph - fourpi;
phi = ph;
}
| 21.198068 | 115 | 0.595488 | elk-audio |
74672b4322ec3e5a5eb396ee1459c844f41b4d54 | 1,370 | cpp | C++ | fk/factory_wipe_worker.cpp | fieldkit/firmware | 09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6 | [
"BSD-3-Clause"
] | 10 | 2019-11-26T11:35:56.000Z | 2021-07-03T07:21:38.000Z | fk/factory_wipe_worker.cpp | fieldkit/firmware | 09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6 | [
"BSD-3-Clause"
] | 1 | 2019-07-03T06:27:21.000Z | 2019-09-06T09:21:27.000Z | fk/factory_wipe_worker.cpp | fieldkit/firmware | 09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6 | [
"BSD-3-Clause"
] | 1 | 2019-09-23T18:13:51.000Z | 2019-09-23T18:13:51.000Z | #include <samd51_common.h>
#include "factory_wipe_worker.h"
#include "hal/hal.h"
#include "storage/storage.h"
#include "gs_progress_callbacks.h"
#include "factory_wipe.h"
#include "graceful_shutdown.h"
namespace fk {
FK_DECLARE_LOGGER("factory-wipe");
FactoryWipeWorker::FactoryWipeWorker(bool restart) : restart_(restart) {
}
void FactoryWipeWorker::run(Pool &pool) {
if (!initialize_memory_if_necessary()) {
logerror("memory failed");
return;
}
auto memory = MemoryFactory::get_data_memory();
GlobalStateProgressCallbacks progress;
Storage storage{ memory, pool, false, true };
FactoryWipe factory_wipe{ storage };
if (factory_wipe.wipe(&progress)) {
if (restart_) {
fk_graceful_shutdown();
fk_restart();
}
}
}
bool FactoryWipeWorker::initialize_memory_if_necessary() {
auto banks = MemoryFactory::get_data_memory_banks();
auto memory = MemoryFactory::get_data_memory();
auto nbanks = 0u;
for (auto i = 0u; i < MemoryFactory::NumberOfDataMemoryBanks; ++i) {
auto &bank = *banks[i];
// TODO: Why is this necessary?
fk_delay(100);
if (bank.begin()) {
loginfo("memory bank #%d... OK", nbanks);
nbanks++;
}
}
if (!memory->begin()) {
return false;
}
return true;
}
}
| 22.459016 | 72 | 0.632117 | fieldkit |
7469b6151ce6cf726fb13b3ad637ca8cef0643cc | 1,343 | cpp | C++ | released_plugins/special_v3d_plugins/teramanager/src/presentation/QGradientBar.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/special_v3d_plugins/teramanager/src/presentation/QGradientBar.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | released_plugins/special_v3d_plugins/teramanager/src/presentation/QGradientBar.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #include "QGradientBar.h"
using namespace teramanager;
void QGradientBar::paintEvent(QPaintEvent * evt)
{
//creatin QPainter object, enabling antialising and setting brush color differently if button is enabled or not
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
if(isEnabled() && nSteps != -1)
{
//drawing gradient
QLinearGradient fade(0, 0, width(), height());
fade.setColorAt(0.0, QColor(0, 0, 255));
fade.setColorAt(0.333, QColor(0, 255, 255));
fade.setColorAt(0.666, QColor(255, 255, 0));
fade.setColorAt(1.0, QColor(255, 0, 0));
painter.fillRect(2, 2, width()-4, height()-4, fade);
//drawing white bar
painter.setBrush(QColor(255, 255, 255));
painter.setPen(QColor(0, 0, 0, 0));
painter.drawRect(static_cast<int>( (step+1)*width()/float(nSteps) +0.5f), 0, static_cast<int>( width()-(step+1)*width()/float(nSteps) +0.5f), height());
//drawing border
painter.setBrush(QColor(255, 255, 255, 0));
painter.setPen(QColor(0, 0, 0));
painter.drawRect(0, 0, width(), height());
}
else
{
painter.setBrush(QColor(0, 0, 0, 0));
painter.setPen(Qt::gray);
painter.drawRect(0, 0, width(), height());
}
}
| 35.342105 | 165 | 0.590469 | zzhmark |
746b9d8341140763cfab097aaf0298b13ce7b568 | 3,378 | cpp | C++ | src/examples/hello_fluid_sim/main.cpp | PavelBlend/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | [
"MIT"
] | 1,355 | 2016-05-08T07:29:22.000Z | 2022-03-30T13:59:35.000Z | src/examples/hello_fluid_sim/main.cpp | Taiyuan-Zhang/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | [
"MIT"
] | 208 | 2016-05-25T19:47:27.000Z | 2022-01-17T04:18:29.000Z | src/examples/hello_fluid_sim/main.cpp | Taiyuan-Zhang/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | [
"MIT"
] | 218 | 2016-08-23T16:51:10.000Z | 2022-03-31T03:55:48.000Z | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <string>
#include <thread>
using namespace std;
using namespace chrono;
const size_t kBufferSize = 80;
// http://paulbourke.net/dataformats/asciiart/
const std::string kGrayScaleTable = " .:-=+*#%@";
const size_t kGrayScaleTableSize = kGrayScaleTable.length();
void updateWave(const double timeInterval, double* x, double* speed) {
(*x) += timeInterval * (*speed);
// Boundary reflection
if ((*x) > 1.0) {
(*speed) *= -1.0;
(*x) = 1.0 + timeInterval * (*speed);
} else if ((*x) < 0.0) {
(*speed) *= -1.0;
(*x) = timeInterval * (*speed);
}
}
void accumulateWaveToHeightField(
const double x,
const double waveLength,
const double maxHeight,
array<double, kBufferSize>* heightField) {
const double quarterWaveLength = 0.25 * waveLength;
const int start = static_cast<int>((x - quarterWaveLength) * kBufferSize);
const int end = static_cast<int>((x + quarterWaveLength) * kBufferSize);
for (int i = start; i < end; ++i) {
int iNew = i;
if (i < 0) {
iNew = -i - 1;
} else if (i >= static_cast<int>(kBufferSize)) {
iNew = 2 * kBufferSize - i - 1;
}
double distance = fabs((i + 0.5) / kBufferSize - x);
double height = maxHeight * 0.5
* (cos(min(distance * M_PI / quarterWaveLength, M_PI)) + 1.0);
(*heightField)[iNew] += height;
}
}
void draw(
const array<double, kBufferSize>& heightField) {
string buffer(kBufferSize, ' ');
// Convert height field to grayscale
for (size_t i = 0; i < kBufferSize; ++i) {
double height = heightField[i];
size_t tableIndex = min(
static_cast<size_t>(floor(kGrayScaleTableSize * height)),
kGrayScaleTableSize - 1);
buffer[i] = kGrayScaleTable[tableIndex];
}
// Clear old prints
for (size_t i = 0; i < kBufferSize; ++i) {
printf("\b");
}
// Draw new buffer
printf("%s", buffer.c_str());
fflush(stdout);
}
int main() {
const double waveLengthX = 0.8;
const double waveLengthY = 1.2;
const double maxHeightX = 0.5;
const double maxHeightY = 0.4;
double x = 0.0;
double y = 1.0;
double speedX = 1.5;
double speedY = -1.0;
const int fps = 100;
const double timeInterval = 1.0/fps;
array<double, kBufferSize> heightField;
for (int i = 0; i < 1000; ++i) {
// March through time
updateWave(timeInterval, &x, &speedX);
updateWave(timeInterval, &y, &speedY);
// Clear height field
for (double& height : heightField) {
height = 0.0;
}
// Accumulate waves for each center point
accumulateWaveToHeightField(x, waveLengthX, maxHeightX, &heightField);
accumulateWaveToHeightField(y, waveLengthY, maxHeightY, &heightField);
// Draw height field
draw(heightField);
// Wait
this_thread::sleep_for(milliseconds(1000 / fps));
}
printf("\n");
fflush(stdout);
return 0;
}
| 26.390625 | 78 | 0.599467 | PavelBlend |
746be647093c5e6f87c9e17d5414193ce5ed227e | 794 | cpp | C++ | 2018/day01/main.cpp | batduck27/Advent_of_code | 6b2dadf28bebd2301464c864f5112dccede9762b | [
"MIT"
] | null | null | null | 2018/day01/main.cpp | batduck27/Advent_of_code | 6b2dadf28bebd2301464c864f5112dccede9762b | [
"MIT"
] | null | null | null | 2018/day01/main.cpp | batduck27/Advent_of_code | 6b2dadf28bebd2301464c864f5112dccede9762b | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <set>
std::vector<int> V;
int solvePart1() {
int res = 0;
for (const auto& x : V) {
res += x;
}
return res;
}
int solvePart2() {
int currFreq = 0;
std::set<int> S;
for (size_t i = 0; i < V.size(); i = ((i == V.size() - 1) ? 0 : i + 1)) {
if (S.find(currFreq) != S.end()) {
break;
}
S.insert(currFreq);
currFreq += V[i];
}
return currFreq;
}
int main() {
std::ifstream fin("data.in");
int nr;
while (fin >> nr) {
V.push_back(nr);
}
std::cout << "The result for part1 is: " << solvePart1() << "\n";
std::cout << "The result for part2 is: " << solvePart2() << "\n";
fin.close();
return 0;
} | 16.541667 | 77 | 0.479849 | batduck27 |
7472b026164b7c1ed40af2b5369b81773828a962 | 19,054 | hh | C++ | admin/darwin/src/help/msiauto.hh | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/darwin/src/help/msiauto.hh | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/darwin/src/help/msiauto.hh | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /* msiauto.hh = help context identifiers for automation help
This file is included by msiauto.hpj, makeodl.cpp, autosrv.cpp
*/
#define MsiBase_Object 1
#define MsiBase_HasInterface 2
#define MsiBase_RefCount 3
#define MsiBase_GetInterface 4
#define Msi_Obsolete 99
#define MsiData_Object 100
#define MsiData_StringValue 199
#define MsiData_IntegerValue 101
#define MsiString_Object 200
#define MsiString_Value 299
#define MsiString_IntegerValue 201
#define MsiString_TextSize 202
#define MsiString_CharacterCount 203
#define MsiString_IsDBCS 204
#define MsiString_Compare 205
#define MsiString_Append 206
#define MsiString_Add 207
#define MsiString_Extract 208
#define MsiString_Remove 209
#define MsiString_UpperCase 210
#define MsiString_LowerCase 211
#define MsiRecord_Object 300
#define MsiRecord_Data 399
#define MsiRecord_StringData 301
#define MsiRecord_IntegerData 302
#define MsiRecord_ObjectData 303
#define MsiRecord_FieldCount 304
#define MsiRecord_IsInteger 305
#define MsiRecord_IsNull 306
#define MsiRecord_IsChanged 307
#define MsiRecord_TextSize 308
#define MsiRecord_FormatText 309
#define MsiRecord_ClearData 310
#define MsiRecord_ClearUpdate 311
#define MsiVolume_Object 400
#define MsiVolume_Path 499
#define MsiVolume_VolumeID 401
#define MsiVolume_DriveType 402
#define MsiVolume_SupportsLFN 403
#define MsiVolume_FreeSpace 404
#define MsiVolume_ClusterSize 405
#define MsiVolume_FileSystem 406
#define MsiVolume_UNCServer 407
#define MsiVolume_SerialNum 408
#define MsiVolume_DiskNotInDrive 409
#define MsiVolume_VolumeLabel 410
#define MsiVolume_TotalSpace 411
#define MsiVolume_FileSystemFlags 412
#define MsiPath_Object 500
#define MsiPath_Path 599
#define MsiPath_Volume 501
#define MsiPath_AppendPiece 502
#define MsiPath_ChopPiece 503
#define MsiPath_FileExists 504
#define MsiPath_GetFullFilePath 505
#define MsiPath_GetFileAttribute 507
#define MsiPath_SetFileAttribute 508
#define MsiPath_Exists 509
#define MsiPath_FileSize 510
#define MsiPath_FileDate 511
#define MsiPath_RemoveFile 512
#define MsiPath_EnsureExists 513
#define MsiPath_Remove 514
#define MsiPath_Writable 515
#define MsiPath_FileWritable 516
#define MsiPath_FileInUse 517
#define MsiPath_UpdateResource 518
#define MsiPath_ClusteredFileSize 519
#define MsiPath_GetFileVersionString 520
#define MsiPath_CheckFileVersion 521
#define MsiPath_GetLangIDStringFromFile 522
#define MsiPath_CheckLanguageIDs 523
#define MsiPath_Compare 524
#define MsiPath_Child 525
#define MsiPath_TempFileName 526
#define MsiPath_FindFile 527
#define MsiPath_SubFolders 528
#define MsiPath_EndSubPath 529
#define MsiPath_ReadResource 530
#define MsiPath_GetImportModulesEnum 531
#define MsiPath_SetVolume 532
#define MsiPath_ComputeFileChecksum 533
#define MsiPath_GetFileOriginalChecksum 534
#define MsiPath_BindImage 535
#define MsiPath_SupportsLFN 536
#define MsiPath_GetFullUNCFilePath 537
#define MsiPath_RelativePath 538
#define MsiPath_GetSelfRelativeSD 539
#define MsiFileCopy_Object 600
#define MsiFileCopy_CopyTo 601
#define MsiFileCopy_ChangeMedia 602
#define MsiRegKey_Object 700
#define MsiRegKey_Value 701
#define MsiRegKey_Exists 702
#define MsiRegKey_RemoveValue 703
#define MsiRegKey_RemoveSubKey 704
#define MsiRegKey_RemoveSubTree 705
#define MsiRegKey_Values 706
#define MsiRegKey_SubKeys 707
#define MsiRegKey_CreateChild 708
#define MsiRegKey_Key 709
#define MsiRegKey_ValueExists 710
#define MsiRegKey_GetSelfRelativeSD 711
#define MsiTable_Object 800
#define MsiTable_Database 801
#define MsiTable_RowCount 802
#define MsiTable_ColumnCount 803
#define MsiTable_PrimaryKeyCount 804
#define MsiTable_ReadOnly 805
#define MsiTable_ColumnName 806
#define MsiTable_ColumnType 807
#define MsiTable_GetColumnIndex 808
#define MsiTable_CreateColumn 809
#define MsiTable_CreateCursor 810
#define MsiTable_LinkTree 811
#define MsiCursor_Object 900
#define MsiCursor_Table 901
#define MsiCursor_Filter 902
#define MsiCursor_IntegerData 903
#define MsiCursor_StringData 904
#define MsiCursor_ObjectData 905
#define MsiCursor_StreamData 906
#define MsiCursor_PutNull 907
#define MsiCursor_Reset 908
#define MsiCursor_Next 909
#define MsiCursor_Update 910
#define MsiCursor_Insert 911
#define MsiCursor_InsertTemporary 912
#define MsiCursor_Assign 913
#define MsiCursor_Merge 914
#define MsiCursor_Refresh 915
#define MsiCursor_Delete 916
#define MsiCursor_Seek 917
#define MsiCursor_RowState 918
#define MsiCursor_DateData 919
#define MsiCursor_Validate 920
#define MsiCursor_Moniker 921
#define MsiCursor_Replace 922
#define MsiAuto_Object 1000
#define MsiAuto_CreateServices 1001
#define MsiAuto_CreateEngine 1002
#define MsiAuto_CreateHandler 1003
#define MsiAuto_CreateMessageHandler 1004
#define MsiAuto_CreateConfigurationManager 1005
#define MsiAuto_OpcodeName 1006
#define MsiAuto_ShowAsserts 1007
#define MsiAuto_SetDBCSSimulation 1008
#define MsiAuto_AssertNoObjects 1009
#define MsiAuto_SetRefTracking 1010
#define MsiAuto_CreateExecutor 1011
#define MsiServices_Object 1100
#define MsiServices_GetAllocator 1101
#define MsiServices_CreateString 1102
#define MsiServices_CreateRecord 1103
#define MsiServices_SetPlatformProperties 1104
#define MsiServices_CreateLog 1105
#define MsiServices_WriteLog 1106
#define MsiServices_LoggingEnabled 1107
#define MsiServices_CreateDatabase 1108
#define MsiServices_CreateDatabaseFromStorage 1109
#define MsiServices_CreatePath 1110
#define MsiServices_CreateVolume 1111
#define MsiServices_CreateCopier 1112
#define MsiServices_ClearAllCaches 1113
#define MsiServices_EnumDriveType 1114
#define MsiServices_GetModuleUsage 1115
#define MsiServices_GetLocalPath 1116
#define MsiServices_CreateRegKey 1117
#define MsiServices_RegisterFont 1118
#define MsiServices_UnRegisterFont 1119
#define MsiServices_WriteIniFile 1120
#define MsiServices_ReadIniFile 1121
#define MsiServices_GetLangNamesFromLangIDString 1122
#define MsiServices_CreateStorage 1123
#define MsiServices_GetUnhandledError 1124
#define MsiServices_SupportLanguageId 1125
#define MsiServices_CreateVolumeFromLabel 1127
#define MsiServices_CreateShortcut 1128
#define MsiServices_RemoveShortcut 1129
#define MsiServices_AttachClient 1132
#define MsiServices_DetachClient 1133
#define MsiServices_ExtractFileName 1134
#define MsiServices_ValidateFileName 1135
#define MsiServices_CreateFileStream 1136
#define MsiServices_CreateMemoryStream 1137
#define MsiServices_RegisterTypeLibrary 1138
#define MsiServices_UnregisterTypeLibrary 1139
#define MsiServices_GetShellFolderPath 1140
#define MsiServices_GetUserProfilePath 1141
#define MsiServices_CreateFilePath 1142
#define MsiServices_RipFileNameFromPath 1143
#define MsiServices_CreatePatcher 1144
#define MsiView_Object 1200
#define MsiView_Execute 1201
#define MsiView_FieldCount 1202
#define MsiView_Fetch 1203
#define MsiView_GetColumnNames 1204
#define MsiView_GetColumnTypes 1205
#define MsiView_Modify 1206
#define MsiView_RowCount 1207
#define MsiView_Close 1208
#define MsiView_GetError 1209
#define MsiView_State 1210
#define MsiDatabase_Object 1300
#define MsiDatabase_UpdateState 1301
#define MsiDatabase_Storage 1302
#define MsiDatabase_OpenView 1303
#define MsiDatabase_GetPrimaryKeys 1304
#define MsiDatabase_ImportTable 1305
#define MsiDatabase_ExportTable 1306
#define MsiDatabase_DropTable 1307
#define MsiDatabase_FindTable 1308
#define MsiDatabase_LoadTable 1309
#define MsiDatabase_CreateTable 1310
#define MsiDatabase_LockTable 1311
#define MsiDatabase_GetCatalogTable 1312
#define MsiDatabase_DecodeString 1313
#define MsiDatabase_EncodeString 1314
#define MsiDatabase_CreateTempTableName 1315
#define MsiDatabase_Commit 1316
#define MsiDatabase_CreateOutputDatabase 1317
#define MsiDatabase_GenerateTransform 1318
#define MsiDatabase_SetTransform 1319
#define MsiDatabase_MergeDatabase 1320
#define MsiDatabase_TableState 1321
#define MsiDatabase_ANSICodePage 1322
#define MsiEngine_Object 1400
#define MsiEngine_Services 1401
#define MsiEngine_ConfigurationServer 1402
#define MsiEngine_Handler 1403
#define MsiEngine_Database 1404
#define MsiEngine_Property 1405
#define MsiEngine_SelectionManager 1406
#define MsiEngine_DirectoryManager 1407
#define MsiEngine_Initialize 1408
#define MsiEngine_Terminate 1409
#define MsiEngine_DoAction 1410
#define MsiEngine_Sequence 1411
#define MsiEngine_Message 1412
#define MsiEngine_OpenView 1414
#define MsiEngine_ResolveFolderProperty 1415
#define MsiEngine_FormatText 1416
#define MsiEngine_EvaluateCondition 1417
#define MsiEngine_ExecuteRecord 1418
#define MsiEngine_ValidateProductID 1419
#define MsiEngine_GetMode 1420
#define MsiEngine_SetMode 1421
#define MsiHandler_Object 1500
#define MsiHandler_Message 1501
#define MsiHandler_DoAction 1502
#define MsiHandler_Break 1503
#define MsiDialog_Object 1600
#define MsiDialog_Visible 1601
#define MsiDialog_ControlCreate 1602
#define MsiDialog_Attribute 1603
#define MsiDialog_Control 1604
#define MsiDialog_AddControl 1605
#define MsiDialog_Execute 1606
#define MsiDialog_Reset 1607
#define MsiDialog_EventAction 1608
#define MsiDialog_RemoveControl 1609
#define MsiDialog_StringValue 1610
#define MsiDialog_IntegerValue 1611
#define MsiDialog_Handler 1612
#define MsiDialog_PropertyChanged 1613
#define MsiDialog_FinishCreate 1614
#define MsiDialog_HandleEvent 1615
#define MsiEvent_Object 1700
#define MsiEvent_PropertyChanged 1701
#define MsiEvent_ControlActivated 1702
#define MsiEvent_RegisterControlEvent 1703
#define MsiEvent_Handler 1704
#define MsiEvent_PublishEvent 1705
#define MsiEvent_Control 1706
#define MsiEvent_Attribute 1707
#define MsiEvent_EventAction 1708
#define MsiEvent_SetFocus 1709
#define MsiEvent_StringValue 1710
#define MsiEvent_IntegerValue 1711
#define MsiEvent_HandleEvent 1712
#define MsiEvent_Engine 1713
#define MsiEvent_Escape 1714
#define MsiControl_Object 1800
#define MsiControl_Attribute 1801
#define MsiControl_CanTakeFocus 1802
#define MsiControl_HandleEvent 1803
#define MsiControl_Undo 1804
#define MsiControl_SetPropertyInDatabase 1805
#define MsiControl_GetPropertyFromDatabase 1806
#define MsiControl_SetFocus 1807
#define MsiControl_Dialog 1808
#define MsiControl_WindowMessage 1809
#define MsiControl_StringValue 1810
#define MsiControl_IntegerValue 1811
#define MsiControl_GetIndirectPropertyFromDatabase 1812
#define MsiDialogHandler_Object 1900
#define MsiDialogHandler_DialogCreate 1901
#define MsiDialogHandler_Dialog 1902
#define MsiDialogHandler_DialogFromWindow 1903
#define MsiDialogHandler_AddDialog 1904
#define MsiDialogHandler_RemoveDialog 1905
#define MsiStorage_Object 2000
#define MsiStorage_Class 2001
#define MsiStorage_OpenStream 2002
#define MsiStorage_OpenStorage 2003
#define MsiStorage_Streams 2004
#define MsiStorage_Storages 2005
#define MsiStorage_RemoveElement 2006
#define MsiStorage_Commit 2007
#define MsiStorage_Rollback 2008
#define MsiStorage_DeleteOnRelease 2009
#define MsiStorage_CreateSummaryInfo 2010
#define MsiStorage_CopyTo 2011
#define MsiStorage_Name 2012
#define MsiStorage_RenameElement 2013
#define MsiStream_Object 2100
#define MsiStream_Length 2101
#define MsiStream_Remaining 2102
#define MsiStream_Error 2103
#define MsiStream_GetData 2104
#define MsiStream_PutData 2105
#define MsiStream_GetInt16 2106
#define MsiStream_GetInt32 2107
#define MsiStream_PutInt16 2108
#define MsiStream_PutInt32 2109
#define MsiStream_Reset 2110
#define MsiStream_Seek 2111
#define MsiStream_Clone 2112
#define MsiSummaryInfo_Object 2200
#define MsiSummaryInfo_Property 2299
#define MsiSummaryInfo_PropertyCount 2201
#define MsiSummaryInfo_PropertyType 2202
#define MsiSummaryInfo_WritePropertyStream 2203
#define MsiMalloc_Object 2300
#define MsiMalloc_Alloc 2301
#define MsiMalloc_Free 2302
#define MsiMalloc_SetDebugFlags 2303
#define MsiMalloc_GetDebugFlags 2304
#define MsiMalloc_CheckAllBlocks 2305
#define MsiMalloc_FCheckBlock 2306
#define MsiMalloc_GetSizeOfBlock 2307
#define MsiSelectionManager_Object 2400
#define MsiSelectionManager_LoadSelectionTables 2401
#define MsiSelectionManager_FeatureTable 2402
#define MsiSelectionManager_ProcessConditionTable 2403
#define MsiSelectionManager_ComponentTable 2404
#define MsiSelectionManager_FreeSelectionTables 2405
#define MsiSelectionManager_SetFeatureHandle 2406
#define MsiSelectionManager_SetComponent 2407
#define MsiSelectionManager_SetInstallLevel 2408
#define MsiSelectionManager_GetVolumeCostTable 2409
#define MsiSelectionManager_RecostDirectory 2411
#define MsiSelectionManager_InitializeDynamicCost 2413
#define MsiSelectionManager_RegisterCostAdjuster 2414
#define MsiSelectionManager_InitializeComponents 2415
#define MsiSelectionManager_ConfigureFeature 2416
#define MsiSelectionManager_GetFeatureCost 2417
#define MsiSelectionManager_GetDescendentFeatureCost 2418
#define MsiSelectionManager_GetAncestryFeatureCost 2419
#define MsiSelectionManager_GetFeatureValidStates 2420
#define MsiDirectoryManager_Object 2500
#define MsiDirectoryManager_LoadDirectoryTable 2501
#define MsiDirectoryManager_DirectoryTable 2502
#define MsiDirectoryManager_FreeDirectoryTable 2503
#define MsiDirectoryManager_CreateTargetPaths 2504
#define MsiDirectoryManager_CreateSourcePaths 2505
#define MsiDirectoryManager_GetTargetPath 2506
#define MsiDirectoryManager_SetTargetPath 2507
#define MsiDirectoryManager_GetSourcePath 2508
#define MsiCostAdjuster_Object 2600
#define MsiConfigurationManager_Object 2700
#define MsiConfigurationManager_RunScript 2704
#define MsiConfigurationManager_RegisterUser 2710
#define MsiConfigurationManager_ProductDatabasePath 2711
#define MsiConfigurationManager_RegisterRollbackScript 2714
#define MsiConfigurationManager_UnregisterRollbackScript 2715
#define MsiConfigurationManager_RollbackScripts 2716
#define MsiConfigurationManager_InstallFinalize 2718
#define MsiConfigurationManager_Services 2719
#define MsiConfigurationManager_RegisterProduct 2720
#define MsiConfigurationManager_UnregisterProduct 2721
#define MsiConfigurationManager_RegisterComponent 2722
#define MsiConfigurationManager_UnregisterComponent 2723
#define MsiConfigurationManager_RegisterFolder 2726
#define MsiConfigurationManager_UnregisterFolder 2727
#define MsiConfigurationManager_IsFolderRemovable 2728
#define MsiConfigurationManager_LockServer 2729
#define MsiConfigurationManager_SetLastUsedSource 2731
#define MsiConfigurationManager_DoInstall 2732
#define MsiConfigurationManager_UnlockServer 2733
#define MsiServer_Object 2800
#define MsiMessage_Object 2900
#define MsiMessage_Message 2901
#define MsiExecute_Object 3000
#define MsiExecute_ExecuteRecord 3001
#define MsiExecute_RunScript 3003
#define MsiExecute_RemoveRollbackFiles 3004
#define MsiExecute_Rollback 3005
#define MsiExecute_RollbackFinalize 3006
#define MsiExecute_CreateScript 3007
#define MsiExecute_WriteScriptRecord 3008
#define MsiExecute_CloseScript 3009
#define MsiFilePatch_Object 3100
#define MsiFilePatch_ApplyPatch 3101
#define MsiFilePatch_ContinuePatch 3102
#define MsiFilePatch_CanPatchFile 3103
#define MsiFilePatch_CancelPatch 3104
#define Server_ScriptOpcodes 5000
// Operation_* defines added in build - based on opcodes.h
| 42.248337 | 67 | 0.701375 | npocmaka |
747645889dcdbedd897f1bad4d954375badbc624 | 1,394 | cpp | C++ | Platformer/World.cpp | renato-grottesi/pokitto | e38bbb07889e88087149709310687d957f00c4c6 | [
"MIT"
] | null | null | null | Platformer/World.cpp | renato-grottesi/pokitto | e38bbb07889e88087149709310687d957f00c4c6 | [
"MIT"
] | null | null | null | Platformer/World.cpp | renato-grottesi/pokitto | e38bbb07889e88087149709310687d957f00c4c6 | [
"MIT"
] | 1 | 2021-01-15T23:35:34.000Z | 2021-01-15T23:35:34.000Z | #include "World.hpp"
#include "assets.h" // TODO: pass in the constructor
uint8_t World::render(uint8_t cnt) {
const uint16_t XCentralTile = xWorldToTile(cameraX);
const uint16_t YCentralTile = yWorldToTile(cameraY);
// TODO: clear this parallax code and make it configurable
const int16_t xOff = (maxX - cameraX) * LCDWIDTH / maxX;
const int16_t yOff = (maxY - cameraY) * LCDHEIGHT / maxY / 5;
display.setup(cnt++, bg_001_pal, bg_001_data, 0xf, PaletteSize::PAL2, xOff - bg_001_data[0],
LCDHEIGHT / 2 - bg_001_data[1] / 2 + yOff);
display.setup(cnt++, bg_001_pal, bg_001_data, 0xf, PaletteSize::PAL2, xOff,
LCDHEIGHT / 2 - bg_001_data[1] / 2 + yOff);
for (int16_t yt = YCentralTile - 6; yt < YCentralTile + 7; yt++) {
for (int16_t xt = XCentralTile - 7; xt < XCentralTile + 8; xt++) {
if (xt < 0)
continue;
if (yt < 0)
continue;
if (xt >= width)
continue;
if (yt >= height)
continue;
uint8_t tile = data[yt * width + xt];
if (tile) {
tile--;
uint16_t screenX = minX + xTileToWorld(xt) - cameraX;
uint16_t screenY = minY + yTileToWorld(yt) - cameraY;
display.setup(cnt++, tile_pals[tile], tile_datas[tile],
tile_pals[tile][0] == 0 ? 0x00 : 0xff, palSizes[tile], screenX, screenY);
}
}
}
return cnt;
}
| 35.74359 | 95 | 0.599713 | renato-grottesi |
7476c428dddb4869a227bb9ff06d7a2ba1821386 | 8,751 | cpp | C++ | Dark Basic Public Shared/Official Plugins/3D Cloth & Particles/Code/DBProPhysicsMaster/Ragdoll_Basic_Setup.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 231 | 2018-01-28T00:06:56.000Z | 2022-03-31T21:39:56.000Z | Dark Basic Public Shared/Official Plugins/3D Cloth & Particles/Code/DBProPhysicsMaster/Ragdoll_Basic_Setup.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 9 | 2016-02-10T10:46:16.000Z | 2017-12-06T17:27:51.000Z | Dark Basic Public Shared/Official Plugins/3D Cloth & Particles/Code/DBProPhysicsMaster/Ragdoll_Basic_Setup.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 66 | 2018-01-28T21:54:52.000Z | 2022-02-16T22:50:57.000Z | #include "stdafx.h"
void Ragdoll_Basic::constructBasicDoll()
{
numParticles=30;
numLinks=68;
particle = new RagdollParticle[numParticles];
//Head, neck, and chest
particle[RAGBASIC_HEADLEFT].Set(-0.055110f,2.0f,0.000000f,0.1f,RAGBASIC_HEADLEFT);
particle[RAGBASIC_HEADRIGHT].Set(0.055110f,2.0f,0.000000f,0.1f,RAGBASIC_HEADRIGHT);
particle[RAGBASIC_NECK].Set(0.000000f,1.745363f,0.000000f,0.1f,RAGBASIC_NECK);
particle[RAGBASIC_CHEST].Set(0.000000f,1.436749f,0.000000f,0.1f,RAGBASIC_CHEST);
//Waist
particle[RAGBASIC_WAISTLEFT].Set(-0.188279f,1.19813f,0.000000f,0.1f,RAGBASIC_WAISTLEFT);
particle[RAGBASIC_WAISTRIGHT].Set(0.188279f,1.19813f,0.000000f,0.1f,RAGBASIC_WAISTRIGHT);
//Left arm
particle[RAGBASIC_HANDLEFT].Set(-1.111011f,1.600000f,0.000000f,0.1f,RAGBASIC_HANDLEFT);
particle[RAGBASIC_BICEPLEFT].Set(-0.591588f,1.65782f,0.070813f,0.1f,RAGBASIC_BICEPLEFT);
particle[RAGBASIC_TRICEPLEFT].Set(-0.591588f,1.65782f,-0.070813f,0.1f,RAGBASIC_TRICEPLEFT);
particle[RAGBASIC_UPELBOWLEFT].Set(-0.678951f,1.721530f,0.000000f,0.1f,RAGBASIC_UPELBOWLEFT);
particle[RAGBASIC_LOWELBOWLEFT].Set(-0.678951f,1.600000f,0.000000f,0.1f,RAGBASIC_LOWELBOWLEFT);
particle[RAGBASIC_SHOULDERLEFT].Set(-0.246891f,1.666339f,0.000000f,0.1f,RAGBASIC_SHOULDERLEFT);
//Right arm
particle[RAGBASIC_HANDRIGHT].Set(1.111011f,1.600000f,0.000000f,0.1f,RAGBASIC_HANDRIGHT);
particle[RAGBASIC_BICEPRIGHT].Set(0.591588f,1.65782f,0.070813f,0.1f,RAGBASIC_BICEPRIGHT);
particle[RAGBASIC_TRICEPRIGHT].Set(0.591588f,1.65782f,-0.070813f,0.1f,RAGBASIC_TRICEPRIGHT);
particle[RAGBASIC_UPELBOWRIGHT].Set(0.678951f,1.721530f,0.000000f,0.1f,RAGBASIC_UPELBOWRIGHT);
particle[RAGBASIC_LOWELBOWRIGHT].Set(0.678951f,1.600000f,0.000000f,0.1f,RAGBASIC_LOWELBOWRIGHT);
particle[RAGBASIC_SHOULDERRIGHT].Set(0.246891f,1.666339f,0.000000f,0.1f,RAGBASIC_SHOULDERRIGHT);
//Left leg
particle[RAGBASIC_LEGTOPLEFT].Set(-0.13131f,0.951243f,0.000000f,0.1f,RAGBASIC_LEGTOPLEFT);
particle[RAGBASIC_QUADLEFT].Set(-0.211058f,0.550156f,0.075043f,0.1f,RAGBASIC_QUADLEFT);
particle[RAGBASIC_HAMLEFT].Set(-0.211058f,0.550156f,-0.075043f,0.1f,RAGBASIC_HAMLEFT);
particle[RAGBASIC_OUTKNEELEFT].Set(-0.271140f,0.488410f,0.000000f,0.1f,RAGBASIC_OUTKNEELEFT);
particle[RAGBASIC_INKNEELEFT].Set(-0.180760f,0.488410f,0.000000f,0.1f,RAGBASIC_INKNEELEFT);
particle[RAGBASIC_FOOTLEFT].Set(-0.271140f,0.0f,0.000000f,0.05f,RAGBASIC_FOOTLEFT);
//Right leg
particle[RAGBASIC_LEGTOPRIGHT].Set(0.13131f,0.951243f,0.000000f,0.1f,RAGBASIC_LEGTOPRIGHT);
particle[RAGBASIC_QUADRIGHT].Set(0.211058f,0.550156f,0.075043f,0.1f,RAGBASIC_QUADRIGHT);
particle[RAGBASIC_HAMRIGHT].Set(0.211058f,0.550156f,-0.075043f,0.1f,RAGBASIC_HAMRIGHT);
particle[RAGBASIC_OUTKNEERIGHT].Set(0.271140f,0.488410f,0.000000f,0.1f,RAGBASIC_OUTKNEERIGHT);
particle[RAGBASIC_INKNEERIGHT].Set(0.180760f,0.488410f,0.000000f,0.1f,RAGBASIC_INKNEERIGHT);
particle[RAGBASIC_FOOTRIGHT].Set(0.271140f,0.0f,0.000000f,0.05f,RAGBASIC_FOOTRIGHT);
//Make normal links
link = new RagdollLink[numLinks];
//Head
link[0].Set(&particle[RAGBASIC_HEADLEFT],&particle[RAGBASIC_HEADRIGHT]);
link[1].Set(&particle[RAGBASIC_HEADLEFT],&particle[RAGBASIC_NECK]);
link[2].Set(&particle[RAGBASIC_HEADRIGHT],&particle[RAGBASIC_NECK]);
//Upper torso
link[3].Set(&particle[RAGBASIC_SHOULDERLEFT],&particle[RAGBASIC_NECK]);
link[4].Set(&particle[RAGBASIC_SHOULDERRIGHT],&particle[RAGBASIC_NECK]);
link[5].Set(&particle[RAGBASIC_SHOULDERLEFT],&particle[RAGBASIC_CHEST]);
link[6].Set(&particle[RAGBASIC_SHOULDERRIGHT],&particle[RAGBASIC_CHEST]);
link[7].Set(&particle[RAGBASIC_SHOULDERLEFT],&particle[RAGBASIC_WAISTLEFT]);
link[8].Set(&particle[RAGBASIC_SHOULDERRIGHT],&particle[RAGBASIC_WAISTRIGHT]);
link[9].Set(&particle[RAGBASIC_NECK],&particle[RAGBASIC_CHEST]);
link[10].Set(&particle[RAGBASIC_WAISTLEFT],&particle[RAGBASIC_CHEST]);
link[11].Set(&particle[RAGBASIC_WAISTRIGHT],&particle[RAGBASIC_CHEST]);
link[12].Set(&particle[RAGBASIC_WAISTLEFT],&particle[RAGBASIC_WAISTRIGHT]);
//Lower torso
link[13].Set(&particle[RAGBASIC_WAISTLEFT],&particle[RAGBASIC_LEGTOPLEFT]);
link[14].Set(&particle[RAGBASIC_WAISTLEFT],&particle[RAGBASIC_LEGTOPRIGHT]);
link[15].Set(&particle[RAGBASIC_WAISTRIGHT],&particle[RAGBASIC_LEGTOPLEFT]);
link[16].Set(&particle[RAGBASIC_WAISTRIGHT],&particle[RAGBASIC_LEGTOPRIGHT]);
link[17].Set(&particle[RAGBASIC_LEGTOPLEFT],&particle[RAGBASIC_LEGTOPRIGHT]);
//Left arm
link[18].Set(&particle[RAGBASIC_SHOULDERLEFT],&particle[RAGBASIC_UPELBOWLEFT]);
link[19].Set(&particle[RAGBASIC_SHOULDERLEFT],&particle[RAGBASIC_LOWELBOWLEFT]);
link[20].Set(&particle[RAGBASIC_SHOULDERLEFT],&particle[RAGBASIC_BICEPLEFT]);
link[21].Set(&particle[RAGBASIC_SHOULDERLEFT],&particle[RAGBASIC_TRICEPLEFT]);
link[22].Set(&particle[RAGBASIC_BICEPLEFT],&particle[RAGBASIC_UPELBOWLEFT]);
link[23].Set(&particle[RAGBASIC_BICEPLEFT],&particle[RAGBASIC_LOWELBOWLEFT]);
link[24].Set(&particle[RAGBASIC_TRICEPLEFT],&particle[RAGBASIC_UPELBOWLEFT]);
link[25].Set(&particle[RAGBASIC_TRICEPLEFT],&particle[RAGBASIC_LOWELBOWLEFT]);
link[26].Set(&particle[RAGBASIC_UPELBOWLEFT],&particle[RAGBASIC_LOWELBOWLEFT]);
link[27].Set(&particle[RAGBASIC_UPELBOWLEFT],&particle[RAGBASIC_HANDLEFT]);
link[28].Set(&particle[RAGBASIC_LOWELBOWLEFT],&particle[RAGBASIC_HANDLEFT]);
//Right arm
link[29].Set(&particle[RAGBASIC_SHOULDERRIGHT],&particle[RAGBASIC_UPELBOWRIGHT]);
link[30].Set(&particle[RAGBASIC_SHOULDERRIGHT],&particle[RAGBASIC_LOWELBOWRIGHT]);
link[31].Set(&particle[RAGBASIC_SHOULDERRIGHT],&particle[RAGBASIC_BICEPRIGHT]);
link[32].Set(&particle[RAGBASIC_SHOULDERRIGHT],&particle[RAGBASIC_TRICEPRIGHT]);
link[33].Set(&particle[RAGBASIC_BICEPRIGHT],&particle[RAGBASIC_UPELBOWRIGHT]);
link[34].Set(&particle[RAGBASIC_BICEPRIGHT],&particle[RAGBASIC_LOWELBOWRIGHT]);
link[35].Set(&particle[RAGBASIC_TRICEPRIGHT],&particle[RAGBASIC_UPELBOWRIGHT]);
link[36].Set(&particle[RAGBASIC_TRICEPRIGHT],&particle[RAGBASIC_LOWELBOWRIGHT]);
link[37].Set(&particle[RAGBASIC_UPELBOWRIGHT],&particle[RAGBASIC_LOWELBOWRIGHT]);
link[38].Set(&particle[RAGBASIC_UPELBOWRIGHT],&particle[RAGBASIC_HANDRIGHT]);
link[39].Set(&particle[RAGBASIC_LOWELBOWRIGHT],&particle[RAGBASIC_HANDRIGHT]);
//Left leg
link[40].Set(&particle[RAGBASIC_LEGTOPLEFT],&particle[RAGBASIC_INKNEELEFT]);
link[41].Set(&particle[RAGBASIC_LEGTOPLEFT],&particle[RAGBASIC_OUTKNEELEFT]);
link[42].Set(&particle[RAGBASIC_LEGTOPLEFT],&particle[RAGBASIC_QUADLEFT]);
link[43].Set(&particle[RAGBASIC_LEGTOPLEFT],&particle[RAGBASIC_HAMLEFT]);
link[44].Set(&particle[RAGBASIC_QUADLEFT],&particle[RAGBASIC_INKNEELEFT]);
link[45].Set(&particle[RAGBASIC_QUADLEFT],&particle[RAGBASIC_OUTKNEELEFT]);
link[46].Set(&particle[RAGBASIC_HAMLEFT],&particle[RAGBASIC_INKNEELEFT]);
link[47].Set(&particle[RAGBASIC_HAMLEFT],&particle[RAGBASIC_OUTKNEELEFT]);
link[48].Set(&particle[RAGBASIC_INKNEELEFT],&particle[RAGBASIC_OUTKNEELEFT]);
link[49].Set(&particle[RAGBASIC_INKNEELEFT],&particle[RAGBASIC_FOOTLEFT]);
link[50].Set(&particle[RAGBASIC_OUTKNEELEFT],&particle[RAGBASIC_FOOTLEFT]);
//Right leg
link[51].Set(&particle[RAGBASIC_LEGTOPRIGHT],&particle[RAGBASIC_INKNEERIGHT]);
link[52].Set(&particle[RAGBASIC_LEGTOPRIGHT],&particle[RAGBASIC_OUTKNEERIGHT]);
link[53].Set(&particle[RAGBASIC_LEGTOPRIGHT],&particle[RAGBASIC_QUADRIGHT]);
link[54].Set(&particle[RAGBASIC_LEGTOPRIGHT],&particle[RAGBASIC_HAMRIGHT]);
link[55].Set(&particle[RAGBASIC_QUADRIGHT],&particle[RAGBASIC_INKNEERIGHT]);
link[56].Set(&particle[RAGBASIC_QUADRIGHT],&particle[RAGBASIC_OUTKNEERIGHT]);
link[57].Set(&particle[RAGBASIC_HAMRIGHT],&particle[RAGBASIC_INKNEERIGHT]);
link[58].Set(&particle[RAGBASIC_HAMRIGHT],&particle[RAGBASIC_OUTKNEERIGHT]);
link[59].Set(&particle[RAGBASIC_INKNEERIGHT],&particle[RAGBASIC_OUTKNEERIGHT]);
link[60].Set(&particle[RAGBASIC_INKNEERIGHT],&particle[RAGBASIC_FOOTRIGHT]);
link[61].Set(&particle[RAGBASIC_OUTKNEERIGHT],&particle[RAGBASIC_FOOTRIGHT]);
//Don't let head get too close to chest
link[62].Set(&particle[RAGBASIC_HEADLEFT],&particle[RAGBASIC_CHEST],RAGLINK_MINIMUM,0.48f*0.48f);
link[63].Set(&particle[RAGBASIC_HEADRIGHT],&particle[RAGBASIC_CHEST],RAGLINK_MINIMUM,0.48f*0.48f);
//Don't let head get too close or far away from shoulders
link[64].Set(&particle[RAGBASIC_HEADLEFT],&particle[RAGBASIC_SHOULDERLEFT],RAGLINK_MINMAX,0.13f*0.13f,0.51f*0.51f);
link[65].Set(&particle[RAGBASIC_HEADRIGHT],&particle[RAGBASIC_SHOULDERRIGHT],RAGLINK_MINMAX,0.13f*0.13f,0.51f*0.51f);
//Rotational head restraint
link[66].Set(&particle[RAGBASIC_SHOULDERRIGHT],&particle[RAGBASIC_HEADLEFT],&particle[RAGBASIC_HEADRIGHT],0.05f);
link[67].Set(&particle[RAGBASIC_SHOULDERLEFT],&particle[RAGBASIC_HEADRIGHT],&particle[RAGBASIC_HEADLEFT],0.05f);
}
| 59.128378 | 118 | 0.801623 | domydev |
7476fde2adbe24d7a6020e259ca1b111a4021917 | 30,297 | hpp | C++ | data_compression/L1/include/hw/inflate.hpp | dycz0fx/Vitis_Libraries | d3fc414b552493657101ddb5245f24528720823d | [
"Apache-2.0"
] | null | null | null | data_compression/L1/include/hw/inflate.hpp | dycz0fx/Vitis_Libraries | d3fc414b552493657101ddb5245f24528720823d | [
"Apache-2.0"
] | null | null | null | data_compression/L1/include/hw/inflate.hpp | dycz0fx/Vitis_Libraries | d3fc414b552493657101ddb5245f24528720823d | [
"Apache-2.0"
] | null | null | null | /*
* (c) Copyright 2019-2021 Xilinx, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _XFCOMPRESSION_INFLATE_HPP_
#define _XFCOMPRESSION_INFLATE_HPP_
#include "ap_axi_sdata.h"
#include "hls_stream.h"
#include "huffman_decoder.hpp"
#include "lz_decompress.hpp"
#include "stream_upsizer.hpp"
#include "stream_downsizer.hpp"
#include "mm2s.hpp"
#include "s2mm.hpp"
#include "checksum_wrapper.hpp"
#include <ap_int.h>
#include <assert.h>
#include <stdint.h>
namespace xf {
namespace compression {
namespace details {
template <int PARALLEL_BYTES>
void lzLiteralUpsizer(hls::stream<ap_uint<10> >& inStream, hls::stream<ap_uint<PARALLEL_BYTES * 8> >& litStream) {
const uint8_t c_parallelBit = PARALLEL_BYTES * 8;
const uint8_t c_maxLitLen = 128;
ap_uint<c_parallelBit> outBuffer;
ap_uint<4> idx = 0;
ap_uint<2> status = 0;
ap_uint<10> val;
bool done = false;
lzliteralUpsizer:
while (status != 2) {
#pragma HLS PIPELINE II = 1
status = 0;
val = inStream.read();
status = val.range(1, 0);
outBuffer.range((idx + 1) * 8 - 1, idx * 8) = val.range(9, 2);
idx++;
if ((status & 1) || (idx == 8)) {
if (status != 3) {
litStream << outBuffer;
}
idx = 0;
}
}
if (idx > 1) {
litStream << outBuffer;
idx = 0;
}
}
template <int PARALLEL_BYTES>
void lzLiteralUpsizerLL(hls::stream<ap_uint<10> >& inStream, hls::stream<ap_uint<PARALLEL_BYTES * 8> >& litStream) {
const uint8_t c_parallelBit = PARALLEL_BYTES * 8;
const uint8_t c_maxLitLen = 128;
ap_uint<c_parallelBit> outBuffer;
ap_uint<4> idx = 0;
ap_uint<2> status = 0;
ap_uint<10> val;
bool done = false;
lzliteralUpsizer:
while (status != 2) {
#pragma HLS PIPELINE II = 1
status = 0;
val = inStream.read();
status = val.range(1, 0);
outBuffer.range((idx + 1) * 8 - 1, idx * 8) = val.range(9, 2);
idx++;
if ((status & 1) || (idx == PARALLEL_BYTES)) {
if (idx > 1) {
litStream << outBuffer;
}
idx = 0;
}
}
if (idx > 1) {
litStream << outBuffer;
idx = 0;
}
}
template <class SIZE_DT = uint8_t>
void lzProcessingUnit(hls::stream<ap_uint<17> >& inStream,
hls::stream<SIZE_DT>& litLenStream,
hls::stream<SIZE_DT>& matchLenStream,
hls::stream<ap_uint<16> >& offsetStream,
hls::stream<ap_uint<10> >& outStream) {
ap_uint<17> inValue, nextValue;
const int c_maxLitLen = 128;
uint16_t offset = 0;
uint16_t matchLen = 0;
uint8_t litLen = 0;
uint8_t outLitLen = 0;
ap_uint<10> lit = 0;
nextValue = inStream.read();
bool eosFlag = nextValue.range(0, 0);
bool lastLiteral = false;
bool isLiteral = true;
lzProcessing:
for (; eosFlag == false;) {
#pragma HLS PIPELINE II = 1
inValue = nextValue;
nextValue = inStream.read();
eosFlag = nextValue.range(0, 0);
bool outFlag, outStreamFlag;
if (inValue.range(16, 9) == 0xFF && isLiteral) {
outStreamFlag = true;
outLitLen = litLen + 1;
if (litLen == c_maxLitLen - 1) {
outFlag = true;
matchLen = 0;
offset = 1; // dummy value
litLen = 0;
} else {
outFlag = false;
litLen++;
}
} else {
if (isLiteral) {
matchLen = inValue.range(16, 1);
isLiteral = false;
outFlag = false;
outStreamFlag = false;
} else {
offset = inValue.range(16, 1);
isLiteral = true;
outFlag = true;
outLitLen = litLen;
litLen = 0;
outStreamFlag = false;
}
}
if (outStreamFlag) {
lit.range(9, 2) = inValue.range(8, 1);
if (nextValue.range(16, 9) == 0xFF) {
lit.range(1, 0) = 0;
} else {
lit.range(1, 0) = 1;
}
lastLiteral = true;
outStream << lit;
} else if (lastLiteral) {
outStream << 3;
lastLiteral = false;
}
if (outFlag) {
litLenStream << outLitLen;
offsetStream << offset;
matchLenStream << matchLen;
}
}
if (litLen) {
litLenStream << litLen;
offsetStream << 0;
matchLenStream << 0;
}
// Terminate condition
outStream << 2;
offsetStream << 0;
matchLenStream << 0;
litLenStream << 0;
}
template <class SIZE_DT = uint8_t, int PARALLEL_BYTES = 8, int OWIDTH = 16>
void lzPreProcessingUnitLL(hls::stream<SIZE_DT>& inLitLen,
hls::stream<SIZE_DT>& inMatchLen,
hls::stream<ap_uint<OWIDTH> >& inOffset,
hls::stream<ap_uint<11 + OWIDTH> >& outInfo) {
SIZE_DT litlen = inLitLen.read();
SIZE_DT matchlen = inMatchLen.read();
ap_uint<OWIDTH> offset = inOffset.read();
ap_uint<OWIDTH> litCount = litlen;
ap_uint<4> l_litlen = 0;
ap_uint<4> l_matchlen = 0;
ap_uint<3> l_stateinfo = 0;
ap_uint<OWIDTH> l_matchloc = litCount - offset;
ap_uint<11 + OWIDTH> outVal = 0; // 0-15 Match Loc, 16-19 Match Len, 20-23 Lit length, 24-26 State Info
bool done = false;
bool read = false;
bool fdone = false;
if (litlen == 0) {
outVal.range(OWIDTH - 1, 0) = 0;
outVal.range(OWIDTH + 3, OWIDTH) = matchlen;
outVal.range(OWIDTH + 7, OWIDTH + 4) = litlen;
outVal.range(OWIDTH + 10, OWIDTH + 8) = 6;
outInfo << outVal;
done = true;
fdone = false;
}
while (!done) {
#pragma HLS PIPELINE II = 1
if (litlen) {
SIZE_DT val = (litlen > PARALLEL_BYTES) ? (SIZE_DT)PARALLEL_BYTES : litlen;
litlen -= val;
l_litlen = val;
l_matchlen = 0;
l_stateinfo = 0;
l_matchloc = 0;
read = (matchlen || litlen) ? false : true;
} else {
l_matchlen = (offset > PARALLEL_BYTES)
? ((matchlen > PARALLEL_BYTES) ? (SIZE_DT)PARALLEL_BYTES : (SIZE_DT)matchlen)
: (matchlen > offset) ? (SIZE_DT)offset : (SIZE_DT)matchlen;
if (offset < 6 * PARALLEL_BYTES) {
l_stateinfo.range(0, 0) = 1;
l_stateinfo.range(2, 1) = 1;
} else {
l_stateinfo.range(0, 0) = 0;
l_stateinfo.range(2, 1) = 1;
}
l_matchloc = litCount - offset;
if (offset < PARALLEL_BYTES) {
offset = offset << 1;
}
l_litlen = 0;
litCount += l_matchlen;
matchlen -= l_matchlen;
litlen = 0;
read = matchlen ? false : true;
}
outVal.range(OWIDTH - 1, 0) = l_matchloc;
outVal.range(OWIDTH + 3, OWIDTH) = l_matchlen;
outVal.range(OWIDTH + 7, OWIDTH + 4) = l_litlen;
outVal.range(OWIDTH + 10, OWIDTH + 8) = l_stateinfo;
outInfo << outVal;
if (read) {
litlen = inLitLen.read();
matchlen = inMatchLen.read();
offset = inOffset.read();
litCount += litlen;
if (litlen == 0 && matchlen == 0) {
done = true;
fdone = true;
}
}
}
if (fdone) {
outVal.range(OWIDTH - 1, 0) = l_matchloc;
outVal.range(OWIDTH + 3, OWIDTH) = matchlen;
outVal.range(OWIDTH + 7, OWIDTH + 4) = litlen;
outVal.range(OWIDTH + 10, OWIDTH + 8) = 6;
outInfo << outVal;
}
}
template <class SIZE_DT = uint8_t>
void lzProcessingUnitLL(hls::stream<ap_uint<16> >& inStream,
hls::stream<SIZE_DT>& litLenStream,
hls::stream<SIZE_DT>& matchLenStream,
hls::stream<ap_uint<16> >& offsetStream,
hls::stream<ap_uint<10> >& outStream) {
ap_uint<16> inValue, nextValue;
const int c_maxLitLen = 128;
uint16_t offset = 0;
uint16_t matchLen = 0;
uint8_t litLen = 0;
uint8_t outLitLen = 0;
ap_uint<10> lit = 0;
const uint16_t lbase[32] = {0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27,
31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
const uint16_t dbase[32] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
nextValue = inStream.read();
bool eosFlag = (nextValue == 0xFFFF) ? true : false;
bool lastLiteral = false;
bool isLitLength = true;
bool isExtra = false;
bool dummyValue = false;
lzProcessing:
for (; eosFlag == false;) {
#pragma HLS PIPELINE II = 1
inValue = nextValue;
nextValue = inStream.read();
eosFlag = (nextValue == 0xFFFF);
bool outFlag, outStreamFlag;
if ((inValue.range(15, 8) == 0xFE) || (inValue.range(15, 8) == 0xFD)) {
// ignore invalid byte
outFlag = false;
outStreamFlag = false;
} else if (inValue.range(15, 8) == 0xF0) {
outStreamFlag = true;
outLitLen = litLen + 1;
if (litLen == c_maxLitLen - 1) {
outFlag = true;
matchLen = 0;
offset = 1; // dummy value
litLen = 0;
} else {
outFlag = false;
matchLen = 0;
offset = 1; // dummy value
litLen++;
}
} else if (isExtra && isLitLength) { // matchLen Extra
matchLen += inValue.range(15, 0);
isExtra = false;
isLitLength = false;
outStreamFlag = true;
} else if (isExtra && !isLitLength) { // offset Extra
offset += inValue.range(15, 0);
isExtra = false;
isLitLength = true;
outFlag = true;
outStreamFlag = true;
} else if (isLitLength) {
auto val = inValue.range(4, 0);
matchLen = lbase[val];
if (val < 9) {
isExtra = false;
isLitLength = false;
} else {
isExtra = true;
isLitLength = true;
}
outFlag = false;
outStreamFlag = true;
dummyValue = true;
} else {
auto val = inValue.range(4, 0);
offset = dbase[val];
if (val < 4) {
isExtra = false;
isLitLength = true;
outFlag = true;
} else {
isExtra = true;
isLitLength = false;
outFlag = false;
}
outLitLen = litLen;
litLen = 0;
outStreamFlag = true;
}
if (outStreamFlag) {
lit.range(9, 2) = inValue.range(7, 0);
if ((inValue.range(15, 8) == 0xF0)) {
lit.range(1, 0) = 0;
} else {
lit.range(1, 0) = 1;
}
outStream << lit;
}
if (outFlag) {
litLenStream << outLitLen;
offsetStream << offset;
matchLenStream << matchLen;
}
}
if (litLen) {
litLenStream << litLen;
offsetStream << 0;
matchLenStream << 0;
outStream << 3;
}
// Terminate condition
outStream << 2;
offsetStream << 0;
matchLenStream << 0;
litLenStream << 0;
}
template <int STREAM_WIDTH>
void kStreamReadZlibDecomp(hls::stream<ap_axiu<STREAM_WIDTH, 0, 0, 0> >& in,
hls::stream<ap_uint<STREAM_WIDTH> >& out,
hls::stream<bool>& outEos) {
/**
* @brief kStreamReadZlibDecomp Read 16-bit wide data from internal streams output by compression modules
* and write to output axi stream.
*
* @param inKStream input kernel stream
* @param readStream internal stream to be read for processing
* @param input_size input data size
*
*/
bool last = false;
while (last == false) {
#pragma HLS PIPELINE II = 1
ap_axiu<STREAM_WIDTH, 0, 0, 0> tmp = in.read();
out << tmp.data;
last = tmp.last;
outEos << 0;
}
out << 0;
outEos << 1; // Terminate condition
}
template <int STREAM_WIDTH>
void kStreamWriteZlibDecomp(hls::stream<ap_axiu<STREAM_WIDTH, 0, 0, 0> >& outKStream,
hls::stream<ap_uint<STREAM_WIDTH + (STREAM_WIDTH / 8)> >& outDataStream) {
/**
* @brief kStreamWriteZlibDecomp Read 16-bit wide data from internal streams output by compression modules
* and write to output axi stream.
*
* @param outKStream output kernel stream
* @param outDataStream output data stream from internal modules
*
*/
ap_uint<STREAM_WIDTH / 8> strb = 0;
ap_uint<STREAM_WIDTH> data;
ap_uint<STREAM_WIDTH + (STREAM_WIDTH / 8)> tmp;
ap_axiu<STREAM_WIDTH, 0, 0, 0> t1;
tmp = outDataStream.read();
strb = tmp.range((STREAM_WIDTH / 8) - 1, 0);
t1.data = tmp.range(STREAM_WIDTH + (STREAM_WIDTH / 8) - 1, STREAM_WIDTH / 8);
t1.strb = strb;
t1.keep = strb;
t1.last = 0;
if (strb == 0) {
t1.last = 1;
outKStream << t1;
}
while (strb != 0) {
#pragma HLS PIPELINE II = 1
tmp = outDataStream.read();
strb = tmp.range((STREAM_WIDTH / 8) - 1, 0);
if (strb == 0) {
t1.last = 1;
}
outKStream << t1;
t1.data = tmp.range(STREAM_WIDTH + (STREAM_WIDTH / 8) - 1, STREAM_WIDTH / 8);
t1.strb = strb;
t1.keep = strb;
t1.last = 0;
}
}
template <int STREAM_WIDTH, int TUSER_WIDTH>
void hls2AXIWithTUSER(hls::stream<ap_axiu<STREAM_WIDTH, TUSER_WIDTH, 0, 0> >& outAxi,
hls::stream<ap_uint<STREAM_WIDTH + (STREAM_WIDTH / 8)> >& inData,
hls::stream<bool>& inError) {
ap_uint<STREAM_WIDTH / 8> strb = 0;
ap_uint<STREAM_WIDTH> data;
ap_uint<STREAM_WIDTH + (STREAM_WIDTH / 8)> tmp;
ap_axiu<STREAM_WIDTH, TUSER_WIDTH, 0, 0> t1;
ap_uint<TUSER_WIDTH - 1> fileSize = 0;
tmp = inData.read();
strb = tmp.range((STREAM_WIDTH / 8) - 1, 0);
t1.data = tmp.range(STREAM_WIDTH + (STREAM_WIDTH / 8) - 1, STREAM_WIDTH / 8);
t1.strb = strb;
t1.keep = strb;
t1.last = 0;
t1.user = 0;
if (strb == 0) {
t1.last = 1;
outAxi << t1;
}
AXI2HLS:
while (strb != 0) {
#pragma HLS PIPELINE II = 1
FILESIZE:
for (ap_uint<4> i = 0; i < (STREAM_WIDTH / 8); i++) {
#pragma HLS UNROLL
fileSize += (strb & 0x1);
strb >>= 1;
}
tmp = inData.read();
strb = tmp.range((STREAM_WIDTH / 8) - 1, 0);
if (strb == 0) {
t1.last = 1;
t1.user.range(TUSER_WIDTH - 1, 1) = fileSize;
t1.user.range(0, 0) = inError.read();
}
outAxi << t1;
t1.data = tmp.range(STREAM_WIDTH + (STREAM_WIDTH / 8) - 1, STREAM_WIDTH / 8);
t1.strb = strb;
t1.keep = strb;
t1.last = 0;
}
}
/**
* @brief Splits input into data and strb
*
* @tparam DATA_WIDTH data width of data stream
* @param input combined input of data and strb
* @param outData output data
* @param outStrb output strb
*/
template <int DATA_WIDTH>
void dataStrbSplitter(hls::stream<ap_uint<(DATA_WIDTH * 8) + DATA_WIDTH> >& input,
hls::stream<ap_uint<DATA_WIDTH * 8> >& outData,
hls::stream<ap_uint<5> >& outStrb) {
ap_uint<DATA_WIDTH> strb = 0;
splitter:
while (1) {
#pragma HLS PIPELINE II = 1
auto inVal = input.read();
auto data = inVal.range((DATA_WIDTH * 8) + DATA_WIDTH - 1, DATA_WIDTH);
strb = inVal.range(DATA_WIDTH - 1, 0);
auto strbVal = strb;
if (strb == 0) break;
outData << data;
ap_uint<5> size = 0;
for (ap_uint<4> i = 0; i < DATA_WIDTH; i++) {
#pragma HLS UNROLL
size += (strbVal & 0x1);
strbVal >>= 1;
}
outStrb << size;
}
if (strb == 0) outStrb << 0;
}
/**
* @brief Splits Data Stream into multiple
*
* @tparam DATA_WIDTH
* @param input input stream
* @param output1 output streams
* @param output2 output streams
*/
template <int DATA_WIDTH>
void streamDistributor(hls::stream<ap_uint<(DATA_WIDTH * 8) + DATA_WIDTH> >& input,
hls::stream<ap_uint<(DATA_WIDTH * 8) + DATA_WIDTH> >& output1,
hls::stream<ap_uint<(DATA_WIDTH * 8) + DATA_WIDTH> >& output2) {
ap_uint<DATA_WIDTH> strb = 0;
do {
#pragma HLS PIPELINE II = 1
auto inVal = input.read();
strb = inVal.range(DATA_WIDTH - 1, 0);
output1 << inVal;
output2 << inVal;
} while (strb != 0);
}
/**
* @brief compare two checksums and generate 0 if match and 1 otherwise
*
* @param checkSum1 1st checksum input
* @param checkSum2 2nd checksum input
* @param output error output
*/
void chckSumComparator(hls::stream<ap_uint<32> >& checkSum1,
hls::stream<ap_uint<32> >& checkSum2,
hls::stream<bool>& output) {
auto chk1 = checkSum1.read();
auto chk2 = checkSum2.read();
output << (chk1 != chk2);
}
template <int DECODER, int PARALLEL_BYTES, int FILE_FORMAT, bool LOW_LATENCY = false, int HISTORY_SIZE = (32 * 1024)>
void inflateMultiByteCore(hls::stream<ap_uint<16> >& inStream,
hls::stream<bool>& inEos,
hls::stream<ap_uint<(PARALLEL_BYTES * 8) + PARALLEL_BYTES> >& outStream) {
const int c_parallelBit = PARALLEL_BYTES * 8;
const eHuffmanType c_decoderType = (eHuffmanType)DECODER;
const FileFormat c_fileformat = (FileFormat)FILE_FORMAT;
hls::stream<ap_uint<17> > bitunpackstream("bitUnPackStream");
hls::stream<ap_uint<16> > bitunpackstreamLL("bitUnPackStreamLL");
hls::stream<ap_uint<c_parallelBit> > litStream("litStream");
hls::stream<ap_uint<9> > matchLenStream("matchLenStream");
hls::stream<ap_uint<9> > litLenStream("litLenStream");
hls::stream<ap_uint<16> > offsetStream("offsetStream");
hls::stream<ap_uint<10> > lzProcOutStream("lzProcOutStream");
hls::stream<ap_uint<27> > infoStream("infoStream");
#pragma HLS STREAM variable = litStream depth = 32
#pragma HLS STREAM variable = lzProcOutStream depth = 16
#pragma HLS STREAM variable = bitunpackstream depth = 1024
#pragma HLS STREAM variable = bitunpackstreamLL depth = 256
#pragma HLS STREAM variable = litLenStream depth = 16
#pragma HLS STREAM variable = matchLenStream depth = 16
#pragma HLS STREAM variable = offsetStream depth = 16
#pragma HLS STREAM variable = infoStream depth = 4
#pragma HLS BIND_STORAGE variable = litStream type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = bitunpackstream type = FIFO impl = BRAM
#pragma HLS BIND_STORAGE variable = bitunpackstreamLL type = fifo impl = lutram
#pragma HLS BIND_STORAGE variable = lzProcOutStream type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = litLenStream type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = matchLenStream type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = offsetStream type = FIFO impl = SRL
#pragma HLS dataflow
if (LOW_LATENCY) {
xf::compression::huffmanDecoderLL<c_decoderType, c_fileformat>(inStream, inEos, bitunpackstreamLL);
xf::compression::details::lzProcessingUnitLL<ap_uint<9> >(bitunpackstreamLL, litLenStream, matchLenStream,
offsetStream, lzProcOutStream);
xf::compression::details::lzPreProcessingUnitLL<ap_uint<9>, PARALLEL_BYTES, 16>(litLenStream, matchLenStream,
offsetStream, infoStream);
xf::compression::details::lzLiteralUpsizerLL<PARALLEL_BYTES>(lzProcOutStream, litStream);
xf::compression::lzMultiByteDecompressLL<PARALLEL_BYTES, HISTORY_SIZE, 16, ap_uint<9>, ap_uint<16> >(
litStream, infoStream, outStream);
} else {
xf::compression::huffmanDecoder<c_decoderType>(inStream, inEos, bitunpackstream);
xf::compression::details::lzProcessingUnit<ap_uint<9> >(bitunpackstream, litLenStream, matchLenStream,
offsetStream, lzProcOutStream);
xf::compression::details::lzLiteralUpsizer<PARALLEL_BYTES>(lzProcOutStream, litStream);
xf::compression::lzMultiByteDecompress<PARALLEL_BYTES, HISTORY_SIZE, ap_uint<9> >(
litLenStream, litStream, offsetStream, matchLenStream, outStream);
}
}
template <int DECODER, int PARALLEL_BYTES, int FILE_FORMAT, int HISTORY_SIZE = (8 * 1024)>
void inflateWithChkSum(hls::stream<ap_uint<16> >& inStream,
hls::stream<bool>& inEos,
hls::stream<ap_uint<(PARALLEL_BYTES * 8) + PARALLEL_BYTES> >& outStream,
hls::stream<bool>& errorStrm) {
const int c_parallelBit = PARALLEL_BYTES * 8;
const eHuffmanType c_decoderType = (eHuffmanType)DECODER;
const FileFormat c_fileformat = (FileFormat)FILE_FORMAT;
hls::stream<ap_uint<16> > bitunpackstreamLL("bitUnPackStreamLL");
hls::stream<ap_uint<c_parallelBit> > litStream("litStream");
hls::stream<ap_uint<9> > matchLenStream("matchLenStream");
hls::stream<ap_uint<9> > litLenStream("litLenStream");
hls::stream<ap_uint<16> > offsetStream("offsetStream");
hls::stream<ap_uint<10> > lzProcOutStream("lzProcOutStream");
hls::stream<ap_uint<27> > infoStream("infoStream");
hls::stream<ap_uint<32> > chckSum[2];
hls::stream<ap_uint<(PARALLEL_BYTES * 8) + PARALLEL_BYTES> > lzOut("lzOut");
hls::stream<ap_uint<(PARALLEL_BYTES * 8) + PARALLEL_BYTES> > lzDistOut("lzDistOut");
hls::stream<ap_uint<(PARALLEL_BYTES * 8)> > lzData("lzData");
hls::stream<ap_uint<5> > lzStrb("lzStrb");
#pragma HLS STREAM variable = litStream depth = 32
#pragma HLS STREAM variable = lzProcOutStream depth = 16
#pragma HLS STREAM variable = bitunpackstreamLL depth = 256
#pragma HLS STREAM variable = litLenStream depth = 64
#pragma HLS STREAM variable = matchLenStream depth = 64
#pragma HLS STREAM variable = offsetStream depth = 64
#pragma HLS STREAM variable = infoStream depth = 4
#pragma HLS STREAM variable = chckSum depth = 4
#pragma HLS STREAM variable = lzOut depth = 4
#pragma HLS STREAM variable = lzDistOut depth = 4
#pragma HLS STREAM variable = lzData depth = 4
#pragma HLS STREAM variable = lzStrb depth = 4
#pragma HLS STREAM variable = chckSum depth = 4
#pragma HLS BIND_STORAGE variable = litStream type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = bitunpackstreamLL type = fifo impl = lutram
#pragma HLS BIND_STORAGE variable = lzProcOutStream type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = litLenStream type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = matchLenStream type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = offsetStream type = FIFO impl = SRL
#pragma HLS dataflow
xf::compression::huffmanDecoderLL<c_decoderType, c_fileformat>(inStream, inEos, bitunpackstreamLL, chckSum[0]);
xf::compression::details::lzProcessingUnitLL<ap_uint<9> >(bitunpackstreamLL, litLenStream, matchLenStream,
offsetStream, lzProcOutStream);
xf::compression::details::lzPreProcessingUnitLL<ap_uint<9>, PARALLEL_BYTES, 16>(litLenStream, matchLenStream,
offsetStream, infoStream);
xf::compression::details::lzLiteralUpsizerLL<PARALLEL_BYTES>(lzProcOutStream, litStream);
xf::compression::lzMultiByteDecompressLL<PARALLEL_BYTES, HISTORY_SIZE, 16, ap_uint<9>, ap_uint<16> >(
litStream, infoStream, lzOut);
xf::compression::details::streamDistributor<PARALLEL_BYTES>(lzOut, lzDistOut, outStream);
xf::compression::details::dataStrbSplitter<PARALLEL_BYTES>(lzDistOut, lzData, lzStrb);
xf::compression::details::adler32<PARALLEL_BYTES>(lzData, lzStrb, chckSum[1]);
xf::compression::details::chckSumComparator(chckSum[0], chckSum[1], errorStrm);
}
} // namespace details
template <int DECODER, int PARALLEL_BYTES, int FILE_FORMAT, bool LOW_LATENCY = false, int HISTORY_SIZE = (32 * 1024)>
void inflateMultiByte(hls::stream<ap_axiu<16, 0, 0, 0> >& inaxistream,
hls::stream<ap_axiu<PARALLEL_BYTES * 8, 0, 0, 0> >& outaxistream) {
const int c_parallelBit = PARALLEL_BYTES * 8;
hls::stream<ap_uint<16> > axi2HlsStrm("axi2HlsStrm");
hls::stream<bool> axi2HlsEos("axi2HlsEos");
hls::stream<ap_uint<c_parallelBit + PARALLEL_BYTES> > inflateOut("inflateOut");
hls::stream<uint64_t> outSizeStream("outSizeStream");
#pragma HLS STREAM variable = axi2HlsStrm depth = 32
#pragma HLS STREAM variable = axi2HlsEos depth = 32
#pragma HLS STREAM variable = inflateOut depth = 32
//#pragma HLS STREAM variable = inflateOut depth = 4096
#pragma HLS BIND_STORAGE variable = axi2HlsStrm type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = axi2HlsEos type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = inflateOut type = fifo impl = SRL
#pragma HLS dataflow
details::kStreamReadZlibDecomp<16>(inaxistream, axi2HlsStrm, axi2HlsEos);
details::inflateMultiByteCore<DECODER, PARALLEL_BYTES, FILE_FORMAT, LOW_LATENCY, HISTORY_SIZE>(
axi2HlsStrm, axi2HlsEos, inflateOut);
details::kStreamWriteZlibDecomp<c_parallelBit>(outaxistream, inflateOut);
}
template <int DECODER, int PARALLEL_BYTES, int FILE_FORMAT, int HISTORY_SIZE = (32 * 1024), int TUSER_WIDTH = 32>
void inflate(hls::stream<ap_axiu<16, 0, 0, 0> >& inaxistream,
hls::stream<ap_axiu<PARALLEL_BYTES * 8, TUSER_WIDTH, 0, 0> >& outaxistream) {
const int c_parallelBit = PARALLEL_BYTES * 8;
hls::stream<ap_uint<16> > axi2HlsStrm("axi2HlsStrm");
hls::stream<bool> axi2HlsEos("axi2HlsEos");
hls::stream<ap_uint<c_parallelBit + PARALLEL_BYTES> > inflateOut("inflateOut");
hls::stream<uint64_t> outSizeStream("outSizeStream");
hls::stream<bool> error("error");
#pragma HLS STREAM variable = axi2HlsStrm depth = 32
#pragma HLS STREAM variable = axi2HlsEos depth = 32
#pragma HLS STREAM variable = inflateOut depth = 32
#pragma HLS STREAM variable = error depth = 4
#pragma HLS BIND_STORAGE variable = axi2HlsStrm type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = axi2HlsEos type = FIFO impl = SRL
#pragma HLS BIND_STORAGE variable = inflateOut type = fifo impl = SRL
#pragma HLS dataflow
details::kStreamReadZlibDecomp<16>(inaxistream, axi2HlsStrm, axi2HlsEos);
details::inflateWithChkSum<DECODER, PARALLEL_BYTES, FILE_FORMAT, HISTORY_SIZE>(axi2HlsStrm, axi2HlsEos, inflateOut,
error);
details::hls2AXIWithTUSER<c_parallelBit, TUSER_WIDTH>(outaxistream, inflateOut, error);
}
template <int GMEM_DATAWIDTH,
int GMEM_BRST_SIZE,
int DECODER,
int PARALLEL_BYTES,
int FILE_FORMAT,
bool LOW_LATENCY = false,
int HISTORY_SIZE = (32 * 1024)>
void inflateMultiByteMM(const ap_uint<GMEM_DATAWIDTH>* in,
ap_uint<GMEM_DATAWIDTH>* out,
uint32_t* encodedSize,
uint32_t inputSize) {
#pragma HLS dataflow
constexpr int c_inBitWidth = 16;
constexpr int c_burstDepth = 2 * GMEM_BRST_SIZE;
// Internal Streams
hls::stream<ap_uint<GMEM_DATAWIDTH> > mm2sStream;
hls::stream<ap_uint<c_inBitWidth> > inInfateStream;
hls::stream<bool> inInfateStreamEos;
hls::stream<uint32_t> sizeStream;
hls::stream<uint32_t> sizeStreamV;
hls::stream<ap_uint<GMEM_DATAWIDTH + PARALLEL_BYTES> > outStream;
// Initialize Size Stream
uint32_t tmp = inputSize;
sizeStreamV.write(tmp);
#pragma HLS STREAM variable = mm2sStream depth = c_burstDepth
#pragma HLS STREAM variable = inInfateStream depth = c_burstDepth
#pragma HLS STREAM variable = inInfateStreamEos depth = c_burstDepth
#pragma HLS STREAM variable = sizeStream depth = 4
#pragma HLS STREAM variable = sizeStreamV depth = 4
#pragma HLS STREAM variable = outStream depth = c_burstDepth
// MM2S
xf::compression::details::mm2sSimple<GMEM_DATAWIDTH, GMEM_BRST_SIZE>(in, mm2sStream, sizeStream, sizeStreamV);
// Downsizer
xf::compression::details::streamDownsizerEos<GMEM_DATAWIDTH, c_inBitWidth>(mm2sStream, sizeStream, inInfateStream,
inInfateStreamEos);
// Decompression
xf::compression::details::inflateMultiByteCore<DECODER, PARALLEL_BYTES, FILE_FORMAT, LOW_LATENCY, HISTORY_SIZE>(
inInfateStream, inInfateStreamEos, outStream);
// S2MM
xf::compression::details::s2mmAxi<GMEM_DATAWIDTH, GMEM_BRST_SIZE, PARALLEL_BYTES>(out, outStream, encodedSize);
}
} // namespace compression
} // namespace xf
#endif
| 37.265683 | 119 | 0.593689 | dycz0fx |
7477040b51470e20cacc6f6f6062009e089f6d9d | 552 | cpp | C++ | Source/RenderPasses/MotionedShadow/MotionedShadow.cpp | ligenvin/RealTimeRayTracing | 4bb738cbcb89ede3d462d11ea23f44c997af8892 | [
"BSD-3-Clause"
] | 2 | 2021-12-19T08:26:31.000Z | 2022-01-24T09:17:32.000Z | Source/RenderPasses/MotionedShadow/MotionedShadow.cpp | ligenvin/RealTimeRayTracing | 4bb738cbcb89ede3d462d11ea23f44c997af8892 | [
"BSD-3-Clause"
] | null | null | null | Source/RenderPasses/MotionedShadow/MotionedShadow.cpp | ligenvin/RealTimeRayTracing | 4bb738cbcb89ede3d462d11ea23f44c997af8892 | [
"BSD-3-Clause"
] | null | null | null | #include "MS_Shadow.h"
#include "MS_Visibility.h"
static const char kDescShadow[] = "Shadow Map";
static const char kDescVisibility[] = "Visibility Map";
extern "C" __declspec(dllexport) const char* getProjDir()
{
return PROJECT_DIR;
}
extern "C" __declspec(dllexport) void getPasses(Falcor::RenderPassLibrary & lib)
{
lib.registerClass("MS_Shadow", kDescShadow, MS_Shadow::create);
lib.registerClass("MS_Visibility", kDescVisibility, MS_Visibility::create);
ScriptBindings::registerBinding(MS_Visibility::registerScriptBindings);
}
| 30.666667 | 80 | 0.762681 | ligenvin |
747707ad544d2548394b55cb711984acf2336f4b | 350 | hpp | C++ | src/pile.hpp | naidjeldias/EDPA-2018 | aeb3e83172419ca2e41735d84449b0ff12c8ec47 | [
"MIT"
] | null | null | null | src/pile.hpp | naidjeldias/EDPA-2018 | aeb3e83172419ca2e41735d84449b0ff12c8ec47 | [
"MIT"
] | null | null | null | src/pile.hpp | naidjeldias/EDPA-2018 | aeb3e83172419ca2e41735d84449b0ff12c8ec47 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
struct node{
int key;
struct node *next;
explicit node(int);
};
class Pile{
private:
node *top;
int size;
protected:
node* insertValeu(node *&, int);
void removeValeu(node *&);
public:
Pile();
int getSize();
void push(int);
int pop();
}; | 11.290323 | 36 | 0.582857 | naidjeldias |
747871383e2ec8185377ec80ce5e859aee85a33c | 223 | cpp | C++ | runtime/src/runtime/network/side.cpp | dumheter/wind_simulation | adf731847cb6145a85792a0ebceacc725a3acf9e | [
"MIT"
] | 1 | 2021-04-26T11:24:02.000Z | 2021-04-26T11:24:02.000Z | runtime/src/runtime/network/side.cpp | dumheter/wind_simulation | adf731847cb6145a85792a0ebceacc725a3acf9e | [
"MIT"
] | 1 | 2020-06-09T08:53:07.000Z | 2020-06-16T13:37:15.000Z | runtime/src/runtime/network/side.cpp | dumheter/wind_simulation | adf731847cb6145a85792a0ebceacc725a3acf9e | [
"MIT"
] | null | null | null | #include "side.hpp"
namespace wind {
std::string SideToString(const Side side) {
switch (side) {
case Side::kServer:
return "server";
case Side::kClient:
default:
return "client";
}
}
} // namespace wind
| 15.928571 | 43 | 0.650224 | dumheter |
7478ca2ef773d766ec27b9d1e49efa7f249eebd5 | 1,674 | cc | C++ | content/renderer/renderer_webcookiejar_impl.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-05-24T13:52:28.000Z | 2021-05-24T13:53:10.000Z | content/renderer/renderer_webcookiejar_impl.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/renderer_webcookiejar_impl.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-03-12T07:58:10.000Z | 2019-08-31T04:53:58.000Z | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/renderer_webcookiejar_impl.h"
#include "base/strings/utf_string_conversions.h"
#include "content/common/frame_messages.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_thread_impl.h"
using blink::WebString;
using blink::WebURL;
namespace content {
void RendererWebCookieJarImpl::SetCookie(const WebURL& url,
const WebURL& first_party_for_cookies,
const WebString& value) {
std::string value_utf8 =
value.Utf8(WebString::UTF8ConversionMode::kStrictReplacingErrorsWithFFFD);
RenderThreadImpl::current()->render_frame_message_filter()->SetCookie(
sender_->GetRoutingID(), url, first_party_for_cookies, value_utf8);
}
WebString RendererWebCookieJarImpl::Cookies(
const WebURL& url,
const WebURL& first_party_for_cookies) {
std::string value_utf8;
RenderThreadImpl::current()->render_frame_message_filter()->GetCookies(
sender_->GetRoutingID(), url, first_party_for_cookies, &value_utf8);
return WebString::FromUTF8(value_utf8);
}
bool RendererWebCookieJarImpl::CookiesEnabled(
const WebURL& url,
const WebURL& first_party_for_cookies) {
bool cookies_enabled = false;
sender_->Send(new FrameHostMsg_CookiesEnabled(
sender_->GetRoutingID(), url, first_party_for_cookies, &cookies_enabled));
return cookies_enabled;
}
} // namespace content
| 36.391304 | 80 | 0.743728 | metux |
74795a655046a2b065a139158ed3fbfbf5af870c | 15,110 | cpp | C++ | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/dbcon/dmlpackageproc/insertpackageprocessor.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/dbcon/dmlpackageproc/insertpackageprocessor.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/dbcon/dmlpackageproc/insertpackageprocessor.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | 2 | 2022-02-27T14:00:01.000Z | 2022-03-31T06:24:22.000Z | /* Copyright (C) 2014 InfiniDB, Inc.
Copyright (C) 2016 MariaDB Corporation
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; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
/***********************************************************************
* $Id: insertpackageprocessor.cpp 9642 2013-06-24 14:57:42Z rdempsey $
*
*
***********************************************************************/
#include <iostream>
#include "insertpackageprocessor.h"
#include "autoincrementdata.h"
#include <vector>
#include <algorithm>
#include <sstream>
#include "messagelog.h"
#include "sqllogger.h"
#include <boost/algorithm/string/case_conv.hpp>
#include "oamcache.h"
#include "bytestream.h"
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include "we_messages.h"
#include "tablelockdata.h"
using namespace boost::algorithm;
using namespace std;
using namespace WriteEngine;
using namespace dmlpackage;
using namespace execplan;
using namespace dataconvert;
using namespace logging;
using namespace oam;
using namespace messageqcpp;
namespace dmlpackageprocessor
{
DMLPackageProcessor::DMLResult InsertPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage)
{
SUMMARY_INFO("InsertPackageProcessor::processPackage");
DMLResult result;
result.result = NO_ERROR;
BRM::TxnID txnid;
// set-up the transaction
txnid.id = cpackage.get_TxnID();
txnid.valid = true;
fSessionID = cpackage.get_SessionID();
DMLTable* tablePtr = cpackage.get_Table();
LoggingID logid( DMLLoggingId, fSessionID, txnid.id);
logging::Message::Args args1;
logging::Message msg(1);
args1.add("Start SQL statement: ");
ostringstream oss;
oss << cpackage.get_SQLStatement() << "; |" << tablePtr->get_SchemaName() << "|";
args1.add(oss.str());
msg.format( args1 );
Logger logger(logid.fSubsysID);
logger.logMessage(LOG_TYPE_DEBUG, msg, logid);
//WriteEngine::ChunkManager* cm = cpackage.get_ChunkManager();
//fWriteEngine.setChunkManager(cm);
//std::map<uint32_t,uint32_t> oids;
VERBOSE_INFO("Processing Insert DML Package...");
uint64_t uniqueId = 0;
//Bug 5070. Added exception handling
try
{
uniqueId = fDbrm->getUnique64();
}
catch (std::exception& ex)
{
logging::Message::Args args;
logging::Message message(9);
args.add(ex.what());
message.format(args);
result.result = INSERT_ERROR;
result.message = message;
fSessionManager.rolledback(txnid);
return result;
}
catch ( ... )
{
logging::Message::Args args;
logging::Message message(9);
args.add("Unknown error occured while getting unique number.");
message.format(args);
result.result = INSERT_ERROR;
result.message = message;
fSessionManager.rolledback(txnid);
return result;
}
uint64_t tableLockId = 0;
int rc = 0;
std::string errorMsg;
OamCache* oamcache = OamCache::makeOamCache();
std::vector<int> moduleIds = oamcache->getModuleIds();
std::vector<uint32_t> pms;
try
{
for (unsigned int i = 0; i < moduleIds.size(); i++)
{
pms.push_back((uint32_t)moduleIds[i]);
}
//cout << "single insert get transaction id " << txnid.id << endl;
// get the table object from the package
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID);
//cout << "DMLProc using syscatptr:sessionid = " << systemCatalogPtr <<":" << fSessionID<< endl;
CalpontSystemCatalog::TableName tableName;
execplan::CalpontSystemCatalog::ROPair roPair;
TablelockData* tablelockData = TablelockData::makeTablelockData(fSessionID);
if (0 != tablePtr)
{
//check table lock
systemCatalogPtr->identity(CalpontSystemCatalog::EC);
systemCatalogPtr->sessionID(fSessionID);
tableName.schema = tablePtr->get_SchemaName();
tableName.table = tablePtr->get_TableName();
roPair = systemCatalogPtr->tableRID( tableName );
tableLockId = tablelockData->getTablelockId(roPair.objnum); //check whether this table is locked already for this session
if (tableLockId == 0)
{
//cout << "tablelock is not found in cache, getting from dbrm" << endl;
uint32_t processID = ::getpid();
int32_t txnId = txnid.id;
int32_t sessionId = fSessionID;
std::string processName("DMLProc");
int i = 0;
try
{
tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING );
}
catch (std::exception&)
{
throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE));
}
if ( tableLockId == 0 )
{
int waitPeriod = 10;
int sleepTime = 100; // sleep 100 milliseconds between checks
int numTries = 10; // try 10 times per second
waitPeriod = Config::getWaitPeriod();
numTries = waitPeriod * 10;
struct timespec rm_ts;
rm_ts.tv_sec = sleepTime / 1000;
rm_ts.tv_nsec = sleepTime % 1000 * 1000000;
for (; i < numTries; i++)
{
#ifdef _MSC_VER
Sleep(rm_ts.tv_sec * 1000);
#else
struct timespec abs_ts;
do
{
abs_ts.tv_sec = rm_ts.tv_sec;
abs_ts.tv_nsec = rm_ts.tv_nsec;
}
while (nanosleep(&abs_ts, &rm_ts) < 0);
#endif
try
{
processID = ::getpid();
txnId = txnid.id;
sessionId = fSessionID;
processName = "DMLProc";
tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING );
}
catch (std::exception&)
{
throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE));
}
if (tableLockId > 0)
break;
}
if (i >= numTries) //error out
{
result.result = INSERT_ERROR;
logging::Message::Args args;
string strOp("insert");
args.add(strOp);
args.add(processName);
args.add((uint64_t)processID);
args.add(sessionId);
throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED, args));
}
}
}
//cout << " tablelock is obtained with id " << tableLockId << endl;
tablelockData->setTablelock(roPair.objnum, tableLockId);
int pmNum = 0;
// Select PM to receive the row.
// 1. Get BRM information
// 2. Find the DBRoot with the fewest in-service blocks.
// DBRoots having no blocks are excluded
// 3. Map the selected DBRoot to the corresponding PM
CalpontSystemCatalog::RIDList ridList = systemCatalogPtr->columnRIDs(tableName, true);
std::vector<BRM::EmDbRootHWMInfo_v> allInfo (pms.size());
for (unsigned i = 0; i < pms.size(); i++)
{
rc = fDbrm->getDbRootHWMInfo((ridList[0].objnum), pms[i], allInfo[i]);
if ( rc != 0 ) //@Bug 4760.
{
result.result = INSERT_ERROR;
ostringstream oss;
oss << "Error getting extent information for table " << tableName.table;
throw std::runtime_error(oss.str());
}
}
// Find DBRoot with fewest blocks; if all DBRoots
// have 0 blocks, then we select the first DBRoot
BRM::EmDbRootHWMInfo tmp;
bool tmpSet = false;
for (unsigned i = 0; i < allInfo.size(); i++)
{
BRM::EmDbRootHWMInfo_v emDbRootHWMInfos = allInfo[i];
for (unsigned j = 0; j < emDbRootHWMInfos.size(); j++)
{
if (!tmpSet)
{
tmp = emDbRootHWMInfos[j];
tmpSet = true;
}
else if (emDbRootHWMInfos[j].totalBlocks > 0)
{
if ((emDbRootHWMInfos[j].totalBlocks < tmp.totalBlocks) ||
(tmp.totalBlocks == 0))
{
tmp = emDbRootHWMInfos[j];
}
}
}
}
// Select the PM to receive the row
uint32_t dbroot;
if (tmpSet)
{
dbroot = tmp.dbRoot;
boost::shared_ptr<std::map<int, int> > dbRootPMMap = oamcache->getDBRootToPMMap();
pmNum = (*dbRootPMMap)[dbroot];
//@Bug 4760. validate pm value
if (pmNum == 0)
{
result.result = INSERT_ERROR;
ostringstream oss;
oss << "Error mapping extent/DBRoot to PM for table " << tableName.table;
throw std::runtime_error(oss.str());
}
}
else
{
result.result = INSERT_ERROR;
ostringstream oss;
oss << "There is no extent information for table " << tableName.table;
throw std::runtime_error(oss.str());
}
//This is for single insert only. Batch insert is handled in dmlprocessor.
//cout << "fWEClient = " << fWEClient << endl;
fWEClient->addQueue(uniqueId);
ByteStream bytestream;
bytestream << (uint8_t)WE_SVR_SINGLE_INSERT;
bytestream << uniqueId;
bytestream << (uint32_t)txnid.id;
bytestream << dbroot;
cpackage.write(bytestream);
boost::shared_ptr<messageqcpp::ByteStream> bsIn;
ByteStream::byte rc1;
try
{
fWEClient->write(bytestream, (uint32_t)pmNum);
#ifdef IDB_DML_DEBUG
cout << "Single insert sending WE_SVR_SINGLE_INSERT to pm " << pmNum << endl;
#endif
bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error
{
rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES";
}
else
{
*bsIn >> rc1;
if (rc1 != 0)
{
*bsIn >> errorMsg;
rc = rc1;
}
}
}
catch (runtime_error& ex) //write error
{
#ifdef IDB_DML_DEBUG
cout << "Single insert got exception" << ex.what() << endl;
#endif
rc = NETWORK_ERROR;
errorMsg = ex.what();
}
catch (...)
{
errorMsg = "Caught ... exception during single row insert";
rc = NETWORK_ERROR;
#ifdef IDB_DML_DEBUG
cout << "Single insert got unknown exception" << endl;
#endif
}
// Log the insert statement.
LoggingID logid( DMLLoggingId, fSessionID, txnid.id);
logging::Message::Args args1;
logging::Message msg(1);
args1.add("End SQL statement");
msg.format( args1 );
Logger logger(logid.fSubsysID);
logger.logMessage(LOG_TYPE_DEBUG, msg, logid);
logging::logDML(cpackage.get_SessionID(), txnid.id, cpackage.get_SQLStatement() + ";", cpackage.get_SchemaName());
}
}
catch (exception& ex)
{
cerr << "InsertPackageProcessor::processPackage: " << ex.what() << endl;
logging::Message::Args args;
logging::Message message(1);
args.add("Insert Failed: ");
args.add(ex.what());
args.add("");
args.add("");
message.format(args);
if ( result.result != VB_OVERFLOW_ERROR )
{
result.result = INSERT_ERROR;
result.message = message;
errorMsg = ex.what();
}
}
catch (...)
{
cerr << "InsertPackageProcessor::processPackage: caught unknown exception!" << endl;
logging::Message::Args args;
logging::Message message(1);
args.add("Insert Failed: ");
args.add("encountered unkown exception");
args.add("");
args.add("");
message.format(args);
result.result = INSERT_ERROR;
result.message = message;
}
if (( rc != 0) && (rc != IDBRANGE_WARNING))
{
logging::Message::Args args;
logging::Message message(1);
args.add("Insert Failed: ");
args.add(errorMsg);
args.add("");
args.add("");
message.format(args);
result.result = INSERT_ERROR;
result.message = message;
}
else if (rc == IDBRANGE_WARNING)
{
logging::Message::Args args;
logging::Message message(1);
args.add(errorMsg);
args.add("");
args.add("");
message.format(args);
result.result = IDBRANGE_WARNING;
result.message = message;
}
fWEClient->removeQueue(uniqueId);
VERBOSE_INFO("Finished Processing Insert DML Package");
return result;
}
} // namespace dmlpackageprocessor
// vim:ts=4 sw=4:
| 34.735632 | 143 | 0.524355 | zettadb |
747b67e5a7aa13f3621ebf5ddd6d16453dcf554e | 18,706 | cpp | C++ | Hooks.cpp | maikel233/X-HOOK-For-CS-GO | 811bd67171ad48c44b9c5c05cc0fbb5fff4b3687 | [
"MIT"
] | 48 | 2018-11-10T06:39:17.000Z | 2022-03-10T18:44:52.000Z | Hooks.cpp | maikel233/X-HOOK-For-CS-GO | 811bd67171ad48c44b9c5c05cc0fbb5fff4b3687 | [
"MIT"
] | 7 | 2018-01-04T15:10:41.000Z | 2020-11-14T03:54:30.000Z | Hooks.cpp | maikel233/X-HOOK-For-CS-GO | 811bd67171ad48c44b9c5c05cc0fbb5fff4b3687 | [
"MIT"
] | 21 | 2018-11-23T23:13:09.000Z | 2022-03-14T21:11:38.000Z | #include "Hooks.h"
#include "Utils/Skins.h"
#include "GUI/Tabs/AimTabs/AimBotTab.h"
#include "SDK/SteamAPI.h"
#include "SDK/materialconfig.h"
#pragma comment(lib, "winmm.lib")
//#pragma comment(lib, "d3d9.lib")
bool Settings::Background::enable = true;
bool SetKeyCodeState::shouldListen = false;
ButtonCode_t* SetKeyCodeState::keyOutput = nullptr;
bool Settings::Misc::AntiAfk = false;
namespace Hooks
{
HRESULT WINAPI hPresent(IDirect3DDevice9* pDevice, RECT* pSourceRect, RECT* pDestRect, HWND hDestWindowOverride, RGNDATA* pDirtyRegion) {
if (GetAsyncKeyState(VK_SNAPSHOT)) {
return Present(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
}
DWORD dwOld_D3DRS_COLORWRITEENABLE;
return Present(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
}
HRESULT WINAPI hReset(LPDIRECT3DDEVICE9 pDevice, D3DPRESENT_PARAMETERS* pPresentationParameters)
{
static Reset_t oReset = D3D9Hook->GetOriginalFunction<Reset_t>(16);
if (!renderer.IsReady() || !pDevice)
return oReset(pDevice, pPresentationParameters);
ImGui_ImplDX9_InvalidateDeviceObjects();
HRESULT result = oReset(pDevice, pPresentationParameters);
ImGui_ImplDX9_CreateDeviceObjects();
return result;
}
void __stdcall hPaintTraverse(unsigned int VGUIPanel, bool forcerepaint, bool allowforce)
{
ESP::PrePaintTraverse(VGUIPanel, forcerepaint, allowforce);
PanelHook->GetOriginalFunction<PaintTraverseFn>(41)(pPanel, VGUIPanel, forcerepaint, allowforce);
static unsigned int drawPanel;
if (!drawPanel)
if (strstr(pPanel->GetName(VGUIPanel), "MatSystemTopPanel"))
drawPanel = VGUIPanel;
if (VGUIPanel != drawPanel)
return;
////Anti ss
if (Settings::ScreenshotCleaner::enabled && pEngine->IsTakingScreenshot())
return;
Dlights::Paint();
ESP::Paint();
GrenadeHelper::Paint();
GrenadePrediction::Paint();
SniperCrosshair::Paint();
Recoilcrosshair::Paint();
Hitmarkers::Paint();
Walkbot::update();
//lbyindicator::Paint();
//AngleIndicator::Paint();
//SpeedIndicator::Paint();
}
bool HookRecvProp(const char* className, const char* propertyName, std::unique_ptr<RecvPropHook>& recvPropHook) {
// FIXME: Does not search recursively.. yet.
// Recursion is a meme, stick to reddit mcswaggens.
for (ClientClass* pClass = pClient->GetAllClasses(); pClass; pClass = pClass->m_pNext) {
if (strcmp(pClass->m_pNetworkName, className) == 0) {
RecvTable* pClassTable = pClass->m_pRecvTable;
for (int nIndex = 0; nIndex < pClassTable->m_nProps; nIndex++) {
RecvProp* pProp = &pClassTable->m_pProps[nIndex];
if (!pProp || strcmp(pProp->m_pVarName, propertyName) != 0)
continue;
recvPropHook = std::make_unique<RecvPropHook>(pProp);
return true;
}
break;
}
}
return false;
}
bool ShouldDrawFogs(void* thisptr) {
if (!Settings::NoFog::enabled)
return ClientModeHook->GetOriginalFunction<ShouldDrawFogFn>(17)(thisptr);
/* Skybox Fog is separate */
IMatRenderContext* renderCtx = pMaterial->GetRenderContext();
renderCtx->FogMode(MaterialFogMode_t::MATERIAL_FOG_NONE);
renderCtx->Release();
/* Return false for normal fog */
return false; // uhhh, no Sweetie, don't draw that fog.
}
bool ShouldDrawFog(void* thisptr) {
return ShouldDrawFogs(thisptr);
}
static int __fastcall SendDatagram(NetworkChannel* network, void* edx, void* datagram)
{
if (!Settings::Aimbot::fakeLat || datagram || !pEngine->IsInGame() || !Settings::Aimbot::backtron)
{
return NetDataGram->GetOriginalFunction<SendDatagramFn>(46)(network, datagram);
}
int instate = network->InReliableState;
int insequencenr = network->InSequenceNr;
int faketimeLimit = Settings::Aimbot::timeLimit; if (faketimeLimit <= 200) { faketimeLimit = 0; }
else { faketimeLimit -= 200; }
float delta = max(0.f, std::clamp(faketimeLimit / 1000.f, 0.f, 0.2f) - network->getLatency(0));
Backtrack::AddLatencyToNetwork(network, delta + (delta / 20.0f));
NetworkChannel* OrigNet = network;
void* OrigData = datagram;
network->InReliableState = instate;
network->InSequenceNr = insequencenr;
return NetDataGram->GetOriginalFunction<SendDatagramFn>(46)(OrigNet, OrigData);
}
bool __stdcall hCreateMove(float frametime, CUserCmd* cmd) {
auto result = ClientModeHook->GetOriginalFunction<CreateMoveFn>(24)(pClientMode, frametime, cmd);
if (!cmd->command_number)
return result;
uintptr_t* framePointer;
__asm mov framePointer, ebp;
bool& sendPacket = *reinterpret_cast<bool*>(*framePointer - 0x1C);
pGlobalVars->serverTime(cmd);
BHop::CreateMove(cmd);
AutoStrafe::CreateMove(cmd);
BHop::CreateMoveCircle(cmd);
//Resolver::CreateMove(cmd);
if (Settings::Misc::AntiAfk && cmd->command_number % 2)
{ cmd->buttons |= 1 << 26; }
static void* oldPointer = nullptr;
C_BasePlayer* localplayer = (C_BasePlayer*)pEntityList->GetClientEntity(pEngine->GetLocalPlayer());
auto network = pEngine->GetNetChannelInfo();
if (oldPointer != network && network && localplayer)
{
oldPointer = network;
Backtrack::UpdateIncomingSequences(true);
NetDataGram = std::make_unique<VMTHook>(network);
NetDataGram->HookFunction(SendDatagram, 46);
}
Backtrack::UpdateIncomingSequences();
GrenadeHelper::CreateMove(cmd);
GrenadePrediction::CreateMove(cmd);
Backtrack::run(cmd);
Aimbot::CreateMove(cmd);
Triggerbot::CreateMove(cmd);
lbyindicator::CreateMove(cmd);
ReportBot::run();
ShowRanks::CreateMove(cmd);
AutoDefuse::CreateMove(cmd);
JumpThrow::CreateMove(cmd);
EdgeJump::PrePredictionCreateMove(cmd);
NoDuckCooldown::CreateMove(cmd);
PredictionSystem::StartPrediction(cmd);
Autoblock::CreateMove(cmd);
NameChanger::fakeBan();
AutoKnife::CreateMove(cmd);
AntiAim::CreateMove(cmd);
Airstuck::CreateMove(cmd);
Fakewalk::CreateMove(cmd);
MoonWalk::CreateMove(cmd);
Walkbot::CreateMove(cmd);
FakeLag::CreateMove(cmd);
ESP::CreateMove(cmd);
PredictionSystem::EndPrediction();
AngleIndicator::PostPredictionCreateMove(cmd);
EdgeJump::PostPredictionCreateMove(cmd);
return false;
}
bool __stdcall Hooked_SendLobbyChatMessage(CSteamID steamIdLobby, const void* pvMsgBody, int cubMsgBody)
{
typedef bool(__thiscall* SendLobbyChatMessage_t)(ISteamMatchmaking*, CSteamID, const void*, int);
static SendLobbyChatMessage_t Original_SendLobbyChatMessage = SteamHook->GetOriginalFunction<SendLobbyChatMessage_t>(26);
if (!LobbyMod::Get()->InterpretLobbyMessage(steamIdLobby, pvMsgBody, cubMsgBody))
return Original_SendLobbyChatMessage(pSteamMatchmaking, steamIdLobby, pvMsgBody, cubMsgBody);//Original_SendLobbyChatMessage(I.SteamMatchmaking(), steamIdLobby, pvMsgBody, cubMsgBody);
return true;
}
using GCRetrieveMessage = EGCResult(__thiscall*)(void*, uint32_t* punMsgType, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize);
using GCSendMessage = EGCResult(__thiscall*)(void*, uint32_t unMsgType, const void* pubData, uint32_t cubData);
EGCResult __fastcall hkGCRetrieveMessage(void* ecx, void*, uint32_t* punMsgType, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize)
{
static auto oGCRetrieveMessage = SteamGameCoordinator->GetOriginalFunction<GCRetrieveMessage>(2);
auto status = oGCRetrieveMessage(ecx, punMsgType, pubDest, cubDest, pcubMsgSize);
if (status == k_EGCResultOK)
{
void* thisPtr = nullptr;
__asm mov thisPtr, ebx;
auto oldEBP = *reinterpret_cast<void**>((uint32_t)_AddressOfReturnAddress() - 4);
uint32_t messageType = *punMsgType & 0x7FFFFFFF;
write.ReceiveMessage(thisPtr, oldEBP, messageType, pubDest, cubDest, pcubMsgSize);
}
return status;
}
EGCResult __fastcall hkGCSendMessage(void* ecx, void*, uint32_t unMsgType, const void* pubData, uint32_t cubData)
{
static auto oGCSendMessage = SteamGameCoordinator->GetOriginalFunction<GCSendMessage>(0);
bool sendMessage = write.PreSendMessage(unMsgType, const_cast<void*>(pubData), cubData);
if (!sendMessage)
return EGCResult::k_EGCResultOK;
return oGCSendMessage(ecx, unMsgType, const_cast<void*>(pubData), cubData);
}
void __stdcall hDrawModelExecute(IMatRenderContext* matctx, const DrawModelState_t& state, const ModelRenderInfo_t& pInfo, matrix3x4_t* pCustomBoneToWorld)
{
if (!Settings::ScreenshotCleaner::enabled || !pEngine->IsTakingScreenshot()) {
Chams::DrawModelExecute(matctx, state, pInfo, pCustomBoneToWorld);
ThirdPerson::DrawModelExecute(matctx, state, pInfo, pCustomBoneToWorld);
}
ModelRenderHook->GetOriginalFunction<DrawModelExecuteFn>(21)(pModelRender, matctx, state, pInfo, pCustomBoneToWorld);
pModelRender->ForcedMaterialOverride(nullptr);
if (!Settings::ScreenshotCleaner::enabled || !pEngine->IsTakingScreenshot()) {
ESP::DrawModelExecute(matctx, state, pInfo, pCustomBoneToWorld);
}
}
#
bool __fastcall hkOverrideConfig(IMaterialSystem* this0, int edx, MaterialSystem_Config_t* config, bool forceUpdate)
{
MaterialConfig::OverrideConfig(config, forceUpdate);
return MaterialHook->GetOriginalFunction<OverrideConfigFn>(21)(this0, config, forceUpdate); //21 is correct.
}
void __fastcall hFrameStageNotify(void* ecx, void* edx, ClientFrameStage_t stage)
{
[[maybe_unused]] static auto backtrackInit = (Backtrack::init(), true);
if (pEngine->isConnnected() && !pEngine->IsInGame())
NameChanger::changeName(true, nullptr, 0.0f);
// PVS fix
if (stage == ClientFrameStage_t::FRAME_RENDER_START)
{
C_BasePlayer* localplayer = (C_BasePlayer*)pEntityList->GetClientEntity(pEngine->GetLocalPlayer());
for (int i = 1; i < pEngine->GetMaxClients(); ++i) {
C_BasePlayer* player = (C_BasePlayer*)pEntityList->GetClientEntity(i);
if (!player
|| player == localplayer
|| player->GetDormant()
|| !player->GetAlive()
|| player->GetImmune())
continue;
IEngineClient::player_info_t playerInfo;
pEngine->GetPlayerInfo(player->GetIndex(), &playerInfo);
// These were hard as shit to find: https://i.imgur.com/gTqgDLO.png
*(int*)((uintptr_t)player + 0xA30) = pGlobalVars->framecount; // Last Occlusion check frame#
*(int*)((uintptr_t)player + 0xA28) = 0; // Occlusion flags
}
}
static bool SpoofCvars = false;
if (!SpoofCvars)
{
ConVar* sv_cheats = pCvar->FindVar("sv_cheats");
SpoofedConvar* sv_cheats_spoofed = new SpoofedConvar(sv_cheats);
sv_cheats_spoofed->SetInt(1);
ConVar* ST = pCvar->FindVar("r_DrawSpecificStaticProp");
ST->SetValue(0);
SpoofCvars = true;
}
if (stage == ClientFrameStage_t::FRAME_START)
{
FPSWindow::update();
}
Backtrack::update(stage);
CustomGlow::FrameStageNotify(stage);
SkinChanger::FrameStageNotifyModels(stage);
SkinChanger::FrameStageNotifySkins(stage);
Noflash::FrameStageNotify(stage);
View::FrameStageNotify(stage);
// Resolver::FrameStageNotify(stage);
SkyBox::FrameStageNotify(stage);
ASUSWalls::FrameStageNotify(stage);
NoSmoke::FrameStageNotify(stage);
ThirdPerson::FrameStageNotify(stage);
if (SkinChanger::forceFullUpdate)
{
pClientState->m_nDeltaTick = -1;
SkinChanger::forceFullUpdate = false;
}
ClientHook->GetOriginalFunction<FrameStageNotifyFn>(37)(ecx, stage);
// Resolver::PostFrameStageNotify(stage);
View::PostFrameStageNotify(stage);
}
IDirect3DStateBlock9* pixel_state = NULL; IDirect3DVertexDeclaration9* vertDec; IDirect3DVertexShader9* vertShader;
DWORD dwOld_D3DRS_COLORWRITEENABLE;
void SaveState(IDirect3DDevice9* pDevice)
{
pDevice->GetRenderState(D3DRS_COLORWRITEENABLE, &dwOld_D3DRS_COLORWRITEENABLE);
// pDevice->CreateStateBlock(D3DSBT_PIXELSTATE, &pixel_state); // This seam not to be needed anymore because valve fixed their shit
pDevice->GetVertexDeclaration(&vertDec);
pDevice->GetVertexShader(&vertShader);
pDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0xffffffff);
pDevice->SetRenderState(D3DRS_SRGBWRITEENABLE, false);
pDevice->SetSamplerState(NULL, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
pDevice->SetSamplerState(NULL, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
pDevice->SetSamplerState(NULL, D3DSAMP_ADDRESSW, D3DTADDRESS_WRAP);
pDevice->SetSamplerState(NULL, D3DSAMP_SRGBTEXTURE, NULL);
}
void RestoreState(IDirect3DDevice9* pDevice) // not restoring everything. Because its not needed.
{
pDevice->SetRenderState(D3DRS_COLORWRITEENABLE, dwOld_D3DRS_COLORWRITEENABLE);
pDevice->SetRenderState(D3DRS_SRGBWRITEENABLE, true);
//pixel_state->Apply();
//pixel_state->Release();
pDevice->SetVertexDeclaration(vertDec);
pDevice->SetVertexShader(vertShader);
}
HRESULT WINAPI hkEndScene(IDirect3DDevice9* device)
{
static EndScene_t oEndScene = D3D9Hook->GetOriginalFunction<EndScene_t>(42);
SaveState(device);
Menu();
RestoreState(device);
device->SetRenderState(D3DRS_COLORWRITEENABLE, dwOld_D3DRS_COLORWRITEENABLE);
return oEndScene(device);
}
bool __fastcall hFireEventClientSide(void* ecx, void* edx, IGameEvent* pEvent)
{
Aimbot::FireGameEvent(pEvent);
Hitmarkers::FireGameEvent(pEvent);
NameStealer::FireGameEvent(pEvent);
// Resolver::FireGameEvent(pEvent);
Spammer::FireGameEvent(pEvent);
EventLogger::FireGameEvent(pEvent);
ValveDSCheck::FireGameEvent(pEvent);
if (pEvent)
{
SkinChanger::FireEventClientSide(pEvent);
SkinChanger::FireGameEvent(pEvent);
}
return FireEventHook->GetOriginalFunction<FireEventClientSideFn>(9)(ecx, pEvent);
}
void __stdcall hBeginFrame(float frameTime)
{
ClanTagChanger::BeginFrame(frameTime);
NameChanger::BeginFrame(frameTime);
NameStealer::BeginFrame(frameTime);
Spammer::BeginFrame(frameTime);
Radar::BeginFrame();
Skins::Localize();
DisablePostProcessing::BeginFrame();
return MaterialHook->GetOriginalFunction<BeginFrameFn>(42)(pMaterial, frameTime);
}
void __fastcall Hooks::EmitSound1(void* thisptr, void* edx, IRecipientFilter& filter, int iEntIndex, int iChannel, const char* pSoundEntry,
unsigned int nSoundEntryHash, const char* pSample, float flVolume, int nSeed,
float flAttenuation, int iFlags, int iPitch, const Vector* pOrigin, const Vector* pDirection,
void* pUtlVecOrigins, bool bUpdatePositions, float soundtime, int speakerentity, int Unknownn) {
ESP::EmitSound(iEntIndex, pSample);
SoundHook->GetOriginalFunction<EmitSound1Fn>(5)(thisptr, filter, iEntIndex, iChannel, pSoundEntry, nSoundEntryHash,
pSample, flVolume, nSeed, flAttenuation, iFlags, iPitch, pOrigin,
pDirection, pUtlVecOrigins, bUpdatePositions, soundtime,
speakerentity, Unknownn);
}
void __fastcall Hooks::EmitSound2(void* thisptr, void* edx, void* Filter, int iEntIndex, int iChannel, const char* pSoundEntry,
unsigned int nSoundEntryHash, const char* pSample, float flVolume, int nSeed,
int iSoundLevel, int iFlags, int iPitch, const Vector* pOrigin,
const Vector* pDirection, void* pUtlVecOrigins, bool bUpdatePositions, float soundtime,
int speakerentity, void* SoundParam ) {
ESP::EmitSound(iEntIndex, pSample);
SoundHook->GetOriginalFunction<EmitSound2Fn>(5)(thisptr, Filter, iEntIndex, iChannel, pSoundEntry, nSoundEntryHash,
pSample, flVolume, nSeed, iSoundLevel, iFlags, iPitch, pOrigin,
pDirection, pUtlVecOrigins, bUpdatePositions, soundtime,
speakerentity, SoundParam);
}
void __fastcall Hooks::hkEmitSound(IEngineSound* thisptr, int edx, IRecipientFilter& filter, int iEntIndex, int iChannel, const char *pSoundEntry, unsigned int nSoundEntryHash, const char *pSample,
float flVolume, float flAttenuation, int nSeed, int iFlags, int iPitch,
const Vector *pOrigin, const Vector *pDirection, CUtlVector< Vector >* pUtlVecOrigins, bool bUpdatePositions, float soundtime, int speakerentity, int Unknownn)
{
ESP::EmitSound(iEntIndex, pSample);
auto oEmitSound = SoundHook->GetOriginalFunction<EmitSound1Fn>(5);
oEmitSound(thisptr, filter, iEntIndex, iChannel, pSoundEntry, nSoundEntryHash, pSample, flVolume, flAttenuation, nSeed, iFlags, iPitch, pOrigin, pDirection, pUtlVecOrigins, bUpdatePositions, soundtime, speakerentity, Unknownn);
}
void OnScreenSizeChanged(void* thisptr, int oldwidth, int oldheight) {
SurfaceHook->GetOriginalFunction<OnScreenSizeChangedFn>(116)(thisptr, oldwidth, oldheight);
//Fonts::SetupFonts();
}
void __stdcall hPlaySounds(const char* fileName)
{
SurfaceHook->GetOriginalFunction<PlaySoundFn>(82)(pSurface, fileName);
AutoAccept::PlaySound(fileName);
}
void __stdcall hLockCursor()
{
bool Lock = G::is_renderer_active;
if (Lock) {
pSurface->unlockcursor();
return;
}
SurfaceHook->GetOriginalFunction<LockCursor>(67)(pSurface);
}
void __fastcall Hooks::RenderSmokePostViewmodel(void* ecx, void* edx) {
if (!NoSmoke::RenderSmokePostViewmodel())
RenderViewHook->GetOriginalFunction<NoSmokeFn>(41)(ecx);
}
void __fastcall hRenderView(void* ecx, void* edx, CViewSetup &setup, CViewSetup &hudViewSetup, int nClearFlags, int whatToDraw)
{
RenderViewHook->GetOriginalFunction<RenderViewFn>(6)(ecx, setup, hudViewSetup, nClearFlags, whatToDraw);
SpeedIndicator::RenderView(ecx, setup, hudViewSetup, nClearFlags, whatToDraw);
}
void __fastcall hOverrideView(void* _this, void* _edx, ViewSetup* setup)
{
if (!Settings::ScreenshotCleaner::enabled || !pEngine->IsTakingScreenshot()) {
GrenadePrediction::OverrideView(setup);
FOVChanger::OverrideView(setup);
ThirdPerson::OverrideView(setup);
}
OverrideView::currentFOV = setup->fov;
ClientModeHook->GetOriginalFunction<OverreideViewFn>(18)(_this, setup);
}
float __stdcall hGetViewModelFOV()
{
float fov = ClientModeHook->GetOriginalFunction<GetViewModelFOVFn>(35)();
FOVChanger::GetViewModelFOV(fov);
return fov;
}
void __fastcall Hooks::SetKeyCodeState(void* thisptr, void* edx, ButtonCode_t code, bool bPressed) {
if (SetKeyCodeState::shouldListen && bPressed) {
SetKeyCodeState::shouldListen = false;
*SetKeyCodeState::keyOutput = code;
UI::UpdateWeaponSettings();
G::input_shouldListen = true;
}
if (!SetKeyCodeState::shouldListen)
Shortcuts::SetKeyCodeState(code, bPressed);
InputInternalHook->GetOriginalFunction<SetKeyCodeStateFn>(91)(thisptr, code, bPressed);
}
void __fastcall Hooks::SetMouseCodeState(void* thisptr, void* edx, ButtonCode_t code, MouseCodeState_t state) {
if (SetKeyCodeState::shouldListen && state == MouseCodeState_t::BUTTON_PRESSED) {
SetKeyCodeState::shouldListen = false;
*SetKeyCodeState::keyOutput = code;
UI::UpdateWeaponSettings();
}
InputInternalHook->GetOriginalFunction<SetMouseCodeStateFn>(92)(thisptr, code, state);
}
}
| 33.523297 | 229 | 0.74559 | maikel233 |
747bc4700ee4c91979da8b6d29fc7fd084701f72 | 10,790 | cpp | C++ | bigo.cpp | andrelrg/cppexercises | 3a12b6a7ac51d75ea973fe77237a81b7a0c08261 | [
"MIT"
] | 1 | 2020-04-26T02:34:25.000Z | 2020-04-26T02:34:25.000Z | bigo.cpp | andrelrg/cppexercises | 3a12b6a7ac51d75ea973fe77237a81b7a0c08261 | [
"MIT"
] | null | null | null | bigo.cpp | andrelrg/cppexercises | 3a12b6a7ac51d75ea973fe77237a81b7a0c08261 | [
"MIT"
] | null | null | null | #include "bigo.h"
int const smallArraySize = 10;
int const bigArraySize = 50;
const int unsortedSmallArray[smallArraySize] = {2,4,1,3,7,6,8,9,10,5};
const int sortedSmallArray[smallArraySize] = {1,2,3,4,5,6,20,8,9,10};
const int unsortedBigArray[bigArraySize] = {50,44,24,1,37,15,7,9,27,42,33,46,6,13,32,48,29,31,8,22,25,38,19,14,12,17,11,43,23,35,39,45,40,16,5,49,26,21,2,34,4,3,47,30,36,20,18,28,10,41};
const int sortedBigArray[bigArraySize] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
void constant(){
printf("O(1) Constant Time\n\n");
printf("O(1) It's algorithms that takes the same amount of time regardless of the size of the input.\n");
printf(" Some examples are:\n");
printf(" - Look for a especific index inside an array\n");
printf(" - Print an especific element of an array.\n\n");
printf("This function will be executed using the first time an array of size %d and then one of size %d, in both looking for the 7 index. It's expected that the time will be equivalent\n", smallArraySize, bigArraySize);
std::cout << ""
" int lookIndex(int arr[], int index){ \n"
" return arr[index]; \n"
" }\n"<<std::endl;
std::chrono::steady_clock::time_point ts1 = std::chrono::steady_clock::now();
lookIndex(unsortedSmallArray, 7);
std::chrono::steady_clock::time_point te1 = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point ts2 = std::chrono::steady_clock::now();
lookIndex(unsortedBigArray, 7);
std::chrono::steady_clock::time_point te2 = std::chrono::steady_clock::now();
std::cout << "First time: " << std::chrono::duration_cast<std::chrono::microseconds>(te1 - ts1).count() << "[µs]"
" Second time: " << std::chrono::duration_cast<std::chrono::microseconds>(te2 - ts2).count() << "[µs]" << std::endl;
}
void linear(){
printf("O(n) Linear time\n\n");
printf("O(n) It's algorithms that takes more time, the bigger input. \n");
printf(" Some examples are:\n");
printf(" - Get the max value in an array.\n");
printf(" - Print all the values in an array.\n");
printf("This function will be executed using the first time an array of size %d and then one of size %d.\n", smallArraySize, bigArraySize);
std::cout << ""
" int maxUnsorted(int arr[]){\n"
" int max = -99;\n"
" for(int i = 0; i<sizeof(arr); i++){\n"
" if (arr[i] > max){\n"
" max = arr[i];\n"
" }\n"
" }\n"
" return max;\n"
" }\n"
""<<std::endl;
std::chrono::steady_clock::time_point ts1 = std::chrono::steady_clock::now();
maxUnsorted(unsortedSmallArray, smallArraySize);
std::chrono::steady_clock::time_point te1 = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point ts2 = std::chrono::steady_clock::now();
maxUnsorted(unsortedBigArray, bigArraySize);
std::chrono::steady_clock::time_point te2 = std::chrono::steady_clock::now();
std::cout << "First time: " << std::chrono::duration_cast<std::chrono::microseconds>(te1 - ts1).count() << "[µs]"
" Second time: " << std::chrono::duration_cast<std::chrono::microseconds>(te2 - ts2).count() << "[µs]" << std::endl;
}
void quadratic(){
printf("O(n^2) Quadratic time\n\n");
printf("O(n^2) It's algorithms that will grow in n^2 rate, basically if the input has a 2 size it will do 4 opperations, and if it has a 8 size it will do 64 opperations. \n");
printf(" Some examples are:\n");
printf(" - Check for duplicated values in an array.\n");
printf(" - Sort elements (bubble sort, etc).\n");
printf("This function will be executed using the first time an array of size %d and then one of size %d.\n", smallArraySize, bigArraySize);
std::cout << ""
" bool hasDuplicates(int arr[], int size){\n"
" int n = 0;\n"
" for (int a=0; a < size; a++){\n"
" for (int b=0; b < size; b++){\n"
" if (a == b) continue;\n"
" if (arr[a] == arr[b]) n++;\n"
" }\n"
" }\n"
" return n > 0;\n"
" }\n\n"
""<<std::endl;
std::chrono::steady_clock::time_point ts1 = std::chrono::steady_clock::now();
hasDuplicates(unsortedSmallArray, smallArraySize);
std::chrono::steady_clock::time_point te1 = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point ts2 = std::chrono::steady_clock::now();
hasDuplicates(unsortedBigArray, bigArraySize);
std::chrono::steady_clock::time_point te2 = std::chrono::steady_clock::now();
std::cout << "First time: " << std::chrono::duration_cast<std::chrono::microseconds>(te1 - ts1).count() << "[µs]"
" Second time: " << std::chrono::duration_cast<std::chrono::microseconds>(te2 - ts2).count() << "[µs]" << std::endl;
}
void logarithimic(){
printf("O(log n) Logarithmic time\n\n");
printf("O(log n) It's algorithms that in every iteration divide the problem in half\n");
printf(" Some examples are:\n");
printf(" - Binary search\n");
printf("This function will find the index that has value 7 be executed using the first time an array of size %d and then one of size %d, both of them already sorted.\n\n", smallArraySize, bigArraySize);
std::cout << ""
" int binarySearch(const int arr[], const int size, int searchNumber){ \n"
" int half = size/2;\n"
"\n"
" if (arr[half] == searchNumber){\n"
" return half;\n"
" } \n"
" else if (arr[half] > searchNumber){\n"
" int narr[half];\n"
" for (int a = 0; a<half; a++){\n"
" narr[a] = arr[a];\n"
" }\n"
" return binarySearch(narr, half, searchNumber);\n"
" } \n"
" else{\n"
" int narr[half];\n"
" for (int a = half; a<size; a++){\n"
" narr[a] = arr[a];\n"
" }\n"
" return binarySearch(narr, half, searchNumber);\n"
" } \n"
" }\n"
""<<std::endl;
std::chrono::steady_clock::time_point ts1 = std::chrono::steady_clock::now();
binarySearch(sortedSmallArray, smallArraySize, 7);
std::chrono::steady_clock::time_point te1 = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point ts2 = std::chrono::steady_clock::now();
binarySearch(sortedBigArray, bigArraySize, 7);
std::chrono::steady_clock::time_point te2 = std::chrono::steady_clock::now();
std::cout << "First time: " << std::chrono::duration_cast<std::chrono::microseconds>(te1 - ts1).count() << "[µs]"
" Second time: " << std::chrono::duration_cast<std::chrono::microseconds>(te2 - ts2).count() << "[µs]" << std::endl;
}
void linearithmic(){
printf("O(n log n) Logarithmic time\n\n");
printf("O(log n) It's algorithms that in every iteration divide the problem in half\n");
printf(" Some examples are:\n");
printf(" - Binary search\n");
printf("This function will sort an array of size %d and then an array of size %d", smallArraySize, bigArraySize);
}
void polynomic(){
}
void exponential(){
printf("O(2^n) Exponential time\n\n");
printf("O(2^n) It's algorithms that double it's running time for each new element.\n");
printf(" Some examples are:\n");
printf(" - Fibonacci\n");
printf(" - Power Set\n");
printf("This function will produce fibonacci numbers, first %d numbers, and then %d numbers.\n", smallArraySize, bigArraySize-20);
std::cout << ""
" int fibonacci(int n){\n"
" if (n <= 1){\n"
" return n;\n"
" }\n"
" return fibonacci(n-1) + fibonacci(n-2);\n"
" }\n"
""<<std::endl;
std::chrono::steady_clock::time_point ts1 = std::chrono::steady_clock::now();
fibonacci(smallArraySize);
std::chrono::steady_clock::time_point te1 = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point ts2 = std::chrono::steady_clock::now();
fibonacci(bigArraySize-20);
std::chrono::steady_clock::time_point te2 = std::chrono::steady_clock::now();
std::cout << "First time: " << std::chrono::duration_cast<std::chrono::microseconds>(te1 - ts1).count() << "[µs]"
" Second time: " << std::chrono::duration_cast<std::chrono::microseconds>(te2 - ts2).count() << "[µs]" << std::endl;
}
void factorial(){
printf("O(n!) Factorial time\n\n");
printf("O(2^n) It's algorithms that do factorial expressions. So it grows factorially.\n");
printf(" Some examples are:\n");
printf(" - Permutations\n");
printf("This function will do permutations on a char array of %d positions and one of %d.\n", smallArraySize-5, bigArraySize-40);
std::cout << ""
" void permutation(std::string a, int start, int end){\n"
" if (start == end) std::cout<<a<<std::endl; \n"
" else{ \n"
" for (int i = start; i <= end; i++) \n"
" { \n"
" std::swap(a[start], a[i]); \n"
" permutation(a, start+1, end); \n"
" std::swap(a[start], a[i]); \n"
" } \n"
" } \n"
" }\n"
""<<std::endl;
std::chrono::steady_clock::time_point ts1 = std::chrono::steady_clock::now();
permutation("abcde", 0, 4);
std::chrono::steady_clock::time_point te1 = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point ts2 = std::chrono::steady_clock::now();
permutation("abcdefghij", 0, 9);
std::chrono::steady_clock::time_point te2 = std::chrono::steady_clock::now();
std::cout << "First time: " << std::chrono::duration_cast<std::chrono::microseconds>(te1 - ts1).count() << "[µs]"
" Second time: " << std::chrono::duration_cast<std::chrono::microseconds>(te2 - ts2).count() << "[µs]" << std::endl;
}
void enterbigo(int py){
system("clear");
gotoxy(0,0);
switch(py){
case BIGO_1:
constant();
break;
case BIGO_2:
logarithimic();
break;
case BIGO_3:
linear();
break;
case BIGO_4:
linearithmic();
break;
case BIGO_5:
quadratic();
break;
case BIGO_6:
polynomic();
break;
case BIGO_7:
exponential();
break;
case BIGO_8:
factorial();
break;
}
}
void bigoMenu(){
gotoxy(3,3);
printf("O(1)");
gotoxy(3,4);
printf("O(log n)");
gotoxy(3,5);
printf("O(n)");
gotoxy(3,6);
printf("O(n log n) (Missing)");
gotoxy(3,7);
printf("O(n^2)");
gotoxy(3,8);
printf("O(n^c) (Missing)");
gotoxy(3,9);
printf("O(2^n)");
gotoxy(3,10);
printf("O(n!)");
} | 39.669118 | 223 | 0.591103 | andrelrg |
747d2c9b57ad67d083031df7ec455524c50e9315 | 282 | cpp | C++ | Node.cpp | goodandevilsoftware/kasai | e2d6b9e84aa2e292ddcc1bc8688c284b9622ba32 | [
"Unlicense"
] | null | null | null | Node.cpp | goodandevilsoftware/kasai | e2d6b9e84aa2e292ddcc1bc8688c284b9622ba32 | [
"Unlicense"
] | null | null | null | Node.cpp | goodandevilsoftware/kasai | e2d6b9e84aa2e292ddcc1bc8688c284b9622ba32 | [
"Unlicense"
] | null | null | null | //
// Created by Nathaniel Blair on 24/10/20.
//
#include "Node.h"
void Node::Connect(Node *otherNode) {
friends.push_back(otherNode);
}
void Node::Receive(string message) {
// TODO: implement Receive
}
void Node::Relay(string message) {
// TODO: implement relay
}
| 14.842105 | 42 | 0.666667 | goodandevilsoftware |
747dc2176fe92551812f62ac58a72c8dce42caf2 | 869 | hpp | C++ | uplift/src/objects/shared_memory.hpp | Inori/uplift | d718b83c66fda6fe018dac85c1fe7cdf79b559d5 | [
"MIT"
] | 1 | 2021-07-07T10:34:50.000Z | 2021-07-07T10:34:50.000Z | uplift/src/objects/shared_memory.hpp | Inori/uplift | d718b83c66fda6fe018dac85c1fe7cdf79b559d5 | [
"MIT"
] | null | null | null | uplift/src/objects/shared_memory.hpp | Inori/uplift | d718b83c66fda6fe018dac85c1fe7cdf79b559d5 | [
"MIT"
] | null | null | null | #pragma once
#include "object.hpp"
namespace uplift::objects
{
class SharedMemory : public Object
{
public:
static const Object::Type ObjectType = Type::SharedMemory;
public:
SharedMemory(Runtime* runtime);
virtual ~SharedMemory();
SyscallError Initialize(const std::string& path, uint32_t flags, uint16_t mode);
SyscallError Close();
SyscallError Read(void* data_buffer, size_t data_size, size_t* read_size);
SyscallError Write(const void* data_buffer, size_t data_size, size_t* written_size);
SyscallError Truncate(int64_t length);
SyscallError IOControl(uint32_t request, void* argp);
SyscallError MMap(void* addr, size_t len, int prot, int flags, size_t offset, void*& allocation);
private:
void* native_handle_;
int64_t length_;
std::string path_;
uint32_t flags_;
uint16_t mode_;
};
}
| 26.333333 | 101 | 0.719217 | Inori |
74843cb88c323b2aabcf9c874ae876b2628b4294 | 4,877 | cc | C++ | ns-allinone-3.27/ns-3.27/src/internet/test/tcp-datasentcb-test.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 93 | 2019-04-21T08:22:26.000Z | 2022-03-30T04:26:29.000Z | ns-allinone-3.27/ns-3.27/src/internet/test/tcp-datasentcb-test.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 12 | 2019-04-19T16:39:58.000Z | 2021-06-22T13:18:32.000Z | ns-allinone-3.27/ns-3.27/src/internet/test/tcp-datasentcb-test.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 21 | 2019-05-27T19:36:12.000Z | 2021-07-26T02:37:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2015 Natale Patriciello <natale.patriciello@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "tcp-general-test.h"
#include "ns3/node.h"
#include "ns3/log.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("TcpDatSentCbTest");
/**
* \ingroup internet-test
* \ingroup tests
*
* \brief Socket that the 50% of the times saves the entire packet in the buffer,
* while in the other 50% saves only half the packet.
*/
class TcpSocketHalfAck : public TcpSocketMsgBase
{
public:
/**
* \brief Get the type ID.
* \return the object TypeId
*/
static TypeId GetTypeId (void);
TcpSocketHalfAck () : TcpSocketMsgBase ()
{
}
protected:
virtual Ptr<TcpSocketBase> Fork ();
virtual void ReceivedData (Ptr<Packet> packet, const TcpHeader& tcpHeader);
};
NS_OBJECT_ENSURE_REGISTERED (TcpSocketHalfAck);
TypeId
TcpSocketHalfAck::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::TcpSocketHalfAck")
.SetParent<TcpSocketMsgBase> ()
.SetGroupName ("Internet")
.AddConstructor<TcpSocketHalfAck> ()
;
return tid;
}
Ptr<TcpSocketBase>
TcpSocketHalfAck::Fork (void)
{
return CopyObject<TcpSocketHalfAck> (this);
}
void
TcpSocketHalfAck::ReceivedData (Ptr<Packet> packet, const TcpHeader &tcpHeader)
{
NS_LOG_FUNCTION (this << packet << tcpHeader);
static uint32_t times = 1;
Ptr<Packet> halved = packet->Copy ();
if (times % 2 == 0)
halved->RemoveAtEnd (packet->GetSize () / 2);
times++;
TcpSocketMsgBase::ReceivedData (halved, tcpHeader);
}
/**
* \ingroup internet-test
* \ingroup tests
*
* \brief Data Sent callback test
*
* The rationale of this test is to check if the dataSent callback advertises
* to the application all the transmitted bytes. We know in advance how many
* bytes are being transmitted, and we check if the amount of data notified
* equals this value.
*
*/
class TcpDataSentCbTestCase : public TcpGeneralTest
{
public:
/**
* Constructor.
* \param desc Test desctiption.
* \param size Packet size.
* \param packets Number of packets.
*/
TcpDataSentCbTestCase (const std::string &desc, uint32_t size, uint32_t packets) :
TcpGeneralTest (desc),
m_pktSize (size),
m_pktCount (packets),
m_notifiedData (0)
{ }
protected:
virtual Ptr<TcpSocketMsgBase> CreateReceiverSocket (Ptr<Node> node);
virtual void DataSent (uint32_t size, SocketWho who);
virtual void ConfigureEnvironment ();
virtual void FinalChecks ();
private:
uint32_t m_pktSize; //!< Packet size.
uint32_t m_pktCount; //!< Number of packets sent.
uint32_t m_notifiedData; //!< Amount of data notified.
};
void
TcpDataSentCbTestCase::ConfigureEnvironment ()
{
TcpGeneralTest::ConfigureEnvironment ();
SetAppPktCount (m_pktCount);
SetAppPktSize (m_pktSize);
}
void
TcpDataSentCbTestCase::DataSent (uint32_t size, SocketWho who)
{
NS_LOG_FUNCTION (this << who << size);
m_notifiedData += size;
}
void
TcpDataSentCbTestCase::FinalChecks ()
{
NS_TEST_ASSERT_MSG_EQ (m_notifiedData, GetPktSize () * GetPktCount (),
"Notified more data than application sent");
}
Ptr<TcpSocketMsgBase>
TcpDataSentCbTestCase::CreateReceiverSocket (Ptr<Node> node)
{
NS_LOG_FUNCTION (this);
return CreateSocket (node, TcpSocketHalfAck::GetTypeId (), m_congControlTypeId);
}
/**
* \ingroup internet-test
* \ingroup tests
*
* \brief TestSuite: Data Sent callback
*/
class TcpDataSentCbTestSuite : public TestSuite
{
public:
TcpDataSentCbTestSuite ()
: TestSuite ("tcp-datasentcb", UNIT)
{
AddTestCase (new TcpDataSentCbTestCase ("Check the data sent callback", 500, 10), TestCase::QUICK);
AddTestCase (new TcpDataSentCbTestCase ("Check the data sent callback", 100, 100), TestCase::QUICK);
AddTestCase (new TcpDataSentCbTestCase ("Check the data sent callback", 1000, 50), TestCase::QUICK);
AddTestCase (new TcpDataSentCbTestCase ("Check the data sent callback", 855, 18), TestCase::QUICK);
AddTestCase (new TcpDataSentCbTestCase ("Check the data sent callback", 1243, 59), TestCase::QUICK);
}
};
static TcpDataSentCbTestSuite g_tcpDataSentCbTestSuite; //!< Static variable for test initialization
| 26.505435 | 104 | 0.718885 | zack-braun |
748bf0f516f8e7819c352625c000de0bfa3e3dd8 | 59 | cpp | C++ | Engine/source/IO/Serializers.cpp | mbatc/Fractal | 0df1f6a64d03676e3dd8af0686413f6ffdbf6627 | [
"MIT"
] | null | null | null | Engine/source/IO/Serializers.cpp | mbatc/Fractal | 0df1f6a64d03676e3dd8af0686413f6ffdbf6627 | [
"MIT"
] | 34 | 2021-05-09T10:31:24.000Z | 2022-01-24T11:26:48.000Z | Engine/source/IO/Serializers.cpp | mbatc/Fractal | 0df1f6a64d03676e3dd8af0686413f6ffdbf6627 | [
"MIT"
] | null | null | null | #include "Fractal/IO/Serializers.h"
namespace Fractal
{
}
| 9.833333 | 35 | 0.745763 | mbatc |
748d1def6c804820e55ee5343f303284e6bdbbbf | 2,159 | cpp | C++ | Graphics3dSolution/Graphics3dLib/Rendering/RenderPaths/GraphicsBufferPath.cpp | TheFloHub/Graphics3dLib | 4e4b310b49b0bae35d45136ccc43a006b39ba2b5 | [
"MIT"
] | null | null | null | Graphics3dSolution/Graphics3dLib/Rendering/RenderPaths/GraphicsBufferPath.cpp | TheFloHub/Graphics3dLib | 4e4b310b49b0bae35d45136ccc43a006b39ba2b5 | [
"MIT"
] | null | null | null | Graphics3dSolution/Graphics3dLib/Rendering/RenderPaths/GraphicsBufferPath.cpp | TheFloHub/Graphics3dLib | 4e4b310b49b0bae35d45136ccc43a006b39ba2b5 | [
"MIT"
] | null | null | null | #include "GraphicsBufferPath.h"
#include <Graphics3dLib/Assets/Shader.h>
#include <Graphics3dLib/Rendering/FrameBufferObject.h>
#include <Graphics3dLib/Components/Camera.h>
#include <Graphics3dLib/Components/Transform.h>
#include <Graphics3dLib/Scene/SceneObject.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/type_ptr.hpp>
G3d::GraphicsBufferPath::GraphicsBufferPath(unsigned int width, unsigned int height) :
RenderPath(
nullptr,
new FrameBufferObject(
width,
height,
GL_DEPTH_COMPONENT24, // depth buffer
GL_RGBA16, // normals, A = roughness
GL_RGBA8)) // albedo, A = metallic
{
}
G3d::GraphicsBufferPath::~GraphicsBufferPath()
{
}
void G3d::GraphicsBufferPath::render(Camera const* pCamera, std::vector<SceneObject const*> sceneObjects)
{
mpFrameBuffer->use();
glViewport(0, 0, mpFrameBuffer->getWidth(), mpFrameBuffer->getHeight());
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::mat4 modelViewMatrix;
glm::mat4 modelViewProjectionMatrix;
glm::mat3 normalMatrix;
for (std::vector<SceneObject const*>::const_iterator objectIter = sceneObjects.cbegin();
objectIter != sceneObjects.cend(); ++objectIter)
{
// TODO: add Camera::current or Camera::main and do this in the materials!?
modelViewMatrix = m180Rotation * pCamera->getSceneObject()->getTransform()->getWorldToLocalMatrix() * (*objectIter)->getTransform()->getLocalToWorldMatrix();
modelViewProjectionMatrix = pCamera->getProjectionMatrix() * modelViewMatrix;
normalMatrix = glm::inverseTranspose(glm::mat3(modelViewMatrix));
Shader::setGlobalMat4("modelViewMatrix", modelViewMatrix);
Shader::setGlobalMat4("modelViewProjectionMatrix", modelViewProjectionMatrix);
Shader::setGlobalMat3("normalMatrix", normalMatrix);
(*objectIter)->render();
}
}
G3d::TexturePtr G3d::GraphicsBufferPath::getDepthBuffer()
{
return mpFrameBuffer->getDepthComponent();
}
G3d::TexturePtr G3d::GraphicsBufferPath::getNormalBuffer()
{
return mpFrameBuffer->getTexture(0);
}
G3d::TexturePtr G3d::GraphicsBufferPath::getAlbedoBuffer()
{
return mpFrameBuffer->getTexture(1);
}
| 31.75 | 160 | 0.764706 | TheFloHub |
748e34b7e0eceb0b1a932b35182c3c6c4ba33e93 | 7,608 | cpp | C++ | Server Lib/Game Server/GAME/bot_gm_event.cpp | eantoniobr/SuperSS-Dev | f57c094f164cc90c2694df33ba394304cd0e7846 | [
"MIT"
] | null | null | null | Server Lib/Game Server/GAME/bot_gm_event.cpp | eantoniobr/SuperSS-Dev | f57c094f164cc90c2694df33ba394304cd0e7846 | [
"MIT"
] | null | null | null | Server Lib/Game Server/GAME/bot_gm_event.cpp | eantoniobr/SuperSS-Dev | f57c094f164cc90c2694df33ba394304cd0e7846 | [
"MIT"
] | 1 | 2021-11-03T00:21:07.000Z | 2021-11-03T00:21:07.000Z | // Arquivo bot_gm_event.cpp
// Criado em 03/11/2020 as 20:06 por Acrisio
// Implementa��o da classe BotGMEvent
#if defined(_WIN32)
#pragma pack(1)
#endif
#if defined(_WIN32)
#include <WinSock2.h>
#endif
#include "bot_gm_event.hpp"
#include "../../Projeto IOCP/DATABASE/normal_manager_db.hpp"
#include "../PANGYA_DB/cmd_bot_gm_event_info.hpp"
#include "../../Projeto IOCP/UTIL/util_time.h"
#include "../UTIL/lottery.hpp"
#include "../../Projeto IOCP/UTIL/random_gen.hpp"
#include <algorithm>
#if defined(_WIN32)
#define TRY_CHECK try { \
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
#define TRY_CHECK try { \
pthread_mutex_lock(&m_cs);
#endif
#if defined(_WIN32)
#define LEAVE_CHECK LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
#define LEAVE_CHECK pthread_mutex_unlock(&m_cs);
#endif
#if defined(_WIN32)
#define CATCH_CHECK(_method) }catch (exception& e) { \
LeaveCriticalSection(&m_cs); \
\
_smp::message_pool::getInstance().push(new message("[BotGMEvent::" + std::string(_method) + "][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
#elif defined(__linux__)
#define CATCH_CHECK(_method) }catch (exception& e) { \
pthread_mutex_unlock(&m_cs); \
\
_smp::message_pool::getInstance().push(new message("[BotGMEvent::" + std::string(_method) + "][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
#endif
#define END_CHECK } \
constexpr uint32_t MAX_REWARD_PER_ROUND = 3u;
using namespace stdA;
BotGMEvent::BotGMEvent() : m_rt(), m_rewards(), m_load(false), m_st{ 0u } {
#if defined(_WIN32)
InitializeCriticalSection(&m_cs);
#elif defined(__linux__)
INIT_PTHREAD_MUTEXATTR_RECURSIVE;
INIT_PTHREAD_MUTEX_RECURSIVE(&m_cs);
DESTROY_PTHREAD_MUTEXATTR_RECURSIVE;
#endif
// Inicializa
initialize();
}
BotGMEvent::~BotGMEvent() {
clear();
#if defined(_WIN32)
DeleteCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_destroy(&m_cs);
#endif
}
void BotGMEvent::clear() {
TRY_CHECK;
if (!m_rt.empty()) {
m_rt.clear();
m_rt.shrink_to_fit();
}
if (!m_rewards.empty()) {
m_rewards.clear();
m_rewards.shrink_to_fit();
}
m_load = false;
LEAVE_CHECK;
CATCH_CHECK("clear");
m_load = false;
END_CHECK;
}
void BotGMEvent::load() {
if (isLoad())
clear();
initialize();
}
bool BotGMEvent::isLoad() {
bool isload = false;
TRY_CHECK;
isload = (m_load);
LEAVE_CHECK;
CATCH_CHECK("isLoad");
isload = false;
END_CHECK;
return isload;
}
void BotGMEvent::initialize() {
TRY_CHECK;
CmdBotGMEventInfo cmd_bgei(true); // Waiter
NormalManagerDB::add(0, &cmd_bgei, nullptr, nullptr);
cmd_bgei.waitEvent();
if (cmd_bgei.getException().getCodeError() != 0)
throw cmd_bgei.getException();
m_rt = cmd_bgei.getTimeInfo();
m_rewards = cmd_bgei.getRewardInfo();
// Log
//#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[BotGMEvent::initialize][Log] Carregou " + std::to_string(m_rt.size()) + " times.", CL_FILE_LOG_AND_CONSOLE));
for (auto& el : m_rt)
_smp::message_pool::getInstance().push(new message("[BotGMEvent::initialize][Log] Time[Start=" + _formatTime(el.m_start) + ", End=" + _formatTime(el.m_end) + ", Channel_id=" + std::to_string((unsigned short)el.m_channel_id) +"].", CL_FILE_LOG_AND_CONSOLE));
_smp::message_pool::getInstance().push(new message("[BotGMEvent::initialize][Log] Bot GM Event System carregado com sucesso!", CL_FILE_LOG_AND_CONSOLE));
/*#else
_smp::message_pool::getInstance().push(new message("[BotGMEvent::initialize][Log] Carregou " + std::to_string(m_rt.size()) + " times.", CL_ONLY_FILE_LOG));
for (auto& el : m_rt)
_smp::message_pool::getInstance().push(new message("[BotGMEvent::initialize][Log] Time[Start=" + _formatTime(el.m_start) + ", End=" + _formatTime(el.m_end) + ", Channel_id=" + std::to_string((unsigned short)el.m_channel_id) + "].", CL_ONLY_FILE_LOG));
_smp::message_pool::getInstance().push(new message("[BotGMEvent::initialize][Log] Bot GM Event System carregado com sucesso!", CL_ONLY_FILE_LOG));
#endif // _DEBUG*/
// Carregou com sucesso
m_load = true;
LEAVE_CHECK;
CATCH_CHECK("initialize");
// Relan�a para o server tomar as provid�ncias
throw;
END_CHECK;
}
bool BotGMEvent::checkTimeToMakeRoom() {
if (!isLoad()) {
_smp::message_pool::getInstance().push(new message("[BotGMEvent::checkTimeToMakeRoom][Error] Bot GM Event not have initialized, please call init function first.", CL_FILE_LOG_AND_CONSOLE));
return false;
}
bool is_time = false;
TRY_CHECK;
GetLocalTime(&m_st);
auto it = std::find_if(m_rt.begin(), m_rt.end(), [&](auto& _el) {
return _el.isBetweenTime(m_st);
});
is_time = (it != m_rt.end());
LEAVE_CHECK;
CATCH_CHECK("checkTimeToMakeRoom");
END_CHECK;
return is_time;
}
bool BotGMEvent::messageSended() {
if (!isLoad()) {
_smp::message_pool::getInstance().push(new message("[BotGMEvent::messageSended][Error] Bot GM Event not have initialized, please call init function first.", CL_FILE_LOG_AND_CONSOLE));
return false;
}
bool is_sended = false;
TRY_CHECK
GetLocalTime(&m_st);
auto it = std::find_if(m_rt.begin(), m_rt.end(), [&](auto& _el) {
return _el.isBetweenTime(m_st);
});
is_sended = (it != m_rt.end() && it->m_sended_message);
LEAVE_CHECK
CATCH_CHECK("messageSended")
END_CHECK
return is_sended;
}
void BotGMEvent::setSendedMessage() {
if (!isLoad()) {
_smp::message_pool::getInstance().push(new message("[BotGMEvent::setSendedMessage][Error] Bot GM Event not have initialized, please call init function first.", CL_FILE_LOG_AND_CONSOLE));
return;
}
TRY_CHECK
GetLocalTime(&m_st);
// Zera todas os intervalos que n�o est� na hora, e o intervalo que est� na hora seta ele
std::for_each(m_rt.begin(), m_rt.end(), [&](auto& _el) {
if (_el.isBetweenTime(m_st))
_el.m_sended_message = true;
else
_el.m_sended_message = false;
});
LEAVE_CHECK
CATCH_CHECK("setSendedMessage")
END_CHECK
}
stRangeTime* BotGMEvent::getInterval() {
if (!isLoad()) {
_smp::message_pool::getInstance().push(new message("[BotGMEvent::getInterval][Error] Bot GM Event not have initialized, please call init function first.", CL_FILE_LOG_AND_CONSOLE));
return nullptr;
}
stRangeTime *rt = nullptr;
TRY_CHECK
GetLocalTime(&m_st);
auto it = std::find_if(m_rt.begin(), m_rt.end(), [&](auto& _el) {
return _el.isBetweenTime(m_st);
});
if (it != m_rt.end())
rt = &(*it);
LEAVE_CHECK
CATCH_CHECK("getInterval")
rt = nullptr;
END_CHECK
return rt;
}
std::vector< stReward > BotGMEvent::calculeReward() {
std::vector< stReward > v_reward;
TRY_CHECK;
// No m�ximo 3 pr�mios
uint32_t num_r = (uint32_t)sRandomGen::getInstance().rIbeMt19937_64_rdeviceRange(1, MAX_REWARD_PER_ROUND);
Lottery lottery(std::clock());
Lottery::LotteryCtx* ctx = nullptr;
for (auto& el : m_rewards)
lottery.push(el.rate, (size_t)&el);
bool remove_to_roleta = num_r < lottery.getCountItem();
// Not loop infinite
num_r = num_r > lottery.getCountItem() ? lottery.getCountItem() : num_r;
while (num_r > 0) {
if ((ctx = lottery.spinRoleta(remove_to_roleta)) == nullptr) {
// Log
_smp::message_pool::getInstance().push(new message("[BotGMEvent::calculeReward][Error][WARNING] nao conseguiu sortear um reward na lottery.", CL_FILE_LOG_AND_CONSOLE));
// Continua
continue;
}
v_reward.push_back(*(stReward*)ctx->value);
// decrease num_r(reward)
num_r--;
}
LEAVE_CHECK;
CATCH_CHECK("calculeReward");
END_CHECK;
return v_reward;
}
| 22.508876 | 260 | 0.699527 | eantoniobr |
74931357432bf0822998d673c69668b226e4ffa3 | 1,120 | cc | C++ | chaos/unit-test/test_sparse.cc | gogdizzy/chaos | cf6400a20320cc3c93bd62b0a514af5ca54f18fb | [
"MIT"
] | null | null | null | chaos/unit-test/test_sparse.cc | gogdizzy/chaos | cf6400a20320cc3c93bd62b0a514af5ca54f18fb | [
"MIT"
] | null | null | null | chaos/unit-test/test_sparse.cc | gogdizzy/chaos | cf6400a20320cc3c93bd62b0a514af5ca54f18fb | [
"MIT"
] | null | null | null | #include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "mem.h"
#include "SparseGridMap.h"
void test( int xs, int ys ) {
SparseGridMap<SparseGridMap<int64_t> > oldCosts;
for( int xu = xs; xu < xs + 100; ++xu ) {
for( int yu = ys; yu < ys + 100; ++yu ) {
for( int xv = xu - 1; xv <= xu + 1; ++xv ) {
for( int yv = yu - 1; yv <= yu + 1; ++yv ) {
if( xu != xv || yu != yv ) {
oldCosts.At( xs + rand() % 1024, ys + rand() % 1024 ).At( xs + rand()%1024, ys + rand() % 1024 ) = 1;
// oldCosts.At( xu, yu ).At( xv, yv ) = 1;
}
}
}
}
}
int tot = 0;
oldCosts.ForEach([&](const int32_t& ux, const int32_t& uy, const SparseGridMap<int64_t>& tmp)
{
tmp.ForEach([&](const int32_t& vx, const int32_t& vy, const int64_t& oldC)
{ tot += oldC;
} );
} );
}
int main() {
// mallopt( M_MMAP_THRESHOLD, 1 );
srand( time(NULL) );
printf( "curRSS:%zu\n", getCurrentRSS() );
for( int i = 0; i < 100; ++i ) {
// test( rand(), rand() );
test( 0, 0 );
printf( "curRSS:%zu\n", getCurrentRSS() );
}
return 0;
}
| 24.347826 | 108 | 0.516964 | gogdizzy |
74967552f28a7fea8e4d986529302219bdfdc46a | 10,708 | hxx | C++ | Modules/Wrappers/ApplicationEngine/include/otbWrapperParameterList.hxx | kikislater/OTB | 8271c62b5891d3da9cb2e9ba3a2706a26de8c323 | [
"Apache-2.0"
] | null | null | null | Modules/Wrappers/ApplicationEngine/include/otbWrapperParameterList.hxx | kikislater/OTB | 8271c62b5891d3da9cb2e9ba3a2706a26de8c323 | [
"Apache-2.0"
] | null | null | null | Modules/Wrappers/ApplicationEngine/include/otbWrapperParameterList.hxx | kikislater/OTB | 8271c62b5891d3da9cb2e9ba3a2706a26de8c323 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbWrapperParameterList_hxx
#define otbWrapperParameterList_hxx
#include <algorithm>
#include <iterator>
#include "otbCast.h"
#include "otbWrapperParameterList.h"
namespace otb
{
namespace Wrapper
{
/*****************************************************************************/
template< typename T >
ParameterList< T >
::ParameterList() :
AbstractParameterList(),
m_Parameters()
{
}
/*****************************************************************************/
template< typename T >
ParameterList< T >
::~ParameterList()
{
}
/*****************************************************************************/
template< typename T >
typename ParameterList< T >::ParameterVector::const_iterator
ParameterList< T >
::begin() const
{
return m_Parameters.begin();
}
/*****************************************************************************/
template< typename T >
typename ParameterList< T >::ParameterVector::const_iterator
ParameterList< T >
::end() const
{
return m_Parameters.end();
}
/*****************************************************************************/
template< typename T >
bool
ParameterList< T >
::HasValue() const
{
return
Size()>0
&&
std::all_of(
begin(),
end(),
[]( auto p ) -> bool
{
assert( p!=nullptr );
return p && p->HasValue();
}
);
}
/*****************************************************************************/
template< typename T >
void
ParameterList< T >
::ClearValue()
{
m_Parameters.clear();
Superclass::ClearValue();
}
/*****************************************************************************/
template< typename T >
void
ParameterList< T >
::SetListFromFileName( const StringVector & strings )
{
this->SetStrings(strings);
}
/*****************************************************************************/
template< typename T >
void
ParameterList< T >
::InsertNullElement( std::size_t index )
{
m_Parameters.insert(
index>=m_Parameters.size()
? m_Parameters.end()
: m_Parameters.begin() + index,
typename T::Pointer()
);
SetActive( false );
Modified();
}
/*****************************************************************************/
template< typename T >
void
ParameterList< T >
::AddFromFileName( const std::string & filename )
{
assert( !filename.empty() );
typename T::Pointer p( T::New() );
p->FromString(filename);
m_Parameters.push_back( p );
assert( !m_Parameters.back().IsNull() );
SetActive( true );
Modified();
}
/*****************************************************************************/
template< typename T >
void
ParameterList< T >
::Insert( const std::string & filename, std::size_t index )
{
typename T::Pointer p( T::New() );
p->FromString(filename);
m_Parameters.insert( m_Parameters.begin() + index, p );
assert( !m_Parameters.back().IsNull() );
SetActive( true );
Modified();
}
/*****************************************************************************/
template< typename T >
void
ParameterList< T >
::SetNthFileName( std::size_t i,
const std::string & filename )
{
assert( i<m_Parameters.size() );
assert( !m_Parameters[ i ].IsNull() );
m_Parameters[i]->FromString(filename);
SetActive( true );
Modified();
}
/*****************************************************************************/
template< typename T >
std::size_t
ParameterList< T >
::SetStrings( const StringVector & strings )
{
// First clear previous file chosen
ClearValue();
if ( !strings.empty() )
{
std::transform(
strings.begin(),
strings.end(),
std::back_inserter( m_Parameters ),
[]( auto s ) -> auto
{
typename T::Pointer parameter(T::New());
parameter->FromString(s);
return parameter;
}
);
SetActive( true );
Modified();
}
return strings.size();
}
/*****************************************************************************/
template< typename T >
std::size_t
ParameterList< T >
::GetStrings( StringVector & strings ) const
{
std::transform(
begin(),
end(),
std::back_inserter( strings ),
[]( auto p ) -> auto
{
return p->ToString();
}
);
return m_Parameters.size();
}
/*****************************************************************************/
template< typename T >
StringListInterface::StringVector
ParameterList< T >
::GetFileNameList() const
{
StringVector filenames;
GetStrings( filenames );
return filenames;
}
/*****************************************************************************/
template< typename T >
std::string
ParameterList< T >
::GetNthFileName( std::size_t i ) const
{
assert( i<m_Parameters.size() );
return m_Parameters[i]->ToString();
}
/*****************************************************************************/
template< typename T >
const std::string &
ParameterList< T >
::GetToolTip( std::size_t i ) const
{
assert( i<m_Parameters.size() );
assert( !m_Parameters[ i ].IsNull() );
return m_Parameters[ i ]->GetDescription();
}
/*****************************************************************************/
template< typename T >
void
ParameterList< T >
::Erase( std::size_t start, std::size_t count )
{
assert( start<m_Parameters.size() );
assert( start+count<=m_Parameters.size() );
m_Parameters.erase(
m_Parameters.begin() + start,
m_Parameters.begin() + start + count
);
Modified();
}
/*****************************************************************************/
template< typename T >
std::size_t
ParameterList< T >
::Size() const
{
return m_Parameters.size();
}
/*****************************************************************************/
template< typename T >
bool
ParameterList< T >
::IsActive( std::size_t i ) const
{
assert( i<m_Parameters.size() );
assert( !m_Parameters[ i ].IsNull() );
return m_Parameters[ i ]->GetActive();
}
/*****************************************************************************/
template< typename T >
void
ParameterList< T >
::Swap( std::size_t i1, std::size_t i2 )
{
assert( !m_Parameters.empty() );
auto clamp = [ this ]( std::size_t i ) -> std::size_t
{
return
i>=m_Parameters.size()
? m_Parameters.size() - 1
: i;
};
std::swap(
m_Parameters[ clamp( i1 ) ],
m_Parameters[ clamp( i2 ) ]
);
}
/*****************************************************************************/
template< typename T >
template< typename L, typename From, typename Get >
void
ParameterList< T >
::SetObjectList( L & this_list,
const L & list,
From from,
Get get )
{
// Force update of input-list elements.
for( std::size_t i=0; i<list.Size(); i++ )
{
assert( list.GetNthElement( i )!=nullptr );
list.GetNthElement( i )->UpdateOutputInformation();
}
// Clear previous target list.
ClearValue();
for( std::size_t i=0; i<list.Size(); i++ )
{
assert( list.GetNthElement( i )!=nullptr );
typename T::Pointer parameter;
from( parameter, list.GetNthElement( i ) );
m_Parameters.push_back( parameter );
assert( get( parameter )!=nullptr );
this_list.PushBack( get( parameter ) );
}
SetActive( true );
Modified();
}
/*****************************************************************************/
template< typename T >
template< typename L, typename Get >
typename L::ObjectType *
ParameterList< T >
::GetObjectList( L & this_list, Get get )
{
assert( this_list );
this_list->Clear();
std::for_each(
begin(),
end(),
[ this_list, get ]( auto parameter ) -> void
{
assert( parameter );
assert( parameter==otb::DynamicCast< T >( parameter ) );
assert( get( DynamicCast< T >( parameter ) ) );
this_list->PushBack(
get(
DynamicCast< T >( parameter )
)
);
}
);
return this_list;
}
/*****************************************************************************/
template< typename T >
template< typename L, typename Get >
const typename L::ObjectType *
ParameterList< T >
::GetObjectList( L & this_list, Get get ) const
{
return
const_cast< ParameterList< T > * >( this )
->GetObjectList( this_list, get );
}
/*****************************************************************************/
template< typename T >
template< typename D, typename From >
void
ParameterList< T >
::AddData( D * data, From from )
{
assert( data!=nullptr );
// Check input availability
data->UpdateOutputInformation();
// Build & add parameter.
m_Parameters.push_back( from( data ) );
Modified();
}
/*****************************************************************************/
template< typename T >
template< typename D, typename Set >
typename T::Pointer
ParameterList< T >
::FromData( D * data,
Set set,
const std::string & description )
{
assert( data!=nullptr );
typename T::Pointer p;
return From( p, data, set, description );
}
/*****************************************************************************/
template< typename T >
template< typename D, typename Set >
typename T::Pointer &
ParameterList< T >
::FromData( typename T::Pointer & parameter,
D * data,
Set set,
const std::string & description )
{
assert( data!=nullptr );
parameter = T::New();
set( parameter, data );
parameter->SetDescription( description );
return parameter;
}
template <typename T>
std::vector<std::string> ParameterList<T>::ToStringList() const
{
return GetFileNameList();
}
template <typename T>
void ParameterList<T>::FromStringList(const std::vector<std::string>& value)
{
SetStrings(value);
}
template <typename T>
std::string ParameterList<T>::ToString() const
{
std::ostringstream oss;
oss << std::setprecision(10);
auto strList = GetFileNameList();
for (size_t i = 0; i < strList.size(); i++)
{
if (i != 0)
{
oss << " ";
}
oss << strList[i];
}
return oss.str();
}
} // End namespace Wrapper
} // End namespace otb
#endif
| 21.120316 | 79 | 0.522226 | kikislater |
7496f38ead2eb93582bc56eef15c9e6fafabd974 | 1,644 | cpp | C++ | GameEngine/src/App/CharacterObject.cpp | MikeAllport/CE301-Final-Year-Project | da2f3a3d52b955b2f8deca43849273a26b49dda3 | [
"Apache-2.0"
] | null | null | null | GameEngine/src/App/CharacterObject.cpp | MikeAllport/CE301-Final-Year-Project | da2f3a3d52b955b2f8deca43849273a26b49dda3 | [
"Apache-2.0"
] | null | null | null | GameEngine/src/App/CharacterObject.cpp | MikeAllport/CE301-Final-Year-Project | da2f3a3d52b955b2f8deca43849273a26b49dda3 | [
"Apache-2.0"
] | null | null | null | #include <gepch.h>
#include "CharacterObject.h"
namespace App
{
CharacterObject::CharacterObject(glm::fvec3 position, Controller& controller) :
CommonGameObject(position, CHARACTER),
controller(controller),
objectPos(-1, -1)
{
}
void CharacterObject::onUpdate(const float& DT)
{
if (isValidObjectPos() && !controller.moved)
moveToObject();
else
moveToController();
GameObject::onUpdate(DT);
}
void CharacterObject::moveToObject()
{
if (movingToObject)
{
if (objectPos.Distance(Vector2D(position.x, position.z)) <= size.x / 2)
{
clearObjectPos();
return;
}
}
else
{
if (objectPos.Distance(Vector2D(position.x, position.z)) <= 8)
{
clearObjectPos();
return;
}
}
Vector2D direction = objectPos - Vector2D(position.x, position.z);
velocity = direction.Normalize() * MAX_SPEED;
}
void CharacterObject::moveToObject(CommonGameObject* obj)
{
if (!obj)
return;
movingToObject = true;
setMoveTo(obj->getPosition().x, obj->getPosition().z);
}
void CharacterObject::moveToFloor(int x, int y)
{
movingToObject = false;
setMoveTo(x, y);
}
void CharacterObject::moveToController()
{
clearObjectPos();
Action action = controller.GetAction();
velocity = Vector2D(action.CharacterHorizontalMovement, action.CharacterDepthMovement).Normalize() * MAX_SPEED;
}
void CharacterObject::setMoveTo(int x, int y)
{
objectPos = Vector2D(x, y);
}
void CharacterObject::clearObjectPos()
{
movingToObject = false;
objectPos = Vector2D(-1, -1);
}
bool CharacterObject::isValidObjectPos()
{
return objectPos.x != -1 || objectPos.y != -1;
}
} | 20.04878 | 113 | 0.685523 | MikeAllport |
749ad4f7bab55d1b6982f9f02223de35176798e2 | 3,419 | cc | C++ | components/history_clusters/core/history_clusters_service_test_api.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/history_clusters/core/history_clusters_service_test_api.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | components/history_clusters/core/history_clusters_service_test_api.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/history_clusters/core/history_clusters_service_test_api.h"
#include "base/time/time.h"
#include "components/history/core/browser/history_types.h"
namespace history_clusters {
// static
std::vector<history::AnnotatedVisit> GetHardcodedTestVisits() {
// For non-flakiness, return a static list of visits, as this relies on Now().
static std::vector<history::AnnotatedVisit> visits;
if (visits.empty()) {
{
history::AnnotatedVisit visit;
visit.url_row.set_id(1);
visit.url_row.set_url(GURL("https://google.com/"));
visit.url_row.set_title(u"Search Engine Title");
visit.visit_row.visit_id = 1;
// Choose a recent time, as otherwise History will discard the visit.
visit.visit_row.visit_time = base::Time::Now() - base::Days(2);
visit.visit_row.visit_duration = base::Milliseconds(5600);
visit.context_annotations.page_end_reason = 3;
visit.context_annotations.is_new_bookmark = true;
visit.source = history::VisitSource::SOURCE_BROWSED;
visits.push_back(visit);
}
{
history::AnnotatedVisit visit;
visit.url_row.set_id(2);
visit.url_row.set_url(GURL("https://github.com/"));
visit.url_row.set_title(u"Code Storage Title");
visit.visit_row.visit_id = 2;
// Choose a recent time, as otherwise History will discard the visit.
visit.visit_row.visit_time = base::Time::Now() - base::Days(1);
visit.visit_row.visit_duration = base::Seconds(20);
visit.visit_row.referring_visit = 1;
visit.context_annotations.page_end_reason = 5;
visit.context_annotations.is_existing_part_of_tab_group = true;
visit.source = history::VisitSource::SOURCE_BROWSED;
visits.push_back(visit);
}
{
// Synched visits should not be included when fetching visits to cluster.
history::AnnotatedVisit visit;
visit.url_row.set_id(3);
visit.url_row.set_url(GURL("https://synched-visit.com/"));
visit.url_row.set_title(u"Synched visit");
visit.visit_row.visit_id = 3;
// Choose a recent time, as otherwise History will discard the visit.
visit.visit_row.visit_time = base::Time::Now() - base::Days(1);
visit.visit_row.visit_duration = base::Seconds(20);
visit.context_annotations.page_end_reason = 5;
visit.source = history::VisitSource::SOURCE_SYNCED;
visits.push_back(visit);
}
{
// Visits older than 30 days should not be included in keyword requests.
history::AnnotatedVisit visit;
visit.url_row.set_id(2);
visit.url_row.set_url(GURL("https://31-day-old-visit.com/"));
visit.url_row.set_title(u"31 day old visit");
visit.visit_row.visit_id = 4;
// Choose a recent time, as otherwise History will discard the visit.
visit.visit_row.visit_time = base::Time::Now() - base::Days(60);
visit.visit_row.visit_duration = base::Seconds(20);
visit.visit_row.referring_visit = 1;
visit.context_annotations.page_end_reason = 5;
visit.context_annotations.is_existing_part_of_tab_group = true;
visit.source = history::VisitSource::SOURCE_BROWSED;
visits.push_back(visit);
}
}
return visits;
}
} // namespace history_clusters
| 39.755814 | 80 | 0.69728 | zealoussnow |
749dc6719febf881b52d956537cd7a548f6a2e28 | 6,612 | hpp | C++ | tpls/pressio/include/pressio/WIP/rom/lspg/impl/steady/rom_compose_steady_lspg_impl.hpp | fnrizzi/pressio-demoapps | 6ff10bbcf4d526610580940753c9620725bff1ba | [
"BSD-3-Clause"
] | 29 | 2019-11-11T13:17:57.000Z | 2022-03-16T01:31:31.000Z | tpls/pressio/include/pressio/WIP/rom/lspg/impl/steady/rom_compose_steady_lspg_impl.hpp | fnrizzi/pressio-demoapps | 6ff10bbcf4d526610580940753c9620725bff1ba | [
"BSD-3-Clause"
] | 303 | 2019-09-30T10:15:41.000Z | 2022-03-30T08:24:04.000Z | tpls/pressio/include/pressio/WIP/rom/lspg/impl/steady/rom_compose_steady_lspg_impl.hpp | fnrizzi/pressio-demoapps | 6ff10bbcf4d526610580940753c9620725bff1ba | [
"BSD-3-Clause"
] | 4 | 2020-07-07T03:32:36.000Z | 2022-03-10T05:21:42.000Z | /*
//@HEADER
// ************************************************************************
//
// rom_compose_steady_lspg_impl.hpp
// Pressio
// Copyright 2019
// National Technology & Engineering Solutions of Sandia, LLC (NTESS)
//
// Under the terms of Contract DE-NA0003525 with NTESS, the
// U.S. Government retains certain rights in this software.
//
// Pressio is licensed under BSD-3-Clause terms of use:
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef ROM_LSPG_IMPL_STEADY_ROM_COMPOSE_STEADY_LSPG_IMPL_HPP_
#define ROM_LSPG_IMPL_STEADY_ROM_COMPOSE_STEADY_LSPG_IMPL_HPP_
#include "../rom_problem_tags.hpp"
#include "./policies/rom_lspg_steady_residual_policy.hpp"
#include "./policies/rom_lspg_steady_jacobian_policy.hpp"
#include "rom_lspg_steady_system.hpp"
#include "./traits/rom_lspg_steady_common_traits.hpp"
#include "./traits/rom_lspg_steady_default_problem_traits.hpp"
#include "./traits/rom_lspg_steady_preconditioned_problem_traits.hpp"
#include "./traits/rom_lspg_steady_masked_problem_traits.hpp"
#include "./traits/rom_lspg_steady_hyper_reduced_problem_traits.hpp"
#include "./traits/rom_lspg_steady_preconditioned_hyper_reduced_problem_traits.hpp"
#include "./rom_lspg_steady_default_problem.hpp"
#include "./rom_lspg_steady_preconditioned_problem.hpp"
#include "./rom_lspg_steady_masked_problem.hpp"
#include "./rom_lspg_steady_hyper_reduced_problem.hpp"
#include "./rom_lspg_steady_preconditioned_hyper_reduced_problem.hpp"
namespace pressio{ namespace rom{ namespace lspg{ namespace impl{
template<
class problem_tag,
class enable,
class fom_system_type,
class decoder_type,
class ...Args
>
struct composeSteady
{
//if we are here, something is wrong, find out what
static_assert
(::pressio::rom::why_not_steady_system_with_user_provided_apply_jacobian
<fom_system_type, typename decoder_type::jacobian_type
>::value, "");
using type = void;
};
//------------------------
// specialize compose
//------------------------
// default
template<
typename fom_system_type,
typename decoder_type,
typename lspg_state_type
>
struct composeSteady<
::pressio::rom::lspg::impl::Default,
mpl::enable_if_t<
::pressio::rom::constraints::steady_system_with_user_provided_apply_jacobian<
fom_system_type, typename decoder_type::jacobian_type>::value
>,
fom_system_type, decoder_type, lspg_state_type>
{
using type = ::pressio::rom::lspg::impl::steady::DefaultProblemSteady<
fom_system_type, lspg_state_type, decoder_type>;
};
// preconditioned default
template<
typename fom_system_type,
typename decoder_type,
typename lspg_state_type,
typename precond_type
>
struct composeSteady<
::pressio::rom::lspg::impl::Preconditioned,
mpl::enable_if_t<
::pressio::rom::constraints::steady_system_with_user_provided_apply_jacobian<
fom_system_type, typename decoder_type::jacobian_type>::value
>,
fom_system_type, decoder_type, lspg_state_type, precond_type>
{
using type = ::pressio::rom::lspg::impl::steady::PreconditionedProblemSteady<
fom_system_type, lspg_state_type, decoder_type, precond_type>;
};
// masked
template<
typename fom_system_type,
typename decoder_type,
typename lspg_state_type,
typename masker_type
>
struct composeSteady<
::pressio::rom::lspg::impl::Masked,
mpl::enable_if_t<
::pressio::rom::constraints::steady_system_with_user_provided_apply_jacobian<
fom_system_type, typename decoder_type::jacobian_type>::value
>,
fom_system_type, decoder_type, lspg_state_type, masker_type>
{
using type = ::pressio::rom::lspg::impl::steady::MaskedProblemSteady<
fom_system_type, lspg_state_type, decoder_type, masker_type>;
};
// hyper-reduced
template<
typename fom_system_type,
typename decoder_type,
typename lspg_state_type
>
struct composeSteady<
::pressio::rom::lspg::impl::HyperReduced,
mpl::enable_if_t<
::pressio::rom::constraints::steady_system_with_user_provided_apply_jacobian<
fom_system_type, typename decoder_type::jacobian_type>::value
>,
fom_system_type, decoder_type, lspg_state_type
>
{
using type = ::pressio::rom::lspg::impl::steady::HyperReducedProblemSteady<
fom_system_type, lspg_state_type, decoder_type>;
};
// preconditioned hyper-reduced
template<
typename fom_system_type,
typename decoder_type,
typename lspg_state_type,
typename precond_type
>
struct composeSteady<
::pressio::rom::lspg::impl::PreconditionedHyperReduced,
mpl::enable_if_t<
::pressio::rom::constraints::steady_system_with_user_provided_apply_jacobian<
fom_system_type, typename decoder_type::jacobian_type>::value
>,
fom_system_type, decoder_type, lspg_state_type, precond_type>
{
using type = ::pressio::rom::lspg::impl::steady::PreconditionedHyperReducedProblemSteady<
fom_system_type, lspg_state_type, decoder_type, precond_type>;
};
}}}}
#endif // ROM_LSPG_IMPL_STEADY_ROM_COMPOSE_STEADY_LSPG_IMPL_HPP_
| 34.4375 | 91 | 0.748941 | fnrizzi |
74a3584759e82b15128bb5342fa2fbdfe2270a5d | 1,331 | cc | C++ | asylo/platform/crypto/sha256_hash.cc | Hasimir/asylo | ac598c5266e36312d18fcdaa55efbc780af88975 | [
"Apache-2.0"
] | 1 | 2019-06-27T12:44:36.000Z | 2019-06-27T12:44:36.000Z | asylo/platform/crypto/sha256_hash.cc | Hasimir/asylo | ac598c5266e36312d18fcdaa55efbc780af88975 | [
"Apache-2.0"
] | null | null | null | asylo/platform/crypto/sha256_hash.cc | Hasimir/asylo | ac598c5266e36312d18fcdaa55efbc780af88975 | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright 2017 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "asylo/platform/crypto/sha256_hash.h"
#include <openssl/sha.h>
namespace asylo {
Sha256Hash::Sha256Hash() {
SHA256_Init(&context_);
}
void Sha256Hash::Update(const void *data, size_t len) {
SHA256_Update(&context_, data, len);
}
std::string Sha256Hash::Hash() {
// Do not finalize the internally stored hash context. Instead, finalize a
// copy of the current context so that the current context can be updated in
// future calls to Update.
uint8_t digest_bytes[SHA256_DIGEST_LENGTH];
SHA256_CTX context_snapshot = context_;
SHA256_Final(digest_bytes, &context_snapshot);
return std::string(reinterpret_cast<char *>(digest_bytes),
SHA256_DIGEST_LENGTH);
}
} // namespace asylo
| 29.577778 | 78 | 0.732532 | Hasimir |
74a9c4d6778e05abad93ba69a0dcdda1da4d528d | 3,654 | cpp | C++ | UnitTests/TestGameEventHandler/testgameeventhandler.cpp | Moppa5/pirkanmaan-valloitus | 725dd1a9ef29dcd314faa179124541618dc8e5bf | [
"MIT"
] | 3 | 2020-10-30T13:26:34.000Z | 2020-12-08T13:21:34.000Z | UnitTests/TestGameEventHandler/testgameeventhandler.cpp | Moppa5/pirkanmaan-valloitus | 725dd1a9ef29dcd314faa179124541618dc8e5bf | [
"MIT"
] | 15 | 2020-12-10T18:13:20.000Z | 2021-06-08T10:37:51.000Z | UnitTests/TestGameEventHandler/testgameeventhandler.cpp | Moppa5/pirkanmaan-valloitus | 725dd1a9ef29dcd314faa179124541618dc8e5bf | [
"MIT"
] | null | null | null | #include <QString>
#include <QtTest>
#include <interfaces/gameeventhandler.hh>
#include "core/player.hh"
using namespace Game;
/**
* @brief The TestGameEventHandler class is for unit testing
* GameEventHandler class. It tests that the methods work properly
* under valid conditions.
*/
class TestGameEventHandler : public QObject
{
Q_OBJECT
public:
/**
* @brief Creates the GameEventHandler to be tested
*/
TestGameEventHandler();
private:
GameEventHandler* geHandler;
const Course::ResourceMap RM1{
{WOOD, 10},
{FOOD, 20},
{STONE, 30},
{ORE, 40},
{MONEY, 50}
};
const Course::ResourceMap RMEmpty{
};
private Q_SLOTS:
/**
* @brief Tests modifyResources if it's successful
* RM1 resourcemap with parameter false so no changes
* RM1 with parameter true so resources change
* Empty resourcemap does nothing
*/
void testModifyResources();
/**
* @brief Tests modifyResource if it's succesful
* False case should not make any changes
* True case with negative result => no changes
* True case with valid result => changes made
*/
void testModifyResource();
/**
* @brief Tests if the resourcemap to be applied for a player is
* valid. No negative resources allowed to be changed
*/
void testValidResourceMap();
};
TestGameEventHandler::TestGameEventHandler()
{
geHandler = new GameEventHandler();
}
void TestGameEventHandler::testModifyResources()
{
std::vector<std::shared_ptr<Player>> players;
std::shared_ptr<Player> player = std::make_shared<Player>("name");
players.push_back(player);
geHandler->setPlayers(players);
// Should not apply change
ResourceMap oldResources = *(player->getResourceMap());
geHandler->modifyResources(player, RM1, false);
QVERIFY(*(player->getResourceMap()) == oldResources);
// Should apply change
geHandler->modifyResources(player, RM1, true);
QVERIFY(*(player->getResourceMap()) == RM1);
// Applying empty should not change resources
geHandler->modifyResources(player, RMEmpty, true);
QVERIFY(*(player->getResourceMap()) == RM1);
}
void TestGameEventHandler::testModifyResource()
{
std::vector<std::shared_ptr<Player>> players;
std::shared_ptr<Player> player = std::make_shared<Player>("name");
players.push_back(player);
geHandler->setPlayers(players);
// Should not apply change
ResourceMap oldResources = *(player->getResourceMap());
geHandler->modifyResource(player, WOOD, 0, false);
QVERIFY(*(player->getResourceMap()) == oldResources);
geHandler->modifyResource(player, WOOD, 20, false);
QVERIFY(*(player->getResourceMap()) == oldResources);
// Should apply change if valid
geHandler->modifyResource(player, WOOD, -100, true);
QVERIFY(*(player->getResourceMap()) == oldResources);
geHandler->modifyResource(player, WOOD, 1.5, true);
QVERIFY((*(player->getResourceMap()))[WOOD] == 1);
}
void TestGameEventHandler::testValidResourceMap()
{
std::vector<std::shared_ptr<Player>> players;
std::shared_ptr<Player> player = std::make_shared<Player>("name");
players.push_back(player);
geHandler->setPlayers(players);
QVERIFY(geHandler->modifyResource(player, WOOD, 0, false) == true);
QVERIFY(geHandler->modifyResource(player, WOOD, 20, false) == true);
QVERIFY(geHandler->modifyResource(player, WOOD, -100, true) == false);
QVERIFY(geHandler->modifyResource(player, WOOD, 1.5, true) == true);
}
QTEST_APPLESS_MAIN(TestGameEventHandler)
#include "testgameeventhandler.moc"
| 28.546875 | 74 | 0.684729 | Moppa5 |
74ac3f5f7dc532fcf4916fc0056d4372ff3a28ce | 4,405 | cpp | C++ | test/geometries/multi_linestring.cpp | jkerkela/geometry | 4034ac88b214da0eab8943172eff0f1200b0a6cc | [
"BSL-1.0"
] | 326 | 2015-02-08T13:47:49.000Z | 2022-03-16T02:13:59.000Z | test/geometries/multi_linestring.cpp | jkerkela/geometry | 4034ac88b214da0eab8943172eff0f1200b0a6cc | [
"BSL-1.0"
] | 623 | 2015-01-02T23:45:23.000Z | 2022-03-09T11:15:23.000Z | test/geometries/multi_linestring.cpp | jkerkela/geometry | 4034ac88b214da0eab8943172eff0f1200b0a6cc | [
"BSL-1.0"
] | 215 | 2015-01-14T15:50:38.000Z | 2022-02-23T03:58:36.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <iostream>
#include <geometry_test_common.hpp>
#include <boost/core/ignore_unused.hpp>
#include <boost/geometry/algorithms/make.hpp>
#include <boost/geometry/algorithms/append.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/linestring.hpp>
#include <boost/geometry/geometries/multi_linestring.hpp>
#include <boost/geometry/geometries/concepts/multi_linestring_concept.hpp>
#include <boost/geometry/geometries/adapted/c_array.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
#include <boost/geometry/io/dsv/write.hpp>
#include <test_common/test_point.hpp>
BOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)
#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST
#include <initializer_list>
#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST
template <typename P>
bg::model::linestring<P> create_linestring()
{
bg::model::linestring<P> l1;
P p1(1, 2);
bg::append(l1, p1);
return l1;
}
template <typename P, typename L>
bg::model::multi_linestring<L> create_multi_linestring()
{
bg::model::multi_linestring<L> ml1;
L l1(create_linestring<P>());
ml1.push_back(l1);
ml1.push_back(l1);
return ml1;
}
template <typename ML, typename L>
void check_multi_linestring(ML& to_check, L l1)
{
ML cur;
cur.push_back(l1);
cur.push_back(l1);
std::ostringstream out1, out2;
out1 << bg::dsv(to_check);
out2 << bg::dsv(cur);
BOOST_CHECK_EQUAL(out1.str(), out2.str());
}
template <typename P, typename L>
void test_default_constructor()
{
bg::model::multi_linestring<L> ml1(create_multi_linestring<P, L>());
check_multi_linestring(ml1, L(create_linestring<P>()));
}
template <typename P, typename L>
void test_copy_constructor()
{
bg::model::multi_linestring<L> ml1 = create_multi_linestring<P, L>();
check_multi_linestring(ml1, L(create_linestring<P>()));
}
template <typename P, typename L>
void test_copy_assignment()
{
bg::model::multi_linestring<L> ml1(create_multi_linestring<P, L>()), ml2;
ml2 = ml1;
check_multi_linestring(ml2, L(create_linestring<P>()));
}
template <typename L>
void test_concept()
{
typedef bg::model::multi_linestring<L> ML;
BOOST_CONCEPT_ASSERT( (bg::concepts::ConstMultiLinestring<ML>) );
BOOST_CONCEPT_ASSERT( (bg::concepts::MultiLinestring<ML>) );
typedef typename bg::coordinate_type<ML>::type T;
typedef typename bg::point_type<ML>::type PML;
boost::ignore_unused<T, PML>();
}
template <typename P>
void test_all()
{
typedef bg::model::linestring<P> L;
test_default_constructor<P, L>();
test_copy_constructor<P, L>();
test_copy_assignment<P, L>();
test_concept<L>();
}
template <typename P>
void test_custom_multi_linestring(bg::model::linestring<P> IL)
{
typedef bg::model::linestring<P> L;
std::initializer_list<L> LIL = {IL};
bg::model::multi_linestring<L> ml1(LIL);
std::ostringstream out;
out << bg::dsv(ml1);
BOOST_CHECK_EQUAL(out.str(), "(((1, 1), (2, 2), (3, 3), (0, 0), (0, 2), (0, 3)))");
}
template <typename P>
void test_custom()
{
#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST
std::initializer_list<P> IL1 = {P(1, 1), P(2, 2), P(3, 3)};
std::initializer_list<P> IL2 = {P(0, 0), P(0, 2), P(0, 3)};
bg::model::linestring<P> l1;
bg::append(l1, IL1);
bg::append(l1, IL2);
test_custom_multi_linestring<P>(l1);
#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST
}
template <typename CS>
void test_cs()
{
test_all<bg::model::point<int, 2, CS> >();
test_all<bg::model::point<float, 2, CS> >();
test_all<bg::model::point<double, 2, CS> >();
test_custom<bg::model::point<double, 2, CS> >();
}
int test_main(int, char* [])
{
test_cs<bg::cs::cartesian>();
test_cs<bg::cs::spherical<bg::degree> >();
test_cs<bg::cs::spherical_equatorial<bg::degree> >();
test_cs<bg::cs::geographic<bg::degree> >();
test_custom<bg::model::d2::point_xy<double> >();
return 0;
}
| 27.53125 | 87 | 0.695119 | jkerkela |
74ad20acebdfb2edc5e92b64d849d2a69949196f | 2,947 | cpp | C++ | tests/tagwriter.cpp | dda119141/mp3tags | c75818e4fd6341f2c0c0b482f5c6eb1809b382aa | [
"MIT"
] | 1 | 2020-08-01T21:51:05.000Z | 2020-08-01T21:51:05.000Z | tests/tagwriter.cpp | dda119141/mp3tags | c75818e4fd6341f2c0c0b482f5c6eb1809b382aa | [
"MIT"
] | 1 | 2020-05-01T11:52:59.000Z | 2020-05-01T11:52:59.000Z | tests/tagwriter.cpp | dda119141/mp3tags | c75818e4fd6341f2c0c0b482f5c6eb1809b382aa | [
"MIT"
] | null | null | null | // Copyright(c) 2020-present, Moge & contributors.
// Email: dda119141@gmail.com
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#include <iostream>
#include <memory>
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include "tagreader.hpp"
#include "tagwriter.hpp"
TEST_CASE("Read/Write from/to id3v2 tag") {
namespace fs = id3::filesystem;
using std::cout;
using std::endl;
std::string filename;
#ifdef HAS_FS_EXPERIMENTAL
const std::string currentFilePath = fs::system_complete(__FILE__);
#else
const std::string currentFilePath = fs::absolute(__FILE__).string();
#endif
cout << "current file path:" << currentFilePath << endl;
const std::string mp3Path =
(fs::path(currentFilePath).parent_path() /= "../files").string();
const auto findFileName = [&](const std::string& filName){
const auto pos = filName.find_last_of('/');
return filName.substr(pos+1);
};
try {
for (auto& filen : fs::directory_iterator(mp3Path)) {
std::string _filename = filen.path().string();
if (findFileName(_filename) == std::string("test1.mp3")) {
filename = _filename;
} /* else if (_filename.find("test1.mp3") != std::string::npos) {
filename = _filename;
} */
}
} catch (fs::filesystem_error& e) {
cout << "wrong path:" << e.what() << endl;
}
SECTION("test path") {
REQUIRE(filename == (fs::path(mp3Path) /= "test1.mp3").string());
}
// cout << "File type: " << GetFileType(filename) << endl;
// cout << "Group Description: " << GetContentGroupDescription(filename)
// << endl;
// cout << "GetTrackPosition: " << GetTrackPosition(filename) << endl;
/*
SECTION("Test writing album name: test2"){
REQUIRE(SetAlbum(filename, "test1") == 1);
}
*/
SECTION("Test writing album") {
REQUIRE(SetAlbum(filename, "AlbYingAlbum") == 1);
}
SECTION("Test writing title") {
REQUIRE(SetTitle(filename, "testYingYangTitle") == 1);
}
SECTION("Test writing artist") {
REQUIRE(SetLeadArtist(filename, "TitTestYingArtist") == 1);
}
SECTION("Test reading back album") {
REQUIRE(GetAlbum(filename) == "AlbYingAlbum");
}
SECTION("Test reading back title") {
REQUIRE(GetTitle(filename) == "testYingYangTitle");
}
SECTION("Test reading back artist") {
REQUIRE(GetLeadArtist(filename) == "TitTestYingArtist");
}
SECTION("Test reading Year") { REQUIRE(GetYear(filename) == "2009"); }
SECTION("Test reading Content type") {
REQUIRE(GetContentType(filename) == "Rap");
}
SECTION("Test reading track position") {
REQUIRE(GetTrackPosition(filename) == "05/18");
}
SECTION("Test reading band orchestra") {
REQUIRE(GetBandOrchestra(filename) == "Ying Yang Twins");
}
}
| 30.697917 | 79 | 0.608755 | dda119141 |
74ae7a99bdc0e9f5314ab89af36d7eee13582383 | 12,869 | cpp | C++ | framework/unitest/core/test_process_profiler.cpp | HFauto/CNStream | 1d4847327fff83eedbc8de6911855c5f7bb2bf22 | [
"Apache-2.0"
] | 172 | 2019-08-24T10:05:14.000Z | 2022-03-29T07:45:18.000Z | framework/unitest/core/test_process_profiler.cpp | HFauto/CNStream | 1d4847327fff83eedbc8de6911855c5f7bb2bf22 | [
"Apache-2.0"
] | 27 | 2019-09-01T11:04:45.000Z | 2022-01-17T09:27:07.000Z | framework/unitest/core/test_process_profiler.cpp | HFauto/CNStream | 1d4847327fff83eedbc8de6911855c5f7bb2bf22 | [
"Apache-2.0"
] | 72 | 2019-08-24T10:13:06.000Z | 2022-03-28T08:26:05.000Z | /*************************************************************************
* Copyright (C) [2019] by Cambricon, Inc. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*************************************************************************/
#include <gtest/gtest.h>
#include <string>
#include <utility>
#include "profiler/process_profiler.hpp"
namespace cnstream {
TEST(CoreProcessProfiler, GetName) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
EXPECT_EQ(profiler_name, profiler.GetName());
}
TEST(CoreProcessProfiler, SetModuleName) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
const std::string module_name = "module";
profiler.SetModuleName(module_name).SetTraceLevel(TraceEvent::Level::MODULE);
profiler.RecordStart(std::make_pair("stream0", 100));
PipelineTrace trace = tracer.GetTrace(Time::min(), Time::max());
EXPECT_NE(trace.module_traces.find(module_name), trace.module_traces.end());
EXPECT_EQ(trace.module_traces[module_name].size(), 1);
EXPECT_NE(trace.module_traces[module_name].find(profiler_name), trace.module_traces[module_name].end());
EXPECT_EQ(trace.module_traces[module_name][profiler_name].size(), 1);
}
TEST(CoreProcessProfiler, SetTraceLevel) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
const std::string module_name = "module";
profiler.SetModuleName(module_name).SetTraceLevel(TraceEvent::Level::PIPELINE);
profiler.RecordStart(std::make_pair("stream0", 100));
PipelineTrace trace = tracer.GetTrace(Time::min(), Time::max());
EXPECT_EQ(trace.module_traces.find(module_name), trace.module_traces.end());
EXPECT_NE(trace.process_traces.find(profiler_name), trace.process_traces.end());
EXPECT_EQ(trace.process_traces[profiler_name].size(), 1);
}
TEST(CoreProcessProfiler, RecordStartModule) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
const std::string module_name = "module";
profiler.SetModuleName(module_name).SetTraceLevel(TraceEvent::Level::MODULE);
RecordKey key = std::make_pair("stream0", 100);
profiler.RecordStart(key);
PipelineTrace trace = tracer.GetTrace(Time::min(), Time::max());
EXPECT_NE(trace.module_traces.find(module_name), trace.module_traces.end());
EXPECT_EQ(trace.module_traces[module_name].size(), 1);
EXPECT_NE(trace.module_traces[module_name].find(profiler_name), trace.module_traces[module_name].end());
EXPECT_EQ(trace.module_traces[module_name][profiler_name].size(), 1);
TraceElem elem = trace.module_traces[module_name][profiler_name][0];
EXPECT_EQ(elem.type, TraceEvent::Type::START);
EXPECT_EQ(elem.key, key);
}
TEST(CoreProcessProfiler, RecordEndModule) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
const std::string module_name = "module";
profiler.SetModuleName(module_name).SetTraceLevel(TraceEvent::Level::MODULE);
RecordKey key = std::make_pair("stream0", 100);
profiler.RecordEnd(key);
PipelineTrace trace = tracer.GetTrace(Time::min(), Time::max());
ASSERT_NE(trace.module_traces.find(module_name), trace.module_traces.end());
ASSERT_EQ(trace.module_traces[module_name].size(), 1);
ASSERT_NE(trace.module_traces[module_name].find(profiler_name), trace.module_traces[module_name].end());
ASSERT_EQ(trace.module_traces[module_name][profiler_name].size(), 1);
TraceElem elem = trace.module_traces[module_name][profiler_name][0];
EXPECT_EQ(elem.type, TraceEvent::Type::END);
EXPECT_EQ(elem.key, key);
}
TEST(CoreProcessProfiler, RecordStartPipeline) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
profiler.SetTraceLevel(TraceEvent::Level::PIPELINE);
RecordKey key = std::make_pair("stream0", 100);
profiler.RecordStart(key);
PipelineTrace trace = tracer.GetTrace(Time::min(), Time::max());
ASSERT_NE(trace.process_traces.find(profiler_name), trace.process_traces.end());
ASSERT_EQ(trace.process_traces[profiler_name].size(), 1);
TraceElem elem = trace.process_traces[profiler_name][0];
EXPECT_EQ(elem.type, TraceEvent::Type::START);
EXPECT_EQ(elem.key, key);
}
TEST(CoreProcessProfiler, RecordEndPipeline) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
profiler.SetTraceLevel(TraceEvent::Level::PIPELINE);
RecordKey key = std::make_pair("stream0", 100);
profiler.RecordEnd(key);
PipelineTrace trace = tracer.GetTrace(Time::min(), Time::max());
ASSERT_NE(trace.process_traces.find(profiler_name), trace.process_traces.end());
ASSERT_EQ(trace.process_traces[profiler_name].size(), 1);
TraceElem elem = trace.process_traces[profiler_name][0];
EXPECT_EQ(elem.type, TraceEvent::Type::END);
EXPECT_EQ(elem.key, key);
}
TEST(CoreProcessProfiler, RecordEndRecordEnd) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
profiler.SetTraceLevel(TraceEvent::Level::PIPELINE);
const std::string stream_name = "stream0";
RecordKey key = std::make_pair("stream0", 100);
profiler.RecordEnd(key);
profiler.RecordEnd(key);
ProcessProfile profile = profiler.GetProfile();
EXPECT_EQ(profile.completed, 2);
}
TEST(CoreProcessProfiler, DropData) {
static constexpr uint64_t kDEFAULT_MAX_DPB_SIZE = 16;
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
profiler.SetTraceLevel(TraceEvent::Level::PIPELINE);
const std::string stream_name = "stream0";
uint64_t dropped = 2;
uint64_t ts = 0;
for (; ts < dropped; ++ts) {
RecordKey key = std::make_pair(stream_name, ts);
profiler.RecordStart(key);
}
for (; ts < kDEFAULT_MAX_DPB_SIZE + dropped + 1; ++ts) {
RecordKey key = std::make_pair(stream_name, ts);
profiler.RecordStart(key);
profiler.RecordEnd(key);
}
ProcessProfile profile = profiler.GetProfile();
EXPECT_EQ(profile.dropped, dropped);
EXPECT_EQ(profile.completed, kDEFAULT_MAX_DPB_SIZE + 1);
EXPECT_EQ(profile.ongoing, 0);
EXPECT_EQ(profile.stream_profiles.size(), 1);
EXPECT_EQ(profile.stream_profiles[0].stream_name, stream_name);
EXPECT_EQ(profile.stream_profiles[0].dropped, dropped);
EXPECT_EQ(profile.stream_profiles[0].completed, kDEFAULT_MAX_DPB_SIZE + 1);
}
TEST(CoreProcessProfiler, GetProfile0) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
profiler.SetTraceLevel(TraceEvent::Level::PIPELINE);
const std::string stream_name = "stream0";
RecordKey key = std::make_pair("stream0", 100);
profiler.RecordEnd(key);
ProcessProfile profile = profiler.GetProfile();
EXPECT_EQ(profile.dropped, 0);
EXPECT_EQ(profile.completed, 1);
EXPECT_EQ(profile.ongoing, 0);
EXPECT_EQ(profile.stream_profiles.size(), 1);
EXPECT_EQ(profile.stream_profiles[0].completed, 1);
EXPECT_EQ(profile.stream_profiles[0].dropped, 0);
}
TEST(CoreProcessProfiler, GetProfile1) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
profiler.SetTraceLevel(TraceEvent::Level::PIPELINE);
const std::string stream_name = "stream0";
RecordKey key1 = std::make_pair(stream_name, 100);
RecordKey key2 = std::make_pair(stream_name, 200);
ProcessTrace trace;
TraceElem elem_start1;
elem_start1.key = key1;
elem_start1.time = Time(std::chrono::duration_cast<Time::duration>(std::chrono::duration<double, std::milli>(50)));
elem_start1.type = TraceEvent::Type::START;
TraceElem elem_start2;
elem_start2.key = key2;
elem_start2.time = Time(std::chrono::duration_cast<Time::duration>(std::chrono::duration<double, std::milli>(100)));
elem_start2.type = TraceEvent::Type::START;
TraceElem elem_end1;
elem_end1.key = key1;
elem_end1.time = Time(std::chrono::duration_cast<Time::duration>(std::chrono::duration<double, std::milli>(200)));
elem_end1.type = TraceEvent::Type::END;
TraceElem elem_end2;
elem_end2.key = key2;
elem_end2.time = Time(std::chrono::duration_cast<Time::duration>(std::chrono::duration<double, std::milli>(300)));
elem_end2.type = TraceEvent::Type::END;
trace.push_back(elem_start1);
trace.push_back(elem_start2);
trace.push_back(elem_end1);
trace.push_back(elem_end2);
ProcessProfile profile = profiler.GetProfile(trace);
EXPECT_EQ(profile.completed, 2);
EXPECT_EQ(profile.fps, 1e3 / 250 * 2);
EXPECT_EQ(profile.dropped, 0);
EXPECT_EQ(profile.latency, 175);
EXPECT_EQ(profile.minimum_latency, 150);
EXPECT_EQ(profile.maximum_latency, 200);
EXPECT_EQ(profile.ongoing, 0);
EXPECT_EQ(profile.process_name, profiler_name);
EXPECT_EQ(profile.stream_profiles.size(), 1);
EXPECT_EQ(profile.stream_profiles[0].stream_name, stream_name);
EXPECT_EQ(profile.stream_profiles[0].completed, 2);
EXPECT_EQ(profile.stream_profiles[0].dropped, 0);
EXPECT_EQ(profile.stream_profiles[0].fps, 1e3 / 250 * 2);
EXPECT_EQ(profile.stream_profiles[0].minimum_latency, 150);
EXPECT_EQ(profile.stream_profiles[0].maximum_latency, 200);
}
TEST(CoreProcessProfiler, OnStreamEos) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
profiler.SetTraceLevel(TraceEvent::Level::PIPELINE);
const std::string stream_name = "stream0";
RecordKey key = std::make_pair(stream_name, 100);
profiler.RecordStart(key);
profiler.RecordEnd(key);
EXPECT_EQ(profiler.GetProfile().stream_profiles.size(), 1);
profiler.OnStreamEos(stream_name);
EXPECT_EQ(profiler.GetProfile().stream_profiles.size(), 0);
}
TEST(CoreProcessProfiler, OnStreamEosBorderCase) {
PipelineTracer tracer;
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, &tracer);
profiler.SetTraceLevel(TraceEvent::Level::PIPELINE);
const std::string stream_name = "stream0";
EXPECT_EQ(profiler.GetProfile().stream_profiles.size(), 0);
profiler.OnStreamEos(stream_name);
EXPECT_EQ(profiler.GetProfile().stream_profiles.size(), 0);
}
TEST(CoreProcessProfiler, NullTracer) {
ProfilerConfig config;
config.enable_profiling = true;
config.enable_tracing = true;
const std::string profiler_name = "profiler";
ProcessProfiler profiler(config, profiler_name, nullptr);
RecordKey key = std::make_pair("stream0", 100);
profiler.RecordStart(key);
}
} // namespace cnstream
| 40.090343 | 118 | 0.749165 | HFauto |
74aefc16b404caa3326daf5ae556579f7c20d025 | 4,889 | hpp | C++ | rocprim/include/rocprim/device/detail/device_transform.hpp | lawruble13/rocPRIM | ebcbda559194ac20ca627f641e7657d3c8af4f20 | [
"MIT"
] | null | null | null | rocprim/include/rocprim/device/detail/device_transform.hpp | lawruble13/rocPRIM | ebcbda559194ac20ca627f641e7657d3c8af4f20 | [
"MIT"
] | null | null | null | rocprim/include/rocprim/device/detail/device_transform.hpp | lawruble13/rocPRIM | ebcbda559194ac20ca627f641e7657d3c8af4f20 | [
"MIT"
] | null | null | null | // Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef ROCPRIM_DEVICE_DETAIL_DEVICE_TRANSFORM_HPP_
#define ROCPRIM_DEVICE_DETAIL_DEVICE_TRANSFORM_HPP_
#include <type_traits>
#include <iterator>
#include "../../config.hpp"
#include "../../detail/various.hpp"
#include "../../detail/match_result_type.hpp"
#include "../../intrinsics.hpp"
#include "../../functional.hpp"
#include "../../types.hpp"
#include "../../block/block_load.hpp"
#include "../../block/block_store.hpp"
BEGIN_ROCPRIM_NAMESPACE
namespace detail
{
// Wrapper for unpacking tuple to be used with BinaryFunction.
// See transform function which accepts two input iterators.
template<class T1, class T2, class BinaryFunction>
struct unpack_binary_op
{
using result_type = typename ::rocprim::detail::invoke_result<BinaryFunction, T1, T2>::type;
ROCPRIM_HOST_DEVICE inline
unpack_binary_op() = default;
ROCPRIM_HOST_DEVICE inline
unpack_binary_op(BinaryFunction binary_op) : binary_op_(binary_op)
{
}
ROCPRIM_HOST_DEVICE inline
~unpack_binary_op() = default;
ROCPRIM_HOST_DEVICE inline
result_type operator()(const ::rocprim::tuple<T1, T2>& t)
{
return binary_op_(::rocprim::get<0>(t), ::rocprim::get<1>(t));
}
private:
BinaryFunction binary_op_;
};
template<
unsigned int BlockSize,
unsigned int ItemsPerThread,
class ResultType,
class InputIterator,
class OutputIterator,
class UnaryFunction
>
ROCPRIM_DEVICE inline
void transform_kernel_impl(InputIterator input,
const size_t input_size,
OutputIterator output,
UnaryFunction transform_op)
{
using input_type = typename std::iterator_traits<InputIterator>::value_type;
using output_type = typename std::iterator_traits<OutputIterator>::value_type;
using result_type =
typename std::conditional<
std::is_void<output_type>::value, ResultType, output_type
>::type;
constexpr unsigned int items_per_block = BlockSize * ItemsPerThread;
const unsigned int flat_id = ::rocprim::detail::block_thread_id<0>();
const unsigned int flat_block_id = ::rocprim::detail::block_id<0>();
const unsigned int block_offset = flat_block_id * items_per_block;
const unsigned int number_of_blocks = ::rocprim::detail::grid_size<0>();
const unsigned int valid_in_last_block = input_size - block_offset;
input_type input_values[ItemsPerThread];
result_type output_values[ItemsPerThread];
if(flat_block_id == (number_of_blocks - 1)) // last block
{
block_load_direct_striped<BlockSize>(
flat_id,
input + block_offset,
input_values,
valid_in_last_block
);
ROCPRIM_UNROLL
for(unsigned int i = 0; i < ItemsPerThread; i++)
{
if(BlockSize * i + flat_id < valid_in_last_block)
{
output_values[i] = transform_op(input_values[i]);
}
}
block_store_direct_striped<BlockSize>(
flat_id,
output + block_offset,
output_values,
valid_in_last_block
);
}
else
{
block_load_direct_striped<BlockSize>(
flat_id,
input + block_offset,
input_values
);
ROCPRIM_UNROLL
for(unsigned int i = 0; i < ItemsPerThread; i++)
{
output_values[i] = transform_op(input_values[i]);
}
block_store_direct_striped<BlockSize>(
flat_id,
output + block_offset,
output_values
);
}
}
} // end of detail namespace
END_ROCPRIM_NAMESPACE
#endif // ROCPRIM_DEVICE_DETAIL_DEVICE_TRANSFORM_HPP_
| 31.541935 | 96 | 0.67928 | lawruble13 |
74b06b638ef51ec6aeb3ceb5b7c319f69ef2b7f8 | 1,439 | cpp | C++ | 001_OpenGL_GLSL/main.cpp | Nitta-K-git/Qt_Samples2 | 27d118952763db0a3ea89f0c24714e6e9f6a347b | [
"MIT"
] | null | null | null | 001_OpenGL_GLSL/main.cpp | Nitta-K-git/Qt_Samples2 | 27d118952763db0a3ea89f0c24714e6e9f6a347b | [
"MIT"
] | null | null | null | 001_OpenGL_GLSL/main.cpp | Nitta-K-git/Qt_Samples2 | 27d118952763db0a3ea89f0c24714e6e9f6a347b | [
"MIT"
] | null | null | null | #include <iostream>
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QMatrix4x4>
#include <QMainWindow>
#include <QApplication>
class MyGLWidget : public QOpenGLWidget, protected QOpenGLFunctions{
public:
MyGLWidget(QWidget *parent) : QOpenGLWidget(parent) { }
QMatrix4x4 m_proj;
protected:
void initializeGL() override
{
// Set up the rendering context, load shaders and other resources, etc.:
initializeOpenGLFunctions();
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
}
void resizeGL(int w, int h) override
{
// Update projection matrix and other size related settings:
m_proj.setToIdentity();
m_proj.perspective(45.0f, w / float(h), 0.01f, 100.0f);
}
void paintGL() override
{
glClear(GL_COLOR_BUFFER_BIT);
}
};
class MainWindow : public QMainWindow{
Q_OBJECT
public:
MainWindow(){
QOpenGLWidget *widget = new QOpenGLWidget(this);
// QSurfaceFormat format;
// format.setDepthBufferSize(24);
// format.setStencilBufferSize(8);
// format.setVersion(3, 2);
// format.setProfile(QSurfaceFormat::CoreProfile);
// widget->setFormat(format); // must be called before the widget or its parent window gets shown
}
};
int main(int argc, char *argv[]){
QApplication app(argc, argv);
std::cout << "hello" << std::endl;
// MainWindow m;
// m.show();
return app.exec();
}
| 26.648148 | 99 | 0.656011 | Nitta-K-git |
74b5804be34a50f3fd7032bf5d3f30c5d7c250be | 7,178 | cpp | C++ | ares/component/processor/tlcs900h/registers.cpp | moon-chilled/Ares | 909fb098c292f8336d0502dc677050312d8b5c81 | [
"0BSD"
] | 7 | 2020-07-25T11:44:39.000Z | 2021-01-29T13:21:31.000Z | ares/component/processor/tlcs900h/registers.cpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | null | null | null | ares/component/processor/tlcs900h/registers.cpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | 1 | 2021-03-22T16:15:30.000Z | 2021-03-22T16:15:30.000Z | #define a RFP
#define p RFP - 1 & 3
template<> auto TLCS900H::map(Register<uint8> register) const -> maybe<uint8&> {
switch(register.id) {
#define r(id, name) case id: return r.name;
r(0x00, xwa[0].b.b0) r(0x01, xwa[0].b.b1) r(0x02, xwa[0].b.b2) r(0x03, xwa[0].b.b3)
r(0x04, xbc[0].b.b0) r(0x05, xbc[0].b.b1) r(0x06, xbc[0].b.b2) r(0x07, xbc[0].b.b3)
r(0x08, xde[0].b.b0) r(0x09, xde[0].b.b1) r(0x0a, xde[0].b.b2) r(0x0b, xde[0].b.b3)
r(0x0c, xhl[0].b.b0) r(0x0d, xhl[0].b.b1) r(0x0e, xhl[0].b.b2) r(0x0f, xhl[0].b.b3)
r(0x10, xwa[1].b.b0) r(0x11, xwa[1].b.b1) r(0x12, xwa[1].b.b2) r(0x13, xwa[1].b.b3)
r(0x14, xbc[1].b.b0) r(0x15, xbc[1].b.b1) r(0x16, xbc[1].b.b2) r(0x17, xbc[1].b.b3)
r(0x18, xde[1].b.b0) r(0x19, xde[1].b.b1) r(0x1a, xde[1].b.b2) r(0x1b, xde[1].b.b3)
r(0x1c, xhl[1].b.b0) r(0x1d, xhl[1].b.b1) r(0x1e, xhl[1].b.b2) r(0x1f, xhl[1].b.b3)
r(0x20, xwa[2].b.b0) r(0x21, xwa[2].b.b1) r(0x22, xwa[2].b.b2) r(0x23, xwa[2].b.b3)
r(0x24, xbc[2].b.b0) r(0x25, xbc[2].b.b1) r(0x26, xbc[2].b.b2) r(0x27, xbc[2].b.b3)
r(0x28, xde[2].b.b0) r(0x29, xde[2].b.b1) r(0x2a, xde[2].b.b2) r(0x2b, xde[2].b.b3)
r(0x2c, xhl[2].b.b0) r(0x2d, xhl[2].b.b1) r(0x2e, xhl[2].b.b2) r(0x2f, xhl[2].b.b3)
r(0x30, xwa[3].b.b0) r(0x31, xwa[3].b.b1) r(0x32, xwa[3].b.b2) r(0x33, xwa[3].b.b3)
r(0x34, xbc[3].b.b0) r(0x35, xbc[3].b.b1) r(0x36, xbc[3].b.b2) r(0x37, xbc[3].b.b3)
r(0x38, xde[3].b.b0) r(0x39, xde[3].b.b1) r(0x3a, xde[3].b.b2) r(0x3b, xde[3].b.b3)
r(0x3c, xhl[3].b.b0) r(0x3d, xhl[3].b.b1) r(0x3e, xhl[3].b.b2) r(0x3f, xhl[3].b.b3)
r(0xd0, xwa[p].b.b0) r(0xd1, xwa[p].b.b1) r(0xd2, xwa[p].b.b2) r(0xd3, xwa[p].b.b3)
r(0xd4, xbc[p].b.b0) r(0xd5, xbc[p].b.b1) r(0xd6, xbc[p].b.b2) r(0xd7, xbc[p].b.b3)
r(0xd8, xde[p].b.b0) r(0xd9, xde[p].b.b1) r(0xda, xde[p].b.b2) r(0xdb, xde[p].b.b3)
r(0xdc, xhl[p].b.b0) r(0xdd, xhl[p].b.b1) r(0xde, xhl[p].b.b2) r(0xdf, xhl[p].b.b3)
r(0xe0, xwa[a].b.b0) r(0xe1, xwa[a].b.b1) r(0xe2, xwa[a].b.b2) r(0xe3, xwa[a].b.b3)
r(0xe4, xbc[a].b.b0) r(0xe5, xbc[a].b.b1) r(0xe6, xbc[a].b.b2) r(0xe7, xbc[a].b.b3)
r(0xe8, xde[a].b.b0) r(0xe9, xde[a].b.b1) r(0xea, xde[a].b.b2) r(0xeb, xde[a].b.b3)
r(0xec, xhl[a].b.b0) r(0xed, xhl[a].b.b1) r(0xee, xhl[a].b.b2) r(0xef, xhl[a].b.b3)
r(0xf0, xix .b.b0) r(0xf1, xix .b.b1) r(0xf2, xix .b.b2) r(0xf3, xix .b.b3)
r(0xf4, xiy .b.b0) r(0xf5, xiy .b.b1) r(0xf6, xiy .b.b2) r(0xf7, xiy .b.b3)
r(0xf8, xiz .b.b0) r(0xf9, xiz .b.b1) r(0xfa, xiz .b.b2) r(0xfb, xiz .b.b3)
r(0xfc, xsp .b.b0) r(0xfd, xsp .b.b1) r(0xfe, xsp .b.b2) r(0xff, xsp .b.b3)
#undef r
}
return nothing;
}
template<> auto TLCS900H::map(Register<uint16> register) const -> maybe<uint16&> {
switch(register.id & ~1) {
#define r(id, name) case id: return r.name;
r(0x00, xwa[0].w.w0) r(0x02, xwa[0].w.w1) r(0x04, xbc[0].w.w0) r(0x06, xbc[0].w.w1)
r(0x08, xde[0].w.w0) r(0x0a, xde[0].w.w1) r(0x0c, xhl[0].w.w0) r(0x0e, xhl[0].w.w1)
r(0x10, xwa[1].w.w0) r(0x12, xwa[1].w.w1) r(0x14, xbc[1].w.w0) r(0x16, xbc[1].w.w1)
r(0x18, xde[1].w.w0) r(0x1a, xde[1].w.w1) r(0x1c, xhl[1].w.w0) r(0x1e, xhl[1].w.w1)
r(0x20, xwa[2].w.w0) r(0x22, xwa[2].w.w1) r(0x24, xbc[2].w.w0) r(0x26, xbc[2].w.w1)
r(0x28, xde[2].w.w0) r(0x2a, xde[2].w.w1) r(0x2c, xhl[2].w.w0) r(0x2e, xhl[2].w.w1)
r(0x30, xwa[3].w.w0) r(0x32, xwa[3].w.w1) r(0x34, xbc[3].w.w0) r(0x36, xbc[3].w.w1)
r(0x38, xde[3].w.w0) r(0x3a, xde[3].w.w1) r(0x3c, xhl[3].w.w0) r(0x3e, xhl[3].w.w1)
r(0xd0, xwa[p].w.w0) r(0xd2, xwa[p].w.w1) r(0xd4, xbc[p].w.w0) r(0xd6, xbc[p].w.w1)
r(0xd8, xde[p].w.w0) r(0xda, xde[p].w.w1) r(0xdc, xhl[p].w.w0) r(0xde, xhl[p].w.w1)
r(0xe0, xwa[a].w.w0) r(0xe2, xwa[a].w.w1) r(0xe4, xbc[a].w.w0) r(0xe6, xbc[a].w.w1)
r(0xe8, xde[a].w.w0) r(0xea, xde[a].w.w1) r(0xec, xhl[a].w.w0) r(0xee, xhl[a].w.w1)
r(0xf0, xix .w.w0) r(0xf2, xix .w.w1) r(0xf4, xiy .w.w0) r(0xf6, xiy .w.w1)
r(0xf8, xiz .w.w0) r(0xfa, xiz .w.w1) r(0xfc, xsp .w.w0) r(0xfe, xsp .w.w1)
#undef r
}
return nothing;
}
template<> auto TLCS900H::map(Register<uint32> register) const -> maybe<uint32&> {
switch(register.id & ~3) {
#define r(id, name) case id: return r.name;
r(0x00, xwa[0].l.l0) r(0x04, xbc[0].l.l0) r(0x08, xde[0].l.l0) r(0x0c, xhl[0].l.l0)
r(0x10, xwa[1].l.l0) r(0x14, xbc[1].l.l0) r(0x18, xde[1].l.l0) r(0x1c, xhl[1].l.l0)
r(0x20, xwa[2].l.l0) r(0x24, xbc[2].l.l0) r(0x28, xde[2].l.l0) r(0x2c, xhl[2].l.l0)
r(0x30, xwa[3].l.l0) r(0x34, xbc[3].l.l0) r(0x38, xde[3].l.l0) r(0x3c, xhl[3].l.l0)
r(0xd0, xwa[p].l.l0) r(0xd4, xbc[p].l.l0) r(0xd8, xde[p].l.l0) r(0xdc, xhl[p].l.l0)
r(0xe0, xwa[a].l.l0) r(0xe4, xbc[a].l.l0) r(0xe8, xde[a].l.l0) r(0xec, xhl[a].l.l0)
r(0xf0, xix .l.l0) r(0xf4, xiy .l.l0) r(0xf8, xiz .l.l0) r(0xfc, xsp .l.l0)
#undef r
}
return nothing;
}
#undef a
#undef p
template<> auto TLCS900H::load< uint8>(Register< uint8> register) const -> uint8 { return map(register)(Undefined); }
template<> auto TLCS900H::load<uint16>(Register<uint16> register) const -> uint16 { return map(register)(Undefined); }
template<> auto TLCS900H::load<uint32>(Register<uint32> register) const -> uint32 { return map(register)(Undefined); }
template<> auto TLCS900H::store< uint8>(Register< uint8> register, uint32 data) -> void { if(auto r = map(register)) r() = data; }
template<> auto TLCS900H::store<uint16>(Register<uint16> register, uint32 data) -> void { if(auto r = map(register)) r() = data; }
template<> auto TLCS900H::store<uint32>(Register<uint32> register, uint32 data) -> void { if(auto r = map(register)) r() = data; }
auto TLCS900H::expand(Register< uint8> register) const -> Register<uint16> { return {register.id & ~1}; }
auto TLCS900H::expand(Register<uint16> register) const -> Register<uint32> { return {register.id & ~3}; }
auto TLCS900H::shrink(Register<uint32> register) const -> Register<uint16> { return {register.id}; }
auto TLCS900H::shrink(Register<uint16> register) const -> Register< uint8> { return {register.id}; }
auto TLCS900H::load(FlagRegister f) const -> uint8 {
switch(f.id) {
case 0: return r.c << 0 | r.n << 1 | r.v << 2 | r.h << 4 | r.z << 6 | r.s << 7;
case 1: return r.cp << 0 | r.np << 1 | r.vp << 2 | r.hp << 4 | r.zp << 6 | r.sp << 7;
} unreachable;
}
auto TLCS900H::store(FlagRegister f, uint8 data) -> void {
switch(f.id) {
case 0: r.c = data.bit(0); r.n = data.bit(1); r.v = data.bit(2); r.h = data.bit(4); r.z = data.bit(6); r.s = data.bit(7); return;
case 1: r.cp = data.bit(0); r.np = data.bit(1); r.vp = data.bit(2); r.hp = data.bit(4); r.zp = data.bit(6); r.sp = data.bit(7); return;
} unreachable;
}
auto TLCS900H::load(StatusRegister) const -> uint16 {
//900/H: d10 = RFP2 (always 0); d11 = MAX (always 1); d15 = SYSM (always 1)
return load(F) | r.rfp << 8 | 0 << 10 | 1 << 11 | r.iff << 12 | 1 << 15;
}
auto TLCS900H::store(StatusRegister, uint16 data) -> void {
store(F, data.bit(0,7));
r.rfp = data.bit(8,9);
r.iff = data.bit(12,14);
}
auto TLCS900H::load(ProgramCounter) const -> uint32 {
return r.pc.l.l0;
}
auto TLCS900H::store(ProgramCounter, uint32 data) -> void {
r.pc.l.l0 = data;
invalidate();
}
| 56.519685 | 137 | 0.588604 | moon-chilled |
74b78241f3eb513bd3eddfd1ef58940dec286762 | 5,691 | cc | C++ | festus/runtime/g2p-lookup.cc | cibu/language-resources | a6158942286112b2808460b2cdbcb03260e8879b | [
"Apache-2.0"
] | 177 | 2019-05-31T17:58:29.000Z | 2022-03-27T11:24:00.000Z | festus/runtime/g2p-lookup.cc | cibu/language-resources | a6158942286112b2808460b2cdbcb03260e8879b | [
"Apache-2.0"
] | 21 | 2019-05-29T09:51:11.000Z | 2021-12-08T01:54:13.000Z | festus/runtime/g2p-lookup.cc | cibu/language-resources | a6158942286112b2808460b2cdbcb03260e8879b | [
"Apache-2.0"
] | 57 | 2015-09-28T12:05:27.000Z | 2019-05-15T05:44:50.000Z | // festus/runtime/g2p-lookup.cc
//
// 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.
//
// Copyright 2016 Google, Inc.
// Author: mjansche@google.com (Martin Jansche)
//
// \file
// Command-line interface for grapheme-to-phoneme (G2P) pronunciation lookup.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <fst/compat.h>
#include <fst/fstlib.h>
#include <fst/extensions/ngram/ngram-fst.h>
// NB: Non-standard include directive to facilitate stand-alone compilation.
#include "compact.h"
#include "g2p.h"
typedef fst::LogArc MyArc;
typedef festus::G2P<MyArc> MyG2P;
namespace {
// Typically the bytes_to_graphones and phonemes_to_graphones FSTs can be
// stored compactly with arcs represented as follows:
//
// - use 8 bits (255 possible values) for the input label (byte or phoneme);
// - use 10 bits (1023 possible values) for the output label (graphone);
// - no need to store weights, as these machines are typically unweighted;
// - use 14 bits (16383 possible values) for the target state of an arc.
//
// Register the corresponding compact FST type so that the generic Read()
// operation (in the body of ReadFst) can recognize and load such FSTs.
static fst::FstRegisterer<festus::Compact_8_10_0_14_Fst<MyArc>> compact_reg;
// The graphones_model FST is a backoff language model in OpenGrm format.
// Register the LOUDS-compressed FST representation here, for use with Read().
static fst::FstRegisterer<fst::NGramFst<MyArc>> ngram_reg;
inline std::unique_ptr<const MyG2P::Lattice> ReadFst(const string &path) {
// TODO: std::make_unique() in C++14.
return std::unique_ptr<const MyG2P::Lattice>(MyG2P::Lattice::Read(path));
}
} // namespace
static const char kUsage[] =
R"(Grapheme-to-phoneme (G2P) pronunciation lookup.
Reads orthographic words (one word per line) from a file or from stdin
and writes predicted pronunciations to stdout. The output on stdout is in
tab-separated value (TSV) format with the following four columns:
1. the orthographic word,
2. its pronunciation,
3. the marginal posterior probability of the pronunciation, and
4. the cumulative probability of the current and preceding pronunciations.
When multiple pronunciations are generated, they are output in decending order
of posterior probability.
The grapheme-to-phoneme model is specified by the three flags
--bytes_to_graphones, --graphone_model, and --phonemes_to_graphones
corresponding to the factorization of the model.
The flag --max_prons specifies the upper limit on the number of
pronunciations that will be generated for a given word.
The --real_pruning_threshold controls theta the amount of pruning that will be
applied to the marginal posterior lattice during decoding when max_prons > 1.
A hypotheses will be pruned away if its probability is less than theta times
the probability of the most likely hypothesis.
Usage:
g2p-lookup [--flags...] [WORDS_FILE]
)";
DEFINE_string(bytes_to_graphones, "", "Path to bytes_to_graphones FST");
DEFINE_string(graphone_model, "", "Path to graphone_model FST");
DEFINE_string(phonemes_to_graphones, "", "Path to phonemes_to_graphones FST");
DEFINE_int32(max_prons,
festus::G2POptions::kDefaultMaxProns,
"Maximal number of pronunciations per word");
DEFINE_double(real_pruning_threshold,
festus::G2POptions::kDefaultPruningThreshold,
"Real pruning threshold; a number between 0 (no pruning) and 1");
DEFINE_double(delta,
fst::kDelta,
"Convergence threshold for FST operations");
int main(int argc, char *argv[]) {
SET_FLAGS(kUsage, &argc, &argv, true);
auto bytes_to_graphones = ReadFst(FLAGS_bytes_to_graphones);
if (!bytes_to_graphones) return 2;
auto graphone_model = ReadFst(FLAGS_graphone_model);
if (!graphone_model) return 2;
auto phonemes_to_graphones = ReadFst(FLAGS_phonemes_to_graphones);
if (!phonemes_to_graphones) return 2;
MyG2P g2p;
g2p.SetBytesToGraphonesFst(std::move(bytes_to_graphones));
g2p.SetGraphoneModelFst(std::move(graphone_model));
g2p.SetPhonemesToGraphonesFst(std::move(phonemes_to_graphones));
festus::G2POptions options;
options.max_prons = FLAGS_max_prons;
options.real_pruning_threshold = FLAGS_real_pruning_threshold;
options.delta = FLAGS_delta;
festus::G2PResult result;
bool success = true;
for (string word; std::getline(std::cin, word); /*empty*/) {
if (g2p.Pronounce(word, &result, options)) {
VLOG(1) << result.num_hypotheses
<< " hypothes" << (result.num_hypotheses == 1 ? "is" : "es")
<< " searched";
auto num_prons = result.pronunciations.size();
VLOG(1) << num_prons
<< " pronunciation" << (num_prons == 1 ? "" : "s")
<< " found";
double cumul = 0;
for (const auto &p : result.pronunciations) {
cumul += p.second;
std::cout << word << "\t" << p.first << "\t" << p.second
<< "\t" << cumul << std::endl;
}
} else {
LOG(ERROR) << "No prounciations found for " << word
<< ": " << result.error;
success = false;
}
}
return success ? 0 : 1;
}
| 36.954545 | 79 | 0.714989 | cibu |
74b7e5b425d0c88a71b0626c2c79a0f217775019 | 1,372 | cc | C++ | uva/chapter_1/10683.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | uva/chapter_1/10683.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | uva/chapter_1/10683.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
using vi = vector<int>; using vvi = vector<vi>;
using ii = pair<int,int>; using vii = vector<ii>;
using l = long long; using vl = vector<l>; using vvl = vector<vl>;
using ll = pair<l,l>; using vll = vector<ll>; using vvll = vector<vll>;
using lu = unsigned long long;
using vb = vector<bool>; using vvb = vector<vb>;
using vd = vector<double>; using vvd = vector<vd>;
const int INF = numeric_limits<int>::max();
const double EPS = 1e-10;
const l e5 = 100000, e6 = 1000000, e7 = 10000000, e9 = 1000000000;
l strto24(string time) {
l h = stol(time.substr(0, 2).c_str());
l m = stol(time.substr(2, 2).c_str());
l s = stol(time.substr(4, 2).c_str());
l c = stol(time.substr(6, 2).c_str());
// cerr << h << " " << m << " " << s << " " << c << endl;
m += h * 60;
s += m * 60;
c += s * 100;
return c;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
string s;
while (cin >> s) {
l c = strto24(s);
l day = 24 * 60 * 60 * 100;
// part of the day = c / (24 * 60 * 60 * 100)
c *= 10;
l h = c / day;
c -= h * day;
c *= 100;
l m = c / day;
c -= m * day;
c *= 100;
l s = c / day;
c -= s * day;
c *= 100;
l cc = c / day;
cout << setfill('0') << h << setw(2) << m << setw(2) << s << setw(2) << cc << endl;
// cout << seconds << endl;
}
}
| 28 | 87 | 0.528426 | metaflow |
74c369ddc7b5d7bf8c7f8930f9f06e47dd89ba17 | 3,446 | cpp | C++ | CoreTests/STL/Test_Types_FileAddress.cpp | azhirnov/GraphicsGenFramework-modular | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | 12 | 2017-12-23T14:24:57.000Z | 2020-10-02T19:52:12.000Z | CoreTests/STL/Test_Types_FileAddress.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | CoreTests/STL/Test_Types_FileAddress.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#include "CoreTests/STL/Common.h"
using namespace GX_STL;
using namespace GX_STL::GXTypes;
using namespace GX_STL::GXMath;
extern void Test_Types_FileAddress ()
{
const String filename = "../11/../22/33\\44\\55.ab";
const String ext = FileAddress::GetExtension( filename ); TEST( ext == "ab" );
const String name = FileAddress::GetName( filename ); TEST( name == "55" );
const String path = FileAddress::GetPath( filename ); TEST( path == "../11/../22/33\\44" );
const String name_ext = FileAddress::GetNameAndExt( filename ); TEST( name_ext == "55.ab" );
const String ext1 = FileAddress::GetExtensions( "aa/bb.c.d" ); TEST( ext1 == "c.d" );
const String ext2 = FileAddress::GetExtensions( "bb.cx.d" ); TEST( ext2 == "cx.d" );
const String ext3 = FileAddress::GetExtension( "aabb" ); TEST( ext3 == "" );
const String ext4 = FileAddress::GetExtensions( "aabb" ); TEST( ext4 == "" );
const String ext5 = FileAddress::GetExtension( "." ); TEST( ext5 == "" );
const String ext6 = FileAddress::GetExtensions( "." ); TEST( ext6 == "" );
Array<StringCRef> path_arr;
FileAddress::DividePath( filename, path_arr );
TEST( path_arr.Count() == 7 );
TEST( path_arr[0] == ".." );
TEST( path_arr[1] == "11" );
TEST( path_arr[2] == ".." );
TEST( path_arr[3] == "22" );
TEST( path_arr[4] == "33" );
TEST( path_arr[5] == "44" );
TEST( path_arr[6] == "55.ab" );
String without_name = filename;
FileAddress::RemoveName( INOUT without_name );
TEST( without_name == "../11/../22/33\\44" );
String without_ext = filename;
FileAddress::RemoveExtension( INOUT without_ext );
TEST( without_ext == "../11/../22/33\\44\\55" );
String formated = filename;
FileAddress::FormatPath( INOUT formated );
TEST( formated == "../22/33/44/55.ab" );
formated = "aa/bb/../../../aa/bb/cc/dd";
FileAddress::FormatPath( INOUT formated );
TEST( formated == "../aa/bb/cc/dd" );
String left = filename;
FileAddress::RemoveDirectoriesFromLeft( INOUT left, 2 );
TEST( left == "../11" );
String right = filename;
FileAddress::RemoveDirectoriesFromRight( INOUT right, 2 );
TEST( right == "../11/../22/33" );
String dir_path = "path";
FileAddress::AddDirectoryToPath( INOUT dir_path, "dir" );
TEST( dir_path == "path/dir" );
dir_path = "/path/";
FileAddress::AddDirectoryToPath( INOUT dir_path, "/dir1/" );
FileAddress::AddDirectoryToPath( INOUT dir_path, "/dir2/" );
TEST( dir_path == "/path/dir1/dir2/" );
dir_path = "path";
FileAddress::AddBaseDirectoryToPath( INOUT dir_path, "dir" );
TEST( dir_path == "dir/path" );
dir_path = "/path/";
FileAddress::AddBaseDirectoryToPath( INOUT dir_path, "/dir1/" );
FileAddress::AddBaseDirectoryToPath( INOUT dir_path, "/dir2/" );
TEST( dir_path == "/dir2/dir1/path/" );
String name1 = name;
FileAddress::AddExtensionToName( INOUT name1, ".ext" ); TEST( name1 == name + ".ext" );
name1 = name + ".";
FileAddress::AddExtensionToName( INOUT name1, ".ext" ); TEST( name1 == name + ".ext" );
name1 = name;
FileAddress::AddExtensionToName( INOUT name1, "ext" ); TEST( name1 == name + ".ext" );
name1 = name + ".";
FileAddress::AddExtensionToName( INOUT name1, "ext" ); TEST( name1 == name + ".ext" );
String name2 = FileAddress::GetName( "../out/common" ); TEST( name2 == "common" );
String name3 = FileAddress::GetName( "../out/common" ); TEST( name3 == "common" );
}
| 36.659574 | 95 | 0.645386 | azhirnov |
74c48a9860bef86c65d69e148f84fd9d604b209a | 7,736 | cpp | C++ | isis/src/control/objs/ControlNetVitals/unitTest.cpp | robotprogrammer22/ISIS3 | 8a2ec4bb3c91969c81d75c681051a1fe77028788 | [
"CC0-1.0"
] | null | null | null | isis/src/control/objs/ControlNetVitals/unitTest.cpp | robotprogrammer22/ISIS3 | 8a2ec4bb3c91969c81d75c681051a1fe77028788 | [
"CC0-1.0"
] | null | null | null | isis/src/control/objs/ControlNetVitals/unitTest.cpp | robotprogrammer22/ISIS3 | 8a2ec4bb3c91969c81d75c681051a1fe77028788 | [
"CC0-1.0"
] | null | null | null | #include <string>
#include <iostream>
#include <QDebug>
#include <QString>
#include <QStringList>
#include "ControlNetVitals.h"
#include "FileName.h"
#include "IException.h"
#include "Preference.h"
using namespace Isis;
using namespace std;
/**
* Unit test for ControlNetVitals class
*
* @author 2018-06-18 Adam Goins
* @internal
* @history 2018-06-22 Kristin Berry - Upated after fix to numImagesBelowMeasureThreshold()
*/
int main() {
try {
Preference::Preferences(true);
qDebug() << "Testing Control Net Vitals" << endl;
qDebug() << "Loading Network";
QString testNetFile("$ISISTESTDATA/isis/src/control/unitTestData/unitTest_ControlNetVersioner_ProtoNetwork2_ProtoV0002.net");
ControlNet *testNet = new ControlNet(testNetFile);
qDebug() << "Calculating Network Vitals";
ControlNetVitals netVitals(testNet);
qDebug() << "Network ID:" << netVitals.getNetworkId();
qDebug() << "Network Status:" << netVitals.getStatus();
qDebug() << "Status Details:" << netVitals.getStatusDetails();
qDebug() << "Network has additional islands?" << (netVitals.hasIslands() ? "yes" : "no");
qDebug() << "Number of islands in network:" << netVitals.numIslands();
QList< QList<QString> > islandLists = netVitals.getIslands();
for (int islandIndex = 0; islandIndex < islandLists.size(); islandIndex++) {
QStringList islandSerials(islandLists[islandIndex]);
islandSerials.sort();
qDebug() << "Serials in island " << islandIndex;
foreach(QString serial, islandSerials) {
qDebug() << " " << serial;
}
}
int numImages = netVitals.numImages();
int numPoints = netVitals.numPoints();
int numMeasures = netVitals.numMeasures();
int numIgnored = netVitals.numIgnoredPoints();
int numFixed = netVitals.numFixedPoints();
int numFree = netVitals.numFreePoints();
int numLockedPoints = netVitals.numLockedPoints();
int numConstrained = netVitals.numConstrainedPoints();
int pointsWithoutMeasures = netVitals.numPointsBelowMeasureThreshold(1);
int pointsBelowMeasures = netVitals.numPointsBelowMeasureThreshold(3);
int imagesWithoutMeasures = netVitals.numImagesBelowMeasureThreshold(1);
int imagesBelowMeasures = netVitals.numImagesBelowMeasureThreshold(2);
int numImagesBelowHull = netVitals.numImagesBelowHullTolerance();
qDebug() << "Number of images in network:" << numImages;
qDebug() << "Number of points in network:" << numPoints;
qDebug() << "Number of measures in network:" << numMeasures;
qDebug() << "Number of ignored points in network:" << numIgnored;
qDebug() << "Number of editlocked points in network:" << numLockedPoints;
qDebug() << "Number of fixed points in network:" << numFixed;
qDebug() << "Number of constrained points in network:" << numConstrained;
qDebug() << "Number of free points in network:" << numFree;
qDebug() << "Number of points without measures:" << pointsWithoutMeasures;
qDebug() << "Number of points with less than 3 measures:" << pointsBelowMeasures;
qDebug() << "Number of images without measures:" << imagesWithoutMeasures;
qDebug() << "Number of images with less than 2 measures:" << imagesBelowMeasures;
qDebug() << "Number of images with less 75 percent hull coverage:" << numImagesBelowHull;
qDebug() << "Testing getters...";
assert(numImages == netVitals.getCubeSerials().size());
assert(numPoints == netVitals.getAllPoints().size());
assert(numIgnored == netVitals.getIgnoredPoints().size());
assert(numLockedPoints == netVitals.getLockedPoints().size());
assert(numFixed == netVitals.getFixedPoints().size());
assert(numConstrained == netVitals.getConstrainedPoints().size());
assert(numFree == netVitals.getFreePoints().size());
assert(pointsWithoutMeasures == netVitals.getPointsBelowMeasureThreshold(1).size());
assert(pointsBelowMeasures == netVitals.getPointsBelowMeasureThreshold(3).size());
assert(imagesWithoutMeasures == netVitals.getImagesBelowMeasureThreshold(1).size());
assert(imagesBelowMeasures == netVitals.getImagesBelowMeasureThreshold(2).size());
assert(numImagesBelowHull == netVitals.getImagesBelowHullTolerance().size());
qDebug() << "\nTesting signal/slots...";
ControlPoint *testPoint = new ControlPoint;
testPoint->SetEditLock(true);
testNet->AddPoint(testPoint);
numPoints++;
assert( netVitals.numPoints() == testNet->GetNumPoints() );
testPoint->SetEditLock(false);
qDebug() << "Setting type to Free...";
testPoint->SetType(ControlPoint::Free);
assert(netVitals.numFreePoints() == numFree + 1);
qDebug() << "Free points incremented correctly";
qDebug() << "Setting type to Constrained...";
testPoint->SetType(ControlPoint::Constrained);
assert(netVitals.numConstrainedPoints() == numConstrained + 1);
qDebug() << "Constrained points incremented correctly";
qDebug() << "Setting type to Fixed...";
testPoint->SetType(ControlPoint::Fixed);
assert(netVitals.numFixedPoints() == numFixed + 1);
qDebug() << "Fixed points incremented correctly";
qDebug() << "Locking the point...";
testPoint->SetEditLock(true);
assert(netVitals.numLockedPoints() == numLockedPoints + 1);
testPoint->SetEditLock(true);
assert(netVitals.numLockedPoints() == numLockedPoints + 1);
testPoint->SetEditLock(false);
assert(netVitals.numLockedPoints() == numLockedPoints);
testPoint->SetEditLock(false);
assert(netVitals.numLockedPoints() == numLockedPoints);
qDebug() << "Locking the point works appropriately.";
qDebug() << "Ignoring Point...";
testPoint->SetIgnored(true);
assert(netVitals.numIgnoredPoints() == numIgnored + 1);
qDebug() << "Number of Ignored Points increments correctly.";
assert(netVitals.numFixedPoints() == numFixed);
qDebug() << "Ignored point no longer contributes to it's point type statistic correctly.";
qDebug() << "Unignoring Point...";
testPoint->SetIgnored(false);
qDebug() << "Adding a measure...";
ControlMeasure *newMeasure = new ControlMeasure();
newMeasure->SetCubeSerialNumber("Hey.test");
testPoint->Add(newMeasure);
assert(netVitals.numMeasures() == numMeasures + 1);
qDebug() << "Measure added correctly.";
qDebug() << "Setting ignored...";
newMeasure->SetIgnored(true);
newMeasure->SetIgnored(true);
assert(testNet->GetNumValidMeasures() == numMeasures);
qDebug() << "Measure ignored correctly.";
newMeasure->SetIgnored(false);
newMeasure->SetIgnored(false);
qDebug() << "Deleting Measure...";
testPoint->Delete(newMeasure);
assert(netVitals.numMeasures() == numMeasures);
qDebug() << "Measure deleted correctly.";
qDebug() << "Deleting point...";
testPoint->SetEditLock(false);
testNet->DeletePoint(testPoint);
assert(netVitals.numPoints() == --numPoints);
qDebug() << "Point deleted correctly.";
qDebug() << "Adding dummy point...";
ControlPoint *newPoint = new ControlPoint;
testNet->AddPoint(newPoint);
assert(netVitals.numPoints() == ++numPoints);
qDebug() << "Deleting dummy point...";
newPoint->SetIgnored(true);
testNet->DeletePoint(newPoint);
assert(netVitals.numPoints() == --numPoints);
qDebug() << "Point deleted correctly";
qDebug() << "Swapping Control Net...";
ControlNet net;
testNet->swap(net);
assert(netVitals.numPoints() == 0);
qDebug() << "Net swapped correctly.";
delete testNet;
testNet = NULL;
}
catch(IException &e) {
qDebug() << "ControlNetVitals unit test failed!" << endl;
e.print();
}
}
| 39.269036 | 129 | 0.683299 | robotprogrammer22 |
74cb9c22d6bf4f20f239a8c94b290af86685859f | 1,078 | cpp | C++ | chapter02/2.5_Dealing_with_Types/2.5.2_The_auto_Type_Specifier.cpp | NorthFacing/step-by-c | bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3 | [
"MIT"
] | 9 | 2019-05-10T05:39:21.000Z | 2022-02-22T08:04:52.000Z | chapter02/2.5_Dealing_with_Types/2.5.2_The_auto_Type_Specifier.cpp | NorthFacing/step-by-c | bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3 | [
"MIT"
] | null | null | null | chapter02/2.5_Dealing_with_Types/2.5.2_The_auto_Type_Specifier.cpp | NorthFacing/step-by-c | bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3 | [
"MIT"
] | 6 | 2019-05-13T13:39:19.000Z | 2022-02-22T08:05:01.000Z | /**
* 2.5.2 auto 类型说明符
* @Author Bob
* @Eamil 0haizhu0@gmail.com
* @Date 2017/7/14
*/
int main() {
/**
* C++11 新标准引入了 auto 类型说明符,用它就能让编译器替我们去分析表达式所属的类型,
* 也就是让编译器通过初始值来推算变量的类型。显然,auto 定义的变量必须有初始值。
*/
auto item = 1 + 2; // item 初始化未 1与2 的和,因为 1和2 都是int型,所以item也是int类型
auto i = 0, *p = &i; // i 是整数,p是整形指针
// 复合类型、常量 和 auto
/**
* 首先,使用引用其实是使用引用的对象,特别是引用被当做初始值时,真正参与初始化的其实是引用对象的值。
* 此时编译器以引用对象的类型作为auto的类型:
*/
int k=0, &r = k;
auto a = r; // a 是一个整数(r是j的别名,而j是一个整数)
/**
* 其次,auto 会忽略顶层const,保留底层const。比如初始值是一个指向常量的指针:
*/
const int ci = i, &cr = ci;
auto b = ci; // b 是一个整数(ci的顶层const特性被忽略了)
auto c = cr; // c 是一个整数(cr是ci的别名,ci本身是一个顶层const)
auto d = &i; // d 是一个整形指针(整数的地址就是指向整数的指针)
auto e = &ci; // e 是一个指向整数常量的指针(对常量对象取地址是一种底层const)
/**
* 如果希望推断出的类型是一个顶层const,则需要明确指出:
*/
const auto f = ci; // ci的推演类型是int,f是 const int
/**
* 还可以将引用的类型设为auto,此时原来的初始化规则仍然使用
*/
auto &g = ci; // g 是一个整形常量引用,绑定到ci
// auto &h = 42; // 错误:不能为非常量引用绑定字面值
const auto &j = 42; // 可以为常量引用绑定字面值
return 0;
}
| 23.434783 | 68 | 0.613173 | NorthFacing |
74cde53b5ebac6ea9f29daf67aae078b07bdf8bb | 2,869 | cpp | C++ | src/main.cpp | arihantdaga/wifi-dimmer | ba557fef52d3cccda9732538eb6fa38f0766fe50 | [
"MIT"
] | null | null | null | src/main.cpp | arihantdaga/wifi-dimmer | ba557fef52d3cccda9732538eb6fa38f0766fe50 | [
"MIT"
] | null | null | null | src/main.cpp | arihantdaga/wifi-dimmer | ba557fef52d3cccda9732538eb6fa38f0766fe50 | [
"MIT"
] | null | null | null | #include "button.hpp"
#include "config.hpp"
#include "dimmer.hpp"
// #include "encoder.hpp"
#include <Arduino.h>
#include <Embedis.h>
void onRotate(int8_t);
void onClick();
Button button;
unsigned long secondElapsed = millis();
unsigned long fakeFreq = millis();
Embedis embedis(Serial);
void setup() {
delay(2000);
Serial.begin(115200);
Serial.println("\nBooting");
Serial.println(US_TO_RTC_TIMER_TICKS(65));
dimmer::setup();
// encoder::setup(ENCODER_PINA, ENCODER_PINB, onRotate);
button.setup(ButtonType::pulldown, BUTTON_PIN, onClick);
Serial.println("Ready");
// Add pinMode command to mirror Arduino's
Embedis::command( F("dim"), [](Embedis* e) {
if (e->argc != 3) return e->response(Embedis::ARGS_ERROR);
int pin = String(e->argv[1]).toInt();
int val = String(e->argv[2]).toInt();
onRotate(val);
// String argv3(e->argv[2]);
// argv3.toUpperCase();
// int mode;
// if (argv3 == "INPUT") mode = INPUT;
// else if (argv3 == "OUTPUT") mode = OUTPUT;
// else if (argv3 == "INPUT_PULLUP") mode = INPUT_PULLUP;
// else return e->response(Embedis::ARGS_ERROR);
// pinMode(pin, mode);
// e->response(Embedis::OK);
});
Embedis::command( F("toggle"), [](Embedis* e) {
// if (e->argc != 3) return e->response(Embedis::ARGS_ERROR);
// int pin = String(e->argv[1]).toInt();
// int val = String(e->argv[2]).toInt();
onClick();
// String argv3(e->argv[2]);
// argv3.toUpperCase();
// int mode;
// if (argv3 == "INPUT") mode = INPUT;
// else if (argv3 == "OUTPUT") mode = OUTPUT;
// else if (argv3 == "INPUT_PULLUP") mode = INPUT_PULLUP;
// else return e->response(Embedis::ARGS_ERROR);
// pinMode(pin, mode);
// e->response(Embedis::OK);
});
}
void loop() {
// encoder::handle();
button.handle();
// if (millis() - fakeFreq >= 10) {
// fakeFreq = millis(); // reset timer
// dimmer::zeroCrossed();
// }
if (millis() - secondElapsed >= 1000) {
secondElapsed = millis(); // reset timer
Serial.printf("power: %s; brightness: %d; cross count: %d; low count: %d; timer interrupt count: %d; max "
"interrupt count: %d\n",
dimmer::powerOn ? "on" : "off", dimmer::brightness, dimmer::debugCrossCount, dimmer::debugLowCount,
dimmer::debugTimerInterrupt, dimmer::maxInterruptCount);
dimmer::debugCrossCount = 0;
dimmer::debugLowCount = 0;
dimmer::debugTimerInterrupt = 0;
dimmer::maxInterruptCount = 0;
}
embedis.process();
}
void onRotate(int8_t position) {
dimmer::setBrightness(position * 1);
// Serial.println(position);
}
void onClick() { dimmer::togglePower(); }
| 31.877778 | 114 | 0.577553 | arihantdaga |
74ce5c8dfef81c16fb2409634e82a88081b7d993 | 9,880 | cc | C++ | _cxx/envoy/test/extensions/common/sqlutils/sqlutils_test.cc | Asher-Wang/ambassador | 393a52832d081e0d8d0e0ecd5a14cfe18c62b837 | [
"Apache-2.0"
] | 3 | 2020-06-04T03:26:32.000Z | 2020-06-04T03:26:45.000Z | _cxx/envoy/test/extensions/common/sqlutils/sqlutils_test.cc | Asher-Wang/ambassador | 393a52832d081e0d8d0e0ecd5a14cfe18c62b837 | [
"Apache-2.0"
] | 1 | 2020-10-30T03:55:32.000Z | 2020-10-30T03:55:32.000Z | _cxx/envoy/test/extensions/common/sqlutils/sqlutils_test.cc | Asher-Wang/ambassador | 393a52832d081e0d8d0e0ecd5a14cfe18c62b837 | [
"Apache-2.0"
] | 1 | 2021-03-13T05:25:47.000Z | 2021-03-13T05:25:47.000Z | #include "extensions/common/sqlutils/sqlutils.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Extensions {
namespace Common {
namespace SQLUtils {
// MetadataFromSQLTest class is used for parameterized tests.
// The values in the tests are:
// std::string - SQL query
// bool - whether to expect SQL parsing to be successful
// std::map<std::string, std::list<std::string>> map of expected tables accessed based on the query.
// The map is checked only when parsing was successful. Map is indexed by table name and points to
// list of operations performed on the table. For example table1: "select", "insert" says that there
// was SELECT and INSERT operations on table1.
class MetadataFromSQLTest
: public ::testing::TestWithParam<
std::tuple<std::string, bool, std::map<std::string, std::list<std::string>>>> {};
// Test takes SQL query as a parameter and checks if the parsing
// produces the correct metadata.
// Metadata is 2-level structure. First layer is list of resources
// over which the SQL query operates: in our case is list of tables.
// Under each table there is secondary list which contains operations performed
// on the table, like "select", "insert", etc.
TEST_P(MetadataFromSQLTest, ParsingAndMetadataTest) {
// Get the SQL query
const std::string& query = std::get<0>(GetParam());
// vector of queries to check.
std::vector<std::string> test_queries;
test_queries.push_back(query);
// Create uppercase and lowercase versions of the queries and put
// them into vector of queries to check
test_queries.push_back(absl::AsciiStrToLower(query));
test_queries.push_back(absl::AsciiStrToUpper(query));
while (!test_queries.empty()) {
std::string test_query = test_queries.back();
ProtobufWkt::Struct metadata;
// Check if the parsing result is what expected.
ASSERT_EQ(std::get<1>(GetParam()), SQLUtils::setMetadata(test_query, metadata));
// If parsing was expected to fail do not check parsing values.
if (!std::get<1>(GetParam())) {
return;
}
// Access metadata fields, where parsing results are stored.
auto& fields = *metadata.mutable_fields();
// Get the names of resources which SQL query operates on.
std::map<std::string, std::list<std::string>> expected_tables = std::get<2>(GetParam());
// Check if query results return the same number of resources as expected.
ASSERT_EQ(expected_tables.size(), fields.size());
for (const auto& i : fields) {
// Get from created metadata the list of operations on the resource
const auto& operations = i;
std::string table_name = operations.first;
std::transform(table_name.begin(), table_name.end(), table_name.begin(),
[](unsigned char c) { return std::tolower(c); });
// Get the list of expected operations on the same resource from test param.
const auto& table_name_it = expected_tables.find(table_name);
// Make sure that a resource (table) found in metadata is expected.
ASSERT_NE(expected_tables.end(), table_name_it);
auto& operations_list = table_name_it->second;
// The number of expected operations and created in metadata must be the same.
ASSERT_EQ(operations_list.size(), operations.second.list_value().values().size());
// Now iterate over the operations list found in metadata and check if the same operation
// is listed as expected in test param.
for (const auto& j : operations.second.list_value().values()) {
// Find that operation in test params.
const auto operation_it =
std::find(operations_list.begin(), operations_list.end(), j.string_value());
ASSERT_NE(operations_list.end(), operation_it);
// Erase the operation. At the end of the test this list should be empty what means
// that we found all expected operations.
operations_list.erase(operation_it);
}
// Make sure that we went through all expected operations.
ASSERT_TRUE(operations_list.empty());
// Remove the table from the list. At the end of the test this list must be empty.
expected_tables.erase(table_name_it);
}
ASSERT_TRUE(expected_tables.empty());
test_queries.pop_back();
}
}
// Note: This parameterized test's queries are converted to all lowercase and all uppercase
// to validate that parser is case-insensitive. The test routine converts to uppercase and
// lowercase entire query string, not only SQL keywords. This introduces a problem when comparing
// tables' names when verifying parsing result. Therefore the test converts table names to lowercase
// before comparing. It however requires that all table names in the queries below use lowercase
// only.
#define TEST_VALUE(...) \
std::tuple<std::string, bool, std::map<std::string, std::list<std::string>>> { __VA_ARGS__ }
INSTANTIATE_TEST_SUITE_P(
SQLUtilsTestSuite, MetadataFromSQLTest,
::testing::Values(
TEST_VALUE("blahblah;", false, {}),
TEST_VALUE("CREATE TABLE IF NOT EXISTS table1(Usr VARCHAR(40),Count INT);", true,
{{"table1", {"create"}}}),
TEST_VALUE("CREATE TABLE IF NOT EXISTS `table number 1`(Usr VARCHAR(40),Count INT);", true,
{{"table number 1", {"create"}}}),
TEST_VALUE(
"CREATE TABLE IF NOT EXISTS table1(Usr VARCHAR(40),Count INT); SELECT * from table1;",
true, {{"table1", {"select", "create"}}}),
TEST_VALUE(
"CREATE TABLE IF NOT EXISTS table1(Usr VARCHAR(40),Count INT); SELECT * from table2;",
true, {{"table1", {"create"}}, {"table2", {"select"}}}),
TEST_VALUE("CREATE TABLE table1(Usr VARCHAR(40),Count INT);", true,
{{"table1", {"create"}}}),
TEST_VALUE("CREATE TABLE;", false, {}),
TEST_VALUE("CREATE TEMPORARY table table1(Usr VARCHAR(40),Count INT);", true,
{{"table1", {"create"}}}),
TEST_VALUE("DROP TABLE IF EXISTS table1", true, {{"table1", {"drop"}}}),
TEST_VALUE("ALTER TABLE table1 add column Id varchar (20);", true, {{"table1", {"alter"}}}),
TEST_VALUE("INSERT INTO table1 (Usr, Count) VALUES ('allsp2', 3);", true,
{{"table1", {"insert"}}}),
TEST_VALUE("INSERT LOW_PRIORITY INTO table1 (Usr, Count) VALUES ('allsp2', 3);", true,
{{"table1", {"insert"}}}),
TEST_VALUE("INSERT IGNORE INTO table1 (Usr, Count) VALUES ('allsp2', 3);", true,
{{"table1", {"insert"}}}),
TEST_VALUE("INSERT INTO table1 (Usr, Count) VALUES ('allsp2', 3);SELECT * from table1",
true, {{"table1", {"insert", "select"}}}),
TEST_VALUE("DELETE FROM table1 WHERE Count > 3;", true, {{"table1", {"delete"}}}),
TEST_VALUE("DELETE LOW_PRIORITY FROM table1 WHERE Count > 3;", true,
{{"table1", {"delete"}}}),
TEST_VALUE("DELETE QUICK FROM table1 WHERE Count > 3;", true, {{"table1", {"delete"}}}),
TEST_VALUE("DELETE IGNORE FROM table1 WHERE Count > 3;", true, {{"table1", {"delete"}}}),
TEST_VALUE("SELECT * FROM table1 WHERE Count = 1;", true, {{"table1", {"select"}}}),
TEST_VALUE("SELECT * FROM table1 WHERE Count = 1;", true, {{"table1", {"select"}}}),
TEST_VALUE("SELECT product.category FROM table1 WHERE Count = 1;", true,
{{"table1", {"select"}}, {"product", {"unknown"}}}),
TEST_VALUE("SELECT DISTINCT Usr FROM table1;", true, {{"table1", {"select"}}}),
TEST_VALUE("SELECT Usr, Count FROM table1 ORDER BY Count DESC;", true,
{{"table1", {"select"}}}),
TEST_VALUE("SELECT 12 AS a, a FROM table1 GROUP BY a;", true, {{"table1", {"select"}}}),
TEST_VALUE("SELECT;", false, {}), TEST_VALUE("SELECT Usr, Count FROM;", false, {}),
TEST_VALUE("INSERT INTO table1 SELECT * FROM table2;", true,
{{"table1", {"insert"}}, {"table2", {"select"}}}),
TEST_VALUE("INSERT INTO table1 SELECT tbl_temp1.fld_order_id FROM table2;", true,
{{"tbl_temp1", {"unknown"}}, {"table2", {"select"}}, {"table1", {"insert"}}}),
TEST_VALUE("UPDATE table1 SET col1 = col1 + 1", true, {{"table1", {"update"}}}),
TEST_VALUE("UPDATE LOW_PRIORITY table1 SET col1 = col1 + 1", true,
{{"table1", {"update"}}}),
TEST_VALUE("UPDATE IGNORE table1 SET col1 = col1 + 1", true, {{"table1", {"update"}}}),
TEST_VALUE("UPDATE table1 SET column1=(SELECT * columnX from table2);", true,
{{"table1", {"update"}}, {"table2", {"select"}}}),
// operations on database should not create any metadata
TEST_VALUE("CREATE DATABASE testdb;", true, {}),
TEST_VALUE("CREATE DATABASE IF NOT EXISTS testdb;", true, {}),
TEST_VALUE("ALTER DATABASE testdb CHARACTER SET charset_name;", true, {}),
TEST_VALUE("ALTER DATABASE testdb default CHARACTER SET charset_name;", true, {}),
TEST_VALUE("ALTER DATABASE testdb default CHARACTER SET = charset_name;", true, {}),
TEST_VALUE("ALTER SCHEMA testdb default CHARACTER SET = charset_name;", true, {}),
// The following DROP DATABASE tests should not produce metadata.
TEST_VALUE("DROP DATABASE testdb;", true, {}),
TEST_VALUE("DROP DATABASE IF EXISTS testdb;", true, {}),
// Schema. Should be parsed fine, but should not produce any metadata
TEST_VALUE("SHOW databases;", true, {}), TEST_VALUE("SHOW tables;", true, {}),
TEST_VALUE("SELECT * FROM;", false, {}),
TEST_VALUE("SELECT 1 FROM tabletest1;", true, {{"tabletest1", {"select"}}})
));
} // namespace SQLUtils
} // namespace Common
} // namespace Extensions
} // namespace Envoy
| 53.989071 | 100 | 0.637955 | Asher-Wang |
74d12ac16006cf6e7da5d9fc77911a07d658cbe6 | 724 | cpp | C++ | convert_24h_to_12h/convert_24h_to_12h.cpp | BjornChrisnach/Introduction_to_Programming_in_C_plusplus | 57b96b0f99cb486276181474e333c3b09d21a749 | [
"MIT"
] | null | null | null | convert_24h_to_12h/convert_24h_to_12h.cpp | BjornChrisnach/Introduction_to_Programming_in_C_plusplus | 57b96b0f99cb486276181474e333c3b09d21a749 | [
"MIT"
] | null | null | null | convert_24h_to_12h/convert_24h_to_12h.cpp | BjornChrisnach/Introduction_to_Programming_in_C_plusplus | 57b96b0f99cb486276181474e333c3b09d21a749 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main() {
int hour24, minutes24;
int hour12, minutes12;
string period;
char temp;
cout<<"Please enter a time in 24 hour format:"<<endl;
cin>>hour24>>temp>>minutes24;
minutes12 = minutes24;
if(hour24 >= 0 && hour24 <= 11){
period = "am";
if(hour24 == 0){
hour12 = 12;
}
else {
hour12 = hour24;
}
}
else {
period = "pm";
if(hour24 == 12){
hour12 = 12;
}
else {
hour12 = hour24 -12;
}
}
cout<<hour24<<":"<<minutes24<<" is "<<hour12<<":"<<minutes12<<" "<<period<<endl;
return 0;
} | 19.052632 | 84 | 0.476519 | BjornChrisnach |
74d1aaccc9a259ea9b1a58713da86edeca842cc6 | 4,924 | cc | C++ | OpenPEARL/openpearl-code/runtime/common/Duration.cc | BenniN/OpenPEARLThesis | d7db83b0ea15b7ba0f6244d918432c830ddcd697 | [
"Apache-2.0"
] | 1 | 2020-09-15T07:26:00.000Z | 2020-09-15T07:26:00.000Z | OpenPEARL/openpearl-code/runtime/common/Duration.cc | BenniN/OpenPEARLThesis | d7db83b0ea15b7ba0f6244d918432c830ddcd697 | [
"Apache-2.0"
] | null | null | null | OpenPEARL/openpearl-code/runtime/common/Duration.cc | BenniN/OpenPEARLThesis | d7db83b0ea15b7ba0f6244d918432c830ddcd697 | [
"Apache-2.0"
] | null | null | null | /*
[The "BSD license"]
Copyright (c) 2012-2014 Rainer Mueller
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
\file
\brief operation for the data type DURATION
\author R. Mueller
*/
#include "Duration.h"
#include "Signals.h"
using namespace std;
namespace pearlrt {
Fixed63 Duration::get() const {
return intval;
}
Duration::Duration() {
intval = (Fixed63::Fixed63_t)0;
}
int64_t Duration::getSec() const {
int64_t sec;
sec = intval.get() / 1000000LL;
return (sec);
}
int Duration::getUsec() const {
int usec;
usec = intval.get() % 1000000LL;
return (usec);
}
Duration::Duration(const int64_t sec, const int us, const int sign) {
intval = Fixed63(sec);
intval *= 1000000;
intval += us;
if (sign != 1 && sign != -1) {
Log::error("Duration illegal sign");
throw theInternalDatatypeSignal;
}
intval *= sign;
}
Duration& Duration::operator+=(const Duration& rhs) {
try {
intval += rhs.intval;
} catch (ArithmeticOverflowSignal &s) {
throw theDurationRangeSignal;
} catch (ArithmeticUnderflowSignal &s) {
throw theDurationRangeSignal;
}
return (*this);
}
Duration Duration::operator+(const Duration& rhs) const {
return Duration(*this) += rhs;
}
Duration& Duration::operator-=(const Duration& rhs) {
try {
intval -= rhs.intval;
} catch (ArithmeticOverflowSignal &s) {
throw theDurationRangeSignal;
} catch (ArithmeticUnderflowSignal &s) {
throw theDurationRangeSignal;
}
return (*this);
}
Duration Duration::operator-(const Duration& rhs) const {
return Duration(*this) -= rhs;
}
Duration Duration::operator-() const {
return Duration(Duration(0,0) - (*this));
}
Float<23> Duration::operator/=(const Duration& rhs) {
if (rhs.intval.get() == 0) {
throw theDurationDivideByZeroSignal;
}
Float<23> result(intval.get());
result = result / Float<23>(rhs.intval.get());
return result;
}
Float<23> Duration::operator/(const Duration& rhs) const {
return Duration(*this) /= rhs;
}
int Duration::compare(const Duration& rhs) const {
return intval.compare(rhs.intval);
}
BitString<1> Duration::operator==(const Duration& rhs) const {
return BitString<1>(intval.compare(rhs.intval) == 0);
}
BitString<1> Duration::operator!=(const Duration& rhs) const {
return BitString<1>(intval.compare(rhs.intval) != 0);
}
BitString<1> Duration::operator<(const Duration& rhs) const {
return BitString<1>(intval.compare(rhs.intval) < 0);
}
BitString<1> Duration::operator>(const Duration& rhs) const {
return BitString<1>(intval.compare(rhs.intval) > 0);
}
BitString<1> Duration::operator<=(const Duration& rhs) const {
return BitString<1>(intval.compare(rhs.intval) <= 0);
}
BitString<1> Duration::operator>=(const Duration& rhs) const {
return BitString<1>(intval.compare(rhs.intval) >= 0);
}
Duration Duration::abs() const {
if (intval.compare(Fixed63::Fixed63_t(0)) < 0) {
return -(*this);
} else {
return (*this);
}
}
Fixed<1> Duration::sign() const {
int ret = intval.compare(Fixed63::Fixed63_t(0));
if (ret < 0) {
return Fixed<1>(-1);
} else if (ret == 0) {
return Fixed<1>(0);
} else {
return Fixed<1>(1);
}
}
}
| 26.76087 | 74 | 0.647035 | BenniN |