added
stringdate
2024-11-18 17:54:19
2024-11-19 03:39:31
created
timestamp[s]date
1970-01-01 00:04:39
2023-09-06 04:41:57
id
stringlengths
40
40
metadata
dict
source
stringclasses
1 value
text
stringlengths
13
8.04M
score
float64
2
4.78
int_score
int64
2
5
2024-11-18T21:05:53.168170+00:00
2023-06-24T06:46:07
9a9a05f42044d4519fd751dafd67e81607818b73
{ "blob_id": "9a9a05f42044d4519fd751dafd67e81607818b73", "branch_name": "refs/heads/master", "committer_date": "2023-06-24T06:46:07", "content_id": "a4b4ab16bb2c68890c90d18b0148ff1532ebfdd3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "afab28c434b80486496d56c995bae5d77937c656", "extension": "c", "filename": "mq_posix.c", "fork_events_count": 0, "gha_created_at": "2018-09-23T13:41:33", "gha_event_created_at": "2023-02-25T07:52:20", "gha_language": "Go", "gha_license_id": "Apache-2.0", "github_id": 149988025, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3218, "license": "Apache-2.0", "license_type": "permissive", "path": "/c/mq_posix.c", "provenance": "stackv2-0083.json.gz:3133", "repo_name": "harveywangdao/earth", "revision_date": "2023-06-24T06:46:07", "revision_id": "c90d892fbd3e3b40bb1c2bda7c3521f5fe8a09ea", "snapshot_id": "938c2c0d7fa049a56d0b066d3ca3bc2f73b27644", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/harveywangdao/earth/c90d892fbd3e3b40bb1c2bda7c3521f5fe8a09ea/c/mq_posix.c", "visit_date": "2023-07-08T09:27:59.556500" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/sem.h> #include <sys/shm.h> #include <sys/mman.h> #include <mqueue.h> #include <signal.h> //gcc -o app mq_posix.c -lrt #define MQ_NAME "/bigspoon" /*union sigval { int sival_int; void *sival_ptr; }*/ typedef void (*sighandler)(int); static void handler(int no) { printf("no = %d\n", no); printf("SIGABRT = %d\n", SIGABRT); printf("SIGALRM = %d\n", SIGALRM); printf("SIGINT = %d\n", SIGINT); printf("SIGUSR1 = %d\n", SIGUSR1); } void do1() { int ret = 0; struct mq_attr attr; attr.mq_maxmsg = 10; attr.mq_msgsize = 32; mqd_t fd = mq_open(MQ_NAME, O_RDWR|O_CREAT|O_EXCL, 0666, &attr); if (fd == -1) { printf("mq_open fail\n"); return; } ret = mq_getattr(fd, &attr); if (ret == -1) { printf("mq_getattr fail\n"); return; } printf("%ld %ld %ld %ld\n", attr.mq_flags, attr.mq_maxmsg, attr.mq_msgsize, attr.mq_curmsgs); struct mq_attr oattr; attr.mq_flags = 0; ret = mq_setattr(fd, &attr, &oattr); if (ret == -1) { printf("mq_setattr fail\n"); return; } printf("%ld %ld %ld %ld\n", oattr.mq_flags, oattr.mq_maxmsg, oattr.mq_msgsize, oattr.mq_curmsgs); pid_t pid; pid = fork(); if (pid == -1) { printf("fork fail\n"); return; } else if (pid == 0) { printf("son start, pid = %d, ppid = %d\n", getpid(), getppid()); sighandler sig; sig = signal(SIGUSR1, handler); if (sig == SIG_ERR) { perror("signal fail"); exit(0); } struct sigevent sigeve; sigeve.sigev_notify = SIGEV_SIGNAL;//SIGEV_NONE SIGEV_THREAD sigeve.sigev_signo = SIGUSR1; sigeve.sigev_value.sival_ptr = NULL; sigeve.sigev_notify_function = NULL; sigeve.sigev_notify_attributes = NULL; ret = mq_notify(fd, &sigeve); if (ret == -1) { printf("mq_notify fail\n"); exit(0); } sleep(2); char *str = "hello mq"; ret = mq_send(fd, str, strlen(str)+1, 1);//MQ_PRIO_MAX if (ret == -1) { printf("mq_send fail\n"); exit(0); } ret = mq_close(fd); if (ret == -1) { printf("mq_close fail\n"); return; } printf("son end, pid = %d, ppid = %d\n", getpid(), getppid()); exit(0); } else { char buf[32]; unsigned int prio = 1; printf("mq_receive wait\n"); ret = mq_receive(fd, buf, sizeof(buf), &prio);//MQ_PRIO_MAX if (ret == -1) { printf("mq_receive fail\n"); return; } printf("mq_receive buf:%s\n", buf); ret = mq_close(fd); if (ret == -1) { printf("mq_close fail\n"); return; } ret = mq_unlink(MQ_NAME); if (ret == -1) { printf("mq_unlink fail\n"); return; } int status = 0; ret = waitpid(pid, &status, 0); if (ret == -1) { printf("son ret = %d, status = %d\n", ret, status); return; } printf("son ret = %d, status = %d\n", ret, status); } } int main(int argc, char const *argv[]) { do1(); return 0; }
2.484375
2
2024-11-18T21:05:53.522087+00:00
2023-08-13T07:00:15
cf627fd3850c232a964fd76a0b26974077f042b3
{ "blob_id": "cf627fd3850c232a964fd76a0b26974077f042b3", "branch_name": "refs/heads/master", "committer_date": "2023-08-13T07:00:15", "content_id": "2d9447dcb75d2250e42f78fbb7775abd97544235", "detected_licenses": [ "MIT" ], "directory_id": "2266eb133fc3121daf0aa7f4560626b46b94afe0", "extension": "c", "filename": "sroad4.c", "fork_events_count": 49, "gha_created_at": "2017-11-28T03:05:14", "gha_event_created_at": "2023-02-01T03:42:14", "gha_language": "C", "gha_license_id": "MIT", "github_id": 112278568, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 654, "license": "MIT", "license_type": "permissive", "path": "/d/village/sroad4.c", "provenance": "stackv2-0083.json.gz:3261", "repo_name": "oiuv/mud", "revision_date": "2023-08-13T07:00:15", "revision_id": "e9ff076724472256b9b4bd88c148d6bf71dc3c02", "snapshot_id": "6fbabebc7b784279fdfae06d164f5aecaa44ad90", "src_encoding": "UTF-8", "star_events_count": 99, "url": "https://raw.githubusercontent.com/oiuv/mud/e9ff076724472256b9b4bd88c148d6bf71dc3c02/d/village/sroad4.c", "visit_date": "2023-08-18T20:18:37.848801" }
stackv2
// Room: /d/village/sroad4.c inherit ROOM; void create() { set("short", "碎石路"); set("long", @LONG 这是一个宁静的小村子,稀稀落落的分布着几十间土坯泥房,看来村 中人家不多,而且大都生活很艰辛。这是一条南北向的碎石路,往北就是 村子中心的打谷场了,东面是村里唯一的青砖瓦房。 LONG ); set("exits", ([ /* sizeof() == 3 */ "north" : __DIR__"square", "south" : __DIR__"sroad3", "east" : __DIR__"bighouse1", ])); set("outdoors", "village"); setup(); replace_program(ROOM); }
2.046875
2
2024-11-18T21:05:53.593266+00:00
2017-08-14T21:05:50
365b4e3b3d7d64eae1c7894f76eddfad1c984a2e
{ "blob_id": "365b4e3b3d7d64eae1c7894f76eddfad1c984a2e", "branch_name": "refs/heads/master", "committer_date": "2017-08-14T21:05:50", "content_id": "1849a28b75505e30eb7d0873fcfd15fa6ac8bf26", "detected_licenses": [ "MIT" ], "directory_id": "5dbd2bdb8a47ead3d6bb5e6c0549fe19a958b4d0", "extension": "h", "filename": "pid.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 711, "license": "MIT", "license_type": "permissive", "path": "/SOURCE/line_follow/pid.h", "provenance": "stackv2-0083.json.gz:3390", "repo_name": "zhy1120/sumobot", "revision_date": "2017-08-14T21:05:50", "revision_id": "d26bd572d761ddf843cae0d3aeec747c68600cc6", "snapshot_id": "87f94644931991f26d04572d67193f84b91f5181", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zhy1120/sumobot/d26bd572d761ddf843cae0d3aeec747c68600cc6/SOURCE/line_follow/pid.h", "visit_date": "2021-06-21T00:29:17.613312" }
stackv2
//Define Variables we'll be connecting to double Setpoint = 0; double LInput, LOutput, RInput, ROutput; //Define the aggressive and conservative Tuning Parameters double aggKp=5, aggKi=0.2, aggKd=1; //double aggKp=4, aggKi=0.1, aggKd=1; double consKp=1, consKi=0.05, consKd=0.25; //Specify the links and initial tuning parameters PID leftPID(&LInput, &LOutput, &Setpoint, aggKp, aggKi, aggKd, DIRECT); PID rightPID(&RInput, &ROutput, &Setpoint, aggKp, aggKi, aggKd, DIRECT); double pid_tranlation1(){ return ((r5*4)+(r4*2)+(r3*1)) - ((r0*4)+(r1*2)+(r2*1)) * 10.0; } double pid_tranlationL(){ return ((r0*48)+(r1*24)+(r2*20)); } double pid_tranlationR(){ return ((r5*48)+(r4*24)+(r3*20)); }
2.359375
2
2024-11-18T21:05:53.767770+00:00
2016-01-19T10:30:50
6f5163dd8737a528fb9d0d6565cf5c35334fab28
{ "blob_id": "6f5163dd8737a528fb9d0d6565cf5c35334fab28", "branch_name": "refs/heads/master", "committer_date": "2016-01-19T10:30:50", "content_id": "b9380211e77ff39397d0ef6af3785133dff26bd0", "detected_licenses": [ "MIT" ], "directory_id": "9112f07fce0fed12dfaa8149167e6e231650d4fe", "extension": "c", "filename": "picviewer.c", "fork_events_count": 42, "gha_created_at": "2015-11-12T05:10:44", "gha_event_created_at": "2016-01-18T14:17:42", "gha_language": "C", "gha_license_id": null, "github_id": 46030868, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5678, "license": "MIT", "license_type": "permissive", "path": "/xv6/picviewer.c", "provenance": "stackv2-0083.json.gz:3646", "repo_name": "THSS13/XV6", "revision_date": "2016-01-19T10:30:50", "revision_id": "10aa797099e53cefc63b98ce2d3cf4feb57744f0", "snapshot_id": "9ed284f1fca826a7836f9539332da12c5a68a072", "src_encoding": "UTF-8", "star_events_count": 36, "url": "https://raw.githubusercontent.com/THSS13/XV6/10aa797099e53cefc63b98ce2d3cf4feb57744f0/xv6/picviewer.c", "visit_date": "2021-01-10T15:05:22.925260" }
stackv2
#include "picviewer.h" struct Icon wndRes[] = { { "close.bmp", 3, 3 } }; Handler wndEvents[] = { h_closeWnd }; PICNODE pic; int isRun = 1; // 压缩图片 void compressPic(int width, int height) { int w0, h0, w1, h1; float fw, fh; int x0, y0, x1, x2, y1, y2; float fx1, fx2, fy1, fy2; int x, y, index; RGBQUAD* data; w0 = pic.width; h0 = pic.height; w1 = width; h1 = height; fw = w0 * 1.0 / w1; fh = h0 * 1.0 / h1; index = 0; data = (RGBQUAD*)malloc(w1*h1*sizeof(RGBQUAD)); memset(data, 0, (uint)w1*h1*sizeof(RGBQUAD)); for (y = 0; y < h1; ++y) { y0 = y*fh; y1 = (int)y0; y2 = (y1 == h0-1) ? y1 : y1 + 1; fy1 = y1-y0; fy2 = 1.0f-fy1; for (x = 0; x < w1; ++x) { x0 = x*fw; x1 = (int)x0; x2 = (x1 == w0-1) ? x1 : x1 + 1; fx1 = y1-y0; fx2 = 1.0f-fx1; float s1 = fx1*fy1; float s2 = fx2*fy1; float s3 = fx2*fy2; float s4 = fx1*fy2; RGBQUAD p1, p2, p3, p4; p1 = pic.data[x1+y1*w0]; p2 = pic.data[x2+y1*w0]; p3 = pic.data[x1+y2*w0]; p4 = pic.data[x2+y2*w0]; data[index].rgbRed = (BYTE)(p1.rgbRed*s3 + p2.rgbRed*s4 + p3.rgbRed*s2 + p4.rgbRed*s1); data[index].rgbGreen = (BYTE)(p1.rgbGreen*s3 + p2.rgbGreen*s4 + p3.rgbGreen*s2 + p4.rgbGreen*s1); data[index].rgbBlue = (BYTE)(p1.rgbBlue*s3 + p2.rgbBlue*s4 + p3.rgbBlue*s2 + p4.rgbBlue*s1); data[index].rgbRed = p1.rgbRed; data[index].rgbGreen = p1.rgbGreen; data[index].rgbBlue = p1.rgbBlue; ++index; } } freepic(&pic); pic.data = data; pic.width = width; pic.height = height; } void modifyPic(Context context) { int c_width, c_height; int pic_width, pic_height; c_width = context.width; c_height = context.height; pic_width = pic.width; pic_height = pic.height; if (pic_width < c_width && pic_height < c_height) { return; } float scale_p, scale_c; scale_p = pic_width * 1.0 / pic_height; scale_c = c_width * 1.0 / c_height; if (scale_p <= scale_c) { pic_width = scale_p * (c_height-10); pic_height = c_height-10; } else { pic_height = (c_width-5) / scale_p; pic_width = c_width-5; } printf(0, "modifyPic: pic_width: %d, pic_height: %d\n", pic_width, pic_height); compressPic(pic_width, pic_height); } // 绘制窗口 void drawPicViewerWnd(Context context) { int width, height; width = context.width; height = context.height; fill_rect(context, 0, 0, width, height, 0xFFFF); draw_line(context, 0, 0, width-1, 0, BORDERLINE_COLOR); draw_line(context, width-1, 0, width-1, height-1, BORDERLINE_COLOR); draw_line(context, 0, height-1, width-1, height-1, BORDERLINE_COLOR); draw_line(context, 0, height-1, 0, 0, BORDERLINE_COLOR); fill_rect(context, 1, 1, width-2, TOPBAR_HEIGHT, TOPBAR_COLOR); puts_str(context, "PictureViewer", 0, WINDOW_WIDTH/2 - 53, 3); draw_iconlist(context, wndRes, sizeof(wndRes) / sizeof(ICON)); } void drawPicViewerContent(Context context, char* fileName) { int c_width, c_height; int pic_width, pic_height; c_width = context.width; c_height = context.height; pic_width = pic.width; pic_height = pic.height; printf(0, "drawPicViewerContent: pic_width: %d, pic_height: %d\n", pic_width, pic_height); draw_picture(context, pic, (c_width-pic_width) >> 1, TOPBAR_HEIGHT + ((c_height-pic_height) >> 1)); } void h_closeWnd(Point p) { isRun = 0; } void addWndEvent(ClickableManager *cm) { int i; int n = sizeof(wndEvents) / sizeof(Handler); for (i = 0; i < n; i++) { createClickable(cm, initRect(wndRes[i].position_x, wndRes[i].position_y, wndRes[i].pic.width, wndRes[i].pic.height), MSG_LPRESS, wndEvents[i]); } } int main(int argc, char *argv[]) { struct Context context; ClickableManager cm; int winid; struct Msg msg; Point p; winid = init_context(&context, WINDOW_WIDTH, WINDOW_HEIGHT); cm = initClickManager(context); loadBitmap(&pic, argv[1]); load_iconlist(wndRes, sizeof(wndRes) / sizeof(ICON)); modifyPic(context); deleteClickable(&cm.left_click, initRect(0, 0, 800, 600)); addWndEvent(&cm); while (isRun) { getMsg(&msg); switch (msg.msg_type) { case MSG_DOUBLECLICK: p = initPoint(msg.concrete_msg.msg_mouse.x, msg.concrete_msg.msg_mouse.y); if (executeHandler(cm.double_click, p)) { updateWindow(winid, context.addr, msg.msg_detail); } break; case MSG_UPDATE: drawPicViewerWnd(context); drawPicViewerContent(context, argv[1]); updateWindow(winid, context.addr, msg.msg_detail); break; case MSG_PARTIAL_UPDATE: updatePartialWindow(winid, context.addr, msg.concrete_msg.msg_partial_update.x1, msg.concrete_msg.msg_partial_update.y1, msg.concrete_msg.msg_partial_update.x2, msg.concrete_msg.msg_partial_update.y2); break; case MSG_LPRESS: p = initPoint(msg.concrete_msg.msg_mouse.x, msg.concrete_msg.msg_mouse.y); if (executeHandler(cm.left_click, p)) { updateWindow(winid, context.addr, msg.msg_detail); } break; case MSG_RPRESS: p = initPoint(msg.concrete_msg.msg_mouse.x, msg.concrete_msg.msg_mouse.y); if (executeHandler(cm.right_click, p)) { updateWindow(winid, context.addr, msg.msg_detail); } break; default: break; } } free_context(&context, winid); exit(); }
2.40625
2
2024-11-18T21:05:54.002631+00:00
2019-04-16T16:21:07
e61d008fd2706b6f807f70d3f9c685575c8520df
{ "blob_id": "e61d008fd2706b6f807f70d3f9c685575c8520df", "branch_name": "refs/heads/master", "committer_date": "2019-04-16T16:21:07", "content_id": "b1ca6a27184c1203ba3d76efc58f246745466997", "detected_licenses": [ "MIT" ], "directory_id": "5e3c88e95f4266db079b44b96d198246151f4895", "extension": "h", "filename": "Main.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 125774482, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2060, "license": "MIT", "license_type": "permissive", "path": "/Main.h", "provenance": "stackv2-0083.json.gz:3903", "repo_name": "abishek-sampath/SDL-GameFramework", "revision_date": "2019-04-16T16:21:07", "revision_id": "0194540851eeaff6b4563feefb8edae7ca868700", "snapshot_id": "cf6c7d4be7a4724b125d04f9b90efa752fb9d86b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/abishek-sampath/SDL-GameFramework/0194540851eeaff6b4563feefb8edae7ca868700/Main.h", "visit_date": "2021-10-27T06:09:20.537298" }
stackv2
#ifndef RSPWN_BRKOUT_MAIN #define RSPWN_BRKOUT_MAIN #include "Menu.h" #include "ScoreBoard.h" #include "CApp.h" #include "Exit.h" #include "Definitions.h" #undef main // Instance Variables // /** * Points to the menu object */ Menu* menuObj = NULL; /** * Points to the menu object */ ScoreBoard* scoreObj = NULL; /** * Points to the exit object */ Exit* exitObj = NULL; // game variables // /** * Holds the gameStateStack */ stack<State> *gameStateStack; /** * Holds the string text data to be displayed */ StringData* stringData; // SDL variables // /** * Points to the SDL renderer object */ SDL_Renderer* renderer = NULL; /** * Points to the SDL window object */ SDL_Window* window = NULL; /** * Points to the Resource Manager */ ResourceManager* resourceManager = NULL; // Color Variables // /** * Holds the values for blue color */ SDL_Color blueColor = { 0x00, 0x00, 0xdd }; /** * Holds the values for yellow color */ SDL_Color yellowColor = { 0x00, 0xdd, 0xdd }; /** * Holds the values for green color */ SDL_Color greenColor = { 0x00, 0xdd, 0x00 }; /** * Holds the values for white color */ SDL_Color whiteColor = { 0xff, 0xff, 0xff }; // Music variables // /** * Points to the background music file */ Mix_Music* bg_music = NULL; /** * Points to the menu sound */ Mix_Chunk* menu_sound = NULL; /** * Points to the selection sound */ Mix_Chunk* select_sound = NULL; // Global Game Functions // /** * Dummy Initialise Function - Initialize Game components */ void Init(); /** * Dummy Shutdown function */ void CloseGame(); // Helper Functions // /** * Function to load music media */ bool loadMusicMedia(); /** * Function to close music media resources */ void closeMusicMedia(); /** * Clear screen */ void ClearScreen(); /** * Enforce Frame Capping */ void enforceFPS(int frameStartTime); /** * Save score from currently ended game */ void saveScore(int score, Uint32 timeElapsed); /** * Main function */ int main(int argc, char** argv); #endif // !RSPWN_BRKOUT_MAIN
2.171875
2
2024-11-18T21:05:54.104615+00:00
2017-10-23T20:21:43
45b23965694b68ea415aa6be45d01f91c5b6f221
{ "blob_id": "45b23965694b68ea415aa6be45d01f91c5b6f221", "branch_name": "refs/heads/master", "committer_date": "2017-10-23T20:21:43", "content_id": "05d976c5cccd24072bd31f3d9fd5a1ea04af9eef", "detected_licenses": [ "Unlicense" ], "directory_id": "7153aec2542434f29ea3df65a81dbef9788b839e", "extension": "c", "filename": "list.c", "fork_events_count": 2, "gha_created_at": "2017-02-15T20:48:40", "gha_event_created_at": "2017-02-28T16:26:55", "gha_language": "Java", "gha_license_id": null, "github_id": 82105245, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5518, "license": "Unlicense", "license_type": "permissive", "path": "/src/c/list.c", "provenance": "stackv2-0083.json.gz:4031", "repo_name": "hiergaut/hexGame", "revision_date": "2017-10-23T20:21:43", "revision_id": "5ebc36af0cb9d18671fde13bfb539e494901074c", "snapshot_id": "e4015a85a8e8a3e42f53b67cf865e4b1b4cf6f2e", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/hiergaut/hexGame/5ebc36af0cb9d18671fde13bfb539e494901074c/src/c/list.c", "visit_date": "2021-01-19T09:21:15.162280" }
stackv2
#include "list.h" #include <malloc.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include <stdbool.h> typedef struct s_node* node; struct s_node { node next; node prev; void* el; }; struct s_list { node sentinel; unsigned size; void (*printElement)(const void*); }; list list_create() { list l =malloc(sizeof(struct s_list)); l->sentinel =malloc(sizeof(struct s_node)); l->sentinel->next =l->sentinel; l->sentinel->prev =l->sentinel; l->size =0; return l; } void list_pushBack(list l, void* el) { node new =malloc(sizeof(struct s_node)); new->el =el; new->next =l->sentinel; new->prev =l->sentinel->prev; new->next->prev =new; new->prev->next =new; l->size++; } void list_pushFront(list l, void* el) { node new =malloc(sizeof(struct s_node)); new->el =el; new->next =l->sentinel->next; new->prev =l->sentinel; new->next->prev =new; new->prev->next =new; l->size++; } void list_popBack(list l) { assert(l->size); node del =l->sentinel->prev; del->prev->next =del->next; del->next->prev =del->prev; l->size--; free(del); } void list_popFront(list l) { assert(l->size); node del =l->sentinel->next; del->prev->next =del->next; del->next->prev =del->prev; l->size--; free(del); } void list_insertAt(list l, unsigned level, void* el) { assert(level <=l->size); node cur=l->sentinel->next; while (level--) cur =cur->next; node new =malloc(sizeof(struct s_node)); new->next =cur; new->prev =cur->prev; new->el =el; new->next->prev =new; new->prev->next =new; l->size++; } void list_removeAt(list l, unsigned level) { assert(level <l->size); node cur =l->sentinel->next; while(level--) cur =cur->next; cur->prev->next =cur->next; cur->next->prev =cur->prev; l->size--; free(cur); } void list_remove(list l, void* el) { assert(el); node cur =l->sentinel->next; while (cur !=l->sentinel) { if (cur->el ==el) { cur->prev->next =cur->next; cur->next->prev =cur->prev; l->size--; free(cur); return; } cur =cur->next; } assert(0); } void* list_ith(list l, unsigned level) { node cur =l->sentinel->next; while (level--) cur =cur->next; return cur->el; } void* list_front(list l) { return l->sentinel->next->el; } void* list_back(list l) { assert(! list_empty(l)); return l->sentinel->prev->el; } unsigned list_size(list l) { return l->size; } bool list_empty(list l) { return ! l->size; } void list_map(list l, void (*process)(void*)) { node cur=l->sentinel->next; while (cur !=l->sentinel) { process(cur->el); cur =cur->next; } } void list_reduce(list l, void(*process)(void*, void*), void* user_data) { node cur=l->sentinel->next; while (cur !=l->sentinel) { process(cur->el, user_data); cur =cur->next; } } void list_reduce2(list l, void(*process)(void*, void*, void*), void* user_data, void* user_data2) { node cur=l->sentinel->next; while (cur !=l->sentinel) { process(cur->el, user_data, user_data2); cur =cur->next; } } void list_destroy(list* l) { list_clean(*l); /* node cur =(*l)->sentinel->next; */ /* while (cur !=(*l)->sentinel) { */ /* cur =cur->next; */ /* free(cur->prev); */ /* } */ free((*l)->sentinel); free(*l); *l =NULL; } void list_clean(list l) { while (! list_empty(l)) { list_popBack(l); } } void list_translate(void* el, void* l2) { list_pushBack(l2, el); } void list_copy(list l, list l2) { list_clean(l2); list_reduce(l, list_translate, l2); } void list_testBench_print(const void* n) { printf("%d ", *(int*)(unsigned long)n); } void list_testBench_aff(list l) { list_map(l, (void (*)(void*))list_testBench_print); printf("\n"); } void list_testBench() { printf("list_testBench :\n"); list l =list_create(list_testBench_print); int tab[100]; for (int i =0 ;i <30 ;i++) { tab[i] =rand() %100; } list_pushBack(l, &tab[0]); list_testBench_aff(l); list_pushBack(l, &tab[1]); list_testBench_aff(l); list_pushBack(l, &tab[2]); list_testBench_aff(l); list_popBack(l); list_testBench_aff(l); list_popFront(l); list_testBench_aff(l); list_popBack(l); list_testBench_aff(l); list_pushBack(l, &tab[3]); list_testBench_aff(l); list_pushBack(l, &tab[3]); list_testBench_aff(l); list_destroy(&l); printf("\n\n"); } struct s_list_it { list l; node begin; node cur; }; list_it list_it_create(list l) { list_it it =malloc(sizeof(struct s_list_it)); it->l =l; it->begin =l->sentinel->next; it->cur =it->begin; return it; } void list_it_next(list_it it) { it->cur =it->cur->next; } bool list_it_end(list_it it) { return it->cur ==it->l->sentinel; } void* list_it_get(list_it it) { return it->cur->el; } void list_it_destroy(list_it* it) { free(*it); *it =NULL; } void list_it_restart(list_it it) { it->cur =it->begin; } unsigned list_getSize(list l) { return l->size; } int list_in(list l, const void* el) { list_it it =list_it_create(l); while (! list_it_end(it)) { void* cur =list_it_get(it); if (cur ==el) return 1; list_it_next(it); } return 0; }
3.1875
3
2024-11-18T21:05:54.205428+00:00
2020-11-12T21:05:53
df095d1b744c450187ab172ae895b9920413cf0a
{ "blob_id": "df095d1b744c450187ab172ae895b9920413cf0a", "branch_name": "refs/heads/master", "committer_date": "2020-11-12T21:05:53", "content_id": "8c5e12dde696ce1fb234a7b2433ee8873434eefd", "detected_licenses": [ "MIT" ], "directory_id": "bf41d6629faaf34192a159f1e12d50656fbd8d10", "extension": "c", "filename": "ex3.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 511, "license": "MIT", "license_type": "permissive", "path": "/projetos-e-exercicios/Aula 05/ex3.c", "provenance": "stackv2-0083.json.gz:4160", "repo_name": "mpbruder/SI100-PROG1", "revision_date": "2020-11-12T21:05:53", "revision_id": "9510fc6453a85e25bc0d6b4c3fb0296bc2dd5e2c", "snapshot_id": "9c24a0e3196ca2af691438bdf0bc46f3db5c0868", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mpbruder/SI100-PROG1/9510fc6453a85e25bc0d6b4c3fb0296bc2dd5e2c/projetos-e-exercicios/Aula 05/ex3.c", "visit_date": "2023-01-08T23:47:05.253818" }
stackv2
/*AULA 5 (VETORES) - Exercício 3*/ #include <stdio.h> int main () { float notas[20]; float BUSCAnota; int i; // Variavel de controle int b; // Variavel binaria for (i=0; i<20; i++) { scanf ("%f", &notas[i]); } scanf ("%f", &BUSCAnota); while (BUSCAnota > 0) { b = 0; for (i=0; i<20; i++) { if (notas[i] == BUSCAnota) { b++; } } if (b > 0) { printf ("existe\n"); } else { printf ("nao existe\n"); } scanf ("%f", &BUSCAnota); } return 0; }
2.796875
3
2024-11-18T21:05:54.306526+00:00
2012-05-23T10:34:30
2de9f14e333c61a93efc41620eb71c1a043bd0bc
{ "blob_id": "2de9f14e333c61a93efc41620eb71c1a043bd0bc", "branch_name": "refs/heads/master", "committer_date": "2012-05-23T10:34:30", "content_id": "b24a08ee82919b9c4131fbb794836c71b8a33520", "detected_licenses": [ "MIT" ], "directory_id": "111e8a7bc571d3702c6143ba47028b49a50031df", "extension": "c", "filename": "html_form_element.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6226, "license": "MIT", "license_type": "permissive", "path": "/libdom/src/html/html_form_element.c", "provenance": "stackv2-0083.json.gz:4289", "repo_name": "sanyaade-research-hub/NetSurf", "revision_date": "2012-05-23T10:34:30", "revision_id": "afb0f5a9b710cde21aa1c6f7746b412c022fc4a6", "snapshot_id": "4ea5305a13cab0b341100e629141afe1e8efcbcf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sanyaade-research-hub/NetSurf/afb0f5a9b710cde21aa1c6f7746b412c022fc4a6/libdom/src/html/html_form_element.c", "visit_date": "2020-12-25T11:42:18.719331" }
stackv2
/* * This file is part of libdom. * Licensed under the MIT License, * http://www.opensource.org/licenses/mit-license.php * Copyright 2009 Bo Yang <struggleyb.nku.com> */ #include <assert.h> #include <stdlib.h> #include "html/html_form_element.h" #include "html/html_collection.h" #include "html/html_document.h" #include "core/node.h" #include "utils/utils.h" static struct dom_element_protected_vtable _protect_vtable = { { DOM_NODE_PROTECT_VTABLE_HTML_FORM_ELEMENT }, DOM_HTML_FORM_ELEMENT_PROTECT_VTABLE }; static bool _dom_is_form_control(struct dom_node_internal *node); /** * Create a dom_html_form_element object * * \param doc The document object * \param ele The returned element object * \return DOM_NO_ERR on success, appropriate dom_exception on failure. */ dom_exception _dom_html_form_element_create(struct dom_html_document *doc, struct dom_html_form_element **ele) { struct dom_node_internal *node; *ele = malloc(sizeof(dom_html_form_element)); if (*ele == NULL) return DOM_NO_MEM_ERR; /* Set up vtables */ node = (struct dom_node_internal *) *ele; node->base.vtable = &_dom_element_vtable; node->vtable = &_protect_vtable; return _dom_html_form_element_initialise(doc, *ele); } /** * Initialise a dom_html_form_element object * * \param doc The document object * \param ele The dom_html_form_element object * \return DOM_NO_ERR on success, appropriate dom_exception on failure. */ dom_exception _dom_html_form_element_initialise(struct dom_html_document *doc, struct dom_html_form_element *ele) { dom_string *name = NULL; dom_exception err; err = dom_string_create((const uint8_t *) "FORM", SLEN("FORM"), &name); if (err != DOM_NO_ERR) return err; err = _dom_html_element_initialise(doc, &ele->base, name, NULL, NULL); dom_string_unref(name); ele->col = NULL; return err; } /** * Finalise a dom_html_form_element object * * \param ele The dom_html_form_element object */ void _dom_html_form_element_finalise(struct dom_html_form_element *ele) { _dom_html_element_finalise(&ele->base); } /** * Destroy a dom_html_form_element object * * \param ele The dom_html_form_element object */ void _dom_html_form_element_destroy(struct dom_html_form_element *ele) { _dom_html_form_element_finalise(ele); free(ele); } /*------------------------------------------------------------------------*/ /* The protected virtual functions */ /* The virtual function used to parse attribute value, see src/core/element.c * for detail */ dom_exception _dom_html_form_element_parse_attribute(dom_element *ele, dom_string *name, dom_string *value, dom_string **parsed) { UNUSED(ele); UNUSED(name); dom_string_ref(value); *parsed = value; return DOM_NO_ERR; } /* The virtual destroy function, see src/core/node.c for detail */ void _dom_virtual_html_form_element_destroy(dom_node_internal *node) { _dom_html_form_element_destroy((struct dom_html_form_element *) node); } /* The virtual copy function, see src/core/node.c for detail */ dom_exception _dom_html_form_element_copy(dom_node_internal *old, dom_node_internal **copy) { return _dom_html_element_copy(old, copy); } /*-----------------------------------------------------------------------*/ /* Public APIs */ /** * Get the form controls under this form element * * \param ele The form object * \param col The collection of form controls * \return DOM_NO_ERR on success, appropriate dom_exception on failure. */ dom_exception dom_html_form_element_get_elements(dom_html_form_element *ele, struct dom_html_collection **col) { dom_exception err; if (ele->col == NULL) { dom_html_document *doc = (dom_html_document *) dom_node_get_owner(ele); assert(doc != NULL); err = _dom_html_collection_create(doc, (dom_node_internal *) ele, _dom_is_form_control, col); if (err != DOM_NO_ERR) return err; ele->col = *col; } *col = ele->col; dom_html_collection_ref(*col); return DOM_NO_ERR; } /** * Get the number of form controls under this form element * * \param ele The form object * \param len The number of controls * \return DOM_NO_ERR on success, appropriate dom_exception on failure. */ dom_exception dom_html_form_element_get_length(dom_html_form_element *ele, unsigned long *len) { dom_exception err; if (ele->col == NULL) { dom_html_document *doc = (dom_html_document *) dom_node_get_owner(ele); assert(doc != NULL); err = _dom_html_collection_create(doc, (dom_node_internal *) ele, _dom_is_form_control, &ele->col); if (err != DOM_NO_ERR) return err; } return dom_html_collection_get_length(ele->col, len); } /** * Submit this form * * \param ele The form object * \return DOM_NO_ERR on success, appropriate dom_exception on failure. */ dom_exception dom_html_form_element_submit(dom_html_form_element *ele) { struct dom_document *doc = dom_node_get_owner(ele); bool success = false; assert(doc != NULL); /* Dispatch an event and let the default action handler to deal with * the submit action, and a 'submit' event is bubbling and cancelable */ return _dom_dispatch_generic_event(doc, (dom_event_target *) ele, (const uint8_t *) "submit", SLEN("submit"), true, true, &success); } /** * Reset this form * * \param ele The form object * \return DOM_NO_ERR on success, appropriate dom_exception on failure. */ dom_exception dom_html_form_element_reset(dom_html_form_element *ele) { struct dom_document *doc = dom_node_get_owner(ele); bool success = false; assert(doc != NULL); /* Dispatch an event and let the default action handler to deal with * the reset action, and a 'reset' event is bubbling and cancelable */ return _dom_dispatch_generic_event(doc, (dom_event_target *) ele, (const uint8_t *) "reset", SLEN("reset"), true, true, &success); } /*-----------------------------------------------------------------------*/ /* Internal functions */ /* Callback function to test whether certain node is a form control, see * src/html/html_collection.h for detail. */ static bool _dom_is_form_control(struct dom_node_internal *node) { UNUSED(node); assert(node->type == DOM_ELEMENT_NODE); /** \todo: implement */ return false; }
2.328125
2
2024-11-18T21:05:54.450190+00:00
2021-02-08T13:04:39
243775da2687b14dd1baafb2e87b583312bec3bb
{ "blob_id": "243775da2687b14dd1baafb2e87b583312bec3bb", "branch_name": "refs/heads/main", "committer_date": "2021-02-08T13:04:39", "content_id": "7600861e85a7f716b98b706eb7bd026f35b0f6bd", "detected_licenses": [ "MIT" ], "directory_id": "ec3e9b6bf6c4cabec140dcf1be7c414f9f6c4314", "extension": "c", "filename": "ex28.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 336269713, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 331, "license": "MIT", "license_type": "permissive", "path": "/Exercises/ListasAutonomas/ex28.c", "provenance": "stackv2-0083.json.gz:4549", "repo_name": "BrunoOMelo/Exercises-C", "revision_date": "2021-02-08T13:04:39", "revision_id": "0d80c981b9d382a4b8979768de626d074887d27b", "snapshot_id": "2000759a1ffbf5163d234ccaf368ce3f4ee30ca9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BrunoOMelo/Exercises-C/0d80c981b9d382a4b8979768de626d074887d27b/Exercises/ListasAutonomas/ex28.c", "visit_date": "2023-02-27T04:03:04.404820" }
stackv2
#include <stdio.h> #include <stdlib.h> int main(){ float n1,n2,n3; printf("Digite o 1 valor :"); scanf("%f",&n1); printf("Digite o 2 valor :"); scanf("%f",&n2); printf("Digite o 3 valor :"); scanf("%f",&n3); printf("\nSoma dos quadrados:%.2f\n\n", (n1*n1)+(n2*n2)+(n3*n3)); system("PAUSE"); return 0; }
2.71875
3
2024-11-18T21:05:54.536091+00:00
2015-06-07T23:30:17
d04ed12e238a5bef08d26bd26cf2d8ea11fdea33
{ "blob_id": "d04ed12e238a5bef08d26bd26cf2d8ea11fdea33", "branch_name": "refs/heads/master", "committer_date": "2015-06-07T23:30:17", "content_id": "92b592a02fd8c8e5d9bbc8d34eb5c9ae07dc40f0", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7ba74e6f8ebe9aa22fccefa4f5b77e84a6ea3cf4", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 30510434, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8651, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0083.json.gz:4677", "repo_name": "magmastonealex/bigdate", "revision_date": "2015-06-07T23:30:17", "revision_id": "53d04eff72ad434524a0ee63d65419bc7be293db", "snapshot_id": "ecf3998b20e1c084ab07ce92226a10ffab6d3f05", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/magmastonealex/bigdate/53d04eff72ad434524a0ee63d65419bc7be293db/src/main.c", "visit_date": "2016-09-06T15:24:50.617149" }
stackv2
#include <pebble.h> static Window *window; static Layer *layer; static InverterLayer *invertLayer; static GBitmap *image0; static GBitmap *image1; static GBitmap *image2; static GBitmap *image3; static GBitmap *image4; static GBitmap *image5; static GBitmap *image6; static GBitmap *image7; static GBitmap *image8; static GBitmap *image9; static GBitmap *imageD0; static GBitmap *imageD1; static GBitmap *imageD2; static GBitmap *imageD3; static GBitmap *imageD4; static GBitmap *imageD5; static GBitmap *imageD6; static GBitmap *imageD7; static GBitmap *imageD8; static GBitmap *imageD9; static GBitmap *imageW; static GBitmap *imageU; static GBitmap *imageT; static GBitmap *imageS; static GBitmap *imageR; static GBitmap *imageM; static GBitmap *imageH; static GBitmap *imageF; static GBitmap *imageE; static GBitmap *imageA; static GBitmap *imageDot; static char hour_buffer[3]; static char min_buffer[3]; static char day_buffer[3]; static char month_buffer[3]; static char day_name_buffer[4]; static void tick_handler(struct tm *tick_time, TimeUnits units_changed) { // Update things here APP_LOG(APP_LOG_LEVEL_DEBUG, "We'reUpdatingTime"); if (clock_is_24h_style()) { strftime(hour_buffer, sizeof(hour_buffer), "%H", tick_time); } else { strftime(hour_buffer, sizeof(hour_buffer), "%I", tick_time); } strftime(min_buffer, sizeof(min_buffer), "%M", tick_time); strftime(day_buffer, sizeof(day_buffer), "%d", tick_time); strftime(day_name_buffer, sizeof(day_name_buffer), "%a", tick_time); strftime(month_buffer, sizeof(month_buffer), "%m", tick_time); layer_mark_dirty(layer); //text_layer_set_text(some_text_layer, s_time_buffer);s_tim } GBitmap* imageRefForLChar(char ch){ if(ch=='W' || ch=='w'){ return imageW; }else if(ch=='U'||ch=='u'){ return imageU; }else if(ch=='T'||ch=='t'){ return imageT; }else if(ch=='S'||ch=='s'){ return imageS; }else if(ch=='R'||ch=='r'){ return imageR; }else if(ch=='M'||ch=='m'){ return imageM; }else if(ch=='H'||ch=='h'){ return imageH; }else if(ch=='F'||ch=='f'){ return imageF; }else if(ch=='E'||ch=='e'){ return imageE; }else if(ch=='O'||ch=='o'){ return imageD0; }else{ return imageA; } } GBitmap* imageRefForChar(char ch){ //return image0; if(ch=='0'){ return image0; }else if(ch=='1'){ return image1; }else if(ch=='2'){ return image2; }else if(ch=='3'){ return image3; }else if(ch=='4'){ return image4; }else if(ch=='5'){ return image5; }else if(ch=='6'){ return image6; }else if(ch=='7'){ return image7; }else if(ch=='8'){ return image8; }else{ return image9; } } GBitmap* imageDRefForChar(char ch){ //return imageD0; if(ch=='0'){ return imageD0; }else if(ch=='1'){ return imageD1; }else if(ch=='2'){ return imageD2; }else if(ch=='3'){ return imageD3; }else if(ch=='4'){ return imageD4; }else if(ch=='5'){ return imageD5; }else if(ch=='6'){ return imageD6; }else if(ch=='7'){ return imageD7; }else if(ch=='8'){ return imageD8; }else{ return imageD9; } } static void layer_update_callback(Layer *me, GContext* ctx) { // We make sure the dimensions of the GRect to draw into // are equal to the size of the bitmap--otherwise the image // will automatically tile. Which might be what *you* want. GBitmap* hour1=imageRefForChar(hour_buffer[0]); GBitmap* hour2=imageRefForChar(hour_buffer[1]); GBitmap* min1=imageRefForChar(min_buffer[0]); GBitmap* min2=imageRefForChar(min_buffer[1]); GBitmap* dayn1=imageRefForLChar(day_name_buffer[0]); GBitmap* dayn2=imageRefForLChar(day_name_buffer[1]); GBitmap* day1=imageDRefForChar(day_buffer[0]); GBitmap* day2=imageDRefForChar(day_buffer[1]); GBitmap* mon1=imageDRefForChar(month_buffer[0]); GBitmap* mon2=imageDRefForChar(month_buffer[1]); graphics_draw_bitmap_in_rect(ctx, dayn1, (GRect) { .origin = { 0, 0 }, .size = { 20, 28 } }); graphics_draw_bitmap_in_rect(ctx, dayn2, (GRect) { .origin = { 22, 0 }, .size = { 20, 28 } }); graphics_draw_bitmap_in_rect(ctx, imageDot, (GRect) { .origin = { 44, 23 }, .size = { 5, 5 } }); graphics_draw_bitmap_in_rect(ctx, day1, (GRect) { .origin = { 51, 0 }, .size = { 20, 28 } }); graphics_draw_bitmap_in_rect(ctx, day2, (GRect) { .origin = { 73, 0 }, .size = { 20, 28 } }); graphics_draw_bitmap_in_rect(ctx, imageDot, (GRect) { .origin = { 95, 23 }, .size = { 5, 5 } }); graphics_draw_bitmap_in_rect(ctx, mon1, (GRect) { .origin = { 102, 0 }, .size = { 20, 28 } }); graphics_draw_bitmap_in_rect(ctx, mon2, (GRect) { .origin = { 124, 0 }, .size = { 20, 28 } }); graphics_draw_bitmap_in_rect(ctx, min1, (GRect) { .origin = { 0, 100 }, .size = { 71, 68 } }); graphics_draw_bitmap_in_rect(ctx, min2, (GRect) { .origin = { 73, 100 }, .size = { 71, 68 } }); graphics_draw_bitmap_in_rect(ctx, hour1, (GRect) { .origin = { 0, 30 }, .size = { 71, 68 } }); graphics_draw_bitmap_in_rect(ctx, hour2, (GRect) { .origin = { 73, 30 }, .size = { 71, 68 } }); } int main(void) { tick_timer_service_subscribe(MINUTE_UNIT, tick_handler); strcpy(hour_buffer,"10"); strcpy(min_buffer,"01"); //APP_LOG(APP_LOG_LEVEL_INFO, "TimeS: %s", hour_buffer); window = window_create(); window_stack_push(window, true /* Animated */); // Init the layer for display the image Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_frame(window_layer); invertLayer=inverter_layer_create(bounds); layer = layer_create(bounds); layer_set_update_proc(layer, layer_update_callback); layer_add_child(window_layer, inverter_layer_get_layer(invertLayer)); layer_add_child(window_layer, layer); image0 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_0); image1 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_1); image2 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_2); image3 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_3); image4 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_4); image5 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_5); image6 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_6); image7 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_7); image8 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_8); image9 = gbitmap_create_with_resource(RESOURCE_ID_TIME_NUMBER_9); imageDot=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_DOT); imageW=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_W); imageU=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_U); imageT=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_T); imageS=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_S); imageR=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_R); imageM=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_M); imageH=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_H); imageF=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_F); imageE=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_E); imageA=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_A); imageD0=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_0); imageD1=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_1); imageD2=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_2); imageD3=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_3); imageD4=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_4); imageD5=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_5); imageD6=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_6); imageD7=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_7); imageD8=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_8); imageD9=gbitmap_create_with_resource(RESOURCE_ID_IMAGE_DATE_9); app_event_loop(); gbitmap_destroy(image0); gbitmap_destroy(image1); gbitmap_destroy(image2); gbitmap_destroy(image3); gbitmap_destroy(image4); gbitmap_destroy(image5); gbitmap_destroy(image6); gbitmap_destroy(image7); gbitmap_destroy(image8); gbitmap_destroy(image9); gbitmap_destroy(imageD0); gbitmap_destroy(imageD1); gbitmap_destroy(imageD2); gbitmap_destroy(imageD3); gbitmap_destroy(imageD4); gbitmap_destroy(imageD5); gbitmap_destroy(imageD6); gbitmap_destroy(imageD7); gbitmap_destroy(imageD8); gbitmap_destroy(imageD9); gbitmap_destroy(imageW); gbitmap_destroy(imageU); gbitmap_destroy(imageT); gbitmap_destroy(imageS); gbitmap_destroy(imageR); gbitmap_destroy(imageM); gbitmap_destroy(imageH); gbitmap_destroy(imageF); gbitmap_destroy(imageE); gbitmap_destroy(imageA); window_destroy(window); layer_destroy(layer); }
2.203125
2
2024-11-18T21:05:54.755264+00:00
2023-08-17T16:08:06
2201517d813e3dc6ef7240a40e7f32646cffb3c6
{ "blob_id": "2201517d813e3dc6ef7240a40e7f32646cffb3c6", "branch_name": "refs/heads/main", "committer_date": "2023-08-17T16:08:06", "content_id": "8fb0998c09ceffb28f4d1b526e637bbcc445bbee", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "eecd5e4c50d8b78a769bcc2675250576bed34066", "extension": "c", "filename": "plexsubmesh.c", "fork_events_count": 169, "gha_created_at": "2013-03-10T20:55:21", "gha_event_created_at": "2023-03-29T11:02:58", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 8691401, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 182104, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/dm/impls/plex/plexsubmesh.c", "provenance": "stackv2-0083.json.gz:4934", "repo_name": "petsc/petsc", "revision_date": "2023-08-17T16:08:06", "revision_id": "9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9", "snapshot_id": "3b1a04fea71858e0292f9fd4d04ea11618c50969", "src_encoding": "UTF-8", "star_events_count": 341, "url": "https://raw.githubusercontent.com/petsc/petsc/9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9/src/dm/impls/plex/plexsubmesh.c", "visit_date": "2023-08-17T20:51:16.507070" }
stackv2
#include <petsc/private/dmpleximpl.h> /*I "petscdmplex.h" I*/ #include <petsc/private/dmlabelimpl.h> /*I "petscdmlabel.h" I*/ #include <petscsf.h> static PetscErrorCode DMPlexCellIsHybrid_Internal(DM dm, PetscInt p, PetscBool *isHybrid) { DMPolytopeType ct; PetscFunctionBegin; PetscCall(DMPlexGetCellType(dm, p, &ct)); switch (ct) { case DM_POLYTOPE_POINT_PRISM_TENSOR: case DM_POLYTOPE_SEG_PRISM_TENSOR: case DM_POLYTOPE_TRI_PRISM_TENSOR: case DM_POLYTOPE_QUAD_PRISM_TENSOR: *isHybrid = PETSC_TRUE; break; default: *isHybrid = PETSC_FALSE; break; } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexGetTensorPrismBounds_Internal(DM dm, PetscInt dim, PetscInt *cStart, PetscInt *cEnd) { DMLabel ctLabel; PetscFunctionBegin; if (cStart) *cStart = -1; if (cEnd) *cEnd = -1; PetscCall(DMPlexGetCellTypeLabel(dm, &ctLabel)); switch (dim) { case 1: PetscCall(DMLabelGetStratumBounds(ctLabel, DM_POLYTOPE_POINT_PRISM_TENSOR, cStart, cEnd)); break; case 2: PetscCall(DMLabelGetStratumBounds(ctLabel, DM_POLYTOPE_SEG_PRISM_TENSOR, cStart, cEnd)); break; case 3: PetscCall(DMLabelGetStratumBounds(ctLabel, DM_POLYTOPE_TRI_PRISM_TENSOR, cStart, cEnd)); if (*cStart < 0) PetscCall(DMLabelGetStratumBounds(ctLabel, DM_POLYTOPE_QUAD_PRISM_TENSOR, cStart, cEnd)); break; default: PetscFunctionReturn(PETSC_SUCCESS); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexMarkBoundaryFaces_Internal(DM dm, PetscInt val, PetscInt cellHeight, DMLabel label) { PetscSF sf; const PetscInt *rootdegree, *leaves; PetscInt overlap, Nr = -1, Nl, pStart, fStart, fEnd; PetscFunctionBegin; PetscCall(DMGetPointSF(dm, &sf)); PetscCall(DMPlexGetOverlap(dm, &overlap)); if (sf && !overlap) PetscCall(PetscSFGetGraph(sf, &Nr, &Nl, &leaves, NULL)); if (Nr > 0) { PetscCall(PetscSFComputeDegreeBegin(sf, &rootdegree)); PetscCall(PetscSFComputeDegreeEnd(sf, &rootdegree)); } else rootdegree = NULL; PetscCall(DMPlexGetChart(dm, &pStart, NULL)); PetscCall(DMPlexGetHeightStratum(dm, cellHeight + 1, &fStart, &fEnd)); for (PetscInt f = fStart; f < fEnd; ++f) { PetscInt supportSize, loc = -1; PetscCall(DMPlexGetSupportSize(dm, f, &supportSize)); if (supportSize == 1) { /* Do not mark faces which are shared, meaning they are present in the pointSF, or they have rootdegree > 0 since they presumably have cells on the other side */ if (Nr > 0) { PetscCall(PetscFindInt(f, Nl, leaves, &loc)); if (rootdegree[f - pStart] || loc >= 0) continue; } if (val < 0) { PetscInt *closure = NULL; PetscInt clSize, cl, cval; PetscCall(DMPlexGetTransitiveClosure(dm, f, PETSC_TRUE, &clSize, &closure)); for (cl = 0; cl < clSize * 2; cl += 2) { PetscCall(DMLabelGetValue(label, closure[cl], &cval)); if (cval < 0) continue; PetscCall(DMLabelSetValue(label, f, cval)); break; } if (cl == clSize * 2) PetscCall(DMLabelSetValue(label, f, 1)); PetscCall(DMPlexRestoreTransitiveClosure(dm, f, PETSC_TRUE, &clSize, &closure)); } else { PetscCall(DMLabelSetValue(label, f, val)); } } } PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexMarkBoundaryFaces - Mark all faces on the boundary Not Collective Input Parameters: + dm - The original `DM` - val - The marker value, or `PETSC_DETERMINE` to use some value in the closure (or 1 if none are found) Output Parameter: . label - The `DMLabel` marking boundary faces with the given value Level: developer Note: This function will use the point `PetscSF` from the input `DM` to exclude points on the partition boundary from being marked, unless the partition overlap is greater than zero. If you also wish to mark the partition boundary, you can use `DMSetPointSF()` to temporarily set it to `NULL`, and then reset it to the original object after the call. .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLabelCreate()`, `DMCreateLabel()` @*/ PetscErrorCode DMPlexMarkBoundaryFaces(DM dm, PetscInt val, DMLabel label) { DMPlexInterpolatedFlag flg; PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); PetscCall(DMPlexIsInterpolated(dm, &flg)); PetscCheck(flg == DMPLEX_INTERPOLATED_FULL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "DM is not fully interpolated on this rank"); PetscCall(DMPlexMarkBoundaryFaces_Internal(dm, val, 0, label)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexLabelComplete_Internal(DM dm, DMLabel label, PetscBool completeCells) { IS valueIS; PetscSF sfPoint; const PetscInt *values; PetscInt numValues, v, cStart, cEnd, nroots; PetscFunctionBegin; PetscCall(DMLabelGetNumValues(label, &numValues)); PetscCall(DMLabelGetValueIS(label, &valueIS)); PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd)); PetscCall(ISGetIndices(valueIS, &values)); for (v = 0; v < numValues; ++v) { IS pointIS; const PetscInt *points; PetscInt numPoints, p; PetscCall(DMLabelGetStratumSize(label, values[v], &numPoints)); PetscCall(DMLabelGetStratumIS(label, values[v], &pointIS)); PetscCall(ISGetIndices(pointIS, &points)); for (p = 0; p < numPoints; ++p) { PetscInt q = points[p]; PetscInt *closure = NULL; PetscInt closureSize, c; if (cStart <= q && q < cEnd && !completeCells) { /* skip cells */ continue; } PetscCall(DMPlexGetTransitiveClosure(dm, q, PETSC_TRUE, &closureSize, &closure)); for (c = 0; c < closureSize * 2; c += 2) PetscCall(DMLabelSetValue(label, closure[c], values[v])); PetscCall(DMPlexRestoreTransitiveClosure(dm, q, PETSC_TRUE, &closureSize, &closure)); } PetscCall(ISRestoreIndices(pointIS, &points)); PetscCall(ISDestroy(&pointIS)); } PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); PetscCall(DMGetPointSF(dm, &sfPoint)); PetscCall(PetscSFGetGraph(sfPoint, &nroots, NULL, NULL, NULL)); if (nroots >= 0) { DMLabel lblRoots, lblLeaves; IS valueIS, pointIS; const PetscInt *values; PetscInt numValues, v; /* Pull point contributions from remote leaves into local roots */ PetscCall(DMLabelGather(label, sfPoint, &lblLeaves)); PetscCall(DMLabelGetValueIS(lblLeaves, &valueIS)); PetscCall(ISGetLocalSize(valueIS, &numValues)); PetscCall(ISGetIndices(valueIS, &values)); for (v = 0; v < numValues; ++v) { const PetscInt value = values[v]; PetscCall(DMLabelGetStratumIS(lblLeaves, value, &pointIS)); PetscCall(DMLabelInsertIS(label, pointIS, value)); PetscCall(ISDestroy(&pointIS)); } PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); PetscCall(DMLabelDestroy(&lblLeaves)); /* Push point contributions from roots into remote leaves */ PetscCall(DMLabelDistribute(label, sfPoint, &lblRoots)); PetscCall(DMLabelGetValueIS(lblRoots, &valueIS)); PetscCall(ISGetLocalSize(valueIS, &numValues)); PetscCall(ISGetIndices(valueIS, &values)); for (v = 0; v < numValues; ++v) { const PetscInt value = values[v]; PetscCall(DMLabelGetStratumIS(lblRoots, value, &pointIS)); PetscCall(DMLabelInsertIS(label, pointIS, value)); PetscCall(ISDestroy(&pointIS)); } PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); PetscCall(DMLabelDestroy(&lblRoots)); } PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexLabelComplete - Starting with a label marking points on a surface, we add the transitive closure to the surface Input Parameters: + dm - The `DM` - label - A `DMLabel` marking the surface points Output Parameter: . label - A `DMLabel` marking all surface points in the transitive closure Level: developer .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexLabelCohesiveComplete()` @*/ PetscErrorCode DMPlexLabelComplete(DM dm, DMLabel label) { PetscFunctionBegin; PetscCall(DMPlexLabelComplete_Internal(dm, label, PETSC_TRUE)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexLabelAddCells - Starting with a label marking points on a surface, we add a cell for each point Input Parameters: + dm - The `DM` - label - A `DMLabel` marking the surface points Output Parameter: . label - A `DMLabel` incorporating cells Level: developer Note: The cells allow FEM boundary conditions to be applied using the cell geometry .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexLabelAddFaceCells()`, `DMPlexLabelComplete()`, `DMPlexLabelCohesiveComplete()` @*/ PetscErrorCode DMPlexLabelAddCells(DM dm, DMLabel label) { IS valueIS; const PetscInt *values; PetscInt numValues, v, csStart, csEnd, chStart, chEnd; PetscFunctionBegin; PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &csStart, &csEnd)); PetscCall(DMPlexGetHeightStratum(dm, 0, &chStart, &chEnd)); PetscCall(DMLabelGetNumValues(label, &numValues)); PetscCall(DMLabelGetValueIS(label, &valueIS)); PetscCall(ISGetIndices(valueIS, &values)); for (v = 0; v < numValues; ++v) { IS pointIS; const PetscInt *points; PetscInt numPoints, p; PetscCall(DMLabelGetStratumSize(label, values[v], &numPoints)); PetscCall(DMLabelGetStratumIS(label, values[v], &pointIS)); PetscCall(ISGetIndices(pointIS, &points)); for (p = 0; p < numPoints; ++p) { const PetscInt point = points[p]; PetscInt *closure = NULL; PetscInt closureSize, cl, h, pStart, pEnd, cStart, cEnd; // If the point is a hybrid, allow hybrid cells PetscCall(DMPlexGetPointHeight(dm, point, &h)); PetscCall(DMPlexGetSimplexOrBoxCells(dm, h, &pStart, &pEnd)); if (point >= pStart && point < pEnd) { cStart = csStart; cEnd = csEnd; } else { cStart = chStart; cEnd = chEnd; } PetscCall(DMPlexGetTransitiveClosure(dm, points[p], PETSC_FALSE, &closureSize, &closure)); for (cl = closureSize - 1; cl > 0; --cl) { const PetscInt cell = closure[cl * 2]; if ((cell >= cStart) && (cell < cEnd)) { PetscCall(DMLabelSetValue(label, cell, values[v])); break; } } PetscCall(DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_FALSE, &closureSize, &closure)); } PetscCall(ISRestoreIndices(pointIS, &points)); PetscCall(ISDestroy(&pointIS)); } PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexLabelAddFaceCells - Starting with a label marking faces on a surface, we add a cell for each face Input Parameters: + dm - The `DM` - label - A `DMLabel` marking the surface points Output Parameter: . label - A `DMLabel` incorporating cells Level: developer Note: The cells allow FEM boundary conditions to be applied using the cell geometry .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexLabelAddCells()`, `DMPlexLabelComplete()`, `DMPlexLabelCohesiveComplete()` @*/ PetscErrorCode DMPlexLabelAddFaceCells(DM dm, DMLabel label) { IS valueIS; const PetscInt *values; PetscInt numValues, v, cStart, cEnd, fStart, fEnd; PetscFunctionBegin; PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd)); PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd)); PetscCall(DMLabelGetNumValues(label, &numValues)); PetscCall(DMLabelGetValueIS(label, &valueIS)); PetscCall(ISGetIndices(valueIS, &values)); for (v = 0; v < numValues; ++v) { IS pointIS; const PetscInt *points; PetscInt numPoints, p; PetscCall(DMLabelGetStratumSize(label, values[v], &numPoints)); PetscCall(DMLabelGetStratumIS(label, values[v], &pointIS)); PetscCall(ISGetIndices(pointIS, &points)); for (p = 0; p < numPoints; ++p) { const PetscInt face = points[p]; PetscInt *closure = NULL; PetscInt closureSize, cl; if ((face < fStart) || (face >= fEnd)) continue; PetscCall(DMPlexGetTransitiveClosure(dm, face, PETSC_FALSE, &closureSize, &closure)); for (cl = closureSize - 1; cl > 0; --cl) { const PetscInt cell = closure[cl * 2]; if ((cell >= cStart) && (cell < cEnd)) { PetscCall(DMLabelSetValue(label, cell, values[v])); break; } } PetscCall(DMPlexRestoreTransitiveClosure(dm, face, PETSC_FALSE, &closureSize, &closure)); } PetscCall(ISRestoreIndices(pointIS, &points)); PetscCall(ISDestroy(&pointIS)); } PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexLabelClearCells - Remove cells from a label Input Parameters: + dm - The `DM` - label - A `DMLabel` marking surface points and their adjacent cells Output Parameter: . label - A `DMLabel` without cells Level: developer Note: This undoes `DMPlexLabelAddCells()` or `DMPlexLabelAddFaceCells()` .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexLabelComplete()`, `DMPlexLabelCohesiveComplete()`, `DMPlexLabelAddCells()` @*/ PetscErrorCode DMPlexLabelClearCells(DM dm, DMLabel label) { IS valueIS; const PetscInt *values; PetscInt numValues, v, cStart, cEnd; PetscFunctionBegin; PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd)); PetscCall(DMLabelGetNumValues(label, &numValues)); PetscCall(DMLabelGetValueIS(label, &valueIS)); PetscCall(ISGetIndices(valueIS, &values)); for (v = 0; v < numValues; ++v) { IS pointIS; const PetscInt *points; PetscInt numPoints, p; PetscCall(DMLabelGetStratumSize(label, values[v], &numPoints)); PetscCall(DMLabelGetStratumIS(label, values[v], &pointIS)); PetscCall(ISGetIndices(pointIS, &points)); for (p = 0; p < numPoints; ++p) { PetscInt point = points[p]; if (point >= cStart && point < cEnd) PetscCall(DMLabelClearValue(label, point, values[v])); } PetscCall(ISRestoreIndices(pointIS, &points)); PetscCall(ISDestroy(&pointIS)); } PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); PetscFunctionReturn(PETSC_SUCCESS); } /* take (oldEnd, added) pairs, ordered by height and convert them to (oldstart, newstart) pairs, ordered by ascending * index (skipping first, which is (0,0)) */ static inline PetscErrorCode DMPlexShiftPointSetUp_Internal(PetscInt depth, PetscInt depthShift[]) { PetscInt d, off = 0; PetscFunctionBegin; /* sort by (oldend): yes this is an O(n^2) sort, we expect depth <= 3 */ for (d = 0; d < depth; d++) { PetscInt firstd = d; PetscInt firstStart = depthShift[2 * d]; PetscInt e; for (e = d + 1; e <= depth; e++) { if (depthShift[2 * e] < firstStart) { firstd = e; firstStart = depthShift[2 * d]; } } if (firstd != d) { PetscInt swap[2]; e = firstd; swap[0] = depthShift[2 * d]; swap[1] = depthShift[2 * d + 1]; depthShift[2 * d] = depthShift[2 * e]; depthShift[2 * d + 1] = depthShift[2 * e + 1]; depthShift[2 * e] = swap[0]; depthShift[2 * e + 1] = swap[1]; } } /* convert (oldstart, added) to (oldstart, newstart) */ for (d = 0; d <= depth; d++) { off += depthShift[2 * d + 1]; depthShift[2 * d + 1] = depthShift[2 * d] + off; } PetscFunctionReturn(PETSC_SUCCESS); } /* depthShift is a list of (old, new) pairs */ static inline PetscInt DMPlexShiftPoint_Internal(PetscInt p, PetscInt depth, PetscInt depthShift[]) { PetscInt d; PetscInt newOff = 0; for (d = 0; d <= depth; d++) { if (p < depthShift[2 * d]) return p + newOff; else newOff = depthShift[2 * d + 1] - depthShift[2 * d]; } return p + newOff; } /* depthShift is a list of (old, new) pairs */ static inline PetscInt DMPlexShiftPointInverse_Internal(PetscInt p, PetscInt depth, PetscInt depthShift[]) { PetscInt d; PetscInt newOff = 0; for (d = 0; d <= depth; d++) { if (p < depthShift[2 * d + 1]) return p + newOff; else newOff = depthShift[2 * d] - depthShift[2 * d + 1]; } return p + newOff; } static PetscErrorCode DMPlexShiftSizes_Internal(DM dm, PetscInt depthShift[], DM dmNew) { PetscInt depth = 0, d, pStart, pEnd, p; DMLabel depthLabel; PetscFunctionBegin; PetscCall(DMPlexGetDepth(dm, &depth)); if (depth < 0) PetscFunctionReturn(PETSC_SUCCESS); /* Step 1: Expand chart */ PetscCall(DMPlexGetChart(dm, &pStart, &pEnd)); pEnd = DMPlexShiftPoint_Internal(pEnd, depth, depthShift); PetscCall(DMPlexSetChart(dmNew, pStart, pEnd)); PetscCall(DMCreateLabel(dmNew, "depth")); PetscCall(DMPlexGetDepthLabel(dmNew, &depthLabel)); PetscCall(DMCreateLabel(dmNew, "celltype")); /* Step 2: Set cone and support sizes */ for (d = 0; d <= depth; ++d) { PetscInt pStartNew, pEndNew; IS pIS; PetscCall(DMPlexGetDepthStratum(dm, d, &pStart, &pEnd)); pStartNew = DMPlexShiftPoint_Internal(pStart, depth, depthShift); pEndNew = DMPlexShiftPoint_Internal(pEnd, depth, depthShift); PetscCall(ISCreateStride(PETSC_COMM_SELF, pEndNew - pStartNew, pStartNew, 1, &pIS)); PetscCall(DMLabelSetStratumIS(depthLabel, d, pIS)); PetscCall(ISDestroy(&pIS)); for (p = pStart; p < pEnd; ++p) { PetscInt newp = DMPlexShiftPoint_Internal(p, depth, depthShift); PetscInt size; DMPolytopeType ct; PetscCall(DMPlexGetConeSize(dm, p, &size)); PetscCall(DMPlexSetConeSize(dmNew, newp, size)); PetscCall(DMPlexGetSupportSize(dm, p, &size)); PetscCall(DMPlexSetSupportSize(dmNew, newp, size)); PetscCall(DMPlexGetCellType(dm, p, &ct)); PetscCall(DMPlexSetCellType(dmNew, newp, ct)); } } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexShiftPoints_Internal(DM dm, PetscInt depthShift[], DM dmNew) { PetscInt *newpoints; PetscInt depth = 0, maxConeSize, maxSupportSize, maxConeSizeNew, maxSupportSizeNew, pStart, pEnd, p; PetscFunctionBegin; PetscCall(DMPlexGetDepth(dm, &depth)); if (depth < 0) PetscFunctionReturn(PETSC_SUCCESS); PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize)); PetscCall(DMPlexGetMaxSizes(dmNew, &maxConeSizeNew, &maxSupportSizeNew)); PetscCall(PetscMalloc1(PetscMax(PetscMax(maxConeSize, maxSupportSize), PetscMax(maxConeSizeNew, maxSupportSizeNew)), &newpoints)); /* Step 5: Set cones and supports */ PetscCall(DMPlexGetChart(dm, &pStart, &pEnd)); for (p = pStart; p < pEnd; ++p) { const PetscInt *points = NULL, *orientations = NULL; PetscInt size, sizeNew, i, newp = DMPlexShiftPoint_Internal(p, depth, depthShift); PetscCall(DMPlexGetConeSize(dm, p, &size)); PetscCall(DMPlexGetCone(dm, p, &points)); PetscCall(DMPlexGetConeOrientation(dm, p, &orientations)); for (i = 0; i < size; ++i) newpoints[i] = DMPlexShiftPoint_Internal(points[i], depth, depthShift); PetscCall(DMPlexSetCone(dmNew, newp, newpoints)); PetscCall(DMPlexSetConeOrientation(dmNew, newp, orientations)); PetscCall(DMPlexGetSupportSize(dm, p, &size)); PetscCall(DMPlexGetSupportSize(dmNew, newp, &sizeNew)); PetscCall(DMPlexGetSupport(dm, p, &points)); for (i = 0; i < size; ++i) newpoints[i] = DMPlexShiftPoint_Internal(points[i], depth, depthShift); for (i = size; i < sizeNew; ++i) newpoints[i] = 0; PetscCall(DMPlexSetSupport(dmNew, newp, newpoints)); } PetscCall(PetscFree(newpoints)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexShiftCoordinates_Internal(DM dm, PetscInt depthShift[], DM dmNew) { PetscSection coordSection, newCoordSection; Vec coordinates, newCoordinates; PetscScalar *coords, *newCoords; PetscInt coordSize, sStart, sEnd; PetscInt dim, depth = 0, cStart, cEnd, cStartNew, cEndNew, c, vStart, vEnd, vStartNew, vEndNew, v; PetscBool hasCells; PetscFunctionBegin; PetscCall(DMGetCoordinateDim(dm, &dim)); PetscCall(DMSetCoordinateDim(dmNew, dim)); PetscCall(DMPlexGetDepth(dm, &depth)); /* Step 8: Convert coordinates */ PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd)); PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd)); PetscCall(DMPlexGetDepthStratum(dmNew, 0, &vStartNew, &vEndNew)); PetscCall(DMPlexGetHeightStratum(dmNew, 0, &cStartNew, &cEndNew)); PetscCall(DMGetCoordinateSection(dm, &coordSection)); PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &newCoordSection)); PetscCall(PetscSectionSetNumFields(newCoordSection, 1)); PetscCall(PetscSectionSetFieldComponents(newCoordSection, 0, dim)); PetscCall(PetscSectionGetChart(coordSection, &sStart, &sEnd)); hasCells = sStart == cStart ? PETSC_TRUE : PETSC_FALSE; PetscCall(PetscSectionSetChart(newCoordSection, hasCells ? cStartNew : vStartNew, vEndNew)); if (hasCells) { for (c = cStart; c < cEnd; ++c) { PetscInt cNew = DMPlexShiftPoint_Internal(c, depth, depthShift), dof; PetscCall(PetscSectionGetDof(coordSection, c, &dof)); PetscCall(PetscSectionSetDof(newCoordSection, cNew, dof)); PetscCall(PetscSectionSetFieldDof(newCoordSection, cNew, 0, dof)); } } for (v = vStartNew; v < vEndNew; ++v) { PetscCall(PetscSectionSetDof(newCoordSection, v, dim)); PetscCall(PetscSectionSetFieldDof(newCoordSection, v, 0, dim)); } PetscCall(PetscSectionSetUp(newCoordSection)); PetscCall(DMSetCoordinateSection(dmNew, PETSC_DETERMINE, newCoordSection)); PetscCall(PetscSectionGetStorageSize(newCoordSection, &coordSize)); PetscCall(VecCreate(PETSC_COMM_SELF, &newCoordinates)); PetscCall(PetscObjectSetName((PetscObject)newCoordinates, "coordinates")); PetscCall(VecSetSizes(newCoordinates, coordSize, PETSC_DETERMINE)); PetscCall(VecSetBlockSize(newCoordinates, dim)); PetscCall(VecSetType(newCoordinates, VECSTANDARD)); PetscCall(DMSetCoordinatesLocal(dmNew, newCoordinates)); PetscCall(DMGetCoordinatesLocal(dm, &coordinates)); PetscCall(VecGetArray(coordinates, &coords)); PetscCall(VecGetArray(newCoordinates, &newCoords)); if (hasCells) { for (c = cStart; c < cEnd; ++c) { PetscInt cNew = DMPlexShiftPoint_Internal(c, depth, depthShift), dof, off, noff, d; PetscCall(PetscSectionGetDof(coordSection, c, &dof)); PetscCall(PetscSectionGetOffset(coordSection, c, &off)); PetscCall(PetscSectionGetOffset(newCoordSection, cNew, &noff)); for (d = 0; d < dof; ++d) newCoords[noff + d] = coords[off + d]; } } for (v = vStart; v < vEnd; ++v) { PetscInt dof, off, noff, d; PetscCall(PetscSectionGetDof(coordSection, v, &dof)); PetscCall(PetscSectionGetOffset(coordSection, v, &off)); PetscCall(PetscSectionGetOffset(newCoordSection, DMPlexShiftPoint_Internal(v, depth, depthShift), &noff)); for (d = 0; d < dof; ++d) newCoords[noff + d] = coords[off + d]; } PetscCall(VecRestoreArray(coordinates, &coords)); PetscCall(VecRestoreArray(newCoordinates, &newCoords)); PetscCall(VecDestroy(&newCoordinates)); PetscCall(PetscSectionDestroy(&newCoordSection)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexShiftSF_Single(DM dm, PetscInt depthShift[], PetscSF sf, PetscSF sfNew) { const PetscSFNode *remotePoints; PetscSFNode *gremotePoints; const PetscInt *localPoints; PetscInt *glocalPoints, *newLocation, *newRemoteLocation; PetscInt numRoots, numLeaves, l, pStart, pEnd, depth = 0, totShift = 0; PetscFunctionBegin; PetscCall(DMPlexGetDepth(dm, &depth)); PetscCall(DMPlexGetChart(dm, &pStart, &pEnd)); PetscCall(PetscSFGetGraph(sf, &numRoots, &numLeaves, &localPoints, &remotePoints)); totShift = DMPlexShiftPoint_Internal(pEnd, depth, depthShift) - pEnd; if (numRoots >= 0) { PetscCall(PetscMalloc2(numRoots, &newLocation, pEnd - pStart, &newRemoteLocation)); for (l = 0; l < numRoots; ++l) newLocation[l] = DMPlexShiftPoint_Internal(l, depth, depthShift); PetscCall(PetscSFBcastBegin(sf, MPIU_INT, newLocation, newRemoteLocation, MPI_REPLACE)); PetscCall(PetscSFBcastEnd(sf, MPIU_INT, newLocation, newRemoteLocation, MPI_REPLACE)); PetscCall(PetscMalloc1(numLeaves, &glocalPoints)); PetscCall(PetscMalloc1(numLeaves, &gremotePoints)); for (l = 0; l < numLeaves; ++l) { glocalPoints[l] = DMPlexShiftPoint_Internal(localPoints[l], depth, depthShift); gremotePoints[l].rank = remotePoints[l].rank; gremotePoints[l].index = newRemoteLocation[localPoints[l]]; } PetscCall(PetscFree2(newLocation, newRemoteLocation)); PetscCall(PetscSFSetGraph(sfNew, numRoots + totShift, numLeaves, glocalPoints, PETSC_OWN_POINTER, gremotePoints, PETSC_OWN_POINTER)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexShiftSF_Internal(DM dm, PetscInt depthShift[], DM dmNew) { PetscSF sfPoint, sfPointNew; PetscBool useNatural; PetscFunctionBegin; /* Step 9: Convert pointSF */ PetscCall(DMGetPointSF(dm, &sfPoint)); PetscCall(DMGetPointSF(dmNew, &sfPointNew)); PetscCall(DMPlexShiftSF_Single(dm, depthShift, sfPoint, sfPointNew)); /* Step 9b: Convert naturalSF */ PetscCall(DMGetUseNatural(dm, &useNatural)); if (useNatural) { PetscSF sfNat, sfNatNew; PetscCall(DMSetUseNatural(dmNew, useNatural)); PetscCall(DMGetNaturalSF(dm, &sfNat)); PetscCall(DMGetNaturalSF(dmNew, &sfNatNew)); PetscCall(DMPlexShiftSF_Single(dm, depthShift, sfNat, sfNatNew)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexShiftLabels_Internal(DM dm, PetscInt depthShift[], DM dmNew) { PetscInt depth = 0, numLabels, l; PetscFunctionBegin; PetscCall(DMPlexGetDepth(dm, &depth)); /* Step 10: Convert labels */ PetscCall(DMGetNumLabels(dm, &numLabels)); for (l = 0; l < numLabels; ++l) { DMLabel label, newlabel; const char *lname; PetscBool isDepth, isDim; IS valueIS; const PetscInt *values; PetscInt numValues, val; PetscCall(DMGetLabelName(dm, l, &lname)); PetscCall(PetscStrcmp(lname, "depth", &isDepth)); if (isDepth) continue; PetscCall(PetscStrcmp(lname, "dim", &isDim)); if (isDim) continue; PetscCall(DMCreateLabel(dmNew, lname)); PetscCall(DMGetLabel(dm, lname, &label)); PetscCall(DMGetLabel(dmNew, lname, &newlabel)); PetscCall(DMLabelGetDefaultValue(label, &val)); PetscCall(DMLabelSetDefaultValue(newlabel, val)); PetscCall(DMLabelGetValueIS(label, &valueIS)); PetscCall(ISGetLocalSize(valueIS, &numValues)); PetscCall(ISGetIndices(valueIS, &values)); for (val = 0; val < numValues; ++val) { IS pointIS; const PetscInt *points; PetscInt numPoints, p; PetscCall(DMLabelGetStratumIS(label, values[val], &pointIS)); PetscCall(ISGetLocalSize(pointIS, &numPoints)); PetscCall(ISGetIndices(pointIS, &points)); for (p = 0; p < numPoints; ++p) { const PetscInt newpoint = DMPlexShiftPoint_Internal(points[p], depth, depthShift); PetscCall(DMLabelSetValue(newlabel, newpoint, values[val])); } PetscCall(ISRestoreIndices(pointIS, &points)); PetscCall(ISDestroy(&pointIS)); } PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexCreateVTKLabel_Internal(DM dm, PetscBool createGhostLabel, DM dmNew) { PetscSF sfPoint; DMLabel vtkLabel, ghostLabel = NULL; const PetscSFNode *leafRemote; const PetscInt *leafLocal; PetscInt cellHeight, cStart, cEnd, c, fStart, fEnd, f, numLeaves, l; PetscMPIInt rank; PetscFunctionBegin; /* Step 11: Make label for output (vtk) and to mark ghost points (ghost) */ PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank)); PetscCall(DMGetPointSF(dm, &sfPoint)); PetscCall(DMPlexGetVTKCellHeight(dmNew, &cellHeight)); PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd)); PetscCall(PetscSFGetGraph(sfPoint, NULL, &numLeaves, &leafLocal, &leafRemote)); PetscCall(DMCreateLabel(dmNew, "vtk")); PetscCall(DMGetLabel(dmNew, "vtk", &vtkLabel)); if (createGhostLabel) { PetscCall(DMCreateLabel(dmNew, "ghost")); PetscCall(DMGetLabel(dmNew, "ghost", &ghostLabel)); } for (l = 0, c = cStart; l < numLeaves && c < cEnd; ++l, ++c) { for (; c < leafLocal[l] && c < cEnd; ++c) PetscCall(DMLabelSetValue(vtkLabel, c, 1)); if (leafLocal[l] >= cEnd) break; if (leafRemote[l].rank == rank) { PetscCall(DMLabelSetValue(vtkLabel, c, 1)); } else if (ghostLabel) PetscCall(DMLabelSetValue(ghostLabel, c, 2)); } for (; c < cEnd; ++c) PetscCall(DMLabelSetValue(vtkLabel, c, 1)); if (ghostLabel) { PetscCall(DMPlexGetHeightStratum(dmNew, 1, &fStart, &fEnd)); for (f = fStart; f < fEnd; ++f) { PetscInt numCells; PetscCall(DMPlexGetSupportSize(dmNew, f, &numCells)); if (numCells < 2) { PetscCall(DMLabelSetValue(ghostLabel, f, 1)); } else { const PetscInt *cells = NULL; PetscInt vA, vB; PetscCall(DMPlexGetSupport(dmNew, f, &cells)); PetscCall(DMLabelGetValue(vtkLabel, cells[0], &vA)); PetscCall(DMLabelGetValue(vtkLabel, cells[1], &vB)); if (vA != 1 && vB != 1) PetscCall(DMLabelSetValue(ghostLabel, f, 1)); } } } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexShiftTree_Internal(DM dm, PetscInt depthShift[], DM dmNew) { DM refTree; PetscSection pSec; PetscInt *parents, *childIDs; PetscFunctionBegin; PetscCall(DMPlexGetReferenceTree(dm, &refTree)); PetscCall(DMPlexSetReferenceTree(dmNew, refTree)); PetscCall(DMPlexGetTree(dm, &pSec, &parents, &childIDs, NULL, NULL)); if (pSec) { PetscInt p, pStart, pEnd, *parentsShifted, pStartShifted, pEndShifted, depth; PetscInt *childIDsShifted; PetscSection pSecShifted; PetscCall(PetscSectionGetChart(pSec, &pStart, &pEnd)); PetscCall(DMPlexGetDepth(dm, &depth)); pStartShifted = DMPlexShiftPoint_Internal(pStart, depth, depthShift); pEndShifted = DMPlexShiftPoint_Internal(pEnd, depth, depthShift); PetscCall(PetscMalloc2(pEndShifted - pStartShifted, &parentsShifted, pEndShifted - pStartShifted, &childIDsShifted)); PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dmNew), &pSecShifted)); PetscCall(PetscSectionSetChart(pSecShifted, pStartShifted, pEndShifted)); for (p = pStartShifted; p < pEndShifted; p++) { /* start off assuming no children */ PetscCall(PetscSectionSetDof(pSecShifted, p, 0)); } for (p = pStart; p < pEnd; p++) { PetscInt dof; PetscInt pNew = DMPlexShiftPoint_Internal(p, depth, depthShift); PetscCall(PetscSectionGetDof(pSec, p, &dof)); PetscCall(PetscSectionSetDof(pSecShifted, pNew, dof)); } PetscCall(PetscSectionSetUp(pSecShifted)); for (p = pStart; p < pEnd; p++) { PetscInt dof; PetscInt pNew = DMPlexShiftPoint_Internal(p, depth, depthShift); PetscCall(PetscSectionGetDof(pSec, p, &dof)); if (dof) { PetscInt off, offNew; PetscCall(PetscSectionGetOffset(pSec, p, &off)); PetscCall(PetscSectionGetOffset(pSecShifted, pNew, &offNew)); parentsShifted[offNew] = DMPlexShiftPoint_Internal(parents[off], depth, depthShift); childIDsShifted[offNew] = childIDs[off]; } } PetscCall(DMPlexSetTree(dmNew, pSecShifted, parentsShifted, childIDsShifted)); PetscCall(PetscFree2(parentsShifted, childIDsShifted)); PetscCall(PetscSectionDestroy(&pSecShifted)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexConstructGhostCells_Internal(DM dm, DMLabel label, PetscInt *numGhostCells, DM gdm) { PetscSF sf; IS valueIS; const PetscInt *values, *leaves; PetscInt *depthShift; PetscInt d, depth = 0, nleaves, loc, Ng, numFS, fs, fStart, fEnd, ghostCell, cEnd, c; const PetscReal *maxCell, *Lstart, *L; PetscFunctionBegin; PetscCall(DMGetPointSF(dm, &sf)); PetscCall(PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL)); nleaves = PetscMax(0, nleaves); PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd)); /* Count ghost cells */ PetscCall(DMLabelGetValueIS(label, &valueIS)); PetscCall(ISGetLocalSize(valueIS, &numFS)); PetscCall(ISGetIndices(valueIS, &values)); Ng = 0; for (fs = 0; fs < numFS; ++fs) { IS faceIS; const PetscInt *faces; PetscInt numFaces, f, numBdFaces = 0; PetscCall(DMLabelGetStratumIS(label, values[fs], &faceIS)); PetscCall(ISGetLocalSize(faceIS, &numFaces)); PetscCall(ISGetIndices(faceIS, &faces)); for (f = 0; f < numFaces; ++f) { PetscInt numChildren; PetscCall(PetscFindInt(faces[f], nleaves, leaves, &loc)); PetscCall(DMPlexGetTreeChildren(dm, faces[f], &numChildren, NULL)); /* non-local and ancestors points don't get to register ghosts */ if (loc >= 0 || numChildren) continue; if ((faces[f] >= fStart) && (faces[f] < fEnd)) ++numBdFaces; } Ng += numBdFaces; PetscCall(ISRestoreIndices(faceIS, &faces)); PetscCall(ISDestroy(&faceIS)); } PetscCall(DMPlexGetDepth(dm, &depth)); PetscCall(PetscMalloc1(2 * (depth + 1), &depthShift)); for (d = 0; d <= depth; d++) { PetscInt dEnd; PetscCall(DMPlexGetDepthStratum(dm, d, NULL, &dEnd)); depthShift[2 * d] = dEnd; depthShift[2 * d + 1] = 0; } if (depth >= 0) depthShift[2 * depth + 1] = Ng; PetscCall(DMPlexShiftPointSetUp_Internal(depth, depthShift)); PetscCall(DMPlexShiftSizes_Internal(dm, depthShift, gdm)); /* Step 3: Set cone/support sizes for new points */ PetscCall(DMPlexGetHeightStratum(dm, 0, NULL, &cEnd)); for (c = cEnd; c < cEnd + Ng; ++c) PetscCall(DMPlexSetConeSize(gdm, c, 1)); for (fs = 0; fs < numFS; ++fs) { IS faceIS; const PetscInt *faces; PetscInt numFaces, f; PetscCall(DMLabelGetStratumIS(label, values[fs], &faceIS)); PetscCall(ISGetLocalSize(faceIS, &numFaces)); PetscCall(ISGetIndices(faceIS, &faces)); for (f = 0; f < numFaces; ++f) { PetscInt size, numChildren; PetscCall(PetscFindInt(faces[f], nleaves, leaves, &loc)); PetscCall(DMPlexGetTreeChildren(dm, faces[f], &numChildren, NULL)); if (loc >= 0 || numChildren) continue; if ((faces[f] < fStart) || (faces[f] >= fEnd)) continue; PetscCall(DMPlexGetSupportSize(dm, faces[f], &size)); PetscCheck(size == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "DM has boundary face %" PetscInt_FMT " with %" PetscInt_FMT " support cells", faces[f], size); PetscCall(DMPlexSetSupportSize(gdm, faces[f] + Ng, 2)); } PetscCall(ISRestoreIndices(faceIS, &faces)); PetscCall(ISDestroy(&faceIS)); } /* Step 4: Setup ghosted DM */ PetscCall(DMSetUp(gdm)); PetscCall(DMPlexShiftPoints_Internal(dm, depthShift, gdm)); /* Step 6: Set cones and supports for new points */ ghostCell = cEnd; for (fs = 0; fs < numFS; ++fs) { IS faceIS; const PetscInt *faces; PetscInt numFaces, f; PetscCall(DMLabelGetStratumIS(label, values[fs], &faceIS)); PetscCall(ISGetLocalSize(faceIS, &numFaces)); PetscCall(ISGetIndices(faceIS, &faces)); for (f = 0; f < numFaces; ++f) { PetscInt newFace = faces[f] + Ng, numChildren; PetscCall(PetscFindInt(faces[f], nleaves, leaves, &loc)); PetscCall(DMPlexGetTreeChildren(dm, faces[f], &numChildren, NULL)); if (loc >= 0 || numChildren) continue; if ((faces[f] < fStart) || (faces[f] >= fEnd)) continue; PetscCall(DMPlexSetCone(gdm, ghostCell, &newFace)); PetscCall(DMPlexInsertSupport(gdm, newFace, 1, ghostCell)); ++ghostCell; } PetscCall(ISRestoreIndices(faceIS, &faces)); PetscCall(ISDestroy(&faceIS)); } PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); PetscCall(DMPlexShiftCoordinates_Internal(dm, depthShift, gdm)); PetscCall(DMPlexShiftSF_Internal(dm, depthShift, gdm)); PetscCall(DMPlexShiftLabels_Internal(dm, depthShift, gdm)); PetscCall(DMPlexCreateVTKLabel_Internal(dm, PETSC_TRUE, gdm)); PetscCall(DMPlexShiftTree_Internal(dm, depthShift, gdm)); PetscCall(PetscFree(depthShift)); for (c = cEnd; c < cEnd + Ng; ++c) PetscCall(DMPlexSetCellType(gdm, c, DM_POLYTOPE_FV_GHOST)); /* Step 7: Periodicity */ PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L)); PetscCall(DMSetPeriodicity(gdm, maxCell, Lstart, L)); if (numGhostCells) *numGhostCells = Ng; PetscFunctionReturn(PETSC_SUCCESS); } /*@C DMPlexConstructGhostCells - Construct ghost cells which connect to every boundary face Collective Input Parameters: + dm - The original `DM` - labelName - The label specifying the boundary faces, or "Face Sets" if this is `NULL` Output Parameters: + numGhostCells - The number of ghost cells added to the `DM` - dmGhosted - The new `DM` Level: developer Note: If no label exists of that name, one will be created marking all boundary faces .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()` @*/ PetscErrorCode DMPlexConstructGhostCells(DM dm, const char labelName[], PetscInt *numGhostCells, DM *dmGhosted) { DM gdm; DMLabel label; const char *name = labelName ? labelName : "Face Sets"; PetscInt dim, Ng = 0; PetscBool useCone, useClosure; PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); if (numGhostCells) PetscAssertPointer(numGhostCells, 3); PetscAssertPointer(dmGhosted, 4); PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), &gdm)); PetscCall(DMSetType(gdm, DMPLEX)); PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMSetDimension(gdm, dim)); PetscCall(DMGetBasicAdjacency(dm, &useCone, &useClosure)); PetscCall(DMSetBasicAdjacency(gdm, useCone, useClosure)); PetscCall(DMGetLabel(dm, name, &label)); if (!label) { /* Get label for boundary faces */ PetscCall(DMCreateLabel(dm, name)); PetscCall(DMGetLabel(dm, name, &label)); PetscCall(DMPlexMarkBoundaryFaces(dm, 1, label)); } PetscCall(DMPlexConstructGhostCells_Internal(dm, label, &Ng, gdm)); PetscCall(DMCopyDisc(dm, gdm)); PetscCall(DMPlexCopy_Internal(dm, PETSC_TRUE, PETSC_TRUE, gdm)); gdm->setfromoptionscalled = dm->setfromoptionscalled; if (numGhostCells) *numGhostCells = Ng; *dmGhosted = gdm; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DivideCells_Private(DM dm, DMLabel label, DMPlexPointQueue queue) { PetscInt dim, d, shift = 100, *pStart, *pEnd; PetscFunctionBegin; PetscCall(DMGetDimension(dm, &dim)); PetscCall(PetscMalloc2(dim, &pStart, dim, &pEnd)); for (d = 0; d < dim; ++d) PetscCall(DMPlexGetDepthStratum(dm, d, &pStart[d], &pEnd[d])); while (!DMPlexPointQueueEmpty(queue)) { PetscInt cell = -1; PetscInt *closure = NULL; PetscInt closureSize, cl, cval; PetscCall(DMPlexPointQueueDequeue(queue, &cell)); PetscCall(DMLabelGetValue(label, cell, &cval)); PetscCall(DMPlexGetTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure)); /* Mark points in the cell closure that touch the fault */ for (d = 0; d < dim; ++d) { for (cl = 0; cl < closureSize * 2; cl += 2) { const PetscInt clp = closure[cl]; PetscInt clval; if ((clp < pStart[d]) || (clp >= pEnd[d])) continue; PetscCall(DMLabelGetValue(label, clp, &clval)); if (clval == -1) { const PetscInt *cone; PetscInt coneSize, c; /* If a cone point touches the fault, then this point touches the fault */ PetscCall(DMPlexGetCone(dm, clp, &cone)); PetscCall(DMPlexGetConeSize(dm, clp, &coneSize)); for (c = 0; c < coneSize; ++c) { PetscInt cpval; PetscCall(DMLabelGetValue(label, cone[c], &cpval)); if (cpval != -1) { PetscInt dep; PetscCall(DMPlexGetPointDepth(dm, clp, &dep)); clval = cval < 0 ? -(shift + dep) : shift + dep; PetscCall(DMLabelSetValue(label, clp, clval)); break; } } } /* Mark neighbor cells through marked faces (these cells must also touch the fault) */ if (d == dim - 1 && clval != -1) { const PetscInt *support; PetscInt supportSize, s, nval; PetscCall(DMPlexGetSupport(dm, clp, &support)); PetscCall(DMPlexGetSupportSize(dm, clp, &supportSize)); for (s = 0; s < supportSize; ++s) { PetscCall(DMLabelGetValue(label, support[s], &nval)); if (nval == -1) { PetscCall(DMLabelSetValue(label, support[s], clval < 0 ? clval - 1 : clval + 1)); PetscCall(DMPlexPointQueueEnqueue(queue, support[s])); } } } } } PetscCall(DMPlexRestoreTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure)); } PetscCall(PetscFree2(pStart, pEnd)); PetscFunctionReturn(PETSC_SUCCESS); } typedef struct { DM dm; DMPlexPointQueue queue; } PointDivision; static PetscErrorCode divideCell(DMLabel label, PetscInt p, PetscInt val, void *ctx) { PointDivision *div = (PointDivision *)ctx; PetscInt cval = val < 0 ? val - 1 : val + 1; const PetscInt *support; PetscInt supportSize, s; PetscFunctionBegin; PetscCall(DMPlexGetSupport(div->dm, p, &support)); PetscCall(DMPlexGetSupportSize(div->dm, p, &supportSize)); for (s = 0; s < supportSize; ++s) { PetscCall(DMLabelSetValue(label, support[s], cval)); PetscCall(DMPlexPointQueueEnqueue(div->queue, support[s])); } PetscFunctionReturn(PETSC_SUCCESS); } /* Mark cells by label propagation */ static PetscErrorCode DMPlexLabelFaultHalo(DM dm, DMLabel faultLabel) { DMPlexPointQueue queue = NULL; PointDivision div; PetscSF pointSF; IS pointIS; const PetscInt *points; PetscBool empty; PetscInt dim, shift = 100, n, i; PetscFunctionBegin; PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMPlexPointQueueCreate(1024, &queue)); div.dm = dm; div.queue = queue; /* Enqueue cells on fault */ PetscCall(DMLabelGetStratumIS(faultLabel, shift + dim, &pointIS)); if (pointIS) { PetscCall(ISGetLocalSize(pointIS, &n)); PetscCall(ISGetIndices(pointIS, &points)); for (i = 0; i < n; ++i) PetscCall(DMPlexPointQueueEnqueue(queue, points[i])); PetscCall(ISRestoreIndices(pointIS, &points)); PetscCall(ISDestroy(&pointIS)); } PetscCall(DMLabelGetStratumIS(faultLabel, -(shift + dim), &pointIS)); if (pointIS) { PetscCall(ISGetLocalSize(pointIS, &n)); PetscCall(ISGetIndices(pointIS, &points)); for (i = 0; i < n; ++i) PetscCall(DMPlexPointQueueEnqueue(queue, points[i])); PetscCall(ISRestoreIndices(pointIS, &points)); PetscCall(ISDestroy(&pointIS)); } PetscCall(DMGetPointSF(dm, &pointSF)); PetscCall(DMLabelPropagateBegin(faultLabel, pointSF)); /* While edge queue is not empty: */ PetscCall(DMPlexPointQueueEmptyCollective((PetscObject)dm, queue, &empty)); while (!empty) { PetscCall(DivideCells_Private(dm, faultLabel, queue)); PetscCall(DMLabelPropagatePush(faultLabel, pointSF, divideCell, &div)); PetscCall(DMPlexPointQueueEmptyCollective((PetscObject)dm, queue, &empty)); } PetscCall(DMLabelPropagateEnd(faultLabel, pointSF)); PetscCall(DMPlexPointQueueDestroy(&queue)); PetscFunctionReturn(PETSC_SUCCESS); } /* We are adding three kinds of points here: Replicated: Copies of points which exist in the mesh, such as vertices identified across a fault Non-replicated: Points which exist on the fault, but are not replicated Ghost: These are shared fault faces which are not owned by this process. These do not produce hybrid cells and do not replicate Hybrid: Entirely new points, such as cohesive cells When creating subsequent cohesive cells, we shift the old hybrid cells to the end of the numbering at each depth so that the new split/hybrid points can be inserted as a block. */ static PetscErrorCode DMPlexConstructCohesiveCells_Internal(DM dm, DMLabel label, DMLabel splitLabel, DM sdm) { MPI_Comm comm; IS valueIS; PetscInt numSP = 0; /* The number of depths for which we have replicated points */ const PetscInt *values; /* List of depths for which we have replicated points */ IS *splitIS; IS *unsplitIS; IS ghostIS; PetscInt *numSplitPoints; /* The number of replicated points at each depth */ PetscInt *numUnsplitPoints; /* The number of non-replicated points at each depth which still give rise to hybrid points */ PetscInt *numHybridPoints; /* The number of new hybrid points at each depth */ PetscInt *numHybridPointsOld; /* The number of existing hybrid points at each depth */ PetscInt numGhostPoints; /* The number of unowned, shared fault faces */ const PetscInt **splitPoints; /* Replicated points for each depth */ const PetscInt **unsplitPoints; /* Non-replicated points for each depth */ const PetscInt *ghostPoints; /* Ghost fault faces */ PetscSection coordSection; Vec coordinates; PetscScalar *coords; PetscInt *depthMax; /* The first hybrid point at each depth in the original mesh */ PetscInt *depthEnd; /* The point limit at each depth in the original mesh */ PetscInt *depthShift; /* Number of replicated+hybrid points at each depth */ PetscInt *pMaxNew; /* The first replicated point at each depth in the new mesh, hybrids come after this */ PetscInt *coneNew, *coneONew, *supportNew; PetscInt shift = 100, shift2 = 200, depth = 0, dep, dim, d, sp, maxConeSize, maxSupportSize, maxConeSizeNew, maxSupportSizeNew, numLabels, vStart, vEnd, pEnd, p, v; PetscFunctionBegin; PetscCall(PetscObjectGetComm((PetscObject)dm, &comm)); PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMPlexGetDepth(dm, &depth)); PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd)); /* We do not want this label automatically computed, instead we compute it here */ PetscCall(DMCreateLabel(sdm, "celltype")); /* Count split points and add cohesive cells */ PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize)); PetscCall(PetscMalloc5(depth + 1, &depthMax, depth + 1, &depthEnd, 2 * (depth + 1), &depthShift, depth + 1, &pMaxNew, depth + 1, &numHybridPointsOld)); PetscCall(PetscMalloc7(depth + 1, &splitIS, depth + 1, &unsplitIS, depth + 1, &numSplitPoints, depth + 1, &numUnsplitPoints, depth + 1, &numHybridPoints, depth + 1, &splitPoints, depth + 1, &unsplitPoints)); for (d = 0; d <= depth; ++d) { PetscCall(DMPlexGetDepthStratum(dm, d, NULL, &pMaxNew[d])); PetscCall(DMPlexGetTensorPrismBounds_Internal(dm, d, &depthMax[d], NULL)); depthEnd[d] = pMaxNew[d]; depthMax[d] = depthMax[d] < 0 ? depthEnd[d] : depthMax[d]; numSplitPoints[d] = 0; numUnsplitPoints[d] = 0; numHybridPoints[d] = 0; numHybridPointsOld[d] = depthMax[d] < 0 ? 0 : depthEnd[d] - depthMax[d]; splitPoints[d] = NULL; unsplitPoints[d] = NULL; splitIS[d] = NULL; unsplitIS[d] = NULL; /* we are shifting the existing hybrid points with the stratum behind them, so * the split comes at the end of the normal points, i.e., at depthMax[d] */ depthShift[2 * d] = depthMax[d]; depthShift[2 * d + 1] = 0; } numGhostPoints = 0; ghostPoints = NULL; if (label) { PetscCall(DMLabelGetValueIS(label, &valueIS)); PetscCall(ISGetLocalSize(valueIS, &numSP)); PetscCall(ISGetIndices(valueIS, &values)); } for (sp = 0; sp < numSP; ++sp) { const PetscInt dep = values[sp]; if ((dep < 0) || (dep > depth)) continue; PetscCall(DMLabelGetStratumIS(label, dep, &splitIS[dep])); if (splitIS[dep]) { PetscCall(ISGetLocalSize(splitIS[dep], &numSplitPoints[dep])); PetscCall(ISGetIndices(splitIS[dep], &splitPoints[dep])); } PetscCall(DMLabelGetStratumIS(label, shift2 + dep, &unsplitIS[dep])); if (unsplitIS[dep]) { PetscCall(ISGetLocalSize(unsplitIS[dep], &numUnsplitPoints[dep])); PetscCall(ISGetIndices(unsplitIS[dep], &unsplitPoints[dep])); } } PetscCall(DMLabelGetStratumIS(label, shift2 + dim - 1, &ghostIS)); if (ghostIS) { PetscCall(ISGetLocalSize(ghostIS, &numGhostPoints)); PetscCall(ISGetIndices(ghostIS, &ghostPoints)); } /* Calculate number of hybrid points */ for (d = 1; d <= depth; ++d) numHybridPoints[d] = numSplitPoints[d - 1] + numUnsplitPoints[d - 1]; /* There is a hybrid cell/face/edge for every split face/edge/vertex */ for (d = 0; d <= depth; ++d) depthShift[2 * d + 1] = numSplitPoints[d] + numHybridPoints[d]; PetscCall(DMPlexShiftPointSetUp_Internal(depth, depthShift)); /* the end of the points in this stratum that come before the new points: * shifting pMaxNew[d] gets the new start of the next stratum, then count back the old hybrid points and the newly * added points */ for (d = 0; d <= depth; ++d) pMaxNew[d] = DMPlexShiftPoint_Internal(pMaxNew[d], depth, depthShift) - (numHybridPointsOld[d] + numSplitPoints[d] + numHybridPoints[d]); PetscCall(DMPlexShiftSizes_Internal(dm, depthShift, sdm)); /* Step 3: Set cone/support sizes for new points */ for (dep = 0; dep <= depth; ++dep) { for (p = 0; p < numSplitPoints[dep]; ++p) { const PetscInt oldp = splitPoints[dep][p]; const PetscInt newp = DMPlexShiftPoint_Internal(oldp, depth, depthShift) /*oldp + depthOffset[dep]*/; const PetscInt splitp = p + pMaxNew[dep]; const PetscInt *support; DMPolytopeType ct; PetscInt coneSize, supportSize, qf, qn, qp, e; PetscCall(DMPlexGetConeSize(dm, oldp, &coneSize)); PetscCall(DMPlexSetConeSize(sdm, splitp, coneSize)); PetscCall(DMPlexGetSupportSize(dm, oldp, &supportSize)); PetscCall(DMPlexSetSupportSize(sdm, splitp, supportSize)); PetscCall(DMPlexGetCellType(dm, oldp, &ct)); PetscCall(DMPlexSetCellType(sdm, splitp, ct)); if (dep == depth - 1) { const PetscInt hybcell = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1]; /* Add cohesive cells, they are prisms */ PetscCall(DMPlexSetConeSize(sdm, hybcell, 2 + coneSize)); switch (coneSize) { case 2: PetscCall(DMPlexSetCellType(sdm, hybcell, DM_POLYTOPE_SEG_PRISM_TENSOR)); break; case 3: PetscCall(DMPlexSetCellType(sdm, hybcell, DM_POLYTOPE_TRI_PRISM_TENSOR)); break; case 4: PetscCall(DMPlexSetCellType(sdm, hybcell, DM_POLYTOPE_QUAD_PRISM_TENSOR)); break; } /* Shared fault faces with only one support cell now have two with the cohesive cell */ /* TODO Check thaat oldp has rootdegree == 1 */ if (supportSize == 1) { const PetscInt *support; PetscInt val; PetscCall(DMPlexGetSupport(dm, oldp, &support)); PetscCall(DMLabelGetValue(label, support[0], &val)); if (val < 0) PetscCall(DMPlexSetSupportSize(sdm, splitp, 2)); else PetscCall(DMPlexSetSupportSize(sdm, newp, 2)); } } else if (dep == 0) { const PetscInt hybedge = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1]; PetscCall(DMPlexGetSupport(dm, oldp, &support)); for (e = 0, qn = 0, qp = 0, qf = 0; e < supportSize; ++e) { PetscInt val; PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == 1) ++qf; if ((val == 1) || (val == (shift + 1))) ++qn; if ((val == 1) || (val == -(shift + 1))) ++qp; } /* Split old vertex: Edges into original vertex and new cohesive edge */ PetscCall(DMPlexSetSupportSize(sdm, newp, qn + 1)); /* Split new vertex: Edges into split vertex and new cohesive edge */ PetscCall(DMPlexSetSupportSize(sdm, splitp, qp + 1)); /* Add hybrid edge */ PetscCall(DMPlexSetConeSize(sdm, hybedge, 2)); PetscCall(DMPlexSetSupportSize(sdm, hybedge, qf)); PetscCall(DMPlexSetCellType(sdm, hybedge, DM_POLYTOPE_POINT_PRISM_TENSOR)); } else if (dep == dim - 2) { const PetscInt hybface = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1]; PetscCall(DMPlexGetSupport(dm, oldp, &support)); for (e = 0, qn = 0, qp = 0, qf = 0; e < supportSize; ++e) { PetscInt val; PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == dim - 1) ++qf; if ((val == dim - 1) || (val == (shift + dim - 1))) ++qn; if ((val == dim - 1) || (val == -(shift + dim - 1))) ++qp; } /* Split old edge: Faces into original edge and cohesive face (positive side?) */ PetscCall(DMPlexSetSupportSize(sdm, newp, qn + 1)); /* Split new edge: Faces into split edge and cohesive face (negative side?) */ PetscCall(DMPlexSetSupportSize(sdm, splitp, qp + 1)); /* Add hybrid face */ PetscCall(DMPlexSetConeSize(sdm, hybface, 4)); PetscCall(DMPlexSetSupportSize(sdm, hybface, qf)); PetscCall(DMPlexSetCellType(sdm, hybface, DM_POLYTOPE_SEG_PRISM_TENSOR)); } } } for (dep = 0; dep <= depth; ++dep) { for (p = 0; p < numUnsplitPoints[dep]; ++p) { const PetscInt oldp = unsplitPoints[dep][p]; const PetscInt newp = DMPlexShiftPoint_Internal(oldp, depth, depthShift) /*oldp + depthOffset[dep]*/; const PetscInt *support; PetscInt coneSize, supportSize, qf, e, s; PetscCall(DMPlexGetConeSize(dm, oldp, &coneSize)); PetscCall(DMPlexGetSupportSize(dm, oldp, &supportSize)); PetscCall(DMPlexGetSupport(dm, oldp, &support)); if (dep == 0) { const PetscInt hybedge = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1] + numSplitPoints[dep]; /* Unsplit vertex: Edges into original vertex, split edges, and new cohesive edge twice */ for (s = 0, qf = 0; s < supportSize; ++s, ++qf) { PetscCall(PetscFindInt(support[s], numSplitPoints[dep + 1], splitPoints[dep + 1], &e)); if (e >= 0) ++qf; } PetscCall(DMPlexSetSupportSize(sdm, newp, qf + 2)); /* Add hybrid edge */ PetscCall(DMPlexSetConeSize(sdm, hybedge, 2)); for (e = 0, qf = 0; e < supportSize; ++e) { PetscInt val; PetscCall(DMLabelGetValue(label, support[e], &val)); /* Split and unsplit edges produce hybrid faces */ if (val == 1) ++qf; if (val == (shift2 + 1)) ++qf; } PetscCall(DMPlexSetSupportSize(sdm, hybedge, qf)); PetscCall(DMPlexSetCellType(sdm, hybedge, DM_POLYTOPE_POINT_PRISM_TENSOR)); } else if (dep == dim - 2) { const PetscInt hybface = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1] + numSplitPoints[dep]; PetscInt val; for (e = 0, qf = 0; e < supportSize; ++e) { PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == dim - 1) qf += 2; else ++qf; } /* Unsplit edge: Faces into original edge, split face, and cohesive face twice */ PetscCall(DMPlexSetSupportSize(sdm, newp, qf + 2)); /* Add hybrid face */ for (e = 0, qf = 0; e < supportSize; ++e) { PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == dim - 1) ++qf; } PetscCall(DMPlexSetConeSize(sdm, hybface, 4)); PetscCall(DMPlexSetSupportSize(sdm, hybface, qf)); PetscCall(DMPlexSetCellType(sdm, hybface, DM_POLYTOPE_SEG_PRISM_TENSOR)); } } } /* Step 4: Setup split DM */ PetscCall(DMSetUp(sdm)); PetscCall(DMPlexShiftPoints_Internal(dm, depthShift, sdm)); PetscCall(DMPlexGetMaxSizes(sdm, &maxConeSizeNew, &maxSupportSizeNew)); PetscCall(PetscMalloc3(PetscMax(maxConeSize, maxConeSizeNew) * 3, &coneNew, PetscMax(maxConeSize, maxConeSizeNew) * 3, &coneONew, PetscMax(maxSupportSize, maxSupportSizeNew), &supportNew)); /* Step 6: Set cones and supports for new points */ for (dep = 0; dep <= depth; ++dep) { for (p = 0; p < numSplitPoints[dep]; ++p) { const PetscInt oldp = splitPoints[dep][p]; const PetscInt newp = DMPlexShiftPoint_Internal(oldp, depth, depthShift) /*oldp + depthOffset[dep]*/; const PetscInt splitp = p + pMaxNew[dep]; const PetscInt *cone, *support, *ornt; DMPolytopeType ct; PetscInt coneSize, supportSize, q, qf, qn, qp, v, e, s; PetscCall(DMPlexGetCellType(dm, oldp, &ct)); PetscCall(DMPlexGetConeSize(dm, oldp, &coneSize)); PetscCall(DMPlexGetCone(dm, oldp, &cone)); PetscCall(DMPlexGetConeOrientation(dm, oldp, &ornt)); PetscCall(DMPlexGetSupportSize(dm, oldp, &supportSize)); PetscCall(DMPlexGetSupport(dm, oldp, &support)); if (dep == depth - 1) { PetscBool hasUnsplit = PETSC_FALSE; const PetscInt hybcell = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1]; const PetscInt *supportF; coneONew[0] = coneONew[1] = -1000; /* Split face: copy in old face to new face to start */ PetscCall(DMPlexGetSupport(sdm, newp, &supportF)); PetscCall(DMPlexSetSupport(sdm, splitp, supportF)); /* Split old face: old vertices/edges in cone so no change */ /* Split new face: new vertices/edges in cone */ for (q = 0; q < coneSize; ++q) { PetscCall(PetscFindInt(cone[q], numSplitPoints[dep - 1], splitPoints[dep - 1], &v)); if (v < 0) { PetscCall(PetscFindInt(cone[q], numUnsplitPoints[dep - 1], unsplitPoints[dep - 1], &v)); PetscCheck(v >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not locate point %" PetscInt_FMT " in split or unsplit points of depth %" PetscInt_FMT, cone[q], dep - 1); coneNew[2 + q] = DMPlexShiftPoint_Internal(cone[q], depth, depthShift) /*cone[q] + depthOffset[dep-1]*/; hasUnsplit = PETSC_TRUE; } else { coneNew[2 + q] = v + pMaxNew[dep - 1]; if (dep > 1) { const PetscInt *econe; PetscInt econeSize, r, vs, vu; PetscCall(DMPlexGetConeSize(dm, cone[q], &econeSize)); PetscCall(DMPlexGetCone(dm, cone[q], &econe)); for (r = 0; r < econeSize; ++r) { PetscCall(PetscFindInt(econe[r], numSplitPoints[dep - 2], splitPoints[dep - 2], &vs)); PetscCall(PetscFindInt(econe[r], numUnsplitPoints[dep - 2], unsplitPoints[dep - 2], &vu)); if (vs >= 0) continue; PetscCheck(vu >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not locate point %" PetscInt_FMT " in split or unsplit points of depth %" PetscInt_FMT, econe[r], dep - 2); hasUnsplit = PETSC_TRUE; } } } } PetscCall(DMPlexSetCone(sdm, splitp, &coneNew[2])); PetscCall(DMPlexSetConeOrientation(sdm, splitp, ornt)); /* Face support */ PetscInt vals[2]; PetscCall(DMLabelGetValue(label, support[0], &vals[0])); if (supportSize > 1) PetscCall(DMLabelGetValue(label, support[1], &vals[1])); else vals[1] = -vals[0]; PetscCheck(vals[0] * vals[1] < 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid support labels %" PetscInt_FMT " %" PetscInt_FMT, vals[0], vals[1]); for (s = 0; s < 2; ++s) { if (s >= supportSize) { if (vals[s] < 0) { /* Ghost old face: Replace negative side cell with cohesive cell */ PetscCall(DMPlexInsertSupport(sdm, newp, s, hybcell)); } else { /* Ghost new face: Replace positive side cell with cohesive cell */ PetscCall(DMPlexInsertSupport(sdm, splitp, s, hybcell)); } } else { if (vals[s] < 0) { /* Split old face: Replace negative side cell with cohesive cell */ PetscCall(DMPlexInsertSupport(sdm, newp, s, hybcell)); } else { /* Split new face: Replace positive side cell with cohesive cell */ PetscCall(DMPlexInsertSupport(sdm, splitp, s, hybcell)); } } } /* Get orientation for cohesive face using the positive side cell */ { const PetscInt *ncone, *nconeO; PetscInt nconeSize, nc, ocell; PetscBool flip = PETSC_FALSE; if (supportSize > 1) { ocell = vals[0] < 0 ? support[1] : support[0]; } else { ocell = support[0]; flip = vals[0] < 0 ? PETSC_TRUE : PETSC_FALSE; } PetscCall(DMPlexGetConeSize(dm, ocell, &nconeSize)); PetscCall(DMPlexGetCone(dm, ocell, &ncone)); PetscCall(DMPlexGetConeOrientation(dm, ocell, &nconeO)); for (nc = 0; nc < nconeSize; ++nc) { if (ncone[nc] == oldp) { coneONew[0] = flip ? -(nconeO[nc] + 1) : nconeO[nc]; break; } } PetscCheck(nc < nconeSize, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not locate face %" PetscInt_FMT " in neighboring cell %" PetscInt_FMT, oldp, ocell); } /* Cohesive cell: Old and new split face, then new cohesive faces */ { const PetscInt No = DMPolytopeTypeGetNumArrangments(ct) / 2; PetscCheck((coneONew[0] >= -No) && (coneONew[0] < No), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid %s orientation %" PetscInt_FMT, DMPolytopeTypes[ct], coneONew[0]); } const PetscInt *arr = DMPolytopeTypeGetArrangment(ct, coneONew[0]); coneNew[0] = newp; /* Extracted negative side orientation above */ coneNew[1] = splitp; coneONew[1] = coneONew[0]; for (q = 0; q < coneSize; ++q) { /* Hybrid faces must follow order from oriented end face */ const PetscInt qa = arr[q * 2 + 0]; const PetscInt qo = arr[q * 2 + 1]; DMPolytopeType ft = dep == 2 ? DM_POLYTOPE_SEGMENT : DM_POLYTOPE_POINT; PetscCall(PetscFindInt(cone[qa], numSplitPoints[dep - 1], splitPoints[dep - 1], &v)); if (v < 0) { PetscCall(PetscFindInt(cone[qa], numUnsplitPoints[dep - 1], unsplitPoints[dep - 1], &v)); coneNew[2 + q] = v + pMaxNew[dep] + numSplitPoints[dep] + numSplitPoints[dep - 1]; } else { coneNew[2 + q] = v + pMaxNew[dep] + numSplitPoints[dep]; } coneONew[2 + q] = DMPolytopeTypeComposeOrientation(ft, qo, ornt[qa]); } PetscCall(DMPlexSetCone(sdm, hybcell, coneNew)); PetscCall(DMPlexSetConeOrientation(sdm, hybcell, coneONew)); /* Label the hybrid cells on the boundary of the split */ if (hasUnsplit) PetscCall(DMLabelSetValue(label, -hybcell, dim)); } else if (dep == 0) { const PetscInt hybedge = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1]; /* Split old vertex: Edges in old split faces and new cohesive edge */ for (e = 0, qn = 0; e < supportSize; ++e) { PetscInt val; PetscCall(DMLabelGetValue(label, support[e], &val)); if ((val == 1) || (val == (shift + 1))) supportNew[qn++] = DMPlexShiftPoint_Internal(support[e], depth, depthShift) /*support[e] + depthOffset[dep+1]*/; } supportNew[qn] = hybedge; PetscCall(DMPlexSetSupport(sdm, newp, supportNew)); /* Split new vertex: Edges in new split faces and new cohesive edge */ for (e = 0, qp = 0; e < supportSize; ++e) { PetscInt val, edge; PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == 1) { PetscCall(PetscFindInt(support[e], numSplitPoints[dep + 1], splitPoints[dep + 1], &edge)); PetscCheck(edge >= 0, comm, PETSC_ERR_ARG_WRONG, "Edge %" PetscInt_FMT " is not a split edge", support[e]); supportNew[qp++] = edge + pMaxNew[dep + 1]; } else if (val == -(shift + 1)) { supportNew[qp++] = DMPlexShiftPoint_Internal(support[e], depth, depthShift) /*support[e] + depthOffset[dep+1]*/; } } supportNew[qp] = hybedge; PetscCall(DMPlexSetSupport(sdm, splitp, supportNew)); /* Hybrid edge: Old and new split vertex */ coneNew[0] = newp; coneNew[1] = splitp; PetscCall(DMPlexSetCone(sdm, hybedge, coneNew)); for (e = 0, qf = 0; e < supportSize; ++e) { PetscInt val, edge; PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == 1) { PetscCall(PetscFindInt(support[e], numSplitPoints[dep + 1], splitPoints[dep + 1], &edge)); PetscCheck(edge >= 0, comm, PETSC_ERR_ARG_WRONG, "Edge %" PetscInt_FMT " is not a split edge", support[e]); supportNew[qf++] = edge + pMaxNew[dep + 2] + numSplitPoints[dep + 2]; } } PetscCall(DMPlexSetSupport(sdm, hybedge, supportNew)); } else if (dep == dim - 2) { const PetscInt hybface = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1]; /* Split old edge: old vertices in cone so no change */ /* Split new edge: new vertices in cone */ for (q = 0; q < coneSize; ++q) { PetscCall(PetscFindInt(cone[q], numSplitPoints[dep - 1], splitPoints[dep - 1], &v)); if (v < 0) { PetscCall(PetscFindInt(cone[q], numUnsplitPoints[dep - 1], unsplitPoints[dep - 1], &v)); PetscCheck(v >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not locate point %" PetscInt_FMT " in split or unsplit points of depth %" PetscInt_FMT, cone[q], dep - 1); coneNew[q] = DMPlexShiftPoint_Internal(cone[q], depth, depthShift) /*cone[q] + depthOffset[dep-1]*/; } else { coneNew[q] = v + pMaxNew[dep - 1]; } } PetscCall(DMPlexSetCone(sdm, splitp, coneNew)); /* Split old edge: Faces in positive side cells and old split faces */ for (e = 0, q = 0; e < supportSize; ++e) { PetscInt val; PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == dim - 1) { supportNew[q++] = DMPlexShiftPoint_Internal(support[e], depth, depthShift) /*support[e] + depthOffset[dep+1]*/; } else if (val == (shift + dim - 1)) { supportNew[q++] = DMPlexShiftPoint_Internal(support[e], depth, depthShift) /*support[e] + depthOffset[dep+1]*/; } } supportNew[q++] = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1]; PetscCall(DMPlexSetSupport(sdm, newp, supportNew)); /* Split new edge: Faces in negative side cells and new split faces */ for (e = 0, q = 0; e < supportSize; ++e) { PetscInt val, face; PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == dim - 1) { PetscCall(PetscFindInt(support[e], numSplitPoints[dep + 1], splitPoints[dep + 1], &face)); PetscCheck(face >= 0, comm, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " is not a split face", support[e]); supportNew[q++] = face + pMaxNew[dep + 1]; } else if (val == -(shift + dim - 1)) { supportNew[q++] = DMPlexShiftPoint_Internal(support[e], depth, depthShift) /*support[e] + depthOffset[dep+1]*/; } } supportNew[q++] = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1]; PetscCall(DMPlexSetSupport(sdm, splitp, supportNew)); /* Hybrid face */ coneNew[0] = newp; coneNew[1] = splitp; for (v = 0; v < coneSize; ++v) { PetscInt vertex; PetscCall(PetscFindInt(cone[v], numSplitPoints[dep - 1], splitPoints[dep - 1], &vertex)); if (vertex < 0) { PetscCall(PetscFindInt(cone[v], numUnsplitPoints[dep - 1], unsplitPoints[dep - 1], &vertex)); PetscCheck(vertex >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not locate point %" PetscInt_FMT " in split or unsplit points of depth %" PetscInt_FMT, cone[v], dep - 1); coneNew[2 + v] = vertex + pMaxNew[dep] + numSplitPoints[dep] + numSplitPoints[dep - 1]; } else { coneNew[2 + v] = vertex + pMaxNew[dep] + numSplitPoints[dep]; } } PetscCall(DMPlexSetCone(sdm, hybface, coneNew)); for (e = 0, qf = 0; e < supportSize; ++e) { PetscInt val, face; PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == dim - 1) { PetscCall(PetscFindInt(support[e], numSplitPoints[dep + 1], splitPoints[dep + 1], &face)); PetscCheck(face >= 0, comm, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " is not a split face", support[e]); supportNew[qf++] = face + pMaxNew[dep + 2] + numSplitPoints[dep + 2]; } } PetscCall(DMPlexSetSupport(sdm, hybface, supportNew)); } } } for (dep = 0; dep <= depth; ++dep) { for (p = 0; p < numUnsplitPoints[dep]; ++p) { const PetscInt oldp = unsplitPoints[dep][p]; const PetscInt newp = DMPlexShiftPoint_Internal(oldp, depth, depthShift) /*oldp + depthOffset[dep]*/; const PetscInt *cone, *support; PetscInt coneSize, supportSize, supportSizeNew, q, qf, e, f, s; PetscCall(DMPlexGetConeSize(dm, oldp, &coneSize)); PetscCall(DMPlexGetCone(dm, oldp, &cone)); PetscCall(DMPlexGetSupportSize(dm, oldp, &supportSize)); PetscCall(DMPlexGetSupport(dm, oldp, &support)); if (dep == 0) { const PetscInt hybedge = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1] + numSplitPoints[dep]; /* Unsplit vertex */ PetscCall(DMPlexGetSupportSize(sdm, newp, &supportSizeNew)); for (s = 0, q = 0; s < supportSize; ++s) { supportNew[q++] = DMPlexShiftPoint_Internal(support[s], depth, depthShift) /*support[s] + depthOffset[dep+1]*/; PetscCall(PetscFindInt(support[s], numSplitPoints[dep + 1], splitPoints[dep + 1], &e)); if (e >= 0) supportNew[q++] = e + pMaxNew[dep + 1]; } supportNew[q++] = hybedge; supportNew[q++] = hybedge; PetscCheck(q == supportSizeNew, comm, PETSC_ERR_ARG_WRONG, "Support size %" PetscInt_FMT " != %" PetscInt_FMT " for vertex %" PetscInt_FMT, q, supportSizeNew, newp); PetscCall(DMPlexSetSupport(sdm, newp, supportNew)); /* Hybrid edge */ coneNew[0] = newp; coneNew[1] = newp; PetscCall(DMPlexSetCone(sdm, hybedge, coneNew)); for (e = 0, qf = 0; e < supportSize; ++e) { PetscInt val, edge; PetscCall(DMLabelGetValue(label, support[e], &val)); if (val == 1) { PetscCall(PetscFindInt(support[e], numSplitPoints[dep + 1], splitPoints[dep + 1], &edge)); PetscCheck(edge >= 0, comm, PETSC_ERR_ARG_WRONG, "Edge %" PetscInt_FMT " is not a split edge", support[e]); supportNew[qf++] = edge + pMaxNew[dep + 2] + numSplitPoints[dep + 2]; } else if (val == (shift2 + 1)) { PetscCall(PetscFindInt(support[e], numUnsplitPoints[dep + 1], unsplitPoints[dep + 1], &edge)); PetscCheck(edge >= 0, comm, PETSC_ERR_ARG_WRONG, "Edge %" PetscInt_FMT " is not a unsplit edge", support[e]); supportNew[qf++] = edge + pMaxNew[dep + 2] + numSplitPoints[dep + 2] + numSplitPoints[dep + 1]; } } PetscCall(DMPlexSetSupport(sdm, hybedge, supportNew)); } else if (dep == dim - 2) { const PetscInt hybface = p + pMaxNew[dep + 1] + numSplitPoints[dep + 1] + numSplitPoints[dep]; /* Unsplit edge: Faces into original edge, split face, and hybrid face twice */ for (f = 0, qf = 0; f < supportSize; ++f) { PetscInt val, face; PetscCall(DMLabelGetValue(label, support[f], &val)); if (val == dim - 1) { PetscCall(PetscFindInt(support[f], numSplitPoints[dep + 1], splitPoints[dep + 1], &face)); PetscCheck(face >= 0, comm, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " is not a split face", support[f]); supportNew[qf++] = DMPlexShiftPoint_Internal(support[f], depth, depthShift) /*support[f] + depthOffset[dep+1]*/; supportNew[qf++] = face + pMaxNew[dep + 1]; } else { supportNew[qf++] = DMPlexShiftPoint_Internal(support[f], depth, depthShift) /*support[f] + depthOffset[dep+1]*/; } } supportNew[qf++] = hybface; supportNew[qf++] = hybface; PetscCall(DMPlexGetSupportSize(sdm, newp, &supportSizeNew)); PetscCheck(qf == supportSizeNew, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Support size for unsplit edge %" PetscInt_FMT " is %" PetscInt_FMT " != %" PetscInt_FMT, newp, qf, supportSizeNew); PetscCall(DMPlexSetSupport(sdm, newp, supportNew)); /* Add hybrid face */ coneNew[0] = newp; coneNew[1] = newp; PetscCall(PetscFindInt(cone[0], numUnsplitPoints[dep - 1], unsplitPoints[dep - 1], &v)); PetscCheck(v >= 0, comm, PETSC_ERR_ARG_WRONG, "Vertex %" PetscInt_FMT " is not an unsplit vertex", cone[0]); coneNew[2] = v + pMaxNew[dep] + numSplitPoints[dep] + numSplitPoints[dep - 1]; PetscCall(PetscFindInt(cone[1], numUnsplitPoints[dep - 1], unsplitPoints[dep - 1], &v)); PetscCheck(v >= 0, comm, PETSC_ERR_ARG_WRONG, "Vertex %" PetscInt_FMT " is not an unsplit vertex", cone[1]); coneNew[3] = v + pMaxNew[dep] + numSplitPoints[dep] + numSplitPoints[dep - 1]; PetscCall(DMPlexSetCone(sdm, hybface, coneNew)); for (f = 0, qf = 0; f < supportSize; ++f) { PetscInt val, face; PetscCall(DMLabelGetValue(label, support[f], &val)); if (val == dim - 1) { PetscCall(PetscFindInt(support[f], numSplitPoints[dep + 1], splitPoints[dep + 1], &face)); supportNew[qf++] = face + pMaxNew[dep + 2] + numSplitPoints[dep + 2]; } } PetscCall(DMPlexGetSupportSize(sdm, hybface, &supportSizeNew)); PetscCheck(qf == supportSizeNew, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Support size for hybrid face %" PetscInt_FMT " is %" PetscInt_FMT " != %" PetscInt_FMT, hybface, qf, supportSizeNew); PetscCall(DMPlexSetSupport(sdm, hybface, supportNew)); } } } /* Step 6b: Replace split points in negative side cones */ for (sp = 0; sp < numSP; ++sp) { PetscInt dep = values[sp]; IS pIS; PetscInt numPoints; const PetscInt *points; if (dep >= 0) continue; PetscCall(DMLabelGetStratumIS(label, dep, &pIS)); if (!pIS) continue; dep = -dep - shift; PetscCall(ISGetLocalSize(pIS, &numPoints)); PetscCall(ISGetIndices(pIS, &points)); for (p = 0; p < numPoints; ++p) { const PetscInt oldp = points[p]; const PetscInt newp = DMPlexShiftPoint_Internal(oldp, depth, depthShift) /*depthOffset[dep] + oldp*/; const PetscInt *cone; PetscInt coneSize, c; /* PetscBool replaced = PETSC_FALSE; */ /* Negative edge: replace split vertex */ /* Negative cell: replace split face */ PetscCall(DMPlexGetConeSize(sdm, newp, &coneSize)); PetscCall(DMPlexGetCone(sdm, newp, &cone)); for (c = 0; c < coneSize; ++c) { const PetscInt coldp = DMPlexShiftPointInverse_Internal(cone[c], depth, depthShift); PetscInt csplitp, cp, val; PetscCall(DMLabelGetValue(label, coldp, &val)); if (val == dep - 1) { PetscCall(PetscFindInt(coldp, numSplitPoints[dep - 1], splitPoints[dep - 1], &cp)); PetscCheck(cp >= 0, comm, PETSC_ERR_ARG_WRONG, "Point %" PetscInt_FMT " is not a split point of dimension %" PetscInt_FMT, oldp, dep - 1); csplitp = pMaxNew[dep - 1] + cp; PetscCall(DMPlexInsertCone(sdm, newp, c, csplitp)); /* replaced = PETSC_TRUE; */ } } /* Cells with only a vertex or edge on the submesh have no replacement */ /* PetscCheck(replaced,comm, PETSC_ERR_ARG_WRONG, "The cone of point %d does not contain split points", oldp); */ } PetscCall(ISRestoreIndices(pIS, &points)); PetscCall(ISDestroy(&pIS)); } PetscCall(DMPlexReorderCohesiveSupports(sdm)); /* Step 7: Coordinates */ PetscCall(DMPlexShiftCoordinates_Internal(dm, depthShift, sdm)); PetscCall(DMGetCoordinateSection(sdm, &coordSection)); PetscCall(DMGetCoordinatesLocal(sdm, &coordinates)); PetscCall(VecGetArray(coordinates, &coords)); for (v = 0; v < (numSplitPoints ? numSplitPoints[0] : 0); ++v) { const PetscInt newp = DMPlexShiftPoint_Internal(splitPoints[0][v], depth, depthShift) /*depthOffset[0] + splitPoints[0][v]*/; const PetscInt splitp = pMaxNew[0] + v; PetscInt dof, off, soff, d; PetscCall(PetscSectionGetDof(coordSection, newp, &dof)); PetscCall(PetscSectionGetOffset(coordSection, newp, &off)); PetscCall(PetscSectionGetOffset(coordSection, splitp, &soff)); for (d = 0; d < dof; ++d) coords[soff + d] = coords[off + d]; } PetscCall(VecRestoreArray(coordinates, &coords)); /* Step 8: SF, if I can figure this out we can split the mesh in parallel */ PetscCall(DMPlexShiftSF_Internal(dm, depthShift, sdm)); /* TODO We need to associate the ghost points with the correct replica */ /* Step 9: Labels */ PetscCall(DMPlexShiftLabels_Internal(dm, depthShift, sdm)); PetscCall(DMPlexCreateVTKLabel_Internal(dm, PETSC_FALSE, sdm)); PetscCall(DMGetNumLabels(sdm, &numLabels)); for (dep = 0; dep <= depth; ++dep) { for (p = 0; p < numSplitPoints[dep]; ++p) { const PetscInt newp = DMPlexShiftPoint_Internal(splitPoints[dep][p], depth, depthShift) /*depthOffset[dep] + splitPoints[dep][p]*/; const PetscInt splitp = pMaxNew[dep] + p; PetscInt l; if (splitLabel) { const PetscInt val = 100 + dep; PetscCall(DMLabelSetValue(splitLabel, newp, val)); PetscCall(DMLabelSetValue(splitLabel, splitp, -val)); } for (l = 0; l < numLabels; ++l) { DMLabel mlabel; const char *lname; PetscInt val; PetscBool isDepth; PetscCall(DMGetLabelName(sdm, l, &lname)); PetscCall(PetscStrcmp(lname, "depth", &isDepth)); if (isDepth) continue; PetscCall(DMGetLabel(sdm, lname, &mlabel)); PetscCall(DMLabelGetValue(mlabel, newp, &val)); if (val >= 0) PetscCall(DMLabelSetValue(mlabel, splitp, val)); } } } for (sp = 0; sp < numSP; ++sp) { const PetscInt dep = values[sp]; if ((dep < 0) || (dep > depth)) continue; if (splitIS[dep]) PetscCall(ISRestoreIndices(splitIS[dep], &splitPoints[dep])); PetscCall(ISDestroy(&splitIS[dep])); if (unsplitIS[dep]) PetscCall(ISRestoreIndices(unsplitIS[dep], &unsplitPoints[dep])); PetscCall(ISDestroy(&unsplitIS[dep])); } if (ghostIS) PetscCall(ISRestoreIndices(ghostIS, &ghostPoints)); PetscCall(ISDestroy(&ghostIS)); if (label) { PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); } for (d = 0; d <= depth; ++d) { PetscCall(DMPlexGetDepthStratum(sdm, d, NULL, &pEnd)); pMaxNew[d] = pEnd - numHybridPoints[d] - numHybridPointsOld[d]; } PetscCall(PetscFree3(coneNew, coneONew, supportNew)); PetscCall(PetscFree5(depthMax, depthEnd, depthShift, pMaxNew, numHybridPointsOld)); PetscCall(PetscFree7(splitIS, unsplitIS, numSplitPoints, numUnsplitPoints, numHybridPoints, splitPoints, unsplitPoints)); PetscFunctionReturn(PETSC_SUCCESS); } /*@C DMPlexConstructCohesiveCells - Construct cohesive cells which split the face along an internal interface Collective Input Parameters: + dm - The original `DM` - label - The `DMLabel` specifying the boundary faces (this could be auto-generated) Output Parameters: + splitLabel - The `DMLabel` containing the split points, or `NULL` if no output is desired - dmSplit - The new `DM` Level: developer .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMPlexLabelCohesiveComplete()` @*/ PetscErrorCode DMPlexConstructCohesiveCells(DM dm, DMLabel label, DMLabel splitLabel, DM *dmSplit) { DM sdm; PetscInt dim; PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); PetscAssertPointer(dmSplit, 4); PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), &sdm)); PetscCall(DMSetType(sdm, DMPLEX)); PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMSetDimension(sdm, dim)); switch (dim) { case 2: case 3: PetscCall(DMPlexConstructCohesiveCells_Internal(dm, label, splitLabel, sdm)); break; default: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot construct cohesive cells for dimension %" PetscInt_FMT, dim); } *dmSplit = sdm; PetscFunctionReturn(PETSC_SUCCESS); } /* Returns the side of the surface for a given cell with a face on the surface */ static PetscErrorCode GetSurfaceSide_Static(DM dm, DM subdm, PetscInt numSubpoints, const PetscInt *subpoints, PetscInt cell, PetscInt face, PetscBool *pos) { const PetscInt *cone, *ornt; PetscInt dim, coneSize, c; PetscFunctionBegin; *pos = PETSC_TRUE; PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMPlexGetConeSize(dm, cell, &coneSize)); PetscCall(DMPlexGetCone(dm, cell, &cone)); PetscCall(DMPlexGetConeOrientation(dm, cell, &ornt)); for (c = 0; c < coneSize; ++c) { if (cone[c] == face) { PetscInt o = ornt[c]; if (subdm) { const PetscInt *subcone, *subornt; PetscInt subpoint, subface, subconeSize, sc; PetscCall(PetscFindInt(cell, numSubpoints, subpoints, &subpoint)); PetscCall(PetscFindInt(face, numSubpoints, subpoints, &subface)); PetscCall(DMPlexGetConeSize(subdm, subpoint, &subconeSize)); PetscCall(DMPlexGetCone(subdm, subpoint, &subcone)); PetscCall(DMPlexGetConeOrientation(subdm, subpoint, &subornt)); for (sc = 0; sc < subconeSize; ++sc) { if (subcone[sc] == subface) { o = subornt[0]; break; } } PetscCheck(sc < subconeSize, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find subpoint %" PetscInt_FMT " (%" PetscInt_FMT ") in cone for subpoint %" PetscInt_FMT " (%" PetscInt_FMT ")", subface, face, subpoint, cell); } if (o >= 0) *pos = PETSC_TRUE; else *pos = PETSC_FALSE; break; } } PetscCheck(c != coneSize, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Cell %" PetscInt_FMT " in split face %" PetscInt_FMT " support does not have it in the cone", cell, face); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode CheckFaultEdge_Private(DM dm, DMLabel label) { IS facePosIS, faceNegIS, dimIS; const PetscInt *points; PetscInt dim, numPoints, p, shift = 100, shift2 = 200; PetscFunctionBegin; PetscCall(DMGetDimension(dm, &dim)); /* If any faces touching the fault divide cells on either side, split them */ PetscCall(DMLabelGetStratumIS(label, shift + dim - 1, &facePosIS)); PetscCall(DMLabelGetStratumIS(label, -(shift + dim - 1), &faceNegIS)); if (!facePosIS || !faceNegIS) { PetscCall(ISDestroy(&facePosIS)); PetscCall(ISDestroy(&faceNegIS)); PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(ISExpand(facePosIS, faceNegIS, &dimIS)); PetscCall(ISDestroy(&facePosIS)); PetscCall(ISDestroy(&faceNegIS)); PetscCall(ISGetLocalSize(dimIS, &numPoints)); PetscCall(ISGetIndices(dimIS, &points)); for (p = 0; p < numPoints; ++p) { const PetscInt point = points[p]; const PetscInt *support; PetscInt supportSize, valA, valB; PetscCall(DMPlexGetSupportSize(dm, point, &supportSize)); if (supportSize != 2) continue; PetscCall(DMPlexGetSupport(dm, point, &support)); PetscCall(DMLabelGetValue(label, support[0], &valA)); PetscCall(DMLabelGetValue(label, support[1], &valB)); if ((valA == -1) || (valB == -1)) continue; if (valA * valB > 0) continue; /* Check that this face is not incident on only unsplit faces, meaning has at least one split face */ { PetscInt *closure = NULL; PetscBool split = PETSC_FALSE; PetscInt closureSize, cl; PetscCall(DMPlexGetTransitiveClosure(dm, point, PETSC_TRUE, &closureSize, &closure)); for (cl = 0; cl < closureSize * 2; cl += 2) { PetscCall(DMLabelGetValue(label, closure[cl], &valA)); if ((valA >= 0) && (valA <= dim)) { split = PETSC_TRUE; break; } } PetscCall(DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, &closureSize, &closure)); if (!split) continue; } /* Split the face */ PetscCall(DMLabelGetValue(label, point, &valA)); PetscCall(DMLabelClearValue(label, point, valA)); PetscCall(DMLabelSetValue(label, point, dim - 1)); /* Label its closure: unmarked: label as unsplit incident: relabel as split split: do nothing */ { PetscInt *closure = NULL; PetscInt closureSize, cl, dep; PetscCall(DMPlexGetTransitiveClosure(dm, point, PETSC_TRUE, &closureSize, &closure)); for (cl = 0; cl < closureSize * 2; cl += 2) { PetscCall(DMLabelGetValue(label, closure[cl], &valA)); if (valA == -1) { /* Mark as unsplit */ PetscCall(DMPlexGetPointDepth(dm, closure[cl], &dep)); PetscCall(DMLabelSetValue(label, closure[cl], shift2 + dep)); } else if (((valA >= shift) && (valA < shift2)) || ((valA <= -shift) && (valA > -shift2))) { PetscCall(DMPlexGetPointDepth(dm, closure[cl], &dep)); PetscCall(DMLabelClearValue(label, closure[cl], valA)); PetscCall(DMLabelSetValue(label, closure[cl], dep)); } } PetscCall(DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, &closureSize, &closure)); } } PetscCall(ISRestoreIndices(dimIS, &points)); PetscCall(ISDestroy(&dimIS)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexLabelCohesiveComplete - Starting with a label marking points on an internal surface, we add all other mesh pieces to complete the surface Input Parameters: + dm - The `DM` . label - A `DMLabel` marking the surface . blabel - A `DMLabel` marking the vertices on the boundary which will not be duplicated, or `NULL` to find them automatically . bvalue - Value of `DMLabel` marking the vertices on the boundary . flip - Flag to flip the submesh normal and replace points on the other side - subdm - The `DM` associated with the label, or `NULL` Output Parameter: . label - A `DMLabel` marking all surface points Level: developer Note: The vertices in blabel are called "unsplit" in the terminology from hybrid cell creation. .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexConstructCohesiveCells()`, `DMPlexLabelComplete()` @*/ PetscErrorCode DMPlexLabelCohesiveComplete(DM dm, DMLabel label, DMLabel blabel, PetscInt bvalue, PetscBool flip, DM subdm) { DMLabel depthLabel; IS dimIS, subpointIS = NULL; const PetscInt *points, *subpoints; const PetscInt rev = flip ? -1 : 1; PetscInt shift = 100, shift2 = 200, shift3 = 300, dim, depth, numPoints, numSubpoints, p, val; PetscFunctionBegin; PetscCall(DMPlexGetDepth(dm, &depth)); PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMPlexGetDepthLabel(dm, &depthLabel)); if (subdm) { PetscCall(DMPlexGetSubpointIS(subdm, &subpointIS)); if (subpointIS) { PetscCall(ISGetLocalSize(subpointIS, &numSubpoints)); PetscCall(ISGetIndices(subpointIS, &subpoints)); } } /* Mark cell on the fault, and its faces which touch the fault: cell orientation for face gives the side of the fault */ PetscCall(DMLabelGetStratumIS(label, dim - 1, &dimIS)); if (!dimIS) goto divide; PetscCall(ISGetLocalSize(dimIS, &numPoints)); PetscCall(ISGetIndices(dimIS, &points)); for (p = 0; p < numPoints; ++p) { /* Loop over fault faces */ const PetscInt *support; PetscInt supportSize, s; PetscCall(DMPlexGetSupportSize(dm, points[p], &supportSize)); #if 0 if (supportSize != 2) { const PetscInt *lp; PetscInt Nlp, pind; /* Check that for a cell with a single support face, that face is in the SF */ /* THis check only works for the remote side. We would need root side information */ PetscCall(PetscSFGetGraph(dm->sf, NULL, &Nlp, &lp, NULL)); PetscCall(PetscFindInt(points[p], Nlp, lp, &pind)); PetscCheck(pind >= 0,PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Split face %" PetscInt_FMT " has %" PetscInt_FMT " != 2 supports, and the face is not shared with another process", points[p], supportSize); } #endif PetscCall(DMPlexGetSupport(dm, points[p], &support)); for (s = 0; s < supportSize; ++s) { const PetscInt *cone; PetscInt coneSize, c; PetscBool pos; PetscCall(GetSurfaceSide_Static(dm, subdm, numSubpoints, subpoints, support[s], points[p], &pos)); if (pos) PetscCall(DMLabelSetValue(label, support[s], rev * (shift + dim))); else PetscCall(DMLabelSetValue(label, support[s], -rev * (shift + dim))); if (rev < 0) pos = !pos ? PETSC_TRUE : PETSC_FALSE; /* Put faces touching the fault in the label */ PetscCall(DMPlexGetConeSize(dm, support[s], &coneSize)); PetscCall(DMPlexGetCone(dm, support[s], &cone)); for (c = 0; c < coneSize; ++c) { const PetscInt point = cone[c]; PetscCall(DMLabelGetValue(label, point, &val)); if (val == -1) { PetscInt *closure = NULL; PetscInt closureSize, cl; PetscCall(DMPlexGetTransitiveClosure(dm, point, PETSC_TRUE, &closureSize, &closure)); for (cl = 0; cl < closureSize * 2; cl += 2) { const PetscInt clp = closure[cl]; PetscInt bval = -1; PetscCall(DMLabelGetValue(label, clp, &val)); if (blabel) PetscCall(DMLabelGetValue(blabel, clp, &bval)); if ((val >= 0) && (val < dim - 1) && (bval < 0)) { PetscCall(DMLabelSetValue(label, point, pos == PETSC_TRUE ? shift + dim - 1 : -(shift + dim - 1))); break; } } PetscCall(DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, &closureSize, &closure)); } } } } PetscCall(ISRestoreIndices(dimIS, &points)); PetscCall(ISDestroy(&dimIS)); /* Mark boundary points as unsplit */ if (blabel) { IS bdIS; PetscCall(DMLabelGetStratumIS(blabel, bvalue, &bdIS)); PetscCall(ISGetLocalSize(bdIS, &numPoints)); PetscCall(ISGetIndices(bdIS, &points)); for (p = 0; p < numPoints; ++p) { const PetscInt point = points[p]; PetscInt val, bval; PetscCall(DMLabelGetValue(blabel, point, &bval)); if (bval >= 0) { PetscCall(DMLabelGetValue(label, point, &val)); if ((val < 0) || (val > dim)) { /* This could be a point added from splitting a vertex on an adjacent fault, otherwise its just wrong */ PetscCall(DMLabelClearValue(blabel, point, bval)); } } } for (p = 0; p < numPoints; ++p) { const PetscInt point = points[p]; PetscInt val, bval; PetscCall(DMLabelGetValue(blabel, point, &bval)); if (bval >= 0) { const PetscInt *cone, *support; PetscInt coneSize, supportSize, s, valA, valB, valE; /* Mark as unsplit */ PetscCall(DMLabelGetValue(label, point, &val)); PetscCheck(val >= 0 && val <= dim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " has label value %" PetscInt_FMT ", should be part of the fault", point, val); PetscCall(DMLabelClearValue(label, point, val)); PetscCall(DMLabelSetValue(label, point, shift2 + val)); /* Check for cross-edge A cross-edge has endpoints which are both on the boundary of the surface, but the edge itself is not. */ if (val != 0) continue; PetscCall(DMPlexGetSupport(dm, point, &support)); PetscCall(DMPlexGetSupportSize(dm, point, &supportSize)); for (s = 0; s < supportSize; ++s) { PetscCall(DMPlexGetCone(dm, support[s], &cone)); PetscCall(DMPlexGetConeSize(dm, support[s], &coneSize)); PetscCheck(coneSize == 2, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Edge %" PetscInt_FMT " has %" PetscInt_FMT " vertices != 2", support[s], coneSize); PetscCall(DMLabelGetValue(blabel, cone[0], &valA)); PetscCall(DMLabelGetValue(blabel, cone[1], &valB)); PetscCall(DMLabelGetValue(blabel, support[s], &valE)); if ((valE < 0) && (valA >= 0) && (valB >= 0) && (cone[0] != cone[1])) PetscCall(DMLabelSetValue(blabel, support[s], 2)); } } } PetscCall(ISRestoreIndices(bdIS, &points)); PetscCall(ISDestroy(&bdIS)); } /* Mark ghost fault cells */ { PetscSF sf; const PetscInt *leaves; PetscInt Nl, l; PetscCall(DMGetPointSF(dm, &sf)); PetscCall(PetscSFGetGraph(sf, NULL, &Nl, &leaves, NULL)); PetscCall(DMLabelGetStratumIS(label, dim - 1, &dimIS)); if (!dimIS) goto divide; PetscCall(ISGetLocalSize(dimIS, &numPoints)); PetscCall(ISGetIndices(dimIS, &points)); if (Nl > 0) { for (p = 0; p < numPoints; ++p) { const PetscInt point = points[p]; PetscInt val; PetscCall(PetscFindInt(point, Nl, leaves, &l)); if (l >= 0) { PetscInt *closure = NULL; PetscInt closureSize, cl; PetscCall(DMLabelGetValue(label, point, &val)); PetscCheck((val == dim - 1) || (val == shift2 + dim - 1), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " has label value %" PetscInt_FMT ", should be a fault face", point, val); PetscCall(DMLabelClearValue(label, point, val)); PetscCall(DMLabelSetValue(label, point, shift3 + val)); PetscCall(DMPlexGetTransitiveClosure(dm, point, PETSC_TRUE, &closureSize, &closure)); for (cl = 2; cl < closureSize * 2; cl += 2) { const PetscInt clp = closure[cl]; PetscCall(DMLabelGetValue(label, clp, &val)); PetscCheck(val != -1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " is missing from label, but is in the closure of a fault face", point); PetscCall(DMLabelClearValue(label, clp, val)); PetscCall(DMLabelSetValue(label, clp, shift3 + val)); } PetscCall(DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, &closureSize, &closure)); } } } PetscCall(ISRestoreIndices(dimIS, &points)); PetscCall(ISDestroy(&dimIS)); } divide: if (subpointIS) PetscCall(ISRestoreIndices(subpointIS, &subpoints)); PetscCall(DMPlexLabelFaultHalo(dm, label)); PetscCall(CheckFaultEdge_Private(dm, label)); PetscFunctionReturn(PETSC_SUCCESS); } /* Check that no cell have all vertices on the fault */ static PetscErrorCode DMPlexCheckValidSubmesh_Private(DM dm, DMLabel label, DM subdm) { IS subpointIS; const PetscInt *dmpoints; PetscInt defaultValue, cStart, cEnd, c, vStart, vEnd; PetscFunctionBegin; if (!label) PetscFunctionReturn(PETSC_SUCCESS); PetscCall(DMLabelGetDefaultValue(label, &defaultValue)); PetscCall(DMPlexGetSubpointIS(subdm, &subpointIS)); if (!subpointIS) PetscFunctionReturn(PETSC_SUCCESS); PetscCall(DMPlexGetHeightStratum(subdm, 0, &cStart, &cEnd)); PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd)); PetscCall(ISGetIndices(subpointIS, &dmpoints)); for (c = cStart; c < cEnd; ++c) { PetscBool invalidCell = PETSC_TRUE; PetscInt *closure = NULL; PetscInt closureSize, cl; PetscCall(DMPlexGetTransitiveClosure(dm, dmpoints[c], PETSC_TRUE, &closureSize, &closure)); for (cl = 0; cl < closureSize * 2; cl += 2) { PetscInt value = 0; if ((closure[cl] < vStart) || (closure[cl] >= vEnd)) continue; PetscCall(DMLabelGetValue(label, closure[cl], &value)); if (value == defaultValue) { invalidCell = PETSC_FALSE; break; } } PetscCall(DMPlexRestoreTransitiveClosure(dm, dmpoints[c], PETSC_TRUE, &closureSize, &closure)); if (invalidCell) { PetscCall(ISRestoreIndices(subpointIS, &dmpoints)); PetscCall(ISDestroy(&subpointIS)); PetscCall(DMDestroy(&subdm)); SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Ambiguous submesh. Cell %" PetscInt_FMT " has all of its vertices on the submesh.", dmpoints[c]); } } PetscCall(ISRestoreIndices(subpointIS, &dmpoints)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexCreateHybridMesh - Create a mesh with hybrid cells along an internal interface Collective Input Parameters: + dm - The original `DM` . label - The label specifying the interface vertices . bdlabel - The optional label specifying the interface boundary vertices - bdvalue - Value of optional label specifying the interface boundary vertices Output Parameters: + hybridLabel - The label fully marking the interface, or `NULL` if no output is desired . splitLabel - The label containing the split points, or `NULL` if no output is desired . dmInterface - The new interface `DM`, or `NULL` - dmHybrid - The new `DM` with cohesive cells Level: developer Note: The hybridLabel indicates what parts of the original mesh impinged on the division surface. For points directly on the division surface, they are labeled with their dimension, so an edge 7 on the division surface would be 7 (1) in hybridLabel. For points that impinge from the positive side, they are labeled with 100+dim, so an edge 6 with one vertex 3 on the surface would be 6 (101) and 3 (0) in hybridLabel. If an edge 9 from the negative side of the surface also hits vertex 3, it would be 9 (-101) in hybridLabel. The splitLabel indicates what points in the new hybrid mesh were the result of splitting points in the original mesh. The label value is $\pm 100+dim$ for each point. For example, if two edges 10 and 14 in the hybrid resulting from splitting an edge in the original mesh, you would have 10 (101) and 14 (-101) in the splitLabel. The dmInterface is a `DM` built from the original division surface. It has a label which can be retrieved using `DMPlexGetSubpointMap()` which maps each point back to the point in the surface of the original mesh. .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexConstructCohesiveCells()`, `DMPlexLabelCohesiveComplete()`, `DMPlexGetSubpointMap()`, `DMCreate()` @*/ PetscErrorCode DMPlexCreateHybridMesh(DM dm, DMLabel label, DMLabel bdlabel, PetscInt bdvalue, DMLabel *hybridLabel, DMLabel *splitLabel, DM *dmInterface, DM *dmHybrid) { DM idm; DMLabel subpointMap, hlabel, slabel = NULL; PetscInt dim; PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); if (label) PetscAssertPointer(label, 2); if (bdlabel) PetscAssertPointer(bdlabel, 3); if (hybridLabel) PetscAssertPointer(hybridLabel, 5); if (splitLabel) PetscAssertPointer(splitLabel, 6); if (dmInterface) PetscAssertPointer(dmInterface, 7); PetscAssertPointer(dmHybrid, 8); PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMPlexCreateSubmesh(dm, label, 1, PETSC_FALSE, &idm)); PetscCall(DMPlexCheckValidSubmesh_Private(dm, label, idm)); PetscCall(DMPlexOrient(idm)); PetscCall(DMPlexGetSubpointMap(idm, &subpointMap)); PetscCall(DMLabelDuplicate(subpointMap, &hlabel)); PetscCall(DMLabelClearStratum(hlabel, dim)); if (splitLabel) { const char *name; char sname[PETSC_MAX_PATH_LEN]; PetscCall(PetscObjectGetName((PetscObject)hlabel, &name)); PetscCall(PetscStrncpy(sname, name, sizeof(sname))); PetscCall(PetscStrlcat(sname, " split", sizeof(sname))); PetscCall(DMLabelCreate(PETSC_COMM_SELF, sname, &slabel)); } PetscCall(DMPlexLabelCohesiveComplete(dm, hlabel, bdlabel, bdvalue, PETSC_FALSE, idm)); if (dmInterface) { *dmInterface = idm; } else PetscCall(DMDestroy(&idm)); PetscCall(DMPlexConstructCohesiveCells(dm, hlabel, slabel, dmHybrid)); PetscCall(DMPlexCopy_Internal(dm, PETSC_TRUE, PETSC_TRUE, *dmHybrid)); if (hybridLabel) *hybridLabel = hlabel; else PetscCall(DMLabelDestroy(&hlabel)); if (splitLabel) *splitLabel = slabel; { DM cdm; DMLabel ctLabel; /* We need to somehow share the celltype label with the coordinate dm */ PetscCall(DMGetCoordinateDM(*dmHybrid, &cdm)); PetscCall(DMPlexGetCellTypeLabel(*dmHybrid, &ctLabel)); PetscCall(DMSetLabel(cdm, ctLabel)); } PetscFunctionReturn(PETSC_SUCCESS); } /* Here we need the explicit assumption that: For any marked cell, the marked vertices constitute a single face */ static PetscErrorCode DMPlexMarkSubmesh_Uninterpolated(DM dm, DMLabel vertexLabel, PetscInt value, DMLabel subpointMap, PetscInt *numFaces, PetscInt *nFV, DM subdm) { IS subvertexIS = NULL; const PetscInt *subvertices; PetscInt *pStart, *pEnd, pSize; PetscInt depth, dim, d, numSubVerticesInitial = 0, v; PetscFunctionBegin; *numFaces = 0; *nFV = 0; PetscCall(DMPlexGetDepth(dm, &depth)); PetscCall(DMGetDimension(dm, &dim)); pSize = PetscMax(depth, dim) + 1; PetscCall(PetscMalloc2(pSize, &pStart, pSize, &pEnd)); for (d = 0; d <= depth; ++d) PetscCall(DMPlexGetSimplexOrBoxCells(dm, depth - d, &pStart[d], &pEnd[d])); /* Loop over initial vertices and mark all faces in the collective star() */ if (vertexLabel) PetscCall(DMLabelGetStratumIS(vertexLabel, value, &subvertexIS)); if (subvertexIS) { PetscCall(ISGetSize(subvertexIS, &numSubVerticesInitial)); PetscCall(ISGetIndices(subvertexIS, &subvertices)); } for (v = 0; v < numSubVerticesInitial; ++v) { const PetscInt vertex = subvertices[v]; PetscInt *star = NULL; PetscInt starSize, s, numCells = 0, c; PetscCall(DMPlexGetTransitiveClosure(dm, vertex, PETSC_FALSE, &starSize, &star)); for (s = 0; s < starSize * 2; s += 2) { const PetscInt point = star[s]; if ((point >= pStart[depth]) && (point < pEnd[depth])) star[numCells++] = point; } for (c = 0; c < numCells; ++c) { const PetscInt cell = star[c]; PetscInt *closure = NULL; PetscInt closureSize, cl; PetscInt cellLoc, numCorners = 0, faceSize = 0; PetscCall(DMLabelGetValue(subpointMap, cell, &cellLoc)); if (cellLoc == 2) continue; PetscCheck(cellLoc < 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Cell %" PetscInt_FMT " has dimension %" PetscInt_FMT " in the surface label", cell, cellLoc); PetscCall(DMPlexGetTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure)); for (cl = 0; cl < closureSize * 2; cl += 2) { const PetscInt point = closure[cl]; PetscInt vertexLoc; if ((point >= pStart[0]) && (point < pEnd[0])) { ++numCorners; PetscCall(DMLabelGetValue(vertexLabel, point, &vertexLoc)); if (vertexLoc == value) closure[faceSize++] = point; } } if (!(*nFV)) PetscCall(DMPlexGetNumFaceVertices(dm, dim, numCorners, nFV)); PetscCheck(faceSize <= *nFV, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Invalid submesh: Too many vertices %" PetscInt_FMT " of an element on the surface", faceSize); if (faceSize == *nFV) { const PetscInt *cells = NULL; PetscInt numCells, nc; ++(*numFaces); for (cl = 0; cl < faceSize; ++cl) PetscCall(DMLabelSetValue(subpointMap, closure[cl], 0)); PetscCall(DMPlexGetJoin(dm, faceSize, closure, &numCells, &cells)); for (nc = 0; nc < numCells; ++nc) PetscCall(DMLabelSetValue(subpointMap, cells[nc], 2)); PetscCall(DMPlexRestoreJoin(dm, faceSize, closure, &numCells, &cells)); } PetscCall(DMPlexRestoreTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure)); } PetscCall(DMPlexRestoreTransitiveClosure(dm, vertex, PETSC_FALSE, &starSize, &star)); } if (subvertexIS) PetscCall(ISRestoreIndices(subvertexIS, &subvertices)); PetscCall(ISDestroy(&subvertexIS)); PetscCall(PetscFree2(pStart, pEnd)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexMarkSubmesh_Interpolated(DM dm, DMLabel vertexLabel, PetscInt value, PetscBool markedFaces, DMLabel subpointMap, DM subdm) { IS subvertexIS = NULL; const PetscInt *subvertices; PetscInt *pStart, *pEnd; PetscInt dim, d, numSubVerticesInitial = 0, v; PetscFunctionBegin; PetscCall(DMGetDimension(dm, &dim)); PetscCall(PetscMalloc2(dim + 1, &pStart, dim + 1, &pEnd)); for (d = 0; d <= dim; ++d) PetscCall(DMPlexGetSimplexOrBoxCells(dm, dim - d, &pStart[d], &pEnd[d])); /* Loop over initial vertices and mark all faces in the collective star() */ if (vertexLabel) { PetscCall(DMLabelGetStratumIS(vertexLabel, value, &subvertexIS)); if (subvertexIS) { PetscCall(ISGetSize(subvertexIS, &numSubVerticesInitial)); PetscCall(ISGetIndices(subvertexIS, &subvertices)); } } for (v = 0; v < numSubVerticesInitial; ++v) { const PetscInt vertex = subvertices[v]; PetscInt *star = NULL; PetscInt starSize, s, numFaces = 0, f; PetscCall(DMPlexGetTransitiveClosure(dm, vertex, PETSC_FALSE, &starSize, &star)); for (s = 0; s < starSize * 2; s += 2) { const PetscInt point = star[s]; PetscInt faceLoc; if ((point >= pStart[dim - 1]) && (point < pEnd[dim - 1])) { if (markedFaces) { PetscCall(DMLabelGetValue(vertexLabel, point, &faceLoc)); if (faceLoc < 0) continue; } star[numFaces++] = point; } } for (f = 0; f < numFaces; ++f) { const PetscInt face = star[f]; PetscInt *closure = NULL; PetscInt closureSize, c; PetscInt faceLoc; PetscCall(DMLabelGetValue(subpointMap, face, &faceLoc)); if (faceLoc == dim - 1) continue; PetscCheck(faceLoc < 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Face %" PetscInt_FMT " has dimension %" PetscInt_FMT " in the surface label", face, faceLoc); PetscCall(DMPlexGetTransitiveClosure(dm, face, PETSC_TRUE, &closureSize, &closure)); for (c = 0; c < closureSize * 2; c += 2) { const PetscInt point = closure[c]; PetscInt vertexLoc; if ((point >= pStart[0]) && (point < pEnd[0])) { PetscCall(DMLabelGetValue(vertexLabel, point, &vertexLoc)); if (vertexLoc != value) break; } } if (c == closureSize * 2) { const PetscInt *support; PetscInt supportSize, s; for (c = 0; c < closureSize * 2; c += 2) { const PetscInt point = closure[c]; for (d = 0; d < dim; ++d) { if ((point >= pStart[d]) && (point < pEnd[d])) { PetscCall(DMLabelSetValue(subpointMap, point, d)); break; } } } PetscCall(DMPlexGetSupportSize(dm, face, &supportSize)); PetscCall(DMPlexGetSupport(dm, face, &support)); for (s = 0; s < supportSize; ++s) PetscCall(DMLabelSetValue(subpointMap, support[s], dim)); } PetscCall(DMPlexRestoreTransitiveClosure(dm, face, PETSC_TRUE, &closureSize, &closure)); } PetscCall(DMPlexRestoreTransitiveClosure(dm, vertex, PETSC_FALSE, &starSize, &star)); } if (subvertexIS) PetscCall(ISRestoreIndices(subvertexIS, &subvertices)); PetscCall(ISDestroy(&subvertexIS)); PetscCall(PetscFree2(pStart, pEnd)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexMarkCohesiveSubmesh_Uninterpolated(DM dm, PetscBool hasLagrange, const char labelname[], PetscInt value, DMLabel subpointMap, PetscInt *numFaces, PetscInt *nFV, PetscInt *subCells[], DM subdm) { DMLabel label = NULL; const PetscInt *cone; PetscInt dim, cMax, cEnd, c, subc = 0, p, coneSize = -1; PetscFunctionBegin; *numFaces = 0; *nFV = 0; if (labelname) PetscCall(DMGetLabel(dm, labelname, &label)); *subCells = NULL; PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMPlexGetTensorPrismBounds_Internal(dm, dim, &cMax, &cEnd)); if (cMax < 0) PetscFunctionReturn(PETSC_SUCCESS); if (label) { for (c = cMax; c < cEnd; ++c) { PetscInt val; PetscCall(DMLabelGetValue(label, c, &val)); if (val == value) { ++(*numFaces); PetscCall(DMPlexGetConeSize(dm, c, &coneSize)); } } } else { *numFaces = cEnd - cMax; PetscCall(DMPlexGetConeSize(dm, cMax, &coneSize)); } PetscCall(PetscMalloc1(*numFaces * 2, subCells)); if (!(*numFaces)) PetscFunctionReturn(PETSC_SUCCESS); *nFV = hasLagrange ? coneSize / 3 : coneSize / 2; for (c = cMax; c < cEnd; ++c) { const PetscInt *cells; PetscInt numCells; if (label) { PetscInt val; PetscCall(DMLabelGetValue(label, c, &val)); if (val != value) continue; } PetscCall(DMPlexGetCone(dm, c, &cone)); for (p = 0; p < *nFV; ++p) PetscCall(DMLabelSetValue(subpointMap, cone[p], 0)); /* Negative face */ PetscCall(DMPlexGetJoin(dm, *nFV, cone, &numCells, &cells)); /* Not true in parallel PetscCheck(numCells == 2,PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cohesive cells should separate two cells"); */ for (p = 0; p < numCells; ++p) { PetscCall(DMLabelSetValue(subpointMap, cells[p], 2)); (*subCells)[subc++] = cells[p]; } PetscCall(DMPlexRestoreJoin(dm, *nFV, cone, &numCells, &cells)); /* Positive face is not included */ } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexMarkCohesiveSubmesh_Interpolated(DM dm, DMLabel label, PetscInt value, DMLabel subpointMap, DM subdm) { PetscInt *pStart, *pEnd; PetscInt dim, cMax, cEnd, c, d; PetscFunctionBegin; PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMPlexGetTensorPrismBounds_Internal(dm, dim, &cMax, &cEnd)); if (cMax < 0) PetscFunctionReturn(PETSC_SUCCESS); PetscCall(PetscMalloc2(dim + 1, &pStart, dim + 1, &pEnd)); for (d = 0; d <= dim; ++d) PetscCall(DMPlexGetDepthStratum(dm, d, &pStart[d], &pEnd[d])); for (c = cMax; c < cEnd; ++c) { const PetscInt *cone; PetscInt *closure = NULL; PetscInt fconeSize, coneSize, closureSize, cl, val; if (label) { PetscCall(DMLabelGetValue(label, c, &val)); if (val != value) continue; } PetscCall(DMPlexGetConeSize(dm, c, &coneSize)); PetscCall(DMPlexGetCone(dm, c, &cone)); PetscCall(DMPlexGetConeSize(dm, cone[0], &fconeSize)); PetscCheck(coneSize == (fconeSize ? fconeSize : 1) + 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cohesive cells should separate two cells"); /* Negative face */ PetscCall(DMPlexGetTransitiveClosure(dm, cone[0], PETSC_TRUE, &closureSize, &closure)); for (cl = 0; cl < closureSize * 2; cl += 2) { const PetscInt point = closure[cl]; for (d = 0; d <= dim; ++d) { if ((point >= pStart[d]) && (point < pEnd[d])) { PetscCall(DMLabelSetValue(subpointMap, point, d)); break; } } } PetscCall(DMPlexRestoreTransitiveClosure(dm, cone[0], PETSC_TRUE, &closureSize, &closure)); /* Cells -- positive face is not included */ for (cl = 0; cl < 1; ++cl) { const PetscInt *support; PetscInt supportSize, s; PetscCall(DMPlexGetSupportSize(dm, cone[cl], &supportSize)); /* PetscCheck(supportSize == 2,PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cohesive faces should separate two cells"); */ PetscCall(DMPlexGetSupport(dm, cone[cl], &support)); for (s = 0; s < supportSize; ++s) PetscCall(DMLabelSetValue(subpointMap, support[s], dim)); } } PetscCall(PetscFree2(pStart, pEnd)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexGetFaceOrientation(DM dm, PetscInt cell, PetscInt numCorners, PetscInt indices[], PetscInt oppositeVertex, PetscInt origVertices[], PetscInt faceVertices[], PetscBool *posOriented) { MPI_Comm comm; PetscBool posOrient = PETSC_FALSE; const PetscInt debug = 0; PetscInt cellDim, faceSize, f; PetscFunctionBegin; PetscCall(PetscObjectGetComm((PetscObject)dm, &comm)); PetscCall(DMGetDimension(dm, &cellDim)); if (debug) PetscCall(PetscPrintf(comm, "cellDim: %" PetscInt_FMT " numCorners: %" PetscInt_FMT "\n", cellDim, numCorners)); if (cellDim == 1 && numCorners == 2) { /* Triangle */ faceSize = numCorners - 1; posOrient = !(oppositeVertex % 2) ? PETSC_TRUE : PETSC_FALSE; } else if (cellDim == 2 && numCorners == 3) { /* Triangle */ faceSize = numCorners - 1; posOrient = !(oppositeVertex % 2) ? PETSC_TRUE : PETSC_FALSE; } else if (cellDim == 3 && numCorners == 4) { /* Tetrahedron */ faceSize = numCorners - 1; posOrient = (oppositeVertex % 2) ? PETSC_TRUE : PETSC_FALSE; } else if (cellDim == 1 && numCorners == 3) { /* Quadratic line */ faceSize = 1; posOrient = PETSC_TRUE; } else if (cellDim == 2 && numCorners == 4) { /* Quads */ faceSize = 2; if ((indices[1] > indices[0]) && (indices[1] - indices[0] == 1)) { posOrient = PETSC_TRUE; } else if ((indices[0] == 3) && (indices[1] == 0)) { posOrient = PETSC_TRUE; } else { if (((indices[0] > indices[1]) && (indices[0] - indices[1] == 1)) || ((indices[0] == 0) && (indices[1] == 3))) { posOrient = PETSC_FALSE; } else SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Invalid quad crossedge"); } } else if (cellDim == 2 && numCorners == 6) { /* Quadratic triangle (I hate this) */ /* Edges are determined by the first 2 vertices (corners of edges) */ const PetscInt faceSizeTri = 3; PetscInt sortedIndices[3], i, iFace; PetscBool found = PETSC_FALSE; PetscInt faceVerticesTriSorted[9] = { 0, 3, 4, /* bottom */ 1, 4, 5, /* right */ 2, 3, 5, /* left */ }; PetscInt faceVerticesTri[9] = { 0, 3, 4, /* bottom */ 1, 4, 5, /* right */ 2, 5, 3, /* left */ }; for (i = 0; i < faceSizeTri; ++i) sortedIndices[i] = indices[i]; PetscCall(PetscSortInt(faceSizeTri, sortedIndices)); for (iFace = 0; iFace < 3; ++iFace) { const PetscInt ii = iFace * faceSizeTri; PetscInt fVertex, cVertex; if ((sortedIndices[0] == faceVerticesTriSorted[ii + 0]) && (sortedIndices[1] == faceVerticesTriSorted[ii + 1])) { for (fVertex = 0; fVertex < faceSizeTri; ++fVertex) { for (cVertex = 0; cVertex < faceSizeTri; ++cVertex) { if (indices[cVertex] == faceVerticesTri[ii + fVertex]) { faceVertices[fVertex] = origVertices[cVertex]; break; } } } found = PETSC_TRUE; break; } } PetscCheck(found, comm, PETSC_ERR_ARG_WRONG, "Invalid tri crossface"); if (posOriented) *posOriented = PETSC_TRUE; PetscFunctionReturn(PETSC_SUCCESS); } else if (cellDim == 2 && numCorners == 9) { /* Quadratic quad (I hate this) */ /* Edges are determined by the first 2 vertices (corners of edges) */ const PetscInt faceSizeQuad = 3; PetscInt sortedIndices[3], i, iFace; PetscBool found = PETSC_FALSE; PetscInt faceVerticesQuadSorted[12] = { 0, 1, 4, /* bottom */ 1, 2, 5, /* right */ 2, 3, 6, /* top */ 0, 3, 7, /* left */ }; PetscInt faceVerticesQuad[12] = { 0, 1, 4, /* bottom */ 1, 2, 5, /* right */ 2, 3, 6, /* top */ 3, 0, 7, /* left */ }; for (i = 0; i < faceSizeQuad; ++i) sortedIndices[i] = indices[i]; PetscCall(PetscSortInt(faceSizeQuad, sortedIndices)); for (iFace = 0; iFace < 4; ++iFace) { const PetscInt ii = iFace * faceSizeQuad; PetscInt fVertex, cVertex; if ((sortedIndices[0] == faceVerticesQuadSorted[ii + 0]) && (sortedIndices[1] == faceVerticesQuadSorted[ii + 1])) { for (fVertex = 0; fVertex < faceSizeQuad; ++fVertex) { for (cVertex = 0; cVertex < faceSizeQuad; ++cVertex) { if (indices[cVertex] == faceVerticesQuad[ii + fVertex]) { faceVertices[fVertex] = origVertices[cVertex]; break; } } } found = PETSC_TRUE; break; } } PetscCheck(found, comm, PETSC_ERR_ARG_WRONG, "Invalid quad crossface"); if (posOriented) *posOriented = PETSC_TRUE; PetscFunctionReturn(PETSC_SUCCESS); } else if (cellDim == 3 && numCorners == 8) { /* Hexes A hex is two oriented quads with the normal of the first pointing up at the second. 7---6 /| /| 4---5 | | 1-|-2 |/ |/ 0---3 Faces are determined by the first 4 vertices (corners of faces) */ const PetscInt faceSizeHex = 4; PetscInt sortedIndices[4], i, iFace; PetscBool found = PETSC_FALSE; PetscInt faceVerticesHexSorted[24] = { 0, 1, 2, 3, /* bottom */ 4, 5, 6, 7, /* top */ 0, 3, 4, 5, /* front */ 2, 3, 5, 6, /* right */ 1, 2, 6, 7, /* back */ 0, 1, 4, 7, /* left */ }; PetscInt faceVerticesHex[24] = { 1, 2, 3, 0, /* bottom */ 4, 5, 6, 7, /* top */ 0, 3, 5, 4, /* front */ 3, 2, 6, 5, /* right */ 2, 1, 7, 6, /* back */ 1, 0, 4, 7, /* left */ }; for (i = 0; i < faceSizeHex; ++i) sortedIndices[i] = indices[i]; PetscCall(PetscSortInt(faceSizeHex, sortedIndices)); for (iFace = 0; iFace < 6; ++iFace) { const PetscInt ii = iFace * faceSizeHex; PetscInt fVertex, cVertex; if ((sortedIndices[0] == faceVerticesHexSorted[ii + 0]) && (sortedIndices[1] == faceVerticesHexSorted[ii + 1]) && (sortedIndices[2] == faceVerticesHexSorted[ii + 2]) && (sortedIndices[3] == faceVerticesHexSorted[ii + 3])) { for (fVertex = 0; fVertex < faceSizeHex; ++fVertex) { for (cVertex = 0; cVertex < faceSizeHex; ++cVertex) { if (indices[cVertex] == faceVerticesHex[ii + fVertex]) { faceVertices[fVertex] = origVertices[cVertex]; break; } } } found = PETSC_TRUE; break; } } PetscCheck(found, comm, PETSC_ERR_ARG_WRONG, "Invalid hex crossface"); if (posOriented) *posOriented = PETSC_TRUE; PetscFunctionReturn(PETSC_SUCCESS); } else if (cellDim == 3 && numCorners == 10) { /* Quadratic tet */ /* Faces are determined by the first 3 vertices (corners of faces) */ const PetscInt faceSizeTet = 6; PetscInt sortedIndices[6], i, iFace; PetscBool found = PETSC_FALSE; PetscInt faceVerticesTetSorted[24] = { 0, 1, 2, 6, 7, 8, /* bottom */ 0, 3, 4, 6, 7, 9, /* front */ 1, 4, 5, 7, 8, 9, /* right */ 2, 3, 5, 6, 8, 9, /* left */ }; PetscInt faceVerticesTet[24] = { 0, 1, 2, 6, 7, 8, /* bottom */ 0, 4, 3, 6, 7, 9, /* front */ 1, 5, 4, 7, 8, 9, /* right */ 2, 3, 5, 8, 6, 9, /* left */ }; for (i = 0; i < faceSizeTet; ++i) sortedIndices[i] = indices[i]; PetscCall(PetscSortInt(faceSizeTet, sortedIndices)); for (iFace = 0; iFace < 4; ++iFace) { const PetscInt ii = iFace * faceSizeTet; PetscInt fVertex, cVertex; if ((sortedIndices[0] == faceVerticesTetSorted[ii + 0]) && (sortedIndices[1] == faceVerticesTetSorted[ii + 1]) && (sortedIndices[2] == faceVerticesTetSorted[ii + 2]) && (sortedIndices[3] == faceVerticesTetSorted[ii + 3])) { for (fVertex = 0; fVertex < faceSizeTet; ++fVertex) { for (cVertex = 0; cVertex < faceSizeTet; ++cVertex) { if (indices[cVertex] == faceVerticesTet[ii + fVertex]) { faceVertices[fVertex] = origVertices[cVertex]; break; } } } found = PETSC_TRUE; break; } } PetscCheck(found, comm, PETSC_ERR_ARG_WRONG, "Invalid tet crossface"); if (posOriented) *posOriented = PETSC_TRUE; PetscFunctionReturn(PETSC_SUCCESS); } else if (cellDim == 3 && numCorners == 27) { /* Quadratic hexes (I hate this) A hex is two oriented quads with the normal of the first pointing up at the second. 7---6 /| /| 4---5 | | 3-|-2 |/ |/ 0---1 Faces are determined by the first 4 vertices (corners of faces) */ const PetscInt faceSizeQuadHex = 9; PetscInt sortedIndices[9], i, iFace; PetscBool found = PETSC_FALSE; PetscInt faceVerticesQuadHexSorted[54] = { 0, 1, 2, 3, 8, 9, 10, 11, 24, /* bottom */ 4, 5, 6, 7, 12, 13, 14, 15, 25, /* top */ 0, 1, 4, 5, 8, 12, 16, 17, 22, /* front */ 1, 2, 5, 6, 9, 13, 17, 18, 21, /* right */ 2, 3, 6, 7, 10, 14, 18, 19, 23, /* back */ 0, 3, 4, 7, 11, 15, 16, 19, 20, /* left */ }; PetscInt faceVerticesQuadHex[54] = { 3, 2, 1, 0, 10, 9, 8, 11, 24, /* bottom */ 4, 5, 6, 7, 12, 13, 14, 15, 25, /* top */ 0, 1, 5, 4, 8, 17, 12, 16, 22, /* front */ 1, 2, 6, 5, 9, 18, 13, 17, 21, /* right */ 2, 3, 7, 6, 10, 19, 14, 18, 23, /* back */ 3, 0, 4, 7, 11, 16, 15, 19, 20 /* left */ }; for (i = 0; i < faceSizeQuadHex; ++i) sortedIndices[i] = indices[i]; PetscCall(PetscSortInt(faceSizeQuadHex, sortedIndices)); for (iFace = 0; iFace < 6; ++iFace) { const PetscInt ii = iFace * faceSizeQuadHex; PetscInt fVertex, cVertex; if ((sortedIndices[0] == faceVerticesQuadHexSorted[ii + 0]) && (sortedIndices[1] == faceVerticesQuadHexSorted[ii + 1]) && (sortedIndices[2] == faceVerticesQuadHexSorted[ii + 2]) && (sortedIndices[3] == faceVerticesQuadHexSorted[ii + 3])) { for (fVertex = 0; fVertex < faceSizeQuadHex; ++fVertex) { for (cVertex = 0; cVertex < faceSizeQuadHex; ++cVertex) { if (indices[cVertex] == faceVerticesQuadHex[ii + fVertex]) { faceVertices[fVertex] = origVertices[cVertex]; break; } } } found = PETSC_TRUE; break; } } PetscCheck(found, comm, PETSC_ERR_ARG_WRONG, "Invalid hex crossface"); if (posOriented) *posOriented = PETSC_TRUE; PetscFunctionReturn(PETSC_SUCCESS); } else SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Unknown cell type for faceOrientation()."); if (!posOrient) { if (debug) PetscCall(PetscPrintf(comm, " Reversing initial face orientation\n")); for (f = 0; f < faceSize; ++f) faceVertices[f] = origVertices[faceSize - 1 - f]; } else { if (debug) PetscCall(PetscPrintf(comm, " Keeping initial face orientation\n")); for (f = 0; f < faceSize; ++f) faceVertices[f] = origVertices[f]; } if (posOriented) *posOriented = posOrient; PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexGetOrientedFace - Given a cell and a face, as a set of vertices, return the oriented face, as a set of vertices, in faceVertices. The orientation is such that the face normal points out of the cell Not Collective Input Parameters: + dm - The original mesh . cell - The cell mesh point . faceSize - The number of vertices on the face . face - The face vertices . numCorners - The number of vertices on the cell . indices - Local numbering of face vertices in cell cone - origVertices - Original face vertices Output Parameters: + faceVertices - The face vertices properly oriented - posOriented - `PETSC_TRUE` if the face was oriented with outward normal Level: developer .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCone()` @*/ PetscErrorCode DMPlexGetOrientedFace(DM dm, PetscInt cell, PetscInt faceSize, const PetscInt face[], PetscInt numCorners, PetscInt indices[], PetscInt origVertices[], PetscInt faceVertices[], PetscBool *posOriented) { const PetscInt *cone = NULL; PetscInt coneSize, v, f, v2; PetscInt oppositeVertex = -1; PetscFunctionBegin; PetscCall(DMPlexGetConeSize(dm, cell, &coneSize)); PetscCall(DMPlexGetCone(dm, cell, &cone)); for (v = 0, v2 = 0; v < coneSize; ++v) { PetscBool found = PETSC_FALSE; for (f = 0; f < faceSize; ++f) { if (face[f] == cone[v]) { found = PETSC_TRUE; break; } } if (found) { indices[v2] = v; origVertices[v2] = cone[v]; ++v2; } else { oppositeVertex = v; } } PetscCall(DMPlexGetFaceOrientation(dm, cell, numCorners, indices, oppositeVertex, origVertices, faceVertices, posOriented)); PetscFunctionReturn(PETSC_SUCCESS); } /* DMPlexInsertFace_Internal - Puts a face into the mesh Not Collective Input Parameters: + dm - The `DMPLEX` . numFaceVertex - The number of vertices in the face . faceVertices - The vertices in the face for `dm` . subfaceVertices - The vertices in the face for subdm . numCorners - The number of vertices in the `cell` . cell - A cell in `dm` containing the face . subcell - A cell in subdm containing the face . firstFace - First face in the mesh - newFacePoint - Next face in the mesh Output Parameter: . newFacePoint - Contains next face point number on input, updated on output Level: developer */ static PetscErrorCode DMPlexInsertFace_Internal(DM dm, DM subdm, PetscInt numFaceVertices, const PetscInt faceVertices[], const PetscInt subfaceVertices[], PetscInt numCorners, PetscInt cell, PetscInt subcell, PetscInt firstFace, PetscInt *newFacePoint) { MPI_Comm comm; DM_Plex *submesh = (DM_Plex *)subdm->data; const PetscInt *faces; PetscInt numFaces, coneSize; PetscFunctionBegin; PetscCall(PetscObjectGetComm((PetscObject)dm, &comm)); PetscCall(DMPlexGetConeSize(subdm, subcell, &coneSize)); PetscCheck(coneSize == 1, comm, PETSC_ERR_ARG_OUTOFRANGE, "Cone size of cell %" PetscInt_FMT " is %" PetscInt_FMT " != 1", cell, coneSize); #if 0 /* Cannot use this because support() has not been constructed yet */ PetscCall(DMPlexGetJoin(subdm, numFaceVertices, subfaceVertices, &numFaces, &faces)); #else { PetscInt f; numFaces = 0; PetscCall(DMGetWorkArray(subdm, 1, MPIU_INT, (void **)&faces)); for (f = firstFace; f < *newFacePoint; ++f) { PetscInt dof, off, d; PetscCall(PetscSectionGetDof(submesh->coneSection, f, &dof)); PetscCall(PetscSectionGetOffset(submesh->coneSection, f, &off)); /* Yes, I know this is quadratic, but I expect the sizes to be <5 */ for (d = 0; d < dof; ++d) { const PetscInt p = submesh->cones[off + d]; PetscInt v; for (v = 0; v < numFaceVertices; ++v) { if (subfaceVertices[v] == p) break; } if (v == numFaceVertices) break; } if (d == dof) { numFaces = 1; ((PetscInt *)faces)[0] = f; } } } #endif PetscCheck(numFaces <= 1, comm, PETSC_ERR_ARG_WRONG, "Vertex set had %" PetscInt_FMT " faces, not one", numFaces); if (numFaces == 1) { /* Add the other cell neighbor for this face */ PetscCall(DMPlexSetCone(subdm, subcell, faces)); } else { PetscInt *indices, *origVertices, *orientedVertices, *orientedSubVertices, v, ov; PetscBool posOriented; PetscCall(DMGetWorkArray(subdm, 4 * numFaceVertices * sizeof(PetscInt), MPIU_INT, &orientedVertices)); origVertices = &orientedVertices[numFaceVertices]; indices = &orientedVertices[numFaceVertices * 2]; orientedSubVertices = &orientedVertices[numFaceVertices * 3]; PetscCall(DMPlexGetOrientedFace(dm, cell, numFaceVertices, faceVertices, numCorners, indices, origVertices, orientedVertices, &posOriented)); /* TODO: I know that routine should return a permutation, not the indices */ for (v = 0; v < numFaceVertices; ++v) { const PetscInt vertex = faceVertices[v], subvertex = subfaceVertices[v]; for (ov = 0; ov < numFaceVertices; ++ov) { if (orientedVertices[ov] == vertex) { orientedSubVertices[ov] = subvertex; break; } } PetscCheck(ov != numFaceVertices, comm, PETSC_ERR_PLIB, "Could not find face vertex %" PetscInt_FMT " in orientated set", vertex); } PetscCall(DMPlexSetCone(subdm, *newFacePoint, orientedSubVertices)); PetscCall(DMPlexSetCone(subdm, subcell, newFacePoint)); PetscCall(DMRestoreWorkArray(subdm, 4 * numFaceVertices * sizeof(PetscInt), MPIU_INT, &orientedVertices)); ++(*newFacePoint); } #if 0 PetscCall(DMPlexRestoreJoin(subdm, numFaceVertices, subfaceVertices, &numFaces, &faces)); #else PetscCall(DMRestoreWorkArray(subdm, 1, MPIU_INT, (void **)&faces)); #endif PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexCreateSubmesh_Uninterpolated(DM dm, DMLabel vertexLabel, PetscInt value, DM subdm) { MPI_Comm comm; DMLabel subpointMap; IS subvertexIS, subcellIS; const PetscInt *subVertices, *subCells; PetscInt numSubVertices, firstSubVertex, numSubCells; PetscInt *subface, maxConeSize, numSubFaces = 0, firstSubFace, newFacePoint, nFV = 0; PetscInt vStart, vEnd, c, f; PetscFunctionBegin; PetscCall(PetscObjectGetComm((PetscObject)dm, &comm)); /* Create subpointMap which marks the submesh */ PetscCall(DMLabelCreate(PETSC_COMM_SELF, "subpoint_map", &subpointMap)); PetscCall(DMPlexSetSubpointMap(subdm, subpointMap)); PetscCall(DMLabelDestroy(&subpointMap)); if (vertexLabel) PetscCall(DMPlexMarkSubmesh_Uninterpolated(dm, vertexLabel, value, subpointMap, &numSubFaces, &nFV, subdm)); /* Setup chart */ PetscCall(DMLabelGetStratumSize(subpointMap, 0, &numSubVertices)); PetscCall(DMLabelGetStratumSize(subpointMap, 2, &numSubCells)); PetscCall(DMPlexSetChart(subdm, 0, numSubCells + numSubFaces + numSubVertices)); PetscCall(DMPlexSetVTKCellHeight(subdm, 1)); /* Set cone sizes */ firstSubVertex = numSubCells; firstSubFace = numSubCells + numSubVertices; newFacePoint = firstSubFace; PetscCall(DMLabelGetStratumIS(subpointMap, 0, &subvertexIS)); if (subvertexIS) PetscCall(ISGetIndices(subvertexIS, &subVertices)); PetscCall(DMLabelGetStratumIS(subpointMap, 2, &subcellIS)); if (subcellIS) PetscCall(ISGetIndices(subcellIS, &subCells)); for (c = 0; c < numSubCells; ++c) PetscCall(DMPlexSetConeSize(subdm, c, 1)); for (f = firstSubFace; f < firstSubFace + numSubFaces; ++f) PetscCall(DMPlexSetConeSize(subdm, f, nFV)); PetscCall(DMSetUp(subdm)); /* Create face cones */ PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd)); PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, NULL)); PetscCall(DMGetWorkArray(subdm, maxConeSize, MPIU_INT, (void **)&subface)); for (c = 0; c < numSubCells; ++c) { const PetscInt cell = subCells[c]; const PetscInt subcell = c; PetscInt *closure = NULL; PetscInt closureSize, cl, numCorners = 0, faceSize = 0; PetscCall(DMPlexGetTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure)); for (cl = 0; cl < closureSize * 2; cl += 2) { const PetscInt point = closure[cl]; PetscInt subVertex; if ((point >= vStart) && (point < vEnd)) { ++numCorners; PetscCall(PetscFindInt(point, numSubVertices, subVertices, &subVertex)); if (subVertex >= 0) { closure[faceSize] = point; subface[faceSize] = firstSubVertex + subVertex; ++faceSize; } } } PetscCheck(faceSize <= nFV, comm, PETSC_ERR_ARG_WRONG, "Invalid submesh: Too many vertices %" PetscInt_FMT " of an element on the surface", faceSize); if (faceSize == nFV) PetscCall(DMPlexInsertFace_Internal(dm, subdm, faceSize, closure, subface, numCorners, cell, subcell, firstSubFace, &newFacePoint)); PetscCall(DMPlexRestoreTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure)); } PetscCall(DMRestoreWorkArray(subdm, maxConeSize, MPIU_INT, (void **)&subface)); PetscCall(DMPlexSymmetrize(subdm)); PetscCall(DMPlexStratify(subdm)); /* Build coordinates */ { PetscSection coordSection, subCoordSection; Vec coordinates, subCoordinates; PetscScalar *coords, *subCoords; PetscInt numComp, coordSize, v; const char *name; PetscCall(DMGetCoordinateSection(dm, &coordSection)); PetscCall(DMGetCoordinatesLocal(dm, &coordinates)); PetscCall(DMGetCoordinateSection(subdm, &subCoordSection)); PetscCall(PetscSectionSetNumFields(subCoordSection, 1)); PetscCall(PetscSectionGetFieldComponents(coordSection, 0, &numComp)); PetscCall(PetscSectionSetFieldComponents(subCoordSection, 0, numComp)); PetscCall(PetscSectionSetChart(subCoordSection, firstSubVertex, firstSubVertex + numSubVertices)); for (v = 0; v < numSubVertices; ++v) { const PetscInt vertex = subVertices[v]; const PetscInt subvertex = firstSubVertex + v; PetscInt dof; PetscCall(PetscSectionGetDof(coordSection, vertex, &dof)); PetscCall(PetscSectionSetDof(subCoordSection, subvertex, dof)); PetscCall(PetscSectionSetFieldDof(subCoordSection, subvertex, 0, dof)); } PetscCall(PetscSectionSetUp(subCoordSection)); PetscCall(PetscSectionGetStorageSize(subCoordSection, &coordSize)); PetscCall(VecCreate(PETSC_COMM_SELF, &subCoordinates)); PetscCall(PetscObjectGetName((PetscObject)coordinates, &name)); PetscCall(PetscObjectSetName((PetscObject)subCoordinates, name)); PetscCall(VecSetSizes(subCoordinates, coordSize, PETSC_DETERMINE)); PetscCall(VecSetType(subCoordinates, VECSTANDARD)); if (coordSize) { PetscCall(VecGetArray(coordinates, &coords)); PetscCall(VecGetArray(subCoordinates, &subCoords)); for (v = 0; v < numSubVertices; ++v) { const PetscInt vertex = subVertices[v]; const PetscInt subvertex = firstSubVertex + v; PetscInt dof, off, sdof, soff, d; PetscCall(PetscSectionGetDof(coordSection, vertex, &dof)); PetscCall(PetscSectionGetOffset(coordSection, vertex, &off)); PetscCall(PetscSectionGetDof(subCoordSection, subvertex, &sdof)); PetscCall(PetscSectionGetOffset(subCoordSection, subvertex, &soff)); PetscCheck(dof == sdof, comm, PETSC_ERR_PLIB, "Coordinate dimension %" PetscInt_FMT " on subvertex %" PetscInt_FMT ", vertex %" PetscInt_FMT " should be %" PetscInt_FMT, sdof, subvertex, vertex, dof); for (d = 0; d < dof; ++d) subCoords[soff + d] = coords[off + d]; } PetscCall(VecRestoreArray(coordinates, &coords)); PetscCall(VecRestoreArray(subCoordinates, &subCoords)); } PetscCall(DMSetCoordinatesLocal(subdm, subCoordinates)); PetscCall(VecDestroy(&subCoordinates)); } /* Cleanup */ if (subvertexIS) PetscCall(ISRestoreIndices(subvertexIS, &subVertices)); PetscCall(ISDestroy(&subvertexIS)); if (subcellIS) PetscCall(ISRestoreIndices(subcellIS, &subCells)); PetscCall(ISDestroy(&subcellIS)); PetscFunctionReturn(PETSC_SUCCESS); } /* TODO: Fix this to properly propagate up error conditions it may find */ static inline PetscInt DMPlexFilterPoint_Internal(PetscInt point, PetscInt firstSubPoint, PetscInt numSubPoints, const PetscInt subPoints[]) { PetscInt subPoint; PetscErrorCode ierr; ierr = PetscFindInt(point, numSubPoints, subPoints, &subPoint); if (ierr) return -1; return subPoint < 0 ? subPoint : firstSubPoint + subPoint; } /* TODO: Fix this to properly propagate up error conditions it may find */ static inline PetscInt DMPlexFilterPointPerm_Internal(PetscInt point, PetscInt firstSubPoint, PetscInt numSubPoints, const PetscInt subPoints[], const PetscInt subIndices[]) { PetscInt subPoint; PetscErrorCode ierr; ierr = PetscFindInt(point, numSubPoints, subPoints, &subPoint); if (ierr) return -1; return subPoint < 0 ? subPoint : firstSubPoint + (subIndices ? subIndices[subPoint] : subPoint); } static PetscErrorCode DMPlexFilterLabels_Internal(DM dm, const PetscInt numSubPoints[], const PetscInt *subpoints[], const PetscInt firstSubPoint[], DM subdm) { DMLabel depthLabel; PetscInt Nl, l, d; PetscFunctionBegin; // Reset depth label for fast lookup PetscCall(DMPlexGetDepthLabel(dm, &depthLabel)); PetscCall(DMLabelMakeAllInvalid_Internal(depthLabel)); PetscCall(DMGetNumLabels(dm, &Nl)); for (l = 0; l < Nl; ++l) { DMLabel label, newlabel; const char *lname; PetscBool isDepth, isDim, isCelltype, isVTK; IS valueIS; const PetscInt *values; PetscInt Nv, v; PetscCall(DMGetLabelName(dm, l, &lname)); PetscCall(PetscStrcmp(lname, "depth", &isDepth)); PetscCall(PetscStrcmp(lname, "dim", &isDim)); PetscCall(PetscStrcmp(lname, "celltype", &isCelltype)); PetscCall(PetscStrcmp(lname, "vtk", &isVTK)); if (isDepth || isDim || isCelltype || isVTK) continue; PetscCall(DMCreateLabel(subdm, lname)); PetscCall(DMGetLabel(dm, lname, &label)); PetscCall(DMGetLabel(subdm, lname, &newlabel)); PetscCall(DMLabelGetDefaultValue(label, &v)); PetscCall(DMLabelSetDefaultValue(newlabel, v)); PetscCall(DMLabelGetValueIS(label, &valueIS)); PetscCall(ISGetLocalSize(valueIS, &Nv)); PetscCall(ISGetIndices(valueIS, &values)); for (v = 0; v < Nv; ++v) { IS pointIS; const PetscInt *points; PetscInt Np, p; PetscCall(DMLabelGetStratumIS(label, values[v], &pointIS)); PetscCall(ISGetLocalSize(pointIS, &Np)); PetscCall(ISGetIndices(pointIS, &points)); for (p = 0; p < Np; ++p) { const PetscInt point = points[p]; PetscInt subp; PetscCall(DMPlexGetPointDepth(dm, point, &d)); subp = DMPlexFilterPoint_Internal(point, firstSubPoint[d], numSubPoints[d], subpoints[d]); if (subp >= 0) PetscCall(DMLabelSetValue(newlabel, subp, values[v])); } PetscCall(ISRestoreIndices(pointIS, &points)); PetscCall(ISDestroy(&pointIS)); } PetscCall(ISRestoreIndices(valueIS, &values)); PetscCall(ISDestroy(&valueIS)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexCreateSubmeshGeneric_Interpolated(DM dm, DMLabel label, PetscInt value, PetscBool markedFaces, PetscBool isCohesive, PetscInt cellHeight, DM subdm) { MPI_Comm comm; DMLabel subpointMap; IS *subpointIS; const PetscInt **subpoints; PetscInt *numSubPoints, *firstSubPoint, *coneNew, *orntNew; PetscInt totSubPoints = 0, maxConeSize, dim, sdim, cdim, p, d, v; PetscMPIInt rank; PetscFunctionBegin; PetscCall(PetscObjectGetComm((PetscObject)dm, &comm)); PetscCallMPI(MPI_Comm_rank(comm, &rank)); /* Create subpointMap which marks the submesh */ PetscCall(DMLabelCreate(PETSC_COMM_SELF, "subpoint_map", &subpointMap)); PetscCall(DMPlexSetSubpointMap(subdm, subpointMap)); if (cellHeight) { if (isCohesive) PetscCall(DMPlexMarkCohesiveSubmesh_Interpolated(dm, label, value, subpointMap, subdm)); else PetscCall(DMPlexMarkSubmesh_Interpolated(dm, label, value, markedFaces, subpointMap, subdm)); } else { DMLabel depth; IS pointIS; const PetscInt *points; PetscInt numPoints = 0; PetscCall(DMPlexGetDepthLabel(dm, &depth)); PetscCall(DMLabelGetStratumIS(label, value, &pointIS)); if (pointIS) { PetscCall(ISGetIndices(pointIS, &points)); PetscCall(ISGetLocalSize(pointIS, &numPoints)); } for (p = 0; p < numPoints; ++p) { PetscInt *closure = NULL; PetscInt closureSize, c, pdim; PetscCall(DMPlexGetTransitiveClosure(dm, points[p], PETSC_TRUE, &closureSize, &closure)); for (c = 0; c < closureSize * 2; c += 2) { PetscCall(DMLabelGetValue(depth, closure[c], &pdim)); PetscCall(DMLabelSetValue(subpointMap, closure[c], pdim)); } PetscCall(DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_TRUE, &closureSize, &closure)); } if (pointIS) PetscCall(ISRestoreIndices(pointIS, &points)); PetscCall(ISDestroy(&pointIS)); } /* Setup chart */ PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMGetCoordinateDim(dm, &cdim)); PetscCall(PetscMalloc4(dim + 1, &numSubPoints, dim + 1, &firstSubPoint, dim + 1, &subpointIS, dim + 1, &subpoints)); for (d = 0; d <= dim; ++d) { PetscCall(DMLabelGetStratumSize(subpointMap, d, &numSubPoints[d])); totSubPoints += numSubPoints[d]; } // Determine submesh dimension PetscCall(DMGetDimension(subdm, &sdim)); if (sdim > 0) { // Calling function knows what dimension to use, and we include neighboring cells as well sdim = dim; } else { // We reset the subdimension based on what is being selected PetscInt lsdim; for (lsdim = dim; lsdim >= 0; --lsdim) if (numSubPoints[lsdim]) break; PetscCall(MPIU_Allreduce(&lsdim, &sdim, 1, MPIU_INT, MPI_MAX, comm)); PetscCall(DMSetDimension(subdm, sdim)); PetscCall(DMSetCoordinateDim(subdm, cdim)); } PetscCall(DMPlexSetChart(subdm, 0, totSubPoints)); PetscCall(DMPlexSetVTKCellHeight(subdm, cellHeight)); /* Set cone sizes */ firstSubPoint[sdim] = 0; firstSubPoint[0] = firstSubPoint[sdim] + numSubPoints[sdim]; if (sdim > 1) firstSubPoint[sdim - 1] = firstSubPoint[0] + numSubPoints[0]; if (sdim > 2) firstSubPoint[sdim - 2] = firstSubPoint[sdim - 1] + numSubPoints[sdim - 1]; for (d = 0; d <= sdim; ++d) { PetscCall(DMLabelGetStratumIS(subpointMap, d, &subpointIS[d])); if (subpointIS[d]) PetscCall(ISGetIndices(subpointIS[d], &subpoints[d])); } /* We do not want this label automatically computed, instead we compute it here */ PetscCall(DMCreateLabel(subdm, "celltype")); for (d = 0; d <= sdim; ++d) { for (p = 0; p < numSubPoints[d]; ++p) { const PetscInt point = subpoints[d][p]; const PetscInt subpoint = firstSubPoint[d] + p; const PetscInt *cone; PetscInt coneSize; PetscCall(DMPlexGetConeSize(dm, point, &coneSize)); if (cellHeight && (d == sdim)) { PetscInt coneSizeNew, c, val; PetscCall(DMPlexGetCone(dm, point, &cone)); for (c = 0, coneSizeNew = 0; c < coneSize; ++c) { PetscCall(DMLabelGetValue(subpointMap, cone[c], &val)); if (val >= 0) coneSizeNew++; } PetscCall(DMPlexSetConeSize(subdm, subpoint, coneSizeNew)); PetscCall(DMPlexSetCellType(subdm, subpoint, DM_POLYTOPE_FV_GHOST)); } else { DMPolytopeType ct; PetscCall(DMPlexSetConeSize(subdm, subpoint, coneSize)); PetscCall(DMPlexGetCellType(dm, point, &ct)); PetscCall(DMPlexSetCellType(subdm, subpoint, ct)); } } } PetscCall(DMLabelDestroy(&subpointMap)); PetscCall(DMSetUp(subdm)); /* Set cones */ PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, NULL)); PetscCall(PetscMalloc2(maxConeSize, &coneNew, maxConeSize, &orntNew)); for (d = 0; d <= sdim; ++d) { for (p = 0; p < numSubPoints[d]; ++p) { const PetscInt point = subpoints[d][p]; const PetscInt subpoint = firstSubPoint[d] + p; const PetscInt *cone, *ornt; PetscInt coneSize, subconeSize, coneSizeNew, c, subc, fornt = 0; if (d == sdim - 1) { const PetscInt *support, *cone, *ornt; PetscInt supportSize, coneSize, s, subc; PetscCall(DMPlexGetSupport(dm, point, &support)); PetscCall(DMPlexGetSupportSize(dm, point, &supportSize)); for (s = 0; s < supportSize; ++s) { PetscBool isHybrid = PETSC_FALSE; PetscCall(DMPlexCellIsHybrid_Internal(dm, support[s], &isHybrid)); if (!isHybrid) continue; PetscCall(PetscFindInt(support[s], numSubPoints[d + 1], subpoints[d + 1], &subc)); if (subc >= 0) { const PetscInt ccell = subpoints[d + 1][subc]; PetscCall(DMPlexGetCone(dm, ccell, &cone)); PetscCall(DMPlexGetConeSize(dm, ccell, &coneSize)); PetscCall(DMPlexGetConeOrientation(dm, ccell, &ornt)); for (c = 0; c < coneSize; ++c) { if (cone[c] == point) { fornt = ornt[c]; break; } } break; } } } PetscCall(DMPlexGetConeSize(dm, point, &coneSize)); PetscCall(DMPlexGetConeSize(subdm, subpoint, &subconeSize)); PetscCall(DMPlexGetCone(dm, point, &cone)); PetscCall(DMPlexGetConeOrientation(dm, point, &ornt)); for (c = 0, coneSizeNew = 0; c < coneSize; ++c) { PetscCall(PetscFindInt(cone[c], numSubPoints[d - 1], subpoints[d - 1], &subc)); if (subc >= 0) { coneNew[coneSizeNew] = firstSubPoint[d - 1] + subc; orntNew[coneSizeNew] = ornt[c]; ++coneSizeNew; } } PetscCheck(coneSizeNew == subconeSize, comm, PETSC_ERR_PLIB, "Number of cone points located %" PetscInt_FMT " does not match subcone size %" PetscInt_FMT, coneSizeNew, subconeSize); PetscCall(DMPlexSetCone(subdm, subpoint, coneNew)); PetscCall(DMPlexSetConeOrientation(subdm, subpoint, orntNew)); if (fornt < 0) PetscCall(DMPlexOrientPoint(subdm, subpoint, fornt)); } } PetscCall(PetscFree2(coneNew, orntNew)); PetscCall(DMPlexSymmetrize(subdm)); PetscCall(DMPlexStratify(subdm)); /* Build coordinates */ { PetscSection coordSection, subCoordSection; Vec coordinates, subCoordinates; PetscScalar *coords, *subCoords; PetscInt cdim, numComp, coordSize; const char *name; PetscCall(DMGetCoordinateDim(dm, &cdim)); PetscCall(DMGetCoordinateSection(dm, &coordSection)); PetscCall(DMGetCoordinatesLocal(dm, &coordinates)); PetscCall(DMGetCoordinateSection(subdm, &subCoordSection)); PetscCall(PetscSectionSetNumFields(subCoordSection, 1)); PetscCall(PetscSectionGetFieldComponents(coordSection, 0, &numComp)); PetscCall(PetscSectionSetFieldComponents(subCoordSection, 0, numComp)); PetscCall(PetscSectionSetChart(subCoordSection, firstSubPoint[0], firstSubPoint[0] + numSubPoints[0])); for (v = 0; v < numSubPoints[0]; ++v) { const PetscInt vertex = subpoints[0][v]; const PetscInt subvertex = firstSubPoint[0] + v; PetscInt dof; PetscCall(PetscSectionGetDof(coordSection, vertex, &dof)); PetscCall(PetscSectionSetDof(subCoordSection, subvertex, dof)); PetscCall(PetscSectionSetFieldDof(subCoordSection, subvertex, 0, dof)); } PetscCall(PetscSectionSetUp(subCoordSection)); PetscCall(PetscSectionGetStorageSize(subCoordSection, &coordSize)); PetscCall(VecCreate(PETSC_COMM_SELF, &subCoordinates)); PetscCall(PetscObjectGetName((PetscObject)coordinates, &name)); PetscCall(PetscObjectSetName((PetscObject)subCoordinates, name)); PetscCall(VecSetSizes(subCoordinates, coordSize, PETSC_DETERMINE)); PetscCall(VecSetBlockSize(subCoordinates, cdim)); PetscCall(VecSetType(subCoordinates, VECSTANDARD)); PetscCall(VecGetArray(coordinates, &coords)); PetscCall(VecGetArray(subCoordinates, &subCoords)); for (v = 0; v < numSubPoints[0]; ++v) { const PetscInt vertex = subpoints[0][v]; const PetscInt subvertex = firstSubPoint[0] + v; PetscInt dof, off, sdof, soff, d; PetscCall(PetscSectionGetDof(coordSection, vertex, &dof)); PetscCall(PetscSectionGetOffset(coordSection, vertex, &off)); PetscCall(PetscSectionGetDof(subCoordSection, subvertex, &sdof)); PetscCall(PetscSectionGetOffset(subCoordSection, subvertex, &soff)); PetscCheck(dof == sdof, comm, PETSC_ERR_PLIB, "Coordinate dimension %" PetscInt_FMT " on subvertex %" PetscInt_FMT ", vertex %" PetscInt_FMT " should be %" PetscInt_FMT, sdof, subvertex, vertex, dof); for (d = 0; d < dof; ++d) subCoords[soff + d] = coords[off + d]; } PetscCall(VecRestoreArray(coordinates, &coords)); PetscCall(VecRestoreArray(subCoordinates, &subCoords)); PetscCall(DMSetCoordinatesLocal(subdm, subCoordinates)); PetscCall(VecDestroy(&subCoordinates)); } /* Build SF: We need this complexity because subpoints might not be selected on the owning process */ { PetscSF sfPoint, sfPointSub; IS subpIS; const PetscSFNode *remotePoints; PetscSFNode *sremotePoints = NULL, *newLocalPoints = NULL, *newOwners = NULL; const PetscInt *localPoints, *subpoints, *rootdegree; PetscInt *slocalPoints = NULL, *sortedPoints = NULL, *sortedIndices = NULL; PetscInt numRoots, numLeaves, numSubpoints = 0, numSubroots, numSubleaves = 0, l, sl = 0, ll = 0, pStart, pEnd, p; PetscMPIInt rank, size; PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank)); PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size)); PetscCall(DMGetPointSF(dm, &sfPoint)); PetscCall(DMGetPointSF(subdm, &sfPointSub)); PetscCall(DMPlexGetChart(dm, &pStart, &pEnd)); PetscCall(DMPlexGetChart(subdm, NULL, &numSubroots)); PetscCall(DMPlexGetSubpointIS(subdm, &subpIS)); if (subpIS) { PetscBool sorted = PETSC_TRUE; PetscCall(ISGetIndices(subpIS, &subpoints)); PetscCall(ISGetLocalSize(subpIS, &numSubpoints)); for (p = 1; p < numSubpoints; ++p) sorted = sorted && (subpoints[p] >= subpoints[p - 1]) ? PETSC_TRUE : PETSC_FALSE; if (!sorted) { PetscCall(PetscMalloc2(numSubpoints, &sortedPoints, numSubpoints, &sortedIndices)); for (p = 0; p < numSubpoints; ++p) sortedIndices[p] = p; PetscCall(PetscArraycpy(sortedPoints, subpoints, numSubpoints)); PetscCall(PetscSortIntWithArray(numSubpoints, sortedPoints, sortedIndices)); } } PetscCall(PetscSFGetGraph(sfPoint, &numRoots, &numLeaves, &localPoints, &remotePoints)); if (numRoots >= 0) { PetscCall(PetscSFComputeDegreeBegin(sfPoint, &rootdegree)); PetscCall(PetscSFComputeDegreeEnd(sfPoint, &rootdegree)); PetscCall(PetscMalloc2(pEnd - pStart, &newLocalPoints, numRoots, &newOwners)); for (p = 0; p < pEnd - pStart; ++p) { newLocalPoints[p].rank = -2; newLocalPoints[p].index = -2; } /* Set subleaves */ for (l = 0; l < numLeaves; ++l) { const PetscInt point = localPoints[l]; const PetscInt subpoint = DMPlexFilterPointPerm_Internal(point, 0, numSubpoints, sortedPoints ? sortedPoints : subpoints, sortedIndices); if (subpoint < 0) continue; newLocalPoints[point - pStart].rank = rank; newLocalPoints[point - pStart].index = subpoint; ++numSubleaves; } /* Must put in owned subpoints */ for (p = pStart; p < pEnd; ++p) { newOwners[p - pStart].rank = -3; newOwners[p - pStart].index = -3; } for (p = 0; p < numSubpoints; ++p) { /* Hold on to currently owned points */ if (rootdegree[subpoints[p] - pStart]) newOwners[subpoints[p] - pStart].rank = rank + size; else newOwners[subpoints[p] - pStart].rank = rank; newOwners[subpoints[p] - pStart].index = p; } PetscCall(PetscSFReduceBegin(sfPoint, MPIU_2INT, newLocalPoints, newOwners, MPI_MAXLOC)); PetscCall(PetscSFReduceEnd(sfPoint, MPIU_2INT, newLocalPoints, newOwners, MPI_MAXLOC)); for (p = pStart; p < pEnd; ++p) if (newOwners[p - pStart].rank >= size) newOwners[p - pStart].rank -= size; PetscCall(PetscSFBcastBegin(sfPoint, MPIU_2INT, newOwners, newLocalPoints, MPI_REPLACE)); PetscCall(PetscSFBcastEnd(sfPoint, MPIU_2INT, newOwners, newLocalPoints, MPI_REPLACE)); PetscCall(PetscMalloc1(numSubleaves, &slocalPoints)); PetscCall(PetscMalloc1(numSubleaves, &sremotePoints)); for (l = 0; l < numLeaves; ++l) { const PetscInt point = localPoints[l]; const PetscInt subpoint = DMPlexFilterPointPerm_Internal(point, 0, numSubpoints, sortedPoints ? sortedPoints : subpoints, sortedIndices); if (subpoint < 0) continue; if (newLocalPoints[point].rank == rank) { ++ll; continue; } slocalPoints[sl] = subpoint; sremotePoints[sl].rank = newLocalPoints[point].rank; sremotePoints[sl].index = newLocalPoints[point].index; PetscCheck(sremotePoints[sl].rank >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid remote rank for local point %" PetscInt_FMT, point); PetscCheck(sremotePoints[sl].index >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid remote subpoint for local point %" PetscInt_FMT, point); ++sl; } PetscCheck(sl + ll == numSubleaves, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Mismatch in number of subleaves %" PetscInt_FMT " + %" PetscInt_FMT " != %" PetscInt_FMT, sl, ll, numSubleaves); PetscCall(PetscFree2(newLocalPoints, newOwners)); PetscCall(PetscSFSetGraph(sfPointSub, numSubroots, sl, slocalPoints, PETSC_OWN_POINTER, sremotePoints, PETSC_OWN_POINTER)); } if (subpIS) PetscCall(ISRestoreIndices(subpIS, &subpoints)); PetscCall(PetscFree2(sortedPoints, sortedIndices)); } /* Filter labels */ PetscCall(DMPlexFilterLabels_Internal(dm, numSubPoints, subpoints, firstSubPoint, subdm)); /* Cleanup */ for (d = 0; d <= sdim; ++d) { if (subpointIS[d]) PetscCall(ISRestoreIndices(subpointIS[d], &subpoints[d])); PetscCall(ISDestroy(&subpointIS[d])); } PetscCall(PetscFree4(numSubPoints, firstSubPoint, subpointIS, subpoints)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexCreateSubmesh_Interpolated(DM dm, DMLabel vertexLabel, PetscInt value, PetscBool markedFaces, DM subdm) { PetscFunctionBegin; PetscCall(DMPlexCreateSubmeshGeneric_Interpolated(dm, vertexLabel, value, markedFaces, PETSC_FALSE, 1, subdm)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexCreateSubmesh - Extract a hypersurface from the mesh using vertices defined by a label Input Parameters: + dm - The original mesh . vertexLabel - The `DMLabel` marking points contained in the surface . value - The label value to use - markedFaces - `PETSC_TRUE` if surface faces are marked in addition to vertices, `PETSC_FALSE` if only vertices are marked Output Parameter: . subdm - The surface mesh Level: developer Note: This function produces a `DMLabel` mapping original points in the submesh to their depth. This can be obtained using `DMPlexGetSubpointMap()`. .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetSubpointMap()`, `DMGetLabel()`, `DMLabelSetValue()` @*/ PetscErrorCode DMPlexCreateSubmesh(DM dm, DMLabel vertexLabel, PetscInt value, PetscBool markedFaces, DM *subdm) { DMPlexInterpolatedFlag interpolated; PetscInt dim, cdim; PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); PetscAssertPointer(subdm, 5); PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), subdm)); PetscCall(DMSetType(*subdm, DMPLEX)); PetscCall(DMSetDimension(*subdm, dim - 1)); PetscCall(DMGetCoordinateDim(dm, &cdim)); PetscCall(DMSetCoordinateDim(*subdm, cdim)); PetscCall(DMPlexIsInterpolated(dm, &interpolated)); PetscCheck(interpolated != DMPLEX_INTERPOLATED_PARTIAL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Not for partially interpolated meshes"); if (interpolated) { PetscCall(DMPlexCreateSubmesh_Interpolated(dm, vertexLabel, value, markedFaces, *subdm)); } else { PetscCall(DMPlexCreateSubmesh_Uninterpolated(dm, vertexLabel, value, *subdm)); } PetscCall(DMPlexCopy_Internal(dm, PETSC_TRUE, PETSC_TRUE, *subdm)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexCreateCohesiveSubmesh_Uninterpolated(DM dm, PetscBool hasLagrange, const char label[], PetscInt value, DM subdm) { MPI_Comm comm; DMLabel subpointMap; IS subvertexIS; const PetscInt *subVertices; PetscInt numSubVertices, firstSubVertex, numSubCells, *subCells = NULL; PetscInt *subface, maxConeSize, numSubFaces, firstSubFace, newFacePoint, nFV; PetscInt c, f; PetscFunctionBegin; PetscCall(PetscObjectGetComm((PetscObject)dm, &comm)); /* Create subpointMap which marks the submesh */ PetscCall(DMLabelCreate(PETSC_COMM_SELF, "subpoint_map", &subpointMap)); PetscCall(DMPlexSetSubpointMap(subdm, subpointMap)); PetscCall(DMLabelDestroy(&subpointMap)); PetscCall(DMPlexMarkCohesiveSubmesh_Uninterpolated(dm, hasLagrange, label, value, subpointMap, &numSubFaces, &nFV, &subCells, subdm)); /* Setup chart */ PetscCall(DMLabelGetStratumSize(subpointMap, 0, &numSubVertices)); PetscCall(DMLabelGetStratumSize(subpointMap, 2, &numSubCells)); PetscCall(DMPlexSetChart(subdm, 0, numSubCells + numSubFaces + numSubVertices)); PetscCall(DMPlexSetVTKCellHeight(subdm, 1)); /* Set cone sizes */ firstSubVertex = numSubCells; firstSubFace = numSubCells + numSubVertices; newFacePoint = firstSubFace; PetscCall(DMLabelGetStratumIS(subpointMap, 0, &subvertexIS)); if (subvertexIS) PetscCall(ISGetIndices(subvertexIS, &subVertices)); for (c = 0; c < numSubCells; ++c) PetscCall(DMPlexSetConeSize(subdm, c, 1)); for (f = firstSubFace; f < firstSubFace + numSubFaces; ++f) PetscCall(DMPlexSetConeSize(subdm, f, nFV)); PetscCall(DMSetUp(subdm)); /* Create face cones */ PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, NULL)); PetscCall(DMGetWorkArray(subdm, maxConeSize, MPIU_INT, (void **)&subface)); for (c = 0; c < numSubCells; ++c) { const PetscInt cell = subCells[c]; const PetscInt subcell = c; const PetscInt *cone, *cells; PetscBool isHybrid = PETSC_FALSE; PetscInt numCells, subVertex, p, v; PetscCall(DMPlexCellIsHybrid_Internal(dm, cell, &isHybrid)); if (!isHybrid) continue; PetscCall(DMPlexGetCone(dm, cell, &cone)); for (v = 0; v < nFV; ++v) { PetscCall(PetscFindInt(cone[v], numSubVertices, subVertices, &subVertex)); subface[v] = firstSubVertex + subVertex; } PetscCall(DMPlexSetCone(subdm, newFacePoint, subface)); PetscCall(DMPlexSetCone(subdm, subcell, &newFacePoint)); PetscCall(DMPlexGetJoin(dm, nFV, cone, &numCells, &cells)); /* Not true in parallel PetscCheck(numCells == 2,PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cohesive cells should separate two cells"); */ for (p = 0; p < numCells; ++p) { PetscInt negsubcell; PetscBool isHybrid = PETSC_FALSE; PetscCall(DMPlexCellIsHybrid_Internal(dm, cells[p], &isHybrid)); if (isHybrid) continue; /* I know this is a crap search */ for (negsubcell = 0; negsubcell < numSubCells; ++negsubcell) { if (subCells[negsubcell] == cells[p]) break; } PetscCheck(negsubcell != numSubCells, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not find negative face neighbor for cohesive cell %" PetscInt_FMT, cell); PetscCall(DMPlexSetCone(subdm, negsubcell, &newFacePoint)); } PetscCall(DMPlexRestoreJoin(dm, nFV, cone, &numCells, &cells)); ++newFacePoint; } PetscCall(DMRestoreWorkArray(subdm, maxConeSize, MPIU_INT, (void **)&subface)); PetscCall(DMPlexSymmetrize(subdm)); PetscCall(DMPlexStratify(subdm)); /* Build coordinates */ { PetscSection coordSection, subCoordSection; Vec coordinates, subCoordinates; PetscScalar *coords, *subCoords; PetscInt cdim, numComp, coordSize, v; const char *name; PetscCall(DMGetCoordinateDim(dm, &cdim)); PetscCall(DMGetCoordinateSection(dm, &coordSection)); PetscCall(DMGetCoordinatesLocal(dm, &coordinates)); PetscCall(DMGetCoordinateSection(subdm, &subCoordSection)); PetscCall(PetscSectionSetNumFields(subCoordSection, 1)); PetscCall(PetscSectionGetFieldComponents(coordSection, 0, &numComp)); PetscCall(PetscSectionSetFieldComponents(subCoordSection, 0, numComp)); PetscCall(PetscSectionSetChart(subCoordSection, firstSubVertex, firstSubVertex + numSubVertices)); for (v = 0; v < numSubVertices; ++v) { const PetscInt vertex = subVertices[v]; const PetscInt subvertex = firstSubVertex + v; PetscInt dof; PetscCall(PetscSectionGetDof(coordSection, vertex, &dof)); PetscCall(PetscSectionSetDof(subCoordSection, subvertex, dof)); PetscCall(PetscSectionSetFieldDof(subCoordSection, subvertex, 0, dof)); } PetscCall(PetscSectionSetUp(subCoordSection)); PetscCall(PetscSectionGetStorageSize(subCoordSection, &coordSize)); PetscCall(VecCreate(PETSC_COMM_SELF, &subCoordinates)); PetscCall(PetscObjectGetName((PetscObject)coordinates, &name)); PetscCall(PetscObjectSetName((PetscObject)subCoordinates, name)); PetscCall(VecSetSizes(subCoordinates, coordSize, PETSC_DETERMINE)); PetscCall(VecSetBlockSize(subCoordinates, cdim)); PetscCall(VecSetType(subCoordinates, VECSTANDARD)); PetscCall(VecGetArray(coordinates, &coords)); PetscCall(VecGetArray(subCoordinates, &subCoords)); for (v = 0; v < numSubVertices; ++v) { const PetscInt vertex = subVertices[v]; const PetscInt subvertex = firstSubVertex + v; PetscInt dof, off, sdof, soff, d; PetscCall(PetscSectionGetDof(coordSection, vertex, &dof)); PetscCall(PetscSectionGetOffset(coordSection, vertex, &off)); PetscCall(PetscSectionGetDof(subCoordSection, subvertex, &sdof)); PetscCall(PetscSectionGetOffset(subCoordSection, subvertex, &soff)); PetscCheck(dof == sdof, comm, PETSC_ERR_PLIB, "Coordinate dimension %" PetscInt_FMT " on subvertex %" PetscInt_FMT ", vertex %" PetscInt_FMT " should be %" PetscInt_FMT, sdof, subvertex, vertex, dof); for (d = 0; d < dof; ++d) subCoords[soff + d] = coords[off + d]; } PetscCall(VecRestoreArray(coordinates, &coords)); PetscCall(VecRestoreArray(subCoordinates, &subCoords)); PetscCall(DMSetCoordinatesLocal(subdm, subCoordinates)); PetscCall(VecDestroy(&subCoordinates)); } /* Build SF */ CHKMEMQ; { PetscSF sfPoint, sfPointSub; const PetscSFNode *remotePoints; PetscSFNode *sremotePoints, *newLocalPoints, *newOwners; const PetscInt *localPoints; PetscInt *slocalPoints; PetscInt numRoots, numLeaves, numSubRoots = numSubCells + numSubFaces + numSubVertices, numSubLeaves = 0, l, sl, ll, pStart, pEnd, p, vStart, vEnd; PetscMPIInt rank; PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank)); PetscCall(DMGetPointSF(dm, &sfPoint)); PetscCall(DMGetPointSF(subdm, &sfPointSub)); PetscCall(DMPlexGetChart(dm, &pStart, &pEnd)); PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd)); PetscCall(PetscSFGetGraph(sfPoint, &numRoots, &numLeaves, &localPoints, &remotePoints)); if (numRoots >= 0) { /* Only vertices should be shared */ PetscCall(PetscMalloc2(pEnd - pStart, &newLocalPoints, numRoots, &newOwners)); for (p = 0; p < pEnd - pStart; ++p) { newLocalPoints[p].rank = -2; newLocalPoints[p].index = -2; } /* Set subleaves */ for (l = 0; l < numLeaves; ++l) { const PetscInt point = localPoints[l]; const PetscInt subPoint = DMPlexFilterPoint_Internal(point, firstSubVertex, numSubVertices, subVertices); PetscCheck(!(point < vStart) || !(point >= vEnd), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Should not be mapping anything but vertices, %" PetscInt_FMT, point); if (subPoint < 0) continue; newLocalPoints[point - pStart].rank = rank; newLocalPoints[point - pStart].index = subPoint; ++numSubLeaves; } /* Must put in owned subpoints */ for (p = pStart; p < pEnd; ++p) { const PetscInt subPoint = DMPlexFilterPoint_Internal(p, firstSubVertex, numSubVertices, subVertices); if (subPoint < 0) { newOwners[p - pStart].rank = -3; newOwners[p - pStart].index = -3; } else { newOwners[p - pStart].rank = rank; newOwners[p - pStart].index = subPoint; } } PetscCall(PetscSFReduceBegin(sfPoint, MPIU_2INT, newLocalPoints, newOwners, MPI_MAXLOC)); PetscCall(PetscSFReduceEnd(sfPoint, MPIU_2INT, newLocalPoints, newOwners, MPI_MAXLOC)); PetscCall(PetscSFBcastBegin(sfPoint, MPIU_2INT, newOwners, newLocalPoints, MPI_REPLACE)); PetscCall(PetscSFBcastEnd(sfPoint, MPIU_2INT, newOwners, newLocalPoints, MPI_REPLACE)); PetscCall(PetscMalloc1(numSubLeaves, &slocalPoints)); PetscCall(PetscMalloc1(numSubLeaves, &sremotePoints)); for (l = 0, sl = 0, ll = 0; l < numLeaves; ++l) { const PetscInt point = localPoints[l]; const PetscInt subPoint = DMPlexFilterPoint_Internal(point, firstSubVertex, numSubVertices, subVertices); if (subPoint < 0) continue; if (newLocalPoints[point].rank == rank) { ++ll; continue; } slocalPoints[sl] = subPoint; sremotePoints[sl].rank = newLocalPoints[point].rank; sremotePoints[sl].index = newLocalPoints[point].index; PetscCheck(sremotePoints[sl].rank >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid remote rank for local point %" PetscInt_FMT, point); PetscCheck(sremotePoints[sl].index >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid remote subpoint for local point %" PetscInt_FMT, point); ++sl; } PetscCall(PetscFree2(newLocalPoints, newOwners)); PetscCheck(sl + ll == numSubLeaves, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Mismatch in number of subleaves %" PetscInt_FMT " + %" PetscInt_FMT " != %" PetscInt_FMT, sl, ll, numSubLeaves); PetscCall(PetscSFSetGraph(sfPointSub, numSubRoots, sl, slocalPoints, PETSC_OWN_POINTER, sremotePoints, PETSC_OWN_POINTER)); } } CHKMEMQ; /* Cleanup */ if (subvertexIS) PetscCall(ISRestoreIndices(subvertexIS, &subVertices)); PetscCall(ISDestroy(&subvertexIS)); PetscCall(PetscFree(subCells)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexCreateCohesiveSubmesh_Interpolated(DM dm, const char labelname[], PetscInt value, DM subdm) { DMLabel label = NULL; PetscFunctionBegin; if (labelname) PetscCall(DMGetLabel(dm, labelname, &label)); PetscCall(DMPlexCreateSubmeshGeneric_Interpolated(dm, label, value, PETSC_FALSE, PETSC_TRUE, 1, subdm)); PetscFunctionReturn(PETSC_SUCCESS); } /*@C DMPlexCreateCohesiveSubmesh - Extract from a mesh with cohesive cells the hypersurface defined by one face of the cells. Optionally, a label can be given to restrict the cells. Input Parameters: + dm - The original mesh . hasLagrange - The mesh has Lagrange unknowns in the cohesive cells . label - A label name, or `NULL` - value - A label value Output Parameter: . subdm - The surface mesh Level: developer Note: This function produces a `DMLabel` mapping original points in the submesh to their depth. This can be obtained using `DMPlexGetSubpointMap()`. .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetSubpointMap()`, `DMPlexCreateSubmesh()` @*/ PetscErrorCode DMPlexCreateCohesiveSubmesh(DM dm, PetscBool hasLagrange, const char label[], PetscInt value, DM *subdm) { PetscInt dim, cdim, depth; PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); PetscAssertPointer(subdm, 5); PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMPlexGetDepth(dm, &depth)); PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), subdm)); PetscCall(DMSetType(*subdm, DMPLEX)); PetscCall(DMSetDimension(*subdm, dim - 1)); PetscCall(DMGetCoordinateDim(dm, &cdim)); PetscCall(DMSetCoordinateDim(*subdm, cdim)); if (depth == dim) { PetscCall(DMPlexCreateCohesiveSubmesh_Interpolated(dm, label, value, *subdm)); } else { PetscCall(DMPlexCreateCohesiveSubmesh_Uninterpolated(dm, hasLagrange, label, value, *subdm)); } PetscCall(DMPlexCopy_Internal(dm, PETSC_TRUE, PETSC_TRUE, *subdm)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexReorderCohesiveSupports - Ensure that face supports for cohesive end caps are ordered Not Collective Input Parameter: . dm - The `DM` containing cohesive cells Level: developer Note: For the negative size (first) face, the cohesive cell should be first in the support, and for the positive side (second) face, the cohesive cell should be second in the support. .seealso: `DMPlexConstructCohesiveCells()`, `DMPlexCreateCohesiveSubmesh()` @*/ PetscErrorCode DMPlexReorderCohesiveSupports(DM dm) { PetscInt dim, cStart, cEnd; PetscFunctionBegin; PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMPlexGetTensorPrismBounds_Internal(dm, dim, &cStart, &cEnd)); for (PetscInt c = cStart; c < cEnd; ++c) { const PetscInt *cone; PetscInt coneSize; PetscCall(DMPlexGetConeSize(dm, c, &coneSize)); PetscCall(DMPlexGetCone(dm, c, &cone)); PetscCheck(coneSize >= 2, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Hybrid cell %" PetscInt_FMT " cone size %" PetscInt_FMT " must be >= 2", c, coneSize); for (PetscInt s = 0; s < 2; ++s) { const PetscInt *supp; PetscInt suppSize, newsupp[2]; PetscCall(DMPlexGetSupportSize(dm, cone[s], &suppSize)); PetscCall(DMPlexGetSupport(dm, cone[s], &supp)); if (suppSize == 2) { /* Reorder hybrid end cap support */ if (supp[s] == c) { newsupp[0] = supp[1]; newsupp[1] = supp[0]; } else { newsupp[0] = supp[0]; newsupp[1] = supp[1]; } PetscCheck(newsupp[1 - s] == c, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Hybrid end cap %" PetscInt_FMT " support entry %" PetscInt_FMT " != %" PetscInt_FMT " hybrid cell", cone[s], newsupp[1 - s], c); PetscCall(DMPlexSetSupport(dm, cone[s], newsupp)); } } } PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexFilter - Extract a subset of mesh cells defined by a label as a separate mesh Input Parameters: + dm - The original mesh . cellLabel - The `DMLabel` marking cells contained in the new mesh - value - The label value to use Output Parameter: . subdm - The new mesh Level: developer Note: This function produces a `DMLabel` mapping original points in the submesh to their depth. This can be obtained using `DMPlexGetSubpointMap()`. .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetSubpointMap()`, `DMGetLabel()`, `DMLabelSetValue()`, `DMPlexCreateSubmesh()` @*/ PetscErrorCode DMPlexFilter(DM dm, DMLabel cellLabel, PetscInt value, DM *subdm) { PetscInt dim, overlap; PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); PetscAssertPointer(subdm, 4); PetscCall(DMGetDimension(dm, &dim)); PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), subdm)); PetscCall(DMSetType(*subdm, DMPLEX)); /* Extract submesh in place, could be empty on some procs, could have inconsistency if procs do not both extract a shared cell */ PetscCall(DMPlexCreateSubmeshGeneric_Interpolated(dm, cellLabel, value, PETSC_FALSE, PETSC_FALSE, 0, *subdm)); PetscCall(DMPlexCopy_Internal(dm, PETSC_TRUE, PETSC_TRUE, *subdm)); // It is possible to obtain a surface mesh where some faces are in SF // We should either mark the mesh as having an overlap, or delete these from the SF PetscCall(DMPlexGetOverlap(dm, &overlap)); if (!overlap) { PetscSF sf; const PetscInt *leaves; PetscInt cStart, cEnd, Nl; PetscBool hasSubcell = PETSC_FALSE, ghasSubcell; PetscCall(DMPlexGetHeightStratum(*subdm, 0, &cStart, &cEnd)); PetscCall(DMGetPointSF(*subdm, &sf)); PetscCall(PetscSFGetGraph(sf, NULL, &Nl, &leaves, NULL)); for (PetscInt l = 0; l < Nl; ++l) { const PetscInt point = leaves ? leaves[l] : l; if (point >= cStart && point < cEnd) { hasSubcell = PETSC_TRUE; break; } } PetscCall(MPIU_Allreduce(&hasSubcell, &ghasSubcell, 1, MPIU_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm))); if (ghasSubcell) PetscCall(DMPlexSetOverlap(*subdm, NULL, 1)); } PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexGetSubpointMap - Returns a `DMLabel` with point dimension as values Input Parameter: . dm - The submesh `DM` Output Parameter: . subpointMap - The `DMLabel` of all the points from the original mesh in this submesh, or `NULL` if this is not a submesh Level: developer .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreateSubmesh()`, `DMPlexGetSubpointIS()` @*/ PetscErrorCode DMPlexGetSubpointMap(DM dm, DMLabel *subpointMap) { PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); PetscAssertPointer(subpointMap, 2); *subpointMap = ((DM_Plex *)dm->data)->subpointMap; PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexSetSubpointMap - Sets the `DMLabel` with point dimension as values Input Parameters: + dm - The submesh `DM` - subpointMap - The `DMLabel` of all the points from the original mesh in this submesh Level: developer Note: Should normally not be called by the user, since it is set in `DMPlexCreateSubmesh()` .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreateSubmesh()`, `DMPlexGetSubpointIS()` @*/ PetscErrorCode DMPlexSetSubpointMap(DM dm, DMLabel subpointMap) { DM_Plex *mesh = (DM_Plex *)dm->data; DMLabel tmp; PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); tmp = mesh->subpointMap; mesh->subpointMap = subpointMap; PetscCall(PetscObjectReference((PetscObject)mesh->subpointMap)); PetscCall(DMLabelDestroy(&tmp)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode DMPlexCreateSubpointIS_Internal(DM dm, IS *subpointIS) { DMLabel spmap; PetscInt depth, d; PetscFunctionBegin; PetscCall(DMPlexGetSubpointMap(dm, &spmap)); PetscCall(DMPlexGetDepth(dm, &depth)); if (spmap && depth >= 0) { DM_Plex *mesh = (DM_Plex *)dm->data; PetscInt *points, *depths; PetscInt pStart, pEnd, p, off; PetscCall(DMPlexGetChart(dm, &pStart, &pEnd)); PetscCheck(!pStart, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Submeshes must start the point numbering at 0, not %" PetscInt_FMT, pStart); PetscCall(PetscMalloc1(pEnd, &points)); PetscCall(DMGetWorkArray(dm, depth + 1, MPIU_INT, &depths)); depths[0] = depth; depths[1] = 0; for (d = 2; d <= depth; ++d) depths[d] = depth + 1 - d; for (d = 0, off = 0; d <= depth; ++d) { const PetscInt dep = depths[d]; PetscInt depStart, depEnd, n; PetscCall(DMPlexGetDepthStratum(dm, dep, &depStart, &depEnd)); PetscCall(DMLabelGetStratumSize(spmap, dep, &n)); if (((d < 2) && (depth > 1)) || (d == 1)) { /* Only check vertices and cells for now since the map is broken for others */ PetscCheck(n == depEnd - depStart, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of mapped submesh points %" PetscInt_FMT " at depth %" PetscInt_FMT " should be %" PetscInt_FMT, n, dep, depEnd - depStart); } else { if (!n) { if (d == 0) { /* Missing cells */ for (p = 0; p < depEnd - depStart; ++p, ++off) points[off] = -1; } else { /* Missing faces */ for (p = 0; p < depEnd - depStart; ++p, ++off) points[off] = PETSC_MAX_INT; } } } if (n) { IS is; const PetscInt *opoints; PetscCall(DMLabelGetStratumIS(spmap, dep, &is)); PetscCall(ISGetIndices(is, &opoints)); for (p = 0; p < n; ++p, ++off) points[off] = opoints[p]; PetscCall(ISRestoreIndices(is, &opoints)); PetscCall(ISDestroy(&is)); } } PetscCall(DMRestoreWorkArray(dm, depth + 1, MPIU_INT, &depths)); PetscCheck(off == pEnd, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of mapped submesh points %" PetscInt_FMT " should be %" PetscInt_FMT, off, pEnd); PetscCall(ISCreateGeneral(PETSC_COMM_SELF, pEnd, points, PETSC_OWN_POINTER, subpointIS)); PetscCall(PetscObjectStateGet((PetscObject)spmap, &mesh->subpointState)); } PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMPlexGetSubpointIS - Returns an `IS` covering the entire subdm chart with the original points as data Input Parameter: . dm - The submesh `DM` Output Parameter: . subpointIS - The `IS` of all the points from the original mesh in this submesh, or `NULL` if this is not a submesh Level: developer Note: This `IS` is guaranteed to be sorted by the construction of the submesh .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreateSubmesh()`, `DMPlexGetSubpointMap()` @*/ PetscErrorCode DMPlexGetSubpointIS(DM dm, IS *subpointIS) { DM_Plex *mesh = (DM_Plex *)dm->data; DMLabel spmap; PetscObjectState state; PetscFunctionBegin; PetscValidHeaderSpecific(dm, DM_CLASSID, 1); PetscAssertPointer(subpointIS, 2); PetscCall(DMPlexGetSubpointMap(dm, &spmap)); PetscCall(PetscObjectStateGet((PetscObject)spmap, &state)); if (state != mesh->subpointState || !mesh->subpointIS) PetscCall(DMPlexCreateSubpointIS_Internal(dm, &mesh->subpointIS)); *subpointIS = mesh->subpointIS; PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMGetEnclosureRelation - Get the relationship between `dmA` and `dmB` Input Parameters: + dmA - The first `DM` - dmB - The second `DM` Output Parameter: . rel - The relation of `dmA` to `dmB` Level: intermediate .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMGetEnclosurePoint()` @*/ PetscErrorCode DMGetEnclosureRelation(DM dmA, DM dmB, DMEnclosureType *rel) { DM plexA, plexB, sdm; DMLabel spmap; PetscInt pStartA, pEndA, pStartB, pEndB, NpA, NpB; PetscFunctionBegin; PetscAssertPointer(rel, 3); *rel = DM_ENC_NONE; if (!dmA || !dmB) PetscFunctionReturn(PETSC_SUCCESS); PetscValidHeaderSpecific(dmA, DM_CLASSID, 1); PetscValidHeaderSpecific(dmB, DM_CLASSID, 2); if (dmA == dmB) { *rel = DM_ENC_EQUALITY; PetscFunctionReturn(PETSC_SUCCESS); } PetscCall(DMConvert(dmA, DMPLEX, &plexA)); PetscCall(DMConvert(dmB, DMPLEX, &plexB)); PetscCall(DMPlexGetChart(plexA, &pStartA, &pEndA)); PetscCall(DMPlexGetChart(plexB, &pStartB, &pEndB)); /* Assumption 1: subDMs have smaller charts than the DMs that they originate from - The degenerate case of a subdomain which includes all of the domain on some process can be treated as equality */ if ((pStartA == pStartB) && (pEndA == pEndB)) { *rel = DM_ENC_EQUALITY; goto end; } NpA = pEndA - pStartA; NpB = pEndB - pStartB; if (NpA == NpB) goto end; sdm = NpA > NpB ? plexB : plexA; /* The other is the original, enclosing dm */ PetscCall(DMPlexGetSubpointMap(sdm, &spmap)); if (!spmap) goto end; /* TODO Check the space mapped to by subpointMap is same size as dm */ if (NpA > NpB) { *rel = DM_ENC_SUPERMESH; } else { *rel = DM_ENC_SUBMESH; } end: PetscCall(DMDestroy(&plexA)); PetscCall(DMDestroy(&plexB)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ DMGetEnclosurePoint - Get the point `pA` in `dmA` which corresponds to the point `pB` in `dmB` Input Parameters: + dmA - The first `DM` . dmB - The second `DM` . etype - The type of enclosure relation that `dmA` has to `dmB` - pB - A point of `dmB` Output Parameter: . pA - The corresponding point of `dmA` Level: intermediate .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMGetEnclosureRelation()` @*/ PetscErrorCode DMGetEnclosurePoint(DM dmA, DM dmB, DMEnclosureType etype, PetscInt pB, PetscInt *pA) { DM sdm; IS subpointIS; const PetscInt *subpoints; PetscInt numSubpoints; PetscFunctionBegin; /* TODO Cache the IS, making it look like an index */ switch (etype) { case DM_ENC_SUPERMESH: sdm = dmB; PetscCall(DMPlexGetSubpointIS(sdm, &subpointIS)); PetscCall(ISGetIndices(subpointIS, &subpoints)); *pA = subpoints[pB]; PetscCall(ISRestoreIndices(subpointIS, &subpoints)); break; case DM_ENC_SUBMESH: sdm = dmA; PetscCall(DMPlexGetSubpointIS(sdm, &subpointIS)); PetscCall(ISGetLocalSize(subpointIS, &numSubpoints)); PetscCall(ISGetIndices(subpointIS, &subpoints)); PetscCall(PetscFindInt(pB, numSubpoints, subpoints, pA)); if (*pA < 0) { PetscCall(DMViewFromOptions(dmA, NULL, "-dm_enc_A_view")); PetscCall(DMViewFromOptions(dmB, NULL, "-dm_enc_B_view")); SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Point %" PetscInt_FMT " not found in submesh", pB); } PetscCall(ISRestoreIndices(subpointIS, &subpoints)); break; case DM_ENC_EQUALITY: case DM_ENC_NONE: *pA = pB; break; case DM_ENC_UNKNOWN: { DMEnclosureType enc; PetscCall(DMGetEnclosureRelation(dmA, dmB, &enc)); PetscCall(DMGetEnclosurePoint(dmA, dmB, enc, pB, pA)); } break; default: SETERRQ(PetscObjectComm((PetscObject)dmA), PETSC_ERR_ARG_OUTOFRANGE, "Invalid enclosure type %d", (int)etype); } PetscFunctionReturn(PETSC_SUCCESS); }
2.09375
2
2024-11-18T21:05:54.997277+00:00
2017-03-21T23:37:15
a3059528d0e4df6aa228312286d14b74a042dda8
{ "blob_id": "a3059528d0e4df6aa228312286d14b74a042dda8", "branch_name": "refs/heads/master", "committer_date": "2017-03-21T23:37:15", "content_id": "66613720d6af7e48578acc5148a6d8a7f06cf8c7", "detected_licenses": [ "MIT" ], "directory_id": "3ef1c7beca46c31973b65db698e0f6d81fd96121", "extension": "c", "filename": "c_funcs.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 75494170, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 22138, "license": "MIT", "license_type": "permissive", "path": "/src/models/c_functions/c_funcs.c", "provenance": "stackv2-0083.json.gz:5192", "repo_name": "BigBayes/SGMCMC.jl", "revision_date": "2017-03-21T23:37:15", "revision_id": "8499b4e4a1f9c3867daa1f8a4de17a0c2ea9e0a4", "snapshot_id": "f40017df7629673dd0b2560b33f1754878da778b", "src_encoding": "UTF-8", "star_events_count": 18, "url": "https://raw.githubusercontent.com/BigBayes/SGMCMC.jl/8499b4e4a1f9c3867daa1f8a4de17a0c2ea9e0a4/src/models/c_functions/c_funcs.c", "visit_date": "2021-01-20T11:14:32.387619" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "./c_matrix.h" #include "./c_funcs_ispc.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif /* *double drand() [> uniform distribution, (0..1] <] *{ * return (rand()+1.0)/(RAND_MAX+1.0); *} * *double random_normal() [> normal distribution, centered on 0, std dev 1 <] *{ * return sqrt(-2*log(drand())) * cos(2*M_PI*drand()); *} * */ double dot_product(double* a, double* b, int n) { double result = 0.0; for (int i = 0; i < n; i++) { result += a[i] * b[i]; } return result; } //@time R_AB = R - A[uu] - B[ii] //@time c_comp_R_AB_bpmf!(R_AB, R, A, B, uu, ii); void c_comp_R_AB_bpmf(double* R_AB, double* R, double* A, double* B, int* uu, int* ii, int N) { for (int i=0; i < N; i++) R_AB[i] = R[i] - A[uu[i]-1] - B[ii[i]-1]; } //#@time XX = C - B[ii] void c_comp_XX_bpmf(double* XX, double* C, double* B, int* ii, int N) { for (int i=0; i < N; i++) XX[i] = C[i] - B[ii[i]-1]; } void c_comp_C_bpmf(double* C, double* R, double* P, double* Q, int* uu, int* ii, int N, int D) { int idx_u, idx_i; for (int i = 0; i < N; i++) { idx_u = D * (uu[i] - 1); idx_i = D * (ii[i] - 1); C[i] = R[i] - dot_product(&P[idx_u], &Q[idx_i], D); } } void c_comp_error(double* error, double* rr, double mean_rate, double* P, double* Q, double* A, double* B, int* uu, int* ii, int size, int D) { int idx_u, idx_i; /*double dotval;*/ for (int i = 0; i < size; i++) { idx_u = D * (uu[i] - 1); idx_i = D * (ii[i] - 1); error[i] = (rr[i] - mean_rate) - (dot_product(&P[idx_u], &Q[idx_i], D) + A[uu[i]-1] + B[ii[i] - 1]); } } void c_comp_error_m1(double* error, double* rr, double mean_rate, double* P, double* Q, int* uu, int* ii, int size, int D) { int idx_u, idx_i; /*double dotval;*/ for (int i = 0; i < size; i++) { idx_u = D * (uu[i] - 1); idx_i = D * (ii[i] - 1); error[i] = (rr[i] - mean_rate) - dot_product(&P[idx_u], &Q[idx_i], D); } } void c_comp_grad_sum(double* error, int* uu, int* ii, double* P, double* Q, double* A, double* B, double* g_sum_P, double* g_sum_Q, double* g_sum_A, double* g_sum_B, int m, int D) { int uu_i, ii_i, uu_i_d_idx, ii_i_d_idx; double err_i; for (int i = 0; i < m; i++) { uu_i = uu[i] - 1; ii_i = ii[i] - 1; err_i = error[i]; for (int d = 0; d < D; d++) { uu_i_d_idx = D * uu_i + d; ii_i_d_idx = D * ii_i + d; g_sum_P[uu_i_d_idx] = g_sum_P[uu_i_d_idx] + (err_i * Q[ii_i_d_idx]); g_sum_Q[ii_i_d_idx] = g_sum_Q[ii_i_d_idx] + (err_i * P[uu_i_d_idx]); } g_sum_A[uu_i] += err_i; g_sum_B[ii_i] += err_i; } } void c_comp_grad_sum_m1(double* error, int* uu, int* ii, double* P, double* Q, double* g_sum_P, double* g_sum_Q, int m, int D) { int uu_i, ii_i, uu_i_d_idx, ii_i_d_idx; double err_i; for (int i = 0; i < m; i++) { uu_i = uu[i] - 1; ii_i = ii[i] - 1; err_i = error[i]; for (int d = 0; d < D; d++) { uu_i_d_idx = D * uu_i + d; ii_i_d_idx = D * ii_i + d; g_sum_P[uu_i_d_idx] = g_sum_P[uu_i_d_idx] + (err_i * Q[ii_i_d_idx]); g_sum_Q[ii_i_d_idx] = g_sum_Q[ii_i_d_idx] + (err_i * P[uu_i_d_idx]); } } } /* *void c_comp_grad_sum_pmf_m1(double* error, int* uu, int* ii, double* P, double* Q, double* g_sum_P, double* g_sum_Q, int m, int D) *{ * int uu_i, ii_i, uu_i_d_idx, ii_i_d_idx; * double err_i; * for (int i = 0; i < m; i++) { * uu_i = uu[i] - 1; * ii_i = ii[i] - 1; * err_i = error[i]; * for (int d = 0; d < D; d++) { * uu_i_d_idx = D * uu_i + d; * ii_i_d_idx = D * ii_i + d; * g_sum_P[uu_i_d_idx] = g_sum_P[uu_i_d_idx] + (err_i * Q[ii_i_d_idx]); * g_sum_Q[ii_i_d_idx] = g_sum_Q[ii_i_d_idx] + (err_i * P[uu_i_d_idx]); * } * } *} */ void c_update_para(int* ux, double* P, double* g_sum_P, double* prec_P, double* inv_pr_pick, double* rands, double ka, double halfstepsz, double sqrtstepsz, int len_ux, int dim) { int idx_u; int rnd_idx = 0; double inv_pr_pick_i; for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); inv_pr_pick_i = inv_pr_pick[ux[i]-1]; for (int k = 0; k < dim; k++) { P[idx_u + k] += halfstepsz * (ka * g_sum_P[idx_u + k] - prec_P[k] * inv_pr_pick_i * P[idx_u + k]) + sqrtstepsz * rands[rnd_idx++]; g_sum_P[idx_u + k] = 0.0; // initialize! } } } void c_update_para_prior(int* ux, double*restrict P, double*restrict g_sum_P, double*restrict prec_P, double*restrict prior_muprec, double*restrict prior_negprec, double*restrict inv_pr_pick, double*restrict rands, double ka, double halfstepsz, double sqrtstepsz, int len_ux, int dim) { int idx_u; int rnd_idx = 0; double inv_pr_pick_i; for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); inv_pr_pick_i = inv_pr_pick[ux[i]-1]; for (int k = 0; k < dim; k++) { P[idx_u + k] += halfstepsz * (ka * g_sum_P[idx_u + k] - inv_pr_pick_i * (( prec_P[k] - prior_negprec[idx_u + k]) * P[idx_u + k] - prior_muprec[idx_u + k]) ) + sqrtstepsz * rands[rnd_idx++]; g_sum_P[idx_u + k] = 0.0; // initialize! } } } void c_update_para_prior_sghmc(int* ux, double*restrict P, double*restrict mom_P, double*restrict g_sum_P, double*restrict prec_P, double*restrict prior_muprec, double*restrict prior_negprec, double*restrict rands, double ka, double stepsz, double sqrtstepsz, double A, int len_ux, int dim) { int idx_u; int rnd_idx = 0; double prec; for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); for (int k = 0; k < dim; k++) { prec = prec_P[k] - prior_negprec[idx_u + k]; mom_P[idx_u + k] += stepsz * (ka * g_sum_P[idx_u + k] - A * mom_P[idx_u +k] - ( prec*(P[idx_u + k] - prior_muprec[idx_u + k]/prec) )) + sqrtstepsz * rands[rnd_idx++]; P[idx_u + k] += stepsz * mom_P[idx_u + k ]; g_sum_P[idx_u + k] = 0.0; // initialize! } } } void c_update_para_prior_sgnht(int*restrict ux, double*restrict P, double*restrict mom_P, double*restrict g_sum_P, double*restrict prec_P, double*restrict prior_muprec, double*restrict prior_negprec, double*restrict rands, double ka, double stepsz, double sqrtstepsz, double xi, int len_ux, int dim) { int idx_u; int rnd_idx = 0; double prec; for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); for (int k = 0; k < dim; k++) { prec = prec_P[k] - prior_negprec[idx_u + k]; mom_P[idx_u + k] += stepsz * (ka * g_sum_P[idx_u + k] - xi* mom_P[idx_u +k] - ( prec*(P[idx_u + k] - prior_muprec[idx_u + k]/prec) )) + sqrtstepsz * rands[rnd_idx++]; P[idx_u + k] += stepsz * mom_P[idx_u + k ]; g_sum_P[idx_u + k] = 0.0; // initialize! } } } void c_update_para_prior_msgnht(int*restrict ux, double*restrict P, double*restrict mom_P, double* restrict xi_P, double*restrict g_sum_P, double*restrict prec_P, double*restrict prior_muprec, double*restrict prior_negprec, double*restrict rands, double ka, double stepsz, double sqrtstepsz, double mu, int len_ux, int dim) { int idx_u; int rnd_idx = 0; double prec; for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); for (int k = 0; k < dim; k++) { prec = prec_P[k] - prior_negprec[idx_u + k]; xi_P[idx_u + k] += stepsz/mu*(mom_P[idx_u +k ]*mom_P[idx_u + k] - 1.); mom_P[idx_u + k] += stepsz * (ka * g_sum_P[idx_u + k] - xi_P[idx_u+k]* mom_P[idx_u +k] - ( prec*(P[idx_u + k] - prior_muprec[idx_u + k]/prec) )) + sqrtstepsz * rands[rnd_idx++]; P[idx_u + k] += stepsz * mom_P[idx_u + k ]; g_sum_P[idx_u + k] = 0.0; // initialize! } } } double* get_SSHM_covariance_pos(double omega, double gamma, double beta , double cos_2t, double sin_2t, double e_gammat) { double gamma2 = gamma*gamma; double omegar2 = omega*omega - gamma2/4; double beta_2 = beta*beta; double *C = (double*)calloc(2 * 2, sizeof(double)); double omega2 = omega *omega; double omegar = sqrt(omegar2); C[0] = 1.0/(omega2) + e_gammat/(4*omega2* omegar2)*(-4*omega2+gamma2*cos_2t-2*gamma*omegar*sin_2t); C[1] = e_gammat*beta_2/(4*omegar2)*(1.0-cos_2t); C[2] = C[1]; C[3] = 1.+ e_gammat/(4*omegar2)*(-4*omega2+gamma2*cos_2t+2*gamma*omegar*sin_2t); return C; } double* get_SSHM_covariance_neg(double omega, double gamma, double beta , double cosh_2t, double sinh_2t) { //printf("%f %f %f %f %f\n", omega, gamma, beta, cosh_2t, sinh_2t ); double gamma2 = gamma*gamma; double omegar2 = omega*omega - gamma2/4; double beta_2 = beta*beta; double *C = (double*)calloc(2 * 2, sizeof(double)); //printf("%f %f %f %f\n", C[0],C[1], C[2], C[3] ); double omega2 = omega *omega; double omegar = sqrt(-omegar2); C[0] = 1.0/(omega2) + (-4*omega2+gamma2*cosh_2t+2*gamma*omegar*sinh_2t)/(4*omega2* omegar2); C[1] = beta_2/(4*omegar2)*(1.0-cosh_2t); C[2] = C[2]; C[3] = 1.+ (-4*omega2+gamma2*cosh_2t-2*gamma*omegar*sinh_2t)/(4*omegar2); //printf("%f %f %f %f\n", C[0],C[1], C[2], C[3] ); return C; } double* cholesky2(double* A) { double *L = (double*)calloc(2*2, sizeof(double)); L[0] = sqrt(A[0]+1e-6); L[1] = A[1]/L[0]; L[2] = 0.0; L[3] = sqrt(A[3] + 1e-6 - L[1]*L[1]); return L; } void c_sample_sshm(double U, double mom_U, double A, double Lambda, double negPrec_prior, double muPrec_prior, double dt, double randn1, double randn2, double* qq, double* pp) { double omega2 = Lambda-negPrec_prior; //printf("%f %f %f\n", Lambda, negPrec_prior, omega2 ); double omega = sqrt(omega2); double gamma = A; double beta = sqrt(2*A); double omegar2 = omega2-gamma*gamma/4; double e_gammat2 = exp(-gamma*dt/2); double mu = muPrec_prior / omega2; double omegar = 0.0; double cos_t = 0.0; double sin_t = 0.0; //printf("inside c_sample_sshm\n"); if (omegar2 >= 0) { omegar = sqrt(omegar2); cos_t = cos(omegar*dt); sin_t = sqrt(1-cos_t*cos_t); double *C = get_SSHM_covariance_pos(omega,gamma, beta, cos_t*cos_t-sin_t*sin_t,2*cos_t*sin_t,e_gammat2*e_gammat2); double *L = cholesky2(C); // printf("%f %f %f %f\n",L[0], L[1], L[2], L[3] ); // generate random numbers double q = randn1*L[0] + randn2 * L[2]; double p = randn1*L[1] + randn2 * L[3]; free(C); free(L); qq[0] = mu+e_gammat2*((U-mu)*cos_t+(mom_U+gamma*(U-mu)/2)*sin_t/omegar)+q; pp[0] = e_gammat2*(mom_U*cos_t-((U-mu)*omega2+gamma*mom_U/2)*sin_t/omegar) + p; } else { omegar = sqrt(-omegar2); double e_plus= exp(-gamma*dt/2+omegar*dt); //double d_plus = -gamma*dt/2+omega*dt; //double e_plus = 1. + d_plus + d_plus*d_plus/2; double e_minus= exp(-gamma*dt/2-omegar*dt); //double d_minus = -gamma*dt/2-omega*dt; //double e_minus = 1. + d_minus + d_minus*d_minus/2; double cosh_t = 0.5*(e_plus+e_minus); double sinh_t = 0.5*(e_plus-e_minus); double cosh_2t = 0.5*(e_plus*e_plus+e_minus*e_minus); double sinh_2t = 0.5*(e_plus*e_plus-e_minus*e_minus); double *C = get_SSHM_covariance_neg(omega, gamma, beta, cosh_2t ,sinh_2t); //printf("%f %f %f %f\n", C[0],C[1], C[2], C[3] ); double *L = cholesky2(C); //printf("%f %f %f %f\n",L[0], L[1], L[2], L[3] ); // generate random numbers double q = randn1*L[0] + randn2 * L[2]; double p = randn1*L[1] + randn2 * L[3]; free(C); free(L); qq[0] = mu+((U-mu)*cosh_t+(mom_U+gamma*(U-mu)/2)*sinh_t/omegar)+q; pp[0] = (mom_U*cosh_t-((U-mu)*omega2+gamma*mom_U/2)*sinh_t/omegar) + p; } } void c_sshm_update(int* ux, double* P, double* mom_P, int* Delta, double* prec_P, double* prior_muprec, double* prior_negprec, double* rands, double A, double dt, int len_ux, int dim) { int idx_u; int rnd_idx = 0; for (int i = 0; i < len_ux; i++) { if (Delta[i] != 0) { idx_u = dim * (ux[i] - 1); for (int k = 0; k < dim; k++) { double q[1]; double p[1]; c_sample_sshm(P[idx_u+k],mom_P[idx_u+k],A,prec_P[k],prior_negprec[idx_u+k],prior_muprec[idx_u+k],Delta[i]*dt,rands[rnd_idx+1],rands[rnd_idx+2],q,p); rnd_idx = rnd_idx + 2; P[idx_u+k] = q[0]; mom_P[idx_u+k] = p[0]; } } } } void c_update_para_sghmc_sshm(int* ux, double* P, double* mom_P, double* g_sum_P, double* prec_P, double* prior_muprec, double* prior_negprec, double* rands, int* Delta, double ka, double stepsz, double sqrtstepsz, double A, int len_ux, int dim) { int idx_u; int rnd_idx = 0; double prec; //printf("Inside c function\n" ); for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); for (int k = 0; k < dim; k++) { if (Delta[i] != 0) { double q[1]; double p[1]; c_sample_sshm(P[idx_u+k],mom_P[idx_u+k],A,prec_P[k],prior_negprec[idx_u+k],prior_muprec[idx_u+k],Delta[i]*stepsz,rands[rnd_idx+1],rands[rnd_idx+2],q,p); rnd_idx = rnd_idx + 2; P[idx_u+k] = q[0]; mom_P[idx_u+k] = p[0]; } prec = prec_P[k] - prior_negprec[idx_u + k]; mom_P[idx_u + k] += stepsz * (ka * g_sum_P[idx_u + k] - A * mom_P[idx_u +k] - ( prec*(P[idx_u + k] - prior_muprec[idx_u + k]/prec) )) + sqrtstepsz * rands[rnd_idx++]; P[idx_u + k] += stepsz * mom_P[idx_u + k ]; g_sum_P[idx_u + k] = 0.0; // initialize! } } } void c_update_para_sgd_prior(int* ux, double* P, double* g_sum_P, double* prec_P, double* prior_muprec, double* prior_negprec, double* inv_pr_pick, double ka, double halfstepsz, int len_ux, int dim) { int idx_u; double inv_pr_pick_i; for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); inv_pr_pick_i = inv_pr_pick[ux[i]-1]; for (int k = 0; k < dim; k++) { P[idx_u + k] += halfstepsz * (ka * g_sum_P[idx_u + k] - inv_pr_pick_i * (( prec_P[k] - prior_negprec[idx_u + k]) * P[idx_u + k] - prior_muprec[idx_u + k]) ); g_sum_P[idx_u + k] = 0.0; // initialize! } } } void c_add_prior_grad(double*grad, double* P, double* prec_P, double* prior_muprec, double* prior_negprec, int dim, int len_P, double blocksize, double beta) { int idx_u; for (int i=0; i < len_P; i++){ idx_u = dim * i; for (int k=0; k < dim; k++){ grad[idx_u+k] -= (prec_P[k]/(blocksize*beta) - prior_negprec[idx_u + k]) * P[idx_u + k] - prior_muprec[idx_u + k]; } } } void c_update_para_m1(int* ux, double* P, double* g_sum_P, double* mu_p, double* La_p, double* inv_pr_pick, double* rands, double ka, double halfstepsz, double sqrtstepsz, int len_ux, int dim, int batch_sz) { int idx_u; int rnd_idx = 0; double grad_prior_ik; double inv_pr_pick_i; for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); inv_pr_pick_i = inv_pr_pick[ux[i]-1]; for (int k = 0; k < dim; k++) { grad_prior_ik = 0.0; for (int j = 0; j < dim; j++) { grad_prior_ik += La_p[j*dim + k] * (P[idx_u + j] - mu_p[j]); } P[idx_u + k] += (halfstepsz * (ka * g_sum_P[idx_u + k] - inv_pr_pick_i * grad_prior_ik) + sqrtstepsz * rands[rnd_idx++]) ; g_sum_P[idx_u + k] = 0.0; // initialize! } } } void c_update_para_sgd(int* ux, double* P, double* g_sum_P, double* prec_P, double* inv_pr_pick, double ka, double halfstepsz, int len_ux, int dim) { int idx_u; double inv_pr_pick_i; for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); inv_pr_pick_i = inv_pr_pick[ux[i]-1]; for (int k = 0; k < dim; k++) { P[idx_u + k] += halfstepsz * (ka * g_sum_P[idx_u + k] - prec_P[k] * inv_pr_pick_i * P[idx_u + k]); g_sum_P[idx_u + k] = 0.0; // initialize! } } } void c_update_para_sgd_m1(int* ux, double* P, double* g_sum_P, double* mu_p, double* La_p, double* inv_pr_pick, double ka, double halfstepsz, int len_ux, int dim, int batch_sz) { int idx_u; /*double grad_prior_ik;*/ double inv_pr_pick_i; for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); inv_pr_pick_i = inv_pr_pick[ux[i]-1]; for (int k = 0; k < dim; k++) { /* *grad_prior_ik = 0; *for (int j = 0; j < dim; j++) { * grad_prior_ik += La_p[j*dim + k] * (P[idx_u + j] - mu_p[j]); *} */ /*P[idx_u + k] += halfstepsz * (ka * g_sum_P[idx_u + k] - inv_pr_pick_i * grad_prior_ik) ; */ P[idx_u + k] += halfstepsz * (ka * g_sum_P[idx_u + k] - inv_pr_pick_i * La_p[k*dim + k] * (P[idx_u + k] - mu_p[k])) ; g_sum_P[idx_u + k] = 0.0; // initialize! } } } /* *void c_update_para_sgd_m1_(int* ux, double* P, double* g_sum_P, double* grad_prior_P, double* inv_pr_pick, double ka, double halfstepsz, int len_ux, int dim, int batch_sz) *{ * int idx_u, idx_uk; * [>double grad_prior_ik;<] * double inv_pr_pick_i; * for (int i = 0; i < len_ux; i++) { * idx_u = dim * (ux[i] - 1); * inv_pr_pick_i = inv_pr_pick[ux[i]-1]; * for (int k = 0; k < dim; k++) { * [>grad_prior_ik = 0;<] * for (int j = 0; j < dim; j++) { * grad_prior_ik += La_p[j*dim + k] * (P[idx_u + j] - mu_p[j]); * } * idx_uk = idx_u + k; * P[idx_uk] += halfstepsz * (ka * g_sum_P[idx_uk] - inv_pr_pick_i * grad_prior_P[idx_uk]); * g_sum_P[idx_uk] = 0.0; // initialize! * } * } *} */ void c_update_para_sgd_mom_m1(int* ux, double* P, double* g_mom_P, double* g_sum_P, double* mu_p, double* La_p, double ka, double halfstepsz, int len_ux, int dim, int batch_sz, float mom_rate) { int idx_u; double grad_prior_ik; /*double inv_pr_pick_i;*/ for (int i = 0; i < len_ux; i++) { idx_u = dim * (ux[i] - 1); /*inv_pr_pick_i = inv_pr_pick[ux[i]-1];*/ for (int k = 0; k < dim; k++) { grad_prior_ik = 0; for (int j = 0; j < dim; j++) { grad_prior_ik += La_p[j*dim + k] * (P[idx_u + j] - mu_p[j]); } // update gradient momentum g_mom_P[idx_u + k] = mom_rate * g_mom_P[idx_u + k] + halfstepsz * (ka * g_sum_P[idx_u + k] - grad_prior_ik); // update parameter P[idx_u + k] += g_mom_P[idx_u + k]; g_sum_P[idx_u + k] = 0.0; // initialize! } } } void c_rmse_avg_m2(double* testset, double* P, double* Q, double* A, double* B, double* avg_pred, int iter, double min_rate, double max_rate, double mean_rate, int is_burnin, int sz_testset, int dim, double* avg_rmse, double* cur_rmse, int* avg_cnt) { double r_i, p_i, tmp; int u_i, i_i; if (!is_burnin) avg_cnt[0] += 1; for (int i = 0; i < sz_testset; i++) { u_i = testset[i] - 1; i_i = testset[sz_testset + i] - 1; r_i = testset[2*sz_testset + i]; p_i = dot_product(&P[dim * u_i], &Q[dim * i_i], dim) + A[u_i] + B[i_i] + mean_rate; if (p_i < min_rate) p_i = min_rate; if (p_i > max_rate) p_i = max_rate; if (!is_burnin) { avg_pred[i] = (1 - 1./avg_cnt[0]) * avg_pred[i] + 1./avg_cnt[0] * p_i; tmp = r_i - avg_pred[i]; avg_rmse[0] += tmp * tmp; } else { avg_pred[i] = p_i; } tmp = r_i - p_i; cur_rmse[0] += tmp * tmp; } avg_rmse[0] = sqrt(avg_rmse[0] / sz_testset); cur_rmse[0] = sqrt(cur_rmse[0] / sz_testset); } void c_predict(double* testset, double* P, double* Q, double* A, double* B, double* pred, double min_rate, double max_rate, double mean_rate, int sz_testset, int dim) { double p_i; int u_i, i_i; for (int i = 0; i < sz_testset; i++) { u_i = testset[i] - 1; i_i = testset[sz_testset + i] - 1; p_i = dot_product(&P[dim * u_i], &Q[dim * i_i], dim) + A[u_i] + B[i_i] + mean_rate; if (p_i < min_rate) p_i = min_rate; if (p_i > max_rate) p_i = max_rate; pred[i] = p_i; } } void c_rmse_avg_m1(double* testset, double* P, double* Q, double* avg_pred, int iter, double min_rate, double max_rate, double mean_rate, int is_burnin, int sz_testset, int dim, double* avg_rmse, double* cur_rmse, int* avg_cnt) { double r_i, p_i, tmp; int u_i, i_i; if (!is_burnin) avg_cnt[0] += 1; for (int i = 0; i < sz_testset; i++) { u_i = testset[i] - 1; i_i = testset[sz_testset + i] - 1; r_i = testset[2*sz_testset + i]; p_i = dot_product(&P[dim * u_i], &Q[dim * i_i], dim) + mean_rate; if (p_i < min_rate) p_i = min_rate; if (p_i > max_rate) p_i = max_rate; if (!is_burnin) { avg_pred[i] = (1 - 1./avg_cnt[0]) * avg_pred[i] + 1./avg_cnt[0] * p_i; tmp = r_i - avg_pred[i]; avg_rmse[0] += tmp * tmp; } else { avg_pred[i] = p_i; } tmp = r_i - p_i; cur_rmse[0] += tmp * tmp; } avg_rmse[0] = sqrt(avg_rmse[0] / sz_testset); cur_rmse[0] = sqrt(cur_rmse[0] / sz_testset); }
2.375
2
2024-11-18T21:05:55.211372+00:00
2017-06-14T18:51:14
9de59874ff834b681f780ddc502c3679f12a61d3
{ "blob_id": "9de59874ff834b681f780ddc502c3679f12a61d3", "branch_name": "refs/heads/master", "committer_date": "2017-06-14T18:51:14", "content_id": "e828b4334602ea87e3aa0a64f79734e7a27eae48", "detected_licenses": [ "MIT" ], "directory_id": "80ca2199abe2d464b445e686cce99184125d390e", "extension": "h", "filename": "ffadata.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 68370359, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 548, "license": "MIT", "license_type": "permissive", "path": "/ffadata.h", "provenance": "stackv2-0083.json.gz:5321", "repo_name": "adcameron/ffancy", "revision_date": "2017-06-14T18:51:14", "revision_id": "68245d03f7d143ae99e3bf048f7a96eafdf7728c", "snapshot_id": "98220692d5509a4fe67f78a4f2dc81b2b4712944", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/adcameron/ffancy/68245d03f7d143ae99e3bf048f7a96eafdf7728c/ffadata.h", "visit_date": "2021-01-23T22:38:42.204865" }
stackv2
// Defines the ffadata data type // Andrew Cameron, MPIFR, 30/01/2015 #include <stdio.h> #include <stdlib.h> #ifndef FFADATA_H #define FFADATA_H // ***** DATA TYPES ***** typedef double ffadata; // ***** FUNCTION PROTOTYPES ***** // Defines the addition function for the data values ffadata add(ffadata x, ffadata y); // Resamples two values into one value ffadata resample(ffadata x, ffadata y); // comparison function - returns -1 if a < b, 0 if a = b, and 1 if a > b int compare(const void * a, const void * b); #endif /* FFADATA_H */
2.203125
2
2024-11-18T21:05:55.338373+00:00
2020-08-22T03:01:49
e3f2a20930a028e9790f74047bc57d1f16c942ab
{ "blob_id": "e3f2a20930a028e9790f74047bc57d1f16c942ab", "branch_name": "refs/heads/master", "committer_date": "2020-08-22T03:01:49", "content_id": "0398e7cfc1aaef689549a66cdb35b5759cb3839f", "detected_licenses": [ "MIT" ], "directory_id": "6ee090cf252fd091163da91f9c7c073b10dca8d8", "extension": "c", "filename": "ultra.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 289131535, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1994, "license": "MIT", "license_type": "permissive", "path": "/ultra.c", "provenance": "stackv2-0083.json.gz:5449", "repo_name": "joyalraju/beaglebonebackup", "revision_date": "2020-08-22T03:01:49", "revision_id": "c5bda6e17336d46946c51c50c6a014bc21c9b81b", "snapshot_id": "842c474570ba993a9c1ba530a79cd28b1c6792f4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/joyalraju/beaglebonebackup/c5bda6e17336d46946c51c50c6a014bc21c9b81b/ultra.c", "visit_date": "2022-12-10T11:27:13.409210" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <iobb.h> void trigger(char tig) // function to trigger ultrasonic { pin_high (8,tig); iolib_delay_ms (1); pin_low (8,tig); } int echo (char ech){ // function to read echo pin of ultrasonic int value; if(is_high(8,ech)) value=1; else value=0; return value; } void main () { int echo1,echo2,echo3; iolib_init (); // initializing iobb library iolib_setdir (8,7, BBBIO_DIR_OUT); // trigger pin ultrasonic 1 iolib_setdir (8,8, BBBIO_DIR_IN); // echo pin of Ultrasonic 1 iolib_setdir (8, 9, BBBIO_DIR_OUT);//trigger pin ultrasonic 2 iolib_setdir (8, 10, BBBIO_DIR_IN);// echo pin of Ultrasonic 2 iolib_setdir (8, 11, BBBIO_DIR_OUT);//trigger pin ultrasonic 3 iolib_setdir (8, 12, BBBIO_DIR_IN);// echo pin of Ultrasonic 3 while(1) { int counter =3; trigger(7); iolib_delay_ms (5); echo1= echo(8); if(echo1== 1) //check the voltage from echo pin of ultrasonic 1 printf("space 1: vaccant \n"); else { printf("space 1: occupied \n"); counter--; // reduce the number of available slots if occupied } trigger(9); iolib_delay_ms (5); echo2= echo(10); if(echo2==1) //check the voltage from echo pin of ultrasonic 2 printf("space 2: vaccant \n"); else { printf("space 2: occupied \n"); counter--; // reduce the number of available slots if occupied } trigger(11); iolib_delay_ms (5); echo3= echo(12); if(echo3==1) //check the voltage from echo pin of ultrasonic 3 printf("space 3: vaccant \n"); else { printf("space 3: occupied \n"); counter--;//reduce the number of available slots if occupied } if(counter==0) printf("Parking full \n"); else printf("no. of parking available= %d \n",counter); // print available slots iolib_delay_ms (100); } iolib_free (); // closing iobb library }
3.15625
3
2024-11-18T21:05:55.432418+00:00
2019-06-07T14:17:21
d2551d597e6e4a8abc7496319659a71675f68596
{ "blob_id": "d2551d597e6e4a8abc7496319659a71675f68596", "branch_name": "refs/heads/master", "committer_date": "2019-06-07T14:17:21", "content_id": "e42f078c7cbb059bde3de8f1cc002aee41b0f1c5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c5c961d5c88f6b0ee4e8bfa143cca1049c4a6bf8", "extension": "c", "filename": "mqtt_packet.c", "fork_events_count": 0, "gha_created_at": "2018-03-21T14:18:11", "gha_event_created_at": "2019-06-07T14:17:22", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 126189780, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 45032, "license": "Apache-2.0", "license_type": "permissive", "path": "/mqtt/src/mqtt_packet.c", "provenance": "stackv2-0083.json.gz:5578", "repo_name": "Shylock-Hg/mqttor", "revision_date": "2019-06-07T14:17:21", "revision_id": "d119cfd11bcfa7333ab1c1a54aac7eb8f1cb6da4", "snapshot_id": "ecde0d9c5b20f21096c3cd838bb6f5e816be506d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Shylock-Hg/mqttor/d119cfd11bcfa7333ab1c1a54aac7eb8f1cb6da4/mqtt/src/mqtt_packet.c", "visit_date": "2021-04-15T17:19:20.951488" }
stackv2
/*! \file mqtt_buf_packet.c * \brief mqtt packet pack&unpack functions * \author Shylock Hg * \date 2018-04-10 * */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "../inc/mqtt_packet.h" #include "../inc/mqtt_log.h" mqtt_attr_packet_t * mqtt_attr_packet_new(size_t len_payload){ //assert(len_payload); mqtt_attr_packet_t * packet = malloc(sizeof(mqtt_attr_packet_t)); assert(packet); packet->payload = mqtt_attr_payload_new(len_payload); if(0 != len_payload) assert(packet->payload); return packet; } void mqtt_attr_packet_release(mqtt_attr_packet_t * packet){ assert(packet); /* if(MQTT_CTL_TYPE_PUBLISH == packet->hdr.bits.type){ free(packet->attr_packet.publish.topic_name); } */ mqtt_attr_payload_release(packet->payload); free(packet); } //#define MQTT_PACK_CONNECT_VAR_LEN 10 int mqtt_pack_connect( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; /* /// payload /// password struct mqtt_buf_str * p_buf_password = mqtt_buf_str_encode(p_attr_packet->attr_packet.connect.pwd); if(NULL != p_buf_password){ mqtt_buffer_array[i++] = p_buf_password; remaining_length += p_buf_password->len; } /// user struct mqtt_buf_str * p_buf_user = mqtt_buf_str_encode(p_attr_packet->attr_packet.connect.user); if(NULL != p_buf_user){ mqtt_buffer_array[i++] = p_buf_user; remaining_length += p_buf_user->len; } /// w_msg struct mqtt_buf_str * p_buf_w_msg = mqtt_buf_str_encode(p_attr_packet->attr_packet.connect.w_msg); if(NULL != p_buf_w_msg){ mqtt_buffer_array[i++] = p_buf_w_msg; remaining_length += p_buf_w_msg->len; } /// w_topic struct mqtt_buf_str * p_buf_w_topic = mqtt_buf_str_encode(p_attr_packet->attr_packet.connect.w_topic); if(NULL != p_buf_w_topic){ mqtt_buffer_array[i++] = p_buf_w_topic; remaining_length += p_buf_w_topic->len; } /// id_client struct mqtt_buf_str * p_buf_id_client = mqtt_buf_str_encode(p_attr_packet->attr_packet.connect.id_client); if(NULL != p_buf_id_client){ mqtt_buffer_array[i++] = p_buf_id_client; remaining_length += p_buf_id_client->len; } */ /* mqtt_buf_t * p_buf_payload = mqtt_attr_payload_2_buf(p_attr_packet->payload); assert(p_buf_payload); if(NULL != p_buf_payload){ mqtt_buffer_array[i++] = p_buf_payload; remaining_length += p_buf_payload->len; } */ mqtt_buf_t * p_buf_payload = mqtt_attr_payload_deep2_buf( p_attr_packet->payload); assert(p_buf_payload); if(NULL != p_buf_payload){ mqtt_buffer_array[i++] = p_buf_payload; remaining_length += p_buf_payload->len; } /// variable header /// keep alive struct mqtt_buf_uint16 * p_buf_keep_alive = mqtt_buf_uint16_encode(p_attr_packet->attr_packet.connect.keep_alive); mqtt_buffer_array[i++] = p_buf_keep_alive; remaining_length += p_buf_keep_alive->len; /// connect flags struct mqtt_buf_connect_flag * p_buf_connect_flag = mqtt_connect_flag_pack(p_attr_packet->attr_packet.connect.flag); mqtt_buffer_array[i++] = p_buf_connect_flag; remaining_length += p_buf_connect_flag->len; /// level 4 struct mqtt_buf * p_buf_level = mqtt_buf_new(sizeof(uint8_t)); p_buf_level->buf[0] = 4; mqtt_buffer_array[i++] = p_buf_level; remaining_length += p_buf_level->len; /// protocol name "MQTT" struct mqtt_buf_str * p_buf_mqtt_name = mqtt_buf_str_encode(MQTT_PROTOCOL_NAME); mqtt_buffer_array[i++] = p_buf_mqtt_name; remaining_length += p_buf_mqtt_name->len; //!< add varibale header length /// fixed header /// remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len(remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; /// ctl flags union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_CONNECT, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_connect( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ size_t offset = 0; //< fixed header //< control type mqtt_attr_ctl_flag_t attr_hdr; attr_hdr.all = p_buf_packet->buf[offset++]; //< remaining length size_t len_bytes = 0; mqtt_attr_re_len_t attr_remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //< variable header //< protocol name mqtt_buf_str_t * p_buf_protocol_name = mqtt_buf_new_4_buf( p_buf_packet->buf+offset, strlen(MQTT_PROTOCOL_NAME)+MQTT_BUF_STR_MAX_BYTE); mqtt_attr_str_t attr_protocol_name = mqtt_buf_str_decode(p_buf_protocol_name); free(attr_protocol_name); mqtt_buf_release(p_buf_protocol_name); offset += (strlen(MQTT_PROTOCOL_NAME)+MQTT_BUF_STR_MAX_BYTE); //< level uint8_t attr_level = p_buf_packet->buf[offset++]; //< connect flags mqtt_attr_connect_flag_t attr_connect_flag; attr_connect_flag.all = p_buf_packet->buf[offset++]; //< keep alive mqtt_buf_t * p_buf_keepalive = mqtt_buf_new_4_buf(p_buf_packet->buf+offset, sizeof(mqtt_attr_uint16_t)); mqtt_attr_uint16_t attr_keepalive = mqtt_buf_uint16_decode(p_buf_keepalive); mqtt_buf_release(p_buf_keepalive); offset += sizeof(mqtt_attr_uint16_t); //< payload *pp_attr_packet = mqtt_attr_packet_new( p_buf_packet->len-offset); memcpy((*pp_attr_packet)->payload->buf, p_buf_packet->buf+offset, p_buf_packet->len-offset); (*pp_attr_packet)->payload->len_valid = p_buf_packet->len-offset; //< filling packet attributes (*pp_attr_packet)->hdr = attr_hdr; (*pp_attr_packet)->remaining_length = attr_remaining_length; (*pp_attr_packet)->attr_packet.connect.flag = attr_connect_flag; (*pp_attr_packet)->attr_packet.connect.keep_alive = attr_keepalive; return E_NONE; } /* //< connack packet struct { //!< fixed header //!< variable header union mqtt_attr_connack_flag flag; //!< p_connack_flag flags of connack enum mqtt_connect_ret_code ret_code; //!< ret_code return code of connect //!< payload } connack; */ int mqtt_pack_connack( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload //< variable header //< connack return code mqtt_buf_t * buf_ret_code = mqtt_buf_new( sizeof(mqtt_attr_connack_ret_code_t)); buf_ret_code->buf[0] = p_attr_packet->attr_packet.connack.ret_code; remaining_length++; mqtt_buffer_array[i++] = buf_ret_code; //< connack flag mqtt_buf_t * buf_connack_flag = mqtt_buf_new( sizeof(mqtt_attr_connack_flag_t)); buf_connack_flag->buf[0] = p_attr_packet->attr_packet.connack.flag.all; remaining_length++; mqtt_buffer_array[i++] = buf_connack_flag; //< fixed header //< remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len( remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; //< header union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_CONNACK, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_connack( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ //< create packet attributes *pp_attr_packet = mqtt_attr_packet_new(0); int offset = 0; //< unpack packet //< fixed header //< header (*pp_attr_packet)->hdr.all = p_buf_packet->buf[offset++]; //< remaining length size_t len_bytes = 0; (*pp_attr_packet)->remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //< variable header //< connack flag (*pp_attr_packet)->attr_packet.connack.flag.all = p_buf_packet->buf[offset++]; //< connect return code (*pp_attr_packet)->attr_packet.connack.ret_code = p_buf_packet->buf[offset]; //< payload // return E_NONE; } int mqtt_pack_publish( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ //< records mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload if(NULL != p_attr_packet->payload){ mqtt_buf_t * p_buf_payload = mqtt_attr_payload_deep2_buf( p_attr_packet->payload); assert(p_buf_payload); if(NULL != p_buf_payload){ mqtt_buffer_array[i++] = p_buf_payload; remaining_length += p_buf_payload->len; } } //< varialbe header //< packet identify if(0 < p_attr_packet->hdr.bits.QoS){ mqtt_buf_uint16_t * buf_uint16 = mqtt_buf_uint16_encode( p_attr_packet->attr_packet.publish.id_packet); assert(buf_uint16); if(NULL != buf_uint16){ mqtt_buffer_array[i++] = buf_uint16; remaining_length += buf_uint16->len; } } //< topic name mqtt_buf_str_t * buf_topic = mqtt_buf_str_encode( p_attr_packet->attr_packet.publish.topic_name); assert(buf_topic); if(NULL != buf_topic){ mqtt_buffer_array[i++] = buf_topic; remaining_length += buf_topic->len; } /// fixed header /// remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len(remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; /// ctl flags /* union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_CONNECT, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; */ //p_attr_packet->hdr.bits.type = MQTT_CTL_TYPE_PUBLISH; //!< force mqtt_buf_ctl_flag_t * p_buf_ctl_flag = mqtt_ctl_flag_pack( p_attr_packet->hdr); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_publish( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ size_t offset = 0; //< fixed header //< control type mqtt_attr_ctl_flag_t attr_hdr; attr_hdr.all = p_buf_packet->buf[offset++]; //< remaining length size_t len_bytes = 0; mqtt_attr_re_len_t attr_remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //< variable header //< topic name mqtt_attr_uint16_t len_str = BYTES_2_UINT16((p_buf_packet->buf+offset)); mqtt_attr_str_t attr_topic_name = malloc(len_str+1); memcpy(attr_topic_name, p_buf_packet->buf+offset+MQTT_BUF_STR_MAX_BYTE, len_str); attr_topic_name[len_str] = '\0'; offset += MQTT_BUF_STR_MAX_BYTE+len_str; //< packet identify mqtt_attr_uint16_t attr_id_packet = 0; if(0 < attr_hdr.bits.QoS){ mqtt_buf_t * buf_id_packet = mqtt_buf_new(sizeof(mqtt_attr_uint16_t)); memcpy(buf_id_packet->buf, p_buf_packet->buf+offset, sizeof(mqtt_attr_uint16_t)); attr_id_packet = mqtt_buf_uint16_decode( buf_id_packet); offset += sizeof(mqtt_attr_uint16_t); mqtt_buf_release(buf_id_packet); } //< payload *pp_attr_packet = mqtt_attr_packet_new( p_buf_packet->len-offset); memcpy((*pp_attr_packet)->payload->buf, p_buf_packet->buf+offset, p_buf_packet->len-offset); (*pp_attr_packet)->payload->len_valid = p_buf_packet->len-offset; //< filling packet attributes (*pp_attr_packet)->hdr = attr_hdr; (*pp_attr_packet)->remaining_length = attr_remaining_length; (*pp_attr_packet)->attr_packet.publish.topic_name = attr_topic_name; (*pp_attr_packet)->attr_packet.publish.id_packet = attr_id_packet; return E_NONE; // } int mqtt_pack_puback( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload //< variable header //< packet identify mqtt_buf_uint16_t * p_buf_id_packet = mqtt_buf_uint16_encode( p_attr_packet->attr_packet.puback.id_packet); mqtt_buffer_array[i++] = p_buf_id_packet; remaining_length += sizeof(mqtt_attr_uint16_t); //< fixed header //< remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len( remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; //< header union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_PUBACK, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_puback( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ //< create packet attributes *pp_attr_packet = mqtt_attr_packet_new(0); int offset = 0; //mqtt_log_print_buf(p_buf_packet->buf, p_buf_packet->len); //< unpack packet //< fixed header //< header (*pp_attr_packet)->hdr.all = p_buf_packet->buf[offset++]; //printf("offset = `%u`\n",offset); //< remaining length size_t len_bytes = 0; (*pp_attr_packet)->remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //printf("re len = `%u`\n", (*pp_attr_packet)->remaining_length); //printf("offset = `%u`\n",offset); //< variable header //< packet identify (*pp_attr_packet)->attr_packet.puback.id_packet = BYTES_2_UINT16(p_buf_packet->buf+offset); offset += sizeof(mqtt_attr_uint16_t); //printf("id packet = `%u`\n", (*pp_attr_packet)->attr_packet.puback.id_packet); //printf("offset = `%u`\n",offset); //< payload // return E_NONE; } int mqtt_pack_pubrec( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload //< variable header //< packet identify mqtt_buf_uint16_t * p_buf_id_packet = mqtt_buf_uint16_encode( p_attr_packet->attr_packet.pubrec.id_packet); mqtt_buffer_array[i++] = p_buf_id_packet; remaining_length += sizeof(mqtt_attr_uint16_t); //< fixed header //< remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len( remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; //< header union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_PUBREC, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_pubrec( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ //< create packet attributes *pp_attr_packet = mqtt_attr_packet_new(0); int offset = 0; //mqtt_log_print_buf(p_buf_packet->buf, p_buf_packet->len); //< unpack packet //< fixed header //< header (*pp_attr_packet)->hdr.all = p_buf_packet->buf[offset++]; //printf("offset = `%u`\n",offset); //< remaining length size_t len_bytes = 0; (*pp_attr_packet)->remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //printf("re len = `%u`\n", (*pp_attr_packet)->remaining_length); //printf("offset = `%u`\n",offset); //< variable header //< packet identify (*pp_attr_packet)->attr_packet.pubrec.id_packet = BYTES_2_UINT16(p_buf_packet->buf+offset); offset += sizeof(mqtt_attr_uint16_t); //printf("id packet = `%u`\n", (*pp_attr_packet)->attr_packet.pubrec.id_packet); //printf("offset = `%u`\n",offset); //< payload // return E_NONE; } int mqtt_pack_pubrel( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload //< variable header //< packet identify mqtt_buf_uint16_t * p_buf_id_packet = mqtt_buf_uint16_encode( p_attr_packet->attr_packet.pubrel.id_packet); mqtt_buffer_array[i++] = p_buf_id_packet; remaining_length += sizeof(mqtt_attr_uint16_t); //< fixed header //< remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len( remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; //< header union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_PUBREL, .DUP = 0, .QoS = 1, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_pubrel( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ //< create packet attributes *pp_attr_packet = mqtt_attr_packet_new(0); int offset = 0; //mqtt_log_print_buf(p_buf_packet->buf, p_buf_packet->len); //< unpack packet //< fixed header //< header (*pp_attr_packet)->hdr.all = p_buf_packet->buf[offset++]; //printf("offset = `%u`\n",offset); //< remaining length size_t len_bytes = 0; (*pp_attr_packet)->remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //printf("re len = `%u`\n", (*pp_attr_packet)->remaining_length); //printf("offset = `%u`\n",offset); //< variable header //< packet identify (*pp_attr_packet)->attr_packet.pubrel.id_packet = BYTES_2_UINT16(p_buf_packet->buf+offset); offset += sizeof(mqtt_attr_uint16_t); //printf("id packet = `%u`\n", (*pp_attr_packet)->attr_packet.pubrel.id_packet); //printf("offset = `%u`\n",offset); //< payload // return E_NONE; } /*! \brief pack mqtt pubcomp packet * \param p_attr_packet[in] pointer to mqtt packet attributes * \param pp_buf_packet[out] pointer to mqtt packet buffer * \retval mqtt error * */ int mqtt_pack_pubcomp( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload //< variable header //< packet identify mqtt_buf_uint16_t * p_buf_id_packet = mqtt_buf_uint16_encode( p_attr_packet->attr_packet.pubcomp.id_packet); mqtt_buffer_array[i++] = p_buf_id_packet; remaining_length += sizeof(mqtt_attr_uint16_t); //< fixed header //< remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len( remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; //< header union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_PUBCOMP, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } /*! \brief unpack mqtt pubcomp packet * \param p_buf_packet[in] pointer to mqtt packet buffer * \param p_attr_packet[out] pointer to mqtt pubcomp attributes * \retval mqtt error * */ int mqtt_unpack_pubcomp( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ //< create packet attributes *pp_attr_packet = mqtt_attr_packet_new(0); int offset = 0; //mqtt_log_print_buf(p_buf_packet->buf, p_buf_packet->len); //< unpack packet //< fixed header //< header (*pp_attr_packet)->hdr.all = p_buf_packet->buf[offset++]; //printf("offset = `%u`\n",offset); //< remaining length size_t len_bytes = 0; (*pp_attr_packet)->remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //printf("re len = `%u`\n", (*pp_attr_packet)->remaining_length); //printf("offset = `%u`\n",offset); //< variable header //< packet identify (*pp_attr_packet)->attr_packet.pubcomp.id_packet = BYTES_2_UINT16(p_buf_packet->buf+offset); offset += sizeof(mqtt_attr_uint16_t); //printf("id packet = `%u`\n", (*pp_attr_packet)->attr_packet.pubcomp.id_packet); //printf("offset = `%u`\n",offset); //< payload // return E_NONE; } /*! \brief pack mqtt subscribe packet * \param p_attr_packet[in] pointer to mqtt packet attributes * \param pp_buf_packet[out] pointer to mqtt packet buffer * \retval mqtt error * */ int mqtt_pack_subscribe( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; /// payload mqtt_buf_t * p_buf_payload = mqtt_attr_payload_deep2_buf( p_attr_packet->payload); assert(p_buf_payload); if(NULL != p_buf_payload){ mqtt_buffer_array[i++] = p_buf_payload; remaining_length += p_buf_payload->len; } /// variable header //< packet identify mqtt_buf_uint16_t * p_buf_id_packet = mqtt_buf_uint16_encode( p_attr_packet->attr_packet.subscribe.id_packet); mqtt_buffer_array[i++] = p_buf_id_packet; remaining_length += sizeof(mqtt_attr_uint16_t); /// fixed header /// remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len(remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; /// ctl flags union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_SUBSCRIBE, .DUP = 0, .QoS = 1, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } /*! \brief unpack mqtt subscribe packet * \param p_buf_packet[in] pointer to mqtt packet buffer * \param p_attr_packet[out] pointer to mqtt subscribe attributes * \retval mqtt error * */ int mqtt_unpack_subscribe( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ size_t offset = 0; //< fixed header //< control type mqtt_attr_ctl_flag_t attr_hdr; attr_hdr.all = p_buf_packet->buf[offset++]; //< remaining length size_t len_bytes = 0; mqtt_attr_re_len_t attr_remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //< variable header //< packet identify mqtt_attr_uint16_t attr_id_packet = BYTES_2_UINT16(p_buf_packet->buf+offset); offset += sizeof(mqtt_attr_uint16_t); //< payload *pp_attr_packet = mqtt_attr_packet_new( p_buf_packet->len-offset); memcpy((*pp_attr_packet)->payload->buf, p_buf_packet->buf+offset, p_buf_packet->len-offset); (*pp_attr_packet)->payload->len_valid = p_buf_packet->len-offset; //< filling packet attributes (*pp_attr_packet)->hdr = attr_hdr; (*pp_attr_packet)->remaining_length = attr_remaining_length; (*pp_attr_packet)->attr_packet.subscribe.id_packet = attr_id_packet; return E_NONE; } /*! \brief pack mqtt suback packet * \param p_attr_packet[in] pointer to mqtt packet attributes * \param pp_buf_packet[out] pointer to mqtt packet buffer * \retval mqtt error * */ int mqtt_pack_suback( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; /// payload mqtt_buf_t * p_buf_payload = mqtt_attr_payload_deep2_buf( p_attr_packet->payload); assert(p_buf_payload); if(NULL != p_buf_payload){ mqtt_buffer_array[i++] = p_buf_payload; remaining_length += p_buf_payload->len; } /// variable header //< packet identify mqtt_buf_uint16_t * p_buf_id_packet = mqtt_buf_uint16_encode( p_attr_packet->attr_packet.suback.id_packet); mqtt_buffer_array[i++] = p_buf_id_packet; remaining_length += sizeof(mqtt_attr_uint16_t); /// fixed header /// remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len(remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; /// ctl flags union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_SUBACK, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } /*! \brief unpack mqtt suback packet * \param p_buf_packet[in] pointer to mqtt packet buffer * \param p_attr_packet[out] pointer to mqtt suback attributes * \retval mqtt error * */ int mqtt_unpack_suback( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ size_t offset = 0; //< fixed header //< control type mqtt_attr_ctl_flag_t attr_hdr; attr_hdr.all = p_buf_packet->buf[offset++]; //< remaining length size_t len_bytes = 0; mqtt_attr_re_len_t attr_remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //< variable header //< packet identify mqtt_attr_uint16_t attr_id_packet = BYTES_2_UINT16(p_buf_packet->buf+offset); offset += sizeof(mqtt_attr_uint16_t); //< payload *pp_attr_packet = mqtt_attr_packet_new( p_buf_packet->len-offset); memcpy((*pp_attr_packet)->payload->buf, p_buf_packet->buf+offset, p_buf_packet->len-offset); (*pp_attr_packet)->payload->len_valid = p_buf_packet->len - offset; //< filling packet attributes (*pp_attr_packet)->hdr = attr_hdr; (*pp_attr_packet)->remaining_length = attr_remaining_length; (*pp_attr_packet)->attr_packet.suback.id_packet = attr_id_packet; return E_NONE; } int mqtt_pack_unsubscribe( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; /// payload mqtt_buf_t * p_buf_payload = mqtt_attr_payload_deep2_buf( p_attr_packet->payload); assert(p_buf_payload); if(NULL != p_buf_payload){ mqtt_buffer_array[i++] = p_buf_payload; remaining_length += p_buf_payload->len; } /// variable header //< packet identify mqtt_buf_uint16_t * p_buf_id_packet = mqtt_buf_uint16_encode( p_attr_packet->attr_packet.unsubscribe.id_packet); mqtt_buffer_array[i++] = p_buf_id_packet; remaining_length += sizeof(mqtt_attr_uint16_t); /// fixed header /// remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len(remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; /// ctl flags union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_UNSUBSCRIBE, .DUP = 0, .QoS = 1, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_unsubscribe( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ size_t offset = 0; //< fixed header //< control type mqtt_attr_ctl_flag_t attr_hdr; attr_hdr.all = p_buf_packet->buf[offset++]; //< remaining length size_t len_bytes = 0; mqtt_attr_re_len_t attr_remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //< variable header //< packet identify mqtt_attr_uint16_t attr_id_packet = BYTES_2_UINT16(p_buf_packet->buf+offset); offset += sizeof(mqtt_attr_uint16_t); //< payload *pp_attr_packet = mqtt_attr_packet_new( p_buf_packet->len-offset); memcpy((*pp_attr_packet)->payload->buf, p_buf_packet->buf+offset, p_buf_packet->len-offset); (*pp_attr_packet)->payload->len_valid = p_buf_packet->len - offset; //< filling packet attributes (*pp_attr_packet)->hdr = attr_hdr; (*pp_attr_packet)->remaining_length = attr_remaining_length; (*pp_attr_packet)->attr_packet.unsubscribe.id_packet = attr_id_packet; return E_NONE; } int mqtt_pack_unsuback( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload //< variable header //< packet identify mqtt_buf_uint16_t * p_buf_id_packet = mqtt_buf_uint16_encode( p_attr_packet->attr_packet.unsuback.id_packet); mqtt_buffer_array[i++] = p_buf_id_packet; remaining_length += sizeof(mqtt_attr_uint16_t); //< fixed header //< remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len( remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; //< header union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_UNSUBACK, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_unsuback( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ //< create packet attributes *pp_attr_packet = mqtt_attr_packet_new(0); int offset = 0; //mqtt_log_print_buf(p_buf_packet->buf, p_buf_packet->len); //< unpack packet //< fixed header //< header (*pp_attr_packet)->hdr.all = p_buf_packet->buf[offset++]; //printf("offset = `%u`\n",offset); //< remaining length size_t len_bytes = 0; (*pp_attr_packet)->remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //printf("re len = `%u`\n", (*pp_attr_packet)->remaining_length); //printf("offset = `%u`\n",offset); //< variable header //< packet identify (*pp_attr_packet)->attr_packet.unsuback.id_packet = BYTES_2_UINT16(p_buf_packet->buf+offset); offset += sizeof(mqtt_attr_uint16_t); //printf("id packet = `%u`\n", (*pp_attr_packet)->attr_packet.unsuback.id_packet); //printf("offset = `%u`\n",offset); //< payload // return E_NONE; } int mqtt_pack_pingreq( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload //< variable header //< fixed header //< remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len( remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; //< header union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_PINGREQ, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_pingreq( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ //< create packet attributes *pp_attr_packet = mqtt_attr_packet_new(0); int offset = 0; //< fixed header //< header (*pp_attr_packet)->hdr.all = p_buf_packet->buf[offset++]; //< remaining length size_t len_bytes = 0; (*pp_attr_packet)->remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //< variable header //< payload // return E_NONE; } int mqtt_pack_pingresp( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload //< variable header //< fixed header //< remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len( remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; //< header union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_PINGRESP, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_pingresp( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ //< create packet attributes *pp_attr_packet = mqtt_attr_packet_new(0); int offset = 0; //< fixed header //< header (*pp_attr_packet)->hdr.all = p_buf_packet->buf[offset++]; //< remaining length size_t len_bytes = 0; (*pp_attr_packet)->remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //< variable header //< payload // return E_NONE; } int mqtt_pack_disconnect( const mqtt_attr_packet_t * p_attr_packet, mqtt_buf_packet_t ** pp_buf_packet ){ mqtt_attr_re_len_t remaining_length = 0; struct mqtt_buf * mqtt_buffer_array[20] = {NULL}; int i = 0; //< payload //< variable header //< fixed header //< remaining length MQTT_CTL_REMAINING_LEN_CHECK(remaining_length); struct mqtt_buf_re_len * p_buf_re_len = mqtt_ctl_encode_remaining_len( remaining_length); mqtt_buffer_array[i++] = p_buf_re_len; //< header union mqtt_attr_ctl_flag ctl_flag = { .bits = { .type = MQTT_CTL_TYPE_DISCONNECT, .DUP = 0, .QoS = 0, .RETAIN = 0 } }; struct mqtt_buf_ctl_flag * p_buf_ctl_flag = mqtt_ctl_flag_pack(ctl_flag); mqtt_buffer_array[i] = p_buf_ctl_flag; //< |payload|var header|remaining_length_code|fixed header byte| size_t total_len = remaining_length + //!< length of [payload + var header] p_buf_re_len->len + //!< length of [remaining_length] p_buf_ctl_flag->len; //!< length of [fixed header byte] //struct mqtt_buf_packet * p_buf_packet = mqtt_buf_new(total_len); *pp_buf_packet = mqtt_buf_new(total_len); //// copy buffers to mqtt packet then release buffers if(NULL != *pp_buf_packet){ size_t offset = 0; for(; i>=0; i--){ memcpy((*pp_buf_packet)->buf+offset, mqtt_buffer_array[i]->buf, mqtt_buffer_array[i]->len); offset += mqtt_buffer_array[i]->len; mqtt_buf_release(mqtt_buffer_array[i]); } return E_NONE; }else{ //printf("[err]:malloc fail!\n"); mqtt_log_printf(LOG_LEVEL_ERR, "alloc fail!\n"); return E_MEM_FAIL; } } int mqtt_unpack_disconnect( const mqtt_buf_packet_t * p_buf_packet, mqtt_attr_packet_t ** pp_attr_packet ){ //< create packet attributes *pp_attr_packet = mqtt_attr_packet_new(0); int offset = 0; //< fixed header //< header (*pp_attr_packet)->hdr.all = p_buf_packet->buf[offset++]; //< remaining length size_t len_bytes = 0; (*pp_attr_packet)->remaining_length = mqtt_ctl_decode_remaining_len( p_buf_packet->buf+offset, &len_bytes); offset += len_bytes; //< variable header //< payload // return E_NONE; }
2.484375
2
2024-11-18T21:05:55.857251+00:00
2019-03-05T01:32:40
d4d2eb72bdeff3e2950dd57362b04bdf03b7c3f2
{ "blob_id": "d4d2eb72bdeff3e2950dd57362b04bdf03b7c3f2", "branch_name": "refs/heads/master", "committer_date": "2019-03-05T01:51:51", "content_id": "caf821950c0e5a983b77f98e5510ce16daf06578", "detected_licenses": [ "MIT" ], "directory_id": "3e9e641243e61998a6a0c19a9f28bb98af9fc912", "extension": "c", "filename": "memtester.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 173852493, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12960, "license": "MIT", "license_type": "permissive", "path": "/app/src/main/cpp/memtester.c", "provenance": "stackv2-0083.json.gz:5964", "repo_name": "tong-tf/memtest", "revision_date": "2019-03-05T01:32:40", "revision_id": "6d13385d880941891e5bea07711f30b4becf7fa7", "snapshot_id": "92fe8fc292250aed22c09b1d5d4a05932ac24f19", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tong-tf/memtest/6d13385d880941891e5bea07711f30b4becf7fa7/app/src/main/cpp/memtester.c", "visit_date": "2020-04-26T21:48:55.580391" }
stackv2
/* * memtester version 4 * * Very simple but very effective user-space memory tester. * Originally by Simon Kirby <sim@stormix.com> <sim@neato.org> * Version 2 by Charles Cazabon <charlesc-memtester@pyropus.ca> * Version 3 not publicly released. * Version 4 rewrite: * Copyright (C) 2004-2012 Charles Cazabon <charlesc-memtester@pyropus.ca> * Licensed under the terms of the GNU General Public License version 2 (only). * See the file COPYING for details. * */ #include <android/log.h> #define LOG_TAG "tong" #define LOGI(fmt,args...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG, fmt, ##args) #define LOGD(fmt,args...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG, fmt, ##args) #define LOGW(fmt,args...) __android_log_print(ANDROID_LOG_WARNING,LOG_TAG, fmt, ##args) #define LOGE(fmt,args...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG, fmt, ##args) #define __version__ "4.3.0" #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include "types.h" #include "sizes.h" #include "tests.h" #define EXIT_FAIL_NONSTARTER 0x01 #define EXIT_FAIL_ADDRESSLINES 0x02 #define EXIT_FAIL_OTHERTEST 0x04 struct test tests[] = { { "Random Value", test_random_value, 1<<2 }, { "Compare XOR", test_xor_comparison, 1<<3 }, { "Compare SUB", test_sub_comparison, 1<<4}, { "Compare MUL", test_mul_comparison , 1<<5}, { "Compare DIV",test_div_comparison , 1<<6}, { "Compare OR", test_or_comparison , 1<<7}, { "Compare AND", test_and_comparison , 1<<8 }, { "Sequential Increment", test_seqinc_comparison , 1<<9 }, { "Solid Bits", test_solidbits_comparison , 1<<10 }, { "Block Sequential", test_blockseq_comparison , 1<<11 }, { "Checkerboard", test_checkerboard_comparison , 1<<12}, { "Bit Spread", test_bitspread_comparison , 1<<13}, { "Bit Flip", test_bitflip_comparison , 1<<14}, { "Walking Ones", test_walkbits1_comparison , 1<<15}, { "Walking Zeroes", test_walkbits0_comparison , 1<<16}, #ifdef TEST_NARROW_WRITES { "8-bit Writes", test_8bit_wide_random , 1<<17}, { "16-bit Writes", test_16bit_wide_random , 1<<18}, #endif { NULL, NULL } }; /* Sanity checks and portability helper macros. */ #ifdef _SC_VERSION void check_posix_system(void) { if (sysconf(_SC_VERSION) < 198808L) { fprintf(stderr, "A POSIX system is required. Don't be surprised if " "this craps out.\n"); fprintf(stderr, "_SC_VERSION is %lu\n", sysconf(_SC_VERSION)); } } #else #define check_posix_system() #endif #ifdef _SC_PAGE_SIZE int memtester_pagesize(void) { int pagesize = sysconf(_SC_PAGE_SIZE); if (pagesize == -1) { perror("get page size failed"); exit(EXIT_FAIL_NONSTARTER); } printf("pagesize is %ld\n", (long) pagesize); return pagesize; } #else int memtester_pagesize(void) { printf("sysconf(_SC_PAGE_SIZE) not supported; using pagesize of 8192\n"); return 8192; } #endif /* Some systems don't define MAP_LOCKED. Define it to 0 here so it's just a no-op when ORed with other constants. */ #ifndef MAP_LOCKED #define MAP_LOCKED 0 #endif /* Function declarations */ void usage(char *me); /* Global vars - so tests have access to this information */ int use_phys = 0; off_t physaddrbase = 0; /* Function definitions */ void usage(char *me) { LOGI("\n" "Usage: %s [-p physaddrbase [-d device]] <mem>[B|K|M|G] [loops]\n", me); exit(EXIT_FAIL_NONSTARTER); } int do_test(int argc, char **argv, stage_callback callback) { ul loops, loop, i; size_t pagesize, wantraw, wantmb, wantbytes, wantbytes_orig, bufsize, halflen, count; char *memsuffix, *addrsuffix, *loopsuffix; ptrdiff_t pagesizemask; void volatile *buf, *aligned; char buff[128]; ulv *bufa, *bufb; int do_mlock = 1, done_mem = 0; int exit_code = 0; int rv_item = 0; int memfd, opt, memshift; size_t maxbytes = -1; /* addressable memory, in bytes */ size_t maxmb = (maxbytes >> 20) + 1; /* addressable memory, in MB */ /* Device to mmap memory from with -p, default is normal core */ char *device_name = "/dev/mem"; struct stat statbuf; int device_specified = 0; char *env_testmask = 0; ul testmask = 0; int index = 1; for(i=0; i<argc; i++){ LOGI("Args: %d = %s", i, argv[i]); } LOGI("memtester version " __version__ " (%d-bit)\n", UL_LEN); LOGI("Copyright (C) 2001-2012 Charles Cazabon.\n"); LOGI("Licensed under the GNU General Public License version 2 (only).\n"); check_posix_system(); pagesize = memtester_pagesize(); pagesizemask = (ptrdiff_t) ~(pagesize - 1); LOGI("pagesizemask is 0x%tx\n", pagesizemask); /* If MEMTESTER_TEST_MASK is set, we use its value as a mask of which tests we run. */ if (env_testmask = getenv("MEMTESTER_TEST_MASK")) { errno = 0; testmask = strtoul(env_testmask, 0, 0); if (errno) { LOGE("error parsing MEMTESTER_TEST_MASK %s: %s\n", env_testmask, strerror(errno)); usage(argv[0]); /* doesn't return */ } LOGI("using testmask 0x%lx\n", testmask); } if (device_specified && !use_phys) { LOGE("for mem device, physaddrbase (-p) must be specified\n"); usage(argv[0]); /* doesn't return */ } errno = 0; wantraw = (size_t) strtoul(argv[index++], &memsuffix, 0); if (errno != 0) { LOGI(stderr, "failed to parse memory argument"); usage(argv[0]); /* doesn't return */ } switch (*memsuffix) { case 'G': case 'g': memshift = 30; /* gigabytes */ break; case 'M': case 'm': memshift = 20; /* megabytes */ break; case 'K': case 'k': memshift = 10; /* kilobytes */ break; case 'B': case 'b': memshift = 0; /* bytes*/ break; case '\0': /* no suffix */ memshift = 20; /* megabytes */ break; default: /* bad suffix */ usage(argv[0]); /* doesn't return */ } wantbytes_orig = wantbytes = ((size_t) wantraw << memshift); wantmb = (wantbytes_orig >> 20); LOGI("wanted raw = %d, wantmb=%d", wantraw, wantmb); optind++; if (wantmb > maxmb) { LOGE("This system can only address %llu MB.\n", (ull) maxmb); exit(EXIT_FAIL_NONSTARTER); } if (wantbytes < pagesize) { LOGE("bytes %ld < pagesize %ld -- memory argument too large?\n", wantbytes, pagesize); exit(EXIT_FAIL_NONSTARTER); } errno = 0; loops = strtoul(argv[index++], &loopsuffix, 0); if (errno != 0) { LOGE("failed to parse number of loops"); usage(argv[0]); /* doesn't return */ } LOGI("loops = %d", loops); if (*loopsuffix != '\0') { LOGE("loop suffix %c\n", *loopsuffix); usage(argv[0]); /* doesn't return */ } LOGI("want %lluMB (%llu bytes)\n", (ull) wantmb, (ull) wantbytes); sprintf(buff, "want %lluMB (%llu bytes)\n", (ull) wantmb, (ull) wantbytes); callback(buff); buf = NULL; if (use_phys) { memfd = open(device_name, O_RDWR | O_SYNC); if (memfd == -1) { LOGE("failed to open %s for physical memory: %s\n", device_name, strerror(errno)); exit(EXIT_FAIL_NONSTARTER); } buf = (void volatile *) mmap(0, wantbytes, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, memfd, physaddrbase); if (buf == MAP_FAILED) { LOGE("failed to mmap %s for physical memory: %s\n", device_name, strerror(errno)); exit(EXIT_FAIL_NONSTARTER); } if (mlock((void *) buf, wantbytes) < 0) { LOGE("failed to mlock mmap'ed space\n"); do_mlock = 0; } bufsize = wantbytes; /* accept no less */ aligned = buf; done_mem = 1; } while (!done_mem) { while (!buf && wantbytes) { buf = (void volatile *) malloc(wantbytes); if (!buf) wantbytes -= pagesize; } bufsize = wantbytes; sprintf(buff, "got %lluMB (%llu bytes)", (ull) wantbytes >> 20, (ull) wantbytes); callback(buff); LOGI("got %lluMB (%llu bytes)", (ull) wantbytes >> 20, (ull) wantbytes); fflush(stdout); if (do_mlock) { LOGI(", trying mlock ..."); fflush(stdout); if ((size_t) buf % pagesize) { /* printf("aligning to page -- was 0x%tx\n", buf); */ aligned = (void volatile *) ((size_t) buf & pagesizemask) + pagesize; /* printf(" now 0x%tx -- lost %d bytes\n", aligned, * (size_t) aligned - (size_t) buf); */ bufsize -= ((size_t) aligned - (size_t) buf); } else { aligned = buf; } /* Try mlock */ if (mlock((void *) aligned, bufsize) < 0) { switch(errno) { case EAGAIN: /* BSDs */ LOGI("over system/pre-process limit, reducing...\n"); free((void *) buf); buf = NULL; wantbytes -= pagesize; break; case ENOMEM: LOGI("too many pages, reducing...\n"); free((void *) buf); buf = NULL; wantbytes -= pagesize; break; case EPERM: LOGI("insufficient permission.\n"); LOGI("Trying again, unlocked:\n"); do_mlock = 0; free((void *) buf); buf = NULL; wantbytes = wantbytes_orig; break; default: LOGI("failed for unknown reason.\n"); do_mlock = 0; done_mem = 1; } } else { LOGI("locked OK.\n"); done_mem = 1; } } else { done_mem = 1; printf("\n"); } } if (!do_mlock) LOGI(stderr, "Continuing with unlocked memory; testing " "will be slower and less reliable.\n"); halflen = bufsize / 2; count = halflen / sizeof(ul); bufa = (ulv *) aligned; bufb = (ulv *) ((size_t) aligned + halflen); for(loop=1; ((!loops) || loop <= loops); loop++) { LOGI("Loop %lu", loop); sprintf(buff, "Loop %d times\n", loop); callback(buff); if (loops) { printf("/%lu", loops); } fflush(stdout); rv_item = test_stuck_address(aligned, bufsize / sizeof(ul)); if(rv_item != 0){ exit_code |= EXIT_FAIL_ADDRESSLINES; } LOGI(" %-20s: %s", "Stuck Address", rv_item == 0 ? "OK": "FAIL"); for (i=0;tests[i].name;i++) { /* If using a custom testmask, only run this test if the bit corresponding to this test was set by the user. */ if (testmask && (!((1 << i) & testmask))) { continue; } rv_item = tests[i].fp(bufa, bufb, count); if(rv_item){ exit_code |= tests[i].code; } LOGI(" %-20s: %s", tests[i].name, rv_item == 0 ? "OK": "FAIL"); sprintf(buff, " %-20s: %s", tests[i].name, rv_item == 0 ? "OK": "FAIL"); callback(buff); fflush(stdout); } LOGI("\n"); fflush(stdout); } if (do_mlock) munlock((void *) aligned, bufsize); LOGI("Done, exit_code=%d .\n", exit_code); fflush(stdout); return (exit_code); } int memtest(){ int ac = 3; char *av[] = {"./a.out", "10M", "5"}; return do_test(ac, av, NULL); } int memtest2(const char * size, const char * count, stage_callback callback){ char repeat[16]; char *av[3] = {"./aout", size, count}; return do_test(3, av, callback);; } const char * memtest3(const char *size, const char *count, stage_callback callback){ static char buf[512]; // we should ensure, buff is long enough int rv = memtest2(size, count, callback); int i, n=0; n = sprintf(buf+n, "Stuck Address: ", rv & 0x2 ? "FAIL": "OK") ; for(i=0; tests[i].name; i++){ n = sprintf(buf+n, "%s: %s\n", rv & (1<<(i+2)) ? "FAIL": "OK") ; } buf[n] = 0; return buf; }
2.15625
2
2024-11-18T21:05:55.942284+00:00
2017-12-11T07:02:56
0f6c1e09ebcbe239b7fdc250f4cf92f4b08a036a
{ "blob_id": "0f6c1e09ebcbe239b7fdc250f4cf92f4b08a036a", "branch_name": "refs/heads/main", "committer_date": "2017-12-11T07:02:56", "content_id": "8d08ad15ad92a28d0f4d487c30220069ada54b2e", "detected_licenses": [ "MIT" ], "directory_id": "c3becd2e1582131aaa7d9bd2ca5ba05203500148", "extension": "c", "filename": "nbody.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 113798876, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3719, "license": "MIT", "license_type": "permissive", "path": "/nbody.c", "provenance": "stackv2-0083.json.gz:6092", "repo_name": "blacktm/nbody", "revision_date": "2017-12-11T07:02:56", "revision_id": "ca773e7fde0f96735ad3241818000c354ea17b02", "snapshot_id": "4720eaca4cc2692f9c3e65441aa33c9859df78f3", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/blacktm/nbody/ca773e7fde0f96735ad3241818000c354ea17b02/nbody.c", "visit_date": "2021-07-31T21:57:17.329472" }
stackv2
#include <simple2d.h> #include <time.h> S2D_Window *window; int UNIVERSE_WIDTH = 800; int UNIVERSE_HEIGHT = 600; int GRAVITY_CONTANT = 1; #define BODY_COUNT 200 // max: 709 typedef struct { double mass; double size; double x; double y; double vx; double vy; double dx; double dy; } Body; Body bodies[BODY_COUNT]; struct timespec t, now; double distance(Body *b1, Body *b2) { return sqrt(pow(b1->x - b2->x, 2) + pow(b1->y - b2->y, 2)); } void interact(Body *b1, Body *b2) { double force_coefficient = b1->mass * b2->mass * GRAVITY_CONTANT / pow(distance(b1, b2), 2); double force_x = (b1->x - b2->x) * force_coefficient; double force_y = (b1->y - b2->y) * force_coefficient; b1->dx -= force_x; b1->dy -= force_y; b2->dx += force_x; b2->dy += force_y; } void update_body(Body *b, double t_delta) { b->vx += b->dx * t_delta; b->vy += b->dy * t_delta; b->x += b->vx * t_delta; b->y += b->vy * t_delta; b->dx = 0; b->dy = 0; } void update() { // Make each body interact with every other int b1 = 0, b2 = 1; while (b1 < BODY_COUNT - 1) { for (; b2 < BODY_COUNT; b2++) { interact(&bodies[b1], &bodies[b2]); } b1++; b2 = b1 + 1; } // Get the elapsed time clock_gettime(CLOCK_REALTIME, &now); double t_delta = (now.tv_sec - t.tv_sec) + (now.tv_nsec - t.tv_nsec) / 1.0e9; // Update each body for (int i = 0; i < BODY_COUNT; i++) { update_body(&bodies[i], t_delta); } // Set the start_time to be current time clock_gettime(CLOCK_REALTIME, &t); } void render() { for (int i = 0; i < BODY_COUNT; i++) { // // Plain white // S2D_DrawQuad( // bodies[i].x, bodies[i].y, 1, 1, 1, 1, // bodies[i].x + bodies[i].size, bodies[i].y, 1, 1, 1, 1, // bodies[i].x + bodies[i].size, bodies[i].y + bodies[i].size, 1, 1, 1, 1, // bodies[i].x, bodies[i].y + bodies[i].size, 1, 1, 1, 1 // ); // // Uni-directional X celocity color // S2D_DrawQuad( // bodies[i].x, bodies[i].y, bodies[i].vx / 175, bodies[i].vx / 110, 1, bodies[i].vx / 145, // bodies[i].x + bodies[i].size, bodies[i].y, bodies[i].vx / 175, bodies[i].vx / 110, 1, bodies[i].vx / 145, // bodies[i].x + bodies[i].size, bodies[i].y + bodies[i].size, bodies[i].vx / 175, bodies[i].vx / 110, 1, bodies[i].vx / 145, // bodies[i].x, bodies[i].y + bodies[i].size, bodies[i].vx / 175, bodies[i].vx / 110, 1, bodies[i].vx / 145 // ); // X Velocity color S2D_DrawQuad( bodies[i].x, bodies[i].y, bodies[i].vx / 175, bodies[i].vx / -110, 1, 1, bodies[i].x + bodies[i].size +2, bodies[i].y, bodies[i].vx / 175, bodies[i].vx / -110, 1, 1, bodies[i].x + bodies[i].size +2, bodies[i].y + bodies[i].size +2, bodies[i].vx / 175, bodies[i].vx / -110, 1, 1, bodies[i].x, bodies[i].y + bodies[i].size +2, bodies[i].vx / 175, bodies[i].vx / -110, 1, 1 ); } } int main() { for (int i = 0; i < BODY_COUNT; i++) { bodies[i].mass = log(1 - (double)rand() / (double)RAND_MAX) / -0.1; bodies[i].size = sqrt(bodies[i].mass); bodies[i].x = rand() % UNIVERSE_WIDTH; bodies[i].y = rand() % UNIVERSE_HEIGHT; bodies[i].vx = 0; bodies[i].vy = 0; bodies[i].dx = 0; bodies[i].dy = 0; } window = S2D_CreateWindow( "nbody", UNIVERSE_WIDTH, UNIVERSE_HEIGHT, update, render, S2D_RESIZABLE ); // Set t to current time clock_gettime(CLOCK_REALTIME, &t); S2D_Show(window); S2D_FreeWindow(window); return 0; }
2.5
2
2024-11-18T21:05:56.187694+00:00
2018-03-31T08:35:21
eece65a0e5eeab45fd15e305367f6f0f6e2b56b8
{ "blob_id": "eece65a0e5eeab45fd15e305367f6f0f6e2b56b8", "branch_name": "refs/heads/master", "committer_date": "2018-03-31T08:35:21", "content_id": "6dbec3ad98318f45350e700e012c68353fe521aa", "detected_licenses": [ "MIT" ], "directory_id": "04da8da6b93505d0d5e3c3bf591d36070f378400", "extension": "h", "filename": "List.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127514076, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1711, "license": "MIT", "license_type": "permissive", "path": "/Utils/List.h", "provenance": "stackv2-0083.json.gz:6478", "repo_name": "LunguIonut007/Laborator-2-4-OOP", "revision_date": "2018-03-31T08:35:21", "revision_id": "34dde0cbb8ce55716afa6539d3f0b11a7019d858", "snapshot_id": "c0afaa544a98d80aa236d19efda6f124ad6a9035", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LunguIonut007/Laborator-2-4-OOP/34dde0cbb8ce55716afa6539d3f0b11a7019d858/Utils/List.h", "visit_date": "2020-03-07T13:55:48.265646" }
stackv2
#pragma once typedef void(*DestructFunc)(void*); typedef void*(*DeepCopyElementFunc)(void*); typedef void* ElementType; typedef struct { int size; int capacity; ElementType* elements; DestructFunc destructFunc; int elementSize; } List; /** * Functia returneaza un pointer la un List pe heap, struct alocat dinamic * @return List alocat dinamic @param destryFunc o functie ce se va apela cu un obiect din lista si are menirea de a elibera memoria ocupata de entitate @param elementSize - dimensiunea elementelor ce se vor salva in lista * Postconditii: memoria va fi eliberata apeland destroyList */ List* createList(DestructFunc destroyFunc, int elementSize); /** Functia creaza o noua lista in care vor fi copiate deep elementele din lista intiala @param list - lista din care se face copierea @deepCopyFunc - functie ce copiaza in adancime entitatile din lista */ List* deepCopyList(List* list, DeepCopyElementFunc deepCopyFunc); /** * Functia elibereaza memoria alocata unui List * @param List - lista asupra caruia se elibereaza memoria * * Preconditie: List e o lista creata cu createList */ void destroyList(List* List); /** * Returneaza marimiea unei liste date * @param list * @return un int */ int getListSize(List* list); /** * Functia permite iterarea unei liste printr-un index * @param list * @return un obiect Medicine aflat la un anumit index in lista * Preconditie: index este mai mic strict decat marimea listei */ void* getAtListIndex(List* list, int index); /** * Functia adauga in lita list pointer-ul la structul medicine * @param list * @param entity - obiectul ce se adauga in lista */ void addToList(List* list, ElementType entity);
2.59375
3
2024-11-18T21:05:56.791994+00:00
2021-10-26T16:58:35
49560659c29f0604a5a5e633979e7b40c5173198
{ "blob_id": "49560659c29f0604a5a5e633979e7b40c5173198", "branch_name": "refs/heads/master", "committer_date": "2021-10-26T16:58:35", "content_id": "70012f3aea2e9754adf514811e18b2735e31afba", "detected_licenses": [ "BSD-2-Clause", "Apache-2.0" ], "directory_id": "b7b93d229126414f54aa1c0d449626088d1ffe9c", "extension": "c", "filename": "hello-nts.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 421347962, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2960, "license": "BSD-2-Clause,Apache-2.0", "license_type": "permissive", "path": "/libnts/examples/hello-nts.c", "provenance": "stackv2-0083.json.gz:6992", "repo_name": "NTSocks/ntsocks", "revision_date": "2021-10-26T16:58:35", "revision_id": "8029405ea9a15c0876aed30c50840ae9034e1fe7", "snapshot_id": "941109f7998a25ab48e0e76640a0f67a888b27f7", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/NTSocks/ntsocks/8029405ea9a15c0876aed30c50840ae9034e1fe7/libnts/examples/hello-nts.c", "visit_date": "2023-09-01T07:26:27.767102" }
stackv2
// #include "nts_api.h" #include <sys/socket.h> #include <sys/types.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <netdb.h> #include <unistd.h> // #include "socket.h" #define SERVER_IP "10.10.88.210" #define PORT 80 #define test_msg "Hello, NTSocket Server World!" #define large_msg "Hello,Large Msg!" int main(int argc, char *argv[]) { if (argc < 3) { printf("Usage: %s <Server IP> <Port> \n", argv[0]); return 0; } int port = atoi(argv[2]); char *server_ip = argv[1]; printf("Hello libnts app!\n"); int sockfd; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd > 0) { printf("sockfd=%d \n", sockfd); printf("socket() success\n"); } else { printf("socket() failed.\n"); return -1; } int retval; socklen_t saddrlen; struct sockaddr_in saddr; saddr.sin_family = AF_INET; saddr.sin_port = htons(port); saddr.sin_addr.s_addr = inet_addr(server_ip); saddrlen = sizeof(saddr); retval = bind(sockfd, (struct sockaddr *)&saddr, saddrlen); if (retval == -1) { printf("bind() failed.\n"); return -1; } else { printf("bind() success\n"); } retval = listen(sockfd, 8); if (retval == -1) { printf("listen() failed\n"); return -1; } else { printf("listen() success\n"); } int client_sockfd; socklen_t client_saddrlen; struct sockaddr_in client_saddr; // while (1) // { client_sockfd = accept(sockfd, (struct sockaddr *)&client_saddr, &client_saddrlen); if (client_sockfd == -1) { printf("accept() failed\n"); return -1; } else { printf("accept() success with client nt_socket sockfd=%d\n", client_sockfd); } // } // test for write payload that bytes length > 256 char data[512]; memset(data, 0, sizeof(data)); int unit_offset = strlen(large_msg); size_t data_len = strlen(large_msg) * 17; for (size_t i = 0; i < 17; i++) { memcpy(data + i * unit_offset, large_msg, unit_offset); } size_t sent_bytes_len; sent_bytes_len = write(client_sockfd, data, data_len); if (sent_bytes_len > 0) { printf("write large message [%d bytes] success \n", (int)sent_bytes_len); for (size_t i = 0; i < sent_bytes_len; i++) { printf("%c", data[i]); } printf("\n"); } // test for write first in server // size_t write_msg_len; // write_msg_len = write(client_sockfd, test_msg, strlen(test_msg)); // if (write_msg_len > 0) { // printf("write() success with send msg = '%s'\n", test_msg); // } char recv_msg[32] = {0}; size_t read_msg_len; // read_msg_len = read(client_sockfd, recv_msg, sizeof(recv_msg)); // if (read_msg_len > 0) { // printf("read() success with recv msg = '%s' \n", recv_msg); // } read(client_sockfd, recv_msg, sizeof(recv_msg)); close(client_sockfd); close(sockfd); getchar(); // close(sockfd); // nts_init(NTS_CONFIG_FILE); // getchar(); // nts_destroy(); printf("Bye, libnts app.\n"); return 0; }
2.59375
3
2024-11-18T21:05:57.166737+00:00
2020-01-18T18:22:30
391267a9b1e369b68c14819d107116cf6ca773e0
{ "blob_id": "391267a9b1e369b68c14819d107116cf6ca773e0", "branch_name": "refs/heads/master", "committer_date": "2020-01-18T18:22:30", "content_id": "b078eba5271cd4053a7e5feeb09b99fd572212be", "detected_licenses": [ "MIT" ], "directory_id": "ccd8854699e2f9f0a0da351a1015ee4967d50d31", "extension": "c", "filename": "PromptManager.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 216789169, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 527, "license": "MIT", "license_type": "permissive", "path": "/src/PromptManager.c", "provenance": "stackv2-0083.json.gz:7378", "repo_name": "eminfedar/termmminal", "revision_date": "2020-01-18T18:22:30", "revision_id": "b0d6cba90e0c4368b56a35a889ff402c04c42488", "snapshot_id": "aa28772066daf36401d876002954baeb75732016", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/eminfedar/termmminal/b0d6cba90e0c4368b56a35a889ff402c04c42488/src/PromptManager.c", "visit_date": "2020-08-24T07:58:32.231011" }
stackv2
#include "../include/PromptManager.h" #include "../include/CommandManager.h" #include <stdio.h> #include <stdlib.h> void startPrompting() { while (1) { char *input = NULL; size_t n; printf("> "); size_t inputLength = getline(&input, &n, stdin); // Remove the newline '\n' input[inputLength-1] = '\0'; // Process the input parseInput(input); free(input); fflush(stdout); fflush(stderr); fflush(stdin); } }
2.546875
3
2024-11-18T21:05:57.255448+00:00
2015-03-26T05:34:40
d605839558b126aa6744f7f35711e80838917cdf
{ "blob_id": "d605839558b126aa6744f7f35711e80838917cdf", "branch_name": "refs/heads/master", "committer_date": "2015-03-26T05:34:40", "content_id": "df240a2cfaf99f4f41b7f2b9c67ca88e66b790c3", "detected_licenses": [ "MIT" ], "directory_id": "70d3fdca2b976e9295225e99d4709b244589fba7", "extension": "c", "filename": "xxxx.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32906559, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3434, "license": "MIT", "license_type": "permissive", "path": "/extra_hardware_code_collection/working_prototype/xxxx.c", "provenance": "stackv2-0083.json.gz:7506", "repo_name": "shaunakv1/micromouse_project_flood_fill", "revision_date": "2015-03-26T05:34:40", "revision_id": "6e447d64ba0cdc1b4bdc450a2a22d40882e98a43", "snapshot_id": "7de37b5cedf881154a942f8d42bda2d436bc6785", "src_encoding": "WINDOWS-1252", "star_events_count": 1, "url": "https://raw.githubusercontent.com/shaunakv1/micromouse_project_flood_fill/6e447d64ba0cdc1b4bdc450a2a22d40882e98a43/extra_hardware_code_collection/working_prototype/xxxx.c", "visit_date": "2021-01-20T12:03:49.243996" }
stackv2
/***************************************************** This program was produced by the CodeWizardAVR V2.03.8a Evaluation Automatic Program Generator © Copyright 1998-2008 Pavel Haiduc, HP InfoTech s.r.l. http://www.hpinfotech.com Project : Version : Date : 1/18/2009 Author : Freeware, for evaluation and non-commercial use only Company : Comments: Chip type : ATmega32 Program type : Application Clock frequency : 16.000000 MHz Memory model : Small External RAM size : 0 Data Stack size : 512 *****************************************************/ #include <mega32.h> unsigned char step[4]={0xCC,0x66,0x33,0x99}; unsigned char l_overflow,r_overflow,l_step,r_step,x,y,z; // Timer 0 output compare interrupt service routine interrupt [TIM0_COMP] void timer0_comp_isr(void) { // Place your code here { r_overflow=0; PORTB=step[r_step]; PORTC.0=~PINC.0; r_step++; if(r_step>3)r_step=0; } } // Timer 2 output compare interrupt service routine interrupt [TIM2_COMP] void timer2_comp_isr(void) { // Place your code here } // Declare your global variables here void main(void) { // Declare your local variables here // Input/Output Ports initialization // Port A initialization // Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In // State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T PORTA=0x00; DDRA=0x00; // Port B initialization // Func7=In Func6=In Func5=In Func4=In Func3=Out Func2=Out Func1=Out Func0=Out // State7=T State6=T State5=T State4=T State3=0 State2=0 State1=0 State0=0 PORTB=0x00; DDRB=0x0F; // Port C initialization // Func7=In Func6=In Func5=In Func4=In Func3=In Func2=Out Func1=Out Func0=Out // State7=T State6=T State5=T State4=T State3=T State2=1 State1=1 State0=1 PORTC=0x07; DDRC=0x07; // Port D initialization // Func7=Out Func6=Out Func5=Out Func4=Out Func3=In Func2=In Func1=In Func0=In // State7=0 State6=0 State5=0 State4=0 State3=T State2=T State1=T State0=T PORTD=0x00; DDRD=0xF0; // Timer/Counter 0 initialization // Clock source: System Clock // Clock value: 15.625 kHz // Mode: CTC top=OCR0 // OC0 output: Disconnected TCCR0=0x0D; TCNT0=0x00; OCR0=0x64; // Timer/Counter 1 initialization // Clock source: System Clock // Clock value: Timer 1 Stopped // Mode: Normal top=FFFFh // OC1A output: Discon. // OC1B output: Discon. // Noise Canceler: Off // Input Capture on Falling Edge // Timer 1 Overflow Interrupt: Off // Input Capture Interrupt: Off // Compare A Match Interrupt: Off // Compare B Match Interrupt: Off TCCR1A=0x00; TCCR1B=0x00; TCNT1H=0x00; TCNT1L=0x00; ICR1H=0x00; ICR1L=0x00; OCR1AH=0x00; OCR1AL=0x00; OCR1BH=0x00; OCR1BL=0x00; // Timer/Counter 2 initialization // Clock source: System Clock // Clock value: 15.625 kHz // Mode: CTC top=OCR2 // OC2 output: Disconnected ASSR=0x00; TCCR2=0x0F; TCNT2=0x00; OCR2=0x64; // External Interrupt(s) initialization // INT0: Off // INT1: Off // INT2: Off MCUCR=0x00; MCUCSR=0x00; // Timer(s)/Counter(s) Interrupt(s) initialization TIMSK=0x82; // Analog Comparator initialization // Analog Comparator: Off // Analog Comparator Input Capture by Timer/Counter 1: Off ACSR=0x80; SFIOR=0x00; // Global enable interrupts #asm("sei") while (1) { // Place your code here }; }
2.140625
2
2024-11-18T21:05:57.316860+00:00
2023-02-28T14:12:08
f26f720efce7c4294d656af89119db90b98872c2
{ "blob_id": "f26f720efce7c4294d656af89119db90b98872c2", "branch_name": "refs/heads/v3", "committer_date": "2023-02-28T15:16:34", "content_id": "b1700c1a62c0ea55dd9289808233e7d05bcb10b9", "detected_licenses": [ "MIT", "Apache-2.0" ], "directory_id": "e5f85801ed984977df25aecb3a7d65d3d37c98f7", "extension": "c", "filename": "geomean.c", "fork_events_count": 9, "gha_created_at": "2017-06-14T14:01:29", "gha_event_created_at": "2022-03-11T10:51:00", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 94337117, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 429, "license": "MIT,Apache-2.0", "license_type": "permissive", "path": "/templates/cpp/solvable/solvable/app/geomean.c", "provenance": "stackv2-0083.json.gz:7635", "repo_name": "avatao-content/challenge-toolbox", "revision_date": "2023-02-28T14:12:08", "revision_id": "12bb02c36a9ca13ad188031dbf54b3eadf58cd95", "snapshot_id": "048c861a3a3cede7f820123f8835f47af0ad9e5f", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/avatao-content/challenge-toolbox/12bb02c36a9ca13ad188031dbf54b3eadf58cd95/templates/cpp/solvable/solvable/app/geomean.c", "visit_date": "2023-03-04T12:32:11.420038" }
stackv2
#include <stdio.h> #include <stdarg.h> #include <math.h> double geometric_mean(size_t count, ...) { va_list nums; double product = 1.0; va_start(nums, count); for(size_t i = 0; i < count; i++) { product *= va_arg(nums, double); } va_end(nums); return pow(product, 1.0/count); } int main(int argc, char const *argv[]) { printf("%f\n", geometric_mean(3, 1.0, 2.0, 3.0)); return 0; }
3
3
2024-11-18T21:05:57.501719+00:00
2023-06-17T17:46:23
d66b585bf8d0fa0c2dd030df4bd0d6a04020fc7a
{ "blob_id": "d66b585bf8d0fa0c2dd030df4bd0d6a04020fc7a", "branch_name": "refs/heads/master", "committer_date": "2023-07-11T12:25:31", "content_id": "84c0e3a78122904fd23961ddb1bc16b08e96b8bd", "detected_licenses": [ "Unlicense" ], "directory_id": "01ace0f357a25a895df67b2fe60020a9e9713766", "extension": "c", "filename": "test_preuser.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 147276452, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14288, "license": "Unlicense", "license_type": "permissive", "path": "/libcitm/test_preuser.c", "provenance": "stackv2-0083.json.gz:7893", "repo_name": "Splintermail/splintermail-client", "revision_date": "2023-06-17T17:46:23", "revision_id": "029757f727e338d7c9fa251ea71a894097426146", "snapshot_id": "10e7f370b6859e1ae5d75bdaa89f4f1d24e9bb81", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Splintermail/splintermail-client/029757f727e338d7c9fa251ea71a894097426146/libcitm/test_preuser.c", "visit_date": "2023-07-21T15:36:03.409326" }
stackv2
#include "libduv/fake_stream.h" #include "libcitm/libcitm.h" #include "libcitm/fake_citm.h" #include "test/test_utils.h" typedef struct { size_t *count; derr_t *e; dstr_t *user; link_t *servers; link_t *clients; keydir_i **kd; imap_client_t **xc; } ptrs_t; static void cb( void *data, derr_t e, dstr_t user, link_t *servers, link_t *clients, keydir_i *kd, imap_client_t *xc ){ ptrs_t *ptrs = data; (*ptrs->count)++; *ptrs->e = e; *ptrs->user = user; link_list_append_list(ptrs->servers, servers); link_list_append_list(ptrs->clients, clients); *ptrs->kd = kd; *ptrs->xc = xc; } static void sawait_cb( imap_server_t *s, derr_t e, link_t *reads, link_t *writes ){ (void)s; (void)reads; (void)writes; DROP_VAR(&e); } static void cawait_cb( imap_client_t *c, derr_t e, link_t *reads, link_t *writes ){ (void)c; (void)reads; (void)writes; DROP_VAR(&e); } static bool reserve_steps(size_t cancel_after, size_t *steps, size_t n){ if(cancel_after >= *steps + n){ *steps += n; return false; } return true; } // make sure every branch finished static bool branches[8] = {0}; static derr_t do_test_preuser(size_t cancel_after, bool *finished){ derr_t e = E_OK; /* pipeline diagram: ________________ | preuser_t | | | s <-> fs <---> imap_server_t | |________________| Note that we always use IMAP_SEC_INSECURE, so we never need a duv_tls_t to talk to the imap_server_t or imap_client_t, so we can operate on the fake_stream_t's directly. */ size_t steps = 0; manual_scheduler_t m; fake_stream_t c; fake_citm_conn_t fc; citm_conn_t *conn = NULL; fake_citm_connect_t fcnct = {0}; hash_elem_t *elem; hashmap_trav_t trav; dstr_t user = {0}; dstr_t pass = {0}; fake_keydir_t fkd = {0}; keydir_i *kd = NULL; // all the servers and clients that only exist to get freed during failures fake_stream_t s1s, s2s, c1s, c2s; fake_citm_conn_t s1f, s2f, c1f, c2f; citm_conn_t *s1c = NULL, *s2c = NULL, *c1c = NULL, *c2c = NULL; imap_server_t *s1 = NULL, *s2 = NULL; imap_client_t *c1 = NULL, *c2 = NULL; s1c = fake_citm_conn_insec(&s1f, fake_stream(&s1s)); s2c = fake_citm_conn_insec(&s2f, fake_stream(&s2s)); c1c = fake_citm_conn_insec(&c1f, fake_stream(&c1s)); c2c = fake_citm_conn_insec(&c2f, fake_stream(&c2s)); size_t cb_count = 0; derr_t e_result = E_OK; dstr_t u_result = {0}; link_t s_result = {0}; link_t c_result = {0}; keydir_i *kd_result = NULL; imap_client_t *xc_result = NULL; ptrs_t ptrs = { &cb_count, &e_result, &u_result, &s_result, &c_result, &kd_result, &xc_result, }; derr_type_t cancel_error = E_CANCELED; hashmap_t preusers = {0}; scheduler_i *sched = manual_scheduler(&m); conn = fake_citm_conn_insec(&fc, fake_stream(&c)); PROP_GO(&e, dstr_append(&user, &DSTR_LIT("user")), fail); PROP_GO(&e, dstr_append(&pass, &DSTR_LIT("pass")), fail); PROP_GO(&e, hashmap_init(&preusers), fail); PROP_GO(&e, fake_keydir(&fkd, mykey_priv, &kd), fail); PROP_GO(&e, fake_keydir_add_peer(&fkd, peer1_pem), fail); PROP_GO(&e, fake_keydir_add_peer(&fkd, peer2_pem), fail); PROP_GO(&e, imap_server_new(&s1, sched, s1c), fail); PROP_GO(&e, imap_server_new(&s2, sched, s2c), fail); PROP_GO(&e, imap_client_new(&c1, sched, c1c), fail); PROP_GO(&e, imap_client_new(&c2, sched, c2c), fail); imap_server_must_await(s1, sawait_cb, NULL); imap_server_must_await(s2, sawait_cb, NULL); imap_client_must_await(c1, cawait_cb, NULL); imap_client_must_await(c2, cawait_cb, NULL); fake_citm_io_t fio; citm_io_i *io = fake_citm_io(&fio); fake_citm_connect_prep(&fcnct); link_list_append(&fio.fcncts, &fcnct.link); preuser_new( sched, io, STEAL(dstr_t, &user), STEAL(dstr_t, &pass), STEAL(keydir_i, &kd), STEAL(imap_server_t, &s1), STEAL(imap_client_t, &c1), cb, &ptrs, &preusers ); EXPECT_U_GO(&e, "len(preusers)", preusers.num_elems, 1, fail); EXPECT_LIST_LENGTH_GO(&e, "fcncts", &fio.fcncts, 0, fail); #define MAYBE_CANCEL if(cancel_after == steps++) goto cancel MAYBE_CANCEL; #define READ_EX(msg, _s) \ PROP_GO(&e, fake_stream_expect_read(&m, _s, DSTR_LIT(msg)), fail) \ // most reads are from the client #define READ(msg) READ_EX(msg, &c) #define WRITE(msg) \ PROP_GO(&e, fake_stream_write(&m, &c, DSTR_LIT(msg)), fail) \ if(cancel_after == steps++){ // make sure that cancel-then-connect-finishes works preuser_cancel(hashmap_pop_iter(&trav, &preusers)); PROP_GO(&e, fake_citm_connect_finish(&fcnct, conn, E_NONE), fail); ADVANCE_FAKES(&m, &c, &s1s, &s2s); EXPECT_E_VAR_GO(&e, "e_result", &e_result, E_CANCELED, fail); goto cu; }else if(cancel_after == steps++){ // make sure that connection errors result in broken conn message PROP_GO(&e, fake_citm_connect_finish(&fcnct, conn, E_CONN), fail); ADVANCE_FAKES(&m, &c, &s1s, &s2s); // the server should send a broken conn message PROP_GO(&e, establish_imap_server(&m, &s1s), cu); READ_EX("* BYE broken connection to upstream server\r\n", &s1s); ADVANCE_FAKES(&m, &c, &s1s, &s2s); fake_stream_shutdown(&s1s); ADVANCE_FAKES(&m, &c, &s1s, &s2s); EXPECT_U_GO(&e, "cb_count", cb_count, 1, fail); EXPECT_E_VAR_GO(&e, "e_result", &e_result, E_CONN, fail); goto cu; }else{ PROP_GO(&e, fake_citm_connect_finish(&fcnct, conn, E_NONE), fail); } MAYBE_CANCEL; PROP_GO(&e, establish_imap_client(&m, &c), fail); MAYBE_CANCEL; READ( "preuser1 LOGIN user pass\r\n" "preuser2 XKEYSYNC" " eefdab7d7d97bf74d16684f803f3e2a4ef7aa181c9940fbbaff4427f1f7dde32" " 3d94f057f427e2ee34bb51733b8d3ee62a8fdaaa50da71d14e4b2d7f44763471" " 8c7e72356d46734eeaf2d163302cc560f60b513d7644dae92b390b7d8f28ae95" "\r\n" "DONE\r\n" ); MAYBE_CANCEL; if(reserve_steps(cancel_after, &steps, 2)){ WRITE("preuser1 NO login failed\r\n"); if(cancel_after == steps++){ // login failure will dominate cancel_error = E_RESPONSE; goto cancel; } ADVANCE_FAKES(&m, &c, &s1s, &s2s); EXPECT_U_GO(&e, "cb_count", cb_count, 1, fail); EXPECT_E_VAR_GO(&e, "e_result", &e_result, E_RESPONSE, fail); branches[0] = true; goto cu; } WRITE("* OK informational\r\n"); MAYBE_CANCEL; WRITE("preuser1 OK login successful\r\n"); MAYBE_CANCEL; // add a pair to the preuser elem = hashmap_gets(&preusers, &DSTR_LIT("user")); preuser_add_pair( elem, STEAL(imap_server_t, &s2), STEAL(imap_client_t, &c2) ); DSTR_VAR(buf, 4096); if(reserve_steps(cancel_after, &steps, 8)){ // need mykey WRITE( "* XKEYSYNC DELETED" " eefdab7d7d97bf74d16684f803f3e2a4ef7aa181c9940fbbaff4427f1f7dde32" "\r\n" ); MAYBE_CANCEL; WRITE("* XKEYSYNC OK\r\n"); MAYBE_CANCEL; WRITE("+ OK\r\n"); MAYBE_CANCEL; WRITE("preuser2 OK xkeysync complete\r\n"); MAYBE_CANCEL; PROP_GO(&e, FMT(&buf, "preuser3 XKEYADD {%x+}\r\n%x\r\n", FU(mykey_pem.len), FD(mykey_pem) ), fail); PROP_GO(&e, fake_stream_expect_read(&m, &c, buf), fail); MAYBE_CANCEL; if(reserve_steps(cancel_after, &steps, 2)){ // mykey upload fails WRITE("preuser3 NO upload failed\r\n"); if(cancel_after == steps++){ // upload failure will dominate cancel_error = E_RESPONSE; goto cancel; } ADVANCE_FAKES(&m, &c, &s1s, &s2s); EXPECT_U_GO(&e, "cb_count", cb_count, 1, fail); EXPECT_E_VAR_GO(&e, "e_result", &e_result, E_RESPONSE, fail); branches[1] = true; goto cu; } WRITE("preuser3 OK upload successful\r\n"); EXPECT_U_GO(&e, "cb_count", cb_count, 1, fail); EXPECT_E_VAR_GO(&e, "e_result", &e_result, E_NONE, fail); EXPECT_LIST_LENGTH_GO(&e, "npeers", &fkd.peers, 2, fail); branches[2] = true; }else if(reserve_steps(cancel_after, &steps, 3)){ // have extra peer mykey WRITE( "* XKEYSYNC DELETED" " 8c7e72356d46734eeaf2d163302cc560f60b513d7644dae92b390b7d8f28ae95" "\r\n" ); MAYBE_CANCEL; WRITE("* XKEYSYNC OK\r\n"); MAYBE_CANCEL; WRITE("preuser2 OK xkeysync complete\r\n"); EXPECT_LIST_LENGTH_GO(&e, "npeers", &fkd.peers, 1, fail); branches[3] = true; goto fail; }else if(reserve_steps(cancel_after, &steps, 3)){ // missing a peer PROP_GO(&e, FMT(&buf, "* XKEYSYNC CREATED {%x}\r\n%x\r\n", FU(peer3_pem.len), FD(peer3_pem) ), fail); PROP_GO(&e, fake_stream_write(&m, &c, buf), fail); MAYBE_CANCEL; WRITE("* XKEYSYNC OK\r\n"); MAYBE_CANCEL; WRITE("preuser2 OK xkeysync complete\r\n"); EXPECT_LIST_LENGTH_GO(&e, "npeers", &fkd.peers, 3, fail); branches[4] = true; EXPECT_LIST_LENGTH_GO(&e, "npeers", &fkd.peers, 3, fail); goto fail; }else if(reserve_steps(cancel_after, &steps, 2)){ // xkeysync fails WRITE("preuser2 NO xkeysync failed\r\n"); if(cancel_after == steps++){ // xkeysync failure will dominate cancel_error = E_RESPONSE; goto cancel; } ADVANCE_FAKES(&m, &c, &s1s, &s2s); EXPECT_U_GO(&e, "cb_count", cb_count, 1, fail); EXPECT_E_VAR_GO(&e, "e_result", &e_result, E_RESPONSE, fail); branches[5] = true; goto cu; }else if(reserve_steps(cancel_after, &steps, 2)){ // completely unexpected response WRITE("* SEARCH 1\r\n"); if(cancel_after == steps++){ // unexpected response will dominate cancel_error = E_RESPONSE; goto cancel; } ADVANCE_FAKES(&m, &c, &s1s, &s2s); EXPECT_U_GO(&e, "cb_count", cb_count, 1, fail); EXPECT_E_VAR_GO(&e, "e_result", &e_result, E_RESPONSE, fail); branches[6] = true; goto cu; }else{ // we are already synced WRITE("preuser2 OK xkeysync done\r\n"); branches[7] = true; *finished = true; } // ensure we got our callback EXPECT_U_GO(&e, "cb_count", cb_count, 1, fail); EXPECT_E_VAR_GO(&e, "e_result", &e_result, E_NONE, fail); EXPECT_D_GO(&e, "u_result", u_result, DSTR_LIT("user"), fail); EXPECT_LIST_LENGTH_GO(&e, "s_result", &s_result, 2, fail); EXPECT_LIST_LENGTH_GO(&e, "c_result", &c_result, 2, fail); EXPECT_NOT_NULL_GO(&e, "kd_result", kd_result, fail); EXPECT_NOT_NULL_GO(&e, "xc_result", xc_result, fail); goto cu; cancel: preuser_cancel(hashmap_pop_iter(&trav, &preusers)); ADVANCE_FAKES(&m, &c, &s1s, &s2s); if(fcnct.canceled && !fcnct.done){ PROP_GO(&e, fake_citm_connect_finish(&fcnct, NULL, E_CANCELED), fail); } ADVANCE_FAKES(&m, &c, &s1s, &s2s); EXPECT_U_GO(&e, "cb_count", cb_count, 1, fail); EXPECT_E_VAR_GO(&e, "e_result", &e_result, cancel_error, fail); goto cu; fail: elem = hashmap_pop_iter(&trav, &preusers); if(elem){ preuser_cancel(elem); ADVANCE_FAKES(&m, &c, &s1s, &s2s); if(fcnct.canceled && !fcnct.done){ DROP_CMD(fake_citm_connect_finish(&fcnct, NULL, E_CANCELED)); } ADVANCE_FAKES(&m, &c, &s1s, &s2s); } cu: while(!imap_server_list_cancelfree(&s_result)){ ADVANCE_FAKES(&m, &s1s, &s2s); } while(!imap_client_list_cancelfree(&c_result)){ ADVANCE_FAKES(&m, &c1s, &c2s); } if(xc_result){ imap_client_must_await(xc_result, cawait_cb, NULL); imap_client_cancel(xc_result); ADVANCE_FAKES(&m, &c, &s1s, &s2s); imap_client_free(&xc_result); } imap_server_cancel(s1, false); imap_server_cancel(s2, false); imap_client_cancel(c1); imap_client_cancel(c2); ADVANCE_FAKES(&m, &c, &s1s, &s2s, &c1s, &c2s); imap_server_free(&s1); imap_server_free(&s2); imap_client_free(&c1); imap_client_free(&c2); dstr_free(&u_result); dstr_free(&user); dstr_free(&pass); hashmap_free(&preusers); if(kd) kd->free(kd); if(kd_result) kd_result->free(kd_result); return e; } static derr_t test_preuser(void){ derr_t e = E_OK; size_t cancel_after = 0; bool finished = false; while(!finished){ IF_PROP(&e, do_test_preuser(cancel_after++, &finished) ){ TRACE(&e, "cancel_after was %x\n", FU(cancel_after)); return e; } } // make sure every branch reached completion bool ok = true; for(size_t i = 0; i < sizeof(branches)/sizeof(*branches); i++){ if(!branches[i]){ ok = false; TRACE(&e, "branch[%x] did not finish!\n", FU(i)); } } if(!ok){ ORIG(&e, E_INTERNAL, "test reserve_steps() must be buggy\n"); } return e; } int main(int argc, char** argv){ derr_t e = E_OK; int exit_code = 0; // parse options and set default log level PARSE_TEST_OPTIONS(argc, argv, NULL, LOG_LVL_INFO); #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif PROP_GO(&e, ssl_library_init(), fail); PROP_GO(&e, test_preuser(), fail); fail: if(is_error(e)){ DUMP(e); DROP_VAR(&e); LOG_ERROR("FAIL\n"); exit_code = 1; }else{ LOG_ERROR("PASS\n"); } ssl_library_close(); return exit_code; }
2.15625
2
2024-11-18T21:05:58.132743+00:00
2022-10-15T23:51:42
9cbd5f70474a4e6a1b0337a4702799b6ad1d06ae
{ "blob_id": "9cbd5f70474a4e6a1b0337a4702799b6ad1d06ae", "branch_name": "refs/heads/devel", "committer_date": "2022-10-15T23:51:42", "content_id": "d24b114892bff891265627a8f72e92484b173a0e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c7450e719c6fd9ea0513ea3e505562b21e53bcc2", "extension": "c", "filename": "dvcman.c", "fork_events_count": 108, "gha_created_at": "2012-10-21T21:55:11", "gha_event_created_at": "2022-11-10T01:06:30", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 6326098, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10521, "license": "Apache-2.0", "license_type": "permissive", "path": "/channels/drdynvc/dvcman.c", "provenance": "stackv2-0083.json.gz:8149", "repo_name": "neutrinolabs/NeutrinoRDP", "revision_date": "2022-10-15T23:51:42", "revision_id": "50211223318a02db05b57196d03342edb0207c32", "snapshot_id": "2892440cd469291c2b5151e440949f71059d05e0", "src_encoding": "UTF-8", "star_events_count": 42, "url": "https://raw.githubusercontent.com/neutrinolabs/NeutrinoRDP/50211223318a02db05b57196d03342edb0207c32/channels/drdynvc/dvcman.c", "visit_date": "2022-11-16T20:04:23.843326" }
stackv2
/** * FreeRDP: A Remote Desktop Protocol client. * Dynamic Virtual Channel Manager * * Copyright 2010-2011 Vic Lee * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <freerdp/utils/memory.h> #include <freerdp/utils/stream.h> #include <freerdp/utils/list.h> #include <freerdp/utils/load_plugin.h> #include "drdynvc_types.h" #include "dvcman.h" #define MAX_PLUGINS 10 typedef struct _DVCMAN DVCMAN; struct _DVCMAN { IWTSVirtualChannelManager iface; drdynvcPlugin* drdynvc; const char* plugin_names[MAX_PLUGINS]; IWTSPlugin* plugins[MAX_PLUGINS]; int num_plugins; IWTSListener* listeners[MAX_PLUGINS]; int num_listeners; LIST* channels; }; typedef struct _DVCMAN_LISTENER DVCMAN_LISTENER; struct _DVCMAN_LISTENER { IWTSListener iface; DVCMAN* dvcman; char* channel_name; uint32 flags; IWTSListenerCallback* listener_callback; }; typedef struct _DVCMAN_ENTRY_POINTS DVCMAN_ENTRY_POINTS; struct _DVCMAN_ENTRY_POINTS { IDRDYNVC_ENTRY_POINTS iface; DVCMAN* dvcman; RDP_PLUGIN_DATA* plugin_data; }; typedef struct _DVCMAN_CHANNEL DVCMAN_CHANNEL; struct _DVCMAN_CHANNEL { IWTSVirtualChannel iface; DVCMAN* dvcman; DVCMAN_CHANNEL* next; uint32 channel_id; IWTSVirtualChannelCallback* channel_callback; STREAM* dvc_data; }; static int dvcman_get_configuration(IWTSListener* pListener, void** ppPropertyBag) { *ppPropertyBag = NULL; return 1; } static int dvcman_create_listener(IWTSVirtualChannelManager* pChannelMgr, const char* pszChannelName, uint32 ulFlags, IWTSListenerCallback* pListenerCallback, IWTSListener** ppListener) { DVCMAN* dvcman = (DVCMAN*)pChannelMgr; DVCMAN_LISTENER* listener; if (dvcman->num_listeners < MAX_PLUGINS) { DEBUG_DVC("%d.%s.", dvcman->num_listeners, pszChannelName); listener = xnew(DVCMAN_LISTENER); listener->iface.GetConfiguration = dvcman_get_configuration; listener->dvcman = dvcman; listener->channel_name = xstrdup(pszChannelName); listener->flags = ulFlags; listener->listener_callback = pListenerCallback; if (ppListener) *ppListener = (IWTSListener*)listener; dvcman->listeners[dvcman->num_listeners++] = (IWTSListener*)listener; return 0; } else { DEBUG_WARN("Maximum DVC listener number reached."); return 1; } } static int dvcman_push_event(IWTSVirtualChannelManager* pChannelMgr, RDP_EVENT* pEvent) { int error; DVCMAN* dvcman = (DVCMAN*) pChannelMgr; error = drdynvc_push_event(dvcman->drdynvc, pEvent); if (error == 0) { DEBUG_DVC("event_type %d pushed.", pEvent->event_type); } else { DEBUG_WARN("event_type %d push failed.", pEvent->event_type); } return error; } static int dvcman_register_plugin(IDRDYNVC_ENTRY_POINTS* pEntryPoints, const char* name, IWTSPlugin* pPlugin) { DVCMAN* dvcman = ((DVCMAN_ENTRY_POINTS*) pEntryPoints)->dvcman; if (dvcman->num_plugins < MAX_PLUGINS) { DEBUG_DVC("num_plugins %d", dvcman->num_plugins); dvcman->plugin_names[dvcman->num_plugins] = name; dvcman->plugins[dvcman->num_plugins++] = pPlugin; return 0; } else { DEBUG_WARN("Maximum DVC plugin number reached."); return 1; } } IWTSPlugin* dvcman_get_plugin(IDRDYNVC_ENTRY_POINTS* pEntryPoints, const char* name) { int i; DVCMAN* dvcman = ((DVCMAN_ENTRY_POINTS*) pEntryPoints)->dvcman; for (i = 0; i < dvcman->num_plugins; i++) { if (dvcman->plugin_names[i] == name || strcmp(dvcman->plugin_names[i], name) == 0) { return dvcman->plugins[i]; } } return NULL; } RDP_PLUGIN_DATA* dvcman_get_plugin_data(IDRDYNVC_ENTRY_POINTS* pEntryPoints) { return ((DVCMAN_ENTRY_POINTS*) pEntryPoints)->plugin_data; } IWTSVirtualChannelManager* dvcman_new(drdynvcPlugin* plugin) { DVCMAN* dvcman; dvcman = xnew(DVCMAN); dvcman->iface.CreateListener = dvcman_create_listener; dvcman->iface.PushEvent = dvcman_push_event; dvcman->drdynvc = plugin; dvcman->channels = list_new(); return (IWTSVirtualChannelManager*) dvcman; } int dvcman_load_plugin(IWTSVirtualChannelManager* pChannelMgr, RDP_PLUGIN_DATA* data) { DVCMAN_ENTRY_POINTS entryPoints; PDVC_PLUGIN_ENTRY pDVCPluginEntry = NULL; while (data && data->size > 0) { pDVCPluginEntry = freerdp_load_plugin((char*) data->data[0], "DVCPluginEntry"); if (pDVCPluginEntry != NULL) { entryPoints.iface.RegisterPlugin = dvcman_register_plugin; entryPoints.iface.GetPlugin = dvcman_get_plugin; entryPoints.iface.GetPluginData = dvcman_get_plugin_data; entryPoints.dvcman = (DVCMAN*) pChannelMgr; entryPoints.plugin_data = data; pDVCPluginEntry((IDRDYNVC_ENTRY_POINTS*) &entryPoints); } data = (RDP_PLUGIN_DATA*)(((void*) data) + data->size); } return 0; } static void dvcman_channel_free(DVCMAN_CHANNEL* channel) { if (channel->channel_callback) channel->channel_callback->OnClose(channel->channel_callback); xfree(channel); } void dvcman_free(IWTSVirtualChannelManager* pChannelMgr) { int i; IWTSPlugin* pPlugin; DVCMAN_LISTENER* listener; DVCMAN_CHANNEL* channel; DVCMAN* dvcman = (DVCMAN*) pChannelMgr; while ((channel = (DVCMAN_CHANNEL*) list_dequeue(dvcman->channels)) != NULL) dvcman_channel_free(channel); list_free(dvcman->channels); for (i = 0; i < dvcman->num_listeners; i++) { listener = (DVCMAN_LISTENER*) dvcman->listeners[i]; xfree(listener->channel_name); xfree(listener); } for (i = 0; i < dvcman->num_plugins; i++) { pPlugin = dvcman->plugins[i]; if (pPlugin->Terminated) pPlugin->Terminated(pPlugin); } xfree(dvcman); } int dvcman_init(IWTSVirtualChannelManager* pChannelMgr) { int i; IWTSPlugin* pPlugin; DVCMAN* dvcman = (DVCMAN*) pChannelMgr; for (i = 0; i < dvcman->num_plugins; i++) { pPlugin = dvcman->plugins[i]; if (pPlugin->Initialize) pPlugin->Initialize(pPlugin, pChannelMgr); } return 0; } static int dvcman_write_channel(IWTSVirtualChannel* pChannel, uint32 cbSize, uint8* pBuffer, void* pReserved) { DVCMAN_CHANNEL* channel = (DVCMAN_CHANNEL*) pChannel; return drdynvc_write_data(channel->dvcman->drdynvc, channel->channel_id, pBuffer, cbSize); } static int dvcman_close_channel_iface(IWTSVirtualChannel* pChannel) { DVCMAN_CHANNEL* channel = (DVCMAN_CHANNEL*) pChannel; DVCMAN* dvcman = channel->dvcman; DEBUG_DVC("id=%d", channel->channel_id); if (list_remove(dvcman->channels, channel) == NULL) DEBUG_WARN("channel not found"); dvcman_channel_free(channel); return 1; } int dvcman_create_channel(IWTSVirtualChannelManager* pChannelMgr, uint32 ChannelId, const char* ChannelName) { int i; int bAccept; DVCMAN_LISTENER* listener; DVCMAN_CHANNEL* channel; IWTSVirtualChannelCallback* pCallback; DVCMAN* dvcman = (DVCMAN*) pChannelMgr; for (i = 0; i < dvcman->num_listeners; i++) { listener = (DVCMAN_LISTENER*)dvcman->listeners[i]; if (strcmp(listener->channel_name, ChannelName) == 0) { channel = xnew(DVCMAN_CHANNEL); channel->iface.Write = dvcman_write_channel; channel->iface.Close = dvcman_close_channel_iface; channel->dvcman = dvcman; channel->channel_id = ChannelId; bAccept = 1; pCallback = NULL; if (listener->listener_callback->OnNewChannelConnection(listener->listener_callback, (IWTSVirtualChannel*) channel, NULL, &bAccept, &pCallback) == 0 && bAccept == 1) { DEBUG_DVC("listener %s created new channel %d", listener->channel_name, channel->channel_id); channel->channel_callback = pCallback; list_add(dvcman->channels, channel); return 0; } else { DEBUG_WARN("channel rejected by plugin"); dvcman_channel_free(channel); return 1; } } } return 1; } static DVCMAN_CHANNEL* dvcman_find_channel_by_id(IWTSVirtualChannelManager* pChannelMgr, uint32 ChannelId) { LIST_ITEM* curr; DVCMAN* dvcman = (DVCMAN*) pChannelMgr; for (curr = dvcman->channels->head; curr; curr = curr->next) { if (((DVCMAN_CHANNEL*) curr->data)->channel_id == ChannelId) { return (DVCMAN_CHANNEL*)curr->data; } } return NULL; } int dvcman_close_channel(IWTSVirtualChannelManager* pChannelMgr, uint32 ChannelId) { DVCMAN_CHANNEL* channel; IWTSVirtualChannel* ichannel; channel = dvcman_find_channel_by_id(pChannelMgr, ChannelId); if (channel == NULL) { DEBUG_WARN("ChannelId %d not found!", ChannelId); return 1; } if (channel->dvc_data) { stream_free(channel->dvc_data); channel->dvc_data = NULL; } DEBUG_DVC("dvcman_close_channel: channel %d closed", ChannelId); ichannel = (IWTSVirtualChannel*)channel; ichannel->Close(ichannel); return 0; } int dvcman_receive_channel_data_first(IWTSVirtualChannelManager* pChannelMgr, uint32 ChannelId, uint32 length) { DVCMAN_CHANNEL* channel; channel = dvcman_find_channel_by_id(pChannelMgr, ChannelId); if (channel == NULL) { DEBUG_WARN("ChannelId %d not found!", ChannelId); return 1; } if (channel->dvc_data) stream_free(channel->dvc_data); channel->dvc_data = stream_new(length); return 0; } int dvcman_receive_channel_data(IWTSVirtualChannelManager* pChannelMgr, uint32 ChannelId, uint8* data, uint32 data_size) { int error = 0; DVCMAN_CHANNEL* channel; channel = dvcman_find_channel_by_id(pChannelMgr, ChannelId); if (channel == NULL) { DEBUG_WARN("ChannelId %d not found!", ChannelId); return 1; } if (channel->dvc_data) { /* Fragmented data */ if (stream_get_length(channel->dvc_data) + data_size > stream_get_size(channel->dvc_data)) { DEBUG_WARN("data exceeding declared length!"); stream_free(channel->dvc_data); channel->dvc_data = NULL; return 1; } stream_write(channel->dvc_data, data, data_size); if (stream_get_length(channel->dvc_data) >= stream_get_size(channel->dvc_data)) { error = channel->channel_callback->OnDataReceived(channel->channel_callback, stream_get_size(channel->dvc_data), stream_get_data(channel->dvc_data)); stream_free(channel->dvc_data); channel->dvc_data = NULL; } } else { error = channel->channel_callback->OnDataReceived(channel->channel_callback, data_size, data); } return error; }
2.0625
2
2024-11-18T21:05:58.198011+00:00
2023-07-23T07:12:24
3fbbe14066a11731abec7ec70a1660875fadf5ea
{ "blob_id": "3fbbe14066a11731abec7ec70a1660875fadf5ea", "branch_name": "refs/heads/master", "committer_date": "2023-07-23T07:12:24", "content_id": "3db076ef13ab01668a6f0ba4a42c02b04aa186bf", "detected_licenses": [ "MIT" ], "directory_id": "b970e053302588f44ee1c6b7187c4769934c857f", "extension": "js", "filename": "segments.js", "fork_events_count": 5633, "gha_created_at": "2011-02-25T05:53:47", "gha_event_created_at": "2023-06-27T12:32:50", "gha_language": null, "gha_license_id": "MIT", "github_id": 1409811, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1222, "license": "MIT", "license_type": "permissive", "path": "/ajax/libs/openlayers/5.0.0/geom/flat/segments.js", "provenance": "stackv2-0083.json.gz:8279", "repo_name": "cdnjs/cdnjs", "revision_date": "2023-07-23T07:12:24", "revision_id": "6843ffa5339e4595b3a6893ae3e9ede1117cc5f9", "snapshot_id": "2fe0f21477c08618fe609da844f5d133224c3eda", "src_encoding": "UTF-8", "star_events_count": 8894, "url": "https://raw.githubusercontent.com/cdnjs/cdnjs/6843ffa5339e4595b3a6893ae3e9ede1117cc5f9/ajax/libs/openlayers/5.0.0/geom/flat/segments.js", "visit_date": "2023-07-23T14:52:44.587645" }
stackv2
/** * @module ol/geom/flat/segments */ /** * This function calls `callback` for each segment of the flat coordinates * array. If the callback returns a truthy value the function returns that * value immediately. Otherwise the function returns `false`. * @param {Array.<number>} flatCoordinates Flat coordinates. * @param {number} offset Offset. * @param {number} end End. * @param {number} stride Stride. * @param {function(this: S, module:ol/coordinate~Coordinate, module:ol/coordinate~Coordinate): T} callback Function * called for each segment. * @param {S=} opt_this The object to be used as the value of 'this' * within callback. * @return {T|boolean} Value. * @template T,S */ export function forEach(flatCoordinates, offset, end, stride, callback, opt_this) { const point1 = [flatCoordinates[offset], flatCoordinates[offset + 1]]; const point2 = []; let ret; for (; (offset + stride) < end; offset += stride) { point2[0] = flatCoordinates[offset + stride]; point2[1] = flatCoordinates[offset + stride + 1]; ret = callback.call(opt_this, point1, point2); if (ret) { return ret; } point1[0] = point2[0]; point1[1] = point2[1]; } return false; }
2.765625
3
2024-11-18T21:05:58.278714+00:00
2018-02-13T20:18:19
9935a1f1b6ec3cb7fad433d0451fc0d54b429ffb
{ "blob_id": "9935a1f1b6ec3cb7fad433d0451fc0d54b429ffb", "branch_name": "refs/heads/master", "committer_date": "2018-02-13T20:18:19", "content_id": "9ef6f1232a8e7586d671f283b09b95aad1b2322b", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "c9225166490e448c0b18845c90de4c53fdba5725", "extension": "c", "filename": "chmod.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4561, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/cmd/acex-bin/chmod.c", "provenance": "stackv2-0083.json.gz:8408", "repo_name": "jdefrancesco/newsys", "revision_date": "2018-02-13T20:18:19", "revision_id": "314956b8ca463b8d7cc9b30de2be2d4247adf432", "snapshot_id": "98961c1f93a2dab230c24d386301626858aaf099", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jdefrancesco/newsys/314956b8ca463b8d7cc9b30de2be2d4247adf432/cmd/acex-bin/chmod.c", "visit_date": "2023-03-17T03:57:04.187930" }
stackv2
/* Copyright (c) 2017, Piotr Durlej * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <ctype.h> #include <errno.h> #include <stdio.h> #include <err.h> static void parse_mode(const char *mspec, mode_t *set, mode_t *clr, mode_t *bX) { mode_t mode_bigX = 0; mode_t mode_s = 0; mode_t mode_c = 0; mode_t r = 0; mode_t w = 0; mode_t x = 0; mode_t s = 0; const char *p; mode_t *mp; if (isdigit(*mspec)) { *set = strtoul(mspec, NULL, 8); *clr = ~*set; return; } p = mspec; do { r = w = x = s = 0; if (*p != 'a' && *p != 'u' && *p != 'g' && *p != 'o') { r = umask(0777); umask(r); w = ~r & 0222; x = ~r & 0111; r = ~r & 0444; } else while (*p == 'a' || *p == 'u' || *p == 'g' || *p == 'o') { switch (*p) { case 'a': r = S_IRUSR | S_IRGRP | S_IROTH; w = S_IWUSR | S_IWGRP | S_IWOTH; x = S_IXUSR | S_IXGRP | S_IXOTH; s = S_ISUID | S_ISGID; break; case 'u': r |= S_IRUSR; w |= S_IWUSR; x |= S_IXUSR; s |= S_ISUID; break; case 'g': r |= S_IRGRP; w |= S_IWGRP; x |= S_IXGRP; s |= S_ISGID; break; case 'o': r |= S_IROTH; w |= S_IWOTH; x |= S_IXOTH; s |= S_ISGID; break; } p++; } switch (*p) { case '+': mp = &mode_s; break; case '-': mp = &mode_c; break; case '=': mode_c = r | w | x; mp = &mode_s; break; default: goto bad_mstr; } p++; while (*p && *p != ',') { switch(*p) { case 'r': *mp |= r; break; case 'w': *mp |= w; break; case 'x': *mp |= x; break; case 'X': mode_bigX |= x; break; case 's': *mp |= s; break; case '+': mp = &mode_s; break; case '-': mp = &mode_c; break; default: goto bad_mstr; } p++; } if (*p == ',') p++; } while (*p); *bX = mode_bigX; *set = mode_s; *clr = mode_c; return; bad_mstr: errx(255, "bad mode string"); } int main(int argc, char **argv) { struct stat st; mode_t set, clr, bigX = 0; int err = 0; int fd; int i; if (argc == 2 && !strcmp(argv[1], "--help")) { printf("\nUsage: chmod [PERM] FILE...\n" " chmod [a][u][g][o](+|-|=)[r][w][x][X][s][,...] FILE...\n\n" "Set permission bits on FILEs to PERM.\n" "Set (+) specified permission bits (and preserver other bits) on FILEs.\n" "Clear (-) specified permission bits (and preserve other bits) on FILEs.\n" "Clear mode bits according to [a][u][g][o], then set (=) specified permission\n" "bits (and reset other bits) on FILEs.\n\n" ); return 0; } if (argc < 3) errx(255, "too few arguments"); parse_mode(argv[1], &set, &clr, &bigX); for (i = 2; i < argc; i++) { fd = open(argv[i], O_NOIO); if (fd < 0) { err = errno; warn("%s", argv[i]); continue; } if (fstat(fd, &st)) { err = errno; warn("%s", argv[i]); close(fd); continue; } if ((st.st_mode & 0111) || S_ISDIR(st.st_mode)) st.st_mode |= bigX; st.st_mode |= set; st.st_mode &= ~clr; if (fchmod(fd, st.st_mode)) { err = errno; perror(argv[i]); } close(fd); } return err; }
2.09375
2
2024-11-18T21:05:58.381339+00:00
2019-07-24T11:22:17
b0f5913f24110fc42d99a03c041d2bdc966de9b6
{ "blob_id": "b0f5913f24110fc42d99a03c041d2bdc966de9b6", "branch_name": "refs/heads/master", "committer_date": "2019-07-24T11:22:17", "content_id": "75ed7327dd9e9f178ba1b6c04abb402da3b8514e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "fc11300b2cc9b96a4e70c60629c080da95da25bc", "extension": "c", "filename": "avr-i2c.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 181876231, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3471, "license": "Apache-2.0", "license_type": "permissive", "path": "/atmega/i2c/avr-i2c.c", "provenance": "stackv2-0083.json.gz:8536", "repo_name": "lwIoT/lwiot-atmega", "revision_date": "2019-07-24T11:22:17", "revision_id": "fa2e609db616e72ec1cc35876dbfe27099d97a22", "snapshot_id": "962e8a1fbf2154f6ccfd287f190136eb76905b63", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lwIoT/lwiot-atmega/fa2e609db616e72ec1cc35876dbfe27099d97a22/atmega/i2c/avr-i2c.c", "visit_date": "2020-05-14T16:38:48.556924" }
stackv2
/* * AVR I2C implementation. * * @author Michel Megens * @email dev@bietje.net */ #include "avri2c.h" #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <lwiot.h> #include <avr/io.h> #include <avr/interrupt.h> #include <util/twi.h> #define F_SCL 100000UL // SCL frequency #define Prescaler 1 #define TWBR_val ((((F_CPU / F_SCL) / Prescaler) - 16 ) / 2) #define I2C_READ 0x1U #define I2C_WRITE 0x0U #define TMO 200 void avr_i2c_init(void) { TWBR = TWBR_val; } static void i2c_reset_bus() { TWCR = 0; TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); } uint8_t i2c_write_start(uint8_t address) { time_t tmo = lwiot_tick_ms() + TMO; i2c_reset_bus(); while( !(TWCR & (1<<TWINT)) ) { if(tmo < lwiot_tick_ms()) { i2c_reset_bus(); return 1; } } if((TWSR & 0xF8) != TW_START) return 1; TWDR = address; TWCR = (1<<TWINT) | (1<<TWEN); while( !(TWCR & (1<<TWINT)) ) { if(tmo < lwiot_tick_ms()) { i2c_reset_bus(); return 1; } } uint8_t twst = TW_STATUS & 0xF8; if((twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) return 1; return 0; } uint8_t i2c_write(uint8_t data) { time_t tmo = lwiot_tick_ms() + TMO; TWDR = data; TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA); while( !(TWCR & (1<<TWINT)) ) { if(tmo < lwiot_tick_ms()) { i2c_reset_bus(); return 1; } } if( (TWSR & 0xF8) != TW_MT_DATA_ACK ) return 1; return 0; } uint8_t i2c_read_ack(void) { time_t tmo = lwiot_tick_ms() + TMO; TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA); while( !(TWCR & (1<<TWINT)) ) { if(tmo < lwiot_tick_ms()) { i2c_reset_bus(); return 1; } } return TWDR; } uint8_t i2c_read_nack(void) { time_t tmo = lwiot_tick_ms() + TMO; TWCR = (1<<TWINT) | (1<<TWEN); while( !(TWCR & (1<<TWINT)) ) { if(tmo < lwiot_tick_ms()) { i2c_reset_bus(); return 1; } } return TWDR; } uint8_t i2c_read(bool ack) { uint8_t byte; if(ack) byte = i2c_read_ack(); else byte = i2c_read_nack(); return byte; } uint8_t i2c_transmit(uint8_t address, uint8_t* data, uint16_t length, uint8_t stop) { if (i2c_write_start(address | I2C_WRITE)) return 1; for (uint16_t i = 0; i < length; i++) { if (i2c_write(data[i])) return 1; } if(stop) i2c_write_stop(); return 0; } uint8_t i2c_receive(uint8_t address, uint8_t* data, uint16_t length, uint8_t stop) { if (i2c_write_start(address | I2C_READ)) return 1; for (uint16_t i = 0; i < (length-1); i++) { data[i] = i2c_read_ack(); } data[(length-1)] = i2c_read_nack(); if(stop) i2c_write_stop(); return 0; } uint8_t i2c_writeReg(uint8_t devaddr, uint8_t regaddr, uint8_t* data, uint16_t length) { if (i2c_write_start(devaddr | 0x00)) return 1; i2c_write(regaddr); for (uint16_t i = 0; i < length; i++) { if (i2c_write(data[i])) return 1; } i2c_write_stop(); return 0; } uint8_t i2c_readReg(uint8_t devaddr, uint8_t regaddr, uint8_t* data, uint16_t length) { if (i2c_write_start(devaddr)) return 1; i2c_write(regaddr); if (i2c_write_start(devaddr | 0x01)) return 1; for (uint16_t i = 0; i < (length-1); i++) { data[i] = i2c_read_ack(); } data[(length-1)] = i2c_read_nack(); i2c_write_stop(); return 0; } void i2c_write_stop(void) { TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); }
2.625
3
2024-11-18T21:05:58.747474+00:00
2016-05-13T18:27:20
b814118a0af26a51b718084000320ecf91921602
{ "blob_id": "b814118a0af26a51b718084000320ecf91921602", "branch_name": "refs/heads/master", "committer_date": "2016-05-13T18:27:20", "content_id": "7206f446a190f1c1dcf5dcbdc5e451ed865e69cd", "detected_licenses": [ "MIT" ], "directory_id": "79d8fcfd1fdff1177ea94ee6984103c6998f6dbc", "extension": "c", "filename": "dijkstra.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 54215017, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9750, "license": "MIT", "license_type": "permissive", "path": "/dijkstra/dijkstra.c", "provenance": "stackv2-0083.json.gz:8794", "repo_name": "kassisdion/Algorithm", "revision_date": "2016-05-13T18:27:20", "revision_id": "5f37e80976e0a33e2002f3637ee49480c76af1e7", "snapshot_id": "15a1ce8f84c9041bb10178ad4b696271fc35d313", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kassisdion/Algorithm/5f37e80976e0a33e2002f3637ee49480c76af1e7/dijkstra/dijkstra.c", "visit_date": "2021-01-21T13:53:00.872214" }
stackv2
/** * Algorithm homework #3 * * "Dijkstra algorithm" * - on an undirected weighted graph with 200 vertices labeled 1 to 200 * - run Dijkstra's shortest-path algorithm on this graph, using 1 (the first * vertex) as the source vertex, and to compute the shortest-path distances * between 1 and every other vertex of the graph. If there is no path between * a * vertex v and vertex 1, we'll define the shortest-path distance between * 1 and v to be 1000000. * * @ Mar. 7 2015 * @ Jeongyeup Paek **/ /** * @ Student ID : 50151252 * @ Name : Faisant Florian **/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <sys/time.h> #ifdef _WIN64 // define something for Windows (64-bit) #include <time.h> #elif _WIN32 // define something for Windows (32-bit) #include <time.h> #elif __APPLE__ // apple #include <sys/time.h> #elif __linux // linux #include <time.h> #elif __unix // Unix #include <time.h> #elif __posix // POSIX #include <time.h> #endif #define MAX_DISTANCE 1000000 // if no path exists #define MAX_NUM_NODES 200 // 200 vertices labeled 1 to 200 #define MAX_VERTEX_ID 200 // 200 vertices labeled 1 to 200 typedef struct edge_s { int toid; int w; // weight struct edge_s *next; } edge_t; typedef struct vertex_s { int id; // node id unsigned int dist; // minimum distance to source int f; // fromId edge_t *edges; // chained list of edge bool is_current; // saving algorithm progression } vertex_t; vertex_t *m_varray[MAX_NUM_NODES]; // array of all vertices int m_n = 0; // total number of i->j edges. int m_e = 0; // 'm_e/2' is the actual number of undirected edges vertex_t * find_vertex(unsigned int id) { if (id > MAX_VERTEX_ID) { printf("%s: error, invalid vertex id %d\n", __func__, id); return NULL; } //m_varray[id]->id = id+1 (see graph initialization in main) return m_varray[id - 1]; } // find vertex and add if does not exist vertex_t * add_vertex(unsigned int id) { vertex_t *v; if (id > MAX_VERTEX_ID) { printf("%s: error, invalid vertex id %d\n", __func__, id); return NULL; } if ((v = find_vertex(id)) != NULL) { return v; } v = m_varray[id]; v->id = id; v->dist = MAX_DISTANCE; v->f = 0; return v; } // delete all malloc'ed memory (edges and vertices) void delete_graph() { edge_t *tmp; edge_t *head; int i; for (i = 0; i < MAX_NUM_NODES; i++) { head = m_varray[i]->edges; while (head != NULL) { tmp = head; head = head->next; free(tmp); } free(m_varray[i]); } } // print shortest distance of all nodes void print_all_shortest_distance() { int i = 0; while (i < MAX_NUM_NODES) { printf("Vertext %3d : shortest distance %4d\n", m_varray[i]->id, m_varray[i]->dist); i++; } printf("number of nodes processed : %d\n", i); } // print shortest path of all nodes void print_all_shortest_path() { edge_t *tmp; edge_t *head; int i; for (i = 0; i < MAX_NUM_NODES; i++) { printf("Vertext %3d : ", m_varray[i]->id); head = m_varray[i]->edges; while (head != NULL) { tmp = head; head = head->next; printf("%d, %d ", tmp->toid, tmp->w); } printf("\n"); } } edge_t * find_edge(unsigned int fromid, unsigned int toid) { vertex_t *v; if ((v = find_vertex(fromid)) == NULL) { return NULL; } edge_t *current = v->edges; while (current != NULL) { if (current->toid == toid) { return current; } current = current->next; } return NULL; } // find edge and add if does not exist edge_t * add_edge(unsigned int fromid, unsigned int toid, unsigned int ecost) { if (fromid > MAX_VERTEX_ID || toid > MAX_VERTEX_ID) { printf("%s: error, invalid vertex id %d->%d\n", __func__, fromid, toid); return NULL; } vertex_t *v; if ((v = find_vertex(fromid)) == NULL) { return NULL; } if (v->edges == NULL) { v->edges = (edge_t *) calloc(sizeof(edge_t), 1); v->edges->next = NULL; v->edges->toid = toid; v->edges->w = ecost; return v->edges; } else { /* * We could call find_edge(fromid, toid) * But it will call find_vertex() and check result * (2 useless operation) */ edge_t *current = v->edges; while (current->next != NULL) { current = current->next; } current->next = (edge_t *) malloc(sizeof(edge_t)); current->next->next = NULL; current->next->toid = toid; current->next->w = ecost; return current->next; } return NULL; } //find the vertex who has the minimum distance vertex_t * find_min_vertex() { int i, min_i, min_dist; /* * 0 = starting point * So we init our first distance with i=1 */ i = min_i = 1; min_dist = m_varray[i]->dist; for (i = 2; i < MAX_NUM_NODES; i++) { if (m_varray[i]->dist < min_dist && m_varray[i]->is_current == false) { min_dist = m_varray[i]->dist; min_i = i; } } m_varray[min_i]->is_current = true; return m_varray[min_i]; } // run Dijkstra algorithm void run_dijkstra() { int start_point = 1; int index = start_point - 1; int i = 0; edge_t *edge = m_varray[index]->edges; m_varray[index]->f = 0; m_varray[index]->dist = 0; while (edge != NULL) { m_varray[(edge->toid) - 1]->dist = edge->w; m_varray[(edge->toid) - 1]->f = start_point; edge = edge->next; } for (i = 0; i < MAX_NUM_NODES; i++) { vertex_t *v = find_min_vertex(); for (edge = v->edges; edge != NULL; edge = edge->next) { if (v->dist + edge->w < m_varray[edge->toid-1]->dist) { m_varray[(edge->toid) - 1]->dist = v->dist + edge->w; m_varray[(edge->toid) - 1]->f = v->id; } } } } int read_input_file(char *filename) { FILE *fp; char linebuf[1000]; // clear global data before reading the file m_n = 0; // adjacency list representation of a simple undirected graph if ((fp = fopen(filename, "r")) == NULL) { perror("Error opening input file"); return -1; } // read data file, line by line int i; int token_count; int token_array[1000] = {0}; while (fgets(linebuf, sizeof(linebuf), fp) != NULL) { if (m_n > MAX_NUM_NODES) { printf("too many data (n = %d)\n", m_n); break; } //count element token_count = 0; for (i = 1; linebuf[i] != '\n' && linebuf[i] != '\0'; i++) { if (linebuf[i] == '\t' || linebuf[i] == ',' || linebuf[i] == ' ') { token_count++; token_array[token_count] = i + 1; } } for (i = 1; i < token_count; i += 2) { int fromid = m_n + 1; int toid = 0; int ecost = 0; sscanf(&linebuf[token_array[i]], "%d", &toid); sscanf(&linebuf[token_array[i + 1]], "%d", &ecost); if (add_edge(fromid, toid, ecost) == NULL) { return -1; } m_e++; } m_n++; } fclose(fp); printf("%s: total: %d nodes, %d edges\n", __func__, m_n, m_e / 2); return 0; } int main(int argc, char *argv[]) { /* ** Check the number of argument */ if (argc != 2) { printf("No input file\n"); return 0; } /* * Allocate memory to our graph * And then * Init the graph */ int i = 0; while (i < MAX_NUM_NODES) { m_varray[i] = malloc(sizeof(vertex_t)); m_varray[i]->id = i + 1; m_varray[i]->dist = MAX_DISTANCE; m_varray[i]->f = 0; m_varray[i]->edges = NULL; m_varray[i]->is_current = false; i++; } /* * Read input file from filename (argv[1) * And * Complete our graph */ char *filename = argv[1]; if (read_input_file(filename) == -1) { printf("Parsing error\n"); return 0; } /* * Start the clock for running time calculation * run dijkstra here */ struct timeval start, stop; gettimeofday(&start, NULL); run_dijkstra(); /* * print shortest distance of all nodes in increasing order of ID */ print_all_shortest_distance(); /* * if possible, print shortest path of all nodes */ bool option = false; if (option) { print_all_shortest_path(); } printf("homework output:\n"); printf("shortest distance to vertices 7,37,59,82,99,115,133,165,188,197\n"); printf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n", m_varray[6]->dist, m_varray[36]->dist, m_varray[58]->dist, m_varray[81]->dist, m_varray[98]->dist, m_varray[114]->dist, m_varray[132]->dist, m_varray[164]->dist, m_varray[187]->dist, m_varray[196]->dist); /* * calculate running time */ gettimeofday(&stop, NULL); time_t sec = stop.tv_sec - start.tv_sec; time_t msec = (stop.tv_usec - start.tv_usec) / 1000; printf("running time = %lu.%03lu seconds\n", sec, msec); /* * memory clean up */ delete_graph(); return 0; }
3.296875
3
2024-11-18T21:05:59.020249+00:00
2015-12-08T23:30:35
e7139a3e4254e0d1b9ae37554e13373b99f8cfa9
{ "blob_id": "e7139a3e4254e0d1b9ae37554e13373b99f8cfa9", "branch_name": "refs/heads/master", "committer_date": "2015-12-08T23:30:35", "content_id": "0ac60c2100657b24033a6f7b2035b53b0a2df8ef", "detected_licenses": [ "MIT" ], "directory_id": "127e5f66829ed85daafed455b29945233733437d", "extension": "h", "filename": "Lista.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 44889383, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1294, "license": "MIT", "license_type": "permissive", "path": "/Trabalho Final/Lista.h", "provenance": "stackv2-0083.json.gz:9050", "repo_name": "AndressaUmetsu/PRA", "revision_date": "2015-12-08T23:30:35", "revision_id": "6b6e33faa40b3b452623e83504ca00ee91d7ba82", "snapshot_id": "2e66ddfa646375b2f5c12fc5696da54f1cc89d96", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/AndressaUmetsu/PRA/6b6e33faa40b3b452623e83504ca00ee91d7ba82/Trabalho Final/Lista.h", "visit_date": "2016-09-01T12:25:37.003589" }
stackv2
#ifndef LISTA_H_INCLUDED #define LISTA_H_INCLUDED #include <stdlib.h> #define ERRO_ALOCACAO -1 #define ERRO_LISTA_VAZIA -2 #define ERRO_POSICAO_INVALIDA -3 #define ERRO_ELEMENTO_NAO_ENCONTRADO -4 typedef struct elemento { void *info; struct elemento *proximo; } Elemento; typedef struct { size_t tamInfo; Elemento *cabeca; } Lista; void inicializa_lista(Lista *l, size_t t); void mostra_lista(Lista l, void (*mostra_info)(void *)); int insereNoInicio(Lista *l, void *info); int insereNoFim(Lista *l, void *info); int insereNaPosicao(Lista *l, void *info, int pos); int insereEmOrdem(Lista *l, void *info, int (*compara_info)(void *, void *)); int buscaElemento(Lista *l, void *info, int (*compara_info)(void *, void *)); int removeDoInicio(Lista *l, void *info); int removeNaPosicao(Lista *l, void *info, int pos); int removeInfo(Lista *l, void *info); int removeDoFim(Lista *l, void *info); int modificaNaPosicao(Lista *l, void *info, int pos); int leNaPosicao(Lista *l, void *info, int pos); int limpa_lista(Lista *l); int listaVazia(Lista *l); int elementoExiste(Lista *l, void *info, int (*compara_info)(void *, void *)); Elemento *aloca_elemento(size_t t, void *info); #endif // LISTA_H_INCLUDED
2.3125
2
2024-11-18T21:05:59.460020+00:00
2022-04-14T06:16:29
721a5ddc5b05a6315b22b5d1d2a0317272626c18
{ "blob_id": "721a5ddc5b05a6315b22b5d1d2a0317272626c18", "branch_name": "refs/heads/master", "committer_date": "2022-04-14T06:54:02", "content_id": "e27861f8baeff1ec9890f9ea283478c38a9e51a8", "detected_licenses": [ "MIT" ], "directory_id": "b3ccb28a7bfc32da454e321058948fa78a40207e", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 82138386, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3404, "license": "MIT", "license_type": "permissive", "path": "/55_timer_int_pwm/timer_int_pwm/main.c", "provenance": "stackv2-0083.json.gz:9691", "repo_name": "olekmali/ATMega128", "revision_date": "2022-04-14T06:16:29", "revision_id": "00e4fb7ca41b40e6c139ecccdf8a47669366575b", "snapshot_id": "e901bf83113b7f9d934f5950100f1a0698ef36c5", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/olekmali/ATMega128/00e4fb7ca41b40e6c139ecccdf8a47669366575b/55_timer_int_pwm/timer_int_pwm/main.c", "visit_date": "2022-05-22T07:58:14.584700" }
stackv2
//* testing TIMER1 interrupt with software generated PWM - main.c * #include "bios_timer_int.h" #include <stdint.h> #include <avr/interrupt.h> #include "soft_pwm.h" #include "bios_led8.h" #include "bios_key4.h" //------------------------------------------------------------------------------------ // Global constant(s) //------------------------------------------------------------------------------------ #define PWM_FREQUENCY 1000L #define INT_FREQUENCY (PWM_FREQUENCY * PWM_RESOLUTION) #define MAIN_LOOP_FREQUENCY 100 //------------------------------------------------------------------------------------ // Global variable(s) used as bridge to pass parameters to the interrupts //------------------------------------------------------------------------------------ static volatile uint8_t semaphore = 0; // volatile keyword is very important here! //------------------------------------------------------------------------------------ // Timer1 Interrupt Functionality //------------------------------------------------------------------------------------ void MyTimerFN (void) { // Remember: we are inside the interrupt routine // - no excessive loops // - no time consuming tasks // - no interrupt enabling PWM_generator_interrupt(); static uint16_t counter = 0; // ^^^^^^^^ make sure that ( SAMPLING__FRQ / MAIN_LOOP_FREQUENCY ) // fits the variable range! uint8_t - 255, uint16_t - 65535 if (0<counter) counter--; else { counter = ( INT_FREQUENCY / MAIN_LOOP_FREQUENCY ); semaphore = 1; } } int main(void) { led8_init(); led8_set(0); key4_init(); Timer1_initialize( INT_FREQUENCY , MyTimerFN, timer_prescale_1 ); // Set the PWM rates for the PWM channels // Note: the functions will compute the numbers to count based on percentages here uint8_t pwm0 = 0, pwm1 = 100; PWM_generator_setParam (0, pwm0); PWM_generator_setParam (1, pwm1); sei(); uint8_t but_prev = 0; while(1) { // wait for the signal to proceed from the interrupt while ( semaphore==0 ) ; // and immediately reset that signal to wait state semaphore = 0; uint8_t but_cur = key4_get(); uint8_t but_chg = ( but_cur^but_prev ) & but_cur; but_prev = but_cur; // important! update what is now current will be past next time // cycle through five PWM levels with one button if ( (but_chg & B_K4) !=0 ) { // if ( (but_chg & 0b00000001) !=0 ) if (pwm0<100) { pwm0 = pwm0 + 20; } else { pwm0 = 0; } PWM_generator_setParam (0, pwm0); } if ( (but_chg & B_K6) !=0 ) { // if ( (but_chg & 0b00000100) !=0 ) if (pwm1<80) { pwm1 = pwm1 + 20; } else { pwm1 = 100; } PWM_generator_setParam (1, pwm1); } if ( (but_chg & B_K7) !=0 ) { // if ( (but_chg & 0b00001000) !=0 ) if (pwm1>20) { pwm1 = pwm1 - 20; } else { pwm1 = 0; } PWM_generator_setParam (1, pwm1); } } return(0); }
3.03125
3
2024-11-18T21:05:59.653060+00:00
2021-06-01T22:04:52
226a5b6918ea428bf519fb09fc57f0bd13180507
{ "blob_id": "226a5b6918ea428bf519fb09fc57f0bd13180507", "branch_name": "refs/heads/main", "committer_date": "2021-06-01T22:04:52", "content_id": "af70772933454ce734d15ca7442895b03def80d2", "detected_licenses": [ "MIT" ], "directory_id": "54e567b81ba3acb4b28767c94a49f96d22d1fd2c", "extension": "h", "filename": "selectionsort.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 462, "license": "MIT", "license_type": "permissive", "path": "/seso/include/sort/selectionsort.h", "provenance": "stackv2-0083.json.gz:9820", "repo_name": "ajthr/seso", "revision_date": "2021-06-01T22:04:52", "revision_id": "3b09a283e14a84fc18096b4807dab87cc23070a5", "snapshot_id": "a0f499b06ea78991b9b5c5699fb1f015d6456890", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ajthr/seso/3b09a283e14a84fc18096b4807dab87cc23070a5/seso/include/sort/selectionsort.h", "visit_date": "2023-05-23T01:37:47.787636" }
stackv2
#ifndef SELECTION_SORT_H #define SELECTION_SORT_H #include "utils.h" void selectionSort(double *arr, int size) { int i, j, min_index; for (i = 0; i < size - 1; i++) { min_index = i; for (j = i + 1; j < size; j++) { if (arr[min_index] > arr[j]) { min_index = j; } } if (min_index != i) { swap(arr + i, arr + min_index); } } } #endif //SELECTION_SORT_H
2.5625
3
2024-11-18T21:06:00.188422+00:00
2014-11-04T23:15:22
9de5d0cf3143f542c583e8f02c17e73b5197304c
{ "blob_id": "9de5d0cf3143f542c583e8f02c17e73b5197304c", "branch_name": "refs/heads/master", "committer_date": "2014-11-04T23:15:22", "content_id": "ed3857108ac03a5a8f514e52e3012949b12b0c7f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "70214efa2467f6c567b805dc923c0d288bf92733", "extension": "h", "filename": "ximpl.h", "fork_events_count": 5, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 26249164, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1795, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/sys/classes/draw/impls/x/ximpl.h", "provenance": "stackv2-0083.json.gz:10078", "repo_name": "OpenCMISS-Dependencies/petsc", "revision_date": "2014-11-04T23:15:22", "revision_id": "5334b1442d9dabf795f2fdda92d0f565f35ff948", "snapshot_id": "0684cd59bb9bddb6be03f27f2e9c183ad476b208", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/OpenCMISS-Dependencies/petsc/5334b1442d9dabf795f2fdda92d0f565f35ff948/src/sys/classes/draw/impls/x/ximpl.h", "visit_date": "2021-01-17T10:08:25.370917" }
stackv2
/* Defines the internal data structures for the X-windows implementation of the graphics functionality in PETSc. */ #if !defined(_XIMPL_H) #define _XIMPL_H #include <petsc-private/drawimpl.h> #include <X11/Xlib.h> #include <X11/Xutil.h> typedef unsigned long PetscDrawXiPixVal; typedef struct { GC set; PetscDrawXiPixVal cur_pix; } PetscDrawXiGC; typedef struct { Font fnt; int font_w,font_h; int font_descent; PetscDrawXiPixVal font_pix; } PetscDrawXiFont; typedef struct { Display *disp; int screen; Window win; Visual *vis; /* Graphics visual */ PetscDrawXiGC gc; PetscDrawXiFont *font; int depth; /* Depth of visual */ int numcolors; /* Number of available colors */ int maxcolors; /* Current number in use */ Colormap cmap; PetscDrawXiPixVal foreground,background; PetscDrawXiPixVal cmapping[256]; int x,y,w,h; /* Size and location of window */ Drawable drw; } PetscDraw_X; #define PetscDrawXiDrawable(w) ((w)->drw ? (w)->drw : (w)->win) #define PetscDrawXiSetColor(Win,icolor) \ { if (icolor >= 256 || icolor < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Color value out of range"); \ if ((Win)->gc.cur_pix != (Win)->cmapping[icolor]) { \ XSetForeground((Win)->disp,(Win)->gc.set,(Win)->cmapping[icolor]); \ (Win)->gc.cur_pix = (Win)->cmapping[icolor]; \ }} #define PetscDrawXiSetPixVal(Win,pix) \ { if ((PetscDrawXiPixVal) (Win)->gc.cur_pix != pix) { \ XSetForeground((Win)->disp,(Win)->gc.set,pix); \ (Win)->gc.cur_pix = pix; \ }} #endif
2.15625
2
2024-11-18T21:06:00.485264+00:00
2021-06-11T15:43:08
f1d516c74158a3b4fd5b5303ab733a3620f4b859
{ "blob_id": "f1d516c74158a3b4fd5b5303ab733a3620f4b859", "branch_name": "refs/heads/master", "committer_date": "2021-06-11T15:43:08", "content_id": "7cd6b3672be5393062a992e6f4713a3f17b86199", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "14fd126ff68624b66daf64fc251a633244593ab1", "extension": "h", "filename": "datablock_status.h", "fork_events_count": 1, "gha_created_at": "2020-07-09T11:38:12", "gha_event_created_at": "2021-06-11T15:43:09", "gha_language": "Fortran", "gha_license_id": "BSD-2-Clause", "github_id": 278347824, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1146, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/cosmosis/datablock/datablock_status.h", "provenance": "stackv2-0083.json.gz:10336", "repo_name": "ktanidis/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "revision_date": "2021-06-11T15:43:08", "revision_id": "ce195564631b148bef0214a27a57470640c69a08", "snapshot_id": "6749d1dec87b3f070f9d255b602d32260341f478", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ktanidis/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra/ce195564631b148bef0214a27a57470640c69a08/cosmosis/datablock/datablock_status.h", "visit_date": "2023-05-15T09:11:32.086202" }
stackv2
#ifndef COSMOSIS_DATABLOCK_STATUS_H #define COSMOSIS_DATABLOCK_STATUS_H #ifdef __cplusplus extern "C" { #endif /* DATABLOCK_STATUS is type of the status codes returned by the C datablock interface functions that return status codes. In all cases the user can rely upon 0 indicating success, and nonzero indicating some type of failure. The exact numeric values of codes indicating failure should not be relied upon; use the enumerators instead of integral values. */ typedef enum { /* DBS_SUCCESS is returned to indicate success for most functions. */ DBS_SUCCESS = 0, DBS_DATABLOCK_NULL, DBS_SECTION_NULL, DBS_SECTION_NOT_FOUND, DBS_NAME_NULL, DBS_NAME_NOT_FOUND, DBS_NAME_ALREADY_EXISTS, DBS_VALUE_NULL, DBS_WRONG_VALUE_TYPE, DBS_MEMORY_ALLOC_FAILURE, DBS_SIZE_NULL, DBS_SIZE_NONPOSITIVE, DBS_SIZE_INSUFFICIENT, DBS_NDIM_NONPOSITIVE, DBS_NDIM_OVERFLOW, DBS_NDIM_MISMATCH, DBS_EXTENTS_NULL, DBS_EXTENTS_MISMATCH, DBS_LOGIC_ERROR, /* DBS_USED_DEFAULT should never be returned by a user-facing function. */ DBS_USED_DEFAULT, } DATABLOCK_STATUS; #ifdef __cplusplus } #endif #endif
2.03125
2
2024-11-18T21:06:00.692276+00:00
2019-05-20T22:34:54
665b0210eafcbadf1e91d8cbe0132dfc6740af36
{ "blob_id": "665b0210eafcbadf1e91d8cbe0132dfc6740af36", "branch_name": "refs/heads/master", "committer_date": "2019-05-20T22:34:54", "content_id": "13c41040a30ab230fa467201d5c809af489bd75f", "detected_licenses": [ "MIT", "BSD-3-Clause-Clear" ], "directory_id": "61d6b0216e61fb0fab6687dfaddd090f936c7702", "extension": "h", "filename": "RF_events.h", "fork_events_count": 1, "gha_created_at": "2018-10-23T14:37:18", "gha_event_created_at": "2019-05-20T22:34:55", "gha_language": "C", "gha_license_id": "BSD-3-Clause-Clear", "github_id": 154344053, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1108, "license": "MIT,BSD-3-Clause-Clear", "license_type": "permissive", "path": "/MotionSoftware/src/kernel/RF_events.h", "provenance": "stackv2-0083.json.gz:10466", "repo_name": "woookey/JumpingEnergyHarvester", "revision_date": "2019-05-20T22:34:54", "revision_id": "dbde401d053243f27bfd3130c579cdcf6adb4409", "snapshot_id": "28c3f7217d7659b55fd0fad0382636a4b70d8f8d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/woookey/JumpingEnergyHarvester/dbde401d053243f27bfd3130c579cdcf6adb4409/MotionSoftware/src/kernel/RF_events.h", "visit_date": "2020-04-02T10:32:58.278564" }
stackv2
/** * Defines the most basic events */ #ifndef ROBOTIC_FRAMEWORK_EVENTS_H #define ROBOTIC_FRAMEWORK_EVENTS_H #include <stdint.h> #include <stddef.h> /** * This is a structure defining the most basic * event as part of Robotic Framework. Each event * is constructed dynamically during the program * and is dispatched to subscribed agents in order * to be processed by them * * @param signalValue, value of the signal * @param pendingConsumers, number of agents that still * need to consume this event * * TODO: pendingConsumers should be deleted - not needed really */ typedef struct { uint32_t signalValue; uint32_t pendingConsumers; size_t eventSize; }RFEvent; #define RFEVENT_SIZE sizeof(RFEvent) /** * Define some universal signals that will be used * thorough the framework application * * Note: Application signal space has to start with * signal equal to 3 */ enum { RF_INITIAL_SIGNAL = 0, RF_ENTRY_SIGNAL = 1, RF_EXIT_SIGNAL = 2, RF_LAST_SIGNAL = 3 }; extern RFEvent RFEvent_InitialSignal; extern RFEvent RFEvent_EntrySignal; extern RFEvent RFEvent_ExitSignal; #endif
2.578125
3
2024-11-18T21:06:00.761478+00:00
2019-11-22T08:27:45
1c087676d940528b2057f9bc0d96d2cecb600604
{ "blob_id": "1c087676d940528b2057f9bc0d96d2cecb600604", "branch_name": "refs/heads/master", "committer_date": "2019-11-22T08:27:45", "content_id": "aa88f2b7262a8741585a14c7c36854089fc5db82", "detected_licenses": [ "MIT" ], "directory_id": "f5fe4950db8d0a3b7ec7cc5a579456a61fd05b1d", "extension": "h", "filename": "cmc_string.h", "fork_events_count": 0, "gha_created_at": "2019-11-20T08:14:49", "gha_event_created_at": "2019-11-20T08:14:49", "gha_language": null, "gha_license_id": "MIT", "github_id": 222885175, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 402, "license": "MIT", "license_type": "permissive", "path": "/src/utl/cmc_string.h", "provenance": "stackv2-0083.json.gz:10597", "repo_name": "TryExceptElse/C-Macro-Collections", "revision_date": "2019-11-22T08:27:45", "revision_id": "994a168364f73608ddf5c17adfb064943dd6947d", "snapshot_id": "40439680a4b29ebe5cc85bc6c010db7e057f4d50", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TryExceptElse/C-Macro-Collections/994a168364f73608ddf5c17adfb064943dd6947d/src/utl/cmc_string.h", "visit_date": "2020-09-13T19:41:32.541677" }
stackv2
/** * cmc_string.h * * Creation Date: 17/07/2019 * * Authors: * Leonardo Vencovsky (https://github.com/LeoVen) * */ /* A very simple fixed size string used by all collections' method to_string */ #ifndef CMC_STRING_H #define CMC_STRING_H #include <inttypes.h> #include <stddef.h> static const size_t cmc_string_len = 200; struct cmc_string { char s[200]; }; #endif /* CMC_STRING_H */
2.109375
2
2024-11-18T21:06:01.522925+00:00
2016-03-29T01:48:34
9d1903f1c611a9984956ca618328615fbe243a03
{ "blob_id": "9d1903f1c611a9984956ca618328615fbe243a03", "branch_name": "refs/heads/master", "committer_date": "2016-03-29T01:48:34", "content_id": "3586927a80a88aa5811ed06db2a9cc9aa5a3a5c8", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "c98c0a9ac874d1fe014e8541467db988ee67104d", "extension": "c", "filename": "client.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1867, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/testing/nvlist-experiment/client.c", "provenance": "stackv2-0083.json.gz:10984", "repo_name": "cnsuhao/libipc-1", "revision_date": "2016-03-29T01:48:34", "revision_id": "ff5b1aa25fa5e7e65a1a8e4ca29944609b6cd17c", "snapshot_id": "17c7b9c3314a0ff1cb197b9b9394227e1c0ed2e8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cnsuhao/libipc-1/ff5b1aa25fa5e7e65a1a8e4ca29944609b6cd17c/testing/nvlist-experiment/client.c", "visit_date": "2021-05-30T12:53:09.320222" }
stackv2
#include <err.h> #include <fcntl.h> #include <limits.h> #include <string.h> #include <stdlib.h> #include <sys/nv.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> int setup_client_socket() { char statedir[PATH_MAX]; struct sockaddr_un sock; int len, fd; sock.sun_family = AF_LOCAL; len = snprintf(sock.sun_path, sizeof(sock.sun_path), "%s/foo.sock", "/usr/home/mark/tmp"); if (len >= sizeof(sock.sun_path)) { //client->last_error = -IPC_ERROR_NAME_TOO_LONG; return -1; } if (len < 0) { //client->last_error = IPC_CAPTURE_ERRNO; return -1; } fd = socket(AF_LOCAL, SOCK_STREAM, 0); if (fd < 0) { //client->last_error = IPC_CAPTURE_ERRNO; //log_errno("socket(2)"); return -1; } if (connect(fd, (struct sockaddr *) &sock, SUN_LEN(&sock)) < 0) { //client->last_error = IPC_CAPTURE_ERRNO; //log_errno("connect(2) to %s", sock.sun_path); return -1; } return fd; } int main() { nvlist_t *nvl; int fd; int sock; sock = setup_client_socket(); if (sock < 0) err(1, "socket failed"); fd = open("/tmp/foo", O_RDONLY); if (fd < 0) err(1, "open(\"/tmp/foo\") failed"); nvl = nvlist_create(0); /* * There is no need to check if nvlist_create() succeeded, * as the nvlist_add_<type>() functions can cope. * If it failed, nvlist_send() will fail. */ nvlist_add_string(nvl, "command", "hello"); nvlist_add_string(nvl, "filename", "/tmp/foo"); nvlist_add_number(nvl, "flags", O_RDONLY); /* * We just want to send the descriptor, so we can give it * for the nvlist to consume (that's why we use nvlist_move * not nvlist_add). */ nvlist_move_descriptor(nvl, "fd", fd); if (nvlist_send(sock, nvl) < 0) { nvlist_destroy(nvl); err(1, "nvlist_send() failed"); } nvlist_destroy(nvl); }
2.46875
2
2024-11-18T21:06:01.613959+00:00
2016-06-06T01:51:28
6bc332f5e64b203e603a21151eff087073be55a4
{ "blob_id": "6bc332f5e64b203e603a21151eff087073be55a4", "branch_name": "refs/heads/master", "committer_date": "2016-06-06T01:51:28", "content_id": "ad7ff18fa59e5eaaac1a40ad154fb99b1b390a92", "detected_licenses": [ "MIT" ], "directory_id": "73d7a0f5643e0a552b79ac6c2cadd377c6451111", "extension": "c", "filename": "api.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 58879693, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6579, "license": "MIT", "license_type": "permissive", "path": "/src/api.c", "provenance": "stackv2-0083.json.gz:11113", "repo_name": "spiralman/avr-proxy", "revision_date": "2016-06-06T01:51:28", "revision_id": "dcd756c9ff51f4b92ac31d397ab77f3e5d16ede1", "snapshot_id": "0230e46c32862f2fdffcea18434039658b088fb0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/spiralman/avr-proxy/dcd756c9ff51f4b92ac31d397ab77f3e5d16ede1/src/api.c", "visit_date": "2021-03-08T19:32:10.529813" }
stackv2
#include "os_type.h" #include "gpio.h" #include "osapi.h" #include "user_interface.h" #include "espmissingincludes.h" #include "ip_addr.h" #include "espconn.h" #include "platform.h" #include "espfs.h" #include "httpd.h" #include "httpdespfs.h" #include "webpages-espfs.h" #include "ssdp.h" static struct espconn avrConn; static esp_tcp avrTcp; static os_timer_t connectPauseTimer; static os_timer_t responseTimer; static bool awaitingResponse = false; static bool responseReady = false; static char responseBuf[256]; /* Documented max command length */ static char cmd[135]; static int cmdLen; static int cmdErr = ESPCONN_OK; static ConnTypePtr openCmdConn = NULL; static uint8 openCmdRemoteIp[4]; static int openCmdRemotePort; #define OS_QUEUE_LEN 4 static os_event_t osQueue[OS_QUEUE_LEN]; #define OS_TASK_DISCONNECT 0 void ICACHE_FLASH_ATTR os_task_handler(os_event_t * evt) { switch (evt->sig) { case OS_TASK_DISCONNECT: espconn_disconnect(&avrConn); break; } } int ICACHE_FLASH_ATTR ssdp_dev_template(HttpdConnData * connData, char * token, void ** arg) { if (token == NULL) { return HTTPD_CGI_DONE; } if (strcmp(token, "uuid") == 0) { httpdSend(connData, ssdp_uuid(), -1); } return HTTPD_CGI_DONE; } void ICACHE_FLASH_ATTR connect_pause_cb(void * arg) { os_timer_disarm(&connectPauseTimer); os_printf("reconnecting\n"); espconn_connect(&avrConn); } void ICACHE_FLASH_ATTR response_done_cb(void * arg) { awaitingResponse = false; responseReady = true; os_timer_disarm(&responseTimer); /* Pretend like some data was sent, so libesphttpd calls the CGI callback again to respond asynchronously */ httpdSentCb(openCmdConn, (char *)openCmdRemoteIp, openCmdRemotePort); openCmdConn = NULL; } void ICACHE_FLASH_ATTR cmd_sent_cb(void * arg) { os_printf("sent\n"); os_timer_arm(&responseTimer, 200, false); } void ICACHE_FLASH_ATTR cmd_received_cb(void * arg, char * data, unsigned short len) { data[len-1] = '\n'; os_printf("recieved %s\n", data); if (awaitingResponse) { strcat(responseBuf, data); } } void ICACHE_FLASH_ATTR cmd_connected_cb(void * arg) { os_printf("connected\n"); espconn_send(&avrConn, (unsigned char *)cmd, cmdLen); } void ICACHE_FLASH_ATTR cmd_disconnected_cb(void * arg) { os_printf("disconnected\n"); avrConn.state = ESPCONN_NONE; } void ICACHE_FLASH_ATTR cmd_reconnect_cb(void * arg, sint8 err) { os_printf("reconnect error: %d\n", err); /* Happens when we try to reconnect too quickly, if we get requests too close together; wait and try again */ if (err == ESPCONN_RST) { os_timer_arm(&connectPauseTimer, 100, false); } else if (err == ESPCONN_CONN) { /* Only solution to this (so far) seems to be to reboot; note, need to force GPIO 0 and 2 high to boot correctly */ gpio_output_set(1 | (1 << 2), 0, 0, 0); system_restart(); } else { awaitingResponse = false; responseReady = true; cmdErr = err; /* Pretend like some data was sent, so libesphttpd calls the CGI callback again to respond asynchronously */ httpdSentCb(openCmdConn, (char *)openCmdRemoteIp, openCmdRemotePort); openCmdConn = NULL; } } int ICACHE_FLASH_ATTR send_command(HttpdConnData * connData) { if (!awaitingResponse && !responseReady) { if (connData->conn==NULL) { //Connection aborted. Clean up. return HTTPD_CGI_DONE; } if (connData->requestType != HTTPD_METHOD_GET) { httpdStartResponse(connData, 405); httpdEndHeaders(connData); return HTTPD_CGI_DONE; } cmdLen = httpdFindArg(connData->getArgs, "cmd", cmd, sizeof(cmd)); if (cmdLen == -1) { httpdStartResponse(connData, 400); httpdEndHeaders(connData); return HTTPD_CGI_DONE; } cmd[cmdLen++] = '\r'; cmd[cmdLen] = 0; os_printf("Queuing %s\n", cmd); os_printf("connecting\n"); cmdErr = ESPCONN_OK; espconn_connect(&avrConn); openCmdConn = connData->conn; memcpy(openCmdRemoteIp, connData->remote_ip, 4*sizeof(uint8)); openCmdRemotePort = connData->remote_port; awaitingResponse = true; return HTTPD_CGI_MORE; } else if(responseReady) { if (cmdErr == ESPCONN_OK) { os_printf("\nresponse:\n%s\n", responseBuf); httpdStartResponse(connData, 200); httpdHeader(connData, "Content-Type", "text/plain"); httpdEndHeaders(connData); httpdSend(connData, responseBuf, -1); } else { char errMessage[25]; os_sprintf(errMessage, "Communication error: %d\n", cmdErr); httpdStartResponse(connData, 500); httpdHeader(connData, "Content-Type", "text/plain"); httpdEndHeaders(connData); httpdSend(connData, errMessage, -1); } responseBuf[0] = 0; responseReady = false; cmd[0] = 0; cmdLen = 0; system_os_post(USER_TASK_PRIO_0, OS_TASK_DISCONNECT, 0); return HTTPD_CGI_DONE; } else { os_printf("."); return HTTPD_CGI_MORE; } } int ICACHE_FLASH_ATTR hello_world(HttpdConnData * connData) { if (connData->conn == NULL) { return HTTPD_CGI_DONE; } if (connData->requestType!=HTTPD_METHOD_GET) { httpdStartResponse(connData, 405); httpdEndHeaders(connData); return HTTPD_CGI_DONE; } httpdStartResponse(connData, 200); httpdHeader(connData, "Content-Type", "text/plain"); httpdEndHeaders(connData); httpdSend(connData, "Hello, world\n", -1); return HTTPD_CGI_DONE; }; HttpdBuiltInUrl builtInUrls[]={ {"/", hello_world, NULL}, {"/ssdp/device_description.xml", cgiEspFsTemplate, ssdp_dev_template}, {"/avr/command", send_command, NULL}, {NULL, NULL, NULL} }; void ICACHE_FLASH_ATTR api_init() { system_os_task(os_task_handler, USER_TASK_PRIO_0, osQueue, OS_QUEUE_LEN); espFsInit((void*)(webpages_espfs_start)); httpdInit(builtInUrls, 80); os_timer_setfn(&responseTimer, response_done_cb, NULL); os_timer_setfn(&connectPauseTimer, connect_pause_cb, NULL); avrConn.type = ESPCONN_TCP; avrConn.state = ESPCONN_NONE; avrTcp.local_port = espconn_port(); avrTcp.remote_port = 23; avrTcp.remote_ip[0] = 192; avrTcp.remote_ip[1] = 168; avrTcp.remote_ip[2] = 1; avrTcp.remote_ip[3] = 115; avrConn.proto.tcp = &avrTcp; espconn_regist_recvcb(&avrConn, cmd_received_cb); espconn_regist_sentcb(&avrConn, cmd_sent_cb); espconn_regist_connectcb(&avrConn, cmd_connected_cb); espconn_regist_disconcb(&avrConn, cmd_disconnected_cb); espconn_regist_reconcb(&avrConn, cmd_reconnect_cb); };
2.1875
2
2024-11-18T21:06:01.699730+00:00
2019-12-13T15:32:46
99e022b8a353ae9fc489d70924892f847930b410
{ "blob_id": "99e022b8a353ae9fc489d70924892f847930b410", "branch_name": "refs/heads/master", "committer_date": "2019-12-13T15:32:46", "content_id": "a6b0899a4b6087faf2ff63655af07b7e33845225", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1b24cddf7b92f5e7c2c066ea3aabd63d2868b3f6", "extension": "c", "filename": "cohorts.c", "fork_events_count": 0, "gha_created_at": "2019-10-31T22:47:49", "gha_event_created_at": "2019-10-31T22:47:50", "gha_language": null, "gha_license_id": null, "github_id": 218873858, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5043, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/mishegos/cohorts.c", "provenance": "stackv2-0083.json.gz:11242", "repo_name": "mewbak/mishegos", "revision_date": "2019-12-13T15:32:46", "revision_id": "98a36dd65ccaafae10d6be5e13caca1c57c702c6", "snapshot_id": "82f6d19c75ff4eb824f2b9d554465a588a698243", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mewbak/mishegos/98a36dd65ccaafae10d6be5e13caca1c57c702c6/src/mishegos/cohorts.c", "visit_date": "2020-09-01T03:53:54.062410" }
stackv2
#include "mish_core.h" #include "parson.h" static output_cohort cohorts[MISHEGOS_COHORT_NSLOTS]; void cohorts_init() { // NOTE(ww): We don't need to call this with each cohort dump, // so just put it here. json_set_escape_slashes(0); uint32_t nworkers = GET_CONFIG()->nworkers; for (int i = 0; i < MISHEGOS_COHORT_NSLOTS; ++i) { cohorts[i].outputs = malloc(sizeof(output_slot) * nworkers); } } void cohorts_cleanup() { DLOG("cleaning up"); /* NOTE(ww): Nothing here for now. * We could free each cohorts[i].outputs here, but we're exiting anyways. */ } bool add_to_cohort(output_slot *slot) { DLOG("checking cohort slots"); /* First pass: search the cohort slots to see if another worker * has produced an output for the same input as us. */ bool inserted = false; for (int i = 0; i < MISHEGOS_COHORT_NSLOTS; ++i) { int outputno = ffs(cohorts[i].workers); if (outputno == 0) { DLOG("pass 1: no worker outputs added to cohort slot=%d yet", i); continue; } outputno -= 1; output_slot output = cohorts[i].outputs[outputno]; if (slot->input.len != output.input.len || memcmp(slot->input.raw_insn, output.input.raw_insn, output.input.len) != 0) { DLOG("skipping non-matching cohort slot=%d", i); #ifdef DEBUG { char *tmp1, *tmp2; tmp1 = hexdump(&output.input); tmp2 = hexdump(&slot->input); DLOG("expected %s, got %s", tmp1, tmp2); free(tmp1); free(tmp2); } #endif continue; } assert(outputno != slot->workerno && "cohort already has this output"); /* We've found our cohort. */ cohorts[i].outputs[slot->workerno] = *slot; cohorts[i].workers ^= (1 << slot->workerno); inserted = true; if (inserted) { DLOG("inserted worker output=%d into preexisting cohort slot=%d", slot->workerno, i); return true; } } /* Second pass: search the cohort slots for an empty slot. */ for (int i = 0; i < MISHEGOS_COHORT_NSLOTS; ++i) { int outputno = ffs(cohorts[i].workers); if (outputno != 0) { continue; } DLOG("pass 2: found empty cohort slot=%d for worker output=%d", i, slot->workerno); cohorts[i].outputs[slot->workerno] = *slot; cohorts[i].workers ^= (1 << slot->workerno); DLOG("inserted worker output=%d into fresh cohort slot=%d", slot->workerno, i); return true; } DLOG("no cohort slots available..."); return false; } static void dump_cohort(output_cohort *cohort) { DLOG("dumping cohort"); uint32_t nworkers = GET_CONFIG()->nworkers; assert(cohort->workers == ~(~0 << nworkers) && "dump_cohort called on partial cohort"); JSON_Value *root_value = json_value_init_object(); JSON_Object *cohort_obj = json_value_get_object(root_value); input_slot islot = cohort->outputs[0].input; char *input_hex = hexdump(&islot); json_object_set_string(cohort_obj, "input", input_hex); free(input_hex); JSON_Value *outputs_value = json_value_init_array(); JSON_Array *outputs_arr = json_value_get_array(outputs_value); for (int i = 0; i < nworkers; ++i) { JSON_Value *output_value = json_value_init_object(); JSON_Object *output = json_value_get_object(output_value); json_object_set_number(output, "ndecoded", cohort->outputs[i].ndecoded); json_object_set_number(output, "len", cohort->outputs[i].len); if (cohort->outputs[i].len > 0) { json_object_set_string(output, "result", cohort->outputs[i].result); } else { json_object_set_null(output, "result"); } json_object_set_number(output, "workerno", cohort->outputs[i].workerno); json_object_set_number(output, "status", cohort->outputs[i].status); json_object_set_string(output, "status_name", status2str(cohort->outputs[i].status)); const char *worker_so = get_worker_so(cohort->outputs[i].workerno); assert(worker_so != NULL); json_object_set_string(output, "worker_so", worker_so); json_array_append_value(outputs_arr, output_value); } json_object_set_value(cohort_obj, "outputs", outputs_value); char *dump = json_serialize_to_string(root_value); puts(dump); json_free_serialized_string(dump); json_value_free(root_value); } void dump_cohorts() { DLOG("dumping fully populated cohorts"); uint32_t nworkers = GET_CONFIG()->nworkers; for (int i = 0; i < MISHEGOS_COHORT_NSLOTS; ++i) { if (cohorts[i].workers != ~(~0 << nworkers)) { DLOG("skipping incomplete cohort (worker mask=%d, expected=%d)", cohorts[i].workers, ~(~0 << nworkers)); /* Slot not fully populated. */ continue; } DLOG("slot=%d fully populated, dumping and clearing the slot", i); output_cohort *cohort = malloc(sizeof(output_cohort)); memcpy(cohort, &cohorts[i], sizeof(output_cohort)); /* Clear the worker mask. We don't actually have to wipe the cohort's * slots, since only the mask gets checked. */ cohorts[i].workers = 0; dump_cohort(cohort); free(cohort); } }
2.734375
3
2024-11-18T21:06:01.843559+00:00
2018-01-31T11:13:33
0c7527eeb532626c36baa4054a8923c17e5d9430
{ "blob_id": "0c7527eeb532626c36baa4054a8923c17e5d9430", "branch_name": "refs/heads/master", "committer_date": "2018-01-31T11:13:33", "content_id": "f3381a3ec26f18fe6ff28da6683be0dc864d7aec", "detected_licenses": [ "MIT" ], "directory_id": "07e41b8827d63efcd70e2eb4a5becac0c87bbde2", "extension": "h", "filename": "runPE.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3251, "license": "MIT", "license_type": "permissive", "path": "/runPE.h", "provenance": "stackv2-0083.json.gz:11500", "repo_name": "5l1v3r1/humble-file-crypter", "revision_date": "2018-01-31T11:13:33", "revision_id": "2d465c2655405b563ea0d282f58f06c544496f9d", "snapshot_id": "5f21197991f6934264201208505e9b9f890db5a4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/5l1v3r1/humble-file-crypter/2d465c2655405b563ea0d282f58f06c544496f9d/runPE.h", "visit_date": "2023-03-18T03:39:15.000734" }
stackv2
#include <stdio.h> typedef LONG (WINAPI *NtUnmapViewOfSection) (HANDLE ProcessHandle, PVOID BaseAddress); void newRunPE(LPSTR szFilePath, LPCTSTR desiredCurrentDirectory, PVOID pFile, LPTSTR commandLine) { PIMAGE_DOS_HEADER IDH; // DOS .EXE header PIMAGE_NT_HEADERS INH; // NT .EXE header PIMAGE_SECTION_HEADER ISH; // Section Header PROCESS_INFORMATION PI; // Process Information STARTUPINFOA SI; // Start Up Information PCONTEXT CTX; // Context Frame PDWORD dwImageBase; NtUnmapViewOfSection xNtUnmapViewOfSection; LPVOID pImageBase; PDWORD oldProtect; int Count; IDH = PIMAGE_DOS_HEADER(pFile); if (IDH->e_magic == IMAGE_DOS_SIGNATURE) { INH = PIMAGE_NT_HEADERS(DWORD(pFile) + IDH->e_lfanew); // Patch payload subsystem to avoid crashes INH->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI; if (INH->Signature == IMAGE_NT_SIGNATURE) { RtlZeroMemory(&SI, sizeof(SI)); RtlZeroMemory(&PI, sizeof(PI)); // Create new instance of target process if (CreateProcessA(szFilePath, commandLine, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, desiredCurrentDirectory, &SI, &PI)) { CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE)); CTX->ContextFlags = CONTEXT_FULL; // Get image base of target process if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) { ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&dwImageBase), 4, NULL); // Unmap old image if (DWORD(dwImageBase) == INH->OptionalHeader.ImageBase) { xNtUnmapViewOfSection = NtUnmapViewOfSection(GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtUnmapViewOfSection")); xNtUnmapViewOfSection(PI.hProcess, PVOID(dwImageBase)); } // Allocate new memory in target process for the payload pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(INH->OptionalHeader.ImageBase), INH->OptionalHeader.SizeOfImage, 0x3000, PAGE_READWRITE); if (pImageBase) { // Write payload headers and sections into target process WriteProcessMemory(PI.hProcess, pImageBase, pFile, INH->OptionalHeader.SizeOfHeaders, NULL); for (Count = 0; Count < INH->FileHeader.NumberOfSections; Count++) { ISH = PIMAGE_SECTION_HEADER(DWORD(pFile) + IDH->e_lfanew + 248 + (Count * 40)); WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + ISH->VirtualAddress), LPVOID(DWORD(pFile) + ISH->PointerToRawData), ISH->SizeOfRawData, NULL); } // Fix image base WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&INH->OptionalHeader.ImageBase), 4, NULL); // Fix memory protection after write to be more stealthy VirtualProtectEx(PI.hProcess, pImageBase, INH->OptionalHeader.SizeOfImage, PAGE_EXECUTE_READ, oldProtect); // Set new entry point and resume target main thread CTX->Eax = DWORD(pImageBase) + INH->OptionalHeader.AddressOfEntryPoint; SetThreadContext(PI.hThread, LPCONTEXT(CTX)); ResumeThread(PI.hThread); } } } } } VirtualFree(pFile, 0, MEM_RELEASE); }
2.375
2
2024-11-18T21:06:02.092015+00:00
2018-07-14T22:34:33
abf37699fb39459efe5af38fe643ac4ea68085f3
{ "blob_id": "abf37699fb39459efe5af38fe643ac4ea68085f3", "branch_name": "refs/heads/master", "committer_date": "2018-07-14T22:34:33", "content_id": "c5c9bb8edaee6d59d17982f51cd3fde6baa3aeae", "detected_licenses": [ "MIT" ], "directory_id": "bed63a3e626c43c4dab1630b0cc86f6f0b12b059", "extension": "c", "filename": "TRPO_Util.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 135741863, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 591, "license": "MIT", "license_type": "permissive", "path": "/src/TRPO_Util.c", "provenance": "stackv2-0083.json.gz:11885", "repo_name": "custom-computing-ic/TRPO-Robot-Control", "revision_date": "2018-07-14T22:34:33", "revision_id": "043d57edac6f0dbcb92aee8830eff089f512c6ad", "snapshot_id": "ade951ad869b95c83aa3692894e148749bee98a4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/custom-computing-ic/TRPO-Robot-Control/043d57edac6f0dbcb92aee8830eff089f512c6ad/src/TRPO_Util.c", "visit_date": "2020-03-19T03:35:20.876735" }
stackv2
#include <math.h> #include "TRPO.h" // Utility function calculating the number of trainable parameters size_t NumParamsCalc (size_t * LayerSize, size_t NumLayers) { size_t NumParams = 0; for (size_t i=0; i<NumLayers-1; ++i) { // Weight and Bias NumParams += LayerSize[i] * LayerSize[i+1] + LayerSize[i+1]; } // Std NumParams += LayerSize[NumLayers-1]; return NumParams; } // Utility Function Calculating the Max static inline double max(double record, double cur) { double result = (record<fabs(cur)) ? fabs(cur) : record; return result; }
2.1875
2
2024-11-18T21:06:02.155133+00:00
2021-10-21T15:26:57
9565410d1c50c433d37bfaa207a581375fc92569
{ "blob_id": "9565410d1c50c433d37bfaa207a581375fc92569", "branch_name": "refs/heads/master", "committer_date": "2021-10-21T15:26:57", "content_id": "ded26349713d3ea8052a1bc49150db33460f637e", "detected_licenses": [ "0BSD" ], "directory_id": "bcc1e3cd07b83b2e950bd9a1de03ba11fd568c21", "extension": "h", "filename": "cursor.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3831, "license": "0BSD", "license_type": "permissive", "path": "/include/screen/cursor.h", "provenance": "stackv2-0083.json.gz:12013", "repo_name": "tearitco/amateuros", "revision_date": "2021-10-21T15:26:57", "revision_id": "a64940f9c4a0118df93e93b0212ce06cb3db80a5", "snapshot_id": "c674b981c4ec3e7d044f0807d7cb79b34130fe74", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tearitco/amateuros/a64940f9c4a0118df93e93b0212ce06cb3db80a5/include/screen/cursor.h", "visit_date": "2023-08-28T00:55:43.453028" }
stackv2
// // move_cursor.inc: moves hardware cursor to new row/col // assuming VGA txt mode 03 - 80x25 characters, 16 colors // Parms: // input 1: col to move to // input 2: row to move to #pragma once #define FONT_ADDRESS 0xA000 #define FONT_WIDTH 0xA000 #define FONT_HEIGHT (FONT_WIDTH+1) void move_cursor(uint16_t cursor_x, uint16_t cursor_y) { uint8_t *framebuffer = (uint8_t *)gfx_mode->physical_base_pointer; uint8_t bytes_per_pixel = (gfx_mode->bits_per_pixel+1) / 8; uint8_t font_width = *(uint8_t *)FONT_WIDTH; uint8_t font_height = *(uint8_t *)FONT_HEIGHT; uint32_t row = (cursor_y * font_height * gfx_mode->x_resolution) * bytes_per_pixel; // Row to print to in pixels uint32_t col = (cursor_x * font_width) * bytes_per_pixel; // Col to print to in pixels uint8_t *font_char; uint8_t bytes_per_char_line; uint8_t char_size; // Text Cursor Position in screen in pixels to print to framebuffer += (row + col); // Draw cursor // Font memory address = FONT_ADRESS, offset from start of font, // subtract 1 because 'cursor' is only 1 line bytes_per_char_line = ((font_width - 1) / 8) + 1; char_size = bytes_per_char_line * font_height; font_char = (uint8_t *)(FONT_ADDRESS + ((127 * char_size) - bytes_per_char_line)); // Go to last row of cursor character framebuffer += (gfx_mode->x_resolution * (font_height-1)) * bytes_per_pixel; uint8_t num_px_drawn = 0; for (int8_t byte = bytes_per_char_line - 1; byte >= 0; byte--) { for (int8_t bit = 7; bit >= 0; bit--) { // If bit is set draw text color pixel, if not draw background color if (font_char[byte] & (1 << bit)) { *((uint32_t *)framebuffer) = user_gfx_info->fg_color; } else { *((uint32_t *)framebuffer) = user_gfx_info->bg_color; } framebuffer += bytes_per_pixel; // Next pixel position num_px_drawn++; // If done drawing all pixels in current line of char, stop and go on if (num_px_drawn == font_width) { num_px_drawn = 0; break; } } } } void remove_cursor(uint16_t cursor_x, uint16_t cursor_y) { uint8_t *framebuffer = (uint8_t *)gfx_mode->physical_base_pointer; uint8_t bytes_per_pixel = (gfx_mode->bits_per_pixel+1) / 8; uint8_t font_width = *(uint8_t *)FONT_WIDTH; uint8_t font_height = *(uint8_t *)FONT_HEIGHT; uint32_t row = (cursor_y * font_height * gfx_mode->x_resolution) * bytes_per_pixel; // Row to print to in pixels uint32_t col = (cursor_x * font_width) * bytes_per_pixel; // Col to print to in pixels uint8_t *font_char; uint8_t bytes_per_char_line; uint8_t char_size; // Text Cursor Position in screen in pixels to print to framebuffer += (row + col); bytes_per_char_line = ((font_width - 1) / 8) + 1; // Go to last row of cursor character framebuffer += (gfx_mode->x_resolution * (font_height-1)) * bytes_per_pixel; // Draw background color for 1 row uint8_t num_px_drawn = 0; for (int8_t byte = bytes_per_char_line - 1; byte >= 0; byte--) { for (int8_t bit = 7; bit >= 0; bit--) { // If bit is set draw text color pixel, if not draw background color *((uint32_t *)framebuffer) = user_gfx_info->bg_color; framebuffer += bytes_per_pixel; // Next pixel position num_px_drawn++; // If done drawing all pixels in current line of char, stop and go on if (num_px_drawn == font_width) { num_px_drawn = 0; break; } } } }
2.9375
3
2024-11-18T21:06:02.259860+00:00
2018-06-24T16:27:48
83b0c44a15abb50a6ce0a8de933fbefa4a24c358
{ "blob_id": "83b0c44a15abb50a6ce0a8de933fbefa4a24c358", "branch_name": "refs/heads/master", "committer_date": "2018-06-24T16:27:48", "content_id": "9e9b3cdab00fa1021e7f3f3ef43accb936cf0a5c", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "052a92030632a87caf7d31f2697efa61a8503e4a", "extension": "c", "filename": "process.c", "fork_events_count": 0, "gha_created_at": "2019-11-11T12:14:33", "gha_event_created_at": "2020-02-02T01:27:28", "gha_language": "C", "gha_license_id": null, "github_id": 220974276, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2744, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/TP2/Kernel/process.c", "provenance": "stackv2-0083.json.gz:12142", "repo_name": "rlajous/Complex-OS", "revision_date": "2018-06-24T16:27:48", "revision_id": "ebe65a54fd638a0864adfc2f6dc4d17c2a29c2b3", "snapshot_id": "07eb05d1ff59d3eedc319b18e89994326313d425", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/rlajous/Complex-OS/ebe65a54fd638a0864adfc2f6dc4d17c2a29c2b3/TP2/Kernel/process.c", "visit_date": "2021-09-08T18:25:04.225232" }
stackv2
#include <process.h> #include <scheduler.h> #include <threads.h> static int nextPid = 1; process_t * createProcess(void * entryPoint, int argc, char * argv[], char * name) { size_t length = strlen(name); process_t * process = allocateMemory(sizeof(process_t)); process->pid = nextPid++; process->ppid = getpid(); process->standardPipes[0] = -1; process->standardPipes[1] = -1; initializeThreads(process); process->currentThread = 0; process->threads[0].thread = createThread(argc, argv, entryPoint); process->threads[0].next = 0; if(length < MAX_NAME) { memcpy(process->name, name, length); process->name[length] = '\0'; } else process->name[0] = 0; return process; } void initializeThreads(process_t * process) { int i; for(i = 0 ; i < MAX_THREADS ; i++){ process->threads[i].thread = NULL; } } void deleteProcess(process_t * process) { killThreads(process); freeMemory(process); } void callProcess(int argc, char * argv[], void * entryPoint) { ((EntryPoint)(entryPoint))(argc, argv); if(argv != NULL) { while(argc--) { freeMemory(argv[argc]); } freeMemory(argv); } process_t * process = getProcess(getpid()); terminateThread(process, process->currentThread); yield(); } //Source RowDaBoat Wyrm void * fillStackFrame(void * entryPoint, void * stack, int argc, char * argv[]) { stackFrame_t * frame = (stackFrame_t *)stack - 1; frame->gs = 0x001; frame->fs = 0x002; frame->r15 = 0x003; frame->r14 = 0x004; frame->r13 = 0x005; frame->r12 = 0x006; frame->r11 = 0x007; frame->r10 = 0x008; frame->r9 = 0x009; frame->r8 = 0x00A; frame->rsi = (uint64_t)argv; frame->rdi = (uint64_t)argc; frame->rbp = 0x00D; frame->rdx = (uint64_t)entryPoint; frame->rcx = 0x00F; frame->rbx = 0x010; frame->rax = 0x011; frame->rip = (uint64_t)&callProcess; frame->cs = 0x008; frame->eflags = 0x202; frame->rsp = (uint64_t)&(frame->base); frame->ss = 0x000; frame->base = 0x000; return frame; } int addThread(process_t * process, thread_t * thread) { int next, current; int index = firstAvailableThreadSpace(process); if(index != THREAD_LIMIT_REACHED) { current = process->currentThread; process->threads[index].thread = thread; next = process->threads[current].next; process->threads[current].next = index; process->threads[index].next = next; return index; } return -1; } int firstAvailableThreadSpace(process_t * process) { int i; for(i = 0; i < MAX_THREADS; i++) { if(process->threads[i].thread == NULL) return i; } return THREAD_LIMIT_REACHED; }
2.8125
3
2024-11-18T21:06:02.467890+00:00
2019-12-24T03:29:14
a9776a038c97c337bb98d622d64c1d45567d0d83
{ "blob_id": "a9776a038c97c337bb98d622d64c1d45567d0d83", "branch_name": "refs/heads/master", "committer_date": "2019-12-24T03:29:14", "content_id": "703754caec3aef27e859cf0465d088fd9b7f8b08", "detected_licenses": [ "MIT" ], "directory_id": "23d891399a44b293ea232cd023fd4861c35050fc", "extension": "c", "filename": "vectorise.c", "fork_events_count": 0, "gha_created_at": "2019-12-24T03:25:25", "gha_event_created_at": "2019-12-24T03:25:26", "gha_language": null, "gha_license_id": "MIT", "github_id": 229862854, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2881, "license": "MIT", "license_type": "permissive", "path": "/code/vectorise.c", "provenance": "stackv2-0083.json.gz:12270", "repo_name": "Neutree/micropython-ulab", "revision_date": "2019-12-24T03:29:14", "revision_id": "c315a571df49a19b843f7dffc300c21ccb7d4edd", "snapshot_id": "25548683ef2dddeac0934e6be432421f39533729", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/Neutree/micropython-ulab/c315a571df49a19b843f7dffc300c21ccb7d4edd/code/vectorise.c", "visit_date": "2020-11-28T16:04:11.925517" }
stackv2
/* * This file is part of the micropython-ulab project, * * https://github.com/v923z/micropython-ulab * * The MIT License (MIT) * * Copyright (c) 2019 Zoltán Vörös */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include "py/runtime.h" #include "py/binary.h" #include "py/obj.h" #include "py/objarray.h" #include "vectorise.h" #ifndef MP_PI #define MP_PI MICROPY_FLOAT_CONST(3.14159265358979323846) #endif mp_obj_t vectorise_generic_vector(mp_obj_t o_in, mp_float_t (*f)(mp_float_t)) { // Return a single value, if o_in is not iterable if(mp_obj_is_float(o_in) || mp_obj_is_integer(o_in)) { return mp_obj_new_float(f(mp_obj_get_float(o_in))); } mp_float_t x; if(MP_OBJ_IS_TYPE(o_in, &ulab_ndarray_type)) { ndarray_obj_t *source = MP_OBJ_TO_PTR(o_in); ndarray_obj_t *ndarray = create_new_ndarray(source->m, source->n, NDARRAY_FLOAT); mp_float_t *dataout = (mp_float_t *)ndarray->array->items; if(source->array->typecode == NDARRAY_UINT8) { ITERATE_VECTOR(uint8_t, source, dataout); } else if(source->array->typecode == NDARRAY_INT8) { ITERATE_VECTOR(int8_t, source, dataout); } else if(source->array->typecode == NDARRAY_UINT16) { ITERATE_VECTOR(uint16_t, source, dataout); } else if(source->array->typecode == NDARRAY_INT16) { ITERATE_VECTOR(int16_t, source, dataout); } else { ITERATE_VECTOR(mp_float_t, source, dataout); } return MP_OBJ_FROM_PTR(ndarray); } else if(MP_OBJ_IS_TYPE(o_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(o_in, &mp_type_list) || MP_OBJ_IS_TYPE(o_in, &mp_type_range)) { // i.e., the input is a generic iterable mp_obj_array_t *o = MP_OBJ_TO_PTR(o_in); ndarray_obj_t *out = create_new_ndarray(1, o->len, NDARRAY_FLOAT); mp_float_t *dataout = (mp_float_t *)out->array->items; mp_obj_iter_buf_t iter_buf; mp_obj_t item, iterable = mp_getiter(o_in, &iter_buf); size_t i=0; while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { x = mp_obj_get_float(item); dataout[i++] = f(x); } return MP_OBJ_FROM_PTR(out); } return mp_const_none; } MATH_FUN_1(acos, acos); MATH_FUN_1(acosh, acosh); MATH_FUN_1(asin, asin); MATH_FUN_1(asinh, asinh); MATH_FUN_1(atan, atan); MATH_FUN_1(atanh, atanh); MATH_FUN_1(ceil, ceil); MATH_FUN_1(cos, cos); MATH_FUN_1(erf, erf); MATH_FUN_1(erfc, erfc); MATH_FUN_1(exp, exp); MATH_FUN_1(expm1, expm1); MATH_FUN_1(floor, floor); MATH_FUN_1(gamma, tgamma); MATH_FUN_1(lgamma, lgamma); MATH_FUN_1(log, log); MATH_FUN_1(log10, log10); MATH_FUN_1(log2, log2); MATH_FUN_1(sin, sin); MATH_FUN_1(sinh, sinh); MATH_FUN_1(sqrt, sqrt); MATH_FUN_1(tan, tan); MATH_FUN_1(tanh, tanh);
2.46875
2
2024-11-18T21:06:02.943141+00:00
2023-06-14T13:20:32
33141614c698d513219a5769b383752eee6ee148
{ "blob_id": "33141614c698d513219a5769b383752eee6ee148", "branch_name": "refs/heads/master", "committer_date": "2023-06-14T13:20:32", "content_id": "977c2fa2d5e4890b0956b8654843c8e5c89aa375", "detected_licenses": [ "ISC" ], "directory_id": "6c8486a6610d80507a356103dbe359f51dd6312e", "extension": "c", "filename": "nsssd-switch.c", "fork_events_count": 5, "gha_created_at": "2018-06-26T00:28:03", "gha_event_created_at": "2020-06-25T22:15:29", "gha_language": "C", "gha_license_id": "ISC", "github_id": 138663994, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13564, "license": "ISC", "license_type": "permissive", "path": "/src/nsssd/nsssd-switch.c", "provenance": "stackv2-0083.json.gz:12658", "repo_name": "skarnet/nsss", "revision_date": "2023-06-14T13:20:32", "revision_id": "abde4759cd42e895ff1b1f2845921a0ab7b15008", "snapshot_id": "0d248df6b7a7c34dd8215cd5e47534c14b097e00", "src_encoding": "UTF-8", "star_events_count": 23, "url": "https://raw.githubusercontent.com/skarnet/nsss/abde4759cd42e895ff1b1f2845921a0ab7b15008/src/nsssd/nsssd-switch.c", "visit_date": "2023-06-24T12:27:31.566442" }
stackv2
/* ISC license. */ #include <stdint.h> #include <stdlib.h> #include <errno.h> #include <skalibs/types.h> #include <skalibs/buffer.h> #include <skalibs/strerr.h> #include <skalibs/sgetopt.h> #include <skalibs/tai.h> #include <skalibs/stralloc.h> #include <skalibs/genalloc.h> #include <nsss/nsssd.h> #include <nsss/nsss-switch.h> #define USAGE "nsssd-switch bitfield1 backend1... \"\" bitfield2 backend2... \"\"" #define dieusage() strerr_dieusage(100, USAGE) #define MAX_BACKENDS 8 static tain tto = TAIN_INFINITE_RELATIVE ; static stralloc storagesa = STRALLOC_ZERO ; static genalloc storagega = GENALLOC_ZERO ; /* We cannot depend on execline so we duplicate functions here */ static unsigned int el_getstrict (void) { static unsigned int strict = 0 ; static int first = 1 ; if (first) { char const *x = getenv("EXECLINE_STRICT") ; first = 0 ; if (x) uint0_scan(x, &strict) ; } return strict ; } static int el_semicolon (char const **argv) { static unsigned int nblock = 0 ; int argc1 = 0 ; nblock++ ; for (;; argc1++, argv++) { char const *arg = *argv ; if (!arg) return argc1 + 1 ; if (!arg[0]) return argc1 ; else if (arg[0] == ' ') ++*argv ; else { unsigned int strict = el_getstrict() ; if (strict) { char fmt1[UINT_FMT] ; char fmt2[UINT_FMT] ; fmt1[uint_fmt(fmt1, nblock)] = 0 ; fmt2[uint_fmt(fmt2, (unsigned int)argc1)] = 0 ; if (strict >= 2) strerr_dief6x(100, "unquoted argument ", arg, " at block ", fmt1, " position ", fmt2) ; else strerr_warnw6x("unquoted argument ", arg, " at block ", fmt1, " position ", fmt2) ; } } } } /* Real code here */ typedef struct backend_s backend_t, *backend_t_ref ; struct backend_s { nsss_switch_t handle ; uint8_t flags : 3 ; uint8_t failed : 1 ; } ; typedef struct handle_s handle_t, *handle_t_ref ; struct handle_s { backend_t tab[MAX_BACKENDS] ; unsigned int n ; } ; void *nsssd_handle_init (void) { static handle_t a = { .n = 0 } ; return &a ; } int nsssd_handle_start (void *handle, char const *const *argv) { static nsss_switch_t const nsss_switch_zero = NSSS_SWITCH_ZERO ; handle_t *a = handle ; char const **args = (char const **)argv ; unsigned int argc = 0 ; while (args[argc]) { backend_t *be = &a->tab[a->n] ; unsigned int bitfield ; int argc1 ; if (!uint0_scan(args[argc++], &bitfield)) dieusage() ; if (!args[argc]) strerr_dief1x(100, "missing block") ; argc1 = el_semicolon(args + argc) ; if (!argc1) strerr_dief1x(100, "empty block") ; if (!args[argc + argc1]) strerr_dief1x(100, "unterminated block") ; args[argc + argc1] = 0 ; be->handle = nsss_switch_zero ; be->flags = 0 ; be->failed = !nsss_switch_startf(&be->handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW, args + argc, 0, 0) ; if (a->n++ >= MAX_BACKENDS) strerr_dief1x(100, "too many defined backends") ; be->flags |= bitfield & 0x7 ; argc += argc1 ; } if (!a->n) strerr_dief1x(100, "no defined backends") ; return 1 ; } void nsssd_handle_end (void *handle) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->n = 0 ; } int nsssd_pwd_start (void *handle) { (void)handle ; return 1 ; } int nsssd_pwd_rewind (void *handle) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; if (nsss_switch_pwd_rewind_g(&a->tab[i].handle, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & 2) return 0 ; } return 0 ; } int nsssd_pwd_get (void *handle, struct passwd *pw) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; storagesa.len = 0 ; errno = 0 ; if (nsss_switch_pwd_get_g(&a->tab[i].handle, pw, &storagesa, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & (errno ? 2 : 4)) return 0 ; } return 0 ; } int nsssd_pwd_getbyuid (void *handle, struct passwd *pw, uid_t uid) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; storagesa.len = 0 ; errno = 0 ; if (nsss_switch_pwd_getbyuid_g(&a->tab[i].handle, pw, &storagesa, uid, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & (errno ? 2 : 4)) return 0 ; } return 0 ; } int nsssd_pwd_getbyname (void *handle, struct passwd *pw, char const *name) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; storagesa.len = 0 ; errno = 0 ; if (nsss_switch_pwd_getbyname_g(&a->tab[i].handle, pw, &storagesa, name, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & (errno ? 2 : 4)) return 0 ; } return 0 ; } void nsssd_pwd_end (void *handle) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return ; else continue ; } tain_add_g(&deadline, &tto) ; if (nsss_switch_pwd_end_g(&a->tab[i].handle, &deadline)) continue ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } } } int nsssd_grp_start (void *handle) { (void)handle ; return 1 ; } int nsssd_grp_rewind (void *handle) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; if (nsss_switch_grp_rewind_g(&a->tab[i].handle, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & 2) return 0 ; } return 0 ; } int nsssd_grp_get (void *handle, struct group *gr) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; storagesa.len = 0 ; genalloc_setlen(char *, &storagega, 0) ; errno = 0 ; if (nsss_switch_grp_get_g(&a->tab[i].handle, gr, &storagesa, &storagega, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & (errno ? 2 : 4)) return 0 ; } return 0 ; } int nsssd_grp_getbygid (void *handle, struct group *gr, gid_t gid) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; storagesa.len = 0 ; genalloc_setlen(char *, &storagega, 0) ; errno = 0 ; if (nsss_switch_grp_getbygid_g(&a->tab[i].handle, gr, &storagesa, &storagega, gid, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & (errno ? 2 : 4)) return 0 ; } return 0 ; } int nsssd_grp_getbyname (void *handle, struct group *gr, char const *name) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; storagesa.len = 0 ; genalloc_setlen(char *, &storagega, 0) ; errno = 0 ; if (nsss_switch_grp_getbyname_g(&a->tab[i].handle, gr, &storagesa, &storagega, name, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & (errno ? 2 : 4)) return 0 ; } return 0 ; } int nsssd_grp_getlist (void *handle, char const *user, gid_t *gids, size_t n, size_t *r) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; storagesa.len = 0 ; errno = 0 ; if (nsss_switch_grp_getlist_g(&a->tab[i].handle, user, gids, n, r, &storagesa, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & (errno ? 2 : 4)) return 0 ; } return 0 ; } void nsssd_grp_end (void *handle) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return ; else continue ; } tain_add_g(&deadline, &tto) ; if (nsss_switch_grp_end_g(&a->tab[i].handle, &deadline)) continue ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } } } int nsssd_shadow_start (void *handle) { (void)handle ; return 1 ; } int nsssd_shadow_rewind (void *handle) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; if (nsss_switch_shadow_rewind_g(&a->tab[i].handle, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & 2) return 0 ; } return 0 ; } int nsssd_shadow_get (void *handle, struct spwd *sp) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; storagesa.len = 0 ; errno = 0 ; if (nsss_switch_shadow_get_g(&a->tab[i].handle, sp, &storagesa, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & (errno ? 2 : 4)) return 0 ; } return 0 ; } int nsssd_shadow_getbyname (void *handle, struct spwd *sp, char const *name) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return 0 ; else continue ; } tain_add_g(&deadline, &tto) ; storagesa.len = 0 ; errno = 0 ; if (nsss_switch_shadow_getbyname_g(&a->tab[i].handle, sp, &storagesa, name, &deadline)) return 1 ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } if (a->tab[i].flags & (errno ? 2 : 4)) return 0 ; } return 0 ; } void nsssd_shadow_end (void *handle) { handle_t *a = handle ; for (unsigned int i = 0 ; i < a->n ; i++) { tain deadline ; if (a->tab[i].failed) { if (a->tab[i].flags & 1) return ; else continue ; } tain_add_g(&deadline, &tto) ; if (nsss_switch_pwd_end_g(&a->tab[i].handle, &deadline)) continue ; if (errno == ETIMEDOUT) { nsss_switch_end(&a->tab[i].handle, NSSS_SWITCH_PWD | NSSS_SWITCH_GRP | NSSS_SWITCH_SHADOW) ; a->tab[i].failed = 1 ; } } } int main (int argc, char const *const *argv) { PROG = "nsssd-switch" ; { subgetopt l = SUBGETOPT_ZERO ; unsigned int t = 0 ; for (;;) { int opt = subgetopt_r(argc, argv, "t:", &l) ; if (opt == -1) break ; switch (opt) { case 't' : if (!uint0_scan(l.arg, &t)) dieusage() ; break ; default : dieusage() ; } } argc -= l.ind ; argv += l.ind ; if (t) tain_from_millisecs(&tto, t) ; } return nsssd_main(argv) ; }
2.140625
2
2024-11-18T21:06:03.132265+00:00
2016-01-14T20:55:42
c231ebeadd653efbc1c2b2e58d36fac70161fc80
{ "blob_id": "c231ebeadd653efbc1c2b2e58d36fac70161fc80", "branch_name": "refs/heads/master", "committer_date": "2016-01-14T20:55:42", "content_id": "43a6d1f38416025cbe5801339f13f4fa06dd151c", "detected_licenses": [ "MIT" ], "directory_id": "a1f35e9771909ac47ee908081a06b41e5d8a7bdd", "extension": "h", "filename": "object.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 37295043, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3485, "license": "MIT", "license_type": "permissive", "path": "/interpreter/imp/object.h", "provenance": "stackv2-0083.json.gz:12786", "repo_name": "dasmithii/imp", "revision_date": "2016-01-14T20:55:42", "revision_id": "a31cc9ebccc36dcfb5c58f39e5a8e9a8c3c6b4ab", "snapshot_id": "067ca9fa4d0988391a5b4589bd9ddfd2e9d26281", "src_encoding": "UTF-8", "star_events_count": 20, "url": "https://raw.githubusercontent.com/dasmithii/imp/a31cc9ebccc36dcfb5c58f39e5a8e9a8c3c6b4ab/interpreter/imp/object.h", "visit_date": "2021-01-22T20:59:46.427734" }
stackv2
// Imp is a uni-typed/duck-typed language. Everything is // an object, and objects are nothing more than // collections of nested objects (and internal data, in // some cases). // // Objects are collections of slots, essentially, slots // being key-value pairs. // // There are three types of slots: // 1. regular (e.g. objectName:slotName) // 2. special (e.g. objectName:_slotName) // 3. internal (e.g. objectName:__slotName) // // Note that slot names imply their types with prefixed // underscores. // // 1. Regular slots are programmer-defined variables and // are best understood in contrast with special slots. // // 2. Special slots may be activated by the interpreter // for various reasons. _mark, for example, would be // activated during the mark phase of mark & sweep // garbage collection. Another example is _collect, // a destructor of sorts. Others include _each and // _onImport. // // Regular slots, except for #, are never accessed by // the interpreter. // // 3. Internal slots are not mapped to imp object // pointers, but instead, raw pointers. They have no // standard structure. Avoid messing with them // whenever possible. // // The garbage collector, by default, will free // internal pointers. Keep this in mind if you are // wrapping C functions or libraries. Also, always // use utilities from builtin/general.h and c.h; // never interact with internal slots directly. #ifndef IMP_OBJECT #define IMP_OBJECT #include <stdbool.h> #include <stdlib.h> typedef struct { char *key; void *data; } iSlot; typedef struct iObject { iSlot *slots; int slotCount; bool gc_mark; unsigned short refcount; } iObject; //// management void iObject_init(iObject *self); void iObject_clean(iObject *self); void iObject_free(iObject *self); //// slot methods iObject *iSlot_object(iSlot *self); void *iSlot_data(iSlot *self); bool iSlot_isPrimitive(iSlot *self); void iSlot_clean(iSlot *self); void iSlot_setFunction(iSlot *self, iObject*(*f)(int argc, iObject *argv)); //// garbage collection void iObject_mark(iObject *self); void iObject_unmark(iObject *self); void iObject_reference(iObject *self); void iObject_unreference(iObject *self); int iObject_referenceCount(iObject *self); //// slot access void iObject_putKeyShallow(iObject *self, char *key); void iObject_putShallow(iObject *self, char *key, iObject *value); void iObject_putDeep(iObject *self, char *key, iObject *value); void iObject_putDataShallow(iObject *self, char *key, void *value); void iObject_putDataDeep(iObject *self, char *key, void *value); void iObject_remShallow(iObject *self, char *key); iSlot *iObject_getSlotShallow(iObject *self, char *key); iSlot *iObject_getSlotDeep(iObject *self, char *key); iObject *iObject_getShallow(iObject *self, char *key); iObject *iObject_getDeep(iObject *self, char *key); void *iObject_getDataShallow(iObject *self, char *key); void *iObject_getDataDeep(iObject *self, char *key); bool iObject_hasKeyShallow(iObject *self, char *key); bool iObject_hasKeyDeep(iObject *self, char *key); iObject *iObject_rootPrototype(iObject *self); iObject *iObject_prototype(iObject *self); //// miscellaneous bool iObject_isValid(iObject *self); bool iSlot_isValid(iSlot *self); void iObject_print(iObject *self); bool iObject_canBeActivated(iObject *self); bool iObject_hasMethod(iObject *self, char *name); bool iObject_hasSpecialMethod(iObject *self, char *name); #endif
2.015625
2
2024-11-18T21:06:03.254140+00:00
2017-05-18T13:44:46
b570f9e5092f89579ebaffd09573b57d24cd7094
{ "blob_id": "b570f9e5092f89579ebaffd09573b57d24cd7094", "branch_name": "refs/heads/master", "committer_date": "2017-05-18T13:44:46", "content_id": "0947e3a58147c7b2d2675258dfde0efadbe4912f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "dab8ccd3911efa09c8e8ee3ad2ca305765e85c8c", "extension": "c", "filename": "SymmetrizeCandidateSet.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 88631436, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 498, "license": "Apache-2.0", "license_type": "permissive", "path": "/cbLKH/SRC/SymmetrizeCandidateSet.c", "provenance": "stackv2-0083.json.gz:12916", "repo_name": "fcimeson/cbTSP", "revision_date": "2017-05-18T13:44:46", "revision_id": "aaf102c7a6a9f3b36a8b5f0c62570c40409ec7c8", "snapshot_id": "32b90cf56cf6b5615674b0f852e99b05a22d219e", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/fcimeson/cbTSP/aaf102c7a6a9f3b36a8b5f0c62570c40409ec7c8/cbLKH/SRC/SymmetrizeCandidateSet.c", "visit_date": "2021-01-19T21:15:10.325766" }
stackv2
#include "LKH.h" /* * The SymmetrizeCandidateSet function complement the candidate set such * that every candidate edge is associated with both its two end nodes. */ void SymmetrizeCandidateSet() { Node *From, *To; Candidate *NFrom; From = FirstNode; do { for (NFrom = From->CandidateSet; NFrom && (To = NFrom->To); NFrom++) AddCandidate(To, From, NFrom->Cost, NFrom->Alpha); } while ((From = From->Suc) != FirstNode); ResetCandidateSet(); }
2.390625
2
2024-11-18T21:06:03.321927+00:00
2021-11-23T20:45:44
88b96efc50769f4f52fa5cb1350b1172752e81d8
{ "blob_id": "88b96efc50769f4f52fa5cb1350b1172752e81d8", "branch_name": "refs/heads/master", "committer_date": "2021-11-23T20:45:44", "content_id": "508d880fe73681023d9caf45f20d2aa06549a3f1", "detected_licenses": [ "MIT" ], "directory_id": "d6bda5b212245acf83e55d08b48e673eafb92333", "extension": "c", "filename": "tdc-tests.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 187252360, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2966, "license": "MIT", "license_type": "permissive", "path": "/host_software/tdc-tests.c", "provenance": "stackv2-0083.json.gz:13045", "repo_name": "miree/dTOT", "revision_date": "2021-11-23T20:45:44", "revision_id": "9875f0530394f3cb919b89550a430342e55a24e6", "snapshot_id": "37d47ba381c8bafb623b7475d51963acd8608212", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/miree/dTOT/9875f0530394f3cb919b89550a430342e55a24e6/host_software/tdc-tests.c", "visit_date": "2021-11-29T07:11:04.814240" }
stackv2
#include "tdc_control.h" #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> void write_raw_event(int fd, int channel, int timestamp, unsigned char sample) { unsigned char data[5] = { 0x80 | ((channel&0x7)<<4) | (sample>>4), 0x00 | (( sample&0xf)<<3) | ((timestamp>>21)&0x7), 0x00 | ((timestamp>>14)&0x7f), 0x00 | ((timestamp>> 7)&0x7f), 0x00 | ((timestamp>> 0)&0x7f) }; write(fd, data, 5); } char* sample_to_text(unsigned char ch, unsigned long time, int edge) { static char str_out[9] = {0,}; for(int i = 0; i < 8; ++i) { str_out[i] = (ch&0x80?'-':'_'); ch <<= 1; } int idx = time%8; if (edge) { str_out[idx]='/'; } else { str_out[idx]='\\'; } return str_out; } void write_nanosecond_event(int fd, int channel, long delta_t, int reset) { static long int time[TDC_N_CHANNELS] = {0,}; // time in units of 8ns static int level[TDC_N_CHANNELS] = {0,}; if (reset) { for (int ch = 0; ch < TDC_N_CHANNELS; ++ch) { level[ch] = time[ch] = 0; } } time[channel] += delta_t; unsigned char sample = 0xff>>(time[channel]%8); if (level[channel]) { sample = ~sample; } // handle overflow while (time[channel] >= 0x8000000) { if (time[channel] > 0x8000000) { write_raw_event(fd, channel, 0, level[channel]?0xff:0x00); } time[channel] -= 0x8000000; } //printf("write sample %s\n", sample_to_text(sample, sample, !level[channel])); write_raw_event(fd, channel, time[channel]/8, sample); level[channel] = !level[channel]; } void pulser(int fd, int channel, int period, int pulse_length, int n_pulses) { for (int i = 0; i < n_pulses; ++i) { write_nanosecond_event(fd, channel, period-pulse_length, i==0); write_nanosecond_event(fd, channel, pulse_length, 0); int other_channel = channel; while (other_channel == channel) { other_channel = rand()%TDC_N_CHANNELS; } //write_nanosecond_event(fd, other_channel, rand()%period, 0); write_raw_event(fd, other_channel, rand()%0xfffffff, rand()%0xff); } } void run_pulser_test(int channel, int pulse_length, int n_pulses) { // create test data int fd = open("testdata.raw", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); printf("fd=%d\n",fd); pulser(fd, channel, 10000001, pulse_length, n_pulses); close(fd); tdc_t *tdc = tdc_open("testdata.raw"); tdc_event_t event; for(;;) { event = tdc_next_event(tdc); if (event.channel == -1) { break; } printf("%d %d %20ld sample=0x%02x:%s dt=%ld\n", event.channel, event.edge, event.time, event.sample, sample_to_text(event.sample, event.time, event.edge), event.dt); if (event.edge == TDC_EDGE_FALLING && event.channel == channel) { assert(event.dt == pulse_length); } } tdc_close(tdc); } int main() { for (int ch = 0; ch < TDC_N_CHANNELS; ++ch) { run_pulser_test(ch, 101, 1000); } printf("All tests passed!\n"); return 0; }
2.5
2
2024-11-18T21:06:07.140041+00:00
2023-07-19T02:42:12
03eefee3d89eb6b1ad9e025e3acb3820e803ee65
{ "blob_id": "03eefee3d89eb6b1ad9e025e3acb3820e803ee65", "branch_name": "refs/heads/master", "committer_date": "2023-07-19T02:42:12", "content_id": "513a30de90d96c15759a3503246fa6f10e6386df", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3ac08f55efef77a3b6fb8df086793462bc03cb56", "extension": "h", "filename": "regtestHeader.h", "fork_events_count": 20, "gha_created_at": "2016-10-23T03:54:58", "gha_event_created_at": "2023-07-19T02:42:35", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 71680484, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 746, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/api/c/examples/libfreenect/regtestHeader.h", "provenance": "stackv2-0083.json.gz:14075", "repo_name": "OpenISS/OpenISS", "revision_date": "2023-07-19T02:42:12", "revision_id": "3bb6e4507f3876cf0b5587be4099fa92f4e19102", "snapshot_id": "85ad89c93199e41b51752cb2b469199622f843e4", "src_encoding": "UTF-8", "star_events_count": 20, "url": "https://raw.githubusercontent.com/OpenISS/OpenISS/3bb6e4507f3876cf0b5587be4099fa92f4e19102/src/api/c/examples/libfreenect/regtestHeader.h", "visit_date": "2023-07-23T08:16:04.312488" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "libfreenect.h" #include "libfreenect_sync.h" FILE *open_dump(const char *filename) { FILE* fp = fopen(filename, "w"); if (fp == NULL) { fprintf(stderr, "Error: Cannot open file [%s]\n", filename); exit(1); } printf("%s\n", filename); return fp; } void dump_depth(FILE *fp, void *data, unsigned int width, unsigned int height) { fprintf(fp, "P5 %u %u 65535\n", width, height); fwrite(data, width * height * 2, 1, fp); } void dump_rgb(FILE *fp, void *data, unsigned int width, unsigned int height) { fprintf(fp, "P6 %u %u 255\n", width, height); fwrite(data, width * height * 3, 1, fp); } void no_kinect_quit(void) { fprintf(stderr, "Error: Kinect not connected?\n"); exit(1); }
2.421875
2
2024-11-18T21:06:07.669056+00:00
2015-08-20T22:21:19
ffbf9e671496afe0ffd4704ade23a30462e7d982
{ "blob_id": "ffbf9e671496afe0ffd4704ade23a30462e7d982", "branch_name": "refs/heads/master", "committer_date": "2015-08-20T22:21:19", "content_id": "bba6d8fe1fb335fb3ac4c8f217f38c6af1e01379", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "76819d7ec89b0d59cc54c0e554ed176f6668ffa2", "extension": "c", "filename": "ss_zstdfilter.test.c", "fork_events_count": 0, "gha_created_at": "2015-02-02T15:34:03", "gha_event_created_at": "2015-02-02T15:34:06", "gha_language": "C", "gha_license_id": null, "github_id": 30193672, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2471, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/test/unit/ss_zstdfilter.test.c", "provenance": "stackv2-0083.json.gz:14589", "repo_name": "clibs/sophia", "revision_date": "2015-08-20T22:21:19", "revision_id": "2b66cc065e96d8a7971056e87b617395b2961ca6", "snapshot_id": "8099ecff20e791c2b03d5c7cae9c39fee9d89cc9", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/clibs/sophia/2b66cc065e96d8a7971056e87b617395b2961ca6/test/unit/ss_zstdfilter.test.c", "visit_date": "2021-01-16T22:43:19.753961" }
stackv2
/* * sophia database * sphia.org * * Copyright (c) Dmitry Simonenko * BSD License */ #include <sophia.h> #include <libss.h> #include <libsf.h> #include <libsr.h> #include <libsv.h> #include <libso.h> #include <libst.h> static void ss_zstdfilter_compress_decompress(void) { char text[] = "The Early English Text Society is a text publication society dedicated to the" "reprinting of early English texts, especially those only available in manuscript." "Most of its volumes are in Middle English and Old English. It was founded in " "England in 1864 by Frederick James Furnivall. Its stated goal in a report of the " "first year of their existence was \"on the one hand, to print all that is most " "valuable of the yet unprinted MSS. in English, and, on the other, to re-edit " "and reprint all that is most valuable in printed English books, which from their " "scarcity or price are not within the reach of the student of moderate means.\"[1]" "It is known for being the first to print many English " "manuscripts, including Cotton Nero A.x, which contains Pearl, Sir Gawain and the " "Green Knight, and other poems. By its own count, the Society has published 344" "volumes. Famous members of the society when it was formed in 1864 include " "Furnivall himself, Alfred Tennyson (poet laureate), Warren de la Rue (inventor " "of the lightbulb), Richard Chenevix Trench (Irish ecclesiastic), Stephen Austin " "(a Hertford-based printer), Edith Coleridge (granddaughter of Samuel Taylor " "Coleridge), and others."; ssbuf compressed; ss_bufinit(&compressed); ssfilter f; t( ss_filterinit(&f, &ss_zstdfilter, &st_r.a, SS_FINPUT) == 0 ); t( ss_filterstart(&f, &compressed) == 0 ); t( ss_filternext(&f, &compressed, text, sizeof(text) - 1) == 0 ); t( ss_filtercomplete(&f, &compressed) == 0 ); t( ss_filterfree(&f) == 0 ); ssbuf decompressed; ss_bufinit(&decompressed); t( ss_bufensure(&decompressed, &st_r.a, sizeof(text)) == 0 ); t( ss_filterinit(&f, &ss_zstdfilter, &st_r.a, SS_FOUTPUT) == 0 ); t( ss_filternext(&f, &decompressed, compressed.s, ss_bufused(&compressed)) == 0 ); t( ss_filterfree(&f) == 0 ); t( memcmp(text, decompressed.s, sizeof(text) - 1) == 0 ); ss_buffree(&compressed, &st_r.a); ss_buffree(&decompressed, &st_r.a); } stgroup *ss_zstdfilter_group(void) { stgroup *group = st_group("sszstdfilter"); st_groupadd(group, st_test("compress_decompress", ss_zstdfilter_compress_decompress)); return group; }
2
2
2024-11-18T21:06:07.852590+00:00
2021-05-27T07:28:37
4d9ad0652899bce30d8accc80aa90ff128f2b728
{ "blob_id": "4d9ad0652899bce30d8accc80aa90ff128f2b728", "branch_name": "refs/heads/master", "committer_date": "2021-05-27T07:28:37", "content_id": "a56c8a9d3ef2481b9040ce6b2fa43af49ea1ba60", "detected_licenses": [ "MIT" ], "directory_id": "ad869d0e1353009d2fdc5b5541aee958da9f09a3", "extension": "c", "filename": "JsonBoolean.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 639, "license": "MIT", "license_type": "permissive", "path": "/src/Json/value/JsonBoolean.c", "provenance": "stackv2-0083.json.gz:14848", "repo_name": "gkcity/tiny-core", "revision_date": "2021-05-27T07:28:37", "revision_id": "d8c5e2f33ac5a37e7275b952f2546254301570af", "snapshot_id": "573c3cd2f8eb63ed6c47ad005675d0b118d39fe2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gkcity/tiny-core/d8c5e2f33ac5a37e7275b952f2546254301570af/src/Json/value/JsonBoolean.c", "visit_date": "2023-05-06T15:21:33.886766" }
stackv2
/** * Copyright (C) 2013-2015 * * @author jxfengzi@gmail.com * @date 2013-11-19 * * @file JsonBoolean.c * * @remark * */ #include <tiny_malloc.h> #include <tiny_log.h> #include "JsonBoolean.h" #define TAG "JsonBoolean" JsonBoolean * JsonBoolean_New(bool value) { JsonBoolean *thiz = NULL; do { thiz = (JsonBoolean *) tiny_malloc(sizeof(JsonBoolean)); if (thiz == NULL) { LOG_E(TAG, "tiny_malloc FAILED!"); break; } thiz->value = value; } while (0); return thiz; } void JsonBoolean_Delete(JsonBoolean *thiz) { tiny_free(thiz); }
2.3125
2
2024-11-18T21:06:08.279442+00:00
2019-02-13T14:21:46
fe550aa9cd20c7b7eeab71ae64969ad3a582bef7
{ "blob_id": "fe550aa9cd20c7b7eeab71ae64969ad3a582bef7", "branch_name": "refs/heads/master", "committer_date": "2019-02-13T14:21:46", "content_id": "4d3a76b79ed0d10f2633d1ce59f6c3d41704ad61", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "474acfcc41fc7ad6bdff11cc26116afac1cdffb6", "extension": "c", "filename": "pickprimes.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 168935888, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 18760, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/classpoly_v1.0.2/pickprimes.c", "provenance": "stackv2-0083.json.gz:15233", "repo_name": "ph4r05/class-poly", "revision_date": "2019-02-13T14:21:46", "revision_id": "8ca71f3f291767dd917bd53362edd6e57acd3baa", "snapshot_id": "45258ea43187f56848405e3c2f83a94b034cff88", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ph4r05/class-poly/8ca71f3f291767dd917bd53362edd6e57acd3baa/src/classpoly_v1.0.2/pickprimes.c", "visit_date": "2020-04-20T15:37:01.464901" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <limits.h> #include <string.h> #include <time.h> #include <stdint.h> #include "iqclass.h" #include "mpzutil.h" #include "torcosts.h" #include "tecurve.h" #include "findcurve.h" #include "pickprimes.h" #include "bitmap.h" #include "cstd.h" /* Copyright 2012 Andrew V. Sutherland This file is part of classpoly. classpoly 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. classpoly 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 classpoly. If not, see <http://www.gnu.org/licenses/>. */ #define MAX_V 1200 // this really should be consistent with PHI_MAX_V #define MAX_VK 5 static int v_primorials[MAX_VK+1] = { 1, 2, 6, 30, 210, 2310 }; static int32_t *sieve_primes; static int32_t *sieve_sqrts; static int sieve_pcnt, sieve_pmax; static long minL = 3; double split_prime_rating (long p, long t, int *ptwist, int *ptor, int *ps2, int *pt3); void setup_sieve_primes (long maxL, long D) { prime_enum_ctx_t *ctx; double x; int n; int32_t a; register unsigned p; if ( maxL <= minL ) { err_printf ("Invalid maxL=%ld in setup_sieve_primes, minL=%ld\n", maxL, minL); exit (0); } x = maxL; x = x/(log(x)) * (1.0 + 3.0/(2.0*log(x))); // pi(x) < x/log(x) * (1+3/(2log(x))) for x >= 59 (Shoup p.91) n = (int)x; if ( n < 17 ) n = 17; if ( ! sieve_primes ) { sieve_pmax = n/2+2*sqrt(n)+100; // assume about half won't yield a square root sieve_primes = malloc(sieve_pmax*sizeof(*sieve_primes)); sieve_sqrts = malloc(sieve_pmax*sizeof(*sieve_sqrts)); dbg_printf ("sieve_primes malloc %ld bytes\n", sieve_pmax*(sizeof(*sieve_primes)+sizeof(*sieve_sqrts))); } bitmap_alloc(maxL); ctx = fast_prime_enum_start (minL,maxL,0); for ( ; (p = fast_prime_enum(ctx)) ; ) { if ( sieve_pcnt > n ) { err_printf ("Fatal error, pi(x) upper bound failed %d > %d!\n", sieve_pcnt, n); exit (0); } a = (int32_t)i_sqrt_modprime (D,p); if ( a < 0 && p > MAX_V ) continue; if ( sieve_pcnt >= sieve_pmax ) { sieve_pmax = (3*sieve_pmax)/2; sieve_primes = realloc(sieve_primes, sieve_pmax*sizeof(*sieve_primes)); sieve_sqrts = realloc(sieve_sqrts, sieve_pmax*sizeof(*sieve_sqrts)); dbg_printf ("sieve_primes realloc %ld bytes\n", sieve_pmax*(sizeof(*sieve_primes)+sizeof(*sieve_sqrts))); } sieve_primes[sieve_pcnt] = (int32_t)p; sieve_sqrts[sieve_pcnt] = a; sieve_pcnt++; } fast_prime_enum_end(ctx); minL = maxL; dbg_printf ("sieve prime count %d, max=%d, maxL=%ld\n", sieve_pcnt, sieve_primes[sieve_pcnt-1], maxL); } void free_sieve_primes (void) { if ( sieve_primes ) { info_printf ("sieve_primes used %ld bytes\n", sieve_pmax*(sizeof(*sieve_primes)+sizeof(*sieve_sqrts))); free(sieve_primes); free(sieve_sqrts); sieve_primes = 0; sieve_sqrts = 0; sieve_pcnt = sieve_pmax = 0; minL = 3; } } // This is ridiculously slow and is implemented only to prove this fact, and as a sanity check int pick_primes_cornacchia (long *plist, int *tlist, int *vlist, int maxn, long D, long h, double bits) { static mpz_t p, t, v, d; static int init; register double pbits; register int n; if ( ! init ) { mpz_init(p); mpz_init(t); mpz_init(v); mpz_init(d); init = 1; } mpz_set_ui(d,-D); mpz_set_ui(p,-D/4-1); for ( n = 0, pbits = 0.0 ; pbits < bits ; ) { if ( n >= maxn ) { err_printf ("maxn=%d is too small in pick_primes, D=%ld, bits=%f!\n", maxn, D, bits); exit (0); } mpz_nextprime(p,p); if ( mpz_cornacchia4 (t, v, d, p) ) { if ( ! mpz_sgn(t) ) continue; plist[n] = mpz_get_ui(p); tlist[n] = mpz_get_ui(t); vlist[n] = mpz_get_ui(v); pbits += log2(plist[n]); n++; } } return n; } struct split_prime_struct { long p; int32_t t,v; double r; // we could save these values for use by findcurve, but currently we don't bother char tor; char twist; char t3_flag; char s2_flag; }; int split_prime_cmp (const void *a, const void *b) { struct split_prime_struct *p1, *p2; p1 = (struct split_prime_struct *)a; p2 = (struct split_prime_struct *)b; if ( p1->r > p2->r ) return 1; if ( p1->r < p2->r ) return -1; if ( p1->v > p2->v ) return 1; // should use smaller p, but for consistency use v as tiebreaker if ( p1->v < p2->v ) return -1; return 0; } #define SZ_FACTOR 2 int pick_primes (long **pplist, int **ptlist, int **pvlist, long D, long h, double bits, int pfilter, long ellfilter) { struct split_prime_struct *split_primes; time_t start, end; long split_pcnt; double pbits,r,Dbits; long t[MAX_V+1], m[MAX_V+1], wts[MAX_V+1], maxL, a0; double vxb[MAX_VK+1]; int torcnts[40]; int twist,tor,s2,t3; long maxv, maxp; register long a, L, C, N, p, q; register long i,n,v; // compute bounds per lemma in the appendix of "Computing Hilbert Class Polynomials with the CRT" for ( vxb[0] = 1.0, i = 1 ; i <= MAX_VK ; i++ ) vxb[i] = vxb[i-1]*(1.0+2.0/ui_small_prime(i)); /* We assume here that D is fundamental, but this code works reasonably well even when this is not true. */ // Compute wts[v] = H(-v^2D) = sum_{u|v} h(v^2D) = sum_{u|v} h * prod_{p|u}(1-(D/p)) where (D/p) is the Kronecker symbol for ( v = 1 ; v <= MAX_V ; v++ ) wts[v] = h; // Here we take advantage of the fact that H(-v^2D) is multiplicative for ( p = 2 ; p <= MAX_V ; p = ui_next_prime(p) ) { n = p-kronecker_p(D,p); for ( q = p ; q <= MAX_V ; q *= p ) { for ( v = q ; v <= MAX_V ; v += q ) { if ( ! (v%(p*q)) ) continue; wts[v] *= (q -1)/(p-1)*n+1; } } } // Adjust for unit count in cl(D) when D_0=-3 or -4. Round up to get correct count of #curves with a given trace (note that H(3*v^2) and H(4*v^2) are not integers). // Here we do need need to handle the case that D is not fundamental to get the correct value of D_0 v = discriminant_test(D); if ( ! v ) { err_printf ("Invalid disciminant %ld in pick_primes_sieve!\n", D); exit (0); } if ( D/(v*v) == -3 ) { for ( i = 1 ; i <= MAX_V ; i++ ) wts[i] = ui_ceil_ratio(wts[i],3); } else if ( D/(v*v) == -4 ) { for ( i = 1 ; i <= MAX_V ; i++ ) wts[i] = ui_ceil_ratio(wts[i],2); } maxL = (long)sqrt(-D*log(-D)) + 1; if ( maxL < 100 ) maxL = 97; setup_sieve_primes(maxL,D); bitmap_alloc(maxL); split_pcnt = (long) (SZ_FACTOR*bits/log2(-D) + 1); split_primes = malloc(split_pcnt*sizeof(*split_primes)); dbg_printf ("split_pcnt=%ld, split_primes malloced %ld bytes\n", split_pcnt, split_pcnt*sizeof(*split_primes)); pbits = 0.0; n = 0; C = SZ_FACTOR*(-D/h)/4+2; // set initial curve count bound (twice the min for the least prime) Dbits = log2(-D); for ( v = 1 ; v < MAX_V ; v++ ) { if ( Dbits + 2*log2(v) > 60 ) break; switch ( (v*v*D)&0x7 ) { case 0: if ( (pfilter&IQ_FILTER_1MOD4) ) { t[v] = 0; } else { t[v] = 2; m[v] = 4; } break; case 5: t[v] = 1; m[v] = 2; break; case 4: t[v] = 4; m[v] = 4; break; default: t[v] = 0; } if ( ellfilter>1 && ui_gcd(v,ellfilter) > 1 ) t[v]=0; if ( (pfilter&IQ_FILTER_1MOD3) && !(v%3) ) t[v] = 0; } while ( v < MAX_V ) t[v++] = 0; maxv=maxp=0; start = clock(); for(;;) { if ( ui_len(C) > 60 ) { err_printf("Found %ld primes with %f bits up to C=%ld for D=%ld, giving up\n", n, pbits, C, D); exit(0); } for ( v = 1 ; v <= MAX_V ; v++ ) { if ( ! t[v] ) continue; for ( i = 1 ; v_primorials[i] <= v; i++ ); i--; if ( (-v*D)/(4*vxb[i]*h) > C ) continue; if ( v==MAX_V ) { if ( pbits < bits ) { err_printf ("Need to increase MAX_V, pfilter=%d, v=%ld, D=%ld, C=%ld, vxb=%f\n", pfilter, v, D, C, vxb[i]); exit (0); } else { break; } } if ( ui_len(C)+ui_len(wts[v]) > 60 ) continue; // avoid overflow here N = C*wts[v]; if ( 2*ui_len(v)+ui_len(-D) > 62 ) continue; // watch out for overflow here if ( -v*v*D >= 4*N ) continue; L = sqrt(4*N)+1; while( L >= sieve_primes[sieve_pcnt-1] ) { maxL=(3*maxL)/2; setup_sieve_primes (maxL,D); } for ( i = 0 ; ; i++ ) { p = sieve_primes[i]; if ( p > L ) break; a = sieve_sqrts[i]; if (! (v%p) ) a = 0; if ( a < 0 ) continue; a = ui_mod(v*a,p); a0 = a; if ( a < t[v] ) a += p*((t[v]-a)/p); if ( a*a-v*v*D != p && a < L ) bitmap_set(a); for ( a += p ; a < L ; a+= p ) bitmap_set(a); if ( ! a0 ) continue; a = p-a0; if ( a < t[v] ) a += p*((t[v]-a)/p); if ( a*a-v*v*D != p && a < L ) bitmap_set(a); for ( a += p ; a < L ; a += p ) bitmap_set(a); } /* we could speed up the loop below by using, say, a 48 wheel that takes into account the mod4 and mod3 filters, but it probably won't make much difference. */ for ( ; t[v] < L ; t[v] += m[v] ) { p = (t[v]*t[v]-v*v*D)>>2; if ( p < MIN_CRT_PRIME ) continue; if ( p > N ) break; if ( (pfilter&IQ_FILTER_1MOD4) && (p&0x3)==1 ) continue; if ( (pfilter&IQ_FILTER_1MOD3) && (p%3)==1 ) continue; if ( bitmap_test(t[v]) ) continue; // if ( !(p&1) ) continue; // if ( ui_gcd(614889782588491410UL, p) > 1 ) continue; // if ( ! ui_is_prime (p) ) { printf ("Sieve error, p=%ld for t=%d, D=%ld is not prime!\n", p, t[v], D); exit (0); } // if ( 4*p != t[v]*t[v] - v*v*D ) { printf ("Sieve error, 4*%ld != %d^2 - %ld \n", p, t[v], D); exit (0); } split_primes[n].p = p; split_primes[n].t = t[v]; split_primes[n].v = v; r = split_prime_rating_new(p,t[v],&twist,&tor,&s2,&t3); split_primes[n].tor = tor; split_primes[n].twist = twist; split_primes[n].s2_flag = s2; split_primes[n].t3_flag = t3; split_primes[n].r = (r*p)/wts[v]; /* { ff_t f[4]; long cnt,totcnt,msecs; int j; puts(""); printf ("Relative rating for p=%ld t=%ld is r=%f, using tor=%d, s2=%x, t3=%d, twist=%d\n", p, t[v], r, tor, s2, t3, twist); printf ("r/rho = %.0f v=%d, wts[v]=%d\n", split_primes[n].r, v, wts[v]); for ( j = 0;j < 3 ; j++ ) { ff_setup_ui(p); start = clock(); totcnt = 0; for ( i = 0 ; i < 10 ; i++ ) { findcurve (f, t[v], FINDCURVE_NOFILTER, &cnt); totcnt += cnt; } end = clock(); printf ("NO_FILTER: ave cnt = %7ld, ave time %5.1f msecs\n", totcnt/10, (double)delta_msecs(start,end)/10.0); msecs = delta_msecs(start,end); start = clock(); totcnt = 0; for ( i = 0 ; i < 10 ; i++ ) { findcurve (f, t[v], 0, &cnt); totcnt += cnt; } end = clock(); printf (" FILTER: ave cnt = %7ld, ave time %5.1f msecs, ratio %f (vs %f)\n", totcnt/10, (double)delta_msecs(start,end)/10.0, (double)delta_msecs(start,end)/msecs, r); } } */ pbits += log2(p); if ( p > maxp ) maxp=p; if ( v > maxv ) maxv = v; n++; if ( n >= split_pcnt ) { split_pcnt = (3*split_pcnt)/2; dbg_printf ("split_primes reallocing %ld bytes\n", split_pcnt*sizeof(*split_primes)); split_primes = realloc(split_primes,split_pcnt*sizeof(*split_primes)); dbg_printf ("split_primes realloc %ld bytes\n", split_pcnt*sizeof(*split_primes)); } } bitmap_clear(L); if ( n >= split_pcnt ) break; } if ( pbits >= SZ_FACTOR*bits ) break; C = (3*C)/2; } free_sieve_primes(); bitmap_free(); end = clock(); info_printf ("sieved %ld split primes up to z=%ld obtaining a total of %f > %f bits, maxp=%ld, maxv=%ld %ld msecs\n", n, C, pbits, bits, maxp, maxv, delta_msecs(start,end)); qsort(split_primes,n,sizeof(*split_primes),split_prime_cmp); for ( i = 0, pbits = 0.0 ; i < n && pbits < bits ; i++ ) pbits += log2(split_primes[i].p); if ( pbits < bits ) { printf ("error, didn't get the expected number of bits\n"); exit (0); } n = i; *pplist = malloc(n*sizeof(**pplist)); if ( ptlist ) *ptlist = malloc (n*sizeof(**ptlist)); if ( pvlist ) *pvlist = malloc(n*sizeof(**pvlist)); for ( i = 0 ; i < 40 ; i++ ) torcnts[i] = 0; for ( i = 0 ; i < n ; i++ ) { (*pplist)[i] = split_primes[i].p; if ( ptlist ) (*ptlist)[i] = split_primes[i].t; if ( pvlist ) (*pvlist)[i] = split_primes[i].v; torcnts[(int)split_primes[i].tor]++; //split_prime_rating_new(split_primes[i].p,split_primes[i].t,&twist,&tor,&s2,&t3); //out_printf("%d) %ld, t=%d, v=%d, r=%.3f, 1/rho=%ld ", i+1, split_primes[i].p,split_primes[i].t, split_primes[i].v, split_primes[i].r, split_primes[i].p/wts[split_primes[i].v]); //out_printf(" (twist=%d, tor=%d, s2=%x, t3=%d)\n", twist, tor, s2, t3); } mem_free(split_primes); if ( dbg_level > 0 ) { info_printf("Torsion:\n"); for ( i = 0 ; i < 40 ; i++ ) if ( torcnts[i] ) info_printf (" %ld (%.3f)", i, (double)torcnts[i]/n); info_printf("\n"); } //dbg_printf ("%d primes, %f bits, maxp = %ld, maxv = %ld\n", i, pbits, p, v); return n; } #define TWIST_DOUBLE_RATIO (9.0/16.0) double split_prime_rating (long p, long t, int *ptwist, int *ptor, int *ps2, int *pt3) { double minr, r; int j_flags; long n1, n2; int m1, m2, k1, k2, t1, t2, fix; char tormap[TECURVE_MAX_N+1]; register int i, j, k; n1 = p+1-t; n2 = p+1+t; if ( (p%3)==1 && (4*p-t*t)%3 ) j_flags = FILTER_JCUBE; else j_flags = 0; t1 = ( (n1%3) ? FILTER_3TOR_1 : FILTER_3TOR_NOT_1); t2 = ( (n2%3) ? FILTER_3TOR_1 : FILTER_3TOR_NOT_1); for ( m1 = n1, k1 = 0 ; !(m1&1) ; m1>>=1, k1++ ); for ( m2 = n2, k2 = 0 ; !(m2&1) ; m2>>=1, k2++ ); tormap[1] = ( (n1&1) ? 3 : 0 ); for ( i = 2 ; i <= TECURVE_MAX_N ; i++ ) { tormap[i] = 0; if ( !(n1%i) ) tormap[i] |= 1; if ( !(n2%i) ) tormap[i] |= 2; } minr = TECURVE_MAX_COST; fix = 0; for ( j = 0 ; j < 2 ; j++ ) { for ( i = 1 ; i <= TECURVE_MAX_N ; i++ ) { if ( tormap[i]&1 ) { for ( k = 0 ; k <= k1 && k <= 2 ; k++ ) { r = tecurve_free2_density(p,i,k,j*t1,j_flags)*tecurve_free2_cost(p,i,k,j*t1,j_flags); //printf("Free rating tor=%d, k=%d, r=%f\n",i,k,r); if ( r && r < minr ) { minr=r; *ptwist=1; fix=0; *ptor=i; *ps2=k; *pt3=j*t1; } } r = tecurve_fix2_density(p,i,k1,j*t1,j_flags)*tecurve_fix2_cost(p,i,k1,j*t1,j_flags); //printf("Fix rating tor=%d, k=%d, r=%f\n",i,k1,r); if ( r && r < minr ) { minr=r; *ptwist=1; fix=1; *ptor=i; *ps2=k1; *pt3=j*t1; } } if ( tormap[i]&2 ) { for ( k = 0 ; k <= k2 && k <= 2 ; k++ ) { r = tecurve_free2_density(p,i,k,j*t2,j_flags)*tecurve_free2_cost(p,i,k,j*t2,j_flags); //printf("Free rating tor=%d, k=%d, r=%f\n",i,k,r); if ( r && r < minr ) { minr=r; *ptwist=2; fix=0; *ptor=i; *ps2=k; *pt3=j*t2; } } r = tecurve_fix2_density(p,i,k2,j*t2,j_flags)*tecurve_fix2_cost(p,i,k2,j*t2,j_flags); //printf("Fix rating tor=%d, k=%d, r=%f\n",i,k1,r); if ( r < minr ) { minr=r; *ptwist=2; fix=1; *ptor=i; *ps2=k2; *pt3=j*t2; } } if ( tormap[i]==3 && j*t1==j*t2 ) { for ( k = 0 ; k <= ui_min(k1,k2) && k <= 2 ; k++ ) { r = tecurve_free2_density(p,i,k,j*t1,j_flags)*tecurve_free2_cost(p,i,k,j*t1,j_flags)*TWIST_DOUBLE_RATIO; //printf("*Free rating tor=%d, k=%d, r=%f\n",i,k,r); if ( r && r < minr ) {minr=r; *ptwist=3; fix=0; *ptor=i; *ps2=k; *pt3=j*t1; } } if ( k1==k2 ) { r = tecurve_fix2_density(p,i,k1,j*t1,j_flags)*tecurve_fix2_cost(p,i,k1,j*t1,j_flags)*TWIST_DOUBLE_RATIO; //printf("Fix rating tor=%d, k=%d, r=%f\n",i,k1,r); if ( r && r < minr ) { minr=r; *ptwist=3; fix=1; *ptor=i; *ps2=k1; *pt3=j*t1; } } } } } if ( fix ) { *ps2 |= FILTER_2SYLOW_C_LG; } else { if ( *ps2 ==1 ) *ps2 = FILTER_2SYLOW_NOT_1; else if ( *ps2>=2 ) *ps2 = FILTER_2SYLOW_D4; else *ps2 = 0; } //printf ("p=%ld, tor = %d, r=%f\n", p, *ptor, minr); return minr; } double split_prime_rating_new (long p, long t, int *ptwist, int *ptor, int *ps2, int *pt3) { struct torctab_rec *torctab; double tormod[32]; int TORCTAB_SIZE; long n1, n2; int b1, b2, b12; int i; if ( (p%3)==2 ) { if ( (p&3)==3 ) { torctab = torctab1; TORCTAB_SIZE = TORCTAB1_SIZE; } else { torctab = torctab2; TORCTAB_SIZE = TORCTAB2_SIZE; } } else { if ( (p&3)==3 ) { torctab = torctab3; TORCTAB_SIZE = TORCTAB3_SIZE; } else { torctab = torctab4; TORCTAB_SIZE = TORCTAB4_SIZE; } } for ( i = 0 ; i < 32 ; i++ ) tormod[i] = 1.0; if ( (p%5)==1 ) tormod[5] = tormod[10] = tormod[15] = 6.0/5.0; if ( (p%7)==1 ) tormod[7] = tormod[14] = 8.0/7.0; if ( (p%11)== 1 ) tormod[11] = 12.0/11.0; if ( (p%13)==1 ) tormod[13] = 14.0/13.0; if ( (p%17)==1 ) tormod[17] = 18.0/17.0; if ( (p%19)==1 ) tormod[19] = 20.0/19.0; if ( (p%23)==1 ) tormod[23] = 24.0/23.0; if ( (p%29)==1 ) tormod[29] = 30.0/29.0; if ( (p%31)==1 ) tormod[31] = 32.0/31.0; n1 = p+1-t; n2 = p+1+t; b1 = b2 = b12 = -1; for ( i = 0 ; i < TORCTAB_SIZE ; i++ ) if ( ! (n1%torctab[i].m) && ( !torctab[i].fix2 || (n1%(2*torctab[i].m)) ) && ( ! torctab[i].fix3 || (n1%(3*torctab[i].m)) ) ) if ( b1 < 0 || torctab[i].rating*tormod[torctab[i].N] < torctab[b1].rating*tormod[torctab[b1].N] ) b1= i; if ( b1 < 0) { printf ("Error, no suitable torsion found in torctab for n1 = %ld!\n", n1); exit (0); } for ( i = 0 ; i < TORCTAB_SIZE ; i++ ) if ( ! (n2%torctab[i].m) && ( !torctab[i].fix2 || (n2%(2*torctab[i].m)) ) && ( ! torctab[i].fix3 || (n2%(3*torctab[i].m)) ) ) if ( b2 < 0 || torctab[i].rating*tormod[torctab[i].N] < torctab[b2].rating*tormod[torctab[b2].N] ) b2= i; if ( b2 < 0 ) { printf ("Error, no suitable torsion found in torctab for n2 = %ld!\n", n2); exit (0); } for ( i = 0 ; i < TORCTAB_SIZE ; i++ ) if ( ! (n1%torctab[i].m) && ( !torctab[i].fix2 || (n1%(2*torctab[i].m)) ) && ( ! torctab[i].fix3 || (n1%(3*torctab[i].m)) ) ) if ( ! (n2%torctab[i].m) && ( !torctab[i].fix2 || (n2%(2*torctab[i].m)) ) && ( ! torctab[i].fix3 || (n2%(3*torctab[i].m)) ) ) if ( b12 < 0 || torctab[i].rating*tormod[torctab[i].N] < torctab[b12].rating*tormod[torctab[b12].N] ) b12 = i; if ( b12 < 0 ) { printf ("Error, no suitable torsion found in torctab for n1 = %ld, n2 = %ld!\n", n1, n2); exit (0); } if ( b1 > b2 ) { if ( torctab[b2].rating / TWIST_DOUBLE_RATIO > torctab[b12].rating ) { *ptwist = 3; *ptor = torctab[b12].N; *ps2 = torctab[b12].s2_flag; *pt3 = torctab[b12].t3_flag; return torctab[b12].rating*tormod[torctab[b12].N] ; } else { *ptwist = 2; *ptor = torctab[b2].N; *ps2 = torctab[b2].s2_flag; *pt3 = torctab[b2].t3_flag; return torctab[b2].rating*tormod[torctab[b2].N] /TWIST_DOUBLE_RATIO; } } else { if ( torctab[b1].rating / TWIST_DOUBLE_RATIO > torctab[b12].rating ) { *ptwist = 3; *ptor = torctab[b12].N; *ps2 = torctab[b12].s2_flag; *pt3 = torctab[b12].t3_flag; return torctab[b12].rating*tormod[torctab[b12].N] ; } else { *ptwist = 1; *ptor = torctab[b1].N; *ps2 = torctab[b1].s2_flag; *pt3 = torctab[b1].t3_flag; return torctab[b1].rating*tormod[torctab[b1].N] /TWIST_DOUBLE_RATIO; } } }
2.015625
2
2024-11-18T21:06:08.579574+00:00
2018-06-26T12:41:12
860488ae1047ecd40a00f70edb7a4e3554e2289f
{ "blob_id": "860488ae1047ecd40a00f70edb7a4e3554e2289f", "branch_name": "refs/heads/master", "committer_date": "2018-06-26T12:50:04", "content_id": "edd75f7e925aa39f44bf2a4b290aca84387d1aba", "detected_licenses": [ "MIT" ], "directory_id": "87e41ce8114dffe64ce4bdfca72ae7fea4ce7d7d", "extension": "c", "filename": "ParseCmdDefs.c", "fork_events_count": 1, "gha_created_at": "2017-12-22T10:47:41", "gha_event_created_at": "2018-07-06T22:02:53", "gha_language": "C", "gha_license_id": "MIT", "github_id": 115106508, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6390, "license": "MIT", "license_type": "permissive", "path": "/src/cui/ParseCmdDefs.c", "provenance": "stackv2-0083.json.gz:15362", "repo_name": "boldowa/GIEPY", "revision_date": "2018-06-26T12:41:12", "revision_id": "5aa326b264ef19f71d2e0ab5513b08fac7bca941", "snapshot_id": "67a3d5b6a76cdf3dfd93b8e40b7b4bba775802b7", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/boldowa/GIEPY/5aa326b264ef19f71d2e0ab5513b08fac7bca941/src/cui/ParseCmdDefs.c", "visit_date": "2021-09-18T01:28:22.306880" }
stackv2
/** * @file ParseCmdDefs.c */ #include <bolib.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #if isWindows # include <windows.h> # include <tchar.h> #endif #include <ctype.h> #include <assert.h> #include "common/Observer.h" #include "common/puts.h" #include "common/Funex.h" typedef struct _RomFile RomFile; /* for Asarctl.h */ #include "cui/ParseCmdDefs.h" #include "common/GetFmtStr.h" #ifndef _tcslen # define _tcslen(s) strlen(s) #endif #ifndef _tcscmp # define _tcscmp(s1, s2) strcmp(s1,s2) #endif #ifndef _tcscpy_s # define _tcscpy_s(s1,len,s2) strcpy_s(s1,len,s2) #endif #ifndef _tcsncpy_s # define _tcsncpy_s(s1,len,s2, cnt) strncpy_s(s1,len,s2,cnt) #endif static Define* MakeDefine(const char* srcname, const char* srcval) { size_t len; size_t i; size_t st; Define* def = NULL; char* name = NULL; char* val = NULL; if((NULL == srcname) || (NULL == srcval)) { return NULL; } len = _tcslen(srcname); i = 0; SkipSpaces(srcname, &i, len); st = i; for(i=len; 0<i; i--) { if(false == IsSpace(srcname[i])) { break; } } if(i == st) return NULL; len = i - st; name = calloc(len+1, sizeof(char)); val = calloc(_tcslen(srcname)+1, sizeof(char)); def = calloc(1, sizeof(Define)); if(NULL == def || NULL == val || NULL == name) { free(def); free(val); free(name); return NULL; } _tcsncpy_s(name, len+1, &srcname[st], len); _tcscpy_s(val, _tcslen(srcname)+1, srcval); def->name = name; def->val = val; return def; } #if 0 void* CloneDefine(const void* srcv) { Define* src; Define* clone; char* name; char* val; if(NULL == srcv) return NULL; src = (Define*)srcv; name = Str_copy(src->name); val = Str_copy(src->val); clone = calloc(1, sizeof(Define)); if((NULL == name) || (NULL == val) || (NULL == clone)) { free(name); free(val); free(clone); return NULL; } _tcscpy_s(name, _tcslen(src->name)+1, src->name); _tcscpy_s(val, _tcslen(src->val)+1, src->val); clone->name = name; clone->val = val; return clone; } #endif void DelDefine(void* tgt) { Define* def; if(NULL == tgt) return; def = (Define*)tgt; free(def->name); free(def->val); free(def); } enum { Match_Empty = 0, Match_IntegerDefine, Match_ParamDefine, Unmatch }; static bool MatchEmpty(const char* cmd, void* p) { size_t i; size_t len; len = _tcslen(cmd); for(i=0; i<len; i++) { if(false == IsSpace(cmd[i])) { return false; } } if(i != len) return false; return true; } static bool IntegerInjection(const char* cmd) { size_t i; size_t len; len = _tcslen(cmd); i = 0; /* check hex */ if('$' == cmd[0]) { i++; for(; i<len; i++) { if(false == ishex(cmd[i])) { break; } } if(i != len) { return false; } putdebug("Match Hex value: %s", cmd); return true; } /* check integer */ if('-' == cmd[i]) i++; for(; i<len; i++) { if(false == isdigit(cmd[i])) { break; } } if(i != len) { return false; } putdebug("Match Int value: %s", cmd); return true; } static bool MatchParam_Shared(const char* cmd, void* defv, bool (*injection)(const char*)) { size_t i; size_t len; size_t st; char* name; size_t namelen; char* val; size_t vallen; Define *def = (Define*)defv; len = _tcslen(cmd); i = 0; SkipSpaces(cmd, &i, len); st = i; SkipUntilChar(cmd, &i, '=', len); if(i == len) return false; namelen = i - st; name = calloc((size_t)namelen+1, sizeof(char)); if(NULL == name) { putmemerr(); return false; } _tcsncpy_s(name, namelen+1, &cmd[st], namelen); /* '=' */ i++; SkipSpaces(cmd, &i, len); if(i == len) { free(name); return false; } st = i; /* search value */ SkipUntilSpaces(cmd, &i, len); if(i != len) { free(name); return false; } /* get define value */ vallen = i - st; val = calloc(vallen+1, sizeof(char)); if(NULL == val) { putmemerr(); free(name); return false; } _tcsncpy_s(val, vallen+1, &cmd[st], vallen); /* shirk space */ CutOffTailSpaces(val); vallen = _tcslen(val); /* check integer injection */ if(NULL == injection) { char* newval = NULL; vallen += 2; newval = calloc((size_t)vallen+1, sizeof(char)); if(NULL == newval) { putmemerr(); free(name); free(val); return false; } newval[0] = '"'; _tcscpy_s(&newval[1], vallen-1, val); newval[_tcslen(val)+1] = '"'; free(val); val = newval; } else { if(false == injection(val)) { free(name); free(val); return false; } } /* shirk space */ CutOffTailSpaces(name); def->name = name; def->val = val; return true; } static bool MatchIntegerDefine(const char* cmd, void* defv) { return MatchParam_Shared(cmd, defv, IntegerInjection); } static bool MatchParamDefine(const char* cmd, void* defv) { return MatchParam_Shared(cmd, defv, NULL); } static bool SearchDefine(const void* s1, const void* s2) { const char* name = (const char*)s1; Define *d = (Define*)s2; return(0 == _tcscmp(name, d->name)); } bool ParseCmdDefs(void* dst, const char* cmdline) { List* defineList; Define def; Define* d; Iterator* lnode; FunexStruct funex[] = { { MatchEmpty, NULL }, { MatchIntegerDefine, &def }, { MatchParamDefine, &def }, { NULL, NULL } }; if(NULL == dst) { putfatal(0, GSID_PROGLOGIC_ERROR, __func__); return false; } assert(NULL != dst); defineList = *((List**)dst); /* parse define */ switch(FunexMatch(cmdline, funex)) { case Match_Empty: return false; case Match_IntegerDefine: case Match_ParamDefine: putdebug("Match param define: !%s = %s", def.name, def.val); d = malloc(sizeof(Define)); if(NULL == d) { putmemerr(); return false; } memcpy(d, &def, sizeof(Define)); lnode = defineList->search(defineList, d->name, SearchDefine); if(NULL != lnode) { Define* p = lnode->data(lnode); putdebug("update %s %s -> %s", d->name, p->val, d->val); free(p->val); p->val = d->val; break; } defineList->push(defineList, d); break; default: putdebug("Match non-param define"); d = MakeDefine(cmdline, "1"); if(NULL == d) { putmemerr(); return false; } lnode = defineList->search(defineList, d->name, SearchDefine); if(NULL != lnode) { putdebug("popoipo~i %s", d->name); free(d); break; } putdebug("defined: !%s = 1", d->name); defineList->push(defineList, d); break; } return true; }
2.34375
2
2024-11-18T21:06:08.638532+00:00
2017-03-09T09:14:17
3a808c0d6438a18cbc6b29ecf5356589ffe7d5d9
{ "blob_id": "3a808c0d6438a18cbc6b29ecf5356589ffe7d5d9", "branch_name": "refs/heads/master", "committer_date": "2017-03-09T09:14:17", "content_id": "65f721bda446bd2abbe78bf6a19a89f37fa366f9", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "84aa8c9b1dbb4139771f3383f85c2274bf57f6c3", "extension": "c", "filename": "croppa.c", "fork_events_count": 6, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 59880306, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5212, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/tools/croppa/croppa.c", "provenance": "stackv2-0083.json.gz:15490", "repo_name": "alpine9000/blockyskies", "revision_date": "2017-03-09T09:14:17", "revision_id": "08de70af9bfb9f89ac4401996b72e01762ddbfd4", "snapshot_id": "fd51fb2204ce5b0dcd33d655964f5f0304140ccc", "src_encoding": "UTF-8", "star_events_count": 31, "url": "https://raw.githubusercontent.com/alpine9000/blockyskies/08de70af9bfb9f89ac4401996b72e01762ddbfd4/tools/croppa/croppa.c", "visit_date": "2020-03-26T13:07:54.575864" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> #include <magick/api.h> #include <getopt.h> typedef struct { int verbose; int width; int height; int x; int y; int dx; int dy; int rows; int cols; char** argv; } config_t; typedef struct { Image *image; Image *croppedImage; ImageInfo *imageInfo; } image_t; image_t image = {0}; config_t config = { .rows = 1, .cols = 1, .verbose = 0 }; void cleanup() { if (image.image != (Image *) NULL) { DestroyImage(image.image); } if (image.imageInfo != (ImageInfo *) NULL) { DestroyImageInfo(image.imageInfo); } DestroyMagick(); } void abort_(const char * s, ...) { fprintf(stderr, "%s: ", config.argv[0]); va_list args; va_start(args, s); vfprintf(stderr, s, args); fprintf(stderr, "\n"); va_end(args); cleanup(); exit(1); } void usage() { fprintf(stderr, "%s: --input <input.png> --output <output.png> --x <x> --y <y> --width <width> --height <height> \n"\ "options:\n"\ " --dx <dx> (default: width)\n"\ " --dy <dy> (default: height)\n"\ " --rows <num rows> (default: 1)\n"\ " --cols <num columns> (default: 1)\n"\ " --verbose\n", config.argv[0]); exit(1); } int main(int argc, char **argv) { int c; char* inputFile = 0; char* outputFile = 0; ExceptionInfo exception; config.argv = argv; InitializeMagick(NULL); image.imageInfo=CloneImageInfo(0); GetExceptionInfo(&exception); while (1) { static struct option long_options[] = { {"verbose", no_argument, &config.verbose, 1}, {"width", required_argument, 0, 'w'}, {"height", required_argument, 0, 'h'}, {"output", required_argument, 0, 'o'}, {"input", required_argument, 0, 'i'}, {"x", required_argument, 0, 'x'}, {"y", required_argument, 0, 'y'}, {"dx", required_argument, 0, 'd'}, {"dy", required_argument, 0, 'f'}, {"rows", required_argument, 0, 'r'}, {"cols", required_argument, 0, 'c'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "o:i:w:h:b:", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'i': inputFile = optarg; break; case 'o': outputFile = optarg; break; case 'w': if (sscanf(optarg, "%d", &config.width) != 1) { abort_("invalid width"); } break; case 'h': if (sscanf(optarg, "%d", &config.height) != 1) { abort_("invalid height"); } break; case 'x': if (sscanf(optarg, "%d", &config.x) != 1) { abort_("invalid x"); } break; case 'y': if (sscanf(optarg, "%d", &config.y) != 1) { abort_("invalid x"); } break; case 'd': if (sscanf(optarg, "%d", &config.dx) != 1) { abort_("invalid dx"); } break; case 'f': if (sscanf(optarg, "%d", &config.dy) != 1) { abort_("invalid dy"); } break; case 'r': if (sscanf(optarg, "%d", &config.rows) != 1) { abort_("invalid rows"); } break; case 'c': if (sscanf(optarg, "%d", &config.cols) != 1) { abort_("invalid cols"); } break; case '?': usage(); break; default: usage(); break; } } if (inputFile == 0 || outputFile == 0 || config.width == 0 || config.height == 0) { usage(); abort(); } if (config.dx == 0 ) { config.dx = config.width; } if (config.dy == 0 ) { config.dy = config.height; } if (config.verbose) { printf("x: %d, y: %d\n", config.x, config.y); printf("dx: %d, dy: %d\n", config.dx, config.dy); printf("width: %d, height: %d\n", config.width, config.height); printf("rows: %d, cols: %d\n", config.rows, config.cols); } (void) strcpy(image.imageInfo->filename, inputFile); image.image = ReadImage(image.imageInfo, &exception); if (image.image == (Image *) NULL) { CatchException(&exception); abort_("Failed to read image %s\n", inputFile); } for (int x = config.x, count = 0; x < config.x+(config.cols*config.dx); x += config.dx) { for (int y = config.y; y < config.y+(config.rows*config.dy); y += config.dy, count++) { RectangleInfo rect = { .x = x, .y = y, .width = config.width, .height = config.height }; if (config.verbose) { printf("row %d cols %d %ld %ld %ld %ld\n", (y-config.y)/config.dy, (x-config.x)/config.dx, rect.x, rect.y, rect.width, rect.height); } image.croppedImage = CropImage(image.image, &rect, &exception); if (config.rows > 1 || config.cols > 1) { sprintf(image.croppedImage->filename, "%s-%d.png", outputFile, count); } else { strcpy(image.croppedImage->filename, outputFile); } if (!WriteImage(image.imageInfo, image.croppedImage)) { CatchException(&image.croppedImage->exception); abort_("Failed to write image %d\n", outputFile); } if (image.croppedImage != (Image *)NULL) { DestroyImage(image.croppedImage); } } } cleanup(); return 0; }
2.578125
3
2024-11-18T21:06:08.697332+00:00
2016-07-31T00:09:39
1f3c440f51718e49bdbd9bc7c9b9fddf22940856
{ "blob_id": "1f3c440f51718e49bdbd9bc7c9b9fddf22940856", "branch_name": "refs/heads/master", "committer_date": "2016-07-31T00:09:39", "content_id": "dcf202d3d0a33449d70562ba64e05daa4dedf841", "detected_licenses": [ "MIT" ], "directory_id": "e4ebe115cdc36af922f32fdeb0636ecf1b066100", "extension": "c", "filename": "pseudoRandGen.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 13810128, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1322, "license": "MIT", "license_type": "permissive", "path": "/dataStructures/hashlist/pseudoRandGen.c", "provenance": "stackv2-0083.json.gz:15618", "repo_name": "odeke-em/utils", "revision_date": "2016-07-31T00:09:39", "revision_id": "9a0ed5bb4a2809d0a442e1a74c71edd9563f84cf", "snapshot_id": "6a24506786ac8b6ec8b5f36d0d21ed000ac01ca8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/odeke-em/utils/9a0ed5bb4a2809d0a442e1a74c71edd9563f84cf/dataStructures/hashlist/pseudoRandGen.c", "visit_date": "2020-04-06T03:41:16.122745" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "hashList.h" /* Author: Emmanuel Odeke <odeke@ualberta.ca> Theory for pseudo random generation obtained from: http://www.math.utah.edu/~pa/Random/Random.html Given p1, p2, N(limit), and x0 Recurrance formula: xN+1 = (x0*p1) + p2 (mod N) */ Element *pGen(const int p1, const int p2, const int x0, const int limit) { Element *randValues = NULL; if (limit) { HashList *hl = NULL; hl = initHashList(hl); int xN1, xN = x0; while (1) { xN1 = ((p1 * xN) + p2) % limit; Element **query = get(hl, xN1); if (*query == NULL) { int *eMem = (int *)malloc(sizeof(int)); int *rMem = (int *)malloc(sizeof(int)); *eMem = xN1; *rMem = xN1; insertElem(hl, eMem, xN1); randValues = addToHead(randValues, rMem); } else { // Cycle or collision detected time to end break; } xN = xN1; } destroyHashList(hl); } return randValues; } void printIntSL(Element *sl) { printf("["); Element *trav = sl; while (trav != NULL) { printf("%d ", *(int *)trav->value); trav = trav->next; } printf("]"); } int main() { Element *randValues = pGen(29, 69, 999, 1000000); printIntSL(randValues); destroySList(randValues); return 0; }
3.265625
3
2024-11-18T21:06:09.140881+00:00
2017-03-11T19:27:25
33e7c76036e669e464afb1021aea3e1bfc86ca89
{ "blob_id": "33e7c76036e669e464afb1021aea3e1bfc86ca89", "branch_name": "refs/heads/master", "committer_date": "2017-03-11T19:27:25", "content_id": "f26f41778fa6eff18ac78f4a5da83159911d92e2", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "96d4d69c50fa992e19ba6355bdee103db23324f8", "extension": "h", "filename": "text.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1834, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/utils/text.h", "provenance": "stackv2-0083.json.gz:15874", "repo_name": "padymkoclab/c-utils", "revision_date": "2017-03-11T19:27:25", "revision_id": "b0dfab7dac867179672de239e5e802f29ecb8cf9", "snapshot_id": "62e19296697cc60585c7cd498134d77f1ac6902b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/padymkoclab/c-utils/b0dfab7dac867179672de239e5e802f29ecb8cf9/utils/text.h", "visit_date": "2021-06-15T00:14:14.360397" }
stackv2
/** * Utils for working with a text */ /* char str[] = "regcomp() is supplied with preg, a pointer to a pattern buffer storage area; regex, a pointer to the null-terminated string and cflags, flags used to determine the type of compilation."; putd(getCountWords(str)); */ // Idea: word cloud #ifndef __TEXT_H__ #define __TEXT_H__ typedef struct _CounterWords { } CounterWords; // Need rewrite char ** text_get_total_words(char text[], unsigned int *length) { /* char *word; if (text != NULL) { _copy_text_for_words = calloc(strlen(text), sizeof(char)); strcpy(_copy_text_for_words, text); word = splitString(text, " "); } word = splitString(NULL, " "); if (word != NULL) { stripString(word, ",.:();!?", 'b'); } return word; */ return NULL; } unsigned int text_get_count_words(char text[]) { unsigned int length; text_get_words(text, &length); return length; } // Need mapping (dictionary) char ** text_counter_words(CounterWords *counter_words, char text[]) { return NULL; } char * text_get_word(char text[], unsigned int n) { return NULL; } char ** text_search_words(char text[], char pattern[]) { return NULL; } char ** text_get_words(char text[], unsigned int index_from, unsigned int index_to) { return NULL; } char * text_get_words(char text[], char pattern[]) { return NULL; } /* Wraps words at specified line length. Argument: number of characters at which to wrap the text For example: {{ value|wordwrap:5 }} If value is Joel is a slug, the output would be: Joel is a slug */ char * text_wrap(char text[], const unsigned int width) { return NULL; } /** * Tests */ void test_text_wrap() { text_wrap(); } void test_text() { test_text_wrap(); } #endif // __TEXT_H__
2.78125
3
2024-11-18T21:06:09.301709+00:00
2016-08-10T23:21:41
dc8c6b8bebaf86746f16a46254e38de9d36f7435
{ "blob_id": "dc8c6b8bebaf86746f16a46254e38de9d36f7435", "branch_name": "refs/heads/master", "committer_date": "2016-08-10T23:21:41", "content_id": "1d641d05f5b69a9f6f5bd305469a16738e7c05fa", "detected_licenses": [ "MIT" ], "directory_id": "979920f2cb57a308df187018771d025cab432d62", "extension": "c", "filename": "forth.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13670, "license": "MIT", "license_type": "permissive", "path": "/util/forth.c", "provenance": "stackv2-0083.json.gz:16133", "repo_name": "arkenidar/libforth", "revision_date": "2016-08-10T23:21:41", "revision_id": "54e9fd55ea5b9386451328944a8dc8c8f4d502dd", "snapshot_id": "d30dcecec91f45415fe1105b415075e25e9ce690", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/arkenidar/libforth/54e9fd55ea5b9386451328944a8dc8c8f4d502dd/util/forth.c", "visit_date": "2021-01-14T12:47:09.552955" }
stackv2
/** @file forth.c * @brief A version of the libforth interpreter that is does * no memory allocations, which can be used as a starting * point to porting to more esoteric platforms. * @author Richard James Howe. * @copyright Copyright 2016 Richard James Howe. * @license LGPL v2.1 or later version * @email howe.r.j.89@gmail.com */ #include <errno.h> #include <inttypes.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef uintptr_t forth_cell_t; #define PRIuCell PRIdPTR #define PRIxCell PRIxPTR #define CORE_SIZE (2048) /**< default vm size*/ #define STRING_OFFSET (32u) /**< offset into memory of string buffer*/ #define MAX_WORD_LENGTH (32u) /**< max word length, must be < 255 */ #define DICTIONARY_START (STRING_OFFSET + MAX_WORD_LENGTH) /**< start of dic */ #define WORD_LENGTH_OFFSET (8) /**< bit offset for word length start*/ #define WORD_LENGTH(FIELD1) (((FIELD1) >> WORD_LENGTH_OFFSET) & 0xff) #define WORD_HIDDEN(FIELD1) ((FIELD1) & 0x80) /**< is a forth word hidden? */ #define INSTRUCTION_MASK (0x7f) #define instruction(k) ((k) & INSTRUCTION_MASK) #define VERIFY(X) do { if(!(X)) { abort(); } } while(0) static const char *initial_forth_program = "\n\ : state 8 exit : ; immediate ' exit , 0 state ! exit : base 9 ; : pwd 10 ; \n\ : h 6 ; : r 7 ; : here h @ ; : [ immediate 0 state ! ; : ] 1 state ! ; \n\ : :noname immediate here 2 , ] ; : if immediate ' ?branch , here 0 , ; \n\ : else immediate ' branch , here 0 , swap dup here swap - swap ! ; : 0= 0 = ;\n\ : then immediate dup here swap - swap ! ; : 2dup over over ; : <> = 0= ; \n\ : begin immediate here ; : until immediate ' ?branch , here - , ; : '\\n' 10 ; \n\ : not 0= ; : 1+ 1 + ; : 1- 1 - ; : ')' 41 ; : tab 9 emit ; : cr '\\n' emit ; \n\ : ( immediate begin key ')' = until ; : rot >r swap r> swap ; : -rot rot rot ;\n\ : tuck swap over ; : nip swap drop ; : :: [ find : , ] ; : allot here + h ! ; "; static uint8_t *s; /**< convenience pointer for string input buffer */ static char hex_fmt[16]; /**< calculated hex format*/ static forth_cell_t I; /**< instruction pointer */ static forth_cell_t f; /**< top of stack */ static forth_cell_t pc; /**< vm program counter */ static forth_cell_t w; /**< working pointer */ static forth_cell_t *S; /**< stack pointer */ static forth_cell_t m[CORE_SIZE]; /**< Forth Virtual Machine memory !! (as is)*/ static forth_cell_t compile_header; /**< used by compile */ static forth_cell_t compile_len; /**< used by compile */ static char tmp_constant[MAX_WORD_LENGTH+32]; static void forth_set_file_input(FILE *in); static void forth_set_string_input(const char *s); static int forth_eval(const char *s); enum registers { /**< virtual machine registers */ DIC = 6, /**< dictionary pointer */ RSTK = 7, /**< return stack pointer */ STATE = 8, /**< interpreter state; compile or command mode*/ BASE = 9, /**< base conversion variable */ PWD = 10, /**< pointer to previous word */ SOURCE_ID = 11, /**< input source selector */ SIN = 12, /**< string input pointer*/ SIDX = 13, /**< string input index*/ SLEN = 14, /**< string input length*/ START_ADDR = 15, /**< pointer to start of VM */ FIN = 16, /**< file input pointer */ FOUT = 17, /**< file output pointer */ STDIN = 18, /**< file pointer to stdin */ STDOUT = 19, /**< file pointer to stdout */ STDERR = 20, /**< file pointer to stderr */ ARGC = 21, /**< argument count */ ARGV = 22, /**< arguments */ DEBUG = 23, /**< turn debugging on/off if enabled*/ INVALID = 24, /**< if non zero, this interpreter is invalid */ TOP = 25, /**< *stored* version of top of stack */ INSTRUCTION = 26, /**< *stored* version of instruction pointer*/ STACK_SIZE = 27, /**< size of the stacks */ START_TIME = 28, /**< start time in milliseconds */ }; enum input_stream { FILE_IN, STRING_IN = -1 }; enum instructions { PUSH,COMPILE,RUN,DEFINE,IMMEDIATE,READ,LOAD,STORE, SUB,ADD,AND,OR,XOR,INV,SHL,SHR,MUL,DIV,LESS,MORE,EXIT,EMIT,KEY,FROMR,TOR,BRANCH, QBRANCH, PNUM, QUOTE,COMMA,EQUAL,SWAP,DUP,DROP,OVER,FIND,PRINT, DEPTH,LAST }; static const char *names[] = { "read","@","!","-","+","and","or","xor","invert", "lshift","rshift","*","/","u<","u>","exit","emit","key","r>",">r","branch", "?branch", ".","'", ",","=", "swap","dup","drop", "over", "find", "print","depth", NULL }; static int forth_get_char() { /* get a char from string input or a file */ switch(m[SOURCE_ID]) { case FILE_IN: return fgetc((FILE*)(m[FIN])); case STRING_IN: return m[SIDX] >= m[SLEN] ? EOF : ((char*)(m[SIN]))[m[SIDX]++]; default: return EOF; } } static int readin; static int forth_get_word(uint8_t *p) { /*get a word (space delimited, up to 31 chars) from a FILE* or string-in*/ readin = 0; switch(m[SOURCE_ID]) { case FILE_IN: return fscanf((FILE*)(m[FIN]), "%31s%n", p, &readin); case STRING_IN: if(sscanf((char *)&(((char*)(m[SIN]))[m[SIDX]]), "%31s%n", p, &readin) < 0) return EOF; return m[SIDX] += readin, readin; default: return EOF; } } static void compile(forth_cell_t code, const char *str) { /* create a new forth word header */ compile_header = m[DIC]; compile_len = 0; /*FORTH header structure*/ strcpy((char *)(m + compile_header), str); /* 0: Copy the new FORTH word into the new header */ compile_len = strlen(str) + 1; compile_len = (compile_len + (sizeof(forth_cell_t) - 1)) & ~(sizeof(forth_cell_t) - 1); /* align up to sizeof word */ compile_len = compile_len/sizeof(forth_cell_t); m[DIC] += compile_len; /* Add string length in words to header (STRLEN) */ m[m[DIC]++] = m[PWD]; /*0 + STRLEN: Pointer to previous words header*/ m[PWD] = m[DIC] - 1; /* Update the PWD register to new word */ m[m[DIC]++] = (compile_len << WORD_LENGTH_OFFSET) | code; /*1: size of words name and code field */ } static int numberify(int base, forth_cell_t *n, const char *s) { /*returns non zero if conversion was successful*/ char *end = NULL; errno = 0; *n = strtol(s, &end, base); return !errno && *s != '\0' && *end == '\0'; } static forth_cell_t forth_find(const char *s) { /* find a word in the Forth dictionary, which is a linked list, skipping hidden words */ forth_cell_t x = m[PWD]; forth_cell_t len = WORD_LENGTH(m[x+1]); for (;x > DICTIONARY_START && (WORD_HIDDEN(m[x+1]) || strcmp(s,(char*)(&m[x - len])));) { x = m[x]; len = WORD_LENGTH(m[x+1]); } return x > DICTIONARY_START ? x+1 : 0; } static int print_cell(forth_cell_t f) { char *fmt = m[BASE] == 16 ? hex_fmt : "%" PRIuCell; return fprintf((FILE*)(m[FOUT]), fmt, f); } static int forth_define_constant(const char *name, forth_cell_t c) { memset(tmp_constant, 0, MAX_WORD_LENGTH+32); sprintf(tmp_constant, ": %31s %" PRIuCell " ; \n", name, c); return forth_eval(tmp_constant); } static void forth_make_default(FILE *in, FILE *out) { /* set defaults for a forth structure for initialization or reload */ m[STACK_SIZE] = CORE_SIZE / 64; s = (uint8_t*)(m + STRING_OFFSET); /*string store offset into CORE, skip registers*/ m[FOUT] = (forth_cell_t)out; m[START_ADDR] = (forth_cell_t)&(m); m[STDIN] = (forth_cell_t)stdin; m[STDOUT] = (forth_cell_t)stdout; m[STDERR] = (forth_cell_t)stderr; m[RSTK] = CORE_SIZE - m[STACK_SIZE]; /*set up return stk pointer*/ m[ARGC] = m[ARGV] = 0; S = m + CORE_SIZE - (2 * m[STACK_SIZE]); /*set up variable stk pointer*/ sprintf(hex_fmt, "0x%%0%d"PRIxCell, (int)(sizeof(forth_cell_t)*2)); forth_set_file_input(in); /*set up input after our eval*/ } int forth_init(FILE *in, FILE *out) { forth_cell_t i, p; forth_make_default(in, out); m[PWD] = 0; /*special terminating pwd value*/ p = m[DIC] = DICTIONARY_START; /*initial dictionary offset, skip registers and string offset*/ m[m[DIC]++] = READ; /*create a special word that reads in FORTH*/ m[m[DIC]++] = RUN; /*call the special word recursively*/ m[INSTRUCTION] = m[DIC]; /*instruction stream points to our special word*/ m[m[DIC]++] = p; /*recursive call to that word*/ m[m[DIC]++] = m[INSTRUCTION] - 1; /*execute read*/ compile(DEFINE, ":"); /*immediate word*/ compile(IMMEDIATE, "immediate"); /*immediate word*/ for(i = 0, p = READ; names[i]; i++) /*compiling words*/ compile(COMPILE, names[i]), m[m[DIC]++] = p++; VERIFY(forth_eval(initial_forth_program) >= 0); VERIFY(forth_define_constant("size", sizeof(forth_cell_t)) >= 0); VERIFY(forth_define_constant("stack-start", CORE_SIZE - (2 * m[STACK_SIZE])) >= 0); VERIFY(forth_define_constant("max-core", CORE_SIZE) >= 0); VERIFY(forth_define_constant("source-id-reg", SOURCE_ID) >= 0); forth_set_file_input(in); /*set up input after our eval*/ return 0; } static int forth_run(void) { /* this implements the Forth virtual machine; it does all the work */ f = m[TOP]; I = m[INSTRUCTION]; for(;(pc = m[I++]);) { /* Threaded code interpreter */ INNER: switch (w = instruction(m[pc++])) { case PUSH: *++S = f; f = m[I++]; break; case COMPILE: m[m[DIC]++] = pc; break; case RUN: m[++m[RSTK]] = I; I = pc; break; case DEFINE: m[STATE] = 1; /* compile mode */ if(forth_get_word((uint8_t*)(s)) < 0) goto end; compile(COMPILE, (char*)s); m[m[DIC]++] = RUN; break; case IMMEDIATE: m[DIC] -= 2; /* move to first code field */ m[m[DIC]] &= ~INSTRUCTION_MASK; /* zero instruction */ m[m[DIC]] |= RUN; /* set instruction to RUN */ m[DIC]++; /* compilation start here */ break; case READ: m[RSTK]--; /* bit of a hack */ if(forth_get_word(s) < 0) goto end; if ((w = forth_find((char*)s)) > 1) { pc = w; if (!m[STATE] && instruction(m[pc]) == COMPILE) pc++; /* in command mode, execute word */ goto INNER; } else if(!numberify(m[BASE], &w, (char*)s)) { fprintf(stderr, "( error \"%s is not a word\" )\n", s); break; } if (m[STATE]) { /* must be a number then */ m[m[DIC]++] = 2; /*fake word push at m[2]*/ m[m[DIC]++] = w; } else { /* push word */ *++S = f; f = w; } break; case LOAD: f = m[f]; break; case STORE: m[f] = *S--; f = *S--; break; case SUB: f = *S-- - f; break; case ADD: f = *S-- + f; break; case AND: f = *S-- & f; break; case OR: f = *S-- | f; break; case XOR: f = *S-- ^ f; break; case INV: f = ~f; break; case SHL: f = *S-- << f; break; case SHR: f = (forth_cell_t)*S-- >> f; break; case MUL: f = *S-- * f; break; case DIV: if(f) f = *S-- / f; else /* should throw exception */ fputs("( error \"x/0\" )\n", stderr); break; case LESS: f = *S-- < f; break; case MORE: f = *S-- > f; break; case EXIT: I = m[m[RSTK]--]; break; case EMIT: fputc(f, (FILE*)(m[FOUT])); f = *S--; break; case KEY: *++S = f; f = forth_get_char(); break; case FROMR: *++S = f; f = m[m[RSTK]--]; break; case TOR: m[++m[RSTK]] = f; f = *S--; break; case BRANCH: I += m[I]; break; case QBRANCH: I += f == 0 ? m[I] : 1; f = *S--; break; case PNUM: print_cell(f); f = *S--; break; case QUOTE: *++S = f; f = m[I++]; break; case COMMA: m[m[DIC]++] = f; f = *S--; break; case EQUAL: f = *S-- == f; break; case SWAP: w = f; f = *S--; *++S = w; break; case DUP: *++S = f; break; case DROP: f = *S--; break; case OVER: w = *S; *++S = f; f = w; break; case FIND: *++S = f; if(forth_get_word(s) < 0) goto end; f = forth_find((char*)s); f = f < DICTIONARY_START ? 0 : f; break; case PRINT: fputs(((char*)m)+f, (FILE*)(m[FOUT])); f = *S--; break; case DEPTH: w = S - (m + CORE_SIZE - (2 * m[STACK_SIZE])); *++S = f; f = w; break; default: fprintf(stderr, "( fatal 'illegal-op %" PRIuCell " )\n", w); abort(); } } end: m[TOP] = f; return 0; } static int forth_eval(const char *s) { forth_set_string_input(s); return forth_run(); } static void forth_set_file_input(FILE *in) { m[SOURCE_ID] = FILE_IN; m[FIN] = (forth_cell_t)in; } static void forth_set_string_input(const char *s) { m[SIDX] = 0; /*m[SIDX] == current character in string*/ m[SLEN] = strlen(s) + 1; /*m[SLEN] == string len*/ m[SOURCE_ID] = STRING_IN; /*read from string, not a file handle*/ m[SIN] = (forth_cell_t)s; /*sin == pointer to string input*/ } int main(void) { if(forth_init(stdin, stdout)) { fputs("could not initialize core\n",stderr); return -1; } return forth_run(); }
2.265625
2
2024-11-18T21:06:09.605574+00:00
2023-06-25T14:52:43
b1d6fd175ae5c6d048aef1f605f91c560b3fb37d
{ "blob_id": "b1d6fd175ae5c6d048aef1f605f91c560b3fb37d", "branch_name": "refs/heads/master", "committer_date": "2023-06-25T14:52:43", "content_id": "04eddf79c243bacbee2b2935c0fd001edc9fddfe", "detected_licenses": [ "MIT" ], "directory_id": "e66eef8583f128f93f92c20420b842c9d113adde", "extension": "c", "filename": "service.c", "fork_events_count": 36, "gha_created_at": "2014-03-27T15:04:23", "gha_event_created_at": "2023-06-25T14:52:44", "gha_language": "JavaScript", "gha_license_id": "NOASSERTION", "github_id": 18179939, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2883, "license": "MIT", "license_type": "permissive", "path": "/mapmint-services/symbol-tools-src/service.c", "provenance": "stackv2-0083.json.gz:16390", "repo_name": "mapmint/mapmint", "revision_date": "2023-06-25T14:52:43", "revision_id": "8cd796895979aa9274d249222a0ee0f144e1d650", "snapshot_id": "80032041c171c85e996ae1a37469b470b0f1ba3f", "src_encoding": "UTF-8", "star_events_count": 49, "url": "https://raw.githubusercontent.com/mapmint/mapmint/8cd796895979aa9274d249222a0ee0f144e1d650/mapmint-services/symbol-tools-src/service.c", "visit_date": "2023-07-06T23:01:56.639843" }
stackv2
// FreeTypeParser.cpp : définit le point d'entrée pour l'application console. // #ifdef WIN32 #endif #include <ft2build.h> #include <freetype/freetype.h> #include FT_FREETYPE_H #include "service.h" FT_Library library; FT_Face face; extern "C" { #ifdef WIN32 __declspec(dllexport) #endif int getSymbols(maps*& conf,maps*& inputs,maps*& outputs) { FT_Error error = FT_Init_FreeType( &library ); map* tmpMap4Path=getMapFromMaps(conf,"main","dataPath"); map* tmpMap=getMapFromMaps(inputs,"ttf","value"); char ttfFile[1024]; sprintf(ttfFile,"%s/fonts/%s",tmpMap4Path->value,tmpMap->value); fprintf(stderr,"File to open : %s\n",ttfFile); error = FT_New_Face( library, ttfFile, 0, &face ); if ( error == FT_Err_Unknown_File_Format ){ setMapInMaps(conf,"lenv","message","Error unknow format"); return SERVICE_FAILED; } else if ( error ) { setMapInMaps(conf,"lenv","message","Unable to load the specified file"); return SERVICE_FAILED; } //int *charcodes=(int *)malloc(face->num_glyphs*sizeof(int)); //printf("%d|",face->num_glyphs); int n; FT_CharMap found = 0; FT_CharMap charmap; int disp=0; char *charCodes=NULL; for ( n = 0; n < face->num_charmaps; n++ ) { charmap = face->charmaps[n]; //printf("\nplatform_id : %d ; encoding_id %d\n",charmap->platform_id,charmap->encoding_id); found = charmap; error = FT_Set_Charmap( face, found ); FT_UInt agindex; FT_ULong charcode; charcode=FT_Get_First_Char(face,&agindex); int count=1; if(agindex==0){ setMapInMaps(conf,"lenv","message","Unable to find anything in your font file"); return SERVICE_FAILED; } else{ char tmp[100]; if(charCodes==NULL){ sprintf(tmp,"%d",charcode); charCodes=(char*)malloc((strlen(tmp)+2)*sizeof(char)); sprintf(charCodes,"[%s",tmp); }else{ sprintf(tmp,",%d",charcode); char *tmp2=strdup(charCodes); charCodes=(char*)realloc(charCodes,(strlen(tmp2)+strlen(tmp)+1)*sizeof(char)); memcpy(charCodes+strlen(tmp2),tmp,strlen(tmp)+1); free(tmp2); } while ( agindex != 0 ) { charcode = FT_Get_Next_Char( face, charcode, &agindex ); if(agindex != 0 ){ char tmp1[100]; sprintf(tmp1,",%d",charcode); char *tmp2=strdup(charCodes); charCodes=(char*)realloc(charCodes,(strlen(tmp2)+strlen(tmp1)+1)*sizeof(char)); memcpy(charCodes+strlen(tmp2),tmp1,strlen(tmp1)+1); free(tmp2); } } } } char *tmp2=strdup(charCodes); charCodes=(char*)realloc(charCodes,(strlen(tmp2)+2)*sizeof(char)); memcpy(charCodes+strlen(tmp2),"]",2); free(tmp2); //printf("\n**%s**\n",charCodes); setMapInMaps(outputs,"Result","value",charCodes); return SERVICE_SUCCEEDED; } }
2.328125
2
2024-11-18T21:06:09.716638+00:00
2021-11-06T03:40:02
738eda259731b872e96ae097663e451df40825cc
{ "blob_id": "738eda259731b872e96ae097663e451df40825cc", "branch_name": "refs/heads/master", "committer_date": "2021-11-06T03:40:02", "content_id": "515662b8747786cf6047a561bda4d32aab0ea2c0", "detected_licenses": [ "MIT" ], "directory_id": "825800c74893c32bf39d7aab7e662963bd4cff98", "extension": "c", "filename": "Exercício12.c", "fork_events_count": 0, "gha_created_at": "2019-07-09T19:33:08", "gha_event_created_at": "2023-03-05T23:10:38", "gha_language": "Jupyter Notebook", "gha_license_id": null, "github_id": 196071582, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 354, "license": "MIT", "license_type": "permissive", "path": "/C-licious/Lista-1/Exercício12.c", "provenance": "stackv2-0083.json.gz:16518", "repo_name": "PauloKeller/Grade-Projects", "revision_date": "2021-11-06T03:40:02", "revision_id": "c8fdf4133d12a746173f1f0c3b14be30675951f5", "snapshot_id": "230d88ace26b5a76e6e76779fc1e5903f8b82f03", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PauloKeller/Grade-Projects/c8fdf4133d12a746173f1f0c3b14be30675951f5/C-licious/Lista-1/Exercício12.c", "visit_date": "2023-03-16T02:39:09.612282" }
stackv2
#include <stdio.h> int main() { int n,fant=0,fatual=1,fprox,contador=1; printf("Digite o numero:"); scanf("%d", &n); if (n < 2) { printf("%d", n); } else while (contador < n) { fprox = fatual + fant; fant = fatual; fatual = fprox; contador = contador + 1; } printf("O numero fibonacci e %d", fatual); return 0; }
3.15625
3
2024-11-18T21:06:10.547757+00:00
2023-07-29T21:54:06
67149ac87a5c5549fc11a1a1c77ef519f56568f5
{ "blob_id": "67149ac87a5c5549fc11a1a1c77ef519f56568f5", "branch_name": "refs/heads/master", "committer_date": "2023-07-29T21:54:06", "content_id": "4a31ed609370b59ed484c49772c1bd18b896b45b", "detected_licenses": [ "MIT" ], "directory_id": "84e97d818876d20fab9591ff9d88129acfcc4295", "extension": "c", "filename": "system.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 6969810, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3798, "license": "MIT", "license_type": "permissive", "path": "/platform/lpc/lpc43xx/system.c", "provenance": "stackv2-0083.json.gz:17030", "repo_name": "stxent/halm", "revision_date": "2023-07-29T21:54:06", "revision_id": "7396d3d639e696cca262fc926b245e296c22bad1", "snapshot_id": "93bd734be36e4828693551f8184173ba74b338be", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/stxent/halm/7396d3d639e696cca262fc926b245e296c22bad1/platform/lpc/lpc43xx/system.c", "visit_date": "2023-08-08T13:10:39.034473" }
stackv2
/* * system.c * Copyright (C) 2012 xent * Project is distributed under the terms of the MIT License */ #include <halm/platform/lpc/lpc43xx/system_defs.h> #include <halm/platform/lpc/system.h> /*----------------------------------------------------------------------------*/ static LPC_CCU_BRANCH_Type *calcBranchReg(enum SysClockBranch); /*----------------------------------------------------------------------------*/ static LPC_CCU_BRANCH_Type *calcBranchReg(enum SysClockBranch branch) { if (branch < 0x200) return &LPC_CCU1->BRANCH[branch]; else return &LPC_CCU2->BRANCH[branch - 0x200]; } /*----------------------------------------------------------------------------*/ void sysClockEnable(enum SysClockBranch branch) { calcBranchReg(branch)->CFG |= CFG_RUN | CFG_AUTO | CFG_WAKEUP; } /*----------------------------------------------------------------------------*/ void sysClockDisable(enum SysClockBranch branch) { LPC_CCU_BRANCH_Type * const reg = calcBranchReg(branch); /* Use AHB disable protocol and do not enable clock after wake up */ reg->CFG = (reg->CFG & ~CFG_WAKEUP) | CFG_AUTO; reg->CFG &= ~CFG_RUN; /* Disable clock */ } /*----------------------------------------------------------------------------*/ bool sysClockStatus(enum SysClockBranch branch) { return (calcBranchReg(branch)->STAT & STAT_RUN) != 0; } /*----------------------------------------------------------------------------*/ void sysFlashEnable(unsigned int bank) { /* Flash bank A or B */ LPC_CREG->FLASHCFG[bank] |= FLASHCFG_POW; } /*----------------------------------------------------------------------------*/ void sysFlashDisable(unsigned int bank) { LPC_CREG->FLASHCFG[bank] &= ~FLASHCFG_POW; } /*----------------------------------------------------------------------------*/ unsigned int sysFlashLatency(void) { /* Return access time for one of the banks */ return FLASHCFG_FLASHTIM_VALUE(LPC_CREG->FLASHCFGA) + 1; } /*----------------------------------------------------------------------------*/ /** * Set the flash access time. * @param value Flash access time in CPU clocks. * @n Possible values and recommended operating frequencies: * - 1 clock: up to 21 MHz. * - 2 clocks: up to 43 MHz. * - 3 clocks: up to 64 MHz. * - 4 clocks: up to 86 MHz. * - 5 clocks: up to 107 MHz. * - 6 clocks: up to 129 MHz. * - 7 clocks: up to 150 MHz. * - 8 clocks: up to 172 MHz. * - 9 clocks: up to 193 MHz. * - 10 clocks: up to 204 MHz, safe setting for all allowed conditions. */ void sysFlashLatencyUpdate(unsigned int value) { const uint32_t data = FLASHCFG_FLASHTIM(value - 1); /* Update flash access time for all flash banks */ LPC_CREG->FLASHCFGA = (LPC_CREG->FLASHCFGA & ~FLASHCFG_FLASHTIM_MASK) | data; LPC_CREG->FLASHCFGB = (LPC_CREG->FLASHCFGB & ~FLASHCFG_FLASHTIM_MASK) | data; } /*----------------------------------------------------------------------------*/ void sysFlashLatencyReset(void) { sysFlashLatencyUpdate(10); } /*----------------------------------------------------------------------------*/ void sysResetEnable(enum SysBlockReset block) { const uint32_t mask = 1UL << (block & 0x1F); const unsigned int index = block >> 5; LPC_RGU->RESET_CTRL[index] = ~LPC_RGU->RESET_ACTIVE_STATUS[index] | mask; if (block != RST_M0SUB && block != RST_M0APP) { /* Wait for reset to be cleared */ while (!(LPC_RGU->RESET_ACTIVE_STATUS[index] & mask)); } } /*----------------------------------------------------------------------------*/ void sysResetDisable(enum SysBlockReset block) { const uint32_t mask = 1UL << (block & 0x1F); const unsigned int index = block >> 5; if (block == RST_M0SUB || block == RST_M0APP) LPC_RGU->RESET_CTRL[index] = ~(LPC_RGU->RESET_ACTIVE_STATUS[index] | mask); }
2.4375
2
2024-11-18T21:06:12.129383+00:00
2021-09-30T13:06:23
2415cfe86bf6fc787a8f455a52febbacac3d58f7
{ "blob_id": "2415cfe86bf6fc787a8f455a52febbacac3d58f7", "branch_name": "refs/heads/master", "committer_date": "2021-09-30T13:06:23", "content_id": "6f5b67c7912fbab9af33d4a3ebd3f24944b5c04e", "detected_licenses": [ "MIT" ], "directory_id": "f673d8de788484896af9108937461e85ef09ce29", "extension": "c", "filename": "main_stack_1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 131863185, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 409, "license": "MIT", "license_type": "permissive", "path": "/old/Stack/Stack_1_array/main_stack_1.c", "provenance": "stackv2-0083.json.gz:17546", "repo_name": "PetropoulakisPanagiotis/algorithms-data-structures", "revision_date": "2021-09-30T13:06:23", "revision_id": "70ec78e9c4f8164bf29269fe621c1029969fc4f4", "snapshot_id": "b107d14ee43172a7d64dec29c3b8645777c2c40e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PetropoulakisPanagiotis/algorithms-data-structures/70ec78e9c4f8164bf29269fe621c1029969fc4f4/old/Stack/Stack_1_array/main_stack_1.c", "visit_date": "2023-08-06T23:36:20.230870" }
stackv2
#include <stdio.h> #include "stack_1.h" int main(void){ stack_1 stack_test; // We have one stack named: stack_test. int status; // Overflow or underflow. type_s save; // So as to take a value from stack. start_stack(&stack_test); // Begin from empty stack. push(&stack_test,50,&status); push(&stack_test,35,&status); pop(&stack_test,&save,&status); return 0; }
2.703125
3
2024-11-18T21:06:12.384770+00:00
2019-03-05T15:21:20
4f1c2d6418bb17f0c35ba64b86bc7e2a135691a8
{ "blob_id": "4f1c2d6418bb17f0c35ba64b86bc7e2a135691a8", "branch_name": "refs/heads/master", "committer_date": "2019-03-05T15:21:20", "content_id": "dbf4d1ee27eda98c1e4d6b0bb8431034a8d4ade8", "detected_licenses": [ "MIT" ], "directory_id": "808f6f1207652d9985934ed4cb9802e941569979", "extension": "h", "filename": "FilePack.h", "fork_events_count": 0, "gha_created_at": "2018-07-12T14:35:17", "gha_event_created_at": "2019-02-14T00:41:54", "gha_language": "HTML", "gha_license_id": "MIT", "github_id": 140725289, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2419, "license": "MIT", "license_type": "permissive", "path": "/zurapce/FilePack.h", "provenance": "stackv2-0083.json.gz:17932", "repo_name": "zurachu/bbball", "revision_date": "2019-03-05T15:21:20", "revision_id": "70c19e448dd3390e980dc185480c118fb682f05d", "snapshot_id": "3cb1f1871f937a0f588a310beb40a9b65ad1b526", "src_encoding": "SHIFT_JIS", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zurachu/bbball/70c19e448dd3390e980dc185480c118fb682f05d/zurapce/FilePack.h", "visit_date": "2020-03-22T21:58:21.641243" }
stackv2
#if !defined( ZURAPCE_FILE_PACK_H ) #define ZURAPCE_FILE_PACK_H /** @file ファイルパック 関連. P/ECE 開発環境付属の FilePack.exe で生成したパックデータからファイルを抽出します。 @author zurachu */ #include <piece.h> // FILEACC /// パックファイル読み込みハンドル struct FilePackHandle { FILEACC file_acc; ///< ファイル構造体 int file_amount; ///< ファイル数 /** 16bit CRC. ファイル探索時、まずファイル名から取得した CRC が同一か比較し、 同一なら実際にファイル名を比較することで、読み込みの高速化を図る。 ハンドルを開くと、ファイル数×2バイト確保されます。 (Autch氏の libfpk に pceth2 で nsawa氏が施した改良を取り込み) */ unsigned short* crc; }; typedef struct FilePackHandle FilePackHandle; /** ハンドルを開く. @param handle ハンドル @param filename パックファイル名 @retval 0 正常終了 @retval 1 パックファイルが無い */ int FilePackHandle_Open( FilePackHandle* handle, char const* filename ); /** ハンドルを閉じる. @param handle ハンドル @retval 0 常に正常終了 */ int FilePackHandle_Close( FilePackHandle* handle ); /** パックファイルから1ファイルを読み込んでバッファに格納. @param dst 出力先バッファ @param handle ハンドル @param filename ファイル名 @return 読み込みサイズ(失敗時0) @see FileAcc_ReadPosTo() */ int FilePackHandle_ReadTo( unsigned char* dst, FilePackHandle* handle, char const* filename ); /** ファイルサイズ分のヒープを確保して読み込み. @param handle ハンドル @param filename ファイル名 @return 読み込んだヒープ(失敗時 NULL) @warning 不要になったヒープは pceHeapAlloc() で解放すること。 @see FileAcc_ReadPosAlloc() */ unsigned char* FilePackHandle_ReadAlloc( FilePackHandle* handle, char const* filename ); /** メモリ上のパックデータから、指定ファイルへのポインタを取得. デコードsrc の FPK_FindPackData() と等価。 @param filename ファイル名 @param source パックデータ @return 指定ファイルへのポインタ(失敗時 NULL) */ unsigned char* FilePack_Data( char const* filename, unsigned char* source ); #endif // !defined( ZURAPCE_FILE_PACK_H )
2.03125
2
2024-11-18T21:06:12.576636+00:00
2019-02-17T22:30:07
7586c1d5c6836204a401c2d61499ebfc9e38ac68
{ "blob_id": "7586c1d5c6836204a401c2d61499ebfc9e38ac68", "branch_name": "refs/heads/master", "committer_date": "2019-02-17T22:30:07", "content_id": "ed71c5de143030adb868058c2933a6ebc5aba668", "detected_licenses": [ "MIT" ], "directory_id": "c6501dc2148f52aed380eaeb30a69fc3f2e1d611", "extension": "c", "filename": "fizzbuzz.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 168613509, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 294, "license": "MIT", "license_type": "permissive", "path": "/fizzbuzz.c", "provenance": "stackv2-0083.json.gz:18062", "repo_name": "OscarEsC/justC", "revision_date": "2019-02-17T22:30:07", "revision_id": "a048abc73c8ce67115a24d2e8585874797f78084", "snapshot_id": "216344517e6cfbfcfc5b727bff229edfecf505cc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/OscarEsC/justC/a048abc73c8ce67115a24d2e8585874797f78084/fizzbuzz.c", "visit_date": "2020-04-20T03:57:57.082015" }
stackv2
/* Practica 1: FizzBuzz Autor: Espinosa Curiel Oscar */ #include <stdio.h> int main(){ int i; for(i = 30; i > 0; i--) //Utilizo operadores tenarios anidados para la impresion //correspondiente printf((i%15==0)?"FizzBuzz\n":(i%5==0)?"Buzz\n":(i%3==0)?"Fizz\n":"%d\n",i); return 0; }
3.109375
3
2024-11-18T21:06:12.980446+00:00
2014-08-04T21:06:38
101f49e80f30ad1fd4c283e19d0c843c82d7affd
{ "blob_id": "101f49e80f30ad1fd4c283e19d0c843c82d7affd", "branch_name": "refs/heads/master", "committer_date": "2014-08-04T21:06:38", "content_id": "d891b1d2592f9630e5ff7579f4fb49dc75ac8076", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "b595051064323b19ddd91597fd240ff9fcd5daed", "extension": "c", "filename": "joinlayers.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19053, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/joinlayers.c", "provenance": "stackv2-0083.json.gz:18577", "repo_name": "nakhmani/neuroelf", "revision_date": "2014-08-04T21:06:38", "revision_id": "eb87678c86c85077a79f0e9a868830a32d54f079", "snapshot_id": "4ef6aacd04c2f891ebac4fff6ca72f53cfe15f2a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nakhmani/neuroelf/eb87678c86c85077a79f0e9a868830a32d54f079/joinlayers.c", "visit_date": "2020-04-11T01:15:31.134120" }
stackv2
/* joining of transimg layers into a HxWx3 uint8 image + HxW double alpha map FORMAT: [j, a] = joinlayers(tio, l [, o]) Input fields: tio 1x1 struct of transimg content l layer spec (numbers) o override flag (default: false) Output fields: j HxWx3 single image [0.0 .. 255.0] a HxW single alpha map [0.0 .. 1.0] % Version: v0.9b % Build: 11050511 % Date: Aug-07 2010, 6:02 PM EST % Author: Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA % URL/Info: http://neuroelf.net/ Copyright (c) 2010, Jochen Weber 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 Columbia University 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 HOLDERS 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 "mex.h" #include "math.h" #include <stdio.h> void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* dimensions */ int h = 0, w = 0, hw = 0, hw3 = 0, nl = 0, ln = 0, lc = 0, lfield = -1, pfield = -1, afield = -1, ndp = 0, nda = 0, pc = 0, nlist = 0; int od[3] = {0, 0, 3}; const mxArray *layer = NULL, *inpp = NULL, *inpa = NULL; /* pointers */ const double *dp = NULL, *llist = NULL; const unsigned char *pp = NULL, *pp2 = NULL, *pp3 = NULL; const float *ap = NULL, *fpp = NULL, *fpp2 = NULL, *fpp3 = NULL; float *app = NULL, *appp = NULL, *opp = NULL; /* background color */ float al = 1.0, alm = 0.0, oal = 1.0; /* override flag */ bool override = 0; /* output pointers */ float *bf1 = NULL, *bf2 = NULL, *bf3 = NULL; /* variable output string */ /* char vstr[256]; */ /* check number, type, fields of in/out arguments */ if ((nrhs < 2) || (nlhs != 2)) mexErrMsgTxt("Bad number of input/output arguments."); if (!mxIsStruct(*prhs)) mexErrMsgTxt("First input must be of type struct."); if (!mxIsDouble(prhs[1])) mexErrMsgTxt("Second input must be of type double."); nlist = mxGetNumberOfElements(prhs[1]); llist = (const double *) mxGetData(prhs[1]); lfield = mxGetFieldNumber(*prhs, "Layer"); if ((mxGetFieldNumber(*prhs, "Height") < 0) || (lfield < 0) || (mxGetFieldNumber(*prhs, "Width") < 0)) mexErrMsgTxt("Required field missing."); layer = mxGetFieldByNumber(*prhs, 0, lfield); if (!mxIsStruct(layer)) mexErrMsgTxt(".Layer field must be of type struct."); pfield = mxGetFieldNumber(layer, "Pixel"); afield = mxGetFieldNumber(layer, "Alpha"); if ((pfield < 0) || (afield < 0)) mexErrMsgTxt(".Layer field must have subfields .Pixel and .Alpha."); nl = mxGetNumberOfElements(layer); inpa = (const mxArray *) mxGetField(*prhs, 0, "Height"); if (mxGetNumberOfElements(inpa) != 1) mexErrMsgTxt("Invalid .Height field."); if (!mxIsDouble(inpa)) mexErrMsgTxt("Invalid .Height field datatype."); dp = (const double *) mxGetData(inpa); h = (int) *dp; inpa = (const mxArray *) mxGetField(*prhs, 0, "Width"); if (mxGetNumberOfElements(inpa) != 1) mexErrMsgTxt("Invalid .Width field."); if (!mxIsDouble(inpa)) mexErrMsgTxt("Invalid .Width field datatype."); dp = (const double *) mxGetData(inpa); w = (int) *dp; *od = h; od[1] = w; hw = h * w; hw3 = 3 * hw; /* check override flag */ if ((nrhs > 2) && (mxIsLogical(prhs[2])) && (mxGetNumberOfElements(prhs[2]) == 1)) { /* set to true if true */ if ((* ((const unsigned char *) mxGetData(prhs[2]))) > 0) override = 1; } /* create output */ *plhs = (mxArray *) mxCreateNumericArray(3, od, mxSINGLE_CLASS, mxREAL); if (*plhs == NULL) mexErrMsgTxt("Error creating j output."); opp = (float *) mxGetData(*plhs); if (opp == NULL) mexErrMsgTxt("Error getting data pointer to j output mxArray."); plhs[1] = (mxArray *) mxCreateNumericArray(2, od, mxSINGLE_CLASS, mxREAL); if (plhs[1] == NULL) { mxDestroyArray(*plhs); mexErrMsgTxt("Error creating a output."); } app = (float *) mxGetData(plhs[1]); if (app == NULL) { mxDestroyArray(*plhs); mexErrMsgTxt("Error getting data pointer to a output mxArray."); } /* parse layers */ for (lc = 0; lc < nlist; ++lc) { /* get pixel and alpha information */ ln = (int) *llist++; if ((ln < 1) || (ln > nl)) continue; --ln; inpp = mxGetFieldByNumber(layer, ln, pfield); inpa = mxGetFieldByNumber(layer, ln, afield); ndp = mxGetNumberOfDimensions(inpp); nda = mxGetNumberOfDimensions(inpa); if (((!mxIsUint8(inpp)) && (!mxIsSingle(inpp))) || (!mxIsSingle(inpa)) || (ndp > 3) || (nda > 2)) { mxDestroyArray(*plhs); mxDestroyArray(plhs[1]); mexErrMsgTxt("Invalid .Pixel/.Alpha field types/dims."); } ndp = mxGetNumberOfElements(inpp); nda = mxGetNumberOfElements(inpa); if (((ndp != hw) && (ndp != hw3)) || ((nda != 1) && (nda != hw))) { mxDestroyArray(*plhs); mxDestroyArray(plhs[1]); mexErrMsgTxt("Invalid .Pixel/.Alpha field sizes."); } ap = (const float *) mxGetData(inpa); /* skip invisible layers */ if ((nda == 1) && (*ap == 0.0)) continue; /* depending on override flag -> override on (not default!) */ if (override) { /* depending on type -> uint8 */ if (mxIsUint8(inpp)) { /* get data (as uint8 -> unsigned char) */ pp = (const unsigned char *) mxGetData(inpp); /* depending on size of alpha */ if (nda == 1) { /* get alpha value */ al = *ap; /* depending on size of pixels */ if (ndp == hw3) { /* iterate over pixel */ for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], pp2 = &pp[hw], pp3 = &pp2[hw], appp = app, pc = hw; pc > 0; --pc) { oal = *appp * (1.0 - al); *bf1 = oal * *bf1 + al * ((float) *pp++); ++bf1; *bf2 = oal * *bf2 + al * ((float) *pp2++); ++bf2; *bf3 = oal * *bf3 + al * ((float) *pp3++); ++bf3; *appp++ = oal + al; } } else { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], appp = app, pc = hw; pc > 0; --pc) { oal = *appp * (1.0 - al); alm = al * ((float) *pp++); *bf1 = oal * *bf1 + alm; ++bf1; *bf2 = oal * *bf2 + alm; ++bf2; *bf3 = oal * *bf3 + alm; ++bf3; *appp++ = oal + al; } } } else { if (ndp == hw3) { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], pp2 = &pp[hw], pp3 = &pp2[hw], appp = app, pc = hw; pc > 0; --pc) { al = *ap++; if (al > 0.0) { oal = *appp * (1.0 - al); *bf1 = oal * *bf1 + al * ((float) *pp++); ++bf1; *bf2 = oal * *bf2 + al * ((float) *pp2++); ++bf2; *bf3 = oal * *bf3 + al * ((float) *pp3++); ++bf3; *appp++ = oal + al; } else { ++bf1; ++bf2; ++bf3; ++appp; ++pp; ++pp2; ++pp3; } } } else { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], appp = app, pc = hw; pc > 0; --pc) { al = *ap++; if (al > 0.0) { oal = *appp * (1.0 - al); alm = al * ((float) *pp++); *bf1 = oal * *bf1 + alm; ++bf1; *bf2 = oal * *bf2 + alm; ++bf2; *bf3 = oal * *bf3 + alm; ++bf3; *appp++ = oal + al; } else { ++bf1; ++bf2; ++bf3; ++appp; ++pp; } } } } /* type -> single */ } else { /* get data (as single -> float) */ fpp = (const float *) mxGetData(inpp); /* depending on size of alpha */ if (nda == 1) { /* get alpha value */ al = *ap; /* depending on size of pixels */ if (ndp == hw3) { /* iterate over pixel */ for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], fpp2 = &fpp[hw], fpp3 = &fpp2[hw], appp = app, pc = hw; pc > 0; --pc) { oal = *appp * (1.0 - al); *bf1 = oal * *bf1 + al * *fpp++; ++bf1; *bf2 = oal * *bf2 + al * *fpp2++; ++bf2; *bf3 = oal * *bf3 + al * *fpp3++; ++bf3; *appp++ = oal + al; } } else { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], appp = app, pc = hw; pc > 0; --pc) { oal = *appp * (1.0 - al); alm = al * *fpp++; *bf1 = oal * *bf1 + alm; ++bf1; *bf2 = oal * *bf2 + alm; ++bf2; *bf3 = oal * *bf3 + alm; ++bf3; *appp++ = oal + al; } } } else { if (ndp == hw3) { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], fpp2 = &fpp[hw], fpp3 = &fpp2[hw], appp = app, pc = hw; pc > 0; --pc) { al = *ap++; if (al > 0.0) { oal = *appp * (1.0 - al); *bf1 = oal * *bf1 + al * *fpp++; ++bf1; *bf2 = oal * *bf2 + al * *fpp2++; ++bf2; *bf3 = oal * *bf3 + al * *fpp3++; ++bf3; *appp++ = oal + al; } else { ++bf1; ++bf2; ++bf3; ++appp; ++fpp; ++fpp2; ++fpp3; } } } else { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], appp = app, pc = hw; pc > 0; --pc) { al = *ap++; if (al > 0.0) { oal = *appp * (1.0 - al); alm = al * *fpp++; *bf1 = oal * *bf1 + alm; ++bf1; *bf2 = oal * *bf2 + alm; ++bf2; *bf3 = oal * *bf3 + alm; ++bf3; *appp++ = oal + al; } else { ++bf1; ++bf2; ++bf3; ++appp; ++fpp; } } } } } /* override off (default!) */ } else { /* depending on type -> uint8 */ if (mxIsUint8(inpp)) { /* get data (as uint8 -> unsigned char) */ pp = (const unsigned char *) mxGetData(inpp); /* depending on size of alpha */ if (nda == 1) { /* get alpha value */ al = *ap; /* depending on size of pixels */ if (ndp == hw3) { /* iterate over pixel */ for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], pp2 = &pp[hw], pp3 = &pp2[hw], appp = app, pc = hw; pc > 0; --pc) { *bf1++ += al * ((float) *pp++); *bf2++ += al * ((float) *pp2++); *bf3++ += al * ((float) *pp3++); *appp++ += al; } } else { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], appp = app, pc = hw; pc > 0; --pc) { alm = al * ((float) *pp++); *bf1++ += alm; *bf2++ += alm; *bf3++ += alm; *appp++ += al; } } } else { if (ndp == hw3) { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], pp2 = &pp[hw], pp3 = &pp2[hw], appp = app, pc = hw; pc > 0; --pc) { al = *ap++; *bf1++ += al * ((float) *pp++); *bf2++ += al * ((float) *pp2++); *bf3++ += al * ((float) *pp3++); *appp++ += al; } } else { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], appp = app, pc = hw; pc > 0; --pc) { al = *ap++; alm = al * ((float) *pp++); *bf1++ += alm; *bf2++ += alm; *bf3++ += alm; *appp++ += al; } } } /* type -> single */ } else { /* get data (as single -> float) */ fpp = (const float *) mxGetData(inpp); /* depending on size of alpha */ if (nda == 1) { /* get alpha value */ al = *ap; /* depending on size of pixels */ if (ndp == hw3) { /* iterate over pixel */ for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], fpp2 = &fpp[hw], fpp3 = &fpp2[hw], appp = app, pc = hw; pc > 0; --pc) { *bf1++ += al * *fpp++; *bf2++ += al * *fpp2++; *bf3++ += al * *fpp3++; *appp++ += al; } } else { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], appp = app, pc = hw; pc > 0; --pc) { alm = al * *fpp++; *bf1++ += alm; *bf2++ += alm; *bf3++ += alm; *appp++ += al; } } } else { if (ndp == hw3) { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], fpp2 = &fpp[hw], fpp3 = &fpp2[hw], appp = app, pc = hw; pc > 0; --pc) { al = *ap++; *bf1++ += al * *fpp++; *bf2++ += al * *fpp2++; *bf3++ += al * *fpp3++; *appp++ += al; } } else { for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], appp = app, pc = hw; pc > 0; --pc) { al = *ap++; alm = al * *fpp++; *bf1++ += alm; *bf2++ += alm; *bf3++ += alm; *appp++ += al; } } } } } } /* max scale alpha to 1.0 */ if (override) for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], pc = hw; pc > 0; --pc, ++app, ++bf1, ++bf2, ++bf3) { al = *app; if (al > 0.0) { *bf1 /= al; *bf2 /= al; *bf3 /= al; } else { *bf1 = 0.0; *bf2 = 0.0; *bf3 = 0.0; } } else for (bf1 = opp, bf2 = &bf1[hw], bf3 = &bf2[hw], pc = hw; pc > 0; --pc, ++app, ++bf1, ++bf2, ++bf3) { al = *app; if (al > 0.0) { *bf1 /= al; *bf2 /= al; *bf3 /= al; } if (al > 1.0) *app = 1.0; } }
2.015625
2
2024-11-18T21:06:13.661725+00:00
2016-05-18T14:27:10
820b0b1715fc378ce6d6367f1e4c580c6b3ed640
{ "blob_id": "820b0b1715fc378ce6d6367f1e4c580c6b3ed640", "branch_name": "refs/heads/master", "committer_date": "2016-05-18T14:27:10", "content_id": "ece8b34ed4c360720997e40bb5ae39ef5a4413c0", "detected_licenses": [ "CC0-1.0" ], "directory_id": "f1535575b0f0d97120d9fdcb7b1466d80daf624e", "extension": "c", "filename": "freq.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 58933439, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1425, "license": "CC0-1.0", "license_type": "permissive", "path": "/programas/freq.c", "provenance": "stackv2-0083.json.gz:19091", "repo_name": "paulomupucrs/laproi-muken", "revision_date": "2016-05-18T14:27:10", "revision_id": "6594589d1faad7af57238451e84e73c81c050b91", "snapshot_id": "e992dccf0870c4c367e96b86d8fcd5e7a0ec7148", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/paulomupucrs/laproi-muken/6594589d1faad7af57238451e84e73c81c050b91/programas/freq.c", "visit_date": "2021-01-01T05:16:33.086040" }
stackv2
/* Autor: Paulo Vianna Mu <paulo.mu@acad.pucrs.br> & Fernando Ken <fernando.ken@acad.pucrs.br> Descrição: Exibe o(s) caractere(s) mais frequente(s) do arquivo. */ #include <stdio.h> int main(int argc, char* argv[]) { if (argc != 2){ printf("A forma correta de usar o comando é freq.o [nome do arquivo](burro).\n"); return 1; } FILE *arquivo; printf("Vamos ler o arquivo '%s'...\n", argv[1]); arquivo = fopen(argv[1], "r"); int maior = 0; int empate[256] = {0}; if (arquivo != NULL) { int contagemLetras[256] = {0}; char c; while ((c = getc(arquivo)) != EOF) { int index; if (c >= 32 && c <= 90) index = c + 32; else index = c; contagemLetras[index] ++; } int i; for (i = 32; i < 127; i++) { // if (contagemLetras[i]) printf("%5d ['%c'] = %i ocorrência(s)\n", i, i, contagemLetras[i]); if (contagemLetras[i] > contagemLetras[maior]) maior = i; if (contagemLetras[i] == contagemLetras[maior]) empate[i] = 1; } } else { printf("Falha ao abrir o arquivo!\n"); return 1; } printf("\n"); int x; int empatou = 0; for (x = 0; x < 256; x++) { if (empate[x]) { empatou = 1; if (x == 255) printf("['%c']", x); } } if (empatou) printf(" são os caracteres que mais apareceram no arquivo.\n"); else printf("['%c'] é o caractere que mais aparece no arquivo.\n", maior); fclose(arquivo); return 0; }
3.359375
3
2024-11-18T21:06:13.938601+00:00
2019-05-07T21:01:24
da67573111b0d5401703bc473c65681169390f75
{ "blob_id": "da67573111b0d5401703bc473c65681169390f75", "branch_name": "refs/heads/master", "committer_date": "2019-05-07T21:01:24", "content_id": "ebd6956bc13c7c8a891acf46a92c8cb15a72fa2d", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "8b0231925099f101f21b12df18d1b3c42097343f", "extension": "c", "filename": "VkPhysicalDeviceMaintenance3Properties.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 172877300, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3751, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/1.1/src/c/cz/mg/vulkan/VkPhysicalDeviceMaintenance3Properties.c", "provenance": "stackv2-0083.json.gz:19349", "repo_name": "Gekoncze/MgVulkan", "revision_date": "2019-05-07T21:01:24", "revision_id": "2d2ebc0d3df6640d1f18cff32e9782542b0a441e", "snapshot_id": "95e414b9dd321c05fd3eb2829f0701d7d2501bfe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Gekoncze/MgVulkan/2d2ebc0d3df6640d1f18cff32e9782542b0a441e/1.1/src/c/cz/mg/vulkan/VkPhysicalDeviceMaintenance3Properties.c", "visit_date": "2020-04-25T15:23:34.178634" }
stackv2
#include <jni.h> #include <stdlib.h> #include <string.h> #include <vulkan/vulkan.h> jlong jniPointerToLong(const void* p); void* jniLongToPointer(jlong l); jlong jniFunctionPointerToLong(PFN_vkVoidFunction p); PFN_vkVoidFunction jniLongToFunctionPointer(jlong l); void jniThrowException(JNIEnv* env, const char* message); jlong Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_sizeof(JNIEnv* env, jclass jc) { (void)env; (void)jc; return sizeof(VkPhysicalDeviceMaintenance3Properties); } void Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_setNative(JNIEnv* env, jclass jc, jlong o1, jlong o2) { (void)env; (void)jc; memcpy(jniLongToPointer(o1), jniLongToPointer(o2), sizeof(VkPhysicalDeviceMaintenance3Properties)); } jlong Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_getSTypeNative(JNIEnv* env, jclass jc, jlong address) { (void)env; (void)jc; VkPhysicalDeviceMaintenance3Properties* o = (VkPhysicalDeviceMaintenance3Properties*)jniLongToPointer(address); return jniPointerToLong(&o->sType); } void Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_setSTypeNative(JNIEnv* env, jclass jc, jlong address, jlong valueAddress) { (void)env; (void)jc; VkPhysicalDeviceMaintenance3Properties* o = (VkPhysicalDeviceMaintenance3Properties*)jniLongToPointer(address); void* valuePointer = jniLongToPointer(valueAddress); memcpy(&o->sType, valuePointer, sizeof(o->sType)); } jlong Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_getPNextNative(JNIEnv* env, jclass jc, jlong address) { (void)env; (void)jc; VkPhysicalDeviceMaintenance3Properties* o = (VkPhysicalDeviceMaintenance3Properties*)jniLongToPointer(address); return jniPointerToLong(o->pNext); } void Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_setPNextNative(JNIEnv* env, jclass jc, jlong address, jlong valueAddress) { (void)env; (void)jc; VkPhysicalDeviceMaintenance3Properties* o = (VkPhysicalDeviceMaintenance3Properties*)jniLongToPointer(address); void* valuePointer = jniLongToPointer(valueAddress); memcpy(&o->pNext, &valuePointer, sizeof(o->pNext)); } jlong Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_getMaxPerSetDescriptorsNative(JNIEnv* env, jclass jc, jlong address) { (void)env; (void)jc; VkPhysicalDeviceMaintenance3Properties* o = (VkPhysicalDeviceMaintenance3Properties*)jniLongToPointer(address); return jniPointerToLong(&o->maxPerSetDescriptors); } void Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_setMaxPerSetDescriptorsNative(JNIEnv* env, jclass jc, jlong address, jlong valueAddress) { (void)env; (void)jc; VkPhysicalDeviceMaintenance3Properties* o = (VkPhysicalDeviceMaintenance3Properties*)jniLongToPointer(address); void* valuePointer = jniLongToPointer(valueAddress); memcpy(&o->maxPerSetDescriptors, valuePointer, sizeof(o->maxPerSetDescriptors)); } jlong Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_getMaxMemoryAllocationSizeNative(JNIEnv* env, jclass jc, jlong address) { (void)env; (void)jc; VkPhysicalDeviceMaintenance3Properties* o = (VkPhysicalDeviceMaintenance3Properties*)jniLongToPointer(address); return jniPointerToLong(&o->maxMemoryAllocationSize); } void Java_cz_mg_vulkan_VkPhysicalDeviceMaintenance3Properties_setMaxMemoryAllocationSizeNative(JNIEnv* env, jclass jc, jlong address, jlong valueAddress) { (void)env; (void)jc; VkPhysicalDeviceMaintenance3Properties* o = (VkPhysicalDeviceMaintenance3Properties*)jniLongToPointer(address); void* valuePointer = jniLongToPointer(valueAddress); memcpy(&o->maxMemoryAllocationSize, valuePointer, sizeof(o->maxMemoryAllocationSize)); }
2.15625
2
2024-11-18T21:06:14.590127+00:00
2021-01-02T15:15:37
e7aa063267adf932af51bab8f859b12774ac6e68
{ "blob_id": "e7aa063267adf932af51bab8f859b12774ac6e68", "branch_name": "refs/heads/master", "committer_date": "2021-01-02T15:15:37", "content_id": "24347165220f4226ad868d7b25a16d41fe356732", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "bc92c058b0c2dd2877648e30156245e36ee571a4", "extension": "c", "filename": "time_record.c", "fork_events_count": 0, "gha_created_at": "2020-11-03T06:11:06", "gha_event_created_at": "2020-12-08T07:48:54", "gha_language": null, "gha_license_id": "BSD-2-Clause", "github_id": 309591131, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1570, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/source/common/xstream/framework/tools/xstream_prof/library/time_record.c", "provenance": "stackv2-0083.json.gz:20378", "repo_name": "robort-yuan/AI-EXPRESS", "revision_date": "2021-01-02T15:15:37", "revision_id": "56f86d03afbb09f42c21958c8cd9f2f1c6437f48", "snapshot_id": "c1783f5f155b918dcc6da11956c842ae5467de8e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/robort-yuan/AI-EXPRESS/56f86d03afbb09f42c21958c8cd9f2f1c6437f48/source/common/xstream/framework/tools/xstream_prof/library/time_record.c", "visit_date": "2023-02-09T03:51:44.775020" }
stackv2
/** * Copyright 2019 Horizon Robotics * @brief time record * @date 2020-01-15 * @author zhuoran.rong(zhuoran.rong@horizon.ai) **/ #include "time_record.h" // NOLINT #include <pthread.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/syscall.h> #include <sys/time.h> #include <unistd.h> // 获得线程ID #define gettid() syscall(__NR_gettid) // 时间记录flag volatile uint32_t __tr_record_enable = 0; static FILE *log_file = NULL; static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER; // 开始时间记录 int tr_start() { char *log_file_parh = getenv("TR_LOG_FILE"); if (!log_file_parh) { fprintf(stderr, "Time Record: log file not specified!\n"); return -1; } log_file = fopen(log_file_parh, "wb"); if (!log_file) { perror("fopen"); return -1; } __tr_record_enable = 1; return 1; } // 结束时间记录 void tr_stop() { __tr_record_enable = 0; if (!log_file) { return; } fflush(log_file); fclose(log_file); log_file = NULL; } // 记录日志 int tr_record(int start, const char *func, const char *fmt, ...) { va_list arg_ptr; struct timeval tv; va_start(arg_ptr, fmt); pthread_mutex_lock(&write_lock); gettimeofday(&tv, NULL); // 写入行首 fprintf(log_file, "%c|%d|%s|%ld.%ld|", start > 0 ? 'S' : 'E', gettid(), func, tv.tv_sec, tv.tv_usec); // 附加内容 vfprintf(log_file, fmt, arg_ptr); // 写入换行符 fputc('\n', log_file); pthread_mutex_unlock(&write_lock); va_end(arg_ptr); return 0; }
2.859375
3
2024-11-18T21:06:14.838612+00:00
2021-08-15T15:05:14
bd2267ae4f394b7be214fb526f65a4a1d4821573
{ "blob_id": "bd2267ae4f394b7be214fb526f65a4a1d4821573", "branch_name": "refs/heads/master", "committer_date": "2021-08-15T15:05:14", "content_id": "69083584a17ff8517ad3a60914b69d1be02cd5af", "detected_licenses": [ "MIT" ], "directory_id": "7fbbd3c34064c291d0a90054a8f67982cb87ce83", "extension": "h", "filename": "squeaker.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 297009161, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3888, "license": "MIT", "license_type": "permissive", "path": "/src/mmculib/squeaker.h", "provenance": "stackv2-0083.json.gz:20635", "repo_name": "hassan-alhujhoj/Embedded-Systems-Wacky-Races", "revision_date": "2021-08-15T15:05:14", "revision_id": "099e2cdcb98c92fd7eb543aa97c3217a47ccbf4b", "snapshot_id": "9fbd538d8abaa91e181ebc9244e8097368aa70fe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hassan-alhujhoj/Embedded-Systems-Wacky-Races/099e2cdcb98c92fd7eb543aa97c3217a47ccbf4b/src/mmculib/squeaker.h", "visit_date": "2023-07-02T12:38:34.699853" }
stackv2
/** @file squeaker.h @author M. P. Hayes, UCECE @date 14 April 2007 @brief Play simple tunes with PWM. */ #ifndef SQUEAKER_H #define SQUEAKER_H #ifdef __cplusplus extern "C" { #endif #include "config.h" #include "font.h" #include "ticker.h" typedef uint8_t squeaker_speed_t; typedef uint8_t squeaker_scale_t; typedef uint8_t squeaker_note_t; typedef uint8_t squeaker_duration_t; typedef uint8_t squeaker_period_t; typedef uint8_t squeaker_volume_t; enum {SQUEAKER_OCTAVE_DEFAULT = 4}; enum {SQUEAKER_SPEED_DEFAULT = 200}; /* Could calculate scale divisors at run time. 2^(1/2) is approx 1.0594631. A reasonable rational approximation is 267/252 = 1.0595238. Let's save memory and provide a macro to compute the divisors. */ #define SQUEAKER_DIVISOR(POLL_RATE, FREQ) (POLL_RATE / FREQ + 0.5) #if 0 enum {SQUEAKER_NOTE_MIN = 60}; /* Define divisors for chromatic scale C4 -> C5. For better accuracy this should be defined for the lowest frequency scale, however, this may need 16 bits per note. */ #define SQUEAKER_SCALE_TABLE(POLL_RATE) \ {SQUEAKER_DIVISOR (POLL_RATE, 261.6256), \ SQUEAKER_DIVISOR (POLL_RATE, 277.1826), \ SQUEAKER_DIVISOR (POLL_RATE, 293.6648), \ SQUEAKER_DIVISOR (POLL_RATE, 311.1270), \ SQUEAKER_DIVISOR (POLL_RATE, 329.6276), \ SQUEAKER_DIVISOR (POLL_RATE, 349.2282), \ SQUEAKER_DIVISOR (POLL_RATE, 369.9944), \ SQUEAKER_DIVISOR (POLL_RATE, 391.9954), \ SQUEAKER_DIVISOR (POLL_RATE, 415.3047), \ SQUEAKER_DIVISOR (POLL_RATE, 440.0000), \ SQUEAKER_DIVISOR (POLL_RATE, 466.1638), \ SQUEAKER_DIVISOR (POLL_RATE, 493.8833)} #else enum {SQUEAKER_NOTE_MIN = 40}; /* Define divisors for chromatic scale E2 -> D#3. For better accuracy this should be defined for the lowest frequency scale, however, this may need 16 bits per note. */ #define SQUEAKER_SCALE_TABLE(POLL_RATE) \ {SQUEAKER_DIVISOR (POLL_RATE, 82.41), \ SQUEAKER_DIVISOR (POLL_RATE, 87.31), \ SQUEAKER_DIVISOR (POLL_RATE, 92.50), \ SQUEAKER_DIVISOR (POLL_RATE, 98.00), \ SQUEAKER_DIVISOR (POLL_RATE, 103.83), \ SQUEAKER_DIVISOR (POLL_RATE, 110.0), \ SQUEAKER_DIVISOR (POLL_RATE, 116.54), \ SQUEAKER_DIVISOR (POLL_RATE, 123.47), \ SQUEAKER_DIVISOR (POLL_RATE, 130.81), \ SQUEAKER_DIVISOR (POLL_RATE, 138.59), \ SQUEAKER_DIVISOR (POLL_RATE, 146.83), \ SQUEAKER_DIVISOR (POLL_RATE, 155.56)} #endif typedef struct { uint8_t note_clock; uint8_t note_period; uint8_t note_duty; uint8_t note_holdoff; /* Pointer to start of string. */ const char *start; /* Pointer to current position in string. */ const char *cur; uint8_t holdoff; uint16_t poll_rate; const char *loop_start; int8_t loop_count; uint8_t prescaler; uint8_t note_fraction; squeaker_speed_t speed; squeaker_volume_t volume; ticker8_t ticker; squeaker_scale_t *scale_table; uint8_t octave; } squeaker_private_t; typedef squeaker_private_t squeaker_obj_t; typedef squeaker_obj_t *squeaker_t; /* The scale table is usually defined with: static squeaker_scale_t scale_table[] = SQUEAKER_SCALE_TABLE (LOOP_POLL_RATE); */ extern squeaker_t squeaker_init (squeaker_obj_t *dev, uint16_t poll_rate, squeaker_scale_t *scale_table); extern void squeaker_play (squeaker_t squeaker, const char *str); extern int8_t squeaker_update (squeaker_t squeaker); /* Set (base) speed in beats per minute (BPM). */ extern void squeaker_speed_set (squeaker_t squeaker, squeaker_speed_t speed); /* Set volume as percentage of maximum. */ extern void squeaker_volume_set (squeaker_t squeaker, squeaker_volume_t volume); #ifdef __cplusplus } #endif #endif
2.484375
2
2024-11-18T21:06:14.930294+00:00
2016-12-14T04:44:48
6ea83dbbe3fcd1ea38d0bd2dfca8ae56d7d26c7a
{ "blob_id": "6ea83dbbe3fcd1ea38d0bd2dfca8ae56d7d26c7a", "branch_name": "refs/heads/master", "committer_date": "2016-12-14T04:44:48", "content_id": "450c77335a5639bf975dba701abc5ac0d8fc9f28", "detected_licenses": [ "MIT" ], "directory_id": "3a9b7870e610b34b7287ff1c1f5ca89f71cbbdc7", "extension": "c", "filename": "bubble_sort.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 75676125, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1501, "license": "MIT", "license_type": "permissive", "path": "/bubble_sort.c", "provenance": "stackv2-0083.json.gz:20763", "repo_name": "nashkevin/EECS-338-Project", "revision_date": "2016-12-14T04:44:48", "revision_id": "9bd7a54fc98108ce6b308fa726e7000666e065e2", "snapshot_id": "bc4ed5573987166fb9ba166f841871c003914eee", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nashkevin/EECS-338-Project/9bd7a54fc98108ce6b308fa726e7000666e065e2/bubble_sort.c", "visit_date": "2020-06-11T11:39:40.366009" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <omp.h> #include "sorting_algorithms.h" #define BILLION 1000000000L /** Sorts an input array using bubble sort * Returns the time taken to sort the array */ uint64_t bubble_sort (int *a, int n) { struct timespec start, end; uint64_t diff; clock_gettime(CLOCK_MONOTONIC, &start); int i, t, s = 1; while (s) { s = 0; for (i = 1; i < n; i++) { if (a[i] < a[i - 1]) { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; s = 1; } } } clock_gettime(CLOCK_MONOTONIC, &end); diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec; return diff; } /** Sorts an input array using bubble sort and parallel processing * Returns the time taken to sort the array */ uint64_t bubble_sort_parallel (int *a, int n) { struct timespec start, end; uint64_t diff; clock_gettime(CLOCK_MONOTONIC, &start); int i, t, s = 1; while (s) { s = 0; #pragma omp parallel for for (i = 1; i < n; i++) { #pragma omp critical if (a[i] < a[i - 1]) { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; s = 1; } } } clock_gettime(CLOCK_MONOTONIC, &end); diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec; return diff; }
3.3125
3
2024-11-18T22:11:29.110819+00:00
2022-01-31T16:42:45
c4c57d9645cf8df409f051af8d074179fbf4f15b
{ "blob_id": "c4c57d9645cf8df409f051af8d074179fbf4f15b", "branch_name": "refs/heads/master", "committer_date": "2022-01-31T16:42:45", "content_id": "36004866f4f9f8849c334fe3e44bac0c7ec60f7a", "detected_licenses": [ "MIT" ], "directory_id": "ff4045720009d7c5293ed7626b63b9b42a1b8a43", "extension": "c", "filename": "state.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 64103043, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3757, "license": "MIT", "license_type": "permissive", "path": "/state.c", "provenance": "stackv2-0087.json.gz:25", "repo_name": "jmarkowski/design-patterns", "revision_date": "2022-01-31T16:42:45", "revision_id": "5af0fb953109484d7f6617702b1b2bee00ff6323", "snapshot_id": "3117a3d662f247e1ce61b5330d4d6449da7050c8", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/jmarkowski/design-patterns/5af0fb953109484d7f6617702b1b2bee00ff6323/state.c", "visit_date": "2022-02-05T17:51:43.031644" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> /* for strncpy */ /** * Intent * - Allow an object to alter its behavior when its internal state changes. The * object will appear to change its class. */ /** * Use the State pattern when * - An object's behavior depends on its state, and it must change its * behavior at run-time depending on that state. * - Operations have large, multipart conditional statements that depend on the * object's state. This state is usually represented by one or more enumerated * constants. Often, several operations will contain this same conditional * structure. The State pattern puts each branch of the conditional in a * separate class. This lets you treat the object's state as an object in its * own right that can var independently from other objects. */ #define MAX_STATE_ID 10 typedef struct State_s State_t; typedef struct Context_s Context_t; /* * Each state has a set of actions it can do at that state, and for the given * context, it can change the state. */ struct State_s { char id[MAX_STATE_ID]; void (*changeState)(Context_t *, State_t *); State_t *(*action)(Context_t *); }; /* * Configure context (i.e. whatever it is that is subject to states) */ struct Context_s { State_t *currentState; State_t *nextState; State_t *stateX; State_t *stateY; State_t *stateZ; void (*changeState)(Context_t *, State_t *); void (*begin)(Context_t *); void (*end)(Context_t *); void (*step)(Context_t *); }; void stateChangeState(Context_t *c, State_t *s) { State_t *oldState = c->currentState; State_t *nextState = s->action(c); State_t *newState = s; c->currentState = s; c->nextState = nextState; printf("\tChanged from %s to %s (next is %s)\n", oldState->id, newState->id, nextState->id); } State_t *newState(char *id, State_t *(*action)(Context_t *)) { State_t *s = (State_t *) malloc(sizeof(State_t)); strncpy(s->id, id, MAX_STATE_ID); s->changeState = stateChangeState; s->action = action; return s; } State_t * actionX(Context_t *c) { printf("Doing action X"); return c->stateY; } State_t * actionY(Context_t *c) { printf("Doing action Y"); return c->stateZ; } State_t * actionZ(Context_t *c) { printf("Doing action Z"); return c->stateX; } void contextChangeState(Context_t *c, State_t *newState) { c->currentState->changeState(c, newState); } void contextBegin(Context_t *c) { printf("BEGIN:\t"); c->changeState(c, c->stateX); } void contextStep(Context_t *c) { printf("STEP:\t"); c->changeState(c, c->nextState); } void contextEnd(Context_t *c) { printf("END:\t"); c->changeState(c, c->stateZ); } Context_t *newContext(State_t *stateX, State_t *stateY, State_t *stateZ) { Context_t *c = (Context_t *) malloc(sizeof(Context_t)); c->currentState = stateX; c->stateX = stateX; c->stateY = stateY; c->stateZ = stateZ; c->changeState = contextChangeState; c->begin = contextBegin; c->step = contextStep; c->end = contextEnd; return c; } int main(void) { /* * These are the concrete states */ State_t *stateX = newState("X", actionX); State_t *stateY = newState("Y", actionY); State_t *stateZ = newState("Z", actionZ); Context_t *c = newContext(stateX, stateY, stateZ); c->begin(c); /* Start at State X */ c->step(c); /* State Y */ c->step(c); /* State Z */ c->step(c); /* State X */ c->step(c); /* State Y */ c->step(c); /* State Z */ c->step(c); /* State X */ c->end(c); /* End at State Z */ return 0; }
3.4375
3
2024-11-18T22:11:29.402650+00:00
2018-09-17T06:21:54
877e9b22fdb233c6ef9a9c12b1ea97afed303642
{ "blob_id": "877e9b22fdb233c6ef9a9c12b1ea97afed303642", "branch_name": "refs/heads/master", "committer_date": "2018-09-17T06:21:54", "content_id": "a34ae6c218a02058c5813390c34c06cd3a5bd7fa", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9d936b1d01459307d86f3ff0609da0609fb52905", "extension": "h", "filename": "tty.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 142865127, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 879, "license": "Apache-2.0", "license_type": "permissive", "path": "/include/tty.h", "provenance": "stackv2-0087.json.gz:281", "repo_name": "ziyiyizi/OSsimple", "revision_date": "2018-09-17T06:21:54", "revision_id": "0c310a26945352700b2afa596fd3874e5460307f", "snapshot_id": "6248ec0d5ab811d007797d5213a1f0d807b913d2", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ziyiyizi/OSsimple/0c310a26945352700b2afa596fd3874e5460307f/include/tty.h", "visit_date": "2020-03-24T17:36:38.102224" }
stackv2
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ tty.h ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #ifndef _TINIX_TTY_H_ #define _TINIX_TTY_H_ #define TTY_IN_BYTES 256 /* tty input queue size */ struct s_tty; struct s_console; /* TTY */ typedef struct s_tty { t_32 in_buf[TTY_IN_BYTES]; /* TTY 输入缓冲区 */ t_32* p_inbuf_head; /* 指向缓冲区中下一个空闲位置 */ t_32* p_inbuf_tail; /* 指向键盘任务应处理的键值 */ int inbuf_count; /* 缓冲区中已经填充了多少 */ t_32 out_buf[TTY_IN_BYTES]; t_32* p_outbuf_head; t_32* p_outbuf_tail; int outbuf_count; t_32 tempBuffer[TTY_IN_BYTES]; int tempLen; t_bool fEcho; //是否显示字符 t_bool fAccept;//可否接受字符 struct s_console * p_console; }TTY; #endif /* _TINIX_TTY_H_ */
2.234375
2
2024-11-18T22:11:31.545986+00:00
2020-09-22T06:40:20
283aa0177ecf87aa8581a940cd2abb042745c968
{ "blob_id": "283aa0177ecf87aa8581a940cd2abb042745c968", "branch_name": "refs/heads/master", "committer_date": "2020-09-22T06:40:20", "content_id": "565b1b04c31382d8d90eb3d90136575ac0362183", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d4d1fd4d11cd4860b9299c4fd1034b7c491e2cfb", "extension": "c", "filename": "reverseLLUsingRecursionAlogorithm.c", "fork_events_count": 1, "gha_created_at": "2018-07-18T06:05:54", "gha_event_created_at": "2020-10-01T06:36:11", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 141388402, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 927, "license": "Apache-2.0", "license_type": "permissive", "path": "/2-LinkedList/Old/reverseLLUsingRecursionAlogorithm.c", "provenance": "stackv2-0087.json.gz:538", "repo_name": "send2manoo/Data-Structure", "revision_date": "2020-09-22T06:40:20", "revision_id": "c9763ec9709421a558a8dee5e3d811dd8e343960", "snapshot_id": "264168c6310f64d96960c89e805fc9e206d75e45", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/send2manoo/Data-Structure/c9763ec9709421a558a8dee5e3d811dd8e343960/2-LinkedList/Old/reverseLLUsingRecursionAlogorithm.c", "visit_date": "2021-06-26T12:01:32.344639" }
stackv2
#include "stdio.h" #include "stdlib.h" struct Node { int data; struct Node *next; }; struct Node* head; void Insert(int data) { struct Node* temp=(struct Node*)malloc(sizeof(struct Node)); temp->data=data; temp->next=NULL; if(head==NULL) head=temp; else { struct Node* temp1=head; while(temp1->next!=NULL) temp1=temp1->next; temp1->next=temp; } } void Print() { struct Node* temp=head; while(temp!=NULL) { printf("%d\t",temp->data); temp=temp->next; } printf("\n"); } void reversePrint(struct Node* p) { if(p->next==NULL) { head=p; return; } reversePrint(p->next); // very important to understand lecture no 12 struct Node *q=p->next; q->next=p; p->next=NULL; //printf("%d\t", p->data); } int main(int argc, char const *argv[]) { head=NULL; Insert(2); Insert(4); Insert(6); Insert(8); Insert(10); Print(); reversePrint(head); Print(); return 0; }
3.75
4
2024-11-18T22:11:32.361788+00:00
2016-12-13T13:52:45
b30b4a2dff75f0775b5338f6fbed110b77f85135
{ "blob_id": "b30b4a2dff75f0775b5338f6fbed110b77f85135", "branch_name": "refs/heads/master", "committer_date": "2016-12-13T13:52:45", "content_id": "0b2e4ffb02df38dbe128224acdb943ec4132d98e", "detected_licenses": [ "MIT" ], "directory_id": "4d390bf1cf234944b507f3f8e3236a3f728c6ed5", "extension": "h", "filename": "player.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 76362894, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 876, "license": "MIT", "license_type": "permissive", "path": "/src/player.h", "provenance": "stackv2-0087.json.gz:795", "repo_name": "kripod/blokus", "revision_date": "2016-12-13T13:52:45", "revision_id": "fe6f63e1ac16ee97744240e36ebaa820b77fb644", "snapshot_id": "2331833d027d28a0db65107e9505921338ca0c4e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/kripod/blokus/fe6f63e1ac16ee97744240e36ebaa820b77fb644/src/player.h", "visit_date": "2021-01-13T13:40:54.373730" }
stackv2
#ifndef PLAYER_H_INCLUDED #define PLAYER_H_INCLUDED #include <list.h> #include "color.h" #include "shape.h" /** * Represents a player of a Game. */ typedef struct Player { /** * Color of the player. */ Color color; /** * List of the player's unplaced Shape structures. */ list_t *placeable_shapes; /** * List node of the player's currently selected Shape. */ list_node_t *selected_shape_node; /** * Score of the player (based on the amount of cells occupied on the Board). */ int score; } Player; Player Player_Create(Color color, int default_score, list_t *placeable_shapes); void Player_Destroy(Player *self); int Player_ComparePointers(const void *pa, const void *pb); Shape *Player_GetSelectedShape(Player *self); Shape *Player_NextShape(Player *self); Shape *Player_PrevShape(Player *self); #endif // PLAYER_H_INCLUDED
2.40625
2
2024-11-18T22:11:32.613573+00:00
2023-04-08T01:37:00
47348523442ac24118e29fbb8e6594e9f644d425
{ "blob_id": "47348523442ac24118e29fbb8e6594e9f644d425", "branch_name": "refs/heads/main", "committer_date": "2023-04-08T01:37:10", "content_id": "2d5a66ae6dceb4fc48de277ecae470ad0f37f912", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "6135301f6e393e7197b80307b1d0676505365d24", "extension": "c", "filename": "apply-patch.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32195258, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6100, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/libdiffball/apply-patch.c", "provenance": "stackv2-0087.json.gz:924", "repo_name": "ferringb/diffball", "revision_date": "2023-04-08T01:37:00", "revision_id": "69c3f07a8982ea35833703fc83632e9a92306d2d", "snapshot_id": "733406c718e742e0d1e967f8b95bb594df6e9953", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ferringb/diffball/69c3f07a8982ea35833703fc83632e9a92306d2d/libdiffball/apply-patch.c", "visit_date": "2023-04-14T10:35:45.275628" }
stackv2
// SPDX-License-Identifier: BSD-3-Clause // Copyright (C) 2003-2013 Brian Harring <ferringb@gmail.com> #include <stdlib.h> #include <diffball/defs.h> #include <cfile.h> #include <diffball/dcbuffer.h> #include <diffball/apply-patch.h> #include <diffball/defs.h> #define ap_printf(fmt...) \ fprintf(stderr, "%s: ", __FILE__); \ fprintf(stderr, fmt); #define MAX(x, y) ((x) > (y) ? (x) : (y)) int cmp_dcloc_match(const void *vd1, const void *vd2) { #define v_cl(v) ((DCLoc_match *)(v)) return v_cl(vd1)->src_pos < v_cl(vd2)->src_pos ? -1 : v_cl(vd1)->src_pos > v_cl(vd2)->src_pos ? 1 : v_cl(vd1)->len < v_cl(vd2)->len ? -1 : v_cl(vd1)->len > v_cl(vd2)->len ? 1 : 0; } int reconstructFile(CommandBuffer *dcbuff, cfile *out_cfh, int reorder_for_seq_access, unsigned long max_buff_size) { DCommand *dc = NULL; assert(DCBUFFER_FULL_TYPE == dcbuff->DCBtype); command_list *cl, **ov_cl, **norm_cl; unsigned long x, ov_count, norm_count; DCBufferReset(dcbuff); assert(reorder_for_seq_access == 0 || CFH_IS_SEEKABLE(out_cfh) || 1); if (reorder_for_seq_access) { dcb_lprintf(1, "collapsing\n"); if ((cl = DCB_collapse_commands(dcbuff)) == NULL) return MEM_ERROR; if ((ov_cl = (command_list **)malloc(sizeof(command_list *) * dcbuff->src_count)) == NULL) return MEM_ERROR; if ((norm_cl = (command_list **)malloc(sizeof(command_list *) * dcbuff->src_count)) == NULL) return MEM_ERROR; for (x = 0, ov_count = 0, norm_count = 0; x < dcbuff->src_count; x++) { if (dcbuff->srcs[x].ov == NULL) { norm_cl[norm_count] = cl + x; norm_count++; } else { ov_cl[ov_count] = cl + x; ov_count++; } } DCB_free_commands(dcbuff); for (x = 0; x < norm_count; x++) { dcb_lprintf(1, "processing src %lu: %lu commands.\n", (unsigned long)(norm_cl[x] - cl), norm_cl[x]->com_count); if (norm_cl[x]->com_count) { qsort(norm_cl[x]->full_command, norm_cl[x]->com_count, sizeof(DCLoc_match), cmp_dcloc_match); if (read_seq_write_rand(norm_cl[x], dcbuff->srcs + (norm_cl[x] - cl), 0, out_cfh, max_buff_size)) return IO_ERROR; } CL_free(norm_cl[x]); } for (x = 0; x < ov_count; x++) { dcb_lprintf(1, "processing overlay src %lu: %lu commands.\n", (unsigned long)(ov_cl[x] - cl), ov_cl[x]->com_count); if (ov_cl[x]->com_count) { qsort(ov_cl[x]->full_command, ov_cl[x]->com_count, sizeof(DCLoc_match), cmp_dcloc_match); if (read_seq_write_rand(ov_cl[x], dcbuff->srcs + (ov_cl[x] - cl), 1, out_cfh, max_buff_size)) return IO_ERROR; } CL_free(ov_cl[x]); } free(cl); free(ov_cl); free(norm_cl); } else { if ((dc = (DCommand *)malloc(sizeof(DCommand))) == NULL) { return MEM_ERROR; } while (DCB_commands_remain(dcbuff)) { DCB_get_next_command(dcbuff, dc); if (dc->data.len != copyDCB_add_src(dcbuff, dc, out_cfh)) { return EOF_ERROR; } } free(dc); } return 0; } int read_seq_write_rand(command_list *cl, DCB_registered_src *r_src, unsigned char is_overlay, cfile *out_cfh, unsigned long buf_size) { unsigned char *buf; unsigned char *p; unsigned long x, start = 0, end = 0, len = 0; unsigned long max_pos = 0, pos = 0; unsigned long offset; signed long tmp_len; dcb_src_read_func read_func; cfile_window *cfw; u_dcb_src u_src; #define END_POS(x) ((x).src_pos + (x).len) pos = 0; max_pos = 0; if (is_overlay) { read_func = r_src->mask_read_func; } else { read_func = r_src->read_func; } assert(read_func != NULL); u_src = r_src->src_ptr; if (0 != cseek(u_src.cfh, 0, CSEEK_FSTART)) { ap_printf("cseeked failed: bailing, io_error 0\n"); return IO_ERROR; } if ((buf = (unsigned char *)malloc(buf_size)) == NULL) { return MEM_ERROR; } while (start < cl->com_count) { if (pos < cl->full_command[start].src_pos) { pos = cl->full_command[start].src_pos; max_pos = END_POS(cl->full_command[start]); } else { while (start < cl->com_count && pos > cl->full_command[start].src_pos) { start++; } if (start == cl->com_count) continue; pos = cl->full_command[start].src_pos; max_pos = MAX(max_pos, END_POS(cl->full_command[start])); } if (end < start) { end = start; } while (end < cl->com_count && cl->full_command[end].src_pos < max_pos) { max_pos = MAX(max_pos, END_POS(cl->full_command[end])); end++; } if (pos == max_pos) { continue; } while (pos < max_pos) { len = MIN(max_pos - pos, buf_size); x = read_func(u_src, pos, buf, len); if (len != x) { ap_printf("x=%lu, pos=%lu, len=%lu\n", x, pos, len); ap_printf("bailing, io_error 2\n"); free(buf); return IO_ERROR; } for (x = start; x < end; x++) { offset = MAX(cl->full_command[x].src_pos, pos); tmp_len = MIN(END_POS(cl->full_command[x]), pos + len) - offset; if (tmp_len > 0) { if (cl->full_command[x].ver_pos + (offset - cl->full_command[x].src_pos) != cseek(out_cfh, cl->full_command[x].ver_pos + (offset - cl->full_command[x].src_pos), CSEEK_FSTART)) { ap_printf("bailing, io_error 3\n"); free(buf); return IO_ERROR; } if (is_overlay) { p = buf + offset - pos; cfw = expose_page(out_cfh); if (cfw->write_end == 0) { cfw->write_start = cfw->pos; } while (buf + offset - pos + tmp_len > p) { if (cfw->pos == cfw->end) { cfw->write_end = cfw->end; cfw = next_page(out_cfh); if (cfw->end == 0) { ap_printf("bailing from applying overlay mask in read_seq_writ_rand\n"); free(buf); return IO_ERROR; } } cfw->buff[cfw->pos] += *p; p++; cfw->pos++; } cfw->write_end = cfw->pos; } else { if (tmp_len != cwrite(out_cfh, buf + offset - pos, tmp_len)) { ap_printf("bailing, io_error 4\n"); free(buf); return IO_ERROR; } } } } pos += len; } } free(buf); return 0; }
2.25
2
2024-11-18T22:11:32.785883+00:00
2020-11-17T19:40:13
d001d5861497c7d01dec6dec72eed44ec994866b
{ "blob_id": "d001d5861497c7d01dec6dec72eed44ec994866b", "branch_name": "refs/heads/master", "committer_date": "2020-11-17T19:40:13", "content_id": "c17363e3222dde6cb02735290aded3944a768ae5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0518e53526c214da6142d940c42a428ec7d58122", "extension": "c", "filename": "packet-smb-common.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8879, "license": "Apache-2.0", "license_type": "permissive", "path": "/CWE-119/source_files/148881/packet-smb-common.c", "provenance": "stackv2-0087.json.gz:1310", "repo_name": "Adam-01/VulDeePecker", "revision_date": "2020-11-17T19:40:13", "revision_id": "98610f3e116df97a1e819ffc81fbc7f6f138a8f2", "snapshot_id": "eb03cfa2b94d736b1cba17fb1cdcb36b01e18f5e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Adam-01/VulDeePecker/98610f3e116df97a1e819ffc81fbc7f6f138a8f2/CWE-119/source_files/148881/packet-smb-common.c", "visit_date": "2023-03-21T07:37:26.904949" }
stackv2
/* packet-smb-common.c * Common routines for smb packet dissection * Copyright 2000, Jeffrey C. Foster <jfoste@woodward.com> * * $Id: packet-smb-common.c 24525 2008-03-01 17:23:39Z stig $ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * Copied from packet-pop.c * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <string.h> #include <glib.h> #include <epan/packet.h> #include <epan/emem.h> #include <epan/strutil.h> #include "packet-smb-common.h" /* * Share type values - used in LANMAN and in SRVSVC. * * XXX - should we dissect share type values, at least in SRVSVC, as * a subtree with bitfields, as the 0x80000000 bit appears to be a * hidden bit, with some number of bits at the bottom being the share * type? * * Does LANMAN use that bit? */ const value_string share_type_vals[] = { {0, "Directory tree"}, {1, "Printer queue"}, {2, "Communications device"}, {3, "IPC"}, {0x80000000, "Hidden Directory tree"}, {0x80000001, "Hidden Printer queue"}, {0x80000002, "Hidden Communications device"}, {0x80000003, "Hidden IPC"}, {0, NULL} }; int display_ms_string(tvbuff_t *tvb, proto_tree *tree, int offset, int hf_index, char **data) { char *str; gint len; /* display a string from the tree and return the new offset */ str = tvb_get_ephemeral_stringz(tvb, offset, &len); proto_tree_add_string(tree, hf_index, tvb, offset, len, str); /* Return a copy of the string if requested */ if (data) *data = str; return offset+len; } int display_unicode_string(tvbuff_t *tvb, proto_tree *tree, int offset, int hf_index, char **data) { char *str, *p; int len; int charoffset; guint16 character; /* display a unicode string from the tree and return new offset */ /* * Get the length of the string. * XXX - is it a bug or a feature that this will throw an exception * if we don't find the '\0'? I think it's a feature. */ len = 0; while ((character = tvb_get_letohs(tvb, offset + len)) != '\0') len += 2; len += 2; /* count the '\0' too */ /* * Allocate a buffer for the string; "len" is the length in * bytes, not the length in characters. */ str = ep_alloc(len/2); /* * XXX - this assumes the string is just ISO 8859-1; we need * to better handle multiple character sets in Wireshark, * including Unicode/ISO 10646, and multiple encodings of * that character set (UCS-2, UTF-8, etc.). */ charoffset = offset; p = str; while ((character = tvb_get_letohs(tvb, charoffset)) != '\0') { *p++ = (char) character; charoffset += 2; } *p = '\0'; proto_tree_add_string(tree, hf_index, tvb, offset, len, str); if (data) *data = str; return offset+len; } static int dissect_ms_compressed_string_internal(tvbuff_t *tvb, int offset, char *str, int maxlen, gboolean prepend_dot) { guint8 len; len=tvb_get_guint8(tvb, offset); offset+=1; *str=0; /* XXX: Reserve 4 chars for "...\0" */ while(len){ /* add potential field separation dot */ if(prepend_dot){ if(maxlen<=4){ *str=0; return offset; } maxlen--; *str++='.'; *str=0; } if(len==0xc0){ int new_offset; /* ops its a mscldap compressed string */ new_offset=tvb_get_guint8(tvb, offset); if (new_offset == offset - 1) THROW(ReportedBoundsError); offset+=1; dissect_ms_compressed_string_internal(tvb, new_offset, str, maxlen, FALSE); return offset; } prepend_dot=TRUE; if(len>(maxlen-4)){ *str++='.'; *str++='.'; *str++='.'; *str=0; return offset; /* will mess up offset in caller, is unlikely */ } tvb_memcpy(tvb, str, offset, len); str+=len; *str=0; maxlen-=len; offset+=len; len=tvb_get_guint8(tvb, offset); offset+=1; } *str=0; return offset; } /* Max string length for displaying Unicode strings. */ #define MAX_UNICODE_STR_LEN 256 int dissect_ms_compressed_string(tvbuff_t *tvb, proto_tree *tree, int offset, int hf_index, gboolean prepend_dot, char **data) { int old_offset=offset; char *str; int len; len = MAX_UNICODE_STR_LEN+3+1; str=ep_alloc(len); offset=dissect_ms_compressed_string_internal(tvb, offset, str, len, prepend_dot); proto_tree_add_string(tree, hf_index, tvb, old_offset, offset-old_offset, str); if (data) *data = str; return offset; } /* Turn a little-endian Unicode '\0'-terminated string into a string we can display. XXX - for now, we just handle the ISO 8859-1 characters. If exactlen==TRUE then us_lenp contains the exact len of the string in bytes. It might not be null terminated ! bc specifies the number of bytes in the byte parameters; Windows 2000, at least, appears, in some cases, to put only 1 byte of 0 at the end of a Unicode string if the byte count */ static gchar * unicode_to_str(tvbuff_t *tvb, int offset, int *us_lenp, gboolean exactlen, guint16 bc) { gchar *cur; gchar *p; guint16 uchar; int len; int us_len; gboolean overflow = FALSE; cur=ep_alloc(MAX_UNICODE_STR_LEN+3+1); p = cur; len = MAX_UNICODE_STR_LEN; us_len = 0; for (;;) { if (bc == 0) break; if (bc == 1) { /* XXX - explain this */ if (!exactlen) us_len += 1; /* this is a one-byte null terminator */ break; } uchar = tvb_get_letohs(tvb, offset); if (uchar == 0) { us_len += 2; /* this is a two-byte null terminator */ break; } if (len > 0) { if ((uchar & 0xFF00) == 0) *p++ = (gchar) uchar; /* ISO 8859-1 */ else *p++ = '?'; /* not 8859-1 */ len--; } else overflow = TRUE; offset += 2; bc -= 2; us_len += 2; if(exactlen){ if(us_len>= *us_lenp){ break; } } } if (overflow) { /* Note that we're not showing the full string. */ *p++ = '.'; *p++ = '.'; *p++ = '.'; } *p = '\0'; *us_lenp = us_len; return cur; } /* nopad == TRUE : Do not add any padding before this string * exactlen == TRUE : len contains the exact len of the string in bytes. * bc: pointer to variable with amount of data left in the byte parameters * region */ const gchar * get_unicode_or_ascii_string(tvbuff_t *tvb, int *offsetp, gboolean useunicode, int *len, gboolean nopad, gboolean exactlen, guint16 *bcp) { gchar *cur; const gchar *string; int string_len = 0; int copylen; gboolean overflow = FALSE; if (*bcp == 0) { /* Not enough data in buffer */ return NULL; } if (useunicode) { if ((!nopad) && (*offsetp % 2)) { (*offsetp)++; /* Looks like a pad byte there sometimes */ (*bcp)--; if (*bcp == 0) { /* Not enough data in buffer */ return NULL; } } if(exactlen){ string_len = *len; if (string_len < 0) { /* This probably means it's a very large unsigned number; just set it to the largest signed number, so that we throw the appropriate exception. */ string_len = INT_MAX; } } string = unicode_to_str(tvb, *offsetp, &string_len, exactlen, *bcp); } else { if(exactlen){ /* * The string we return must be null-terminated. */ cur=ep_alloc(MAX_UNICODE_STR_LEN+3+1); copylen = *len; if (copylen < 0) { /* This probably means it's a very large unsigned number; just set it to the largest signed number, so that we throw the appropriate exception. */ copylen = INT_MAX; } tvb_ensure_bytes_exist(tvb, *offsetp, copylen); if (copylen > MAX_UNICODE_STR_LEN) { copylen = MAX_UNICODE_STR_LEN; overflow = TRUE; } tvb_memcpy(tvb, (guint8 *)cur, *offsetp, copylen); cur[copylen] = '\0'; if (overflow) g_strlcat(cur, "...",MAX_UNICODE_STR_LEN+3+1); string_len = *len; string = cur; } else { string_len = tvb_strsize(tvb, *offsetp); string = tvb_get_ptr(tvb, *offsetp, string_len); } } *len = string_len; return string; }
2.09375
2
2024-11-18T22:11:33.763605+00:00
2019-06-19T01:56:15
ae9e2c53d6503410bd6ffbca99d3c27118bd068f
{ "blob_id": "ae9e2c53d6503410bd6ffbca99d3c27118bd068f", "branch_name": "refs/heads/master", "committer_date": "2019-06-19T01:56:15", "content_id": "387f1501e6b4aa87d3e4368c6388d71933ac03ea", "detected_licenses": [ "Unlicense" ], "directory_id": "b5e4f739b2be1d56aa27af37a0facd7876909fa8", "extension": "h", "filename": "overdrive.h", "fork_events_count": 5, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 97297257, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2027, "license": "Unlicense", "license_type": "permissive", "path": "/overdrive/overdrive.h", "provenance": "stackv2-0087.json.gz:2084", "repo_name": "transmogrifox/Bela_Misc", "revision_date": "2019-06-19T01:56:15", "revision_id": "f9d4acc7d835dd74c54b3aa4274c8cf6b97cec53", "snapshot_id": "d52b95f6111688be953fca5d5a2084f2d80b664d", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/transmogrifox/Bela_Misc/f9d4acc7d835dd74c54b3aa4274c8cf6b97cec53/overdrive/overdrive.h", "visit_date": "2021-01-01T05:53:00.861423" }
stackv2
#ifndef OVERDRIVE_H #define OVERDRIVE_H #define LPF1P 0 #define HPF1P 1 typedef struct iir_1p_t { // Coefficients float a1; float b0; float b1; // State variables float x1; float y1; } iir_1p; typedef struct overdrive_t { float fs; // Sampling frequency float clipper_fs; // nonlinear processing sampling frequency unsigned int oversample; // Oversampling rate unsigned int blksz; float inverse_oversample_float; // User control settings float gain; // Distortion amount -- 1.0 ... 1000.0 float tone; // Tone control -- 0.0 ... 1.0 float level; // Output level -- 0.0 ... 1.0 float dry; // Mix like od, or none like distortion bool bypass; // Processing buffers float *procbuf; // State variables float xn1; float xc1; // Pre and post emphasis EQ iir_1p anti_alias; iir_1p pre_emph; iir_1p post_emph; iir_1p tone_lp; iir_1p tone_hp; } overdrive; // Allocate the overdrive struct and set default values overdrive* make_overdrive(overdrive* od, unsigned int oversample, unsigned int bsz, float fs); void overdrive_cleanup(overdrive* od); // Set EQ parameters to non-default // Usually for configuring the overdrive flavor at initialization, // but these can be user-configurable in real-time void od_set_cut_pre_emp(overdrive* od, float fc); void od_set_cut_post_emp(overdrive* od, float fc); void od_set_cut_tone_lp(overdrive* od, float fc); void od_set_cut_tone_hp(overdrive* od, float fc); // Typical real-time user-configurable parameters void od_set_drive(overdrive* od, float drive_db); // 0 dB to 45 dB void od_set_tone(overdrive* od, float hf_level_db); // high pass boost/cut, +/- 12dB void od_set_level(overdrive* od, float outlevel_db); // -40 dB to +0 dB void od_set_dry(overdrive* od, float dry); // Clean mix, 0.0 to 1.0 bool od_set_bypass(overdrive* od, bool bypass); // Run the overdrive effect void overdrive_tick(overdrive* od, float* x); #endif //OVERDRIVE_H
2.390625
2
2024-11-18T22:11:34.189616+00:00
2013-11-30T18:52:22
a2394075bc53e17b01ca00461ffacc1622c6bceb
{ "blob_id": "a2394075bc53e17b01ca00461ffacc1622c6bceb", "branch_name": "refs/heads/master", "committer_date": "2013-11-30T18:52:22", "content_id": "0d5c97b6904b4cbf988f16c18b97ac4c60e71572", "detected_licenses": [ "MIT" ], "directory_id": "53b37c869fab9a28806cdabc156a92bb0c61b59c", "extension": "c", "filename": "cpeer.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 14124439, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12418, "license": "MIT", "license_type": "permissive", "path": "/cpeer.c", "provenance": "stackv2-0087.json.gz:2341", "repo_name": "mihirvj/p2p", "revision_date": "2013-11-30T18:52:22", "revision_id": "77351843de9b38284e7a626b0cfc15ecc1dcccb2", "snapshot_id": "e6f1abdcbf0015761e272fd78d0651724f384972", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mihirvj/p2p/77351843de9b38284e7a626b0cfc15ecc1dcccb2/cpeer.c", "visit_date": "2016-09-05T12:45:29.647383" }
stackv2
/***************************************************** cpeer.c peer client implementation Authors: Mihir Joshi, Fenil Kavathia csc573 NCSU *****************************************************/ #include "sock/csock.h" #include "sock/ssock.h" #include<string.h> #include "parser/parse.h" #include<signal.h> #include<pthread.h> #include<stdbool.h> #include<fcntl.h> #include<dirent.h> #define SERVER_PORT 7752 int ssock; int csock; int port; int pid; char myport[50], myhostname[50]; char* SERVER_ADDR; void s_peer(int outpipe); void c_peer(int inpipe); bool download_content(int rfc_no,char* hostname,int port); void *handle_peer(void *arg); void terminate(int sock, char host[50], char port[50]) { char term_req[BUFSIZE]; generate_request(term_req, TERMINATE, -1, host, port, ""); #ifdef APP printf("\nsending: %s\n", term_req); #endif write_to(sock, term_req, BUFSIZE); } void segv(int signum) { int status; char term_req[BUFSIZE]; #ifdef APP printf("\nI %s:%s am closing\n", myhostname, myport); #endif if(strcmp(myhostname, "") != 0 && strcmp(myport, "") != 0) { terminate(csock, myhostname, myport); } close_sock(csock); close_sock(ssock); printf("\npress ctrl + c to exit\n"); wait(&status); signal(signum, SIG_DFL); kill(getpid(), signum); } int main(int argc, char *argv[]) { if(argc!=2) { printf("usage: ./cpeer <Server Address>\n"); return 1; } else { SERVER_ADDR=argv[1]; } int pfd[2]; pipe(pfd); //now we need to fork the process signal(SIGINT, segv); pid=fork(); if(pid==0) { close(pfd[0]); s_peer(pfd[1]); } else { close(pfd[1]); c_peer(pfd[0]); } } // main ends void s_peer(int outpipe) { int cssock; int id; char buf[BUFSIZE]; struct sockaddr_in addr; socklen_t addr_len; char myport[50], myhostname[50]; pthread_attr_t attr; pthread_t threads; srand(time(NULL)); port=(rand()%(65535-1024))+1024; #ifdef GRAN1 printf("\nserver peer port number: %d\n", port); #endif //right now we need to know the port no. so assigned fix one //port=5000; //server socket(speer) ssock=get_sock(); #ifdef GRAN1 printf("[gran 1] created socket\n"); #endif // bind socket bind_sock(ssock, port); #ifdef GRAN1 printf("[gran 1] bind socket\n"); #endif addr_len = sizeof(addr); if(getsockname(ssock, (struct sockaddr * )&addr, &addr_len) == -1) { printf("[error] not able to get socket name\n"); return; } sprintf(myport, "%d", ntohs(addr.sin_port)); /*sprintf(myhostname, "%d.%d.%d.%d", (int)(addr.sin_addr.s_addr&0xFF), (int)((addr.sin_addr.s_addr&0xFF00)>>8), (int)((addr.sin_addr.s_addr&0xFF00)>>16), (int)((addr.sin_addr.s_addr&0xFF00)>>24)); */ read_my_ip(myhostname); #ifdef GRAN1 printf("sending port: %s host: %s\n", myport, myhostname); #endif write_to(outpipe, myport, 50); write_to(outpipe, myhostname, 50); close(outpipe); listen_sock(ssock); #ifdef GRAN1 printf("[gran 1] now listening\n"); #endif pthread_attr_init(&attr); while(1) { // ready to accept connection //communication with one peer completed cssock = accept_con(ssock); id=cssock; // create a thread to handle client peer pthread_create(&threads, &attr, handle_peer, &id); } pthread_join(threads, NULL); } // s_speer ends void c_peer(int inpipe) { int choice, i; char request[BUFSIZE], response[BUFSIZE]; int rfc; char title[50]; char c_rfc[50], host[50], port[50]; DIR *d; struct dirent *entry; //client socket (cpeer); //get client socket descriptor csock = get_sock(); read_from(inpipe, myport, 50); read_from(inpipe, myhostname, 50); close(inpipe); #ifdef GRAN1 printf("received port: %s host: %s\n", myport, myhostname); #endif //connect to server socket //connect_to(sock, SERVER_ADDR, SERVER_PORT); //this is for communication between cpeer and server //right now assume we are using this function to connect to server peer connect_to(csock, SERVER_ADDR, SERVER_PORT); //used 5000 port because we don't know server peer port printf("\n***********Welcome to Peer to Peer RFC Document Transfer Application***********\n"); printf("\nMake sure You have rfc folder in directory of your Executable\n"); // add entries of current rfcs when booted up d = opendir("./rfc"); if(d) { while((entry = readdir(d)) != NULL) { char rfc[50]; if(strcmp(entry->d_name, "..") == 0 || strcmp(entry->d_name, ".") == 0) continue; memset(request,(int) '\0',BUFSIZE); #ifdef APP printf("found file: %s\n", entry->d_name); #endif sscanf(entry->d_name, "%s.txt", rfc); #ifdef APP printf("sending to server: %s\n", rfc); #endif generate_request(request, ADD, atoi(rfc), myhostname, myport, "title"); write_to(csock, request, BUFSIZE); read_from(csock, response, BUFSIZE); #ifdef APP printf("Boot Server Response is \n%s\n",response); #endif } closedir(d); } else // TODO: handle case where no rfc folder is specified { } while(1) // loop forever unless user tells it to stop ; option 4 { memset(request,(int) '\0',BUFSIZE); printf("\n**************************************************************\n"); printf(" MENU "); printf("\nPress 1 for Lookup and download\n"); printf("Press 2 for list\n"); printf("Press 3 for Terminate: \n"); printf("**************************************************************\n"); scanf("%d",&choice); switch(choice) { /*case 1: printf("\n Please Enter RFC Number: "); scanf("%d", &rfc); //what if user by mistake write wrong rfc no? //whether we should automatically do this when client server //starts in begining //what is the proof that I have that file?? printf("\nPlease Enter RFC Title: "); scanf("%s", title); generate_request(request, ADD, rfc, myhostname, myport, title); break;*/ case 1: printf("\nPlease Enter RFC Number: "); scanf("%d", &rfc); printf("\nPlease Enter RFC Title: "); scanf("%s", title); generate_request(request, LOOKUP, rfc, myhostname, myport, title); break; case 2: generate_request(request, LISTALL, -1, myhostname, myport, "sample"); //why -1, doesn't matter break; case 3: ;char c; printf("Are You Sure? Press y(Y) or n(N): "); scanf(" %c",&c); if(c=='y'|| c=='Y') { printf("Thank you for using Program\n"); //terminate(csock, myhostname, myport); //close_sock(csock); raise(SIGINT); return; } else {continue;} } // switch ends //If user press 4 then we need to disable write_to and read_from otherwise it will be written to boot server //server will handle this and generete bad request if user type anything write_to(csock, request, BUFSIZE); read_from(csock, response, BUFSIZE); printf("\n*************Reply From Boot-Server************\n"); printf("%s\n",response); printf("***************************************************"); if(choice == 1) // lookup { i = 0; // printf("\nPlease wait while your file is being downloaded\n"); bool success=false; while(parse_response(response, i, c_rfc, title, host, port) != -1) { #ifdef APP printf("\nI understand that rfc %s is with %s:%s\n", c_rfc, host, port); #endif success = download_content(rfc,host,atoi(port)); //i am using rfc no here not rfc array if(success) { printf("\nRfc %d is sucessfully downloaded\n", atoi(c_rfc)); //send add to server for just downloaded file generate_request(request, ADD, atoi(c_rfc), myhostname, myport, title); write_to(csock, request, BUFSIZE); read_from(csock, response, BUFSIZE); #ifdef APP printf("\nServer responded:\n%s\n", response); #endif break; } else { i++; // try next host } } // while ends if(!success) { printf("\n**************************************************************\n"); printf("No Peer from Currently seems to have the File You are Requesting.Please retry later\n"); printf("**************************************************************\n"); } } // if ends } // while ends } // c_peer ends void *handle_peer(void *arg) { char buf[BUFSIZE]; int cssock = *(int *) arg; int fp; int sent; char err_buf[20], rfc[50], host[50], port[50], title[100], fname[20]; int method, errcode; #ifdef GRAN1 printf("[log] I am handling cpeer thread : %d", csock); #endif read_from(cssock, buf, BUFSIZE); char *temp=buf; #ifdef GRAN1 printf("\n[log] Peer client says: %s\n", buf); #endif errcode = parse_request(buf, rfc, host, port, title, &method); if(errcode != OK) { #ifdef APP printf("\nErrcode: %d\n", errcode); #endif generate_response(buf, errcode, method); write_to(cssock, buf, BUFSIZE); return; } sprintf(fname, "./rfc/%d.txt", atoi(rfc)); #ifdef APP printf("\ngot filename as: %s\n", fname); #endif fp = open(fname, O_RDONLY, S_IRUSR); //here we can make one rfc folder in current directory and put all files there if(fp != -1) { char send_buf[BUFSIZE]; //we don't know the file size in advance (It will be a waste for files which are //relatively small #ifdef GRAN1 printf("[log] writing to Peer client %s\n", buf); #endif memset(send_buf, 0, BUFSIZE); while((sent = read(fp, send_buf, BUFSIZE - 1)) > 0) { if(sent < (BUFSIZE - 1)) { send_buf[sent] = '\0'; } else { send_buf[BUFSIZE] = '\0'; } #ifdef GRAN1 printf("file content is:\n%s\n",send_buf); #endif write_to(cssock, send_buf, sent); #ifdef GRAN1 printf("\nsent %d bytes\n", sent); #endif memset(send_buf, 0, BUFSIZE); } close(fp); #ifdef GRAN1 printf("File operation Completed\n"); #endif } else { memset(err_buf,0,sizeof(err_buf)); perror("Server File Error:"); strcpy(err_buf,"!@#$%^&*"); write_to(cssock, "", 0); } close_sock(cssock); #ifdef GRAN1 printf("[log] client socket closed %d\n", cssock); #endif pthread_exit(NULL); } // handle_peer bool download_content(int rfc_no,char* hostname,int port) { int tsock; char filename[BUFSIZE]; char file_data[BUFSIZE]; char port_no[8]; int fp = -9999, readBytes; bool received = false; tsock=get_sock(); connect_to(tsock,hostname, port); sprintf(port_no,"%d", port); generate_request(filename, GET, rfc_no, myhostname, myport, "title"); #ifdef APP printf("\nseding GET request as:\n%s\n", filename); #endif write_to(tsock, filename, BUFSIZE); // inform peer about file name i want sprintf(filename, "./rfc/%d.txt", rfc_no); memset(file_data, 0, BUFSIZE); #ifdef GRAN1 printf("\ni m waiting while server delivers\n"); #endif while(readBytes = read(tsock, file_data, BUFSIZE - 1) > 0) { received = true; #ifdef GRAN1 printf("\nreceived file chunk: %s\nsize:%d\n", file_data, readBytes); #endif //not sure whether to close socket here or after everything done /*if(strcmp(strncpy(temp_buf,file_data,8),"!@#$%^&*")==0) { printf("\nPeer %s does not have file\n", hostname); close_sock(tsock); printf("closeing peer client socket: and connecting to different peer server one%d\n", tsock); return false; } else {*/ printf("\rPeer server %s has the file and Please wait while it delivers file",hostname); if(fp == -9999) // open file once fp = open(filename, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); //rfc folder should be there if(fp != -1 && fp != -9999) { write(fp, file_data, strlen(file_data)); //write to file memset(file_data, 0, BUFSIZE); } else { perror("**Peer client Error**: "); received = false; //here problem is client side so we should not try connecting to different peer because same will //happen again break; } //} } if(!received) { printf("\n**************************************************************\n"); printf("\nPeer %s does not seem to have file or some error occured\n", hostname); printf("***************************************************************\n"); } if(fp != -9999) close(fp); close_sock(tsock); return received; } // download_content ends
2.453125
2
2024-11-18T22:11:34.309988+00:00
2019-06-24T15:42:30
bbe1b09b443f5fd1e65186e30a75b54b24110b49
{ "blob_id": "bbe1b09b443f5fd1e65186e30a75b54b24110b49", "branch_name": "refs/heads/master", "committer_date": "2019-06-24T15:42:30", "content_id": "024c17faadd3c40a81589ce333147b46abd41c25", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "fdfede61a5e03c5370bcd46aaa65fc53adb5a880", "extension": "c", "filename": "pointer_init.c", "fork_events_count": 0, "gha_created_at": "2019-06-24T19:40:00", "gha_event_created_at": "2019-06-24T19:40:00", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 193567883, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 676, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/tests/pointers/src/pointer_init.c", "provenance": "stackv2-0087.json.gz:2470", "repo_name": "jameysharp/c2rust", "revision_date": "2019-06-24T15:42:30", "revision_id": "30b17c14179e6fac8373368c667415a47da32ade", "snapshot_id": "1e213ffcb241dd0d9d1a6a383fffcc8fc394d8fb", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jameysharp/c2rust/30b17c14179e6fac8373368c667415a47da32ade/tests/pointers/src/pointer_init.c", "visit_date": "2020-06-10T03:29:34.015597" }
stackv2
#include <stdio.h> typedef unsigned long* ulp; ulp foo(void) { return NULL; } // GH #99: Previously bitcasts were ignored for int* to const int* // messing up type inference in read_volatile type conversion int simple(int const * *x, int * volatile *y) { return *x == *y; } void entry(const unsigned int buffer_size, int buffer[]) { char *test = {"string"}; buffer[0] = test[0]; buffer[1] = test[1]; buffer[2] = test[2]; buffer[3] = test[3]; buffer[4] = test[4]; // GH #89: Previously a null ptr return value would cause a // typedef'd pointer type to cause the function to silently // not generate any definition foo(); }
2.578125
3
2024-11-18T22:11:34.666805+00:00
2018-10-19T15:30:46
6c927481ddf5890597951e0ac193930a0c0354de
{ "blob_id": "6c927481ddf5890597951e0ac193930a0c0354de", "branch_name": "refs/heads/master", "committer_date": "2018-10-19T15:30:46", "content_id": "91c364a83e86ff7c61d6e2200941e83ed8460efb", "detected_licenses": [ "Apache-2.0" ], "directory_id": "df48c4bebbaa4f57b36b0e17f51e182180b7626e", "extension": "c", "filename": "pid.c", "fork_events_count": 1, "gha_created_at": "2017-03-08T17:02:41", "gha_event_created_at": "2017-04-08T20:13:48", "gha_language": "C", "gha_license_id": null, "github_id": 84345518, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3608, "license": "Apache-2.0", "license_type": "permissive", "path": "/components/pid/pid.c", "provenance": "stackv2-0087.json.gz:2987", "repo_name": "qjones81/esp32-dev", "revision_date": "2018-10-19T15:30:46", "revision_id": "a41cbb9639e4ad39233316b8412bbf85e1750e41", "snapshot_id": "d7dc5b871835fd8d85bf9136bab582e3459cd5bd", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/qjones81/esp32-dev/a41cbb9639e4ad39233316b8412bbf85e1750e41/components/pid/pid.c", "visit_date": "2021-01-18T15:32:25.759262" }
stackv2
/* * pid.c * * Created on: April 2, 2017 * Author: qjones * * Copyright (c) <2017> <Quincy Jones - qjones@c4solutions.net/> * 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. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "esp_system.h" #include "esp_log.h" #include "pid.h" #include "utils/utils.h" static const char *tag = "pid"; float pid_compute(pid_device_control_t *controller) { float output; // Update time deltas float now = millis(); float dt = (now - controller->last_time); // Error Term float error = controller->set_point - controller->input; // Compute proportional term float p_term = controller->k_p * error; // Compute integral term controller->integral_error += error * dt; // constrain(error, -ITERM_MAX_ERROR, ITERM_MAX_ERROR); controller->integral_error = constrain(controller->integral_error, -controller->integral_windup_max, controller->integral_windup_max); float i_term = (controller->k_i * controller->integral_error); // Compute derivative term float d_error = (error - controller->error_prev) / dt; float d_term = controller->k_d * d_error; // Compute output output = p_term + i_term + d_term; // Clamp output if(controller->clamp_output) { output = constrain(output, controller->output_min, controller->output_max); } // Update state controller->error_prev = error; controller->last_time = now; // Return return (output); } float pid_compute_angle(pid_device_control_t *controller) { float output; // Update time deltas float now = millis(); float dt = (now - controller->last_time); // Error Term float error = controller->set_point - controller->input; error = atan2(sin(error),cos(error)); // Keep between -PI and PI // Compute proportional term float p_term = controller->k_p * error; // Compute integral term controller->integral_error += error * dt; // constrain(error, -ITERM_MAX_ERROR, ITERM_MAX_ERROR); controller->integral_error = constrain(controller->integral_error, -controller->integral_windup_max, controller->integral_windup_max); float i_term = (controller->k_i * controller->integral_error); // Compute derivative term float d_error = (error - controller->error_prev) / dt; float d_term = controller->k_d * d_error; // Compute output output = p_term + i_term + d_term; // Clamp output if(controller->clamp_output) { output = constrain(output, controller->output_min, controller->output_max); } // Update state controller->error_prev = error; controller->last_time = now; // Return return (output); }
2.3125
2
2024-11-18T22:11:34.752680+00:00
2014-11-23T01:42:50
4b85ef432ea072db468b3564bb43d425d0eef203
{ "blob_id": "4b85ef432ea072db468b3564bb43d425d0eef203", "branch_name": "refs/heads/master", "committer_date": "2014-11-23T01:42:50", "content_id": "affa4b455b163ed81cb3b2b38d62da7394cdbf10", "detected_licenses": [ "MIT" ], "directory_id": "8667a8b43c65d16ab90cc5246cb31126411da114", "extension": "c", "filename": "mrsh.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2386, "license": "MIT", "license_type": "permissive", "path": "/src/mrsh.c", "provenance": "stackv2-0087.json.gz:3115", "repo_name": "gitter-badger/MrShell", "revision_date": "2014-11-23T01:42:50", "revision_id": "c4609108f8c00746ad7a14ba54ad3e3fcee40a3a", "snapshot_id": "6f63bb334fb249f7b9d49d10b8350f2599af4f5e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gitter-badger/MrShell/c4609108f8c00746ad7a14ba54ad3e3fcee40a3a/src/mrsh.c", "visit_date": "2021-01-21T18:05:08.652129" }
stackv2
#include <stdio.h> // printf, sprintf, perror #include <stdlib.h> // strtol, getenv #include <unistd.h> // getcwd #include <string.h> // strcmp #include <pthread.h> #include <readline/readline.h> // readline #include <readline/history.h> // add_history // #include "common.h" // printWelcome #include "parse.h" // parse #include "execute.h" // execute #include "chalk.h" // color constants // === Structs === // struct commandArgs { // int argc; // //const char **argv; // char *argv[64]; // }; int main (void) { printWelcome(); char *line; char *argv[64]; /* the command line argument */ // struct commandArgs cmd; // pthread_t run_thread; char cwd[1024]; char promptMessage[1024]; while (1) { // Get Current Working Directory if (getcwd(cwd, sizeof(cwd)) != NULL) { // Get current user char *user = getenv("USER"); if(user == NULL) { exit(1); } // Prompt User sprintf(promptMessage, "%s%s%s@%s%s%s%s", KRED, user, KNORMAL, KBLUE, cwd, KNORMAL, "$ "); line = readline(promptMessage); if (line == NULL) { perror("READLINE ERROR!"); exit(1); } // Add the line to history if (line[0]!=0) { add_history(line); } //printf("Line: %s\n", line); parse(line, argv); /* parse the line */ //printf("Argv: %s\n", argv[0]); // If no parameters restart loop if (argv[0] == NULL) { //printf("Please enter a valid command.\n"); continue; } else if (strcmp(line, "exit") == 0 || strcmp(line, "quit") == 0) { // If user wishes to exit mrsh break out of loop break; } else // Else execute command { execute(argv); } } else { perror("Error: Couldn't get the current directory, weird."); exit(1); } } printf("\nMrShell piping out!\n"); return 0; }
2.875
3
2024-11-18T22:11:36.528853+00:00
2019-01-19T19:17:42
105733ab9eb31046547ff623d9a5ee220b2da6a5
{ "blob_id": "105733ab9eb31046547ff623d9a5ee220b2da6a5", "branch_name": "refs/heads/master", "committer_date": "2019-01-19T19:17:42", "content_id": "8bdc371b44a48d25d5f919ab2ee695905c66c489", "detected_licenses": [ "MIT" ], "directory_id": "415723f96bc30db1f3d545a39538da62d4309739", "extension": "c", "filename": "gen.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 166581670, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5804, "license": "MIT", "license_type": "permissive", "path": "/gen.c", "provenance": "stackv2-0087.json.gz:4016", "repo_name": "Radnyx/Fast-BF", "revision_date": "2019-01-19T19:17:42", "revision_id": "01a53e332dffa2c77f56679046ea6f49ce7f9a0c", "snapshot_id": "bed4f3f92fb73572f436afd1e71f7e74c9e3bf57", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Radnyx/Fast-BF/01a53e332dffa2c77f56679046ea6f49ce7f9a0c/gen.c", "visit_date": "2020-04-17T12:29:52.447728" }
stackv2
#include "gen.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "abstract.h" const int DEFAULT_BUFFER_SIZE = 256; /* Begins an output C program */ const char * HEAD = "#include <stdio.h>\n" "#include <stdlib.h>\n" "#include <string.h>\n" "unsigned tapeSize;\n" "unsigned * tape;\n" "unsigned * ptr;\n" "const size_t ELEM_SIZE = sizeof(*ptr);\n" "void moveLeft(int steps) {\n" " while (ptr - steps < tape) {\n" " int offset = tape - ptr;\n" " int * newTape = calloc(tapeSize * 2, ELEM_SIZE);\n" " memset(newTape, 0, tapeSize * ELEM_SIZE);\n" " memcpy(newTape + tapeSize, tape, tapeSize * ELEM_SIZE);\n" " free(tape);\n" " tape = newTape;\n" " ptr = tape + tapeSize + offset;\n" " tapeSize *= 2;\n" " }\n" " ptr -= steps;\n" "}\n" "void moveRight(int steps) {\n" " ptr += steps;\n" " while (ptr >= tape + tapeSize) {\n" " int overshoot = ptr - (tape + tapeSize);\n" " int * newTape = calloc(tapeSize * 2, ELEM_SIZE);\n" " memset(newTape + tapeSize, 0, tapeSize * ELEM_SIZE);\n" " memcpy(newTape, tape, tapeSize * ELEM_SIZE);\n" " free(tape);\n" " tape = newTape;\n" " ptr = tape + tapeSize + overshoot;\n" " tapeSize *= 2;\n" " }\n" "}\n" "int main() {\n" " tapeSize = 256;\n" " tape = calloc(tapeSize, ELEM_SIZE);\n" " ptr = tape;\n" " memset(tape, 0, tapeSize);\n"; /* Finishes an output C program */ const char * TAIL = " free(tape);\n" " return 0;\n" "}\n"; const char * INCREMENT = "++*ptr;"; const char * DECREMENT = "--*ptr;"; const char * MOVE_LEFT = "moveLeft(1);"; const char * MOVE_RGHT = "moveRight(1);"; const char * WHILE_NZR = "while(*ptr) {"; const char * END_WHILE = "}"; const char * PRNT_CHAR = "putchar(*ptr);"; const char * READ_CHAR = "*ptr = getchar();"; const char * INC_TEMPL = "*ptr += %d;"; const char * DEC_TEMPL = "*ptr -= %d;"; const char * MVL_TEMPL = "moveLeft(%d);"; const char * MVR_TEMPL = "moveRight(%d);"; const char * ASN_TEMPL = "*ptr = %d;"; void initProgram(Program * program, Settings * settings, int capacity) { program->code = malloc(capacity); program->length = 0; program->code[0] = '\0'; program->capacity = capacity; program->depth = 2; program->settings = settings; } /* Resizes a program string if needed */ void tryResize(Program * program) { assert(program->length <= program->capacity); if (program->length == program->capacity) { char * newCode = malloc(program->capacity * 2); memcpy(newCode, program->code, program->capacity); free(program->code); program->code = newCode; program->capacity *= 2; } } /* Emit a single character to the program */ void emitc(Program * program, char c) { tryResize(program); program->code[program->length++] = c; // if (program->settings->verbose) { // putchar(c); // } } /* Emit text to the given C program */ void emit(Program * program, const char * text) { while (*text != 0) emitc(program, *(text++)); } /* Emit a given number of spaces to the program */ void emitSpaces(Program * program, int spaces) { while(spaces--) emitc(program, ' '); } /* Emit code specifically, and finish a comment */ void emitCode(Program * program, const char * code) { emitSpaces(program, program->depth); emit(program, code); } void genAtom(Atom * atom, Program * program) { switch(atom->symbol) { case '[': emitCode(program, WHILE_NZR); program->depth += 2; break; case ']': program->depth -= 2; emitCode(program, END_WHILE); break; case '.': emitCode(program, PRNT_CHAR); break; case ',': emitCode(program, READ_CHAR); break; default: printf("%d\n", atom->symbol);error("Incorrect symbol."); } } void genRepeat(Atom * atom, Program * program) { int times = ((Repeat *) atom)->times; // Just emit ++/-- if (times == 1) { switch (atom->symbol) { case '+': emitCode(program, INCREMENT); break; case '-': emitCode(program, DECREMENT); break; case '<': emitCode(program, MOVE_LEFT); break; case '>': emitCode(program, MOVE_RGHT); break; default: printf("%d\n", atom->symbol); error("Incorrect symbol."); } } // Emit +=/-= %d else { char buff[256]; const char * template; switch(atom->symbol) { case '+': template = INC_TEMPL; break; case '-': template = DEC_TEMPL; break; case '<': template = MVL_TEMPL; break; case '>': template = MVR_TEMPL; break; default: printf("%d\n", atom->symbol); error("Incorrect symbol."); } sprintf(buff, template, times); emitCode(program, buff); } } void genAssign(Atom * atom, Program * program) { assert(atom->symbol == 0); char buff[256]; sprintf(buff, ASN_TEMPL, ((Assign *) atom)->value); emitCode(program, buff); } void generate(Program * program, Abstract * abstract) { if (program->settings->verbose) printf("\n====== Generating Code ======\n"); for (Atom * atom = abstract->front; atom != NULL; atom = atom->next) { atom->generate(atom, program); emitc(program, '\n'); } }
3.015625
3
2024-11-18T22:11:36.635979+00:00
2020-04-21T14:44:54
8074c8370bc1433b7bdf2b7ef1c4365a85d1b8f1
{ "blob_id": "8074c8370bc1433b7bdf2b7ef1c4365a85d1b8f1", "branch_name": "refs/heads/master", "committer_date": "2020-04-21T14:45:22", "content_id": "31bd291d7a711ecfdd0b66b5c7ed0dfc32e33934", "detected_licenses": [ "CC0-1.0" ], "directory_id": "7d26005ab4d4a8a451c8e247a9915c6d0c0dfb39", "extension": "c", "filename": "heap.c", "fork_events_count": 4, "gha_created_at": "2019-07-15T19:03:21", "gha_event_created_at": "2020-05-25T11:52:18", "gha_language": "C", "gha_license_id": null, "github_id": 197056304, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 26396, "license": "CC0-1.0", "license_type": "permissive", "path": "/src/heap.c", "provenance": "stackv2-0087.json.gz:4145", "repo_name": "aradzie/dlmalloc", "revision_date": "2020-04-21T14:44:54", "revision_id": "9a42988209d01072c596e071728ad102c854de1d", "snapshot_id": "acc49e5069333dd17c93483dfcda27a9a1741bc8", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/aradzie/dlmalloc/9a42988209d01072c596e071728ad102c854de1d/src/heap.c", "visit_date": "2020-06-20T08:17:21.381022" }
stackv2
#include <errno.h> #include <sys/types.h> #include <string.h> #include "assert.h" #include "check.h" #include "chunk.h" #include "config.h" #include "debug.h" #include "error.h" #include "heap.h" #include "init.h" #include "lock.h" #include "os.h" dl_force_inline void *dl_malloc_impl(struct malloc_state *state, size_t bytes) { /* Basic algorithm: If a small request (< 256 bytes minus per-chunk overhead): 1. If one exists, use a remainderless chunk in associated small_bin. (Remainderless means that there are too few excess bytes to represent as a chunk.) 2. If it is big enough, use the dv chunk, which is normally the chunk adjacent to the one used for the most recent small request. 3. If one exists, split the smallest available chunk in a bin, saving remainder in dv. 4. If it is big enough, use the top chunk. 5. If available, get memory from system and use it Otherwise, for a large request: 1. Find the smallest available binned chunk that fits, and use it if it is better fitting than dv chunk, splitting if necessary. 2. If better fitting than any binned chunk, use the dv chunk. 3. If it is big enough, use the top chunk. 4. If request size >= mmap threshold, try to directly mmap this chunk. 5. If available, get memory from system and use it The ugly goto's here ensure that postaction occurs along all paths. */ if (!PREACTION(state)) { void *mem; size_t nb; if (bytes <= MAX_SMALL_REQUEST) { bin_map_t small_bits; nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes); bin_index_t idx = small_index(nb); small_bits = state->small_map >> idx; if ((small_bits & 0x3U) != 0) { /* Remainderless fit to a small_bin. */ idx += ~small_bits & 1; /* Uses next bin if idx empty */ struct malloc_chunk *b = small_bin_at(state, idx); struct malloc_chunk *p = b->fd; dl_assert(chunk_size(p) == small_index_to_size(idx)); unlink_first_small_chunk(state, b, p, idx); set_inuse_and_prev_inuse(state, p, small_index_to_size(idx)); mem = chunk_to_mem(p); check_malloced_chunk(state, mem, nb); goto postaction; } else if (nb > state->dv_size) { if (small_bits != 0) { /* Use chunk in next nonempty small_bin */ bin_index_t i; bin_map_t left_bits = (small_bits << idx) & left_bits(index_to_bit(idx)); bin_map_t least_bit = least_bit(left_bits); compute_bit2idx(least_bit, i); struct malloc_chunk *b = small_bin_at(state, i); struct malloc_chunk *p = b->fd; dl_assert(chunk_size(p) == small_index_to_size(i)); unlink_first_small_chunk(state, b, p, i); size_t rsize = small_index_to_size(i) - nb; /* Fit here cannot be remainderless if 4byte sizes */ if (sizeof(size_t) != 4 && rsize < MIN_CHUNK_SIZE) { set_inuse_and_prev_inuse(state, p, small_index_to_size(i)); } else { set_size_and_prev_inuse_of_inuse_chunk(state, p, nb); struct malloc_chunk *r = chunk_plus_offset(p, nb); set_size_and_prev_inuse_of_free_chunk(r, rsize); replace_dv(state, r, rsize); } mem = chunk_to_mem(p); check_malloced_chunk(state, mem, nb); goto postaction; } else if (state->tree_map != 0 && (mem = tmalloc_small(state, nb)) != 0) { check_malloced_chunk(state, mem, nb); goto postaction; } } } else if (bytes >= MAX_REQUEST) { nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ } else { nb = pad_request(bytes); if (state->tree_map != 0 && (mem = tmalloc_large(state, nb)) != 0) { check_malloced_chunk(state, mem, nb); goto postaction; } } if (nb <= state->dv_size) { size_t rsize = state->dv_size - nb; struct malloc_chunk *p = state->dv; if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ struct malloc_chunk *r = state->dv = chunk_plus_offset(p, nb); state->dv_size = rsize; set_size_and_prev_inuse_of_free_chunk(r, rsize); set_size_and_prev_inuse_of_inuse_chunk(state, p, nb); } else { /* exhaust dv */ size_t dvs = state->dv_size; state->dv_size = 0; state->dv = 0; set_inuse_and_prev_inuse(state, p, dvs); } mem = chunk_to_mem(p); check_malloced_chunk(state, mem, nb); goto postaction; } else if (nb < state->top_size) { /* Split top */ size_t rsize = state->top_size -= nb; struct malloc_chunk *p = state->top; struct malloc_chunk *r = state->top = chunk_plus_offset(p, nb); r->head = rsize | PREV_INUSE_BIT; set_size_and_prev_inuse_of_inuse_chunk(state, p, nb); mem = chunk_to_mem(p); check_top_chunk(state, state->top); check_malloced_chunk(state, mem, nb); goto postaction; } mem = sys_alloc(state, nb); postaction: POSTACTION(state); return mem; } return 0; } dl_force_inline void dl_free_impl(struct malloc_state *state, struct malloc_chunk *p) { /* Consolidate freed chunks with preceding or succeeding bordering free chunks, if they exist, and then place in a bin. Intermixed with special cases for top, dv, mmapped chunks, and usage errors. */ if (!PREACTION(state)) { check_inuse_chunk(state, p); if (likely(ok_address(state, p) && ok_inuse(p))) { size_t psize = chunk_size(p); struct malloc_chunk *next = chunk_plus_offset(p, psize); if (!prev_inuse(p)) { size_t prev_size = p->prev_foot; if (is_mmapped(p)) { psize += prev_size + MMAP_FOOT_PAD; if (call_munmap((char *) p - prev_size, psize) == 0) { state->footprint -= psize; } goto postaction; } else { struct malloc_chunk *prev = chunk_minus_offset(p, prev_size); psize += prev_size; p = prev; if (likely(ok_address(state, prev))) { /* consolidate backward */ if (p != state->dv) { unlink_chunk(state, p, prev_size); } else if ((next->head & INUSE_BITS) == INUSE_BITS) { state->dv_size = psize; set_free_with_prev_inuse(p, psize, next); goto postaction; } } else { goto erroraction; } } } if (likely(ok_next(p, next) && ok_prev_inuse(next))) { if (!curr_inuse(next)) { /* consolidate forward */ if (next == state->top) { size_t tsize = state->top_size += psize; state->top = p; p->head = tsize | PREV_INUSE_BIT; if (p == state->dv) { state->dv = 0; state->dv_size = 0; } if (should_trim(state, tsize)) { sys_trim(state, 0); } goto postaction; } else if (next == state->dv) { size_t dsize = state->dv_size += psize; state->dv = p; set_size_and_prev_inuse_of_free_chunk(p, dsize); goto postaction; } else { size_t nsize = chunk_size(next); psize += nsize; unlink_chunk(state, next, nsize); set_size_and_prev_inuse_of_free_chunk(p, psize); if (p == state->dv) { state->dv_size = psize; goto postaction; } } } else { set_free_with_prev_inuse(p, psize, next); } if (is_small(psize)) { insert_small_chunk(state, p, psize); check_free_chunk(state, p); } else { struct malloc_tree_chunk *tp = (struct malloc_tree_chunk *) p; insert_large_chunk(state, tp, psize); check_free_chunk(state, p); if (--state->release_checks == 0) { release_unused_segments(state); } } goto postaction; } } erroraction: usage_error(state, p); postaction: POSTACTION(state); } } /* allocate a large request from the best fitting chunk in a tree_bin */ void *tmalloc_large(struct malloc_state *state, size_t nb) { struct malloc_tree_chunk *v = 0; size_t rsize = -nb; /* Unsigned negation */ struct malloc_tree_chunk *t; bin_index_t idx; compute_tree_index(nb, idx); if ((t = *tree_bin_at(state, idx)) != 0) { /* Traverse tree for this bin looking for node with size == nb */ size_t sizebits = nb << leftshift_for_tree_index(idx); struct malloc_tree_chunk *rst = 0; /* The deepest untaken right subtree */ for (;;) { struct malloc_tree_chunk *rt; size_t trem = chunk_size(t) - nb; if (trem < rsize) { v = t; if ((rsize = trem) == 0) { break; } } rt = t->child[1]; t = t->child[(sizebits >> (SIZE_T_BITSIZE - (size_t) 1)) & 1]; if (rt != 0 && rt != t) { rst = rt; } if (t == 0) { t = rst; /* set t to least subtree holding sizes > nb */ break; } sizebits <<= 1; } } if (t == 0 && v == 0) { /* set t to root of next non-empty tree_bin */ bin_map_t left_bits = left_bits(index_to_bit(idx)) & state->tree_map; if (left_bits != 0) { bin_index_t i; bin_map_t least_bit = least_bit(left_bits); compute_bit2idx(least_bit, i); t = *tree_bin_at(state, i); } } while (t != 0) { /* find smallest of tree or subtree */ size_t trem = chunk_size(t) - nb; if (trem < rsize) { rsize = trem; v = t; } t = leftmost_child(t); } /* If dv is a better fit, return 0 so malloc will use it */ if (v != 0 && rsize < (size_t) (state->dv_size - nb)) { if (likely(ok_address(state, v))) { /* split */ struct malloc_chunk *r = chunk_plus_offset(v, nb); dl_assert(chunk_size(v) == rsize + nb); if (likely(ok_next(v, r))) { unlink_large_chunk(state, v); if (rsize < MIN_CHUNK_SIZE) { set_inuse_and_prev_inuse(state, v, (rsize + nb)); } else { set_size_and_prev_inuse_of_inuse_chunk(state, v, nb); set_size_and_prev_inuse_of_free_chunk(r, rsize); insert_chunk(state, r, rsize); } return chunk_to_mem(v); } } corruption_error(state); } return 0; } /* allocate a small request from the best fitting chunk in a tree_bin */ void *tmalloc_small(struct malloc_state *state, size_t nb) { struct malloc_tree_chunk *t, *v; bin_index_t i; bin_map_t least_bit = least_bit(state->tree_map); compute_bit2idx(least_bit, i); v = t = *tree_bin_at(state, i); size_t rsize = chunk_size(t) - nb; while ((t = leftmost_child(t)) != 0) { size_t trem = chunk_size(t) - nb; if (trem < rsize) { rsize = trem; v = t; } } if (likely(ok_address(state, v))) { struct malloc_chunk *r = chunk_plus_offset(v, nb); dl_assert(chunk_size(v) == rsize + nb); if (likely(ok_next(v, r))) { unlink_large_chunk(state, v); if (rsize < MIN_CHUNK_SIZE) { set_inuse_and_prev_inuse(state, v, (rsize + nb)); } else { set_size_and_prev_inuse_of_inuse_chunk(state, v, nb); set_size_and_prev_inuse_of_free_chunk(r, rsize); replace_dv(state, r, rsize); } return chunk_to_mem(v); } } corruption_error(state); return 0; } /* Try to realloc; only in-place unless can_move true */ struct malloc_chunk *try_realloc_chunk(struct malloc_state *state, struct malloc_chunk *chunk, size_t nb, int can_move) { struct malloc_chunk *new_p = 0; size_t old_size = chunk_size(chunk); struct malloc_chunk *next = chunk_plus_offset(chunk, old_size); if (likely(ok_address(state, chunk) && ok_inuse(chunk) && ok_next(chunk, next) && ok_prev_inuse(next))) { if (is_mmapped(chunk)) { new_p = mmap_resize(state, chunk, nb, can_move); } else if (old_size >= nb) { /* already big enough */ size_t rsize = old_size - nb; if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */ struct malloc_chunk *r = chunk_plus_offset(chunk, nb); set_inuse(state, chunk, nb); set_inuse(state, r, rsize); dispose_chunk(state, r, rsize); } new_p = chunk; } else if (next == state->top) { /* extend into top */ if (old_size + state->top_size > nb) { size_t new_size = old_size + state->top_size; size_t new_top_size = new_size - nb; struct malloc_chunk *new_top = chunk_plus_offset(chunk, nb); set_inuse(state, chunk, nb); new_top->head = new_top_size | PREV_INUSE_BIT; state->top = new_top; state->top_size = new_top_size; new_p = chunk; } } else if (next == state->dv) { /* extend into dv */ size_t dvs = state->dv_size; if (old_size + dvs >= nb) { size_t dsize = old_size + dvs - nb; if (dsize >= MIN_CHUNK_SIZE) { struct malloc_chunk *r = chunk_plus_offset(chunk, nb); struct malloc_chunk *n = chunk_plus_offset(r, dsize); set_inuse(state, chunk, nb); set_size_and_prev_inuse_of_free_chunk(r, dsize); clear_prev_inuse(n); state->dv_size = dsize; state->dv = r; } else { /* exhaust dv */ size_t new_size = old_size + dvs; set_inuse(state, chunk, new_size); state->dv_size = 0; state->dv = 0; } new_p = chunk; } } else if (!curr_inuse(next)) { /* extend into next free chunk */ size_t next_size = chunk_size(next); if (old_size + next_size >= nb) { size_t rsize = old_size + next_size - nb; unlink_chunk(state, next, next_size); if (rsize < MIN_CHUNK_SIZE) { size_t new_size = old_size + next_size; set_inuse(state, chunk, new_size); } else { struct malloc_chunk *r = chunk_plus_offset(chunk, nb); set_inuse(state, chunk, nb); set_inuse(state, r, rsize); dispose_chunk(state, r, rsize); } new_p = chunk; } } } else { usage_error(state, chunk_to_mem(chunk)); } return new_p; } void *internal_memalign(struct malloc_state *state, size_t alignment, size_t bytes) { void *mem = 0; if (alignment < MIN_CHUNK_SIZE) { /* must be at least a minimum chunk size */ alignment = MIN_CHUNK_SIZE; } if ((alignment & (alignment - (size_t) 1)) != 0) {/* Ensure a power of 2 */ size_t a = MALLOC_ALIGNMENT << 1; while (a < alignment) { a <<= 1; } alignment = a; } if (bytes >= MAX_REQUEST - alignment) { if (state != 0) { /* Test isn't needed but avoids compiler warning */ malloc_failure(); } } else { size_t nb = request_to_size(bytes); size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; mem = internal_malloc(state, req); if (mem != 0) { struct malloc_chunk *p = mem_to_chunk(mem); if (PREACTION(state)) { return 0; } if ((((size_t) mem) & (alignment - 1)) != 0) { /* misaligned */ /* Find an aligned spot inside chunk. Since we need to give back leading space in a chunk of at least MIN_CHUNK_SIZE, if the first calculation places us at a spot with less than MIN_CHUNK_SIZE leader, we can move to the next aligned spot. We've allocated enough total room so that this is always possible. */ char *br = (char *) mem_to_chunk( (void *) (((size_t) ((char *) mem + alignment - (size_t) 1)) & -alignment)); char *pos = (size_t) (br - (char *) p) >= MIN_CHUNK_SIZE ? br : br + alignment; struct malloc_chunk *new_p = (struct malloc_chunk *) pos; size_t lead_size = pos - (char *) p; size_t new_size = chunk_size(p) - lead_size; if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ new_p->prev_foot = p->prev_foot + lead_size; new_p->head = new_size; } else { /* Otherwise, give back leader, use the rest */ set_inuse(state, new_p, new_size); set_inuse(state, p, lead_size); dispose_chunk(state, p, lead_size); } p = new_p; } /* Give back spare room at the end */ if (!is_mmapped(p)) { size_t size = chunk_size(p); if (size > nb + MIN_CHUNK_SIZE) { size_t remainder_size = size - nb; struct malloc_chunk *remainder = chunk_plus_offset(p, nb); set_inuse(state, p, nb); set_inuse(state, remainder, remainder_size); dispose_chunk(state, remainder, remainder_size); } } mem = chunk_to_mem(p); dl_assert (chunk_size(p) >= nb); dl_assert(((size_t) mem & (alignment - 1)) == 0); check_inuse_chunk(state, p); POSTACTION(state); } } return mem; } /* Common support for independent_X routines, handling all of the combinations that can result. The opts arg has: bit 0 set if all elements are same size (using sizes[0]) bit 1 set if elements should be zeroed */ void **ialloc(struct malloc_state *state, size_t n_elements, size_t *sizes, int opts, void *chunks[]) { size_t element_size; /* chunk_size of each element, if all same */ size_t contents_size; /* total size of elements */ size_t array_size; /* request size of pointer array */ void *mem; /* malloced aggregate space */ struct malloc_chunk *p; /* corresponding chunk */ size_t remainder_size; /* remaining bytes while splitting */ void **marray; /* either "chunks" or malloced ptr array */ struct malloc_chunk *array_chunk; /* chunk for malloced ptr array */ flag_t was_enabled; /* to disable mmap */ size_t size; size_t i; ensure_initialization(); /* compute array length, if needed */ if (chunks != 0) { if (n_elements == 0) { return chunks; } /* nothing to do */ marray = chunks; array_size = 0; } else { /* if empty req, must still return chunk representing empty array */ if (n_elements == 0) { return (void **) internal_malloc(state, 0); } marray = 0; array_size = request_to_size(n_elements * (sizeof(void *))); } /* compute total element size */ if (opts & 0x1) { /* all-same-size */ element_size = request_to_size(*sizes); contents_size = n_elements * element_size; } else { /* add up all the sizes */ element_size = 0; contents_size = 0; for (i = 0; i != n_elements; ++i) { contents_size += request_to_size(sizes[i]); } } size = contents_size + array_size; /* Allocate the aggregate chunk. First disable direct-mmapping so malloc won't use it, since we would not be able to later free/realloc space internal to a segregated mmap region. */ was_enabled = use_mmap(state); disable_mmap(state); mem = internal_malloc(state, size - CHUNK_OVERHEAD); if (was_enabled) { enable_mmap(state); } if (mem == 0) { return 0; } if (PREACTION(state)) { return 0; } p = mem_to_chunk(mem); remainder_size = chunk_size(p); dl_assert(!is_mmapped(p)); if (opts & 0x2) { /* optionally clear the elements */ memset((size_t *) mem, 0, remainder_size - sizeof(size_t) - array_size); } /* If not provided, allocate the pointer array as final part of chunk */ if (marray == 0) { size_t array_chunk_size; array_chunk = chunk_plus_offset(p, contents_size); array_chunk_size = remainder_size - contents_size; marray = (void **) (chunk_to_mem(array_chunk)); set_size_and_prev_inuse_of_inuse_chunk(state, array_chunk, array_chunk_size); remainder_size = contents_size; } /* split out elements */ for (i = 0;; ++i) { marray[i] = chunk_to_mem(p); if (i != n_elements - 1) { if (element_size != 0) { size = element_size; } else { size = request_to_size(sizes[i]); } remainder_size -= size; set_size_and_prev_inuse_of_inuse_chunk(state, p, size); p = chunk_plus_offset(p, size); } else { /* the final element absorbs any overallocation slop */ set_size_and_prev_inuse_of_inuse_chunk(state, p, remainder_size); break; } } #if DEBUG if (marray != chunks) { /* final element must have exactly exhausted chunk */ if (element_size != 0) { dl_assert(remainder_size == element_size); } else { dl_assert(remainder_size == request_to_size(sizes[i])); } check_inuse_chunk(state, mem_to_chunk(marray)); } for (i = 0; i != n_elements; ++i) { check_inuse_chunk(state, mem_to_chunk(marray[i])); } #endif /* DEBUG */ POSTACTION(state); return marray; } /* Try to free all pointers in the given array. Note: this could be made faster, by delaying consolidation, at the price of disabling some user integrity checks, We still optimize some consolidations by combining adjacent chunks before freeing, which will occur often if allocated with ialloc or the array is sorted. */ size_t internal_bulk_free(struct malloc_state *state, void *array[], size_t nelem) { size_t unfreed = 0; if (!PREACTION(state)) { void **a; void **fence = &(array[nelem]); for (a = array; a != fence; ++a) { void *mem = *a; if (mem != 0) { struct malloc_chunk *p = mem_to_chunk(mem); size_t p_size = chunk_size(p); #if FOOTERS if (get_state_for(p) != state) { ++unfreed; continue; } #endif check_inuse_chunk(state, p); *a = 0; if (likely(ok_address(state, p) && ok_inuse(p))) { void **b = a + 1; /* try to merge with next chunk */ struct malloc_chunk *next = next_chunk(p); if (b != fence && *b == chunk_to_mem(next)) { size_t new_size = chunk_size(next) + p_size; set_inuse(state, p, new_size); *b = chunk_to_mem(p); } else { dispose_chunk(state, p, p_size); } } else { corruption_error(state); break; } } } if (should_trim(state, state->top_size)) { sys_trim(state, 0); } POSTACTION(state); } return unfreed; }
2.453125
2
2024-11-18T22:11:37.596090+00:00
2021-04-01T05:19:30
259d1b87dd20ad09b75890a7ddc47aeab9118628
{ "blob_id": "259d1b87dd20ad09b75890a7ddc47aeab9118628", "branch_name": "refs/heads/main", "committer_date": "2021-04-01T05:19:30", "content_id": "b31e3a43aa4b9557c10380fb78a0fe7ccb031e4f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "12d5b77ed33be6c225fff94b7f1093759058e3ec", "extension": "h", "filename": "pal_arm_gic.h", "fork_events_count": 0, "gha_created_at": "2021-07-04T00:04:36", "gha_event_created_at": "2021-07-04T00:04:37", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 382730245, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6001, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/platform/driver/inc/pal_arm_gic.h", "provenance": "stackv2-0087.json.gz:4536", "repo_name": "QPC-database/ff-a-acs", "revision_date": "2021-04-01T05:19:30", "revision_id": "f3a730bc421d8f265a1509aec9dcccbde6b8335b", "snapshot_id": "855dab8c9fa503399c4b1e04c1e689a53a220ad7", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/QPC-database/ff-a-acs/f3a730bc421d8f265a1509aec9dcccbde6b8335b/platform/driver/inc/pal_arm_gic.h", "visit_date": "2023-03-29T16:55:32.831427" }
stackv2
/* * Copyright (c) 2021, Arm Limited or its affliates. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause * */ #ifndef __ARM_GIC_H__ #define __ARM_GIC_H__ #include <stdint.h> /*************************************************************************** * Defines and prototypes for ARM GIC driver. **************************************************************************/ #define MAX_SGIS 16 #define MIN_SGI_ID 0 #define MAX_SGI_ID 15 #define MIN_PPI_ID 16 #define MAX_PPI_ID 31 #define MIN_SPI_ID 32 #define MAX_SPI_ID 1019 #define IS_SGI(irq_num) \ (((irq_num) >= MIN_SGI_ID) && ((irq_num) <= MAX_SGI_ID)) #define IS_PPI(irq_num) \ (((irq_num) >= MIN_PPI_ID) && ((irq_num) <= MAX_PPI_ID)) #define IS_SPI(irq_num) \ (((irq_num) >= MIN_SPI_ID) && ((irq_num) <= MAX_SPI_ID)) #define IS_VALID_INTR_ID(irq_num) \ (((irq_num) >= MIN_SGI_ID) && ((irq_num) <= MAX_SPI_ID)) #define GIC_HIGHEST_NS_PRIORITY 0 #define GIC_LOWEST_NS_PRIORITY 254 /* 255 would disable an interrupt */ #define GIC_SPURIOUS_INTERRUPT 1023 /****************************************************************************** * Setup the global GIC interface. In case of GICv2, it would be the GIC * Distributor and in case of GICv3 it would be GIC Distributor and * Re-distributor. *****************************************************************************/ void arm_gic_setup_global(void); /****************************************************************************** * Setup the GIC interface local to the CPU *****************************************************************************/ void arm_gic_setup_local(void); /****************************************************************************** * Disable interrupts for this local CPU *****************************************************************************/ void arm_gic_disable_interrupts_local(void); /****************************************************************************** * Enable interrupts for this local CPU *****************************************************************************/ void arm_gic_enable_interrupts_local(void); /****************************************************************************** * Send SGI with ID `sgi_id` to a core with index `core_pos`. *****************************************************************************/ void arm_gic_send_sgi(int sgi_id, unsigned int core_pos); /****************************************************************************** * Set the interrupt target of interrupt ID `num` to a core with index * `core_pos` *****************************************************************************/ void arm_gic_set_intr_target(int num, unsigned int core_pos); /****************************************************************************** * Get the priority of the interrupt ID `num`. *****************************************************************************/ unsigned int arm_gic_get_intr_priority(int num); /****************************************************************************** * Set the priority of the interrupt ID `num` to `priority`. *****************************************************************************/ void arm_gic_set_intr_priority(int num, unsigned int priority); /****************************************************************************** * Check if the interrupt ID `num` is enabled *****************************************************************************/ unsigned int arm_gic_intr_enabled(int num); /****************************************************************************** * Enable the interrupt ID `num` *****************************************************************************/ void arm_gic_intr_enable(int num); /****************************************************************************** * Disable the interrupt ID `num` *****************************************************************************/ void arm_gic_intr_disable(int num); /****************************************************************************** * Acknowledge the highest pending interrupt. Return the interrupt ID of the * acknowledged interrupt. The raw interrupt acknowledge register value will * be populated in `raw_iar`. *****************************************************************************/ unsigned int arm_gic_intr_ack(unsigned int *raw_iar); /****************************************************************************** * Signal the end of interrupt processing of a interrupt. The raw interrupt * acknowledge register value returned by arm_gic_intr_ack() should be passed * as argument to this function. *****************************************************************************/ void arm_gic_end_of_intr(unsigned int raw_iar); /****************************************************************************** * Check if the interrupt with ID `num` is pending at the GIC. Returns 1 if * interrupt is pending else returns 0. *****************************************************************************/ unsigned int arm_gic_is_intr_pending(unsigned int num); /****************************************************************************** * Clear the pending status of the interrupt with ID `num` at the GIC. *****************************************************************************/ void arm_gic_intr_clear(unsigned int num); /****************************************************************************** * Initialize the GIC Driver. This function will detect the GIC Architecture * present on the system and initialize the appropriate driver. The * `gicr_base` argument will be ignored on GICv2 systems. *****************************************************************************/ void arm_gic_init(uintptr_t gicc_base, uintptr_t gicd_base, uintptr_t gicr_base); #endif /* __ARM_GIC_H__ */
2.15625
2
2024-11-18T22:11:38.123947+00:00
2016-07-05T19:28:10
17b55ed16197057858b5d6b1d8b59bf05f2ecc04
{ "blob_id": "17b55ed16197057858b5d6b1d8b59bf05f2ecc04", "branch_name": "refs/heads/master", "committer_date": "2016-07-05T19:28:10", "content_id": "09aadf4a141ac60204487f4b38eafc79eaf9f8b9", "detected_licenses": [ "MIT" ], "directory_id": "d5d5cd412f34c49d56211550d8b6e6ae19d899c7", "extension": "c", "filename": "EventHandler.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 62642636, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1389, "license": "MIT", "license_type": "permissive", "path": "/lemtils/EventHandler.c", "provenance": "stackv2-0087.json.gz:4665", "repo_name": "mccarpat/S4-Logger", "revision_date": "2016-07-05T19:28:10", "revision_id": "16133cbd47d6396b30daf6a59c8ff61744836c76", "snapshot_id": "f1c1e99f30b6cf9d143c512bb933654504696928", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mccarpat/S4-Logger/16133cbd47d6396b30daf6a59c8ff61744836c76/lemtils/EventHandler.c", "visit_date": "2021-01-19T01:17:16.899253" }
stackv2
#ifndef _LEM_EVENTHANDLER_C #define _LEM_EVENTHANDLER_C 1 /* * EventHandler.c * * Created: 11/27/2015 * Author: Patrick McCarthy * Part of Patrick's "lemtils" utility package * A task manager for the ATmega328p, for use with the EGR 326 Alarm Clock project. * */ #include "EventHandler.h" void event_Start(struct an_event *event){ event->countdown = event->default_countdown; // Means: event.countdown = event.default_countdown; event->is_planned = true; } void event_StartNow(struct an_event *event){ event->countdown = 0; event->is_planned = true; } void event_ResetCountdown(struct an_event *event){ event->countdown = event->default_countdown; } void event_Cancel(struct an_event *event){ event->is_planned = false; } void event_Tick(struct an_event *event){ if ((event->is_planned == true) && (event->countdown > 0)) {event->countdown--;} } void event_Initialize(struct an_event *event, unsigned short default_countdown){ event->default_countdown = default_countdown; event->is_planned = false; } bool event_IsReady(struct an_event *event) { if ((event->is_planned == true) && (event->countdown == 0)){ event->is_planned = false; // Turn off the event countdown return true; } else { return false; } } bool event_CountdownIsZero(struct an_event *event) { if (event->countdown == 0){ return true; } else { return false; } } #endif
2.3125
2
2024-11-18T22:11:38.329436+00:00
2021-03-16T19:44:32
1ad3804f34af98020865173e573056336e3c0454
{ "blob_id": "1ad3804f34af98020865173e573056336e3c0454", "branch_name": "refs/heads/main", "committer_date": "2021-03-16T19:44:32", "content_id": "a836095ab77bffe6d88923c955c3ce2fd2157017", "detected_licenses": [ "MIT" ], "directory_id": "d0d4acfc2f7ce949448f9cbe3a34278cf9c1ce6e", "extension": "h", "filename": "lista_de_adjacencia.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7400, "license": "MIT", "license_type": "permissive", "path": "/src/model/lista_de_adjacencia.h", "provenance": "stackv2-0087.json.gz:4923", "repo_name": "leandrohl/graph-manipulation", "revision_date": "2021-03-16T19:44:32", "revision_id": "bafa420acc3dcba3abc3bcee60b3ccf44be8247d", "snapshot_id": "1c47dfb9ce1970feebd61b5d8112bfbf5601e534", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/leandrohl/graph-manipulation/bafa420acc3dcba3abc3bcee60b3ccf44be8247d/src/model/lista_de_adjacencia.h", "visit_date": "2023-03-23T03:38:38.468514" }
stackv2
#ifndef LISTA_DE_ADJACENCIA_H_INCLUDED #define LISTA_DE_ADJACENCIA_H_INCLUDED typedef struct no *No; struct no{ int vertice; int peso; No next; }; typedef struct { int tipoGrafo; //0 para dígrafo e 1 para grafo não orientado int numVertices; //numero de vertices do grafo int numArcos; //se o grafo for um dígrafo, esta variavel sera utilizada int numArestas; //se for um grafo nao orientado, esta variavel sera utilizada No *lista; //armazena a lista de adjacencia } GraphList; void graphListView(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. GraphList* graphListReadArq(FILE *log, FILE *arq); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //FILE *arq -> arquivo que contem os dados do grafo orientado ou não orientado. void insertArqOrEdgesToGraphList(FILE *log, FILE *arq, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //FILE *arq -> arquivo que contem os dados do grafo orientado ou não orientado. //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. void graphListWriteArq(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. void graphListWriteArqDFS(FILE *log, GraphList *graph, int *d, int *f); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. //int *d -> um ponteiro para uma lista que armazena o tempo de descoberta de cada vertice //int *f -> um ponteiro para uma lista que armazena o tempo de finalização de cada vertice void graphListDFSVISIT(FILE *log, GraphList *graph, int vertex, char *cor, int *d, int *f, int *tempo); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. //int vertex -> indica o vertice que está sendo visitado //int *cor -> um ponteiro para uma lista que armazena a cor de cada vertice //int *d -> um ponteiro para uma lista que armazena o tempo de descoberta de cada vertice //int *f -> um ponteiro para uma lista que armazena o tempo de finalização de cada vertice //int *tempo -> um ponteiro para uma variavel inteira que armazena o tempo void graphListDFS(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. void graphListWriteArqBFS(FILE *log, GraphList *graph, int raiz, int *d, int *f); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. //int raiz -> raiz da busca //int *d -> um ponteiro para uma lista que armazena a distancia de cada vertice a origem(raiz) //int *f -> um ponteiro para uma lista que armazena o vertice predecessor de cada vertice void graphListBFS(FILE *log, GraphList *graph, int raiz); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. //int raiz -> raiz da busca GraphList* graphListInsertVertex(FILE *log, GraphList *graph, int qtd); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. //int qtd -> indica a quantidade de vertices que serão inseridos no grafo void insertArqOrEdgesGraphList(FILE *log, GraphList *graph, int ini, int fim, int peso); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. //int ini -> indica o vertice inicial do arco/aresta //int fim -> indica o vertice final do arco/aresta //int peso -> indica o peso do arco void graphListRemoveVertex(FILE *log, GraphList *graph, int vertex); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. //int vertex -> indica o vertice que deve ser removido void graphListRemoveArcOrEdges(FILE *log, GraphList *graph, int ini, int fim); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. //int ini -> indica o vertice inicial da arco/aresta //int fim -> indica o vertice final do arco/aresta void grauVertexGraphListOrd(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. void grauVertexGraphListNOrd(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. void orderAndSizeGraphList(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. void listVertexAndArcGraphList(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. void listVertexAndEdgesGraphList(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. void checkLacesGraphList(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. void checkMultipleEdgesGraphList(FILE *log, GraphList *graph); //FILE *log -> ponteiro para um arquivo em que será escrito o nome desta função (log do processamento) //GraphList *graph -> um ponteiro para a estrutura que armazena os dados do grafo e a lista de adjacencia. #endif // LISTA_DE_ADJACENCIA_H_INCLUDED
2.609375
3
2024-11-18T22:11:38.410362+00:00
2021-04-09T07:28:14
db5d480a905ea5564b91e8f32f94352fb3e87454
{ "blob_id": "db5d480a905ea5564b91e8f32f94352fb3e87454", "branch_name": "refs/heads/master", "committer_date": "2021-04-09T07:28:14", "content_id": "d3678a0c541f38250291ac8df486769f078aa8d8", "detected_licenses": [ "MIT" ], "directory_id": "be35500a8c82755553acb020e8095e182000c90a", "extension": "h", "filename": "ConvertBoard.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 252348139, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11623, "license": "MIT", "license_type": "permissive", "path": "/UI/ConvertBoard.h", "provenance": "stackv2-0087.json.gz:5051", "repo_name": "NickLee2050/HustProgramDesign", "revision_date": "2021-04-09T07:28:14", "revision_id": "41f90c406218f0960a7c51112beb26b6c3e10d68", "snapshot_id": "f97ba44ed9cad51f969f92902805f00c7d29e5cd", "src_encoding": "UTF-8", "star_events_count": 19, "url": "https://raw.githubusercontent.com/NickLee2050/HustProgramDesign/41f90c406218f0960a7c51112beb26b6c3e10d68/UI/ConvertBoard.h", "visit_date": "2021-05-20T15:24:12.518326" }
stackv2
#include <stdlib.h> #include <stdbool.h> #include "DataSetDef.h" #ifndef __PRELIM__ #define __PRELIM__ #define TRUE 1 #define OK 1 #define FALSE 0 #define ERROR 0 #define INFEASIBLE -1 #define OVF -1 #define INIT_SIZE 10 #define SIZE_INCREAMENT 5 typedef int Status; #endif #ifndef __BOARD__CONVERT__ #define __BOARD__CONVERT__ ClaNode *TripletAvoid(int size, ClaNode *head) { ClaNode *prev = head; //In row for (int i = 0; i < size; i++) for (int j = 0; j < size - 2; j++) { ClaNode *cur = InitCla(); cur->next = InitCla(); cla_count += 2; for (int k = j; k <= j + 2; k++) AddToCla(cur, i * size + k + 1); for (int k = j; k <= j + 2; k++) AddToCla(cur->next, (i * size + k + 1) * -1); cur->next->next = prev; prev = cur; } //In line for (int i = 0; i < size; i++) for (int j = 0; j < size - 2; j++) { ClaNode *cur = InitCla(); cur->next = InitCla(); cla_count += 2; for (int k = j; k <= j + 2; k++) AddToCla(cur, k * size + i + 1); for (int k = j; k <= j + 2; k++) AddToCla(cur->next, (k * size + i + 1) * -1); cur->next->next = prev; prev = cur; } return prev; } ClaNode *HalfVar(int size, ClaNode *head) { if (size % 2) return NULL; int count = size / 2 + 1; ClaNode *prev = head; int *arrange = (int *)malloc(sizeof(int) * count); if (!arrange) exit(-1); for (int i = 0; i < size; i++) { //Initialization for (int j = 0; j < count; j++) arrange[j] = j; //Detect final reach bool final_reach; do { //Create new constraints //In row { ClaNode *cur = InitCla(); cur->next = InitCla(); cla_count += 2; for (int k = 0; k < count; k++) AddToCla(cur, i * size + arrange[k] + 1); for (int k = 0; k < count; k++) AddToCla(cur->next, (i * size + arrange[k] + 1) * -1); cur->next->next = prev; prev = cur; } //In line { ClaNode *cur = InitCla(); cur->next = InitCla(); cla_count += 2; for (int k = 0; k < count; k++) AddToCla(cur, arrange[k] * size + i + 1); for (int k = 0; k < count; k++) AddToCla(cur->next, (arrange[k] * size + i + 1) * -1); cur->next->next = prev; prev = cur; } //Assume that in this cycle, we would reach final arrange final_reach = true; for (int j = count - 1; j >= 0; j--) { if (arrange[j] != size + j - count) { arrange[j]++; //Move latter numbers to set a sub-initial status //when non-latest number got moved for (int k = j + 1; k < count; k++) arrange[k] = arrange[j] + k - j; //Any adjustment means we haven't reached final arrange final_reach = false; break; } } } while (!final_reach); //Terminate when reached final arrange } return prev; } ClaNode *TseytinAddInRow(int i, int j, int size, ClaNode *head) { ClaNode *prev = head; //Positive Group for (int k = 0; k < size; k++) { var_count++; for (int l = 0; l < 3; l++) { ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; switch (l) { case 0: { AddToCla(cur, i * size + k + 1); AddToCla(cur, var_count * -1); break; } case 1: { AddToCla(cur, j * size + k + 1); AddToCla(cur, var_count * -1); break; } case 2: { AddToCla(cur, (i * size + k + 1) * -1); AddToCla(cur, (j * size + k + 1) * -1); AddToCla(cur, var_count); break; } } } } //Negative Group for (int k = 0; k < size; k++) { var_count++; for (int l = 0; l < 3; l++) { ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; switch (l) { case 0: { AddToCla(cur, (i * size + k + 1) * -1); AddToCla(cur, var_count * -1); break; } case 1: { AddToCla(cur, (j * size + k + 1) * -1); AddToCla(cur, var_count * -1); break; } case 2: { AddToCla(cur, i * size + k + 1); AddToCla(cur, j * size + k + 1); AddToCla(cur, var_count); break; } } } } //OR for both groups above for (int k = 0; k < size; k++) { var_count++; for (int l = 0; l < 3; l++) { ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; switch (l) { case 0: { AddToCla(cur, (var_count - size) * -1); AddToCla(cur, var_count); break; } case 1: { AddToCla(cur, (var_count - 2 * size) * -1); AddToCla(cur, var_count); break; } case 2: { AddToCla(cur, var_count - size); AddToCla(cur, var_count - 2 * size); AddToCla(cur, var_count * -1); break; } } } } //Final AND var_count++; ClaNode *final = InitCla(); cla_count++; final->next = prev; prev = final; AddToCla(final, var_count * -1); for (int k = 0; k < size; k++) { ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; AddToCla(final, (var_count - k - 1) * -1); AddToCla(cur, var_count - k - 1); AddToCla(cur, var_count); } ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; AddToCla(cur, var_count); return prev; } ClaNode *TseytinAddInLine(int i, int j, int size, ClaNode *head) { ClaNode *prev = head; //Positive Group for (int k = 0; k < size; k++) { var_count++; for (int l = 0; l < 3; l++) { ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; switch (l) { case 0: { AddToCla(cur, k * size + i + 1); AddToCla(cur, var_count * -1); break; } case 1: { AddToCla(cur, k * size + j + 1); AddToCla(cur, var_count * -1); break; } case 2: { AddToCla(cur, (k * size + i + 1) * -1); AddToCla(cur, (k * size + j + 1) * -1); AddToCla(cur, var_count); break; } } } } //Negative Group for (int k = 0; k < size; k++) { var_count++; for (int l = 0; l < 3; l++) { ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; switch (l) { case 0: { AddToCla(cur, (k * size + i + 1) * -1); AddToCla(cur, var_count * -1); break; } case 1: { AddToCla(cur, (k * size + j + 1) * -1); AddToCla(cur, var_count * -1); break; } case 2: { AddToCla(cur, k * size + i + 1); AddToCla(cur, k * size + j + 1); AddToCla(cur, var_count); break; } } } } //OR for both groups above for (int k = 0; k < size; k++) { var_count++; for (int l = 0; l < 3; l++) { ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; switch (l) { case 0: { AddToCla(cur, (var_count - size) * -1); AddToCla(cur, var_count); break; } case 1: { AddToCla(cur, (var_count - 2 * size) * -1); AddToCla(cur, var_count); break; } case 2: { AddToCla(cur, var_count - size); AddToCla(cur, var_count - 2 * size); AddToCla(cur, var_count * -1); break; } } } } //Final AND var_count++; ClaNode *final = InitCla(); cla_count++; final->next = prev; prev = final; AddToCla(final, var_count * -1); for (int k = 0; k < size; k++) { ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; AddToCla(final, (var_count - k - 1) * -1); AddToCla(cur, var_count - k - 1); AddToCla(cur, var_count); } //Ensure the condition satisfies ClaNode *cur = InitCla(); cla_count++; cur->next = prev; prev = cur; AddToCla(cur, var_count); return prev; } ClaNode *SameArrangeAvoid(int size, ClaNode *head) { //Using Tseytin Transformation ClaNode *prev = head; ClaNode *cur = NULL; for (int i = 0; i < size - 1; i++) for (int j = i + 1; j < size; j++) { cur = TseytinAddInRow(i, j, size, prev); prev = cur; } for (int i = 0; i < size - 1; i++) for (int j = i + 1; j < size; j++) { cur = TseytinAddInLine(j, i, size, prev); prev = cur; } return prev; } int FindSingleCla(ClaNode *head) { ClaNode *cur = head; while (cur) { if (cur->len == 1) return cur->data[0]; cur = cur->next; } return 0; } ClaNode *ConvertBoard(board *b) { if (!b) return NULL; var_count = b->size * b->size; cla_count = 0; ClaNode *head = SameArrangeAvoid(b->size, NULL); head = HalfVar(b->size, head); head = TripletAvoid(b->size, head); ClaNode *prev = head; ClaNode *cur = NULL; for (int i = 0; i < b->size; i++) for (int j = 0; j < b->size; j++) if (b->data[i][j] != 0) { cur = InitCla(); cur->next = prev; if (b->data[i][j] > 0) AddToCla(cur, i * b->size + j + 1); else AddToCla(cur, (i * b->size + j + 1) * -1); prev = cur; } return prev; } #endif
2.53125
3
2024-11-18T22:11:38.802240+00:00
2023-08-27T19:18:57
38abf5bb9b16712e8a2a38c430f5505af88fe975
{ "blob_id": "38abf5bb9b16712e8a2a38c430f5505af88fe975", "branch_name": "refs/heads/master", "committer_date": "2023-08-27T19:18:57", "content_id": "c9f13ebe35e51a957d1a86a676bfcdb89f5e1a43", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "76f7459a09acb9be2d52407132f5ff8955627da2", "extension": "h", "filename": "f2c_types_win.h", "fork_events_count": 361, "gha_created_at": "2014-01-22T15:58:24", "gha_event_created_at": "2023-08-27T19:18:58", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 16143904, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2360, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/blastest/f2c/f2c_types_win.h", "provenance": "stackv2-0087.json.gz:5438", "repo_name": "flame/blis", "revision_date": "2023-08-27T19:18:57", "revision_id": "6dcf7666eff14348e82fbc2750be4b199321e1b9", "snapshot_id": "448bc0ad139b726188129c5627c304274b41c3c1", "src_encoding": "UTF-8", "star_events_count": 1696, "url": "https://raw.githubusercontent.com/flame/blis/6dcf7666eff14348e82fbc2750be4b199321e1b9/blastest/f2c/f2c_types_win.h", "visit_date": "2023-09-01T14:56:11.920485" }
stackv2
/* include/f2c.h. Generated from f2c.h.in by configure. */ /* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_TYPES_WIN_H #define F2C_TYPES_WIN_H #ifdef __cplusplus extern "C" { #endif /* Define to the number of bits in an integer */ #define F2C_INT_BITS 32 /* Define to the number of bits in a long integer */ #define F2C_LONG_BITS 64 typedef int integer; typedef unsigned int uinteger; typedef __int64 longint; typedef unsigned __int64 ulongint; /*#define INTEGER_STAR_8*/ typedef char integer1; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; typedef integer logical; typedef shortint shortlogical; typedef integer1 logical1; #ifdef f2c_i2 /* for -i2 */ typedef short flag; typedef short ftnlen; typedef short ftnint; #else typedef integer flag; typedef integer ftnlen; typedef integer ftnint; #endif /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef int /* Unknown procedure type */ (*U_fp)(...); typedef shortint (*J_fp)(...); typedef integer (*I_fp)(...); typedef real (*R_fp)(...); typedef doublereal (*D_fp)(...), (*E_fp)(...); typedef /* Complex */ void (*C_fp)(...); typedef /* Double Complex */ void (*Z_fp)(...); typedef logical (*L_fp)(...); typedef shortlogical (*K_fp)(...); typedef /* Character */ void (*H_fp)(...); typedef /* Subroutine */ int (*S_fp)(...); #else typedef int /* Unknown procedure type */ (*U_fp)(); typedef shortint (*J_fp)(); typedef integer (*I_fp)(); typedef real (*R_fp)(); typedef doublereal (*D_fp)(), (*E_fp)(); typedef /* Complex */ void (*C_fp)(); typedef /* Double Complex */ void (*Z_fp)(); typedef logical (*L_fp)(); typedef shortlogical (*K_fp)(); typedef /* Character */ void (*H_fp)(); typedef /* Subroutine */ int (*S_fp)(); #endif /* E_fp is for real functions when -R is not specified */ typedef void C_f; /* complex function */ typedef void H_f; /* character function */ typedef void Z_f; /* double complex function */ typedef doublereal E_f; /* real function with -R not specified */ #ifdef __cplusplus } #endif #endif /* F2C_TYPES_H */
2.140625
2
2024-11-18T22:11:38.998751+00:00
2021-08-18T02:38:08
0ddd9625f4d1b496112a514878db73bfed423af3
{ "blob_id": "0ddd9625f4d1b496112a514878db73bfed423af3", "branch_name": "refs/heads/master", "committer_date": "2021-08-18T02:38:08", "content_id": "b9b908978e476b06928d9e2f8a6b4804eb05b585", "detected_licenses": [ "Apache-2.0", "curl" ], "directory_id": "11ddbb17eebddb29a4dbd2e89cf1e403a4e5942d", "extension": "c", "filename": "test_v1beta2_rolling_update_stateful_set_strategy.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2606, "license": "Apache-2.0,curl", "license_type": "permissive", "path": "/kubernetes/unit-test/test_v1beta2_rolling_update_stateful_set_strategy.c", "provenance": "stackv2-0087.json.gz:5827", "repo_name": "duokuiwang/c", "revision_date": "2021-08-18T02:38:08", "revision_id": "3cb0df06851a369e9b7062cb533ecf6b766e4130", "snapshot_id": "86494f7ace5992f9402e4374e22eb5f6f67de984", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/duokuiwang/c/3cb0df06851a369e9b7062cb533ecf6b766e4130/kubernetes/unit-test/test_v1beta2_rolling_update_stateful_set_strategy.c", "visit_date": "2023-07-09T10:23:06.946203" }
stackv2
#ifndef v1beta2_rolling_update_stateful_set_strategy_TEST #define v1beta2_rolling_update_stateful_set_strategy_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define v1beta2_rolling_update_stateful_set_strategy_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/v1beta2_rolling_update_stateful_set_strategy.h" v1beta2_rolling_update_stateful_set_strategy_t* instantiate_v1beta2_rolling_update_stateful_set_strategy(int include_optional); v1beta2_rolling_update_stateful_set_strategy_t* instantiate_v1beta2_rolling_update_stateful_set_strategy(int include_optional) { v1beta2_rolling_update_stateful_set_strategy_t* v1beta2_rolling_update_stateful_set_strategy = NULL; if (include_optional) { v1beta2_rolling_update_stateful_set_strategy = v1beta2_rolling_update_stateful_set_strategy_create( 56 ); } else { v1beta2_rolling_update_stateful_set_strategy = v1beta2_rolling_update_stateful_set_strategy_create( 56 ); } return v1beta2_rolling_update_stateful_set_strategy; } #ifdef v1beta2_rolling_update_stateful_set_strategy_MAIN void test_v1beta2_rolling_update_stateful_set_strategy(int include_optional) { v1beta2_rolling_update_stateful_set_strategy_t* v1beta2_rolling_update_stateful_set_strategy_1 = instantiate_v1beta2_rolling_update_stateful_set_strategy(include_optional); cJSON* jsonv1beta2_rolling_update_stateful_set_strategy_1 = v1beta2_rolling_update_stateful_set_strategy_convertToJSON(v1beta2_rolling_update_stateful_set_strategy_1); printf("v1beta2_rolling_update_stateful_set_strategy :\n%s\n", cJSON_Print(jsonv1beta2_rolling_update_stateful_set_strategy_1)); v1beta2_rolling_update_stateful_set_strategy_t* v1beta2_rolling_update_stateful_set_strategy_2 = v1beta2_rolling_update_stateful_set_strategy_parseFromJSON(jsonv1beta2_rolling_update_stateful_set_strategy_1); cJSON* jsonv1beta2_rolling_update_stateful_set_strategy_2 = v1beta2_rolling_update_stateful_set_strategy_convertToJSON(v1beta2_rolling_update_stateful_set_strategy_2); printf("repeating v1beta2_rolling_update_stateful_set_strategy:\n%s\n", cJSON_Print(jsonv1beta2_rolling_update_stateful_set_strategy_2)); } int main() { test_v1beta2_rolling_update_stateful_set_strategy(1); test_v1beta2_rolling_update_stateful_set_strategy(0); printf("Hello world \n"); return 0; } #endif // v1beta2_rolling_update_stateful_set_strategy_MAIN #endif // v1beta2_rolling_update_stateful_set_strategy_TEST
2.515625
3
2024-11-18T22:11:39.065928+00:00
2023-08-08T09:39:15
2fa884ffee01b970ee976be8fbf5ce616ff8a739
{ "blob_id": "2fa884ffee01b970ee976be8fbf5ce616ff8a739", "branch_name": "refs/heads/master", "committer_date": "2023-08-08T09:39:15", "content_id": "6061e65f1f44d162fbc0f8294621304d36e876f6", "detected_licenses": [ "ISC" ], "directory_id": "f8cc1dd4b1378490386def2e0571561fab10b275", "extension": "c", "filename": "socket_connect4_u32.c", "fork_events_count": 32, "gha_created_at": "2015-02-28T12:01:41", "gha_event_created_at": "2021-04-11T10:10:54", "gha_language": "C", "gha_license_id": "ISC", "github_id": 31461366, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 230, "license": "ISC", "license_type": "permissive", "path": "/src/libstddjb/socket_connect4_u32.c", "provenance": "stackv2-0087.json.gz:5955", "repo_name": "skarnet/skalibs", "revision_date": "2023-08-08T09:39:15", "revision_id": "1f2d5f95684e93f8523e369ef1fed7a75c444082", "snapshot_id": "b1eb2a0e38663cbfa918ee0a7916f56227bd7c2d", "src_encoding": "UTF-8", "star_events_count": 104, "url": "https://raw.githubusercontent.com/skarnet/skalibs/1f2d5f95684e93f8523e369ef1fed7a75c444082/src/libstddjb/socket_connect4_u32.c", "visit_date": "2023-08-23T07:33:20.996016" }
stackv2
/* ISC license. */ #include <skalibs/uint32.h> #include <skalibs/socket.h> int socket_connect4_u32 (int s, uint32_t ip, uint16_t port) { char pack[4] ; uint32_pack_big(pack, ip) ; return socket_connect4(s, pack, port) ; }
2.109375
2
2024-11-18T22:11:39.158076+00:00
2018-04-17T16:48:46
e741e202e1c49129e5f21b41297833bd9cf39fa7
{ "blob_id": "e741e202e1c49129e5f21b41297833bd9cf39fa7", "branch_name": "refs/heads/haiku", "committer_date": "2018-04-17T16:48:46", "content_id": "44aded450c615978f5b000d58ac2a32c4246739a", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "7ec5d6bdb52c2693af01686bc8678d951d06429e", "extension": "c", "filename": "vcache.c", "fork_events_count": 6, "gha_created_at": "2017-02-15T22:01:51", "gha_event_created_at": "2023-09-09T16:13:53", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 82111290, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8890, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/add-ons/dosfs/vcache.c", "provenance": "stackv2-0087.json.gz:6083", "repo_name": "HaikuArchives/BeSampleCode", "revision_date": "2018-04-17T16:48:46", "revision_id": "ca5a319fecf425a69e944f3c928a85011563a932", "snapshot_id": "c3787cc3a5b8134cc73fb0b5428a6276ed3f7e46", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/HaikuArchives/BeSampleCode/ca5a319fecf425a69e944f3c928a85011563a932/add-ons/dosfs/vcache.c", "visit_date": "2021-09-12T14:36:35.392130" }
stackv2
/* Copyright 1999, Be Incorporated. All Rights Reserved. This file may be used under the terms of the Be Sample Code License. */ /* The FAT file system has no good way of assigning unique persistent values to nodes. The only obvious choice, storing the starting cluster number of the file, is unusable because 0 byte files exist as directory entries only. Further, even if it were usable, it would potentially require a full directory tree traversal to locate an arbitrary node. We must resort to some ickiness in order to make persistent vnode id's (at least across a given mount) work. There are three ways to encode a vnode id: 1. Combine the starting cluster of the entry with the starting cluster of the directory it appears in. This is used for files with data. 2. Combine the starting cluster of the directory the entry appears in with the index of the entry in the directory. This is used for 0-byte files. 3. A unique number that doesn't match any possible values from encodings 1 or 2. With the first encoding, the vnode id is invalidated (i.e. no longer describes the file's location) when the file moves to a different directory or when its starting cluster changes (this can occur if the file is truncated and data is subsequently written to it). With the second encoding, the vnode id is invalidated when the file position is moved within a directory (as a result of a renaming), when it's moved to a different directory, or when data is written to it. The third encoding doesn't describe the file's location on disk, and so it is invalid from the start. Since we can't change vnode id's once they are assigned, we have to create a mapping table to translate vnode id's to locations. This file serves this purpose. */ #define DPRINTF(a,b) if (debug_vcache > (a)) dprintf b #define LOCK_CACHE_R \ acquire_sem(vol->vcache.vc_sem) #define LOCK_CACHE_W \ acquire_sem_etc(vol->vcache.vc_sem, READERS, 0, 0) #define UNLOCK_CACHE_R \ release_sem(vol->vcache.vc_sem) #define UNLOCK_CACHE_W \ release_sem_etc(vol->vcache.vc_sem, READERS, 0) #include <fsproto.h> #include <KernelExport.h> #include <stdio.h> #include <string.h> #include "dosfs.h" #include "vcache.h" #include "util.h" struct vcache_entry { vnode_id vnid; /* originally reported vnid */ vnode_id loc; /* where the file is now */ struct vcache_entry *next_vnid; /* next entry in vnid hash table */ struct vcache_entry *next_loc; /* next entry in location hash table */ }; void dump_vcache(nspace *vol) { int i; struct vcache_entry *c; dprintf("vnid cache size %lx, cur vnid = %Lx\n" "vnid loc\n", vol->vcache.cache_size, vol->vcache.cur_vnid); for (i=0;i<vol->vcache.cache_size;i++) for (c = vol->vcache.by_vnid[i];c;c=c->next_vnid) dprintf("%16Lx %16Lx\n", c->vnid, c->loc); } #define hash(v) ((v) & (vol->vcache.cache_size-1)) status_t init_vcache(nspace *vol) { char name[16]; DPRINTF(0, ("init_vcache called\n")); vol->vcache.cur_vnid = ARTIFICIAL_VNID_BITS; #ifdef DEBUG vol->vcache.cache_size = 4; #else vol->vcache.cache_size = 512; /* must be power of 2 */ #endif vol->vcache.by_vnid = calloc(sizeof(struct vache_entry *), vol->vcache.cache_size); if (vol->vcache.by_vnid == NULL) { dprintf("init_vcache: out of core\n"); return ENOMEM; } vol->vcache.by_loc = calloc(sizeof(struct vache_entry *), vol->vcache.cache_size); if (vol->vcache.by_loc == NULL) { dprintf("init_vcache: out of core\n"); free(vol->vcache.by_vnid); vol->vcache.by_vnid = NULL; return ENOMEM; } sprintf(name, "fat cache %lx", vol->id); if ((vol->vcache.vc_sem = create_sem(READERS, name)) < 0) { free(vol->vcache.by_vnid); vol->vcache.by_vnid = NULL; free(vol->vcache.by_loc); vol->vcache.by_loc = NULL; return vol->vcache.vc_sem; } DPRINTF(0, ("init_vcache: initialized vnid cache with %lx entries\n", vol->vcache.cache_size)); return 0; } status_t uninit_vcache(nspace *vol) { int i, count = 0; struct vcache_entry *c, *n; DPRINTF(0, ("uninit_vcache called\n")); LOCK_CACHE_W; /* free entries */ for (i=0;i<vol->vcache.cache_size;i++) { c = vol->vcache.by_vnid[i]; while (c) { count++; n = c->next_vnid; free(c); c = n; } } DPRINTF(0, ("%x vcache entries removed\n", count)); free(vol->vcache.by_vnid); vol->vcache.by_vnid = NULL; free(vol->vcache.by_loc); vol->vcache.by_loc = NULL; delete_sem(vol->vcache.vc_sem); return 0; } vnode_id generate_unique_vnid(nspace *vol) { DPRINTF(0, ("generate_unique_vnid\n")); /* only one thread per volume will be in here at any given time anyway * due to volume locking */ return vol->vcache.cur_vnid++; } static status_t _add_to_vcache_(nspace *vol, vnode_id vnid, vnode_id loc) { int hash1 = hash(vnid), hash2 = hash(loc); struct vcache_entry *e, *c, *p; DPRINTF(0, ("add_to_vcache %Lx/%Lx\n", vnid, loc)); ASSERT(vnid != loc); e = malloc(sizeof(struct vcache_entry)); if (e == NULL) return ENOMEM; e->vnid = vnid; e->loc = loc; e->next_vnid = NULL; e->next_loc = NULL; c = p = vol->vcache.by_vnid[hash1]; while (c) { if (vnid < c->vnid) break; ASSERT((vnid != c->vnid) && (loc != c->loc)); p = c; c = c->next_vnid; } ASSERT(!c || (vnid != c->vnid)); e->next_vnid = c; if (p == c) vol->vcache.by_vnid[hash1] = e; else p->next_vnid = e; c = p = vol->vcache.by_loc[hash2]; while (c) { if (loc < c->loc) break; ASSERT((vnid != c->vnid) && (loc != c->loc)); p = c; c = c->next_loc; } ASSERT(!c || (loc != c->loc)); e->next_loc = c; if (p == c) vol->vcache.by_loc[hash2] = e; else p->next_loc = e; return B_OK; } static status_t _remove_from_vcache_(nspace *vol, vnode_id vnid, char check_integrity) { int hash1 = hash(vnid), hash2; struct vcache_entry *c, *p, *e; DPRINTF(0, ("remove_from_vcache %Lx\n", vnid)); c = p = vol->vcache.by_vnid[hash1]; while (c) { if (vnid == c->vnid) break; ASSERT(c->vnid < vnid); p = c; c = c->next_vnid; } ASSERT(c); if (!c) return ENOENT; if (p == c) vol->vcache.by_vnid[hash1] = c->next_vnid; else p->next_vnid = c->next_vnid; e = c; hash2 = hash(c->loc); c = p = vol->vcache.by_loc[hash2]; while (c) { if (vnid == c->vnid) break; if (check_integrity) ASSERT(c->loc < e->loc); p = c; c = c->next_loc; } ASSERT(c); if (!c) return ENOENT; if (p == c) vol->vcache.by_loc[hash2] = c->next_loc; else p->next_loc = c->next_loc; free(c); return 0; } static struct vcache_entry *_find_vnid_in_vcache_(nspace *vol, vnode_id vnid) { int hash1 = hash(vnid); struct vcache_entry *c; c = vol->vcache.by_vnid[hash1]; while (c) { if (c->vnid == vnid) break; if (c->vnid > vnid) return NULL; c = c->next_vnid; } return c; } static struct vcache_entry *_find_loc_in_vcache_(nspace *vol, vnode_id loc) { int hash2 = hash(loc); struct vcache_entry *c; c = vol->vcache.by_loc[hash2]; while (c) { if (c->loc == loc) break; if (c->loc > loc) return NULL; c = c->next_loc; } return c; } status_t add_to_vcache(nspace *vol, vnode_id vnid, vnode_id loc) { status_t result; LOCK_CACHE_W; result = _add_to_vcache_(vol,vnid,loc); UNLOCK_CACHE_W; if (result < 0) DPRINTF(0, ("add_to_vcache failed (%s)\n", strerror(result))); return result; } /* XXX: do this in a smarter fashion */ static status_t _update_loc_in_vcache_(nspace *vol, vnode_id vnid, vnode_id loc) { status_t result; result = _remove_from_vcache_(vol, vnid, 0); if (result == 0) result = _add_to_vcache_(vol, vnid, loc); return result; } status_t remove_from_vcache(nspace *vol, vnode_id vnid) { status_t result; LOCK_CACHE_W; result = _remove_from_vcache_(vol,vnid,1); UNLOCK_CACHE_W; if (result < 0) DPRINTF(0, ("remove_from_vcache failed (%s)\n", strerror(result))); return result; } status_t vcache_vnid_to_loc(nspace *vol, vnode_id vnid, vnode_id *loc) { struct vcache_entry *e; DPRINTF(1, ("vcache_vnid_to_loc %Lx %lx\n", vnid, (uint32)loc)); LOCK_CACHE_R; e = _find_vnid_in_vcache_(vol, vnid); if (loc && e) *loc = e->loc; UNLOCK_CACHE_R; return (e) ? B_OK : ENOENT; } status_t vcache_loc_to_vnid(nspace *vol, vnode_id loc, vnode_id *vnid) { struct vcache_entry *e; DPRINTF(1, ("vcache_loc_to_vnid %Lx %lx\n", loc, (uint32)vnid)); LOCK_CACHE_R; e = _find_loc_in_vcache_(vol, loc); if (vnid && e) *vnid = e->vnid; UNLOCK_CACHE_R; return (e) ? B_OK : ENOENT; } status_t vcache_set_entry(nspace *vol, vnode_id vnid, vnode_id loc) { struct vcache_entry *e; status_t result = B_OK; DPRINTF(0, ("vcache_set_entry: %Lx -> %Lx\n", vnid, loc)); LOCK_CACHE_W; e = _find_vnid_in_vcache_(vol, vnid); if (e) { if (e->vnid == loc) result = _remove_from_vcache_(vol, vnid,1); else result = _update_loc_in_vcache_(vol, vnid, loc); } else { if (vnid != loc) result = _add_to_vcache_(vol,vnid,loc); } UNLOCK_CACHE_W; return result; }
2.421875
2
2024-11-18T22:11:39.339583+00:00
2019-03-28T17:28:56
e6159fb64fc8e32adbf59eacfad34ecf0eec0978
{ "blob_id": "e6159fb64fc8e32adbf59eacfad34ecf0eec0978", "branch_name": "refs/heads/jumpstart-php", "committer_date": "2019-03-28T17:28:56", "content_id": "4a8cff5b886118ea465048fbbd8b8c26a577ac2b", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "24d856d98c85a319d53be2768ccc176a50873fa3", "extension": "c", "filename": "parseulog.c", "fork_events_count": 2, "gha_created_at": "2019-08-03T17:57:58", "gha_event_created_at": "2019-08-03T19:45:44", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 200405626, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3622, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/test/parseulog.c", "provenance": "stackv2-0087.json.gz:6340", "repo_name": "dozenow/shortcut", "revision_date": "2019-03-28T17:28:56", "revision_id": "b140082a44c58f05af3495259c1beaaa9a63560b", "snapshot_id": "a4803b59c95e72a01d73bb30acaae45cf76b0367", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/dozenow/shortcut/b140082a44c58f05af3495259c1beaaa9a63560b/test/parseulog.c", "visit_date": "2020-06-29T11:41:05.842760" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #define __user #include "../linux-lts-quantal-3.5.0/include/linux/pthread_log.h" int main (int argc, char* argv[]) { int fd, rc; struct stat st; int bytes_read = 0; #ifndef USE_DEBUG_LOG u_long total_clock = 0; int new_errno; #endif if (argc < 2) { printf ("Format: parseulog <log file>\n"); exit (0); } rc = stat(argv[1], &st); if (rc < 0) { fprintf(stderr, "stat of %s failed with %d\n", argv[1], rc); perror("stat failed\n"); return rc; } fd = open (argv[1], O_RDONLY); if (fd < 0) { perror ("open log file\n"); return fd; } while (bytes_read < st.st_size) { if (bytes_read > st.st_size) { perror("bytes_read > st.st_size ???\n"); } // mcc: Each user log segment now contains the number of entries before the entries int count = 0; int num_bytes; rc = read (fd, &num_bytes, sizeof(int)); if (rc != sizeof(int)) { perror("Could not read the count\n"); return -1; } printf ("** reading %d bytes ***\n", num_bytes); bytes_read += rc; while (count < num_bytes) { #ifdef USE_DEBUG_LOG struct pthread_log_data rec; rc = read (fd, &rec, sizeof(struct pthread_log_data)); if (rc < 0) { perror ("read log record\n"); return rc; } printf ("clock %lu type %lu check %lx retval %d (%x)\n", rec.clock, rec.type, rec.check, rec.retval, rec.retval); count += rc; bytes_read += rc; #else u_long entry; long i; int skip, retval, fake_calls; rc = read (fd, &entry, sizeof(u_long)); if (rc != sizeof(u_long)) { perror ("read log record\n"); return rc; } count += rc; bytes_read += rc; printf (" entry %lx usual recs %ld non-zero retval? %d errno change? %d fake calls? %d skip? %d\n", entry, (entry&CLOCK_MASK), !!(entry&NONZERO_RETVAL_FLAG), !!(entry&ERRNO_CHANGE_FLAG), !!(entry&FAKE_CALLS_FLAG), !!(entry&SKIPPED_CLOCK_FLAG)); for (i = 0; i < (entry&CLOCK_MASK); i++) { total_clock++; printf ("clock %lu fake calls 0 retval 0\n", total_clock-1); } if (entry&SKIPPED_CLOCK_FLAG) { rc = read (fd, &skip, sizeof(int)); if (rc != sizeof(int)) { perror ("read skip value\n"); return rc; } printf (" skip %d records\n", skip); count += rc; bytes_read += rc; total_clock += skip + 1; } else { total_clock++; } if (entry&NONZERO_RETVAL_FLAG) { rc = read (fd, &retval, sizeof(int)); if (rc != sizeof(int)) { perror ("read retval value\n"); return rc; } count += rc; bytes_read += rc; } else { retval = 0; } if (entry&ERRNO_CHANGE_FLAG) { rc = read (fd, &new_errno, sizeof(int)); if (rc != sizeof(int)) { perror ("read retval value\n"); return rc; } count += rc; bytes_read += rc; } else { retval = 0; } if (entry&FAKE_CALLS_FLAG) { rc = read (fd, &fake_calls, sizeof(int)); if (rc != sizeof(int)) { perror ("read fake calls value\n"); return rc; } count += rc; bytes_read += rc; } else { fake_calls = 0; } if (entry&(SKIPPED_CLOCK_FLAG|NONZERO_RETVAL_FLAG|FAKE_CALLS_FLAG|ERRNO_CHANGE_FLAG)) { printf ("clock %lu fake calls %d retval %d \n", total_clock-1, fake_calls, retval); } #endif } } close (fd); return 0; }
2.28125
2
2024-11-18T22:11:39.606806+00:00
2020-01-30T15:52:16
0e9ea8563e855fafe13b4c0e3b4ff6e1e70b6257
{ "blob_id": "0e9ea8563e855fafe13b4c0e3b4ff6e1e70b6257", "branch_name": "refs/heads/master", "committer_date": "2020-01-30T15:52:16", "content_id": "6a6e067e13c5d798356fcaa19958405092af6cf0", "detected_licenses": [ "MIT" ], "directory_id": "40de3da30239862f11a946166b50438174c2fd4e", "extension": "c", "filename": "bak.nghost.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 237240459, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4208, "license": "MIT", "license_type": "permissive", "path": "/lib/wizards/neophyte/city/monst/bak.nghost.c", "provenance": "stackv2-0087.json.gz:6599", "repo_name": "vlehtola/questmud", "revision_date": "2020-01-30T15:52:16", "revision_id": "8bc3099b5ad00a9e0261faeb6637c76b521b6dbe", "snapshot_id": "f53b7205351f30e846110300d60b639d52d113f8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vlehtola/questmud/8bc3099b5ad00a9e0261faeb6637c76b521b6dbe/lib/wizards/neophyte/city/monst/bak.nghost.c", "visit_date": "2020-12-23T19:59:44.886028" }
stackv2
inherit "obj/monster"; int helpers; int phase; object torso,gloves,legs,paper1,paper2,paper3; reset(arg) { ::reset(arg); if (arg) { return; phase = 0; helpers = 0; } set_level(76+random(4)); set_name("ghost"); set_alias("navigator_ghost"); set_short("A enourmous ghost of navigators"); set_long("The ghost don't look like a normal ghost, more like"+ "lots of ghost are binded together. It has everglowing\n"+ "bright eye sockets.\n"); set_al(-100); set_undead(1); set_aggressive(1); set_special(10); set_extra(1); set_log(); set_dead_ob(this_object()); set_str(query_str()+100); torso = clone_object("/wizards/neophyte/city/eq/torso.c"); move_object(torso, this_object()); init_command("wear mail"); gloves = clone_object("/wizards/neophyte/city/eq/gloves.c"); move_object(gloves, this_object()); init_command("wear gloves"); legs = clone_object("/wizards/neophyte/city/eq/legs.c"); move_object(legs, this_object()); init_command("wear leggings"); /* paper1 = clone_object("/wizards/neophyte/city/eq/paper1"); move_object(paper1,this_object()); paper2 = clone_object("/wizards/neophyte/city/eq/paper1"); move_object(paper2,this_object()); paper3 = clone_object("/wizards/neophyte/city/eq/paper1"); move_object(paper3,this_object()); */ } catch_tell(str) { string who; if(sscanf(str, "%s is DEAD, R.I.P.", who) == 1) { if(who != "Ghost") { tell_room(environment(this_object()), "The ghost looks much more healthier as "+who+" dies.\n"); this_object()->heal_self(15000); return 1; } } } extra() { int i; if(phase == 4) { return 1; } /* phase = get_phase(this_object()->query_hp()*100 / this_object()->query_max_hp()); */ tell_room(environment(this_object()),"THE GHOST PHASE IS NOW "+phase+".\n"); i = phase*10; set_special(10+i); } get_phase(int i) { switch(i) { case 0..25: return 4; case 26.. 40: return 3; case 41..54: return 2; case 55..85: return 1; } return 0; } special_move() { object ob; ob = this_object()->query_attacker(); if(phase == 0) { move_object(ob, "/wizards/neophyte/city/lighthouse/corridor16"); tell_object(ob, "The ghost pushes you out of the room.\n"); init_command("close door"); return 1; } if(phase == 1) { helper(); return 1; } if(phase == 2) { hp_leech(); return 1; } if(phase == 3) { move_phase(); return 1; } if(phase ==4) { if(!random(2)) { hp_leech(); } if(!random(5)) { helper(); return 1; } } } helper() { object ghost; if(helpers < 3) { ghost = clone_object("/wizards/neophyte/city/monst/ghost"); move_object(ghost,environment(this_object())); tell_room(environment(this_object()), "The ghost yells loudly 'ASHOHIA' and a minor ghost appears from shadows.\n"); helpers += 1; return 1; } } hp_leech() { object *ob, leechob; int x,xx; ob = all_inventory(this_object()); for(x=0;x<sizeof(ob);x++) { if(living(ob[x])) { xx = random(x); if(!ob[xx]->query_hp_leech()) { leechob = clone_object("/wizards/neophyte/city/obj/leechob"); leechob->start(ob[xx],random(120)); tell_object(ob[xx], "The ghost starts to leech you!\n"); say("The ghost starts to leech "+ob[xx]->query_name()+"!\n",ob[xx]); return 1; } } } } move_phase() { object portal; tell_room(environment(this_object()), "The ghost chants magical words and suddenly a portal appears from nowhere.\n"); tell_room(environment(this_object()), "The ghost steps in the portal and it is gone.\n"); portal = clone_object("/wizards/neophyte/city/obj/portal"); move_object(portal,environment(this_object())); move_object(this_object(), "/wizards/neophyte/city/void"); phase = 4; return 1; } reduce_number() { helpers -= 1; } hit_with_spell(int damage, arg2,arg3,arg4,arg5,arg6) { object ob; ob = present("ghost", environment(this_object())); if(ob) { tell_room(environment(this_object()), "But smaller ghost steps front of the enormous ghost and spell hits smaller one.\n"); ob->hit_with_spell(damage, arg2,arg3,arg4,arg5,arg6); return 1; } } query_phase() { return phase; } set_phase(int i) { phase=i; } query_helper() { return helpers; }
2.09375
2
2024-11-18T22:11:39.834036+00:00
2018-09-15T02:37:48
c822af88940b8603b91b21a18c4bde053219842f
{ "blob_id": "c822af88940b8603b91b21a18c4bde053219842f", "branch_name": "refs/heads/master", "committer_date": "2018-09-15T02:37:48", "content_id": "de20e2760c09a8471b2680636b9697b139c6a42f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e77a179ba52e178051854e8cb23095d05729095a", "extension": "c", "filename": "716-2_ka_1-3.c", "fork_events_count": 0, "gha_created_at": "2018-09-14T21:46:31", "gha_event_created_at": "2018-09-15T02:37:48", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 148844952, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 146, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/716-2_ka_1-3.c", "provenance": "stackv2-0087.json.gz:6988", "repo_name": "716-2ka/timp-716-2_ka", "revision_date": "2018-09-15T02:37:48", "revision_id": "2a53e4ae3b1e7a1784aa7a25b3b22185ef8bd302", "snapshot_id": "1419775c97a10dc56b5c5f2be5f86fe71d2570ef", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/716-2ka/timp-716-2_ka/2a53e4ae3b1e7a1784aa7a25b3b22185ef8bd302/716-2_ka_1-3.c", "visit_date": "2020-03-28T18:01:02.647879" }
stackv2
#include <stdio.h> #include <math.h> void main () { double x,y; scanf ("%lf%lf", &x, &y); double result=pow(x,y); printf ("%lf\n", result); }
2.21875
2
2024-11-18T22:11:39.895723+00:00
2020-03-27T20:11:33
2cfe32e4b8ad02dc1e0138d0e6aa8ce3ed05721d
{ "blob_id": "2cfe32e4b8ad02dc1e0138d0e6aa8ce3ed05721d", "branch_name": "refs/heads/master", "committer_date": "2020-03-27T20:11:33", "content_id": "ad80ef14025b65cf31a7d432125034860acd0b0f", "detected_licenses": [ "MIT" ], "directory_id": "83f46917f0f8647a9a201823f2ab769f8b8443c3", "extension": "c", "filename": "2switchMONTH.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 250632785, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 781, "license": "MIT", "license_type": "permissive", "path": "/C source codes/Assignment4/2switchMONTH.c", "provenance": "stackv2-0087.json.gz:7116", "repo_name": "HEXcube/BTechLabs", "revision_date": "2020-03-27T20:11:33", "revision_id": "ddc274b584782eace936efea96f71c50dfbd5d78", "snapshot_id": "315eb8194e470fb902493d11d044c1fa19e6de1c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/HEXcube/BTechLabs/ddc274b584782eace936efea96f71c50dfbd5d78/C source codes/Assignment4/2switchMONTH.c", "visit_date": "2021-05-17T04:50:18.442586" }
stackv2
/*Program to display the name of mont for the corresponding number inputed*/ void main() { unsigned int month; //The number of month clrscr(); printf("Enter a number(1-12) to see the corresponding month:"); scanf("%u",&month); printf("The month %u is ",month); switch(month) { case 1 :printf("January");break; case 2 :printf("February");break; case 3 :printf("March");break; case 4 :printf("April");break; case 5 :printf("May");break; case 6 :printf("June");break; case 7 :printf("July");break; case 8 :printf("August");break; case 9 :printf("September");break; case 10:printf("October");break; case 11:printf("November");break; case 12:printf("December");break; default:printf("Invalid!"); } printf("\nPress any key...."); getch(); }
2.84375
3
2024-11-18T22:11:40.041647+00:00
2018-04-24T14:47:27
77184ba130be1878ca7bbcfd87c761702099b4f2
{ "blob_id": "77184ba130be1878ca7bbcfd87c761702099b4f2", "branch_name": "refs/heads/master", "committer_date": "2018-04-24T14:48:48", "content_id": "17cbdb4ec5dec97349aa00d2a94878a240ad0d60", "detected_licenses": [ "MIT" ], "directory_id": "af67006372325a4c896edc2dc5eb8242462e10da", "extension": "c", "filename": "adder.c", "fork_events_count": 0, "gha_created_at": "2018-01-26T15:13:30", "gha_event_created_at": "2018-01-26T15:13:31", "gha_language": null, "gha_license_id": null, "github_id": 119066521, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1834, "license": "MIT", "license_type": "permissive", "path": "/exercises/ex02/adder.c", "provenance": "stackv2-0087.json.gz:7372", "repo_name": "davidabrahams/ExercisesInC", "revision_date": "2018-04-24T14:47:27", "revision_id": "e8bf25d8a6e6b25bb1709a0d40a7583b016277a5", "snapshot_id": "19560f96b0bfbed01bee1bbc4d4ab5ed44d29697", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/davidabrahams/ExercisesInC/e8bf25d8a6e6b25bb1709a0d40a7583b016277a5/exercises/ex02/adder.c", "visit_date": "2021-05-09T14:31:44.565726" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> // Return // 0: EOF // 1: Valid input // 2: Input too long int readUserInput(const char* prompt, char* into, int length) { printf("%s: ", prompt); // read the first 'length - 1' characters into 'into' char* result = fgets(into,length,stdin); if (result == NULL) return 0; int slen = strlen(into); // check if the final character is a new line if (into[slen - 1] == '\n') { // remove the new line and return true into[slen - 1] = '\0'; return 1; } // read from stdin until we find the new line if (getchar() == '\n') return 1; while (getchar() != '\n') {} return 2; } int* resizeArray(int* A, int oldSize, int newSize) { printf("RESIZE"); int* B = malloc(newSize * sizeof(int)); for (int i = 0; i < oldSize; i++) { B[i] = A[i]; } free(A); return B; } int main() { int capacity = 2; int size = 0; int* A = malloc(2 * sizeof(int)); char string[11]; int valid = 1; while (valid != 0) { // read user input, capping at 11 characters valid = readUserInput("Please enter an integer", string, 11); if (valid == 0) continue; printf("You entered: %s\n", string); int i = atoi(string); // Check if input was too long, or was not an integer if (valid == 2 || (i == 0 && (strlen(string) != 1 || string[0] != '0'))) { printf("Invalid input recieved.\n"); continue; } if (++size > capacity) { // Check if we have to resize the array A = resizeArray(A, capacity, capacity * 2); // double the size capacity = capacity * 2; } // Store the user input in the array A[size - 1] = i; } // Finally, take the sum and print it int sum = 0; for (int i = 0; i < size; i++) sum += A[i]; printf("\nSum of array: %d", sum); }
3.796875
4
2024-11-18T22:11:40.130655+00:00
2018-01-11T06:09:59
b0426ac739f8e8541ae3ce91c2d8f9f5d8d21e00
{ "blob_id": "b0426ac739f8e8541ae3ce91c2d8f9f5d8d21e00", "branch_name": "refs/heads/master", "committer_date": "2018-01-11T06:09:59", "content_id": "786688e78a0a7efebb44f95278d2a964763769e1", "detected_licenses": [ "MIT" ], "directory_id": "9543fb168026bfb6ed3a61300d96a426b393165f", "extension": "h", "filename": "debug_print.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 96912595, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1628, "license": "MIT", "license_type": "permissive", "path": "/src/debug_print.h", "provenance": "stackv2-0087.json.gz:7500", "repo_name": "andrei91ro/lulu_pcol_sim_c", "revision_date": "2018-01-11T06:09:59", "revision_id": "5cc52b0cb891e787834135b8e4acdfe0b0e3a7c0", "snapshot_id": "3d7d9f9f84df93e1c3eafb72fbef967d8c7a2d87", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/andrei91ro/lulu_pcol_sim_c/5cc52b0cb891e787834135b8e4acdfe0b0e3a7c0/src/debug_print.h", "visit_date": "2020-06-24T01:09:42.166763" }
stackv2
/** * @file debug_print.h * @brief Debugging utility funtions * In this header we define a set of macros that help with message logging * and can be easily removed from the code * @author Andrei G. Florea * @author Catalin Buiu * @date 2016-02-23 */ #ifndef DEBUG_PRINT_H #define DEBUG_PRINT_H #ifndef DEBUG_PRINT #define printd(...) do { } while(0) #define printi(...) do { } while(0) #define printw(...) do { } while(0) #define printe(...) do { } while(0) #else #include <stdio.h> #if DEBUG_PRINT == 0 #ifndef PCOL_SIM #define printd(...) (puts("\nD: "),printf(__VA_ARGS__)) #else #define printd(...) (puts("\n\e[36mD: "),printf(__VA_ARGS__),puts("\e[0m")) #endif #else #define printd(...) do { } while(0) #endif #if DEBUG_PRINT <= 1 #ifndef PCOL_SIM #define printi(...) (puts("\nI: "),printf(__VA_ARGS__)) #else #define printi(...) (puts("\n\e[32mI: "),printf(__VA_ARGS__),puts("\e[0m")) #endif #else #define printi(...) do { } while(0) #endif #if DEBUG_PRINT <= 2 #ifndef PCOL_SIM #define printw(...) (puts("\nW: "),printf(__VA_ARGS__)) #else #define printw(...) (puts("\n\e[33mW: "),printf(__VA_ARGS__),puts("\e[0m")) #endif #else #define printw(...) do { } while(0) #endif #ifndef PCOL_SIM #define printe(...) (puts("\nE: "),printf(__VA_ARGS__)) #else #define printe(...) (puts("\n\e[31mE: "),printf(__VA_ARGS__),puts("\e[0m")) #endif #endif #endif
2.203125
2
2024-11-18T22:11:40.392210+00:00
2023-05-06T02:04:24
7771ace9e15cc1e698b70568923af188e6a5b188
{ "blob_id": "7771ace9e15cc1e698b70568923af188e6a5b188", "branch_name": "refs/heads/master", "committer_date": "2023-05-06T02:04:24", "content_id": "7b2d53295eac4971165a1ddaef7c94d94459d40c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c0bfd93cd7f26a271268e504959256f1e02c6806", "extension": "c", "filename": "spi_master_example_main.c", "fork_events_count": 1749, "gha_created_at": "2014-12-05T09:27:12", "gha_event_created_at": "2023-08-09T10:48:13", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 27584181, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10946, "license": "Apache-2.0", "license_type": "permissive", "path": "/examples/peripherals/spi/high_performance/spi_master/main/spi_master_example_main.c", "provenance": "stackv2-0087.json.gz:7629", "repo_name": "espressif/ESP8266_RTOS_SDK", "revision_date": "2023-05-06T02:04:24", "revision_id": "af0cdc36fa2600033d0a09301c754008cf1503c1", "snapshot_id": "606f396e92d2675d9854f0fabd88587fbbbaf267", "src_encoding": "UTF-8", "star_events_count": 3163, "url": "https://raw.githubusercontent.com/espressif/ESP8266_RTOS_SDK/af0cdc36fa2600033d0a09301c754008cf1503c1/examples/peripherals/spi/high_performance/spi_master/main/spi_master_example_main.c", "visit_date": "2023-08-24T22:40:15.373553" }
stackv2
/* spi_master example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <stdio.h> #include <string.h> #include <sys/time.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "freertos/stream_buffer.h" #include "esp8266/spi_struct.h" #include "esp8266/gpio_struct.h" #include "esp_system.h" #include "esp_log.h" #include "driver/gpio.h" #include "driver/spi.h" #include "time.h" static const char* TAG = "spi_master_example"; #define SPI_MASTER_HANDSHARK_GPIO 4 #define SPI_MASTER_HANDSHARK_SEL (1ULL<<SPI_MASTER_HANDSHARK_GPIO) #define SPI_BUFFER_MAX_SIZE 4096 #define ESP_HSPI_MASTER_SEND // Define the macro is master send mode, delete will be master receive mode static StreamBufferHandle_t spi_master_send_ring_buf = NULL; static StreamBufferHandle_t spi_master_recv_ring_buf = NULL; static uint32_t transmit_len = 0; static bool wait_recv_data = false; typedef enum { SPI_NULL = 0, SPI_WRITE, SPI_READ } spi_master_mode_t; static spi_master_mode_t intr_trans_mode = SPI_NULL; /* SPI master send length, format: 8bit command(value:1) + 32bit status length */ static void IRAM_ATTR spi_master_send_length(uint32_t len) { spi_trans_t trans; uint16_t cmd = SPI_MASTER_WRITE_STATUS_TO_SLAVE_CMD; memset(&trans, 0x0, sizeof(trans)); trans.bits.val = 0; trans.bits.cmd = 8 * 1; trans.bits.addr = 0; // transmit status do not use address bit trans.bits.mosi = 8 * 4; // status length is 32bit trans.cmd = &cmd; trans.addr = NULL; trans.mosi = &len; spi_trans(HSPI_HOST, &trans); } /* SPI master revecive length, format: 8bit command(value:4) + 32bit status length */ static uint32_t IRAM_ATTR spi_master_get_length(void) { spi_trans_t trans; uint32_t len = 0; uint16_t cmd = SPI_MASTER_READ_STATUS_FROM_SLAVE_CMD; memset(&trans, 0x0, sizeof(trans)); trans.bits.val = 0; trans.cmd = &cmd; trans.miso = &len; trans.addr = NULL; trans.bits.cmd = 8 * 1; trans.bits.miso = 8 * 4; spi_trans(HSPI_HOST, &trans); return len; } /* SPI transmit data, format: 8bit command (read value: 3, write value: 4) + 8bit address(value: 0x0) + 64byte data * For convenience, every time we send 64bytes, SPI SLAVE will determine how much data to read based on the status value */ static void IRAM_ATTR spi_master_transmit(spi_master_mode_t trans_mode, uint32_t* data) { spi_trans_t trans; uint16_t cmd; uint32_t addr = 0x0; memset(&trans, 0x0, sizeof(trans)); trans.bits.val = 0; // clear all bit if (trans_mode == SPI_WRITE) { cmd = SPI_MASTER_WRITE_DATA_TO_SLAVE_CMD; trans.bits.mosi = 8 * 64; // One time transmit only support 64bytes trans.mosi = data; } else if (trans_mode == SPI_READ) { cmd = SPI_MASTER_READ_DATA_FROM_SLAVE_CMD; trans.bits.miso = 8 * 64; trans.miso = data; } trans.bits.cmd = 8 * 1; trans.bits.addr = 8 * 1; // transmit data will use 8bit address trans.cmd = &cmd; trans.addr = &addr; spi_trans(HSPI_HOST, &trans); } static void IRAM_ATTR gpio_isr_handler(void* arg) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; uint32_t read_len = 0; uint32_t recv_actual_len = 0; uint32_t transmit_data[16]; if (intr_trans_mode == SPI_NULL) { // Some data need to read or write??? // have some data need to send ??? if (xStreamBufferIsEmpty(spi_master_send_ring_buf) == pdFALSE) { intr_trans_mode = SPI_WRITE; transmit_len = xStreamBufferBytesAvailable(spi_master_send_ring_buf); ESP_EARLY_LOGD(TAG, "Send len: %d\n", transmit_len); spi_master_send_length(transmit_len); return; } // Check if there is any data to receive transmit_len = spi_master_get_length(); if (transmit_len > 0) { ESP_EARLY_LOGD(TAG, "Receive data len: %d\n", transmit_len); intr_trans_mode = SPI_READ; return; } else { ESP_EARLY_LOGE(TAG, "Nothing to do"); return; } } read_len = transmit_len > 64 ? 64 : transmit_len; // SPI slave have some data want to transmit, read it if (intr_trans_mode == SPI_READ) { if (xStreamBufferSpacesAvailable(spi_master_recv_ring_buf) >= 64) { // Stream buffer not full, can be read agian spi_master_transmit(SPI_READ, transmit_data); recv_actual_len = xStreamBufferSendFromISR(spi_master_recv_ring_buf, (void*) transmit_data, read_len, &xHigherPriorityTaskWoken); assert(recv_actual_len == read_len); transmit_len -= read_len; if (transmit_len == 0) { intr_trans_mode = SPI_NULL; /* When SPI slave sending data , maybe MCU also have some date wait for send */ if (xStreamBufferIsEmpty(spi_master_send_ring_buf) == pdFALSE) { GPIO.status_w1ts |= BIT(SPI_MASTER_HANDSHARK_GPIO); // Manual generate GPIO interrupts } } } else { // stream buffer full, wait to be tacken out wait_recv_data = true; } // MCU want to send data to ESP8266 } else if (intr_trans_mode == SPI_WRITE) { if (read_len > 0) { recv_actual_len = xStreamBufferReceiveFromISR(spi_master_send_ring_buf, (void*)transmit_data, read_len, &xHigherPriorityTaskWoken); if (recv_actual_len != read_len) { ESP_EARLY_LOGE(TAG, "Expect to send %d bytes, but only %d bytes", read_len, recv_actual_len); return; } spi_master_transmit(SPI_WRITE, transmit_data); transmit_len -= read_len; } else { intr_trans_mode = SPI_NULL; if (xStreamBufferIsEmpty(spi_master_send_ring_buf) == pdFALSE) { GPIO.status_w1ts |= BIT(SPI_MASTER_HANDSHARK_GPIO); // Manual generate GPIO interrupts } else { // if ring buffer is empty, send status=0 tell slave send done spi_master_send_length(0); } } } if (xHigherPriorityTaskWoken == pdTRUE) { taskYIELD(); } } #ifdef ESP_HSPI_MASTER_SEND static void IRAM_ATTR spi_master_write_slave_task(void* arg) { #define TEST_SEND_BUFFER_LEN 2048 time_t start; time_t end; uint32_t total_len = 0; uint8_t* buf = malloc(TEST_SEND_BUFFER_LEN); memset(buf, 0x33, TEST_SEND_BUFFER_LEN); vTaskDelay(5000 / portTICK_RATE_MS); printf(" Test send\r\n"); start = time(NULL); while (1) { size_t xBytesSent = xStreamBufferSend(spi_master_send_ring_buf, (void*) buf, TEST_SEND_BUFFER_LEN, portMAX_DELAY); if (xBytesSent != TEST_SEND_BUFFER_LEN) { ESP_LOGE(TAG, "Send error, len:%d", xBytesSent); break; } portENTER_CRITICAL(); if (intr_trans_mode == SPI_NULL) { ESP_LOGI(TAG, "Manual generate GPIO interrupts"); GPIO.status_w1ts |= BIT(SPI_MASTER_HANDSHARK_GPIO); } portEXIT_CRITICAL(); total_len += TEST_SEND_BUFFER_LEN; if (total_len > 10 * 1024 * 1024) { end = time(NULL); printf("send done, total len: %d, time: %lds\n", total_len, (end - start)); break; } } vTaskDelete(NULL); } #else uint32_t read_count = 0; static void spi_master_count_task(void* arg) { uint32_t tmp_count = 0; while (1) { printf("recv_count: %d , speed: %dB/s\n", read_count, ((read_count - tmp_count) / 2)); tmp_count = read_count; vTaskDelay(2000 / portTICK_RATE_MS); } } static void IRAM_ATTR spi_master_read_slave_task(void* arg) { size_t xReceivedBytes; uint8_t read_data[1024 + 1]; while (1) { xReceivedBytes = xStreamBufferReceive(spi_master_recv_ring_buf, read_data, 1024, 2000 / portTICK_RATE_MS); if (xReceivedBytes != 0) { for (int i = 0; i < xReceivedBytes; i++) { if (read_data[i] != 0x44) { printf("receive error data: %x\n", read_data[i]); } } #if 0 read_data[xReceivedBytes] = '\0'; printf("%s", read_data); fflush(stdout); //Force to print even if have not '\n' #else read_count += xReceivedBytes; #endif } // steam buffer full if (wait_recv_data) { if (xStreamBufferBytesAvailable(spi_master_recv_ring_buf) > 64) { wait_recv_data = false; GPIO.status_w1ts |= BIT(SPI_MASTER_HANDSHARK_GPIO); // Manual generate GPIO interrupts } } } } #endif void app_main(void) { spi_master_send_ring_buf = xStreamBufferCreate(SPI_BUFFER_MAX_SIZE, 1024); spi_master_recv_ring_buf = xStreamBufferCreate(SPI_BUFFER_MAX_SIZE, 1); ESP_LOGI(TAG, "init gpio"); gpio_config_t io_conf; io_conf.intr_type = GPIO_INTR_POSEDGE; io_conf.mode = GPIO_MODE_INPUT; io_conf.pin_bit_mask = SPI_MASTER_HANDSHARK_SEL; io_conf.pull_down_en = 0; io_conf.pull_up_en = 0; gpio_config(&io_conf); gpio_install_isr_service(0); gpio_isr_handler_add(SPI_MASTER_HANDSHARK_GPIO, gpio_isr_handler, (void*) SPI_MASTER_HANDSHARK_GPIO); ESP_LOGI(TAG, "init spi"); spi_config_t spi_config; // Load default interface parameters // CS_EN:1, MISO_EN:1, MOSI_EN:1, BYTE_TX_ORDER:1, BYTE_TX_ORDER:1, BIT_RX_ORDER:0, BIT_TX_ORDER:0, CPHA:0, CPOL:0 spi_config.interface.val = SPI_DEFAULT_INTERFACE; // Load default interrupt enable // TRANS_DONE: true, WRITE_STATUS: false, READ_STATUS: false, WRITE_BUFFER: false, READ_BUFFER: false spi_config.intr_enable.val = SPI_MASTER_DEFAULT_INTR_ENABLE; // Set SPI to master mode // ESP8266 Only support half-duplex spi_config.mode = SPI_MASTER_MODE; // Set the SPI clock frequency division factor spi_config.clk_div = SPI_20MHz_DIV; // Register SPI event callback function spi_config.event_cb = NULL; spi_init(HSPI_HOST, &spi_config); #ifdef ESP_HSPI_MASTER_SEND // create spi_master_write_slave_task xTaskCreate(spi_master_write_slave_task, "spi_master_write_slave_task", 2048, NULL, 6, NULL); #else // create spi_master_read_slave_task xTaskCreate(spi_master_read_slave_task, "spi_master_read_slave_task", 2048, NULL, 5, NULL); xTaskCreate(spi_master_count_task, "spi_master_count_task", 2048, NULL, 4, NULL); #endif }
2.46875
2
2024-11-18T22:11:40.459544+00:00
2020-03-08T03:12:16
d887d5fa42d8a6ffbec6f7aa49967199831693fe
{ "blob_id": "d887d5fa42d8a6ffbec6f7aa49967199831693fe", "branch_name": "refs/heads/master", "committer_date": "2020-03-08T03:12:16", "content_id": "7c845d621ff579774c91ba4e501efa4b2558e802", "detected_licenses": [ "MIT" ], "directory_id": "4dd3eb9b51ee64ee887cc700d0f7a4ccc323809a", "extension": "h", "filename": "zzz-internal-type.h", "fork_events_count": 0, "gha_created_at": "2020-03-02T16:40:45", "gha_event_created_at": "2020-03-07T23:02:04", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 244421725, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2680, "license": "MIT", "license_type": "permissive", "path": "/src/zzz-internal-type.h", "provenance": "stackv2-0087.json.gz:7759", "repo_name": "DavisVaughan/rray2", "revision_date": "2020-03-08T03:12:16", "revision_id": "e8824b533f13811349cd0bd15210cd412bc7f2aa", "snapshot_id": "dca61017b5066306ebbe1922b2cfebd2d866dfd1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DavisVaughan/rray2/e8824b533f13811349cd0bd15210cd412bc7f2aa/src/zzz-internal-type.h", "visit_date": "2021-02-10T21:38:55.762366" }
stackv2
#ifndef RRAY_INTERNAL_TYPE_H #define RRAY_INTERNAL_TYPE_H #include "zzz-internal-r.h" #include "zzz-internal-util.h" enum r_type { r_type_null = 0, r_type_symbol = 1, r_type_pairlist = 2, r_type_closure = 3, r_type_environment = 4, r_type_promise = 5, r_type_call = 6, r_type_special = 7, r_type_builtin = 8, r_type_string = 9, r_type_logical = 10, r_type_integer = 13, r_type_double = 14, r_type_complex = 15, r_type_character = 16, r_type_dots = 17, r_type_any = 18, r_type_list = 19, r_type_expression = 20, r_type_bytecode = 21, r_type_pointer = 22, r_type_weakref = 23, r_type_raw = 24, r_type_s4 = 25, r_type_new = 30, r_type_free = 31, r_type_function = 99 }; static inline enum r_type r_typeof(sexp* x) { return TYPEOF(x); } static inline const char* r_type_as_friendly_c_string(enum r_type type) { switch (type) { case r_type_null: return "NULL"; case r_type_symbol: return "a symbol"; case r_type_pairlist: return "a pairlist node"; case r_type_closure: return "a function"; case r_type_environment: return "an environment"; case r_type_promise: return "an internal promise"; case r_type_call: return "a call"; case r_type_special: return "a primitive function"; case r_type_builtin: return "a primitive function"; case r_type_string: return "an internal string"; case r_type_logical: return "a logical vector"; case r_type_integer: return "an integer vector"; case r_type_double: return "a double vector"; case r_type_complex: return "a complex vector"; case r_type_character: return "a character vector"; case r_type_dots: return "an internal dots object"; case r_type_any: return "an internal `any` object"; case r_type_list: return "a list"; case r_type_expression: return "an expression vector"; case r_type_bytecode: return "an internal bytecode object"; case r_type_pointer: return "a pointer"; case r_type_weakref: return "a weak reference"; case r_type_raw: return "a raw vector"; case r_type_s4: return "an S4 object"; case r_type_new: return "an internal `new` object"; case r_type_free: return "an internal `free` object"; case r_type_function: return "a function"; } never_reached("r_type_as_friendly_c_string"); } static inline const char* r_sexp_as_friendly_c_string(sexp* x) { return r_type_as_friendly_c_string(r_typeof(x)); } #endif
2.046875
2
2024-11-18T22:11:40.571413+00:00
2020-11-30T19:09:49
23035236f63551d556e62e6b1d10481312c51d64
{ "blob_id": "23035236f63551d556e62e6b1d10481312c51d64", "branch_name": "refs/heads/master", "committer_date": "2020-11-30T19:09:49", "content_id": "286353d434d1d7ca50b5f6f65ba5db07a2019016", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "9646047ca1f4b6f4a54e749d8670b11d940bf616", "extension": "c", "filename": "test_str_normalize_space.c", "fork_events_count": 1, "gha_created_at": "2019-12-06T17:01:05", "gha_event_created_at": "2020-11-30T19:09:51", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 226373813, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1702, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/tests/test_str_normalize_space.c", "provenance": "stackv2-0087.json.gz:7888", "repo_name": "jhunkeler/spmc", "revision_date": "2020-11-30T19:09:49", "revision_id": "ecc7897bf007c0672d5bdc7711bcbf9fb104f995", "snapshot_id": "c766d527334fe5c4ab51d5565a1f8fd535d11de4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jhunkeler/spmc/ecc7897bf007c0672d5bdc7711bcbf9fb104f995/tests/test_str_normalize_space.c", "visit_date": "2021-07-12T22:35:22.514330" }
stackv2
#include "spm.h" #include "framework.h" const char *testFmt = "case: '%s': returned '%s', expected '%s'\n"; struct TestCase testCase[] = { {.caseValue.sptr = "no extra whitespace in the string", .truthValue.sptr = "no extra whitespace in the string"}, {.caseValue.sptr = "two extra spaces in the string", .truthValue.sptr = "two extra spaces in the string"}, {.caseValue.sptr = "three extra spaces in the string", .truthValue.sptr = "three extra spaces in the string"}, {.caseValue.sptr = " leading whitespace", .truthValue.sptr = "leading whitespace"}, {.caseValue.sptr = "trailing whitespace ", .truthValue.sptr = "trailing whitespace"}, {.caseValue.sptr = " leading and trailing whitespace ", .truthValue.sptr = "leading and trailing whitespace"}, {.caseValue.sptr = " varying degrees of whitespace everywhere ", .truthValue.sptr = "varying degrees of whitespace everywhere"}, {.caseValue.sptr = "nowhitespace", .truthValue.sptr = "nowhitespace"}, {.caseValue.sptr = NULL, .truthValue.sptr = NULL}, }; size_t numCases = sizeof(testCase) / sizeof(struct TestCase); int main(int argc, char *argv[]) { for (size_t i = 0; i < numCases; i++) { if (testCase[i].caseValue.sptr == NULL && testCase[i].truthValue.sptr == NULL) { // null input is null output continue; } char *result = strdup(testCase[i].caseValue.sptr); normalize_space(result); myassert(strcmp(result, testCase[i].truthValue.sptr) == 0, testFmt, testCase[i].caseValue.sptr, result, testCase[i].truthValue.sptr); } return 0; }
2.453125
2
2024-11-18T22:11:40.805216+00:00
2015-06-14T20:25:45
40c2f7584b707c2b87c0fc6c2445f8e8dee86d88
{ "blob_id": "40c2f7584b707c2b87c0fc6c2445f8e8dee86d88", "branch_name": "refs/heads/master", "committer_date": "2015-06-14T20:25:45", "content_id": "f6885b4153d3fe57b8ce622195635c7224064050", "detected_licenses": [ "MIT" ], "directory_id": "8efbed94f05ecb239e609f1bc7e13f886d83b8ca", "extension": "c", "filename": "app_font_viewer.c", "fork_events_count": 1, "gha_created_at": "2015-06-14T20:24:30", "gha_event_created_at": "2015-06-14T20:24:31", "gha_language": null, "gha_license_id": null, "github_id": 37428293, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2516, "license": "MIT", "license_type": "permissive", "path": "/watchapps/app_font_viewer/src/app_font_viewer.c", "provenance": "stackv2-0087.json.gz:8144", "repo_name": "tkafka/pebble-sdk-examples", "revision_date": "2015-06-14T20:25:45", "revision_id": "6dd78f3d103cfc12a08f0429e00a98f2a9aeb373", "snapshot_id": "4cdbf33056cf0eb3780775a5c1e736bc0f521b6a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tkafka/pebble-sdk-examples/6dd78f3d103cfc12a08f0429e00a98f2a9aeb373/watchapps/app_font_viewer/src/app_font_viewer.c", "visit_date": "2021-01-22T13:04:21.609726" }
stackv2
// Font Viewer -- Cycle through some of the characters in a symbol font. #include <pebble.h> #define PADDING 5 #define REPEAT_INTERVAL_MS 100 static Window *s_main_window; static TextLayer *s_text_layer; static TextLayer *s_char_text_layer; static char s_text_buffer[] = "Aa"; static void down_single_click_handler(ClickRecognizerRef recognizer, void *context) { if (s_text_buffer[0] != 'Z') { s_text_buffer[0]++; s_text_buffer[1]++; text_layer_set_text(s_text_layer, s_text_buffer); text_layer_set_text(s_char_text_layer, s_text_buffer); } } static void up_single_click_handler(ClickRecognizerRef recognizer, void *context) { if (s_text_buffer[0] != 'A') { s_text_buffer[0]--; s_text_buffer[1]--; text_layer_set_text(s_text_layer, s_text_buffer); text_layer_set_text(s_char_text_layer, s_text_buffer); } } static void click_config_provider(void *context) { window_single_repeating_click_subscribe(BUTTON_ID_UP, REPEAT_INTERVAL_MS, up_single_click_handler); window_single_repeating_click_subscribe(BUTTON_ID_DOWN, REPEAT_INTERVAL_MS, down_single_click_handler); } static void main_window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); s_text_layer = text_layer_create((GRect) { { PADDING, 0 }, { bounds.size.w - 2*PADDING, bounds.size.h } }); text_layer_set_text(s_text_layer, s_text_buffer); text_layer_set_font(s_text_layer, fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_UNICONS_30))); layer_add_child(window_layer, text_layer_get_layer(s_text_layer)); s_char_text_layer = text_layer_create((GRect) { { PADDING, bounds.size.h - 60 }, { bounds.size.w - 2*PADDING, 40 } }); text_layer_set_text(s_char_text_layer, s_text_buffer); text_layer_set_font(s_char_text_layer, fonts_get_system_font(FONT_KEY_BITHAM_30_BLACK)); layer_add_child(window_layer, text_layer_get_layer(s_char_text_layer)); } static void main_window_unload(Window *window) { text_layer_destroy(s_text_layer); text_layer_destroy(s_char_text_layer); } static void init() { s_main_window = window_create(); window_set_click_config_provider(s_main_window, click_config_provider); window_set_window_handlers(s_main_window, (WindowHandlers) { .load = main_window_load, .unload = main_window_unload, }); window_stack_push(s_main_window, true); } static void deinit() { window_destroy(s_main_window); } int main(void) { init(); app_event_loop(); deinit(); }
2.640625
3
2024-11-18T22:11:41.316997+00:00
2023-08-30T05:36:57
761f73c5b8103f81742d6f924fb767fdcfc21c08
{ "blob_id": "761f73c5b8103f81742d6f924fb767fdcfc21c08", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T05:36:57", "content_id": "cab9370c8e6ab883e43bb956cc1d503834a0ed35", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "bfb49b61aeca694f7c5d15de1df3e397ec3e8247", "extension": "c", "filename": "manl.c", "fork_events_count": 2, "gha_created_at": "2015-12-27T11:52:52", "gha_event_created_at": "2021-01-25T08:26:24", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 48643177, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2815, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/manl.c", "provenance": "stackv2-0087.json.gz:8787", "repo_name": "Wodan58/Moy", "revision_date": "2023-08-30T05:36:57", "revision_id": "85e7f5f4cd951cea552933508afdf20c655f6ea2", "snapshot_id": "0dfaf7bbda205287a03735b6b1c4703fbdb2fcc9", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/Wodan58/Moy/85e7f5f4cd951cea552933508afdf20c655f6ea2/manl.c", "visit_date": "2023-08-31T07:16:36.145158" }
stackv2
/* module : manl.c version : 1.1 date : 07/10/23 */ #include "globals.h" #define PLAIN (style == 0) #define HTML (style == 1) #define LATEX (style == 2) #define HEADER(N, NAME, HEAD) \ if (strcmp(N, NAME) == 0) { \ printf("\n\n"); \ if (HTML) \ printf("<DT><BR><B>"); \ if (LATEX) \ printf("\\item[--- \\BX{"); \ printf("%s", HEAD); \ if (LATEX) \ printf("} ---] \\verb# #"); \ if (HTML) \ printf("</B><BR><BR>"); \ printf("\n\n"); \ } PUBLIC void make_manual(int style /* 0=plain, 1=HTML, 2=Latex */) { int i; OpTable *optable; if (HTML) printf("<HTML>\n<DL>\n"); for (i = BOOLEAN_; (optable = readtable(i)) != 0; i++) { char *n = optable->name; HEADER(n, " truth value type", "literal") else HEADER(n, "false", "operand") else HEADER(n, "id", "operator") else HEADER(n, "null", "predicate") else HEADER(n, "i", "combinator") else HEADER(n, "help", "miscellaneous commands") if (n[0] != '_') { if (HTML) printf("\n<DT>"); else if (LATEX) { if (n[0] == ' ') { n++; printf("\\item[\\BX{"); } else printf("\\item[\\JX{"); } if (HTML && strcmp(n, "<=") == 0) printf("&lt;="); else printf("%s", n); if (LATEX) printf("}] \\verb#"); if (HTML) printf(" <CODE> : </CODE> "); /* the above line does not produce the spaces around ":" */ else printf("\t: "); printf("%s", optable->messg1); if (HTML) printf("\n<DD>"); else if (LATEX) printf("# \\\\ \n {\\small\\verb#"); else printf("\n"); printf("%s", optable->messg2); if (LATEX) printf("#}"); printf("\n\n"); } } if (HTML) printf("\n</DL>\n</HTML>\n"); }
2.3125
2