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:47:08.457098+00:00
2017-08-12T22:10:25
b48228b21c870e4518cb81da7de6d397e1a7bc0b
{ "blob_id": "b48228b21c870e4518cb81da7de6d397e1a7bc0b", "branch_name": "refs/heads/master", "committer_date": "2017-08-12T22:10:25", "content_id": "5194592b9afd3cc2b75fbcea574b2bc643dfbecc", "detected_licenses": [ "MIT" ], "directory_id": "acee1466e000325f82bdf16df71eddf8e6638531", "extension": "c", "filename": "makise_text.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": 3617, "license": "MIT", "license_type": "permissive", "path": "/MakiseGUI/makise_text.c", "provenance": "stackv2-0130.json.gz:51163", "repo_name": "shaman1010/MakiseGUI", "revision_date": "2017-08-12T22:10:25", "revision_id": "971c7c731628e21b06fa9d0de0c7fec73a8588d1", "snapshot_id": "d2255aa5a6a5deda089fff5958f44dbe7ec2a8eb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/shaman1010/MakiseGUI/971c7c731628e21b06fa9d0de0c7fec73a8588d1/MakiseGUI/makise_text.c", "visit_date": "2020-04-09T03:23:03.568875" }
stackv2
#include "makise_text.h" static void _makise_draw_char(MakiseBuffer *b, uint16_t ind, int16_t x, int16_t y, const MakiseFont *font, uint32_t c, uint16_t width) { uint32_t bitCounter, rawIndex, colIndex; const uint8_t * ptrByte; if(b->border.ex + b->border.w < x || b->border.ey + b->border.h < y || x <= b->border.x - width || y <= b->border.y - font->height) return; ptrByte = &font->table[font->char_index[ind]]; for(rawIndex = 0; rawIndex < font->height; rawIndex++) { bitCounter = 0; for(colIndex = 0; colIndex < width; colIndex++) { if (bitCounter > 7) { bitCounter = 0; ptrByte++; } if(*ptrByte & (1<<bitCounter)) { makise_pset(b, x+colIndex, y+rawIndex, c); } bitCounter++; } ptrByte++; } } void makise_d_char(MakiseBuffer *b, uint16_t ch, int16_t x, int16_t y, const MakiseFont *font, uint32_t c) { uint32_t width; ch = (uint8_t)ch - font->offset; // Symbol width if (ch > font->num_char) ch = 0; width = font->width ? font->width : font->char_width[ch]; // Draw Char _makise_draw_char(b, ch, x, y, font, c, width); } void makise_d_string(MakiseBuffer *b, char *s, uint32_t len, int16_t x, int16_t y, MDTextPlacement place, const MakiseFont *font, uint32_t c) { uint32_t width, i = 0; if(s == 0) return; if(place == MDTextPlacement_Center ) { width = makise_d_string_width(s, len, font); x -= width / 2; y -= font->height / 2; } else if(place == MDTextPlacement_CenterUp ) { width = makise_d_string_width(s, len, font); x -= width / 2; } else if(place == MDTextPlacement_CenterDown ) { width = makise_d_string_width(s, len, font); x -= width / 2; y -= font->height; } uint32_t ch, xt = x, yt = y; if(y + font->height < b->border.y || y > b->border.ey) //borders return; while (i < len && s[i]) { ch = s[i]; ch = (uint8_t)ch - font->offset; // Symbol width if (ch > font->num_char) ch = 0; width = font->width ? font->width : font->char_width[ch]; // Draw Char _makise_draw_char(b, ch, xt, yt, font, c, width); xt += width + font->space_char; i++; if(xt >= b->border.ex) //border return; } } uint32_t makise_d_string_width(char *s, uint32_t len, const MakiseFont *font) { uint32_t width , i = 0; uint32_t ch, res = 0; if(s == 0) return 0; while (i < len && s[i]) { ch = s[i]; ch = (uint8_t)ch - font->offset; // Symbol width if (ch > font->num_char) ch = 0; width = font->width ? font->width : font->char_width[ch]; res += width + font->space_char; i++; } return res; } //draw multiline text in the defined frame void makise_d_string_frame(MakiseBuffer *b, char *s, uint32_t len, int16_t x, int16_t y, uint16_t w, uint16_t h, const MakiseFont *font, uint16_t line_spacing, uint32_t c) { uint32_t width, i = 0; uint32_t ch, xt = x, yt = y; if(s == 0) return; while (i < len && s[i]) { if(s[i] == '\n' || s[i] == '\r') { xt = x; yt += font->height + line_spacing; if(yt + font->height > y + h) return; } else { ch = s[i]; ch = (uint8_t)ch - font->offset; // Symbol width if (ch > font->num_char) ch = 0; width = font->width ? font->width : font->char_width[ch]; if(xt + width > x + w) { xt = x; yt += font->height + line_spacing; if(yt + font->height > y + h) return; } // Draw Char _makise_draw_char(b, ch, xt, yt, font, c, width); xt += width + font->space_char; } i++; } }
2.828125
3
2024-11-18T21:47:08.543889+00:00
2020-04-27T08:11:47
bbbead3df8c29b9544f1d1b5e049824fb2fb5718
{ "blob_id": "bbbead3df8c29b9544f1d1b5e049824fb2fb5718", "branch_name": "refs/heads/master", "committer_date": "2020-04-27T08:11:47", "content_id": "384df52e4ca2ae80e3a9b6793fdb83121f5c5733", "detected_licenses": [ "Apache-2.0" ], "directory_id": "957f793bd3168fb4ea965b35f1de4ecd60180b4a", "extension": "h", "filename": "hlw.h", "fork_events_count": 0, "gha_created_at": "2020-06-18T12:29:24", "gha_event_created_at": "2020-06-18T12:29:24", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 273232142, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2573, "license": "Apache-2.0", "license_type": "permissive", "path": "/app/src/main/cpp/hlw.h", "provenance": "stackv2-0130.json.gz:51294", "repo_name": "touchain-project/ShowCore-Open", "revision_date": "2020-04-27T08:11:47", "revision_id": "c13383a7233cb64e782e2dbcfddbbccdf8cc5a88", "snapshot_id": "f7a081f3ff1892dedbe208a4159d381cd52c911e", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/touchain-project/ShowCore-Open/c13383a7233cb64e782e2dbcfddbbccdf8cc5a88/app/src/main/cpp/hlw.h", "visit_date": "2022-05-28T13:40:03.325771" }
stackv2
#ifndef __CAE_INTF_H__ #define __CAE_INTF_H__ typedef void * CAE_HANDLE; //angle 角度 //channel 虚拟波束编号 //power 波束能量 //CMScore 唤醒分值 //beam 麦克风编号 //userData 用户回调数据 typedef void (*cae_ivw_fn)(short angle, short channel, float power, short CMScore, short beam, char *param1, void *param2, void *userData); //audioData 识别音频地址 //audioLen 识别音频字节数 //userData 用户回调数据 typedef void (*cae_audio_fn)(const void *audioData, unsigned int audioLen, int param1, const void *param2, void *userData); //audioData 唤醒音频地址 //audioLen 唤醒音频字节数 //userData 用户回调数据 typedef void (*cae_ivw_audio_fn)(const void *audioData, unsigned int audioLen, int param1, const void *param2, void *userData); #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* 初始化实例(实例地址、资源地址、唤醒信息回调、唤醒音频回调、识别音频回调、预留参数、用户回调数据) */ int CAENew(CAE_HANDLE *cae, const char* resPath, cae_ivw_fn ivwCb, cae_ivw_audio_fn ivwAudioCb, cae_audio_fn audioCb, const char *param, void *userData); typedef int (* Proc_CAENew)(CAE_HANDLE *cae, const char* resPath, cae_ivw_fn ivwCb, cae_ivw_audio_fn ivwAudioCb, cae_audio_fn audioCb, const char *param, void *userData); /* 重新加载资源(实例地址、资源路径) */ int CAEReloadResource(CAE_HANDLE cae, const char* resPath); typedef int (* Proc_CAEReloadResource)(CAE_HANDLE cae, const char* resPath); /* 写入音频数据(实例地址、录音数据地址、录音数据长度) */ int CAEAudioWrite(CAE_HANDLE cae, const void *audioData, unsigned int audioLen); typedef int (* Proc_CAEAudioWrite)(CAE_HANDLE cae, const void *audioData, unsigned int audioLen); /* 设置麦克风编号(唤醒模式内部已经设置编号外部不用再次调用、手动模式需要调用设置麦克风编号) */ int CAESetRealBeam(CAE_HANDLE cae, int beam); typedef int (* Proc_CAESetRealBeam)(CAE_HANDLE cae, int beam); /* 获取版本号 */ char* CAEGetVersion(); typedef char (* Proc_CAEGetVersion)(); /* 销毁实例(实例地址) */ int CAEDestroy(CAE_HANDLE cae); typedef int (* Proc_CAEDestroy)(CAE_HANDLE cae); /* 设置日志级别(日志级别 0 调试、1 信息、2错误) */ int CAESetShowLog(int show_log); typedef int (* Proc_CAESetShowLog)(int show_log); /* 请求鉴权(设备授权编号)*/ int CAEAuth(char *sn); typedef int (* Proc_CAEAuth)(char *sn); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __CAE_INTF_H__ */
2.078125
2
2024-11-18T21:47:09.046327+00:00
2020-12-16T23:37:27
dbc27e0e838fdeb21e5c18d66311be0670551303
{ "blob_id": "dbc27e0e838fdeb21e5c18d66311be0670551303", "branch_name": "refs/heads/master", "committer_date": "2020-12-16T23:46:23", "content_id": "67b23bb9c5f7f8146d79694aeef970b8726bce4d", "detected_licenses": [ "MIT" ], "directory_id": "96e22527a7daf26caddbcaac28acfdc4287667a5", "extension": "h", "filename": "fat_standard.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": 3478, "license": "MIT", "license_type": "permissive", "path": "/lib/fat_standard.h", "provenance": "stackv2-0130.json.gz:51424", "repo_name": "gabrielggd/asyncfatfs", "revision_date": "2020-12-16T23:37:27", "revision_id": "153a00930eab8b7de1941cc6486ac8fd63778134", "snapshot_id": "210d942ab700c8005052c9a79994f448e1772234", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gabrielggd/asyncfatfs/153a00930eab8b7de1941cc6486ac8fd63778134/lib/fat_standard.h", "visit_date": "2023-02-01T22:50:48.541741" }
stackv2
#pragma once #include <stdint.h> #include <stdbool.h> #define MBR_PARTITION_TYPE_FAT16 0x06 #define MBR_PARTITION_TYPE_FAT32 0x0B #define MBR_PARTITION_TYPE_FAT32_LBA 0x0C #define MBR_PARTITION_TYPE_FAT16_LBA 0x0E // Signature bytes found at index 510 and 511 in the volume ID sector #define FAT_VOLUME_ID_SIGNATURE_1 0x55 #define FAT_VOLUME_ID_SIGNATURE_2 0xAA #define FAT_DIRECTORY_ENTRY_SIZE 32 #define FAT_SMALLEST_LEGAL_CLUSTER_NUMBER 2 #define FAT_MAXIMUM_FILESIZE 0xFFFFFFFF #define FAT12_MAX_CLUSTERS 4084 #define FAT16_MAX_CLUSTERS 65524 #define FAT_FILE_ATTRIBUTE_READ_ONLY 0x01 #define FAT_FILE_ATTRIBUTE_HIDDEN 0x02 #define FAT_FILE_ATTRIBUTE_SYSTEM 0x04 #define FAT_FILE_ATTRIBUTE_VOLUME_ID 0x08 #define FAT_FILE_ATTRIBUTE_DIRECTORY 0x10 #define FAT_FILE_ATTRIBUTE_ARCHIVE 0x20 #define FAT_FILENAME_LENGTH 11 #define FAT_DELETED_FILE_MARKER 0xE5 #define FAT_MAKE_DATE(year, month, day) (day | (month << 5) | ((year - 1980) << 9)) #define FAT_MAKE_TIME(hour, minute, second) ((second / 2) | (minute << 5) | (hour << 11)) typedef enum { FAT_FILESYSTEM_TYPE_INVALID, FAT_FILESYSTEM_TYPE_FAT12, FAT_FILESYSTEM_TYPE_FAT16, FAT_FILESYSTEM_TYPE_FAT32, } fatFilesystemType_e; typedef struct mbrPartitionEntry_t { uint8_t bootFlag; uint8_t chsBegin[3]; uint8_t type; uint8_t chsEnd[3]; uint32_t lbaBegin; uint32_t numSectors; } __attribute__((packed)) mbrPartitionEntry_t; typedef struct fat16Descriptor_t { uint8_t driveNumber; uint8_t reserved1; uint8_t bootSignature; uint32_t volumeID; char volumeLabel[11]; char fileSystemType[8]; } __attribute__((packed)) fat16Descriptor_t; typedef struct fat32Descriptor_t { uint32_t FATSize32; uint16_t extFlags; uint16_t fsVer; uint32_t rootCluster; uint16_t fsInfo; uint16_t backupBootSector; uint8_t reserved[12]; uint8_t driveNumber; uint8_t reserved1; uint8_t bootSignature; uint32_t volumeID; char volumeLabel[11]; char fileSystemType[8]; } __attribute__((packed)) fat32Descriptor_t; typedef struct fatVolumeID_t { uint8_t jmpBoot[3]; char oemName[8]; uint16_t bytesPerSector; uint8_t sectorsPerCluster; uint16_t reservedSectorCount; uint8_t numFATs; uint16_t rootEntryCount; uint16_t totalSectors16; uint8_t media; uint16_t FATSize16; uint16_t sectorsPerTrack; uint16_t numHeads; uint32_t hiddenSectors; uint32_t totalSectors32; union { fat16Descriptor_t fat16; fat32Descriptor_t fat32; } fatDescriptor; } __attribute__((packed)) fatVolumeID_t; typedef struct fatDirectoryEntry_t { char filename[FAT_FILENAME_LENGTH]; uint8_t attrib; uint8_t ntReserved; uint8_t creationTimeTenths; uint16_t creationTime; uint16_t creationDate; uint16_t lastAccessDate; uint16_t firstClusterHigh; uint16_t lastWriteTime; uint16_t lastWriteDate; uint16_t firstClusterLow; uint32_t fileSize; } __attribute__((packed)) fatDirectoryEntry_t; uint32_t fat32_decodeClusterNumber(uint32_t clusterNumber); bool fat32_isEndOfChainMarker(uint32_t clusterNumber); bool fat16_isEndOfChainMarker(uint16_t clusterNumber); bool fat_isFreeSpace(uint32_t clusterNumber); bool fat_isDirectoryEntryTerminator(fatDirectoryEntry_t *entry); bool fat_isDirectoryEntryEmpty(fatDirectoryEntry_t *entry); void fat_convertFilenameToFATStyle(const char *filename, uint8_t *fatFilename);
2
2
2024-11-18T21:47:09.208545+00:00
2013-09-12T09:59:19
e7e125c4ef2aa62702a1d8c9800816dfe7ce7980
{ "blob_id": "e7e125c4ef2aa62702a1d8c9800816dfe7ce7980", "branch_name": "refs/heads/master", "committer_date": "2013-09-12T09:59:19", "content_id": "9cb993e4cc384de7f155d0d60abc580d2fa4e279", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9266b5c7083daa4e08f75b6148ff46d31a80f6e6", "extension": "c", "filename": "event.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": 4649, "license": "Apache-2.0", "license_type": "permissive", "path": "/event.c", "provenance": "stackv2-0130.json.gz:51555", "repo_name": "wvdschel/gamer", "revision_date": "2013-09-12T09:59:19", "revision_id": "6310065a06c707b0060db5f1c396fbe5a418a303", "snapshot_id": "9597d59ba9f278e172e1f753219747c0de2e3871", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wvdschel/gamer/6310065a06c707b0060db5f1c396fbe5a418a303/event.c", "visit_date": "2020-05-31T00:37:04.904700" }
stackv2
#include <ruby.h> #include <SDL/SDL.h> #include "event.h" VALUE gam_cEvent; void Init_event(VALUE module) { gam_cEvent = rb_define_class_under(module, "Event", rb_cObject); rb_define_alloc_func(gam_cEvent, event_allocate); rb_define_method(gam_cEvent, "type", event_get_type, 0); rb_define_method(gam_cEvent, "x", event_get_mouse_x, 0); rb_define_method(gam_cEvent, "y", event_get_mouse_x, 0); rb_define_method(gam_cEvent, "button", event_get_mouse_button, 1); rb_define_method(gam_cEvent, "keycode", event_get_keycode, 0); rb_define_method(gam_cEvent, "unicode", event_get_unicode, 0); rb_define_const(module, "KEYDOWN", INT2FIX(KEYDOWN)); rb_define_const(module, "KEYUP", INT2FIX(KEYUP)); rb_define_const(module, "MOUSEDOWN", INT2FIX(MOUSEDOWN)); rb_define_const(module, "MOUSEUP", INT2FIX(MOUSEUP)); rb_define_const(module, "MOUSEMOVE", INT2FIX(MOUSEMOVE)); rb_define_const(module, "QUIT", INT2FIX(QUIT)); rb_define_const(module, "EXPOSE", INT2FIX(EXPOSE)); rb_define_const(module, "ACTIVE", INT2FIX(ACTIVE)); rb_define_const(module, "RESIZE", INT2FIX(RESIZE)); } VALUE event_allocate(VALUE klass) { event_t *evt = malloc(sizeof(event_t)); evt->initialized = 0; return Data_Wrap_Struct(klass, event_mark, event_free, evt); } void event_free(event_t *evt) { free(evt); } void event_mark(event_t *evt) {} VALUE event_get_type(VALUE object) { event_t *evt; Data_Get_Struct(object, event_t, evt); if(evt->initialized) { switch(evt->event.type) { case SDL_KEYDOWN: return INT2FIX(KEYDOWN); case SDL_KEYUP: return INT2FIX(KEYUP); case SDL_ACTIVEEVENT: return INT2FIX(ACTIVE); case SDL_MOUSEMOTION: return INT2FIX(MOUSEMOVE); case SDL_MOUSEBUTTONUP: return INT2FIX(MOUSEUP); case SDL_MOUSEBUTTONDOWN: return INT2FIX(MOUSEDOWN); case SDL_VIDEORESIZE: return INT2FIX(RESIZE); case SDL_VIDEOEXPOSE: return INT2FIX(EXPOSE); case SDL_QUIT: return INT2FIX(QUIT); default: return Qfalse; } } else return Qnil; } VALUE event_get_mouse_x(VALUE object) { event_t *evt; Data_Get_Struct(object, event_t, evt); if(evt->event.type == SDL_MOUSEMOTION) { return UINT2NUM(evt->event.motion.x); } else if(evt->event.type == SDL_MOUSEBUTTONUP || evt->event.type == SDL_MOUSEBUTTONDOWN) { return UINT2NUM(evt->event.button.x); } else rb_raise(rb_eTypeError, "only MOUSEMOTION, MOUSEUP and MOUSEDOWN events can report mouse coordinates. Use Surface#mouse_x instead"); } VALUE event_get_mouse_y(VALUE object) { event_t *evt; Data_Get_Struct(object, event_t, evt); if(evt->event.type == SDL_MOUSEMOTION) return UINT2NUM(evt->event.motion.y); else if(evt->event.type == SDL_MOUSEBUTTONUP || evt->event.type == SDL_MOUSEBUTTONDOWN) return UINT2NUM(evt->event.button.y); else rb_raise(rb_eTypeError, "only MOUSEMOTION, MOUSEUP and MOUSEDOWN events can report mouse coordinates. Use Surface#mouse_y instead"); } VALUE event_get_mouse_button(VALUE object, VALUE btn) { Uint8 state; event_t *evt; Data_Get_Struct(object, event_t, evt); if(evt->event.type == SDL_MOUSEMOTION) state = evt->event.motion.state; if(evt->event.type == SDL_MOUSEBUTTONUP || evt->event.type == SDL_MOUSEBUTTONDOWN) state = evt->event.button.state; else rb_raise(rb_eTypeError, "only MOUSEMOTION, MOUSEUP and MOUSEDOWN events can report mouse button states. Use Surface#mouse_button? instead"); if(state & SDL_BUTTON(NUM2UINT(btn)) ) return Qtrue; else return Qfalse; } VALUE event_get_keycode(VALUE object) { event_t *evt; Data_Get_Struct(object, event_t, evt); if(evt->event.type == SDL_KEYUP || evt->event.type == SDL_KEYDOWN) return INT2FIX(evt->event.key.keysym.sym); else rb_raise(rb_eTypeError, "only KEYUP and KEYDOWN events can report keycodes"); } VALUE event_get_unicode(VALUE object) { event_t *evt; Data_Get_Struct(object, event_t, evt); if(evt->event.type == SDL_KEYUP || evt->event.type == SDL_KEYDOWN) return INT2FIX(evt->event.key.keysym.unicode); else rb_raise(rb_eTypeError, "only KEYUP and KEYDOWN events can report unicodes"); } VALUE wrap_event(SDL_Event sdl_event, surface_t *surface) { event_t *evt; VALUE event; if(sdl_event.type == SDL_VIDEORESIZE) { surface->width = sdl_event.resize.w; surface->height = sdl_event.resize.h; } event = rb_class_new_instance(0, NULL, gam_cEvent); Data_Get_Struct(event, event_t, evt); evt->event = sdl_event; evt->initialized = 1; return event; }
2.484375
2
2024-11-18T21:47:10.282789+00:00
2020-08-18T11:16:19
86e17499c59e77effc7f30643a94c5649c87f6fd
{ "blob_id": "86e17499c59e77effc7f30643a94c5649c87f6fd", "branch_name": "refs/heads/master", "committer_date": "2020-08-18T11:16:19", "content_id": "571e730c92d37b5940045a68fefd5bd6167e8f04", "detected_licenses": [ "MIT" ], "directory_id": "71833e8a7d447fb2c2eaf5aae29bae58fdc50541", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 232076022, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1268, "license": "MIT", "license_type": "permissive", "path": "/test/test.c", "provenance": "stackv2-0130.json.gz:52590", "repo_name": "Daniel1993/tcpSocketLib", "revision_date": "2020-08-18T11:16:19", "revision_id": "39cefa9ca810aed723624ef4591218b5c7d7298e", "snapshot_id": "e8d4a4976f7d3503fe1dc2730e9dbd3b72bc3e1d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Daniel1993/tcpSocketLib/39cefa9ca810aed723624ef4591218b5c7d7298e/test/test.c", "visit_date": "2020-12-05T10:06:07.777883" }
stackv2
#include "tcpSocketLib.h" #include "input_handler.h" #include <stdio.h> #include <assert.h> #include <string.h> void handler(void *msg, size_t len, void(*respondWith)(void*,size_t), void(*waitResponse)(void*, size_t*)) { printf("[SERVER] got message: %s\n", (char*)msg); char buffer[TSL_MSG_BUFFER] = "world!"; size_t len2 = strlen(buffer)+1; respondWith(buffer, len2); waitResponse((void*)buffer, &len2); printf("[SERVER] got message: %s\n", (char*)buffer); } int main (int argc, char **argv) { char port[64] = "16080"; char buffer[TSL_MSG_BUFFER] = "hello"; char buffer2[TSL_MSG_BUFFER] = "bye!"; size_t len; input_parse(argc, argv); if (input_exists("PORT")) { input_getString("PORT", port); // test size } printf("openning port %s\n", port); tsl_init(port); tsl_add_handler(handler); int connId = tsl_connect_to("127.0.0.1", port); printf("connection = %i\n", connId); tsl_send_msg(connId, buffer, strlen(buffer)+1); // do not forget \0 tsl_recv_msg(connId, (void*)buffer, &len); tsl_send_msg(connId, buffer2, strlen(buffer2)+1); tsl_close_all_connections(); printf("[CLIENT]: got message %s\n", (char*)buffer); tsl_destroy(); return EXIT_SUCCESS; }
2.65625
3
2024-11-18T21:47:10.330680+00:00
2020-09-08T18:31:42
54b24b49a51116be2e3011bb50909fb56682f0ce
{ "blob_id": "54b24b49a51116be2e3011bb50909fb56682f0ce", "branch_name": "refs/heads/master", "committer_date": "2020-09-08T19:03:31", "content_id": "f4691a56b8c9cf1d5b1a66ee9214a2d20040f073", "detected_licenses": [ "Unlicense" ], "directory_id": "b6795c3a2e3acac78585dfb182ac5455a564f801", "extension": "c", "filename": "vfs.c", "fork_events_count": 6, "gha_created_at": "2020-09-08T18:30:35", "gha_event_created_at": "2021-11-08T19:08:43", "gha_language": "C", "gha_license_id": "Unlicense", "github_id": 293895117, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2637, "license": "Unlicense", "license_type": "permissive", "path": "/src/vfs.c", "provenance": "stackv2-0130.json.gz:52719", "repo_name": "r-lyeh/stdarc.c", "revision_date": "2020-09-08T18:31:42", "revision_id": "6f6a6de53c59bcdd4091020e6e68ee065e31107c", "snapshot_id": "687665a2a38fb421742dda242e3e6df7d96b2147", "src_encoding": "UTF-8", "star_events_count": 54, "url": "https://raw.githubusercontent.com/r-lyeh/stdarc.c/6f6a6de53c59bcdd4091020e6e68ee065e31107c/src/vfs.c", "visit_date": "2021-11-29T18:08:31.964177" }
stackv2
// virtual filesystem (registered directories and/or compressed zip archives). // - rlyeh, public domain. // // - note: vfs_mount() order matters (the most recent the higher priority). void vfs_mount(const char *path); // zipfile or directory/with/trailing/slash/ char* vfs_load(const char *filename, int *size); // must free() after use // ----------------------------------------------------------------------------- #ifdef VFS_C #pragma once #include <stdio.h> #include <stdlib.h> #include <string.h> static char *vfs_read_file(const char *filename, int *len) { FILE *fp = fopen(filename, "rb"); if( fp ) { fseek(fp, 0L, SEEK_END); size_t sz = ftell(fp); fseek(fp, 0L, SEEK_SET); char *bin = REALLOC(0, sz+1); fread(bin,sz,1,fp); fclose(fp); bin[sz] = 0; if(len) *len = (int)sz; return bin; } return 0; } typedef struct vfs_dir { char* path; // const zip* archive; int is_directory; struct vfs_dir *next; } vfs_dir; static vfs_dir *dir_head = NULL; void vfs_mount(const char *path) { zip *z = NULL; int is_directory = ('/' == path[strlen(path)-1]); if( !is_directory ) z = zip_open(path, "rb"); if( !is_directory && !z ) return; vfs_dir *prev = dir_head, zero = {0}; *(dir_head = REALLOC(0, sizeof(vfs_dir))) = zero; dir_head->next = prev; dir_head->path = STRDUP(path); dir_head->archive = z; dir_head->is_directory = is_directory; } char *vfs_load(const char *filename, int *size) { // must free() after use char *data = NULL; for(vfs_dir *dir = dir_head; dir && !data; dir = dir->next) { if( dir->is_directory ) { char buf[512]; snprintf(buf, sizeof(buf), "%s%s", dir->path, filename); data = vfs_read_file(buf, size); } else { int index = zip_find(dir->archive, filename); data = zip_extract(dir->archive, index); if( size ) *size = zip_size(dir->archive, index); } // printf("%c trying %s in %s ...\n", data ? 'Y':'N', filename, dir->path); } return data; } #ifdef VFS_DEMO int main() { vfs_mount("../src/"); // directories/must/end/with/slash/ vfs_mount("demo.zip"); // zips supported printf("vfs.c file found? %s\n", vfs_load("vfs.c", 0) ? "Y":"N"); // should be Y printf("stdarc.c file found? %s\n", vfs_load("stdarc.c", 0) ? "Y":"N"); // should be N printf("demo_zip.c file found? %s\n", vfs_load("demo_zip.c", 0) ? "Y":"N"); // should be Y after running demo_zip.exe } #define main main__ #endif // VFS_DEMO #endif // VFS_C
2.796875
3
2024-11-18T21:47:10.412697+00:00
2020-09-12T14:03:15
31bfac786082f43a85e8fe86ae0efee475dbfe9b
{ "blob_id": "31bfac786082f43a85e8fe86ae0efee475dbfe9b", "branch_name": "refs/heads/master", "committer_date": "2020-09-12T14:11:18", "content_id": "87025525e2f58e067b50a83791bc532782aa872e", "detected_licenses": [ "MIT" ], "directory_id": "6b2a273178d028c48e021d2cef74b8d00f36a288", "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": 286668723, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3440, "license": "MIT", "license_type": "permissive", "path": "/asm/main.c", "provenance": "stackv2-0130.json.gz:52850", "repo_name": "HowyoungZhou/cyber-melody-2", "revision_date": "2020-09-12T14:03:15", "revision_id": "b96fff16f4bc57b47867389f8d6dc297fae58387", "snapshot_id": "aa416a499338d25e3122552090748bda9e696542", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/HowyoungZhou/cyber-melody-2/b96fff16f4bc57b47867389f8d6dc297fae58387/asm/main.c", "visit_date": "2022-12-14T04:40:33.604849" }
stackv2
int keycode_octave_lut[256]; int score[]; int indicator_x_lut[256]; int colors[12]; void draw(int mode, int tl, int rd, int color); void draw_rect(int x0, int y0, int x1, int y1, int color); void draw_image(int x0, int y0, int x1, int y1, int address); void draw_indicator(int note_octave, int y, int length) { int x0 = indicator_x_lut[note_octave]; // s0 if (x0 == 0) return; int y0 = y - length + 1; // s1 if (y0 < 0) y0 = 0; // L9 int x1 = x0 + 11; // s2 int y1 = y; // s3 int color = colors[note_octave >> 4 && 0xf]; // s4 draw_rect(0, y0, x0 - 1, y1, 0xfff); draw_rect(x0, y0, x1, y1, color); draw_rect(x1 + 1, y0, 639, y1, 0xfff); } void draw_octave_indicator(int octave) { if (octave == 0) { draw_rect(0, 406, 639, 411, 0xfff); return; } // L10 int x0 = indicator_x_lut[0x10 | octave]; // s0 int x1 = x0 + 167; // s1 if (x1 > 631) x1 = 631; // L11 draw_rect(0, 406, x0 - 1, 411, 0xfff); draw_rect(x0, 406, x1, 411, 0x39e); draw_rect(x1 + 1, 406, 639, 411, 0xfff); } int main() { while (*(int *)0xD0000000 & 0x80000000 == 0) ; draw_rect(0, 0, 639, 479, 0xfff); draw_image(8, 412, 631, 479, 0); int cur_octave = 4; // s0 int last_key_ready = 0; // s1 int last_key_code = 0; // s2 int note_pointer = 0; // s3 *(int *)0x30000000 = score[note_pointer] >> 8; for (;;) { int cur_length = *(int *)0x30000000; // t0 if (cur_length == 0) { note_pointer++; cur_length = score[note_pointer] >> 8; *(int *)0x30000000 = cur_length; } // L4 int cur_lenoc = score[note_pointer] & 0xFF; // s4 int cur_y = 405; // s5 int length = cur_length / 4; // a2 draw_indicator(cur_lenoc, cur_y, length); cur_y -= length; int note_cursor = note_pointer + 1; // s6 while (cur_y > 0) // L5 { int lenoc = score[note_cursor]; // t0 int length = (lenoc >> 8) / 4; // a2 draw_indicator(lenoc & 0xFF, cur_y, length); cur_y -= length; note_cursor++; } // L6 draw_octave_indicator(cur_octave); int pitch_gen_output = 0; // t3 if (*(int *)0xf0000000 & 1 == 1) // t4 { pitch_gen_output = cur_lenoc; } else // L7 { int ps2_data = *(int *)0xD0000000; // t0 int key_ready = ps2_data & 0x80000000; // t1 int key_code = ps2_data & 0x000000FF; // t2 if (key_ready) { pitch_gen_output = keycode_octave_lut[key_code] + cur_octave; } else if (last_key_ready) // L1 { if (last_key_code == 0x5A) { cur_octave = (cur_octave + 1) % 8; } // L2 else if (last_key_code == 0x59) { cur_octave = (cur_octave + 7) % 8; } } // L3 last_key_ready = key_ready; last_key_code = key_code; } // L8 *(int *)0x20000000 = pitch_gen_output; } }
2.125
2
2024-11-18T21:47:10.729813+00:00
2013-09-25T00:08:01
3f5140349cbebfade514f968111e1224e912c626
{ "blob_id": "3f5140349cbebfade514f968111e1224e912c626", "branch_name": "refs/heads/master", "committer_date": "2013-09-25T00:08:01", "content_id": "f7adef43d4730b6a52db0b19ab659179e3ed6c23", "detected_licenses": [ "MIT" ], "directory_id": "065a5dca8c4b50107e92390f527cca5fcb8df5c2", "extension": "h", "filename": "PSPLBuffer.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": 973, "license": "MIT", "license_type": "permissive", "path": "/include/PSPL/PSPLBuffer.h", "provenance": "stackv2-0130.json.gz:53241", "repo_name": "jackoalan/PSPL", "revision_date": "2013-09-25T00:08:01", "revision_id": "cfe71d1c0c46d11a849b729a04cb928b3b20b3b4", "snapshot_id": "8cf19f6d7fc2e39f0a71f8b086830a43df8885ca", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jackoalan/PSPL/cfe71d1c0c46d11a849b729a04cb928b3b20b3b4/include/PSPL/PSPLBuffer.h", "visit_date": "2021-01-22T13:42:13.325042" }
stackv2
// // Buffer.h // PSPL // // Created by Jack Andersen on 5/1/13. // // #ifndef PSPL_Buffer_h #define PSPL_Buffer_h #include <stdlib.h> /* This API provides a common way to maintain an externally "owned" * append-mutable string buffer (using a common struct to maintain buffer state). */ /* Any error conditions are handled by `pspl_error` * (resulting in program termination) */ /* First, the buffer state structure */ typedef struct { size_t buf_cap; char* buf; char* buf_cur; } pspl_buffer_t; /* Init a buffer with specified size */ void pspl_buffer_init(pspl_buffer_t* buf, size_t cap); /* Append a copied string */ void pspl_buffer_addstr(pspl_buffer_t* buf, const char* str); void pspl_buffer_addstrn(pspl_buffer_t* buf, const char* str, size_t str_len); /* Append a single character */ void pspl_buffer_addchar(pspl_buffer_t* buf, char ch); /* Free memory used by the buffer */ void pspl_buffer_free(pspl_buffer_t* buf); #endif
2.5
2
2024-11-18T21:47:11.232578+00:00
2016-02-26T13:04:19
069a01779134120e05e5ab0fd0d8f28b77c7f060
{ "blob_id": "069a01779134120e05e5ab0fd0d8f28b77c7f060", "branch_name": "refs/heads/master", "committer_date": "2016-02-26T13:04:19", "content_id": "b8cd96310a2abaea6c226423c39cf53d15a7200a", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "27978c970f847255f642b415e91a84f577b67e2c", "extension": "c", "filename": "test_ietf.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": 2695, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/tests/schema/yin/test_ietf.c", "provenance": "stackv2-0130.json.gz:53371", "repo_name": "VitaliySh/libyang", "revision_date": "2016-02-26T13:04:19", "revision_id": "8c203a6677bff771c42568d8bf32ecf6c80ed09f", "snapshot_id": "2152568713166a14c185d92d991434f660dcb094", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/VitaliySh/libyang/8c203a6677bff771c42568d8bf32ecf6c80ed09f/tests/schema/yin/test_ietf.c", "visit_date": "2020-05-09T15:55:59.553977" }
stackv2
/** * \file test_ietf.c * \author Radek Krejci <[email protected]> * \brief libyang tests - loading standard IETF modules * * Copyright (c) 2016 CESNET, z.s.p.o. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of the Company nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * */ #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <pthread.h> #include <setjmp.h> #include <stdarg.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <cmocka.h> #include "../../../src/libyang.h" #include "../../config.h" #define SCHEMA_FOLDER TESTS_DIR"/schema/yin/ietf" static int setup_ctx(void **state) { //ly_verb(LY_LLVRB); (*state) = ly_ctx_new(SCHEMA_FOLDER); if (!(*state)) { return -1; } return 0; } static int teardown_ctx(void **state) { ly_ctx_destroy((struct ly_ctx *)(*state), NULL); (*state) = NULL; return 0; } static void test_modules(void **state) { struct ly_ctx *ctx = *state; DIR *dir; struct dirent *file; size_t flen; dir = opendir(SCHEMA_FOLDER); if (!dir) { fprintf(stderr, "unable to open \"%s\" folder.\n", SCHEMA_FOLDER); fail(); } chdir(SCHEMA_FOLDER); while ((file = readdir(dir))) { flen = strlen(file->d_name); if (strcmp(&file->d_name[flen - 4], ".yin")) { /* skip non-YIN files */ continue; } if (!strncmp(file->d_name, "ietf-snmp-", 10)) { /* skip ietf-snmp's submodules */ continue; } fprintf(stdout, "Loading \"%s\" module ... ", file->d_name); if (!lys_parse_path(ctx, file->d_name, LYS_IN_YIN)) { fprintf(stdout, "failed\n"); closedir(dir); fail(); } fprintf(stdout, "ok\n"); } closedir(dir); } int main(void) { const struct CMUnitTest cmut[] = { cmocka_unit_test_setup_teardown(test_modules, setup_ctx, teardown_ctx) }; return cmocka_run_group_tests(cmut, NULL, NULL); }
2.140625
2
2024-11-18T21:47:11.338678+00:00
2017-04-13T23:58:33
5cef6dace9aadfd20c79206c8807ce7e8e5d0e0b
{ "blob_id": "5cef6dace9aadfd20c79206c8807ce7e8e5d0e0b", "branch_name": "refs/heads/master", "committer_date": "2017-04-13T23:58:33", "content_id": "636a318959e9bf50b3d9351dedea82d77437e361", "detected_licenses": [ "MIT" ], "directory_id": "9c8da28093c5c8cb9ca5a6980f94bfb6b1cacf9a", "extension": "c", "filename": "arch.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": 14496, "license": "MIT", "license_type": "permissive", "path": "/src/kernel/x86/arch.c", "provenance": "stackv2-0130.json.gz:53500", "repo_name": "matrix-1996/fudge", "revision_date": "2017-04-13T23:58:33", "revision_id": "2e7883a8b4ba9c02e505859473ea07808328b407", "snapshot_id": "3ab01baafd152efd8d8374052c70f975d69029b4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/matrix-1996/fudge/2e7883a8b4ba9c02e505859473ea07808328b407/src/kernel/x86/arch.c", "visit_date": "2021-01-19T23:19:54.951481" }
stackv2
#include <fudge.h> #include <kernel.h> #include "cpu.h" #include "arch.h" #include "gdt.h" #include "idt.h" #include "tss.h" #include "isr.h" #include "mmu.h" #define GDTDESCRIPTORS 6 #define IDTDESCRIPTORS 256 #define TSSDESCRIPTORS 1 #define KERNELSTACK 0x00400000 #define TASKSTACK 0x80000000 #define CONTAINERMMUBASE 0x00400000 #define CONTAINERMMUCOUNT 8 #define TASKMMUBASE 0x00480000 #define TASKMMUCOUNT 4 #define PHYSBASE 0x01000000 #define CODESIZE 0x00080000 #define STACKSIZE 0x00008000 static struct { struct gdt_pointer pointer; struct gdt_descriptor descriptors[GDTDESCRIPTORS]; } gdt; static struct { struct idt_pointer pointer; struct idt_descriptor descriptors[IDTDESCRIPTORS]; } idt; static struct { struct tss_pointer pointer; struct tss_descriptor descriptors[TSSDESCRIPTORS]; } tss; static struct { unsigned short kcode; unsigned short kstack; unsigned short ucode; unsigned short ustack; unsigned short tlink; } selector; static struct cpu_general registers[KERNEL_TASKS]; static struct arch_context current; static struct mmu_directory *getdirectory(unsigned int index, unsigned int base, unsigned int count) { return (struct mmu_directory *)base + index * count; } static struct mmu_table *gettable(unsigned int index, unsigned int base, unsigned int count) { return (struct mmu_table *)base + index * count + 1; } static void copymap(struct container *container, struct task *task) { struct mmu_directory *cdirectory = getdirectory(container->id, CONTAINERMMUBASE, CONTAINERMMUCOUNT); struct mmu_directory *tdirectory = getdirectory(task->id, TASKMMUBASE, TASKMMUCOUNT); memory_copy(tdirectory, cdirectory, sizeof (struct mmu_directory)); } static void mapcontainer(struct container *container) { struct mmu_directory *directory = getdirectory(container->id, CONTAINERMMUBASE, CONTAINERMMUCOUNT); struct mmu_table *table = gettable(container->id, CONTAINERMMUBASE, CONTAINERMMUCOUNT); mmu_map(directory, &table[0], 0x00000000, 0x00000000, 0x00400000, MMU_TFLAG_PRESENT | MMU_TFLAG_WRITEABLE, MMU_PFLAG_PRESENT | MMU_PFLAG_WRITEABLE); mmu_map(directory, &table[1], 0x00400000, 0x00400000, 0x00400000, MMU_TFLAG_PRESENT | MMU_TFLAG_WRITEABLE, MMU_PFLAG_PRESENT | MMU_PFLAG_WRITEABLE); mmu_map(directory, &table[2], 0x00800000, 0x00800000, 0x00400000, MMU_TFLAG_PRESENT | MMU_TFLAG_WRITEABLE, MMU_PFLAG_PRESENT | MMU_PFLAG_WRITEABLE); mmu_map(directory, &table[3], 0x00C00000, 0x00C00000, 0x00400000, MMU_TFLAG_PRESENT | MMU_TFLAG_WRITEABLE, MMU_PFLAG_PRESENT | MMU_PFLAG_WRITEABLE); } static void maptask(struct task *task, unsigned int code, unsigned int stack) { struct mmu_directory *directory = getdirectory(task->id, TASKMMUBASE, TASKMMUCOUNT); struct mmu_table *table = gettable(task->id, TASKMMUBASE, TASKMMUCOUNT); mmu_map(directory, &table[0], PHYSBASE + task->id * (CODESIZE + STACKSIZE), code, CODESIZE, MMU_TFLAG_PRESENT | MMU_TFLAG_WRITEABLE | MMU_TFLAG_USERMODE, MMU_PFLAG_PRESENT | MMU_PFLAG_WRITEABLE | MMU_PFLAG_USERMODE); mmu_map(directory, &table[1], PHYSBASE + task->id * (CODESIZE + STACKSIZE) + CODESIZE, stack, STACKSIZE, MMU_TFLAG_PRESENT | MMU_TFLAG_WRITEABLE | MMU_TFLAG_USERMODE, MMU_PFLAG_PRESENT | MMU_PFLAG_WRITEABLE | MMU_PFLAG_USERMODE); } static void activate(struct task *task) { struct mmu_directory *directory = getdirectory(task->id, TASKMMUBASE, TASKMMUCOUNT); mmu_setdirectory(directory); } static void saveregisters(struct task *task, struct cpu_general *general) { memory_copy(&registers[task->id], general, sizeof (struct cpu_general)); } static void loadregisters(struct task *task, struct cpu_general *general) { memory_copy(general, &registers[task->id], sizeof (struct cpu_general)); } static unsigned int spawn(struct container *container, struct task *task, void *stack) { struct task *next = kernel_findinactivetask(); if (!next) return 0; copymap(container, next); kernel_copyservices(task, next); if (!kernel_setupbinary(next, TASKSTACK)) return 0; kernel_activatetask(next); return 1; } static unsigned int despawn(struct container *container, struct task *task, void *stack) { kernel_inactivatetask(task); return 1; } void arch_setinterrupt(unsigned char index, void (*callback)(void)) { idt_setdescriptor(&idt.pointer, index, callback, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); } void arch_setmap(unsigned char index, unsigned int paddress, unsigned int vaddress, unsigned int size) { struct mmu_directory *directory = getdirectory(current.container->id, CONTAINERMMUBASE, CONTAINERMMUCOUNT); struct mmu_table *table = gettable(current.container->id, CONTAINERMMUBASE, CONTAINERMMUCOUNT); mmu_map(directory, &table[index], paddress, vaddress, size, MMU_TFLAG_PRESENT | MMU_TFLAG_WRITEABLE, MMU_PFLAG_PRESENT | MMU_PFLAG_WRITEABLE); mmu_setdirectory(directory); } unsigned int arch_call(unsigned int index, void *stack, unsigned int rewind) { current.task->state.rewind = rewind; return abi_call(index, current.container, current.task, stack); } struct arch_context *arch_schedule(struct cpu_general *general, unsigned int ip, unsigned int sp) { if (current.task) { current.task->state.ip = ip; current.task->state.sp = sp; saveregisters(current.task, general); } current.task = kernel_findactivetask(); if (current.task) { if (current.task->state.status == TASK_STATUS_UNBLOCKED) { kernel_activatetask(current.task); task_setstate(current.task, current.task->state.ip - current.task->state.rewind, current.task->state.sp); } loadregisters(current.task, general); activate(current.task); } return &current; } unsigned short arch_resume(struct cpu_general *general, struct cpu_interrupt *interrupt) { struct arch_context *context = arch_schedule(general, interrupt->eip.value, interrupt->esp.value); if (context->task) { interrupt->cs.value = selector.ucode; interrupt->ss.value = selector.ustack; interrupt->eip.value = context->task->state.ip; interrupt->esp.value = context->task->state.sp; } else { interrupt->cs.value = selector.kcode; interrupt->ss.value = selector.kstack; interrupt->eip.value = context->ip; interrupt->esp.value = context->sp; } return interrupt->ss.value; } unsigned short arch_zero(struct cpu_general general, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: divide by zero"); if (interrupt.cs.value == selector.ucode) kernel_inactivatetask(current.task); return arch_resume(&general, &interrupt); } unsigned short arch_debug(struct cpu_general general, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: debug"); return arch_resume(&general, &interrupt); } unsigned short arch_nmi(struct cpu_general general, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: non-maskable interrupt"); return arch_resume(&general, &interrupt); } unsigned short arch_breakpoint(struct cpu_general general, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: breakpoint"); return arch_resume(&general, &interrupt); } unsigned short arch_overflow(struct cpu_general general, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: overflow"); return arch_resume(&general, &interrupt); } unsigned short arch_bound(struct cpu_general general, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: bound range exceeded"); return arch_resume(&general, &interrupt); } unsigned short arch_opcode(struct cpu_general general, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: invalid opcode"); return arch_resume(&general, &interrupt); } unsigned short arch_device(struct cpu_general general, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: device unavailable"); return arch_resume(&general, &interrupt); } unsigned short arch_doublefault(struct cpu_general general, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: double fault"); return arch_resume(&general, &interrupt); } unsigned short arch_tss(struct cpu_general general, unsigned int selector, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: invalid tss"); return arch_resume(&general, &interrupt); } unsigned short arch_segment(struct cpu_general general, unsigned int selector, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: segment not present"); return arch_resume(&general, &interrupt); } unsigned short arch_stack(struct cpu_general general, unsigned int selector, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: stack segment fault"); return arch_resume(&general, &interrupt); } unsigned short arch_generalfault(struct cpu_general general, unsigned int selector, struct cpu_interrupt interrupt) { DEBUG(DEBUG_INFO, "exception: general fault"); return arch_resume(&general, &interrupt); } unsigned short arch_pagefault(struct cpu_general general, unsigned int type, struct cpu_interrupt interrupt) { unsigned int address = cpu_getcr2(); DEBUG(DEBUG_INFO, "exception: page fault"); if (current.task) { address = current.task->format->findbase(&current.task->node, address); if (address) { maptask(current.task, address, TASKSTACK - STACKSIZE); current.task->format->copyprogram(&current.task->node); } else { kernel_inactivatetask(current.task); } } return arch_resume(&general, &interrupt); } unsigned short arch_syscall(struct cpu_general general, struct cpu_interrupt interrupt) { general.eax.value = arch_call(general.eax.value, interrupt.esp.reference, 7); return arch_resume(&general, &interrupt); } static void leave(void) { struct cpu_interrupt interrupt; interrupt.cs.value = selector.ucode; interrupt.ss.value = selector.ustack; interrupt.eip.value = current.task->state.ip; interrupt.esp.value = current.task->state.sp; interrupt.eflags.value = cpu_geteflags() | CPU_FLAGS_IF; cpu_leave(interrupt); } void arch_setup(struct service_backend *backend) { gdt_initpointer(&gdt.pointer, GDTDESCRIPTORS, gdt.descriptors); idt_initpointer(&idt.pointer, IDTDESCRIPTORS, idt.descriptors); tss_initpointer(&tss.pointer, TSSDESCRIPTORS, tss.descriptors); selector.kcode = gdt_setdescriptor(&gdt.pointer, 0x01, 0x00000000, 0xFFFFFFFF, GDT_ACCESS_PRESENT | GDT_ACCESS_ALWAYS1 | GDT_ACCESS_RW | GDT_ACCESS_EXECUTE, GDT_FLAG_GRANULARITY | GDT_FLAG_32BIT); selector.kstack = gdt_setdescriptor(&gdt.pointer, 0x02, 0x00000000, 0xFFFFFFFF, GDT_ACCESS_PRESENT | GDT_ACCESS_ALWAYS1 | GDT_ACCESS_RW, GDT_FLAG_GRANULARITY | GDT_FLAG_32BIT); selector.ucode = gdt_setdescriptor(&gdt.pointer, 0x03, 0x00000000, 0xFFFFFFFF, GDT_ACCESS_PRESENT | GDT_ACCESS_RING3 | GDT_ACCESS_ALWAYS1 | GDT_ACCESS_RW | GDT_ACCESS_EXECUTE, GDT_FLAG_GRANULARITY | GDT_FLAG_32BIT); selector.ustack = gdt_setdescriptor(&gdt.pointer, 0x04, 0x00000000, 0xFFFFFFFF, GDT_ACCESS_PRESENT | GDT_ACCESS_RING3 | GDT_ACCESS_ALWAYS1 | GDT_ACCESS_RW, GDT_FLAG_GRANULARITY | GDT_FLAG_32BIT); selector.tlink = gdt_setdescriptor(&gdt.pointer, 0x05, (unsigned int)tss.pointer.descriptors, (unsigned int)tss.pointer.descriptors + tss.pointer.limit, GDT_ACCESS_PRESENT | GDT_ACCESS_EXECUTE | GDT_ACCESS_ACCESSED, GDT_FLAG_32BIT); idt_setdescriptor(&idt.pointer, 0x00, isr_zero, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x01, isr_debug, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x02, isr_nmi, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x03, isr_breakpoint, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT | IDT_FLAG_RING3); idt_setdescriptor(&idt.pointer, 0x04, isr_overflow, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x05, isr_bound, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x06, isr_opcode, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x07, isr_device, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x08, isr_doublefault, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x0A, isr_tss, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x0B, isr_segment, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x0C, isr_stack, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x0D, isr_generalfault, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x0E, isr_pagefault, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT); idt_setdescriptor(&idt.pointer, 0x80, isr_syscall, selector.kcode, IDT_FLAG_PRESENT | IDT_FLAG_TYPE32INT | IDT_FLAG_RING3); tss_setdescriptor(&tss.pointer, 0x00, selector.kstack, KERNELSTACK); cpu_setgdt(&gdt.pointer, selector.kcode, selector.kstack); cpu_setidt(&idt.pointer); cpu_settss(selector.tlink); kernel_setup(); current.container = kernel_setupcontainers(); current.task = kernel_setuptasks(); current.ip = (unsigned int)cpu_halt; current.sp = KERNELSTACK; kernel_setupservices(); kernel_setupramdisk(current.container, current.task, backend); mapcontainer(current.container); copymap(current.container, current.task); kernel_copyservices(current.task, current.task); kernel_setupbinary(current.task, TASKSTACK); kernel_activatetask(current.task); activate(current.task); mmu_setup(); abi_setup(spawn, despawn); leave(); }
2.25
2
2024-11-18T21:47:11.670273+00:00
2019-01-13T13:13:43
97d5e50039f784042712774d11d0542f41769b0c
{ "blob_id": "97d5e50039f784042712774d11d0542f41769b0c", "branch_name": "refs/heads/master", "committer_date": "2019-01-13T13:13:43", "content_id": "2bea2381e0e6959157245e794ded387bf4b1346f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "692a7d984f1ea1cb912983803547454e295fdb35", "extension": "c", "filename": "slob.c", "fork_events_count": 1, "gha_created_at": "2018-09-24T06:53:32", "gha_event_created_at": "2019-01-11T02:04:52", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 150065105, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9007, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/kernel/mm/slob.c", "provenance": "stackv2-0130.json.gz:53759", "repo_name": "sjn4048/OS_Exp", "revision_date": "2019-01-13T13:13:43", "revision_id": "2206eff17100b4be604b86c7d80b31a5ca0f1e45", "snapshot_id": "5f7132a11e503670e6c0d830a7ae4d902a550c11", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/sjn4048/OS_Exp/2206eff17100b4be604b86c7d80b31a5ca0f1e45/kernel/mm/slob.c", "visit_date": "2020-03-29T15:28:34.230292" }
stackv2
#include <arch.h> #include <driver/vga.h> #include <zjunix/slob.h> #include <zjunix/utils.h> #include <zjunix/buddy.h> #include <zjunix/slab.h> #include <zjunix/memory.h> struct slob_block { int units; struct slob_block *next; }; typedef struct slob_block slob_t; #ifdef SLOB_SINGLE static slob_t arena = {.next = &arena, .units = 1}; static slob_t *slobfree = &arena; #else #define SLOB_BREAK1 256 #define SLOB_BREAK2 1024 static slob_t free_slob_small = {.next = &free_slob_small, .units = 1}; static slob_t free_slob_medium = {.next = &free_slob_medium, .units = 1}; static slob_t free_slob_large = {.next = &free_slob_large, .units = 1}; static slob_t *small_cur = &free_slob_small; static slob_t *medium_cur = &free_slob_medium; static slob_t *large_cur = &free_slob_large; static slob_t *slobfree = &free_slob_small; #endif #define SLOB_UNIT sizeof(slob_t) #define SLOB_UNITS(size) (((size) + (SLOB_UNIT)-1) / (SLOB_UNIT)) typedef struct bigblock { int order; void *pages; struct bigblock *next; } bigblock_t; static bigblock_t *bigblocks; extern void init_slob() { // TODO } static void slob_free(void *block, int size) { slob_t *cur, *b = (slob_t *)block; if (!block) { return; } if (size) { b->units = SLOB_UNITS(size); } /* Find reinsertion point */ for (cur = slobfree; !(b > cur && b < cur->next); cur = cur->next) { if (cur >= cur->next && (b > cur || b < cur->next)) { break; } } if (b + b->units == cur->next) { b->units += cur->next->units; b->next = cur->next->next; } else { b->next = cur->next; } if (cur + cur->units == b) { cur->units += b->units; cur->next = b->next; } else { cur->next = b; } slobfree = cur; } static void *slob_alloc(unsigned int size) { #ifdef SLOB_DEBUG kernel_printf("enter slob_alloc. Size: %d\n", size); kernel_getchar(); #endif // SLOB_DEBUG slob_t *prev, *cur, *aligned = 0; int delta = 0, units = SLOB_UNITS(size); #ifdef SLOB_SINGLE prev = slobfree; #else // if use multiple slobs if (size < SLOB_BREAK1) { #ifdef SLOB_DEBUG kernel_printf("Use small slob to handle.\n"); kernel_getchar(); #endif // SLOB_DEBUG slobfree = &free_slob_small; } else if (size < SLOB_BREAK2) { #ifdef SLOB_DEBUG kernel_printf("Use medium slob to handle.\n"); kernel_getchar(); #endif // SLOB_DEBUG slobfree = &free_slob_medium; } else { #ifdef SLOB_DEBUG kernel_printf("Use large slob to handle.\n"); kernel_getchar(); #endif // SLOB_DEBUG slobfree = &free_slob_large; } #endif for (cur = prev->next;; prev = cur, cur = cur->next) { #ifdef SLOB_DEBUG kernel_printf("Cur: %x\tPrev: %x\t\n", cur, prev); kernel_printf("cur->units: %d\tunits: %d\tdelta: %d\n", cur->units, units, delta); kernel_getchar(); #endif // SLOB_DEBUG if (cur->units >= units + delta) { #ifdef SLOB_DEBUG kernel_printf("room is enough.\n"); kernel_getchar(); #endif // SLOB_DEBUG \ // if room is enough if (delta) { // need to fragment head to align? aligned->units = cur->units - delta; aligned->next = cur->next; cur->next = aligned; cur->units = delta; prev = cur; cur = aligned; } if (cur->units == units) { #ifdef SLOB_DEBUG kernel_printf("exact fit.\n"); kernel_getchar(); #endif // SLOB_DEBUG \ // if exact fit, unlink prev->next = cur->next; } else { // make fragment prev->next = cur + units; prev->next->units = cur->units - units; prev->next->next = cur->next; cur->units = units; #ifdef SLOB_DEBUG kernel_printf("After fragment.\n"); kernel_printf("prev->next: %x, prev->next->units: %d, prev->next->next: %x, cur->units: %d", prev->next, prev->next->units, prev->next->next, cur->units); kernel_getchar(); #endif // SLOB_DEBUG } slobfree = prev; #ifdef SLOB_DEBUG kernel_printf("slob_alloc returns %x.\n", cur); kernel_getchar(); #endif // SLOB_DEBUG return cur; } if (cur == slobfree) { // trying to shrink arena if (size == PAGE_SIZE) { #ifdef SLOB_DEBUG kernel_printf("tring to shrink arena. returns 0 as size == PAGE_SIZE.\n"); kernel_getchar(); #endif // SLOB_DEBUG return 0; } cur = (slob_t *)alloc_pages(1); #ifdef SLOB_DEBUG kernel_printf("alloc new page %x for cur. Page no: %d\n", cur, ((unsigned int)cur - KERNEL_ENTRY) >> PAGE_SHIFT); kernel_getchar(); #endif // SLOB_DEBUG if (!cur) { return 0; } #ifdef SLOB_DEBUG kernel_printf("call slob_free for cur.\n"); kernel_getchar(); #endif // SLOB_DEBUG slob_free(cur, PAGE_SIZE); cur = slobfree; } } } static int find_order(int size) { int order = 0; for (; size > 4096; size >>= 1) order++; return order; } void *slob_kmalloc(unsigned int size) { slob_t *m; bigblock_t *bb; #ifdef SLOB_DEBUG kernel_printf("kmalloc %d memory in slob.\n", size, PAGE_SIZE, SLOB_UNIT, PAGE_SIZE - SLOB_UNIT); kernel_getchar(); #endif // SLOB_DEBUG // if the size is not bigger than the page size if (size < PAGE_SIZE - SLOB_UNIT) { #ifdef SLOB_DEBUG kernel_printf("Handle malloc in slob.\n"); kernel_getchar(); #endif // SLOB_DEBUG m = slob_alloc(size + SLOB_UNIT); return m ? (void *)(m + 1) : 0; } // else call buddy to solve this #ifdef SLOB_DEBUG kernel_printf("Handle malloc in buddy instead.\n"); kernel_getchar(); #endif // SLOB_DEBUG bb = slob_alloc(sizeof(bigblock_t)); if (!bb) { return 0; } // calculate the order, which is temporarily not used. size = UPPER_ALLIGN(size, PAGE_SIZE); bb->order = find_order(size); bb->pages = alloc_pages(size >> PAGE_SHIFT); if (bb->pages) { bb->next = bigblocks; bigblocks = bb; return (void *)(KERNEL_ENTRY | (unsigned int)bb->pages); }; slob_free(bb, sizeof(bigblock_t)); return 0; } void *slob_kzalloc(unsigned int size) { void *ret = slob_kmalloc(size); if (ret) kernel_memset(ret, 0, size); return ret; } void slob_kfree(const void *block) { bigblock_t *bb, **last = &bigblocks; if (!block) { return; } if (!((unsigned int)block & (PAGE_SIZE - 1))) { /* might be on the big block list */ for (bb = bigblocks; bb; last = &bb->next, bb = bb->next) { if (bb->pages == block) { *last = bb->next; free_pages((void *)block, bb->order); slob_free(bb, sizeof(bigblock_t)); return; } } } slob_free((slob_t *)block - 1, 0); return; } unsigned int slob_ksize(const void *block) { bigblock_t *bb; if (!block) return 0; if (!((unsigned int)block & (PAGE_SIZE - 1))) { for (bb = bigblocks; bb; bb = bb->next) { if (bb->pages == block) { return PAGE_SIZE << bb->order; } } } return ((slob_t *)block - 1)->units * SLOB_UNIT; } struct kmem_cache_s { unsigned int size, align; const char *name; void (*ctor)(); void (*dtor)(); }; kmem_cache_t *kmem_cache_create(char *name, unsigned int size, unsigned int align, void (*ctor)(), void (*dtor)()) { kmem_cache_t *c; c = slob_alloc(sizeof(kmem_cache_t)); if (c) { c->name = name; c->size = size; // c->ctor = ctor; // c->dtor = dtor; /* ignore alignment */ // c->align = 0; // if (c->align < align) // c->align = align; } return c; } int kmem_cache_destroy(kmem_cache_t *c) { slob_free(c, sizeof(kmem_cache_t)); return 0; } void *kmem_cache_alloc(kmem_cache_t *c) { void *b; if (c->size < PAGE_SIZE) b = slob_alloc(c->size); else b = (void *)__alloc_pages(find_order(c->size)); return b; } void kmem_cache_free(kmem_cache_t *c, void *b) { if (c->size < PAGE_SIZE) slob_free(b, c->size); else free_pages(b, find_order(c->size)); } unsigned int kmem_cache_size(kmem_cache_t *c) { return c->size; } const char *kmem_cache_name(kmem_cache_t *c) { return c->name; } void kmem_cache_init(void) { void *p = slob_alloc(PAGE_SIZE); if (p) free_pages(p, 0); }
2.578125
3
2024-11-18T21:47:12.013501+00:00
2022-07-28T18:42:05
d7c6e0b3276c78c5795bc83a6fde269966f6c9dd
{ "blob_id": "d7c6e0b3276c78c5795bc83a6fde269966f6c9dd", "branch_name": "refs/heads/master", "committer_date": "2022-07-28T18:42:05", "content_id": "f1d5b075f11817d930397bbd9ed96278750d5237", "detected_licenses": [ "MIT" ], "directory_id": "18e9c7d661584e1c7698670d60e0588ef353ebe1", "extension": "h", "filename": "hashcons.h", "fork_events_count": 0, "gha_created_at": "2020-02-13T17:42:36", "gha_event_created_at": "2020-03-13T10:46:13", "gha_language": "C", "gha_license_id": "MIT", "github_id": 240323111, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5543, "license": "MIT", "license_type": "permissive", "path": "/pkg/urbit/include/ur/hashcons.h", "provenance": "stackv2-0130.json.gz:53889", "repo_name": "botter-nidnul/urbit", "revision_date": "2022-07-28T18:42:05", "revision_id": "04645cbf08e2fb592975606adae3a20a2caf11bc", "snapshot_id": "0b1ec5d7e67be473dfd8ddde176d5b421e177be7", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/botter-nidnul/urbit/04645cbf08e2fb592975606adae3a20a2caf11bc/pkg/urbit/include/ur/hashcons.h", "visit_date": "2022-08-17T05:45:58.196564" }
stackv2
#ifndef UR_HASHCONS_H #define UR_HASHCONS_H #include <inttypes.h> #include <assert.h> #include <limits.h> #include <stdio.h> #include "ur/defs.h" /* ** 64-bit noun references, with the top 2 bits reserved for type tags. */ typedef uint64_t ur_nref; typedef enum { ur_direct = 0, ur_iatom = 1, ur_icell = 2, } ur_tag; #define ur_nref_tag(ref) ( ref >> 62 ) #define ur_nref_idx(ref) ur_mask_62(ref) /* ** 31-bit, non-zero, murmur3-based noun hash. */ typedef uint32_t ur_mug; /* ** associative structures (dictionaries) of noun references, ** distributed by mug across fixed-size buckets (pails), ** reallocated with fibonacci growth once a bucket is full. ** ** - ur_dict_t: set of noun references ** - ur_dict32_t: map from noun reference to uint32 ** - ur_dict32_t: map from noun reference to uint64 */ #define ur_pail_max 10 typedef struct ur_pail32_s { ur_nref refs[ur_pail_max]; uint32_t vals[ur_pail_max]; } ur_pail32_t; typedef struct ur_dict32_s { uint64_t prev; uint64_t size; uint8_t *fills; ur_pail32_t *buckets; } ur_dict32_t; typedef struct ur_pail64_s { ur_nref refs[ur_pail_max]; uint64_t vals[ur_pail_max]; } ur_pail64_t; typedef struct ur_dict64_s { uint64_t prev; uint64_t size; uint8_t *fills; ur_pail64_t *buckets; } ur_dict64_t; typedef struct ur_pail_s { ur_nref refs[ur_pail_max]; } ur_pail_t; typedef struct ur_dict_s { uint64_t prev; uint64_t size; uint8_t *fills; ur_pail_t *buckets; } ur_dict_t; /* ** cells are hash-consed, atoms are deduplicated (byte-array comparison), ** mug hashes are stored, and noun references are unique within a root. */ typedef struct ur_cells_s { ur_dict_t dict; uint64_t prev; uint64_t size; uint64_t fill; ur_mug *mugs; ur_nref *heads; ur_nref *tails; } ur_cells_t; typedef struct ur_atoms_s { ur_dict_t dict; uint64_t prev; uint64_t size; uint64_t fill; ur_mug *mugs; uint8_t **bytes; uint64_t *lens; } ur_atoms_t; typedef struct ur_root_s { ur_cells_t cells; ur_atoms_t atoms; } ur_root_t; /* ** a vector of noun references. */ typedef struct ur_nvec_s { uint64_t fill; ur_nref* refs; } ur_nvec_t; /* ** opaque handle for repeated traversal. */ typedef struct ur_walk_fore_s ur_walk_fore_t; /* ** type-specific dictionary operations. ** ** NB: [r] is only used to retrieve the stored mug of cells and ** indirect atoms. If all references are direct atoms (62-bits or less), ** [r] can be null. This option is used extensively in cue (de-serialization) ** implementations, where the dictionary keys are bit-cursors. */ void ur_dict32_grow(ur_root_t *r, ur_dict32_t *dict, uint64_t prev, uint64_t size); ur_bool_t ur_dict32_get(ur_root_t *r, ur_dict32_t *dict, ur_nref ref, uint32_t *out); void ur_dict32_put(ur_root_t *r, ur_dict32_t *dict, ur_nref ref, uint32_t val); void ur_dict32_wipe(ur_dict32_t *dict); void ur_dict64_grow(ur_root_t *r, ur_dict64_t *dict, uint64_t prev, uint64_t size); ur_bool_t ur_dict64_get(ur_root_t *r, ur_dict64_t *dict, ur_nref ref, uint64_t *out); void ur_dict64_put(ur_root_t *r, ur_dict64_t *dict, ur_nref ref, uint64_t val); void ur_dict64_wipe(ur_dict64_t *dict); void ur_dict_grow(ur_root_t *r, ur_dict_t *dict, uint64_t prev, uint64_t size); ur_bool_t ur_dict_get(ur_root_t *r, ur_dict_t *dict, ur_nref ref); void ur_dict_put(ur_root_t *r, ur_dict_t *dict, ur_nref ref); void ur_dict_wipe(ur_dict_t *dict); /* ** free the buckets of any dictionary (cast to ur_dict_t*). */ void ur_dict_free(ur_dict_t *dict); /* ** measure the bloq (binary-exponent) length of an atom in [r] */ uint64_t ur_met(ur_root_t *r, uint8_t bloq, ur_nref ref); /* ** find or allocate an atom in [r] ** ** unsafe variant is unsafe wrt allocation (byte arrays must be ** allocated with system malloc) and trailing null bytes (not allowed). */ ur_nref ur_coin_bytes_unsafe(ur_root_t *r, uint64_t len, uint8_t *byt); ur_nref ur_coin_bytes(ur_root_t *r, uint64_t len, uint8_t *byt); ur_nref ur_coin64(ur_root_t *r, uint64_t n); /* ** find or construct a cell in [r] */ ur_nref ur_cons(ur_root_t *r, ur_nref hed, ur_nref tal); /* ** calculate the mug of [ref], or produce the stored value in [r]. */ ur_mug ur_nref_mug(ur_root_t *r, ur_nref ref); /* ** initialize a noun arena (root). */ ur_root_t* ur_root_init(void); /* ** print root details to [f] */ void ur_root_info(FILE *f, ur_root_t *r); /* ** dispose all allocations in [r] */ void ur_root_free(ur_root_t *r); /* ** initialize or dispose a vector of noun references */ void ur_nvec_init(ur_nvec_t *v, uint64_t size); void ur_nvec_free(ur_nvec_t *v); /* ** depth-first, pre-order noun traversal, cells can short-circuit. */ void ur_walk_fore(ur_root_t *r, ur_nref ref, void *v, void (*atom)(ur_root_t*, ur_nref, void*), ur_bool_t (*cell)(ur_root_t*, ur_nref, void*)); ur_walk_fore_t* ur_walk_fore_init_with(ur_root_t *r, uint32_t s_prev, uint32_t s_size); ur_walk_fore_t* ur_walk_fore_init(ur_root_t *r); void ur_walk_fore_with(ur_walk_fore_t *w, ur_nref ref, void *v, void (*atom)(ur_root_t*, ur_nref, void*), ur_bool_t (*cell)(ur_root_t*, ur_nref, void*)); void ur_walk_fore_done(ur_walk_fore_t *w); #endif /* ifndef UR_HASHCONS_H */
2.25
2
2024-11-18T21:47:12.350386+00:00
2020-10-20T02:35:57
866a18293d583fb1106647586644bf130bed027b
{ "blob_id": "866a18293d583fb1106647586644bf130bed027b", "branch_name": "refs/heads/master", "committer_date": "2020-10-20T02:35:57", "content_id": "155e7674c69d8e51b028bbc3c3c379f11e442f70", "detected_licenses": [ "MIT" ], "directory_id": "e4dbb3bd4b70500e3dc057a175c3a5aae069c346", "extension": "c", "filename": "vtss_appl_board_jr1_eval.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": 6840, "license": "MIT", "license_type": "permissive", "path": "/vtss_api/appl/vtss_appl_board_jr1_eval.c", "provenance": "stackv2-0130.json.gz:54277", "repo_name": "jkengg/unified_api_4x", "revision_date": "2020-10-20T02:35:57", "revision_id": "88bd09ec0225279a6156d04aa863f8b60067234d", "snapshot_id": "da22813543d251a713aaa90e4504ef5253282b7b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jkengg/unified_api_4x/88bd09ec0225279a6156d04aa863f8b60067234d/vtss_api/appl/vtss_appl_board_jr1_eval.c", "visit_date": "2023-05-12T16:41:55.201365" }
stackv2
/* Copyright (c) 2004-2018 Microsemi Corporation "Microsemi". 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 "vtss_api.h" #include "vtss_appl.h" #if defined(BOARD_JAGUAR1_EVAL) /* ================================================================= * * Register access * ================================================================= */ #include <sys/ioctl.h> #include <fcntl.h> #include <linux/vitgenio.h> static int fd; static vtss_rc board_rd_wr(const u32 addr, u32 *const value, int write) { struct vitgenio_cpld_spi_readwrite spi_buf; char *buf = &spi_buf.buffer[0]; u32 val; /* Address is 22 bits: (tgt_id << 14) + reg_addr */ val = (write ? *value : 0xffffffff); buf[0] = ((write << 7) | ((addr >> 16) & 0x3f)); buf[1] = ((addr >> 8) & 0xff); buf[2] = ((addr >> 0) & 0xff); buf[3] = ((val >> 24) & 0xff); buf[4] = ((val >> 16) & 0xff); buf[5] = ((val >> 8) & 0xff); buf[6] = ((val >> 0) & 0xff); spi_buf.length = 7; if (ioctl(fd, VITGENIO_CPLD_SPI_READWRITE, &spi_buf) < 0) { T_E("SPI_READWRITE failed"); return VTSS_RC_ERROR; } if (!write) { *value = ((buf[3] << 24) | (buf[4] << 16) | (buf[5] << 8) | (buf[6] << 0)); } T_N("%s: addr 0x%08x (0x%02x:0x%04x), value: 0x%08x", write ? "WR" : "RD", addr, (addr >> 14) & 0xff, addr & 0x3fff, *value); return VTSS_RC_OK; } static vtss_rc reg_read(const vtss_chip_no_t chip_no, const u32 addr, u32 *const value) { return board_rd_wr(addr, value, 0); } static vtss_rc reg_write(const vtss_chip_no_t chip_no, const u32 addr, const u32 value) { u32 val = value; return board_rd_wr(addr, &val, 1); } static void board_io_init(void) { struct vitgenio_cpld_spi_setup setup = { /* char ss_select; Which of the CPLD_GPIOs is used for Slave Select */ VITGENIO_SPI_SS_CPLD_GPIO0, VITGENIO_SPI_SS_ACTIVE_LOW, /* char ss_activelow; Slave Select (Chip Select) active low: true, active high: false */ VITGENIO_SPI_CPOL_0, /* char sck_activelow; CPOL=0: false, CPOL=1: true */ VITGENIO_SPI_CPHA_0, /* char sck_phase_early; CPHA=0: false, CPHA=1: true */ VITGENIO_SPI_MSBIT_FIRST, /* char bitorder_msbfirst; */ 0, /* char reserved1; currently unused, only here for alignment purposes */ 0, /* char reserved2; currently unused, only here for alignment purposes */ 0, /* char reserved3; currently unused, only here for alignment purposes */ 200 /* unsigned int ndelay; minimum delay in nanoseconds, two of these delays are used per clock cycle */ }; if ((fd = open("/dev/vitgenio", 0)) < 0) { T_E("open /dev/vitgenio failed"); return; } /* SI */ ioctl(fd, VITGENIO_ENABLE_CPLD_SPI); ioctl(fd, VITGENIO_CPLD_SPI_SETUP, &setup); /* CPLD0 */ setup.ss_select = VITGENIO_SPI_SS_CPLD_GPIO1; ioctl(fd, VITGENIO_ENABLE_CPLD_SPI); ioctl(fd, VITGENIO_CPLD_SPI_SETUP, &setup); /* CPLD1 */ setup.ss_select = VITGENIO_SPI_SS_CPLD_GPIO2; ioctl(fd, VITGENIO_ENABLE_CPLD_SPI); ioctl(fd, VITGENIO_CPLD_SPI_SETUP, &setup); /* Set DUT reset (CPLD reg 3) */ reg_write(0, 3, 0); VTSS_MSLEEP(500); /* Release DUT reset (CPLD reg 3) */ reg_write(0, 3, 0x7); VTSS_MSLEEP(500); /* SI */ setup.ss_select = VITGENIO_SPI_SS_CPLD_GPIO0; ioctl(fd, VITGENIO_ENABLE_CPLD_SPI); ioctl(fd, VITGENIO_CPLD_SPI_SETUP, &setup); } /* Board port map */ static vtss_port_map_t port_map[VTSS_PORT_ARRAY_SIZE]; static vtss_port_interface_t port_interface(vtss_port_no_t port_no) { vtss_port_map_t *map = &port_map[port_no]; return (map->chip_port > 23 ? VTSS_PORT_INTERFACE_XAUI : VTSS_PORT_INTERFACE_SGMII); } /* ================================================================= * * Board init. * ================================================================= */ static int board_init(int argc, const char **argv, vtss_appl_board_t *board) { vtss_port_no_t port_no; vtss_port_map_t *map; board_io_init(); board->init.init_conf->reg_read = reg_read; board->init.init_conf->reg_write = reg_write; board->init.init_conf->mux_mode = VTSS_PORT_MUX_MODE_0; board->port_map = port_map; board->port_interface = port_interface; /* Setup port map and calculate port count */ board->port_count = VTSS_PORTS; for (port_no = VTSS_PORT_NO_START; port_no < VTSS_PORT_NO_END; port_no++) { map = &port_map[port_no]; if (port_no < 24) { /* 1G ports */ map->chip_port = port_no; map->miim_controller = VTSS_MIIM_CONTROLLER_0; map->miim_addr = (port_no + 8); } else if (port_no < 28) { /* XAUI ports */ map->chip_port = (port_no + 3); map->miim_controller = VTSS_MIIM_CONTROLLER_NONE; map->miim_addr = -1; } else { map->chip_port = CHIP_PORT_UNUSED; map->miim_controller = VTSS_MIIM_CONTROLLER_NONE; map->miim_addr = -1; if (port_no < board->port_count) { board->port_count = port_no; } } } return 0; } static void board_init_post(vtss_appl_board_t *board) { } void vtss_board_jr1_eval_init(vtss_appl_board_t *board) { board->descr = "Jaguar1"; board->target = VTSS_TARGET_JAGUAR_1; board->feature.port_control = 1; board->feature.layer2 = 1; board->feature.packet = 0; board->board_init = board_init; board->board_init_post = board_init_post; } #endif /* BOARD_JAGUAR1_EVAL */
2.140625
2
2024-11-18T21:47:12.452143+00:00
2014-02-15T20:16:59
c9419226ee4acf269b330fc6653aa163a75e5674
{ "blob_id": "c9419226ee4acf269b330fc6653aa163a75e5674", "branch_name": "refs/heads/master", "committer_date": "2014-02-15T20:16:59", "content_id": "6a67e05a41f9ad780e0b70a4aadf447f65dcbadd", "detected_licenses": [ "MIT" ], "directory_id": "b5a87787aff1656e36a10786a9194af0bfdd3861", "extension": "c", "filename": "jpeg-recompress.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": 7854, "license": "MIT", "license_type": "permissive", "path": "/jpeg-recompress.c", "provenance": "stackv2-0130.json.gz:54405", "repo_name": "eranhazout/jpeg-archive", "revision_date": "2014-02-15T20:16:59", "revision_id": "09a130be1c79a1a52b1a2b9fcd875a245e471a48", "snapshot_id": "0deeed0b8a27fc51acab3ae61fdaca2aca2ecd53", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/eranhazout/jpeg-archive/09a130be1c79a1a52b1a2b9fcd875a245e471a48/jpeg-recompress.c", "visit_date": "2021-01-18T09:10:46.938427" }
stackv2
/* Recompress a JPEG file while attempting to keep visual quality the same by using structural similarity (SSIM) as a metric. Does a binary search between JPEG quality 40 and 95 to find the best match. Also makes sure that huffman tables are optimized if they weren't already. TODO: Include jpegrescan functionality? It doesn't save much... */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "src/commander.h" #include "src/edit.h" #include "src/iqa/include/iqa.h" #include "src/util.h" const char *COMMENT = "Compressed by jpeg-recompress"; // Number of binary search steps int attempts = 6; // Target quality (SSIM) value float target = 0.9999; // Min/max JPEG quality int jpegMin = 40; int jpegMax = 95; // Progressive image output int progressive = 0; // Strip metadata from the file? int strip = 0; // Defish the image? float defishStrength = 0.0; float defishZoom = 1.0; static void setAttempts(command_t *self) { attempts = atoi(self->arg); } static void setTarget(command_t *self) { target = atof(self->arg); } static void setQuality(command_t *self) { if (!strcmp("low", self->arg)) { target = 0.999; } else if (!strcmp("medium", self->arg)) { target = 0.9999; } else if (!strcmp("high", self->arg)) { target = 0.99995; } else if (!strcmp("veryhigh", self->arg)) { target = 0.99999; } else { fprintf(stderr, "Unknown quality preset '%s'!\n", self->arg); } } static void setMinimum(command_t *self) { jpegMin = atoi(self->arg); } static void setMaximum(command_t *self) { jpegMax = atoi(self->arg); } static void setProgressive(command_t *self) { progressive = 1; } static void setStrip(command_t *self) { strip = 1; } static void setDefish(command_t *self) { defishStrength = atof(self->arg); } static void setZoom(command_t *self) { defishZoom = atof(self->arg); } int main (int argc, char **argv) { unsigned char *buf; long bufSize = 0; unsigned char *original; long originalSize = 0; unsigned char *originalGray; long originalGraySize = 0; unsigned char *compressed = NULL; unsigned long compressedSize = 0; unsigned char *compressedGray; long compressedGraySize = 0; unsigned char *tmpImage; int width, height; unsigned char *metaBuf; unsigned int metaSize = 0; // Parse commandline options command_t cmd; command_init(&cmd, argv[0], "1.0.1"); cmd.usage = "[options] input.jpg compressed-output.jpg"; command_option(&cmd, "-t", "--target [arg]", "Set target SSIM [0.9999]", setTarget); command_option(&cmd, "-q", "--quality [arg]", "Set a quality preset: low, medium, high, veryhigh [medium]", setQuality); command_option(&cmd, "-n", "--min [arg]", "Minimum JPEG quality [40]", setMinimum); command_option(&cmd, "-m", "--max [arg]", "Maximum JPEG quality [95]", setMaximum); command_option(&cmd, "-l", "--loops [arg]", "Set the number of runs to attempt [6]", setAttempts); command_option(&cmd, "-p", "--progressive", "Set progressive JPEG output", setProgressive); command_option(&cmd, "-s", "--strip", "Strip metadata", setStrip); command_option(&cmd, "-d", "--defish [arg]", "Set defish strength [0.0]", setDefish); command_option(&cmd, "-z", "--zoom [arg]", "Set defish zoom [1.0]", setZoom); command_parse(&cmd, argc, argv); if (cmd.argc < 2) { command_help(&cmd); return 255; } // Read original bufSize = readFile((char *) cmd.argv[0], (void **) &buf); if (!bufSize) { return 1; } // Decode the JPEG originalSize = decodeJpeg(buf, bufSize, &original, &width, &height, JCS_RGB); if (defishStrength) { fprintf(stderr, "Defishing...\n"); tmpImage = malloc(width * height * 3); defish(original, tmpImage, width, height, 3, defishStrength, defishZoom); free(original); original = tmpImage; } // Convert RGB input into Y originalGraySize = width * height; originalGray = malloc(originalGraySize); int stride = width * 3; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // Y = 0.299R + 0.587G + 0.114B originalGray[y * width + x] = original[y * stride + x * 3] * 0.299 + original[y * stride + x * 3 + 1] * 0.587 + original[y * stride + x * 3 + 2] * 0.114 + 0.5; } } // Read metadata (EXIF / IPTC / XMP tags) if (getMetadata(buf, bufSize, &metaBuf, &metaSize, COMMENT)) { fprintf(stderr, "File already processed by jpeg-recompress!\n"); return 2; } if (strip) { // Pretend we have no metadata metaSize = 0; } else { fprintf(stderr, "Metadata size is %ukb\n", metaSize / 1024); } if (!originalSize || !originalGraySize) { return 1; } free(buf); // Do a binary search to find the optimal encoding quality for the // given target SSIM value. int min = jpegMin, max = jpegMax; for (int attempt = attempts - 1; attempt >= 0; --attempt) { int quality = min + (max - min) / 2; // Recompress to a new quality level (progressive only on last run if // it was requested, as this saves time) compressedSize = encodeJpeg(&compressed, original, width, height, JCS_RGB, quality, (attempt == 0) ? progressive : 0); // Load compressed luma for quality comparison compressedGraySize = decodeJpeg(compressed, compressedSize, &compressedGray, &width, &height, JCS_GRAYSCALE); // Measure structural similarity (SSIM) float ssim = iqa_ssim(originalGray, compressedGray, width, height, width, 0, 0); fprintf(stderr, "ssim at q=%i (%i - %i): %f\n", quality, min, max, ssim); if (ssim < target) { if (compressedSize >= bufSize) { fprintf(stderr, "Output file would be larger than input, aborting!\n"); free(compressed); free(compressedGray); return 1; } // Too distorted, increase quality min = quality + 1; } else { // Higher SSIM than required, decrease quality max = quality - 1; } // If we aren't done yet, then free the image data if (attempt) { free(compressed); free(compressedGray); } } // Calculate and show savings, if any int percent = (compressedSize + metaSize) * 100 / bufSize; unsigned long saved = (bufSize > compressedSize) ? bufSize - compressedSize - metaSize : 0; fprintf(stderr, "New size is %i%% of original (saved %lu kb)\n", percent, saved / 1024); if (compressedSize >= bufSize) { fprintf(stderr, "Output file is larger than input, aborting!\n"); return 1; } // Write output FILE *file; if (strcmp("-", cmd.argv[1]) == 0) { file = stdout; } else { file = fopen(cmd.argv[1], "wb"); } fwrite(compressed, 20, 1, file); /* 0xffd8 and JFIF marker */ // Write comment so we know not to reprocess this file // in the future if it gets passed in again. // 0xfffe (COM marker), two-byte big-endian length, string fputc(0xff, file); fputc(0xfe, file); fputc(0x00, file); fputc(32, file); fwrite(COMMENT, 30, 1, file); // Write metadata markers if (!strip) { fwrite(metaBuf, metaSize, 1, file); } // Write image data fwrite(compressed + 20, compressedSize - 20, 1, file); fclose(file); // Cleanup command_free(&cmd); if (!strip) { free(metaBuf); } free(compressed); free(original); free(originalGray); free(compressedGray); return 0; }
2.734375
3
2024-11-18T21:47:12.570023+00:00
2019-04-03T00:46:08
b09d7eedcb03a4684fcf08121fbebada193b3f50
{ "blob_id": "b09d7eedcb03a4684fcf08121fbebada193b3f50", "branch_name": "refs/heads/master", "committer_date": "2019-04-03T00:46:08", "content_id": "7d2fb9e5fa9e36658f08b23cf1ad9d9f954f1e24", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "56035f563611ffbafbcef749eb4e759cd8471245", "extension": "h", "filename": "ising-param.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 165532320, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 764, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/ising-param.h", "provenance": "stackv2-0130.json.gz:54536", "repo_name": "francosauvisky/ising-opencl", "revision_date": "2019-04-03T00:46:08", "revision_id": "a6db94bac07fc0ec52332c4a45e1c8af412f5398", "snapshot_id": "e3d45b9cfd5b269bac79c7bddb25e9a72ca6ed6a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/francosauvisky/ising-opencl/a6db94bac07fc0ec52332c4a45e1c8af412f5398/src/ising-param.h", "visit_date": "2020-04-16T11:20:47.392280" }
stackv2
#define sizeY 64 #define sizeX 64 #define iter 1024 // number of iteration to calculate each cycle #define prob_length 5 // num of neighborhood+1 #define prob_buff 16 // prob buffer size when using multiple probs #define prob_zero ((prob_length-1)/2) #define max_prob 1.0 #define svec_length (sizeX*sizeY) #ifdef __OPENCL_VERSION__ typedef char state_t; typedef char4 state_v; #else typedef cl_char state_t; typedef cl_char4 state_v; #endif #define max(x,y) ((x)>(y)?(x):(y)) // Index macro for 2D -> 1D. f: fast, c: iteration counter #define ind(x,y) ( ((x)%sizeX)*sizeX + ((y)%sizeY) ) #define find(x,y) ( (x)*sizeX + (y) ) #define cind(c,x,y) ( (c)*svec_length + ((x)%sizeX)*sizeX + ((y)%sizeY) ) #define cfind(c,x,y) ( (c)*svec_length + (x)*sizeX + (y) )
2.03125
2
2024-11-18T21:47:12.654302+00:00
2015-02-17T00:43:11
ad1ecd0c3965c98264396af8fb720fae6bb83806
{ "blob_id": "ad1ecd0c3965c98264396af8fb720fae6bb83806", "branch_name": "refs/heads/master", "committer_date": "2015-02-17T00:43:11", "content_id": "135ceca4666af5a7687d68c35fb8af11b5a17353", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f7b3d259d572a7fc4ca20b158b30a0aaa9effd66", "extension": "c", "filename": "spfenum.c", "fork_events_count": 1, "gha_created_at": "2015-01-28T22:43:38", "gha_event_created_at": "2015-01-28T22:43:38", "gha_language": null, "gha_license_id": null, "github_id": 29992226, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2600, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/libsauth/spf/spfenum.c", "provenance": "stackv2-0130.json.gz:54666", "repo_name": "z3APA3A/yenma", "revision_date": "2015-02-17T00:43:11", "revision_id": "36c5f6310bccb355f7bd6007013c7f6b1748da5e", "snapshot_id": "d32adfe88593abe508ff1925669c5407d02e1437", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/z3APA3A/yenma/36c5f6310bccb355f7bd6007013c7f6b1748da5e/libsauth/spf/spfenum.c", "visit_date": "2020-12-26T04:26:42.976812" }
stackv2
/* * Copyright (c) 2008-2014 Internet Initiative Japan Inc. All rights reserved. * * The terms and conditions of the accompanying program * shall be provided separately by Internet Initiative Japan Inc. * Any use, reproduction or distribution of the program are permitted * provided that you agree to be bound to such terms and conditions. * * $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <stdio.h> #include <string.h> #include "keywordmap.h" #include "spf.h" #include "spfenum.h" static const KeywordMap spf_score_tbl[] = { {"none", SPF_SCORE_NONE}, {"neutral", SPF_SCORE_NEUTRAL}, {"pass", SPF_SCORE_PASS}, {"policy", SPF_SCORE_POLICY}, {"fail", SPF_SCORE_FAIL}, {"hardfail", SPF_SCORE_FAIL}, // one way from string to value {"softfail", SPF_SCORE_SOFTFAIL}, {"temperror", SPF_SCORE_TEMPERROR}, {"permerror", SPF_SCORE_PERMERROR}, {"syserror", SPF_SCORE_SYSERROR}, // logging use only, not as a final score {NULL, SPF_SCORE_NULL}, }; static const KeywordMap spf_classic_score_tbl[] = { {"none", SPF_SCORE_NONE}, {"neutral", SPF_SCORE_NEUTRAL}, {"pass", SPF_SCORE_PASS}, {"policy", SPF_SCORE_POLICY}, {"hardfail", SPF_SCORE_FAIL}, {"fail", SPF_SCORE_FAIL}, // one way from string to value (and nonsense here) {"softfail", SPF_SCORE_SOFTFAIL}, {"temperror", SPF_SCORE_TEMPERROR}, {"permerror", SPF_SCORE_PERMERROR}, {"syserror", SPF_SCORE_SYSERROR}, // logging use only, not as a final score {NULL, SPF_SCORE_NULL}, }; //////////////////////////////////////////////////////////// SpfScore SpfEnum_lookupScoreByKeyword(const char *keyword) { return (SpfScore) KeywordMap_lookupByCaseString(spf_score_tbl, keyword); } // end function: SpfEnum_lookupScoreByKeyword SpfScore SpfEnum_lookupScoreByKeywordSlice(const char *head, const char *tail) { return (SpfScore) KeywordMap_lookupByCaseStringSlice(spf_score_tbl, head, tail); } // end function: SpfEnum_lookupScoreByKeywordSlice const char * SpfEnum_lookupScoreByValue(SpfScore value) { return KeywordMap_lookupByValue(spf_score_tbl, value); } // end function: SpfEnum_lookupScoreByValue /* * almost the same as SpfEnum_lookupScoreByValue except for returning "hardfail" * instead of "fail" when value is SPF_SCORE_FAIL (= SPF_SCORE_HARDFAIL) */ const char * SpfEnum_lookupClassicScoreByValue(SpfScore value) { return KeywordMap_lookupByValue(spf_classic_score_tbl, value); } // end function: SpfEnum_lookupClassicScoreByValue ////////////////////////////////////////////////////////////
2.15625
2
2024-11-18T21:47:12.986379+00:00
2016-05-29T22:21:30
589e5ed349a5a575eaf36d7186c68783e34ebd97
{ "blob_id": "589e5ed349a5a575eaf36d7186c68783e34ebd97", "branch_name": "refs/heads/master", "committer_date": "2016-05-29T22:21:30", "content_id": "85025e3667324010eb3efce657128d04102fdd24", "detected_licenses": [ "MIT" ], "directory_id": "0890732d56261e41900803d0136acf7bc6d700d2", "extension": "c", "filename": "test_get.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 58563426, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 386, "license": "MIT", "license_type": "permissive", "path": "/www/cgi-bin/test_get.c", "provenance": "stackv2-0130.json.gz:55183", "repo_name": "ValerioLuconi/PHP-Web-Server", "revision_date": "2016-05-29T22:21:30", "revision_id": "43161d0c14ecd9a82fa7b1d20686456efdc301b4", "snapshot_id": "b6db192cf9a2af36fea1abb60c8e414f8474d7e5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ValerioLuconi/PHP-Web-Server/43161d0c14ecd9a82fa7b1d20686456efdc301b4/www/cgi-bin/test_get.c", "visit_date": "2021-01-01T03:32:01.000757" }
stackv2
#include <stdlib.h> #include <stdio.h> int main(int argc, char** argv) { char* env; env = getenv("QUERY_STRING"); printf("Content-type: text/html\r\n\r\n"); printf("<html><head><title>TEST PAGE</title></head>\n"); printf("<body><pre>\n"); printf("GET QUERY STRING: %s\n", env); printf("</pre></body></html>"); exit(0); }
2.234375
2
2024-11-18T21:47:13.310544+00:00
2017-11-23T05:55:06
6f0d821587d287aa7a0f5c57667d0ac1fe79326f
{ "blob_id": "6f0d821587d287aa7a0f5c57667d0ac1fe79326f", "branch_name": "refs/heads/master", "committer_date": "2017-11-23T05:55:06", "content_id": "d8f2ff6b8115749ade71f774baeb32a81df95265", "detected_licenses": [ "ISC" ], "directory_id": "4769780c65cfcb95cf8d706a0f2fba9e127d13b9", "extension": "c", "filename": "test038.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 111769138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 405, "license": "ISC", "license_type": "permissive", "path": "/cc1/tests/test038.c", "provenance": "stackv2-0130.json.gz:55311", "repo_name": "temach/scc-qbe-hacked", "revision_date": "2017-11-23T05:55:06", "revision_id": "2fb0a858aab1e429b155c08a1c020096e4b35984", "snapshot_id": "3101aabbcb6cef1659dce46d4305b82822c00d47", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/temach/scc-qbe-hacked/2fb0a858aab1e429b155c08a1c020096e4b35984/cc1/tests/test038.c", "visit_date": "2021-05-07T06:37:35.447332" }
stackv2
/* See LICENSE file for copyright and license details. */ /* name: TEST038 description: Basic test for tentative definitions error: test038.c:45: error: redeclaration of 'x' output: G1 I "x G1 I "x ( #I0 ) X3 I F "main G5 P F "foo { \ h X3 'P } G3 I F "main { \ G1 #I0 :I h G1 } */ int x; int x = 0; int x; int main(); void * foo() { return &main; } int main() { x = 0; return x; } int x = 1;
2.140625
2
2024-11-18T21:47:14.252246+00:00
2017-06-16T13:32:47
dc28b7f683b788959fc12efa7400c9ba21ebed42
{ "blob_id": "dc28b7f683b788959fc12efa7400c9ba21ebed42", "branch_name": "refs/heads/master", "committer_date": "2017-06-16T13:32:47", "content_id": "7cfdd00bcbc82f67e4bd9e68503b0a16b40c6ecf", "detected_licenses": [ "MIT" ], "directory_id": "cc496132287d171d9081a337b57fc56f3ddf050d", "extension": "c", "filename": "demo_ByXYZ.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 94071542, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1619, "license": "MIT", "license_type": "permissive", "path": "/meta-nexcom/recipes-tools/gsensortools/files/demo_ByXYZ.c", "provenance": "stackv2-0130.json.gz:55834", "repo_name": "brizio73/tmp-yocto-repo", "revision_date": "2017-06-16T13:32:47", "revision_id": "f4629b1c661dd0dd363371b53311a81b4920a3a5", "snapshot_id": "d81b069dcdb266b64382e34d77c2acc51696f56e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/brizio73/tmp-yocto-repo/f4629b1c661dd0dd363371b53311a81b4920a3a5/meta-nexcom/recipes-tools/gsensortools/files/demo_ByXYZ.c", "visit_date": "2020-06-01T10:43:06.410407" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <termios.h> #include "G-sensor.h" int main(int argc , char *argv[]) { int fh=0, value=0,value1=0,value2=0,x=0; char key,key1; fh = open("/dev/NEXCOM_SMBus", O_RDWR); if (fh<=0) { printf("NEXCOM_SMBus driver cannot be opened.\n"); return -1; } InitAccelerometer(fh); printf("Please select which value you wnat to get :\n"); printf("1) Get X-Axis value\n"); printf("2) Get Y-Axis value\n"); printf("3) Get Z-Axis value\n"); printf("4) Get XYZ-Axis value\n"); printf("Please select the number (1~4):"); scanf("%c",&key); switch (key) { case '1': x=1; break; case '2': x=2; break; case '3': x=3; break; case '4': x=4; break; default: printf("The number of you select is wrong, please execute this program again.\n"); return -1; } if ( x==1) { G_Sensor_X_Axis(&value,fh); printf("This value of X-Axis is 0x%x.\n",value); } else if ( x==2) { G_Sensor_Y_Axis(&value,fh); printf("This value of Y-Axis is 0x%x.\n",value); } else if ( x==3) { G_Sensor_Z_Axis(&value,fh); printf("This value of Z-Axis is 0x%x.\n",value); } else { G_Sensor_3_Axis(&value,&value1,&value2,fh); printf("This value of X-Axis is 0x%x.\n",value); printf("This value of Y-Axis is 0x%x.\n",value1); printf("This value of Z-Axis is 0x%x.\n",value2); } exit(0); }
3.0625
3
2024-11-18T21:47:14.472080+00:00
2014-06-16T03:39:33
d76b56662d002bbd179720d00fdcb44857c76cea
{ "blob_id": "d76b56662d002bbd179720d00fdcb44857c76cea", "branch_name": "refs/heads/master", "committer_date": "2014-06-16T03:39:33", "content_id": "f935fa1221fc432ced0dfadab22975b49ad8e02e", "detected_licenses": [ "BSD-2-Clause-Views" ], "directory_id": "516fa17b949ab9a326971e912cbfadf3e96cdd58", "extension": "h", "filename": "syscall.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 17003960, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3432, "license": "BSD-2-Clause-Views", "license_type": "permissive", "path": "/OSDev/include/syscall.h", "provenance": "stackv2-0130.json.gz:56224", "repo_name": "ravikiranp/SBUnix", "revision_date": "2014-06-16T03:39:33", "revision_id": "87f2a65ba1d66a478ad2f77ef1f7dc773153f8b0", "snapshot_id": "b55247a43417728b9b04b8d693107316c0c02d90", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/ravikiranp/SBUnix/87f2a65ba1d66a478ad2f77ef1f7dc773153f8b0/OSDev/include/syscall.h", "visit_date": "2020-06-03T10:46:07.110400" }
stackv2
#ifndef _SYSCALL_H #define _SYSCALL_H #include <defs.h> #include<function.h> #define SYSCALL_PROTO(n) static __inline uint64_t __syscall##n SYSCALL_PROTO(0)(uint64_t n) { //uint16_t pid; //uint64_t fork_ret; switch(n) { case 1: //EXIT __asm__ volatile( "mov $0x85,%%eax;" " int $0x85;" : : :"memory" ); break; case 2: //GET_PID __asm__ volatile( "mov $0x82,%%eax;" " int $0x82;" : : :"memory" ); break; case 3: //FORK __asm__ volatile( "mov $0x81,%%eax;" "int $0x81;" : : :"memory" ); break; case 4: //SCANF __asm__ volatile( "mov $0x87,%%eax;" " int $0x87;" : : :"memory" ); break; case 5: //DUMMY __asm__ volatile( "mov $0x80,%%eax;" "int $0x80;" : : :"memory" ); break; default: break; } return 0; } SYSCALL_PROTO(1)(uint64_t n, uint64_t a1) { switch(n) { case 1: //kern_sleep((uint16_t)a1); __asm__ volatile( "mov $0x83,%%eax;" " int $0x83;" : : :"memory" ); break; case 2: //kern_waitpid((uint16_t)a1); __asm__ volatile( "mov $0x84,%%eax;" " int $0x84;" : : :"memory" ); break; case 3: //kern_printf((char *)a1); __asm__ volatile( "mov $0x86,%%eax;" " int $0x86;" : : :"memory" ); break; case 4: //user_malloc __asm__ volatile ( "mov $0x88,%%eax;" "int $0x88;" : : :"memory" ); break; case 5: //open __asm__ volatile ( "mov $0x89,%%eax;" "int $0x89;" : : :"memory" ); break; case 6: //exec __asm__ volatile ( "mov $0x52,%%eax;" "int $0x52;" : : :"memory","%eax" ); break; case 7: //close __asm__ volatile ( "mov $0x50,%%eax;" "int $0x50;" : : :"memory","%eax" ); break; default : break; } return 0; } SYSCALL_PROTO(2)(uint64_t n, uint64_t a1, uint64_t a2) { switch(n) { case 1: //kscanf((char *)a1,(uint64_t *)a2); break; default: break; } return 0; } SYSCALL_PROTO(3)(uint64_t n, uint64_t a1, uint64_t a2, uint64_t a3) { switch(n) { case 1: //read __asm__ volatile( "mov $0x51, %%eax;" "int $0x51;" : : :"memory" ); break; default : break; } return 0; } SYSCALL_PROTO(4)(uint64_t n, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4) { return 0; } #endif
2.28125
2
2024-11-18T21:47:14.642476+00:00
2017-11-26T20:52:17
6bc4043308f05e8222ab32fa2c5381d4b5d7e7af
{ "blob_id": "6bc4043308f05e8222ab32fa2c5381d4b5d7e7af", "branch_name": "refs/heads/master", "committer_date": "2017-11-26T20:52:17", "content_id": "1325ee8052f40854199c1832e2daf65c09151e03", "detected_licenses": [ "MIT" ], "directory_id": "f80d9f70477ee3689df6e61728ea97005c7a0d0d", "extension": "c", "filename": "setup_OpenCL.c", "fork_events_count": 4, "gha_created_at": "2016-11-01T00:02:39", "gha_event_created_at": "2017-01-21T20:12:53", "gha_language": "C", "gha_license_id": null, "github_id": 72488293, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10906, "license": "MIT", "license_type": "permissive", "path": "/3_Image-Generator_OpenCL/PixelGenerator/src/setup_OpenCL.c", "provenance": "stackv2-0130.json.gz:56353", "repo_name": "BernhardLindner/Image-Generator", "revision_date": "2017-11-26T20:52:17", "revision_id": "32707e941b4176e7999016319670a798d3171787", "snapshot_id": "69e774ea50e8ae49d9b7a91ac84e0cc83019e522", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/BernhardLindner/Image-Generator/32707e941b4176e7999016319670a798d3171787/3_Image-Generator_OpenCL/PixelGenerator/src/setup_OpenCL.c", "visit_date": "2021-01-12T12:25:17.282260" }
stackv2
/* * FILE = /src/setup_OpenCL.c * * RELATED FILES: *.c *.h * numberOfPixel.c numberOfPixel.h * mem_cleanup_opencl.c mem_cleanup_opencl.h * setup_OpenCL.h * universalSettings.h * * This function takes a colorpalette created by the function * create_color_palette() as an arguments. * * The setup_OpenCL() function creates an OpenCL program and kernel for * the generation of an image of the mandelbrot set. * The image generation and execution of the kernel happens inside * the generate_image() function. * * By changing COMPUTE_DEVICE defined in setup_OpenCL.h the image can be * calculated either on the CPU or if available on a GPU. * * Copyright (c) 2016 Bernhard Lindner * * This file is licensed under the terms of the MIT License. * See /LICENSE for details. */ #include "setup_OpenCL.h" #include "numberOfPixel.h" #include "universalSettings.h" #include "mem_cleanup_opencl.h" /* * The following sources are great starting points on OpenCL. * * A great article on OpenCL: * "A Gentle Introduction to OpenCL" * http://www.drdobbs.com/parallel/a-gentle-introduction-to-opencl/231002854 * * A great lecture course on OpenCL: * "Hands On OpenCL" * https://handsonopencl.github.io */ /*---------------------------------------------------------------------------*/ /* K E R N E L S O U R C E S */ /*---------------------------------------------------------------------------*/ /* * the kernelsource can be found inside kernelsource_OpenCL/mandelbrot_openCL.cl * * Use the script: * https://github.com/UoB-HPC/SNAP_MPI_OpenCL/blob/master/src/stringify_opencl * to convert the .cl kernelsource into a char *kernelsource string. * * Alternatively the .cl file could be opened with fopen() and read into a * char *string with fread(). */ char * kernelsource = "__kernel void mandelbrot(__global unsigned char *imagebuffer,\n" " double xmin,\n" " double xmax,\n" " double ymin,\n" " double ymax,\n" " double e,\n" " double zoom,\n" " __global unsigned char *palette,\n" " int WIDTH,\n" " int HEIGHT)\n" "{\n" " const int MAX_ITERATION = 1023;\n" "\n" " double xp;\n" " xp = ((xmax - xmin) / WIDTH);\n" " double yp;\n" " yp = ((ymax - ymin) / HEIGHT);\n" "\n" " int pixel_y = get_global_id(0);\n" " int pixel_x = get_global_id(1);\n" "\n" " if ((pixel_y < HEIGHT) && (pixel_x < WIDTH))\n" " {\n" " double x0;\n" " x0 = ((xmin + (pixel_x * xp)) / zoom);\n" "\n" " double y0;\n" " y0 = ((ymax - (pixel_y * yp)) / zoom);\n" "\n" " double x;\n" " x = 0.0;\n" "\n" " double y;\n" " y = 0.0;\n" "\n" " int iteration;\n" " iteration = 0;\n" "\n" " double q;\n" " q = (x0 - 0.25) * (x0 - 0.25) + (y0 * y0);\n" "\n" " if (((q * (q + (x0 - 0.25))) < (0.25 * (y0 * y0))) ||\n" " (((x0 + 1) * (x0 + 1) + (y0 * y0)) < (0.0625)))\n" " {\n" " iteration = MAX_ITERATION;\n" " imagebuffer[(pixel_y * WIDTH * 3 + (3 * pixel_x))] =\n" " palette[iteration * 3];\n" "\n" " imagebuffer[(pixel_y * WIDTH * 3 + (3 * pixel_x) + 1)] =\n" " palette[iteration * 3 + 1];\n" "\n" " imagebuffer[(pixel_y * WIDTH * 3 + (3 * pixel_x) + 2)] =\n" " palette[iteration * 3 + 2];\n" " }\n" " else\n" " {\n" " while ((((x * x) + (y * y)) < 4) && (iteration < MAX_ITERATION))\n" " {\n" " double xtemp;\n" " xtemp = ((x * x) - (y * y) + x0);\n" "\n" " y = ((2 * x * y) + y0);\n" " x = xtemp;\n" " iteration = iteration + 1;\n" " }\n" " imagebuffer[(pixel_y * WIDTH * 3 + (3 * pixel_x))] =\n" " palette[iteration * 3];\n" "\n" " imagebuffer[(pixel_y * WIDTH * 3 + (3 * pixel_x) + 1)] =\n" " palette[iteration * 3 + 1];\n" "\n" " imagebuffer[(pixel_y * WIDTH * 3 + (3 * pixel_x) + 2)] =\n" " palette[iteration * 3 + 2];\n" " }\n" " }\n" "}\n" ; int setup_OpenCL(unsigned char *palette, void *OpenCLdata) { /* * struct cl_mem_data defined in mandelbrot.h */ struct cl_mem_data *data = (struct cl_mem_data *) OpenCLdata; /*---------------------------------------------------------------------------*/ /* I D E N T I F Y A P L A T F O R M */ /*---------------------------------------------------------------------------*/ cl_int err; cl_platform_id platform; err = clGetPlatformIDs(1, &platform, NULL); if (err < 0) { perror("Couldn't identify a platform"); mem_cleanup_opencl(data); return EXIT_FAILURE; } /*---------------------------------------------------------------------------*/ /* C O N N E C T T O A C O M P U T E D E V I C E */ /*---------------------------------------------------------------------------*/ /* * COMPUTE_DEVICE defined in mandelbrot.h */ cl_device_id device; cl_device_id devices[3]; cl_uint numdevices = 3; err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 3, devices, &numdevices); if (err != CL_SUCCESS) { printf("Error: Failed to create a device group!\n"); return EXIT_FAILURE; } device = devices[COMPUTE_DEVICE]; char devicename[256]; cl_device_info info = CL_DEVICE_NAME; err = clGetDeviceInfo(device, info, 256, devicename, NULL); if (err != CL_SUCCESS) { printf("Error: Failed to get Device Info!\n"); return EXIT_FAILURE; } #if DEBUG printf("\nUsing OpenCL device: %s\n", devicename); #endif /*---------------------------------------------------------------------------*/ /* C R E A T E A C O M P U T E C O N T E X T */ /*---------------------------------------------------------------------------*/ data->context = clCreateContext(0, 1, &device, NULL, NULL, &err); if (err != CL_SUCCESS) { printf("Error: Failed to create a compute context!\n"); mem_cleanup_opencl(data); return EXIT_FAILURE; } /*---------------------------------------------------------------------------*/ /* C R E A T E A C O M M A N D Q U E U E */ /*---------------------------------------------------------------------------*/ /* OpenCL 2 */ #if OS_FEDORA data->commands = clCreateCommandQueueWithProperties(data->context, device, 0, &err); if (err != CL_SUCCESS) { printf("Error: Failed to create a command commands!\n"); mem_cleanup_opencl(data); return EXIT_FAILURE; } /* OpenCL 1.2 */ #else data->commands = clCreateCommandQueue(data->context, device, 0, &err); if (err != CL_SUCCESS) { printf("Error: Failed to create a command commands!\n"); mem_cleanup_opencl(data); return EXIT_FAILURE; } #endif /*---------------------------------------------------------------------------*/ /* C R E A T E M E M O R Y B U F F E R S */ /*---------------------------------------------------------------------------*/ data->imgb = clCreateBuffer(data->context, CL_MEM_READ_WRITE, sizeof(unsigned char) * MAX_DATA, NULL, &err); if (err != CL_SUCCESS) { printf("Error: creating Buffer for imagedata!\n"); mem_cleanup_opencl(data); return EXIT_FAILURE; } data->colpb = clCreateBuffer(data->context, CL_MEM_READ_WRITE, sizeof(unsigned char) * 3072, NULL, &err); if (err != CL_SUCCESS) { printf("Error: creating Buffer for colorpalette!\n"); mem_cleanup_opencl(data); return EXIT_FAILURE; } /*---------------------------------------------------------------------------*/ /* C R E A T E A P R O G R A M F R O M K E R N E L S O U R C E */ /*---------------------------------------------------------------------------*/ data->program = clCreateProgramWithSource(data->context, 1, (const char **) &kernelsource, NULL, &err); if (err != CL_SUCCESS) { printf("Error: Creating program from kernelsource!\n"); mem_cleanup_opencl(data); return EXIT_FAILURE; } /*---------------------------------------------------------------------------*/ /* B U I L D T H E P R O G R A M E X E C U T A B L E */ /*---------------------------------------------------------------------------*/ err = clBuildProgram(data->program, 0, NULL, NULL, NULL, NULL); if (err != CL_SUCCESS) { size_t len; char buffer[2048]; printf("Error: Failed to build program executable!\n"); clGetProgramBuildInfo(data->program, device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len); printf("%s\n", buffer); mem_cleanup_opencl(data); return EXIT_FAILURE; } /*---------------------------------------------------------------------------*/ /* C R E A T E T H E C O M P U T E K E R N E L */ /*---------------------------------------------------------------------------*/ data->kernel = clCreateKernel(data->program, "mandelbrot", &err); if (err != CL_SUCCESS) { printf("Error: Failed to create compute kernel!\n"); mem_cleanup_opencl(data); return EXIT_FAILURE; } /*---------------------------------------------------------------------------*/ /* W R I T E C O L O R P A L E T T E I N T O B U F F E R */ /*---------------------------------------------------------------------------*/ err = clEnqueueWriteBuffer(data->commands, data->colpb, CL_TRUE, 0, sizeof(unsigned char) * 3072, palette, 0, NULL, NULL); if (err != CL_SUCCESS) { printf("Error: Failed to write colorpalette to buffer!\n"); mem_cleanup_opencl(data); return EXIT_FAILURE; } /*---------------------------------------------------------------------------*/ /* S E T K E R N E L A R G U M E N T S */ /*---------------------------------------------------------------------------*/ err = clSetKernelArg(data->kernel, 0, sizeof(cl_mem), &data->imgb); err |= clSetKernelArg(data->kernel, 7, sizeof(cl_mem), &data->colpb); err |= clSetKernelArg(data->kernel, 8, sizeof(int), &WIDTH); err |= clSetKernelArg(data->kernel, 9, sizeof(int), &HEIGHT); if (err != CL_SUCCESS) { printf("Error: Failed to set kernel arguments! %d\n", err); mem_cleanup_opencl(data); return EXIT_FAILURE; } return EXIT_SUCCESS; }
2.09375
2
2024-11-18T21:47:19.815273+00:00
2021-11-09T18:47:51
77c832785aecc45eda9483a86d78ab33469ce44d
{ "blob_id": "77c832785aecc45eda9483a86d78ab33469ce44d", "branch_name": "refs/heads/master", "committer_date": "2021-11-09T18:47:51", "content_id": "37b69c0b7d90f4d013bc062c821949f8b240c9bc", "detected_licenses": [ "Unlicense" ], "directory_id": "51ff7efb67cc42f1e7b2fae2ca3720618219f89b", "extension": "c", "filename": "weighted-quick-union.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 227649551, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1815, "license": "Unlicense", "license_type": "permissive", "path": "/weighted-quick-union.c", "provenance": "stackv2-0130.json.gz:56743", "repo_name": "abdnh/chex-game", "revision_date": "2021-11-09T18:47:51", "revision_id": "de3183be97021d4571247e71e998aff7ec8209a7", "snapshot_id": "5f590aa18d67ccf871d7a81cccd934c384839cbb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/abdnh/chex-game/de3183be97021d4571247e71e998aff7ec8209a7/weighted-quick-union.c", "visit_date": "2023-08-28T23:40:50.139078" }
stackv2
#include <stdlib.h> #include "weighted-quick-union.h" int w_quickunion_init(struct wqu_uf *uf, size_t size) { uf->nodes = malloc(size * sizeof(struct wqu_node)); if (!uf->nodes) return 0; for (size_t i = 0; i < size; i++) { uf->nodes[i].id = i; uf->nodes[i].size = 1; } uf->size = size; uf->count = size; return 1; } void w_quickunion_destroy(struct wqu_uf *uf) { free(uf->nodes); uf->nodes = NULL; uf->size = 0; uf->count = 0; } /* static size_t root_id(struct wqu_uf *uf, size_t p) { struct wqu_node *node = &uf->nodes[p]; while(node->id != uf->nodes[node->id].id) { uf->nodes[node->id].id = uf->nodes[uf->nodes[node->id].id].id; // path halving node = &uf->nodes[node->id]; } return node->id; } */ static size_t root_id(struct wqu_uf *uf, size_t p) { size_t root_i = uf->nodes[p].id; while (root_i != uf->nodes[root_i].id) root_i = uf->nodes[root_i].id; while (p != root_i) { size_t newp = uf->nodes[p].id; uf->nodes[p].id = root_i; p = newp; } return root_i; } bool w_quickunion_is_connected(struct wqu_uf *uf, size_t p, size_t q) { return root_id(uf, p) == root_id(uf, q); } void w_quickunion_union(struct wqu_uf *uf, size_t p, size_t q) { size_t p_root_id = root_id(uf, p); size_t q_root_id = root_id(uf, q); if (p_root_id == q_root_id) return; struct wqu_node *p_node = &uf->nodes[p]; struct wqu_node *q_node = &uf->nodes[q]; if (p_node->size <= q_node->size) { uf->nodes[p_root_id].id = uf->nodes[q_root_id].id; q_node->size += p_node->size; } else { uf->nodes[q_root_id].id = uf->nodes[p_root_id].id; p_node->size += q_node->size; } uf->count--; }
2.859375
3
2024-11-18T22:28:07.282250+00:00
2021-10-21T01:42:17
3ad452b79dae3029e5fff8b37d532d55aa0aa8c6
{ "blob_id": "3ad452b79dae3029e5fff8b37d532d55aa0aa8c6", "branch_name": "refs/heads/master", "committer_date": "2021-10-21T01:42:17", "content_id": "928ec59ee5d879e43c1507e57a0a3bac16ae172c", "detected_licenses": [ "MIT" ], "directory_id": "7b134abd9b8b3f347a0dcac20978dc16b885dd22", "extension": "c", "filename": "conductor.c", "fork_events_count": 9, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 151113915, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1457, "license": "MIT", "license_type": "permissive", "path": "/conductor.c", "provenance": "stackv2-0132.json.gz:65112", "repo_name": "CSE3320/Office-Hours-Assignment", "revision_date": "2021-10-21T01:42:17", "revision_id": "f259d864aa075767ae1498df8766057dadc8e19c", "snapshot_id": "607837a1fcb14df544d665f53e526144d764316f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CSE3320/Office-Hours-Assignment/f259d864aa075767ae1498df8766057dadc8e19c/conductor.c", "visit_date": "2021-10-22T16:32:44.944506" }
stackv2
#include <semaphore.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #define MAX_THREADS 2000000 pthread_t tid[ MAX_THREADS ]; pthread_t ctid; sem_t studentASemaphore; sem_t studentBSemaphore; void * studentA( void * arg ) { sem_wait( &studentASemaphore ); printf("Tick\n"); return NULL; } void * studentB( void * arg ) { sem_wait( &studentBSemaphore ); printf("Tock\n"); return NULL; } void * conductor( void * arg ) { int i; for( i = 0; i < MAX_THREADS; i ++ ) { if( i % 2 == 0 ) { sem_post( &studentASemaphore ); } else { sem_post( &studentBSemaphore ); } usleep( 1000000 ); } } int main( ) { int i; sem_init( &studentASemaphore, 0, 0 ); sem_init( &studentBSemaphore, 0, 0 ); pthread_create( &ctid, 0, conductor, NULL ); for( i = 0; i < MAX_THREADS; i ++ ) { if( i % 2 == 0 ) { int ret = pthread_create( &tid[i], 0, studentA, NULL ); if( ret == -1 ) perror( "Thread create failed: "); } else { int ret = pthread_create( &tid[i], 0, studentB, NULL ); if( ret == -1 ) perror( "Thread create failed: "); } } for( i = 0; i < MAX_THREADS; i ++ ) { printf("Calling join on thread %d\n", i ); pthread_join( tid[i], NULL ); } // Here is where the threads do work // printf("Done with all the joins\n"); return 0; }
3.40625
3
2024-11-18T22:28:07.759769+00:00
2013-10-13T19:35:10
1bdac8e453281c312a02401ded87eefd790509d5
{ "blob_id": "1bdac8e453281c312a02401ded87eefd790509d5", "branch_name": "refs/heads/master", "committer_date": "2013-10-13T19:35:10", "content_id": "3bdb523a12781992fab1c3e4d5f37537bda182bd", "detected_licenses": [ "MIT" ], "directory_id": "a4b607fa73f1f2147dd0b70d3a6e65e2d3692032", "extension": "c", "filename": "stermp.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": 6999, "license": "MIT", "license_type": "permissive", "path": "/stermp.c", "provenance": "stackv2-0132.json.gz:65757", "repo_name": "fduhia/stermp", "revision_date": "2013-10-13T19:35:10", "revision_id": "e333f31106090484240b60b147ec0ef643741402", "snapshot_id": "394f91184bcab7dd5ca0e66116c585f244b91415", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fduhia/stermp/e333f31106090484240b60b147ec0ef643741402/stermp.c", "visit_date": "2020-08-17T12:35:32.465231" }
stackv2
/* ---------------------------------------------------------- */ /* | Nombre: stermp.c ( Simple Terminal Play) | */ /* | Autor: Gaspar Fernández ([email protected]) | */ /* | Fecha: 05 Enero 2009 | */ /* | Web: http://www.totaki.com/poesiabinaria/ | */ /* ---------------------------------------------------------- */ /* | Description: | */ /* | Colors and position handling for terminal programs | */ /* | made for easy terminal projects, to make it as | */ /* | similar as possible to conio.h, and make those old | */ /* | programs portable. | */ /* ---------------------------------------------------------- */ /* | Descripción: | */ /* | Manejo de colores y posicionamiento de texto en un | */ /* | terminal para nostálgicos de conio.h | */ /* ---------------------------------------------------------- */ /* The MIT License (MIT) */ /* Copyright (c) 2013 Gaspar Fernández */ /* 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 <unistd.h> #include <string.h> #include "stermp.h" #include <errno.h> #include <fcntl.h> #include <signal.h> #define KBHIT_USLEEP() { \ if (kbh_usleep) \ usleep(kbh_usleep); \ } #define KBHIT_PRE() { \ termnoecho(1); \ fcntl(STDIN_FILENO, F_SETFL, fdflags | O_NONBLOCK); /* Now we activate NON_BLOCK flag to not stop execution */ \ KBHIT_USLEEP(); \ } /* Equivalencias de colores */ static const char ansicolors[16] = {30, 34, 32, 36, 31, 35, 33, 37, 0, 34, 32, 36, 31, 35, 33, 37}; struct termios orig_tty; /* Initial terminal attributes */ struct termios save_tty; /* Backgup of terminal attributes */ int orig_fdf; /* Initial flag values */ int fdflags; /* Flag values */ int kbh_usleep=100000; /* No lighten CPU usage and avoid lots of kbhits() all the time, we usleep after each one of them */ int __init=0; /* Is it initialized? */ void clrscr() { printf("\033[2J"); // Clears screen printf("\033[1;1H"); // Go to row 1, column 1 } void gotoxy(int x, int y) { printf("\033[%d;%dH", y, x); /* Put cursor in X, Y */ } void textcolor(int color) { int atrval=0; if (color & UNDERLINE) atrval=UNDERLINE_ATTR; else if (color & BLINK) atrval=BLINK_ATTR; else if (color>=BRILLO_MIN) atrval=BRILLO_ATTR; color=ansicolors[color & 15]; printf("\033[%d;%dm", atrval, color); } void textbackground(int color) { if (color<BRILLO_MIN) { /* Only some colors can be at background */ color=ansicolors[color & 15]+10; printf("\033[%dm", color); } } void restore_color() { printf("\033[0m"); } int wherex() { coord_t coord; coord=wherexy(0); return coord.x; } int wherey() { coord_t coords; coords=wherexy(0); return coords.y; } int screenwidth() { coord_t coords; coords=wherexy(1); return coords.x; } int screenheight() { coord_t coords; coords=wherexy(1); return coords.y; } coord_t wherexy(int abs) { coord_t coords; char buf[12]; char *p; fflush(stdout); /* Flush stdout */ termnoecho(1); if (abs) /* To get screen dimensions */ { fprintf(stdout, "\033[s"); /* Saves current position */ fprintf(stdout, "\033[r"); /* Avoids scroll */ fprintf(stdout, "\033[255;255H"); /* Go to the bottom right position */ } fprintf(stdout, "\033[6n"); /* Gets data */ fflush(stdout); while (read(STDIN_FILENO, buf, sizeof(buf))==0); sscanf(buf, "\033[%d;%dR", &coords.y, &coords.x); if (abs) { fprintf(stdout, "\033[u"); /* Restores cursor position */ } restore_terminal(); /* Restores terminal properties */ return coords; } void termnoecho(int canon) { struct termios tty; if (__init) save_term_info(); tty = save_tty; if (canon) tty.c_lflag &= ~(ICANON); tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL); tty.c_cc[VMIN] = 1; tty.c_cc[VTIME] = 1; if ( tcsetattr(STDIN_FILENO, TCSANOW, &tty) == -1 ) error ("ERROR: I can't set terminal attributes."); } int getch() { int key; termnoecho(1); key=getch(); restore_terminal(); } int getche() { int key; termnoecho(0); key=getch(); restore_terminal(); } void kbhit_pre() { KBHIT_PRE(); } int __kbhit() { int key; key=getchar(); if (key!=EOF) return key; } int kbhit2() { int key; KBHIT_PRE(); key=getchar(); restore_terminal(); if (key!=EOF) return key; return 0; } int kbhit() { int key; KBHIT_PRE(); key=getchar(); restore_terminal(); if (key!=EOF) { ungetc(key, stdin); return 1; } return 0; } void restore_terminal() { restore_term(&save_tty, &fdflags); } void restore_term(struct termios *tty, int *stdinflags) { if ( tcsetattr(STDIN_FILENO, TCSANOW, tty) == -1 ) error ("ERROR: I can't set terminal attributes."); if ( fcntl(STDIN_FILENO, F_SETFL, stdinflags) == -1 ) error ("ERROR: I can't set stdin flags."); } void error(char *err) { fprintf(stderr, "%s errno=%d (%s)\n", err, errno, strerror(errno)); exit (EXIT_CODE); } void term_info(struct termios *tty, int *stdinflags) { if ( tcgetattr(STDIN_FILENO, tty) == -1 ) error ("ERROR: I Can't get terminal attributes."); *stdinflags = fcntl(STDIN_FILENO, F_GETFL, 0); } void save_term_info() { term_info (&save_tty, &fdflags); /* Store flags in temporary variable */ } void sigio(int s) { } void term_init() { /* Save initial values */ term_info (&orig_tty, &orig_fdf); /* Backup values */ save_tty=orig_tty; fdflags=orig_fdf; if (signal(SIGIO, sigio)==SIG_ERR) error("ERROR: Can't block SIGIO signal"); __init=1; } void term_defaults() { restore_term(&orig_tty, &orig_fdf); }
2.359375
2
2024-11-18T22:28:07.851306+00:00
2019-03-01T05:16:46
c2c821c4e671827dc8c7f28eb19ef1cb9f6cb07a
{ "blob_id": "c2c821c4e671827dc8c7f28eb19ef1cb9f6cb07a", "branch_name": "refs/heads/master", "committer_date": "2019-03-01T05:16:46", "content_id": "8448769dd88abc3c9962bc828ffe54b394ae4a37", "detected_licenses": [ "MIT" ], "directory_id": "5a17a3d150c4773318d397a46878d2fd74c0671f", "extension": "c", "filename": "bailongjian.c", "fork_events_count": 0, "gha_created_at": "2018-12-26T11:38:10", "gha_event_created_at": "2018-12-26T11:38:10", "gha_language": null, "gha_license_id": "MIT", "github_id": 163173406, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1915, "license": "MIT", "license_type": "permissive", "path": "/nitan/clone/lonely/bailongjian.c", "provenance": "stackv2-0132.json.gz:65887", "repo_name": "cantona/NT6", "revision_date": "2019-03-01T05:16:46", "revision_id": "073f4d491b3cfe6bfbe02fbad12db8983c1b9201", "snapshot_id": "e9adc7308619b614990fa64456c294fad5f07d61", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cantona/NT6/073f4d491b3cfe6bfbe02fbad12db8983c1b9201/nitan/clone/lonely/bailongjian.c", "visit_date": "2020-04-15T21:16:28.817947" }
stackv2
#include <weapon.h> #include <ansi.h> inherit SWORD; void create() { set_name(HIW "白龍劍" NOR, ({ "bailong jian", "bailong", "jian" }) ); set_weight(5500); if (clonep()) destruct(this_object()); else { set("long", HIW "青鋒長約三尺,劍脊花紋古樸,鋒口隱隱發着銀澤。\n" NOR); set("unit", "柄"); set("value", 800000); set("no_sell", 1); set("material", "steel"); set("wield_msg", HIW "$N" HIW "從背後「唰」的抽出一柄利劍," "劍刃在陽光下閃閃生輝。\n" NOR); set("unwield_msg", HIW "$N" HIW "將手中白龍劍空舞個劍花,插" "回劍鞘。\n" NOR); set("stable", 100); } init_sword(150); setup(); } mixed hit_ob(object me, object victim, int damage_bonus) { int n; int my_exp, ob_exp; if (me->query_skill_mapped("sword") != "rouyun-jian" || me->query_skill("rouyun-jian", 1) < 100) return damage_bonus / 2; switch (random(10)) { case 0: if (! victim->is_busy()) victim->start_busy(me->query_skill("sword") / 10 + 2); return HIW "$N" HIW "將手中白龍劍斜斜削出,劍身陡然漾起一道" "白光,將$n" HIW "逼得連連後退!\n" NOR; case 1: n = me->query_skill("sword"); victim->receive_damage("qi", n * 3 / 4, me); victim->receive_wound("qi", n * 3 / 4, me); return HIW "$N" HIW "一聲清嘯,手中白龍劍連舞出七、八個劍花" ",繽紛削向$n" HIW "周身各處!\n" NOR; } return damage_bonus; }
2
2
2024-11-18T22:28:07.911812+00:00
2020-05-31T09:57:52
1c85cee492cc2a6270b957a23cc74eee3bc0bf32
{ "blob_id": "1c85cee492cc2a6270b957a23cc74eee3bc0bf32", "branch_name": "refs/heads/master", "committer_date": "2020-05-31T09:57:52", "content_id": "693ad3a480d7f21a13971a0b114338ee07b3b963", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "66f65529b631c0b60b7a5c79144114fcb2ae878c", "extension": "c", "filename": "cbmdosvfs.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 205799639, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8593, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/lib/1541img/cbmdosvfs.c", "provenance": "stackv2-0132.json.gz:66017", "repo_name": "excess-c64/lib1541img", "revision_date": "2020-05-31T09:57:52", "revision_id": "face2dd71ba58ef75b523815eb6d074f1ca06caf", "snapshot_id": "75cb5d2ccfd7a88ced57d56284f8db45b52abcd6", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/excess-c64/lib1541img/face2dd71ba58ef75b523815eb6d074f1ca06caf/src/lib/1541img/cbmdosvfs.c", "visit_date": "2020-07-16T13:48:19.563207" }
stackv2
#include <stdlib.h> #include <string.h> #include "util.h" #include "log.h" #include <1541img/event.h> #include <1541img/cbmdosfile.h> #include <1541img/petscii.h> #include <1541img/cbmdosvfs.h> #define DIRCHUNKSIZE 144 struct CbmdosVfs { char *name; char *id; int autoMapToLc; CbmdosFile **files; Event *changedEvent; unsigned fileCount; unsigned fileCapa; uint8_t nameLength; uint8_t idLength; uint8_t dosver; }; static void fileHandler(void *receiver, int id, const void *sender, const void *args) { (void)id; CbmdosVfs *self = receiver; unsigned pos; for (pos = 0; pos < self->fileCount; ++pos) { if (self->files[pos] == sender) break; } CbmdosVfsEventArgs ea = { .what = CVE_FILECHANGED, .fileEventArgs = args, .filepos = pos }; Event_raise(self->changedEvent, &ea); } SOEXPORT CbmdosVfs *CbmdosVfs_create(void) { CbmdosVfs *self = xmalloc(sizeof *self); memset(self, 0, sizeof *self); self->files = xmalloc(DIRCHUNKSIZE * sizeof *self->files); self->fileCapa = DIRCHUNKSIZE; self->dosver = 0x41; self->changedEvent = Event_create(0, self); return self; } SOEXPORT uint8_t CbmdosVfs_dosver(const CbmdosVfs *self) { return self->dosver; } SOEXPORT void CbmdosVfs_setDosver(CbmdosVfs *self, uint8_t dosver) { self->dosver = dosver; CbmdosVfsEventArgs args = { .what = CVE_DOSVERCHANGED }; Event_raise(self->changedEvent, &args); } SOEXPORT const char *CbmdosVfs_name(const CbmdosVfs *self, uint8_t *length) { if (length) { *length = self->nameLength; } return self->name; } SOEXPORT void CbmdosVfs_setName( CbmdosVfs *self, const char *name, uint8_t length) { if (length > 16) { logmsg(L_WARNING, "CbmdosVfs_setName: truncating long name."); length = 16; } free(self->name); if (name) { self->name = xmalloc(length+1); memcpy(self->name, name, length); self->name[length] = 0; } else { self->name = 0; if (length) { logmsg(L_WARNING, "CbmdosVfs_setName: length > 0 given for empty " "name."); length = 0; } } self->nameLength = length; if (self->autoMapToLc) { petscii_mapUpperGfxToLower(self->name, self->nameLength); } CbmdosVfsEventArgs args = { .what = CVE_NAMECHANGED }; Event_raise(self->changedEvent, &args); } SOEXPORT const char *CbmdosVfs_id(const CbmdosVfs *self, uint8_t *length) { if (length) { *length = self->idLength; } return self->id; } SOEXPORT void CbmdosVfs_setId(CbmdosVfs *self, const char *id, uint8_t length) { if (length > 5) { logmsg(L_WARNING, "CbmdosVfs_setId: truncating long id."); length = 5; } free(self->id); if (id) { self->id = xmalloc(length+1); memcpy(self->id, id, length); self->id[length] = 0; } else { self->id = 0; if (length) { logmsg(L_WARNING, "CbmdosVfs_setId: length > 0 given for empty " "id."); length = 0; } } self->idLength = length; if (self->autoMapToLc) { petscii_mapUpperGfxToLower(self->id, self->idLength); } CbmdosVfsEventArgs args = { .what = CVE_IDCHANGED }; Event_raise(self->changedEvent, &args); } SOEXPORT void CbmdosVfs_mapUpperGfxToLower(CbmdosVfs *self, int mapFiles) { if (mapFiles) { for (unsigned i = 0; i < self->fileCount; ++i) { CbmdosFile_mapUpperGfxToLower(self->files[i]); } } petscii_mapUpperGfxToLower(self->name, self->nameLength); CbmdosVfsEventArgs args = { .what = CVE_NAMECHANGED }; Event_raise(self->changedEvent, &args); petscii_mapUpperGfxToLower(self->id, self->idLength); args.what = CVE_IDCHANGED; Event_raise(self->changedEvent, &args); } SOEXPORT unsigned CbmdosVfs_fileCount(const CbmdosVfs *self) { return self->fileCount; } SOEXPORT const CbmdosFile *CbmdosVfs_rfile(const CbmdosVfs *self, unsigned pos) { if (pos >= self->fileCount) return 0; return self->files[pos]; } SOEXPORT CbmdosFile *CbmdosVfs_file(CbmdosVfs *self, unsigned pos) { if (pos >= self->fileCount) return 0; return self->files[pos]; } SOEXPORT int CbmdosVfs_delete(CbmdosVfs *self, const CbmdosFile *file) { unsigned pos; for (pos = 0; pos < self->fileCount; ++pos) { if (self->files[pos] == file) break; } if (pos == self->fileCount) { logmsg(L_WARNING, "CbmdosVfs_delete: file not found."); return -1; } return CbmdosVfs_deleteAt(self, pos); } SOEXPORT int CbmdosVfs_deleteAt(CbmdosVfs *self, unsigned pos) { if (pos >= self->fileCount) { logmsg(L_WARNING, "CbmdosVfs_deleteAt: file not found."); return -1; } CbmdosFile_destroy(self->files[pos]); if (pos < --self->fileCount) { memmove(self->files + pos, self->files + pos + 1, (self->fileCount - pos) * sizeof *self->files); } CbmdosVfsEventArgs args = { .what = CVE_FILEDELETED, .filepos = pos }; Event_raise(self->changedEvent, &args); return 0; } static int ensureSpace(CbmdosVfs *self) { if (self->fileCount == self->fileCapa) { unsigned newCapa = self->fileCapa + DIRCHUNKSIZE; if (newCapa <= self->fileCapa) { logmsg(L_ERROR, "CbmdosVfs: directory overflow."); return -1; } CbmdosFile **newFiles = realloc(self->files, newCapa * sizeof *newFiles); if (!newFiles) { logmsg(L_ERROR, "CbmdosVfs: memory allocation failed."); return -1; } self->files = newFiles; self->fileCapa = newCapa; } return 0; } SOEXPORT int CbmdosVfs_append(CbmdosVfs *self, CbmdosFile *file) { if (ensureSpace(self) < 0) return -1; self->files[self->fileCount++] = file; Event_register(CbmdosFile_changedEvent(file), self, fileHandler); CbmdosVfsEventArgs args = { .what = CVE_FILEADDED, .filepos = self->fileCount - 1 }; Event_raise(self->changedEvent, &args); return 0; } SOEXPORT int CbmdosVfs_insert(CbmdosVfs *self, CbmdosFile *file, unsigned pos) { if (pos >= self->fileCount) return CbmdosVfs_append(self, file); if (ensureSpace(self) < 0) return -1; memmove(self->files + pos + 1, self->files + pos, (self->fileCount++ - pos) * sizeof *self->files); self->files[pos] = file; Event_register(CbmdosFile_changedEvent(file), self, fileHandler); CbmdosVfsEventArgs args = { .what = CVE_FILEADDED, .filepos = pos }; Event_raise(self->changedEvent, &args); return 0; } SOEXPORT int CbmdosVfs_move(CbmdosVfs *self, unsigned to, unsigned from) { if (from >= self->fileCount) return -1; if (to >= self->fileCount) to = self->fileCount - 1; if (to == from) return 0; CbmdosFile *tmp = self->files[from]; if (to > from) { memmove(self->files + from, self->files + from + 1, (to - from) * sizeof *self->files); } else { memmove(self->files + to + 1, self->files + to, (from - to) * sizeof *self->files); } self->files[to] = tmp; CbmdosVfsEventArgs args = { .what = CVE_FILEMOVED, .filepos = from, .targetpos = to }; Event_raise(self->changedEvent, &args); return 0; } SOEXPORT void CbmdosVfs_getDirHeader(const CbmdosVfs *self, uint8_t *line) { memset(line, 0xa0, 24); line[0] = 0x22; line[17] = 0x22; line[22] = 0x32; line[23] = self->dosver; memcpy(line+1, self->name, self->nameLength); memcpy(line+19, self->id, self->idLength); } SOEXPORT int CbmdosVfs_autoMapToLc(const CbmdosVfs *self) { return self->autoMapToLc; } SOEXPORT void CbmdosVfs_setAutoMapToLc( CbmdosVfs *self, int autoMapToLc, int applyToFiles) { if (applyToFiles) { for (unsigned i = 0; i < self->fileCount; ++i) { CbmdosFile_setAutoMapToLc(self->files[i], autoMapToLc); } } self->autoMapToLc = !!autoMapToLc; } SOEXPORT Event *CbmdosVfs_changedEvent(CbmdosVfs *self) { return self->changedEvent; } SOEXPORT void CbmdosVfs_destroy(CbmdosVfs *self) { if (!self) return; for (unsigned pos = 0; pos < self->fileCount; ++pos) { CbmdosFile_destroy(self->files[pos]); } Event_destroy(self->changedEvent); free(self->files); free(self->name); free(self->id); free(self); }
2.421875
2
2024-11-18T22:28:07.993950+00:00
2020-02-15T00:48:41
d368c05ff4fdc1661d6025fde852e84b1a7fdde4
{ "blob_id": "d368c05ff4fdc1661d6025fde852e84b1a7fdde4", "branch_name": "refs/heads/master", "committer_date": "2020-02-15T00:48:41", "content_id": "083d05990a62f8e070f0fe432ceef0ee504565ba", "detected_licenses": [ "MIT" ], "directory_id": "c058ff6da33b8c80198c32013ad9a241cc8d28df", "extension": "c", "filename": "lab2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 237306917, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2688, "license": "MIT", "license_type": "permissive", "path": "/lab2.c", "provenance": "stackv2-0132.json.gz:66145", "repo_name": "Surya5599/xv6_concurrency", "revision_date": "2020-02-15T00:48:41", "revision_id": "7339adf02eff144b701be1f35569bef876fa5768", "snapshot_id": "48cd5998b1b51bccf2fa43abac03a698ae2cb661", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Surya5599/xv6_concurrency/7339adf02eff144b701be1f35569bef876fa5768/lab2.c", "visit_date": "2020-12-23T23:20:26.977149" }
stackv2
#include "types.h" #include "user.h" int main(int argc, char *argv[]) { int PScheduler(void); int priorityChange(void); if(atoi(argv[1]) == 1){ PScheduler(); } else if(atoi(argv[1]) == 2){ priorityChange(); } return 0; } int PScheduler(void){ // use this part to test the priority scheduler. Assuming that the priorities range between range between 0 to 31 // 0 is the highest priority and 31 is the lowest priority. int pid; int i,j,k; printf(1, "\n Step 2: testing the priority scheduler and setpriority(int priority)) systema call:\n"); printf(1, "\n Step 2: Assuming that the priorities range between range between 0 to 31\n"); printf(1, "\n Step 2: 31 is the highest priority. All processes have a default priority of 15\n"); printf(1, "\n Step 2: The parent processes will switch to priority 31\n"); setpriority(31); for (i = 0; i < 3; i++) { pid = fork(); if (pid > 0 ) { continue; } else if ( pid == 0) { setpriority(30-10*i); for (j=0;j<50000;j++) { for(k=0;k<1000;k++) { asm("nop"); } } printf(1, "\n child# %d with priority %d has finished! \n",getpid(),30-10*i); exit(0); } else { printf(2," \n Error \n"); } } if(pid > 0) { for (i = 0; i < 3; i++) { wait(0); } printf(1,"\n if processes with highest priority finished first then its correct \n"); } exit(0); return 0; } int priorityChange(void){ int pid; int i,j,k; printf(1, "\n Step 2: testing the aging properties systema call:\n"); printf(1, "\n Step 2: Assuming that the priorities range between range between 0 to 31\n"); printf(1, "\n Step 2: 31 is the highest priority. All processes have a default priority of 15\n"); printf(1, "\n Step 2: The parent processes will switch to priority 31\n"); setpriority(31); for (i = 0; i < 3; i++) { pid = fork(); if (pid > 0 ) { continue; } else if ( pid == 0) { setpriority(30-10*i); printf(1, "\n Starting child %d, priority to %d\n",getpid(), 30-10*i); for (j=0;j<50000;j++) { if(j % 10000 == 0 && j != 0){ printf(1, "\n child# %d with priority %d is running with priority %d\n",getpid(),30-10*i, getpriority()); } for(k=0;k<1000;k++) { asm("nop"); } } printf(1, "\n child# %d with priority %d has finished! With Priority %d\n",getpid(),30-10*i, getpriority()); exit(0); } else { printf(2," \n Error \n"); } } if(pid > 0) { for (i = 0; i < 3; i++) { wait(0); } printf(1,"\n if processes with highest priority finished first then its correct \n"); } exit(0); return 0; }
3.234375
3
2024-11-18T22:28:08.084766+00:00
2017-03-12T06:46:19
4ef5e46675af203920b9127dbfd8f8219f78a4a5
{ "blob_id": "4ef5e46675af203920b9127dbfd8f8219f78a4a5", "branch_name": "refs/heads/master", "committer_date": "2017-03-12T06:46:19", "content_id": "fa98f6628d9111549769de6121590a31aeb06802", "detected_licenses": [ "Apache-2.0" ], "directory_id": "135622a968ee1a32a9adb20aaf152658b768b0e8", "extension": "c", "filename": "dsk_memory_maximum_test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 16906023, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 247, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/C/C code/dsk_memory_maximum_test.c", "provenance": "stackv2-0132.json.gz:66274", "repo_name": "resolutedreamer/NeuroPass", "revision_date": "2017-03-12T06:46:19", "revision_id": "0d4046e5c1f31944b8d0a90647158d6c6bf66ca8", "snapshot_id": "5d74353c12d47f7ccbe95595f6b7713e3505864d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/resolutedreamer/NeuroPass/0d4046e5c1f31944b8d0a90647158d6c6bf66ca8/src/C/C code/dsk_memory_maximum_test.c", "visit_date": "2021-01-17T15:34:50.141258" }
stackv2
int main() { int i; double * test; printf("malloc-ing.\n"); test = (double*)malloc(2000*sizeof(double)); if (test == NULL) printf("mem allocation failure.\n"); else printf("mem allocation success.\n"); printf("done.\n"); return 0; }
2.4375
2
2024-11-18T22:28:08.196909+00:00
2014-08-19T13:12:55
43aa2714fbd77b42e99aff05de7e9a5e97eab8ed
{ "blob_id": "43aa2714fbd77b42e99aff05de7e9a5e97eab8ed", "branch_name": "refs/heads/master", "committer_date": "2014-08-19T13:12:55", "content_id": "2e0fd756bcf7cab50a69121641bd3b81ae6218fe", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "1e6229d38914c634bfc24859cb193ade9fc3ac19", "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": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2626, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0132.json.gz:66404", "repo_name": "clfa/fedorabk", "revision_date": "2014-08-19T13:12:55", "revision_id": "1941c727c596df6c9c7cb6d73154185c8045e846", "snapshot_id": "f3aa9e27a7e412c52e8a1d4a430217373b17dbd6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/clfa/fedorabk/1941c727c596df6c9c7cb6d73154185c8045e846/main.c", "visit_date": "2021-05-29T13:41:58.129138" }
stackv2
#include <getopt.h> #include <stdlib.h> #include "fedorabk.h" #include <string.h> #define PRINT(S) printf("%s\n", S); /*#define FOR_TEST*/ char cFrom[MAX_PATH] = "/home/example/Work"; char cTo[MAX_PATH] = "/mnt/data/Backup/fedora/Work"; const char* ProgName; const char* const ArgShortOpt = "h:q:l:f:t:v"; const struct option ArgLongOpt[] = { {"help", 0, NULL, 'h' }, {"quiet", 1, NULL, 'q' }, {"list", 1, NULL, 'l' }, {"from", 1, NULL, 'f' }, {"to", 1, NULL, 't' }, {"version", 1, NULL, 'v' }, {NULL, 0, NULL, 0 } }; void PrintHelp(FILE* stream, int exit_code) { fprintf(stream, "Usage: %s [options] [source-path dst-path]\n", ProgName); fprintf(stream, " -h --help Display this usage information.\n" " -q --quiet Quiet execute program.\n" " -l --list List backup or copy files.\n" " -f --from Source Path.\n" " -t --to Backup Path.\n" " -v --version Program version information.\n" ); exit(exit_code); } int main(int argc, char* argv[]) { if(argc == 1) { #ifndef FOR_TEST MakeBackup(cFrom, cTo, 1); #endif } else { int iList = 1; int iNexOpt; ProgName = argv[0]; do { iNexOpt = getopt_long(argc, argv, ArgShortOpt, ArgLongOpt, NULL); switch(iNexOpt) { case 'h': PrintHelp(stdout, 0); case 'q': iList = 0; break; case 'l': iList = 1; break; case 'f': strcpy(cFrom, optarg); break; case 't': strcpy(cTo, optarg); break; case 'v': printf("fedorabk v1.0\n"); break; default: break; } } while(iNexOpt != -1); #ifndef FOR_TEST MakeBackup(cFrom, cTo, iList); #endif } return 0; }
2.484375
2
2024-11-18T22:28:08.345913+00:00
2023-08-29T06:33:10
24d72fa55639128da15852ce6ee175171b6d3f52
{ "blob_id": "24d72fa55639128da15852ce6ee175171b6d3f52", "branch_name": "refs/heads/master", "committer_date": "2023-08-29T06:33:10", "content_id": "136479904d68bcce7370477d908b06f7a32ca464", "detected_licenses": [ "Apache-2.0" ], "directory_id": "676acab8ff535019faff7da3afb8eecc3fa127f5", "extension": "c", "filename": "cfft.c", "fork_events_count": 143, "gha_created_at": "2021-09-02T20:42:56", "gha_event_created_at": "2023-09-12T05:28:39", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 402557689, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13641, "license": "Apache-2.0", "license_type": "permissive", "path": "/target/cubepilot/cubeorange/libraries/stm32_lib/CMSIS/DSP/DSP_Lib_TestSuite/RefLibs/src/TransformFunctions/cfft.c", "provenance": "stackv2-0132.json.gz:66663", "repo_name": "Firmament-Autopilot/FMT-Firmware", "revision_date": "2023-08-29T06:33:10", "revision_id": "0212fe89820376bfbedaded519552f6b011a7b8a", "snapshot_id": "f8c324577245bd7e91af436954b4ce9421acbb41", "src_encoding": "UTF-8", "star_events_count": 351, "url": "https://raw.githubusercontent.com/Firmament-Autopilot/FMT-Firmware/0212fe89820376bfbedaded519552f6b011a7b8a/target/cubepilot/cubeorange/libraries/stm32_lib/CMSIS/DSP/DSP_Lib_TestSuite/RefLibs/src/TransformFunctions/cfft.c", "visit_date": "2023-09-01T11:37:46.194145" }
stackv2
#include "ref.h" #include "arm_const_structs.h" void ref_cfft_f32( const arm_cfft_instance_f32 * S, float32_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag) { int n, mmax, m, j, istep, i; float32_t wtemp, wr, wpr, wpi, wi, theta; float32_t tempr, tempi; float32_t * data = p1; uint32_t N = S->fftLen; int32_t dir = (ifftFlag) ? -1 : 1; // decrement pointer since the original version used fortran style indexing. data--; n = N << 1; j = 1; for (i = 1; i < n; i += 2) { if (j > i) { tempr = data[j]; data[j] = data[i]; data[i] = tempr; tempr = data[j+1]; data[j+1] = data[i+1]; data[i+1] = tempr; } m = n >> 1; while (m >= 2 && j > m) { j -= m; m >>= 1; } j += m; } mmax = 2; while (n > mmax) { istep = 2*mmax; theta = -6.283185307179586f/(dir*mmax); wtemp = sinf(0.5f*theta); wpr = -2.0f*wtemp*wtemp; wpi = sinf(theta); wr = 1.0f; wi = 0.0f; for (m = 1; m < mmax; m += 2) { for (i = m; i <= n; i += istep) { j =i + mmax; tempr = wr*data[j] - wi*data[j+1]; tempi = wr*data[j+1] + wi*data[j]; data[j] = data[i] - tempr; data[j+1] = data[i+1] - tempi; data[i] += tempr; data[i+1] += tempi; } wr = (wtemp = wr)*wpr - wi*wpi + wr; wi = wi*wpr + wtemp*wpi + wi; } mmax = istep; } // Inverse transform is scaled by 1/N if (ifftFlag) { data++; for(i = 0; i<2*N; i++) { data[i] /= N; } } } void ref_cfft_q31( const arm_cfft_instance_q31 * S, q31_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag) { uint32_t i; float32_t *fSrc = (float32_t*)p1; for(i=0;i<S->fftLen*2;i++) { //read the q31 data, cast to float, scale down for float fSrc[i] = (float32_t)p1[i] / 2147483648.0f; } switch(S->fftLen) { case 16: ref_cfft_f32(&arm_cfft_sR_f32_len16, fSrc, ifftFlag, bitReverseFlag); break; case 32: ref_cfft_f32(&arm_cfft_sR_f32_len32, fSrc, ifftFlag, bitReverseFlag); break; case 64: ref_cfft_f32(&arm_cfft_sR_f32_len64, fSrc, ifftFlag, bitReverseFlag); break; case 128: ref_cfft_f32(&arm_cfft_sR_f32_len128, fSrc, ifftFlag, bitReverseFlag); break; case 256: ref_cfft_f32(&arm_cfft_sR_f32_len256, fSrc, ifftFlag, bitReverseFlag); break; case 512: ref_cfft_f32(&arm_cfft_sR_f32_len512, fSrc, ifftFlag, bitReverseFlag); break; case 1024: ref_cfft_f32(&arm_cfft_sR_f32_len1024, fSrc, ifftFlag, bitReverseFlag); break; case 2048: ref_cfft_f32(&arm_cfft_sR_f32_len2048, fSrc, ifftFlag, bitReverseFlag); break; case 4096: ref_cfft_f32(&arm_cfft_sR_f32_len4096, fSrc, ifftFlag, bitReverseFlag); break; } if (ifftFlag) { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q31, cast to q31 p1[i] = (q31_t)( fSrc[i] * 2147483648.0f ); } } else { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q31, cast to q31 p1[i] = (q31_t)( fSrc[i] * 2147483648.0f / (float32_t)S->fftLen); } } } void ref_cfft_q15( const arm_cfft_instance_q15 * S, q15_t * pSrc, uint8_t ifftFlag, uint8_t bitReverseFlag) { uint32_t i; float32_t *fSrc = (float32_t*)pSrc; for(i=0;i<S->fftLen*2;i++) { //read the q15 data, cast to float, scale down for float, place in temporary buffer scratchArray[i] = (float32_t)pSrc[i] / 32768.0f; } for(i=0;i<S->fftLen*2;i++) { //copy from temp buffer to final buffer fSrc[i] = scratchArray[i]; } switch(S->fftLen) { case 16: ref_cfft_f32(&arm_cfft_sR_f32_len16, fSrc, ifftFlag, bitReverseFlag); break; case 32: ref_cfft_f32(&arm_cfft_sR_f32_len32, fSrc, ifftFlag, bitReverseFlag); break; case 64: ref_cfft_f32(&arm_cfft_sR_f32_len64, fSrc, ifftFlag, bitReverseFlag); break; case 128: ref_cfft_f32(&arm_cfft_sR_f32_len128, fSrc, ifftFlag, bitReverseFlag); break; case 256: ref_cfft_f32(&arm_cfft_sR_f32_len256, fSrc, ifftFlag, bitReverseFlag); break; case 512: ref_cfft_f32(&arm_cfft_sR_f32_len512, fSrc, ifftFlag, bitReverseFlag); break; case 1024: ref_cfft_f32(&arm_cfft_sR_f32_len1024, fSrc, ifftFlag, bitReverseFlag); break; case 2048: ref_cfft_f32(&arm_cfft_sR_f32_len2048, fSrc, ifftFlag, bitReverseFlag); break; case 4096: ref_cfft_f32(&arm_cfft_sR_f32_len4096, fSrc, ifftFlag, bitReverseFlag); break; } if (ifftFlag) { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q15, cast to q15 pSrc[i] = (q15_t)( fSrc[i] * 32768.0f ); } } else { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q15, cast to q15 pSrc[i] = (q15_t)( fSrc[i] * 32768.0f / (float32_t)S->fftLen); } } } void ref_cfft_radix2_f32( const arm_cfft_radix2_instance_f32 * S, float32_t * pSrc) { switch(S->fftLen) { case 16: ref_cfft_f32(&arm_cfft_sR_f32_len16, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 32: ref_cfft_f32(&arm_cfft_sR_f32_len32, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 64: ref_cfft_f32(&arm_cfft_sR_f32_len64, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 128: ref_cfft_f32(&arm_cfft_sR_f32_len128, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 256: ref_cfft_f32(&arm_cfft_sR_f32_len256, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 512: ref_cfft_f32(&arm_cfft_sR_f32_len512, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 1024: ref_cfft_f32(&arm_cfft_sR_f32_len1024, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 2048: ref_cfft_f32(&arm_cfft_sR_f32_len2048, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 4096: ref_cfft_f32(&arm_cfft_sR_f32_len4096, pSrc, S->ifftFlag, S->bitReverseFlag); break; } } void ref_cfft_radix2_q31( const arm_cfft_radix2_instance_q31 * S, q31_t * pSrc) { uint32_t i; float32_t *fSrc = (float32_t*)pSrc; for(i=0;i<S->fftLen*2;i++) { //read the q31 data, cast to float, scale down for float fSrc[i] = (float32_t)pSrc[i] / 2147483648.0f; } switch(S->fftLen) { case 16: ref_cfft_f32(&arm_cfft_sR_f32_len16, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 32: ref_cfft_f32(&arm_cfft_sR_f32_len32, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 64: ref_cfft_f32(&arm_cfft_sR_f32_len64, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 128: ref_cfft_f32(&arm_cfft_sR_f32_len128, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 256: ref_cfft_f32(&arm_cfft_sR_f32_len256, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 512: ref_cfft_f32(&arm_cfft_sR_f32_len512, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 1024: ref_cfft_f32(&arm_cfft_sR_f32_len1024, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 2048: ref_cfft_f32(&arm_cfft_sR_f32_len2048, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 4096: ref_cfft_f32(&arm_cfft_sR_f32_len4096, fSrc, S->ifftFlag, S->bitReverseFlag); break; } if (S->ifftFlag) { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q31, cast to q31 pSrc[i] = (q31_t)( fSrc[i] * 2147483648.0f ); } } else { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q31, cast to q31 pSrc[i] = (q31_t)( fSrc[i] * 2147483648.0f / (float32_t)S->fftLen); } } } void ref_cfft_radix2_q15( const arm_cfft_radix2_instance_q15 * S, q15_t * pSrc) { uint32_t i; float32_t *fSrc = (float32_t*)pSrc; for(i=0;i<S->fftLen*2;i++) { //read the q15 data, cast to float, scale down for float, place in temporary buffer scratchArray[i] = (float32_t)pSrc[i] / 32768.0f; } for(i=0;i<S->fftLen*2;i++) { //copy from temp buffer to final buffer fSrc[i] = scratchArray[i]; } switch(S->fftLen) { case 16: ref_cfft_f32(&arm_cfft_sR_f32_len16, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 32: ref_cfft_f32(&arm_cfft_sR_f32_len32, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 64: ref_cfft_f32(&arm_cfft_sR_f32_len64, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 128: ref_cfft_f32(&arm_cfft_sR_f32_len128, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 256: ref_cfft_f32(&arm_cfft_sR_f32_len256, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 512: ref_cfft_f32(&arm_cfft_sR_f32_len512, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 1024: ref_cfft_f32(&arm_cfft_sR_f32_len1024, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 2048: ref_cfft_f32(&arm_cfft_sR_f32_len2048, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 4096: ref_cfft_f32(&arm_cfft_sR_f32_len4096, fSrc, S->ifftFlag, S->bitReverseFlag); break; } if (S->ifftFlag) { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q15, cast to q15 pSrc[i] = (q15_t)( fSrc[i] * 32768.0f ); } } else { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q15, cast to q15 pSrc[i] = (q15_t)( fSrc[i] * 32768.0f / (float32_t)S->fftLen); } } } void ref_cfft_radix4_f32( const arm_cfft_radix4_instance_f32 * S, float32_t * pSrc) { switch(S->fftLen) { case 16: ref_cfft_f32(&arm_cfft_sR_f32_len16, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 32: ref_cfft_f32(&arm_cfft_sR_f32_len32, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 64: ref_cfft_f32(&arm_cfft_sR_f32_len64, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 128: ref_cfft_f32(&arm_cfft_sR_f32_len128, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 256: ref_cfft_f32(&arm_cfft_sR_f32_len256, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 512: ref_cfft_f32(&arm_cfft_sR_f32_len512, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 1024: ref_cfft_f32(&arm_cfft_sR_f32_len1024, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 2048: ref_cfft_f32(&arm_cfft_sR_f32_len2048, pSrc, S->ifftFlag, S->bitReverseFlag); break; case 4096: ref_cfft_f32(&arm_cfft_sR_f32_len4096, pSrc, S->ifftFlag, S->bitReverseFlag); break; } } void ref_cfft_radix4_q31( const arm_cfft_radix4_instance_q31 * S, q31_t * pSrc) { uint32_t i; float32_t *fSrc = (float32_t*)pSrc; for(i=0;i<S->fftLen*2;i++) { //read the q31 data, cast to float, scale down for float fSrc[i] = (float32_t)pSrc[i] / 2147483648.0f; } switch(S->fftLen) { case 16: ref_cfft_f32(&arm_cfft_sR_f32_len16, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 32: ref_cfft_f32(&arm_cfft_sR_f32_len32, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 64: ref_cfft_f32(&arm_cfft_sR_f32_len64, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 128: ref_cfft_f32(&arm_cfft_sR_f32_len128, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 256: ref_cfft_f32(&arm_cfft_sR_f32_len256, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 512: ref_cfft_f32(&arm_cfft_sR_f32_len512, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 1024: ref_cfft_f32(&arm_cfft_sR_f32_len1024, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 2048: ref_cfft_f32(&arm_cfft_sR_f32_len2048, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 4096: ref_cfft_f32(&arm_cfft_sR_f32_len4096, fSrc, S->ifftFlag, S->bitReverseFlag); break; } if (S->ifftFlag) { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q31, cast to q31 pSrc[i] = (q31_t)( fSrc[i] * 2147483648.0f ); } } else { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q31, cast to q31 pSrc[i] = (q31_t)( fSrc[i] * 2147483648.0f / (float32_t)S->fftLen); } } } void ref_cfft_radix4_q15( const arm_cfft_radix4_instance_q15 * S, q15_t * pSrc) { uint32_t i; float32_t *fSrc = (float32_t*)pSrc; for(i=0;i<S->fftLen*2;i++) { //read the q15 data, cast to float, scale down for float, place in temporary buffer scratchArray[i] = (float32_t)pSrc[i] / 32768.0f; } for(i=0;i<S->fftLen*2;i++) { //copy from temp buffer to final buffer fSrc[i] = scratchArray[i]; } switch(S->fftLen) { case 16: ref_cfft_f32(&arm_cfft_sR_f32_len16, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 32: ref_cfft_f32(&arm_cfft_sR_f32_len32, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 64: ref_cfft_f32(&arm_cfft_sR_f32_len64, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 128: ref_cfft_f32(&arm_cfft_sR_f32_len128, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 256: ref_cfft_f32(&arm_cfft_sR_f32_len256, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 512: ref_cfft_f32(&arm_cfft_sR_f32_len512, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 1024: ref_cfft_f32(&arm_cfft_sR_f32_len1024, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 2048: ref_cfft_f32(&arm_cfft_sR_f32_len2048, fSrc, S->ifftFlag, S->bitReverseFlag); break; case 4096: ref_cfft_f32(&arm_cfft_sR_f32_len4096, fSrc, S->ifftFlag, S->bitReverseFlag); break; } if (S->ifftFlag) { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q15, cast to q15 pSrc[i] = (q15_t)( fSrc[i] * 32768.0f ); } } else { for(i=0;i<S->fftLen*2;i++) { //read the float data, scale up for q15, cast to q15 pSrc[i] = (q15_t)( fSrc[i] * 32768.0f / (float32_t)S->fftLen); } } }
2.484375
2
2024-11-18T22:28:08.681357+00:00
2021-08-10T08:59:19
85d9e079d6d700e7f1a4b6f97effcf6b6f5f65ce
{ "blob_id": "85d9e079d6d700e7f1a4b6f97effcf6b6f5f65ce", "branch_name": "refs/heads/master", "committer_date": "2021-08-10T08:59:19", "content_id": "09abb71fd06097038a938a0c9d33f40476b8a3ea", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "5ddbfac096f97973306f682887a3df32b6b34b8a", "extension": "h", "filename": "pfile.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 284419617, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 565, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/pfile.h", "provenance": "stackv2-0132.json.gz:67054", "repo_name": "junjihashimoto/ximageviewer", "revision_date": "2021-08-10T08:59:19", "revision_id": "ed2eddcd16dea06ea0de3897d7164d89928a5d0f", "snapshot_id": "1bad893dafe091afadcc7ea358189465b381fd89", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/junjihashimoto/ximageviewer/ed2eddcd16dea06ea0de3897d7164d89928a5d0f/pfile.h", "visit_date": "2023-07-04T09:16:54.200666" }
stackv2
#ifndef FILECPP_H #define FILECPP_H #ifdef WIN32 extern "C"{ #include <windows.h> #include <io.h> #include <direct.h> #include <sys/stat.h> #include <fcntl.h> } #include <cstdio> typedef int FD; typedef LONG OFF_T; #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 inline int mkdir(const char* dir,int mode){ return mkdir(dir); } #else //WIN32 extern "C"{ #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <errno.h> } typedef int FD; #endif //WIN32 #endif // FILECPP_H
2.03125
2
2024-11-18T22:28:08.776681+00:00
2022-10-03T00:11:46
627437cfee5a0aead84535ffda755d5705df4bbc
{ "blob_id": "627437cfee5a0aead84535ffda755d5705df4bbc", "branch_name": "refs/heads/master", "committer_date": "2022-10-03T00:11:46", "content_id": "f3908a2589ec31918982e4c1a9da2f9e947a4a9d", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "7c7d6f504bfde6685e761ac5fe0dedf0c60b5479", "extension": "h", "filename": "arch_intrinsics.h", "fork_events_count": 141, "gha_created_at": "2014-07-04T14:00:07", "gha_event_created_at": "2023-06-05T05:24:31", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 21498990, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 623, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/cbits/decaf/include/arch_32/arch_intrinsics.h", "provenance": "stackv2-0132.json.gz:67184", "repo_name": "haskell-crypto/cryptonite", "revision_date": "2022-10-03T00:11:46", "revision_id": "d163f69512a3d162baa69a95927f3d6369833f7d", "snapshot_id": "504a55915321cd771a1dedf402f28c4948b76dfd", "src_encoding": "UTF-8", "star_events_count": 224, "url": "https://raw.githubusercontent.com/haskell-crypto/cryptonite/d163f69512a3d162baa69a95927f3d6369833f7d/cbits/decaf/include/arch_32/arch_intrinsics.h", "visit_date": "2023-02-05T01:38:40.411460" }
stackv2
/* Copyright (c) 2016 Cryptography Research, Inc. * Released under the MIT License. See LICENSE.txt for license information. */ #ifndef __ARCH_ARCH_32_ARCH_INTRINSICS_H__ #define __ARCH_ARCH_32_ARCH_INTRINSICS_H__ #define ARCH_WORD_BITS 32 static __inline__ __attribute((always_inline,unused)) uint32_t word_is_zero(uint32_t a) { /* let's hope the compiler isn't clever enough to optimize this. */ return (((uint64_t)a)-1)>>32; } static __inline__ __attribute((always_inline,unused)) uint64_t widemul(uint32_t a, uint32_t b) { return ((uint64_t)a) * b; } #endif /* __ARCH_ARM_32_ARCH_INTRINSICS_H__ */
2.15625
2
2024-11-18T22:28:09.553082+00:00
2023-09-01T10:48:17
338a43032c4e04f93b229602f7ecc2f0ec3e305a
{ "blob_id": "338a43032c4e04f93b229602f7ecc2f0ec3e305a", "branch_name": "refs/heads/master", "committer_date": "2023-09-01T10:48:17", "content_id": "bd1e96f7827979d72a8971d81ef974e4417c344c", "detected_licenses": [ "MIT" ], "directory_id": "228640e0cf31aa1f34ef41de74a071b8bb6c970e", "extension": "c", "filename": "output.c", "fork_events_count": 24, "gha_created_at": "2018-08-04T16:29:54", "gha_event_created_at": "2023-07-19T07:57:23", "gha_language": "Nix", "gha_license_id": null, "github_id": 143545025, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7274, "license": "MIT", "license_type": "permissive", "path": "/repos/fortuneteller2k/pkgs/tiramisu/src/src/output.c", "provenance": "stackv2-0132.json.gz:67702", "repo_name": "nix-community/nur-combined", "revision_date": "2023-09-01T10:48:17", "revision_id": "f697e5f9607548252db151fb423e03a7eb53392f", "snapshot_id": "064d953e50b4cc4e6cb1d8d1b82f958f53d412f4", "src_encoding": "UTF-8", "star_events_count": 96, "url": "https://raw.githubusercontent.com/nix-community/nur-combined/f697e5f9607548252db151fb423e03a7eb53392f/repos/fortuneteller2k/pkgs/tiramisu/src/src/output.c", "visit_date": "2023-09-01T12:18:28.204100" }
stackv2
#include <stdio.h> #include <glib.h> #include "tiramisu.h" #include "output.h" char *sanitize(const char *string) { /* allocating double the size of the original string should be enough */ char *out = calloc(strlen(string) * 2 + 1, 1); while (*string) { if (*string == '"') strcat(out, "\\\""); else if (*string == '\n') strcat(out, "\\n"); else out[strlen(out)] = *string; string++; } return out; } void output_notification(GVariant *parameters) { GVariantIter iterator; gchar *app_name; guint32 replaces_id; gchar *app_icon; gchar *summary; gchar *body; gchar **actions; GVariant *hints; gint32 timeout; g_variant_iter_init(&iterator, parameters); g_variant_iter_next(&iterator, "s", &app_name); g_variant_iter_next(&iterator, "u", &replaces_id); g_variant_iter_next(&iterator, "s", &app_icon); g_variant_iter_next(&iterator, "s", &summary); g_variant_iter_next(&iterator, "s", &body); g_variant_iter_next(&iterator, "^a&s", &actions); g_variant_iter_next(&iterator, "@a{sv}", &hints); g_variant_iter_next(&iterator, "i", &timeout); char *app_name_sanitized = sanitize(app_name); char *app_icon_sanitized = sanitize(app_icon); char *summary_sanitized = sanitize(summary); char *body_sanitized = sanitize(body); if (print_json) json_output(app_name_sanitized, app_icon_sanitized, replaces_id, timeout, hints, actions, summary_sanitized, body_sanitized); else default_output(app_name_sanitized, app_icon_sanitized, replaces_id, timeout, hints, actions, summary_sanitized, body_sanitized); free(app_name_sanitized); free(app_icon_sanitized); free(app_name); free(app_icon); free(actions); free(summary); free(body); free(summary_sanitized); free(body_sanitized); fflush(stdout); } void hints_output_iterator(GVariant *hints, const char *str_format, const char *int_format, const char *uint_format, const char *double_format, const char *boolean_format, const char *byte_format, const char *err_format, const char *element_delimiter) { GVariantIter iterator; gchar *key; GVariant *value; unsigned int index = 0; char *value_sanitized; g_variant_iter_init(&iterator, hints); while (g_variant_iter_loop(&iterator, "{sv}", &key, NULL)) { if (index) printf(element_delimiter); /* Strings */ if ((value = g_variant_lookup_value(hints, key, GT_STRING))) { value_sanitized = sanitize(g_variant_get_string(value, NULL)); printf(str_format, key, value_sanitized); free(value_sanitized); } /* Integers */ else if ((value = g_variant_lookup_value(hints, key, GT_INT16))) printf(int_format, key, g_variant_get_int16(value)); else if ((value = g_variant_lookup_value(hints, key, GT_INT32))) printf(int_format, key, g_variant_get_int32(value)); else if ((value = g_variant_lookup_value(hints, key, GT_INT64))) printf(int_format, key, g_variant_get_int64(value)); /* Unsigned integers */ else if ((value = g_variant_lookup_value(hints, key, GT_UINT16))) printf(uint_format, key, g_variant_get_uint16(value)); else if ((value = g_variant_lookup_value(hints, key, GT_UINT32))) printf(uint_format, key, g_variant_get_uint32(value)); else if ((value = g_variant_lookup_value(hints, key, GT_UINT64))) printf(uint_format, key, g_variant_get_uint64(value)); /* Doubles */ else if ((value = g_variant_lookup_value(hints, key, GT_DOUBLE))) printf(double_format, key, g_variant_get_double(value)); /* Bytes */ else if ((value = g_variant_lookup_value(hints, key, GT_BYTE))) printf(byte_format, key, g_variant_get_byte(value)); /* Booleans */ else if ((value = g_variant_lookup_value(hints, key, GT_BOOL))) printf(boolean_format, key, g_variant_get_boolean(value)); else { // value is of unknown type printf(err_format, key); index++; continue; } g_variant_unref(value); index++; } g_variant_unref(hints); } void default_output(gchar *app_name, gchar *app_icon, guint32 replaces_id, gint32 timeout, GVariant *hints, gchar **actions, gchar *summary, gchar *body) { printf("app_name: %s%sapp_icon: %s%sreplaces_id: %u%stimeout: %d%s", app_name, delimiter, app_icon, delimiter, replaces_id, delimiter, timeout, delimiter); printf("hints:%s", delimiter); char *str_format = calloc(64, sizeof(char)), // should be enough *int_format = calloc(64, sizeof(char)), *uint_format = calloc(64, sizeof(char)), *double_format = calloc(64, sizeof(char)), *boolean_format = calloc(64, sizeof(char)), *byte_format = calloc(64, sizeof(char)), *err_format = calloc(64, sizeof(char)); sprintf(str_format, "\t%%s: %%s%s", delimiter); sprintf(int_format, "\t%%s: %%d%s", delimiter); sprintf(uint_format, "\t%%s: %%u%s", delimiter); sprintf(double_format, "\t%%s: %%f%s", delimiter); sprintf(boolean_format, "\t%%s: %%x%s", delimiter); sprintf(byte_format, "\t%%s: %%d%s", delimiter); sprintf(err_format, "\t%%s:%s", delimiter); hints_output_iterator(hints, str_format, int_format, uint_format, double_format, boolean_format, byte_format, err_format, ""); free(str_format); free(int_format); free(uint_format); free(double_format); free(boolean_format); free(byte_format); free(err_format); printf("actions:%s", delimiter); unsigned int index = 0; while (actions[index] && actions[index + 1]) { printf("\t%s: %s%s", actions[index + 1], actions[index], delimiter); index += 2; } printf("summary: %s%sbody: %s%s", summary, delimiter, body, delimiter); } void json_output(gchar *app_name, gchar *app_icon, guint32 replaces_id, gint32 timeout, GVariant *hints, gchar **actions, gchar *summary, gchar *body) { printf("{" "\"app_name\": \"%s\", " "\"app_icon\": \"%s\", " "\"replaces_id\": %u, " "\"timeout\": %d, ", app_name, app_icon, replaces_id, timeout); printf("\"hints\": {"); hints_output_iterator(hints, "\"%s\": \"%s\"", "\"%s\": %d", "\"%s\": %u", "\"%s\": %f", "\"%s\": %x", "\"%s\": %d", "\"%s\": \"\"", ", "); printf("}, \"actions\": {"); unsigned int index = 0; while (actions[index] && actions[index + 1]) { if (index) printf(", "); printf("\"%s\": \"%s\"", actions[index + 1], actions[index]); index += 2; } printf("}, "); printf("\"summary\": \"%s\", " "\"body\": \"%s\"}\n", summary, body); }
2.34375
2
2024-11-18T22:28:09.640109+00:00
2022-11-03T03:45:28
3d5eb28df9d01db02ee65efe717409c6ab969746
{ "blob_id": "3d5eb28df9d01db02ee65efe717409c6ab969746", "branch_name": "refs/heads/master", "committer_date": "2022-11-03T03:45:28", "content_id": "d30d7769bc4b7afb16f4cd3aeb2993daa8c7fb2f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "dc6b8fb257a820e378ca5fca55466031190da3ca", "extension": "c", "filename": "string.c", "fork_events_count": 8, "gha_created_at": "2019-12-17T05:40:35", "gha_event_created_at": "2020-09-18T07:39:31", "gha_language": "Verilog", "gha_license_id": "BSD-3-Clause", "github_id": 228541400, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8276, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/sw/elibc/string.c", "provenance": "stackv2-0132.json.gz:67831", "repo_name": "eisl-nctu/aquila", "revision_date": "2022-11-03T03:45:28", "revision_id": "c113ae45c2c10ecfb738b19cae7ef07b842e8e83", "snapshot_id": "c1ca62a1632fd8b01a1d3d86d3e276c0c0536205", "src_encoding": "UTF-8", "star_events_count": 20, "url": "https://raw.githubusercontent.com/eisl-nctu/aquila/c113ae45c2c10ecfb738b19cae7ef07b842e8e83/sw/elibc/string.c", "visit_date": "2022-11-04T05:52:15.110582" }
stackv2
// ============================================================================= // Program : string.c // Author : Chun-Jen Tsai // Date : Dec/09/2019 // ----------------------------------------------------------------------------- // Description: // This is the minimal string library for aquila. // ----------------------------------------------------------------------------- // Revision information: // // Oct/6/2020, by Chun-Jen Tsai: // Replace strcpy(), strncpy(), strncmp(), and strcmp() with code extracted // from the RISC-V port of Newlib at https://github.com/riscv/riscv-newlib. // These functions boost DMIPS by 28.5%. // ----------------------------------------------------------------------------- // License information: // // This software is released under the BSD-3-Clause Licence, // see https://opensource.org/licenses/BSD-3-Clause for details. // In the following license statements, "software" refers to the // "source code" of the complete hardware/software system. // // Copyright 2019, // Embedded Intelligent Systems Lab (EISL) // Deparment of Computer Science // National Chiao Tung Uniersity // Hsinchu, Taiwan. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ============================================================================= #include <stdio.h> #include <string.h> // ------------------------------------------------------------------------------ // Functions extracted from Newlib. // #define UNALIGNED(X,Y) (((long)X & (sizeof(long)-1))|((long)Y & (sizeof(long)-1))) #define DETECTNULL(X) (((X)-0x01010101) & ~(X) & 0x80808080) char *strcpy(char *dst, char *src) { char *dst0 = dst; const char *src0 = src; long *aligned_dst; const long *aligned_src; // If SRC or DEST is unaligned, then copy bytes. if (!UNALIGNED(src0, dst0)) { aligned_dst = (long *) dst0; aligned_src = (long *) src0; // Perform word copying since both strings are word-aligned. while (!DETECTNULL(*aligned_src)) { *aligned_dst++ = *aligned_src++; } dst0 = (char *) aligned_dst; src0 = (char *) aligned_src; } // Copying trailing bytes for aligned strings, or the entire // strings if not aligned. while ((*dst0++ = *src0++)) ; return dst; } int strcmp(char *s1, char *s2) { unsigned long *a1; unsigned long *a2; /* If s1 or s2 are unaligned, then compare bytes. */ if (!UNALIGNED(s1, s2)) { /* If s1 and s2 are word-aligned, compare them a word at a time. */ a1 = (unsigned long *) s1; a2 = (unsigned long *) s2; while (*a1 == *a2) { /* To get here, *a1 == *a2, thus if we find a null in *a1, then the strings must be equal, so return zero. */ if (DETECTNULL(*a1)) return 0; a1++; a2++; } /* A difference was detected in last few bytes of s1, so search bytewise */ s1 = (char *) a1; s2 = (char *) a2; } while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } return (*s1 - *s2); } char *strncpy(char *dst, char *src, size_t n) { char *dst0 = dst; const char *src0 = src; long *aligned_dst; const long *aligned_src; // If SRC or DEST is unaligned, then copy bytes. if (!UNALIGNED(src0, dst0)) { aligned_dst = (long *) dst0; aligned_src = (long *) src0; // Perform word copying since both strings are word-aligned. while (!DETECTNULL(*aligned_src) && n > sizeof(long)) { *aligned_dst++ = *aligned_src++; n -= sizeof(long); } dst0 = (char *) aligned_dst; src0 = (char *) aligned_src; } // Copying trailing bytes for aligned strings, or the entire // strings if not aligned. while ((*dst0++ = *src0++) && n-- > 0) ; if (++n == 0) *dst0 = 0; return dst; } int strncmp(char *s1, char *s2, size_t n) { unsigned long *a1; unsigned long *a2; /* If s1 or s2 are unaligned, then compare bytes. */ if (!UNALIGNED(s1, s2)) { /* If s1 and s2 are word-aligned, compare them a word at a time. */ a1 = (unsigned long *) s1; a2 = (unsigned long *) s2; while (*a1 == *a2 && n > sizeof(long)) { /* To get here, *a1 == *a2, thus if we find a null in *a1, then the strings must be equal, so return zero. */ if (DETECTNULL(*a1)) return 0; a1++; a2++; n -= sizeof(long); } /* A difference was detected in last few bytes of s1, so search bytewise */ s1 = (char *) a1; s2 = (char *) a2; } while (--n && *s1 != '\0' && *s1 == *s2) { s1++; s2++; } return (*s1 - *s2); } void *memcpy(void *d, void *s, size_t n) { char *d0 = d; const char *s0 = s; long *aligned_d; const long *aligned_s; // If SRC or DEST is unaligned, then copy bytes. if (!UNALIGNED(s0, d0)) { aligned_d = (long *) d0; aligned_s = (long *) s0; // Perform word copying since both pointers are word-aligned. while (!DETECTNULL(*aligned_s) && n > sizeof(long)) { *aligned_d++ = *aligned_s++; n -= sizeof(long); } d0 = (char *) aligned_d; s0 = (char *) aligned_s; } // Copying trailing bytes for aligned memory block, or the entire // memory block if not aligned. while ((*d0++ = *s0++) && n-- > 0) ; if (++n == 0) *d0 = 0; return d; } // End of functions extracted from Newlib. // ------------------------------------------------------------------------------ void *memmove(void *d, void *s, size_t n) { unsigned char *dst = (unsigned char *) d + n - 1; unsigned char *src = (unsigned char *) s + n - 1; if ((unsigned) d >= (unsigned) s && (unsigned) d <= (unsigned) s + n) { while (n--) *(dst--) = *(src--); } else memcpy(d, s, n); return d; } void *memset(void *d, int v, size_t n) { unsigned char *dst = (unsigned char *) d; while (n--) *(dst++) = (unsigned char) v; return d; } long strlen(char *s) { long n = 0; while (*s++) n++; return n; } char *strcat(char *dst, char *src) { char *tmp = dst; while (*tmp) tmp++; while (*src) *(tmp++) = *(src++); *tmp = 0; return dst; } char *strncat(char *dst, char *src, size_t n) { char *tmp = dst; while (*tmp) tmp++; while (*src && n) *(tmp++) = *(src++), n--; *tmp = 0; return dst; }
2.4375
2
2024-11-18T22:28:09.702236+00:00
2014-02-08T00:10:50
e36aa2ac7a542d67490bd3be02c91f99d17d20d3
{ "blob_id": "e36aa2ac7a542d67490bd3be02c91f99d17d20d3", "branch_name": "refs/heads/master", "committer_date": "2014-02-08T00:10:50", "content_id": "eb6fd23fd1ee28507ed847811ec171315c132494", "detected_licenses": [ "MIT" ], "directory_id": "cb1617a9385b800c5a6b45c2b81e4da49d73798c", "extension": "c", "filename": "unescape.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 4105656, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3449, "license": "MIT", "license_type": "permissive", "path": "/tests/unescape.c", "provenance": "stackv2-0132.json.gz:67961", "repo_name": "jedisct1/jsonsl", "revision_date": "2014-02-08T00:10:50", "revision_id": "8b8aced6ee3c3198f488bdfbcd11631173d02758", "snapshot_id": "9113b4924b238c1822de21384e744039ff624cd6", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jedisct1/jsonsl/8b8aced6ee3c3198f488bdfbcd11631173d02758/tests/unescape.c", "visit_date": "2023-05-29T14:48:47.855715" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <jsonsl.h> #include <assert.h> #include <wchar.h> #include <locale.h> #include <string.h> #include "all-tests.h" static size_t res; static jsonsl_error_t err; static char *out; static int strtable[0xff] = { 0 }; const char *escaped; /** * Check a single octet escape of four hex digits */ void test_single_uescape(void) { escaped = "\\u002B"; strtable['u'] = 1; out = malloc(strlen(escaped)+1); res = jsonsl_util_unescape(escaped, out, strlen(escaped), strtable, &err); assert(res == 1); assert(out[0] == 0x2b); free(out); } /** * Test that we handle the null escape correctly (or that we do it right) */ void test_null_escape(void) { escaped = "\\u0000"; strtable['u'] = 1; out = malloc(strlen(escaped)+1); res = jsonsl_util_unescape(escaped, out, strlen(escaped), strtable, &err); assert(res == 1); assert(out[0] == '\0'); free(out); } /** * Test multiple sequences of escapes. */ void test_multibyte_escape(void) { int mbres; jsonsl_special_t flags; wchar_t dest[4]; /* שלום */ escaped = "\\uD7A9\\uD79C\\uD795\\uD79D"; strtable['u'] = 1; out = malloc(strlen(escaped)); res = jsonsl_util_unescape_ex(escaped, out, strlen(escaped), strtable, &flags, &err, NULL); assert(res == 8); mbres = mbstowcs(dest, out, 4); assert(memcmp(L"שלום", dest, 8) == 0); assert(flags & JSONSL_SPECIALf_NONASCII); free(out); } /** * Check that things we don't want being unescaped are not unescaped */ void test_ignore_escape(void) { escaped = "Some \\nWeird String"; out = malloc(strlen(escaped)+1); strtable['W'] = 0; res = jsonsl_util_unescape(escaped, out, strlen(escaped), strtable, &err); out[res] = '\0'; assert(res == strlen(escaped)); assert(strncmp(escaped, out, res) == 0); escaped = "\\tA String"; res = jsonsl_util_unescape(escaped, out, strlen(escaped), strtable, &err); out[res] = '\0'; assert(res == strlen(escaped)); assert(strncmp(escaped, out, res) == 0); free(out); } /** * Check that the built-in mappings for the 'sane' defaults work */ void test_replacement_escape(void) { escaped = "This\\tIs\\tA\\tTab"; out = malloc(strlen(escaped)+1); strtable['t'] = 1; res = jsonsl_util_unescape(escaped, out, strlen(escaped), strtable, &err); assert(res > 0); out[res] = '\0'; assert(out[4] == '\t'); assert(strcmp(out, "This\tIs\tA\tTab") == 0); free(out); } void test_invalid_escape(void) { escaped = "\\invalid \\escape"; out = malloc(strlen(escaped)+1); res = jsonsl_util_unescape(escaped, out, strlen(escaped), strtable, &err); assert(res == 0); assert(err == JSONSL_ERROR_ESCAPE_INVALID); free(out); } JSONSL_TEST_UNESCAPE_FUNC { char *curlocale = setlocale(LC_ALL, ""); test_single_uescape(); test_null_escape(); if (curlocale && strstr(curlocale, "UTF-8") != NULL) { test_multibyte_escape(); } else { fprintf(stderr, "Skipping multibyte tests because LC_ALL is not set to UTF8\n"); } test_ignore_escape(); test_replacement_escape(); test_invalid_escape(); return 0; }
2.5625
3
2024-11-18T22:28:10.191886+00:00
2016-01-15T10:06:49
efc12e81034034f704f9587e51837c37aa3576a9
{ "blob_id": "efc12e81034034f704f9587e51837c37aa3576a9", "branch_name": "refs/heads/master", "committer_date": "2016-01-15T10:06:49", "content_id": "cf7d8b7fc4014505001077ca3766af56cf1391ba", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "9ccbd44704f098690d63458a7b0dd36c35f69be7", "extension": "h", "filename": "region.h", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 14766832, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1184, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/kernel/include/base/mem/region.h", "provenance": "stackv2-0132.json.gz:68089", "repo_name": "Helix-OS/helix-os", "revision_date": "2016-01-15T10:06:49", "revision_id": "443f43445c1e3294296e0d5e218f582f93e8539f", "snapshot_id": "6e29ae39ef1398e2a5f62a1268fd6421dd157c9a", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Helix-OS/helix-os/443f43445c1e3294296e0d5e218f582f93e8539f/kernel/include/base/mem/region.h", "visit_date": "2020-08-05T20:54:40.539416" }
stackv2
#ifndef SOME_REGION_THING #define SOME_REGION_THING 1 #include <base/stdint.h> #include <arch/paging.h> //#define PAGE_SIZE 0x1000 #define GLOBAL_REGION_SIZE 128 * 1024 * 1024 #define GLOBAL_REGION_NPAGES GLOBAL_REGION_SIZE / PAGE_SIZE #define GLOBAL_REGION_BITMAP_SIZE GLOBAL_REGION_NPAGES / 8 struct region; typedef void *(*region_page_alloc)( struct region *region, unsigned n ); typedef void (*region_page_free) ( struct region *region, void *ptr ); typedef struct region { void *addr; void *data; region_page_alloc alloc_page; region_page_free free_page; unsigned pages; unsigned extra_data; unsigned *pagedir; } region_t; region_t *bitmap_region_init_at_addr( void *vaddr, unsigned size, region_t *addr, void *bitmap, unsigned *pagedir ); region_t *bitmap_region_init( void *vaddr, unsigned size, unsigned *pagedir ); void bitmap_region_free( region_t *addr ); void *bitmap_region_alloc_page( region_t *region, unsigned n ); void bitmap_region_free_page( region_t *region, void *ptr ); #endif
2.046875
2
2024-11-18T22:28:10.334101+00:00
2023-08-23T04:46:46
06a8699d38871a5e751ebe59a241c00551f2ae2b
{ "blob_id": "06a8699d38871a5e751ebe59a241c00551f2ae2b", "branch_name": "refs/heads/master", "committer_date": "2023-08-23T04:46:46", "content_id": "b9a898d8e5f0cd8620cc28596689479ee2ab535a", "detected_licenses": [ "MIT" ], "directory_id": "2c73a693c2b3c162eae2ab94f649d8c4494878ba", "extension": "c", "filename": "lv_ex_checkbox_1.c", "fork_events_count": 93, "gha_created_at": "2019-12-27T08:29:19", "gha_event_created_at": "2021-12-17T02:19:30", "gha_language": "C", "gha_license_id": "MIT", "github_id": 230403844, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 534, "license": "MIT", "license_type": "permissive", "path": "/components/lvgl/lv_demos/src/lv_ex_widgets/lv_ex_checkbox/lv_ex_checkbox_1.c", "provenance": "stackv2-0132.json.gz:68348", "repo_name": "openLuat/LuatOS", "revision_date": "2023-08-23T04:46:46", "revision_id": "4b29d5121ab4f7133630331e8502c526c7856897", "snapshot_id": "185e1e140aed908434168133571ddcafe98f4e12", "src_encoding": "UTF-8", "star_events_count": 378, "url": "https://raw.githubusercontent.com/openLuat/LuatOS/4b29d5121ab4f7133630331e8502c526c7856897/components/lvgl/lv_demos/src/lv_ex_widgets/lv_ex_checkbox/lv_ex_checkbox_1.c", "visit_date": "2023-08-23T04:57:23.263539" }
stackv2
#include "../../../lv_examples.h" #include <stdio.h> #if LV_USE_CHECKBOX static void event_handler(lv_obj_t * obj, lv_event_t event) { if(event == LV_EVENT_VALUE_CHANGED) { printf("State: %s\n", lv_checkbox_is_checked(obj) ? "Checked" : "Unchecked"); } } void lv_ex_checkbox_1(void) { lv_obj_t * cb = lv_checkbox_create(lv_scr_act(), NULL); lv_checkbox_set_text(cb, "I agree to terms and conditions."); lv_obj_align(cb, NULL, LV_ALIGN_CENTER, 0, 0); lv_obj_set_event_cb(cb, event_handler); } #endif
2.5
2
2024-11-18T22:28:10.474950+00:00
2017-10-30T01:55:45
eccfccf50f626b44c6c591a0d0a0f0e7ec0d0c86
{ "blob_id": "eccfccf50f626b44c6c591a0d0a0f0e7ec0d0c86", "branch_name": "refs/heads/master", "committer_date": "2017-10-30T01:55:45", "content_id": "b905767a1a596f9c772d1370f6a061bbad13bd81", "detected_licenses": [ "BSD-2-Clause-Views" ], "directory_id": "b886a105ceb220d9e367571c8c91e80911d07b64", "extension": "h", "filename": "mesh.h", "fork_events_count": 0, "gha_created_at": "2017-10-31T23:25:37", "gha_event_created_at": "2017-10-31T23:25:38", "gha_language": null, "gha_license_id": null, "github_id": 109062881, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 37244, "license": "BSD-2-Clause-Views", "license_type": "permissive", "path": "/src/mesh.h", "provenance": "stackv2-0132.json.gz:68478", "repo_name": "esc0rtd3w/OpenLara", "revision_date": "2017-10-30T01:55:45", "revision_id": "701cc4697851b16ee1f6ad3c82a9e0406b50ac9c", "snapshot_id": "d8ec223cd09def3741ae3e1f9789ea221c48ed7b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/esc0rtd3w/OpenLara/701cc4697851b16ee1f6ad3c82a9e0406b50ac9c/src/mesh.h", "visit_date": "2021-07-21T04:09:30.916438" }
stackv2
#ifndef H_MESH #define H_MESH #include "core.h" #include "format.h" TR::ObjectTexture barTile[5 /* UI::BAR_MAX */]; TR::ObjectTexture &whiteTile = barTile[4]; // BAR_WHITE struct MeshRange { int iStart; int iCount; int vStart; int aIndex; MeshRange() : iStart(0), iCount(0), vStart(0), aIndex(-1) {} void setup() const { glEnableVertexAttribArray(aCoord); glEnableVertexAttribArray(aNormal); glEnableVertexAttribArray(aTexCoord); glEnableVertexAttribArray(aParam); glEnableVertexAttribArray(aColor); Vertex *v = (Vertex*)NULL + vStart; glVertexAttribPointer(aCoord, 4, GL_SHORT, false, sizeof(Vertex), &v->coord); glVertexAttribPointer(aNormal, 4, GL_SHORT, true, sizeof(Vertex), &v->normal); glVertexAttribPointer(aTexCoord, 4, GL_SHORT, true, sizeof(Vertex), &v->texCoord); glVertexAttribPointer(aParam, 4, GL_UNSIGNED_BYTE, false, sizeof(Vertex), &v->param); glVertexAttribPointer(aColor, 4, GL_UNSIGNED_BYTE, true, sizeof(Vertex), &v->color); } void bind(GLuint *VAO) const { GLuint vao = aIndex == -1 ? 0 : VAO[aIndex]; if (Core::support.VAO && Core::active.VAO != vao) glBindVertexArray(Core::active.VAO = vao); } }; #define PLANE_DETAIL 48 #define CIRCLE_SEGS 16 #define DYN_MESH_QUADS 1024 struct Mesh { GLuint ID[2]; GLuint *VAO; int iCount; int vCount; int aCount; int aIndex; Mesh(Index *indices, int iCount, Vertex *vertices, int vCount, int aCount) : VAO(NULL), iCount(iCount), vCount(vCount), aCount(aCount), aIndex(0) { if (Core::support.VAO) glBindVertexArray(Core::active.VAO = 0); glGenBuffers(2, ID); bind(true); glBufferData(GL_ELEMENT_ARRAY_BUFFER, iCount * sizeof(Index), indices, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, vCount * sizeof(Vertex), vertices, GL_STATIC_DRAW); if (Core::support.VAO && aCount) { VAO = new GLuint[aCount]; glGenVertexArrays(aCount, VAO); } } void update(Index *indices, int iCount, Vertex *vertices, int vCount) { if (Core::support.VAO) glBindVertexArray(Core::active.VAO = 0); if (indices && iCount) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Core::active.iBuffer = ID[0]); glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, iCount * sizeof(Index), indices); } if (vertices && vCount) { glBindBuffer(GL_ARRAY_BUFFER, Core::active.vBuffer = ID[1]); glBufferSubData(GL_ARRAY_BUFFER, 0, vCount * sizeof(Vertex), vertices); } } virtual ~Mesh() { if (VAO) { glDeleteVertexArrays(aCount, VAO); delete[] VAO; } glDeleteBuffers(2, ID); } void initRange(MeshRange &range) { if (Core::support.VAO) { range.aIndex = aIndex++; range.bind(VAO); bind(true); range.setup(); } else range.aIndex = -1; } void bind(bool force = false) { if (force || Core::active.iBuffer != ID[0]) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Core::active.iBuffer = ID[0]); if (force || Core::active.vBuffer != ID[1]) glBindBuffer(GL_ARRAY_BUFFER, Core::active.vBuffer = ID[1]); } void render(const MeshRange &range) { range.bind(VAO); if (range.aIndex == -1) { bind(); range.setup(); }; Core::DIP(range.iStart, range.iCount); } }; #define CHECK_NORMAL(n) \ if (!(n.x | n.y | n.z)) {\ vec3 o(mVertices[f.vertices[0]]);\ vec3 a = o - mVertices[f.vertices[1]];\ vec3 b = o - mVertices[f.vertices[2]];\ o = b.cross(a).normal() * 16300.0f;\ n.x = (int)o.x;\ n.y = (int)o.y;\ n.z = (int)o.z;\ }\ #define CHECK_ROOM_NORMAL(n) \ vec3 o(d.vertices[f.vertices[0]].vertex);\ vec3 a = o - d.vertices[f.vertices[1]].vertex;\ vec3 b = o - d.vertices[f.vertices[2]].vertex;\ o = b.cross(a).normal() * 16300.0f;\ n.x = (int)o.x;\ n.y = (int)o.y;\ n.z = (int)o.z; float intensityf(uint16 lighting) { if (lighting > 0x1FFF) return 1.0f; float lum = 1.0f - (lighting >> 5) / 255.0f; //return powf(lum, 2.2f); // gamma to linear space return lum;// * lum; // gamma to "linear" space } uint8 intensity(int lighting) { return uint8(intensityf(lighting) * 255); } struct MeshBuilder { MeshRange dynRange; Mesh *dynMesh; Mesh *mesh; // level struct RoomRange { MeshRange geometry[2]; // opaque & transparent MeshRange sprites; MeshRange **meshes; } *rooms; struct ModelRange { MeshRange geometry; bool opaque; } *models; MeshRange *sequences; // procedured MeshRange shadowBlob; MeshRange quad, circle; MeshRange plane; vec2 *animTexRanges; vec2 *animTexOffsets; int animTexRangesCount; int animTexOffsetsCount; TR::Level *level; MeshBuilder(TR::Level &level) : level(&level) { dynMesh = new Mesh(NULL, DYN_MESH_QUADS * 6, NULL, DYN_MESH_QUADS * 4, 1); dynRange.vStart = 0; dynRange.iStart = 0; dynMesh->initRange(dynRange); initAnimTextures(level); // allocate room geometry ranges rooms = new RoomRange[level.roomsCount]; int iCount = 0, vCount = 0; // get size of mesh for rooms (geometry & sprites) for (int i = 0; i < level.roomsCount; i++) { TR::Room &r = level.rooms[i]; TR::Room::Data &d = r.data; iCount += d.rCount * 6 + d.tCount * 3; vCount += d.rCount * 4 + d.tCount * 3; if (Core::settings.detail.water > Core::Settings::LOW) roomRemoveWaterSurfaces(r, iCount, vCount); for (int j = 0; j < r.meshesCount; j++) { TR::Room::Mesh &m = r.meshes[j]; TR::StaticMesh *s = &level.staticMeshes[m.meshIndex]; if (!level.meshOffsets[s->mesh]) continue; TR::Mesh &mesh = level.meshes[level.meshOffsets[s->mesh]]; iCount += mesh.rCount * 6 + mesh.tCount * 3; vCount += mesh.rCount * 4 + mesh.tCount * 3; } iCount += d.sCount * 6; vCount += d.sCount * 4; } // get models info models = new ModelRange[level.modelsCount]; for (int i = 0; i < level.modelsCount; i++) { TR::Model &model = level.models[i]; for (int j = 0; j < model.mCount; j++) { int index = level.meshOffsets[model.mStart + j]; if (!index && model.mStart + j > 0) continue; TR::Mesh &mesh = level.meshes[index]; iCount += mesh.rCount * 6 + mesh.tCount * 3; vCount += mesh.rCount * 4 + mesh.tCount * 3; } } // get size of mesh for sprite sequences sequences = new MeshRange[level.spriteSequencesCount]; for (int i = 0; i < level.spriteSequencesCount; i++) { iCount += level.spriteSequences[i].sCount * 6; vCount += level.spriteSequences[i].sCount * 4; } // shadow blob mesh (8 triangles, 8 vertices) iCount += 8 * 3 * 3; vCount += 8 * 2 + 1; // quad (post effect filter) iCount += 2 * 3; vCount += 4; // circle iCount += CIRCLE_SEGS * 3; vCount += CIRCLE_SEGS + 1; // detailed plane iCount += PLANE_DETAIL * 2 * PLANE_DETAIL * 2 * (2 * 3); vCount += (PLANE_DETAIL * 2 + 1) * (PLANE_DETAIL * 2 + 1); // make meshes buffer (single vertex buffer object for all geometry & sprites on level) Index *indices = new Index[iCount]; Vertex *vertices = new Vertex[vCount]; iCount = vCount = 0; int aCount = 0; // build rooms int vStartRoom = vCount; aCount++; for (int i = 0; i < level.roomsCount; i++) { TR::Room &room = level.rooms[i]; TR::Room::Data &d = room.data; RoomRange &range = rooms[i]; for (int transp = 0; transp < 2; transp++) { // opaque, opacity range.geometry[transp].vStart = vStartRoom; range.geometry[transp].iStart = iCount; // rooms geometry buildRoom(!transp, room, level, indices, vertices, iCount, vCount, vStartRoom); // static meshes for (int j = 0; j < room.meshesCount; j++) { TR::Room::Mesh &m = room.meshes[j]; TR::StaticMesh *s = &level.staticMeshes[m.meshIndex]; if (!level.meshOffsets[s->mesh]) continue; TR::Mesh &mesh = level.meshes[level.meshOffsets[s->mesh]]; int x = m.x - room.info.x; int y = m.y; int z = m.z - room.info.z; int d = m.rotation.value / 0x4000; buildMesh(!transp, mesh, level, indices, vertices, iCount, vCount, vStartRoom, 0, x, y, z, d); } range.geometry[transp].iCount = iCount - range.geometry[transp].iStart; } // rooms sprites range.sprites.vStart = vStartRoom; range.sprites.iStart = iCount; for (int j = 0; j < d.sCount; j++) { TR::Room::Data::Sprite &f = d.sprites[j]; TR::Room::Data::Vertex &v = d.vertices[f.vertex]; TR::SpriteTexture &sprite = level.spriteTextures[f.texture]; addSprite(indices, vertices, iCount, vCount, vStartRoom, v.vertex.x, v.vertex.y, v.vertex.z, sprite, intensity(v.lighting)); } range.sprites.iCount = iCount - range.sprites.iStart; } // build models geometry int vStartModel = vCount; aCount++; for (int i = 0; i < level.modelsCount; i++) { TR::Model &model = level.models[i]; ModelRange &range = models[i]; range.geometry.vStart = vStartModel; range.geometry.iStart = iCount; range.opaque = true; for (int j = 0; j < model.mCount; j++) { int index = level.meshOffsets[model.mStart + j]; if (!index && model.mStart + j > 0) continue; TR::Mesh &mesh = level.meshes[index]; bool opaque = buildMesh(true, mesh, level, indices, vertices, iCount, vCount, vStartModel, j, 0, 0, 0, 0); if (!opaque) buildMesh(false, mesh, level, indices, vertices, iCount, vCount, vStartModel, j, 0, 0, 0, 0); TR::Entity::fixOpaque(model.type, opaque); range.opaque &= opaque; } range.geometry.iCount = iCount - range.geometry.iStart; } // build sprite sequences int vStartSprite = vCount; aCount++; for (int i = 0; i < level.spriteSequencesCount; i++) { MeshRange &range = sequences[i]; range.vStart = vStartSprite; range.iStart = iCount; for (int j = 0; j < level.spriteSequences[i].sCount; j++) { TR::SpriteTexture &sprite = level.spriteTextures[level.spriteSequences[i].sStart + j]; addSprite(indices, vertices, iCount, vCount, vStartSprite, 0, 0, 0, sprite, 255); } range.iCount = iCount - range.iStart; } // build common primitives int vStartCommon = vCount; aCount++; shadowBlob.vStart = vStartCommon; shadowBlob.iStart = iCount; shadowBlob.iCount = 8 * 3 * 3; for (int i = 0; i < 9; i++) { Vertex &v0 = vertices[vCount + i * 2 + 0]; v0.normal = { 0, -1, 0, 0 }; v0.texCoord = { whiteTile.texCoord[0].x, whiteTile.texCoord[0].y, 32767, 32767 }; v0.param = { 0, 0, 0, 0 }; v0.color = { 0, 0, 0, 0 }; if (i == 8) { v0.coord = { 0, 0, 0, 0 }; break; } float a = i * (PI / 4.0f) + (PI / 8.0f); float c = cosf(a); float s = sinf(a); short c0 = short(c * 256.0f); short s0 = short(s * 256.0f); short c1 = short(c * 512.0f); short s1 = short(s * 512.0f); v0.coord = { c0, 0, s0, 0 }; Vertex &v1 = vertices[vCount + i * 2 + 1]; v1 = v0; v1.coord = { c1, 0, s1, 0 }; v1.color = { 255, 255, 255, 0 }; int idx = iCount + i * 3 * 3; int j = ((i + 1) % 8) * 2; indices[idx++] = i * 2; indices[idx++] = 8 * 2; indices[idx++] = j; indices[idx++] = i * 2 + 1; indices[idx++] = i * 2; indices[idx++] = j; indices[idx++] = i * 2 + 1; indices[idx++] = j; indices[idx++] = j + 1; } vCount += 8 * 2 + 1; iCount += shadowBlob.iCount; // quad quad.vStart = vStartCommon; quad.iStart = iCount; quad.iCount = 2 * 3; addQuad(indices, iCount, vCount, vStartCommon, vertices, &whiteTile); vertices[vCount + 3].coord = { -1, -1, 0, 0 }; vertices[vCount + 2].coord = { 1, -1, 1, 0 }; vertices[vCount + 1].coord = { 1, 1, 1, 1 }; vertices[vCount + 0].coord = { -1, 1, 0, 1 }; for (int i = 0; i < 4; i++) { Vertex &v = vertices[vCount + i]; v.normal = { 0, 0, 0, 0 }; v.color = { 255, 255, 255, 255 }; v.texCoord = { whiteTile.texCoord[0].x, whiteTile.texCoord[0].y, 32767, 32767 }; v.param = { 0, 0, 0, 0 }; } vCount += 4; // circle circle.vStart = vStartCommon; circle.iStart = iCount; circle.iCount = CIRCLE_SEGS * 3; vec2 pos(32767.0f, 0.0f); vec2 cs(cosf(PI2 / CIRCLE_SEGS), sinf(PI2 / CIRCLE_SEGS)); int baseIdx = vCount - vStartCommon; for (int i = 0; i < CIRCLE_SEGS; i++) { Vertex &v = vertices[vCount + i]; pos.rotate(cs); v.coord = { short(pos.x), short(pos.y), 0, 0 }; v.normal = { 0, 0, 0, 0 }; v.color = { 255, 255, 255, 255 }; v.texCoord = { whiteTile.texCoord[0].x, whiteTile.texCoord[0].y, 32767, 32767 }; v.param = { 0, 0, 0, 0 }; indices[iCount++] = baseIdx + i; indices[iCount++] = baseIdx + (i + 1) % CIRCLE_SEGS; indices[iCount++] = baseIdx + CIRCLE_SEGS; } vertices[vCount + CIRCLE_SEGS] = vertices[vCount]; vertices[vCount + CIRCLE_SEGS].coord = { 0, 0, 0, 0 }; vCount += CIRCLE_SEGS + 1; // plane plane.vStart = vStartCommon; plane.iStart = iCount; plane.iCount = PLANE_DETAIL * 2 * PLANE_DETAIL * 2 * (2 * 3); baseIdx = vCount - vStartCommon; for (int16 j = -PLANE_DETAIL; j <= PLANE_DETAIL; j++) for (int16 i = -PLANE_DETAIL; i <= PLANE_DETAIL; i++) { vertices[vCount++].coord = { i, j, 0, 0 }; if (j < PLANE_DETAIL && i < PLANE_DETAIL) { int idx = baseIdx + (j + PLANE_DETAIL) * (PLANE_DETAIL * 2 + 1) + i + PLANE_DETAIL; indices[iCount + 0] = idx + PLANE_DETAIL * 2 + 1; indices[iCount + 1] = idx + 1; indices[iCount + 2] = idx; indices[iCount + 3] = idx + PLANE_DETAIL * 2 + 2; indices[iCount + 4] = idx + 1; indices[iCount + 5] = idx + PLANE_DETAIL * 2 + 1; iCount += 6; } } LOG("MegaMesh: %d %d %d\n", iCount, vCount, aCount); // compile buffer and ranges mesh = new Mesh(indices, iCount, vertices, vCount, aCount); delete[] indices; delete[] vertices; PROFILE_LABEL(BUFFER, mesh->ID[0], "Geometry indices"); PROFILE_LABEL(BUFFER, mesh->ID[1], "Geometry vertices"); // initialize Vertex Arrays MeshRange rangeRoom; rangeRoom.vStart = vStartRoom; mesh->initRange(rangeRoom); for (int i = 0; i < level.roomsCount; i++) { RoomRange &r = rooms[i]; r.geometry[0].aIndex = rangeRoom.aIndex; r.geometry[1].aIndex = rangeRoom.aIndex; r.sprites.aIndex = rangeRoom.aIndex; } MeshRange rangeModel; rangeModel.vStart = vStartModel; mesh->initRange(rangeModel); for (int i = 0; i < level.modelsCount; i++) models[i].geometry.aIndex = rangeModel.aIndex; MeshRange rangeSprite; rangeSprite.vStart = vStartSprite; mesh->initRange(rangeSprite); for (int i = 0; i < level.spriteSequencesCount; i++) sequences[i].aIndex = rangeSprite.aIndex; MeshRange rangeCommon; rangeCommon.vStart = vStartCommon; mesh->initRange(rangeCommon); shadowBlob.aIndex = rangeCommon.aIndex; quad.aIndex = rangeCommon.aIndex; circle.aIndex = rangeCommon.aIndex; plane.aIndex = rangeCommon.aIndex; } ~MeshBuilder() { delete[] animTexRanges; delete[] animTexOffsets; delete[] rooms; delete[] models; delete[] sequences; delete mesh; delete dynMesh; } inline short4 rotate(const short4 &v, int dir) { if (dir == 0) return v; short4 res = v; switch (dir) { case 1 : res.x = v.z, res.z = -v.x; break; case 2 : res.x = -v.x, res.z = -v.z; break; case 3 : res.x = -v.z, res.z = v.x; break; default : ASSERT(false); } return res; } inline short4 transform(const short4 &v, int joint, int x, int y, int z, int dir) { short4 res = rotate(v, dir); res.x += x; res.y += y; res.z += z; res.w = joint; return res; } bool isWaterSurface(int delta, int roomIndex, bool fromWater) { if (roomIndex != TR::NO_ROOM && delta == 0) { TR::Room &r = level->rooms[roomIndex]; if (r.flags.water ^ fromWater) return true; if (r.alternateRoom > -1 && level->rooms[r.alternateRoom].flags.water ^ fromWater) return true; } return false; } void roomRemoveWaterSurfaces(TR::Room &room, int &iCount, int &vCount) { // remove animated water polygons from room geometry for (int i = 0; i < room.data.rCount; i++) { TR::Rectangle &f = room.data.rectangles[i]; if (f.vertices[0] == 0xFFFF) continue; TR::Vertex &a = room.data.vertices[f.vertices[0]].vertex; TR::Vertex &b = room.data.vertices[f.vertices[1]].vertex; TR::Vertex &c = room.data.vertices[f.vertices[2]].vertex; TR::Vertex &d = room.data.vertices[f.vertices[3]].vertex; if (a.y != b.y || a.y != c.y || a.y != d.y) // skip non-horizontal or non-portal plane primitive continue; int sx = (int(a.x) + int(b.x) + int(c.x) + int(d.x)) / 4 / 1024; int sz = (int(a.z) + int(b.z) + int(c.z) + int(d.z)) / 4 / 1024; TR::Room::Sector &s = room.sectors[sx * room.zSectors + sz]; int yt = abs(a.y - s.ceiling * 256); int yb = abs(s.floor * 256 - a.y); if (yt > 0 && yb > 0) continue; if (isWaterSurface(yt, s.roomAbove, room.flags.water) || isWaterSurface(yb, s.roomBelow, room.flags.water)) { f.vertices[0] = 0xFFFF; // mark as unused iCount -= 6; vCount -= 4; } } for (int i = 0; i < room.data.tCount; i++) { TR::Triangle &f = room.data.triangles[i]; if (f.vertices[0] == 0xFFFF) continue; TR::Vertex &a = room.data.vertices[f.vertices[0]].vertex; TR::Vertex &b = room.data.vertices[f.vertices[1]].vertex; TR::Vertex &c = room.data.vertices[f.vertices[2]].vertex; if (a.y != b.y || a.y != c.y) // skip non-horizontal or non-portal plane primitive continue; int sx = (int(a.x) + int(b.x) + int(c.x)) / 3 / 1024; int sz = (int(a.z) + int(b.z) + int(c.z)) / 3 / 1024; TR::Room::Sector &s = room.sectors[sx * room.zSectors + sz]; int yt = abs(a.y - s.ceiling * 256); int yb = abs(s.floor * 256 - a.y); if (yt > 0 && yb > 0) continue; if (isWaterSurface(yt, s.roomAbove, room.flags.water) || isWaterSurface(yb, s.roomBelow, room.flags.water)) { f.vertices[0] = 0xFFFF; // mark as unused iCount -= 3; vCount -= 3; } } } bool buildRoom(bool opaque, const TR::Room &room, const TR::Level &level, Index *indices, Vertex *vertices, int &iCount, int &vCount, int vStart) { const TR::Room::Data &d = room.data; bool isOpaque = true; for (int j = 0; j < d.rCount; j++) { TR::Rectangle &f = d.rectangles[j]; TR::ObjectTexture &t = level.objectTextures[f.texture]; if (f.vertices[0] == 0xFFFF) continue; // skip if marks as unused (removing water planes) if (t.attribute != 0) isOpaque = false; if (opaque != (t.attribute == 0)) continue; addQuad(indices, iCount, vCount, vStart, vertices, &t, d.vertices[f.vertices[0]].vertex, d.vertices[f.vertices[1]].vertex, d.vertices[f.vertices[2]].vertex, d.vertices[f.vertices[3]].vertex); TR::Vertex n; CHECK_ROOM_NORMAL(n); for (int k = 0; k < 4; k++) { TR::Room::Data::Vertex &v = d.vertices[f.vertices[k]]; vertices[vCount].coord = { v.vertex.x, v.vertex.y, v.vertex.z, 0 }; vertices[vCount].normal = { n.x, n.y, n.z, 0 }; vertices[vCount].color = { 255, 255, 255, intensity(v.lighting) }; vCount++; } } for (int j = 0; j < d.tCount; j++) { TR::Triangle &f = d.triangles[j]; TR::ObjectTexture &t = level.objectTextures[f.texture]; if (f.vertices[0] == 0xFFFF) continue; // skip if marks as unused (removing water planes) if (t.attribute != 0) isOpaque = false; if (opaque != (t.attribute == 0)) continue; addTriangle(indices, iCount, vCount, vStart, vertices, &t); TR::Vertex n; CHECK_ROOM_NORMAL(n); for (int k = 0; k < 3; k++) { auto &v = d.vertices[f.vertices[k]]; vertices[vCount].coord = { v.vertex.x, v.vertex.y, v.vertex.z, 0 }; vertices[vCount].normal = { n.x, n.y, n.z, 0 }; vertices[vCount].color = { 255, 255, 255, intensity(v.lighting) }; vCount++; } } return isOpaque; } bool buildMesh(bool opaque, const TR::Mesh &mesh, const TR::Level &level, Index *indices, Vertex *vertices, int &iCount, int &vCount, int vStart, int16 joint, int x, int y, int z, int dir) { TR::Color24 COLOR_WHITE = { 255, 255, 255 }; bool isOpaque = true; for (int j = 0; j < mesh.rCount; j++) { TR::Rectangle &f = mesh.rectangles[j]; TR::ObjectTexture &t = f.color ? whiteTile : level.objectTextures[f.texture]; if (t.attribute != 0) isOpaque = false; if (opaque != (t.attribute == 0)) continue; TR::Color24 c = f.color ? level.getColor(f.texture) : COLOR_WHITE; addQuad(indices, iCount, vCount, vStart, vertices, &t, mesh.vertices[f.vertices[0]].coord, mesh.vertices[f.vertices[1]].coord, mesh.vertices[f.vertices[2]].coord, mesh.vertices[f.vertices[3]].coord); for (int k = 0; k < 4; k++) { TR::Mesh::Vertex &v = mesh.vertices[f.vertices[k]]; vertices[vCount].coord = transform(v.coord, joint, x, y, z, dir); vertices[vCount].normal = rotate(v.normal, dir); vertices[vCount].color = { c.r, c.g, c.b, intensity(v.coord.w) }; vCount++; } } for (int j = 0; j < mesh.tCount; j++) { TR::Triangle &f = mesh.triangles[j]; TR::ObjectTexture &t = f.color ? whiteTile : level.objectTextures[f.texture]; if (t.attribute != 0) isOpaque = false; if (opaque != (t.attribute == 0)) continue; TR::Color24 c = f.color ? level.getColor(f.texture) : COLOR_WHITE; addTriangle(indices, iCount, vCount, vStart, vertices, &t); for (int k = 0; k < 3; k++) { TR::Mesh::Vertex &v = mesh.vertices[f.vertices[k]]; vertices[vCount].coord = transform(v.coord, joint, x, y, z, dir); vertices[vCount].normal = rotate(v.normal, dir); vertices[vCount].color = { c.r, c.g, c.b, intensity(v.coord.w) }; vCount++; } } return isOpaque; } vec2 getTexCoord(const TR::ObjectTexture &tex) { return vec2(tex.texCoord[0].x / 32767.0f, tex.texCoord[0].y / 32767.0f); } void initAnimTextures(TR::Level &level) { ASSERT(level.animTexturesDataSize); uint16 *ptr = &level.animTexturesData[0]; animTexRangesCount = *ptr++ + 1; animTexRanges = new vec2[animTexRangesCount]; animTexRanges[0] = vec2(0.0f, 1.0f); animTexOffsetsCount = 1; for (int i = 1; i < animTexRangesCount; i++) { TR::AnimTexture *animTex = (TR::AnimTexture*)ptr; int start = animTexOffsetsCount; animTexOffsetsCount += animTex->count + 1; animTexRanges[i] = vec2((float)start, (float)(animTexOffsetsCount - start)); ptr += (sizeof(TR::AnimTexture) + sizeof(animTex->textures[0]) * (animTex->count + 1)) / sizeof(uint16); } animTexOffsets = new vec2[animTexOffsetsCount]; animTexOffsets[0] = vec2(0.0f); animTexOffsetsCount = 1; ptr = &level.animTexturesData[1]; for (int i = 1; i < animTexRangesCount; i++) { TR::AnimTexture *animTex = (TR::AnimTexture*)ptr; vec2 first = getTexCoord(level.objectTextures[animTex->textures[0]]); animTexOffsets[animTexOffsetsCount++] = vec2(0.0f); // first - first for first frame %) for (int j = 1; j <= animTex->count; j++) animTexOffsets[animTexOffsetsCount++] = getTexCoord(level.objectTextures[animTex->textures[j]]) - first; ptr += (sizeof(TR::AnimTexture) + sizeof(animTex->textures[0]) * (animTex->count + 1)) / sizeof(uint16); } } TR::ObjectTexture* getAnimTexture(TR::ObjectTexture *tex, uint8 &range, uint8 &frame) { range = frame = 0; if (!level->animTexturesDataSize) return tex; uint16 *ptr = &level->animTexturesData[1]; for (int i = 1; i < animTexRangesCount; i++) { TR::AnimTexture *animTex = (TR::AnimTexture*)ptr; for (int j = 0; j <= animTex->count; j++) if (tex == &level->objectTextures[animTex->textures[j]]) { range = i; frame = j; return &level->objectTextures[animTex->textures[0]]; } ptr += (sizeof(TR::AnimTexture) + sizeof(animTex->textures[0]) * (animTex->count + 1)) / sizeof(uint16); } return tex; } void addTexCoord(Vertex *vertices, int vCount, TR::ObjectTexture *tex, bool triangle) { uint8 range, frame; tex = getAnimTexture(tex, range, frame); int count = triangle ? 3 : 4; for (int i = 0; i < count; i++) { Vertex &v = vertices[vCount + i]; v.texCoord = { tex->texCoord[i].x, tex->texCoord[i].y, 32767, 32767 }; v.param = { range, frame, 0, 0 }; } if (level->version == TR::VER_TR1_PSX && !triangle) swap(vertices[vCount + 2].texCoord, vertices[vCount + 3].texCoord); } void addTriangle(Index *indices, int &iCount, int vCount, int vStart, Vertex *vertices, TR::ObjectTexture *tex) { int vIndex = vCount - vStart; indices[iCount + 0] = vIndex + 0; indices[iCount + 1] = vIndex + 1; indices[iCount + 2] = vIndex + 2; iCount += 3; if (tex) addTexCoord(vertices, vCount, tex, true); } void addQuad(Index *indices, int &iCount, int vCount, int vStart, Vertex *vertices, TR::ObjectTexture *tex) { int vIndex = vCount - vStart; indices[iCount + 0] = vIndex + 0; indices[iCount + 1] = vIndex + 1; indices[iCount + 2] = vIndex + 2; indices[iCount + 3] = vIndex + 0; indices[iCount + 4] = vIndex + 2; indices[iCount + 5] = vIndex + 3; iCount += 6; if (tex) addTexCoord(vertices, vCount, tex, false); } void addQuad(Index *indices, int &iCount, int &vCount, int vStart, Vertex *vertices, TR::ObjectTexture *tex, const short3 &c0, const short3 &c1, const short3 &c2, const short3 &c3) { addQuad(indices, iCount, vCount, vStart, vertices, tex); vec3 a = c0 - c1; vec3 b = c3 - c2; vec3 c = c0 - c3; vec3 d = c1 - c2; float aL = a.length(); float bL = b.length(); float cL = c.length(); float dL = d.length(); float ab = a.dot(b) / (aL * bL); float cd = c.dot(d) / (cL * dL); int16 tx = abs(vertices[vCount + 0].texCoord.x - vertices[vCount + 3].texCoord.x); int16 ty = abs(vertices[vCount + 0].texCoord.y - vertices[vCount + 3].texCoord.y); if (ab > cd) { int k = (tx > ty) ? 3 : 2; if (aL > bL) vertices[vCount + 2].texCoord[k] = vertices[vCount + 3].texCoord[k] = int16(bL / aL * 32767.0f); else vertices[vCount + 0].texCoord[k] = vertices[vCount + 1].texCoord[k] = int16(aL / bL * 32767.0f); } else { int k = (tx > ty) ? 2 : 3; if (cL > dL) { vertices[vCount + 1].texCoord[k] = vertices[vCount + 2].texCoord[k] = int16(dL / cL * 32767.0f); } else vertices[vCount + 0].texCoord[k] = vertices[vCount + 3].texCoord[k] = int16(cL / dL * 32767.0f); } } void addSprite(Index *indices, Vertex *vertices, int &iCount, int &vCount, int vStart, int16 x, int16 y, int16 z, const TR::SpriteTexture &sprite, uint8 intensity, bool expand = false) { addQuad(indices, iCount, vCount, vStart, NULL, NULL); Vertex *quad = &vertices[vCount]; int16 x0, y0, x1, y1; if (expand) { x0 = x + int16(sprite.l); y0 = y + int16(sprite.t); x1 = x + int16(sprite.r); y1 = y + int16(sprite.b); } else { x0 = x1 = x; y0 = y1 = y; } quad[0].coord = { x0, y0, z, 0 }; quad[1].coord = { x1, y0, z, 0 }; quad[2].coord = { x1, y1, z, 0 }; quad[3].coord = { x0, y1, z, 0 }; quad[0].normal = quad[1].normal = quad[2].normal = quad[3].normal = { 0, 0, 0, 0 }; quad[0].color = quad[1].color = quad[2].color = quad[3].color = { 255, 255, 255, intensity }; quad[0].param = quad[1].param = quad[2].param = quad[3].param = { 0, 0, 0, 0 }; quad[0].texCoord = { sprite.texCoord[0].x, sprite.texCoord[0].y, sprite.l, sprite.t }; quad[1].texCoord = { sprite.texCoord[1].x, sprite.texCoord[0].y, sprite.r, sprite.t }; quad[2].texCoord = { sprite.texCoord[1].x, sprite.texCoord[1].y, sprite.r, sprite.b }; quad[3].texCoord = { sprite.texCoord[0].x, sprite.texCoord[1].y, sprite.l, sprite.b }; vCount += 4; } void addBar(Index *indices, Vertex *vertices, int &iCount, int &vCount, const TR::ObjectTexture &tile, const vec2 &pos, const vec2 &size, uint32 color, uint32 color2 = 0) { addQuad(indices, iCount, vCount, 0, vertices, NULL); int16 minX = int16(pos.x); int16 minY = int16(pos.y); int16 maxX = int16(size.x) + minX; int16 maxY = int16(size.y) + minY; vertices[vCount + 0].coord = { minX, minY, 0, 0 }; vertices[vCount + 1].coord = { maxX, minY, 0, 0 }; vertices[vCount + 2].coord = { maxX, maxY, 0, 0 }; vertices[vCount + 3].coord = { minX, maxY, 0, 0 }; for (int i = 0; i < 4; i++) { Vertex &v = vertices[vCount + i]; v.normal = { 0, 0, 0, 0 }; if (color2 != 0 && (i == 0 || i == 3)) v.color = *((ubyte4*)&color2); else v.color = *((ubyte4*)&color); short2 uv = tile.texCoord[i]; v.texCoord = { uv.x, uv.y, 32767, 32767 }; v.param = { 0, 0, 0, 0 }; } vCount += 4; } void addFrame(Index *indices, Vertex *vertices, int &iCount, int &vCount, const vec2 &pos, const vec2 &size, uint32 color1, uint32 color2) { short4 uv = { whiteTile.texCoord[0].x, whiteTile.texCoord[0].y, 32767, 32767 }; int16 minX = int16(pos.x); int16 minY = int16(pos.y); int16 maxX = int16(size.x) + minX; int16 maxY = int16(size.y) + minY; vertices[vCount + 0].coord = { minX, minY, 0, 0 }; vertices[vCount + 1].coord = { maxX, minY, 0, 0 }; vertices[vCount + 2].coord = { maxX, int16(minY + 1), 0, 0 }; vertices[vCount + 3].coord = { minX, int16(minY + 1), 0, 0 }; vertices[vCount + 4].coord = { minX, minY, 0, 0 }; vertices[vCount + 5].coord = { int16(minX + 1), minY, 0, 0 }; vertices[vCount + 6].coord = { int16(minX + 1), maxY, 0, 0 }; vertices[vCount + 7].coord = { minX, maxY, 0, 0 }; for (int i = 0; i < 8; i++) { Vertex &v = vertices[vCount + i]; v.normal = { 0, 0, 0, 0 }; v.color = *((ubyte4*)&color1); v.texCoord = uv; } addQuad(indices, iCount, vCount, 0, vertices, NULL); vCount += 4; addQuad(indices, iCount, vCount, 0, vertices, NULL); vCount += 4; vertices[vCount + 0].coord = { minX, int16(maxY - 1), 0, 0 }; vertices[vCount + 1].coord = { maxX, int16(maxY - 1), 0, 0 }; vertices[vCount + 2].coord = { maxX, maxY, 0, 0 }; vertices[vCount + 3].coord = { minX, maxY, 0, 0 }; vertices[vCount + 4].coord = { int16(maxX - 1), minY, 0, 0 }; vertices[vCount + 5].coord = { maxX, minY, 0, 0 }; vertices[vCount + 6].coord = { maxX, maxY, 0, 0 }; vertices[vCount + 7].coord = { int16(maxX - 1), maxY, 0, 0 }; for (int i = 0; i < 8; i++) { Vertex &v = vertices[vCount + i]; v.normal = { 0, 0, 0, 0 }; v.color = *((ubyte4*)&color2); v.texCoord = uv; } addQuad(indices, iCount, vCount, 0, vertices, NULL); vCount += 4; addQuad(indices, iCount, vCount, 0, vertices, NULL); vCount += 4; } void bind() { mesh->bind(); } void renderBuffer(Index *indices, int iCount, Vertex *vertices, int vCount) { dynRange.iStart = 0; dynRange.iCount = iCount; dynMesh->update(indices, iCount, vertices, vCount); dynMesh->render(dynRange); } void renderRoomGeometry(int roomIndex, bool transparent) { ASSERT(rooms[roomIndex].geometry[transparent].iCount > 0); mesh->render(rooms[roomIndex].geometry[transparent]); } void renderRoomSprites(int roomIndex) { mesh->render(rooms[roomIndex].sprites); } void renderModel(int modelIndex) { mesh->render(models[modelIndex].geometry); } void renderSprite(int sequenceIndex, int frame) { MeshRange range = sequences[sequenceIndex]; range.iCount = 6; range.iStart += frame * 6; mesh->render(range); } void renderShadowBlob() { mesh->render(shadowBlob); } void renderQuad() { mesh->render(quad); } void renderCircle() { mesh->render(circle); } void renderPlane() { mesh->render(plane); } }; #endif
2.0625
2
2024-11-18T22:28:10.830147+00:00
2021-06-23T12:45:37
6108b0bcdfacd7f40d1905fa0b66ca482c774f95
{ "blob_id": "6108b0bcdfacd7f40d1905fa0b66ca482c774f95", "branch_name": "refs/heads/main", "committer_date": "2021-06-23T12:45:37", "content_id": "52b81c200b3b2e08deb5d1c0d26ef29140bdf357", "detected_licenses": [ "PostgreSQL", "Apache-2.0" ], "directory_id": "35f8bec57b5c1466e237102ce53aafeb688e7c0f", "extension": "c", "filename": "util.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 360806291, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4774, "license": "PostgreSQL,Apache-2.0", "license_type": "permissive", "path": "/apps/postgresql-9.0.10/contrib/pg_upgrade/util.c", "provenance": "stackv2-0132.json.gz:68736", "repo_name": "vusec/firestarter", "revision_date": "2021-06-23T12:45:37", "revision_id": "2048c1f731b8f3c5570a920757f9d7730d5f716a", "snapshot_id": "e89a454b86487a18ffbbcacb8afa058b9100df99", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/vusec/firestarter/2048c1f731b8f3c5570a920757f9d7730d5f716a/apps/postgresql-9.0.10/contrib/pg_upgrade/util.c", "visit_date": "2023-06-01T11:25:27.740555" }
stackv2
/* * util.c * * utility functions * * Copyright (c) 2010, PostgreSQL Global Development Group * $PostgreSQL: pgsql/contrib/pg_upgrade/util.c,v 1.5 2010/07/06 19:18:55 momjian Exp $ */ #include "pg_upgrade.h" #include <signal.h> /* * report_status() * * Displays the result of an operation (ok, failed, error message,...) */ void report_status(migratorContext *ctx, eLogType type, const char *fmt,...) { va_list args; char message[MAX_STRING]; va_start(args, fmt); vsnprintf(message, sizeof(message), fmt, args); va_end(args); pg_log(ctx, type, "%s\n", message); } /* * prep_status(&ctx, ) * * Displays a message that describes an operation we are about to begin. * We pad the message out to MESSAGE_WIDTH characters so that all of the "ok" and * "failed" indicators line up nicely. * * A typical sequence would look like this: * prep_status(&ctx, "about to flarb the next %d files", fileCount ); * * if(( message = flarbFiles(fileCount)) == NULL) * report_status(ctx, PG_REPORT, "ok" ); * else * pg_log(ctx, PG_FATAL, "failed - %s", message ); */ void prep_status(migratorContext *ctx, const char *fmt,...) { va_list args; char message[MAX_STRING]; va_start(args, fmt); vsnprintf(message, sizeof(message), fmt, args); va_end(args); if (strlen(message) > 0 && message[strlen(message) - 1] == '\n') pg_log(ctx, PG_REPORT, "%s", message); else pg_log(ctx, PG_REPORT, "%-" MESSAGE_WIDTH "s", message); } void pg_log(migratorContext *ctx, eLogType type, char *fmt,...) { va_list args; char message[MAX_STRING]; va_start(args, fmt); vsnprintf(message, sizeof(message), fmt, args); va_end(args); if (ctx->log_fd != NULL) { fwrite(message, strlen(message), 1, ctx->log_fd); /* if we are using OVERWRITE_MESSAGE, add newline */ if (strchr(message, '\r') != NULL) fwrite("\n", 1, 1, ctx->log_fd); fflush(ctx->log_fd); } switch (type) { case PG_INFO: if (ctx->verbose) printf("%s", _(message)); break; case PG_REPORT: case PG_WARNING: printf("%s", _(message)); break; case PG_FATAL: printf("%s", "\n"); printf("%s", _(message)); exit_nicely(ctx, true); break; case PG_DEBUG: if (ctx->debug) fprintf(ctx->debug_fd, "%s\n", _(message)); break; default: break; } fflush(stdout); } void check_ok(migratorContext *ctx) { /* all seems well */ report_status(ctx, PG_REPORT, "ok"); fflush(stdout); } /* * quote_identifier() * Properly double-quote a SQL identifier. * * The result should be pg_free'd, but most callers don't bother because * memory leakage is not a big deal in this program. */ char * quote_identifier(migratorContext *ctx, const char *s) { char *result = pg_malloc(ctx, strlen(s) * 2 + 3); char *r = result; *r++ = '"'; while (*s) { if (*s == '"') *r++ = *s; *r++ = *s; s++; } *r++ = '"'; *r++ = '\0'; return result; } /* * get_user_info() * (copied from initdb.c) find the current user */ int get_user_info(migratorContext *ctx, char **user_name) { int user_id; #ifndef WIN32 struct passwd *pw = getpwuid(geteuid()); user_id = geteuid(); #else /* the windows code */ struct passwd_win32 { int pw_uid; char pw_name[128]; } pass_win32; struct passwd_win32 *pw = &pass_win32; DWORD pwname_size = sizeof(pass_win32.pw_name) - 1; GetUserName(pw->pw_name, &pwname_size); user_id = 1; #endif *user_name = pg_strdup(ctx, pw->pw_name); return user_id; } void exit_nicely(migratorContext *ctx, bool need_cleanup) { stop_postmaster(ctx, true, true); pg_free(ctx->logfile); if (ctx->log_fd) fclose(ctx->log_fd); if (ctx->debug_fd) fclose(ctx->debug_fd); /* terminate any running instance of postmaster */ if (ctx->postmasterPID != 0) kill(ctx->postmasterPID, SIGTERM); if (need_cleanup) { /* * FIXME must delete intermediate files */ exit(1); } else exit(0); } void * pg_malloc(migratorContext *ctx, int n) { void *p = malloc(n); if (p == NULL) pg_log(ctx, PG_FATAL, "%s: out of memory\n", ctx->progname); return p; } void pg_free(void *p) { if (p != NULL) free(p); } char * pg_strdup(migratorContext *ctx, const char *s) { char *result = strdup(s); if (result == NULL) pg_log(ctx, PG_FATAL, "%s: out of memory\n", ctx->progname); return result; } /* * getErrorText() * * Returns the text of the error message for the given error number * * This feature is factored into a separate function because it is * system-dependent. */ const char * getErrorText(int errNum) { #ifdef WIN32 _dosmaperr(GetLastError()); #endif return strdup(strerror(errNum)); } /* * str2uint() * * convert string to oid */ unsigned int str2uint(const char *str) { return strtoul(str, NULL, 10); }
2.453125
2
2024-11-18T22:28:11.367036+00:00
2021-05-27T14:17:43
72f8cf488688f9913783b07e24be066d993771de
{ "blob_id": "72f8cf488688f9913783b07e24be066d993771de", "branch_name": "refs/heads/master", "committer_date": "2021-06-01T20:41:31", "content_id": "63dae0c6765b109b8c62a3147f16a1189ab34ac2", "detected_licenses": [ "Apache-2.0" ], "directory_id": "07ba368d71420f84de0cff20fc2a8cdde5b2e993", "extension": "h", "filename": "soc.h", "fork_events_count": 2, "gha_created_at": "2019-03-28T20:38:48", "gha_event_created_at": "2022-02-09T00:27:18", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 178278729, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4671, "license": "Apache-2.0", "license_type": "permissive", "path": "/soc/xtensa/intel_adsp/common/include/soc.h", "provenance": "stackv2-0132.json.gz:68998", "repo_name": "MicrochipTech/zephyr", "revision_date": "2021-05-27T14:17:43", "revision_id": "5531525f17d2e5fe9b9511bbb8a97a6a8e41b36a", "snapshot_id": "57b7d6a526a3e4d3ec647287b35907dabe15c7e9", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/MicrochipTech/zephyr/5531525f17d2e5fe9b9511bbb8a97a6a8e41b36a/soc/xtensa/intel_adsp/common/include/soc.h", "visit_date": "2023-08-08T03:35:06.691742" }
stackv2
/* * Copyright (c) 2019 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <errno.h> #include <cavs/version.h> #include <sys/sys_io.h> #include <adsp/cache.h> #ifndef __INC_SOC_H #define __INC_SOC_H /* macros related to interrupt handling */ #define XTENSA_IRQ_NUM_SHIFT 0 #define CAVS_IRQ_NUM_SHIFT 8 #define XTENSA_IRQ_NUM_MASK 0xff #define CAVS_IRQ_NUM_MASK 0xff /* * IRQs are mapped on 2 levels. 3rd and 4th level are left as 0x00. * * 1. Peripheral Register bit offset. * 2. CAVS logic bit offset. */ #define XTENSA_IRQ_NUMBER(_irq) \ ((_irq >> XTENSA_IRQ_NUM_SHIFT) & XTENSA_IRQ_NUM_MASK) #define CAVS_IRQ_NUMBER(_irq) \ (((_irq >> CAVS_IRQ_NUM_SHIFT) & CAVS_IRQ_NUM_MASK) - 1) /* Macro that aggregates the bi-level interrupt into an IRQ number */ #define SOC_AGGREGATE_IRQ(cavs_irq, core_irq) \ ( \ ((core_irq & XTENSA_IRQ_NUM_MASK) << XTENSA_IRQ_NUM_SHIFT) | \ (((cavs_irq + 1) & CAVS_IRQ_NUM_MASK) << CAVS_IRQ_NUM_SHIFT) \ ) #define CAVS_L2_AGG_INT_LEVEL2 DT_IRQN(DT_INST(0, intel_cavs_intc)) #define CAVS_L2_AGG_INT_LEVEL3 DT_IRQN(DT_INST(1, intel_cavs_intc)) #define CAVS_L2_AGG_INT_LEVEL4 DT_IRQN(DT_INST(2, intel_cavs_intc)) #define CAVS_L2_AGG_INT_LEVEL5 DT_IRQN(DT_INST(3, intel_cavs_intc)) #define CAVS_ICTL_INT_CPU_OFFSET(x) (0x40 * x) #define IOAPIC_EDGE 0 #define IOAPIC_HIGH 0 /* I2S */ #define I2S_CAVS_IRQ(i2s_num) \ SOC_AGGREGATE_IRQ(0, (i2s_num), CAVS_L2_AGG_INT_LEVEL5) #define I2S0_CAVS_IRQ I2S_CAVS_IRQ(0) #define I2S1_CAVS_IRQ I2S_CAVS_IRQ(1) #define I2S2_CAVS_IRQ I2S_CAVS_IRQ(2) #define I2S3_CAVS_IRQ I2S_CAVS_IRQ(3) #define SSP_MN_DIV_SIZE (8) #define SSP_MN_DIV_BASE(x) \ (0x00078D00 + ((x) * SSP_MN_DIV_SIZE)) #define PDM_BASE DMIC_BASE /* SOC DSP SHIM Registers */ #if CAVS_VERSION == CAVS_VERSION_1_5 #define SOC_DSP_SHIM_REG_BASE 0x00001000 #else #define SOC_DSP_SHIM_REG_BASE 0x00071f00 #endif /* SOC DSP SHIM Register - Clock Control */ #define SOC_CLKCTL_REQ_AUDIO_PLL_CLK BIT(31) #define SOC_CLKCTL_REQ_XTAL_CLK BIT(30) #define SOC_CLKCTL_REQ_FAST_CLK BIT(29) #define SOC_CLKCTL_TCPLCG_POS(x) (16 + x) #define SOC_CLKCTL_TCPLCG_DIS(x) (1 << SOC_CLKCTL_TCPLCG_POS(x)) #define SOC_CLKCTL_DPCS_POS(x) (8 + x) #define SOC_CLKCTL_DPCS_DIV1(x) (0 << SOC_CLKCTL_DPCS_POS(x)) #define SOC_CLKCTL_DPCS_DIV2(x) (1 << SOC_CLKCTL_DPCS_POS(x)) #define SOC_CLKCTL_DPCS_DIV4(x) (3 << SOC_CLKCTL_DPCS_POS(x)) #define SOC_CLKCTL_TCPAPLLS BIT(7) #define SOC_CLKCTL_LDCS_POS (5) #define SOC_CLKCTL_LDCS_LMPCS (0 << SOC_CLKCTL_LDCS_POS) #define SOC_CLKCTL_LDCS_LDOCS (1 << SOC_CLKCTL_LDCS_POS) #define SOC_CLKCTL_HDCS_POS (4) #define SOC_CLKCTL_HDCS_HMPCS (0 << SOC_CLKCTL_HDCS_POS) #define SOC_CLKCTL_HDCS_HDOCS (1 << SOC_CLKCTL_HDCS_POS) #define SOC_CLKCTL_LDOCS_POS (3) #define SOC_CLKCTL_LDOCS_PLL (0 << SOC_CLKCTL_LDOCS_POS) #define SOC_CLKCTL_LDOCS_FAST (1 << SOC_CLKCTL_LDOCS_POS) #define SOC_CLKCTL_HDOCS_POS (2) #define SOC_CLKCTL_HDOCS_PLL (0 << SOC_CLKCTL_HDOCS_POS) #define SOC_CLKCTL_HDOCS_FAST (1 << SOC_CLKCTL_HDOCS_POS) #define SOC_CLKCTL_LPMEM_PLL_CLK_SEL_POS (1) #define SOC_CLKCTL_LPMEM_PLL_CLK_SEL_DIV2 \ (0 << SOC_CLKCTL_LPMEM_PLL_CLK_SEL_POS) #define SOC_CLKCTL_LPMEM_PLL_CLK_SEL_DIV4 \ (1 << SOC_CLKCTL_LPMEM_PLL_CLK_SEL_POS) #define SOC_CLKCTL_HPMEM_PLL_CLK_SEL_POS (0) #define SOC_CLKCTL_HPMEM_PLL_CLK_SEL_DIV2 \ (0 << SOC_CLKCTL_HPMEM_PLL_CLK_SEL_POS) #define SOC_CLKCTL_HPMEM_PLL_CLK_SEL_DIV4 \ (1 << SOC_CLKCTL_HPMEM_PLL_CLK_SEL_POS) /* SOC DSP SHIM Register - Power Control */ #define SOC_PWRCTL_DISABLE_PWR_GATING_DSP0 BIT(0) #define SOC_PWRCTL_DISABLE_PWR_GATING_DSP1 BIT(1) /* DSP Wall Clock Timers (0 and 1) */ #define DSP_WCT_IRQ(x) \ SOC_AGGREGATE_IRQ((22 + x), CAVS_L2_AGG_INT_LEVEL2) #define DSP_WCT_CS_TA(x) BIT(x) #define DSP_WCT_CS_TT(x) BIT(4 + x) struct soc_dsp_shim_regs { uint32_t reserved[8]; union { struct { uint32_t walclk32_lo; uint32_t walclk32_hi; }; uint64_t walclk; }; uint32_t dspwctcs; uint32_t reserved1[1]; union { struct { uint32_t dspwct0c32_lo; uint32_t dspwct0c32_hi; }; uint64_t dspwct0c; }; union { struct { uint32_t dspwct1c32_lo; uint32_t dspwct1c32_hi; }; uint64_t dspwct1c; }; uint32_t reserved2[14]; uint32_t clkctl; uint32_t clksts; uint32_t reserved3[4]; uint16_t pwrctl; uint16_t pwrsts; uint32_t lpsctl; uint32_t lpsdmas0; uint32_t lpsdmas1; uint32_t reserved4[22]; }; extern void z_soc_irq_enable(uint32_t irq); extern void z_soc_irq_disable(uint32_t irq); extern int z_soc_irq_is_enabled(unsigned int irq); #endif /* __INC_SOC_H */
2.078125
2
2024-11-18T22:28:11.677503+00:00
2014-04-06T13:50:32
a0d3f9a8d3f8627da1fa14468f8d8c78e27d2f70
{ "blob_id": "a0d3f9a8d3f8627da1fa14468f8d8c78e27d2f70", "branch_name": "refs/heads/master", "committer_date": "2014-04-06T13:50:32", "content_id": "774042b370a52efab0df716b8386dd89e2e7ac74", "detected_licenses": [ "Apache-2.0" ], "directory_id": "783d9416135d5cebd62f29e6bb0e3dfde7cfb258", "extension": "c", "filename": "octopus.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": 2229, "license": "Apache-2.0", "license_type": "permissive", "path": "/octopus.c", "provenance": "stackv2-0132.json.gz:69386", "repo_name": "leeyiw/octopus", "revision_date": "2014-04-06T13:50:32", "revision_id": "14e8e302bd869c76f9a6aa4431cee8ed2bce4a05", "snapshot_id": "a835a82c17cf514d824ecd7493719c94c487dda0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/leeyiw/octopus/14e8e302bd869c76f9a6aa4431cee8ed2bce4a05/octopus.c", "visit_date": "2021-01-22T10:22:15.797639" }
stackv2
#include <arpa/inet.h> #include <netinet/in.h> #include <signal.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include "oct_log.h" #include "oct_socket.h" #include "oct_thread.h" int main(int argc, const char *argv[]) { int listen_fd = 0; struct sockaddr_in proxy_addr; const char *ip = "0.0.0.0"; uint16_t port = 8080; /* 屏蔽信号SIGPIPE,防止向一个已经被对端关闭的套接字调用send时, * 产生SIGPIPE导致进程退出 */ struct sigaction sa; sa.sa_handler = SIG_IGN; sa.sa_flags = 0; if (-1 == sigemptyset(&sa.sa_mask)) { oct_log_fatal("set signal mask empty error: %s", ERRMSG); exit(EXIT_FAILURE); } if (-1 == sigaction(SIGPIPE, &sa, NULL)) { oct_log_fatal("set ignore SIGPIPE error: %s", ERRMSG); exit(EXIT_FAILURE); } oct_log_info("actopus start/running"); /* 初始化套接字 */ listen_fd = socket(AF_INET, SOCK_STREAM, 0); if (-1 == listen_fd) { oct_log_fatal("create socket error: %s", ERRMSG); exit(EXIT_FAILURE); } /* 设置地址重用 */ if (-1 == oct_set_so_reuseaddr(listen_fd)) { oct_log_warn("set socket reuse address error: %s", ERRMSG); exit(EXIT_FAILURE); } /* 设置监听套接字为非阻塞 */ if (-1 == oct_set_nonblocking(listen_fd)) { oct_log_warn("set socket nonblocking error: %s", ERRMSG); exit(EXIT_FAILURE); } /* 设置监听地址 */ memset(&proxy_addr, 0, sizeof(proxy_addr)); proxy_addr.sin_family = AF_INET; proxy_addr.sin_port = htons(port); if (1 != inet_pton(AF_INET, ip, &proxy_addr.sin_addr)) { oct_log_fatal("set proxy ip address to %s error", ip); exit(EXIT_FAILURE); } /* 绑定监听地址到套接字上 */ if (-1 == bind(listen_fd, (const struct sockaddr *)&proxy_addr, sizeof(proxy_addr))) { oct_log_fatal("bind socket to address %s:%d error: %s", ip, port, ERRMSG); exit(EXIT_FAILURE); } /* 开始监听套接字 */ if (-1 == listen(listen_fd, 64)) { oct_log_fatal("listen to socket error: %s", ERRMSG); exit(EXIT_FAILURE); } /* 创建线程处理请求 */ oct_thread_arg_t arg; arg.listen_fd = listen_fd; oct_thread_create(&arg, 5); /* TODO 循环侦测线程状态,判断是否需要添加线程 */ while (1) {} return 0; }
2.65625
3
2024-11-18T22:28:12.223971+00:00
2023-06-01T09:46:53
8f46e0bfefaca53da078f0988727ffe85c1a9fb5
{ "blob_id": "8f46e0bfefaca53da078f0988727ffe85c1a9fb5", "branch_name": "refs/heads/master", "committer_date": "2023-06-01T09:46:53", "content_id": "9b2d2cae58328ee8e3572f9540e781896f892c19", "detected_licenses": [ "MIT" ], "directory_id": "b9cf57dfae2dae16e4a3208e0e6f4cec26ae1147", "extension": "c", "filename": "tst-parse-error.c", "fork_events_count": 28, "gha_created_at": "2019-04-26T12:42:34", "gha_event_created_at": "2023-06-01T09:46:54", "gha_language": "C", "gha_license_id": "MIT", "github_id": 183626660, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2773, "license": "MIT", "license_type": "permissive", "path": "/tests/tst-parse-error.c", "provenance": "stackv2-0132.json.gz:69774", "repo_name": "openSUSE/libeconf", "revision_date": "2023-06-01T09:46:53", "revision_id": "5d0fd7435ab7d34dfcf6c1dca9494dc3e7376eec", "snapshot_id": "84fb3cd2ba4fa09bab61105391966498c0adb989", "src_encoding": "UTF-8", "star_events_count": 58, "url": "https://raw.githubusercontent.com/openSUSE/libeconf/5d0fd7435ab7d34dfcf6c1dca9494dc3e7376eec/tests/tst-parse-error.c", "visit_date": "2023-08-17T06:55:48.941376" }
stackv2
#ifdef HAVE_CONFIG_H # include <config.h> #endif #include <stdio.h> #include <string.h> #include "libeconf.h" /* Test case: Reporting parsing errors. */ int main(void) { econf_file *key_file = NULL; econf_err error; char *filename = NULL; uint64_t line_nr = 0; error = econf_readDirs (&key_file, TESTSDIR"tst-parse-error/usr/etc", TESTSDIR"tst-parse-error/etc", "missing_bracket", "conf", "=", "#"); econf_free (key_file); if (error != ECONF_MISSING_BRACKET) { fprintf (stderr, "wrong return value for missing brackets: %s\n", econf_errString(error)); return 1; } econf_errLocation( &filename, &line_nr); if (strcmp(filename,TESTSDIR"tst-parse-error/etc/missing_bracket.conf.d/missing_bracket.conf")!=0 || line_nr != 4) { fprintf (stderr, "wrong error info for parsing a text with missing bracket: %s: %d\n", filename, (int) line_nr); free(filename); return 1; } free(filename); error = econf_readFile(&key_file, TESTSDIR"tst-parse-error/missing_delim.conf", "=", "#"); econf_free (key_file); if (error != ECONF_MISSING_DELIMITER) { fprintf (stderr, "wrong return value for missing delimiters: %s\n", econf_errString(error)); return 1; } econf_errLocation( &filename, &line_nr); if (strcmp(filename,TESTSDIR"tst-parse-error/missing_delim.conf")!=0 || line_nr != 3) { fprintf (stderr, "wrong error info for parsing a text with missing delimiters: %s: %d\n", filename, (int) line_nr); free(filename); return 1; } free(filename); error = econf_readFile(&key_file, TESTSDIR"tst-parse-error/empty_section.conf", "=", "#"); econf_free (key_file); if (error != ECONF_EMPTY_SECTION_NAME) { fprintf (stderr, "wrong return value for empty section names: %s\n", econf_errString(error)); return 1; } econf_errLocation( &filename, &line_nr); if (strcmp(filename,TESTSDIR"tst-parse-error/empty_section.conf")!=0 || line_nr != 4) { fprintf (stderr, "wrong error info for parsing a text after an empty section: %s: %d\n", filename, (int) line_nr); free(filename); return 1; } free(filename); error = econf_readFile(&key_file, TESTSDIR"tst-parse-error/text_after_section.conf", "=", "#"); econf_free (key_file); if (error != ECONF_TEXT_AFTER_SECTION) { fprintf (stderr, "wrong return value for parsing a text after a section: %s\n", econf_errString(error)); return 1; } econf_errLocation( &filename, &line_nr); if (strcmp(filename,TESTSDIR"tst-parse-error/text_after_section.conf")!=0 || line_nr != 4) { fprintf (stderr, "wrong error info for parsing a text after a section: %s: %d\n", filename, (int) line_nr); free(filename); return 1; } free(filename); return 0; }
2.3125
2
2024-11-18T22:28:12.371666+00:00
2020-07-18T09:51:19
057821b0a897bd57bf0a40fe0f65573868eb2473
{ "blob_id": "057821b0a897bd57bf0a40fe0f65573868eb2473", "branch_name": "refs/heads/master", "committer_date": "2020-07-18T09:51:19", "content_id": "762bf452d5d8d818e7962c9d282dbd95e4787bf5", "detected_licenses": [ "MIT" ], "directory_id": "f7ebae0eee2696eff04c96bba4523c2985622491", "extension": "h", "filename": "common.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 280254134, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3603, "license": "MIT", "license_type": "permissive", "path": "/common.h", "provenance": "stackv2-0132.json.gz:69904", "repo_name": "k1r0d3v/shell", "revision_date": "2020-07-18T09:51:19", "revision_id": "1a3c1368ad182d68ff3f20935cb805d4e11affc4", "snapshot_id": "eb22dca801101d5cfcccef65a83274e6930e83c0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/k1r0d3v/shell/1a3c1368ad182d68ff3f20935cb805d4e11affc4/common.h", "visit_date": "2022-11-17T01:06:43.582611" }
stackv2
#ifndef COMMON_H #define COMMON_H #include <stddef.h> #include <stdint.h> #include <inttypes.h> #include <sys/stat.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> // Terminal bold colors #define TERM_BRED(x) "\033[1;31m" x "\033[0m" #define TERM_BBLUE(x) "\033[1;34m" x "\033[0m" #define TERM_BGREEN(x) "\033[1;32m" x "\033[0m" /* #define TERM_BRED(x) x #define TERM_BBLUE(x) x #define TERM_BGREEN(x) x */ // Large print mode #define LIST_FLAG_MLPRINT 0x1 // Show special folders flag #define LIST_FLAG_RECURSIVE 0x2 // Force directories elimination #define ELIMINATE_FLAG_FORCE 0x1 #define MEMORY_TYPE_MALLOC 0 #define MEMORY_TYPE_MMAP 1 #define MEMORY_TYPE_SHARED 2 struct mmap_record { int fd; char *filename; }; struct shared_record { key_t key; }; typedef struct memory_record_t { int type; void *memory; size_t size; time_t time; union { struct mmap_record mr; struct shared_record sr; }; } memory_record_t; typedef struct job_record_t { pid_t pid; char *cmdline; time_t time; int priority; int status; int active; } job_record_t; /** * @brief Formatted perror, like perror but with format * * @return Number of characteres write */ int perrorf(const char *format, ...); /** * @brief Concatenates parent and child paths * * @note This function allocates memory, * call free when finish to work with the string * * @param left Left path * @param right Right path * * @return Pointer to the new created string on success else NULL */ char *concat_path(const char *left, const char *right, int is_dir) ; /** * @brief Prints a line with the format of ls -li or ls -lid * * @param sb File stat struct * @return 0 on success else -1 */ int print_stat_ls(const char *path, const struct stat *sb); /** * @brief Eliminate a file or a directory recursively * * @param path Path to the file or directory * @param flags If path is a folder also delete their contents * * @return 0 on success else -1 */ int eliminate_path(const char *path, int flags); /** * @brief Lists a directory recursively * * @param path The path to list * @param max_deep The maximum deep to list, -1 == infinite * @param deep The current deep * @param flags Print flags, use the macros LIST_FLAG_* * * @return 0 on success else -1 */ int list_path(const char *path, int flags); int create_malloc_record(size_t size, memory_record_t **r); int create_mmap_record(const char *filename, const char *perms, memory_record_t **r); int create_shared_key(key_t key, size_t size); int free_malloc_record(size_t size, memory_record_t *r); int free_mmap_record(const char *filename, memory_record_t *r); int free_shared_key(key_t key); int free_memory_record(void *address); int free_memory_records(); int map_shared_record(key_t key, memory_record_t **r); int unmap_shared_record(key_t key, memory_record_t *r); int print_memory_record(memory_record_t *r); void print_memory_records(int type); uintptr_t str2uintptr(const char *s); intptr_t str2intptr(const char *s); void hexdump(const void *p, size_t size, int cols, int col_bytes); void memdump(const void *p, size_t size); int read_to_mem(const char *filename, void *dst, size_t *size); int write_from_mem(const char *filename, int append, void *src, size_t size); int find_executable(const char *path, const char *name); int create_job_record(pid_t pid, int argc, char **argv); int clear_job_records(); int print_job_record_by_pid(pid_t pid); void print_job_records(); #endif
2.375
2
2024-11-18T22:28:12.635456+00:00
2021-03-03T02:01:32
8a695a234493c260e2e155cdf07b750235cd0fdc
{ "blob_id": "8a695a234493c260e2e155cdf07b750235cd0fdc", "branch_name": "refs/heads/master", "committer_date": "2021-03-03T02:01:32", "content_id": "f40cdd8b141af0caa7e4899f41d320b0cf0ff2a7", "detected_licenses": [ "MIT" ], "directory_id": "135dc036d1a10b1672efd2cb10166578e9b7439d", "extension": "c", "filename": "timespec.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 100192911, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 215, "license": "MIT", "license_type": "permissive", "path": "/test/wasm/time/timespec.c", "provenance": "stackv2-0132.json.gz:70161", "repo_name": "jdh8/metallic", "revision_date": "2021-03-03T02:01:32", "revision_id": "a9e3ec4c9c36196dfd0ee1849da3cce04e681025", "snapshot_id": "4fd1ad8f8f0bde50bddab8983c2c2a21a2d73ba9", "src_encoding": "UTF-8", "star_events_count": 44, "url": "https://raw.githubusercontent.com/jdh8/metallic/a9e3ec4c9c36196dfd0ee1849da3cce04e681025/test/wasm/time/timespec.c", "visit_date": "2021-06-04T17:55:27.991041" }
stackv2
#include <time.h> #include <stdio.h> #include <assert.h> int main(void) { struct timespec spec; assert(timespec_get(&spec, TIME_UTC)); assert(printf("%lld.%.9ld\n", spec.tv_sec, spec.tv_nsec) >= 0); }
2.578125
3
2024-11-18T22:28:12.748241+00:00
2020-11-25T14:03:20
db3c05aa564f349897d647dc5881223f0398e3e7
{ "blob_id": "db3c05aa564f349897d647dc5881223f0398e3e7", "branch_name": "refs/heads/main", "committer_date": "2020-11-25T14:03:20", "content_id": "78b2cc25d82dcb2a070b781d6a9f83bf516e5454", "detected_licenses": [ "MIT" ], "directory_id": "f735a4de463fb2f2ea9cd0ecc9634011ec746c24", "extension": "c", "filename": "kernel.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": 1432, "license": "MIT", "license_type": "permissive", "path": "/src/kernel.c", "provenance": "stackv2-0132.json.gz:70419", "repo_name": "mamh-mixed/os-MiniOS-demos", "revision_date": "2020-11-25T14:03:20", "revision_id": "5c138b95185131c7f7b69e70a1ec536f072d3590", "snapshot_id": "bcf5b8e2d2f200a43b7ae343923a3e413bae266e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mamh-mixed/os-MiniOS-demos/5c138b95185131c7f7b69e70a1ec536f072d3590/src/kernel.c", "visit_date": "2023-01-28T10:23:25.653997" }
stackv2
#include <kernel.h> void funca() { while (1) { // for (int i = 0; i < 999; i++); // puts("Hello "); } } void funcb() { while (1) { puts("Hello "); for (int i = 0; i < 99999; i++) ; } } int main() { initInterruptManagement(); initMemoryManagement(); initStdioManagement(); initKeyboardDriver(); initGdtManagement(); initScheduler(); initFileSystem(); Pcb *pcb = createProcess(1024, 3, FALSE); Tcb *tcb = createThread(pcb, 0, "funcb", (void *)0x10000000, NULL); startProcess(pcb); startThread(tcb); loadProgram(pcb->cr3, 100000, 100, (void *)0x10000000); char content[512] = TEXT; char filename[] = "README.txt"; char list[512]; getFileList(list); puts(list); if (createFile(filename, GernalFile) == TRUE) { ASSERT(openFile(filename, GernalOpen, 0, 512) == TRUE); ASSERT(writeFile(filename, content, 512) == TRUE); ASSERT(closeFile(filename) == TRUE); } interruptEnable(); // Uint32 count = 0; ASSERT(openFile("stdin", GernalOpen, 0, 0) == TRUE); while (1) { char str[3] = {0}; readFile("stdin", str); if (str[0] != '\0') { puts(str); } } } void loadProgram(Uint32 cr3, Uint32 startSector, Uint32 sectorCount, void *startAddr) { Uint32 curCr3; asm volatile( "mov %%cr3,%%eax; \ mov %%ebx,%%cr3;" : "=a"(curCr3) : "b"(cr3) : "memory"); readDisk(startSector, sectorCount, startAddr); asm volatile( "mov %%eax,%%cr3;" ::"a"(curCr3) :); }
2.40625
2
2024-11-18T22:28:13.074795+00:00
2017-04-24T09:13:37
6c0d4fbb463d2a0386f998027c843eda46db8f7b
{ "blob_id": "6c0d4fbb463d2a0386f998027c843eda46db8f7b", "branch_name": "refs/heads/master", "committer_date": "2017-04-24T09:13:37", "content_id": "9e525e638ccf7abdf12a02423ecf137d3849ff30", "detected_licenses": [ "MIT" ], "directory_id": "c6ec6a85bde1fe199f50cad456ab51fc11775da2", "extension": "h", "filename": "table.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": 17471, "license": "MIT", "license_type": "permissive", "path": "/src/ysinclude/mid/table.h", "provenance": "stackv2-0132.json.gz:70681", "repo_name": "acehong/testhelper", "revision_date": "2017-04-24T09:13:37", "revision_id": "8d109cd70a4996a0db912c265a710d4a0c457a84", "snapshot_id": "617defc27b211c9d68b0217b9ee6bd52011a32be", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/acehong/testhelper/8d109cd70a4996a0db912c265a710d4a0c457a84/src/ysinclude/mid/table.h", "visit_date": "2021-12-14T09:13:22.809555" }
stackv2
#ifndef _TABLE_H_ #define _TABLE_H_ #include "sttbx.h" //#include "common.h" #include "ctrlst.h" #define INVALID_COL TABLE_BASE+1 #define ROW_MOVE BUTTON_PRESS+100 /**************************************************************************/ typedef void MidTableRowObj_t; /*The function for retrieving the text for the item member*/ typedef HRESULT (*MidTableRowObjGetText)(MidTableRowObj_t *pRowObj, int iCol, char *pText, int *pnLen, UI32 nSetting, MidTextStyle_t *pTextStyle); /*The function for retrieving the status from underlying object*/ typedef HRESULT (*MidTableRowObjGetSetting)(MidTableRowObj_t *pRowObj, UI32 *pnSetting); /*The function for saving the status from underlying object*/ typedef HRESULT (*MidTableRowObjSaveSetting)(MidTableRowObj_t *pRowObj, UI32 nSetting); /*The function for retrieving the next underlying object*/ typedef HRESULT (*MidTableRowObjGetNext)(MidTableRowObj_t *pRowObj); /*The function called to set message for the object connect to the selected row*/ typedef bool (*MidTableRowObjSetMsg)(MidTableRowObj_t* pObj, MessageInfo_t* pMsg, UI32 nOperation); /*The function for getting the access to underlying object*/ typedef bool (*MidTableRowObjBlock)(MidTableRowObj_t* pObj); /*The function for releasing the access to underlying object*/ typedef bool (*MidTableRowObjUnBlock)(MidTableRowObj_t* pObj); typedef struct MidTableRowObjCat { MidTableRowObjGetText GetText; MidTableRowObjGetSetting GetSetting; MidTableRowObjSaveSetting SaveSetting; MidTableRowObjGetNext GetNext; MidTableRowObjSetMsg SetMsg; MidTableRowObjBlock Block; MidTableRowObjUnBlock UnBlock; } MidTableRowObjCat_t; /* Name : MidTableColSetting * Description : This is the structure holding all the necessary infomation for columns*/ typedef struct MidTableColSetting { U8 nColNum; /*The number of column*/ U8 nScrollColNum; /*The scroll column*/ UI16 *pnWidths; /*the array of column width*/ int *pnStyle; MidLineSettingList_t LineSettings; /*the pointer to the line setting list for column*/ } MidTableColSetting_t; /* Name : MidTableRowSetting * Description : This is the structure holding all the necessary infomation for Rows*/ typedef struct MidTableRowSetting { UI16 nHeight; MidTextSettingList_t TextSettings; MidLineSettingList_t LineSettings; } MidTableRowSetting_t; /* Name : MidTableRowSetting * Description : This is the structure holding all the necessary infomation for Rows*/ typedef struct MidTableRow { // UI16 nRowId; Rect_t rcRow; UI32 nSetting; /*the displaying style of the row */ MidTableRowSetting_t *pRowSetting; /*The general setting of the rows*/ MidTableColSetting_t *pColSetting; /*The setting for the columns shared by all*/ MidTableRowObj_t *pRowObj; /*pointer to the underlieing item*/ MidTableRowObjCat_t *pRowObjCat; /*TableRow的图形属性*/ BOOL bRowGraphic; //tablerow显示方式(是否以图形方式) MidGraphicSettingList_t *pRowGraphicSetting; //tablerow显示图片列表 int Num; }MidTableRow_t; #define SCROLL_BMP_NAME_MAX_LEN 8 //滚动条阴影设置 typedef struct MidTableScrollShadowSetting { UI16 nShadowWidth; int UpLeftLineColor; int DownRightColor; }MidTableScrollShadowSetting_t; //滚动条头尾的设置 typedef struct MidTableScrollHeadSetting { int TrangelMargin; int BackColor; int ForeColor; Rect_t HeadRect; Rect_t EndRect; char HeadBmp[SCROLL_BMP_NAME_MAX_LEN]; char EndBmp[SCROLL_BMP_NAME_MAX_LEN]; }MidTableScrollHeadSetting_t; //滚动条中间部分设置 typedef struct MidTableScrollBarSetting { int BackColor; int ForeColor; int BarLength; int BarPosition; Rect_t BarBackRect; char BarBmp[SCROLL_BMP_NAME_MAX_LEN]; char BarBackBmp[SCROLL_BMP_NAME_MAX_LEN]; }MidTableScrollBarSetting_t; typedef struct MidTableScroll { BOOL bRowGraphic; //是否贴图 UI16 nDistance; //滚动条离table的距离 UI16 nWidth; //滚动条的宽度 MidTableScrollShadowSetting_t ShadowSetting; //阴影设置,对贴图模式无意义 MidTableScrollHeadSetting_t ScrollHeadSetting; MidTableScrollBarSetting_t ScrollBarSetting; }MidTableScroll_t; /******************************************************************************* ***** MidTableRow ***** *******************************************************************************/ /* Name : MidTableRowUpdate * Description : update the table row features; * Parameters : * pRow :[In] the row to initialize * pRowObj :[In] the underlying object * pRowObjCat :[In] the category of underlying object * Return : succeed or not*/ bool MidTableRowUpdate( MidTableRow_t *pRow, MidTableRowObj_t *pRowObj, MidTableRowObjCat_t *pRowObjCat); /* Name : MidTableRowDraw * Description : draw the table row according to the row feature * Parameters : * pRow :[In] the row to draw * Return : nothing*/ void MidTableRowDraw(MidTableRow_t *pRow); /* Name : MidTableRowGetFocus * Description : the current row get the operation focus; * Parameters : * pRow :[In]The row * Return :succeed or not*/ bool MidTableRowGetFocus ( MidTableRow_t *pRow ); /* Name : MidTableRowLoseFocus * Description : the current row lose the operation focus; * Parameters : * pRow :[In]The row * Return :succeed or not*/ bool MidTableRowLoseFocus ( MidTableRow_t *pRow ); /* Name : MidTableRowSelected * Description : the current row get checked; * Parameters : * pRow :[In]The row * Return :succeed or not*/ bool MidTableRowSelected( MidTableRow_t *pRow ); /* Name : MidTableRowDeselected * Description : the current row lose selected mark; * Parameters : * pRow :[In]The row * Return :succeed or not*/ bool MidTableRowDeselected( MidTableRow_t *pRow ); /* Name : MidTableRowProcess * Description : Processing the input message * Parameters : * pRow :[In] the objective row * pMsgIn :[In] the incoming message * pMsgOut :[In] the buffer for outgoing message [Out]the outgoing message * Return : processed or not*/ bool MidTableRowProcess (MidTableRow_t *pRow, MessageInfo_t *pMsgIn, MessageInfo_t *pMsgOut, ControlList_t* pControlList ); /*******************************************************************************************/ typedef void MidTableObj_t; typedef void MidTableInitParam_t; /*The function for retrieving the title for the column*/ typedef HRESULT (*MidTableObjGetTitle)(UI32 nId, MidTableObj_t *pObj, int iCol, char *pText, int *pnLen); /*The function for registering the access to underlying object, return the id in pnId*/ typedef HRESULT (*MidTableObjRegister)(MidTableObj_t *pObj, UI32 *pnId, MidTableInitParam_t* pInitParam); /*The function for releasing the access to underlying object*/ typedef HRESULT (*MidTableObjRelease)(UI32 nId, MidTableObj_t *pObj); /*The function for setting the index item for underlying object, nId is not understandable by table, 0 is the default*/ typedef HRESULT (*MidTableObjIndexBy)(UI32 nId, MidTableObj_t *pObj, int n2Id); /*The function for getting the number of object meeting condition after pRowObj(exclusive)*/ typedef int (*MidTableObjGetCount)(UI32 nId, MidTableObj_t *pObj, MidTableRowObj_t * pRowObj, bool bNext); /*The function for getting the sub objects' category*/ typedef MidTableRowObjCat_t* (*MidTableObjGetSubCat)(); /*The function for getting the current object meeting condition, if pRowObj == NULL, return the current; if pRowObj != NULL and is valid, set it as the current*/ typedef MidTableRowObj_t* (*MidTableObjGetAt)(UI32 nId, MidTableObj_t *pObj, MidTableRowObj_t *pRowObj); /*The function for getting the first object meeting condition*/ typedef MidTableRowObj_t* (*MidTableObjGetFirst)(UI32 nId, MidTableObj_t *pObj); /*The function for getting the first object meeting condition*/ typedef MidTableRowObj_t* (*MidTableObjGetLast)(UI32 nId, MidTableObj_t *pObj); /*The function for retrieving the next underlying object of pObj*/ typedef MidTableRowObj_t* (*MidTableObjGetNext)(UI32 nId, MidTableObj_t *pObj); /*The function for retrieving the previous underlying object for pObj*/ typedef MidTableRowObj_t* (*MidTableObjGetPrev)(UI32 nId, MidTableObj_t *pObj); /* 将pRowObj加入到pObj中iIndex的位置,若iIndex为-1,则插入到当前项之前;首项是0 */ typedef MidTableRowObj_t *(*MidTableObjAddItem)(UI32 nId, MidTableObj_t *pObj, MidTableRowObj_t *pRowObj, int iIndex, bool bDirector); /* 从pObj中第iIndex项,如果iIndex为-1,则删除当前项;首项是0 */ typedef bool (*MidTableObjRemoveItem)(UI32 nId, MidTableObj_t *pObj, int iIndex); typedef struct MidTableObjCat { MidTableObjGetTitle GetTitle; MidTableObjRegister Register; MidTableObjRelease Release; MidTableObjIndexBy IndexBy; MidTableObjGetCount GetCount; MidTableObjGetSubCat GetSubCat; MidTableObjGetAt GetAt; MidTableObjGetFirst GetFirst; MidTableObjGetLast GetLast; MidTableObjGetNext GetNext; MidTableObjGetPrev GetPrev; MidTableObjAddItem AddItem; MidTableObjRemoveItem RemoveItem; }MidTableObjCat_t; /*******************************************************************************************/ typedef void (*MidTableDrawIcon)(struct ControlItem *this); typedef struct MidTable { UI32 nId; /*The id for accessing underlying object*/ MidTableRowSetting_t RowSetting; /*The generic setting of the table rows*/ MidTableColSetting_t ColSetting; /*The generic col setting of the table*/ UI16 nRow; /*The number of visible rows*///绑定数据的总数 UI16 nRowInTable; /*The number of rows in one screen displaying *注意:取值范围是1-N */ UI16 nRowValid; /*The number of rows valid in the view *注意:取值范围是1-nRowInTable*/ MidTableRow_t *pRows; /*The pointer to the array of row information */ int iFocusRow; /*index of the focus row in visible region *注意:取值范围是0-(nRowValid-1) */ MidTableObj_t *pObj; /*pointer to the underlieing item*/ MidTableObjCat_t *pObjCat; /*The underlying category of the item*/ MidTableRowObjCat_t *pRowObjCat; /*the underlying object category of the row item*/ MidTableRowSetting_t TitleSetting; /*The setting of the title row*/ MidTableScroll_t *ScrollSetting;/*滚动条设置*/ /*TableRow的图形属性*/ BOOL bRowGraphic; //tablerow显示方式(是否以图形方式) MidGraphicSettingList_t RowGraphicSetting; //tablerow显示图片列表 UI16 RowSpace;//the space between rows MidTableDrawIcon DrawIcon; } MidTable_t ; UI16 MidTableGetVisibleRowNum(ControlItem_t *pTable); bool MidTableRollUp(ControlItem_t *pTable); bool MidTableRollDown(ControlItem_t *pTable); bool MidTablePageUp(ControlItem_t *pTable); bool MidTablePageDown(ControlItem_t *pTable); void MidTableDrawTitle(ControlItem_t *pTable); void MidTableDrawCol(ControlItem_t *pTable); void MidTableInitScroll(ControlItem_t *pTable); int MidTableGetRowNO(ControlItem_t *pTable, int iIndex); /* 下列函数已失去作用 */ void MidControlTableHide(ControlItem_t *pTable); void MidControlTableSetCat ( ControlCatInfo_t *pCatInfo ); /* Name : MidControlTableCreate * Description : create a table object; * Parameters : * pControlList :[In] the pointer to the control list, * pstrTable :[In] the string of control information * nLen :[In] the length of the information string * Return : the pointer to the control item if create successfully, else NULL*/ ControlItem_t* MidControlTableCreate (ControlList_t* pControlList, char *pstrTable, int nLen ); /* Name : MidTableDestroy * Description : Delete the table object, free the space occupied by the object; * Parameters : * pTable :[In] the table to destroy * pControlList:[In] * Return : err code*/ HRESULT MidControlTableDestroy(ControlItem_t *pTable, ControlList_t* pControlList ); /* Name : MidControlTableLoadFromString * Description : load the generic information of control object from the string pointed by pstrTable to the object pointed by pTable; * Parameters : * pTable :[In] pointer to the table to initiate * pstrTable :[In] the input string * nLen :[In] the stringlength * pControlList:[In] the controllist for inserting the control * Return :err code*/ HRESULT MidControlTableLoadFromString(ControlItem_t* pTable, char *pstrTable, int nLen, ControlList_t *pControlList ); /* Name : MidControlTableInit * Description : Initiate the table * Parameters : * pTable :[In]the table to initiate * pObj :[In]the underlying object * pObjCat :[In]the underlying object category * pControlList:[In] * Return : Succeed or not*/ bool MidControlTableInit( ControlItem_t* pTable, void *pObj, void *pObjCat, MidControlInitParam_t *pInitParam, ControlList_t *pControlList); /* Name : MidControlTableUpdate * Description : Update the contents of the table when the underlying object changed * Parameters : * pTable :[In]the table to initiate * pObj :[In]the underlying object * pObjCat :[In]the underlying object category, kept simply for compatibilty * pControlList:[In] * Return : error code*/ HRESULT MidControlTableUpdate(ControlItem_t* pTable, void *pObj, void *pObjCat, MidControlInitParam_t *pInitParam, ControlList_t *pControlList); /* Name :MidControlTableGetFocus * Description :the current table get the operating focus; * Parameters : * pTable :[In] the table gaining focus * Return :err code*/ HRESULT MidControlTableGetFocus (ControlItem_t *pTable); /* Name : MidControlTableLoseFocus * Description : the table lose the operating focus; * Parameters : * pTable :[In] the table * Return : err code*/ HRESULT MidControlTableLoseFocus(ControlItem_t *pTable); /* Name : MidTableUpdateRows * Description : Update the rows in the table * Parameters : * pTable :[In] the table whose rows to initiate * Return :nothing*/ void MidTableUpdateRows(ControlItem_t *pTable, int iNewFocusRow ); /* Name : MidControlTableProcess * Description : Processing the incoming message * Parameters : * pTable :[In] the table to process the incoming message * pMsgIn :[In] the incoming message * pMsgOut :[In] the buffer to hold the outgoing message * [Out]the outgoing message * Return : processed or not*/ bool MidControlTableProcess(ControlItem_t *pTable, MessageInfo_t *pMsgIn, MessageInfo_t *pMsgOut, ControlList_t *pControlList ); /* Name : MidControlTableDraw * Description : draw the table with the table feature * Parameters : * pTable :[In]the table to draw * nStyle :[In]the style for drawing * Return : nothing*/ void MidControlTableDraw(ControlItem_t *pTable, int nStyle); HRESULT MidTableRemoveItem(ControlItem_t *pTable, int iIndex); HRESULT MidTableRemoveEndItem(ControlItem_t *pTable); HRESULT MidTableAddItem(ControlItem_t *pTable, void *pRowObjData, int iIndex, bool bNext); HRESULT MidTableRowRefresh(ControlItem_t *pTable, int iIndex); HRESULT MidTableSetFocus(ControlItem_t *pTable, int iIndex); HRESULT MidControlTableSetCallback(struct ControlItem *this, void *pFunc, int nType); bool MidTableRowDisableFocus ( MidTableRow_t *pRow ); void MidTableUpdateRowsNew(ControlItem_t *pTable); void MidTableInitRows(ControlItem_t *pTable); void MidTableGetCurrentPageStatus(ControlItem_t *pTable, MidTableRowObj_t **pPageFirstRowObj, int *pPageFocus); void MidTableSetCurrentPageStatus(ControlItem_t *pTable, MidTableRowObj_t *pPageFirstRowObj, int PageFocus); bool MidTableIsRollUp(ControlItem_t *pTable); bool MidTableIsRollDown(ControlItem_t *pTable); void MidTableSetRollforTooLong(BOOL value); #endif
2.0625
2
2024-11-18T22:28:13.907362+00:00
2015-11-10T20:47:03
3bc7ecc5581ff07e7be6f45f7a95efc5f846ada0
{ "blob_id": "3bc7ecc5581ff07e7be6f45f7a95efc5f846ada0", "branch_name": "refs/heads/master", "committer_date": "2015-11-10T20:47:03", "content_id": "30a5bbecd522fb0acb0cdc87b9c58e5a626e6c48", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "4ea7b3a72e98b1d77c8b40e8df661d530f08c834", "extension": "c", "filename": "utils.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": 2235, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Src/utils.c", "provenance": "stackv2-0132.json.gz:71334", "repo_name": "glocklueng/STM32F401-GTS-Detect", "revision_date": "2015-11-10T20:47:03", "revision_id": "a818541c6a13602530c7d7b438f2c61b0cab6cad", "snapshot_id": "194ba5d2c6d3eda6c05c93e48e0e23ddaf7056fc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/glocklueng/STM32F401-GTS-Detect/a818541c6a13602530c7d7b438f2c61b0cab6cad/Src/utils.c", "visit_date": "2021-01-17T23:12:29.552641" }
stackv2
#include <stdio.h> #include "stm32f4xx_hal.h" #include "utils.h" static TIM_HandleTypeDef TIM_Handle2; static TIM_HandleTypeDef TIM_Handle5; static PeriodicCalledFunction_type PeriodicCalledFcn; static uint8_t started=0; void TickTock_Init(void) { __TIM5_CLK_ENABLE(); TIM_Handle5.Instance = TIM5; TIM_Handle5.Init.Period = 0xFFFFFFFF; TIM_Handle5.Init.Prescaler = 83; TIM_Handle5.Init.ClockDivision = 0; TIM_Handle5.Init.CounterMode = TIM_COUNTERMODE_UP; HAL_TIM_Base_Init(&TIM_Handle5); HAL_TIM_Base_Start(&TIM_Handle5); } void TickTock_Start(void) { __HAL_TIM_SetCounter(&TIM_Handle5,0); } void TickTock_Start_OneShot(void) { if (started==0) { __HAL_TIM_SetCounter(&TIM_Handle5,0); started=1; } } void TickTock_Stop(void) { uint32_t TockValue; TockValue=__HAL_TIM_GetCounter(&TIM_Handle5); started = 0; printf("Tiempo transcurrido: %u uS\n",TockValue); } void PeriodicCaller_Init(void) { __TIM2_CLK_ENABLE(); TIM_Handle2.Instance = TIM2; TIM_Handle2.Init.Period = 999999; TIM_Handle2.Init.Prescaler = 83; TIM_Handle2.Init.ClockDivision = 0; TIM_Handle2.Init.CounterMode = TIM_COUNTERMODE_UP; HAL_TIM_Base_Init(&TIM_Handle2); HAL_NVIC_SetPriority(TIM2_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM2_IRQn); } void PeriodicCaller_Start(PeriodicCalledFunction_type PeriodicCalledFunction) { TickTock_Init(); PeriodicCalledFcn=PeriodicCalledFunction; HAL_TIM_Base_Start(&TIM_Handle2); HAL_TIM_Base_Start_IT(&TIM_Handle2); __HAL_TIM_SetCounter(&TIM_Handle2,0); } void PeriodicCaller_Reset(void) { __HAL_TIM_SetCounter(&TIM_Handle2,0); } void PeriodicCaller_Stop(void) { HAL_TIM_Base_Stop(&TIM_Handle2); } void TIM2_IRQHandler(void) { if (__HAL_TIM_GET_FLAG(&TIM_Handle2, TIM_FLAG_UPDATE) != RESET) //In case other interrupts are also running { if (__HAL_TIM_GET_ITSTATUS(&TIM_Handle2, TIM_IT_UPDATE) != RESET) { __HAL_TIM_CLEAR_FLAG(&TIM_Handle2, TIM_FLAG_UPDATE); PeriodicCalledFcn(); } } }
2.453125
2
2024-11-18T22:28:14.324660+00:00
2019-02-01T18:53:38
15362f7a2d9faf292b768c57ddb0126f4ff858ac
{ "blob_id": "15362f7a2d9faf292b768c57ddb0126f4ff858ac", "branch_name": "refs/heads/master", "committer_date": "2019-02-01T18:53:38", "content_id": "3aa66559a006f07c8a089d4b84ac1480fa7909d6", "detected_licenses": [ "MIT" ], "directory_id": "50b8f61cd96254d052884f52abad9f838b84ffaf", "extension": "c", "filename": "RS485.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": 2841, "license": "MIT", "license_type": "permissive", "path": "/Software/DEMO0/Central_Controller_CPU1/Comm/RS485.c", "provenance": "stackv2-0132.json.gz:71463", "repo_name": "dongdong-2009/Kirtley_picogrid", "revision_date": "2019-02-01T18:53:38", "revision_id": "3bb52c55e9ed9cb5f91d36e366ab3978a417813a", "snapshot_id": "b107399b7c0e683c26c021a2a5c83b03ab00eb59", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dongdong-2009/Kirtley_picogrid/3bb52c55e9ed9cb5f91d36e366ab3978a417813a/Software/DEMO0/Central_Controller_CPU1/Comm/RS485.c", "visit_date": "2023-04-01T23:31:05.961336" }
stackv2
#include "F28x_Project.h" #include "Comm.h" #include "../Peripheral/SCI.h" //***********************************************************************// // G l o b a l V a r i a b l e s // //***********************************************************************// Uint16 device_flag[NUMOFDEVICE] = {0}; Uint16 cast_flag[NUMOFDEVICE] = {0}; Uint16 RS485_addr[NUMOFDEVICE] = {0}; Uint16 RS485_tx[NUMOFDEVICE][SIZEOFRS485_TX] = {0}; Uint16 RS485_rx[NUMOFDEVICE][SIZEOFRS485_RX] = {0}; Uint16 RX_ctr = 0; extern Uint16 usb_tx[SIZEOFUSB_TX]; //***********************************************************************// // F u n c t i o n s // //***********************************************************************// void RS485_init(void) { ScibRegs.SCICTL1.bit.RXENA = 1; //Enable SCIB RX GpioDataRegs.GPACLEAR.bit.GPIO13 = 0; //Disable RS485 Driver GpioDataRegs.GPACLEAR.bit.GPIO12 = 1; //Initialize RS485 Receiver RS485_addr[0] = ADDR_DEVICE1; //device addr RS485_addr[1] = ADDR_DEVICE2; //device addr RS485_addr[2] = ADDR_DEVICE3; //device addr Uint16 i; for (i = 0; i < NUMOFDEVICE; i++) { RS485_tx[i][0] = 222; //device command: 222: stop RS485_tx[i][1] = 0; //device value } } void RS485_RX(Uint16 device_rx) { Uint16 addr = 0; if (ScibRegs.SCICTL1.bit.SLEEP && RX_ctr == 0) { addr = ScibRegs.SCIRXBUF.all; if (addr == ADDR_HOST) { ScibRegs.SCICTL1.bit.SLEEP = 0; //if address detected wake up } } else { RS485_rx[device_rx][RX_ctr] = ScibRegs.SCIRXBUF.all; RX_ctr ++; } if (RX_ctr == SIZEOFRS485_RX) { ScibRegs.SCICTL1.bit.SLEEP = 1; //back to sleep RX_ctr = 0; //ctr reset Uint16 i; for (i = 0; i < SIZEOFRS485_TX; i++) usb_tx[4*device_rx+i] = RS485_rx[device_rx][i]; } } void RS485_TX(Uint16 device) { GpioDataRegs.GPASET.bit.GPIO12 = 1; // Disable RS485 Receiver // adding delay? GpioDataRegs.GPASET.bit.GPIO13 = 1; // Enable RS485 Driver EALLOW; ScibRegs.SCICTL1.bit.TXENA = 1; //Enable TX ScibRegs.SCICTL1.bit.TXWAKE = 1; SCIB_xmit(cast_flag[device]? ADDR_BROADCAST: RS485_addr[device]); SCIB_xmit(device_flag[device]? RS485_tx[device][0]: CMD_NTH); // cmd or nth Uint16 i; for(i = 1; i < SIZEOFRS485_TX; i++) SCIB_xmit(RS485_tx[device][i]); // value, P_ref, Q_ref, w_avg, V_avg ScibRegs.SCICTL1.bit.TXENA = 0; //Disable TX EDIS; while (ScibRegs.SCICTL2.bit.TXEMPTY == 0) {} cast_flag[device] = 0;//Unflag device_flag[device] = 0; //Unflag GpioDataRegs.GPACLEAR.bit.GPIO13 = 1; // Disable RS485 Driver GpioDataRegs.GPACLEAR.bit.GPIO12 = 1; // Enable RS485 Receiver }
2.140625
2
2024-11-18T22:28:14.640643+00:00
2018-04-27T17:23:17
7722ea40a7d40d5809994b0083c1f9c9150b862d
{ "blob_id": "7722ea40a7d40d5809994b0083c1f9c9150b862d", "branch_name": "refs/heads/master", "committer_date": "2018-04-27T17:23:17", "content_id": "c3272c5d988a60d71dde30379a17225fde3d548d", "detected_licenses": [ "MIT" ], "directory_id": "107f12f146102a4393015acbac4060f060a3e819", "extension": "c", "filename": "tsargs.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": 4741, "license": "MIT", "license_type": "permissive", "path": "/src/tsargs.c", "provenance": "stackv2-0132.json.gz:71853", "repo_name": "Fahrek/tagsystem", "revision_date": "2018-04-27T17:23:17", "revision_id": "ca2948026d02d7a062a5cb6d8745e7571d286cce", "snapshot_id": "b1ee162ec729d5493309b8789ad4304941737823", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Fahrek/tagsystem/ca2948026d02d7a062a5cb6d8745e7571d286cce/src/tsargs.c", "visit_date": "2020-07-29T20:56:15.454437" }
stackv2
#include <stdio.h> #include <stdbool.h> #include <ctype.h> #include "hash.h" #include "sds.h" #include "tserror.h" #include "tsargs.h" #include "tsstr.h" // boolean arguments will be set to pointers to one of these values const bool _ts_args_true = true; const bool _ts_args_false = false; bool ts_args_matches(char * arg_name, char * arg_input_value) { /* checks if an argument matches a given input following certain rules: 1. case is ignored 2. an input can only be the first few letters of an argument (ie lis will match list) 3. vowels will be ignored (ie ls will match list) */ bool success = false; char * op_lowercase = malloc(strlen(arg_input_value) + 1); strcpy(op_lowercase, arg_input_value); ts_str_to_lower(op_lowercase); sds no_vowels = ts_str_without_vowels(sdsempty(), arg_name); if(ts_str_begins_with(arg_name, op_lowercase)) success = true; if(ts_str_begins_with(no_vowels, op_lowercase)) success = true; free(op_lowercase); sdsfree(no_vowels); return success; } int ts_args_create(ts_args * self) { // create an argument parsing object self->pending_value = false; self->latest_arg = 0; self->args = 0; return TS_SUCCESS; } void ** _ts_args_add(ts_args * self, char * name, ts_arg_type type) { /* add an argument to the 'self' argument parsing object arguments are stored as a singly linked list */ ts_arg * arg = calloc(sizeof(ts_arg), 1); if(self->args != 0) { self->latest_arg->next = arg; self->latest_arg = arg; } else { self->args = arg; self->latest_arg = arg; } self->latest_arg->type = type; self->latest_arg->name = name; return &self->latest_arg->value; } bool ** ts_args_add_bool(ts_args * self, char * name) { bool ** out = (bool**)_ts_args_add(self, name, ARG_TYPE_BOOL); *out = &_ts_args_false; return out; } char ** ts_args_add_str(ts_args * self, char * name) { return (char**)_ts_args_add(self, name, ARG_TYPE_STR); } bool _ts_args_set_param(ts_args * self, char * arg_input_value) { /* once an argument has been found, this function sets the value or flags that we are waiting for a string value to bind to the argument name */ bool success = false; ts_arg * arg = self->args; while(arg != 0) { if(ts_args_matches(arg->name, arg_input_value)) { if(arg->type == ARG_TYPE_BOOL) { arg->value = (void*)(&_ts_args_true); self->pending_value = false; success = true; break; } else if(arg->type == ARG_TYPE_STR) { self->pending_value_addr = &arg->value; self->pending_value = true; success = true; break; } } arg = arg->next; } return success; } int ts_args_parse(ts_args * self, int argc, char * argv[]) { /* Go through each provided argument and bind it to the argument variable that corosponds to its name */ self->pending_value = false; int i = 0; for(; i < argc; i++) { if(ts_str_begins_with(argv[i], "--")) { sds next = sdsnew(argv[i]); sdstrim(next, "-"); bool success = _ts_args_set_param(self, next); sdsfree(next); if(!success) { // error parsing argument break; } } else if(ts_str_begins_with(argv[i], "-")) { // arguments can be packed, so each char is a seperate arg int argv_len = strlen(argv[i]); for(int j = 1; j < argv_len; j++) { char next_char[2]; next_char[0] = argv[i][j]; next_char[1] = 0; if(!_ts_args_set_param(self, next_char)) { // parsing error break; } } } // if we're waiting for a string argument else if(self->pending_value) { *self->pending_value_addr = argv[i]; self->pending_value = false; } // otherwise, we're out of well formatted arguments else { break; } } // concat remaining values into a single 'rest' string self->rest = ts_str_concat_string(sdsempty(), argc - i, &argv[i]); return TS_SUCCESS; } int _ts_arg_close(ts_arg * arg) { // unwind the linked list of arguments if(arg->next != 0) _ts_arg_close(arg->next); free(arg); return TS_SUCCESS; } int ts_args_close(ts_args * self) { sdsfree(self->rest); _ts_arg_close(self->args); return TS_SUCCESS; }
2.984375
3
2024-11-18T22:28:14.922668+00:00
2019-07-01T03:27:51
73bfbcd6082364ec624610fcef33376f751af864
{ "blob_id": "73bfbcd6082364ec624610fcef33376f751af864", "branch_name": "refs/heads/master", "committer_date": "2019-07-01T03:27:51", "content_id": "a2e24241f9a8693ba0330b7852f2be189a27a16f", "detected_licenses": [ "MIT" ], "directory_id": "2209d192023cb24a529c90a60ec66d95619319f2", "extension": "c", "filename": "hello3.c", "fork_events_count": 0, "gha_created_at": "2019-07-06T00:28:27", "gha_event_created_at": "2019-07-06T00:28:27", "gha_language": null, "gha_license_id": "MIT", "github_id": 195480690, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 409, "license": "MIT", "license_type": "permissive", "path": "/Chapter 2/hello3.c", "provenance": "stackv2-0132.json.gz:71983", "repo_name": "urantialife/Learn-C-Programming---Fundamentals-of-C", "revision_date": "2019-07-01T03:27:51", "revision_id": "8d4988d2fb7ee24afd97e9be03eb141d936b5dc2", "snapshot_id": "1d8ad9a70fc11f5db4eb2ac930e7e9e2d1f718f3", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/urantialife/Learn-C-Programming---Fundamentals-of-C/8d4988d2fb7ee24afd97e9be03eb141d936b5dc2/Chapter 2/hello3.c", "visit_date": "2020-06-16T04:32:07.167767" }
stackv2
// // hello3.c // Chapter 2 // <book title> // // Using two functions, one function that takes no parameters, // and one function that takes a string parameter. // #include <stdio.h> void printComma() { printf( ", " ); } void printWord( char* word ) { printf( "%s" , word ); } int main() { printWord( "Hello" ); printComma(); printWord( "world" ); printf( "!\n" ); return 0; } // <eof>
3.203125
3
2024-11-18T22:28:15.074554+00:00
2011-09-24T11:29:25
550fbebf5af1949d2851427217e55f26a6066748
{ "blob_id": "550fbebf5af1949d2851427217e55f26a6066748", "branch_name": "refs/heads/master", "committer_date": "2011-09-24T11:29:25", "content_id": "d685fff51ca06117fb573ada9dc726380f5a1dbe", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "2fd9dddeb34b2ed12a01b454160e91223a443a4f", "extension": "c", "filename": "motor.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 1300939, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4533, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/control/motor.c", "provenance": "stackv2-0132.json.gz:72244", "repo_name": "PSU-UROV/Control", "revision_date": "2011-09-24T11:29:25", "revision_id": "3bbba48e5a331017dc14866652c6d54331dc0a55", "snapshot_id": "ab65ecd073f641d5f3c7d49ed4c8432a7c5fc917", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PSU-UROV/Control/3bbba48e5a331017dc14866652c6d54331dc0a55/control/motor.c", "visit_date": "2021-01-25T05:27:56.428907" }
stackv2
/* * Author: Gregory Haynes <[email protected]> * * Software License Agreement (BSD License) * * Copyright (c) 2011, Gregory Haynes * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders 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 ''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 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 "motor.h" #include "../esc/esc.h" static struct motor_controller_t _motor_controller; static float motor_val_pwm_fact; void motorsSyncDutyCycle(void); struct motor_controller_t *motorControllerGet(void) { return &_motor_controller; } void motorsInit(void) { motor_val_pwm_fact = ((float)CFG_MOTOR_MIN_THRUST - CFG_MOTOR_MAX_THRUST) / CFG_MOTOR_MAX; struct esc_controller_t *esc_controller; uint8_t i; esc_controller = escGetController(); for(i = 0;i < CFG_MOTOR_CNT;i++) _motor_controller.motors[i] = 0; ESC_SETUP(esc_controller->escs[0], ESC_1_PWM_PIN, ESC_1_PWM_TIMER, CFG_MOTOR_DEFAULT_DUTY_CYCLE) ESC_SETUP(esc_controller->escs[1], ESC_0_PWM_PIN, ESC_0_PWM_TIMER, CFG_MOTOR_DEFAULT_DUTY_CYCLE) ESC_SETUP(esc_controller->escs[2], ESC_2_PWM_PIN, ESC_2_PWM_TIMER, CFG_MOTOR_DEFAULT_DUTY_CYCLE) ESC_SETUP(esc_controller->escs[3], ESC_3_PWM_PIN, ESC_3_PWM_TIMER, CFG_MOTOR_DEFAULT_DUTY_CYCLE) escsInit(); } void motorsStart(void) { uint8_t i; escsArm(); motorsSyncDutyCycle(); } // If any motors are over CFG_MOTOR_MAX we rescale all, equally to make // this not the case void motors_rescale(float *motor_vals, int *scaled_vals) { int i; float scale_factor; // motor into working array for(i = 0;i < CFG_MOTOR_CNT;++i) scaled_vals[i] = motor_vals[i]; // Find max int max_ndx = 0; for(i = 1;i < CFG_MOTOR_CNT;++i) { if(scaled_vals[i] > scaled_vals[max_ndx]) max_ndx = i; } // We need to rescale if(scaled_vals[max_ndx] > CFG_MOTOR_MAX) { scale_factor = ((float)CFG_MOTOR_MAX) / scaled_vals[max_ndx]; for(i = 0;i < CFG_MOTOR_CNT;++i) scaled_vals[i] *= scale_factor; } } int motor_val_to_pwm(int val) { if(val < 0) return CFG_MOTOR_MIN_THRUST; return CFG_MOTOR_MIN_THRUST - (val * motor_val_pwm_fact); } // Called to actually apply motor changes void motorsSyncDutyCycle(void) { int i; // Rescale motors int scaled_vals[CFG_MOTOR_CNT]; motors_rescale(_motor_controller.motors, scaled_vals); // Convert to pwm duty cycle for(i = 0;i < CFG_MOTOR_CNT;++i) { scaled_vals[i] = motor_val_to_pwm(scaled_vals[i]); } struct esc_controller_t *controller; controller = escGetController(); for(i = 0;i < CFG_MOTOR_CNT;++i) { escSetDutyCycle(&controller->escs[i], scaled_vals[i]); } } void motors_off(void) { float vals[4]; int i; for(i = 0;i < CFG_MOTOR_CNT;++i) vals[i] = 0; motors_set(vals); } void motor_set(int ndx, float value) { _motor_controller.motors[ndx] = value; motorsSyncDutyCycle(); } void motors_set(float *values) { uint8_t i; for(i = 0;i < CFG_MOTOR_CNT;i++) _motor_controller.motors[i] = values[i]; motorsSyncDutyCycle(); } float motor_get_val(int ndx) { if(ndx < 0 || ndx >= CFG_MOTOR_CNT) return 0; return _motor_controller.motors[ndx]; }
2.234375
2
2024-11-18T22:28:15.555497+00:00
2018-06-02T17:10:45
ff8fd8ff891e49b39e7da6dc8fa1f4f7f7fba4f6
{ "blob_id": "ff8fd8ff891e49b39e7da6dc8fa1f4f7f7fba4f6", "branch_name": "refs/heads/master", "committer_date": "2018-06-02T17:10:45", "content_id": "1205d60c8731fa61e5950f90929275e0bbc632e8", "detected_licenses": [ "MIT" ], "directory_id": "96eb6ca6e25dbd8d53d97f6674256779d333d466", "extension": "h", "filename": "window.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": 1441, "license": "MIT", "license_type": "permissive", "path": "/src/window.h", "provenance": "stackv2-0132.json.gz:72634", "repo_name": "devangkantharia/CHICKENCOUP", "revision_date": "2018-06-02T17:10:45", "revision_id": "c3720b017f0a1582fe0fa8039faed9497ceb7f1f", "snapshot_id": "9e3e4f8539d2d14f2c759f7a2e8c16f90da710b4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/devangkantharia/CHICKENCOUP/c3720b017f0a1582fe0fa8039faed9497ceb7f1f/src/window.h", "visit_date": "2020-05-01T03:54:27.662849" }
stackv2
#ifndef EX_WINDOW_H #define EX_WINDOW_H #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include <inttypes.h> #ifdef __EMSCRIPTEN__ #include <emscripten/html5.h> #endif typedef struct { GLFWwindow *window; double mouse_x, mouse_y; } ex_window_t; extern ex_window_t display; extern uint8_t ex_keys_down[GLFW_KEY_LAST]; extern uint8_t ex_buttons_down[GLFW_KEY_LAST]; void ex_key_callback(GLFWwindow *window, int key, int scancode, int action, int mode); void ex_button_callback(GLFWwindow *window, int button, int action, int mods); void ex_char_callback(GLFWwindow *window, unsigned int c); void ex_scroll_callback(GLFWwindow *window, double xoffset, double yoffset); void ex_mouse_callback(GLFWwindow* window, double x, double y); void ex_resize_callback(GLFWwindow* window, int width, int height); #ifdef __EMSCRIPTEN__ EM_BOOL ex_ehandle_keys(int type, const EmscriptenKeyboardEvent *e, void *user_data); EM_BOOL ex_ehandle_mouse(int type, const EmscriptenMouseEvent *e, void *user_data); #endif /** * [ex_window_init creates the window and gl context] * @param width [window width] * @param height [window height] * @param title [window title] * @return [true on success] */ int ex_window_init(uint32_t width, uint32_t height, const char *title); void ex_window_begin(); void ex_window_end(); /** * [window_exit clean up any data] */ void ex_window_destroy(); #endif // EX_WINDOW_H
2.078125
2
2024-11-18T22:28:16.151237+00:00
2020-06-17T08:24:47
713e6c55ef9a6295f6c97ec0c6d36d6061ba79cf
{ "blob_id": "713e6c55ef9a6295f6c97ec0c6d36d6061ba79cf", "branch_name": "refs/heads/master", "committer_date": "2020-06-17T08:24:47", "content_id": "b4a48b6f1ecfb02d3bb6fd40605b33ed7faef5c7", "detected_licenses": [ "MIT" ], "directory_id": "df04509fc215f47961cef9601090c32a2054d136", "extension": "c", "filename": "set_sockaddr_in.c", "fork_events_count": 0, "gha_created_at": "2020-06-03T17:44:15", "gha_event_created_at": "2020-06-03T17:44:16", "gha_language": null, "gha_license_id": "MIT", "github_id": 269155186, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 314, "license": "MIT", "license_type": "permissive", "path": "/src/lib/set_sockaddr_in.c", "provenance": "stackv2-0132.json.gz:73025", "repo_name": "khrushv/MultiThreaded-TCP-Server-Client", "revision_date": "2020-06-17T08:24:47", "revision_id": "5981ad6cdef6a861a82507d969ce8d84e32641f2", "snapshot_id": "9abad93310e9309876c0cf67b53965d5f9ef0bf3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/khrushv/MultiThreaded-TCP-Server-Client/5981ad6cdef6a861a82507d969ce8d84e32641f2/src/lib/set_sockaddr_in.c", "visit_date": "2022-10-23T07:51:26.330137" }
stackv2
// // Created by khrushv on 14.06.2020. // #include <netinet/in.h> #include "set_sockaddr_in.h" void set_sockaddr_in(struct sockaddr_in* server, short s_port, unsigned short port, unsigned long s_addr) { server->sin_family = s_port; server->sin_port = htons(port); server->sin_addr.s_addr = s_addr; }
2.21875
2
2024-11-18T22:28:16.947111+00:00
2021-07-08T15:31:48
dea6eb42d2743a0c612bc42a2474ffdf58f3e599
{ "blob_id": "dea6eb42d2743a0c612bc42a2474ffdf58f3e599", "branch_name": "refs/heads/main", "committer_date": "2021-07-08T15:31:48", "content_id": "642acf5d7c7517afcdd6c2c765bdd3c4f25bebb8", "detected_licenses": [ "Zlib" ], "directory_id": "ddf8d00f202136b168a1c9df010b0c08f7cea430", "extension": "c", "filename": "marquee-displaydaemon.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 381151782, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 32071, "license": "Zlib", "license_type": "permissive", "path": "/marquee-displaydaemon.c", "provenance": "stackv2-0132.json.gz:73416", "repo_name": "icculus/arcade1up-lcd-marquee", "revision_date": "2021-07-08T15:31:48", "revision_id": "4258d5065998ed690e47b416431650678c19fc6b", "snapshot_id": "0bdabd7a42b87a144931efc6f0bf104ab84c2bea", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/icculus/arcade1up-lcd-marquee/4258d5065998ed690e47b416431650678c19fc6b/marquee-displaydaemon.c", "visit_date": "2023-06-13T23:46:19.631881" }
stackv2
/** * arcade1up-lcd-marquee; control an LCD in a Arcade1Up marquee. * * Please see the file LICENSE.txt in the source's root directory. * * This file written by Ryan C. Gordon. */ #include <stdio.h> #include "SDL.h" #ifdef __linux__ #define USE_DBUS 1 #define USE_LIBEVDEV 1 #else #define USE_DBUS 0 #define USE_LIBEVDEV 0 #endif #if USE_DBUS #include <dbus/dbus.h> #endif #if USE_LIBEVDEV #include <libevdev/libevdev-uinput.h> #endif //#define STBI_SSE2 1 #if defined(__ARM_NEON) || (defined(__ARM_ARCH) && (__ARM_ARCH >= 8)) /* ARMv8 always has NEON. */ #define STBI_NEON 1 #endif //#define STB_IMAGE_STATIC #define STB_IMAGE_IMPLEMENTATION #define STBI_ASSERT(x) SDL_assert(x) #define STBI_MALLOC(x) SDL_malloc(x) #define STBI_REALLOC(x,y) SDL_realloc(x, y) #define STBI_FREE(x) SDL_free(x) #include "stb_image.h" #define NANOSVG_IMPLEMENTATION #include "nanosvg.h" #define NANOSVGRAST_IMPLEMENTATION #include "nanosvgrast.h" static SDL_Window *window = NULL; static SDL_Renderer *renderer = NULL; static SDL_Texture *texture = NULL; static int texturew = 0; static int textureh = 0; static int screenw = 0; static int screenh = 0; static Uint32 fadems = 500; #if USE_DBUS static DBusConnection *dbus = NULL; #endif static int fingers_down = 0; // virtual mouse state static SDL_bool motion_finger_down = SDL_FALSE; static SDL_FingerID motion_finger = 0; static SDL_bool button_finger_down = SDL_FALSE; static SDL_FingerID button_finger = 0; #if USE_LIBEVDEV static struct libevdev *evdev_mouse = NULL; static struct libevdev_uinput *uidev_mouse = NULL; #endif // virtual keyboard state typedef struct { unsigned int scancode; SDL_Rect rect; } virtkey; typedef struct { SDL_bool pressed; SDL_FingerID finger; int keyindex; } keypress; static SDL_bool keyboard_slide_cooldown = SDL_FALSE; static float keyboard_slide_percent = 0.0f; static int keyboardw = 0; static int keyboardh = 0; static SDL_Texture *keyboard_texture = NULL; static virtkey keyinfo[64]; static keypress pressed_keys[10]; static Uint32 keyboard_slide_ms = 500; #if USE_LIBEVDEV static struct libevdev *evdev_keyboard = NULL; static struct libevdev_uinput *uidev_keyboard = NULL; #endif static void (*handle_fingerdown)(const SDL_TouchFingerEvent *e) = NULL; static void (*handle_fingerup)(const SDL_TouchFingerEvent *e) = NULL; static void (*handle_fingermotion)(const SDL_TouchFingerEvent *e) = NULL; static void (*handle_redraw)(void) = NULL; static void redraw_window(void) { SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); if (texture) { // fading in SDL_RenderSetLogicalSize(renderer, texturew, textureh); SDL_SetTextureAlphaMod(texture, 255); SDL_RenderCopy(renderer, texture, NULL, NULL); } SDL_RenderSetLogicalSize(renderer, screenw, screenh); if (handle_redraw) { handle_redraw(); } SDL_RenderPresent(renderer); } static void handle_fingerdown_keyboard(const SDL_TouchFingerEvent *e); static void handle_fingerup_keyboard(const SDL_TouchFingerEvent *e); static void handle_fingermotion_keyboard(const SDL_TouchFingerEvent *e); static void handle_redraw_keyboard(void); static void handle_fingerdown_mouse(const SDL_TouchFingerEvent *e); static void handle_fingerup_mouse(const SDL_TouchFingerEvent *e); static void handle_fingermotion_mouse(const SDL_TouchFingerEvent *e); static SDL_Texture *load_image(const char *fname, int *_w, int *_h) { SDL_Texture *newtex = NULL; if (fname) { const char *ext = SDL_strrchr(fname, '.'); if (ext && (SDL_strcasecmp(ext, ".svg") == 0)) { NSVGimage *image = image = nsvgParseFromFile(fname, "px", 96.0f); if (!image) { fprintf(stderr, "WARNING: couldn't load SVG image \"%s\"\n", fname); } else { NSVGrasterizer *rast = nsvgCreateRasterizer(); if (!rast) { fprintf(stderr, "WARNING: couldn't create SVG rasterizer for \"%s\"\n", fname); } else { const int w = (int) image->width; const int h = (int) image->height; *_w = w; *_h = h; unsigned char *img = SDL_malloc(w * h * 4); if (!img) { fprintf(stderr, "WARNING: out of memory for \"%s\"\n", fname); } else { nsvgRasterize(rast, image, 0, 0, 1, img, w, h, w * 4); newtex = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, w, h); if (!newtex) { fprintf(stderr, "WARNING: couldn't create texture for \"%s\"\n", fname); } else { SDL_UpdateTexture(newtex, NULL, img, w * 4); SDL_SetTextureBlendMode(newtex, SDL_BLENDMODE_BLEND); } SDL_free(img); } nsvgDeleteRasterizer(rast); } nsvgDelete(image); } } else { int n; stbi_uc *img = stbi_load(fname, _w, _h, &n, 4); if (!img) { fprintf(stderr, "WARNING: couldn't load image \"%s\"\n", fname); } else { newtex = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, *_w, *_h); if (!newtex) { fprintf(stderr, "WARNING: couldn't create texture for \"%s\"\n", fname); } else { SDL_UpdateTexture(newtex, NULL, img, *_w * 4); SDL_SetTextureBlendMode(newtex, SDL_BLENDMODE_BLEND); } stbi_image_free(img); } } } return newtex; } static void set_new_image(const char *fname) { int w = 0; int h = 0; printf("Setting new image \"%s\"\n", fname); SDL_Texture *newtex = load_image(fname, &w, &h); const Uint32 startms = SDL_GetTicks(); const Uint32 timeout = startms + fadems; for (Uint32 now = startms; !SDL_TICKS_PASSED(now, timeout); now = SDL_GetTicks()) { const float unclamped_percent = ((float) (now - startms)) / ((float) fadems); const float percent = SDL_max(0.0f, SDL_min(unclamped_percent, 1.0f)); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); if (texture) { // fading out SDL_RenderSetLogicalSize(renderer, texturew, textureh); SDL_SetTextureAlphaMod(texture, (Uint8) (255.0f * (1.0f - percent))); SDL_RenderCopy(renderer, texture, NULL, NULL); } if (newtex) { // fading in SDL_RenderSetLogicalSize(renderer, w, h); SDL_SetTextureAlphaMod(newtex, (Uint8) (255.0f * percent)); SDL_RenderCopy(renderer, newtex, NULL, NULL); } // !!! FIXME: move this loop to state variables and make it part of // !!! FIXME: redraw_window() instead of shoving a handle_redraw // !!! FIXME: call in here. if (handle_redraw) { handle_redraw(); } SDL_RenderPresent(renderer); SDL_Delay(10); } SDL_Texture *destroyme = texture; texture = newtex; texturew = w; textureh = h; // one last time, with no fade at all. redraw_window(); if (destroyme) { SDL_DestroyTexture(destroyme); } } static void slide_in_keyboard(void) { if (!keyboard_texture) { return; // no keyboard for you. } //printf("Sliding in keyboard!\n"); // Send keyup events for anything that fingers are still touching. #if USE_LIBEVDEV if (button_finger_down && uidev_mouse) { libevdev_uinput_write_event(uidev_mouse, EV_KEY, BTN_LEFT, 0); libevdev_uinput_write_event(uidev_mouse, EV_SYN, SYN_REPORT, 0); } #endif motion_finger_down = SDL_FALSE; motion_finger = 0; button_finger_down = SDL_FALSE; button_finger = 0; keyboard_slide_cooldown = SDL_TRUE; handle_fingerup = handle_fingerup_keyboard; handle_fingerdown = handle_fingerdown_keyboard; handle_fingermotion = handle_fingermotion_keyboard; handle_redraw = handle_redraw_keyboard; keyboard_slide_percent = 0.0f; const Uint32 startms = SDL_GetTicks(); const Uint32 timeout = startms + keyboard_slide_ms; for (Uint32 now = startms; !SDL_TICKS_PASSED(now, timeout); now = SDL_GetTicks()) { const float unclamped_percent = ((float) (now - startms)) / ((float) keyboard_slide_ms); keyboard_slide_percent = SDL_max(0.0f, SDL_min(unclamped_percent, 1.0f)); redraw_window(); } keyboard_slide_percent = 1.0f; redraw_window(); } static void slide_out_keyboard(void) { //printf("Sliding out keyboard!\n"); // Send keyup events for anything that fingers are still touching. for (int i = 0; i < SDL_arraysize(pressed_keys); i++) { if (pressed_keys[i].pressed) { //printf("Released virtual keyboard key %u\n", keyinfo[pressed_keys[i].keyindex].scancode); pressed_keys[i].pressed = SDL_FALSE; #if USE_LIBEVDEV if (uidev_keyboard) { libevdev_uinput_write_event(uidev_keyboard, EV_KEY, keyinfo[pressed_keys[i].keyindex].scancode, 0); libevdev_uinput_write_event(uidev_keyboard, EV_SYN, SYN_REPORT, 0); } #endif } } keyboard_slide_cooldown = SDL_TRUE; handle_fingerup = handle_fingerup_mouse; handle_fingerdown = handle_fingerdown_mouse; handle_fingermotion = handle_fingermotion_mouse; handle_redraw = handle_redraw_keyboard; keyboard_slide_percent = 0.0f; const Uint32 startms = SDL_GetTicks(); const Uint32 timeout = startms + keyboard_slide_ms; for (Uint32 now = startms; !SDL_TICKS_PASSED(now, timeout); now = SDL_GetTicks()) { const float unclamped_percent = ((float) (now - startms)) / ((float) keyboard_slide_ms); keyboard_slide_percent = 1.0f - SDL_max(0.0f, SDL_min(unclamped_percent, 1.0f)); redraw_window(); } keyboard_slide_percent = 0.0f; redraw_window(); handle_redraw = NULL; } static void handle_fingerdown_mouse(const SDL_TouchFingerEvent *e) { if (fingers_down == 4) { slide_in_keyboard(); } else if (!motion_finger_down) { //printf("FINGERDOWN: This is the motion finger.\n"); motion_finger = e->fingerId; motion_finger_down = SDL_TRUE; } else if (!button_finger_down) { //printf("FINGERDOWN: This is the button finger.\n"); button_finger = e->fingerId; button_finger_down = SDL_TRUE; #if USE_LIBEVDEV if (uidev_mouse) { libevdev_uinput_write_event(uidev_mouse, EV_KEY, BTN_LEFT, 1); libevdev_uinput_write_event(uidev_mouse, EV_SYN, SYN_REPORT, 0); } #endif } } static void handle_fingerup_mouse(const SDL_TouchFingerEvent *e) { if (motion_finger_down && (e->fingerId == motion_finger)) { //printf("FINGERUP: This is the motion finger.\n"); motion_finger_down = SDL_FALSE; motion_finger = 0; } else if (button_finger_down && (e->fingerId == button_finger)) { //printf("FINGERUP: This is the button finger.\n"); button_finger_down = SDL_FALSE; button_finger = 0; #if USE_LIBEVDEV if (uidev_mouse) { libevdev_uinput_write_event(uidev_mouse, EV_KEY, BTN_LEFT, 0); libevdev_uinput_write_event(uidev_mouse, EV_SYN, SYN_REPORT, 0); } #endif } } static void handle_fingermotion_mouse(const SDL_TouchFingerEvent *e) { if (!motion_finger_down || (e->fingerId != motion_finger)) { return; } #if USE_LIBEVDEV if (uidev_mouse) { SDL_bool hasdata = SDL_FALSE; if (e->dx != 0.0f) { hasdata = SDL_TRUE; const int val = (int) (((float) screenw) * e->dx); //printf("X FINGERMOTION: %d\n", val); libevdev_uinput_write_event(uidev_mouse, EV_REL, REL_X, val); } if (e->dy != 0.0f) { hasdata = SDL_TRUE; const int val = (int) (((float) screenh) * e->dy); //printf("Y FINGERMOTION: %d\n", val); libevdev_uinput_write_event(uidev_mouse, EV_REL, REL_Y, val); } if (hasdata) { libevdev_uinput_write_event(uidev_mouse, EV_SYN, SYN_REPORT, 0); } } #endif } static void handle_fingerdown_keyboard(const SDL_TouchFingerEvent *e) { if (fingers_down == 4) { slide_out_keyboard(); } else { const int x = (int) (((float) screenw) * e->x); const int y = (int) (((float) screenh) * e->y); const SDL_Point pt = { x, y }; int keyindex = -1; // find the key we're touching for (int i = 0; i < SDL_arraysize(keyinfo); i++) { if (SDL_PointInRect(&pt, &keyinfo[i].rect)) { keyindex = i; break; } } if (keyindex == -1) { return; // not touching a key } int pressedindex = -1; for (int i = 0; i < SDL_arraysize(pressed_keys); i++) { if (!pressed_keys[i].pressed) { pressedindex = i; } else if (pressed_keys[i].keyindex == keyindex) { return; // already a finger on this key, ignore it. } } if (pressedindex == -1) { return; // no open slots?!?! } pressed_keys[pressedindex].pressed = SDL_TRUE; pressed_keys[pressedindex].finger = e->fingerId; pressed_keys[pressedindex].keyindex = keyindex; //printf("Pressed virtual keyboard key %u\n", keyinfo[keyindex].scancode); #if USE_LIBEVDEV if (uidev_keyboard) { libevdev_uinput_write_event(uidev_keyboard, EV_KEY, keyinfo[keyindex].scancode, 1); libevdev_uinput_write_event(uidev_keyboard, EV_SYN, SYN_REPORT, 0); } #endif redraw_window(); } } static void handle_fingerup_keyboard(const SDL_TouchFingerEvent *e) { for (int i = 0; i < SDL_arraysize(pressed_keys); i++) { if (pressed_keys[i].pressed && (pressed_keys[i].finger == e->fingerId)) { //printf("Released virtual keyboard key %u\n", keyinfo[pressed_keys[i].keyindex].scancode); pressed_keys[i].pressed = SDL_FALSE; #if USE_LIBEVDEV if (uidev_keyboard) { libevdev_uinput_write_event(uidev_keyboard, EV_KEY, keyinfo[pressed_keys[i].keyindex].scancode, 0); libevdev_uinput_write_event(uidev_keyboard, EV_SYN, SYN_REPORT, 0); } #endif redraw_window(); return; } } } static void handle_fingermotion_keyboard(const SDL_TouchFingerEvent *e) { // does nothing right now. } static void handle_redraw_keyboard(void) { const int w = screenw; const int h = screenh; const int y = screenh - ((int) (((float) h) * keyboard_slide_percent)); const SDL_Rect dst = { 0, y, w, keyboardh }; //SDL_SetTextureAlphaMod(keyboard_texture, 255.0f * keyboard_slide_percent); SDL_RenderCopy(renderer, keyboard_texture, NULL, &dst); SDL_SetRenderDrawColor(renderer, 175, 0, 0, 90); for (int i = 0; i < SDL_arraysize(pressed_keys); i++) { if (pressed_keys[i].pressed) { SDL_RenderFillRect(renderer, &keyinfo[pressed_keys[i].keyindex].rect); } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 0); } static SDL_bool iterate(void) { SDL_bool redraw = SDL_FALSE; SDL_bool saw_event = SDL_FALSE; char *newimage = NULL; SDL_Event e; while (SDL_PollEvent(&e)) { saw_event = SDL_TRUE; switch (e.type) { case SDL_FINGERDOWN: fingers_down++; //printf("FINGER DOWN! We now have %d fingers\n", fingers_down); if (!keyboard_slide_cooldown) { handle_fingerdown(&e.tfinger); } break; case SDL_FINGERUP: fingers_down--; //printf("FINGER UP! We now have %d fingers\n", fingers_down); if (!keyboard_slide_cooldown) { handle_fingerup(&e.tfinger); } else if (!fingers_down) { keyboard_slide_cooldown = SDL_FALSE; } break; case SDL_FINGERMOTION: if (!keyboard_slide_cooldown) { handle_fingermotion(&e.tfinger); } break; case SDL_QUIT: printf("Got SDL_QUIT event, quitting now...\n"); return SDL_FALSE; case SDL_WINDOWEVENT: if ( (e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) || (e.window.event == SDL_WINDOWEVENT_EXPOSED) ) { redraw = SDL_TRUE; } break; case SDL_DROPFILE: /* you aren't going to get a DROPFILE event on the Pi, but this is useful for testing when building on a desktop system. */ SDL_free(newimage); newimage = e.drop.file; break; default: break; } } #if USE_DBUS if (dbus) { dbus_connection_read_write(dbus, 0); DBusMessage *msg; while ((msg = dbus_connection_pop_message(dbus)) != NULL) { if (dbus_message_is_signal(msg, "org.icculus.Arcade1UpMarquee", "ShowImage")) { saw_event = SDL_TRUE; DBusMessageIter args; if ( dbus_message_iter_init(msg, &args) && (dbus_message_iter_get_arg_type(&args) == DBUS_TYPE_STRING) ) { char *param = NULL; dbus_message_iter_get_basic(&args, &param); //printf("Got D-Bus request to show image \"%s\"\n", param); SDL_free(newimage); newimage = SDL_strdup(param); } } dbus_message_unref(msg); } } #endif if (!saw_event && !fingers_down) { SDL_Delay(100); } else if (newimage) { set_new_image(newimage); SDL_free(newimage); } else if (redraw) { redraw_window(); } return SDL_TRUE; } static void set_backlight(const SDL_bool value) { // we don't care if any of this fails. FILE *io = fopen("/sys/class/backlight/rpi_backlight/bl_power", "w"); if (io) { fputs(value ? "0" : "1", io); // yes, this looks backwards. fclose(io); } } static void deinitialize(void) { #if USE_DBUS if (dbus) { dbus_connection_unref(dbus); dbus = NULL; } #endif #if USE_LIBEVDEV if (uidev_mouse) { libevdev_uinput_destroy(uidev_mouse); uidev_mouse = NULL; } if (evdev_mouse) { libevdev_free(evdev_mouse); evdev_mouse = NULL; } if (uidev_keyboard) { libevdev_uinput_destroy(uidev_keyboard); uidev_keyboard = NULL; } if (evdev_keyboard) { libevdev_free(evdev_keyboard); evdev_keyboard = NULL; } #endif if (texture) { SDL_DestroyTexture(texture); texture = NULL; } if (keyboard_texture) { SDL_DestroyTexture(keyboard_texture); keyboard_texture = NULL; } if (renderer) { SDL_DestroyRenderer(renderer); renderer = NULL; } if (window) { SDL_DestroyWindow(window); window = NULL; } SDL_Quit(); set_backlight(SDL_FALSE); } static SDL_Texture *build_keyboard_texture(void) { SDL_Texture *tex = load_image("/home/pi/arcade1up-lcd-marquee/keyboard-en.png", &keyboardw, &keyboardh); // !!! FIXME: hardcoded if (!tex) { return NULL; } int posx = 4; int posy = 4; int keyw = 52; int keyh = 52; virtkey *k = keyinfo; #define ADDKEY(sc, x, y, w, h) { \ SDL_assert((k - keyinfo) < SDL_arraysize(keyinfo)); \ const SDL_Rect r = { x, y, w, h }; \ SDL_memcpy(&k->rect, &r, sizeof (SDL_Rect)); \ k->scancode = KEY_##sc; \ k++; \ posx += (w + 1); \ } // !!! FIXME: hardcoded mess ADDKEY(GRAVE, posx, posy, keyw, keyh); ADDKEY(1, posx, posy, keyw, keyh); ADDKEY(2, posx, posy, keyw, keyh); ADDKEY(3, posx, posy, keyw, keyh); ADDKEY(4, posx, posy, keyw, keyh); ADDKEY(5, posx, posy, keyw, keyh); ADDKEY(6, posx, posy, keyw, keyh); ADDKEY(7, posx, posy, keyw, keyh); ADDKEY(8, posx, posy, keyw, keyh); ADDKEY(9, posx, posy, keyw, keyh); ADDKEY(0, posx, posy, keyw, keyh); ADDKEY(MINUS, posx, posy, keyw, keyh); ADDKEY(EQUAL, posx, posy, keyw, keyh); ADDKEY(BACKSPACE, posx, posy, 105, keyh); posx = 4; posy += (keyh + 1); ADDKEY(TAB, posx, posy, 78, keyh); ADDKEY(Q, posx, posy, keyw, keyh); ADDKEY(W, posx, posy, keyw, keyh); ADDKEY(E, posx, posy, keyw, keyh); ADDKEY(R, posx, posy, keyw, keyh); ADDKEY(T, posx, posy, keyw, keyh); ADDKEY(Y, posx, posy, keyw, keyh); ADDKEY(U, posx, posy, keyw, keyh); ADDKEY(I, posx, posy, keyw, keyh); ADDKEY(O, posx, posy, keyw, keyh); ADDKEY(P, posx, posy, keyw, keyh); ADDKEY(LEFTBRACE, posx, posy, keyw, keyh); ADDKEY(RIGHTBRACE, posx, posy, keyw, keyh); ADDKEY(BACKSLASH, posx, posy, 78, keyh); posx = 4; posy += (keyh + 1); ADDKEY(CAPSLOCK, posx, posy, 91, keyh); ADDKEY(A, posx, posy, keyw, keyh); ADDKEY(S, posx, posy, keyw, keyh); ADDKEY(D, posx, posy, keyw, keyh); ADDKEY(F, posx, posy, keyw, keyh); ADDKEY(G, posx, posy, keyw, keyh); ADDKEY(H, posx, posy, keyw, keyh); ADDKEY(J, posx, posy, keyw, keyh); ADDKEY(K, posx, posy, keyw, keyh); ADDKEY(L, posx, posy, keyw, keyh); ADDKEY(SEMICOLON, posx, posy, keyw, keyh); ADDKEY(APOSTROPHE, posx, posy, keyw, keyh); ADDKEY(ENTER, posx, posy, 118, keyh); posx = 4; posy += (keyh + 1); ADDKEY(LEFTSHIFT, posx, posy, 118, keyh); ADDKEY(Z, posx, posy, keyw, keyh); ADDKEY(X, posx, posy, keyw, keyh); ADDKEY(C, posx, posy, keyw, keyh); ADDKEY(V, posx, posy, keyw, keyh); ADDKEY(B, posx, posy, keyw, keyh); ADDKEY(N, posx, posy, keyw, keyh); ADDKEY(M, posx, posy, keyw, keyh); ADDKEY(COMMA, posx, posy, keyw, keyh); ADDKEY(DOT, posx, posy, keyw, keyh); ADDKEY(SLASH, posx, posy, keyw, keyh); ADDKEY(RIGHTSHIFT, posx, posy, 145, keyh); posx = 4; posy += (keyh + 1); ADDKEY(LEFTCTRL, posx, posy, 78, keyh); ADDKEY(LEFTMETA, posx, posy, 65, keyh); ADDKEY(LEFTALT, posx, posy, 65, keyh); ADDKEY(SPACE, posx, posy, 304, keyh); ADDKEY(RIGHTALT, posx, posy, 65, keyh); ADDKEY(RIGHTMETA, posx, posy, 65, keyh); ADDKEY(RIGHTCTRL, posx, posy, 78, keyh); #undef ADDKEY return tex; } static SDL_bool initialize(const int argc, char **argv) { // make sure static vars are sane. fingers_down = 0; motion_finger_down = SDL_FALSE; motion_finger = 0; button_finger_down = SDL_FALSE; button_finger = 0; keyboard_slide_cooldown = SDL_FALSE; keyboard_slide_percent = 0.0f; SDL_zero(keyinfo); SDL_zero(pressed_keys); handle_fingerdown = handle_fingerdown_mouse; handle_fingerup = handle_fingerup_mouse; handle_fingermotion = handle_fingermotion_mouse; handle_redraw = NULL; int displayidx = 1; // presumably a good default for our use case. const char *initial_image = NULL; Uint32 window_flags = SDL_WINDOW_FULLSCREEN_DESKTOP; int width = 800; int height = 480; for (int i = 1; i < argc; i++) { const char *arg = argv[i]; if (SDL_strcmp(arg, "--display") == 0) { displayidx = SDL_atoi(argv[++i]); } else if (SDL_strcmp(arg, "--width") == 0) { width = SDL_atoi(argv[++i]); } else if (SDL_strcmp(arg, "--height") == 0) { height = SDL_atoi(argv[++i]); } else if (SDL_strcmp(arg, "--fadems") == 0) { fadems = (Uint32) SDL_atoi(argv[++i]); } else if (SDL_strcmp(arg, "--keyboardms") == 0) { keyboard_slide_ms = (Uint32) SDL_atoi(argv[++i]); } else if (SDL_strcmp(arg, "--windowed") == 0) { window_flags &= ~SDL_WINDOW_FULLSCREEN_DESKTOP; } else if (SDL_strcmp(arg, "--fullscreen") == 0) { window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } else if (SDL_strcmp(arg, "--startimage") == 0) { initial_image = argv[++i]; } else { fprintf(stderr, "WARNING: Ignoring unknown command line option \"%s\"\n", arg); } } if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "ERROR! SDL_Init(SDL_INIT_VIDEO) failed: %s\n", SDL_GetError()); return SDL_FALSE; } const char *driver = SDL_GetCurrentVideoDriver(); const SDL_bool isRpi = (SDL_strcasecmp(driver, "rpi") == 0); if (!isRpi) { fprintf(stderr, "WARNING: you aren't using SDL's \"rpi\" video target.\n" "WARNING: (you are using \"%s\" instead.)\n" "WARNING: This is probably _not_ what you wanted to do!\n", driver); } const int numdpy = SDL_GetNumVideoDisplays(); if (numdpy <= displayidx) { if (isRpi) { fprintf(stderr, "ERROR: We want display index %d, but there are only %d displays.\n" "ERROR: So as not to hijack the wrong display, we are aborting now.\n", displayidx, numdpy); return SDL_FALSE; } else { const int replacement = numdpy - 1; fprintf(stderr, "WARNING: We want display index %d, but there are only %d displays.\n" "WARNING: Choosing index %d instead.\n" "WARNING: This is probably _not_ what you wanted to do!\n", displayidx, numdpy, replacement); displayidx = replacement; } } window = SDL_CreateWindow("Arcade1Up LCD Marquee", SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayidx), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayidx), width, height, window_flags); if (!window) { fprintf(stderr, "ERROR! SDL_CreateWindow failed: %s\n", SDL_GetError()); return SDL_FALSE; } SDL_GetWindowSize(window, &screenw, &screenh); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!renderer) { fprintf(stderr, "WARNING! SDL_CreateRenderer(accel|vsync) failed: %s\n", SDL_GetError()); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { fprintf(stderr, "WARNING! SDL_CreateRenderer(accel) failed: %s\n", SDL_GetError()); renderer = SDL_CreateRenderer(window, -1, 0); if (!renderer) { fprintf(stderr, "ERROR! SDL_CreateRenderer(0) failed: %s\n", SDL_GetError()); fprintf(stderr, "Giving up.\n"); return SDL_FALSE; } } } #if 0 SDL_RendererInfo info; SDL_zero(info); SDL_GetRendererInfo(renderer, &info); printf("SDL renderer target: %s\n", info.name); #endif SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); SDL_RenderPresent(renderer); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); set_backlight(SDL_TRUE); /* on some systems, your window doesn't show up until the event queue gets pumped. */ SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) return SDL_FALSE; } set_new_image(initial_image); keyboard_texture = build_keyboard_texture(); // if d-bus fails, we carry on, with at least a default image showing. #if USE_DBUS DBusError err; dbus_error_init(&err); dbus = dbus_bus_get(DBUS_BUS_SYSTEM, &err); if (dbus_error_is_set(&err)) { fprintf(stderr, "ERROR: Can't connect to system D-Bus: %s\n", err.message); dbus_error_free(&err); dbus = NULL; } else if (dbus == NULL) { fprintf(stderr, "ERROR: Can't connect to system D-Bus\n"); } else { const int rc = dbus_bus_request_name(dbus, "org.icculus.Arcade1UpMarquee", DBUS_NAME_FLAG_REPLACE_EXISTING, &err); if (dbus_error_is_set(&err)) { fprintf(stderr, "ERROR: Couldn't acquire D-Bus service name: %s\n", err.message); dbus_error_free(&err); dbus_connection_unref(dbus); dbus = NULL; } else if (rc != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { fprintf(stderr, "ERROR: Not the primary owner of the D-Bus service name (%d)\n", rc); dbus_connection_unref(dbus); dbus = NULL; } if (dbus) { dbus_bus_add_match(dbus, "type='signal',interface='org.icculus.Arcade1UpMarquee'", &err); dbus_connection_flush(dbus); if (dbus_error_is_set(&err)) { fprintf(stderr, "ERROR: Can't match on D-Bus interface name (%d)\n", rc); dbus_connection_unref(dbus); dbus = NULL; } } } #endif #if USE_LIBEVDEV int rc; evdev_mouse = libevdev_new(); libevdev_set_name(evdev_mouse, "Icculus's LCD Marquee Mouse"); libevdev_enable_event_type(evdev_mouse, EV_REL); libevdev_enable_event_code(evdev_mouse, EV_REL, REL_X, NULL); libevdev_enable_event_code(evdev_mouse, EV_REL, REL_Y, NULL); libevdev_enable_event_type(evdev_mouse, EV_KEY); libevdev_enable_event_code(evdev_mouse, EV_KEY, BTN_LEFT, NULL); //libevdev_enable_event_code(evdev_mouse, EV_KEY, BTN_MIDDLE, NULL); //libevdev_enable_event_code(evdev_mouse, EV_KEY, BTN_RIGHT, NULL); rc = libevdev_uinput_create_from_device(evdev_mouse, LIBEVDEV_UINPUT_OPEN_MANAGED, &uidev_mouse); if (rc != 0) { fprintf(stderr, "WARNING: Couldn't set up uinput; no mouse emulation for you! (rc=%d)\n", rc); libevdev_free(evdev_mouse); evdev_mouse = NULL; } evdev_keyboard = libevdev_new(); libevdev_set_name(evdev_keyboard, "Icculus's LCD Marquee Keyboard"); libevdev_enable_event_type(evdev_keyboard, EV_KEY); // we don't send all of these, but this is easier than picking them all out and maintaining a list here. for (unsigned int i = KEY_ESC; i < KEY_WIMAX; i++) { libevdev_enable_event_code(evdev_keyboard, EV_KEY, i, NULL); } rc = libevdev_uinput_create_from_device(evdev_keyboard, LIBEVDEV_UINPUT_OPEN_MANAGED, &uidev_keyboard); if (rc != 0) { fprintf(stderr, "WARNING: Couldn't set up uinput; no keyboard emulation for you! (rc=%d)\n", rc); libevdev_free(evdev_keyboard); evdev_keyboard = NULL; } #endif return SDL_TRUE; } int main(int argc, char **argv) { if (!initialize(argc, argv)) { deinitialize(); return 1; } while (iterate()) { // spin. } deinitialize(); return 0; } // end of marquee-displaydaemon.c ...
2.328125
2
2024-11-18T22:28:18.571490+00:00
2018-09-30T23:40:04
749382d2d934de0e64325458ad513b4b7bff80cd
{ "blob_id": "749382d2d934de0e64325458ad513b4b7bff80cd", "branch_name": "refs/heads/master", "committer_date": "2018-09-30T23:40:04", "content_id": "c77391bf388ffcae8f8584398ae7de299b6a8f6e", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "afe204e8f1e48de8f6fff87904396921c3bfaf75", "extension": "c", "filename": "gencrctable.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 151015956, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 749, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/gencrctable.c", "provenance": "stackv2-0132.json.gz:73677", "repo_name": "jessexm/dbgutils", "revision_date": "2018-09-30T23:40:04", "revision_id": "149e5ee1a49ff87861601ea992918d1d56873bc2", "snapshot_id": "eda88f096b645a8eaa0a1ae73d244444421e9556", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/jessexm/dbgutils/149e5ee1a49ff87861601ea992918d1d56873bc2/gencrctable.c", "visit_date": "2020-03-30T08:26:49.760526" }
stackv2
/* $Id: gencrctable.c,v 1.1 2004/08/03 14:23:48 jnekl Exp $ * * Utility to generate 'const uint8_t *crctable'. */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <ctype.h> /**************************************************************/ #define CRC_CCITT_POLY 0x8408 int main(int argc, char **argv) { int i; int j; uint16_t crc; printf("\nconst uint16_t *crctable = {"); for(i=0; i<256; i++) { crc = i; for(j=0; j<8; j++) { if(crc & 0x01) { crc >>= 1; crc ^= CRC_CCITT_POLY; } else { crc >>= 1; } } if(i % 8 == 0) { printf("\n\t"); } printf("0x%04X, ", crc); } printf("\n};\n\n"); return EXIT_SUCCESS; } /**************************************************************/
2.9375
3
2024-11-18T22:28:18.834267+00:00
2023-08-22T06:54:06
e6223dc0b4cc585eec85f7d405d6a9c04064a3ff
{ "blob_id": "e6223dc0b4cc585eec85f7d405d6a9c04064a3ff", "branch_name": "refs/heads/master", "committer_date": "2023-08-22T06:54:06", "content_id": "d9fab246f0b48c8bb7ad3263d967d0521854881b", "detected_licenses": [ "MIT" ], "directory_id": "9800559d454a39817f1d922f60fcb80c31934877", "extension": "c", "filename": "pdl_thread.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 186227923, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5735, "license": "MIT", "license_type": "permissive", "path": "/Poodle/pdl_thread/pdl_thread.c", "provenance": "stackv2-0132.json.gz:73805", "repo_name": "iOS-Developer-Sun/Poodle", "revision_date": "2023-08-22T06:54:06", "revision_id": "c21efacfe3cb1942197d091769ddc5bfcff61c16", "snapshot_id": "8b83e796119c05a16e5155c03b5616dceaacae88", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/iOS-Developer-Sun/Poodle/c21efacfe3cb1942197d091769ddc5bfcff61c16/Poodle/pdl_thread/pdl_thread.c", "visit_date": "2023-08-29T23:07:29.926259" }
stackv2
// // pdl_thread.c // Poodle // // Created by Poodle on 2020/5/12. // Copyright © 2020 Poodle. All rights reserved. // #include "pdl_thread.h" #include "pdl_thread_define.h" #include "pdl_pac.h" extern void *pdl_thread_fake(void **frames, void *(*start)(void *), void *arg); static void *pdl_thread_fake_end(void **frames, unsigned int frames_count, void *(*start)(void *), void *arg, int hidden_count) { int hc = hidden_count; unsigned int total_frames_count = frames_count; if (frames_count == 0) { total_frames_count++; } bool hides_without_self = hc > 0; if (hides_without_self) { total_frames_count++; } else { hc = -hc; } #ifdef __i386__ int alignment = 4; __attribute__((aligned(4))) void *aligned_frames[total_frames_count * alignment + 2]; void **stack_frames = aligned_frames + 2; #else int alignment = 2; void *aligned_frames[total_frames_count * alignment]; void **stack_frames = aligned_frames; #endif void (*self_lr)(void) = pdl_builtin_return_address(0); void *self_fp = pdl_builtin_frame_address(0); void (*lr)(void) = self_lr; void *fp = self_fp; int current_count = pdl_thread_frames(lr, fp, NULL, __INT_MAX__) - 1; if (current_count < hc) { lr = NULL; } else { int from = hc; if (hides_without_self) { from++; } fp = pdl_builtin_frame_address(from); lr = pdl_builtin_return_address(from); } if (frames_count > 0) { for (int i = 0; i < frames_count; i++) { int fp_index = i * alignment; int lr_index = i * alignment + 1; if (i != frames_count - 1) { stack_frames[fp_index] = &stack_frames[fp_index + alignment]; stack_frames[lr_index] = frames[i]; } else { if (hides_without_self) { stack_frames[fp_index] = &stack_frames[fp_index + alignment]; stack_frames[lr_index] = self_lr; stack_frames[fp_index + alignment] = fp; stack_frames[lr_index + alignment] = lr; } else { stack_frames[fp_index] = fp; stack_frames[lr_index] = lr; } } } } else { int fp_index = 0; int lr_index = 1; if (hides_without_self) { stack_frames[fp_index] = &stack_frames[fp_index + alignment]; stack_frames[lr_index] = self_lr; stack_frames[fp_index + alignment] = fp; stack_frames[lr_index + alignment] = lr; } else { stack_frames[fp_index] = fp; stack_frames[lr_index] = lr; } } void *ret = pdl_thread_fake(stack_frames, start, arg); return ret; } void *pdl_thread_execute(void **frames, unsigned int frames_count, void *(*start)(void *), void *arg, int hidden_count) { void *ret = pdl_thread_fake_end(frames, frames_count, start, arg, hidden_count); return ret; } int pdl_thread_frames(void *link_register, void *frame_pointer, void **frames, int count) { return pdl_thread_frames_with_filter(link_register, frame_pointer, frames, count, NULL); } #if defined(__x86_64__) #define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 0) #elif defined(__i386__) #define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 8) #elif defined(__arm__) || defined(__arm64__) #define ISALIGNED(a) ((((uintptr_t)(a)) & 0x1) == 0) #endif int pdl_thread_frames_with_filter(void *link_register, void *frame_pointer, void **frames, int count, pdl_thread_frame_filter *filter) { int ret = 0; void *lr = (void *)link_register; void **fp = (void **)frame_pointer; if (filter && filter->init) { bool valid = filter->init(filter); if (!valid) { return 0; } } while (true) { if (ret > count) { break; } bool available = true; if (filter && filter->is_valid) { available = filter->is_valid(filter, lr); } if (available) { if (frames) { frames[ret] = lr; } ret++; } if (!fp || !ISALIGNED(fp)) { break; } if (!lr) { break; } fp = *fp; if (fp && ISALIGNED(fp)) { lr = *(fp + 1); lr = pdl_ptrauth_strip_function(lr); } else { lr = NULL; } } if (filter && filter->destroy) { bool valid = filter->destroy(filter); if (!valid) { return 0; } } return ret; } bool pdl_thread_fake_begin_filter(void *link_register) { bool available = (link_register < (void *)&pdl_thread_fake) || (link_register > (void *)&pdl_thread_fake + pdl_thread_fake_size); return available; } bool pdl_thread_fake_end_filter(void *link_register) { bool available = (link_register < (void *)&pdl_thread_fake_end) || (link_register > (void *)&pdl_thread_fake_end + pdl_thread_fake_end_size); return available; } __attribute__((noinline)) void *pdl_builtin_frame_address(int frame) { void *fp = __builtin_frame_address(1); int count = frame; while (count > 0) { fp = *(void **)fp; count--; if (fp == NULL) { break; } } return fp; } __attribute__((noinline)) void *pdl_builtin_return_address(int frame) { void *lr = NULL; if (frame == 0) { lr = __builtin_return_address(0); } else { void **fp = pdl_builtin_frame_address(frame); if (fp) { lr = fp[1]; } } return lr; }
2.25
2
2024-11-18T22:28:20.073681+00:00
2019-02-23T04:35:27
850dfebef0310e82ed431e75dee4fa986fd926d9
{ "blob_id": "850dfebef0310e82ed431e75dee4fa986fd926d9", "branch_name": "refs/heads/master", "committer_date": "2019-02-23T04:35:27", "content_id": "2c0f942f4ff85ae5239ae46480bdba497d8fdbff", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ce364ab6343d88ca2b99655f414d78f9b5d5b47c", "extension": "h", "filename": "overflow.h", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 171314185, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7748, "license": "Apache-2.0", "license_type": "permissive", "path": "/Utils/src/uk/utils/compiler/overflow.h", "provenance": "stackv2-0132.json.gz:73934", "repo_name": "c-sonntag/UnknownKraken", "revision_date": "2019-02-23T04:35:27", "revision_id": "73405df4a56c73ab059bb3b87d3788c1cc3b4f06", "snapshot_id": "6531a7afcb7704c3ff88fe9c9fbdf6a5cd6a6517", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/c-sonntag/UnknownKraken/73405df4a56c73ab059bb3b87d3788c1cc3b4f06/Utils/src/uk/utils/compiler/overflow.h", "visit_date": "2020-04-23T16:54:49.592586" }
stackv2
/******************************************************************************* * Copyright (C) 2018 Charly Lamothe * * * * This file is part of LibUnknownEchoUtilsModule. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *******************************************************************************/ #ifndef UnknownKrakenUtils_OVERFLOW_H #define UnknownKrakenUtils_OVERFLOW_H #include <uk/utils/compiler/inline.h> #include <uk/utils/compiler/bool.h> #include <uk/utils/compiler/warn_unused_result.h> #include <uk/utils/compiler/typecheck.h> #include <uk/utils/compiler/typeof.h> #include <stddef.h> #include <stdint.h> #include <limits.h> #if defined(__unix__) #include <sys/cdefs.h> #endif /* Support for gcc/clang __has_builtin intrinsic */ #ifndef __has_builtin # define __has_builtin(x) 0 #endif /* Use clang/gcc compiler intrinsics whenever pueumsible */ #if (SIZE_MAX == ULONG_MAX) && __has_builtin(__builtin_uaddl_overflow) # define uk_utils__add_sizet_overflow(one, two, out) \ __builtin_uaddl_overflow(one, two, out) # define uk_utils__mul_sizet_overflow(one, two, out) \ __builtin_umull_overflow(one, two, out) # define uk_utils__sub_sizet_overflow(one, two, out) \ __builtin_usubl_overflow(one, two, out); #elif (SIZE_MAX == UINT_MAX) && __has_builtin(__builtin_uadd_overflow) # define uk_utils__add_sizet_overflow(one, two, out) \ __builtin_uadd_overflow(one, two, out) # define uk_utils__mul_sizet_overflow(one, two, out) \ __builtin_umul_overflow(one, two, out) # define uk_utils__sub_sizet_overflow(one, two, out) \ __builtin_usub_overflow(one, two, out); #else /** * Sets `one + two` into `out`, unless the arithmetic would overflow. * @return true if the result fits in a `size_t`, false on overflow. */ uk_utils__inline(bool) uk_utils__add_sizet_overflow(size_t one, size_t two, size_t *out) { if (ULONG_MAX - one < two) { return true; } *out = one + two; return false; } /** * Sets `one * two` into `out`, unless the arithmetic would overflow. * @return true if the result fits in a `size_t`, false on overflow. */ uk_utils__inline(bool) uk_utils__mul_sizet_overflow(size_t one, size_t two, size_t *out) { if (one && ULONG_MAX / one < two) { return true; } *out = one * two; return false; } /** * @source inspired from https://wiki.sei.cmu.edu/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap */ uk_utils__inline(bool) uk_utils__sub_sizet_overflow(size_t one, size_t two, size_t *out) { if (one < two) { return true; } *out = one - two; return false; } #endif /* * Facilities for performing type- and overflow-checked arithmetic. These * functions return non-zero if overflow occured, zero otherwise. In either case, * the potentially overflowing operation is fully performed, mod the size of the * output type. See: * https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html * http://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins * for full details. * * The compiler enforces that users of uk_utils__*_overflow() check the return value to * determine whether overflow occured. */ #if __has_builtin(__builtin_add_overflow) && \ __has_builtin(__builtin_sub_overflow) && \ __has_builtin(__builtin_mul_overflow) #define uk_utils__add_overflow(a, b, res) uk_utils__warn_unused_result(__builtin_add_overflow((a), (b), (res))) #define uk_utils__sub_overflow(a, b, res) uk_utils__warn_unused_result(__builtin_sub_overflow((a), (b), (res))) #define uk_utils__mul_overflow(a, b, res) uk_utils__warn_unused_result(__builtin_mul_overflow((a), (b), (res))) /* C11 */ #elif __STDC_VERSION__ >= 201112L #define uk___utils__add_overflow_func(T,U,V) _Generic((T), \ unsigned: __builtin_uadd_overflow, \ unsigned long: __builtin_uaddl_overflow, \ unsigned long long: __builtin_uaddll_overflow, \ int: __builtin_sadd_overflow, \ long: __builtin_saddl_overflow, \ long long: __builtin_saddll_overflow \ )(T,U,V) #define uk___utils__sub_overflow_func(T,U,V) _Generic((T), \ unsigned: __builtin_usub_overflow, \ unsigned long: __builtin_usubl_overflow, \ unsigned long long: __builtin_usubll_overflow, \ int: __builtin_ssub_overflow, \ long: __builtin_ssubl_overflow, \ long long: __builtin_ssubll_overflow \ )(T,U,V) #define uk___utils__mul_overflow_func(T,U,V) _Generic((T), \ unsigned: __builtin_umul_overflow, \ unsigned long: __builtin_umull_overflow, \ unsigned long long: __builtin_umulll_overflow, \ int: __builtin_smul_overflow, \ long: __builtin_smull_overflow, \ long long: __builtin_smulll_overflow \ )(T,U,V) #define uk_utils__add_overflow(a, b, res) uk_utils__warn_unused_result(__extension__({ \ typecheck((a), (b)); \ typecheck((b), *(res)); \ uk___utils__add_overflow_func((a), (b), (res)); \ })) #define uk_utils__sub_overflow(a, b, res) uk_utils__warn_unused_result(__extension__({ \ typecheck((a), (b)); \ typecheck((b), *(res)); \ uk___utils__sub_overflow_func((a), (b), (res)); \ })) #define uk_utils__mul_overflow(a, b, res) uk_utils__warn_unused_result(__extension__({ \ typecheck((a), (b)); \ typecheck((b), *(res)); \ uk___utils__mul_overflow_func((a), (b), (res)); \ })) #else #define uk_utils__add_overflow(a, b, res) 0 #define uk_utils__sub_overflow(a, b, res) 0 #define uk_utils__mul_overflow(a, b, res) 0 #endif /* __has_builtin(...) */ /* uk_utils__add3_overflow(a, b, c) -> (a + b + c) */ #define uk_utils__add3_overflow(a, b, c, res) uk_utils__warn_unused_result(__extension__({ \ __typeof__(*(res)) _tmp; \ bool _s, _t; \ _s = uk_utils__add_overflow((a), (b), &_tmp); \ _t = uk_utils__add_overflow((c), _tmp, (res)); \ _s | _t; \ })) /* uk_utils__add_and_mul_overflow(a, b, x) -> (a + b)*x */ #define uk_utils__add_and_mul_overflow(a, b, x, res) uk_utils__warn_unused_result(__extension__({ \ __typeof__(*(res)) _tmp; \ bool _s, _t; \ _s = uk_utils__add_overflow((a), (b), &_tmp); \ _t = uk_utils__mul_overflow((x), _tmp, (res)); \ _s | _t; \ })) /* uk_utils__mul_and_add_overflow(a, x, b) -> a*x + b */ #define uk_utils__mul_and_add_overflow(a, x, b, res) uk_utils__warn_unused_result(__extension__({ \ __typeof__(*(res)) _tmp; \ bool _s, _t; \ _s = uk_utils__mul_overflow((a), (x), &_tmp); \ _t = uk_utils__add_overflow((b), _tmp, (res)); \ _s | _t; \ })) #endif
2.171875
2
2024-11-18T22:28:20.159727+00:00
2020-12-18T09:34:34
e94a3682a21471de5715a5ff32d059d715248e4e
{ "blob_id": "e94a3682a21471de5715a5ff32d059d715248e4e", "branch_name": "refs/heads/main", "committer_date": "2020-12-18T09:34:34", "content_id": "1b7ce917d88ddd241984adb14be1c04cafb78300", "detected_licenses": [ "Apache-2.0" ], "directory_id": "2f943e125909f5f9e98737b86fd58b286ac93e51", "extension": "h", "filename": "cpu.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 321526240, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9560, "license": "Apache-2.0", "license_type": "permissive", "path": "/uart_ex2_loopback_udma/device/driverlib_cm/cpu.h", "provenance": "stackv2-0132.json.gz:74066", "repo_name": "NULL981/28388_cm_uart_udma", "revision_date": "2020-12-18T09:34:34", "revision_id": "16967d0c1aec724668945076d7b490af278f6d21", "snapshot_id": "1faf09df62f22534b1444ca889d9189592d25bbf", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/NULL981/28388_cm_uart_udma/16967d0c1aec724668945076d7b490af278f6d21/uart_ex2_loopback_udma/device/driverlib_cm/cpu.h", "visit_date": "2023-02-01T11:21:30.833682" }
stackv2
//########################################################################### // // FILE: cpu.h // // TITLE: Instruction wrappers for special CPU instructions needed by the // drivers. // //########################################################################### // $TI Release: F2838x Support Library v3.03.00.00 $ // $Release Date: Sun Oct 4 16:00:36 IST 2020 $ // $Copyright: // Copyright (C) 2020 Texas Instruments Incorporated - http://www.ti.com/ // // 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 Texas Instruments Incorporated nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // $ //########################################################################### #ifndef CPU_H #define CPU_H //***************************************************************************** // // If building with a C++ compiler, make all of the definitions in this header // have a C binding. // //***************************************************************************** #ifdef __cplusplus extern "C" { #endif //***************************************************************************** // //! \addtogroup cpu_api CPU //! \brief The module is used for configuring Cortex-M core registers //! @{ // //***************************************************************************** #include <stdint.h> // // Define for no operation // #ifndef NOP #define NOP __asm(" NOP") #endif //***************************************************************************** // //! Returns the state of FAULTMASK register on entry and disable all //! interrupts except NMI. //! //! This function is wrapper function for the CPSID instruction. It returns //! the state of FAULTMASK on entry and disable all interrupts except NMI. //! //! \return Returns the state of FAULTMASK register. // //***************************************************************************** static inline uint32_t CPU_setFAULTMASK(void) { // // Disable interrupts and return previous FAULTMASK. // return(_disable_interrupts()); } //***************************************************************************** // //! Returns the state of FAULTMASK register //! //! This function is wrapper function for returning the state of FAULTMASK //! register(indicating whether interrupts except NMI are enabled or disabled). //! //! \return Returns the state of FAULTMASK register. // //***************************************************************************** static inline uint32_t CPU_getFAULTMASK(void) { // // Read FAULTMASK register. // __asm(" mrs r0, FAULTMASK\n" " bx lr\n"); // // The following keeps the compiler happy, because it wants to see a // return value from this function. It will generate code to return // a zero. However, the real return is the "bx lr" above, so the // return(0) is never executed and the function returns with the value // you expect in R0. // return(0U); } //***************************************************************************** // //! Returns the state of FAULTMASK register and enable the interrupts //! //! This function is wrapper function for returning the state of FAULTMASK //! register and enabling the interrupts. //! //! \return Returns the state of FAULTMASK register. // //***************************************************************************** static inline uint32_t CPU_clearFAULTMASK(void) { // // Enable interrupts and return previous FAULTMASK status. // return(_enable_interrupts()); } //***************************************************************************** // //! Returns the state of PRIMASK register on entry and disable interrupts //! //! This function is wrapper function for the CPSID instruction. It returns //! the state of PRIMASK on entry and disable interrupts. //! //! \return Returns the state of PRIMASK register. // //***************************************************************************** static inline uint32_t CPU_setPRIMASK(void) { // // Read PRIMASK and Disable interrupts. // return(_disable_IRQ()); } //***************************************************************************** // //! Returns the state of PRIMASK register //! //! This function is wrapper function for returning the state of PRIMASK //! register(indicating whether interrupts are enabled or disabled). //! //! \return Returns the state of PRIMASK register. // //***************************************************************************** static inline uint32_t CPU_getPRIMASK(void) { // // Return PRIMASK register status. // return(__get_PRIMASK()); } //***************************************************************************** // //! Returns the state of PRIMASK register and enable the interrupts //! //! This function is wrapper function for returning the state of PRIMASK //! register and enabling the interrupts. //! //! \return Returns the state of PRIMASK register. // //***************************************************************************** static inline uint32_t CPU_clearPRIMASK(void) { // // Enable interrupts and return previous PRIMASK setting. // return(_enable_IRQ()); } //***************************************************************************** // //! Wrapper function for the WFI instruction //! //! This function is wrapper function for the WFI instruction. //! //! \return None // //***************************************************************************** static inline void CPU_wfi(void) { // // Wait for the next interrupt. // __asm(" wfi\n"); } //***************************************************************************** // //! Writes the BASEPRI register //! //! \param basePriority is the value to be set //! //! This function is wrapper function for writing the BASEPRI register. MSB //! 3-bits are enabled for setting the priority and non-implemented low-order //! bits read as zero and ignore writes. To set the base priority of 0x2U, //! the param \e basePriority to be passed should be 0x20U. //! //! \return None. // //***************************************************************************** static inline void CPU_setBASEPRI(uint32_t basePriority) { // // Set the BASEPRI register // _set_interrupt_priority(basePriority); } //***************************************************************************** // //! Returns the state of BASEPRI register //! //! This function is wrapper function for reading the BASEPRI register. //! //! \return Returns the state of BASEPRI register // //***************************************************************************** static inline uint32_t CPU_getBASEPRI(void) { // // Read BASEPRI register. // __asm(" mrs r0, BASEPRI\n" " bx lr\n"); // // The following keeps the compiler happy, because it wants to see a // return value from this function. It will generate code to return // a zero. However, the real return is the "bx lr" above, so the // return(0) is never executed and the function returns with the value // you expect in R0. // return(0U); } //***************************************************************************** // // Extern compiler intrinsic prototypes. See compiler User's Guide for details. // //***************************************************************************** extern uint32_t __get_PRIMASK(void); extern uint32_t _disable_interrupts(void); extern uint32_t _enable_interrupts(); extern uint32_t _disable_IRQ(); extern uint32_t _enable_IRQ(); extern uint32_t _set_interrupt_priority(uint32_t priority); //***************************************************************************** // // Close the Doxygen group. //! @} // //***************************************************************************** //***************************************************************************** // // Mark the end of the C bindings section for C++ compilers. // //***************************************************************************** #ifdef __cplusplus } #endif #endif // CPU_H
2.015625
2
2024-11-18T22:28:21.911051+00:00
2021-07-29T14:01:10
17065331e812e3d1a93ddbbc187f0d2d9e343a92
{ "blob_id": "17065331e812e3d1a93ddbbc187f0d2d9e343a92", "branch_name": "refs/heads/main", "committer_date": "2021-07-29T14:01:10", "content_id": "7e6c39c33c6d611a05b6745962bb33f29d655df6", "detected_licenses": [ "Apache-2.0" ], "directory_id": "210d9b5826438f9bddd64ab6c3d141c1b30f0fec", "extension": "h", "filename": "pelz_socket.h", "fork_events_count": 0, "gha_created_at": "2021-05-07T15:31:17", "gha_event_created_at": "2021-05-07T15:31:18", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 365277852, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2927, "license": "Apache-2.0", "license_type": "permissive", "path": "/include/pelz_socket.h", "provenance": "stackv2-0132.json.gz:74455", "repo_name": "PeterHamilton/pelz", "revision_date": "2021-07-29T14:01:10", "revision_id": "76cfb9eafaf87ace91df299b0ea1d8720f477724", "snapshot_id": "d352082bc0f8aa0a4a2ea605a498aedf0dfb6083", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PeterHamilton/pelz/76cfb9eafaf87ace91df299b0ea1d8720f477724/include/pelz_socket.h", "visit_date": "2023-06-28T17:31:28.514974" }
stackv2
/** * @file pelz_key_socket.h * @brief Provides global constants and macros for Pelz Key's socket feature */ #ifndef PELZ_KEY_SOCKET_H #define PELZ_KEY_SOCKET_H /** * The C libraries needed for Pelz Key socket */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <pelz_request_handler.h> /** * <pre> * Initialization of the socket used by the pelz key service. * -Configure Local Address * -Create socket * -Bind socket to local address * <pre> * * @param[in] max_request Value for maxim request received at once * @param[out] socket_id Integer representation of listening socket * * @return 0 on success, 1 on error * */ int pelz_key_socket_init(int max_request, int *socket_listen_id); /** * <pre> * Accepting connection from client for the socket used by the pelz key service. * -Wait for Connection * -Accepts Connection * <pre> * * @param[in] socket_listen_id Integer representation of listening socket * @param[out] socket_id Integer representation of socket * * @return 0 on success, 1 on error * */ int pelz_key_socket_accept(int socket_listen_id, int *socket_id); /** * <pre> * Receiving request for pelz key service from database. * -Receiving Request * -Reading Request * -Returning Request * <pre> * * @param[in] socket_id Integer representation of socket * @param[out] message.chars The request for the pelz key service received from the database, should be passed to pelz key service for processing * @param[out] message.len The length of the request sent * * @return 0 on success, 1 on error * */ int pelz_key_socket_recv(int socket_id, charbuf * message); /** * <pre> * Sending processed request as response to database * -Start with processed message * -Send response * <pre> * * @param[in] socket_id Integer representation of socket * @param[in] response.chars The processed request to be sent back to the database * @param[in] response.len The length of the processed request * * @return 0 on success, 1 on error * */ int pelz_key_socket_send(int socket_id, charbuf response); /** * <pre> * Check for client connection. * <pre> * * @param[in] socket_id Integer representation of socket * * @return 0 on socket open, 1 on socket close * */ int pelz_key_socket_check(int socket_id); /** * <pre> * Closing client connection. * -Close Connection * <pre> * * @param[in] socket_id Integer representation of socket * * @return 0 on success, 1 on error * */ int pelz_key_socket_close(int socket_id); /** * <pre> * Closing listening socket for the pelz key service. * -Close Socket * <pre> * * @param[in] socket_listen_id Integer representation of listening socket * * @return 0 on success, 1 on error * */ int pelz_key_socket_teardown(int *socket_listen_id); #endif
2.21875
2
2024-11-18T22:28:22.049727+00:00
2020-03-19T11:52:38
536f28ccd5f8ac57d2cda20ad119a4c219029a43
{ "blob_id": "536f28ccd5f8ac57d2cda20ad119a4c219029a43", "branch_name": "refs/heads/master", "committer_date": "2020-03-19T11:52:38", "content_id": "1b650ba04af6e1356c2e2a93cda0fcf8955f248d", "detected_licenses": [ "MIT" ], "directory_id": "90aec2d50db24f96abde86a4872ff922f3cb9280", "extension": "c", "filename": "Radix_Sort.c", "fork_events_count": 1, "gha_created_at": "2017-11-20T06:04:51", "gha_event_created_at": "2020-03-19T11:52:39", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 111368592, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2056, "license": "MIT", "license_type": "permissive", "path": "/Radix_Sort.c", "provenance": "stackv2-0132.json.gz:74585", "repo_name": "LasVegasCoder/Data-Science-Sort-Algorithms", "revision_date": "2020-03-19T11:52:38", "revision_id": "e490c4a13e84ff5533eb1c08cb0a7a70526bf2eb", "snapshot_id": "3b5d4aa36cf3e8938d8f7365b19def3ca3f99744", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/LasVegasCoder/Data-Science-Sort-Algorithms/e490c4a13e84ff5533eb1c08cb0a7a70526bf2eb/Radix_Sort.c", "visit_date": "2022-04-13T00:41:00.891892" }
stackv2
void radix_sort(unsigned *begin, unsigned *end) { unsigned *begin1 = new unsigned[end - begin]; unsigned *end1 = begin1 + (end - begin); for (unsigned shift = 0; shift < 32; shift += 8) { size_t count[0x100] = {}; for (unsigned *p = begin; p != end; p++) count[(*p >> shift) & 0xFF]++; unsigned *bucket[0x100], *q = begin1; for (int i = 0; i < 0x100; q += count[i++]) bucket[i] = q; for (unsigned *p = begin; p != end; p++) *bucket[(*p >> shift) & 0xFF]++ = *p; std::swap(begin, begin1); std::swap(end, end1); } delete[] begin1; } void _radix_sort_lsb(unsigned *begin, unsigned *end, unsigned *begin1, unsigned maxshift) { unsigned *end1 = begin1 + (end - begin); for (unsigned shift = 0; shift <= maxshift; shift += 8) { size_t count[0x100] = {}; for (unsigned *p = begin; p != end; p++) count[(*p >> shift) & 0xFF]++; unsigned *bucket[0x100], *q = begin1; for (int i = 0; i < 0x100; q += count[i++]) bucket[i] = q; for (unsigned *p = begin; p != end; p++) *bucket[(*p >> shift) & 0xFF]++ = *p; std::swap(begin, begin1); std::swap(end, end1); } } void _radix_sort_msb(unsigned *begin, unsigned *end, unsigned *begin1, unsigned shift) { unsigned *end1 = begin1 + (end - begin); size_t count[0x100] = {}; for (unsigned *p = begin; p != end; p++) count[(*p >> shift) & 0xFF]++; unsigned *bucket[0x100], *obucket[0x100], *q = begin1; for (int i = 0; i < 0x100; q += count[i++]) obucket[i] = bucket[i] = q; for (unsigned *p = begin; p != end; p++) *bucket[(*p >> shift) & 0xFF]++ = *p; for (int i = 0; i < 0x100; ++i) _radix_sort_lsb(obucket[i], bucket[i], begin + (obucket[i] - begin1), shift - 8); } void radix_sort(unsigned *begin, unsigned *end) { unsigned *begin1 = new unsigned[end - begin]; _radix_sort_msb(begin, end, begin1, 24); delete[] begin1; }
2.78125
3
2024-11-18T22:28:22.435746+00:00
2020-10-29T21:53:02
ebc225100d513cac84f6dbe2cc9490ca89cd14bf
{ "blob_id": "ebc225100d513cac84f6dbe2cc9490ca89cd14bf", "branch_name": "refs/heads/master", "committer_date": "2020-10-29T21:53:02", "content_id": "3205d427037e89ff3fb9dfa0f32a29dbe0942068", "detected_licenses": [ "MIT" ], "directory_id": "3e950bd3fac41260123662aee1f8a2648ebd2b2e", "extension": "c", "filename": "Amardilha.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 300467109, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1783, "license": "MIT", "license_type": "permissive", "path": "/Exercicios[C]/JOGOS/Amardilha.c", "provenance": "stackv2-0132.json.gz:74973", "repo_name": "DamaLeaN/ProgramasEmC", "revision_date": "2020-10-29T21:53:02", "revision_id": "dcf4f4c7656a6b156f74487130845d2233b6a4db", "snapshot_id": "3da2493afbad558efe96a9eae25d9665ac5fca27", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DamaLeaN/ProgramasEmC/dcf4f4c7656a6b156f74487130845d2233b6a4db/Exercicios[C]/JOGOS/Amardilha.c", "visit_date": "2023-01-01T20:54:26.170858" }
stackv2
#include <stdio.h> #include <locale.h> #include <time.h> // time #include <stdlib.h> // rand srand int main() { setlocale (LC_ALL,"Portuguese"); int num, inferior, superior, vida = 6, tentativa=0; srand(time(NULL)); num = rand() % 101; // resto da divisão por 101 = 0 até 100 //printf ("%d",num); //para vender o JOGO, devemos apagar essa linha printf ("\n\nJá pensei no número. Agora é sua vez de adivinhar um número de 1 a 100"); while (vida > 0) { printf ("\n\nDigite o limite inferior: "); scanf ("%d",&inferior); printf ("\n\nDigite o limite superior: "); scanf ("%d",&superior); if(inferior > superior){ if((num == inferior)&&(num==superior)){ tentativa++; printf("Você levou %d tentativas para acertar",tentativa); } else if ((num >=superior)&&(num <=inferior)) { tentativa++; printf ("\n\nMeu número está entre os seus"); } else{ tentativa++; printf ("Meu número não está entre os seus");} vida--; //vida = vida - 1; if (vida ==0) printf ("\n\nGAME OVER"); } else{ if((num == inferior)&&(num == superior)){ tentativa++; printf("\n\nVocê levou %d tentativas para acertar",tentativa); vida = -8; } else if ((num >=inferior)&&(num <=superior)) { tentativa++; printf ("Meu número está entre os seus"); } else { tentativa++; printf ("Meu número não está entre os seus"); } vida--; //vida = vida - 1; if (vida ==0) printf ("\n\nGAME OVER"); } } getch(); return 0; }
3.0625
3
2024-11-18T22:28:22.696666+00:00
2017-05-17T15:59:40
0c05966f390fa8607789e3a4d1b69aafcdd8b52e
{ "blob_id": "0c05966f390fa8607789e3a4d1b69aafcdd8b52e", "branch_name": "refs/heads/master", "committer_date": "2017-05-17T15:59:40", "content_id": "c819ed1a668311cd40f34a345ae2fb7bbc5fb63f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "14c6f371416bd9dd0e27de5e4e0b7160d13b1eb0", "extension": "c", "filename": "check_test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 39553812, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3563, "license": "Apache-2.0", "license_type": "permissive", "path": "/tests/check_test.c", "provenance": "stackv2-0132.json.gz:75362", "repo_name": "zouzias/REK-C", "revision_date": "2017-05-17T15:59:40", "revision_id": "9df14edfb932e48c3a6eac405c4c9bd08656fe74", "snapshot_id": "e201a695ff9bd5fb2388cd81ea7ce3d141579d23", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/zouzias/REK-C/9df14edfb932e48c3a6eac405c4c9bd08656fe74/tests/check_test.c", "visit_date": "2021-05-16T05:25:21.685744" }
stackv2
#include <stdlib.h> #include "../matrix/sparseMatrix.h" #include "../matrix/matrix.h" #include "../utils/utils.h" #include "../algorithms/REK/REKBLAS.h" #include<check.h> double test_dense_gaussian_system(int m, int n, double TOL); double test_sparse_gaussian_system(int m, int n, double sparsity, double TOL); START_TEST (test_name) { /* unit test code */ ck_assert_msg(0 != 1); } END_TEST START_TEST (test_dense_gaussian) { ck_assert_msg( test_dense_gaussian_system(1000, 100, 10e-7) < 10e-4 ); // Test if accuracy less than 5 digits } END_TEST START_TEST (test_sparse_gaussian) { ck_assert_msg( test_sparse_gaussian_system(1000, 100, 0.2, 10e-7) < 10e-4 ); // Test if accuracy less than 5 digits } END_TEST double test_dense_gaussian_system(int m, int n, double TOL){ printf("--->Test REK for dense (%dx%d)-matrix.\n", m, n); /* initialize random seed */ srand(time(NULL)); // Allocating space for unknown vector x, right size vector b, and solution vector xls, for Ax = b double *xls = gaussianVector(n); double* b = (double*) malloc( m * sizeof(double)); double* x = (double*) malloc( n * sizeof(double)); memset (x, 0, n * sizeof (double)); // LS Error double error = 0.0; //********************************************** // Test the dense version of REK * //********************************************** MAT *A = fillRandomEntries(m, n); memset (b, 0, m * sizeof (double)); memset (x, 0, n * sizeof (double)); myDGEMV(A,xls, b); denseREKBLAS(A, x, b, TOL); error = lsError(A, x, b); freeMAT(A); printf("Dense REK: LS error is : %e\n", error); free(xls); free(x); free(b); return error; } double test_sparse_gaussian_system(int m, int n, double sparsity, double TOL){ printf("--->Test REK for sparse (%dx%d)-matrix with sparsity %f.\n", m, n, sparsity); /* initialize random seed */ srand(time(NULL)); // Allocating space for unknown vector x, right size vector b, and solution vector xls, for Ax = b double *xls = gaussianVector(n); double* b = (double*) malloc( m * sizeof(double)); double* x = (double*) malloc( n * sizeof(double)); memset (x, 0, n * sizeof (double)); memset (b, 0, m * sizeof (double)); // LS Error double error = 0.0; // Input matrix is sparse (REK_sparse) SMAT *As = fillSparseMat(m, n, sparsity); // Set b = As * x myDGEMVSparse(As,xls, b); //********************************************** // Test the sparse version of REK * //********************************************** sparseREK (As, x, b, TOL); error = lsErrorSparse(As, x, b); freeSMAT(As); printf("Sparse REK: LS error is : %e\n", error); free(xls); free(x); free(b); return error; } Suite * unit_test_suite(void) { Suite *s; TCase *tc_core; s = suite_create("Unit_tests_temp"); /* Core test case */ tc_core = tcase_create("Core"); tcase_add_test(tc_core, test_name); tcase_add_test(tc_core, test_dense_gaussian); tcase_add_test(tc_core, test_sparse_gaussian); suite_add_tcase(s, tc_core); return s; } int main(void) { int number_failed; Suite *s; SRunner *sr; s = unit_test_suite(); sr = srunner_create(s); srunner_run_all(sr, CK_NORMAL); number_failed = srunner_ntests_failed(sr); srunner_free(sr); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
2.375
2
2024-11-18T22:28:23.261307+00:00
2019-03-14T14:23:44
9e0aecd6827a5fc1231e2fc71fe9794f5e97840e
{ "blob_id": "9e0aecd6827a5fc1231e2fc71fe9794f5e97840e", "branch_name": "refs/heads/master", "committer_date": "2019-03-14T14:23:44", "content_id": "9f0ce1cba927d0add7b3014933f15a7c2ebefc7d", "detected_licenses": [ "MIT" ], "directory_id": "d695eccd894af8aef48ce4003121987d5a9e95e8", "extension": "c", "filename": "ex02-01.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 167369394, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 646, "license": "MIT", "license_type": "permissive", "path": "/chap-02/01.ranges/ex02-01.c", "provenance": "stackv2-0132.json.gz:76011", "repo_name": "felipeAraujo/c-examples", "revision_date": "2019-03-14T14:23:44", "revision_id": "68376b30b1a33d08103190fcaf6ca72adb3431a3", "snapshot_id": "7114a38f50cd468965a168653d3ad214470dcd7e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/felipeAraujo/c-examples/68376b30b1a33d08103190fcaf6ca72adb3431a3/chap-02/01.ranges/ex02-01.c", "visit_date": "2020-04-18T07:42:13.870421" }
stackv2
#include<stdio.h> #include<limits.h> int main() { printf("int limits: %d <=> %d\n", INT_MAX, INT_MIN); printf("char limits: %d <=> %d\n", CHAR_MAX, CHAR_MIN); printf("long limits: %ld <=> %ld\n", LONG_MAX, LONG_MIN); printf("signed char limits: %d <=> %d\n", SCHAR_MAX, SCHAR_MIN); printf("short limits: %d <=> %d\n", SHRT_MAX, SHRT_MIN); printf("signed char limits: %d <=> %d\n", SCHAR_MAX, SCHAR_MIN); printf("unsigned char max: %d\n", UCHAR_MAX); printf("unsigned int max: %u\n", UINT_MAX); printf("unsigned long max %lu\n", ULONG_MAX); printf("unsigned short max %d\n", USHRT_MAX); return 0; }
2.71875
3
2024-11-18T22:28:24.138914+00:00
2020-05-29T12:50:46
f2ef7be48c05d5a939f27ad702bff104f2e60b07
{ "blob_id": "f2ef7be48c05d5a939f27ad702bff104f2e60b07", "branch_name": "refs/heads/master", "committer_date": "2020-05-29T12:50:46", "content_id": "81f716bfc48c71a9c982cd92c40b37e421385c97", "detected_licenses": [ "MIT" ], "directory_id": "9ce4292954000fd66bcdbd0797a280c306308d08", "extension": "c", "filename": "menu1.c", "fork_events_count": 0, "gha_created_at": "2018-06-15T01:29:31", "gha_event_created_at": "2020-10-13T08:56:12", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 137426553, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1456, "license": "MIT", "license_type": "permissive", "path": "/books/BLP/ch16/menu1.c", "provenance": "stackv2-0132.json.gz:76140", "repo_name": "JiniousChoi/encyclopedia-in-code", "revision_date": "2020-05-29T12:50:46", "revision_id": "77bc551a03a2a3e3808e50016ece14adb5cfbd96", "snapshot_id": "0c786f2405bfc1d33291715d9574cae625ae45be", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/JiniousChoi/encyclopedia-in-code/77bc551a03a2a3e3808e50016ece14adb5cfbd96/books/BLP/ch16/menu1.c", "visit_date": "2021-06-27T07:50:10.789732" }
stackv2
#include <gnome.h> void closeApp ( GtkWidget *window, gpointer data) { gtk_main_quit(); } void item_clicked(GtkWidget *widget, gpointer user_data) { printf("Item Clicked!\n"); } static GnomeUIInfo submenu[] = { {GNOME_APP_UI_ITEM, "SubMenu", "SubMenu Hint", GTK_SIGNAL_FUNC(item_clicked), NULL, NULL, 0, NULL, 0, 0, NULL}, {GNOME_APP_UI_ENDOFINFO, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 0, NULL} }; static GnomeUIInfo menu[] = { {GNOME_APP_UI_ITEM, "Menu Item 1", "Menu Hint", NULL, NULL, NULL, 0, NULL, 0, 0, NULL}, {GNOME_APP_UI_SUBTREE, "Menu Item 2", "Menu Hint", submenu, NULL, NULL, 0, NULL, 0, 0, NULL}, {GNOME_APP_UI_ENDOFINFO, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 0, NULL} }; static GnomeUIInfo menubar[] = { {GNOME_APP_UI_SUBTREE, "Toplevel Item", NULL, menu, NULL, NULL, 0, NULL, 0, 0, NULL}, {GNOME_APP_UI_ENDOFINFO, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 0, NULL} }; int main (int argc, char *argv[]) { GtkWidget *app; gnome_program_init ("gnome1", "0.1", LIBGNOMEUI_MODULE, argc, argv, GNOME_PARAM_NONE); app = gnome_app_new("gnome1", "Menus, menus, menus"); gtk_window_set_default_size ( GTK_WINDOW(app), 300, 200); g_signal_connect ( GTK_OBJECT (app), "destroy", GTK_SIGNAL_FUNC ( closeApp), NULL); gnome_app_create_menus ( GNOME_APP(app), menubar); gtk_widget_show(app); gtk_main(); return 0; }
2.21875
2
2024-11-18T22:28:24.234764+00:00
2019-08-29T20:39:24
877e50246cba1636894e86f10aa0bf1a9e92f8bf
{ "blob_id": "877e50246cba1636894e86f10aa0bf1a9e92f8bf", "branch_name": "refs/heads/master", "committer_date": "2019-08-29T20:39:24", "content_id": "4c5fa8e13f2ddc805fbe57ecacb2bfade3c72e79", "detected_licenses": [ "MIT" ], "directory_id": "40924b41cac2670df4bf56009e04c8c8be24f9fe", "extension": "c", "filename": "signald.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 200942025, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1866, "license": "MIT", "license_type": "permissive", "path": "/daemon/signald.c", "provenance": "stackv2-0132.json.gz:76270", "repo_name": "GabMill/alsp", "revision_date": "2019-08-29T20:39:24", "revision_id": "f276e90ae10a2788ad64ceecb6faa6d989b081e5", "snapshot_id": "56945cfe4054bb4f6a2b016ab4cd3b4aa334c448", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GabMill/alsp/f276e90ae10a2788ad64ceecb6faa6d989b081e5/daemon/signald.c", "visit_date": "2020-06-30T20:18:12.265035" }
stackv2
//signal daemon - Gabriel Miller //Starts a daemon that logs signals as they're received #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <sys/resource.h> int daemonize() { int i, fd0, fd1, fd2, log_fd; pid_t pid; struct rlimit rl; struct sigaction sa; umask(0); log_fd = open("/home/gabrielm/signald.log", O_RDWR); if(getrlimit(RLIMIT_NOFILE, &rl) < 0) { printf("Unable to get file limit\n"); abort(); } if((pid = fork()) < 0) { printf("Fork error\n"); abort(); } else if(pid != 0) exit(0); setsid(); sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if(sigaction(SIGHUP, &sa, NULL) < 0) { printf("Cannot ignore SIGHUP\n"); abort(); } if((pid = fork()) < 0) { printf("Fork error (second fork)\n"); abort(); } else if(pid != 0) exit(0); if(chdir("/") < 0) { printf("Chdir error\n"); abort(); } if(rl.rlim_max == RLIM_INFINITY) rl.rlim_max = 1024; for(i = 0; i < rl.rlim_max; i++) close(i); fd0 = open("/dev/null", O_RDWR); fd1 = dup(0); fd2 = dup(0); dprintf(log_fd, "made it this far at least\n"); return log_fd; } int main(int argc, char **argv) { struct sigaction sa; int wait, signo, log_fd; sigset_t mask; log_fd = daemonize(); sigfillset(&mask); for(;;) { wait = sigwait(&mask, &signo); if(wait != 0) exit(0); switch(signo) { case SIGHUP: dprintf(log_fd, "Received SIGHUP\n"); case SIGTERM: dprintf(log_fd, "Received SIGTERM\n"); case SIGUSR1: dprintf(log_fd, "Received SIGUSR1\n"); default: dprintf(log_fd, "Received unsupported signal\n"); break; } } close(log_fd); exit(0); }
2.859375
3
2024-11-18T22:28:24.302485+00:00
2015-03-23T04:32:49
521d5fabdc0838c8ebb3f2a012250f824803c2f2
{ "blob_id": "521d5fabdc0838c8ebb3f2a012250f824803c2f2", "branch_name": "refs/heads/master", "committer_date": "2015-03-23T04:32:49", "content_id": "39540caac30e74211c9ca1af0a341264da54ab7c", "detected_licenses": [ "MIT" ], "directory_id": "59ed19612271c19ae6d26cb81378c47e3d41fef6", "extension": "c", "filename": "token.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 30949766, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 38104, "license": "MIT", "license_type": "permissive", "path": "/src/token.c", "provenance": "stackv2-0132.json.gz:76399", "repo_name": "caiosm1005/bcce", "revision_date": "2015-03-23T04:32:49", "revision_id": "3de89b607fb32f2a5860b2efe7269acc351fb4bd", "snapshot_id": "b259460e7ce761cda3c526f937763793a7e72cb4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/caiosm1005/bcce/3de89b607fb32f2a5860b2efe7269acc351fb4bd/src/token.c", "visit_date": "2020-12-25T15:40:25.821726" }
stackv2
#include <stdio.h> #include <string.h> #include <stdarg.h> #include <ctype.h> #include "task.h" struct source_request { const char* path; struct source* source; bool load_once; bool err_open; bool err_loading; bool err_loaded_before; }; static void load_source( struct task* task, struct source_request* ); static void init_source_request( struct source_request*, const char* ); static enum tk peek( struct task*, int ); static void read_source( struct task*, struct token* ); static void escape_ch( struct task*, char*, char**, bool ); static char read_ch( struct task* ); static void diag_acc( struct task*, int, va_list* ); static void make_pos( struct task*, struct pos*, const char**, int*, int* ); void t_init_fields_token( struct task* task ) { task->tk = TK_END; task->tk_text = NULL; task->tk_length = 0; task->source = NULL; task->source_main = NULL; task->library = NULL; task->library_main = NULL; } void t_load_main_source( struct task* task ) { struct source_request request; init_source_request( &request, task->options->source_file ); load_source( task, &request ); if ( request.source ) { task->source_main = request.source; task->library_main->file_pos.id = request.source->id; } else { t_diag( task, DIAG_ERR, "failed to load source file: %s", task->options->source_file ); t_bail( task ); } } struct source* t_load_included_source( struct task* task ) { struct source_request request; init_source_request( &request, task->tk_text ); load_source( task, &request ); if ( ! request.source ) { if ( request.err_loading ) { t_diag( task, DIAG_POS_ERR, &task->tk_pos, "file already being loaded" ); t_bail( task ); } else { t_diag( task, DIAG_POS_ERR, &task->tk_pos, "failed to load file: %s", task->tk_text ); t_bail( task ); } } return request.source; } void init_source_request( struct source_request* request, const char* path ) { request->path = path; request->source = NULL; request->load_once = false; request->err_open = false; request->err_loaded_before = false; request->err_loading = false; } void load_source( struct task* task, struct source_request* request ) { // Try path directly. struct str path; str_init( &path ); str_append( &path, request->path ); struct fileid fileid; if ( c_read_fileid( &fileid, path.value ) ) { goto load_file; } // Try directory of current file. if ( task->source ) { str_copy( &path, task->source->full_path.value, task->source->full_path.length ); c_extract_dirname( &path ); str_append( &path, "/" ); str_append( &path, request->path ); if ( c_read_fileid( &fileid, path.value ) ) { goto load_file; } } // Try user-specified directories. list_iter_t i; list_iter_init( &i, &task->options->includes ); while ( ! list_end( &i ) ) { char* include = list_data( &i ); str_clear( &path ); str_append( &path, include ); str_append( &path, "/" ); str_append( &path, request->path ); if ( c_read_fileid( &fileid, path.value ) ) { goto load_file; } list_next( &i ); } // Error: request->err_open = true; goto finish; load_file: // See if the file should be loaded once. list_iter_init( &i, &task->loaded_sources ); while ( ! list_end( &i ) ) { struct source* source = list_data( &i ); if ( c_same_fileid( &fileid, &source->fileid ) ) { if ( source->load_once ) { request->err_loaded_before = true; goto finish; } else { break; } } list_next( &i ); } // The file should not currently be processing. struct source* source = task->source; while ( source ) { if ( c_same_fileid( &source->fileid, &fileid ) ) { if ( request->load_once ) { source->load_once = true; request->err_loaded_before = true; } else { request->err_loading = true; } goto finish; } source = source->prev; } // Load file. FILE* fh = fopen( path.value, "rb" ); if ( ! fh ) { request->err_open = true; goto finish; } fseek( fh, 0, SEEK_END ); size_t size = ftell( fh ); rewind( fh ); char* save = mem_alloc( size + 1 + 1 ); char* text = save + 1; size_t num_read = fread( text, sizeof( char ), size, fh ); fclose( fh ); if ( num_read != size ) { // For now, a read-error will be the same as an open-error. request->err_open = true; goto finish; } text[ size ] = 0; // Create source. source = mem_alloc( sizeof( *source ) ); source->text = text; source->left = text; source->save = save; source->save[ 0 ] = 0; source->prev = task->source; source->fileid = fileid; str_init( &source->path ); str_append( &source->path, request->path ); str_init( &source->full_path ); c_read_full_path( path.value, &source->full_path ); source->line = 1; source->column = 0; source->id = list_size( &task->loaded_sources ) + 1; source->active_id = source->id; source->find_dirc = true; source->load_once = request->load_once; source->imported = false; source->ch = ' '; list_append( &task->loaded_sources, source ); task->source = source; task->tk = TK_END; request->source = source; finish: str_deinit( &path ); } void t_read_tk( struct task* task ) { struct token* token = NULL; if ( task->tokens.peeked ) { // When dequeuing, shift the queue elements. For now, this will suffice. // In the future, maybe use a circular buffer. int i = 0; while ( i < task->tokens.peeked ) { task->tokens.buffer[ i ] = task->tokens.buffer[ i + 1 ]; ++i; } token = &task->tokens.buffer[ 0 ]; --task->tokens.peeked; } else { token = &task->tokens.buffer[ 0 ]; read_source( task, token ); if ( token->type == TK_END ) { bool imported = task->source->imported; if ( task->source->prev ) { task->source = task->source->prev; if ( ! imported ) { t_read_tk( task ); return; } } } } task->tk = token->type; task->tk_text = token->text; task->tk_pos = token->pos; task->tk_length = token->length; } enum tk t_peek( struct task* task ) { return peek( task, 1 ); } // NOTE: Make sure @pos is not more than ( TK_BUFFER_SIZE - 1 ). enum tk peek( struct task* task, int pos ) { int i = 0; while ( true ) { // Peeked tokens begin at position 1. struct token* token = &task->tokens.buffer[ i + 1 ]; if ( i == task->tokens.peeked ) { read_source( task, token ); ++task->tokens.peeked; } ++i; if ( i == pos ) { return token->type; } } } void read_source( struct task* task, struct token* token ) { char ch = task->source->ch; char* save = task->source->save; int line = 0; int column = 0; enum tk tk = TK_END; state_space: // ----------------------------------------------------------------------- while ( isspace( ch ) ) { ch = read_ch( task ); } state_token: // ----------------------------------------------------------------------- line = task->source->line; column = task->source->column; // Identifier: if ( isalpha( ch ) || ch == '_' ) { char* id = save; while ( isalnum( ch ) || ch == '_' ) { *save = ch; ++save; ch = read_ch( task ); } *save = 0; ++save; // NOTE: Reserved identifiers must be listed in ascending order. static const struct { const char* name; enum tk tk; } reserved[] = { { "bluereturn", TK_BLUE_RETURN }, { "bool", TK_BOOL }, { "break", TK_BREAK }, { "case", TK_CASE }, { "clientside", TK_CLIENTSIDE }, { "const", TK_CONST }, { "continue", TK_CONTINUE }, { "createtranslation", TK_PALTRANS }, { "death", TK_DEATH }, { "default", TK_DEFAULT }, { "disconnect", TK_DISCONNECT }, { "do", TK_DO }, { "else", TK_ELSE }, { "enter", TK_ENTER }, { "enum", TK_ENUM }, { "event", TK_EVENT }, { "false", TK_FALSE }, { "fixed", TK_FIXED }, { "for", TK_FOR }, { "function", TK_FUNCTION }, { "global", TK_GLOBAL }, { "goto", TK_GOTO }, { "if", TK_IF }, { "import", TK_IMPORT }, { "int", TK_INT }, { "lightning", TK_LIGHTNING }, { "net", TK_NET }, { "open", TK_OPEN }, { "pickup", TK_PICKUP }, { "redreturn", TK_RED_RETURN }, { "region", TK_REGION }, { "respawn", TK_RESPAWN }, { "restart", TK_RESTART }, { "return", TK_RETURN }, { "script", TK_SCRIPT }, { "special", TK_RESERVED }, { "static", TK_STATIC }, { "str", TK_STR }, { "struct", TK_STRUCT }, { "suspend", TK_SUSPEND }, { "switch", TK_SWITCH }, { "terminate", TK_TERMINATE }, { "true", TK_TRUE }, { "unloading", TK_UNLOADING }, { "until", TK_UNTIL }, { "upmost", TK_UPMOST }, { "void", TK_VOID }, { "while", TK_WHILE }, { "whitereturn", TK_WHITE_RETURN }, { "world", TK_WORLD }, // Terminator. { "\x7F", TK_END } }; #define RESERVED_MAX ARRAY_SIZE( reserved ) #define RESERVED_MID ( RESERVED_MAX / 2 ) int i = 0; if ( *id >= *reserved[ RESERVED_MID ].name ) { i = RESERVED_MID; } while ( true ) { // Identifier. if ( reserved[ i ].name[ 0 ] > *id ) { tk = TK_ID; break; } // Reserved identifier. else if ( strcmp( reserved[ i ].name, id ) == 0 ) { tk = reserved[ i ].tk; break; } else { ++i; } } goto state_finish; } else if ( ch == '0' ) { ch = read_ch( task ); // Binary. if ( ch == 'b' || ch == 'B' ) { goto binary_literal; } // Hexadecimal. else if ( ch == 'x' || ch == 'X' ) { goto hex_literal; } // Fixed-point number. else if ( ch == '.' ) { save[ 0 ] = '0'; save[ 1 ] = '.'; save += 2; ch = read_ch( task ); goto fraction; } // Octal. else { goto octal_literal; } } else if ( isdigit( ch ) ) { goto decimal_literal; } else if ( ch == '"' ) { ch = read_ch( task ); goto state_string; } else if ( ch == '\'' ) { ch = read_ch( task ); if ( ch == '\'' || ! ch ) { struct pos pos = { task->source->line, task->source->column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "missing character in character literal" ); t_bail( task ); } if ( ch == '\\' ) { ch = read_ch( task ); if ( ch == '\'' ) { save[ 0 ] = ch; save[ 1 ] = 0; save += 2; ch = read_ch( task ); } else { escape_ch( task, &ch, &save, false ); } } else { save[ 0 ] = ch; save[ 1 ] = 0; save += 2; ch = read_ch( task ); } if ( ch != '\'' ) { struct pos pos = { task->source->line, column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "multiple characters in character literal" ); t_bail( task ); } ch = read_ch( task ); tk = TK_LIT_CHAR; goto state_finish; } else if ( ch == '/' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_ASSIGN_DIV; ch = read_ch( task ); goto state_finish; } else if ( ch == '/' ) { goto state_comment; } else if ( ch == '*' ) { ch = read_ch( task ); goto state_comment_m; } else { tk = TK_SLASH; goto state_finish; } } else if ( ch == '=' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_EQ; ch = read_ch( task ); } else { tk = TK_ASSIGN; } goto state_finish; } else if ( ch == '+' ) { ch = read_ch( task ); if ( ch == '+' ) { tk = TK_INC; ch = read_ch( task ); } else if ( ch == '=' ) { tk = TK_ASSIGN_ADD; ch = read_ch( task ); } else { tk = TK_PLUS; } goto state_finish; } else if ( ch == '-' ) { ch = read_ch( task ); if ( ch == '-' ) { tk = TK_DEC; ch = read_ch( task ); } else if ( ch == '=' ) { tk = TK_ASSIGN_SUB; ch = read_ch( task ); } else { tk = TK_MINUS; } goto state_finish; } else if ( ch == '<' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_LTE; ch = read_ch( task ); } else if ( ch == '<' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_ASSIGN_SHIFT_L; ch = read_ch( task ); } else { tk = TK_SHIFT_L; } } else { tk = TK_LT; } goto state_finish; } else if ( ch == '>' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_GTE; ch = read_ch( task ); } else if ( ch == '>' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_ASSIGN_SHIFT_R; ch = read_ch( task ); goto state_finish; } else { tk = TK_SHIFT_R; goto state_finish; } } else { tk = TK_GT; } goto state_finish; } else if ( ch == '&' ) { ch = read_ch( task ); if ( ch == '&' ) { tk = TK_LOG_AND; ch = read_ch( task ); } else if ( ch == '=' ) { tk = TK_ASSIGN_BIT_AND; ch = read_ch( task ); } else { tk = TK_BIT_AND; } goto state_finish; } else if ( ch == '|' ) { ch = read_ch( task ); if ( ch == '|' ) { tk = TK_LOG_OR; ch = read_ch( task ); } else if ( ch == '=' ) { tk = TK_ASSIGN_BIT_OR; ch = read_ch( task ); } else { tk = TK_BIT_OR; } goto state_finish; } else if ( ch == '^' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_ASSIGN_BIT_XOR; ch = read_ch( task ); } else { tk = TK_BIT_XOR; } goto state_finish; } else if ( ch == '!' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_NEQ; ch = read_ch( task ); } else { tk = TK_LOG_NOT; } goto state_finish; } else if ( ch == '*' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_ASSIGN_MUL; ch = read_ch( task ); } else { tk = TK_STAR; } goto state_finish; } else if ( ch == '%' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_ASSIGN_MOD; ch = read_ch( task ); } else { tk = TK_MOD; } goto state_finish; } else if ( ch == ':' ) { ch = read_ch( task ); if ( ch == '=' ) { tk = TK_ASSIGN_COLON; ch = read_ch( task ); } else if ( ch == ':' ) { tk = TK_COLON_2; ch = read_ch( task ); } else { tk = TK_COLON; } goto state_finish; } else if ( ch == '\\' ) { struct pos pos = { task->source->line, column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "`\\` not followed with newline character" ); t_bail( task ); } // End. else if ( ! ch ) { tk = TK_END; goto state_finish; } else { // Single character tokens. static const int singles[] = { ';', TK_SEMICOLON, ',', TK_COMMA, '(', TK_PAREN_L, ')', TK_PAREN_R, '{', TK_BRACE_L, '}', TK_BRACE_R, '[', TK_BRACKET_L, ']', TK_BRACKET_R, '~', TK_BIT_NOT, '.', TK_DOT, '#', TK_HASH, 0 }; int i = 0; while ( true ) { if ( singles[ i ] == ch ) { tk = singles[ i + 1 ]; ch = read_ch( task ); goto state_finish; } else if ( ! singles[ i ] ) { struct pos pos = { task->source->line, column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "invalid character" ); t_bail( task ); } else { i += 2; } } } binary_literal: // ----------------------------------------------------------------------- ch = read_ch( task ); while ( true ) { if ( ch == '0' || ch == '1' ) { *save = ch; ++save; ch = read_ch( task ); } // Underscores can be used to improve readability of a numeric literal // by grouping digits, and are ignored. else if ( ch == '_' ) { ch = read_ch( task ); } else if ( isalnum( ch ) ) { struct pos pos = { task->source->line, task->source->column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "invalid digit in binary literal" ); t_bail( task ); } else if ( save == task->source->save ) { struct pos pos = { task->source->line, column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "no digits found in binary literal" ); t_bail( task ); } else { *save = 0; ++save; tk = TK_LIT_BINARY; goto state_finish; } } hex_literal: // ----------------------------------------------------------------------- ch = read_ch( task ); while ( true ) { if ( isxdigit( ch ) ) { *save = ch; ++save; ch = read_ch( task ); } else if ( ch == '_' ) { ch = read_ch( task ); } else if ( isalnum( ch ) ) { struct pos pos = { task->source->line, task->source->column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "invalid digit in hexadecimal literal" ); t_bail( task ); } else if ( save == task->source->save ) { struct pos pos = { task->source->line, column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "no digits found in hexadecimal literal" ); t_bail( task ); } else { *save = 0; ++save; tk = TK_LIT_HEX; goto state_finish; } } octal_literal: // ----------------------------------------------------------------------- while ( true ) { if ( ch >= '0' && ch <= '7' ) { *save = ch; ++save; ch = read_ch( task ); } else if ( ch == '_' ) { ch = read_ch( task ); } else if ( isalnum( ch ) ) { struct pos pos = { task->source->line, task->source->column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "invalid digit in octal literal" ); t_bail( task ); } else { // We consider the number zero to be a decimal literal. if ( save == task->source->save ) { save[ 0 ] = '0'; save[ 1 ] = 0; save += 2; tk = TK_LIT_DECIMAL; } else { *save = 0; ++save; tk = TK_LIT_OCTAL; } goto state_finish; } } decimal_literal: // ----------------------------------------------------------------------- while ( true ) { if ( isdigit( ch ) ) { *save = ch; ++save; ch = read_ch( task ); } else if ( ch == '_' ) { ch = read_ch( task ); } // Fixed-point number. else if ( ch == '.' ) { *save = ch; ++save; ch = read_ch( task ); goto fraction; } else if ( isalpha( ch ) ) { struct pos pos = { task->source->line, task->source->column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "invalid digit in octal literal" ); t_bail( task ); } else { *save = 0; ++save; tk = TK_LIT_DECIMAL; goto state_finish; } } fraction: // ----------------------------------------------------------------------- while ( true ) { if ( isdigit( ch ) ) { *save = ch; ++save; ch = read_ch( task ); } else if ( ch == '_' ) { ch = read_ch( task ); } else if ( isalpha( ch ) ) { struct pos pos = { task->source->line, task->source->column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "invalid digit in fractional part of fixed-point literal" ); t_bail( task ); } else if ( save[ -1 ] == '.' ) { struct pos pos = { task->source->line, column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "no digits found in fractional part of fixed-point literal" ); t_bail( task ); } else { *save = 0; ++save; tk = TK_LIT_FIXED; goto state_finish; } } state_string: // ----------------------------------------------------------------------- while ( true ) { if ( ! ch ) { struct pos pos = { line, column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "unterminated string" ); t_bail( task ); } else if ( ch == '"' ) { ch = read_ch( task ); goto state_string_concat; } else if ( ch == '\\' ) { ch = read_ch( task ); if ( ch == '"' ) { *save = ch; ++save; ch = read_ch( task ); } // Color codes are not parsed. else if ( ch == 'c' || ch == 'C' ) { save[ 0 ] = '\\'; save[ 1 ] = ch; save += 2; ch = read_ch( task ); } else { escape_ch( task, &ch, &save, true ); } } else { *save = ch; ++save; ch = read_ch( task ); } } state_string_concat: // ----------------------------------------------------------------------- while ( isspace( ch ) ) { ch = read_ch( task ); } // Next string. if ( ch == '"' ) { ch = read_ch( task ); goto state_string; } // Done. else { *save = 0; ++save; tk = TK_LIT_STRING; goto state_finish; } state_comment: // ----------------------------------------------------------------------- while ( ch && ch != '\n' ) { ch = read_ch( task ); } goto state_space; state_comment_m: // ----------------------------------------------------------------------- while ( true ) { if ( ! ch ) { struct pos pos = { line, column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "unterminated comment" ); t_bail( task ); } else if ( ch == '*' ) { ch = read_ch( task ); if ( ch == '/' ) { ch = read_ch( task ); goto state_space; } } else { ch = read_ch( task ); } } state_finish: // ----------------------------------------------------------------------- token->type = tk; if ( save != task->source->save ) { token->text = task->source->save; // Minus 1 so to not include the NUL character in the count. token->length = save - task->source->save - 1; task->source->save = save; } else { token->text = NULL; token->length = 0; } token->pos.line = line; token->pos.column = column; token->pos.id = task->source->active_id; task->source->ch = ch; } char read_ch( struct task* task ) { // Determine position of character. char* left = task->source->left; if ( left[ -1 ] ) { if ( left[ -1 ] == '\n' ) { ++task->source->line; task->source->column = 0; } else if ( left[ -1 ] == '\t' ) { task->source->column += task->options->tab_size - ( ( task->source->column + task->options->tab_size ) % task->options->tab_size ); } else { ++task->source->column; } } // Line concatenation. while ( left[ 0 ] == '\\' ) { // Linux. if ( left[ 1 ] == '\n' ) { ++task->source->line; task->source->column = 0; left += 2; } // Windows. else if ( left[ 1 ] == '\r' && left[ 2 ] == '\n' ) { ++task->source->line; task->source->column = 0; left += 3; } else { break; } } // Process character. if ( *left == '\n' ) { task->source->left = left + 1; return '\n'; } else if ( *left == '\r' && left[ 1 ] == '\n' ) { task->source->left = left + 2; return '\n'; } else { task->source->left = left + 1; return *left; } } void escape_ch( struct task* task, char* ch_out, char** save_out, bool in_string ) { char ch = *ch_out; char* save = *save_out; if ( ! ch ) { empty: ; struct pos pos = { task->source->line, task->source->column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "empty escape sequence" ); t_bail( task ); } int slash = task->source->column - 1; static const char singles[] = { 'a', '\a', 'b', '\b', 'f', '\f', 'n', '\n', 'r', '\r', 't', '\t', 'v', '\v', 0 }; int i = 0; while ( singles[ i ] ) { if ( singles[ i ] == ch ) { *save = singles[ i + 1 ]; ++save; ch = read_ch( task ); goto finish; } i += 2; } // Octal notation. char buffer[ 4 ]; int code = 0; i = 0; while ( ch >= '0' && ch <= '7' ) { if ( i == 3 ) { too_many_digits: ; struct pos pos = { task->source->line, task->source->column, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "too many digits" ); t_bail( task ); } buffer[ i ] = ch; ch = read_ch( task ); ++i; } if ( i ) { buffer[ i ] = 0; code = strtol( buffer, NULL, 8 ); goto save_ch; } if ( ch == '\\' ) { // In a string context, like the NUL character, the backslash character // must not be escaped. if ( in_string ) { save[ 0 ] = '\\'; save[ 1 ] = '\\'; save += 2; } else { save[ 0 ] = '\\'; save += 1; } ch = read_ch( task ); } // Hexadecimal notation. else if ( ch == 'x' || ch == 'X' ) { ch = read_ch( task ); i = 0; while ( ( ch >= '0' && ch <= '9' ) || ( ch >= 'a' && ch <= 'f' ) || ( ch >= 'A' && ch <= 'F' ) ) { if ( i == 2 ) { goto too_many_digits; } buffer[ i ] = ch; ch = read_ch( task ); ++i; } if ( ! i ) { goto empty; } buffer[ i ] = 0; code = strtol( buffer, NULL, 16 ); goto save_ch; } else { // In a string context, when encountering an unknown escape sequence, // leave it for the engine to process. if ( in_string ) { // TODO: Merge this code and the code above. Both handle the newline // character. if ( ch == '\n' ) { t_bail( task ); } save[ 0 ] = '\\'; save[ 1 ] = ch; save += 2; ch = read_ch( task ); } else { struct pos pos = { task->source->line, slash, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "unknown escape sequence" ); t_bail( task ); } } goto finish; save_ch: // ----------------------------------------------------------------------- // Code needs to be a valid character. if ( code > 127 ) { struct pos pos = { task->source->line, slash, task->source->active_id }; t_diag( task, DIAG_POS_ERR, &pos, "invalid character `\\%s`", buffer ); t_bail( task ); } // In a string context, the NUL character must not be escaped. Leave it // for the engine to process it. if ( code == 0 && in_string ) { save[ 0 ] = '\\'; save[ 1 ] = '0'; save += 2; } else { *save = ( char ) code; ++save; } finish: // ----------------------------------------------------------------------- *ch_out = ch; *save_out = save; } void t_test_tk( struct task* task, enum tk expected ) { if ( task->tk != expected ) { if ( task->tk == TK_RESERVED ) { t_diag( task, DIAG_POS_ERR, &task->tk_pos, "`%s` is a reserved identifier that is not currently used", task->tk_text ); } else { t_diag( task, DIAG_POS_ERR, &task->tk_pos, "unexpected %s", t_get_token_name( task->tk ) ); t_diag( task, DIAG_FILE | DIAG_LINE | DIAG_COLUMN, &task->tk_pos, "expecting %s here", t_get_token_name( expected ), t_get_token_name( task->tk ) ); } t_bail( task ); } } const char* t_get_token_name( enum tk tk ) { static const struct { enum tk tk; const char* name; } names[] = { { TK_BRACKET_L, "`[`" }, { TK_BRACKET_R, "`]`" }, { TK_PAREN_L, "`(`" }, { TK_PAREN_R, "`)`" }, { TK_BRACE_L, "`{`" }, { TK_BRACE_R, "`}`" }, { TK_DOT, "`.`" }, { TK_INC, "`++`" }, { TK_DEC, "`--`" }, { TK_COMMA, "`,`" }, { TK_COLON, "`:`" }, { TK_SEMICOLON, "`;`" }, { TK_ASSIGN, "`=`" }, { TK_ASSIGN_ADD, "`+=`" }, { TK_ASSIGN_SUB, "`-=`" }, { TK_ASSIGN_MUL, "`*=`" }, { TK_ASSIGN_DIV, "`/=`" }, { TK_ASSIGN_MOD, "`%=`" }, { TK_ASSIGN_SHIFT_L, "`<<=`" }, { TK_ASSIGN_SHIFT_R, "`>>=`" }, { TK_ASSIGN_BIT_AND, "`&=`" }, { TK_ASSIGN_BIT_XOR, "`^=`" }, { TK_ASSIGN_BIT_OR, "`|=`" }, { TK_ASSIGN_COLON, "`:=`" }, { TK_EQ, "`==`" }, { TK_NEQ, "`!=`" }, { TK_LOG_NOT, "`!`" }, { TK_LOG_AND, "`&&`" }, { TK_LOG_OR, "`||`" }, { TK_BIT_AND, "`&`" }, { TK_BIT_OR, "`|`" }, { TK_BIT_XOR, "`^`" }, { TK_BIT_NOT, "`~`" }, { TK_LT, "`<`" }, { TK_LTE, "`<=`" }, { TK_GT, "`>`" }, { TK_GTE, "`>=`" }, { TK_PLUS, "`+`" }, { TK_MINUS, "`-`" }, { TK_SLASH, "`/`" }, { TK_STAR, "`*`" }, { TK_MOD, "`%`" }, { TK_SHIFT_L, "`<<`" }, { TK_SHIFT_R, "`>>`" }, { TK_HASH, "`#`" }, { TK_BREAK, "`break`" }, { TK_CASE, "`case`" }, { TK_CONST, "`const`" }, { TK_CONTINUE, "`continue`" }, { TK_DEFAULT, "`default`" }, { TK_DO, "`do`" }, { TK_ELSE, "`else`" }, { TK_ENUM, "`enum`" }, { TK_FOR, "`for`" }, { TK_IF, "`if`" }, { TK_INT, "`int`" }, { TK_FIXED, "`fixed`" }, { TK_RETURN, "`return`" }, { TK_STATIC, "`static`" }, { TK_STR, "`str`" }, { TK_STRUCT, "`struct`" }, { TK_SWITCH, "`switch`" }, { TK_VOID, "`void`" }, { TK_WHILE, "`while`" }, { TK_BOOL, "`bool`" }, { TK_PALTRANS, "`createtranslation`" }, { TK_GLOBAL, "`global`" }, { TK_SCRIPT, "`script`" }, { TK_UNTIL, "`until`" }, { TK_WORLD, "`world`" }, { TK_OPEN, "`open`" }, { TK_RESPAWN, "`respawn`" }, { TK_DEATH, "`death`" }, { TK_ENTER, "`enter`" }, { TK_PICKUP, "`pickup`" }, { TK_BLUE_RETURN, "`bluereturn`" }, { TK_RED_RETURN, "`redreturn`" }, { TK_WHITE_RETURN, "`whitereturn`" }, { TK_LIGHTNING, "`lightning`" }, { TK_DISCONNECT, "`disconnect`" }, { TK_UNLOADING, "`unloading`" }, { TK_CLIENTSIDE, "`clientside`" }, { TK_NET, "`net`" }, { TK_RESTART, "`restart`" }, { TK_SUSPEND, "`suspend`" }, { TK_TERMINATE, "`terminate`" }, { TK_FUNCTION, "`function`" }, { TK_IMPORT, "`import`" }, { TK_GOTO, "`goto`" }, { TK_TRUE, "`true`" }, { TK_FALSE, "`false`" }, { TK_IMPORT, "`import`" }, { TK_REGION, "`region`" }, { TK_UPMOST, "`upmost`" }, { TK_EVENT, "`event`" }, { TK_LIT_OCTAL, "octal number" }, { TK_LIT_DECIMAL, "decimal number" }, { TK_LIT_HEX, "hexadecimal number" }, { TK_LIT_BINARY, "binary number" }, { TK_LIT_FIXED, "fixed-point number" }, { TK_NL, "newline character" }, { TK_END, "end-of-input" }, { TK_LIB, "start-of-library" }, { TK_LIB_END, "end-of-library" }, { TK_COLON_2, "`::`" } }; STATIC_ASSERT( TK_TOTAL == 107 ); switch ( tk ) { case TK_LIT_STRING: return "string literal"; case TK_LIT_CHAR: return "character literal"; case TK_ID: return "identifier"; default: for ( size_t i = 0; i < ARRAY_SIZE( names ); ++i ) { if ( names[ i ].tk == tk ) { return names[ i ].name; } } return ""; } } void t_diag( struct task* task, int flags, ... ) { va_list args; va_start( args, flags ); if ( task->options->acc_err ) { diag_acc( task, flags, &args ); } else { if ( flags & DIAG_FILE ) { const char* file = NULL; int line = 0, column = 0; make_pos( task, va_arg( args, struct pos* ), &file, &line, &column ); printf( "%s", file ); if ( flags & DIAG_LINE ) { printf( ":%d", line ); if ( flags & DIAG_COLUMN ) { printf( ":%d", column ); } } printf( ": " ); } if ( flags & DIAG_ERR ) { printf( "error: " ); } else if ( flags & DIAG_WARN ) { printf( "warning: " ); } const char* format = va_arg( args, const char* ); vprintf( format, args ); printf( "\n" ); } va_end( args ); } // Line format: <file>:<line>: <message> void diag_acc( struct task* task, int flags, va_list* args ) { if ( ! task->err_file ) { struct str str; str_init( &str ); if ( task->source_main ) { str_copy( &str, task->source_main->path.value, task->source_main->path.length ); while ( str.length && str.value[ str.length - 1 ] != '/' && str.value[ str.length - 1 ] != '\\' ) { str.value[ str.length - 1 ] = 0; --str.length; } } str_append( &str, "acs.err" ); task->err_file = fopen( str.value, "w" ); if ( ! task->err_file ) { printf( "error: failed to load error output file: %s\n", str.value ); t_bail( task ); } str_deinit( &str ); } if ( flags & DIAG_FILE ) { const char* file = NULL; int line = 0, column = 0; make_pos( task, va_arg( *args, struct pos* ), &file, &line, &column ); fprintf( task->err_file, "%s:", file ); if ( flags & DIAG_LINE ) { // For some reason, DB2 decrements the line number by one. Add one to // make the number correct. fprintf( task->err_file, "%d:", line + 1 ); } } fprintf( task->err_file, " " ); if ( flags & DIAG_ERR ) { fprintf( task->err_file, "error: " ); } else if ( flags & DIAG_WARN ) { fprintf( task->err_file, "warning: " ); } const char* message = va_arg( *args, const char* ); vfprintf( task->err_file, message, *args ); fprintf( task->err_file, "\n" ); } void make_pos( struct task* task, struct pos* pos, const char** file, int* line, int* column ) { // Path of source file. struct source* source = NULL; list_iter_t i; list_iter_init( &i, &task->loaded_sources ); while ( ! list_end( &i ) ) { source = list_data( &i ); if ( source->id == pos->id ) { break; } list_next( &i ); } *file = source->path.value; *line = pos->line; *column = pos->column; if ( task->options->one_column ) { ++*column; } } void t_bail( struct task* task ) { longjmp( *task->bail, 1 ); } void t_skip_block( struct task* task ) { while ( task->tk != TK_END && task->tk != TK_BRACE_L ) { t_read_tk( task ); } t_test_tk( task, TK_BRACE_L ); t_read_tk( task ); int depth = 0; while ( true ) { if ( task->tk == TK_BRACE_L ) { ++depth; t_read_tk( task ); } else if ( task->tk == TK_BRACE_R ) { if ( depth ) { --depth; t_read_tk( task ); } else { break; } } else if ( task->tk == TK_LIB_END ) { break; } else if ( task->tk == TK_END ) { break; } else { t_read_tk( task ); } } t_test_tk( task, TK_BRACE_R ); t_read_tk( task ); } bool t_same_pos( struct pos* a, struct pos* b ) { return ( a->id == b->id && a->line == b->line && a->column == b->column ); }
2.140625
2
2024-11-18T22:28:24.386098+00:00
2016-08-02T22:37:40
1f4f3ddfe7200e65345fc7a1ae5b4505c92fd8b8
{ "blob_id": "1f4f3ddfe7200e65345fc7a1ae5b4505c92fd8b8", "branch_name": "refs/heads/master", "committer_date": "2016-08-02T22:37:40", "content_id": "657a417011d32961c499b810dc8e32bd14522a1e", "detected_licenses": [ "MIT" ], "directory_id": "eb6fa00093dd735edee5337fb47199a835fcaf78", "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": 61163561, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2057, "license": "MIT", "license_type": "permissive", "path": "/pa03/main.c", "provenance": "stackv2-0132.json.gz:76530", "repo_name": "asheemchhetri/ECE264", "revision_date": "2016-08-02T22:37:40", "revision_id": "04292557d33730e2b167434bb10162323ea73203", "snapshot_id": "633bdede9d5630294f11f81b7c3bff5ed9da2e7e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/asheemchhetri/ECE264/04292557d33730e2b167434bb10162323ea73203/pa03/main.c", "visit_date": "2020-04-10T21:06:58.230040" }
stackv2
/* *============================================================================== * @Author : Asheem Chhetri <asheem> * @Date : Friday, June 24th 2016, 11:18:35 pm * @Email : [email protected] * @Project Name : main.c * @Last modified by : asheem * @Last modified time : Tuesday, June 28th 2016, 6:16:07 pm *============================================================================== *@Program Purpose : * This program corresponds to understand the function of pointer in working * of a swap function. It takes two inputs, and flips the location of initial * value storage. * *============================================================================== */ #include <stdio.h> #include <string.h> #include <stdlib.h> // This does not work. You will need to fix it. // Hint: look up swap(int *, int *) in the textbook void swapString(char * * a, char * * b) { char * tmp = *a; *a = *b; *b = tmp; printf("Calling swapString(...)\n"); printf("&a = %p\n", &a); printf("&b = %p\n", &b); printf("&tmp = %p\n", &tmp); } int main(int argc, char * * argv) { printf("Welcome to PA03.\n" "\n" "Please make sure that the swapString(...) function works\n" "\n"); printf("Print out some memory addresses for argc, argv...\n" "to illustrate how memory is laid out.\n"); printf("&argc = %p\n", &argc); printf("&argv = %p\n", &argv); printf("argv = %p\n", argv); printf("*argv = %p\n", *argv); printf("*argv = %s\n", *argv); printf("**argv = %c\n", **argv); // Let's create our own array of strings printf("\nTesting swapString(...)\n"); char * str1 = "one"; char * str2 = "two"; printf("Before swap, str1 == %p (i.e., '%s'), " "str2 == %p (i.e., '%s')\n", str1, str1, str2, str2); swapString(&str1, &str2); printf("After swap, str1 == %p (i.e., '%s'), " "str2 == %p (i.e., '%s')\n", str1, str1, str2, str2); return EXIT_SUCCESS; }
3.6875
4
2024-11-18T22:28:24.883019+00:00
2016-01-17T21:31:33
43b20966ca8399ea289293075b9ceb12403f8c04
{ "blob_id": "43b20966ca8399ea289293075b9ceb12403f8c04", "branch_name": "refs/heads/master", "committer_date": "2016-01-17T21:31:33", "content_id": "7dbdb6e78d996b3ee417b36bb500bdd4f5441631", "detected_licenses": [ "MIT" ], "directory_id": "1e7b5202003f9da1b2a2c0cfc704049f21f6ff55", "extension": "c", "filename": "emu.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 48631776, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1638, "license": "MIT", "license_type": "permissive", "path": "/src/emu.c", "provenance": "stackv2-0132.json.gz:76919", "repo_name": "timwaterman/GB_Emulator", "revision_date": "2016-01-17T21:31:33", "revision_id": "849282a003e616b2766c7637f9058904ae702ff2", "snapshot_id": "1d7a22351d7391c0a550e60e1158de65e16934a9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/timwaterman/GB_Emulator/849282a003e616b2766c7637f9058904ae702ff2/src/emu.c", "visit_date": "2021-01-10T02:38:21.137414" }
stackv2
/* Tim Waterman 26 December 2015 Emulator Main */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "opcodes.h" #include "SDL.h" unsigned char *memoryspace; //die with an error void die(const char *message) { perror(message); exit(1); } /* Getsize will return the size of a file in bytes File must already be opened prior to call */ int getSize(FILE *file) { fseek(file, 0L, SEEK_END); //go to the end of the file int size = ftell(file); rewind(file); //go back to beginning of file return size; } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "%s\n", "Usage: ./gbemu <rom file>"); exit(1); } memoryspace = malloc(0xFFFF); //create the memory space of 64K registers regs; FILE *rom = fopen(argv[1], "r"); if (rom == NULL) { die("Fopen failed\n"); } if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) { fprintf(stderr, "SDL_INIT() Failure: %s\n", SDL_GetError()); exit(1); } //establish size and buffer int size = getSize(rom); char buffer[size]; memset(buffer, 0, sizeof(buffer)); //read the file into buffer to use as input stream fread(buffer, size, 1, rom); initRegisters(&regs); //initialize all the registers loadLogo(); memoryspace[0xFF44] = 0x90; //init the display to work, ONLY HERE FOR TESTING SDL_Quit(); //only here because I'm not using the display now while(regs.pc < sizeof buffer) { fprintf(stderr, "PC is %u\n", regs.pc); opcode op = decodeInstruction(buffer[regs.pc], buffer[regs.pc + 1] ); executeInstruction(&regs, op, buffer); printRegisters(&regs); fprintf(stderr, "PC is %u\n", regs.pc); } return 0; }
3
3
2024-11-18T22:28:24.964113+00:00
2017-11-08T21:34:21
a810c8bb5590983189de1b8edbeb1ddef7c7bdaa
{ "blob_id": "a810c8bb5590983189de1b8edbeb1ddef7c7bdaa", "branch_name": "refs/heads/master", "committer_date": "2017-11-08T21:34:21", "content_id": "0dec3a6694e2c2ad4e9eceb562988c634e844c57", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e8c566f43dc39d3bb948a5d326be26af389589a3", "extension": "c", "filename": "timerTick.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 110021846, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 567, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Kernel/timerTick.c", "provenance": "stackv2-0132.json.gz:77047", "repo_name": "Estebank94/ClicOSNapEdition", "revision_date": "2017-11-08T21:34:21", "revision_id": "ee38cd79c691d5153f9e9fef35a700c582970326", "snapshot_id": "2a917323b49228cb30fc67058bdb2acbb878ee55", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Estebank94/ClicOSNapEdition/ee38cd79c691d5153f9e9fef35a700c582970326/Kernel/timerTick.c", "visit_date": "2021-07-25T16:22:01.926525" }
stackv2
#include "include/timerTick.h" #include "include/vsa_driver.h" #include "include/lib.h" typedef void (*event)() ; static unsigned int cdown[MAXCOUNTERS]; void rem(int i){ cdown[i]--; } void tick(){ for(int i=0;i<MAXCOUNTERS;i++){ if(cdown[i]>0){ rem(i); } } } int addTick(int t){ for(int i=0;i<MAXCOUNTERS;i++) { if (cdown[i] == 0) { cdown[i] = t; return i; } } return -1; } void sleep(int t){ _cli(); int x=addTick(t); _sti(); while(cdown[x]>0); }
2.203125
2
2024-11-18T22:28:25.080721+00:00
2020-07-09T07:56:18
180b25a3e0c652a6d5e2c51706f217772eb7d966
{ "blob_id": "180b25a3e0c652a6d5e2c51706f217772eb7d966", "branch_name": "refs/heads/master", "committer_date": "2020-07-09T07:56:18", "content_id": "770c630bb5e347735965614a87619ce5c1c7222f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e6b57fff8ff0a22e1f45d0f052f0efbc89b0af3f", "extension": "c", "filename": "encode.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 269530214, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15079, "license": "Apache-2.0", "license_type": "permissive", "path": "/guacamole-server-1.1.0/src/guacenc/encode.c", "provenance": "stackv2-0132.json.gz:77177", "repo_name": "yuyiliang1993/guacenc", "revision_date": "2020-07-09T07:56:18", "revision_id": "a9714fb37dbabcfe48ade2ce98d2c8ce4cff00ff", "snapshot_id": "194413c9c7930879adbd8c3cee85c97df1fd5a6c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/yuyiliang1993/guacenc/a9714fb37dbabcfe48ade2ce98d2c8ce4cff00ff/guacamole-server-1.1.0/src/guacenc/encode.c", "visit_date": "2022-11-12T13:54:56.010741" }
stackv2
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "encode_video.h" static InsTransVideo_t *g_ptr_transVideo = NULL; int ins_read_video_configure(struct VideoConfig*config){ //setup temp data,will read file to set config->width = 800; config->height = 600; config->bitrate = 2000000; strcpy(config->codec,"mpeg4"); config->codec[5] = 0; const char*tmp = "/home/workroom1/test.m4v"; strcpy(config->outfile,tmp); config->outfile[strlen(tmp)] = 0; return 0; } InsTransVideo_t*ins_transVideo_create(struct VideoConfig *config){ struct InsTransVideo *ins = \ (struct InsTransVideo*)malloc(sizeof(struct InsTransVideo)*1); if(ins == NULL) return NULL; ins->offsetLen = 0; ins->display = NULL; ins->parser = NULL; ins->parser = guac_parser_alloc(); if(access(config->tmpfile,F_OK) == 0) unlink(config->tmpfile); ins->display = guacenc_display_alloc(config->tmpfile,\ config->codec,config->width, config->height,config->bitrate); if(ins->display == NULL || ins->parser == NULL){ if(ins->display) guacenc_display_free(ins->display); if(ins->parser) guac_parser_alloc(ins->parser); free(ins); ins = NULL; } return ins; } void ins_transVideo_delete(InsTransVideo_t *ins){ if(ins){ printf("free transvideo\n"); if(ins->display) guacenc_display_free(ins->display); if(ins->parser) guac_parser_alloc(ins->parser); free(ins); } } //change by yuliang static void ins_parser_reset(guac_parser* parser) { parser->opcode = NULL; parser->argc = 0; parser->state = GUAC_PARSE_LENGTH; parser->__elementc = 0; parser->__element_length = 0; } static void ins_free_global_memory(void){ printf("free transVideo_delete\n"); ins_transVideo_delete(g_ptr_transVideo); g_ptr_transVideo = NULL; } static void ins_handle_complete_instruction(guacenc_display*display,guac_parser* parser){ if (guacenc_handle_instruction(display, parser->opcode, parser->argc, parser->argv)) { guacenc_log(GUAC_LOG_DEBUG, "Handling of \"%s\" instruction " "failed.", parser->opcode); } } static int ins_read_instructions(InsTransVideo_t*ins,char *dest,int size){ if(NULL == ins) return -1; char *buffer = ins->data; if(ins->offsetLen == 0){ return 0; } int *length =& ins->offsetLen; int rv = 0; if(size >= ins->offsetLen){ memcpy(dest,buffer,*length); rv = *length; *length = 0; } else { memcpy(dest,buffer,size); memmove(buffer,buffer+size,*length - size); *length -= size; rv = size; } return rv; } int ins_parser_read(InsTransVideo_t *ins){ if(ins == NULL) return (-1); #if 1 guac_parser* parser = ins->parser; if(parser == NULL) return (-1); char* unparsed_end = parser->__instructionbuf_unparsed_end; char* unparsed_start = parser->__instructionbuf_unparsed_start; char* instr_start = parser->__instructionbuf_unparsed_start; char* buffer_end = parser->__instructionbuf + sizeof(parser->__instructionbuf); int loop = 1; do{ if (parser->state == GUAC_PARSE_COMPLETE){ ins_handle_complete_instruction(ins->display,parser); ins_parser_reset(parser); } /* Add any available data to buffer */ int parsed = guac_parser_append(parser, unparsed_start, unparsed_end - unparsed_start); if(parser->state == GUAC_PARSE_ERROR){ printf("parer error\n"); break; } /* Read more data if not enough data to parse */ if (parsed == 0 && parser->state != GUAC_PARSE_ERROR) { int retval; /* If no space left to read, fail */ if (unparsed_end == buffer_end) { /* Shift backward if possible */ if (instr_start != parser->__instructionbuf) { int i; /* Shift buffer */ int offset = instr_start - parser->__instructionbuf; memmove(parser->__instructionbuf, instr_start, unparsed_end - instr_start); /* Update tracking pointers */ unparsed_end -= offset; unparsed_start -= offset; instr_start = parser->__instructionbuf; /* Update parsed elements, if any */ for (i=0; i < parser->__elementc; i++) parser->__elementv[i] -= offset; } /* Otherwise, no memory to read */ else { printf("Instruction too long\n"); guac_error = GUAC_STATUS_NO_MEMORY; guac_error_message = "Instruction too long"; return -1; } } retval = ins_read_instructions(ins,unparsed_end,buffer_end - unparsed_end); if(retval <= 0) loop = 0; unparsed_end += retval; } /* If data was parsed, advance buffer */ else unparsed_start += parsed; }while(loop); /* Fail on error */ if (parser->state == GUAC_PARSE_ERROR) { guac_error = GUAC_STATUS_PROTOCOL_ERROR; guac_error_message = "Instruction parse error"; printf("Instruction parse error\n"); return -1; } parser->__instructionbuf_unparsed_start = unparsed_start; parser->__instructionbuf_unparsed_end = unparsed_end; #endif return 0; } //接口,在guacd直接调用,使用此接口, //如果使用外置服务器,我们使用 int ins_convert_video(const char *buf,int length){ static struct VideoConfig conf; if(g_ptr_transVideo == NULL){ printf("g_ptr_transVideo == NULL\n"); ins_read_video_configure(&conf); unlink(conf.outfile); g_ptr_transVideo = ins_transVideo_create(&conf); if(g_ptr_transVideo == NULL) return (-1); atexit(ins_free_global_memory); } int k = 0; while(k < length){ if(g_ptr_transVideo->offsetLen > sizeof(g_ptr_transVideo->data)){ printf("Too long instructs\n"); g_ptr_transVideo->offsetLen = 0; return -1; } g_ptr_transVideo->data[g_ptr_transVideo->offsetLen++] = buf[k++]; if(g_ptr_transVideo->data[g_ptr_transVideo->offsetLen-1] == ';'){ ins_parser_read(g_ptr_transVideo); g_ptr_transVideo->offsetLen = 0; } } return 0; } void ins_test_read(int argc,char **argv){ if(argc != 2){ fprintf(stdout,"Usage:guacenc <in_file>\n"); return ; } const char *filename = argv[1]; printf("Start open filename:%s\n",filename); int fd = open(filename, O_RDONLY); if (fd < 0) { printf("%s: %s", filename, strerror(errno)); return ; } char buffer[4096]; int nbytes = 0; while(1){ nbytes = read(fd,buffer,sizeof(buffer)); if(nbytes < 0){ perror("read file"); break; } if(nbytes == 0) break; if(ins_convert_video(buffer,nbytes) < 0) break; } printf("Read completed!\n"); close(fd); } #if 0 #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define SERVER_IPADDR "0.0.0.0" #define SERVER_PORT "1234" #include <string.h> int test_net_handle_instructions(){ int sck = socket(AF_INET,SOCK_STREAM,0); if(sck < 0){ perror("socket"); return -1; } struct sockaddr_in addr; memset(&addr,0,sizeof(addr)); addr.sin_family=AF_INET; addr.sin_port = htons(atoi(SERVER_PORT)); addr.sin_addr.s_addr = inet_addr(SERVER_IPADDR); int val = 1; setsockopt(sck,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(val)); if(bind(sck,(struct sockaddr*)&addr,sizeof(addr)) < 0){ perror("bind"); close(sck); return -1; } listen(sck,0); fd_set rfds; int max = sck; int connfd = -1; printf("server start listen:%s:%s\n",SERVER_IPADDR,SERVER_PORT); while(1){ // rfds= tmp_rfds; FD_ZERO(&rfds); FD_SET(sck,&rfds); if(connfd > -1) FD_SET(connfd,&rfds); max = connfd>max?connfd:max; int n = select(max+1,&rfds,NULL,NULL,NULL); if(n < 0){ if(errno == EINTR) continue; perror("select"); break; } if(n == 0) continue; if(FD_ISSET(sck,&rfds)){ struct sockaddr_in cliaddr; memset(&cliaddr,0,sizeof(cliaddr)); socklen_t addrlen = sizeof(cliaddr); int tmpfd = accept(sck,(struct sockaddr*)&cliaddr,&addrlen); if(tmpfd < 0){ perror("accept"); }else { if(connfd != -1) close(connfd);//关闭旧连接 printf("accept new connection:%s:%d\n",\ inet_ntoa(cliaddr.sin_addr),\ ntohs(cliaddr.sin_port)); connfd = tmpfd; } if(--n <= 0) continue; } if(FD_ISSET(connfd,&rfds)){ char buf[256]; int nbytes = read(connfd,buf,sizeof(buf)); if(nbytes > 0){ buf[nbytes] = 0; // printf("read:%s\n",buf); ins_convert_video(buf,nbytes); } if(nbytes == 0){ unlink("/home/workroom1/123.avi"); system("ffmpeg -i /home/workroom1/test.m4v /home/workroom1/123.avi"); printf("client close\n"); close(connfd); connfd = (-1); } if(nbytes < 0){ if(errno == EINTR || errno == EAGAIN); else{ close(connfd); connfd = (-1); } } if(--n <= 0) continue; } } close(sck); close(connfd); return 0; } #endif /** * Reads and handles all Guacamole instructions from the given guac_socket * until end-of-stream is reached. * * @param display * The current internal display of the Guacamole video encoder. * * @param path * The name of the file being parsed (for logging purposes). This file * must already be open and available through the given socket. * * @param socket * The guac_socket through which instructions should be read. * * @return * Zero on success, non-zero if parsing of Guacamole protocol data through * the given socket fails. */ static int guacenc_read_instructions(guacenc_display* display, const char* path, guac_socket* socket) { /* Obtain Guacamole protocol parser */ guac_parser* parser = guac_parser_alloc(); if (parser == NULL) return 1; /* Continuously read and handle all instructions */ //从指令文件中读取数据,并且把数据解析到parser中 while (!guac_parser_read(parser, socket, -1)) { if (guacenc_handle_instruction(display, parser->opcode, parser->argc, parser->argv)) { guacenc_log(GUAC_LOG_DEBUG, "Handling of \"%s\" instruction " "failed.", parser->opcode); } } /* Fail on read/parse error */ if (guac_error != GUAC_STATUS_CLOSED) { guacenc_log(GUAC_LOG_ERROR, "%s: %s", path, guac_status_string(guac_error)); guac_parser_free(parser); return 1; } /* Parse complete */ guac_parser_free(parser); return 0; } int guacenc_encode(const char* path, const char* out_path, const char* codec, int width, int height, int bitrate, bool force) { /* Open input file */ int fd = open(path, O_RDONLY); if (fd < 0) { guacenc_log(GUAC_LOG_ERROR, "%s: %s", path, strerror(errno)); return 1; } /* Lock entire input file for reading by the current process */ struct flock file_lock = { .l_type = F_RDLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 0, .l_pid = getpid() }; /* Abort if file cannot be locked for reading */ if (!force && fcntl(fd, F_SETLK, &file_lock) == -1) { /* Warn if lock cannot be acquired */ if (errno == EACCES || errno == EAGAIN) guacenc_log(GUAC_LOG_WARNING, "Refusing to encode in-progress " "recording \"%s\" (specify the -f option to override " "this behavior).", path); /* Log an error if locking fails in an unexpected way */ else guacenc_log(GUAC_LOG_ERROR, "Cannot lock \"%s\" for reading: %s", path, strerror(errno)); close(fd); return 1; } /* Allocate display for encoding process */ guacenc_display* display = guacenc_display_alloc(out_path, codec, width, height, bitrate); if (display == NULL) { close(fd); return 1; } /* Obtain guac_socket wrapping file descriptor */ guac_socket* socket = guac_socket_open(fd); if (socket == NULL) { guacenc_log(GUAC_LOG_ERROR, "%s: %s", path, guac_status_string(guac_error)); close(fd); guacenc_display_free(display); return 1; } guacenc_log(GUAC_LOG_INFO, "Encoding \"%s\" to \"%s\" ...", path, out_path); /* Attempt to read all instructions in the file */ if (guacenc_read_instructions(display, path, socket)) { guac_socket_free(socket); guacenc_display_free(display); return 1; } /* Close input and finish encoding process */ guac_socket_free(socket); return guacenc_display_free(display); }
2.140625
2
2024-11-18T22:28:25.372489+00:00
2023-09-02T14:55:31
934cc1d6c53e092d9fc3eccd0673e59bc80b0110
{ "blob_id": "934cc1d6c53e092d9fc3eccd0673e59bc80b0110", "branch_name": "refs/heads/master", "committer_date": "2023-09-02T14:55:31", "content_id": "d0c5a33a9ac110f01826ab38fd1c78157bbef42f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "8838eb997879add5759b6dfb23f9a646464e53ca", "extension": "c", "filename": "ipl_impl.c", "fork_events_count": 325, "gha_created_at": "2015-03-29T15:27:48", "gha_event_created_at": "2023-09-14T16:58:34", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 33078138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 390, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/arch/riscv/kernel/ipl_impl.c", "provenance": "stackv2-0132.json.gz:77565", "repo_name": "embox/embox", "revision_date": "2023-09-02T14:55:31", "revision_id": "98e3c06e33f3fdac10a29c069c20775568e0a6d1", "snapshot_id": "d6aacec876978522f01cdc4b8de37a668c6f4c80", "src_encoding": "UTF-8", "star_events_count": 1087, "url": "https://raw.githubusercontent.com/embox/embox/98e3c06e33f3fdac10a29c069c20775568e0a6d1/src/arch/riscv/kernel/ipl_impl.c", "visit_date": "2023-09-04T03:02:20.165042" }
stackv2
/** * @file * * @date 14.05.2019 * @author Dmitry Kurbatov */ //#include <ipl_impl.h> #include <hal/ipl.h> #include <asm/regs.h> #include <asm/interrupts.h> void ipl_init(void) { enable_interrupts(); } ipl_t ipl_save(void) { ipl_t csr; csr = read_csr(mstatus); write_csr(mstatus, csr & ~(MSTATUS_MIE)); return csr; } void ipl_restore(ipl_t ipl) { write_csr(mstatus, ipl); }
2.09375
2
2024-11-18T22:28:25.636498+00:00
2022-08-30T19:53:19
2074bfc79a6c067c13f5830cd231ecd8b259547a
{ "blob_id": "2074bfc79a6c067c13f5830cd231ecd8b259547a", "branch_name": "refs/heads/master", "committer_date": "2022-08-30T19:53:19", "content_id": "b504a135b96a03cb1b34916092b2573f33a670c1", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "a9a591fc3964117db3b16583c3bfa5a24cfc0114", "extension": "c", "filename": "lfds720_freelist_n_push.c", "fork_events_count": 10, "gha_created_at": "2017-01-07T15:53:24", "gha_event_created_at": "2021-05-25T01:43:22", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 78288048, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3684, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/lib/liblfds7.2.0/src/liblfds720/src/lfds720_freelist_nodeallocate/lfds720_freelist_n_push.c", "provenance": "stackv2-0132.json.gz:77693", "repo_name": "grz0zrg/fas", "revision_date": "2022-08-30T19:53:19", "revision_id": "07b08a77b78781dd5ed7984117f294fe4fcbe3fd", "snapshot_id": "9cd0a55c7e86fcf5cafffd44ebdf633f3ee5fefa", "src_encoding": "UTF-8", "star_events_count": 142, "url": "https://raw.githubusercontent.com/grz0zrg/fas/07b08a77b78781dd5ed7984117f294fe4fcbe3fd/lib/liblfds7.2.0/src/liblfds720/src/lfds720_freelist_nodeallocate/lfds720_freelist_n_push.c", "visit_date": "2022-09-18T05:29:27.983761" }
stackv2
/***** includes *****/ #include "lfds720_freelist_n_internal.h" /****************************************************************************/ void lfds720_freelist_n_threadsafe_push( struct lfds720_freelist_n_state *fs, struct lfds720_freelist_n_per_thread_state *fpts, struct lfds720_freelist_n_element *fe ) { char unsigned result; lfds720_pal_uint_t backoff_iteration = LFDS720_BACKOFF_INITIAL_VALUE, elimination_array_index, loop; struct lfds720_freelist_n_element LFDS720_PAL_ALIGN(LFDS720_PAL_DOUBLE_POINTER_LENGTH_IN_BYTES) *new_top[LFDS720_MISC_PAC_SIZE], *volatile original_top[LFDS720_MISC_PAC_SIZE]; LFDS720_PAL_ASSERT( fs != NULL ); LFDS720_PAL_ASSERT( (fs->elimination_array != NULL and fpts != NULL) or (fs->elimination_array == NULL and fpts == NULL) ); LFDS720_PAL_ASSERT( fe != NULL ); if( fs->elimination_array != NULL ) { elimination_array_index = ( (fpts->elimination_array_round_robin_push_counter++) & (fs->elimination_array_number_of_lines-1) ); // TRD : full scan of one cache line, max pointers per cache line for( loop = 0 ; loop < LFDS720_FREELIST_N_ELIMINATION_ARRAY_USED_LINE_LENGTH_IN_FREELIST_N_POINTER_ELEMENTS ; loop++ ) if( fs->elimination_array[elimination_array_index][loop] == NULL ) { LFDS720_PAL_ATOMIC_EXCHANGE( fs->elimination_array[elimination_array_index][loop], fe, struct lfds720_freelist_n_element * ); if( fe == NULL ) { fpts->elimination_array_round_robin_pop_counter = fpts->elimination_array_round_robin_push_counter; return; } } } new_top[LFDS720_MISC_POINTER] = fe; original_top[LFDS720_MISC_COUNTER] = fs->top[LFDS720_MISC_COUNTER]; original_top[LFDS720_MISC_POINTER] = fs->top[LFDS720_MISC_POINTER]; do { fe->next = original_top[LFDS720_MISC_POINTER]; LFDS720_MISC_BARRIER_STORE; new_top[LFDS720_MISC_COUNTER] = original_top[LFDS720_MISC_COUNTER] + 1; LFDS720_PAL_ATOMIC_DWCAS( fs->top, original_top, new_top, LFDS720_MISC_CAS_STRENGTH_WEAK, result ); if( result == 0 ) LFDS720_BACKOFF_EXPONENTIAL_BACKOFF( fs->push_backoff, backoff_iteration ); } while( result == 0 ); LFDS720_BACKOFF_AUTOTUNE( fs->push_backoff, backoff_iteration ); return; } /****************************************************************************/ void lfds720_freelist_n_internal_push_without_ea( struct lfds720_freelist_n_state *fs, struct lfds720_freelist_n_element *fe ) { char unsigned result; lfds720_pal_uint_t backoff_iteration = LFDS720_BACKOFF_INITIAL_VALUE; struct lfds720_freelist_n_element LFDS720_PAL_ALIGN(LFDS720_PAL_DOUBLE_POINTER_LENGTH_IN_BYTES) *new_top[LFDS720_MISC_PAC_SIZE], *volatile original_top[LFDS720_MISC_PAC_SIZE]; LFDS720_PAL_ASSERT( fs != NULL ); LFDS720_PAL_ASSERT( fe != NULL ); new_top[LFDS720_MISC_POINTER] = fe; original_top[LFDS720_MISC_COUNTER] = fs->top[LFDS720_MISC_COUNTER]; original_top[LFDS720_MISC_POINTER] = fs->top[LFDS720_MISC_POINTER]; do { fe->next = original_top[LFDS720_MISC_POINTER]; LFDS720_MISC_BARRIER_STORE; new_top[LFDS720_MISC_COUNTER] = original_top[LFDS720_MISC_COUNTER] + 1; LFDS720_PAL_ATOMIC_DWCAS( fs->top, original_top, new_top, LFDS720_MISC_CAS_STRENGTH_WEAK, result ); if( result == 0 ) LFDS720_BACKOFF_EXPONENTIAL_BACKOFF( fs->push_backoff, backoff_iteration ); } while( result == 0 ); LFDS720_BACKOFF_AUTOTUNE( fs->push_backoff, backoff_iteration ); return; }
2.078125
2
2024-11-18T22:28:25.706574+00:00
2023-08-08T06:09:20
1a219757fa09a5002a6b989db703bcba08d9f4a8
{ "blob_id": "1a219757fa09a5002a6b989db703bcba08d9f4a8", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T04:38:20", "content_id": "e195ad71eb4c4d158cd16370a6099398feb67c08", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0744dcc5394cebf57ebcba343747af6871b67017", "extension": "c", "filename": "lib_roundf.c", "fork_events_count": 719, "gha_created_at": "2017-02-20T04:38:30", "gha_event_created_at": "2023-09-14T06:54:49", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 82517252, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1677, "license": "Apache-2.0", "license_type": "permissive", "path": "/lib/libc/math/lib_roundf.c", "provenance": "stackv2-0132.json.gz:77823", "repo_name": "Samsung/TizenRT", "revision_date": "2023-08-08T06:09:20", "revision_id": "1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686", "snapshot_id": "96abf62f1853f61fcf91ff14671a5e0c6ca48fdb", "src_encoding": "UTF-8", "star_events_count": 590, "url": "https://raw.githubusercontent.com/Samsung/TizenRT/1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686/lib/libc/math/lib_roundf.c", "visit_date": "2023-08-31T08:59:33.327998" }
stackv2
/**************************************************************************** * * Copyright 2016-2017 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ /************************************************************************ * lib/math/lib_roundf.c * * This file is a part of NuttX: * * Copyright (C) 2012 Gregory Nutt. All rights reserved. * (C) 2012 Petteri Aimonen <[email protected]> * ************************************************************************/ /************************************************************************ * Included Files ************************************************************************/ #include <math.h> /************************************************************************ * Public Functions ************************************************************************/ float roundf(float x) { float f; if (isnan(x)) { return NAN; } f = modff(x, &x); if (x <= 0.0f && f <= -0.5f) { x -= 1.0f; } if (x >= 0.0f && f >= 0.5f) { x += 1.0f; } return x; }
2.1875
2
2024-11-18T22:28:26.377460+00:00
2023-08-16T08:49:18
3003fdf4c05a26294b7c30bae04b198170d715a2
{ "blob_id": "3003fdf4c05a26294b7c30bae04b198170d715a2", "branch_name": "refs/heads/master", "committer_date": "2023-08-16T08:49:18", "content_id": "e2fe02a3996ff5c69895b657eb6fa80e74ec1079", "detected_licenses": [ "MIT" ], "directory_id": "e3acfc4f06840e23ef1185dcf367f40d3e3f59b4", "extension": "c", "filename": "06-mukherjee_simpleLoop5.c", "fork_events_count": 62, "gha_created_at": "2011-07-18T15:10:56", "gha_event_created_at": "2023-09-14T18:48:34", "gha_language": "OCaml", "gha_license_id": "MIT", "github_id": 2066905, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1195, "license": "MIT", "license_type": "permissive", "path": "/tests/regression/52-apron-mukherjee/06-mukherjee_simpleLoop5.c", "provenance": "stackv2-0132.json.gz:78208", "repo_name": "goblint/analyzer", "revision_date": "2023-08-16T08:49:18", "revision_id": "69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f", "snapshot_id": "d62d3c610b86ed288849371b41c330c30678abc7", "src_encoding": "UTF-8", "star_events_count": 141, "url": "https://raw.githubusercontent.com/goblint/analyzer/69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f/tests/regression/52-apron-mukherjee/06-mukherjee_simpleLoop5.c", "visit_date": "2023-08-16T21:58:53.013737" }
stackv2
// SKIP PARAM: --set ana.activated[+] apron --set ana.path_sens[+] threadflag --set ana.activated[+] threadJoins --enable ana.apron.threshold_widening #include <pthread.h> #include <goblint.h> unsigned int a, b, c; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void* T1_SL5(void* arg){ while(1) { pthread_mutex_lock(&lock); __goblint_check(a != b); //TODO requires disjunctions pthread_mutex_unlock(&lock); } return NULL; } void* T2_SL5(void* arg){ while(1) { pthread_mutex_lock(&lock); int temp = a; a = b; b = c; c = temp; pthread_mutex_unlock(&lock); } return NULL; } void* T3_SL5(void* arg){ while(1) { pthread_mutex_lock(&lock); int temp = a; a = b; b = c; c = temp; pthread_mutex_unlock(&lock); } return NULL; } int main(){ a = 1; b = 2; c = 3; pthread_t t1; pthread_t t2; pthread_t t3; pthread_create(&t1, 0, T1_SL5, 0); pthread_create(&t2, 0, T2_SL5, 0); pthread_create(&t3, 0, T3_SL5, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); return 0; }
2.5
2
2024-11-18T22:28:27.025399+00:00
2020-11-15T23:30:27
f8663f9576284b51f008ed6006f3c28c6499a8cb
{ "blob_id": "f8663f9576284b51f008ed6006f3c28c6499a8cb", "branch_name": "refs/heads/master", "committer_date": "2020-11-15T23:30:27", "content_id": "e9732593a0b79443568e91689abd56f1cd32b7d6", "detected_licenses": [ "MIT" ], "directory_id": "549b2397cd65ecc7f45a802332fad67b7cee6f4e", "extension": "h", "filename": "thing.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 310667625, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2416, "license": "MIT", "license_type": "permissive", "path": "/include/gsi/thing.h", "provenance": "stackv2-0132.json.gz:78727", "repo_name": "emanuelmoraes-dev/g-social-interactive", "revision_date": "2020-11-15T23:30:27", "revision_id": "e71e9367f9d8b0b860e820d3f05fc218c52078d1", "snapshot_id": "bfc0abd2bfc8dbbfbddafb8385c40ecfca1b5a24", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/emanuelmoraes-dev/g-social-interactive/e71e9367f9d8b0b860e820d3f05fc218c52078d1/include/gsi/thing.h", "visit_date": "2023-01-12T16:18:04.579940" }
stackv2
#ifndef GSI_THING_H_INCLUDED #define GSI_THING_H_INCLUDED #include "gsi/types/thing.h" #include "gsi/annotations.h" #include "cemdutil/dynamic_string.h" struct thing_type { char name[100]; // nome do tipo owner String* description; // descrição do tipo double rarity; // raridade double monetary_value; // valor monetário double liquidity; // liquidez: taxa por unidade de tempo de desvalorização do valor monetário double utility_value; // valor útil double durability; // durabilidade: taxa por unidade de tempo de desvalorização do valor útil }; struct thing { borrowed ThingType* type; // tipo char name[100]; // nome owner String* description; // descrição }; /** * Inicializa um ThingType * * @param thing_type instância de ThingType a ser inicializado * @param name nome * @param description descrição * @param rarity raridade * @param monetary_value valor monetário * @param liquidity liquidez: taxa por unidade de tempo de desvalorização do valor monetário * @param utility_value valor útil * @param durability durabilidade: taxa por unidade de tempo de desvalorização do valor útil */ void thing_type_init( ThingType* thing_type, const char name[100], String* description, double rarity, double monetary_value, double liquidity, double utility_value, double durability ); /** * Libera da memória os espaços alocados, porém NÃO desaloca da memória a instância de ThingType * * @param _thing_type instância de ThingType */ void thing_type_clear(void* _thing_type); /** * Libera da memória os espaços alocados e desaloca da memória a instância de ThingType * * @param _thing_type instância de ThingType */ void thing_type_free(void* _thing_type); /** * Inicializa um Thing * * @param thing instância de Thing a ser inicializado * @param type tipo * @param name nome * @param description descrição */ void thing_init(Thing* thing, ThingType* type, char name[100], String* description); /** * Libera da memória os espaços alocados, porém NÃO desaloca da memória a instância de Thing * * @param _thing instância de Thing */ void thing_clear(void* _thing); /** * Libera da memória os espaços alocados e desaloca da memória a instância de Thing * * @param _thing instância de Thing */ void thing_free(void* _thing); #endif // GSI_THING_H_INCLUDED
2.4375
2
2024-11-18T22:28:27.226428+00:00
2023-03-22T17:19:12
d88dddf294bc254732fb5817834d8d8b67250443
{ "blob_id": "d88dddf294bc254732fb5817834d8d8b67250443", "branch_name": "refs/heads/master", "committer_date": "2023-03-22T17:19:12", "content_id": "7b5ca08c3d208c8399882264b7345b21b0c041b3", "detected_licenses": [ "MIT" ], "directory_id": "5fb733bee490d6164d7d178acdffe669c3dc21a3", "extension": "c", "filename": "test_list.c", "fork_events_count": 46, "gha_created_at": "2016-04-15T18:49:16", "gha_event_created_at": "2023-04-05T19:19:23", "gha_language": "Boogie", "gha_license_id": "MIT", "github_id": 56342516, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3598, "license": "MIT", "license_type": "permissive", "path": "/test/old-regressions/c-smack/kernel-lists/test_list.c", "provenance": "stackv2-0132.json.gz:78986", "repo_name": "boogie-org/corral", "revision_date": "2023-03-22T17:19:12", "revision_id": "33dd98eed1e2d5087c7c5df9a782652772af2b2e", "snapshot_id": "9ffa0853725207a5c30a6c0c9bb98679326d1dab", "src_encoding": "UTF-8", "star_events_count": 57, "url": "https://raw.githubusercontent.com/boogie-org/corral/33dd98eed1e2d5087c7c5df9a782652772af2b2e/test/old-regressions/c-smack/kernel-lists/test_list.c", "visit_date": "2023-04-14T00:50:46.884451" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "list.h" struct kool_list{ int to; struct list_head list; int from; }; int main(int argc, char **argv){ struct kool_list *tmp; struct list_head *pos, *q; unsigned int i; struct kool_list mylist; INIT_LIST_HEAD(&mylist.list); /* or you could have declared this with the following macro * LIST_HEAD(mylist); which declares and initializes the list */ /* adding elements to mylist */ for(i=5; i!=0; --i){ tmp= (struct kool_list *)malloc(sizeof(struct kool_list)); /* INIT_LIST_HEAD(&tmp->list); * * this initializes a dynamically allocated list_head. we * you can omit this if subsequent call is add_list() or * anything along that line because the next, prev * fields get initialized in those functions. */ printf("enter to and from:"); scanf("%d %d", &tmp->to, &tmp->from); /* add the new item 'tmp' to the list of items in mylist */ list_add(&(tmp->list), &(mylist.list)); /* you can also use list_add_tail() which adds new items to * the tail end of the list */ } printf("\n"); /* now you have a circularly linked list of items of type struct kool_list. * now let us go through the items and print them out */ /* list_for_each() is a macro for a for loop. * first parameter is used as the counter in for loop. in other words, inside the * loop it points to the current item's list_head. * second parameter is the pointer to the list. it is not manipulated by the macro. */ printf("traversing the list using list_for_each()\n"); list_for_each(pos, &mylist.list){ /* at this point: pos->next points to the next item's 'list' variable and * pos->prev points to the previous item's 'list' variable. Here item is * of type struct kool_list. But we need to access the item itself not the * variable 'list' in the item! macro list_entry() does just that. See "How * does this work?" below for an explanation of how this is done. */ tmp= list_entry(pos, struct kool_list, list); /* given a pointer to struct list_head, type of data structure it is part of, * and it's name (struct list_head's name in the data structure) it returns a * pointer to the data structure in which the pointer is part of. * For example, in the above line list_entry() will return a pointer to the * struct kool_list item it is embedded in! */ printf("to= %d from= %d\n", tmp->to, tmp->from); } printf("\n"); /* since this is a circularly linked list. you can traverse the list in reverse order * as well. all you need to do is replace 'list_for_each' with 'list_for_each_prev' * everything else remain the same! * * Also you can traverse the list using list_for_each_entry() to iterate over a given * type of entries. For example: */ printf("traversing the list using list_for_each_entry()\n"); list_for_each_entry(tmp, &mylist.list, list) printf("to= %d from= %d\n", tmp->to, tmp->from); printf("\n"); /* now let's be good and free the kool_list items. since we will be removing items * off the list using list_del() we need to use a safer version of the list_for_each() * macro aptly named list_for_each_safe(). Note that you MUST use this macro if the loop * involves deletions of items (or moving items from one list to another). */ printf("deleting the list using list_for_each_safe()\n"); list_for_each_safe(pos, q, &mylist.list){ tmp= list_entry(pos, struct kool_list, list); printf("freeing item to= %d from= %d\n", tmp->to, tmp->from); list_del(pos); free(tmp); } return 0; }
3.578125
4
2024-11-18T22:28:27.414486+00:00
2023-08-15T21:20:57
daf01eb32cf20da91799066762f0fcbe826c79e4
{ "blob_id": "daf01eb32cf20da91799066762f0fcbe826c79e4", "branch_name": "refs/heads/master", "committer_date": "2023-08-15T21:20:57", "content_id": "c2128b42b8f1e051ff77f28973c9d3684734d4ea", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "06664ad86a2bedc77a538a97df92ceb2da1121a3", "extension": "c", "filename": "xdmf_output.c", "fork_events_count": 7, "gha_created_at": "2020-02-05T19:42:48", "gha_event_created_at": "2023-06-13T20:21:51", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 238533805, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9674, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/core/xdmf_output.c", "provenance": "stackv2-0132.json.gz:79117", "repo_name": "lanl/nubhlight", "revision_date": "2023-08-15T21:20:57", "revision_id": "59755b0d941aac1bcde40ddbf9cdd0b01500409e", "snapshot_id": "d3f90fa3d1871959524e449d4d7b36417b9f3f8d", "src_encoding": "UTF-8", "star_events_count": 25, "url": "https://raw.githubusercontent.com/lanl/nubhlight/59755b0d941aac1bcde40ddbf9cdd0b01500409e/core/xdmf_output.c", "visit_date": "2023-08-17T09:28:01.201679" }
stackv2
/****************************************************************************** * * * xdmf_output.c * * * * Write the metadata for xdmf for Visit * * * ******************************************************************************/ /* * For information on xdmf see: * http://www.xdmf.org/index.php/XDMF_Model_and_Format * and * https://www.visitusers.org/index.php?title=Using_XDMF_to_read_HDF5 * And this was a particularly useful example: * https://stackoverflow.com/questions/36718593/describing-5-dimensional-hdf5-matrix-with-xdmf * * Note that visit supports vectors and tensors... and in principle xdmf does * too however discussions online indicate that combining the two is dodgy, so I * treat everything as a scalar using hyperslabs ~JMM */ #include "decs.h" static int iX1_max; static char dname[STRLEN], gname[STRLEN], name[STRLEN], fname[STRLEN]; void geom_meta(FILE *fp); void coord_meta(FILE *fp, int indx); void prim_meta(FILE *fp, const char *vnams[NVAR], int indx); void scalar_meta( FILE *fp, const char *name, const char *sourcename, int precision); void vec_meta(FILE *fp, const char *name); void tensor_meta( FILE *fp, const char *name, const char *sourcename, int precision); void vec_component(FILE *fp, const char *name, int indx); void tensor_component(FILE *fp, const char *name, const char *sourcename, int precision, int mu, int nu); void write_xml_file(int dump_id, double t, const char *vnams[NVAR]) { // I know I don't need to do this every time... but it doesn't cost anything // ~JMM #if METRIC == MKS iX1_max = bl_i_of_r(Rout_vis); #else iX1_max = N1TOT; #endif // METRIC sprintf(dname, "../dump_%08d.h5", dump_id); sprintf(gname, "../grid.h5"); sprintf(fname, "dump_%08d.xmf", dump_id); strcpy(name, xmfdir); strcat(name, fname); int full_dump = (dump_id % DTf == 0); fprintf(stdout, "XMF %s\n", name); FILE *fp = fopen(name, "w"); // header fprintf(fp, "<?xml version=\"1.0\" ?>\n"); fprintf(fp, "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n"); fprintf(fp, "<Xdmf Version=\"3.0\">\n"); fprintf(fp, " <Domain>\n"); fprintf(fp, " <Grid Name=\"mesh\" GridType=\"Uniform\">\n"); fprintf(fp, " <Time Value=\"%16.14e\"/>\n", t); fprintf(fp, " <Topology TopologyType=\"3DSMesh\" NumberOfElements=\"%d %d " "%d\"/>\n", iX1_max + 1, N2TOT + 1, N3TOT + 1); geom_meta(fp); // Geometry fprintf(fp, "\n"); // Jacobians fprintf(fp, " <!-- JACOBIANS -->\n"); fprintf(fp, " <!-- contravariant -->\n"); tensor_meta(fp, "Lambda_h2cart_con", gname, 64); fprintf(fp, " <!-- covariant -->\n"); tensor_meta(fp, "Lambda_h2cart_cov", gname, 64); fprintf(fp, "\n"); // Metric fprintf(fp, " <!-- METRIC -->\n"); fprintf(fp, " <!-- contravariant -->\n"); tensor_meta(fp, "gcon", gname, 64); fprintf(fp, " <!-- covariant -->\n"); tensor_meta(fp, "gcov", gname, 64); fprintf(fp, " <!-- determinant -->\n"); scalar_meta(fp, "gdet", gname, 64); fprintf(fp, " <!-- lapse -->\n"); scalar_meta(fp, "alpha", gname, 64); fprintf(fp, "\n"); // Variables fprintf(fp, " <!-- PRIMITIVES -->\n"); PLOOP prim_meta(fp, vnams, ip); fprintf(fp, "\n"); if (full_dump) { fprintf(fp, " <!-- DERIVED VARS -->\n"); scalar_meta(fp, "divb", dname, 32); fprintf(fp, " <!-- jcon -->\n"); vec_meta(fp, "jcon"); #if OUTPUT_EOSVARS { scalar_meta(fp, "PRESS", dname, 32); scalar_meta(fp, "ENT", dname, 32); scalar_meta(fp, "TEMP", dname, 32); scalar_meta(fp, "CS2", dname, 32); } #endif #if ELECTRONS { scalar_meta(fp, "Qvisc", dname, 32); #if RADIATION { scalar_meta(fp, "Qcoul", dname, 32); } #endif // RADIATION } #endif // ELECTRONS #if RADIATION { scalar_meta(fp, "nph", dname, 32); fprintf(fp, " <!-- Jrad -->\n"); vec_meta(fp, "Jrad"); fprintf(fp, " <!-- Rmunu -->\n"); tensor_meta(fp, "Rmunu", dname, 32); } #endif // RADIATION } // footer fprintf(fp, " </Grid>\n"); fprintf(fp, " </Domain>\n"); fprintf(fp, "</Xdmf>\n"); fclose(fp); } void geom_meta(FILE *fp) { fprintf(fp, " <!-- GRID DEFINITION -->\n"); fprintf(fp, " <Geometry GeometryType=\"X_Y_Z\">\n"); for (int d = 1; d < NDIM; d++) coord_meta(fp, d); fprintf(fp, " </Geometry>\n"); } void vec_meta(FILE *fp, const char *name) { DLOOP1 vec_component(fp, name, mu); } void tensor_meta( FILE *fp, const char *name, const char *sourcename, int precision) { DLOOP2 tensor_component(fp, name, sourcename, precision, mu, nu); } void coord_meta(FILE *fp, int indx) { fprintf(fp, " <DataItem ItemType=\"Hyperslab\" Dimensions=\"%d %d %d\" " "Type=\"Hyperslab\">\n", iX1_max + 1, N2TOT + 1, N3TOT + 1); fprintf(fp, " <DataItem Dimensions=\"3 4\" Format=\"XML\">\n"); fprintf(fp, " 0 0 0 %d\n", indx); fprintf(fp, " 1 1 1 1\n"); fprintf(fp, " %d %d %d 1\n", iX1_max + 1, N2TOT + 1, N3TOT + 1); fprintf(fp, " </DataItem>\n"); fprintf(fp, " <DataItem Dimensions=\"%d %d %d %d\" NumberType=\"Float\" " "Precision=\"64\" Format=\"HDF\">\n", N1TOT + 1, N2TOT + 1, N3TOT + 1, NDIM); fprintf(fp, " %s:/XFcart\n", gname); fprintf(fp, " </DataItem>\n"); fprintf(fp, " </DataItem>\n"); } void prim_meta(FILE *fp, const char *vnams[NVAR], int indx) { fprintf(fp, " <Attribute Name=\"%s\" AttributeType=\"Scalar\" " "Center=\"Cell\">\n", vnams[indx]); fprintf(fp, " <DataItem ItemType=\"Hyperslab\" Dimensions=\"%d %d %d\" " "Type=\"Hyperslab\">\n", iX1_max, N2TOT, N3TOT); fprintf(fp, " <DataItem Dimensions=\"3 4\" Format=\"XML\">\n"); fprintf(fp, " 0 0 0 %d\n", indx); fprintf(fp, " 1 1 1 1\n"); fprintf(fp, " %d %d %d 1\n", iX1_max, N2TOT, N3TOT); fprintf(fp, " </DataItem>\n"); fprintf(fp, " <DataItem Dimensions=\"%d %d %d %d\" NumberType=\"Float\" " "Precision=\"32\" Format=\"HDF\">\n", N1TOT, N2TOT, N3TOT, NVAR); fprintf(fp, " %s:/P\n", dname); fprintf(fp, " </DataItem>\n"); fprintf(fp, " </DataItem>\n"); fprintf(fp, " </Attribute>\n"); } void scalar_meta( FILE *fp, const char *name, const char *sourcename, int precision) { fprintf(fp, " <Attribute Name=\"%s\" AttributeType=\"Scalar\" " "Center=\"Cell\">\n", name); fprintf(fp, " <DataItem ItemType=\"Hyperslab\" Dimensions=\"%d %d %d\" " "Type=\"Hyperslab\">\n", iX1_max, N2TOT, N3TOT); fprintf(fp, " <DataItem Dimensions=\"3 3\" Format=\"XML\">\n"); fprintf(fp, " 0 0 0\n"); fprintf(fp, " 1 1 1\n"); fprintf(fp, " %d %d %d\n", iX1_max, N2TOT, N3TOT); fprintf(fp, " </DataItem>\n"); fprintf(fp, " <DataItem Dimensions=\"%d %d %d\" NumberType=\"Float\" " "Precision=\"%d\" Format=\"HDF\">\n", N1TOT, N2TOT, N3TOT, precision); fprintf(fp, " %s:/%s\n", sourcename, name); fprintf(fp, " </DataItem>\n"); fprintf(fp, " </DataItem>\n"); fprintf(fp, " </Attribute>\n"); } void vec_component(FILE *fp, const char *name, int indx) { fprintf(fp, " <Attribute Name=\"%s_%d\" AttributeType=\"Scalar\" " "Center=\"Cell\">\n", name, indx); fprintf(fp, " <DataItem ItemType=\"Hyperslab\" Dimensions=\"%d %d %d\" " "Type=\"Hyperslab\">\n", iX1_max, N2TOT, N3TOT); fprintf(fp, " <DataItem Dimensions=\"3 4\" Format=\"XML\">\n"); fprintf(fp, " 0 0 0 %d\n", indx); fprintf(fp, " 1 1 1 1 \n"); fprintf(fp, " %d %d %d 1\n", iX1_max, N2TOT, N3TOT); fprintf(fp, " </DataItem>\n"); fprintf(fp, " <DataItem Dimensions=\"%d %d %d %d\" NumberType=\"Float\" " "Precision=\"32\" Format=\"HDF\">\n", N1TOT, N2TOT, N3TOT, NDIM); fprintf(fp, " %s:/%s\n", fname, name); fprintf(fp, " </DataItem>\n"); fprintf(fp, " </DataItem>\n"); fprintf(fp, " </Attribute>\n"); } void tensor_component(FILE *fp, const char *name, const char *sourcename, int precision, int mu, int nu) { fprintf(fp, " <Attribute Name=\"%s_%d%d\" AttributeType=\"Scalar\" " "Center=\"Cell\">\n", name, mu, nu); fprintf(fp, " <DataItem ItemType=\"Hyperslab\" Dimensions=\"%d %d %d\" " "Type=\"Hyperslab\">\n", iX1_max, N2TOT, N3TOT); fprintf(fp, " <DataItem Dimensions=\"3 5\" Format=\"XML\">\n"); fprintf(fp, " 0 0 0 %d %d\n", mu, nu); fprintf(fp, " 1 1 1 1 1\n"); fprintf(fp, " %d %d %d 1 1\n", iX1_max, N2TOT, N3TOT); fprintf(fp, " </DataItem>\n"); fprintf(fp, " <DataItem Dimensions=\"%d %d %d %d %d\" NumberType=\"Float\" " "Precision=\"%d\" Format=\"HDF\">\n", N1TOT, N2TOT, N3TOT, NDIM, NDIM, precision); fprintf(fp, " %s:/%s\n", sourcename, name); fprintf(fp, " </DataItem>\n"); fprintf(fp, " </DataItem>\n"); fprintf(fp, " </Attribute>\n"); }
2.03125
2
2024-11-18T22:28:27.513603+00:00
2021-07-04T12:39:45
879935c72956f1e74030433df0fad48b70c40ca5
{ "blob_id": "879935c72956f1e74030433df0fad48b70c40ca5", "branch_name": "refs/heads/master", "committer_date": "2021-07-04T12:39:45", "content_id": "ade19b90cd8dbb402b7205778d8829862a203efb", "detected_licenses": [ "MIT" ], "directory_id": "88a8c2fdd21c634881871b99f90e1866f324d92d", "extension": "c", "filename": "normalization.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 382848714, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2093, "license": "MIT", "license_type": "permissive", "path": "/src/normalization.c", "provenance": "stackv2-0132.json.gz:79246", "repo_name": "zaerl/mojibake", "revision_date": "2021-07-04T12:39:45", "revision_id": "d7f181292c063644aea163e3b6e4a72fd4ad354d", "snapshot_id": "50742e73bbf175d13d6212d7df39a5bf87b04620", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zaerl/mojibake/d7f181292c063644aea163e3b6e4a72fd4ad354d/src/normalization.c", "visit_date": "2023-06-08T09:39:47.818030" }
stackv2
/** * The mojibake library * * This file is distributed under the MIT License. See LICENSE for details. */ #include "array.h" #include "db.h" static size_t mjb_next_codepoint(void *buffer, size_t size, size_t index, mjb_encoding encoding, mjb_codepoint *codepoint) { /* if(encoding == MJB_ENCODING_UTF_32) { */ *codepoint = ((mjb_codepoint*)buffer)[index]; return index + 1; } /* Normalize a string */ MJB_EXPORT void *mjb_normalize(mojibake *mjb, void *source, size_t source_size, size_t *output_size, mjb_encoding encoding, mjb_normalization form) { if(!mjb_ready(mjb)) { return NULL; } if(source_size == 0) { return NULL; } if(form == MJB_ENCODING_UNKNOWN) { encoding = mjb_string_encoding(source, source_size); } if(encoding == MJB_ENCODING_UNKNOWN) { return NULL; } mjb_codepoint codepoint; size_t next = 0; size_t size = source_size; unsigned int i = 0; unsigned short combining = 0; bool starter = false; mjb_array array; *output_size = 0; /* Cycle the string */ do { next = mjb_next_codepoint(source, source_size, next, encoding, &codepoint); if(next > size) { /* ret = mjb_realloc(ret, size * realloc_step); ++realloc_step; */ break; } /* ASCII characters (U+0000..U+007F) are left unaffected by all of the Normalization Forms */ /* Latin-1 characters (U+0000..U+00FF) are unaffected by NFC */ if(codepoint <= 0x7F || (codepoint < 0xFF && form == MJB_NORMALIZATION_NFC)) { mjb_array_push(mjb, &array, (char*)&codepoint); ++i; } else { do { break; } while(1); /* The codepoint is a starter */ starter = combining == 0; /*ret = sqlite3_clear_bindings(mjb.decomposition_stmt); DB_CHECK(ret, false)*/ } /* ((mjb_codepoint*)ret)[i] = codepoint; */ } while(next < source_size); *output_size = i; return array.buffer; }
2.578125
3
2024-11-18T22:28:28.435863+00:00
2021-03-17T13:06:47
424c29b37c1a460602295e08a95af1d19db17e9f
{ "blob_id": "424c29b37c1a460602295e08a95af1d19db17e9f", "branch_name": "refs/heads/main", "committer_date": "2021-03-17T13:06:47", "content_id": "6c2327f1d08ddff5ccab0597a4428fd2891ea44a", "detected_licenses": [ "MIT" ], "directory_id": "d92af119d13b9af9afa3f6effa057c1f07cdb7c6", "extension": "h", "filename": "SimpleMath.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": 1122, "license": "MIT", "license_type": "permissive", "path": "/Project/Libs/TrinityEngine/SimpleMath.h", "provenance": "stackv2-0132.json.gz:79761", "repo_name": "fromasmtodisasm/Vivid3D", "revision_date": "2021-03-17T13:06:47", "revision_id": "66b429cae3290e1953552263e02b43a8c96f7bcb", "snapshot_id": "b0e89cd6ea859f579f9fae2b4cabcbebff3bacbc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fromasmtodisasm/Vivid3D/66b429cae3290e1953552263e02b43a8c96f7bcb/Project/Libs/TrinityEngine/SimpleMath.h", "visit_date": "2023-03-21T09:50:15.571173" }
stackv2
#pragma once #include "Vec2.h" #include <math.h> const float PI = 3.1415926535897932384626433; inline float degToRad(float v) { return (v * PI) / 180.0f; } inline float radToDeg(float v) { return(v * 180.0f) / PI; } inline Vec2 vecAdd(Vec2 p, float x, float y) { return Vec2(p.X + x, p.Y + y); } inline float area(int x1, int y1, int x2, int y2, int x3, int y3) { return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } inline bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y) { /* Calculate area of triangle ABC */ float A = area(x1, y1, x2, y2, x3, y3); /* Calculate area of triangle PBC */ float A1 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PAC */ float A2 = area(x1, y1, x, y, x3, y3); /* Calculate area of triangle PAB */ float A3 = area(x1, y1, x2, y2, x, y); /* Check if sum of A1, A2 and A3 is same as A */ return (A == A1 + A2 + A3); } inline Vec2 rotatePoint(Vec2 p, float angle) { angle = degToRad(angle); float s = sin(angle); float c = cos(angle); Vec2 np(p.X * c - p.Y * s,p.X * s + p.Y * c); return np; }
3.21875
3
2024-11-18T22:28:28.570679+00:00
2016-01-05T16:03:20
6d96b3b5c0c8166b06a644222985177960c4aec8
{ "blob_id": "6d96b3b5c0c8166b06a644222985177960c4aec8", "branch_name": "refs/heads/master", "committer_date": "2016-01-05T16:03:20", "content_id": "2f357e1341a194bb8c5ffa1eac2fd47d6fa56a02", "detected_licenses": [ "Unlicense" ], "directory_id": "1c0429419f41ef1f273c34ed15e0709d7b03b676", "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": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1641, "license": "Unlicense", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0132.json.gz:79891", "repo_name": "andrey-kun/FaNES-Example-2-Ride-Balls", "revision_date": "2016-01-05T16:03:20", "revision_id": "b5d83d7390dea2e631e0a99f089b5c8a4b164e0c", "snapshot_id": "333a7c99aa9ed1e747828b76e8081ca0f1c54062", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/andrey-kun/FaNES-Example-2-Ride-Balls/b5d83d7390dea2e631e0a99f089b5c8a4b164e0c/main.c", "visit_date": "2022-05-03T04:49:51.746321" }
stackv2
#include <FaNES.h> #define BALLS_MAX 64 const uchar paletteSprites[16] = { 0x0f,0x17,0x27,0x37, 0x0f,0x11,0x21,0x31, 0x0f,0x15,0x25,0x35, 0x0f,0x19,0x29,0x39 }; static uchar ballX[BALLS_MAX]; static uchar ballY[BALLS_MAX]; static uchar ballSpeedHorizontal[BALLS_MAX]; static uchar ballSpeedVertical[BALLS_MAX]; static uchar i = 0, x = 0, y = 0, h = 0, v = 0; void main() { uchar randomDirectionSeed; setPaletteColor(PALETTE_BACKGROUND_1 + 0, 0x0F); setPaletteSprites(paletteSprites); for (i = 0; i < BALLS_MAX; i++) { ballX[i] = getRandomUchar() % (256 - 8); ballY[i] = getRandomUchar() % (240 - 8); randomDirectionSeed = getRandomUchar(); ballSpeedHorizontal[i] = 1 + getRandomUchar() % 3; ballSpeedVertical[i] = 1 + getRandomUchar() % 3; ballSpeedHorizontal[i] = (randomDirectionSeed & 1) ? ballSpeedHorizontal[i] : -ballSpeedHorizontal[i]; ballSpeedVertical[i] = (randomDirectionSeed & 2) ? ballSpeedVertical[i] : -ballSpeedVertical[i]; newSprite(ballX[i], ballY[i], 0x0F, i & 3, i << 2); } onGraphics(); while(TRUE) { for (i = 0; i < BALLS_MAX; ++i) { x = ballX[i]; y = ballY[i]; h = ballSpeedHorizontal[i]; v = ballSpeedVertical[i]; setSpritePosition(x, y, i << 2); x += h; y += v; if (x >= (256 - 8)) h = -h; if (y >= (240 - 8)) v = -v; ballX[i] = x; ballY[i] = y; ballSpeedHorizontal[i] = h; ballSpeedVertical[i] = v; } waitFrame(); } }
2.3125
2
2024-11-18T22:28:28.842611+00:00
2018-11-27T23:24:43
9003b7b5fa93ca5f4eb287100f0d13d9baef3d93
{ "blob_id": "9003b7b5fa93ca5f4eb287100f0d13d9baef3d93", "branch_name": "refs/heads/master", "committer_date": "2018-11-27T23:24:43", "content_id": "05a34016c140cd4e324cd1fd7d5d183d4d8baed2", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "430bb02f6c685baf8fa67a81afdf004fa273f8d0", "extension": "c", "filename": "aniso_weights.c", "fork_events_count": 0, "gha_created_at": "2019-09-19T22:10:06", "gha_event_created_at": "2019-09-19T22:10:07", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 209656937, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12264, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/aniso_weights.c", "provenance": "stackv2-0132.json.gz:80154", "repo_name": "IMGamba/SpectralBTE", "revision_date": "2018-11-27T23:24:43", "revision_id": "c4f3c85218036d6d9abebf05bd87b486710f2e7a", "snapshot_id": "33e308982f6fd5255f6a7e1a38b5a734980ad9d2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/IMGamba/SpectralBTE/c4f3c85218036d6d9abebf05bd87b486710f2e7a/src/aniso_weights.c", "visit_date": "2020-07-29T03:45:29.667007" }
stackv2
#include <math.h> #include <omp.h> #include <stdio.h> #include <gsl/gsl_integration.h> #include <mpi.h> #include "aniso_weights.h" struct integration_args { double arg0; //zetalen double arg1; //xizeta/zetalen double arg2; //xiperp double arg3; //r double arg4; //cosphi double arg5; //sinphi double arg6; //r cosphi zetadot double arg7; //r cosphi 0.5 zetalen double arg8; //0.5 r zetalen sinphi double arg9; //cos(r cosphi zetadot) gsl_integration_cquad_workspace *w_th; gsl_function F_th; gsl_integration_workspace *w_ph; gsl_function F_ph; }; const double eightPi = 8.0/M_PI; static int N; static double *eta; static double L_v; static int weight_flag; static double glance; static int numNodes; static int rank; static gsl_integration_glfixed_table *GL_table; static double lambda; void initialize_weights_AnIso(int nodes, double *zeta, double Lv, double lam, int weightFlag, double **conv_weights, double glance) { N = nodes; eta = zeta; L_v = Lv; weight_flag = weightFlag; lambda = lam; GL_table = gsl_integration_glfixed_table_alloc(64); FILE *fidWeights; char buffer_weights[100]; char output_buffer[100]; int readFlag; MPI_Comm_size(MPI_COMM_WORLD,&numNodes); MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Status status; N = nodes; zeta = eta; L_v = Lv; int i,j; for(i=0;i<N*N*N;i++) { conv_weights[i] = malloc(N*N*N*sizeof(double)); } if(glance == 0) sprintf(buffer_weights,"Weights/N%d_Aniso_L_v%g_lambda%g_Landau.wts",N,L_v,lambda); else sprintf(buffer_weights,"Weights/N%d_AnIso_L_v%g_lambda%g_glance%g.wts",N,L_v,lambda,glance); if(weightFlag == 0) { //Check to see if the weights are there if((fidWeights = fopen(buffer_weights,"r"))) { printf("Loading weights from file %s\n",buffer_weights); for(i=0;i<N*N*N;i++) { readFlag = (int) fread(conv_weights[i],sizeof(double),N*N*N,fidWeights); if(readFlag != N*N*N) { printf("Error reading weight file\n"); exit(1); } } } else { printf("Stored weights not found for this configuration, generating ...\n"); generate_conv_weights_AnIso(conv_weights); MPI_Barrier(MPI_COMM_WORLD); //get weights from everyone else... if(rank == 0) { //dump the weights we've computed into a file fidWeights = fopen(buffer_weights,"w"); for(i=0;i<(N*N*N/numNodes);i++) { fwrite(conv_weights[i],sizeof(double),N*N*N,fidWeights); } //receive from all other processes for(i=1;i<numNodes;i++) { for(j=0;j<(N*N*N/numNodes);j++) { MPI_Recv(output_buffer,N*N*N,MPI_DOUBLE,i,j + i*N*N*N/numNodes,MPI_COMM_WORLD,&status); fwrite(output_buffer,sizeof(double),N*N*N,fidWeights); } } if(fflush(fidWeights) != 0) { printf("Something is wrong with storing the weights"); exit(0); } fclose(fidWeights); } else { for(i=0;i<N*N*N/numNodes;i++) MPI_Send(conv_weights[i],N*N*N,MPI_DOUBLE,0,rank*(N*N*N/numNodes)+i,MPI_COMM_WORLD); } } } else { //weights forced to be regenerated printf("Fresh version of weights being computed and stored for this configuration\n"); generate_conv_weights_AnIso(conv_weights); MPI_Barrier(MPI_COMM_WORLD); //get weights from everyone else... if(rank == 0) { //dump the weights we've computed into a file fidWeights = fopen(buffer_weights,"w"); for(i=0;i<(N*N*N/numNodes);i++) { fwrite(conv_weights[i],sizeof(double),N*N*N,fidWeights); } //receive from all other processes for(i=1;i<numNodes;i++) { for(j=0;j<(N*N*N/numNodes);j++) { MPI_Recv(output_buffer,N*N*N,MPI_DOUBLE,i,j + i*N*N*N/numNodes,MPI_COMM_WORLD,&status); fwrite(output_buffer,sizeof(double),N*N*N,fidWeights); } } if(fflush(fidWeights) != 0) { printf("Something is wrong with storing the weights"); exit(0); } fclose(fidWeights); } else { for(i=0;i<N*N*N/numNodes;i++) MPI_Send(conv_weights[i],N*N*N,MPI_DOUBLE,0,rank*(N*N*N/numNodes)+i,MPI_COMM_WORLD); } } printf("Finished with weights\n"); } double ghat_theta_AnIso(double theta, void* args) { struct integration_args intargs = *((struct integration_args *)args); //HARD SPHERES //gsl_integration_qag(&F_ph,0,M_PI,1e-2,1e-6,6,10000,w_ph,&result,&error); //return sin(theta)*(1.0/(4.0*M_PI))*result; //return sin(theta)*(1.0/(4.0*M_PI))*gauss_legendre(64,ghat_phi,dargs,0,M_PI); //printf("%g %g %g\n",intargs.arg0,intargs.arg1,intargs.arg2); /* Just to remind ourselves... double arg0; //zetalen double arg1; //xizeta/zetalen double arg2; //xiperp double arg3; //r double arg4; //cosphi double arg5; //sinphi double arg6; //r cosphi zetadot double arg7; //0.5 r cosphi zetalen double arg8; //0.5 r sinphi zetalen double arg9; //cos(r cosphi zetadot) */ //Linear convergence case //double bcos = eightPi*(glance/(theta*theta))*pow(theta,-2.0); //Coulomb case double bcos = (cos(0.5*theta)/pow(sin(0.5*theta),3) ) / (-M_PI*log(sin(0.5*glance))); return bcos*(cos(intargs.arg7*(1-cos(theta)) - intargs.arg6) * j0(intargs.arg8*sin(theta)) - intargs.arg9); } //Computes the Taylor expansion portion double ghat_theta2(double theta, void* args) { double *dargs = (double *)args; double r = dargs[0]; double cosphi = dargs[1]; double sinphi = dargs[2]; double zetalen = dargs[3]; double zetadot = dargs[4]; double c1 = 0.5*r*zetalen*cosphi; double c2 = 0.5*r*zetalen*sinphi; double c3 = r*zetadot*cosphi; return eightPi*( ((glance/theta)/theta)*(-0.25*c2*c2*cos(c3) + 0.5*c1*sin(c3))); //return (8.0/M_PI)*( ((glance/theta)/theta)*(-0.25*c2*c2*cos(c3) + 0.5*c1*sin(c3)) + (glance/192.0)*(-8.0*(3.0*c2*c2 +1)*c1*sin(c3) -24.0*c1*c1*cos(c3) + c2*c2*(3.0*c2 + 16.0)*cos(c3))); } double ghat_phi_AnIso(double phi, void* args) { struct integration_args intargs = *((struct integration_args *)args); double result1,result2; gsl_function F_th = intargs.F_th; double r = intargs.arg3; /* Just to remind ourselves... double arg0; //zetalen double arg1; //xizeta/zetalen double arg2; //xiperp double arg3; //r double arg4; //cosphi double arg5; //sinphi double arg6; //r cosphi zetadot double arg7; //0.5 r cosphi zetalen double arg8; //0.5 r sinphi zetalen double arg9; //cos(r cosphi zetadot) */ intargs.arg4 = cos(phi); intargs.arg5 = sin(phi); intargs.arg6 = r * intargs.arg4 * intargs.arg1; intargs.arg7 = 0.5 * r * intargs.arg4 * intargs.arg0; intargs.arg8 = 0.5 * r * intargs.arg5 * intargs.arg0; intargs.arg9 = cos(r * intargs.arg4 * intargs.arg1); F_th.params = &intargs; //F_th2.params = &thargs; gsl_integration_cquad(&F_th ,sqrt(glance),M_PI ,1e-6,1e-6,intargs.w_th,&result1,NULL,NULL); //"good" part //gsl_integration_qag(&F_th ,sqrt(glance),M_PI ,1e-6,1e-6,6,10000,intargs.w_th,&result1,&error); //"good" part //gsl_integration_cquad(&F_th2,glance ,sqrt(glance),1e-6,1e-6,w_th,&result2,NULL,NULL); //singular part //analytically solve the singular part with Taylor expansion double c1 = 0.5*r*intargs.arg0*intargs.arg4; double c2 = 0.5*r*intargs.arg0*intargs.arg5; double c3 = r*intargs.arg1*intargs.arg4; double C = (-0.25*c2*c2*cos(c3) + 0.5*c1*sin(c3)); //Linear case //result2 = C*eightPi*(1 - sqrt(glance)); //Coulomb case result2 = C/(2.0*M_PI); //gsl_integration_cquad_workspace_free(w_th); //gsl_integration_workspace_free(w_th); return intargs.arg5*j0(intargs.arg3*intargs.arg5*intargs.arg2)*(result1 + result2); } double ghat_r_AnIso(double r, void* args) { struct integration_args intargs = *((struct integration_args *)args); //double phargs[4]; double result, error; //gsl_integration_workspace *w_ph = gsl_integration_workspace_alloc(1000); gsl_function F_ph = intargs.F_ph; /* phargs[0] = dargs[0]; //zetalen phargs[1] = dargs[1]; //xizeta/zetalen phargs[2] = dargs[2]; //xiperp phargs[3] = r; */ intargs.arg3 = r; F_ph.params = &intargs; gsl_integration_qag(&F_ph,0,M_PI,1e-6,1e-6,6,1000,intargs.w_ph,&result,&error); //gsl_integration_workspace_free(w_ph); return pow(r,lambda+2)*result; } /* function gHat3 -------------- computes integral for each convolution weight using gauss-legendre quadrature inputs ki, eta: wavenumbers for the convolution weight */ double gHat3_AnIso(double zeta1, double zeta2, double zeta3, double xi1, double xi2, double xi3) { double result, error; //double args[3]; gsl_integration_workspace *w_r = gsl_integration_workspace_alloc(1000); gsl_function F_r, F_th, F_ph; F_r.function = &ghat_r_AnIso; F_th.function = &ghat_theta_AnIso; F_ph.function = &ghat_phi_AnIso; /* w_th = gsl_integration_cquad_workspace_alloc(10000); F_th.function = &ghat_theta; F_th2.function = &ghat_theta2; w_ph = gsl_integration_workspace_alloc(10000); F_ph.function = &ghat_phi; */ struct integration_args intargs; double zetalen2 = zeta1*zeta1 + zeta2*zeta2 + zeta3*zeta3; double xilen2 = xi1*xi1 + xi2*xi2 + xi3*xi3; double xizeta = xi1*zeta1 + xi2*zeta2 + xi3*zeta3; double zetalen = sqrt(zetalen2); double xiperp; if( ((xilen2 - xizeta*xizeta/zetalen2) < 0) || (zetalen2 == 0)) xiperp = 0; else xiperp = sqrt( xilen2 - xizeta*xizeta/zetalen2); //args[0] = zetalen; //args[1] = xizeta/zetalen; //args[2] = xiperp; intargs.arg0 = zetalen; if(zetalen != 0) intargs.arg1 = xizeta/zetalen; else intargs.arg1 = 0.0; intargs.arg2 = xiperp; intargs.w_th = gsl_integration_cquad_workspace_alloc(1000); intargs.F_th = F_th; intargs.w_ph = gsl_integration_workspace_alloc(1000); intargs.F_ph = F_ph; //printf("%g %g %g\n",zetalen,xizeta/zetalen,xiperp); //result = 4.0*M_PI*M_PI*gauss_legendre(GL, ghat_r, args, 0, L_v); F_r.params = &intargs; gsl_integration_qag(&F_r,0,L_v,1e-6,1e-6,6,1000,w_r,&result,&error); gsl_integration_workspace_free(w_r); gsl_integration_cquad_workspace_free(intargs.w_th); gsl_integration_workspace_free(intargs.w_ph); return 4*M_PI*M_PI*result; } double ghatL2(double theta, void* args) { double *dargs = (double *)args; double r = dargs[4]; return sin(theta)*j0(r*dargs[0]*sin(theta))*(-r*r*dargs[1]*sin(theta)*sin(theta)*cos(r*dargs[2]*cos(theta)) + 4*r*dargs[3]*sin(r*dargs[2]*cos(theta))*cos(theta)); } double ghatL(double r, void* args) { double *dargs = (double *)args; dargs[4] = r; gsl_function F_2; F_2.function = ghatL2; F_2.params = dargs; return pow(r,lambda+2)*gsl_integration_glfixed(&F_2,0,M_PI,GL_table); } double gHat3L(double zeta1, double zeta2, double zeta3, double xi1, double xi2, double xi3) { double result = 0.0; double args[5]; double zetalen2 = zeta3*zeta3 + zeta2*zeta2 + zeta1*zeta1; double xilen2 = xi1*xi1 + xi2*xi2 + xi3*xi3; double xizeta = xi1*zeta1 + xi2*zeta2 + xi3*zeta3; double zetalen = sqrt(zetalen2); double xiperp; if( ((xilen2 - xizeta*xizeta/zetalen2) < 0) || (zetalen2 == 0)) xiperp = 0; else xiperp = sqrt( xilen2 - xizeta*xizeta/zetalen2); args[0] = xiperp; args[1] = zetalen2; if(zetalen != 0) args[2] = xizeta/zetalen; else args[2] = 0.0; args[3] = zetalen; gsl_function F_ghat; F_ghat.function = ghatL; F_ghat.params = args; result = 2.0*M_PI*gsl_integration_glfixed(&F_ghat,0,L_v,GL_table); return result; } //this generates the convolution weights G_hat(zeta,xi) void generate_conv_weights_AnIso(double **conv_weights) { int i, j, k, l, m, n, z; //zeta iteration #pragma omp parallel for private(i,j,k,l,m,n,z) for(z=rank*(N*N*N/numNodes);z<(rank+1)*(N*N*N/numNodes);z++) { k = z % N; j = ((z-k)/N) % N; i = (z - k - N*j)/(N*N); //xi iteration for(l=0;l<N;l++) for(m=0;m<N;m++) { for(n=0;n<N;n++) { if(glance == 0) conv_weights[z%(N*N*N/numNodes)][n + N*(m + N*l)] = gHat3L(eta[i], eta[j], eta[k],eta[l], eta[m], eta[n]); else conv_weights[z%(N*N*N/numNodes)][n + N*(m + N*l)] = gHat3_AnIso(eta[i], eta[j], eta[k],eta[l], eta[m], eta[n]); //if(isnan(conv_weights[z%(N*N*N/numNodes)][n + N*(m + N*l)])) //printf("%g %g %g %g %g %g\n",eta[i],eta[j],eta[k],eta[l],eta[m],eta[n]); } } } }
2.25
2
2024-11-18T22:28:29.056941+00:00
2015-05-24T10:02:30
5e12cddb9921d7917d9c1a3eb736e7ae0d95e859
{ "blob_id": "5e12cddb9921d7917d9c1a3eb736e7ae0d95e859", "branch_name": "refs/heads/master", "committer_date": "2015-05-24T10:02:30", "content_id": "a74e825f9277f1e705b2e0cb93cc66d4fe345bd6", "detected_licenses": [ "MIT", "BSD-2-Clause" ], "directory_id": "e999151a74f8547334db0072332c0bb8772f5401", "extension": "c", "filename": "fastlzcat.c", "fork_events_count": 4, "gha_created_at": "2013-03-18T12:57:01", "gha_event_created_at": "2013-11-27T09:21:27", "gha_language": "Shell", "gha_license_id": null, "github_id": 8854157, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11689, "license": "MIT,BSD-2-Clause", "license_type": "permissive", "path": "/fastlzcat.c", "provenance": "stackv2-0132.json.gz:80541", "repo_name": "bareos/fastlzlib", "revision_date": "2015-05-24T10:02:30", "revision_id": "35ffa7b1f6ba11f5bda6930acc4200c45aa30662", "snapshot_id": "b76a3ad1b2cf39bf9a7d4f04de26169426a43f4f", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/bareos/fastlzlib/35ffa7b1f6ba11f5bda6930acc4200c45aa30662/fastlzcat.c", "visit_date": "2020-04-02T23:24:41.355332" }
stackv2
/* zlib-like interface to fast block compression (LZ4 or FastLZ) libraries Copyright (C) 2010-2013 Exalead SA. (http://www.exalead.com/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Remarks/Bugs: LZ4 compression library by Yann Collet ([email protected]) FastLZ compression library by Ariya Hidayat ([email protected]) Library encapsulation by Xavier Roche ([email protected]) */ /* compress or uncompress streams */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "fastlzlib.h" static void usage(char *arg0) { fprintf(stderr, "%s, FastLZ compression/decompression tool.\n" "Usage: %s (filename|-) (filename ..)\t#input filename(s) or stdin\n" "\t[--output (filename|-)]\t#output filename or stdout\n" "\t[--compress|--decompress]\t#mode\n" "\t[--lz4|--fastlz]\t#compression type\n" "\t[--fast|--normal]\t#compression speed\n" "\t[--inbufsize n]\t#input buffer size (262144)\n" "\t[--outbufsize n]\t#output buffer size (1048576)\n" "\t[--blocksize n]\t#block stream size (1048576)\n" "\t[--flush]\t#flush uncompressed data regularly\n" , arg0, arg0); } static void error(const char *msg) { fprintf(stderr, "%s\n", msg); exit(EXIT_FAILURE); } static void syserror(const char *msg) { const int e = errno; fprintf(stderr, "%s: %s\n", msg, strerror(e)); exit(EXIT_FAILURE); } static void flzerror(zfast_stream *s, const char *msg) { fprintf(stderr, "%s: %s\n", msg, s->msg != NULL ? s->msg : "unknown error"); exit(EXIT_FAILURE); } int main(int argc, char **argv) { int *files = malloc(sizeof(int) * argc); int nfiles = 0; const char *output = NULL; int compress = 0; int list = 0; int flush = 0; zfast_stream_compressor type = COMPRESSOR_FASTLZ; int perfs = 2; uInt block_size = 262144; uInt inbufsize = 1048576; uInt outbufsize = 1048576; int i; /* process args */ for(i = 1 ; i < argc ; i++) { if (strcmp(argv[i], "--compress") == 0) { compress = 1; } else if (strcmp(argv[i], "--decompress") == 0 || strcmp(argv[i], "--uncompress") == 0 || strcmp(argv[i], "-d") == 0) { compress = 0; } else if (strcmp(argv[i], "--list") == 0 || strcmp(argv[i], "-l") == 0) { list = 1; } else if (strcmp(argv[i], "--flush") == 0) { flush = 1; } else if (strcmp(argv[i], "--lz4") == 0) { type = COMPRESSOR_LZ4; } else if (strcmp(argv[i], "--fastlz") == 0) { type = COMPRESSOR_FASTLZ; } else if (strcmp(argv[i], "--fast") == 0) { perfs = 1; } else if (strcmp(argv[i], "--normal") == 0) { perfs = 2; } else if (i + 1 < argc && strcmp(argv[i], "--inbufsize") == 0) { int size; if (sscanf(argv[i + 1], "%d", &size) == 1) { inbufsize = size; } else { error("invalid size"); } i++; } else if (i + 1 < argc && strcmp(argv[i], "--outbufsize") == 0) { int size; if (sscanf(argv[i + 1], "%d", &size) == 1) { outbufsize = size; } else { error("invalid size"); } i++; } else if (i + 1 < argc && strcmp(argv[i], "--blocksize") == 0) { int size; if (sscanf(argv[i + 1], "%d", &size) == 1) { block_size = size; } else { error("invalid size"); } i++; } else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--stdout") == 0 || strcmp(argv[i], "--to-stdout") == 0) { output = "-"; } else if (i + 1 < argc && strcmp(argv[i], "--output") == 0) { output = argv[i + 1]; i++; } else if (i + 1 < argc && strcmp(argv[i], "--input") == 0) { files[nfiles++] = i; } else if (argv[i][0] == '-' && ( argv[i][1] >= '0' && argv[i][1] <= '9' ) && argv[i][2] == '\0' ) { int level = argv[i][1] - '0'; perfs = level >= 2 ? 2 : 1; error("invalid option"); } else if (argv[i][0] == '-' && argv[i][1] == '-') { error("invalid option"); } else { files[nfiles++] = i; } } /* list mode: only read headers */ if (list) { inbufsize = fastlzlibGetHeaderSize(); output = NULL; } /* rock'in */ if (nfiles != 0) { FILE *outstream = NULL; int closeoutstream = 0; Bytef *buf = malloc(inbufsize); Bytef *dest = malloc(outbufsize); int i; zfast_stream stream; memset(&stream, 0, sizeof(stream)); if (compress) { if (fastlzlibCompressInit2(&stream, perfs, block_size) != Z_OK) { flzerror(&stream, "unable to initialize the compressor"); } } else { if (fastlzlibDecompressInit2(&stream, block_size) != Z_OK) { flzerror(&stream, "unable to initialize the uncompressor"); } } if (fastlzlibSetCompressor(&stream, type) != Z_OK) { flzerror(&stream, "unable to initialize the specified compressor"); } if (output != NULL) { if (strcmp(output, "-") == 0) { outstream = stdout; closeoutstream = 0; } else { outstream = fopen(output, "wb"); if (outstream == NULL) { syserror("can not open output file"); } closeoutstream = 1; } } for(i = 0 ; i < nfiles ; i++, fastlzlibReset(&stream), stream.total_in = stream.total_out = 0) { FILE *instream; int closeinstream; const char*const filename = argv[files[i]]; uLong total_out = 0; uLong total_in = 0; if (strcmp(filename, "-") == 0) { instream = stdin; closeinstream = 0; } else { instream = fopen(filename, "rb"); if (instream == NULL) { syserror("can not open input file"); } closeinstream = 1; } if (instream != NULL) { while(!feof(instream)) { int n = fread(buf, 1, inbufsize, instream); const int is_eof = feof(instream); if (n >= 0) { /* list mode (scan stream without reading/processing) */ if (list) { /* next block */ uInt compressed_size; uInt uncompressed_size; if (n != (int) inbufsize) { error("truncated input"); } if (fastlzlibGetStreamInfo(buf, n, &compressed_size, &uncompressed_size) != Z_OK) { error("stream read error"); } fprintf(stdout, "%s block at %u ([%u .. %u[):" "\tcompressed=%u\tuncompressed=%u" "\t[block_size=%u]\n", compressed_size != uncompressed_size ? "compressed" : "uncompressed", (int) total_in, (int) total_out, (int) ( total_out + uncompressed_size ), (int) compressed_size, (int) uncompressed_size, fastlzlibGetStreamBlockSize(buf, n)); /* check eof consistency */ if (compressed_size == 0 && uncompressed_size == 0) { int n = fread(buf, 1, 1, instream); const int is_eof = feof(instream); if (n != 0 || !is_eof) { error("premature EOF before end of stream"); } } else if (is_eof) { error("premature end of stream"); } /* skip compressed data */ if (fseek(instream, compressed_size, SEEK_CUR) != 0) { if (errno == EBADF) { /* fseek() on stdin */ int skip, n; for(skip = compressed_size ; skip > 0 && ( n = fread(dest, 1, outbufsize, instream) ) > 0 ; skip -= n) ; if (skip != 0) { syserror("seek error"); } } else { syserror("seek error"); } } total_in += n + compressed_size; total_out += uncompressed_size; } /* compress/uncompress mode */ else { int success; stream.next_in = buf; stream.avail_in = n; do { stream.next_out = dest; stream.avail_out = outbufsize; if (compress) { success = fastlzlibCompress(&stream, is_eof ? Z_FINISH : ( flush ? Z_SYNC_FLUSH : Z_NO_FLUSH ) ); } else { success = fastlzlibDecompress(&stream); } if (success == Z_STREAM_END) { if (stream.avail_in > 0 || !is_eof) { error("premature EOF before end of stream"); } } if (outstream != NULL && stream.next_out != dest) { const size_t len = stream.next_out - dest; if (len > 0) { if (fwrite(dest, 1, len, outstream) != len || ( flush && fflush(outstream) != 0 ) ) { syserror("write error"); } } } } while(success == Z_OK); /* Z_BUF_ERROR means that we need to feed more */ if (success == Z_BUF_ERROR) { if (is_eof && stream.avail_out != 0) { error("premature end of stream"); } } else if (success < 0) { flzerror(&stream, "stream error"); } } } else if (n < 0) { syserror("read error"); } } if (closeinstream && instream != NULL) { fclose(instream); } } else { syserror("can not open file"); } } /* cleanup */ if (closeoutstream && outstream != NULL) { fclose(outstream); } fastlzlibEnd(&stream); free(buf); free(dest); } else { usage(argv[0]); return EXIT_FAILURE; } free(files); return EXIT_SUCCESS; }
2.171875
2
2024-11-18T22:28:29.913289+00:00
2020-01-30T15:52:16
46fa8f4b07cf5594dce57267723c4b7c89e24951
{ "blob_id": "46fa8f4b07cf5594dce57267723c4b7c89e24951", "branch_name": "refs/heads/master", "committer_date": "2020-01-30T15:52:16", "content_id": "38761ad110c461b30e082ea2bc4f523e0dddbdad", "detected_licenses": [ "MIT" ], "directory_id": "40de3da30239862f11a946166b50438174c2fd4e", "extension": "c", "filename": "mist2.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": 1649, "license": "MIT", "license_type": "permissive", "path": "/lib/wizards/aarrgh/nyxi/mist2.c", "provenance": "stackv2-0132.json.gz:80800", "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/aarrgh/nyxi/mist2.c", "visit_date": "2020-12-23T19:59:44.886028" }
stackv2
inherit "room/room"; reset(arg) { set_light(1); set_not_out(1); add_exit("out", "/wizards/aarrgh/nyxi/mist.c"); short_desc = "Inside a dusty tomb"; long_desc = "This is a dark tomb with few gothic style windows on each wall. This room is\n" "much darker than outside. A dusty tombstone lies in thecenter of this ancient\n" "tomb and it seems to be ancient and covered with dust.\n"; items = allocate(4); items[0] = "tombstone"; items[1] = "This tombstone is covered with ancient runes. The tombstone seems to hold something inside"; } init() { ::init(); add_action("open1", "open"); } int check; open1(str) { object skeletoni; if(str != "tombstone" ) { write("open what?\n"); return 1; } skeletoni = clone_object("/wizards/aarrgh/nyxi/mon/skelppari"); if(str == "tombstone" && check == 1 ) { write("The tombstone is already empty.\n"); return 1; } if(str == "tombstone" && present("skeleton", environment(this_player() ))) { write("The monster is present.\n"); return 1; } if(str == "tombstone" && check != 1 && !present("skeleton", environment(this_player() ))) { write("You have waken the demonic skeleton!\n"); say(this_player()->query_name()+" opens the tomb and the skeleton raises on its feet.\n"); this_player()->set_quest("Wake the mystical skeleton", 2);// call_other("/wizards/aarrgh/nyxi/mist.c", move_object(skeletoni, environment(this_player() )); tell_room("/wizards/aarrgh/nyxi/mist.c", "The demonic skeleton is awakened!\n"); check = 1; return 1; } }
2.140625
2
2024-11-18T22:28:30.665667+00:00
2023-07-17T16:32:04
f663db739b5862635ec68f21b462cadd11c9b5da
{ "blob_id": "f663db739b5862635ec68f21b462cadd11c9b5da", "branch_name": "refs/heads/master", "committer_date": "2023-07-17T16:32:04", "content_id": "e3dc4135abdeb3a41bce21a9d1c5e45fe17bf41f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1db673907c7946c2ea857cc9aa8b6f7f4060e36a", "extension": "c", "filename": "setjmp.c", "fork_events_count": 49, "gha_created_at": "2017-07-12T16:23:01", "gha_event_created_at": "2023-04-30T15:33:47", "gha_language": "C", "gha_license_id": null, "github_id": 97029119, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3110, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/CommonLib/CPlusPlus/setjmp.c", "provenance": "stackv2-0132.json.gz:81058", "repo_name": "pdpdds/SkyOS", "revision_date": "2023-07-17T16:32:04", "revision_id": "db2ce044c581fc2dfe068723fb0be2336c7f18d9", "snapshot_id": "a973cd9f1b4e541ae4ac26d19df29aa3f4110db3", "src_encoding": "UTF-8", "star_events_count": 160, "url": "https://raw.githubusercontent.com/pdpdds/SkyOS/db2ce044c581fc2dfe068723fb0be2336c7f18d9/CommonLib/CPlusPlus/setjmp.c", "visit_date": "2023-07-21T15:24:46.457637" }
stackv2
// // setjmp.c // // Non-local goto // // Copyright (C) 2002 Michael Ringgaard. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the project nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. // #include <signal.h> #include <setjmp.h> #define OFS_EBP 0 #define OFS_EBX 4 #define OFS_EDI 8 #define OFS_ESI 12 #define OFS_ESP 16 #define OFS_EIP 20 __declspec(naked) int setjmp(jmp_buf env) { __asm { mov edx, 4[esp] // Get jmp_buf pointer mov eax, [esp] // Save EIP mov OFS_EIP[edx], eax mov OFS_EBP[edx], ebp // Save EBP, EBX, EDI, ESI, and ESP mov OFS_EBX[edx], ebx mov OFS_EDI[edx], edi mov OFS_ESI[edx], esi mov OFS_ESP[edx], esp xor eax, eax // Return 0 ret } } __declspec(naked) void longjmp(jmp_buf env, int value) { __asm { mov edx, 4[esp] // Get jmp_buf pointer mov eax, 8[esp] // Get return value (eax) mov esp, OFS_ESP[edx] // Switch to new stack position mov ebx, OFS_EIP[edx] // Get new EIP value and set as return address mov [esp], ebx mov ebp, OFS_EBP[edx] // Restore EBP, EBX, EDI, and ESI mov ebx, OFS_EBX[edx] mov edi, OFS_EDI[edx] mov esi, OFS_ESI[edx] ret } } /* int sigsetjmp(sigjmp_buf env, int savesigs) { if (savesigs) { sigprocmask(SIG_BLOCK, NULL, &env->sigmask); } else { env->sigmask = -1; } return setjmp(env->env); } void siglongjmp(sigjmp_buf env, int value) { if (env->sigmask != -1) { sigprocmask(SIG_SETMASK, &env->sigmask, NULL); } longjmp(env->env, value); } */
2.03125
2
2024-11-18T22:28:31.220947+00:00
2013-09-02T06:10:27
e7d52a1d4b9c4b1546378f208dd8c75b198c621b
{ "blob_id": "e7d52a1d4b9c4b1546378f208dd8c75b198c621b", "branch_name": "refs/heads/master", "committer_date": "2013-09-02T06:10:27", "content_id": "2d5322a0bb2e1fda58a6f572289dfecf50269cb4", "detected_licenses": [ "MIT" ], "directory_id": "493a895660368bd9d092c39b80be24faf8f2b801", "extension": "c", "filename": "lista.c", "fork_events_count": 1, "gha_created_at": "2013-05-21T02:06:11", "gha_event_created_at": "2013-06-01T04:16:20", "gha_language": "C", "gha_license_id": null, "github_id": 10185947, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1490, "license": "MIT", "license_type": "permissive", "path": "/lista/lista.c", "provenance": "stackv2-0132.json.gz:81572", "repo_name": "Sirquini/C-TADs", "revision_date": "2013-09-02T06:10:27", "revision_id": "f0e7ecca7fa4146a0cdb09c853b3e53d85a03f66", "snapshot_id": "09771e02f581c90103f9df00bd02a481f5d2a472", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Sirquini/C-TADs/f0e7ecca7fa4146a0cdb09c853b3e53d85a03f66/lista/lista.c", "visit_date": "2021-01-01T15:50:16.600380" }
stackv2
#include <stdlib.h> #include "lista.h" Lista crearLista(void) { Lista l = NULL; return l; } Lista anxLista(Lista l, lElement d) { Lista nueva, tmp; nueva = (Lista) malloc(sizeof(struct node)); nueva -> data = d; nueva -> sig = NULL; if (vaciaLista(l)) l = nueva; else { tmp = l; while(tmp->sig != NULL) { tmp = tmp -> sig; } tmp -> sig = nueva; } return l; } Lista insLista(Lista l, lElement d, int pos) { Lista nuevo, tmp, tmp2; int i; nuevo = (Lista)malloc(sizeof(struct node)); nuevo -> data = d; nuevo -> sig = NULL; if (pos == 1) { nuevo -> sig = l; l = nuevo; } else { tmp = tmp2 = l; for (i = 0; i < pos - 2; ++i) { tmp = tmp -> sig; } tmp2 = tmp -> sig; tmp -> sig = nuevo; nuevo -> sig = tmp2; } return l; } Lista elimLista(Lista l, int pos) { Lista tmp, tmp2; int i; tmp = tmp2 = l; if (pos == 1) l = l -> sig; else { for (i = 0; i < pos - 2; ++i) { tmp = tmp -> sig; } tmp2 = tmp -> sig; tmp -> sig = tmp2 -> sig; } tmp2 -> sig = NULL; free(tmp2); return l; } lElement infoLista(Lista l, int pos) { int i; Lista tmp = l; for (i = 1; i < pos; ++i) tmp = tmp -> sig; return tmp -> data; } int longLista(Lista l) { unsigned int i; Lista tmp = l; for (i = 0; tmp != NULL ; ++i) tmp = tmp -> sig; return i; } int vaciaLista(Lista l) { return (l == NULL) ? 1 : 0; } void destruirLista(Lista l) { Lista tmp; while(l != NULL) { tmp = l; l = l -> sig; free(tmp); } }
3.21875
3
2024-11-18T22:28:31.278467+00:00
2023-06-15T22:44:18
81580b795b54f9ea96a8097cbe64c75fa3d2104e
{ "blob_id": "81580b795b54f9ea96a8097cbe64c75fa3d2104e", "branch_name": "refs/heads/master", "committer_date": "2023-06-15T22:44:18", "content_id": "0095f1423774c58e42fc22f12f31d4ccd5e0d1fb", "detected_licenses": [ "MIT" ], "directory_id": "9b84e8426b477f702441b51a91aebbd8f61cbb5c", "extension": "c", "filename": "TICC_calc.c", "fork_events_count": 22, "gha_created_at": "2016-03-26T14:41:40", "gha_event_created_at": "2020-09-08T15:27:39", "gha_language": "C", "gha_license_id": "MIT", "github_id": 54783260, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2457, "license": "MIT", "license_type": "permissive", "path": "/example_code/TICC_calc.c", "provenance": "stackv2-0132.json.gz:81701", "repo_name": "TAPR/TICC", "revision_date": "2023-06-15T22:44:18", "revision_id": "e5a1912ef8f87870640850e5cd63ec1b30af597e", "snapshot_id": "53bb4a55106a576b5556b5df697b30dc39ee683e", "src_encoding": "UTF-8", "star_events_count": 33, "url": "https://raw.githubusercontent.com/TAPR/TICC/e5a1912ef8f87870640850e5cd63ec1b30af597e/example_code/TICC_calc.c", "visit_date": "2023-06-22T06:08:28.335594" }
stackv2
// Routine to calculate TDC7200 results using integer math. Many thanks // to "BigBobby" of the Programming Questions board at forum.arduino.cc // Initial version -- 27 March 2016 #include <stdint.h> // define unint16_t, uint32_t #define PS_PER_SEC (1e12) // ps/s #define CLOCK_FREQ (1e8) // Hz #define CLOCK_PERIOD_PS (uint32_t)(PS_PER_SEC/CLOCK_FREQ) // ps #define CALIBRATION2_PERIODS 10 // Can only be 2, 10, 20, or 40. uint16_t CALIBRATION2 = 1; uint16_t CALIBRATION1 = 2; uint16_t TIME1 = 3; uint16_t TIME2 = 4; uint32_t CLOCK_COUNT1 = 5; void dummy_function_name() { // Calculation from 8.4.2.2.1 of datasheet. // These registers are 23 bits, but in example never // got larger than 16bit when CALIBRATION_PERIODS = 10. CALIBRATION2 = 23133; CALIBRATION1 = 2315; // These registers are 23 bits, but in example never // got larger than 16bit. // If I understand their example correctly, // they should never be larger than that in your // application either. TIME1 = 2147; TIME2 = 201; // This register is 23 bits, and but in example neveri // got larger than 16bit. // If I understand their example correctly, // I think it will be >16 bits in your case. // CLOCK_COUNT1 = 3814; // Datasheet said 39.855us // results in 3814 count. If 39.855us results in 3814, // then 1ms should result in proportionally more. CLOCK_COUNT1 = (uint32_t)(1.0F * 3814*1000000/39855 + 0.5); uint32_t calc_time; uint16_t tempu16; uint32_t tempu32; // Perform calculation while measuring the calculation time. calc_time = micros(); // since TIME1 will always be > TIME2, this is still 16 bit. tempu16 = (TIME1 - TIME2); // After multiplying by the constants, you will now be a 32 bit number. tempu32 = tempu16 * (CLOCK_PERIOD_PS * (CALIBRATION2_PERIODS-1)); // This division sort of sucks, but since I assume these must be // variables there's no way around it. tempu32 = (tempu32 + ((CALIBRATION2 - CALIBRATION1 + 1) >> 1)) / (CALIBRATION2 - CALIBRATION1); // Add in another 32bit variable. Given the limitations on // inputs, these two 32 bits still won't overflow. tempu32 += CLOCK_COUNT1 * CLOCK_PERIOD_PS; // Calculate the time it took for function. calc_time = micros() - calc_time; LT_printf(F("calculated %lu in %lu us\r\n"), tempu32, calc_time); }
2.828125
3
2024-11-18T22:28:31.486317+00:00
2021-10-03T16:51:34
73af7ecbefcf26e7ba9354b3fb1efe473f1ff595
{ "blob_id": "73af7ecbefcf26e7ba9354b3fb1efe473f1ff595", "branch_name": "refs/heads/main", "committer_date": "2021-10-03T16:51:34", "content_id": "4e859f5b5704703930874cb1496415592c7ca2f2", "detected_licenses": [ "MIT" ], "directory_id": "ed5e239442a1c2dfcfc2ab91c4ca1b424ebb4f2a", "extension": "h", "filename": "hashtab.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 413132704, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4183, "license": "MIT", "license_type": "permissive", "path": "/include/coxeter/hashtab.h", "provenance": "stackv2-0132.json.gz:81958", "repo_name": "iclue-summer-2020/coxeter", "revision_date": "2021-10-03T16:51:34", "revision_id": "4d8f2ab271387db6550880a6b9bb64b6b2118477", "snapshot_id": "35ef56b9ad65686c95779ac21bcf3145610f8cd1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iclue-summer-2020/coxeter/4d8f2ab271387db6550880a6b9bb64b6b2118477/include/coxeter/hashtab.h", "visit_date": "2023-08-29T09:24:46.233083" }
stackv2
#ifndef _HASHTAB_H #define _HASHTAB_H #include <stdio.h> #include <stdlib.h> #ifndef _HASHKEY_T #define _HASHKEY_T typedef unsigned long hashkey_t; /* should be 32 bit */ typedef int (*cmp_t) (void *, void *); /* return 0 if equal */ typedef hashkey_t (*hash_t) (void *); #endif typedef struct { int card; cmp_t cmp; hash_t hash; size_t table_sz; size_t *table; size_t elts_sz; struct _hashelt *elts; size_t free_elts; } hashtab; struct _hashelt { size_t next; hashkey_t hkey; void *key; int value; }; #define _S_END ((size_t) -1) #define USE_FAC 2 #define INIT_TABSZ 2003 #define INIT_ELTSZ 100 #define hash_card(s) ((s)->card) #define hash_cmp(s) ((s)->cmp) #define hash_hash(s) ((s)->hash) #define hash_tabsz(s) ((s)->table_sz) #define hash_table(s) ((s)->table) #define hash_eltsz(s) ((s)->elts_sz) #define hash_elts(s) ((s)->elts) extern int hash_key_used; extern void *hash_removed_key; hashtab *hash_new(cmp_t cm, hash_t hsh); void hash_free(hashtab *ht); void hash_reset(hashtab *ht); void hash_copy(hashtab *ht1, hashtab *ht2); /* ht1 := ht2 */ hashtab *hash_new_copy(hashtab *ht); /* For int type values */ /* This macro renames hash_insert to avoids a name clash leading to a segmentation fault on Open Solaris. See also http://trac.sagemath.org/sage_trac/ticket/11563 */ #define hash_insert lrcalc_hash_insert #define hash_lookupint(ht, key) \ (hash_lookup((ht), (key))) #define hash_insertint(ht, key, value) \ (hash_insert(ht, (key), (value))) #define hash_mkfindint(ht, key) \ (hash_mkfind((ht), (key))) /* Returns value associated with key, or NULL if key is not in table. */ int hash_lookup(hashtab *ht, void *key); /* Associates value to key. The old value of key is returned. * If key is already in the hash table, the old key pointer is kept, * and the given key pointer is not stored. If so the global variable * hash_key_used is set to 0, otherwise it is set to 1. However, if * the old key pointer is physically equal to the given, hash_key_used is * set to 1. * * Example: * * oldvalue = hash_insert(ht, key, value); * if (! hash_key_used) * free(key); * if (oldvalue != NULL && oldvalue != value) * free(oldvalue); */ int hash_insert(hashtab *ht, void *key, int value); /* Creates an entry in the hashtable with the given key. * A pointer to the value pointer of the hash table is returned. * hash_key_used is set like in hash_insert(). * * Warning: The returned pointer may become invalid if more insertions * are made. * * Example: * * valuep = hash_mkfind(ht, key) * if (*valuep == NULL) * { * <calculate value> * *valuep = value; * if (! hash_key_used) * free(key); * } * value = *valuep; * <use value> */ #define hash_mkfind(ht, key) (_hash_mkfind_k((ht), (key), hash_hash(ht)(key))) /* Removes any entry with the given key from the hash table. * If such an entry exists, the key and value pointers for that entry * are stored in the global variables hash_removed_key and * hash_removed_value. Otherwise these variables are set to NULL. */ #define hash_remove(ht, key) (_hash_remove_k((ht), (key), hash_hash(ht)(e))) #include "list.h" list *hash_elemlist(hashtab *ht); void hash_print_stat(hashtab *ht, size_t range); typedef void (*freekey_t)(void *); typedef void *(*copykey_t)(void *); void lincomb_add_multiple(hashtab *res, int c, hashtab *lc, freekey_t freekey, copykey_t copykey); typedef struct { hashtab *s; size_t index; size_t i; } hash_itr; #define hash_good(itr) ((itr).i != _S_END) #define hash_key(itr) ((itr).s->elts[(itr).i].key) #define hash_value(itr) ((itr).s->elts[(itr).i].value) #define hash_intvalue(itr) ((int)(long) (itr).s->elts[(itr).i].value) #define hash_first(s,itr) (_hash_first((s), &(itr))) #define hash_next(itr) \ ((((itr).i = (itr).s->elts[(itr).i].next) == _S_END) \ ? _hash_next(&(itr)) : (void)0) void _hash_first(hashtab *s, hash_itr *itr); void _hash_next(hash_itr *itr); int *_hash_mkfind_k(hashtab *ht, void *key, hashkey_t k); int _hash_remove_k(hashtab *ht, void *key, hashkey_t k); void hash_print_stat(hashtab *s, size_t range); #endif
2.75
3
2024-11-18T22:28:32.191850+00:00
2020-05-17T21:26:14
f4d523a73652b927dc1aa37c30176f025f549f55
{ "blob_id": "f4d523a73652b927dc1aa37c30176f025f549f55", "branch_name": "refs/heads/master", "committer_date": "2020-05-17T21:26:14", "content_id": "c4467b9a4465715983a0d0b2f22e670a23ef8a45", "detected_licenses": [ "MIT" ], "directory_id": "d65a76b4d684a09b5c479b8c3a43252de07cd7e6", "extension": "c", "filename": "work_anchor.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 264758559, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1468, "license": "MIT", "license_type": "permissive", "path": "/tools/region_filter-0.19/work_anchor.c", "provenance": "stackv2-0132.json.gz:82219", "repo_name": "chpublichp/masspred", "revision_date": "2020-05-17T21:26:14", "revision_id": "492ccc9d38e5b938661b74a1ace848575d0c8ace", "snapshot_id": "fa0ab9485ce9204f0c974a12bfc9b54d93bfe2b9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/chpublichp/masspred/492ccc9d38e5b938661b74a1ace848575d0c8ace/tools/region_filter-0.19/work_anchor.c", "visit_date": "2022-08-02T15:27:28.236493" }
stackv2
#include "main.h" _FUNCTION_DECLARATION_BEGIN_ void work_anchor(profile_t* profile) _FUNCTION_DECLARATION_END_ { char* name; row_t row; int row_number; char aa; float probability; int status; region_t region; int region_start; int region_end; name = "ANCHOR"; region = REGION_UNKNOWN; while(fgets(row, MAX_ROW_SIZE, profile->input) != NULL) if(sscanf(row, " %d %c %f %d %*s", &row_number, &aa, &probability, &status) == 4) if(profile->numeric == TRUE) if(status == 0) dump_numeric_o(profile, name, row_number, aa, probability); else dump_numeric_d(profile, name, row_number, aa, probability); else { if(status == 0) { if(region == REGION_D) dump_plain_d(profile, name, region_start, region_end); if(region != REGION_O) region_start = row_number; region = REGION_O; } else { if(region == REGION_O) dump_plain_o(profile, name, region_start, region_end); if(region != REGION_D) region_start = row_number; region = REGION_D; } region_end = row_number; } if(profile->numeric != TRUE) switch(region) { case REGION_O: dump_plain_o(profile, name, region_start, region_end); break; case REGION_D: dump_plain_d(profile, name, region_start, region_end); break; } }
2.359375
2
2024-11-18T22:28:32.298493+00:00
2017-03-17T07:29:44
7f28494fa3195ee19103266ff14b9d182f6cad96
{ "blob_id": "7f28494fa3195ee19103266ff14b9d182f6cad96", "branch_name": "refs/heads/master", "committer_date": "2017-03-17T07:29:44", "content_id": "1465421da5aec16786c6851a8a4daab55fd06e48", "detected_licenses": [ "Unlicense" ], "directory_id": "92fd3c32d25101ddf8ee68c6c9862a9427e7271f", "extension": "c", "filename": "mtf.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 80017009, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 658, "license": "Unlicense", "license_type": "permissive", "path": "/decompressor/mtf.c", "provenance": "stackv2-0132.json.gz:82347", "repo_name": "avinashshenoy97/Text-Compression", "revision_date": "2017-03-17T07:29:44", "revision_id": "6a120cb4f30f55d2325b4319e673958c5b073e70", "snapshot_id": "c24fab63362c2e2ba5b53b248959ded3cc85608c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/avinashshenoy97/Text-Compression/6a120cb4f30f55d2325b4319e673958c5b073e70/decompressor/mtf.c", "visit_date": "2021-01-13T15:48:16.344494" }
stackv2
#include "proto.h" #include "mtf.h" char *imtf(int *arr, int len) { int i, j; int asc[128]; //to store ASCII characters char *s = (char *)malloc(sizeof(char) * (len+1)); //allocate space to return int rank; for(i = 0 ; i < 128 ; i++) asc[i] = i; for(i = 0 ; i < len ; i++) { rank = arr[i]; //store rank of each ASCII character, i.e, index in MTF s[i] = asc[rank]; //store ASCII character itself in string for(j = rank ; j > 0 ; j--) asc[j] = asc[j-1]; //shift all elements forward asc[0] = s[i]; //insert in front of MTF array } i = 0; s[len] = 0; //add null character to return string return s; }
3.140625
3
2024-11-18T22:28:36.185799+00:00
2019-11-16T20:33:52
520e9721e765cd2f6e98bc91845cb026e5ca999a
{ "blob_id": "520e9721e765cd2f6e98bc91845cb026e5ca999a", "branch_name": "refs/heads/master", "committer_date": "2019-11-16T20:34:34", "content_id": "3d323034c0b5948a039709fe8ed38705d7882a5b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ef83b5de93967e6605ab23301600457f574f3f78", "extension": "c", "filename": "class_PropertyValueStatement.c", "fork_events_count": 2, "gha_created_at": "2019-02-01T21:28:53", "gha_event_created_at": "2023-02-25T02:51:29", "gha_language": "C", "gha_license_id": null, "github_id": 168762574, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5756, "license": "Apache-2.0", "license_type": "permissive", "path": "/appdistsrc/github.com/acplt/rte/addonlibs/administration/propertyValueStatement/source/class_PropertyValueStatement.c", "provenance": "stackv2-0132.json.gz:82744", "repo_name": "gearboxworks/gearbox", "revision_date": "2019-11-16T20:33:52", "revision_id": "0180d4fc85ddfcb8462d4f238d1b4b790b2dcd48", "snapshot_id": "18438ce92efbe2b9c6d61862369ca4a35e7279f0", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/gearboxworks/gearbox/0180d4fc85ddfcb8462d4f238d1b4b790b2dcd48/appdistsrc/github.com/acplt/rte/addonlibs/administration/propertyValueStatement/source/class_PropertyValueStatement.c", "visit_date": "2023-03-10T19:26:53.583933" }
stackv2
/****************************************************************************** * * FILE * ---- * PropertyValueStatement.c * * History * ------- * 2017-06-22 File created * ******************************************************************************* * * This file is generated by the 'acplt_builder' command * ******************************************************************************/ #ifndef OV_COMPILE_LIBRARY_propertyValueStatement #define OV_COMPILE_LIBRARY_propertyValueStatement #endif #include "propertyValueStatement.h" #include "libov/ov_macros.h" OV_DLLFNCEXPORT OV_ACCESS propertyValueStatement_PropertyValueStatement_getaccess( OV_INSTPTR_ov_object pobj, const OV_ELEMENT *pelem, const OV_TICKET *pticket ) { /* * local variables */ switch(pelem->elemtype) { case OV_ET_VARIABLE: if(pelem->elemunion.pvar->v_offset >= offsetof(OV_INST_ov_object,__classinfo)) { if(pelem->elemunion.pvar->v_vartype == OV_VT_CTYPE) return OV_AC_NONE; else{ if((pelem->elemunion.pvar->v_varprops & OV_VP_DERIVED)){ if((pelem->elemunion.pvar->v_varprops & OV_VP_SETACCESSOR)){ return OV_AC_READWRITE; } else { return OV_AC_READ; } } else { return OV_AC_READWRITE; } } } break; default: break; } return ov_object_getaccess(pobj, pelem, pticket); } OV_DLLFNCEXPORT OV_RESULT propertyValueStatement_PropertyValueStatement_constructor( OV_INSTPTR_ov_object pobj ) { /* * local variables */ OV_INSTPTR_propertyValueStatement_PropertyValueStatement pinst = Ov_StaticPtrCast(propertyValueStatement_PropertyValueStatement, pobj); OV_RESULT result; /* do what the base class does first */ result = ov_object_constructor(pobj); if(Ov_Fail(result)) return result; /* do what */ OV_INSTPTR_ov_domain pparent = NULL; pparent = Ov_GetParent(ov_containment, pobj); if (!Ov_CanCastTo(propertyValueStatement_PropertyValueStatementList, pparent)){ ov_logfile_error("%s: cannot instantiate - Parent have to be from class propertyValueStatementList", pinst->v_identifier); return OV_ERR_ALREADYEXISTS; } OV_BOOL CarrierIdFound = FALSE; OV_BOOL PropertyIdFound = FALSE; OV_BOOL ExpressionLogicFound = FALSE; OV_BOOL ExpressionSemanticFound = FALSE; OV_BOOL ViewFound = FALSE; OV_BOOL VisibilityFound = FALSE; OV_INSTPTR_ov_object pchild = NULL; Ov_ForEachChild(ov_containment, pparent, pchild){ if (Ov_CanCastTo(propertyValueStatement_CarrierId, pchild)){ CarrierIdFound = TRUE; }else if(Ov_CanCastTo(propertyValueStatement_PropertyId, pchild)){ PropertyIdFound = TRUE; }else if(Ov_CanCastTo(propertyValueStatement_ExpressionLogic, pchild)){ ExpressionLogicFound = TRUE; }else if(Ov_CanCastTo(propertyValueStatement_ExpressionSemantic, pchild)){ ExpressionSemanticFound = TRUE; }else if(Ov_CanCastTo(propertyValueStatement_View, pchild)){ ViewFound = TRUE; }else if(Ov_CanCastTo(propertyValueStatement_Visibility, pchild)){ VisibilityFound = TRUE; } } if (CarrierIdFound == FALSE){ //result = Ov_CreateObject(propertyValueStatement_CarrierId, pchild, Ov_DynamicPtrCast(ov_domain, pobj), "CarrierId"); result = ov_class_createobject(pclass_propertyValueStatement_CarrierId, Ov_DynamicPtrCast(ov_domain, pobj), "CarrierId", OV_PMH_DEFAULT, NULL, NULL, NULL, &pchild); if(Ov_Fail(result)){ ov_logfile_error("Fatal: could not create CarrierId"); return result; } } if (PropertyIdFound == FALSE){ //result = Ov_CreateObject(propertyValueStatement_PropertyId, pchild, Ov_DynamicPtrCast(ov_domain, pobj), "PropertyId"); result = ov_class_createobject(pclass_propertyValueStatement_PropertyId, Ov_DynamicPtrCast(ov_domain, pobj), "PropertyId", OV_PMH_DEFAULT, NULL, NULL, NULL, &pchild); if(Ov_Fail(result)){ ov_logfile_error("Fatal: could not create PropertyId"); return result; } } if (ExpressionLogicFound == FALSE){ //result = Ov_CreateObject(propertyValueStatement_ExpressionLogic, pchild, Ov_DynamicPtrCast(ov_domain, pobj), "ExpressionLogic");# result = ov_class_createobject(pclass_propertyValueStatement_ExpressionLogic, Ov_DynamicPtrCast(ov_domain, pobj), "ExpressionLogic", OV_PMH_DEFAULT, NULL, NULL, NULL, &pchild); if(Ov_Fail(result)){ ov_logfile_error("Fatal: could not create ExpressionLogic"); return result; } } if (ExpressionSemanticFound == FALSE){ //result = Ov_CreateObject(propertyValueStatement_ExpressionSemantic, pchild, Ov_DynamicPtrCast(ov_domain, pobj), "ExpressionSemantic"); result = ov_class_createobject(pclass_propertyValueStatement_ExpressionSemantic, Ov_DynamicPtrCast(ov_domain, pobj), "ExpressionSemantic", OV_PMH_DEFAULT, NULL, NULL, NULL, &pchild); if(Ov_Fail(result)){ ov_logfile_error("Fatal: could not create ExpressionSemantic"); return result; } } if (ViewFound == FALSE){ //result = Ov_CreateObject(propertyValueStatement_View, pchild, Ov_DynamicPtrCast(ov_domain, pobj), "View"); result = ov_class_createobject(pclass_propertyValueStatement_View, Ov_DynamicPtrCast(ov_domain, pobj), "View", OV_PMH_DEFAULT, NULL, NULL, NULL, &pchild); if(Ov_Fail(result)){ ov_logfile_error("Fatal: could not create View"); return result; } } if (VisibilityFound == FALSE){ //result = Ov_CreateObject(propertyValueStatement_Visibility, pchild, Ov_DynamicPtrCast(ov_domain, pobj), "Visibility"); result = ov_class_createobject(pclass_propertyValueStatement_Visibility, Ov_DynamicPtrCast(ov_domain, pobj), "Visibility", OV_PMH_DEFAULT, NULL, NULL, NULL, &pchild); if(Ov_Fail(result)){ ov_logfile_error("Fatal: could not create Visibility"); return result; } } return OV_ERR_OK; }
2.0625
2
2024-11-18T22:28:36.237707+00:00
2019-09-06T01:31:16
9f20f5171aa00d568062d9f720e5d0bb0de54c8f
{ "blob_id": "9f20f5171aa00d568062d9f720e5d0bb0de54c8f", "branch_name": "refs/heads/master", "committer_date": "2019-09-06T01:31:16", "content_id": "938c9a904346476443cee560695b15322e8c2711", "detected_licenses": [ "TCL" ], "directory_id": "7e167301a49a7b7ac6ff8b23dc696b10ec06bd4b", "extension": "c", "filename": "tkUnixFont.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 193439385, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 85956, "license": "TCL", "license_type": "permissive", "path": "/prev_work/opensource/fMRI/FSL/fsl/extras/src/tk/unix/tkUnixFont.c", "provenance": "stackv2-0132.json.gz:82875", "repo_name": "Sejik/SignalAnalysis", "revision_date": "2019-09-06T01:31:16", "revision_id": "c04118369dbba807d99738accb8021d77ff77cb6", "snapshot_id": "6c6245880b0017e9f73b5a343641065eb49e5989", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Sejik/SignalAnalysis/c04118369dbba807d99738accb8021d77ff77cb6/prev_work/opensource/fMRI/FSL/fsl/extras/src/tk/unix/tkUnixFont.c", "visit_date": "2020-06-09T12:47:30.314791" }
stackv2
/* * tkUnixFont.c -- * * Contains the Unix implementation of the platform-independant * font package interface. * * Copyright (c) 1996-1997 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) $Id: tkUnixFont.c,v 1.1.1.1 2007/07/10 15:05:18 duncan Exp $ */ #include "tkUnixInt.h" #include "tkFont.h" #include <netinet/in.h> /* for htons() prototype */ #include <arpa/inet.h> /* inet_ntoa() */ /* * The preferred font encodings. */ static CONST char *encodingList[] = { "iso8859-1", "jis0208", "jis0212", NULL }; /* * The following structure represents a font family. It is assumed that * all screen fonts constructed from the same "font family" share certain * properties; all screen fonts with the same "font family" point to a * shared instance of this structure. The most important shared property * is the character existence metrics, used to determine if a screen font * can display a given Unicode character. * * Under Unix, there are three attributes that uniquely identify a "font * family": the foundry, face name, and charset. */ #define FONTMAP_SHIFT 10 #define FONTMAP_PAGES (1 << (sizeof(Tcl_UniChar)*8 - FONTMAP_SHIFT)) #define FONTMAP_BITSPERPAGE (1 << FONTMAP_SHIFT) typedef struct FontFamily { struct FontFamily *nextPtr; /* Next in list of all known font families. */ int refCount; /* How many SubFonts are referring to this * FontFamily. When the refCount drops to * zero, this FontFamily may be freed. */ /* * Key. */ Tk_Uid foundry; /* Foundry key for this FontFamily. */ Tk_Uid faceName; /* Face name key for this FontFamily. */ Tcl_Encoding encoding; /* Encoding key for this FontFamily. */ /* * Derived properties. */ int isTwoByteFont; /* 1 if this is a double-byte font, 0 * otherwise. */ char *fontMap[FONTMAP_PAGES]; /* Two-level sparse table used to determine * quickly if the specified character exists. * As characters are encountered, more pages * in this table are dynamically alloced. The * contents of each page is a bitmask * consisting of FONTMAP_BITSPERPAGE bits, * representing whether this font can be used * to display the given character at the * corresponding bit position. The high bits * of the character are used to pick which * page of the table is used. */ } FontFamily; /* * The following structure encapsulates an individual screen font. A font * object is made up of however many SubFonts are necessary to display a * stream of multilingual characters. */ typedef struct SubFont { char **fontMap; /* Pointer to font map from the FontFamily, * cached here to save a dereference. */ XFontStruct *fontStructPtr; /* The specific screen font that will be * used when displaying/measuring chars * belonging to the FontFamily. */ FontFamily *familyPtr; /* The FontFamily for this SubFont. */ } SubFont; /* * The following structure represents Unix's implementation of a font * object. */ #define SUBFONT_SPACE 3 #define BASE_CHARS 256 typedef struct UnixFont { TkFont font; /* Stuff used by generic font package. Must * be first in structure. */ SubFont staticSubFonts[SUBFONT_SPACE]; /* Builtin space for a limited number of * SubFonts. */ int numSubFonts; /* Length of following array. */ SubFont *subFontArray; /* Array of SubFonts that have been loaded * in order to draw/measure all the characters * encountered by this font so far. All fonts * start off with one SubFont initialized by * AllocFont() from the original set of font * attributes. Usually points to * staticSubFonts, but may point to malloced * space if there are lots of SubFonts. */ SubFont controlSubFont; /* Font to use to display control-character * expansions. */ Display *display; /* Display that owns font. */ int pixelSize; /* Original pixel size used when font was * constructed. */ TkXLFDAttributes xa; /* Additional attributes that specify the * preferred foundry and encoding to use when * constructing additional SubFonts. */ int widths[BASE_CHARS]; /* Widths of first 256 chars in the base * font, for handling common case. */ int underlinePos; /* Offset from baseline to origin of * underline bar (used when drawing underlined * font) (pixels). */ int barHeight; /* Height of underline or overstrike bar * (used when drawing underlined or strikeout * font) (pixels). */ } UnixFont; /* * The following structure and definition is used to keep track of the * alternative names for various encodings. Asking for an encoding that * matches one of the alias patterns will result in actually getting the * encoding by its real name. */ typedef struct EncodingAlias { char *realName; /* The real name of the encoding to load if * the provided name matched the pattern. */ char *aliasPattern; /* Pattern for encoding name, of the form * that is acceptable to Tcl_StringMatch. */ } EncodingAlias; /* * Just some utility structures used for passing around values in helper * procedures. */ typedef struct FontAttributes { TkFontAttributes fa; TkXLFDAttributes xa; } FontAttributes; typedef struct ThreadSpecificData { FontFamily *fontFamilyList; /* The list of font families that are * currently loaded. As screen fonts * are loaded, this list grows to hold * information about what characters * exist in each font family. */ FontFamily controlFamily; /* FontFamily used to handle control * character expansions. The encoding * of this FontFamily converts UTF-8 to * backslashed escape sequences. */ } ThreadSpecificData; static Tcl_ThreadDataKey dataKey; /* * The set of builtin encoding alises to convert the XLFD names for the * encodings into the names expected by the Tcl encoding package. */ static EncodingAlias encodingAliases[] = { {"gb2312-raw", "gb2312*"}, {"big5", "big5*"}, {"cns11643-1", "cns11643*-1"}, {"cns11643-1", "cns11643*.1-0"}, {"cns11643-2", "cns11643*-2"}, {"cns11643-2", "cns11643*.2-0"}, {"jis0201", "jisx0201*"}, {"jis0201", "jisx0202*"}, {"jis0208", "jisc6226*"}, {"jis0208", "jisx0208*"}, {"jis0212", "jisx0212*"}, {"tis620", "tis620*"}, {"ksc5601", "ksc5601*"}, {"dingbats", "*dingbats"}, #ifdef WORDS_BIGENDIAN {"unicode", "iso10646-1"}, #else /* * ucs-2be is needed if native order isn't BE. */ {"ucs-2be", "iso10646-1"}, #endif {NULL, NULL} }; /* * Procedures used only in this file. */ static void FontPkgCleanup _ANSI_ARGS_((ClientData clientData)); static FontFamily * AllocFontFamily _ANSI_ARGS_((Display *display, XFontStruct *fontStructPtr, int base)); static SubFont * CanUseFallback _ANSI_ARGS_((UnixFont *fontPtr, CONST char *fallbackName, int ch, SubFont **fixSubFontPtrPtr)); static SubFont * CanUseFallbackWithAliases _ANSI_ARGS_(( UnixFont *fontPtr, char *fallbackName, int ch, Tcl_DString *nameTriedPtr, SubFont **fixSubFontPtrPtr)); static int ControlUtfProc _ANSI_ARGS_((ClientData clientData, CONST char *src, int srcLen, int flags, Tcl_EncodingState *statePtr, char *dst, int dstLen, int *srcReadPtr, int *dstWrotePtr, int *dstCharsPtr)); static XFontStruct * CreateClosestFont _ANSI_ARGS_((Tk_Window tkwin, CONST TkFontAttributes *faPtr, CONST TkXLFDAttributes *xaPtr)); static SubFont * FindSubFontForChar _ANSI_ARGS_((UnixFont *fontPtr, int ch, SubFont **fixSubFontPtrPtr)); static void FontMapInsert _ANSI_ARGS_((SubFont *subFontPtr, int ch)); static void FontMapLoadPage _ANSI_ARGS_((SubFont *subFontPtr, int row)); static int FontMapLookup _ANSI_ARGS_((SubFont *subFontPtr, int ch)); static void FreeFontFamily _ANSI_ARGS_((FontFamily *afPtr)); static CONST char * GetEncodingAlias _ANSI_ARGS_((CONST char *name)); static int GetFontAttributes _ANSI_ARGS_((Display *display, XFontStruct *fontStructPtr, FontAttributes *faPtr)); static XFontStruct * GetScreenFont _ANSI_ARGS_((Display *display, FontAttributes *wantPtr, char **nameList, int bestIdx[], unsigned int bestScore[])); static XFontStruct * GetSystemFont _ANSI_ARGS_((Display *display)); static int IdentifySymbolEncodings _ANSI_ARGS_(( FontAttributes *faPtr)); static void InitFont _ANSI_ARGS_((Tk_Window tkwin, XFontStruct *fontStructPtr, UnixFont *fontPtr)); static void InitSubFont _ANSI_ARGS_((Display *display, XFontStruct *fontStructPtr, int base, SubFont *subFontPtr)); static char ** ListFonts _ANSI_ARGS_((Display *display, CONST char *faceName, int *numNamesPtr)); static char ** ListFontOrAlias _ANSI_ARGS_((Display *display, CONST char *faceName, int *numNamesPtr)); static unsigned int RankAttributes _ANSI_ARGS_((FontAttributes *wantPtr, FontAttributes *gotPtr)); static void ReleaseFont _ANSI_ARGS_((UnixFont *fontPtr)); static void ReleaseSubFont _ANSI_ARGS_((Display *display, SubFont *subFontPtr)); static int SeenName _ANSI_ARGS_((CONST char *name, Tcl_DString *dsPtr)); #ifndef WORDS_BIGENDIAN static int Ucs2beToUtfProc _ANSI_ARGS_((ClientData clientData, CONST char *src, int srcLen, int flags, Tcl_EncodingState *statePtr, char *dst, int dstLen, int *srcReadPtr, int *dstWrotePtr, int *dstCharsPtr)); static int UtfToUcs2beProc _ANSI_ARGS_((ClientData clientData, CONST char *src, int srcLen, int flags, Tcl_EncodingState *statePtr, char *dst, int dstLen, int *srcReadPtr, int *dstWrotePtr, int *dstCharsPtr)); #endif /* *------------------------------------------------------------------------- * * FontPkgCleanup -- * * This procedure is called when an application is created. It * initializes all the structures that are used by the * platform-dependent code on a per application basis. * * Results: * None. * * Side effects: * Releases thread-specific resources used by font pkg. * *------------------------------------------------------------------------- */ static void FontPkgCleanup(ClientData clientData) { ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); if (tsdPtr->controlFamily.encoding != NULL) { FontFamily *familyPtr = &tsdPtr->controlFamily; int i; Tcl_FreeEncoding(familyPtr->encoding); for (i = 0; i < FONTMAP_PAGES; i++) { if (familyPtr->fontMap[i] != NULL) { ckfree(familyPtr->fontMap[i]); } } tsdPtr->controlFamily.encoding = NULL; } } /* *------------------------------------------------------------------------- * * TkpFontPkgInit -- * * This procedure is called when an application is created. It * initializes all the structures that are used by the * platform-dependent code on a per application basis. * * Results: * None. * * Side effects: * None. * *------------------------------------------------------------------------- */ void TkpFontPkgInit(mainPtr) TkMainInfo *mainPtr; /* The application being created. */ { ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); Tcl_EncodingType type; SubFont dummy; int i; if (tsdPtr->controlFamily.encoding == NULL) { type.encodingName = "X11ControlChars"; type.toUtfProc = ControlUtfProc; type.fromUtfProc = ControlUtfProc; type.freeProc = NULL; type.clientData = NULL; type.nullSize = 0; tsdPtr->controlFamily.refCount = 2; tsdPtr->controlFamily.encoding = Tcl_CreateEncoding(&type); tsdPtr->controlFamily.isTwoByteFont = 0; dummy.familyPtr = &tsdPtr->controlFamily; dummy.fontMap = tsdPtr->controlFamily.fontMap; for (i = 0x00; i < 0x20; i++) { FontMapInsert(&dummy, i); FontMapInsert(&dummy, i + 0x80); } #ifndef WORDS_BIGENDIAN /* * UCS-2BE is unicode (UCS-2) in big-endian format. Define this * if native order isn't BE. It is used in iso10646 fonts. */ type.encodingName = "ucs-2be"; type.toUtfProc = Ucs2beToUtfProc; type.fromUtfProc = UtfToUcs2beProc; type.freeProc = NULL; type.clientData = NULL; type.nullSize = 2; Tcl_CreateEncoding(&type); #endif Tcl_CreateThreadExitHandler(FontPkgCleanup, NULL); } } /* *------------------------------------------------------------------------- * * ControlUtfProc -- * * Convert from UTF-8 into the ASCII expansion of a control * character. * * Results: * Returns TCL_OK if conversion was successful. * * Side effects: * None. * *------------------------------------------------------------------------- */ static int ControlUtfProc(clientData, src, srcLen, flags, statePtr, dst, dstLen, srcReadPtr, dstWrotePtr, dstCharsPtr) ClientData clientData; /* Not used. */ CONST char *src; /* Source string in UTF-8. */ int srcLen; /* Source string length in bytes. */ int flags; /* Conversion control flags. */ Tcl_EncodingState *statePtr;/* Place for conversion routine to store * state information used during a piecewise * conversion. Contents of statePtr are * initialized and/or reset by conversion * routine under control of flags argument. */ char *dst; /* Output buffer in which converted string * is stored. */ int dstLen; /* The maximum length of output buffer in * bytes. */ int *srcReadPtr; /* Filled with the number of bytes from the * source string that were converted. This * may be less than the original source length * if there was a problem converting some * source characters. */ int *dstWrotePtr; /* Filled with the number of bytes that were * stored in the output buffer as a result of * the conversion. */ int *dstCharsPtr; /* Filled with the number of characters that * correspond to the bytes stored in the * output buffer. */ { CONST char *srcStart, *srcEnd; char *dstStart, *dstEnd; Tcl_UniChar ch; int result; static char hexChars[] = "0123456789abcdef"; static char mapChars[] = { 0, 0, 0, 0, 0, 0, 0, 'a', 'b', 't', 'n', 'v', 'f', 'r' }; result = TCL_OK; srcStart = src; srcEnd = src + srcLen; dstStart = dst; dstEnd = dst + dstLen - 6; for ( ; src < srcEnd; ) { if (dst > dstEnd) { result = TCL_CONVERT_NOSPACE; break; } src += Tcl_UtfToUniChar(src, &ch); dst[0] = '\\'; if ((ch < sizeof(mapChars)) && (mapChars[ch] != 0)) { dst[1] = mapChars[ch]; dst += 2; } else if (ch < 256) { dst[1] = 'x'; dst[2] = hexChars[(ch >> 4) & 0xf]; dst[3] = hexChars[ch & 0xf]; dst += 4; } else { dst[1] = 'u'; dst[2] = hexChars[(ch >> 12) & 0xf]; dst[3] = hexChars[(ch >> 8) & 0xf]; dst[4] = hexChars[(ch >> 4) & 0xf]; dst[5] = hexChars[ch & 0xf]; dst += 6; } } *srcReadPtr = src - srcStart; *dstWrotePtr = dst - dstStart; *dstCharsPtr = dst - dstStart; return result; } #ifndef WORDS_BIGENDIAN /* *------------------------------------------------------------------------- * * Ucs2beToUtfProc -- * * Convert from UCS-2BE (big-endian 16-bit Unicode) to UTF-8. * This is only defined on LE machines. * * Results: * Returns TCL_OK if conversion was successful. * * Side effects: * None. * *------------------------------------------------------------------------- */ static int Ucs2beToUtfProc(clientData, src, srcLen, flags, statePtr, dst, dstLen, srcReadPtr, dstWrotePtr, dstCharsPtr) ClientData clientData; /* Not used. */ CONST char *src; /* Source string in Unicode. */ int srcLen; /* Source string length in bytes. */ int flags; /* Conversion control flags. */ Tcl_EncodingState *statePtr;/* Place for conversion routine to store * state information used during a piecewise * conversion. Contents of statePtr are * initialized and/or reset by conversion * routine under control of flags argument. */ char *dst; /* Output buffer in which converted string * is stored. */ int dstLen; /* The maximum length of output buffer in * bytes. */ int *srcReadPtr; /* Filled with the number of bytes from the * source string that were converted. This * may be less than the original source length * if there was a problem converting some * source characters. */ int *dstWrotePtr; /* Filled with the number of bytes that were * stored in the output buffer as a result of * the conversion. */ int *dstCharsPtr; /* Filled with the number of characters that * correspond to the bytes stored in the * output buffer. */ { CONST char *srcStart, *srcEnd; char *dstEnd, *dstStart; int result, numChars; result = TCL_OK; /* check alignment with ucs-2 (2 == sizeof(UCS-2)) */ if ((srcLen % 2) != 0) { result = TCL_CONVERT_MULTIBYTE; srcLen--; } srcStart = src; srcEnd = src + srcLen; dstStart = dst; dstEnd = dst + dstLen - TCL_UTF_MAX; for (numChars = 0; src < srcEnd; numChars++) { if (dst > dstEnd) { result = TCL_CONVERT_NOSPACE; break; } /* * Need to swap byte-order on little-endian machines (x86) for * UCS-2BE. We know this is an LE->BE swap. */ dst += Tcl_UniCharToUtf(htons(*((short *)src)), dst); src += 2 /* sizeof(UCS-2) */; } *srcReadPtr = src - srcStart; *dstWrotePtr = dst - dstStart; *dstCharsPtr = numChars; return result; } /* *------------------------------------------------------------------------- * * UtfToUcs2beProc -- * * Convert from UTF-8 to UCS-2BE (fixed 2-byte encoding). * * Results: * Returns TCL_OK if conversion was successful. * * Side effects: * None. * *------------------------------------------------------------------------- */ static int UtfToUcs2beProc(clientData, src, srcLen, flags, statePtr, dst, dstLen, srcReadPtr, dstWrotePtr, dstCharsPtr) ClientData clientData; /* TableEncodingData that specifies encoding. */ CONST char *src; /* Source string in UTF-8. */ int srcLen; /* Source string length in bytes. */ int flags; /* Conversion control flags. */ Tcl_EncodingState *statePtr;/* Place for conversion routine to store * state information used during a piecewise * conversion. Contents of statePtr are * initialized and/or reset by conversion * routine under control of flags argument. */ char *dst; /* Output buffer in which converted string * is stored. */ int dstLen; /* The maximum length of output buffer in * bytes. */ int *srcReadPtr; /* Filled with the number of bytes from the * source string that were converted. This * may be less than the original source length * if there was a problem converting some * source characters. */ int *dstWrotePtr; /* Filled with the number of bytes that were * stored in the output buffer as a result of * the conversion. */ int *dstCharsPtr; /* Filled with the number of characters that * correspond to the bytes stored in the * output buffer. */ { CONST char *srcStart, *srcEnd, *srcClose, *dstStart, *dstEnd; int result, numChars; Tcl_UniChar ch; srcStart = src; srcEnd = src + srcLen; srcClose = srcEnd; if ((flags & TCL_ENCODING_END) == 0) { srcClose -= TCL_UTF_MAX; } dstStart = dst; dstEnd = dst + dstLen - 2 /* sizeof(UCS-2) */; result = TCL_OK; for (numChars = 0; src < srcEnd; numChars++) { if ((src > srcClose) && (!Tcl_UtfCharComplete(src, srcEnd - src))) { /* * If there is more string to follow, this will ensure that the * last UTF-8 character in the source buffer hasn't been cut off. */ result = TCL_CONVERT_MULTIBYTE; break; } if (dst > dstEnd) { result = TCL_CONVERT_NOSPACE; break; } src += Tcl_UtfToUniChar(src, &ch); /* * Ensure big-endianness (store big bits first). * XXX: This hard-codes the assumed size of Tcl_UniChar as 2. * Make sure to work in char* for Tcl_UtfToUniChar alignment. * [Bug 1122671] */ *dst++ = (ch >> 8); *dst++ = (ch & 0xFF); } *srcReadPtr = src - srcStart; *dstWrotePtr = dst - dstStart; *dstCharsPtr = numChars; return result; } #endif /* WORDS_BIGENDIAN */ /* *--------------------------------------------------------------------------- * * TkpGetNativeFont -- * * Map a platform-specific native font name to a TkFont. * * Results: * The return value is a pointer to a TkFont that represents the * native font. If a native font by the given name could not be * found, the return value is NULL. * * Every call to this procedure returns a new TkFont structure, * even if the name has already been seen before. The caller should * call TkpDeleteFont() when the font is no longer needed. * * The caller is responsible for initializing the memory associated * with the generic TkFont when this function returns and releasing * the contents of the generic TkFont before calling TkpDeleteFont(). * * Side effects: * Memory allocated. * *--------------------------------------------------------------------------- */ TkFont * TkpGetNativeFont(tkwin, name) Tk_Window tkwin; /* For display where font will be used. */ CONST char *name; /* Platform-specific font name. */ { UnixFont *fontPtr; XFontStruct *fontStructPtr; FontAttributes fa; CONST char *p; int hasSpace, dashes, hasWild; /* * The behavior of X when given a name that isn't an XLFD is unspecified. * For example, Exceed 6 returns a valid font for any random string. This * is awkward since system names have higher priority than the other Tk * font syntaxes. So, we need to perform a quick sanity check on the * name and fail if it looks suspicious. We fail if the name: * - contains a space immediately before a dash * - contains a space, but no '*' characters and fewer than 14 dashes */ hasSpace = dashes = hasWild = 0; for (p = name; *p != '\0'; p++) { if (*p == ' ') { if (p[1] == '-') { return NULL; } hasSpace = 1; } else if (*p == '-') { dashes++; } else if (*p == '*') { hasWild = 1; } } if ((dashes < 14) && !hasWild && hasSpace) { return NULL; } fontStructPtr = XLoadQueryFont(Tk_Display(tkwin), name); if (fontStructPtr == NULL) { /* * Handle all names that look like XLFDs here. Otherwise, when * TkpGetFontFromAttributes is called from generic code, any * foundry or encoding information specified in the XLFD will have * been parsed out and lost. But make sure we don't have an * "-option value" string since TkFontParseXLFD would return a * false success when attempting to parse it. */ if (name[0] == '-') { if (name[1] != '*') { char *dash; dash = strchr(name + 1, '-'); if ((dash == NULL) || (isspace(UCHAR(dash[-1])))) { return NULL; } } } else if (name[0] != '*') { return NULL; } if (TkFontParseXLFD(name, &fa.fa, &fa.xa) != TCL_OK) { return NULL; } fontStructPtr = CreateClosestFont(tkwin, &fa.fa, &fa.xa); } fontPtr = (UnixFont *) ckalloc(sizeof(UnixFont)); InitFont(tkwin, fontStructPtr, fontPtr); return (TkFont *) fontPtr; } /* *--------------------------------------------------------------------------- * * TkpGetFontFromAttributes -- * * Given a desired set of attributes for a font, find a font with * the closest matching attributes. * * Results: * The return value is a pointer to a TkFont that represents the * font with the desired attributes. If a font with the desired * attributes could not be constructed, some other font will be * substituted automatically. * * Every call to this procedure returns a new TkFont structure, * even if the specified attributes have already been seen before. * The caller should call TkpDeleteFont() to free the platform- * specific data when the font is no longer needed. * * The caller is responsible for initializing the memory associated * with the generic TkFont when this function returns and releasing * the contents of the generic TkFont before calling TkpDeleteFont(). * * Side effects: * Memory allocated. * *--------------------------------------------------------------------------- */ TkFont * TkpGetFontFromAttributes(tkFontPtr, tkwin, faPtr) TkFont *tkFontPtr; /* If non-NULL, store the information in * this existing TkFont structure, rather than * allocating a new structure to hold the * font; the existing contents of the font * will be released. If NULL, a new TkFont * structure is allocated. */ Tk_Window tkwin; /* For display where font will be used. */ CONST TkFontAttributes *faPtr; /* Set of attributes to match. */ { UnixFont *fontPtr; TkXLFDAttributes xa; XFontStruct *fontStructPtr; TkInitXLFDAttributes(&xa); fontStructPtr = CreateClosestFont(tkwin, faPtr, &xa); fontPtr = (UnixFont *) tkFontPtr; if (fontPtr == NULL) { fontPtr = (UnixFont *) ckalloc(sizeof(UnixFont)); } else { ReleaseFont(fontPtr); } InitFont(tkwin, fontStructPtr, fontPtr); fontPtr->font.fa.underline = faPtr->underline; fontPtr->font.fa.overstrike = faPtr->overstrike; return (TkFont *) fontPtr; } /* *--------------------------------------------------------------------------- * * TkpDeleteFont -- * * Called to release a font allocated by TkpGetNativeFont() or * TkpGetFontFromAttributes(). The caller should have already * released the fields of the TkFont that are used exclusively by * the generic TkFont code. * * Results: * None. * * Side effects: * TkFont is deallocated. * *--------------------------------------------------------------------------- */ void TkpDeleteFont(tkFontPtr) TkFont *tkFontPtr; /* Token of font to be deleted. */ { UnixFont *fontPtr; fontPtr = (UnixFont *) tkFontPtr; ReleaseFont(fontPtr); } /* *--------------------------------------------------------------------------- * * TkpGetFontFamilies -- * * Return information about the font families that are available * on the display of the given window. * * Results: * Modifies interp's result object to hold a list of all the available * font families. * * Side effects: * None. * *--------------------------------------------------------------------------- */ void TkpGetFontFamilies(interp, tkwin) Tcl_Interp *interp; /* Interp to hold result. */ Tk_Window tkwin; /* For display to query. */ { int i, new, numNames; char *family; Tcl_HashTable familyTable; Tcl_HashEntry *hPtr; Tcl_HashSearch search; char **nameList; Tcl_Obj *resultPtr, *strPtr; resultPtr = Tcl_GetObjResult(interp); Tcl_InitHashTable(&familyTable, TCL_STRING_KEYS); nameList = ListFonts(Tk_Display(tkwin), "*", &numNames); for (i = 0; i < numNames; i++) { char *familyEnd; family = strchr(nameList[i] + 1, '-'); if (family == NULL) { /* * Apparently, sometimes ListFonts() can return a font name with * zero or one '-' character in it. This is probably indicative of * a server misconfiguration, but crashing because of it is a very * bad idea anyway. [Bug 1475865] */ continue; } family++; /* Advance to char after '-'. */ familyEnd = strchr(family, '-'); if (familyEnd == NULL) { continue; /* See comment above. */ } *familyEnd = '\0'; family = strchr(nameList[i] + 1, '-') + 1; Tcl_CreateHashEntry(&familyTable, family, &new); } XFreeFontNames(nameList); hPtr = Tcl_FirstHashEntry(&familyTable, &search); while (hPtr != NULL) { strPtr = Tcl_NewStringObj(Tcl_GetHashKey(&familyTable, hPtr), -1); Tcl_ListObjAppendElement(NULL, resultPtr, strPtr); hPtr = Tcl_NextHashEntry(&search); } Tcl_DeleteHashTable(&familyTable); } /* *------------------------------------------------------------------------- * * TkpGetSubFonts -- * * A function used by the testing package for querying the actual * screen fonts that make up a font object. * * Results: * Modifies interp's result object to hold a list containing the * names of the screen fonts that make up the given font object. * * Side effects: * None. * *------------------------------------------------------------------------- */ void TkpGetSubFonts(interp, tkfont) Tcl_Interp *interp; Tk_Font tkfont; { int i; Tcl_Obj *objv[3]; Tcl_Obj *resultPtr, *listPtr; UnixFont *fontPtr; FontFamily *familyPtr; resultPtr = Tcl_GetObjResult(interp); fontPtr = (UnixFont *) tkfont; for (i = 0; i < fontPtr->numSubFonts; i++) { familyPtr = fontPtr->subFontArray[i].familyPtr; objv[0] = Tcl_NewStringObj(familyPtr->faceName, -1); objv[1] = Tcl_NewStringObj(familyPtr->foundry, -1); objv[2] = Tcl_NewStringObj(Tcl_GetEncodingName(familyPtr->encoding), -1); listPtr = Tcl_NewListObj(3, objv); Tcl_ListObjAppendElement(NULL, resultPtr, listPtr); } } /* *--------------------------------------------------------------------------- * * Tk_MeasureChars -- * * Determine the number of characters from the string that will fit * in the given horizontal span. The measurement is done under the * assumption that Tk_DrawChars() will be used to actually display * the characters. * * Results: * The return value is the number of bytes from source that * fit into the span that extends from 0 to maxLength. *lengthPtr is * filled with the x-coordinate of the right edge of the last * character that did fit. * * Side effects: * None. * *--------------------------------------------------------------------------- */ int Tk_MeasureChars(tkfont, source, numBytes, maxLength, flags, lengthPtr) Tk_Font tkfont; /* Font in which characters will be drawn. */ CONST char *source; /* UTF-8 string to be displayed. Need not be * '\0' terminated. */ int numBytes; /* Maximum number of bytes to consider * from source string. */ int maxLength; /* If >= 0, maxLength specifies the longest * permissible line length in pixels; don't * consider any character that would cross * this x-position. If < 0, then line length * is unbounded and the flags argument is * ignored. */ int flags; /* Various flag bits OR-ed together: * TK_PARTIAL_OK means include the last char * which only partially fit on this line. * TK_WHOLE_WORDS means stop on a word * boundary, if possible. * TK_AT_LEAST_ONE means return at least one * character even if no characters fit. */ int *lengthPtr; /* Filled with x-location just after the * terminating character. */ { UnixFont *fontPtr; SubFont *lastSubFontPtr; int curX, curByte; /* * Unix does not use kerning or fractional character widths when * displaying text on the screen. So that means we can safely measure * individual characters or spans of characters and add up the widths * w/o any "off-by-one-pixel" errors. */ fontPtr = (UnixFont *) tkfont; lastSubFontPtr = &fontPtr->subFontArray[0]; if (numBytes == 0) { curX = 0; curByte = 0; } else if (maxLength < 0) { CONST char *p, *end, *next; Tcl_UniChar ch; SubFont *thisSubFontPtr; FontFamily *familyPtr; Tcl_DString runString; /* * A three step process: * 1. Find a contiguous range of characters that can all be * represented by a single screen font. * 2. Convert those chars to the encoding of that font. * 3. Measure converted chars. */ curX = 0; end = source + numBytes; for (p = source; p < end; ) { next = p + Tcl_UtfToUniChar(p, &ch); thisSubFontPtr = FindSubFontForChar(fontPtr, ch, &lastSubFontPtr); if (thisSubFontPtr != lastSubFontPtr) { familyPtr = lastSubFontPtr->familyPtr; Tcl_UtfToExternalDString(familyPtr->encoding, source, p - source, &runString); if (familyPtr->isTwoByteFont) { curX += XTextWidth16(lastSubFontPtr->fontStructPtr, (XChar2b *) Tcl_DStringValue(&runString), Tcl_DStringLength(&runString) / 2); } else { curX += XTextWidth(lastSubFontPtr->fontStructPtr, Tcl_DStringValue(&runString), Tcl_DStringLength(&runString)); } Tcl_DStringFree(&runString); lastSubFontPtr = thisSubFontPtr; source = p; } p = next; } familyPtr = lastSubFontPtr->familyPtr; Tcl_UtfToExternalDString(familyPtr->encoding, source, p - source, &runString); if (familyPtr->isTwoByteFont) { curX += XTextWidth16(lastSubFontPtr->fontStructPtr, (XChar2b *) Tcl_DStringValue(&runString), Tcl_DStringLength(&runString) >> 1); } else { curX += XTextWidth(lastSubFontPtr->fontStructPtr, Tcl_DStringValue(&runString), Tcl_DStringLength(&runString)); } Tcl_DStringFree(&runString); curByte = numBytes; } else { CONST char *p, *end, *next, *term; int newX, termX, sawNonSpace, dstWrote; Tcl_UniChar ch; FontFamily *familyPtr; char buf[16]; /* * How many chars will fit in the space allotted? * This first version may be inefficient because it measures * every character individually. */ next = source + Tcl_UtfToUniChar(source, &ch); newX = curX = termX = 0; term = source; end = source + numBytes; sawNonSpace = (ch > 255) || !isspace(ch); familyPtr = lastSubFontPtr->familyPtr; for (p = source; ; ) { if ((ch < BASE_CHARS) && (fontPtr->widths[ch] != 0)) { newX += fontPtr->widths[ch]; } else { lastSubFontPtr = FindSubFontForChar(fontPtr, ch, NULL); familyPtr = lastSubFontPtr->familyPtr; Tcl_UtfToExternal(NULL, familyPtr->encoding, p, next - p, 0, NULL, buf, sizeof(buf), NULL, &dstWrote, NULL); if (familyPtr->isTwoByteFont) { newX += XTextWidth16(lastSubFontPtr->fontStructPtr, (XChar2b *) buf, dstWrote >> 1); } else { newX += XTextWidth(lastSubFontPtr->fontStructPtr, buf, dstWrote); } } if (newX > maxLength) { break; } curX = newX; p = next; if (p >= end) { term = end; termX = curX; break; } next += Tcl_UtfToUniChar(next, &ch); if ((ch < 256) && isspace(ch)) { if (sawNonSpace) { term = p; termX = curX; sawNonSpace = 0; } } else { sawNonSpace = 1; } } /* * P points to the first character that doesn't fit in the desired * span. Use the flags to figure out what to return. */ if ((flags & TK_PARTIAL_OK) && (p < end) && (curX < maxLength)) { /* * Include the first character that didn't quite fit in the desired * span. The width returned will include the width of that extra * character. */ curX = newX; p += Tcl_UtfToUniChar(p, &ch); } if ((flags & TK_AT_LEAST_ONE) && (term == source) && (p < end)) { term = p; termX = curX; if (term == source) { term += Tcl_UtfToUniChar(term, &ch); termX = newX; } } else if ((p >= end) || !(flags & TK_WHOLE_WORDS)) { term = p; termX = curX; } curX = termX; curByte = term - source; } *lengthPtr = curX; return curByte; } /* *--------------------------------------------------------------------------- * * Tk_DrawChars -- * * Draw a string of characters on the screen. Tk_DrawChars() * expands control characters that occur in the string to * \xNN sequences. * * Results: * None. * * Side effects: * Information gets drawn on the screen. * *--------------------------------------------------------------------------- */ void Tk_DrawChars(display, drawable, gc, tkfont, source, numBytes, x, y) Display *display; /* Display on which to draw. */ Drawable drawable; /* Window or pixmap in which to draw. */ GC gc; /* Graphics context for drawing characters. */ Tk_Font tkfont; /* Font in which characters will be drawn; * must be the same as font used in GC. */ CONST char *source; /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) * should be stripped out of the string that * is passed to this function. If they are * not stripped out, they will be displayed as * regular printing characters. */ int numBytes; /* Number of bytes in string. */ int x, y; /* Coordinates at which to place origin of * string when drawing. */ { UnixFont *fontPtr; SubFont *thisSubFontPtr, *lastSubFontPtr; Tcl_DString runString; CONST char *p, *end, *next; int xStart, needWidth, window_width, do_width; Tcl_UniChar ch; FontFamily *familyPtr; #ifdef TK_DRAW_CHAR_XWINDOW_CHECK int rx, ry; unsigned int width, height, border_width, depth; Drawable root; #endif fontPtr = (UnixFont *) tkfont; lastSubFontPtr = &fontPtr->subFontArray[0]; xStart = x; #ifdef TK_DRAW_CHAR_XWINDOW_CHECK /* * Get the window width so we can abort drawing outside of the window */ if (XGetGeometry(display, drawable, &root, &rx, &ry, &width, &height, &border_width, &depth) == False) { window_width = INT_MAX; } else { window_width = width; } #else /* * This is used by default until we find a solution that doesn't * round-trip to the X server (need to get Tk cached window width). */ window_width = 32768; #endif end = source + numBytes; needWidth = fontPtr->font.fa.underline + fontPtr->font.fa.overstrike; for (p = source; p <= end; ) { if (p < end) { next = p + Tcl_UtfToUniChar(p, &ch); thisSubFontPtr = FindSubFontForChar(fontPtr, ch, &lastSubFontPtr); } else { next = p + 1; thisSubFontPtr = lastSubFontPtr; } if ((thisSubFontPtr != lastSubFontPtr) || (p == end) || (p-source > 200)) { if (p > source) { do_width = (needWidth || (p != end)) ? 1 : 0; familyPtr = lastSubFontPtr->familyPtr; Tcl_UtfToExternalDString(familyPtr->encoding, source, p - source, &runString); if (familyPtr->isTwoByteFont) { XDrawString16(display, drawable, gc, x, y, (XChar2b *) Tcl_DStringValue(&runString), Tcl_DStringLength(&runString) / 2); if (do_width) { x += XTextWidth16(lastSubFontPtr->fontStructPtr, (XChar2b *) Tcl_DStringValue(&runString), Tcl_DStringLength(&runString) / 2); } } else { XDrawString(display, drawable, gc, x, y, Tcl_DStringValue(&runString), Tcl_DStringLength(&runString)); if (do_width) { x += XTextWidth(lastSubFontPtr->fontStructPtr, Tcl_DStringValue(&runString), Tcl_DStringLength(&runString)); } } Tcl_DStringFree(&runString); } lastSubFontPtr = thisSubFontPtr; source = p; XSetFont(display, gc, lastSubFontPtr->fontStructPtr->fid); if (x > window_width) { break; } } p = next; } if (lastSubFontPtr != &fontPtr->subFontArray[0]) { XSetFont(display, gc, fontPtr->subFontArray[0].fontStructPtr->fid); } if (fontPtr->font.fa.underline != 0) { XFillRectangle(display, drawable, gc, xStart, y + fontPtr->underlinePos, (unsigned) (x - xStart), (unsigned) fontPtr->barHeight); } if (fontPtr->font.fa.overstrike != 0) { y -= fontPtr->font.fm.descent + (fontPtr->font.fm.ascent) / 10; XFillRectangle(display, drawable, gc, xStart, y, (unsigned) (x - xStart), (unsigned) fontPtr->barHeight); } } /* *------------------------------------------------------------------------- * * CreateClosestFont -- * * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes(). * Given a set of font attributes, construct a close XFontStruct. * If requested face name is not available, automatically * substitutes an alias for requested face name. If encoding is * not specified (or the requested one is not available), * automatically chooses another encoding from the list of * preferred encodings. If the foundry is not specified (or * is not available) automatically prefers "adobe" foundry. * For all other attributes, if the requested value was not * available, the appropriate "close" value will be used. * * Results: * Return value is the XFontStruct that best matched the * requested attributes. The return value is never NULL; some * font will always be returned. * * Side effects: * None. * *------------------------------------------------------------------------- */ static XFontStruct * CreateClosestFont(tkwin, faPtr, xaPtr) Tk_Window tkwin; /* For display where font will be used. */ CONST TkFontAttributes *faPtr; /* Set of generic attributes to match. */ CONST TkXLFDAttributes *xaPtr; /* Set of X-specific attributes to match. */ { FontAttributes want; char **nameList; int numNames, nameIdx; Display *display; XFontStruct *fontStructPtr; int bestIdx[2]; unsigned int bestScore[2]; want.fa = *faPtr; want.xa = *xaPtr; if (want.xa.foundry == NULL) { want.xa.foundry = Tk_GetUid("adobe"); } if (want.fa.family == NULL) { want.fa.family = Tk_GetUid("fixed"); } want.fa.size = -TkFontGetPixels(tkwin, faPtr->size); if (want.xa.charset == NULL || *want.xa.charset == '\0') { want.xa.charset = Tk_GetUid("iso8859-1"); /* locale. */ } display = Tk_Display(tkwin); /* * Algorithm to get the closest font to the name requested. * * try fontname * try all aliases for fontname * foreach fallback for fontname * try the fallback * try all aliases for the fallback */ nameList = ListFontOrAlias(display, want.fa.family, &numNames); if (numNames == 0) { char ***fontFallbacks; int i, j; char *fallback; fontFallbacks = TkFontGetFallbacks(); for (i = 0; fontFallbacks[i] != NULL; i++) { for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) { if (strcasecmp(want.fa.family, fallback) == 0) { break; } } if (fallback != NULL) { for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) { nameList = ListFontOrAlias(display, fallback, &numNames); if (numNames != 0) { goto found; } } } } nameList = ListFonts(display, "fixed", &numNames); if (numNames == 0) { nameList = ListFonts(display, "*", &numNames); } if (numNames == 0) { return GetSystemFont(display); } } found: bestIdx[0] = -1; bestIdx[1] = -1; bestScore[0] = (unsigned int) -1; bestScore[1] = (unsigned int) -1; for (nameIdx = 0; nameIdx < numNames; nameIdx++) { FontAttributes got; int scalable; unsigned int score; if (TkFontParseXLFD(nameList[nameIdx], &got.fa, &got.xa) != TCL_OK) { continue; } IdentifySymbolEncodings(&got); scalable = (got.fa.size == 0); score = RankAttributes(&want, &got); if (score < bestScore[scalable]) { bestIdx[scalable] = nameIdx; bestScore[scalable] = score; } if (score == 0) { break; } } fontStructPtr = GetScreenFont(display, &want, nameList, bestIdx, bestScore); XFreeFontNames(nameList); if (fontStructPtr == NULL) { return GetSystemFont(display); } return fontStructPtr; } /* *--------------------------------------------------------------------------- * * InitFont -- * * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes(). * Initializes the memory for a new UnixFont that wraps the * platform-specific data. * * The caller is responsible for initializing the fields of the * TkFont that are used exclusively by the generic TkFont code, and * for releasing those fields before calling TkpDeleteFont(). * * Results: * Fills the WinFont structure. * * Side effects: * Memory allocated. * *--------------------------------------------------------------------------- */ static void InitFont(tkwin, fontStructPtr, fontPtr) Tk_Window tkwin; /* For screen where font will be used. */ XFontStruct *fontStructPtr; /* X information about font. */ UnixFont *fontPtr; /* Filled with information constructed from * the above arguments. */ { ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); unsigned long value; int minHi, maxHi, minLo, maxLo, fixed, width, limit, i, n; FontAttributes fa; TkFontAttributes *faPtr; TkFontMetrics *fmPtr; SubFont *controlPtr, *subFontPtr; char *pageMap; Display *display; /* * Get all font attributes and metrics. */ display = Tk_Display(tkwin); GetFontAttributes(display, fontStructPtr, &fa); minHi = fontStructPtr->min_byte1; maxHi = fontStructPtr->max_byte1; minLo = fontStructPtr->min_char_or_byte2; maxLo = fontStructPtr->max_char_or_byte2; fixed = 1; if (fontStructPtr->per_char != NULL) { width = 0; limit = (maxHi - minHi + 1) * (maxLo - minLo + 1); for (i = 0; i < limit; i++) { n = fontStructPtr->per_char[i].width; if (n != 0) { if (width == 0) { width = n; } else if (width != n) { fixed = 0; break; } } } } fontPtr->font.fid = fontStructPtr->fid; faPtr = &fontPtr->font.fa; faPtr->family = fa.fa.family; faPtr->size = TkFontGetPoints(tkwin, fa.fa.size); faPtr->weight = fa.fa.weight; faPtr->slant = fa.fa.slant; faPtr->underline = 0; faPtr->overstrike = 0; fmPtr = &fontPtr->font.fm; fmPtr->ascent = fontStructPtr->ascent; fmPtr->descent = fontStructPtr->descent; fmPtr->maxWidth = fontStructPtr->max_bounds.width; fmPtr->fixed = fixed; fontPtr->display = display; fontPtr->pixelSize = TkFontGetPixels(tkwin, fa.fa.size); fontPtr->xa = fa.xa; fontPtr->numSubFonts = 1; fontPtr->subFontArray = fontPtr->staticSubFonts; InitSubFont(display, fontStructPtr, 1, &fontPtr->subFontArray[0]); fontPtr->controlSubFont = fontPtr->subFontArray[0]; subFontPtr = FindSubFontForChar(fontPtr, '0', NULL); controlPtr = &fontPtr->controlSubFont; controlPtr->fontStructPtr = subFontPtr->fontStructPtr; controlPtr->familyPtr = &tsdPtr->controlFamily; controlPtr->fontMap = tsdPtr->controlFamily.fontMap; pageMap = fontPtr->subFontArray[0].fontMap[0]; for (i = 0; i < 256; i++) { if ((minHi > 0) || (i < minLo) || (i > maxLo) || (((pageMap[i >> 3] >> (i & 7)) & 1) == 0)) { n = 0; } else if (fontStructPtr->per_char == NULL) { n = fontStructPtr->max_bounds.width; } else { n = fontStructPtr->per_char[i - minLo].width; } fontPtr->widths[i] = n; } if (XGetFontProperty(fontStructPtr, XA_UNDERLINE_POSITION, &value)) { fontPtr->underlinePos = value; } else { /* * If the XA_UNDERLINE_POSITION property does not exist, the X * manual recommends using the following value: */ fontPtr->underlinePos = fontStructPtr->descent / 2; } fontPtr->barHeight = 0; if (XGetFontProperty(fontStructPtr, XA_UNDERLINE_THICKNESS, &value)) { fontPtr->barHeight = value; } if (fontPtr->barHeight == 0) { /* * If the XA_UNDERLINE_THICKNESS property does not exist, the X * manual recommends using the width of the stem on a capital * letter. I don't know of a way to get the stem width of a letter, * so guess and use 1/3 the width of a capital I. */ fontPtr->barHeight = fontPtr->widths['I'] / 3; if (fontPtr->barHeight == 0) { fontPtr->barHeight = 1; } } if (fontPtr->underlinePos + fontPtr->barHeight > fontStructPtr->descent) { /* * If this set of cobbled together values would cause the bottom of * the underline bar to stick below the descent of the font, jack * the underline up a bit higher. */ fontPtr->barHeight = fontStructPtr->descent - fontPtr->underlinePos; if (fontPtr->barHeight == 0) { fontPtr->underlinePos--; fontPtr->barHeight = 1; } } } /* *------------------------------------------------------------------------- * * ReleaseFont -- * * Called to release the unix-specific contents of a TkFont. * The caller is responsible for freeing the memory used by the * font itself. * * Results: * None. * * Side effects: * Memory is freed. * *--------------------------------------------------------------------------- */ static void ReleaseFont(fontPtr) UnixFont *fontPtr; /* The font to delete. */ { int i; for (i = 0; i < fontPtr->numSubFonts; i++) { ReleaseSubFont(fontPtr->display, &fontPtr->subFontArray[i]); } if (fontPtr->subFontArray != fontPtr->staticSubFonts) { ckfree((char *) fontPtr->subFontArray); } } /* *------------------------------------------------------------------------- * * InitSubFont -- * * Wrap a screen font and load the FontFamily that represents * it. Used to prepare a SubFont so that characters can be mapped * from UTF-8 to the charset of the font. * * Results: * The subFontPtr is filled with information about the font. * * Side effects: * None. * *------------------------------------------------------------------------- */ static void InitSubFont(display, fontStructPtr, base, subFontPtr) Display *display; /* Display in which font will be used. */ XFontStruct *fontStructPtr; /* The screen font. */ int base; /* Non-zero if this SubFont is being used * as the base font for a font object. */ SubFont *subFontPtr; /* Filled with SubFont constructed from * above attributes. */ { subFontPtr->fontStructPtr = fontStructPtr; subFontPtr->familyPtr = AllocFontFamily(display, fontStructPtr, base); subFontPtr->fontMap = subFontPtr->familyPtr->fontMap; } /* *------------------------------------------------------------------------- * * ReleaseSubFont -- * * Called to release the contents of a SubFont. The caller is * responsible for freeing the memory used by the SubFont itself. * * Results: * None. * * Side effects: * Memory and resources are freed. * *--------------------------------------------------------------------------- */ static void ReleaseSubFont(display, subFontPtr) Display *display; /* Display which owns screen font. */ SubFont *subFontPtr; /* The SubFont to delete. */ { XFreeFont(display, subFontPtr->fontStructPtr); FreeFontFamily(subFontPtr->familyPtr); } /* *------------------------------------------------------------------------- * * AllocFontFamily -- * * Find the FontFamily structure associated with the given font * name. The information should be stored by the caller in a * SubFont and used when determining if that SubFont supports a * character. * * Cannot use the string name used to construct the font as the * key, because the capitalization may not be canonical. Therefore * use the face name actually retrieved from the font metrics as * the key. * * Results: * A pointer to a FontFamily. The reference count in the FontFamily * is automatically incremented. When the SubFont is released, the * reference count is decremented. When no SubFont is using this * FontFamily, it may be deleted. * * Side effects: * A new FontFamily structure will be allocated if this font family * has not been seen. TrueType character existence metrics are * loaded into the FontFamily structure. * *------------------------------------------------------------------------- */ static FontFamily * AllocFontFamily(display, fontStructPtr, base) Display *display; /* Display in which font will be used. */ XFontStruct *fontStructPtr; /* Screen font whose FontFamily is to be * returned. */ int base; /* Non-zero if this font family is to be * used in the base font of a font object. */ { FontFamily *familyPtr; FontAttributes fa; Tcl_Encoding encoding; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); GetFontAttributes(display, fontStructPtr, &fa); encoding = Tcl_GetEncoding(NULL, GetEncodingAlias(fa.xa.charset)); familyPtr = tsdPtr->fontFamilyList; for (; familyPtr != NULL; familyPtr = familyPtr->nextPtr) { if ((familyPtr->faceName == fa.fa.family) && (familyPtr->foundry == fa.xa.foundry) && (familyPtr->encoding == encoding)) { Tcl_FreeEncoding(encoding); familyPtr->refCount++; return familyPtr; } } familyPtr = (FontFamily *) ckalloc(sizeof(FontFamily)); memset(familyPtr, 0, sizeof(FontFamily)); familyPtr->nextPtr = tsdPtr->fontFamilyList; tsdPtr->fontFamilyList = familyPtr; /* * Set key for this FontFamily. */ familyPtr->foundry = fa.xa.foundry; familyPtr->faceName = fa.fa.family; familyPtr->encoding = encoding; /* * An initial refCount of 2 means that FontFamily information will * persist even when the SubFont that loaded the FontFamily is released. * Change it to 1 to cause FontFamilies to be unloaded when not in use. */ familyPtr->refCount = 2; /* * One byte/character fonts have both min_byte1 and max_byte1 0, * and max_char_or_byte2 <= 255. * Anything else specifies a two byte/character font. */ familyPtr->isTwoByteFont = !( (fontStructPtr->min_byte1 == 0) && (fontStructPtr->max_byte1 == 0) && (fontStructPtr->max_char_or_byte2 < 256)); return familyPtr; } /* *------------------------------------------------------------------------- * * FreeFontFamily -- * * Called to free an FontFamily when the SubFont is finished using * it. Frees the contents of the FontFamily and the memory used by * the FontFamily itself. * * Results: * None. * * Side effects: * None. * *------------------------------------------------------------------------- */ static void FreeFontFamily(familyPtr) FontFamily *familyPtr; /* The FontFamily to delete. */ { FontFamily **familyPtrPtr; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); int i; if (familyPtr == NULL) { return; } familyPtr->refCount--; if (familyPtr->refCount > 0) { return; } Tcl_FreeEncoding(familyPtr->encoding); for (i = 0; i < FONTMAP_PAGES; i++) { if (familyPtr->fontMap[i] != NULL) { ckfree(familyPtr->fontMap[i]); } } /* * Delete from list. */ for (familyPtrPtr = &tsdPtr->fontFamilyList; ; ) { if (*familyPtrPtr == familyPtr) { *familyPtrPtr = familyPtr->nextPtr; break; } familyPtrPtr = &(*familyPtrPtr)->nextPtr; } ckfree((char *) familyPtr); } /* *------------------------------------------------------------------------- * * FindSubFontForChar -- * * Determine which screen font is necessary to use to * display the given character. If the font object does not have * a screen font that can display the character, another screen font * may be loaded into the font object, following a set of preferred * fallback rules. * * Results: * The return value is the SubFont to use to display the given * character. * * Side effects: * The contents of fontPtr are modified to cache the results * of the lookup and remember any SubFonts that were dynamically * loaded. The table of SubFonts might be extended, and if a non-NULL * reference to a subfont pointer is available, it is updated if it * previously pointed into the old subfont table. * *------------------------------------------------------------------------- */ static SubFont * FindSubFontForChar(fontPtr, ch, fixSubFontPtrPtr) UnixFont *fontPtr; /* The font object with which the character * will be displayed. */ int ch; /* The Unicode character to be displayed. */ SubFont **fixSubFontPtrPtr; /* Subfont reference to fix up if we * reallocate our subfont table. */ { int i, j, k, numNames; Tk_Uid faceName; char *fallback; char **aliases, **nameList, **anyFallbacks; char ***fontFallbacks; SubFont *subFontPtr; Tcl_DString ds; if (FontMapLookup(&fontPtr->subFontArray[0], ch)) { return &fontPtr->subFontArray[0]; } for (i = 1; i < fontPtr->numSubFonts; i++) { if (FontMapLookup(&fontPtr->subFontArray[i], ch)) { return &fontPtr->subFontArray[i]; } } if (FontMapLookup(&fontPtr->controlSubFont, ch)) { return &fontPtr->controlSubFont; } /* * Keep track of all face names that we check, so we don't check some * name multiple times if it can be reached by multiple paths. */ Tcl_DStringInit(&ds); /* * Are there any other fonts with the same face name as the base * font that could display this character, e.g., if the base font * is adobe:fixed:iso8859-1, we could might be able to use * misc:fixed:iso8859-8 or sony:fixed:jisx0208.1983-0 */ faceName = fontPtr->font.fa.family; if (SeenName(faceName, &ds) == 0) { subFontPtr = CanUseFallback(fontPtr, faceName, ch, fixSubFontPtrPtr); if (subFontPtr != NULL) { goto end; } } aliases = TkFontGetAliasList(faceName); subFontPtr = NULL; fontFallbacks = TkFontGetFallbacks(); for (i = 0; fontFallbacks[i] != NULL; i++) { for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) { if (strcasecmp(fallback, faceName) == 0) { /* * If the base font has a fallback... */ goto tryfallbacks; } else if (aliases != NULL) { /* * Or if an alias for the base font has a fallback... */ for (k = 0; aliases[k] != NULL; k++) { if (strcasecmp(fallback, aliases[k]) == 0) { goto tryfallbacks; } } } } continue; tryfallbacks: /* * ...then see if we can use one of the fallbacks, or an * alias for one of the fallbacks. */ for (j = 0; (fallback = fontFallbacks[i][j]) != NULL; j++) { subFontPtr = CanUseFallbackWithAliases(fontPtr, fallback, ch, &ds, fixSubFontPtrPtr); if (subFontPtr != NULL) { goto end; } } } /* * See if we can use something from the global fallback list. */ anyFallbacks = TkFontGetGlobalClass(); for (i = 0; (fallback = anyFallbacks[i]) != NULL; i++) { subFontPtr = CanUseFallbackWithAliases(fontPtr, fallback, ch, &ds, fixSubFontPtrPtr); if (subFontPtr != NULL) { goto end; } } /* * Try all face names available in the whole system until we * find one that can be used. */ nameList = ListFonts(fontPtr->display, "*", &numNames); for (i = 0; i < numNames; i++) { fallback = strchr(nameList[i] + 1, '-') + 1; strchr(fallback, '-')[0] = '\0'; if (SeenName(fallback, &ds) == 0) { subFontPtr = CanUseFallback(fontPtr, fallback, ch, fixSubFontPtrPtr); if (subFontPtr != NULL) { XFreeFontNames(nameList); goto end; } } } XFreeFontNames(nameList); end: Tcl_DStringFree(&ds); if (subFontPtr == NULL) { /* * No font can display this character, so it will be displayed as a * control character expansion. */ subFontPtr = &fontPtr->controlSubFont; FontMapInsert(subFontPtr, ch); } return subFontPtr; } /* *------------------------------------------------------------------------- * * FontMapLookup -- * * See if the screen font can display the given character. * * Results: * The return value is 0 if the screen font cannot display the * character, non-zero otherwise. * * Side effects: * New pages are added to the font mapping cache whenever the * character belongs to a page that hasn't been seen before. * When a page is loaded, information about all the characters on * that page is stored, not just for the single character in * question. * *------------------------------------------------------------------------- */ static int FontMapLookup(subFontPtr, ch) SubFont *subFontPtr; /* Contains font mapping cache to be queried * and possibly updated. */ int ch; /* Character to be tested. */ { int row, bitOffset; row = ch >> FONTMAP_SHIFT; if (subFontPtr->fontMap[row] == NULL) { FontMapLoadPage(subFontPtr, row); } bitOffset = ch & (FONTMAP_BITSPERPAGE - 1); return (subFontPtr->fontMap[row][bitOffset >> 3] >> (bitOffset & 7)) & 1; } /* *------------------------------------------------------------------------- * * FontMapInsert -- * * Tell the font mapping cache that the given screen font should be * used to display the specified character. This is called when no * font on the system can be be found that can display that * character; we lie to the font and tell it that it can display * the character, otherwise we would end up re-searching the entire * fallback hierarchy every time that character was seen. * * Results: * None. * * Side effects: * New pages are added to the font mapping cache whenever the * character belongs to a page that hasn't been seen before. * When a page is loaded, information about all the characters on * that page is stored, not just for the single character in * question. * *------------------------------------------------------------------------- */ static void FontMapInsert(subFontPtr, ch) SubFont *subFontPtr; /* Contains font mapping cache to be * updated. */ int ch; /* Character to be added to cache. */ { int row, bitOffset; row = ch >> FONTMAP_SHIFT; if (subFontPtr->fontMap[row] == NULL) { FontMapLoadPage(subFontPtr, row); } bitOffset = ch & (FONTMAP_BITSPERPAGE - 1); subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7); } /* *------------------------------------------------------------------------- * * FontMapLoadPage -- * * Load information about all the characters on a given page. * This information consists of one bit per character that indicates * whether the associated screen font can (1) or cannot (0) display * the characters on the page. * * Results: * None. * * Side effects: * Mempry allocated. * *------------------------------------------------------------------------- */ static void FontMapLoadPage(subFontPtr, row) SubFont *subFontPtr; /* Contains font mapping cache to be * updated. */ int row; /* Index of the page to be loaded into * the cache. */ { char buf[16], src[TCL_UTF_MAX]; int minHi, maxHi, minLo, maxLo, scale, checkLo; int i, end, bitOffset, isTwoByteFont, n; Tcl_Encoding encoding; XFontStruct *fontStructPtr; XCharStruct *widths; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); subFontPtr->fontMap[row] = (char *) ckalloc(FONTMAP_BITSPERPAGE / 8); memset(subFontPtr->fontMap[row], 0, FONTMAP_BITSPERPAGE / 8); if (subFontPtr->familyPtr == &tsdPtr->controlFamily) { return; } fontStructPtr = subFontPtr->fontStructPtr; encoding = subFontPtr->familyPtr->encoding; isTwoByteFont = subFontPtr->familyPtr->isTwoByteFont; widths = fontStructPtr->per_char; minHi = fontStructPtr->min_byte1; maxHi = fontStructPtr->max_byte1; minLo = fontStructPtr->min_char_or_byte2; maxLo = fontStructPtr->max_char_or_byte2; scale = maxLo - minLo + 1; checkLo = minLo; if (! isTwoByteFont) { if (minLo < 32) { checkLo = 32; } } end = (row + 1) << FONTMAP_SHIFT; for (i = row << FONTMAP_SHIFT; i < end; i++) { int hi, lo; if (Tcl_UtfToExternal(NULL, encoding, src, Tcl_UniCharToUtf(i, src), TCL_ENCODING_STOPONERROR, NULL, buf, sizeof(buf), NULL, NULL, NULL) != TCL_OK) { continue; } if (isTwoByteFont) { hi = ((unsigned char *) buf)[0]; lo = ((unsigned char *) buf)[1]; } else { hi = 0; lo = ((unsigned char *) buf)[0]; } if ((hi < minHi) || (hi > maxHi) || (lo < checkLo) || (lo > maxLo)) { continue; } n = (hi - minHi) * scale + lo - minLo; if ((widths == NULL) || ((widths[n].width + widths[n].rbearing) != 0)) { bitOffset = i & (FONTMAP_BITSPERPAGE - 1); subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7); } } } /* *--------------------------------------------------------------------------- * * CanUseFallbackWithAliases -- * * Helper function for FindSubFontForChar. Determine if the * specified face name (or an alias of the specified face name) * can be used to construct a screen font that can display the * given character. * * Results: * See CanUseFallback(). * * Side effects: * If the name and/or one of its aliases was rejected, the * rejected string is recorded in nameTriedPtr so that it won't * be tried again. The table of SubFonts might be extended, and if * a non-NULL reference to a subfont pointer is available, it is * updated if it previously pointed into the old subfont table. * *--------------------------------------------------------------------------- */ static SubFont * CanUseFallbackWithAliases(fontPtr, faceName, ch, nameTriedPtr, fixSubFontPtrPtr) UnixFont *fontPtr; /* The font object that will own the new * screen font. */ char *faceName; /* Desired face name for new screen font. */ int ch; /* The Unicode character that the new * screen font must be able to display. */ Tcl_DString *nameTriedPtr; /* Records face names that have already * been tried. It is possible for the same * face name to be queried multiple times when * trying to find a suitable screen font. */ SubFont **fixSubFontPtrPtr; /* Subfont reference to fix up if we * reallocate our subfont table. */ { SubFont *subFontPtr; char **aliases; int i; if (SeenName(faceName, nameTriedPtr) == 0) { subFontPtr = CanUseFallback(fontPtr, faceName, ch, fixSubFontPtrPtr); if (subFontPtr != NULL) { return subFontPtr; } } aliases = TkFontGetAliasList(faceName); if (aliases != NULL) { for (i = 0; aliases[i] != NULL; i++) { if (SeenName(aliases[i], nameTriedPtr) == 0) { subFontPtr = CanUseFallback(fontPtr, aliases[i], ch, fixSubFontPtrPtr); if (subFontPtr != NULL) { return subFontPtr; } } } } return NULL; } /* *--------------------------------------------------------------------------- * * SeenName -- * * Used to determine we have already tried and rejected the given * face name when looking for a screen font that can support some * Unicode character. * * Results: * The return value is 0 if this face name has not already been seen, * non-zero otherwise. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static int SeenName(name, dsPtr) CONST char *name; /* The name to check. */ Tcl_DString *dsPtr; /* Contains names that have already been * seen. */ { CONST char *seen, *end; seen = Tcl_DStringValue(dsPtr); end = seen + Tcl_DStringLength(dsPtr); while (seen < end) { if (strcasecmp(seen, name) == 0) { return 1; } seen += strlen(seen) + 1; } Tcl_DStringAppend(dsPtr, (char *) name, (int) (strlen(name) + 1)); return 0; } /* *------------------------------------------------------------------------- * * CanUseFallback -- * * If the specified screen font has not already been loaded * into the font object, determine if the specified screen * font can display the given character. * * Results: * The return value is a pointer to a newly allocated SubFont, * owned by the font object. This SubFont can be used to display * the given character. The SubFont represents the screen font * with the base set of font attributes from the font object, but * using the specified face name. NULL is returned if the font * object already holds a reference to the specified font or if * the specified font doesn't exist or cannot display the given * character. * * Side effects: * The font object's subFontArray is updated to contain a reference * to the newly allocated SubFont. The table of SubFonts might be * extended, and if a non-NULL reference to a subfont pointer is * available, it is updated if it previously pointed into the old * subfont table. * *------------------------------------------------------------------------- */ static SubFont * CanUseFallback(fontPtr, faceName, ch, fixSubFontPtrPtr) UnixFont *fontPtr; /* The font object that will own the new * screen font. */ CONST char *faceName; /* Desired face name for new screen font. */ int ch; /* The Unicode character that the new * screen font must be able to display. */ SubFont **fixSubFontPtrPtr; /* Subfont reference to fix up if we * reallocate our subfont table. */ { int i, nameIdx, numNames, srcLen; Tk_Uid hateFoundry; int bestIdx[2]; CONST char *charset, *hateCharset; unsigned int bestScore[2]; char **nameList, **nameListOrig; FontAttributes want, got; char src[TCL_UTF_MAX]; Display *display; SubFont subFont; XFontStruct *fontStructPtr; Tcl_DString dsEncodings; int numEncodings; Tcl_Encoding *encodingCachePtr; /* * Assume: the face name is times. * Assume: adobe:times:iso8859-1 has already been used. * * Are there any versions of times that can display this * character (e.g., perhaps linotype:times:iso8859-2)? * a. Get list of all times fonts. * b1. Cross out all names whose encodings we've already used. * b2. Cross out all names whose foundry & encoding we've already seen. * c. Cross out all names whose encoding cannot handle the character. * d. Rank each name and pick the best match. * e. If that font cannot actually display the character, cross * out all names with the same foundry and encoding and go * back to (c). */ display = fontPtr->display; nameList = ListFonts(display, faceName, &numNames); if (numNames == 0) { return NULL; } nameListOrig = nameList; srcLen = Tcl_UniCharToUtf(ch, src); want.fa = fontPtr->font.fa; want.xa = fontPtr->xa; want.fa.family = Tk_GetUid(faceName); want.fa.size = -fontPtr->pixelSize; hateFoundry = NULL; hateCharset = NULL; numEncodings = 0; Tcl_DStringInit(&dsEncodings); charset = NULL; /* lint, since numNames must be > 0 to get here. */ retry: bestIdx[0] = -1; bestIdx[1] = -1; bestScore[0] = (unsigned int) -1; bestScore[1] = (unsigned int) -1; for (nameIdx = 0; nameIdx < numNames; nameIdx++) { Tcl_Encoding encoding; char dst[16]; int scalable, srcRead, dstWrote; unsigned int score; if (nameList[nameIdx] == NULL) { continue; } if (TkFontParseXLFD(nameList[nameIdx], &got.fa, &got.xa) != TCL_OK) { goto crossout; } IdentifySymbolEncodings(&got); charset = GetEncodingAlias(got.xa.charset); if (hateFoundry != NULL) { /* * E. If the font we picked cannot actually display the * character, cross out all names with the same foundry and * encoding. */ if ((hateFoundry == got.xa.foundry) && (strcmp(hateCharset, charset) == 0)) { goto crossout; } } else { /* * B. Cross out all names whose encodings we've already used. */ for (i = 0; i < fontPtr->numSubFonts; i++) { encoding = fontPtr->subFontArray[i].familyPtr->encoding; if (strcmp(charset, Tcl_GetEncodingName(encoding)) == 0) { goto crossout; } } } /* * C. Cross out all names whose encoding cannot handle the character. */ encodingCachePtr = (Tcl_Encoding *) Tcl_DStringValue(&dsEncodings); for (i = numEncodings; --i >= 0; encodingCachePtr++) { encoding = *encodingCachePtr; if (strcmp(Tcl_GetEncodingName(encoding), charset) == 0) { break; } } if (i < 0) { encoding = Tcl_GetEncoding(NULL, charset); if (encoding == NULL) { goto crossout; } Tcl_DStringAppend(&dsEncodings, (char *) &encoding, sizeof(encoding)); numEncodings++; } Tcl_UtfToExternal(NULL, encoding, src, srcLen, TCL_ENCODING_STOPONERROR, NULL, dst, sizeof(dst), &srcRead, &dstWrote, NULL); if (dstWrote == 0) { goto crossout; } /* * D. Rank each name and pick the best match. */ scalable = (got.fa.size == 0); score = RankAttributes(&want, &got); if (score < bestScore[scalable]) { bestIdx[scalable] = nameIdx; bestScore[scalable] = score; } if (score == 0) { break; } continue; crossout: if (nameList == nameListOrig) { /* * Not allowed to change pointers to memory that X gives you, * so make a copy. */ nameList = (char **) ckalloc(numNames * sizeof(char *)); memcpy(nameList, nameListOrig, numNames * sizeof(char *)); } nameList[nameIdx] = NULL; } fontStructPtr = GetScreenFont(display, &want, nameList, bestIdx, bestScore); encodingCachePtr = (Tcl_Encoding *) Tcl_DStringValue(&dsEncodings); for (i = numEncodings; --i >= 0; encodingCachePtr++) { Tcl_FreeEncoding(*encodingCachePtr); } Tcl_DStringFree(&dsEncodings); numEncodings = 0; if (fontStructPtr == NULL) { if (nameList != nameListOrig) { ckfree((char *) nameList); } XFreeFontNames(nameListOrig); return NULL; } InitSubFont(display, fontStructPtr, 0, &subFont); if (FontMapLookup(&subFont, ch) == 0) { /* * E. If the font we picked cannot actually display the character, * cross out all names with the same foundry and encoding and pick * another font. */ hateFoundry = got.xa.foundry; hateCharset = charset; ReleaseSubFont(display, &subFont); goto retry; } if (nameList != nameListOrig) { ckfree((char *) nameList); } XFreeFontNames(nameListOrig); if (fontPtr->numSubFonts >= SUBFONT_SPACE) { SubFont *newPtr; newPtr = (SubFont *) ckalloc(sizeof(SubFont) * (fontPtr->numSubFonts + 1)); memcpy((char *) newPtr, fontPtr->subFontArray, fontPtr->numSubFonts * sizeof(SubFont)); if (fixSubFontPtrPtr != NULL) { register SubFont *fixSubFontPtr = *fixSubFontPtrPtr; if (fixSubFontPtr != &fontPtr->controlSubFont) { *fixSubFontPtrPtr = newPtr + (fixSubFontPtr - fontPtr->subFontArray); } } if (fontPtr->subFontArray != fontPtr->staticSubFonts) { ckfree((char *) fontPtr->subFontArray); } fontPtr->subFontArray = newPtr; } fontPtr->subFontArray[fontPtr->numSubFonts] = subFont; fontPtr->numSubFonts++; return &fontPtr->subFontArray[fontPtr->numSubFonts - 1]; } /* *--------------------------------------------------------------------------- * * RankAttributes -- * * Determine how close the attributes of the font in question match * the attributes that we want. * * Results: * The return value is the score; lower numbers are better. * *scalablePtr is set to 0 if the font was not scalable, 1 otherwise. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static unsigned int RankAttributes(wantPtr, gotPtr) FontAttributes *wantPtr; /* The desired attributes. */ FontAttributes *gotPtr; /* The attributes we have to live with. */ { unsigned int penalty; penalty = 0; if (gotPtr->xa.foundry != wantPtr->xa.foundry) { penalty += 4500; } if (gotPtr->fa.family != wantPtr->fa.family) { penalty += 9000; } if (gotPtr->fa.weight != wantPtr->fa.weight) { penalty += 90; } if (gotPtr->fa.slant != wantPtr->fa.slant) { penalty += 60; } if (gotPtr->xa.slant != wantPtr->xa.slant) { penalty += 10; } if (gotPtr->xa.setwidth != wantPtr->xa.setwidth) { penalty += 1000; } if (gotPtr->fa.size == 0) { /* * A scalable font is almost always acceptable, but the * corresponding bitmapped font would be better. */ penalty += 10; } else { int diff; /* * It's worse to be too large than to be too small. */ diff = (-gotPtr->fa.size - -wantPtr->fa.size); if (diff > 0) { penalty += 600; } else if (diff < 0) { penalty += 150; diff = -diff; } penalty += 150 * diff; } if (gotPtr->xa.charset != wantPtr->xa.charset) { int i; CONST char *gotAlias, *wantAlias; penalty += 65000; gotAlias = GetEncodingAlias(gotPtr->xa.charset); wantAlias = GetEncodingAlias(wantPtr->xa.charset); if (strcmp(gotAlias, wantAlias) != 0) { penalty += 30000; for (i = 0; encodingList[i] != NULL; i++) { if (strcmp(gotAlias, encodingList[i]) == 0) { penalty -= 30000; break; } penalty += 20000; } } } return penalty; } /* *--------------------------------------------------------------------------- * * GetScreenFont -- * * Given the names for the best scalable and best bitmapped font, * actually construct an XFontStruct based on the best XLFD. * This is where all the alias and fallback substitution bottoms * out. * * Results: * The screen font that best corresponds to the set of attributes. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static XFontStruct * GetScreenFont(display, wantPtr, nameList, bestIdx, bestScore) Display *display; /* Display for new XFontStruct. */ FontAttributes *wantPtr; /* Contains desired actual pixel-size if the * best font was scalable. */ char **nameList; /* Array of XLFDs. */ int bestIdx[2]; /* Indices into above array for XLFD of * best bitmapped and best scalable font. */ unsigned int bestScore[2]; /* Scores of best bitmapped and best * scalable font. XLFD corresponding to * lowest score will be constructed. */ { XFontStruct *fontStructPtr; if ((bestIdx[0] < 0) && (bestIdx[1] < 0)) { return NULL; } /* * Now we know which is the closest matching scalable font and the * closest matching bitmapped font. If the scalable font was a * better match, try getting the scalable font; however, if the * scalable font was not actually available in the desired * pointsize, fall back to the closest bitmapped font. */ fontStructPtr = NULL; if (bestScore[1] < bestScore[0]) { char *str, *rest; char buf[256]; int i; /* * Fill in the desired pixel size for this font. */ tryscale: str = nameList[bestIdx[1]]; for (i = 0; i < XLFD_PIXEL_SIZE; i++) { str = strchr(str + 1, '-'); } rest = str; for (i = XLFD_PIXEL_SIZE; i < XLFD_CHARSET; i++) { rest = strchr(rest + 1, '-'); } *str = '\0'; sprintf(buf, "%.200s-%d-*-*-*-*-*%s", nameList[bestIdx[1]], -wantPtr->fa.size, rest); *str = '-'; fontStructPtr = XLoadQueryFont(display, buf); bestScore[1] = INT_MAX; } if (fontStructPtr == NULL) { fontStructPtr = XLoadQueryFont(display, nameList[bestIdx[0]]); if (fontStructPtr == NULL) { /* * This shouldn't happen because the font name is one of the * names that X gave us to use, but it does anyhow. */ if (bestScore[1] < INT_MAX) { goto tryscale; } return GetSystemFont(display); } } return fontStructPtr; } /* *--------------------------------------------------------------------------- * * GetSystemFont -- * * Absolute fallback mechanism, called when we need a font and no * other font can be found and/or instantiated. * * Results: * A pointer to a font. Never NULL. * * Side effects: * If there are NO fonts installed on the system, this call will * panic, but how did you get X running in that case? * *--------------------------------------------------------------------------- */ static XFontStruct * GetSystemFont(display) Display *display; /* Display for new XFontStruct. */ { XFontStruct *fontStructPtr; fontStructPtr = XLoadQueryFont(display, "fixed"); if (fontStructPtr == NULL) { fontStructPtr = XLoadQueryFont(display, "*"); if (fontStructPtr == NULL) { panic("TkpGetFontFromAttributes: cannot get any font"); } } return fontStructPtr; } /* *--------------------------------------------------------------------------- * * GetFontAttributes -- * * Given a screen font, determine its actual attributes, which are * not necessarily the attributes that were used to construct it. * * Results: * *faPtr is filled with the screen font's attributes. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static int GetFontAttributes(display, fontStructPtr, faPtr) Display *display; /* Display that owns the screen font. */ XFontStruct *fontStructPtr; /* Screen font to query. */ FontAttributes *faPtr; /* For storing attributes of screen font. */ { unsigned long value; char *name; if ((XGetFontProperty(fontStructPtr, XA_FONT, &value) != False) && (value != 0)) { name = XGetAtomName(display, (Atom) value); if (TkFontParseXLFD(name, &faPtr->fa, &faPtr->xa) != TCL_OK) { faPtr->fa.family = Tk_GetUid(name); faPtr->xa.foundry = Tk_GetUid(""); faPtr->xa.charset = Tk_GetUid(""); } XFree(name); } else { TkInitFontAttributes(&faPtr->fa); TkInitXLFDAttributes(&faPtr->xa); } /* * Do last ditch check for family. It seems that some X servers can * fail on the X font calls above, slipping through earlier checks. * X-Win32 5.4 is one of these. */ if (faPtr->fa.family == NULL) { faPtr->fa.family = Tk_GetUid(""); faPtr->xa.foundry = Tk_GetUid(""); faPtr->xa.charset = Tk_GetUid(""); } return IdentifySymbolEncodings(faPtr); } /* *--------------------------------------------------------------------------- * * ListFonts -- * * Utility function to return the array of all XLFDs on the system * with the specified face name. * * Results: * The return value is an array of XLFDs, which should be freed with * XFreeFontNames(), or NULL if no XLFDs matched the requested name. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static char ** ListFonts(display, faceName, numNamesPtr) Display *display; /* Display to query. */ CONST char *faceName; /* Desired face name, or "*" for all. */ int *numNamesPtr; /* Filled with length of returned array, or * 0 if no names were found. */ { char buf[256]; sprintf(buf, "-*-%.80s-*-*-*-*-*-*-*-*-*-*-*-*", faceName); return XListFonts(display, buf, 10000, numNamesPtr); } static char ** ListFontOrAlias(display, faceName, numNamesPtr) Display *display; /* Display to query. */ CONST char *faceName; /* Desired face name, or "*" for all. */ int *numNamesPtr; /* Filled with length of returned array, or * 0 if no names were found. */ { char **nameList, **aliases; int i; nameList = ListFonts(display, faceName, numNamesPtr); if (nameList != NULL) { return nameList; } aliases = TkFontGetAliasList(faceName); if (aliases != NULL) { for (i = 0; aliases[i] != NULL; i++) { nameList = ListFonts(display, aliases[i], numNamesPtr); if (nameList != NULL) { return nameList; } } } *numNamesPtr = 0; return NULL; } /* *--------------------------------------------------------------------------- * * IdentifySymbolEncodings -- * * If the font attributes refer to a symbol font, update the * charset field of the font attributes so that it reflects the * encoding of that symbol font. In general, the raw value for * the charset field parsed from an XLFD is meaningless for symbol * fonts. * * Symbol fonts are all fonts whose name appears in the symbolClass. * * Results: * The return value is non-zero if the font attributes specify a * symbol font, or 0 otherwise. If a non-zero value is returned * the charset field of the font attributes will be changed to * the string that represents the actual encoding for the symbol font. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static int IdentifySymbolEncodings(faPtr) FontAttributes *faPtr; { int i, j; char **aliases, **symbolClass; symbolClass = TkFontGetSymbolClass(); for (i = 0; symbolClass[i] != NULL; i++) { if (strcasecmp(faPtr->fa.family, symbolClass[i]) == 0) { faPtr->xa.charset = Tk_GetUid(GetEncodingAlias(symbolClass[i])); return 1; } aliases = TkFontGetAliasList(symbolClass[i]); for (j = 0; (aliases != NULL) && (aliases[j] != NULL); j++) { if (strcasecmp(faPtr->fa.family, aliases[j]) == 0) { faPtr->xa.charset = Tk_GetUid(GetEncodingAlias(aliases[j])); return 1; } } } return 0; } /* *--------------------------------------------------------------------------- * * GetEncodingAlias -- * * Map the name of an encoding to another name that should be used * when actually loading the encoding. For instance, the encodings * "jisc6226.1978", "jisx0208.1983", "jisx0208.1990", and * "jisx0208.1996" are well-known names for the same encoding and * are represented by one encoding table: "jis0208". * * Results: * As above. If the name has no alias, the original name is returned. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static CONST char * GetEncodingAlias(name) CONST char *name; /* The name to look up. */ { EncodingAlias *aliasPtr; for (aliasPtr = encodingAliases; aliasPtr->aliasPattern != NULL; ) { if (Tcl_StringMatch((char *) name, aliasPtr->aliasPattern)) { return aliasPtr->realName; } aliasPtr++; } return name; }
2.15625
2
2024-11-18T22:28:36.531600+00:00
2019-04-15T19:25:24
e134c4c816aec136833f651bd12ca84ca6df48db
{ "blob_id": "e134c4c816aec136833f651bd12ca84ca6df48db", "branch_name": "refs/heads/master", "committer_date": "2019-04-15T19:25:24", "content_id": "664f8d6f2be3ace546d8dd9cd8e09a430d8267c3", "detected_licenses": [ "MIT" ], "directory_id": "e06319912bcb4902a0de42a4b525e06b264fea61", "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": 106736379, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6089, "license": "MIT", "license_type": "permissive", "path": "/A.S. 2017-2018/Battaglia navale/main.c", "provenance": "stackv2-0132.json.gz:83132", "repo_name": "MarcoBuster/ITIS", "revision_date": "2019-04-15T19:25:24", "revision_id": "1c5f627f4f48898a5dd05746a71372a425cd6bc0", "snapshot_id": "2b04636609a259fadf242f0e6a7d9938c18c0b80", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/MarcoBuster/ITIS/1c5f627f4f48898a5dd05746a71372a425cd6bc0/A.S. 2017-2018/Battaglia navale/main.c", "visit_date": "2021-10-27T03:57:24.267443" }
stackv2
/* * Implementare il gioco della battaglia navale in C. * Generata una griglia con delle navi di lunghezza minima 1 e massima 4 * e date le coordinate del lancio, stabilire se il missile ha fatto * l'acqua, ha fatto fuoco, ha colpito la nave o l'ha affondata completamente. * * (c) Marco Aceti, 2018. Some rights reserved. * See LICENSE file for more details. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> const int TABLE_SIZE = 10; const int MAX_SHIP_LENGTH = 4; const int MIN_SHIP_LENGTH = 1; const int SHIPS_NUMBER = 5; void popolateTable(int table[TABLE_SIZE][TABLE_SIZE]); void printTable(int table[TABLE_SIZE][TABLE_SIZE]); int getRandomNumber(int low, int high); void generateRandomTable(int table[TABLE_SIZE][TABLE_SIZE]); int sendMissle(int table[TABLE_SIZE][TABLE_SIZE], int x, int y); int main() { int table[TABLE_SIZE][TABLE_SIZE]; srand((unsigned int) time(0)); popolateTable(table); generateRandomTable(table); printTable(table); int x, y; int result; int water=0, near=0, hit=0, fired=0, attemps=0; do { printf("Inserisci le coordinate [coordinata X]: "); scanf("%d", &x); printf("Inserisci le coordinate [coordinata Y]: "); scanf("%d", &y); result = sendMissle(table, x, y); printf("\t"); switch (result) { case -1: printf("[ERRORE: Nave già colpita]"); break; case 0: water++; printf("[ACQUA]"); break; case 1: near++; printf("[FUOCO]"); break; case 2: hit++; printf("[COLPITO]"); break; case 3: fired++; printf("[AFFONDATO] - Affondate: %d/%d", fired, SHIPS_NUMBER); break; default: printf("[ERRORE]"); break; } printTable(table); attemps++; } while (fired < SHIPS_NUMBER); printf("\n\n-- Gioco terminato --"); printf("\n[Statistiche]"); printf("\nAcqua: %d\nFuoco: %d\nColpito: %d\nAffondato: %d\nMosse totali: %d", water, near, hit, fired, attemps); return 0; } void popolateTable(int table[TABLE_SIZE][TABLE_SIZE]) { int i, k; for (i=0; i<TABLE_SIZE; i++) { for (k=0; k<TABLE_SIZE; k++) { table[i][k] = 0; } } } void printTable(int table[TABLE_SIZE][TABLE_SIZE]) { int i, k; printf("\n"); for (i=0; i<TABLE_SIZE; i++) { if (i == 0) { printf("\t"); for (k=0; k<TABLE_SIZE; k++) printf("%d ", k); printf("\n\t"); for (k=0; k<TABLE_SIZE; k++) printf("--"); printf("\n"); } printf("%d | ", i); for (k=0; k<TABLE_SIZE; k++) { printf("%d ", table[i][k]); } printf("\n"); } } int getRandomNumber(int low, int high) { return (int) (low + ((float) rand() / RAND_MAX) * (high - low)); } void generateRandomTable(int table[TABLE_SIZE][TABLE_SIZE]) { int i; int rx, ry, rl, rd; // randomx, randomy, randomlength, randomdirection int diff; int failed=0, success=0; bool exit; do { exit = false; rx = getRandomNumber(0, TABLE_SIZE); ry = getRandomNumber(0, TABLE_SIZE); rl = getRandomNumber(MIN_SHIP_LENGTH, MAX_SHIP_LENGTH+1); rd = getRandomNumber(0, 4); switch (rd) { case 0: diff = rx + rl; break; case 1: diff = rx - rl; break; case 2: diff = ry + rl; break; case 3: diff = ry - rl; break; default: diff = -1; break; } if (diff > TABLE_SIZE || diff < 0) exit = true; for (i = 0; i < rl && !exit; i++) { if (table[rx][ry] != 0) exit = true; else { // table[rx][ry] = success+1; switch (rd) { case 0: rx++; break; case 1: rx--; break; case 2: ry++; break; case 3: ry--; break; default: ; } } } for (i = 0; i < rl && !exit; i++) { table[rx][ry] = success+1; switch (rd) { case 0: rx++; break; case 1: rx--; break; case 2: ry++; break; case 3: ry--; break; default: ; } } if (exit) failed++; else success++; } while (success < SHIPS_NUMBER && failed < TABLE_SIZE*TABLE_SIZE); // infinite-loop check if (failed >= TABLE_SIZE*TABLE_SIZE) { printf("Failed."); } } int sendMissle(int table[TABLE_SIZE][TABLE_SIZE], int x, int y) { if (table[x][y] < 0) return -1; // already hit else if (table[x][y] > 0) { table[x][y] = -table[x][y]; // hit int i, k; for (i=0; i<TABLE_SIZE; i++) for (k=0; k<TABLE_SIZE; k++) if (table[i][k] == abs(table[x][y])) return 2; // ship hit return 3; // ship fired } else if (table[x+1][y] > 0 || table[x][y+1] > 0 || table[x-1][y] > 0 || table[x][y-1] > 0) return 1; // a ship is near return 0; // no ship near }
3.109375
3
2024-11-18T22:28:36.754499+00:00
2012-09-07T05:52:19
7b650d5cec038f6e6c1b49214e284d86db8c0224
{ "blob_id": "7b650d5cec038f6e6c1b49214e284d86db8c0224", "branch_name": "refs/heads/master", "committer_date": "2012-09-07T05:52:19", "content_id": "c4c6fc760e9232bfc48895fe455f262b02164f33", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5568646cf2b3184948a02a40e0be992abccf64ec", "extension": "c", "filename": "unicode.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 1755156, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3924, "license": "Apache-2.0", "license_type": "permissive", "path": "/libfreerdp-utils/unicode.c", "provenance": "stackv2-0132.json.gz:83388", "repo_name": "tenchman/FreeRDP", "revision_date": "2012-09-07T05:52:19", "revision_id": "a7b44e51baf42fe4c0a81cda54cef36e0261c382", "snapshot_id": "428c8089f3dacb92b53621b567fccbf79551bb33", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tenchman/FreeRDP/a7b44e51baf42fe4c0a81cda54cef36e0261c382/libfreerdp-utils/unicode.c", "visit_date": "2021-01-18T07:53:31.575601" }
stackv2
/* FreeRDP: A Remote Desktop Protocol client. Unicode Utils Copyright 2011 Marc-Andre Moreau <[email protected]> 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 "config.h" #include <errno.h> #include <freerdp/utils/memory.h> #include <freerdp/utils/unicode.h> /* Convert pin/in_len from WINDOWS_CODEPAGE - return like xstrdup, 0-terminated */ char* freerdp_uniconv_in(UNICONV *uniconv, unsigned char* pin, size_t in_len) { unsigned char *conv_pin = pin; size_t conv_in_len = in_len; char *pout = xmalloc(in_len + 1), *conv_pout = pout; size_t conv_out_len = in_len; #ifdef HAVE_ICONV if (iconv(uniconv->in_iconv_h, (ICONV_CONST char **) &conv_pin, &conv_in_len, &conv_pout, &conv_out_len) == (size_t) - 1) { /* TODO: xrealloc if conv_out_len == 0 - it shouldn't be needed, but would allow a smaller initial alloc ... */ printf("freerdp_uniconv_in: iconv failure\n"); return 0; } #else while (conv_in_len >= 2) { if ((signed char)(*conv_pin) < 0) { printf("freerdp_uniconv_in: wrong input conversion of char %d\n", *conv_pin); } *conv_pout++ = *conv_pin++; if ((*conv_pin) != 0) { printf("freerdp_uniconv_in: wrong input conversion skipping non-zero char %d\n", *conv_pin); } conv_pin++; conv_in_len -= 2; conv_out_len--; } #endif if (conv_in_len > 0) { printf("freerdp_uniconv_in: conversion failure - %d chars left\n", (int) conv_in_len); } *conv_pout = 0; return pout; } /* Convert str from DEFAULT_CODEPAGE to WINDOWS_CODEPAGE and return buffer like xstrdup. * Buffer is 0-terminated but that is not included in the returned length. */ char* freerdp_uniconv_out(UNICONV *uniconv, char *str, size_t *pout_len) { size_t ibl = strlen(str), obl = 2 * ibl; /* FIXME: worst case */ char *pin = str, *pout0 = xmalloc(obl + 2), *pout = pout0; #ifdef HAVE_ICONV if (iconv(uniconv->out_iconv_h, (ICONV_CONST char **) &pin, &ibl, &pout, &obl) == (size_t) - 1) { printf("freerdp_uniconv_out: iconv() error\n"); return NULL; } #else while ((ibl > 0) && (obl > 0)) { if ((signed char)(*pin) < 0) { return NULL; } *pout++ = *pin++; *pout++ = 0; ibl--; obl -= 2; } #endif if (ibl > 0) { printf("freerdp_uniconv_out: string not fully converted - %d chars left\n", (int) ibl); } *pout_len = pout - pout0; *pout++ = 0; /* Add extra double zero termination */ *pout = 0; return pout0; } /* Uppercase a unicode string */ void freerdp_uniconv_uppercase(UNICONV *uniconv, char *wstr, int length) { int i; char* p; p = wstr; for (i = 0; i < length; i++) { if (p[i * 2] >= 'a' && p[i * 2] <= 'z') p[i * 2] = p[i * 2] - 32; } } UNICONV* freerdp_uniconv_new() { UNICONV *uniconv = xmalloc(sizeof(UNICONV)); memset(uniconv, '\0', sizeof(UNICONV)); #ifdef HAVE_ICONV uniconv->iconv = 1; uniconv->in_iconv_h = iconv_open(DEFAULT_CODEPAGE, WINDOWS_CODEPAGE); if (errno == EINVAL) { printf("Error opening iconv converter to %s from %s\n", DEFAULT_CODEPAGE, WINDOWS_CODEPAGE); } uniconv->out_iconv_h = iconv_open(WINDOWS_CODEPAGE, DEFAULT_CODEPAGE); if (errno == EINVAL) { printf("Error opening iconv converter to %s from %s\n", WINDOWS_CODEPAGE, DEFAULT_CODEPAGE); } #endif return uniconv; } void freerdp_uniconv_free(UNICONV *uniconv) { if (uniconv != NULL) { #ifdef HAVE_ICONV iconv_close(uniconv->in_iconv_h); iconv_close(uniconv->out_iconv_h); #endif xfree(uniconv); } }
2.640625
3
2024-11-18T22:28:38.228306+00:00
2011-06-14T07:08:11
ecf097d3699a4ffc42614536d98fc04b2fafe034
{ "blob_id": "ecf097d3699a4ffc42614536d98fc04b2fafe034", "branch_name": "refs/heads/master", "committer_date": "2011-06-14T07:08:11", "content_id": "84ecc567fcb743c576d102030d5841c516a9fa25", "detected_licenses": [ "Apache-2.0" ], "directory_id": "797c702a8cf3760273509c8f0bb39236e1435835", "extension": "c", "filename": "error.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 1908055, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2032, "license": "Apache-2.0", "license_type": "permissive", "path": "/lib/core/error.c", "provenance": "stackv2-0132.json.gz:83904", "repo_name": "bnoordhuis/selene", "revision_date": "2011-06-14T07:08:11", "revision_id": "b8e03061105b7ae4e842c55bcbdc5c85ed8f322d", "snapshot_id": "e5d36bb5d3ec0063c1984960faf12fb5d60ccd4f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/bnoordhuis/selene/b8e03061105b7ae4e842c55bcbdc5c85ed8f322d/lib/core/error.c", "visit_date": "2021-01-18T03:31:10.837019" }
stackv2
/* * Licensed to Selene developers ('Selene') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Selene licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef LINUX #define _GNU_SOURCE #endif #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "selene_error.h" selene_error_t* selene_error_create_impl(selene_status_t err, const char *msg, uint32_t line, const char *file) { selene_error_t *e; e = malloc(sizeof(*e)); e->err = err; e->msg = strdup(msg); e->line = line; e->file = strdup(file); return e; } selene_error_t * selene_error_createf_impl(selene_status_t err, uint32_t line, const char *file, const char *fmt, ...) { int rv; selene_error_t *e; va_list ap; e = malloc(sizeof(*e)); e->err = err; va_start(ap, fmt); rv = vasprintf((char **) &e->msg, fmt, ap); va_end(ap); if (rv == -1) { e->msg = strdup("vasprintf inside selene_error_createf_impl returned -1, you likely have larger problems here"); } e->line = line; e->file = strdup(file); return e; } void selene_error_clear(selene_error_t *err) { if (err) { free((void *) err->msg); free((void *) err->file); free(err); } }
2.171875
2
2024-11-18T22:28:38.616109+00:00
2022-11-23T14:16:15
3041d979813fcd55c6273d32f9e0f03b25cef6ce
{ "blob_id": "3041d979813fcd55c6273d32f9e0f03b25cef6ce", "branch_name": "refs/heads/master", "committer_date": "2022-11-23T14:16:15", "content_id": "0305249d1846a0fbe771948a72f49a68a7d0f953", "detected_licenses": [ "BSD-3-Clause-Open-MPI" ], "directory_id": "e16ebe774e710b19e78006bc45276161a26b40d9", "extension": "c", "filename": "psdot_.c", "fork_events_count": 56, "gha_created_at": "2018-06-30T23:24:28", "gha_event_created_at": "2022-11-23T14:16:16", "gha_language": "Fortran", "gha_license_id": "NOASSERTION", "github_id": 139287059, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 28063, "license": "BSD-3-Clause-Open-MPI", "license_type": "permissive", "path": "/PBLAS/SRC/psdot_.c", "provenance": "stackv2-0132.json.gz:84295", "repo_name": "Reference-ScaLAPACK/scalapack", "revision_date": "2022-11-23T14:16:15", "revision_id": "2072b8602f0a5a84d77a712121f7715c58a2e80d", "snapshot_id": "1f06618119a19c2b0af51ad7cdee61aee84d835d", "src_encoding": "UTF-8", "star_events_count": 108, "url": "https://raw.githubusercontent.com/Reference-ScaLAPACK/scalapack/2072b8602f0a5a84d77a712121f7715c58a2e80d/PBLAS/SRC/psdot_.c", "visit_date": "2022-12-02T05:15:46.251774" }
stackv2
/* --------------------------------------------------------------------- * * -- PBLAS routine (version 2.0) -- * University of Tennessee, Knoxville, Oak Ridge National Laboratory, * and University of California, Berkeley. * April 1, 1998 * * --------------------------------------------------------------------- */ /* * Include files */ #include "pblas.h" #include "PBpblas.h" #include "PBtools.h" #include "PBblacs.h" #include "PBblas.h" #ifdef __STDC__ void psdot_( Int * N, float * DOT, float * X, Int * IX, Int * JX, Int * DESCX, Int * INCX, float * Y, Int * IY, Int * JY, Int * DESCY, Int * INCY ) #else void psdot_( N, DOT, X, IX, JX, DESCX, INCX, Y, IY, JY, DESCY, INCY ) /* * .. Scalar Arguments .. */ Int * INCX, * INCY, * IX, * IY, * JX, * JY, * N; float * DOT; /* * .. Array Arguments .. */ Int * DESCX, * DESCY; float * X, * Y; #endif { /* * Purpose * ======= * * PSDOT forms the dot product of two subvectors, * * DOT := sub( X )**T * sub( Y ), * * where * * sub( X ) denotes X(IX,JX:JX+N-1) if INCX = M_X, * X(IX:IX+N-1,JX) if INCX = 1 and INCX <> M_X, and, * * sub( Y ) denotes Y(IY,JY:JY+N-1) if INCY = M_Y, * Y(IY:IY+N-1,JY) if INCY = 1 and INCY <> M_Y. * * Notes * ===== * * A description vector is associated with each 2D block-cyclicly dis- * tributed matrix. This vector stores the information required to * establish the mapping between a matrix entry and its corresponding * process and memory location. * * In the following comments, the character _ should be read as * "of the distributed matrix". Let A be a generic term for any 2D * block cyclicly distributed matrix. Its description vector is DESC_A: * * NOTATION STORED IN EXPLANATION * ---------------- --------------- ------------------------------------ * DTYPE_A (global) DESCA[ DTYPE_ ] The descriptor type. * CTXT_A (global) DESCA[ CTXT_ ] The BLACS context handle, indicating * the NPROW x NPCOL BLACS process grid * A is distributed over. The context * itself is global, but the handle * (the integer value) may vary. * M_A (global) DESCA[ M_ ] The number of rows in the distribu- * ted matrix A, M_A >= 0. * N_A (global) DESCA[ N_ ] The number of columns in the distri- * buted matrix A, N_A >= 0. * IMB_A (global) DESCA[ IMB_ ] The number of rows of the upper left * block of the matrix A, IMB_A > 0. * INB_A (global) DESCA[ INB_ ] The number of columns of the upper * left block of the matrix A, * INB_A > 0. * MB_A (global) DESCA[ MB_ ] The blocking factor used to distri- * bute the last M_A-IMB_A rows of A, * MB_A > 0. * NB_A (global) DESCA[ NB_ ] The blocking factor used to distri- * bute the last N_A-INB_A columns of * A, NB_A > 0. * RSRC_A (global) DESCA[ RSRC_ ] The process row over which the first * row of the matrix A is distributed, * NPROW > RSRC_A >= 0. * CSRC_A (global) DESCA[ CSRC_ ] The process column over which the * first column of A is distributed. * NPCOL > CSRC_A >= 0. * LLD_A (local) DESCA[ LLD_ ] The leading dimension of the local * array storing the local blocks of * the distributed matrix A, * IF( Lc( 1, N_A ) > 0 ) * LLD_A >= MAX( 1, Lr( 1, M_A ) ) * ELSE * LLD_A >= 1. * * Let K be the number of rows of a matrix A starting at the global in- * dex IA,i.e, A( IA:IA+K-1, : ). Lr( IA, K ) denotes the number of rows * that the process of row coordinate MYROW ( 0 <= MYROW < NPROW ) would * receive if these K rows were distributed over NPROW processes. If K * is the number of columns of a matrix A starting at the global index * JA, i.e, A( :, JA:JA+K-1, : ), Lc( JA, K ) denotes the number of co- * lumns that the process MYCOL ( 0 <= MYCOL < NPCOL ) would receive if * these K columns were distributed over NPCOL processes. * * The values of Lr() and Lc() may be determined via a call to the func- * tion PB_Cnumroc: * Lr( IA, K ) = PB_Cnumroc( K, IA, IMB_A, MB_A, MYROW, RSRC_A, NPROW ) * Lc( JA, K ) = PB_Cnumroc( K, JA, INB_A, NB_A, MYCOL, CSRC_A, NPCOL ) * * Arguments * ========= * * N (global input) INTEGER * On entry, N specifies the length of the subvectors to be * multiplied. N must be at least zero. * * DOT (local output) REAL array * On exit, DOT specifies the dot product of the two subvectors * sub( X ) and sub( Y ) only in their scope (See below for fur- * ther details). * * X (local input) REAL array * On entry, X is an array of dimension (LLD_X, Kx), where LLD_X * is at least MAX( 1, Lr( 1, IX ) ) when INCX = M_X and * MAX( 1, Lr( 1, IX+N-1 ) ) otherwise, and, Kx is at least * Lc( 1, JX+N-1 ) when INCX = M_X and Lc( 1, JX ) otherwise. * Before entry, this array contains the local entries of the * matrix X. * * IX (global input) INTEGER * On entry, IX specifies X's global row index, which points to * the beginning of the submatrix sub( X ). * * JX (global input) INTEGER * On entry, JX specifies X's global column index, which points * to the beginning of the submatrix sub( X ). * * DESCX (global and local input) INTEGER array * On entry, DESCX is an integer array of dimension DLEN_. This * is the array descriptor for the matrix X. * * INCX (global input) INTEGER * On entry, INCX specifies the global increment for the * elements of X. Only two values of INCX are supported in * this version, namely 1 and M_X. INCX must not be zero. * * Y (local input) REAL array * On entry, Y is an array of dimension (LLD_Y, Ky), where LLD_Y * is at least MAX( 1, Lr( 1, IY ) ) when INCY = M_Y and * MAX( 1, Lr( 1, IY+N-1 ) ) otherwise, and, Ky is at least * Lc( 1, JY+N-1 ) when INCY = M_Y and Lc( 1, JY ) otherwise. * Before entry, this array contains the local entries of the * matrix Y. * * IY (global input) INTEGER * On entry, IY specifies Y's global row index, which points to * the beginning of the submatrix sub( Y ). * * JY (global input) INTEGER * On entry, JY specifies Y's global column index, which points * to the beginning of the submatrix sub( Y ). * * DESCY (global and local input) INTEGER array * On entry, DESCY is an integer array of dimension DLEN_. This * is the array descriptor for the matrix Y. * * INCY (global input) INTEGER * On entry, INCY specifies the global increment for the * elements of Y. Only two values of INCY are supported in * this version, namely 1 and M_Y. INCY must not be zero. * * Further Details * =============== * * When the result of a vector-oriented PBLAS call is a scalar, this * scalar is set only within the process scope which owns the vector(s) * being operated on. Let sub( X ) be a generic term for the input vec- * tor(s). Then, the processes owning the correct the answer is determi- * ned as follows: if an operation involves more than one vector, the * processes receiving the result will be the union of the following set * of processes for each vector: * * If N = 1, M_X = 1 and INCX = 1, then one cannot determine if a pro- * cess row or process column owns the vector operand, therefore only * the process owning sub( X ) receives the correct result; * * If INCX = M_X, then sub( X ) is a vector distributed over a process * row. Each process in this row receives the result; * * If INCX = 1, then sub( X ) is a vector distributed over a process * column. Each process in this column receives the result; * * -- Written on April 1, 1998 by * Antoine Petitet, University of Tennessee, Knoxville 37996, USA. * * --------------------------------------------------------------------- */ /* * .. Local Scalars .. */ char scope, * top; Int OneBlock, OneDgrid, RRorCC, Square, Xcol, Xi, Xii, XinbD, Xinb1D, XisD, XisR, XisRow, Xj, Xjj, Xld, Xlinc, XmyprocD, XmyprocR, XnbD, XnpD, XnprocsD, XnprocsR, XprocD, XprocR, Xrow, Ycol, Yi, Yii, YinbD, Yinb1D, YisD, YisR, YisRow, Yj, Yjj, Yld, Ylinc, YmyprocD, YmyprocR, YnbD, YnpD, YnprocsD, YnprocsR, YprocD, YprocR, Yrow, cdst, csrc, ctxt, dst, info, ione=1, mycol, myrow, npcol, nprow, rdst, rsrc, size, src; PBTYP_T * type; VVDOT_T dot; /* * .. Local Arrays .. */ char * buf = NULL; Int Xd[DLEN_], Yd[DLEN_], dbuf[ DLEN_ ]; /* .. * .. Executable Statements .. * */ PB_CargFtoC( *IX, *JX, DESCX, &Xi, &Xj, Xd ); PB_CargFtoC( *IY, *JY, DESCY, &Yi, &Yj, Yd ); #ifndef NO_ARGCHK /* * Test the input parameters */ Cblacs_gridinfo( ( ctxt = Xd[CTXT_] ), &nprow, &npcol, &myrow, &mycol ); if( !( info = ( ( nprow == -1 ) ? -( 601 + CTXT_ ) : 0 ) ) ) { PB_Cchkvec( ctxt, "PSDOT", "X", *N, 1, Xi, Xj, Xd, *INCX, 6, &info ); PB_Cchkvec( ctxt, "PSDOT", "Y", *N, 1, Yi, Yj, Yd, *INCY, 11, &info ); } if( info ) { PB_Cabort( ctxt, "PSDOT", info ); return; } #endif DOT[REAL_PART] = ZERO; /* * Quick return if possible */ if( *N == 0 ) return; /* * Handle degenerate case */ if( ( *N == 1 ) && ( ( Xd[ M_ ] == 1 ) || ( Yd[ M_ ] == 1 ) ) ) { type = PB_Cstypeset(); PB_Cpdot11( type, *N, ((char *) DOT), ((char *) X), Xi, Xj, Xd, *INCX, ((char *) Y), Yi, Yj, Yd, *INCY, type->Fvvdotu ); return; } /* * Start the operations */ #ifdef NO_ARGCHK Cblacs_gridinfo( ( ctxt = Xd[ CTXT_ ] ), &nprow, &npcol, &myrow, &mycol ); #endif /* * Determine if sub( X ) is distributed or not */ if( ( XisRow = ( *INCX == Xd[M_] ) ) != 0 ) XisD = ( ( Xd[CSRC_] >= 0 ) && ( ( XnprocsD = npcol ) > 1 ) ); else XisD = ( ( Xd[RSRC_] >= 0 ) && ( ( XnprocsD = nprow ) > 1 ) ); /* * Determine if sub( Y ) is distributed or not */ if( ( YisRow = ( *INCY == Yd[M_] ) ) != 0 ) YisD = ( ( Yd[CSRC_] >= 0 ) && ( ( YnprocsD = npcol ) > 1 ) ); else YisD = ( ( Yd[RSRC_] >= 0 ) && ( ( YnprocsD = nprow ) > 1 ) ); /* * Are sub( X ) and sub( Y ) both row or column vectors ? */ RRorCC = ( ( XisRow && YisRow ) || ( !( XisRow ) && !( YisRow ) ) ); /* * XisD && YisD <=> both vector operands are indeed distributed */ if( XisD && YisD ) { /* * Retrieve sub( X )'s local information: Xii, Xjj, Xrow, Xcol */ PB_Cinfog2l( Xi, Xj, Xd, nprow, npcol, myrow, mycol, &Xii, &Xjj, &Xrow, &Xcol ); if( XisRow ) { XinbD = Xd[INB_]; XnbD = Xd[NB_]; Xld = Xd[LLD_]; Xlinc = Xld; XprocD = Xcol; XmyprocD = mycol; XprocR = Xrow; XmyprocR = myrow; XnprocsR = nprow; XisR = ( ( Xrow == -1 ) || ( XnprocsR == 1 ) ); Mfirstnb( Xinb1D, *N, Xj, XinbD, XnbD ); } else { XinbD = Xd[IMB_]; XnbD = Xd[MB_]; Xld = Xd[LLD_]; Xlinc = 1; XprocD = Xrow; XmyprocD = myrow; XprocR = Xcol; XmyprocR = mycol; XnprocsR = npcol; XisR = ( ( Xcol == -1 ) || ( XnprocsR == 1 ) ); Mfirstnb( Xinb1D, *N, Xi, XinbD, XnbD ); } /* * Retrieve sub( Y )'s local information: Yii, Yjj, Yrow, Ycol */ PB_Cinfog2l( Yi, Yj, Yd, nprow, npcol, myrow, mycol, &Yii, &Yjj, &Yrow, &Ycol ); if( YisRow ) { YinbD = Yd[INB_]; YnbD = Yd[NB_]; Yld = Yd[LLD_]; Ylinc = Yld; YprocD = Ycol; YmyprocD = mycol; YprocR = Yrow; YmyprocR = myrow; YnprocsR = nprow; YisR = ( ( Yrow == -1 ) || ( YnprocsR == 1 ) ); Mfirstnb( Yinb1D, *N, Yj, YinbD, YnbD ); } else { YinbD = Yd[IMB_]; YnbD = Yd[MB_]; Yld = Yd[LLD_]; Ylinc = 1; YprocD = Yrow; YmyprocD = myrow; YprocR = Ycol; YmyprocR = mycol; YnprocsR = npcol; YisR = ( ( Ycol == -1 ) || ( YnprocsR == 1 ) ); Mfirstnb( Yinb1D, *N, Yi, YinbD, YnbD ); } /* * Do sub( X ) and sub( Y ) span more than one process ? */ OneDgrid = ( ( XnprocsD == 1 ) && ( YnprocsD == 1 ) ); OneBlock = ( ( Xinb1D >= *N ) && ( Yinb1D >= *N ) ); /* * Are sub( X ) and sub( Y ) distributed in the same manner ? */ Square = ( ( Xinb1D == Yinb1D ) && ( XnbD == YnbD ) && ( XnprocsD == YnprocsD ) ); if( !( XisR ) ) { /* * sub( X ) is not replicated */ if( YisR ) { /* * If sub( X ) is not replicated, but sub( Y ) is, a process row or column * YprocR need to be selected. It will contain the non-replicated vector used * to perform the dot product computation. */ if( RRorCC ) { /* * sub( X ) and sub( Y ) are both row or column vectors */ if( ( OneDgrid || OneBlock || Square ) && ( XprocD == YprocD ) ) { /* * sub( X ) and sub( Y ) start in the same process row or column XprocD=YprocD. * Enforce a purely local operation by choosing YprocR to be equal to XprocR. */ YprocR = XprocR; } else { /* * Otherwise, communication has to occur, so choose the next process row or * column for YprocR to maximize the number of links, i.e reduce contention. */ YprocR = MModAdd1( XprocR, XnprocsR ); } } else { /* * sub( X ) and sub( Y ) are distributed in orthogonal directions, what is * chosen for YprocR does not really matter. Select the process origin. */ YprocR = XprocD; } } else { /* * Neither sub( X ) nor sub( Y ) are replicated. If I am not in process row or * column XprocR and not in process row or column YprocR, then quick return. */ if( ( XmyprocR != XprocR ) && ( YmyprocR != YprocR ) ) return; } } else { /* * sub( X ) is distributed and replicated (so no quick return possible) */ if( YisR ) { /* * sub( Y ) is distributed and replicated as well */ if( RRorCC ) { /* * sub( X ) and sub( Y ) are both row or column vectors */ if( ( OneDgrid || OneBlock || Square ) && ( XprocD == YprocD ) ) { /* * sub( X ) and sub( Y ) start in the same process row or column XprocD=YprocD. * Enforce a purely local operation by choosing XprocR and YprocR to be equal * to zero. */ XprocR = YprocR = 0; } else { /* * Otherwise, communication has to occur, so select YprocR to be zero and the * next process row or column for XprocR in order to maximize the number of * used links, i.e reduce contention. */ YprocR = 0; XprocR = MModAdd1( YprocR, YnprocsR ); } } else { /* * sub( X ) and sub( Y ) are distributed in orthogonal directions, select the * origin processes. */ XprocR = YprocD; YprocR = XprocD; } } else { /* * sub( Y ) is distributed, but not replicated */ if( RRorCC ) { /* * sub( X ) and sub( Y ) are both row or column vectors */ if( ( OneDgrid || OneBlock || Square ) && ( XprocD == YprocD ) ) { /* * sub( X ) and sub( Y ) start in the same process row or column XprocD=YprocD. * Enforce a purely local operation by choosing XprocR to be equal to YprocR. */ XprocR = YprocR; } else { /* * Otherwise, communication has to occur, so choose the next process row or * column for XprocR to maximize the number of links, i.e reduce contention. */ XprocR = MModAdd1( YprocR, YnprocsR ); } } else { /* * sub( X ) and sub( Y ) are distributed in orthogonal directions, what is * chosen for XprocR does not really matter. Select the origin process. */ XprocR = YprocD; } } } /* * Even if sub( X ) and/or sub( Y ) are replicated, only two process row or * column are active, namely XprocR and YprocR. If any of those operands is * replicated, broadcast will occur (unless there is an easy way out). */ type = PB_Cstypeset(); size = type->size; dot = type->Fvvdotu; /* * A purely operation occurs iff the operands start in the same process and if * either the grid is mono-dimensional or there is a single local block to be * operated with or if both operands are aligned. */ if( ( ( RRorCC && ( XprocD == YprocD ) && ( XprocR == YprocR ) ) || ( !( RRorCC ) && ( XprocD == YprocR ) && ( XprocR == YprocD ) ) ) && ( OneDgrid || OneBlock || ( RRorCC && Square ) ) ) { if( ( !XisR && ( XmyprocR == XprocR ) && !YisR && ( YmyprocR == YprocR ) ) || ( !XisR && YisR && ( YmyprocR == YprocR ) ) || ( !YisR && XisR && ( XmyprocR == XprocR ) ) || ( XisR && YisR ) ) { XnpD = PB_Cnumroc( *N, 0, Xinb1D, XnbD, XmyprocD, XprocD, XnprocsD ); YnpD = PB_Cnumroc( *N, 0, Yinb1D, YnbD, YmyprocD, YprocD, YnprocsD ); if( ( XnpD > 0 ) && ( YnpD > 0 ) ) { dot( &XnpD, ((char *) DOT), Mptr( ((char *) X), Xii, Xjj, Xld, size ), &Xlinc, Mptr( ((char *) Y), Yii, Yjj, Yld, size ), &Ylinc ); } } /* * Combine the local results in sub( X )'s scope */ if( ( XisR && YisR ) || ( XmyprocR == XprocR ) ) { scope = ( XisRow ? CROW : CCOLUMN ); top = PB_Ctop( &ctxt, COMBINE, &scope, TOP_GET ); Csgsum2d( ctxt, &scope, top, 1, 1, ((char *) DOT), 1, -1, 0 ); } if( RRorCC && XisR && YisR ) return; } else if( ( RRorCC && OneDgrid ) || OneBlock || Square ) { /* * Otherwise, it may be possible to compute the desired dot-product in a single * message exchange iff the grid is mono-dimensional and the operands are * distributed in the same direction, or there is just one block to be exchanged * or if both operands are similarly distributed in their respective direction. */ if( ( YmyprocR == YprocR ) ) { /* * The processes owning a piece of sub( Y ) send it to the corresponding * process owning s piece of sub ( X ). */ YnpD = PB_Cnumroc( *N, 0, Yinb1D, YnbD, YmyprocD, YprocD, YnprocsD ); if( YnpD > 0 ) { dst = XprocD + MModSub( YmyprocD, YprocD, YnprocsD ); dst = MPosMod( dst, XnprocsD ); if( XisRow ) { rdst = XprocR; cdst = dst; } else { rdst = dst; cdst = XprocR; } if( ( myrow == rdst ) && ( mycol == cdst ) ) { dot( &YnpD, ((char *) DOT), Mptr( ((char *) X), Xii, Xjj, Xld, size ), &Xlinc, Mptr( ((char *) Y), Yii, Yjj, Yld, size ), &Ylinc ); } else { if( YisRow ) Csgesd2d( ctxt, 1, YnpD, Mptr( ((char *) Y), Yii, Yjj, Yld, size ), Yld, rdst, cdst ); else Csgesd2d( ctxt, YnpD, 1, Mptr( ((char *) Y), Yii, Yjj, Yld, size ), Yld, rdst, cdst ); } } } if( XmyprocR == XprocR ) { /* * The processes owning a piece of sub( X ) receive the corresponding local * piece of sub( Y ), compute the local dot product and combine the results * within sub( X )'s scope. */ XnpD = PB_Cnumroc( *N, 0, Xinb1D, XnbD, XmyprocD, XprocD, XnprocsD ); if( XnpD > 0 ) { src = YprocD + MModSub( XmyprocD, XprocD, XnprocsD ); src = MPosMod( src, YnprocsD ); if( YisRow ) { rsrc = YprocR; csrc = src; } else { rsrc = src; csrc = YprocR; } if( ( myrow != rsrc ) || ( mycol != csrc ) ) { buf = PB_Cmalloc( XnpD * size ); if( YisRow ) Csgerv2d( ctxt, 1, XnpD, buf, 1, rsrc, csrc ); else Csgerv2d( ctxt, XnpD, 1, buf, XnpD, rsrc, csrc ); dot( &XnpD, ((char *) DOT), Mptr( ((char *) X), Xii, Xjj, Xld, size ), &Xlinc, buf, &ione ); if( buf ) free( buf ); } } if( XisRow ) { top = PB_Ctop( &ctxt, COMBINE, ROW, TOP_GET ); Csgsum2d( ctxt, ROW, top, 1, 1, ((char*)DOT), 1, -1, 0 ); } else { top = PB_Ctop( &ctxt, COMBINE, COLUMN, TOP_GET ); Csgsum2d( ctxt, COLUMN, top, 1, 1, ((char*)DOT), 1, -1, 0 ); } } } else { /* * General case, copy sub( Y ) within sub( X )'s scope, compute the local * results and combine them within sub( X )'s scope. */ XnpD = PB_Cnumroc( *N, 0, Xinb1D, XnbD, XmyprocD, XprocD, XnprocsD ); if( XisRow ) { PB_Cdescset( dbuf, 1, *N, 1, Xinb1D, 1, XnbD, XprocR, XprocD, ctxt, 1 ); } else { PB_Cdescset( dbuf, *N, 1, Xinb1D, 1, XnbD, 1, XprocD, XprocR, ctxt, MAX( 1, XnpD ) ); } if( ( XmyprocR == XprocR ) && ( XnpD > 0 ) ) buf = PB_Cmalloc( XnpD * size ); if( YisRow ) { PB_Cpaxpby( type, NOCONJG, 1, *N, type->one, ((char *) Y), Yi, Yj, Yd, ROW, type->zero, buf, 0, 0, dbuf, ( XisRow ? ROW : COLUMN ) ); } else { PB_Cpaxpby( type, NOCONJG, *N, 1, type->one, ((char *) Y), Yi, Yj, Yd, COLUMN, type->zero, buf, 0, 0, dbuf, ( XisRow ? ROW : COLUMN ) ); } if( XmyprocR == XprocR ) { if( XnpD > 0 ) { dot( &XnpD, ((char *) DOT), Mptr( ((char *) X), Xii, Xjj, Xld, size ), &Xlinc, buf, &ione ); if( buf ) free( buf ); } if( XisRow ) { top = PB_Ctop( &ctxt, COMBINE, ROW, TOP_GET ); Csgsum2d( ctxt, ROW, top, 1, 1, ((char*)DOT), 1, -1, 0 ); } else { top = PB_Ctop( &ctxt, COMBINE, COLUMN, TOP_GET ); Csgsum2d( ctxt, COLUMN, top, 1, 1, ((char*)DOT), 1, -1, 0 ); } } } /* * Send the DOT product result within sub( Y )'s scope */ if( XisR || YisR ) { /* * Either sub( X ) or sub( Y ) are replicated, so that every process should have * the result -> broadcast it orthogonally from sub( X )'s direction. */ if( XisRow ) { top = PB_Ctop( &ctxt, BCAST, COLUMN, TOP_GET ); if( XmyprocR == XprocR ) Csgebs2d( ctxt, COLUMN, top, 1, 1, ((char*)DOT), 1 ); else Csgebr2d( ctxt, COLUMN, top, 1, 1, ((char*)DOT), 1, XprocR, XmyprocD ); } else { top = PB_Ctop( &ctxt, BCAST, ROW, TOP_GET ); if( XmyprocR == XprocR ) Csgebs2d( ctxt, ROW, top, 1, 1, ((char*)DOT), 1 ); else Csgebr2d( ctxt, ROW, top, 1, 1, ((char*)DOT), 1, XmyprocD, XprocR ); } } else { /* * Neither sub( X ) nor sub( Y ) are replicated */ if( RRorCC ) { /* * Both sub( X ) are distributed in the same direction -> the process row or * column XprocR sends the result to the process row or column YprocR. */ if( XprocR != YprocR ) { if( XmyprocR == XprocR ) { if( XisRow ) Csgesd2d( ctxt, 1, 1, ((char *) DOT), 1, YprocR, YmyprocD ); else Csgesd2d( ctxt, 1, 1, ((char *) DOT), 1, YmyprocD, YprocR ); } else if( YmyprocR == YprocR ) { if( XisRow ) Csgerv2d( ctxt, 1, 1, ((char *) DOT), 1, XprocR, XmyprocD ); else Csgerv2d( ctxt, 1, 1, ((char *) DOT), 1, XmyprocD, XprocR ); } } } else { /* * Otherwise, the process at the intersection of sub( X )'s and sub( Y )'s * scope, broadcast the result within sub( Y )'s scope. */ if( YmyprocR == YprocR ) { if( YisRow ) { top = PB_Ctop( &ctxt, BCAST, ROW, TOP_GET ); if( YmyprocD == XprocR ) Csgebs2d( ctxt, ROW, top, 1, 1, ((char*)DOT), 1 ); else Csgebr2d( ctxt, ROW, top, 1, 1, ((char*)DOT), 1, YprocR, XprocR ); } else { top = PB_Ctop( &ctxt, BCAST, COLUMN, TOP_GET ); if( YmyprocD == XprocR ) Csgebs2d( ctxt, COLUMN, top, 1, 1, ((char*)DOT), 1 ); else Csgebr2d( ctxt, COLUMN, top, 1, 1, ((char*)DOT), 1, XprocR, YprocR ); } } } } } else if( !( XisD ) && YisD ) { /* * sub( X ) is not distributed and sub( Y ) is distributed. */ type = PB_Cstypeset(); PB_CpdotND( type, *N, ((char *) DOT), ((char *) X), Xi, Xj, Xd, *INCX, ((char *) Y), Yi, Yj, Yd, *INCY, type->Fvvdotu ); } else if( XisD && !( YisD ) ) { /* * sub( X ) is distributed and sub( Y ) is not distributed. */ type = PB_Cstypeset(); PB_CpdotND( type, *N, ((char *) DOT), ((char *) Y), Yi, Yj, Yd, *INCY, ((char *) X), Xi, Xj, Xd, *INCX, type->Fvvdotu ); } else { /* * Neither sub( X ) nor sub( Y ) are distributed */ type = PB_Cstypeset(); PB_CpdotNN( type, *N, ((char *) DOT), ((char *) X), Xi, Xj, Xd, *INCX, ((char *) Y), Yi, Yj, Yd, *INCY, type->Fvvdotu ); } /* * End of PSDOT */ }
2.109375
2
2024-11-18T22:28:38.700861+00:00
2019-07-29T23:42:07
38727503051cdef934150cc493c733cb7708e186
{ "blob_id": "38727503051cdef934150cc493c733cb7708e186", "branch_name": "refs/heads/master", "committer_date": "2019-07-29T23:42:07", "content_id": "486cc950cd3569b81f714df7d8467ca6d3d99cf2", "detected_licenses": [ "Apache-2.0" ], "directory_id": "565fcb5c72eb641de24b0fb874bf143f7b973aad", "extension": "c", "filename": "ui_console.c", "fork_events_count": 2, "gha_created_at": "2020-06-05T06:10:13", "gha_event_created_at": "2020-06-05T06:10:14", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 269545011, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7027, "license": "Apache-2.0", "license_type": "permissive", "path": "/ble-profiles/sources/apps/app/common/ui_console.c", "provenance": "stackv2-0132.json.gz:84425", "repo_name": "tuyafei/cordio", "revision_date": "2019-07-29T23:42:07", "revision_id": "eb18d61b2c139963cb9b67c0057f5be5c6fb5521", "snapshot_id": "9b5b743a409559fcd714f6213410ac580af2570b", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/tuyafei/cordio/eb18d61b2c139963cb9b67c0057f5be5c6fb5521/ble-profiles/sources/apps/app/common/ui_console.c", "visit_date": "2022-03-14T16:08:34.458416" }
stackv2
/*************************************************************************************************/ /*! * \file * * \brief User Interface - Console * * Copyright (c) 2017-2019 Arm Ltd. * * Copyright (c) 2019 Packetcraft, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*************************************************************************************************/ #include <string.h> #include "wsf_types.h" #include "wsf_assert.h" #include "util/bda.h" #include "app_api.h" #include "app_main.h" #include "app_db.h" #include "app_cfg.h" #include "ui_api.h" #include "wsf_trace.h" /************************************************************************************************** Function Prototypes **************************************************************************************************/ /*! Action Function Prototypes */ static void uiConsoleDispSplash(const UiSplashScreen_t *pSplash); static void uiConsoleDispMenu(const UiMenu_t *pMenu); static void uiConsoleDispDialog(const UiDialog_t *pDialog); static void uiConsoleProcessKey(uint8_t input); /************************************************************************************************** Local Variables **************************************************************************************************/ /* Console Control Block */ struct { int8_t alphaNumOffset; } uiConsoleCb; /* Console display action functions */ UiActionTbl_t uiConsoleActionTbl = { uiConsoleDispSplash, uiConsoleDispMenu, uiConsoleDispDialog, uiConsoleProcessKey }; /*************************************************************************************************/ /*! * \brief Process a key press from the user * * \param key User keypress. * * \return None */ /*************************************************************************************************/ static void uiConsoleProcessKey(uint8_t key) { UiDialog_t *pDialog; switch(UiCb.activeScreenType) { case UI_SCREEN_SPLASH: if ((key >= '0' && key <= '9') || (key == '\r')) { /* Jump to main menu on any key */ UiLoadMenu(UiCb.pMainMenu); } break; case UI_SCREEN_MENU: if (key >= '0' && key <= '9') { UiSelection(key - '0'); } break; case UI_SCREEN_DIALOG: pDialog = (UiDialog_t*) UiCb.pActiveScreen; if (pDialog->type == UI_DLG_TYPE_INPUT_SELECT) { if (key > '0' && key <= '9') { /* User pressed a number from 1 - 9 for selection */ UiSelection(key - '0'); } else if (key == '\r') { /* User pressed enter on pause screen */ UiSelection(0); } } else { if (uiConsoleCb.alphaNumOffset < pDialog->entryMaxLen) { /* TODO: Add backspace key? */ /* User in process of entering alpha numeric input */ pDialog->pEntry[uiConsoleCb.alphaNumOffset++] = key; } else { pDialog->pEntry[uiConsoleCb.alphaNumOffset] = '\0'; uiConsoleCb.alphaNumOffset = 0; /* Notify callback of selection */ UiSelection(0); /* Exit to parent */ UiLoadMenu(pDialog->base.pParentMenu); } } break; default: break; } } /*************************************************************************************************/ /*! * \brief Display a splash screen on a Console * * \param pSplash Pointer to the splash screen object to display. * * \return None */ /*************************************************************************************************/ static void uiConsoleDispSplash(const UiSplashScreen_t *pSplash) { /* Print the splash widget identifier */ UiConsolePrintLn("{Splash}"); /* Print splash screen */ UiConsolePrint(pSplash->pAppName); UiConsolePrint(", "); UiConsolePrintLn(pSplash->pAppVer); UiConsolePrintLn(pSplash->pCopyright); UiConsoleFlush(); } /*************************************************************************************************/ /*! * \brief Display a menu on a Console * * \param pMenu Pointer to the menu object to display. * * \return None */ /*************************************************************************************************/ static void uiConsoleDispMenu(const UiMenu_t *pMenu) { int8_t i; char ch[2]; /* Print the menu widget identifier */ UiConsolePrint("\r\n"); UiConsolePrintLn("{Menu}"); /* Print the title to the Console */ UiConsolePrintLn(pMenu->pTitle); /* Print the menu items */ for (i = 0; i < pMenu->numItems; i++) { UiConsolePrint(" "); ch[0] = '1' + i; ch[1] = '\0'; UiConsolePrint(ch); UiConsolePrint(". "); UiConsolePrintLn(pMenu->pItems[i]); } UiConsolePrint("\r\n"); UiConsolePrint("Choice? "); UiConsoleFlush(); } /*************************************************************************************************/ /*! * \brief Display a dialog on a Console * * \param pDialog Pointer to the dialog object to display. * * \return None */ /*************************************************************************************************/ static void uiConsoleDispDialog(const UiDialog_t *pDialog) { int8_t i; char ch[2]; /* Print the dialog widget identifier */ UiConsolePrint("\r\n"); UiConsolePrintLn("{Dialog}"); /* Print the title to the Console */ UiConsolePrintLn(pDialog->pTitle); /* Print the message to the Console */ UiConsolePrintLn(pDialog->pMsg); if (pDialog->type == UI_DLG_TYPE_INPUT_SELECT) { if (pDialog->numSelectItems == 0) { UiConsolePrintLn("ENTER to continue"); } else { /* Print the dialog items */ for (i = 0; i < pDialog->numSelectItems; i++) { UiConsolePrint(" "); ch[0] = '1' + i; ch[1] = '\0'; UiConsolePrint(ch); UiConsolePrint(". "); UiConsolePrintLn(pDialog->pSelectItems[i]); } } } else { /* Print prompt */ UiConsolePrint("> "); UiConsolePrint(pDialog->pEntry); } UiConsoleFlush(); } /*************************************************************************************************/ /*! * \brief Initialize the Console User Interface * * \return None */ /*************************************************************************************************/ void UiConsoleInit(void) { uiConsoleCb.alphaNumOffset = 0; UiRegisterDisplay(uiConsoleActionTbl, UI_DISPLAY_CONSOLE); }
2.171875
2
2024-11-18T22:28:38.794354+00:00
2015-08-21T23:14:50
54d1db11fbb92ee6264d4d2430bc62073c0c2539
{ "blob_id": "54d1db11fbb92ee6264d4d2430bc62073c0c2539", "branch_name": "refs/heads/master", "committer_date": "2015-08-21T23:14:50", "content_id": "12993c67a411d16583ca9e17711d343c787c533a", "detected_licenses": [ "Unlicense" ], "directory_id": "ef8dbeac9d61def2f9ace2529e4ff356af34f3bc", "extension": "h", "filename": "spi.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 41179799, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2556, "license": "Unlicense", "license_type": "permissive", "path": "/basic/spi-dma/SPI_DMA/spi.h", "provenance": "stackv2-0132.json.gz:84553", "repo_name": "iiKoe/XmegaFun", "revision_date": "2015-08-21T23:14:50", "revision_id": "a16d3de0b6229cc327adddb894c2d753d5d7e5d0", "snapshot_id": "25052794f5928ca1998421e23693b1f9009bf953", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iiKoe/XmegaFun/a16d3de0b6229cc327adddb894c2d753d5d7e5d0/basic/spi-dma/SPI_DMA/spi.h", "visit_date": "2021-01-23T13:22:44.519980" }
stackv2
/************************************************************************************ Title : Header file for the xmega spi library (spi.c) Author: Vito https://github.com/iiKoe File: oled.h, version 1.0, 05/02/2013 Software: AVR-GCC 4.6.2 Hardware: any AVR XMEGA Code: include spi.h in main code ************************************************************************************/ /** DESCRIPTION This basic "library" makes it easeyer to use HW SPI or UART SPI */ #ifndef SPI_H_ #define SPI_H_ /************************************************ * * HARDWARE SPI MODE * *************************************************/ /** * @name Port decelerations for the HW-SPI */ #define SPI_PORT PORTC #define SPI SPIC /** * @name Pin decelerations for the HW-SPI */ #define SPI_MOSI PIN5_bm #define SPI_MISO PIN6_bm #define SPI_SS PIN4_bm #define SPI_CLK PIN7_bm #define SPI_SS_SET() (SPI_PORT.OUTSET = SPI_SS) #define SPI_SS_CLR() (SPI_PORT.OUTCLR = SPI_SS) /** @brief Setup Hardware SPI in Master mode @param none @return none */ void SPI_master_setup(void); /** @brief Write 8-bit SPI data using HW-SPI @param 8-bit data @return none */ void SPI_master_write_data(uint8_t data); /** @brief Read 8-bit SPI data using HW-SPI @param none @return 8-bit data */ uint8_t SPI_master_read_data(void); /************************************************ * * USART SPI MODE * *************************************************/ /** * @name Port decelerations for the UART-SPI */ #define USS_PORT PORTD #define USPI_PORT PORTD #define USPI USARTD0 /** * @name Pin decelerations for the UART-SPI */ #define USPI_MOSI PIN3_bm //TX #define USPI_MISO PIN2_bm //RX #define USPI_SS PIN4_bm //SS #define USPI_CLK PIN1_bm //XCK0 #define USPI_SS_SET() (USS_PORT.OUTSET = USPI_SS) #define USPI_SS_CLR() (USS_PORT.OUTCLR = USPI_SS) /** @brief Setup UART SPI in Master mode @param none @return none */ void USPI_master_setup(void); /** @brief Write 8-bit SPI data using UART-SPI @param 8-bit data @return none */ void USPI_master_write_data(uint8_t data); /** @brief Read 8-bit SPI data using UART-SPI @param none @return 8-bit data */ uint8_t USPI_master_read_data(void); #endif /* SPI_H_ */
2.171875
2
2024-11-18T22:28:38.929828+00:00
2019-12-05T16:14:30
151ebaaaa34c5ad872bff693fdbe7073335b5aa7
{ "blob_id": "151ebaaaa34c5ad872bff693fdbe7073335b5aa7", "branch_name": "refs/heads/master", "committer_date": "2019-12-05T16:14:30", "content_id": "0d8b874f25c719032131314d4ab16302d30fe4d9", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "8a8193a26c57c3d8e4dd4667572e599c3d538df7", "extension": "c", "filename": "sonometer_task.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 180425866, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4084, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/freeRTOS/src/sonometer_task.c", "provenance": "stackv2-0132.json.gz:84681", "repo_name": "alesuarez/soniforo", "revision_date": "2019-12-05T16:14:30", "revision_id": "e44775826a583b072a95caf43f0b9a207e8d1753", "snapshot_id": "c8deb2d3f3325577a383784ede03839fcb6c0d80", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alesuarez/soniforo/e44775826a583b072a95caf43f0b9a207e8d1753/freeRTOS/src/sonometer_task.c", "visit_date": "2020-05-07T10:39:18.116161" }
stackv2
#include "sonometer_task.h" #include "task.h" #include "sapi.h" #include "peripheral_driver.h" #define MUY_BAJO 4 #define BAJO 3 #define MEDIO 2 #define ALTO 1 #define alpha 0.05 #define VENTANA_MUESTRA 20 #define CANTIDAD_MUESTRA 10 #define PRIMERA_VENTANA 10 #define MUESTRA_VENTANA_VENTANA 10 static void updateSignalPowerValue( uint16_t); void sonomterTask(void * a) { portTickType xPeriodicity = 200 / portTICK_RATE_MS; portTickType xLastWakeTime = xTaskGetTickCount(); uint16_t muestra = 0; uint16_t adc_filtrado = 0; uint16_t maxMuestra = 0; uint16_t minMuestra = 1024; uint16_t contadorMuestras = 0; uint16_t indexVentana = 0; uint16_t ventanaMuestras[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint16_t promVentana = 0; uint16_t muestraVentana = 0; uint16_t maxMuestraVentana = 0; uint16_t minMuestraVentana = 0; uint16_t indexMuestraVentana = 0; uint16_t contadorMuestraVentana = 0; uint16_t promMuestraVentana = 0; uint16_t ventanaMuestrasVentana[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint16_t otherWindows[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint16_t contadorOtherWindows = 0; uint16_t indexOtherWindows = 0; uint16_t promOtherWindows = 0; uint16_t valorFinal = 0; // ---------- REPETIR POR SIEMPRE -------------------------- while (TRUE) { //gpioToggle(LEDB); // Envia la tarea al estado bloqueado durante xPeriodicity (delay periodico) muestra = adcRead(CH1); if (muestra > maxMuestra) { maxMuestra = muestra; } if (muestra < minMuestra) { minMuestra = muestra; } if (contadorMuestras >= CANTIDAD_MUESTRA) { taskENTER_CRITICAL(); ventanaMuestras[indexVentana] = maxMuestra - minMuestra; taskEXIT_CRITICAL(); indexVentana++; contadorMuestras = 0; maxMuestra = 0; minMuestra = 1024; } if (indexVentana >= VENTANA_MUESTRA) { indexVentana = 0; } contadorMuestras++; for (int i = 0; i < PRIMERA_VENTANA; i++) { promVentana += ventanaMuestras[i]; } muestraVentana = promVentana / PRIMERA_VENTANA; if (muestraVentana > maxMuestraVentana) { maxMuestraVentana = muestraVentana; } if (muestraVentana > minMuestraVentana) { minMuestraVentana = muestraVentana; } contadorMuestraVentana++; if (contadorMuestraVentana >= MUESTRA_VENTANA_VENTANA) { ventanaMuestrasVentana[indexMuestraVentana] = (maxMuestraVentana + minMuestraVentana) / 2; indexMuestraVentana++; maxMuestraVentana = 0; minMuestraVentana = 1024; contadorMuestraVentana = 0; } if (indexMuestraVentana >= MUESTRA_VENTANA_VENTANA) { indexMuestraVentana = 0; } for (int i = 0; i < MUESTRA_VENTANA_VENTANA; i++) { promMuestraVentana += ventanaMuestrasVentana[i]; } contadorOtherWindows++; if (contadorOtherWindows >= MUESTRA_VENTANA_VENTANA) { otherWindows[indexOtherWindows] = promMuestraVentana / MUESTRA_VENTANA_VENTANA; indexOtherWindows++; contadorOtherWindows = 0; } for (int i = 0; i < MUESTRA_VENTANA_VENTANA; i++) { promOtherWindows += otherWindows[i]; } if (indexOtherWindows >= MUESTRA_VENTANA_VENTANA) { indexOtherWindows = 0; } valorFinal = promOtherWindows / MUESTRA_VENTANA_VENTANA; adc_filtrado = (alpha * valorFinal) + ((1 - alpha) * adc_filtrado); updateSignalPowerValue(adc_filtrado); promVentana = 0; promMuestraVentana = 0; promOtherWindows = 0; vTaskDelayUntil(&xLastWakeTime, xPeriodicity); } } static void updateSignalPowerValue(uint16_t signal) { if (signal < 400) { /*gpioWrite(LED3, ON); gpioWrite(LED2, OFF); gpioWrite(LED1, OFF); gpioWrite(LEDB, OFF);*/ setSignalPower(MUY_BAJO); } if (signal > 500 & signal < 600) { /*gpioWrite(LED3, ON); gpioWrite(LED2, ON); gpioWrite(LED1, OFF); gpioWrite(LEDB, OFF);*/ setSignalPower(BAJO); } if (signal > 600 & signal < 700) { /*gpioWrite(LED3, ON); gpioWrite(LED2, ON); gpioWrite(LED1, ON); gpioWrite(LEDB, OFF);*/ setSignalPower(MEDIO); } if (signal > 700) { /*gpioWrite(LED3, ON); gpioWrite(LED2, ON); gpioWrite(LED1, ON); gpioWrite(LEDB, ON);*/ setSignalPower(ALTO); } }
2.21875
2
2024-11-18T22:28:39.026868+00:00
2020-09-08T23:00:26
c1d196b81cb4633048fdee0c004cdae6b9bbb481
{ "blob_id": "c1d196b81cb4633048fdee0c004cdae6b9bbb481", "branch_name": "refs/heads/main", "committer_date": "2020-09-08T23:06:46", "content_id": "419f1778407e926bb323d824b2029f0585e2e411", "detected_licenses": [ "MIT" ], "directory_id": "a5b3ab27e358dddf9988f8398058d854049c8fd0", "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": 293157920, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3486, "license": "MIT", "license_type": "permissive", "path": "/projects/holub/ex-1.4/main.c", "provenance": "stackv2-0132.json.gz:84809", "repo_name": "macmade/XCC-Compiler-Experiments", "revision_date": "2020-09-08T23:00:26", "revision_id": "22932d1c21a9dcf4ed8a99c79b62101e0f6c8ac4", "snapshot_id": "6fde737bbfafe051c3708f32848a6d62148742a5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/macmade/XCC-Compiler-Experiments/22932d1c21a9dcf4ed8a99c79b62101e0f6c8ac4/projects/holub/ex-1.4/main.c", "visit_date": "2023-07-03T17:51:51.021506" }
stackv2
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2020 Jean-David Gadina - www.xs-labs.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ /*! * @file main.c * @copyright (c) 2020, Jean-David Gadina - www.xs-labs.com * @dicussion Adapted from "Compiler Design in C" by Allen I. Holub. * ISBN 0-13-155045-4 - https://holub.com/compiler */ #include <stdlib.h> #include <stdio.h> #include "Parser.h" #include "Variable.h" int main( void ) { VariableRef v1; VariableRef v2; VariableRef v3; VariableRef v4; VariableRef v5; v1 = Variable_Create(); v2 = Variable_Create(); v3 = Variable_Create(); v4 = Variable_Create(); v5 = Variable_Create(); { StringRef name; name = String_CreateWithCString( "var1" ); Variable_SetName( v1, name ); Variable_AddQualifier( v1, QualifierConst ); Variable_AddQualifier( v1, QualifierVolatile ); String_Release( name ); } { StringRef name; name = String_CreateWithCString( "var2" ); Variable_SetName( v2, name ); Variable_SetType( v2, TypeDouble ); Variable_SetAsArray( v2, 42 ); String_Release( name ); } { StringRef name; StringRef id; name = String_CreateWithCString( "var3" ); id = String_CreateWithCString( "TestStruct" ); Variable_SetName( v3, name ); Variable_SetAsStruct( v3, id ); String_Release( name ); String_Release( id ); } { StringRef name; name = String_CreateWithCString( "var4" ); Variable_SetName( v4, name ); Variable_AddQualifier( v4, QualifierConst ); Variable_SetAsPointer( v4, v1 ); String_Release( name ); } { StringRef name; name = String_CreateWithCString( "var5" ); Variable_SetName( v5, name ); Variable_SetAsPointer( v5, v4 ); String_Release( name ); } Variable_PrintDescription( v1, stdout ); Variable_PrintDescription( v2, stdout ); Variable_PrintDescription( v3, stdout ); Variable_PrintDescription( v4, stdout ); Variable_PrintDescription( v5, stdout ); Variable_Release( v1 ); Variable_Release( v2 ); return EXIT_SUCCESS; }
2.09375
2
2024-11-18T22:28:39.102123+00:00
2019-09-27T05:45:41
6cf7e997625978a804bec8a341f81d868c5dca10
{ "blob_id": "6cf7e997625978a804bec8a341f81d868c5dca10", "branch_name": "refs/heads/master", "committer_date": "2019-09-27T05:45:41", "content_id": "36074317b28e51704dee0c84ab301e69a25cb1bd", "detected_licenses": [ "MIT" ], "directory_id": "eb4fe7385bda4411b81f971a4b1e97d1867b15a2", "extension": "c", "filename": "permutations.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": 8293, "license": "MIT", "license_type": "permissive", "path": "/lib/permutations.c", "provenance": "stackv2-0132.json.gz:84939", "repo_name": "JKTG94/Lisp", "revision_date": "2019-09-27T05:45:41", "revision_id": "9431587a1e21b0bd09749c1ffb30cdd6dc89a5e5", "snapshot_id": "415437513ce477ec671a77fa9172258ab66b90e6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JKTG94/Lisp/9431587a1e21b0bd09749c1ffb30cdd6dc89a5e5/lib/permutations.c", "visit_date": "2022-02-23T11:01:10.949467" }
stackv2
#include <permutations.h> #include <limits.h> #include <assert.h> #ifdef __cplusplus #include <cstdint> #else #include <stdint.h> #endif // static forward declarations static inline int find_largest_mobile(const permuter *p); static void reset_directions(permuter *p); static int compare(const permuter *p, int i, int j); static inline bool is_mobile(const permuter *p, int i); static inline void *permuter_ith(const permuter *p, int i); static inline void swap(permuter *p, int i, int j); static inline void swap_facing(permuter *p, int i); static inline void swap_adjacent(permuter *p, int i, enum Direction dir); static inline int direction_arr_len(int num_elems); static enum Direction ith_direction(const permuter *p, int i); static inline void set_ith_direction(permuter *p, int i, enum Direction direction); static inline void flip_ith_direction(permuter *p, int i); static int ith_false(const bool booleans[], size_t len, int i); static inline int div_round_up(int numer, int denom); /** * @struct permuter * @brief encapsulates the metadata required to perform the * Steinhaus–Johnson–Trotter algorithm so that the user of the * API doesn't need to understand the algorithm */ struct permuter { int n; // number of elements to take the permutation of size_t elem_size; // the size of each element void *elems; // pointer to the elements void *tmp; // temporary element pointer for swapping elements CompareFn cmp; // comparison function between elements int index; // number of the current permutation uint8_t directions[]; // bit-array storing directions of each element of size n }; permuter *new_permuter(void *elems, int nelems, size_t elem_size, CompareFn cmp) { assert(elems != NULL); permuter *p = malloc(sizeof(permuter) + direction_arr_len(nelems)); if (p == NULL) return NULL; // Allocate space for temporary element used to swapping p->tmp = malloc(elem_size); if (p->tmp == NULL) { free(p); return NULL; } p->n = nelems; p->elem_size = elem_size; p->elems = elems; p->cmp = cmp; reset_permuter(p); // set all the directions to "left" return p; } void *get_permutation(const permuter *p) { assert(p != NULL); return p->elems; } int permutation_index(const permuter *p) { assert(p != NULL); return p->index; } permuter *new_cstring_permuter(const char *string) { assert(string != 0); char *str = strdup(string); qsort(str, strlen(str), sizeof(char), cmp_char); return new_permuter(str, strlen(str), sizeof(char), cmp_char); } void cstring_permuter_dispose(permuter *p) { assert(p != NULL); free(p->elems); permuter_dispose(p); } int cmp_char(const void *pchar1, const void *pchar2) { assert(pchar1 != NULL); assert(pchar2 != NULL); char char1 = *(const char *) pchar1; char char2 = *(const char *) pchar2; return char1 - char2; } void permuter_dispose(permuter *p) { assert(p != NULL); free(p->tmp); free(p); } void *next_permutation(permuter *p) { assert(p != NULL); int max_mobile_idx = find_largest_mobile(p); if (max_mobile_idx < 0) return NULL; // no more permutations // flip the direction of all elements larger than the swap element for (int i = 0; i < p->n; ++i) if (compare(p, i, max_mobile_idx) > 0) flip_ith_direction(p, i); // swap the largest mobile element with the element adjacent to // it in the direction that it is facing swap_facing(p, max_mobile_idx); p->index++; return p->elems; } void reset_permuter(permuter *p) { assert(p != NULL); qsort(p->elems, p->n, p->elem_size, p->cmp); reset_directions(p); p->index = 0; } int permuter_size(permuter *p) { assert(p != NULL); return p->n; } void nth_combination(const void *elements, size_t elem_size, int n, const void *end, const void *combination) { int i = 0; while (n != 0) { int first_offset = __builtin_ctz(n); // Find offset of first bit void *dst = (char *) combination + i * elem_size; void *src = (char *) elements + elem_size * first_offset; memcpy(dst, src, elem_size); n &= n - 1; // Turn that bit off i++; } memcpy((char *) combination + i * elem_size, end, elem_size); // add the end } int factorial(int n) { int f = 1; for (int i = 2; i <= n; ++i) f *= i; return f; } static inline int find_largest_mobile(const permuter *p) { assert(p != NULL); int max_mobile_idx = -1; for (int i = 0; i < p->n; ++i) { if (!is_mobile(p, i)) continue; if (max_mobile_idx == -1 || compare(p, i, max_mobile_idx) > 0) { max_mobile_idx = i; } } return max_mobile_idx; } static void reset_directions(permuter *p) { assert(p != NULL); for (int i = 0; i < direction_arr_len(p->n); ++i) p->directions[i] = 0; } /* an element is said to be mobile if it is larger than the element * adjacent to it in the direction that it is facing */ static inline bool is_mobile(const permuter *p, int i) { assert(p != NULL); enum Direction dir = ith_direction(p, i); if (dir == left) return i > 0 && compare(p, i, i - 1) > 0; else return i < (p->n - 1) && compare(p, i, i + 1) > 0; } /* * swap an element with the adjacent element in the direction that it is facing */ static inline void swap_facing(permuter *p, int i) { assert(p != NULL); assert(i >= 0 && i < p->n); swap_adjacent(p, i, ith_direction(p, i)); } static inline void swap_adjacent(permuter *p, int i, enum Direction dir) { assert(p != NULL); assert(i >= 0 && i < p->n); int adjacent = (dir == left) ? i - 1 : i + 1; swap(p, i, adjacent); } static inline void swap(permuter *p, int i, int j) { assert(p != NULL); assert(i >= 0 && i < p->n); assert(j >= 0 && j < p->n); // must swap direction bits also! enum Direction dir_i = ith_direction(p, i); set_ith_direction(p, i, ith_direction(p, j)); set_ith_direction(p, j, dir_i); // swap elements memcpy(p->tmp, permuter_ith(p, i), p->elem_size); // NOTE: if you get a segmentation fault here, it's probably // because you passed an array of elements in read-only memory. // i.e. you probably passed an ARRAY/STRING LITERAL memcpy(permuter_ith(p, i), permuter_ith(p, j), p->elem_size); memcpy(permuter_ith(p, j), p->tmp, p->elem_size); } static int compare(const permuter *p, int i, int j) { assert(p != NULL); assert(i >= 0 && i < p->n); assert(j >= 0 && j < p->n); return p->cmp(permuter_ith(p, i), permuter_ith(p, j)); } static inline void *permuter_ith(const permuter *p, int i) { assert(p != NULL); assert(i >= 0); return (char *) p->elems + i * p->elem_size; } static enum Direction ith_direction(const permuter *p, int i) { assert(p != NULL); uint8_t dir_bucket = p->directions[i / CHAR_BIT]; uint8_t mask = (uint8_t) (1 << (i % CHAR_BIT)); bool bit = dir_bucket & mask; return bit ? right : left; } static inline void flip_ith_direction(permuter *p, int i) { assert(p != NULL); enum Direction dir = ith_direction(p, i); set_ith_direction(p, i, dir == left ? right : left); } static inline void set_ith_direction(permuter *p, int i, enum Direction direction) { assert(p != NULL); int index = i / CHAR_BIT; char mask = (1 << (i % CHAR_BIT)); if (direction == left) p->directions[index] &= ~mask; else p->directions[index] |= mask; } static inline int direction_arr_len(int num_elems) { return div_round_up(num_elems, CHAR_BIT); } static inline int div_round_up(int numer, int denom) { if (numer == 0) return 0; return 1 + (numer - 1) / denom; } void nth_permutation(const char *string, int n, char *perm) { size_t len = strlen(string); bool *used = calloc(sizeof(bool) * len, 1); for (int i = (int) len - 1; i >= 0; --i) { int digit = n / factorial(i); // Get the "digit"'th unused character int index = ith_false(used, len, digit); used[index] = true; perm[i] = string[index]; // reduce permutation number by one digit n = n % factorial(i); } perm[len] = '\0'; // null terminate permutation free(used); } static int ith_false(const bool booleans[], size_t len, int i) { for (int j = 0; j < (int) len; ++j) { if (booleans[j]) continue; if (i == 0) return j; i--; } return -1; }
3.03125
3