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-18T19:53:07.498534+00:00
2023-08-30T05:36:57
59990c99eea2f9a961b5f481665e7cc24875ba5c
{ "blob_id": "59990c99eea2f9a961b5f481665e7cc24875ba5c", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T05:36:57", "content_id": "bdd1e646282b2090416c1208aa9080f9bf239633", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "bfb49b61aeca694f7c5d15de1df3e397ec3e8247", "extension": "c", "filename": "chr.c", "fork_events_count": 2, "gha_created_at": "2015-12-27T11:52:52", "gha_event_created_at": "2021-01-25T08:26:24", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 48643177, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 362, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/chr.c", "provenance": "stackv2-0061.json.gz:3786", "repo_name": "Wodan58/Moy", "revision_date": "2023-08-30T05:36:57", "revision_id": "85e7f5f4cd951cea552933508afdf20c655f6ea2", "snapshot_id": "0dfaf7bbda205287a03735b6b1c4703fbdb2fcc9", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/Wodan58/Moy/85e7f5f4cd951cea552933508afdf20c655f6ea2/src/chr.c", "visit_date": "2023-08-31T07:16:36.145158" }
stackv2
/* module : chr.c version : 1.2 date : 08/23/23 */ #ifndef CHR_C #define CHR_C /** OK 1470 chr : DA I -> C C is the character whose Ascii value is integer I (or logical or character). */ void chr_(pEnv env) { Node node; PARM(1, PREDSUCC); node = lst_pop(env->stck); node.op = CHAR_; lst_push(env->stck, node); } #endif
2.1875
2
2024-11-18T19:53:08.353068+00:00
2020-08-09T20:18:23
6733750268665b649845ffe2321a9570c7fb667c
{ "blob_id": "6733750268665b649845ffe2321a9570c7fb667c", "branch_name": "refs/heads/master", "committer_date": "2020-08-09T20:18:23", "content_id": "e66e362ecf31b640d9e57173bd165593960f2293", "detected_licenses": [ "MIT" ], "directory_id": "8970365b7a53bf6da4c0a824aa1e8768c133beab", "extension": "c", "filename": "tin.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 286133718, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 476, "license": "MIT", "license_type": "permissive", "path": "/modules/tin.c", "provenance": "stackv2-0061.json.gz:4428", "repo_name": "zen3d/utone", "revision_date": "2020-08-09T20:18:23", "revision_id": "4ec1a76ffe4c560d70c8787e678e0a1c2de4f20f", "snapshot_id": "0edbe6a02a603ccfe6af044b995437692a3c57e4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zen3d/utone/4ec1a76ffe4c560d70c8787e678e0a1c2de4f20f/modules/tin.c", "visit_date": "2022-12-02T03:44:15.847629" }
stackv2
#include <stdlib.h> #include "utone.h" int ut_tin_create(ut_tin **p) { *p = malloc(sizeof(ut_tin)); return UT_OK; } int ut_tin_destroy(ut_tin **p) { free(*p); return UT_OK; } int ut_tin_init(ut_data *ut, ut_tin *p) { p->fp = stdin; p->val = 0; return UT_OK; } int ut_tin_compute(ut_data *ut, ut_tin *p, UTFLOAT *in, UTFLOAT *out) { if(*in) { fread(&p->val, sizeof(UTFLOAT), 1, p->fp); } *out = p->val; return UT_OK; }
2.265625
2
2024-11-18T19:53:08.487906+00:00
2023-05-09T20:08:24
07928acb09a99e854153e3efe7a8e468e0a44ba0
{ "blob_id": "07928acb09a99e854153e3efe7a8e468e0a44ba0", "branch_name": "refs/heads/master", "committer_date": "2023-05-09T20:08:24", "content_id": "3d252aeef1f5f711013b389bd04d9c39fdda9779", "detected_licenses": [ "MIT" ], "directory_id": "b5d28de0f81d800758bc8234f265e5290bc303df", "extension": "c", "filename": "lcd02.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 4457913, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4463, "license": "MIT", "license_type": "permissive", "path": "/drivers/lcd/lcd02.c", "provenance": "stackv2-0061.json.gz:4684", "repo_name": "f4deb/cen-electronic", "revision_date": "2023-05-09T20:08:24", "revision_id": "eadf1a839445b57bba0319ba54c30ce333f912f0", "snapshot_id": "026c9b9d650487e70fde472cbbcf1a81ec9fe980", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/f4deb/cen-electronic/eadf1a839445b57bba0319ba54c30ce333f912f0/drivers/lcd/lcd02.c", "visit_date": "2023-05-09T23:58:02.262631" }
stackv2
#include <I2C.h> #include <stdlib.h> #include <string.h> #include "lcd02.h" void lcd02_setCursorAtHome(void) { lcd02_sendCommand(1); } void lcd02_sendCommand(char command) { IdleI2C(); //attend que le bus soit libre StartI2C(); /* Wait till Start sequence is completed */ while (I2CCONbits.SEN); MasterWriteI2C(LCD02_ADDRESS_WRITE); // adresse I2C IdleI2C(); MasterWriteI2C(LCD02_COMMAND_REGISTER); // registre de commande IdleI2C(); // commande MasterWriteI2C(command); IdleI2C(); StopI2C(); } void internalSendCommand1(unsigned command, unsigned char value1) { //attend que le bus soit libre IdleI2C(); StartI2C(); /* Wait till Start sequence is completed */ while (I2CCONbits.SEN); // adresse I2C MasterWriteI2C(LCD02_ADDRESS_WRITE); IdleI2C(); // registre de commande MasterWriteI2C(LCD02_COMMAND_REGISTER); IdleI2C(); // commande MasterWriteI2C(command); IdleI2C(); // data MasterWriteI2C(value1); IdleI2C(); StopI2C(); } void internalSendCommand2(unsigned command, unsigned char value1, unsigned char value2) { IdleI2C(); //attend que le bus soit libre StartI2C(); /* Wait till Start sequence is completed */ while (I2CCONbits.SEN); MasterWriteI2C(LCD02_ADDRESS_WRITE); // adresse I2C IdleI2C(); MasterWriteI2C(LCD02_COMMAND_REGISTER); // registre de commande IdleI2C(); MasterWriteI2C(command); // commande IdleI2C(); MasterWriteI2C(value1); // commande IdleI2C(); MasterWriteI2C(value2); // commande IdleI2C(); StopI2C(); } void lcd02_setCursorPosition(char position) { internalSendCommand1(2, position); } void lcd02_setCursorRowAndColumn(char row, char column) { internalSendCommand2(3, row, column); } void lcd02_hideCursor(void) { lcd02_sendCommand(4); } void lcd02_showUnderlineCursor(void) { lcd02_sendCommand(5); } void lcd02_setBlinkCursor(void) { lcd02_sendCommand(6); } void lcd02_backSpaceCursor(void) { lcd02_sendCommand(8); } void lcd02_setBacklight(unsigned char enabled) { if (enabled) { lcd02_sendCommand(BACKLIGHT_ON); } else { lcd02_sendCommand(BACKLIGHT_OFF); } } void lcd02_tabCursor(void) { lcd02_sendCommand(9); } void lcd02_smartLineCursor(void) { lcd02_sendCommand(10); } void lcd02_verticalTabCursor(void) { lcd02_sendCommand(11); } void lcd02_clearScreen(void) { lcd02_sendCommand(12); } void lcd02_carriageReturnCursor(void) { lcd02_sendCommand(13); } void lcd02_clearColumnCursor(void) { lcd02_sendCommand(17); } void lcd02_setTabulationSize(char tabulationSize) { internalSendCommand1(18, tabulationSize); } void lcd02_writeChar(char c) { // the command to write a char is the same as writing command but with limited range of char to only non binary character lcd02_sendCommand(c); } unsigned int getLCD02SoftwareRevision(void) { unsigned int version; IdleI2C(); StartI2C(); /* Wait till Start sequence is completed */ while (I2CCONbits.SEN); MasterWriteI2C(LCD02_ADDRESS_WRITE); //adddresse I2C de la carte IdleI2C(); MasterWriteI2C(3); //registre de version IdleI2C(); StopI2C(); IdleI2C(); StartI2C(); /* Wait till Start sequence is completed */ while (I2CCONbits.SEN) //adddresse I2C de la carte MasterWriteI2C(LCD02_ADDRESS_READ); IdleI2C(); //registre de version version = MasterReadI2C(); IdleI2C(); return (version); } unsigned int isLCD02DeviceOk(void) { return getLCD02SoftwareRevision() < 255; } void initLCD02(void) { lcd02_clearScreen(); lcd02_setBacklight(1); } void stopLCD02(void) { // Disable backlight when it will be managed lcd02_setBacklight(0); } const char* getLCD02DeviceName(void) { return "LCD02"; } DeviceDescriptor getLCD02DeviceDescriptor() { DeviceDescriptor result; result.deviceInit = &initLCD02; result.deviceShutDown = &stopLCD02; result.deviceIsOk = &isLCD02DeviceOk; result.deviceGetSoftwareRevision = &getLCD02SoftwareRevision; result.deviceGetName = &getLCD02DeviceName; result.enabled = 1; return result; }
2.734375
3
2024-11-18T19:53:08.813055+00:00
2017-08-03T08:39:43
b1ee09291d9eb649efb1ac59c57496cb3fa6db53
{ "blob_id": "b1ee09291d9eb649efb1ac59c57496cb3fa6db53", "branch_name": "refs/heads/master", "committer_date": "2017-08-03T08:39:43", "content_id": "dcaf93694559a8bab7eecce15b1c440cb80c944a", "detected_licenses": [ "MIT" ], "directory_id": "8700fa500c760a8049c65df590632783cd64940a", "extension": "c", "filename": "testtimer.c", "fork_events_count": 0, "gha_created_at": "2019-06-17T13:20:38", "gha_event_created_at": "2019-06-17T13:20:39", "gha_language": null, "gha_license_id": "MIT", "github_id": 192351172, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 548, "license": "MIT", "license_type": "permissive", "path": "/testc/testlinux/testtimer.c", "provenance": "stackv2-0061.json.gz:5198", "repo_name": "SrikanthParsha14/test", "revision_date": "2017-08-03T08:39:43", "revision_id": "8cee69e09c8557d53d8d30382cec8ea5c1f82f6e", "snapshot_id": "8ebac746f31d450b39eca1001525961497d962ba", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/SrikanthParsha14/test/8cee69e09c8557d53d8d30382cec8ea5c1f82f6e/testc/testlinux/testtimer.c", "visit_date": "2020-06-05T06:54:36.274446" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/time.h> #include <unistd.h> void catch_alarm (int sig) { printf("Alarm event\n"); signal(sig, catch_alarm); } int main(void) { struct itimerval new; signal(SIGALRM, catch_alarm); new.it_interval.tv_sec = 1; new.it_interval.tv_usec = 500000; new.it_value.tv_sec = 1; new.it_value.tv_usec = 500000; if (setitimer(ITIMER_REAL, &new, NULL) < 0) printf("timer init failed\n"); else printf("timer init succeeded\n"); while (1) sleep(2); return EXIT_SUCCESS; }
2.859375
3
2024-11-18T19:53:08.921064+00:00
2013-05-28T03:02:44
e4b588ca00daf27bc631755c9fcb2d593b2ee208
{ "blob_id": "e4b588ca00daf27bc631755c9fcb2d593b2ee208", "branch_name": "refs/heads/master", "committer_date": "2013-05-28T03:02:44", "content_id": "37aabc12a27c348884517f7a057ec4993491c89c", "detected_licenses": [ "MIT" ], "directory_id": "02771a2a22ad014a037e8b74f7bc0b3291decb68", "extension": "c", "filename": "tests_matrix.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": 4005, "license": "MIT", "license_type": "permissive", "path": "/cbp/tests/tests_matrix.c", "provenance": "stackv2-0061.json.gz:5327", "repo_name": "piratejon/matrot", "revision_date": "2013-05-28T03:02:44", "revision_id": "5459c66074f7539620c7b7be7b7f4c3cdd3a2f0b", "snapshot_id": "63e241fc520bd7573e760209c8d487a540c729e3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/piratejon/matrot/5459c66074f7539620c7b7be7b7f4c3cdd3a2f0b/cbp/tests/tests_matrix.c", "visit_date": "2016-09-01T21:57:48.176350" }
stackv2
#include <math.h> #include "matrix.h" #include "tests.h" void sanity_check_zero ( void ) { ASSERT ( 0 == 0, "Zero failed to be equal to zero." ); } void initialize_matrix ( void ) { SquareMatrix * mat = initialize_square_matrix ( 22, sizeof(Int) ); ASSERT(mat != NULL, "Wrong value for square matrix pointer after init."); ASSERT(mat->n == 22, "Wrong size for square matrix after init."); ASSERT(mat->a != NULL, "Matrix body NULL."); matrix_fill(mat, fill_matrix_random); // print_matrix(mat); free_square_matrix ( mat ); mat = initialize_square_matrix ( 19, sizeof(Int) ); ASSERT(mat != NULL, "Wrong value for square matrix pointer after init."); ASSERT(mat->n == 19, "Wrong size for square matrix after init."); ASSERT(mat->a != NULL, "Matrix body NULL."); matrix_fill(mat, fill_matrix_random); // print_matrix(mat); free_square_matrix ( mat ); } void copy_matrix ( void ) { SquareMatrix * mat, * cpy; int row, col; mat = initialize_square_matrix ( 29, sizeof(Int) ); matrix_fill(mat, fill_matrix_random); cpy = matrix_copy ( mat ); ASSERT(cpy->n == mat->n, "Copy has wrong dimension."); ASSERT(cpy->a != mat->a, "Copy uses same memory as original."); for ( row = 0; row < mat->n; row += 1 ) { for ( col = 0; col < mat->n; col += 1 ) { ASSERT((mat->a + (col*mat->n + row)) != (cpy->a + (col*cpy->n + row)), "Copy cell has same address as original cell."); ASSERT( ((Int*)(mat->a + (col*mat->n + row)))->lol == ((Int*)(cpy->a + (col*cpy->n + row)))->lol, "Copy cell has different value than original cell."); } } free_square_matrix ( mat ); free_square_matrix ( cpy ); } void rotate_matrix ( void ) { int row, col, half_width; SquareMatrix * mat, * rot; mat = initialize_square_matrix ( 99, sizeof(Int) ); matrix_fill(mat, fill_matrix_random); rot = matrix_copy(mat); matrix_rotate(rot); ASSERT ( rot->n == mat->n, "Wrong dimensions after copy/rotate." ); print_matrix(mat); printf("\n"); print_matrix(rot); half_width = ceil(mat->n/2.); for ( col = 0; col < half_width; col += 1 ) { for ( row = 0; row < half_width; row += 1 ) { ASSERT ( ((Int*)MatrixAt(rot, row, col))->lol == ((Int*)MatrixAt(mat, col, mat->n - 1 - row))->lol, "Wrong rotated value." ); ASSERT ( ((Int*)MatrixAt(rot, col, rot->n - 1 - row))->lol == ((Int*)MatrixAt(mat, mat->n - 1 - row, mat->n - 1 - col))->lol, "Wrong rotated value." ); ASSERT ( ((Int*)MatrixAt(rot, rot->n - 1 - row, rot->n - 1 - col))->lol == ((Int*)MatrixAt(mat, mat->n - 1 - col, row))->lol, "Wrong rotated value." ); ASSERT ( ((Int*)MatrixAt(rot, rot->n - 1 - col, row))->lol == ((Int*)MatrixAt(mat, row, col))->lol, "Wrong rotated value." ); } } free_square_matrix ( mat ); free_square_matrix ( rot ); mat = initialize_square_matrix ( 102, sizeof(Int) ); matrix_fill(mat, fill_matrix_random); rot = matrix_copy(mat); matrix_rotate(rot); ASSERT ( rot->n == mat->n, "Wrong dimensions after copy/rotate." ); print_matrix(mat); printf("\n"); print_matrix(rot); half_width = ceil(mat->n/2.); for ( col = 0; col < half_width; col += 1 ) { for ( row = 0; row < half_width; row += 1 ) { ASSERT ( ((Int*)MatrixAt(rot, row, col))->lol == ((Int*)MatrixAt(mat, col, mat->n - 1 - row))->lol, "Wrong rotated value." ); ASSERT ( ((Int*)MatrixAt(rot, col, rot->n - 1 - row))->lol == ((Int*)MatrixAt(mat, mat->n - 1 - row, mat->n - 1 - col))->lol, "Wrong rotated value." ); ASSERT ( ((Int*)MatrixAt(rot, rot->n - 1 - row, rot->n - 1 - col))->lol == ((Int*)MatrixAt(mat, mat->n - 1 - col, row))->lol, "Wrong rotated value." ); ASSERT ( ((Int*)MatrixAt(rot, rot->n - 1 - col, row))->lol == ((Int*)MatrixAt(mat, row, col))->lol, "Wrong rotated value." ); } } free_square_matrix ( mat ); free_square_matrix ( rot ); } void do_tests ( void ) { srand(0); TEST ( sanity_check_zero ); TEST ( initialize_matrix ); TEST ( copy_matrix ); TEST ( rotate_matrix ); }
2.921875
3
2024-11-18T19:53:08.976650+00:00
2023-08-17T12:05:52
65acf70f9de2c64c1397b46764f8a59047cf7114
{ "blob_id": "65acf70f9de2c64c1397b46764f8a59047cf7114", "branch_name": "refs/heads/master", "committer_date": "2023-08-17T12:05:52", "content_id": "1cdac4687ed1069ab7d850f40c72add3b17b00a7", "detected_licenses": [ "ISC" ], "directory_id": "d453a1364f27ae3c99c1f77f46b084b93d616ccb", "extension": "h", "filename": "values.h", "fork_events_count": 165, "gha_created_at": "2013-02-01T15:07:26", "gha_event_created_at": "2023-08-30T11:38:33", "gha_language": "Haskell", "gha_license_id": "ISC", "github_id": 7960131, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 22914, "license": "ISC", "license_type": "permissive", "path": "/rts/c/values.h", "provenance": "stackv2-0061.json.gz:5456", "repo_name": "diku-dk/futhark", "revision_date": "2023-08-17T12:05:52", "revision_id": "ea2b8d2600b1d361904091d057ecdadc1deb46a2", "snapshot_id": "a41f2f5d3851ea8f854c025482dac00a7b471a9d", "src_encoding": "UTF-8", "star_events_count": 1929, "url": "https://raw.githubusercontent.com/diku-dk/futhark/ea2b8d2600b1d361904091d057ecdadc1deb46a2/rts/c/values.h", "visit_date": "2023-08-17T23:44:04.185732" }
stackv2
// Start of values.h. //// Text I/O typedef int (*writer)(FILE*, const void*); typedef int (*bin_reader)(void*); typedef int (*str_reader)(const char *, void*); struct array_reader { char* elems; int64_t n_elems_space; int64_t elem_size; int64_t n_elems_used; int64_t *shape; str_reader elem_reader; }; static void skipspaces(FILE *f) { int c; do { c = getc(f); } while (isspace(c)); if (c != EOF) { ungetc(c, f); } } static int constituent(char c) { return isalnum(c) || c == '.' || c == '-' || c == '+' || c == '_'; } // Produces an empty token only on EOF. static void next_token(FILE *f, char *buf, int bufsize) { start: skipspaces(f); int i = 0; while (i < bufsize) { int c = getc(f); buf[i] = (char)c; if (c == EOF) { buf[i] = 0; return; } else if (c == '-' && i == 1 && buf[0] == '-') { // Line comment, so skip to end of line and start over. for (; c != '\n' && c != EOF; c = getc(f)); goto start; } else if (!constituent((char)c)) { if (i == 0) { // We permit single-character tokens that are not // constituents; this lets things like ']' and ',' be // tokens. buf[i+1] = 0; return; } else { ungetc(c, f); buf[i] = 0; return; } } i++; } buf[bufsize-1] = 0; } static int next_token_is(FILE *f, char *buf, int bufsize, const char* expected) { next_token(f, buf, bufsize); return strcmp(buf, expected) == 0; } static void remove_underscores(char *buf) { char *w = buf; for (char *r = buf; *r; r++) { if (*r != '_') { *w++ = *r; } } *w++ = 0; } static int read_str_elem(char *buf, struct array_reader *reader) { int ret; if (reader->n_elems_used == reader->n_elems_space) { reader->n_elems_space *= 2; reader->elems = (char*) realloc(reader->elems, (size_t)(reader->n_elems_space * reader->elem_size)); } ret = reader->elem_reader(buf, reader->elems + reader->n_elems_used * reader->elem_size); if (ret == 0) { reader->n_elems_used++; } return ret; } static int read_str_array_elems(FILE *f, char *buf, int bufsize, struct array_reader *reader, int64_t dims) { int ret; int first = 1; char *knows_dimsize = (char*) calloc((size_t)dims, sizeof(char)); int cur_dim = (int)dims-1; int64_t *elems_read_in_dim = (int64_t*) calloc((size_t)dims, sizeof(int64_t)); while (1) { next_token(f, buf, bufsize); if (strcmp(buf, "]") == 0) { if (knows_dimsize[cur_dim]) { if (reader->shape[cur_dim] != elems_read_in_dim[cur_dim]) { ret = 1; break; } } else { knows_dimsize[cur_dim] = 1; reader->shape[cur_dim] = elems_read_in_dim[cur_dim]; } if (cur_dim == 0) { ret = 0; break; } else { cur_dim--; elems_read_in_dim[cur_dim]++; } } else if (strcmp(buf, ",") == 0) { next_token(f, buf, bufsize); if (strcmp(buf, "[") == 0) { if (cur_dim == dims - 1) { ret = 1; break; } first = 1; cur_dim++; elems_read_in_dim[cur_dim] = 0; } else if (cur_dim == dims - 1) { ret = read_str_elem(buf, reader); if (ret != 0) { break; } elems_read_in_dim[cur_dim]++; } else { ret = 1; break; } } else if (strlen(buf) == 0) { // EOF ret = 1; break; } else if (first) { if (strcmp(buf, "[") == 0) { if (cur_dim == dims - 1) { ret = 1; break; } cur_dim++; elems_read_in_dim[cur_dim] = 0; } else { ret = read_str_elem(buf, reader); if (ret != 0) { break; } elems_read_in_dim[cur_dim]++; first = 0; } } else { ret = 1; break; } } free(knows_dimsize); free(elems_read_in_dim); return ret; } static int read_str_empty_array(FILE *f, char *buf, int bufsize, const char *type_name, int64_t *shape, int64_t dims) { if (strlen(buf) == 0) { // EOF return 1; } if (strcmp(buf, "empty") != 0) { return 1; } if (!next_token_is(f, buf, bufsize, "(")) { return 1; } for (int i = 0; i < dims; i++) { if (!next_token_is(f, buf, bufsize, "[")) { return 1; } next_token(f, buf, bufsize); if (sscanf(buf, "%"SCNu64, (uint64_t*)&shape[i]) != 1) { return 1; } if (!next_token_is(f, buf, bufsize, "]")) { return 1; } } if (!next_token_is(f, buf, bufsize, type_name)) { return 1; } if (!next_token_is(f, buf, bufsize, ")")) { return 1; } // Check whether the array really is empty. for (int i = 0; i < dims; i++) { if (shape[i] == 0) { return 0; } } // Not an empty array! return 1; } static int read_str_array(FILE *f, int64_t elem_size, str_reader elem_reader, const char *type_name, void **data, int64_t *shape, int64_t dims) { int ret; struct array_reader reader; char buf[100]; int dims_seen; for (dims_seen = 0; dims_seen < dims; dims_seen++) { if (!next_token_is(f, buf, sizeof(buf), "[")) { break; } } if (dims_seen == 0) { return read_str_empty_array(f, buf, sizeof(buf), type_name, shape, dims); } if (dims_seen != dims) { return 1; } reader.shape = shape; reader.n_elems_used = 0; reader.elem_size = elem_size; reader.n_elems_space = 16; reader.elems = (char*) realloc(*data, (size_t)(elem_size*reader.n_elems_space)); reader.elem_reader = elem_reader; ret = read_str_array_elems(f, buf, sizeof(buf), &reader, dims); *data = reader.elems; return ret; } #define READ_STR(MACRO, PTR, SUFFIX) \ remove_underscores(buf); \ int j; \ if (sscanf(buf, "%"MACRO"%n", (PTR*)dest, &j) == 1) { \ return !(strcmp(buf+j, "") == 0 || strcmp(buf+j, SUFFIX) == 0); \ } else { \ return 1; \ } static int read_str_i8(char *buf, void* dest) { // Some platforms (WINDOWS) does not support scanf %hhd or its // cousin, %SCNi8. Read into int first to avoid corrupting // memory. // // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63417 remove_underscores(buf); int j, x; if (sscanf(buf, "%i%n", &x, &j) == 1) { *(int8_t*)dest = (int8_t)x; return !(strcmp(buf+j, "") == 0 || strcmp(buf+j, "i8") == 0); } else { return 1; } } static int read_str_u8(char *buf, void* dest) { // Some platforms (WINDOWS) does not support scanf %hhd or its // cousin, %SCNu8. Read into int first to avoid corrupting // memory. // // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63417 remove_underscores(buf); int j, x; if (sscanf(buf, "%i%n", &x, &j) == 1) { *(uint8_t*)dest = (uint8_t)x; return !(strcmp(buf+j, "") == 0 || strcmp(buf+j, "u8") == 0); } else { return 1; } } static int read_str_i16(char *buf, void* dest) { READ_STR(SCNi16, int16_t, "i16"); } static int read_str_u16(char *buf, void* dest) { READ_STR(SCNi16, int16_t, "u16"); } static int read_str_i32(char *buf, void* dest) { READ_STR(SCNi32, int32_t, "i32"); } static int read_str_u32(char *buf, void* dest) { READ_STR(SCNi32, int32_t, "u32"); } static int read_str_i64(char *buf, void* dest) { READ_STR(SCNi64, int64_t, "i64"); } static int read_str_u64(char *buf, void* dest) { // FIXME: This is not correct, as SCNu64 only permits decimal // literals. However, SCNi64 does not handle very large numbers // correctly (it's really for signed numbers, so that's fair). READ_STR(SCNu64, uint64_t, "u64"); } static int read_str_f16(char *buf, void* dest) { remove_underscores(buf); if (strcmp(buf, "f16.nan") == 0) { *(uint16_t*)dest = float2halfbits(NAN); return 0; } else if (strcmp(buf, "f16.inf") == 0) { *(uint16_t*)dest = float2halfbits(INFINITY); return 0; } else if (strcmp(buf, "-f16.inf") == 0) { *(uint16_t*)dest = float2halfbits(-INFINITY); return 0; } else { int j; float x; if (sscanf(buf, "%f%n", &x, &j) == 1) { if (strcmp(buf+j, "") == 0 || strcmp(buf+j, "f16") == 0) { *(uint16_t*)dest = float2halfbits(x); return 0; } } return 1; } } static int read_str_f32(char *buf, void* dest) { remove_underscores(buf); if (strcmp(buf, "f32.nan") == 0) { *(float*)dest = (float)NAN; return 0; } else if (strcmp(buf, "f32.inf") == 0) { *(float*)dest = (float)INFINITY; return 0; } else if (strcmp(buf, "-f32.inf") == 0) { *(float*)dest = (float)-INFINITY; return 0; } else { READ_STR("f", float, "f32"); } } static int read_str_f64(char *buf, void* dest) { remove_underscores(buf); if (strcmp(buf, "f64.nan") == 0) { *(double*)dest = (double)NAN; return 0; } else if (strcmp(buf, "f64.inf") == 0) { *(double*)dest = (double)INFINITY; return 0; } else if (strcmp(buf, "-f64.inf") == 0) { *(double*)dest = (double)-INFINITY; return 0; } else { READ_STR("lf", double, "f64"); } } static int read_str_bool(char *buf, void* dest) { if (strcmp(buf, "true") == 0) { *(char*)dest = 1; return 0; } else if (strcmp(buf, "false") == 0) { *(char*)dest = 0; return 0; } else { return 1; } } static int write_str_i8(FILE *out, int8_t *src) { return fprintf(out, "%hhdi8", *src); } static int write_str_u8(FILE *out, uint8_t *src) { return fprintf(out, "%hhuu8", *src); } static int write_str_i16(FILE *out, int16_t *src) { return fprintf(out, "%hdi16", *src); } static int write_str_u16(FILE *out, uint16_t *src) { return fprintf(out, "%huu16", *src); } static int write_str_i32(FILE *out, int32_t *src) { return fprintf(out, "%di32", *src); } static int write_str_u32(FILE *out, uint32_t *src) { return fprintf(out, "%uu32", *src); } static int write_str_i64(FILE *out, int64_t *src) { return fprintf(out, "%"PRIi64"i64", *src); } static int write_str_u64(FILE *out, uint64_t *src) { return fprintf(out, "%"PRIu64"u64", *src); } static int write_str_f16(FILE *out, uint16_t *src) { float x = halfbits2float(*src); if (isnan(x)) { return fprintf(out, "f16.nan"); } else if (isinf(x) && x >= 0) { return fprintf(out, "f16.inf"); } else if (isinf(x)) { return fprintf(out, "-f16.inf"); } else { return fprintf(out, "%.6ff16", x); } } static int write_str_f32(FILE *out, float *src) { float x = *src; if (isnan(x)) { return fprintf(out, "f32.nan"); } else if (isinf(x) && x >= 0) { return fprintf(out, "f32.inf"); } else if (isinf(x)) { return fprintf(out, "-f32.inf"); } else { return fprintf(out, "%.6ff32", x); } } static int write_str_f64(FILE *out, double *src) { double x = *src; if (isnan(x)) { return fprintf(out, "f64.nan"); } else if (isinf(x) && x >= 0) { return fprintf(out, "f64.inf"); } else if (isinf(x)) { return fprintf(out, "-f64.inf"); } else { return fprintf(out, "%.6ff64", *src); } } static int write_str_bool(FILE *out, void *src) { return fprintf(out, *(char*)src ? "true" : "false"); } //// Binary I/O #define BINARY_FORMAT_VERSION 2 #define IS_BIG_ENDIAN (!*(unsigned char *)&(uint16_t){1}) static void flip_bytes(size_t elem_size, unsigned char *elem) { for (size_t j=0; j<elem_size/2; j++) { unsigned char head = elem[j]; size_t tail_index = elem_size-1-j; elem[j] = elem[tail_index]; elem[tail_index] = head; } } // On Windows we need to explicitly set the file mode to not mangle // newline characters. On *nix there is no difference. #ifdef _WIN32 #include <io.h> #include <fcntl.h> static void set_binary_mode(FILE *f) { setmode(fileno(f), O_BINARY); } #else static void set_binary_mode(FILE *f) { (void)f; } #endif static int read_byte(FILE *f, void* dest) { size_t num_elems_read = fread(dest, 1, 1, f); return num_elems_read == 1 ? 0 : 1; } //// Types struct primtype_info_t { const char binname[4]; // Used for parsing binary data. const char* type_name; // Same name as in Futhark. const int64_t size; // in bytes const writer write_str; // Write in text format. const str_reader read_str; // Read in text format. }; static const struct primtype_info_t i8_info = {.binname = " i8", .type_name = "i8", .size = 1, .write_str = (writer)write_str_i8, .read_str = (str_reader)read_str_i8}; static const struct primtype_info_t i16_info = {.binname = " i16", .type_name = "i16", .size = 2, .write_str = (writer)write_str_i16, .read_str = (str_reader)read_str_i16}; static const struct primtype_info_t i32_info = {.binname = " i32", .type_name = "i32", .size = 4, .write_str = (writer)write_str_i32, .read_str = (str_reader)read_str_i32}; static const struct primtype_info_t i64_info = {.binname = " i64", .type_name = "i64", .size = 8, .write_str = (writer)write_str_i64, .read_str = (str_reader)read_str_i64}; static const struct primtype_info_t u8_info = {.binname = " u8", .type_name = "u8", .size = 1, .write_str = (writer)write_str_u8, .read_str = (str_reader)read_str_u8}; static const struct primtype_info_t u16_info = {.binname = " u16", .type_name = "u16", .size = 2, .write_str = (writer)write_str_u16, .read_str = (str_reader)read_str_u16}; static const struct primtype_info_t u32_info = {.binname = " u32", .type_name = "u32", .size = 4, .write_str = (writer)write_str_u32, .read_str = (str_reader)read_str_u32}; static const struct primtype_info_t u64_info = {.binname = " u64", .type_name = "u64", .size = 8, .write_str = (writer)write_str_u64, .read_str = (str_reader)read_str_u64}; static const struct primtype_info_t f16_info = {.binname = " f16", .type_name = "f16", .size = 2, .write_str = (writer)write_str_f16, .read_str = (str_reader)read_str_f16}; static const struct primtype_info_t f32_info = {.binname = " f32", .type_name = "f32", .size = 4, .write_str = (writer)write_str_f32, .read_str = (str_reader)read_str_f32}; static const struct primtype_info_t f64_info = {.binname = " f64", .type_name = "f64", .size = 8, .write_str = (writer)write_str_f64, .read_str = (str_reader)read_str_f64}; static const struct primtype_info_t bool_info = {.binname = "bool", .type_name = "bool", .size = 1, .write_str = (writer)write_str_bool, .read_str = (str_reader)read_str_bool}; static const struct primtype_info_t* primtypes[] = { &i8_info, &i16_info, &i32_info, &i64_info, &u8_info, &u16_info, &u32_info, &u64_info, &f16_info, &f32_info, &f64_info, &bool_info, NULL // NULL-terminated }; // General value interface. All endian business taken care of at // lower layers. static int read_is_binary(FILE *f) { skipspaces(f); int c = getc(f); if (c == 'b') { int8_t bin_version; int ret = read_byte(f, &bin_version); if (ret != 0) { futhark_panic(1, "binary-input: could not read version.\n"); } if (bin_version != BINARY_FORMAT_VERSION) { futhark_panic(1, "binary-input: File uses version %i, but I only understand version %i.\n", bin_version, BINARY_FORMAT_VERSION); } return 1; } ungetc(c, f); return 0; } static const struct primtype_info_t* read_bin_read_type_enum(FILE *f) { char read_binname[4]; int num_matched = fscanf(f, "%4c", read_binname); if (num_matched != 1) { futhark_panic(1, "binary-input: Couldn't read element type.\n"); } const struct primtype_info_t **type = primtypes; for (; *type != NULL; type++) { // I compare the 4 characters manually instead of using strncmp because // this allows any value to be used, also NULL bytes if (memcmp(read_binname, (*type)->binname, 4) == 0) { return *type; } } futhark_panic(1, "binary-input: Did not recognize the type '%s'.\n", read_binname); return NULL; } static void read_bin_ensure_scalar(FILE *f, const struct primtype_info_t *expected_type) { int8_t bin_dims; int ret = read_byte(f, &bin_dims); if (ret != 0) { futhark_panic(1, "binary-input: Couldn't get dims.\n"); } if (bin_dims != 0) { futhark_panic(1, "binary-input: Expected scalar (0 dimensions), but got array with %i dimensions.\n", bin_dims); } const struct primtype_info_t *bin_type = read_bin_read_type_enum(f); if (bin_type != expected_type) { futhark_panic(1, "binary-input: Expected scalar of type %s but got scalar of type %s.\n", expected_type->type_name, bin_type->type_name); } } //// High-level interface static int read_bin_array(FILE *f, const struct primtype_info_t *expected_type, void **data, int64_t *shape, int64_t dims) { int ret; int8_t bin_dims; ret = read_byte(f, &bin_dims); if (ret != 0) { futhark_panic(1, "binary-input: Couldn't get dims.\n"); } if (bin_dims != dims) { futhark_panic(1, "binary-input: Expected %i dimensions, but got array with %i dimensions.\n", dims, bin_dims); } const struct primtype_info_t *bin_primtype = read_bin_read_type_enum(f); if (expected_type != bin_primtype) { futhark_panic(1, "binary-input: Expected %iD-array with element type '%s' but got %iD-array with element type '%s'.\n", dims, expected_type->type_name, dims, bin_primtype->type_name); } int64_t elem_count = 1; for (int i=0; i<dims; i++) { int64_t bin_shape; ret = (int)fread(&bin_shape, sizeof(bin_shape), 1, f); if (ret != 1) { futhark_panic(1, "binary-input: Couldn't read size for dimension %i of array.\n", i); } if (IS_BIG_ENDIAN) { flip_bytes(sizeof(bin_shape), (unsigned char*) &bin_shape); } elem_count *= bin_shape; shape[i] = bin_shape; } int64_t elem_size = expected_type->size; void* tmp = realloc(*data, (size_t)(elem_count * elem_size)); if (tmp == NULL) { futhark_panic(1, "binary-input: Failed to allocate array of size %i.\n", elem_count * elem_size); } *data = tmp; int64_t num_elems_read = (int64_t)fread(*data, (size_t)elem_size, (size_t)elem_count, f); if (num_elems_read != elem_count) { futhark_panic(1, "binary-input: tried to read %i elements of an array, but only got %i elements.\n", elem_count, num_elems_read); } // If we're on big endian platform we must change all multibyte elements // from using little endian to big endian if (IS_BIG_ENDIAN && elem_size != 1) { flip_bytes((size_t)elem_size, (unsigned char*) *data); } return 0; } static int read_array(FILE *f, const struct primtype_info_t *expected_type, void **data, int64_t *shape, int64_t dims) { if (!read_is_binary(f)) { return read_str_array(f, expected_type->size, (str_reader)expected_type->read_str, expected_type->type_name, data, shape, dims); } else { return read_bin_array(f, expected_type, data, shape, dims); } } static int end_of_input(FILE *f) { skipspaces(f); char token[2]; next_token(f, token, sizeof(token)); if (strcmp(token, "") == 0) { return 0; } else { return 1; } } static int write_str_array(FILE *out, const struct primtype_info_t *elem_type, const unsigned char *data, const int64_t *shape, int8_t rank) { if (rank==0) { elem_type->write_str(out, (const void*)data); } else { int64_t len = (int64_t)shape[0]; int64_t slice_size = 1; int64_t elem_size = elem_type->size; for (int8_t i = 1; i < rank; i++) { slice_size *= shape[i]; } if (len*slice_size == 0) { fprintf(out, "empty("); for (int64_t i = 0; i < rank; i++) { fprintf(out, "[%"PRIi64"]", shape[i]); } fprintf(out, "%s", elem_type->type_name); fprintf(out, ")"); } else if (rank==1) { fputc('[', out); for (int64_t i = 0; i < len; i++) { elem_type->write_str(out, (const void*) (data + i * elem_size)); if (i != len-1) { fprintf(out, ", "); } } fputc(']', out); } else { fputc('[', out); for (int64_t i = 0; i < len; i++) { write_str_array(out, elem_type, data + i * slice_size * elem_size, shape+1, rank-1); if (i != len-1) { fprintf(out, ", "); } } fputc(']', out); } } return 0; } static int write_bin_array(FILE *out, const struct primtype_info_t *elem_type, const unsigned char *data, const int64_t *shape, int8_t rank) { int64_t num_elems = 1; for (int64_t i = 0; i < rank; i++) { num_elems *= shape[i]; } fputc('b', out); fputc((char)BINARY_FORMAT_VERSION, out); fwrite(&rank, sizeof(int8_t), 1, out); fwrite(elem_type->binname, 4, 1, out); if (shape != NULL) { fwrite(shape, sizeof(int64_t), (size_t)rank, out); } if (IS_BIG_ENDIAN) { for (int64_t i = 0; i < num_elems; i++) { const unsigned char *elem = data+i*elem_type->size; for (int64_t j = 0; j < elem_type->size; j++) { fwrite(&elem[elem_type->size-j], 1, 1, out); } } } else { fwrite(data, (size_t)elem_type->size, (size_t)num_elems, out); } return 0; } static int write_array(FILE *out, int write_binary, const struct primtype_info_t *elem_type, const void *data, const int64_t *shape, const int8_t rank) { if (write_binary) { return write_bin_array(out, elem_type, data, shape, rank); } else { return write_str_array(out, elem_type, data, shape, rank); } } static int read_scalar(FILE *f, const struct primtype_info_t *expected_type, void *dest) { if (!read_is_binary(f)) { char buf[100]; next_token(f, buf, sizeof(buf)); return expected_type->read_str(buf, dest); } else { read_bin_ensure_scalar(f, expected_type); size_t elem_size = (size_t)expected_type->size; size_t num_elems_read = fread(dest, elem_size, 1, f); if (IS_BIG_ENDIAN) { flip_bytes(elem_size, (unsigned char*) dest); } return num_elems_read == 1 ? 0 : 1; } } static int write_scalar(FILE *out, int write_binary, const struct primtype_info_t *type, void *src) { if (write_binary) { return write_bin_array(out, type, src, NULL, 0); } else { return type->write_str(out, src); } } // End of values.h.
2.75
3
2024-11-18T19:53:10.761335+00:00
2012-11-14T15:53:24
234b2f985dd9ce03a37478ad7bce9d4878fb04b0
{ "blob_id": "234b2f985dd9ce03a37478ad7bce9d4878fb04b0", "branch_name": "refs/heads/master", "committer_date": "2012-11-14T15:53:24", "content_id": "5d2823eecfe806e8d349ccac048afdc02d3099ac", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "8e9c02e194b85009f21f082183de211161e3b030", "extension": "c", "filename": "i2c.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": 13565, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/contiki-2.6/platform/u101-stm32l/i2c.c", "provenance": "stackv2-0061.json.gz:5969", "repo_name": "hjawe557/marsta", "revision_date": "2012-11-14T15:53:24", "revision_id": "c7aed70ab0186b0fcf60bd9dc3eb40757d39aff5", "snapshot_id": "acd79f6ff21ef590205b8ce5b09b2fb10913dcfd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hjawe557/marsta/c7aed70ab0186b0fcf60bd9dc3eb40757d39aff5/contiki-2.6/platform/u101-stm32l/i2c.c", "visit_date": "2021-01-23T02:40:28.916592" }
stackv2
#include <stdint.h> #include <stdlib.h> #include <gpio.h> #include <stm32l_i2c.h> #include <stm32l_rcc.h> #include "i2c.h" uint32_t i2c_buses[] = { I2C1_BASE, I2C2_BASE, NULL }; /* This is painful. I2C operations implemented according to app. note AN2824 - "STM32F10xxx I2C optimized examples" using polling read and write in order to test the on-board I2C peripherals. Ideally these should be implemented using interrupts and/or DMA.x */ void i2c_init(const uint32_t busnum, uint32_t rate) { I2C_ *ib = (I2C_ *)i2c_buses[busnum]; /* Ensure that the external bus doesn't interfere with i2c */ /* AFIO->MAPR2 |= 0x400; */ /* Enable alternate functions, port B and i2c */ RCC->AHBENR |= RCC_AHBENR_GPIOBEN; RCC->APB1ENR |= RCC_APB1ENR_I2C1EN; if (I2C_BUS_1 == busnum) { gpio_conf_af(GPIOB, 6, GPIO_OUTPUT_TYPE_PPULL, GPIO_OSPEED_40MHZ, GPIO_RESISTORS_PULLUP); gpio_conf_af(GPIOB, 7, GPIO_OUTPUT_TYPE_PPULL, GPIO_OSPEED_40MHZ, GPIO_RESISTORS_PULLUP); gpio_map_af(GPIOB, 6, GPIO_AF_I2C1); gpio_map_af(GPIOB, 7, GPIO_AF_I2C1); } else { /* We're careful with this for now. It's shared with the debug USART */ return; } #if 0 /* SCL1 */ GPIO_CONF_OUTPUT_PORT(B, 6, ALT_OPEN_DRAIN, 50); /* SDA1 */ GPIO_CONF_OUTPUT_PORT(B, 7, ALT_OPEN_DRAIN, 50); #endif #if 0 /* Disable */ ib->CR1 &= ~(I2C_CR1_PE); /* Fast */ /* ib->CCR &= I2C_CCR_FS; */ /* CCR */ tmp = ib->CCR; tmp &= 0xf000; tmp |= 0x5e; ib->CCR = tmp; /* Freq */ tmp = ib->CR2; tmp &= 0xffc0; tmp |= 0x20; ib->CR2 = tmp; /* TRISE */ ib->TRISE = 0x0b; #else /* Disable peripheral while configuring */ ib->CR1 &= ~(I2C_CR1_PE); /* Bit 14 should be kept at 1 by software */ ib->OAR1 = 0x4000; /* Frequency, 8 MHz */ ib->CR2 = 0x0008; /* clock configure, period is 0x28 (dec 40) * PCLK */ ib->CCR = 0x0028; /* Rise time... */ ib->TRISE = 0x0009; /* Set ACK bit */ ib->CR1 |= I2C_CR1_ACK; #endif /* Enable */ ib->CR1 |= I2C_CR1_PE; } #if 0 static void i2c_send_address(uint32_t bus, uint8_t slave, uint8_t rw) { I2C_ *ib = (I2C_ *)bus; ib->DR = (uint8_t)((slave) | rw); } #endif static void i2c_busywait(uint32_t n) { for(; n != 0; n--); } static int i2c_start(uint32_t bus) { I2C_ *ib = (I2C_ *)bus; int i; int timeout; timeout = 0x10000; /* Send start */ ib->CR1 |= I2C_CR1_START; /* Wait until start is sent and bus is switched to master */ for (i=0; i < timeout && !((ib->SR1 & I2C_SR1_SB) && (ib->SR2 & (I2C_SR2_MSL | I2C_SR2_BUSY))); i++) { i2c_busywait(100); } if (i >= timeout) { return -2; } return 0; } int i2c_read(uint32_t bus, uint8_t address, const uint8_t len, uint8_t *buf) { I2C_ *ib = (I2C_ *)bus; int timeout; int i; int n; volatile uint32_t tmp; if (i2c_start(bus)) { return -1; } /* Send address, 1 for read */ ib->DR = (uint8_t)(address | 0x01); timeout = 0x10000; /* Wait until address is set */ for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_ADDR); i++) { i2c_busywait(100); } if (i >= timeout) { //return -3; } if (len == 1) { /* ACK = 0 */ ib->CR1 &= ~(I2C_CR1_ACK); /* Disable interrupts */ ib->CR2 &= ~(I2C_CR2_ITBUFEN | I2C_CR2_ITEVTEN | I2C_CR2_ITERREN); /* Read SR1 and SR2 to clear the ADDR bit in SR1 */ tmp = ib->SR1; tmp = ib->SR2; /* Set STOP */ ib->CR1 |= I2C_CR1_STOP; /* Enable interrupts */ ib->CR2 |= (I2C_CR2_ITBUFEN | I2C_CR2_ITEVTEN | I2C_CR2_ITERREN); /* Wait until RXNE == 1 */ for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_RXNE); i++) { i2c_busywait(100); } if (i >= timeout) { return -4; } /* Read data */ tmp = (ib->DR); /* len = 1 so we only want one byte */ buf[0] = (uint8_t)tmp; /* Wait until STOP is cleared by hw */ for (i=0; i < timeout && (ib->CR1 & I2C_CR1_STOP); i++) { i2c_busywait(100); } if (i >= timeout) { return -5; } /* ACK = 1 so we're ready for next reception */ ib->CR1 |= (I2C_CR1_ACK); } else if (len == 2) { /* POS = 1 */ ib->CR1 |= (I2C_CR1_POS); /* Disable interrupts */ ib->CR2 &= ~(I2C_CR2_ITBUFEN | I2C_CR2_ITEVTEN | I2C_CR2_ITERREN); /* Clear ADDR in SR1 by reading SR1 and SR2 */ tmp = ib->SR1; tmp = ib->SR2; /* ACK = 0 */ ib->CR1 &= ~(I2C_CR1_ACK); /* Enable interrupts */ ib->CR2 |= (I2C_CR2_ITBUFEN | I2C_CR2_ITEVTEN | I2C_CR2_ITERREN); /* Wait for BTF == 1 */ for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_BTF); i++) { i2c_busywait(100); } if (i >= timeout) { return -6; } /* Disable interrupts */ ib->CR2 &= ~(I2C_CR2_ITBUFEN | I2C_CR2_ITEVTEN | I2C_CR2_ITERREN); /* STOP = 1 */ ib->CR1 |= I2C_CR1_STOP; /* Wait until RXNE == 1 */ for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_RXNE); i++) { i2c_busywait(100); } /* Read data 1 (0) */ tmp = (ib->DR); /* len = 1 so we only want one byte */ buf[0] = (uint8_t)tmp; /* Enable interrupts */ ib->CR2 |= (I2C_CR2_ITBUFEN | I2C_CR2_ITEVTEN | I2C_CR2_ITERREN); /* Read data 2 (1) */ tmp = (ib->DR); /* len = 1 so we only want one byte */ buf[1] = (uint8_t)tmp; /* Wait until STOP is cleared by hw */ for (i=0; i < timeout && (ib->CR1 & I2C_CR1_STOP); i++) { i2c_busywait(100); } if (i >= timeout) { return -7; } /* POS = 0 */ ib->CR1 &= ~(I2C_CR1_POS); /* ACK = 1 so we're ready for next reception */ ib->CR1 |= (I2C_CR1_ACK); } else { /* We have read 0 bytes yet */ n = 0; /* Read all bytes but the last in this loop */ while (n+3 >= len) { /* Wait until RXNE == 1 */ for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_RXNE); i++) { i2c_busywait(100); } if (i >= timeout) { return -11; } /* Read data N */ tmp = (ib->DR); /* len = 1 so we only want one byte */ buf[n] = (uint8_t)tmp; /* We have read one more byte */ n++; } /* Wait until BTF == 1 is set */ for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_BTF); i++) { i2c_busywait(100); } if (i >= timeout) { /* Maybe we should do something better here? */ return -83; } /* ACK = 0 */ ib->CR1 &= ~(I2C_CR1_ACK); /* Disable interrupts */ ib->CR2 &= ~(I2C_CR2_ITBUFEN | I2C_CR2_ITEVTEN | I2C_CR2_ITERREN); /* STOP = 1 */ ib->CR1 |= I2C_CR1_STOP; /* Read data n */ tmp = (ib->DR); /* len = 1 so we only want one byte */ buf[n] = (uint8_t)tmp; /* We have read one more byte */ n++; /* Enable interrupts */ ib->CR2 |= (I2C_CR2_ITBUFEN | I2C_CR2_ITEVTEN | I2C_CR2_ITERREN); /* Wait until RXNE == 1 */ for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_RXNE); i++) { i2c_busywait(100); } if (i >= timeout) { return -11; } /* Read data N */ tmp = (ib->DR); /* len = 1 so we only want one byte */ buf[n] = (uint8_t)tmp; /* We have read one more byte */ n++; /* Wait until STOP is cleared by hw */ for (i=0; i < timeout && (ib->CR1 & I2C_CR1_STOP); i++) { i2c_busywait(100); } if (i >= timeout) { return -7; } /* ACK = 1 so we're ready for next reception */ ib->CR1 |= (I2C_CR1_ACK); return -20; } return 0; } #define I2C_WAIT(x, t, e) \ { int _i; \ for (_i=0; _i < t && x; _i++) \ { i2c_busywait(100); } \ if (_i >= timeout) return e; \ } int i2c_write(uint32_t bus, uint8_t address, const uint8_t len, uint8_t *buf, uint8_t nostop) { I2C_ *ib = (I2C_ *)bus; int timeout; int i, j; volatile uint32_t tmp; timeout = 0x10000; /* LSB must be zero, since it differentiates between read and write */ if (address & 0x01) { return -1; } if (i2c_start(bus)) { return -2; } /* Send address, low bit 0 for read */ ib->DR = (uint8_t)address; /* Wait until address is set */ I2C_WAIT(!(ib->SR1 & I2C_SR1_ADDR), timeout, -3); #if 0 for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_ADDR); i++) { i2c_busywait(100); } if (i >= timeout) { return -81; } #endif /* Clear ADDR in SR1 by reading SR1 and SR2 */ tmp = ib->SR1; tmp = ib->SR2; for (j=0; j<len; j++) { /* Send byte */ ib->DR = buf[j]; /* Wait until byte is sent is set */ for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_TXE); i++) { i2c_busywait(100); } if (i >= timeout) { /* Maybe we should do something better here? */ return -82; } } /* Wait until BTF == 1 is set */ for (i=0; i < timeout && !(ib->SR1 & I2C_SR1_BTF); i++) { i2c_busywait(100); } if (i >= timeout) { /* Maybe we should do something better here? */ return -83; } if (!nostop) { ib->CR1 |= (I2C_CR1_STOP); /* Wait until STOP is cleared by hw */ for (i=0; i < timeout && (ib->CR1 & I2C_CR1_STOP); i++) { i2c_busywait(100); } if (i >= timeout) { return -84; } } return 0; } int i2c_transact(uint32_t bus, uint8_t address, uint8_t rw, const uint8_t len, uint8_t nostop, uint8_t *buf) { if (len == 0) { return -1; } if (1 == rw) { return i2c_read(bus, address, len, buf); } else { return i2c_write(bus, address, len, buf, nostop); } }
2.390625
2
2024-11-18T19:53:11.267857+00:00
2021-11-15T23:48:57
eec5190df3790dce1c5a8e5381773bb8236ad954
{ "blob_id": "eec5190df3790dce1c5a8e5381773bb8236ad954", "branch_name": "refs/heads/main", "committer_date": "2021-11-15T23:48:57", "content_id": "de82e2bf577266847590debced3e7ca95b0d5cf5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "28e4073b48688904621621d82820138496400f5a", "extension": "h", "filename": "Contesti.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 428443199, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2790, "license": "Apache-2.0", "license_type": "permissive", "path": "/INC/Contesti.h", "provenance": "stackv2-0061.json.gz:6740", "repo_name": "gtoffoli/iperlogo", "revision_date": "2021-11-15T23:48:57", "revision_id": "568fd89addbd90c35cdc7b2620705faa6f488f8e", "snapshot_id": "3a8bb3d0a6c1b90b60e91d2aeeb2133ed0b3d452", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gtoffoli/iperlogo/568fd89addbd90c35cdc7b2620705faa6f488f8e/INC/Contesti.h", "visit_date": "2023-08-30T16:28:00.234811" }
stackv2
/* CONTESTI.H Giovanni Toffoli 990919 uso di #pragma pack per passaggio /Zp1 -> /Zp8 (standard) 981224 DIM_LSTACK: 1000 -> 10000; MAX_CONTESTO: 10 -> 100 980831 eliminato node 980127 estratto da ILCOMUNE.C */ #define DIM_LSTACK 10000 // dimensione dello stack logo in elementi di array typedef unsigned long DWORD; // #define node DWORD #define MAX_CONTESTO 100 // massima nidificazione di contesti #pragma pack(push, contesti, 1) struct contesto { node _id_contesto; /* identificatore del motivo di attivazione contesto */ int _dev_recupera, /* device per comando recupera */ _liv_procedura, /* livello di nest delle procedure LOGO */ _in_liv_proc, /* valore di liv_procedura a inizio PAUSA/RECUPERA */ _liv_funzione, /* livello di profondita' delle funzioni */ _in_liv_funzione;/* valore di liv_funzione a inizio PAUSA/RECUPERA */ node _funzione; /* indir. funzione (primitiva o procedura) corrente */ int _liv_esecuzione, /* livello di discesa albero di esecuzione (blocchi) */ _val_verifica, /* valore corrente del predicato argomento di "se" */ _conto_esegui; /* contatore delle iterazioni di un blocco */ int _RepCount, _RepTotal; node _token, /* elemento della lista di comando */ _ini_token; /* token iniziale */ int _n_arg_attesi, /* numero argomenti attesi */ _n_arg_trovati, /* numero argomenti incontrati */ _parentesi, /* */ _conto_parentesi,/* conto algebrico parentesi in valut. espressione */ _p_sc, /* pointer allo stack di controllo */ _p_sv, /* pointer allo stack dei valori */ _ini_p_sv; /* pointer iniziale allo stack dei valori in contesto*/ node _linea_com; /* lista che rappresenta una linea di comando parsed */ }; #pragma pack(pop, contesti) #define DIM_CONTESTO (sizeof (struct contesto)) /* dim. contesto in byte */ #define id_contesto (contesti[0]._id_contesto) #define dev_recupera (contesti[0]._dev_recupera) #define liv_procedura (contesti[0]._liv_procedura) #define in_liv_proc (contesti[0]._in_liv_proc) #define liv_funzione (contesti[0]._liv_funzione) #define in_liv_funzione (contesti[0]._in_liv_funzione) #define funzione (contesti[0]._funzione) #define liv_esecuzione (contesti[0]._liv_esecuzione) #define val_verifica (contesti[0]._val_verifica) #define conto_esegui (contesti[0]._conto_esegui) #define RepCount (contesti[0]._RepCount) #define RepTotal (contesti[0]._RepTotal) #define token (contesti[0]._token) #define ini_token (contesti[0]._ini_token) #define n_arg_attesi (contesti[0]._n_arg_attesi) #define n_arg_trovati (contesti[0]._n_arg_trovati) #define parentesi (contesti[0]._parentesi) #define conto_parentesi (contesti[0]._conto_parentesi) #define p_sc (contesti[0]._p_sc) #define p_sv (contesti[0]._p_sv) #define ini_p_sv (contesti[0]._ini_p_sv) #define linea_com (contesti[0]._linea_com)
2.421875
2
2024-11-18T19:53:11.477471+00:00
2021-07-06T13:27:18
9c6d9434fac1a34797bb6dff88636aee312d0ab6
{ "blob_id": "9c6d9434fac1a34797bb6dff88636aee312d0ab6", "branch_name": "refs/heads/master", "committer_date": "2021-07-06T13:27:18", "content_id": "c9f0ddee3ef20db0f913646d2c1ce7ea2ff6581e", "detected_licenses": [ "MIT" ], "directory_id": "094f891c992a9c1406b5b7ffe681b35967a5dcfd", "extension": "h", "filename": "vbac_compression.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": 2847, "license": "MIT", "license_type": "permissive", "path": "/include/vbac_compression.h", "provenance": "stackv2-0061.json.gz:6997", "repo_name": "PeterZhouSZ/Vertex-Blend-Attribute-Compression", "revision_date": "2021-07-06T13:27:18", "revision_id": "4c651fff06d4ab6dfa2649b1dacf2c10b7b8b4e4", "snapshot_id": "bd13bf0792f972ad19706db6010104992ac05863", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PeterZhouSZ/Vertex-Blend-Attribute-Compression/4c651fff06d4ab6dfa2649b1dacf2c10b7b8b4e4/include/vbac_compression.h", "visit_date": "2023-06-13T06:11:21.038785" }
stackv2
/* Copyright 2021 Bastian Kuth [email protected], Quirin Meyer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #ifndef VBAC_COMPRESSION #define VBAC_COMPRESSION /* C interface */ #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <math.h> typedef uint8_t bone_index; /* struct that gets generated by the OSS compression function. Needs to be passed to the decompression function */ typedef struct { uint64_t N; /* number of sample points at the v2 axis */ uint64_t MI4; /* maximum global Index into v4 axis (used for flipping the function) */ double scale; /* distance between two saple points (twice the maximum quantization error) */ } vbac_oss_info; /* --- DECLARATION OF INTERFACE FUNCTIONS --- */ /* * Sorts a weight tuple and the corresponding index tuple descending by weight (w1 >= w2 >= w3 ...) * Takes an array of weights and an array of indices. weightsPerTuple is usually 4. nTuples is the total number of weight and index tuples. * Selection sort is used to sort the tuples */ void vbac_sortTuplesByWeight( float* const weightTuples, bone_index* const indexTuples, size_t const weightsPerTuple, size_t const nTuples ); /* * Compresses the weight tuples with the OSS method. * Returns the vbac_oss_info struct that is required for decompression. */ vbac_oss_info vbac_oss_compress( float const* weightTuples, size_t const nTuples, size_t const totalBits, uint64_t* const compressedData ); /* * Decompresses the weight tuples compressed with the OSS method. * As this is supposed to be done on the GPU, this function is only ment to be used for testing. */ void vbac_oss_decompress( uint64_t const* compressedData, size_t const nTuples, vbac_oss_info const info, float* weightTuples ); #ifdef __cplusplus } #endif #endif
2.234375
2
2024-11-18T19:53:12.364591+00:00
2012-12-22T05:59:30
8f9e675ba5fddb4db9b34430c1f9894f54d7c3e4
{ "blob_id": "8f9e675ba5fddb4db9b34430c1f9894f54d7c3e4", "branch_name": "refs/heads/master", "committer_date": "2012-12-22T06:02:05", "content_id": "5bdee51851df3ece90e55676d6e64c465835da78", "detected_licenses": [ "MIT" ], "directory_id": "afee5a2565216ff1958d9f698002b5453d71d0d3", "extension": "c", "filename": "collision.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 7283055, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 591, "license": "MIT", "license_type": "permissive", "path": "/collision.c", "provenance": "stackv2-0061.json.gz:7638", "repo_name": "aatishnn/CarRace", "revision_date": "2012-12-22T05:59:30", "revision_id": "5d4ec784e7610a3a5e7f7620c7bcaefb1b8ca4c1", "snapshot_id": "d73a37caca5018caf4b31aae6da31e458ebc32ff", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aatishnn/CarRace/5d4ec784e7610a3a5e7f7620c7bcaefb1b8ca4c1/collision.c", "visit_date": "2020-04-06T03:41:52.775006" }
stackv2
#include <SDL/SDL.h> #include "main.h" int check_collision ( SDL_Rect A, SDL_Rect B ) { int leftA, leftB; int rightA, rightB; int topA, topB; int bottomA, bottomB; leftA = A.x; rightA = A.x + A.w; topA = A.y; bottomA = A.y + A.h; leftB = B.x; rightB = B.x + B.w; topB = B.y; bottomB = B.y + B.h; if ( bottomA <= topB ) { return FALSE; } if ( topA >= bottomB ) { return FALSE; } if ( rightA <= leftB ) { return FALSE; } if ( leftA >= rightB ) { return FALSE; } return TRUE; }
2.453125
2
2024-11-18T19:53:12.745920+00:00
2021-07-13T10:41:07
956605be410ec9646125335ae96533d534110048
{ "blob_id": "956605be410ec9646125335ae96533d534110048", "branch_name": "refs/heads/master", "committer_date": "2021-07-13T10:41:07", "content_id": "3fe551821e13281857131586b9bee0c08982449c", "detected_licenses": [ "MIT" ], "directory_id": "07b73cd7a7a00829a3c234d73f9e14cdd1a774d9", "extension": "h", "filename": "duplication.h", "fork_events_count": 1, "gha_created_at": "2018-06-08T05:07:19", "gha_event_created_at": "2021-06-29T06:43:39", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 136568996, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5446, "license": "MIT", "license_type": "permissive", "path": "/lib/include/xnetwork/generators/duplication.h", "provenance": "stackv2-0061.json.gz:8023", "repo_name": "luk036/xnetwork", "revision_date": "2021-07-13T10:41:07", "revision_id": "462c25da3aead6b834e6027f4d679dc47965b134", "snapshot_id": "b70b0a27e46f9a78c82925786b35d9122ad28180", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/luk036/xnetwork/462c25da3aead6b834e6027f4d679dc47965b134/lib/include/xnetwork/generators/duplication.h", "visit_date": "2021-07-23T18:42:16.184275" }
stackv2
// duplication.py - functions for generating graphs by duplicating nodes // // Copyright 2016-2018 XNetwork developers. // Copyright (C) 2004-2018 by // Wai-Shing Luk <[email protected]> // Dan Schult <[email protected]> // Pieter Swart <[email protected]> // // This file is part of XNetwork. // // XNetwork is distributed under a BSD license; see LICENSE.txt for more // information. /** Functions for generating graphs based on the "duplication" method. These graph generators start with a small initial graph then duplicate nodes && (partially) duplicate their edges. These functions are generally inspired by biological networks. /** import random #include <xnetwork.hpp> // as xn #include <xnetwork/exception.hpp> // import XNetworkError static const auto __all__ = ["partial_duplication_graph", "duplication_divergence_graph"]; auto partial_duplication_graph(N, n, p, q, seed=None) { /** Return a random graph using the partial duplication model. Parameters ---------- N : int The total number of nodes : the final graph. n : int The number of nodes : the initial clique. p : double The probability of joining each neighbor of a node to the duplicate node. Must be a number : the between zero && one, inclusive. q : double The probability of joining the source node to the duplicate node. Must be a number : the between zero && one, inclusive. seed : int, optional Seed for random number generator (default=None). Notes ----- A graph of nodes is grown by creating a fully connected graph of size `n`. The following procedure is then repeated until a total of `N` nodes have been reached. 1. A random node, *u*, is picked && a new node, *v*, is created. 2. For each neighbor of *u* an edge from the neighbor to *v* is created with probability `p`. 3. An edge from *u* to *v* is created with probability `q`. This algorithm appears : [1]. This implementation allows the possibility of generating disconnected graphs. References ---------- .. [1] Knudsen Michael, && Carsten Wiuf. "A Markov chain approach to randomly grown graphs." Journal of Applied Mathematics 2008. <https://doi.org/10.1155/2008/190836> */ if (p < 0 || p > 1 || q < 0 || q > 1) { const auto msg = "partial duplication graph must have 0 <= p, q <= 1." throw XNetworkError(msg); if (n > N) { throw XNetworkError("partial duplication graph must have n <= N."); if (seed is not None) { random.seed(seed); G = xn::complete_graph(n); for (auto new_node : range(n, N) { // Add a new vertex, v, to the graph. G.add_node(new_node); // Pick a random vertex, u, already : the graph. src_node = random.randint(0, new_node); // Join v && u with probability q. if (random.random() < q) { G.add_edge(new_node, src_node); // For each neighbor of u... for (auto neighbor_node : list(xn::all_neighbors(G, src_node)) { // Add the neighbor to v with probability p. if (random.random() < p) { G.add_edge(new_node, neighbor_node); return G; auto duplication_divergence_graph(n, p, seed=None) { /** Return an undirected graph using the duplication-divergence model. A graph of `n` nodes is created by duplicating the initial nodes && retaining edges incident to the original nodes with a retention probability `p`. Parameters ---------- n : int The desired number of nodes : the graph. p : double The probability for retaining the edge of the replicated node. seed : int, optional A seed for the random number generator of :mod:`random` (default=None). Returns ------- G : Graph Raises ------ XNetworkError If `p` is not a valid probability. If `n` is less than 2. Notes ----- This algorithm appears : [1]. This implementation disallows the possibility of generating disconnected graphs. References ---------- .. [1] I. Ispolatov, P. L. Krapivsky, A. Yuryev, "Duplication-divergence model of protein interaction network", Phys. Rev. E, 71, 061911, 2005. */ if (p > 1 || p < 0) { const auto msg = "XNetworkError p={0} is not : [0,1].".format(p); throw xn::XNetworkError(msg); if (n < 2) { const auto msg = "n must be greater than || equal to 2"; throw xn::XNetworkError(msg); if (seed is not None) { random.seed(seed); G = xn::Graph(); // Initialize the graph with two connected nodes. G.add_edge(0, 1); i = 2 while (i < n) { // Choose a random node from current graph to duplicate. random_node = random.choice(list(G)); // Make the replica. G.add_node(i); // flag indicates whether at least one edge is connected on the replica. flag = false; for (auto nbr : G.neighbors(random_node) { if (random.random() < p) { // Link retention step. G.add_edge(i, nbr); flag = true; if (!flag) { // Delete replica if (no edges retained. G.remove_node(i); } else { // Successful duplication. i += 1; return G;
2.25
2
2024-11-18T19:53:13.204341+00:00
2023-04-03T09:05:33
39037378822447cdeec05d4654c60851dd894156
{ "blob_id": "39037378822447cdeec05d4654c60851dd894156", "branch_name": "refs/heads/master", "committer_date": "2023-04-03T09:05:33", "content_id": "4b012649fb0a88f142efc7380a5e0a35e9c3e3fc", "detected_licenses": [ "MIT" ], "directory_id": "9dfd4730250717a816da4516f2da5b2eb9649d84", "extension": "c", "filename": "timer_test.c", "fork_events_count": 2, "gha_created_at": "2019-10-31T15:22:13", "gha_event_created_at": "2020-10-19T07:06:14", "gha_language": "C", "gha_license_id": null, "github_id": 218796798, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3673, "license": "MIT", "license_type": "permissive", "path": "/test/timer/timer_test.c", "provenance": "stackv2-0061.json.gz:8540", "repo_name": "Maldus512/generic_embedded_libs", "revision_date": "2023-04-03T09:05:33", "revision_id": "f5c2ccfc6e1cdd4fa93970f115064f96959e36ae", "snapshot_id": "74ac7e45b541e9cbff33f3b90ba1df7a7dd25cde", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Maldus512/generic_embedded_libs/f5c2ccfc6e1cdd4fa93970f115064f96959e36ae/test/timer/timer_test.c", "visit_date": "2023-04-15T10:17:23.629104" }
stackv2
#include <string.h> #include <stdio.h> #include <stdlib.h> #include "timer/stopwatch.h" #include "unity.h" void setUp() {} void tearDown() {} void test_start_timer() { stopwatch_t timer; stopwatch_init(&timer); TEST_ASSERT_EQUAL(TIMER_STOPPED, stopwatch_get_state(&timer)); TEST_ASSERT_EQUAL(0, stopwatch_start(&timer, 0)); TEST_ASSERT_EQUAL(TIMER_COUNTING, stopwatch_get_state(&timer)); TEST_ASSERT_EQUAL(-1, stopwatch_start(&timer, 0)); } void test_count_timer() { stopwatch_t timer; stopwatch_init(&timer); stopwatch_start(&timer, 0); TEST_ASSERT_EQUAL(0, stopwatch_get_elapsed(&timer, 0)); TEST_ASSERT_EQUAL(10, stopwatch_get_elapsed(&timer, 10)); TEST_ASSERT_EQUAL(1000, stopwatch_get_elapsed(&timer, 1000)); TEST_ASSERT_EQUAL(200, stopwatch_get_elapsed(&timer, 200)); stopwatch_stop(&timer); TEST_ASSERT_EQUAL(TIMER_STOPPED, stopwatch_get_state(&timer)); TEST_ASSERT_EQUAL(0, stopwatch_get_elapsed(&timer, 0)); TEST_ASSERT_EQUAL(0, stopwatch_get_elapsed(&timer, 10)); TEST_ASSERT_EQUAL(0, stopwatch_get_elapsed(&timer, 1000)); } void test_set_timer() { stopwatch_t timer; stopwatch_init(&timer); TEST_ASSERT_EQUAL(0, stopwatch_set(&timer, 1000)); TEST_ASSERT_EQUAL(1000, stopwatch_get_total_time(&timer)); TEST_ASSERT_EQUAL(0, stopwatch_set(&timer, 2000)); TEST_ASSERT_EQUAL(2000, stopwatch_get_total_time(&timer)); TEST_ASSERT_EQUAL(TIMER_STOPPED, stopwatch_get_state(&timer)); // Cannot set a started timer; it has to be stopped first stopwatch_start(&timer, 0); TEST_ASSERT_EQUAL(-1, stopwatch_set(&timer, 2000)); TEST_ASSERT_EQUAL(2000, stopwatch_get_remaining(&timer, 0)); TEST_ASSERT_EQUAL(1500, stopwatch_get_remaining(&timer, 500)); TEST_ASSERT(!stopwatch_is_timer_reached(&timer, 500)); TEST_ASSERT_EQUAL(500, stopwatch_get_remaining(&timer, 1500)); TEST_ASSERT_EQUAL(0, stopwatch_get_remaining(&timer, 2000)); TEST_ASSERT(stopwatch_is_timer_reached(&timer, 2001)); TEST_ASSERT_EQUAL(0, stopwatch_get_remaining(&timer, 2500)); stopwatch_change(&timer, 42, 40); TEST_ASSERT(!stopwatch_is_timer_reached(&timer, 40)); TEST_ASSERT(stopwatch_is_timer_reached(&timer, 82)); TEST_ASSERT_EQUAL(42, stopwatch_get_total_time(&timer)); } void test_pause_timer() { stopwatch_t timer; unsigned long time = 0; stopwatch_init(&timer); stopwatch_set(&timer, 100); stopwatch_start(&timer, time); time += 20; TEST_ASSERT_EQUAL(0, stopwatch_pause(&timer, time)); TEST_ASSERT_EQUAL(-1, stopwatch_pause(&timer, time)); time += 100; stopwatch_start(&timer, time); TEST_ASSERT_EQUAL(80, stopwatch_get_remaining(&timer, time)); time += 70; TEST_ASSERT_EQUAL(10, stopwatch_get_remaining(&timer, time)); time += 10; TEST_ASSERT_EQUAL(0, stopwatch_get_remaining(&timer, time)); } void test_stress() { unsigned long time = 0, elapsed = 0; stopwatch_t timer; stopwatch_init(&timer); srand(42); stopwatch_set(&timer, 100000000); stopwatch_start(&timer, time); while (!stopwatch_is_timer_reached(&timer, time)) { unsigned long delay = rand() % 1000; time += delay; if (stopwatch_get_state(&timer) == TIMER_COUNTING) elapsed += delay; switch (rand() % 2) { case 0: stopwatch_pause(&timer, time); break; case 1: stopwatch_start(&timer, time); break; default: break; } TEST_ASSERT_EQUAL(elapsed, stopwatch_get_elapsed(&timer, time)); } }
2.5
2
2024-11-18T19:53:13.263293+00:00
2014-05-18T23:09:40
ed3602cb3ca428a191f9d9c8874d57a8fc0c43af
{ "blob_id": "ed3602cb3ca428a191f9d9c8874d57a8fc0c43af", "branch_name": "refs/heads/master", "committer_date": "2014-05-18T23:09:40", "content_id": "9a93f91394fa3860d19753dac419e0807b0e1b7a", "detected_licenses": [ "MIT" ], "directory_id": "44f5e95f7f34ec63d35215de61e21d14dff212a2", "extension": "c", "filename": "collfs_fopen.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": 1860, "license": "MIT", "license_type": "permissive", "path": "/collfs_fopen.c", "provenance": "stackv2-0061.json.gz:8668", "repo_name": "michaeldcruz/collfs", "revision_date": "2014-05-18T23:09:40", "revision_id": "e00c5d744c2646f8cab90dcace99639ce1fce12a", "snapshot_id": "c5c28c936873936fb6df9f2aab2c63cb94e96bde", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/michaeldcruz/collfs/e00c5d744c2646f8cab90dcace99639ce1fce12a/collfs_fopen.c", "visit_date": "2021-01-23T17:43:25.837740" }
stackv2
/* This file implements custom C string streams for read-only collective file system access. For more information about custom C strings, see: http://www.gnu.org/software/libc/manual/html_node/Custom-Streams.html#Custom-Streams */ #define _GNU_SOURCE // needed to expose cookie_io_functions_t #include <errno.h> #include <libio.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <sys/types.h> #include <fcntl.h> #include "collfs-private.h" typedef struct fcollfs_cookie_struct fcollfs_cookie_t; struct fcollfs_cookie_struct { int fd; }; static ssize_t fcollfs_read (void *cookie, char *b, size_t s) { int fd; fcollfs_cookie_t *c; c = (fcollfs_cookie_t *) cookie; fd = c->fd; return __collfs_libc_read(fd, b, s); } static ssize_t fcollfs_write (void *cookie __attribute__ ((unused)), const char *b __attribute__ ((unused)), size_t s __attribute__ ((unused))) { // this is an error! return 0; } static int fcollfs_seek (void *cookie, _IO_off64_t *p, int w) { int fd; off_t new_p; fcollfs_cookie_t *c; c = (fcollfs_cookie_t *) cookie; fd = c->fd; new_p = __collfs_lseek(fd, *p, w); if (new_p == -1) { return -1; } *p = new_p; return 0; } static int fcollfs_close (void *cookie) { int fd; fcollfs_cookie_t *c; c = (fcollfs_cookie_t *) cookie; fd = c->fd; free (c); return __collfs_close(fd); } FILE * fcollfs_open (const char *pathname, const char *mode) { cookie_io_functions_t iof; fcollfs_cookie_t *c; if (mode[0] != 'r') return NULL; c = (fcollfs_cookie_t *) malloc (sizeof (fcollfs_cookie_t)); if (c == NULL) return NULL; c->fd = __collfs_open(pathname, O_RDONLY); iof.read = fcollfs_read; iof.write = fcollfs_write; iof.seek = fcollfs_seek; iof.close = fcollfs_close; return fopencookie (c, mode, iof); }
2.65625
3
2024-11-18T19:53:13.343346+00:00
2021-06-20T16:12:14
1704370fc2b408fab664c2850999a78472cef61c
{ "blob_id": "1704370fc2b408fab664c2850999a78472cef61c", "branch_name": "refs/heads/main", "committer_date": "2021-06-20T16:12:14", "content_id": "b7b58f733192768abfa10bb001c0c5ef98a572a1", "detected_licenses": [ "MIT" ], "directory_id": "1a8727fb395c611176da7dc9c8b3613787d7b8c1", "extension": "c", "filename": "HelloSystem.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 342709586, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 202, "license": "MIT", "license_type": "permissive", "path": "/SO/Laboratorul_2/HelloSystem.c", "provenance": "stackv2-0061.json.gz:8796", "repo_name": "ParaschivAlex/FMI-Thangs", "revision_date": "2021-06-20T16:12:14", "revision_id": "26d8a13b08344744ee6ab56f088dd4adb665980e", "snapshot_id": "a5f7ea6ebbbd0bc2f569298bf2afaa3a140058f4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ParaschivAlex/FMI-Thangs/26d8a13b08344744ee6ab56f088dd4adb665980e/SO/Laboratorul_2/HelloSystem.c", "visit_date": "2023-05-29T17:30:08.316074" }
stackv2
#include <stdio.h> #include <unistd.h> #include <sys/syscall.h> #include <fcntl.h> int main() { int d; d = open("foo.txt", O_RDWR | O_CREAT); write(d, "Hello World!\n", 13); close(d); return 0; }
2.3125
2
2024-11-18T20:30:35.970904+00:00
2018-04-17T02:07:29
bd57683d96f0af191365a20d0da2f960c6c7fe2f
{ "blob_id": "bd57683d96f0af191365a20d0da2f960c6c7fe2f", "branch_name": "refs/heads/master", "committer_date": "2018-04-17T02:07:29", "content_id": "8831a1721be25c363feeae8ae4f22fe0e7512eaa", "detected_licenses": [ "MIT" ], "directory_id": "a00e10d3a0f1143910b338ec0952ead97b7e05bb", "extension": "h", "filename": "pwm.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": 5582, "license": "MIT", "license_type": "permissive", "path": "/include/dev/hw/pwm.h", "provenance": "stackv2-0062.json.gz:274432", "repo_name": "cnguoyj/F4OS", "revision_date": "2018-04-17T02:07:29", "revision_id": "43e067e2108356c9a84f9b8362384143ba7f3f3f", "snapshot_id": "cd414138082f3244b73a9bccce4c6ea664435924", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cnguoyj/F4OS/43e067e2108356c9a84f9b8362384143ba7f3f3f/include/dev/hw/pwm.h", "visit_date": "2020-05-27T15:41:04.465055" }
stackv2
/* * Copyright (C) 2013 F4OS Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef DEV_PWM_H_INCLUDED #define DEV_PWM_H_INCLUDED #include <stdint.h> #include <kernel/obj.h> struct pwm { struct obj *gpio; struct obj obj; void *priv; }; /* Takes obj and returns containing struct pwm */ static inline struct pwm *to_pwm(struct obj *o) { return (struct pwm *) container_of(o, struct pwm, obj); } struct pwm_ops { /** * Enable or disable output * * Enables or disables PWM output on the channel. * * All parameters may be get/set whether output is enabled or disabled. * * @param pwm PWM output to enable/disable * @param enable Enable output if 1, disable if 0 * @return zero on success, negative on error */ int (*enable)(struct pwm *, uint8_t); /** * Set period * * Sets the period of the PWM output, in microseconds. If the * period cannot be changed (if a timer is being shared between several * outputs, for example), an error value is returned. * * The period will be set as closely to the passed in parameter as * possible. The actual set period will be returned. * * @param pwm PWM output to change period of * @param period Desired period, in microseconds * @returns set period, negative on error */ int32_t (*set_period)(struct pwm *, uint32_t); /** * Get period * * Gets the current period of the PWM output, in microseconds. * * If output is disabled, this returns the configured period value, * should the output be enabled. * * @param pwm PWM output to get period of * @returns Period of output */ uint32_t(*get_period)(struct pwm *); /** * Set pulse width * * Sets the PWM output pulse width, in microseconds. * * The pulse width will be set as closely as possible to the passed in * parameter. The actual set pulse width will be returned. * * @param pwm PWM output to set * @param width Desired pulse width, in microseconds * @returns set pulse width, negative on error */ int32_t (*set_pulse_width)(struct pwm *, uint32_t); /** * Get pulse width * * Gets the current pulse width of the PWM output, in microseconds. * * If output is disabled, this returns the configured pulse width value, * should the output be enabled. * * @param pwm PWM output to get pulse width of * @returns Pulse width of output */ uint32_t(*get_pulse_width)(struct pwm *); /** * Determine if PWM output hardware or software controlled * * @param pwm PWM output to check * @returns 1 if PWM controlled in hardware (e.g., with a timer), * 0 if controlled in software */ uint8_t (*is_hardware)(struct pwm *); /** * Implementation specific destructor * * Performs any implementation specific destruction necessary when freeing the * PWM object. * * @param pwm PWM object being destroyed * @returns zero on success, negative on error */ int (*dtor)(struct pwm *); }; extern struct class pwm_class; /** * Get PWM object * * Note: This function is implemented by the chip GPIO driver * * Get PWM object for passed in GPIO obj. A PWM object, controlled * either in hardware or software is allocated, and will output signals * on the passed in GPIO. * * The desired period is passed in to aid in matching the GPIO with a * compatible timer. If matched with a timer used by other PWM outputs, * it may not be possible to change the period after instantiation. * * If neither a hardware or software object can be allocated, NULL will be * returned. * * The reference count on the GPIO will be incremented when the object is * instantiated, and decremented when the object is destroyed. * * Once allocated, the output must be enabled with the enable method. Once * finish, the object should be freed with pwm_put(). * * @param gpio GPIO number to get PWM object for * @param period Desired period * @returns PWM object on success, NULL on error */ struct obj *pwm_get(struct obj *gpio, uint32_t period); /** * Return PWM object * * Release a PWM object received by pwm_get. This must be called when * you are finished using the PWM. * * @param obj PWM obj received from pwm_get to release */ static inline void pwm_put(struct obj *o) { obj_put(o); } #endif
2.15625
2
2024-11-18T20:30:36.072714+00:00
2023-08-18T12:54:06
31d158b81b870a8e382732563daaf17ef63080c5
{ "blob_id": "31d158b81b870a8e382732563daaf17ef63080c5", "branch_name": "refs/heads/master", "committer_date": "2023-08-18T12:54:06", "content_id": "4019e4f2e7199f61e7e0e9b02618fa495621e87f", "detected_licenses": [ "MIT" ], "directory_id": "22446075c2e71ef96b4a4777fe966714ac96b405", "extension": "c", "filename": "main.c", "fork_events_count": 68, "gha_created_at": "2020-09-30T10:18:15", "gha_event_created_at": "2023-09-08T12:56:11", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 299882138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2253, "license": "MIT", "license_type": "permissive", "path": "/clicks/alcohol/example/main.c", "provenance": "stackv2-0062.json.gz:274562", "repo_name": "MikroElektronika/mikrosdk_click_v2", "revision_date": "2023-08-18T12:54:06", "revision_id": "49ab937390bef126beb7b703d5345fa8cd6e3555", "snapshot_id": "2cc2987869649a304763b0f9d27c920d42a11c16", "src_encoding": "UTF-8", "star_events_count": 77, "url": "https://raw.githubusercontent.com/MikroElektronika/mikrosdk_click_v2/49ab937390bef126beb7b703d5345fa8cd6e3555/clicks/alcohol/example/main.c", "visit_date": "2023-08-21T22:15:09.036635" }
stackv2
/*! * @file main.c * @brief Alcohol Click Example. * * # Description * The demo application shows the reading of the adc * values given by the sensors. * * The demo application is composed of two sections : * * ## Application Init * Configuring clicks and log objects. * * ## Application Task * Reads the adc value and prints in two forms (DEC and HEX). * * @author Jelena Milosavljevic * */ #include "board.h" #include "log.h" #include "alcohol.h" static alcohol_t alcohol; /**< Alcohol Click driver object. */ static log_t logger; /**< Logger object. */ void application_init ( void ) { log_cfg_t log_cfg; /**< Logger config object. */ alcohol_cfg_t alcohol_cfg; /**< Click config object. */ /** * Logger initialization. * Default baud rate: 115200 * Default log level: LOG_LEVEL_DEBUG * @note If USB_UART_RX and USB_UART_TX * are defined as HAL_PIN_NC, you will * need to define them manually for log to work. * See @b LOG_MAP_USB_UART macro definition for detailed explanation. */ LOG_MAP_USB_UART( log_cfg ); log_init( &logger, &log_cfg ); log_info( &logger, " Application Init " ); // Click initialization. alcohol_cfg_setup( &alcohol_cfg ); ALCOHOL_MAP_MIKROBUS( alcohol_cfg, MIKROBUS_1 ); if ( alcohol_init( &alcohol, &alcohol_cfg ) == ADC_ERROR ) { log_error( &logger, " Application Init Error. " ); log_info( &logger, " Please, run program again... " ); for ( ; ; ); } log_info( &logger, " Application Task " ); Delay_ms( 100 ); } void application_task ( void ) { uint16_t alcohol_an_value = 0; if ( alcohol_read_an_pin_value ( &alcohol, &alcohol_an_value ) != ADC_ERROR ) { log_printf( &logger, " ADC Value : %u\r\n", alcohol_an_value ); } float alcohol_an_voltage = 0; if ( alcohol_read_an_pin_voltage ( &alcohol, &alcohol_an_voltage ) != ADC_ERROR ) { log_printf( &logger, " AN Voltage : %.3f[V]\r\n\n", alcohol_an_voltage ); } Delay_ms( 1000 ); } void main ( void ) { application_init( ); for ( ; ; ) { application_task( ); } } // ------------------------------------------------------------------------ END
2.84375
3
2024-11-18T20:30:36.214546+00:00
2015-04-27T06:53:07
405f727db68acebcae83328ed66bdde7484ff181
{ "blob_id": "405f727db68acebcae83328ed66bdde7484ff181", "branch_name": "refs/heads/master", "committer_date": "2015-04-27T06:53:07", "content_id": "79eca78dec0d8ada989e83c92dba149fc6d1be07", "detected_licenses": [ "MIT" ], "directory_id": "63923259f3d7342350e2d8549b84485367c88fc5", "extension": "c", "filename": "test_main.c", "fork_events_count": 1, "gha_created_at": "2015-01-15T22:37:40", "gha_event_created_at": "2015-01-21T22:22:24", "gha_language": "Go", "gha_license_id": null, "github_id": 29321724, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12497, "license": "MIT", "license_type": "permissive", "path": "/system/task_pool/test_main.c", "provenance": "stackv2-0062.json.gz:274693", "repo_name": "superboy0712/ttk4145_2015spring", "revision_date": "2015-04-27T06:53:07", "revision_id": "9cddfbb5f229c96a7571756ede7bae3911811f38", "snapshot_id": "d4ed7aa206b4a4684a9ba80057a6a188d9df55df", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/superboy0712/ttk4145_2015spring/9cddfbb5f229c96a7571756ede7bae3911811f38/system/task_pool/test_main.c", "visit_date": "2021-01-20T12:22:02.585156" }
stackv2
/* * test_main.c * * Created on: Mar 28, 2015 * Author: yulongb */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <pthread.h> #include <string.h> /** * interfaces design * @ */ #include "lift_task_queue.h" #define N_LENGTH_OF_TASK_POOL 19 request_type_t request_pool[N_LENGTH_OF_TASK_POOL] = { 0 }; request_type_t request_pool2[N_LENGTH_OF_TASK_POOL] = { 0, 0, 0, 1, 2, 3, 4, 7, 6, 5, 4, 3, 2, 3, 1, 3, 1, request_call_up, 0 }; request_type_t request_pool3[N_LENGTH_OF_TASK_POOL] = { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, request_call_down, request_call_down }; request_type_t request_pool4[N_LENGTH_OF_TASK_POOL] = { request_call_down, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, request_call_up }; unsigned int get_nr_of_req(const request_type_t * pool, unsigned int length) { int ret = 0; for (int i = 0; i < length; i++) { switch (pool[i]) { case request_call_up: case request_call_down: case request_call_cmd: ret++; break; case request_call_up | request_call_down: case request_call_up | request_call_cmd: case request_call_cmd | request_call_down: ret += 2; break; case request_call_up | request_call_down | request_call_cmd: ret += 3; break; default: break; } } return ret; } /** * @return -1: empty, otherwise the optimal request * @ direction: input the searching direction, return the request's direction */ int get_optimal_request_from_specified_on_search_direction( const request_type_t * const pool, int specified, int *direction, request_type_t * ret_type) { int failed_count = 0; int ret = specified; if (*direction == 0){ *ret_type = request_up_dn_cmd; return ret; } while (1) { /* failed even */ if (failed_count % 2 == 0){ if (*direction > 0) { ret = get_nearest_request_of_specified_upward(pool, specified, request_up_n_cmd); *ret_type = request_up_n_cmd; } else { ret = get_nearest_request_of_specified_downward(pool, specified, request_dn_n_cmd); *ret_type = request_dn_n_cmd; } if (ret == -1) { failed_count++; *direction = -*direction; } else { return ret; } } /* failed odd */ assert(failed_count > 0); if (failed_count % 2 == 1) { if (*direction > 0) { ret = get_nearest_request_of_specified_upward(pool, 0, request_up_n_cmd); *ret_type = request_up_n_cmd; } else { ret = get_nearest_request_of_specified_downward(pool, N_LENGTH_OF_TASK_POOL - 1, request_dn_n_cmd); *ret_type = request_dn_n_cmd; } if (ret == -1) { failed_count++; *direction = -*direction; } else { return ret; } } /* failed limit */ if (failed_count >= 4){ *ret_type = request_empty; return -1; } } return ret; } extern const char *request_parse_string_table[8]; void get_optimal_test(int dir, const request_type_t * const pool, const char * testname) { printf("---------------------------%s, dir %d!!---------------------------",testname, dir); print_request_pool(pool, N_LENGTH_OF_TASK_POOL); request_type_t ret_type = request_empty; for (int i = 0; i < N_LENGTH_OF_TASK_POOL; i++) { int temp_dir = dir; int j = get_optimal_request_from_specified_on_search_direction( request_pool2, i, &temp_dir, &ret_type); printf("@%d, ret:%d %s dir:%d\n", i, j, request_parse_string_table[ret_type], temp_dir); } } typedef enum states { first_try = 1, second_try, third_try } states_t; int get_optimal_request_from_specified_on_search_direction_ver2( const request_type_t * const pool, int specified, int *direction, request_type_t * ret_type) { int ret = specified; states_t state = first_try; if (*direction == 0){ *ret_type = request_up_dn_cmd; return ret; } while (1) { switch (state) { case first_try: if (*direction > 0) { ret = get_nearest_request_of_specified_upward(pool, specified, request_up_n_cmd); *ret_type = request_up_n_cmd; } else { ret = get_nearest_request_of_specified_downward(pool, specified, request_dn_n_cmd); *ret_type = request_dn_n_cmd; } if(ret == -1){ state = second_try; *direction = -*direction; }else{ return ret; } break; case second_try: if (*direction > 0) { ret = get_nearest_request_of_specified_upward(pool, 0, request_up_n_cmd); *ret_type = request_up_n_cmd; } else { ret = get_nearest_request_of_specified_downward(pool, N_LENGTH_OF_TASK_POOL-1, request_dn_n_cmd); *ret_type = request_dn_n_cmd; } if(ret == -1){ state = third_try; *direction = -*direction; }else{ return ret; } break; case third_try: if (*direction > 0) { ret = get_nearest_request_of_specified_upward(pool, specified, request_up_n_cmd); *ret_type = request_up_n_cmd; } else { ret = get_nearest_request_of_specified_downward(pool, specified, request_dn_n_cmd); *ret_type = request_dn_n_cmd; } if(ret == -1){ *ret_type = request_empty; } return ret; break; default: break; } } return ret; } int get_optimal_request_from_specified_on_search_direction_ver3( const request_type_t * const pool, int specified, int *direction, request_type_t * ret_type) { int ret = specified; states_t state = first_try; if (*direction == 0){ *ret_type = request_up_dn_cmd; return ret; } while (1) { switch (state) { case first_try: if (*direction > 0) { ret = get_nearest_request_of_specified_upward(pool, specified, request_up_n_cmd); *ret_type = request_up_n_cmd; } else { ret = get_nearest_request_of_specified_downward(pool, specified, request_dn_n_cmd); *ret_type = request_dn_n_cmd; } if(ret == -1){ state = second_try; *direction = -*direction; }else{ return ret; } break; case second_try: if (*direction > 0) { ret = get_nearest_request_of_specified_upward(pool, 0, request_up_n_cmd); *ret_type = request_up_n_cmd; } else { ret = get_nearest_request_of_specified_downward(pool, N_LENGTH_OF_TASK_POOL-1, request_dn_n_cmd); *ret_type = request_dn_n_cmd; } if(ret == -1){ state = third_try; *direction = -*direction; }else{ return ret; } break; case third_try: if (*direction > 0) { ret = get_nearest_request_of_specified_upward(pool, 0, request_up_n_cmd); *ret_type = request_up_n_cmd; } else { ret = get_nearest_request_of_specified_downward(pool, N_LENGTH_OF_TASK_POOL-1, request_dn_n_cmd); *ret_type = request_dn_n_cmd; } if(ret == -1){ *ret_type = request_empty; } return ret; break; default: break; } } return ret; } void scheduling_test_general(int cur_floor, int dir, const request_type_t * const pool, const char * testname, int (*get_optimal_request)( const request_type_t * const pool, int specified, int *direction, request_type_t * ret_type)) { request_type_t request_pool_local[N_LENGTH_OF_TASK_POOL]; memcpy(request_pool_local, pool, N_LENGTH_OF_TASK_POOL * sizeof(request_type_t)); printf("\n\n\n%s\n", testname); puts("origin pool: "); print_request_pool(request_pool_local, N_LENGTH_OF_TASK_POOL); int temp_dir = dir; printf("TASKS LEFT %d, current floor is %d, direction %d\n", get_nr_of_req(request_pool_local, N_LENGTH_OF_TASK_POOL), cur_floor, temp_dir); puts("---------------------------Tests Start!!---------------------------"); int rc = cur_floor; request_type_t ret_type; int last_none_zero_actual_moving_dir = temp_dir; int mov_dir = temp_dir; while (get_nr_of_req(request_pool_local, N_LENGTH_OF_TASK_POOL) != 0) { rc = get_optimal_request(request_pool_local, cur_floor, &temp_dir, &ret_type); if(rc == -1){ break; } if(rc != cur_floor){ last_none_zero_actual_moving_dir = (rc-cur_floor)/abs(rc-cur_floor); cur_floor += last_none_zero_actual_moving_dir; mov_dir = last_none_zero_actual_moving_dir; }else{ mov_dir = 0; } if(cur_floor == rc){ clr_request_type(request_pool_local + rc, ret_type); } /* when 7 up, push 0 up */ if(cur_floor == 7 && mov_dir>0){ set_request_type(request_pool_local+0, request_call_up); } /** printing **/ //print_request_pool(request_pool_local, N_FLOORS); printf("TASKS LEFT %d, current floor is %d, output direction %d, moving dir %d\n", get_nr_of_req(request_pool_local, N_LENGTH_OF_TASK_POOL), cur_floor, temp_dir, mov_dir); temp_dir = last_none_zero_actual_moving_dir; } puts("---------------------------Tests End!!---------------------------"); puts("---------------------------Final Result!!---------------------------"); print_request_pool(request_pool_local, N_LENGTH_OF_TASK_POOL); printf("TASKS LEFT %d, current floor is %d, direction %d\n", get_nr_of_req(request_pool_local, N_LENGTH_OF_TASK_POOL), cur_floor, temp_dir); } void scheduling_test_general_dynamic(int cur_floor, int dir, const request_type_t * const pool, const char * testname, int (*get_optimal_request)( const request_type_t * const pool, int specified, int *direction, request_type_t * ret_type)) { request_type_t request_pool_local[N_LENGTH_OF_TASK_POOL]; memcpy(request_pool_local, pool, N_LENGTH_OF_TASK_POOL * sizeof(request_type_t)); printf("\n\n\n%s\n", testname); puts("origin pool: "); print_request_pool(request_pool_local, N_LENGTH_OF_TASK_POOL); int temp_dir = dir; printf("TASKS LEFT %d, current floor is %d, direction %d\n", get_nr_of_req(request_pool_local, N_LENGTH_OF_TASK_POOL), cur_floor, temp_dir); puts("---------------------------Tests Start!!---------------------------"); int rc = cur_floor; request_type_t ret_type; int last_none_zero_actual_moving_dir = temp_dir; int mov_dir = temp_dir; while (get_nr_of_req(request_pool_local, N_LENGTH_OF_TASK_POOL) != 0) { rc = get_optimal_request(request_pool_local, cur_floor, &temp_dir, &ret_type); if(rc == -1){ break; } if(rc != cur_floor){ last_none_zero_actual_moving_dir = (rc-cur_floor)/abs(rc-cur_floor); cur_floor += last_none_zero_actual_moving_dir; mov_dir = last_none_zero_actual_moving_dir; }else{ mov_dir = 0; } if(cur_floor == rc){ clr_request_type(request_pool_local + rc, ret_type); } /* ask if continue or insert some more new req */ char new_type; int new_floor; printf("'x' :continue; u/d/c number: new req. \n"); scanf("%c %d\n", &new_type, &new_floor); switch (new_type) { case 'x': break; case 'u': set_request_type(request_pool_local+new_floor, request_call_up); break; case 'd': set_request_type(request_pool_local+new_floor, request_call_down); break; case 'c': set_request_type(request_pool_local+new_floor, request_call_cmd); break; default: break; } /** printing **/ //print_request_pool(request_pool_local, N_FLOORS); printf("TASKS LEFT %d, current floor is %d, output direction %d, moving dir %d\n", get_nr_of_req(request_pool_local, N_LENGTH_OF_TASK_POOL), cur_floor, temp_dir, mov_dir); temp_dir = last_none_zero_actual_moving_dir; } puts("---------------------------Tests End!!---------------------------"); puts("---------------------------Final Result!!---------------------------"); print_request_pool(request_pool_local, N_LENGTH_OF_TASK_POOL); printf("TASKS LEFT %d, current floor is %d, direction %d\n", get_nr_of_req(request_pool_local, N_LENGTH_OF_TASK_POOL), cur_floor, temp_dir); } int main(void) { get_nearest_length_init(N_LENGTH_OF_TASK_POOL); // scheduling_test(N_LENGTH_OF_TASK_POOL - 1, -1, request_pool3, "top down"); // scheduling_test(0, 1, request_pool3, "bottom up"); // scheduling_test(N_LENGTH_OF_TASK_POOL - 1, 1, request_pool3, "top up"); // scheduling_test_general(8, 1, request_pool3, "8 up full from v1", get_optimal_request_from_specified_on_search_direction); // scheduling_test_general(8, 1, request_pool3, "8 up full from v2", get_optimal_request_from_specified_on_search_direction_ver2); scheduling_test_general_dynamic(8, 1, request_pool3, "8 up full from v3", get_optimal_request_from_specified_on_search_direction_ver3); // scheduling_test_general(N_LENGTH_OF_TASK_POOL - 1, -1, request_pool3, "top down",get_optimal_request_from_specified_on_search_direction_ver3); // scheduling_test_general(0, 1, request_pool3, "bottom up", get_optimal_request_from_specified_on_search_direction_ver3); return 0; }
2.421875
2
2024-11-18T20:57:34.930050+00:00
2011-08-22T16:52:58
ccf7357ac9f6c772ab2250a8b1e6c3dadf3ed7db
{ "blob_id": "ccf7357ac9f6c772ab2250a8b1e6c3dadf3ed7db", "branch_name": "refs/heads/master", "committer_date": "2011-08-22T16:52:58", "content_id": "0541b52258a14533f75f372658aa28061823ab67", "detected_licenses": [ "ISC" ], "directory_id": "a1446c3f95df2dfe097a9bd6b463767b00f18140", "extension": "c", "filename": "acl.c", "fork_events_count": 4, "gha_created_at": "2011-05-05T14:08:03", "gha_event_created_at": "2017-04-06T19:17:29", "gha_language": "C", "gha_license_id": null, "github_id": 1706491, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10728, "license": "ISC", "license_type": "permissive", "path": "/usr.sbin/bind/lib/dns/acl.c", "provenance": "stackv2-0064.json.gz:68491", "repo_name": "chrissicool/l4openbsd", "revision_date": "2011-08-22T16:52:58", "revision_id": "077177814444e08500e47bc2488502f11469bc60", "snapshot_id": "e2fb756debc1c3bdc1c2da509fa228c25a3185e8", "src_encoding": "UTF-8", "star_events_count": 18, "url": "https://raw.githubusercontent.com/chrissicool/l4openbsd/077177814444e08500e47bc2488502f11469bc60/usr.sbin/bind/lib/dns/acl.c", "visit_date": "2021-04-09T17:12:53.122136" }
stackv2
/* * Copyright (C) 2004-2006 Internet Systems Consortium, Inc. ("ISC") * Copyright (C) 1999-2002 Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* $ISC: acl.c,v 1.25.18.5 2006/03/02 00:37:21 marka Exp $ */ /*! \file */ #include <config.h> #include <isc/mem.h> #include <isc/string.h> #include <isc/util.h> #include <dns/acl.h> isc_result_t dns_acl_create(isc_mem_t *mctx, int n, dns_acl_t **target) { isc_result_t result; dns_acl_t *acl; /* * Work around silly limitation of isc_mem_get(). */ if (n == 0) n = 1; acl = isc_mem_get(mctx, sizeof(*acl)); if (acl == NULL) return (ISC_R_NOMEMORY); acl->mctx = mctx; acl->name = NULL; result = isc_refcount_init(&acl->refcount, 1); if (result != ISC_R_SUCCESS) { isc_mem_put(mctx, acl, sizeof(*acl)); return (result); } acl->elements = NULL; acl->alloc = 0; acl->length = 0; ISC_LINK_INIT(acl, nextincache); /* * Must set magic early because we use dns_acl_detach() to clean up. */ acl->magic = DNS_ACL_MAGIC; acl->elements = isc_mem_get(mctx, n * sizeof(dns_aclelement_t)); if (acl->elements == NULL) { result = ISC_R_NOMEMORY; goto cleanup; } acl->alloc = n; memset(acl->elements, 0, n * sizeof(dns_aclelement_t)); *target = acl; return (ISC_R_SUCCESS); cleanup: dns_acl_detach(&acl); return (result); } isc_result_t dns_acl_appendelement(dns_acl_t *acl, const dns_aclelement_t *elt) { if (acl->length + 1 > acl->alloc) { /* * Resize the ACL. */ unsigned int newalloc; void *newmem; newalloc = acl->alloc * 2; if (newalloc < 4) newalloc = 4; newmem = isc_mem_get(acl->mctx, newalloc * sizeof(dns_aclelement_t)); if (newmem == NULL) return (ISC_R_NOMEMORY); memcpy(newmem, acl->elements, acl->length * sizeof(dns_aclelement_t)); isc_mem_put(acl->mctx, acl->elements, acl->alloc * sizeof(dns_aclelement_t)); acl->elements = newmem; acl->alloc = newalloc; } /* * Append the new element. */ acl->elements[acl->length++] = *elt; return (ISC_R_SUCCESS); } static isc_result_t dns_acl_anyornone(isc_mem_t *mctx, isc_boolean_t neg, dns_acl_t **target) { isc_result_t result; dns_acl_t *acl = NULL; result = dns_acl_create(mctx, 1, &acl); if (result != ISC_R_SUCCESS) return (result); acl->elements[0].negative = neg; acl->elements[0].type = dns_aclelementtype_any; acl->length = 1; *target = acl; return (result); } isc_result_t dns_acl_any(isc_mem_t *mctx, dns_acl_t **target) { return (dns_acl_anyornone(mctx, ISC_FALSE, target)); } isc_result_t dns_acl_none(isc_mem_t *mctx, dns_acl_t **target) { return (dns_acl_anyornone(mctx, ISC_TRUE, target)); } isc_result_t dns_acl_match(const isc_netaddr_t *reqaddr, const dns_name_t *reqsigner, const dns_acl_t *acl, const dns_aclenv_t *env, int *match, dns_aclelement_t const**matchelt) { unsigned int i; REQUIRE(reqaddr != NULL); REQUIRE(matchelt == NULL || *matchelt == NULL); for (i = 0; i < acl->length; i++) { dns_aclelement_t *e = &acl->elements[i]; if (dns_aclelement_match(reqaddr, reqsigner, e, env, matchelt)) { *match = e->negative ? -((int)i+1) : ((int)i+1); return (ISC_R_SUCCESS); } } /* No match. */ *match = 0; return (ISC_R_SUCCESS); } isc_result_t dns_acl_elementmatch(const dns_acl_t *acl, const dns_aclelement_t *elt, const dns_aclelement_t **matchelt) { unsigned int i; REQUIRE(elt != NULL); REQUIRE(matchelt == NULL || *matchelt == NULL); for (i = 0; i < acl->length; i++) { dns_aclelement_t *e = &acl->elements[i]; if (dns_aclelement_equal(e, elt) == ISC_TRUE) { if (matchelt != NULL) *matchelt = e; return (ISC_R_SUCCESS); } } return (ISC_R_NOTFOUND); } isc_boolean_t dns_aclelement_match(const isc_netaddr_t *reqaddr, const dns_name_t *reqsigner, const dns_aclelement_t *e, const dns_aclenv_t *env, const dns_aclelement_t **matchelt) { dns_acl_t *inner = NULL; const isc_netaddr_t *addr; isc_netaddr_t v4addr; int indirectmatch; isc_result_t result; switch (e->type) { case dns_aclelementtype_ipprefix: if (env == NULL || env->match_mapped == ISC_FALSE || reqaddr->family != AF_INET6 || !IN6_IS_ADDR_V4MAPPED(&reqaddr->type.in6)) addr = reqaddr; else { isc_netaddr_fromv4mapped(&v4addr, reqaddr); addr = &v4addr; } if (isc_netaddr_eqprefix(addr, &e->u.ip_prefix.address, e->u.ip_prefix.prefixlen)) goto matched; break; case dns_aclelementtype_keyname: if (reqsigner != NULL && dns_name_equal(reqsigner, &e->u.keyname)) goto matched; break; case dns_aclelementtype_nestedacl: inner = e->u.nestedacl; nested: result = dns_acl_match(reqaddr, reqsigner, inner, env, &indirectmatch, matchelt); INSIST(result == ISC_R_SUCCESS); /* * Treat negative matches in indirect ACLs as * "no match". * That way, a negated indirect ACL will never become * a surprise positive match through double negation. * XXXDCL this should be documented. */ if (indirectmatch > 0) goto matchelt_set; /* * A negative indirect match may have set *matchelt, * but we don't want it set when we return. */ if (matchelt != NULL) *matchelt = NULL; break; case dns_aclelementtype_any: matched: if (matchelt != NULL) *matchelt = e; matchelt_set: return (ISC_TRUE); case dns_aclelementtype_localhost: if (env != NULL && env->localhost != NULL) { inner = env->localhost; goto nested; } else { break; } case dns_aclelementtype_localnets: if (env != NULL && env->localnets != NULL) { inner = env->localnets; goto nested; } else { break; } default: INSIST(0); break; } return (ISC_FALSE); } void dns_acl_attach(dns_acl_t *source, dns_acl_t **target) { REQUIRE(DNS_ACL_VALID(source)); isc_refcount_increment(&source->refcount, NULL); *target = source; } static void destroy(dns_acl_t *dacl) { unsigned int i; for (i = 0; i < dacl->length; i++) { dns_aclelement_t *de = &dacl->elements[i]; switch (de->type) { case dns_aclelementtype_keyname: dns_name_free(&de->u.keyname, dacl->mctx); break; case dns_aclelementtype_nestedacl: dns_acl_detach(&de->u.nestedacl); break; default: break; } } if (dacl->elements != NULL) isc_mem_put(dacl->mctx, dacl->elements, dacl->alloc * sizeof(dns_aclelement_t)); if (dacl->name != NULL) isc_mem_free(dacl->mctx, dacl->name); isc_refcount_destroy(&dacl->refcount); dacl->magic = 0; isc_mem_put(dacl->mctx, dacl, sizeof(*dacl)); } void dns_acl_detach(dns_acl_t **aclp) { dns_acl_t *acl = *aclp; unsigned int refs; REQUIRE(DNS_ACL_VALID(acl)); isc_refcount_decrement(&acl->refcount, &refs); if (refs == 0) destroy(acl); *aclp = NULL; } isc_boolean_t dns_aclelement_equal(const dns_aclelement_t *ea, const dns_aclelement_t *eb) { if (ea->type != eb->type) return (ISC_FALSE); switch (ea->type) { case dns_aclelementtype_ipprefix: if (ea->u.ip_prefix.prefixlen != eb->u.ip_prefix.prefixlen) return (ISC_FALSE); return (isc_netaddr_eqprefix(&ea->u.ip_prefix.address, &eb->u.ip_prefix.address, ea->u.ip_prefix.prefixlen)); case dns_aclelementtype_keyname: return (dns_name_equal(&ea->u.keyname, &eb->u.keyname)); case dns_aclelementtype_nestedacl: return (dns_acl_equal(ea->u.nestedacl, eb->u.nestedacl)); case dns_aclelementtype_localhost: case dns_aclelementtype_localnets: case dns_aclelementtype_any: return (ISC_TRUE); default: INSIST(0); return (ISC_FALSE); } } isc_boolean_t dns_acl_equal(const dns_acl_t *a, const dns_acl_t *b) { unsigned int i; if (a == b) return (ISC_TRUE); if (a->length != b->length) return (ISC_FALSE); for (i = 0; i < a->length; i++) { if (! dns_aclelement_equal(&a->elements[i], &b->elements[i])) return (ISC_FALSE); } return (ISC_TRUE); } static isc_boolean_t is_loopback(const dns_aclipprefix_t *p) { switch (p->address.family) { case AF_INET: if (p->prefixlen == 32 && htonl(p->address.type.in.s_addr) == INADDR_LOOPBACK) return (ISC_TRUE); break; case AF_INET6: if (p->prefixlen == 128 && IN6_IS_ADDR_LOOPBACK(&p->address.type.in6)) return (ISC_TRUE); break; default: break; } return (ISC_FALSE); } isc_boolean_t dns_acl_isinsecure(const dns_acl_t *a) { unsigned int i; for (i = 0; i < a->length; i++) { dns_aclelement_t *e = &a->elements[i]; /* A negated match can never be insecure. */ if (e->negative) continue; switch (e->type) { case dns_aclelementtype_ipprefix: /* The loopback address is considered secure. */ if (! is_loopback(&e->u.ip_prefix)) return (ISC_TRUE); continue; case dns_aclelementtype_keyname: case dns_aclelementtype_localhost: continue; case dns_aclelementtype_nestedacl: if (dns_acl_isinsecure(e->u.nestedacl)) return (ISC_TRUE); continue; case dns_aclelementtype_localnets: case dns_aclelementtype_any: return (ISC_TRUE); default: INSIST(0); return (ISC_TRUE); } } /* No insecure elements were found. */ return (ISC_FALSE); } isc_result_t dns_aclenv_init(isc_mem_t *mctx, dns_aclenv_t *env) { isc_result_t result; env->localhost = NULL; env->localnets = NULL; result = dns_acl_create(mctx, 0, &env->localhost); if (result != ISC_R_SUCCESS) goto cleanup_nothing; result = dns_acl_create(mctx, 0, &env->localnets); if (result != ISC_R_SUCCESS) goto cleanup_localhost; env->match_mapped = ISC_FALSE; return (ISC_R_SUCCESS); cleanup_localhost: dns_acl_detach(&env->localhost); cleanup_nothing: return (result); } void dns_aclenv_copy(dns_aclenv_t *t, dns_aclenv_t *s) { dns_acl_detach(&t->localhost); dns_acl_attach(s->localhost, &t->localhost); dns_acl_detach(&t->localnets); dns_acl_attach(s->localnets, &t->localnets); t->match_mapped = s->match_mapped; } void dns_aclenv_destroy(dns_aclenv_t *env) { dns_acl_detach(&env->localhost); dns_acl_detach(&env->localnets); }
2.046875
2
2024-11-18T20:57:36.637851+00:00
2021-01-21T14:26:47
307d42a395b713b46be44c0d1f787961644740f4
{ "blob_id": "307d42a395b713b46be44c0d1f787961644740f4", "branch_name": "refs/heads/master", "committer_date": "2021-01-21T14:26:47", "content_id": "63f4b871b3fe286945bbedfe6f48141a2afb4114", "detected_licenses": [ "MIT" ], "directory_id": "3cca537e780ba900087b187d1494713f0c81a24d", "extension": "c", "filename": "coordinates.c", "fork_events_count": 33, "gha_created_at": "2014-12-11T16:43:33", "gha_event_created_at": "2023-07-12T10:53:00", "gha_language": "Python", "gha_license_id": null, "github_id": 27881137, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 224, "license": "MIT", "license_type": "permissive", "path": "/lenstools/extern/coordinates.c", "provenance": "stackv2-0064.json.gz:69005", "repo_name": "apetri/LensTools", "revision_date": "2021-01-21T14:26:47", "revision_id": "9151988bfe6fbd6809353a33cfb556d44b6806ed", "snapshot_id": "4119c1b5c0570fb6e4078fa67fb3acd5b443c0a5", "src_encoding": "UTF-8", "star_events_count": 32, "url": "https://raw.githubusercontent.com/apetri/LensTools/9151988bfe6fbd6809353a33cfb556d44b6806ed/lenstools/extern/coordinates.c", "visit_date": "2023-07-19T02:03:26.708366" }
stackv2
int min_int(int i,int j){ if(i<j){ return i; } else{ return j; } } int max_int(int i,int j){ if(i>j) return i; else return j; } long min_long(long i,long j){ if(i<j){ return i; } else{ return j; } }
2.15625
2
2024-11-18T20:57:36.845012+00:00
2021-06-01T14:00:16
ae2b0d32ad3ad5f2574eac7e2984d65d62f23a33
{ "blob_id": "ae2b0d32ad3ad5f2574eac7e2984d65d62f23a33", "branch_name": "refs/heads/master", "committer_date": "2021-06-01T14:00:16", "content_id": "2692e866d3d19c43a3b3fa68245e2bf7312ebc3e", "detected_licenses": [ "MIT" ], "directory_id": "f8d99958a090df19e3367e7e770befa763f5c73a", "extension": "c", "filename": "mm.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 179876671, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2872, "license": "MIT", "license_type": "permissive", "path": "/2018/hitconctf/abyss/exp_kernel/mm.c", "provenance": "stackv2-0064.json.gz:69133", "repo_name": "theKidOfArcrania/ctf-writeups", "revision_date": "2021-06-01T14:00:16", "revision_id": "dc03760ca8e8b9a246a4e4f27357ed427b1a51fe", "snapshot_id": "01a9ba662a8351c2e715249a10832ef0b103bec4", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/theKidOfArcrania/ctf-writeups/dc03760ca8e8b9a246a4e4f27357ed427b1a51fe/2018/hitconctf/abyss/exp_kernel/mm.c", "visit_date": "2021-06-08T23:01:02.019457" }
stackv2
#include "mm.h" #include "hypercall.h" #include "string.h" #include "utils.h" #include <linux/kvm.h> #define _OFFSET(v, bits) (((uint64_t)(v) >> (bits)) & 0x1ff) #define PML4OFF(v) _OFFSET(v, 39) #define PDPOFF(v) _OFFSET(v, 30) #define PDOFF(v) _OFFSET(v, 21) #define PTOFF(v) _OFFSET(v, 12) #define INVALID ((uint64_t)-1) #define VMFD 4 #define HADDR_START_ADDR (1<<25) static inline uint64_t* get_pml4_addr() { uint64_t pml4; asm("mov %[pml4], cr3" : [pml4]"=r"(pml4)); return (uint64_t*) (pml4 | KERNEL_BASE_OFFSET); } // Stub to call actual kernel void* kmalloc(uint64_t size, uint64_t padding) { return ((void* (*)(uint64_t, uint64_t))(0x15e0 | KERNEL_BASE_OFFSET))(size, padding); } // Stub to call actual kernel void kfree(void *mem) { ((void (*)(void*))(0x1577 | KERNEL_BASE_OFFSET))(mem); } uint32_t physical(void *vaddr_) { uint64_t vaddr = (uint64_t)vaddr_; if (!((uint64_t)vaddr & KERNEL_BASE_OFFSET)) hp_panic("mm.c#physical(): Not kernel memory address"); vaddr = vaddr ^ KERNEL_BASE_OFFSET; if (vaddr >> 32) hp_panic("mm.c#physical(): Hyper address cannot fit into 32-bit integer!"); return (uint32_t)vaddr; } /* if vaddr is already mapping to some address, overwrite it. */ void *create_mmap(void* vaddr_, void* paddr_) { uint64_t vaddr = (uint64_t) vaddr_; uint64_t paddr = (uint64_t) paddr_ & ~KERNEL_BASE_OFFSET; uint64_t* pml4 = get_pml4_addr(), *pdp, *pd, *pt; #define PAGING(p, c) do { \ if(!(*p & PDE64_PRESENT)) { \ c = (uint64_t*) kmalloc(PAGE_SIZE, PAGE_SIZE); \ *p = PDE64_PRESENT | PDE64_RW | PDE64_USER | physical(c); \ } else { \ c = (uint64_t*) ((*p & -0x1000) | KERNEL_BASE_OFFSET); \ } \ } while(0); PAGING(&pml4[PML4OFF(vaddr)], pdp); PAGING(&pdp[PDPOFF(vaddr)], pd); PAGING(&pd[PDOFF(vaddr)], pt); #undef PAGING pt[PTOFF(vaddr)] = PDE64_PRESENT | PDE64_USER | PDE64_RW | paddr; return vaddr_; } int next_slot = 1; uint64_t next_memoff = 0; void *create_hmmap(void* haddr_, uint64_t size) { void* vaddr_ = (void*)(EXT_MEM_OFFSET + next_memoff); uint64_t paddr = HADDR_START_ADDR + next_memoff; uint64_t haddr = (uint64_t)haddr_; struct kvm_userspace_memory_region *region = kmalloc(sizeof(*region), 0); region->slot = next_slot; region->flags = 0; region->guest_phys_addr = paddr; region->memory_size = size; region->userspace_addr = haddr; next_memoff += size; next_slot++; int res = hp_ioctl(VMFD, KVM_SET_USER_MEMORY_REGION, region); if (res < 0) { hp_exit(res); hp_panic("mm.c#create_hmmac: hp_ioctl failed"); } kfree(region); uint64_t pages = size / PAGE_SIZE; while (pages --> 0) create_mmap(vaddr_ + pages * PAGE_SIZE, (void*)(paddr + pages * PAGE_SIZE)); return vaddr_; } void *memdup(void *src, size_t size) { void *dst = kmalloc(size, 0); memcpy(dst, src, size); return dst; }
2.21875
2
2024-11-18T20:57:36.933973+00:00
2019-10-14T09:53:15
f70ebbc3890b795e2d25781b9bc1e4d296e2b873
{ "blob_id": "f70ebbc3890b795e2d25781b9bc1e4d296e2b873", "branch_name": "refs/heads/master", "committer_date": "2019-10-14T09:53:15", "content_id": "059ccad3285c771f246a34ebdeee2a5535a0c244", "detected_licenses": [ "MIT" ], "directory_id": "a70e2dac8f266f5f9c3cb7679043621cfeef5acf", "extension": "c", "filename": "imgwrite.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 207224909, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5653, "license": "MIT", "license_type": "permissive", "path": "/tools/efi_imgwrite/imgwrite.c", "provenance": "stackv2-0064.json.gz:69261", "repo_name": "phamsodiep/pc_firmware", "revision_date": "2019-10-14T09:53:15", "revision_id": "3412c0d7f575a257606580f39744bffe6ada3203", "snapshot_id": "4f4cc501394ca7a40462bd21bc1bdcf66a982ed6", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/phamsodiep/pc_firmware/3412c0d7f575a257606580f39744bffe6ada3203/tools/efi_imgwrite/imgwrite.c", "visit_date": "2020-07-22T13:54:32.491189" }
stackv2
#include <efi.h> #include <efilib.h> #include <efishellparm.h> #define PARAMETER_MAX_CHAR_COUNT (64) #define BUFFER_SIZE (4096 * 4) static const EFI_GUID simpleFileSystemGUID = SIMPLE_FILE_SYSTEM_PROTOCOL; static const EFI_GUID loadedImageGUID = LOADED_IMAGE_PROTOCOL; static const EFI_GUID blkGUID = EFI_BLOCK_IO_PROTOCOL_GUID; int processParams(EFI_HANDLE ImageHandle, CHAR16* srcImgFileName); EFI_FILE* openImageFile(EFI_HANDLE ImageHandle, CHAR16* srcImgFileName); EFI_BLOCK_IO* inputTargetDevice(); UINTN writeImage(EFI_FILE* imgFile, EFI_BLOCK_IO* targetDevice); EFI_STATUS EFIAPI efi_main( EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable ) { CHAR16 srcImgFileName[PARAMETER_MAX_CHAR_COUNT]; EFI_FILE* imgFile; EFI_BLOCK_IO* targetDevice; InitializeLib(ImageHandle, SystemTable); if (processParams(ImageHandle, srcImgFileName)) { Print(L"Source image file name: %s\n", srcImgFileName); imgFile = openImageFile(ImageHandle, srcImgFileName); if (imgFile) { Print(L"Open image file: ok\n"); targetDevice = inputTargetDevice(); if (targetDevice) { Print(L"Open target device: ok\n"); writeImage(imgFile, targetDevice); } } else { Print(L"Failure to open image file.\n"); } } Print(L"\n"); return EFI_SUCCESS; } int processParams( EFI_HANDLE ImageHandle, CHAR16* srcImgFileName ) { INTN argc; CHAR16** argv; argc = GetShellArgcArgv(ImageHandle, &argv); if (argc != 2) { Print(L"Usage: %s <image file name>\n", argv[0]); Print( L"No image file name is input. 'ROM.BIN' is applied instead.", argv[0] ); StrCpy(srcImgFileName, L"ROM.BIN"); return 1; } if (StrLen(argv[1]) >= PARAMETER_MAX_CHAR_COUNT) { return 0; } StrCpy(srcImgFileName, argv[1]); return 1; } EFI_FILE* openImageFile(EFI_HANDLE ImageHandle, CHAR16* srcImgFileName) { EFI_STATUS status = EFI_SUCCESS; EFI_HANDLE deviceHandle = 0; EFI_LOADED_IMAGE* loadedImg = NULL; EFI_FILE_IO_INTERFACE* fileIO = NULL; EFI_FILE* root = NULL; EFI_FILE* imgFile = NULL; if (!srcImgFileName) { return NULL; } // Retrieve deviceHandle status = uefi_call_wrapper( BS->HandleProtocol, 3, ImageHandle, &loadedImageGUID, &loadedImg ); if (status != EFI_SUCCESS) { return NULL; } deviceHandle = loadedImg->DeviceHandle; // Retrieve file io interface status = uefi_call_wrapper( BS->HandleProtocol, 3, deviceHandle, &simpleFileSystemGUID, &fileIO ); if (status != EFI_SUCCESS) { return NULL; } // Retrieve root folder status = uefi_call_wrapper( fileIO->OpenVolume, 2, fileIO, &root ); if (status != EFI_SUCCESS) { return NULL; } // Open image file status = uefi_call_wrapper( root->Open, 5, root, &imgFile, srcImgFileName, EFI_FILE_MODE_READ, 0); if (status != EFI_SUCCESS) { return NULL; } return imgFile; } EFI_BLOCK_IO* inputTargetDevice() { UINTN i = 0; EFI_STATUS status; UINTN handleCount = 0; EFI_HANDLE handle = 0; EFI_HANDLE* handles = NULL; EFI_BLOCK_IO* rawBlkIo = NULL; EFI_DEVICE_PATH *devPath = NULL; CHAR16 buffer[4]; // Retrieve all raw block io devices status = uefi_call_wrapper( BS->LocateHandleBuffer, 5, ByProtocol, &blkGUID, NULL, &handleCount, &handles ); if (status != EFI_SUCCESS) { goto Failure; } Print(L"List of block devices:\n", handleCount); for (i = 0; i < handleCount; i++) { handle = handles[i]; devPath = DevicePathFromHandle(handle); Print(L" %d. %s\n", (i + 1), DevicePathToStr(devPath)); } Print(L"Input target device (1..%d) or 0 to exit: ", handleCount); Input(NULL, buffer, 4); Print(L"\n"); i = xtoi(buffer); if (i == 0 || i > handleCount) { goto Failure; } handle = handles[i - 1]; status = uefi_call_wrapper( BS->HandleProtocol, 3, handle, &blkGUID, &rawBlkIo ); FreePool(handles); return rawBlkIo; Failure: if (handles) { FreePool(handles); } return NULL; } UINTN writeImage(EFI_FILE* imgFile, EFI_BLOCK_IO* targetDevice) { EFI_STATUS status; uint8_t buffer[BUFFER_SIZE]; UINTN i = 0; UINTN bufferSize; UINTN blockSize = targetDevice->Media->BlockSize; EFI_FILE_INFO* imgFileInfo = LibFileInfo(imgFile); UINT64 fileSize = imgFileInfo->FileSize; UINT64 step = fileSize / 50;//100; UINT64 boundary = step; UINT64 curPosition = 0; if (blockSize > BUFFER_SIZE) { return 0; } Print(L"Writing %d MiB...\n", (int)(fileSize / (1024 * 1024))); Print(L"[-------------------------------------------------]"); status = uefi_call_wrapper( ST->ConOut->SetCursorPosition, 3, ST->ConOut, 1, ST->ConOut->Mode->CursorRow ); if (status != EFI_SUCCESS) { return 0; } while(1){ bufferSize = blockSize; status = uefi_call_wrapper( imgFile->Read, 3, imgFile, &bufferSize, buffer ); if (!bufferSize) { break; } if (status != EFI_SUCCESS) { break; } status = uefi_call_wrapper( targetDevice->WriteBlocks, 3, targetDevice, targetDevice->Media->MediaId, i, blockSize, buffer ); curPosition += blockSize; if (curPosition >= boundary) { boundary += step; Print(L"#"); } i += 1; if (curPosition > fileSize) { break; } } Print(L"]\n"); uefi_call_wrapper(imgFile->Close, 1, imgFile); uefi_call_wrapper(targetDevice->FlushBlocks, 1, targetDevice); return 1; }
2.328125
2
2024-11-18T20:57:37.353866+00:00
2016-02-11T17:26:09
2ff0438b26d9828c5c594ba5f45d49e4f40335e2
{ "blob_id": "2ff0438b26d9828c5c594ba5f45d49e4f40335e2", "branch_name": "refs/heads/master", "committer_date": "2016-02-11T17:26:09", "content_id": "12d2cd5d152bfffca7d31484d0675a7f92255b7f", "detected_licenses": [ "MIT" ], "directory_id": "34edab51b4e6966c1b6666152926d505dfbd11a5", "extension": "c", "filename": "conv.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 51531688, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3908, "license": "MIT", "license_type": "permissive", "path": "/src/output/audio/conv.c", "provenance": "stackv2-0064.json.gz:69646", "repo_name": "xaradevil/tcvp", "revision_date": "2016-02-11T17:26:09", "revision_id": "9d17022cb6470d546e11c65aafa41b940c888d5f", "snapshot_id": "8e5ce807f077fa4c0add31126de68ce7640e40d8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xaradevil/tcvp/9d17022cb6470d546e11c65aafa41b940c888d5f/src/output/audio/conv.c", "visit_date": "2021-01-10T01:52:50.414533" }
stackv2
/** Copyright (C) 2003-2005 Michael Ahlberg, Måns Rullgård Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <tctypes.h> #include <unistd.h> #include <tcendian.h> #include <audio_tc2.h> #include <audiomod.h> #define snd_conv(sname, stype, dname, dtype, conv) \ static void \ sname##_##dname(void *dst, void *src, int samples, int channels) \ { \ stype *s = src; \ dtype *d = dst; \ int i; \ \ for(i = 0; i < samples * channels; i++) \ d[i] = conv(s[i]); \ } #define s2u8(x) (x + 128) #define s32s16(x) (x >> 16) snd_conv(le16, int16_t, be16, int16_t, bswap_16) snd_conv(s8, char, u8, u_char, s2u8) snd_conv(s32, int32_t, s16, int16_t, s32s16); #define copy(ss) \ static void \ copy_##ss(void *dst, void *src, int samples, int channels) \ { \ memcpy(dst, src, samples * channels * ss / 8); \ } copy(8) copy(16) copy(32) #define HE TCVP_ENDIAN static struct { char *in; char *out; sndconv_t conv; } conv_table[] = { { "s16le", "s16be", le16_be16 }, { "s16be", "s16le", le16_be16 }, { "u16le", "u16be", le16_be16 }, { "u16be", "u16le", le16_be16 }, { "s16le", "s16le", copy_16 }, { "s16be", "s16be", copy_16 }, { "u16le", "u16le", copy_16 }, { "u16be", "u16be", copy_16 }, { "u8", "u8", copy_8 }, { "s8", "s8", copy_8 }, { "s8", "u8", s8_u8 }, { "s32"HE, "s16"HE, s32_s16 }, { "f32le", "f32le", copy_32 }, { "f32be", "f32be", copy_32 }, { NULL, NULL, NULL } }; extern sndconv_t audio_conv(char *in, char *out) { int i; for(i = 0; conv_table[i].in; i++){ if(!strcmp(in, conv_table[i].in) && !strcmp(out, conv_table[i].out)){ return conv_table[i].conv; } } return NULL; } extern char ** audio_all_conv(char *in) { char **cv = calloc(sizeof(*cv), sizeof(conv_table) / sizeof(conv_table[0])); int i, j; cv[0] = in; for(i = 0, j = 1; conv_table[i].in; i++){ if(!strcmp(in, conv_table[i].in) && strcmp(conv_table[i].in, conv_table[i].out)) cv[j++] = conv_table[i].out; } return cv; }
2.15625
2
2024-11-18T20:57:37.446039+00:00
2012-12-14T00:32:54
0946e7b08b4a562c803590f3853da68f0bcc5dd3
{ "blob_id": "0946e7b08b4a562c803590f3853da68f0bcc5dd3", "branch_name": "refs/heads/master", "committer_date": "2012-12-14T00:32:54", "content_id": "669b78872b81a91bb968ee420755943006715755", "detected_licenses": [ "MIT" ], "directory_id": "09dbb5a4fb108719b66f86626aba7f4448e942f7", "extension": "c", "filename": "filebuffer.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": 2392, "license": "MIT", "license_type": "permissive", "path": "/src/file/filebuffer.c", "provenance": "stackv2-0064.json.gz:69774", "repo_name": "mogria/2do", "revision_date": "2012-12-14T00:32:54", "revision_id": "3181b77ca2eca94e521d6115ad16f49182ad6403", "snapshot_id": "10ecbb4cdab4b0ab5f086f3fa3be1d815a3aaf50", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mogria/2do/3181b77ca2eca94e521d6115ad16f49182ad6403/src/file/filebuffer.c", "visit_date": "2021-01-22T07:39:09.536762" }
stackv2
#include "filebuffer.h" #include "../array.h" #include <stddef.h> #include <stdio.h> #include <string.h> void write_file(filebuffer *buffer, FILE *file) { int x; char *line; for(x = 0; x < buffer->num_lines; x++) { line = c_string(buffer->lines[x]); fprintf(file, "%s\n", line); free(line); } } void read_file(filebuffer *buffer, FILE *file) { char c; char *line; size_t linesize = 1; // go back to the start of the file rewind(file); filebuffer_init(buffer); ALLOC1(char, line, 1); // iterate through the file until the end while((c = fgetc(file)) != EOF) { // create a new element to the buffer if a new line begins if(c == '\n') { line[linesize - 1] = '\0'; filebuffer_append(buffer, new_string(line)); linesize = 1; RALLOC1(char, line, linesize); } else { linesize++; RALLOC1(char, line, linesize); line[linesize - 2] = c; } } FREE1(line); } void filebuffer_init(filebuffer *buffer) { buffer->num_lines = 0; ALLOC1(mcstring *, buffer->lines, buffer->num_lines); } void filebuffer_append(filebuffer *buffer, mcstring *line) { RALLOC1(mcstring *, buffer->lines, ++buffer->num_lines); buffer->lines[buffer->num_lines - 1] = line; } void filebuffer_clear(filebuffer *buffer) { free_filebuffer(buffer); filebuffer_init(buffer); } unsigned char filebuffer_remove(filebuffer *buffer, int line_number) { // linenumber == 0 -> clear() // linenumber > 0 -> remove line with this number // linenumber < 0 -> same as above, but relative // to the end of the file unsigned char ret = 1; if(line_number == 0) { filebuffer_clear(buffer); } else { if(line_number < 0) { line_number = buffer->num_lines - line_number + 1; } line_number--; if((ret = (line_number >= 0 && line_number < buffer->num_lines))) { memmove(&buffer->lines[line_number], &buffer->lines[line_number + 1], sizeof(mcstring*) * (buffer->num_lines - 1 - line_number)); RALLOC1(mcstring *, buffer->lines, ++buffer->num_lines); } } return ret; } void free_filebuffer(filebuffer *buffer) { int x; for(x = 0; x < buffer->num_lines; x++) { free_string(buffer->lines[x]); } only_free_filebuffer(buffer); } void only_free_filebuffer(filebuffer *buffer) { FREE1(buffer->lines); buffer->num_lines = 0; }
3.109375
3
2024-11-18T20:57:37.516563+00:00
2020-05-18T08:40:13
5195ad4d2574f57de2e97d76bdd9b95802ca6231
{ "blob_id": "5195ad4d2574f57de2e97d76bdd9b95802ca6231", "branch_name": "refs/heads/master", "committer_date": "2020-05-18T08:40:13", "content_id": "11dc0d7ee36f3e0e0fb5f453496329706461d198", "detected_licenses": [ "MIT" ], "directory_id": "7787ef9628a6c46f756df61789379eeb158bbe6a", "extension": "c", "filename": "getopts.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 241601371, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4269, "license": "MIT", "license_type": "permissive", "path": "/examples/getopts.c", "provenance": "stackv2-0064.json.gz:69904", "repo_name": "drobin/nuts-getopts", "revision_date": "2020-05-18T08:40:13", "revision_id": "447c9a92c379feb548f1f0e29fd11b2fae76debd", "snapshot_id": "426d5f31fad3085bda626e1695d4484e1776b184", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/drobin/nuts-getopts/447c9a92c379feb548f1f0e29fd11b2fae76debd/examples/getopts.c", "visit_date": "2021-01-07T06:04:42.854978" }
stackv2
/****************************************************************************** * MIT License * * Copyright (c) 2020 Robin Doer * * 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. *****************************************************************************/ /** * @example getopts.c * * This is an example of how to use the _nuts-getopts_ library. */ #include <stdlib.h> #include <stdio.h> #include <nuts-getopts.h> static void handle_tool_event(const struct nuts_getopts_event* ev) { printf("tool: %s\n", ev->u.tool); } static void handle_option_event(const struct nuts_getopts_event* ev) { // The options which was selected. const struct nuts_getopts_option* option = ev->u.opt.option; if (option->arg == nuts_getopts_required_argument) { printf("option: %c/%s, arg: %s\n", option->sname, option->lname, ev->u.opt.value); } else { printf("option: %c/%s, no-arg\n", option->sname, option->lname); } } static void handle_argument_event(const struct nuts_getopts_event* ev) { printf("argument: %s\n", ev->u.arg); } static void handle_error_event(const struct nuts_getopts_event* ev) { switch (ev->u.err.type) { case nuts_getopts_invalid_option: fprintf(stderr, "error: invalid option %.*s\n", ev->u.err.option_len, ev->u.err.option); break; case nuts_getopts_missing_value: fprintf(stderr, "error: missing value for option %.*s\n", ev->u.err.option_len, ev->u.err.option); break; case nuts_getopts_needless_value: fprintf(stderr, "error: needless value for option %.*s\n", ev->u.err.option_len, ev->u.err.option); break; } } int main(int argc, char* argv[]) { // Defines three options: // // 1. The first option requires an argument and has a short name `-v` and a // long name `--verbose`. // 2. The second option has no argument and has only a long name `--quiet`. // 3. The third option requires an argument and has only a short name `-f`. const struct nuts_getopts_option options[] = { { 'v', "verbose", nuts_getopts_required_argument }, { 0, "quiet", nuts_getopts_no_argument }, { 'f', NULL, nuts_getopts_required_argument }, { 0 } }; // The state of the parser. // Must be initialized with zeros before the first invocation of // nuts_getopts(). Don't modify the variable afterwards, nuts_getopts() // stores its internal state in the variable. nuts_getopts_state state = { 0 }; // The event the parser emits. // nuts_getopts() stores the next event in this variable. The parser will // re-initialize its content with each invation of nuts_getopts(). struct nuts_getopts_event ev = { 0 }; // Call the parser in a loop. while (nuts_getopts(argc, argv, options, 0, &state, &ev) != -1) { // Depending on the event-type call a related handler. switch (ev.type) { case nuts_getopts_tool_event: handle_tool_event(&ev); break; case nuts_getopts_option_event: handle_option_event(&ev); break; case nuts_getopts_argument_event: handle_argument_event(&ev); break; case nuts_getopts_error_event: handle_error_event(&ev); return 1; } } return 0; }
2.546875
3
2024-11-18T20:57:37.753916+00:00
2019-12-31T09:38:56
baa14f515d45b7c5e04c02635061c931f1476ba8
{ "blob_id": "baa14f515d45b7c5e04c02635061c931f1476ba8", "branch_name": "refs/heads/master", "committer_date": "2019-12-31T09:38:56", "content_id": "fd7c5159f238a7f913cf95ae7c3f7fd9701054ea", "detected_licenses": [ "MIT" ], "directory_id": "adf0e69f92394a12eecb7a956363c5985af7fd4d", "extension": "h", "filename": "network.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 176869862, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1081, "license": "MIT", "license_type": "permissive", "path": "/src/common/network.h", "provenance": "stackv2-0064.json.gz:70161", "repo_name": "mizdra/minimum-ot-editor", "revision_date": "2019-12-31T09:38:56", "revision_id": "351fbf89e12f7cd6379beba81b332d18ec4b4b08", "snapshot_id": "f19347e81cbc5b151069033ed18168c380b039b3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mizdra/minimum-ot-editor/351fbf89e12f7cd6379beba81b332d18ec4b4b08/src/common/network.h", "visit_date": "2020-04-30T13:48:24.369917" }
stackv2
#pragma once #include <arpa/inet.h> #include <netdb.h> #include <stdlib.h> #include "common/util.h" struct sockaddr_in create_sockaddr_in(char *host, int port) { struct hostent *hp = gethostbyname(host); struct sockaddr_in sin; bzero(&sin, sizeof(sin)); sin.sin_family = PF_INET; sin.sin_addr = *(struct in_addr *)hp->h_addr_list[0]; sin.sin_port = htons(port); return sin; } int socket_connect(char *host, int port) { struct sockaddr_in sin = create_sockaddr_in(host, port); int sockfd = socket(PF_INET, SOCK_STREAM, 0); if (sockfd == -1) PANIC("fail to `socket`"); if (connect(sockfd, (struct sockaddr *)&sin, sizeof(sin)) == -1) PANIC("fail to `connect`"); return sockfd; } int socket_listen(char *host, int port) { struct sockaddr_in sin = create_sockaddr_in(host, port); int sockfd = socket(PF_INET, SOCK_STREAM, 0); if (sockfd == -1) PANIC("fail to `socket`"); if (bind(sockfd, (struct sockaddr *)&sin, sizeof(sin)) == -1) PANIC("fail to `bind`"); if (listen(sockfd, 5) == -1) PANIC("fail to `listen`"); return sockfd; }
2.53125
3
2024-11-18T20:57:37.877414+00:00
2017-07-25T23:57:00
63494d87034e4ce7df00419aa67f26398394700b
{ "blob_id": "63494d87034e4ce7df00419aa67f26398394700b", "branch_name": "refs/heads/master", "committer_date": "2017-07-25T23:57:00", "content_id": "18b87bc4714373dd9c87ffacd601c99be91ac127", "detected_licenses": [ "MIT" ], "directory_id": "ca9626a52becfd4e10cc19a2c8ff0510a8358672", "extension": "c", "filename": "draw.c", "fork_events_count": 1, "gha_created_at": "2017-10-28T18:34:13", "gha_event_created_at": "2017-10-28T18:34:13", "gha_language": null, "gha_license_id": null, "github_id": 108674219, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19662, "license": "MIT", "license_type": "permissive", "path": "/src/draw.c", "provenance": "stackv2-0064.json.gz:70290", "repo_name": "JamesLinus/rirc", "revision_date": "2017-07-25T23:57:00", "revision_id": "0da688aa55919e3c42dd370335507592efc84e6c", "snapshot_id": "76673cd682a10424dd8550ea51adc8aca29c31a5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/JamesLinus/rirc/0da688aa55919e3c42dd370335507592efc84e6c/src/draw.c", "visit_date": "2021-07-16T13:46:52.806595" }
stackv2
/* draw.c * * Draw the elements in state.c to the terminal. * * Assumes vt-100 compatible escape codes, as such YMMV */ #include <alloca.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../config.h" #include "input.h" #include "state.h" #include "utils.h" #define ESC "\x1b" #define RESET_ATTRIBUTES ESC"[0m" #define FG(X) ESC"[38;5;"#X"m" #define BG(X) ESC"[48;5;"#X"m" #define MOVE(X, Y) ESC"["#X";"#Y"H" #define CLEAR_FULL ESC"[2J" #define CLEAR_RIGHT ESC"[0K" #define CLEAR_LEFT ESC"[1K" #define CLEAR_LINE ESC"[2K" /* Save and restore the cursor's location */ #define CURSOR_SAVE ESC"[s" #define CURSOR_RESTORE ESC"[u" /* Minimum rows or columns to safely draw */ #define COLS_MIN 5 #define ROWS_MIN 5 /* Size of a full colour string for purposes of pre-formating text to print */ #define COLOUR_SIZE sizeof(RESET_ATTRIBUTES FG(255) BG(255)) #ifndef BUFFER_PADDING #define BUFFER_PADDING 1 #elif BUFFER_PADDING != 0 && BUFFER_PADDING != 1 #error "BUFFER_PADDING options are 0 (no pad), 1 (padded)" #endif static int actv_colours[ACTIVITY_T_SIZE] = ACTIVITY_COLOURS static int nick_colours[] = NICK_COLOURS /* Terminal coordinate row/column boundaries (inclusive) for objects being drawn * * \ c0 cN * +---------+ * r0| | * | | * | | * rN| | * +---------+ * * The origin for terminal coordinates is in the top left, indexed from 1 * * */ struct coords { unsigned int c1; unsigned int cN; unsigned int r1; unsigned int rN; }; static int _draw_fmt(char**, size_t*, size_t*, int, const char*, ...); static void _draw_buffer_line(struct buffer_line*, struct coords, unsigned int, unsigned int, unsigned int, unsigned int); static void _draw_buffer(struct buffer*, struct coords); static void _draw_input(struct input*, struct coords); static void _draw_nav(struct channel*); static void _draw_status(struct channel*); static inline unsigned int nick_col(char*); static inline void check_coords(struct coords); static char* _colour(int, int); void draw(union draw draw) { if (!draw.all_bits) return; struct channel *c = current_channel(); if (_term_cols() < COLS_MIN || _term_rows() < ROWS_MIN) { printf(CLEAR_FULL MOVE(1, 1) "rirc"); goto no_draw; } printf(CURSOR_SAVE); if (draw.bits.buffer) _draw_buffer(&c->buffer, (struct coords) { .c1 = 1, .cN = _term_cols(), .r1 = 3, .rN = _term_rows() - 2 }); if (draw.bits.nav) _draw_nav(c); if (draw.bits.input) _draw_input(c->input, (struct coords) { .c1 = 1, .cN = _term_cols(), .r1 = _term_rows(), .rN = _term_rows() }); if (draw.bits.status) _draw_status(c); printf(RESET_ATTRIBUTES); printf(CURSOR_RESTORE); no_draw: fflush(stdout); } void bell(void) { if (BELL_ON_PINGED) putchar('\a'); } /* FIXME: works except when it doesn't. * * Fails when line headers are very long compared to text. tests/draw.c needed */ static void _draw_buffer_line( struct buffer_line *line, struct coords coords, unsigned int head_w, unsigned int text_w, unsigned int skip, unsigned int pad) { check_coords(coords); char *print_p1, *print_p2, *p1 = line->text, *p2 = line->text + line->text_len; if (skip == 0) { /* Print the line header * * Since formatting codes don't occupy columns, enough space * should be allocated for all such sequences * */ char header[head_w + COLOUR_SIZE * 4 + 1]; char *header_ptr = header; size_t buff_n = sizeof(header) - 1, /* */ text_n = head_w - 1; struct tm *line_tm = localtime(&line->time); if (!_draw_fmt(&header_ptr, &buff_n, &text_n, 0, _colour(BUFFER_LINE_HEADER_FG_NEUTRAL, -1))) goto print_header; if (!_draw_fmt(&header_ptr, &buff_n, &text_n, 1, " %02d:%02d ", line_tm->tm_hour, line_tm->tm_min)) goto print_header; if (!_draw_fmt(&header_ptr, &buff_n, &text_n, 1, "%*s", pad, "")) goto print_header; if (!_draw_fmt(&header_ptr, &buff_n, &text_n, 0, RESET_ATTRIBUTES)) goto print_header; switch (line->type) { case BUFFER_LINE_OTHER: if (!_draw_fmt(&header_ptr, &buff_n, &text_n, 0, _colour(BUFFER_LINE_HEADER_FG_NEUTRAL, -1))) goto print_header; break; case BUFFER_LINE_CHAT: if (!_draw_fmt(&header_ptr, &buff_n, &text_n, 0, _colour(nick_col(line->from), -1))) goto print_header; break; case BUFFER_LINE_PINGED: if (!_draw_fmt(&header_ptr, &buff_n, &text_n, 0, _colour(BUFFER_LINE_HEADER_FG_PINGED, BUFFER_LINE_HEADER_BG_PINGED))) goto print_header; break; case BUFFER_LINE_T_SIZE: break; } if (!_draw_fmt(&header_ptr, &buff_n, &text_n, 1, "%s", line->from)) goto print_header; print_header: /* Print the line header */ printf(MOVE(%d, 1) "%s " RESET_ATTRIBUTES, coords.r1, header); } while (skip--) word_wrap(text_w, &p1, p2); do { char *sep = " "VERTICAL_SEPARATOR" "; if ((coords.cN - coords.c1) >= sizeof(*sep) + text_w) { printf(MOVE(%d, %d), coords.r1, (int)(coords.cN - (sizeof(*sep) + text_w + 1))); fputs(_colour(BUFFER_LINE_HEADER_FG_NEUTRAL, -1), stdout); fputs(sep, stdout); } if (*p1) { printf(MOVE(%d, %d), coords.r1, head_w); print_p1 = p1; print_p2 = word_wrap(text_w, &p1, p2); fputs(_colour(line->text[0] == QUOTE_CHAR ? BUFFER_LINE_TEXT_FG_GREEN : BUFFER_LINE_TEXT_FG_NEUTRAL, -1), stdout); printf("%.*s", (int)(print_p2 - print_p1), print_p1); } coords.r1++; } while (*p1 && coords.r1 <= coords.rN); } static void _draw_buffer(struct buffer *b, struct coords coords) { /* Dynamically draw the current channel's buffer such that: * * - The scrollback line should always be drawn in full when possible * - Lines wrap on whitespace when possible * - The top-most lines draws partially when required * - Buffers requiring fewer rows than available draw from the top down * * Rows are numbered from the top down, 1 to term_rows, so for term_rows = N, * the drawable area for the buffer is bounded [r3, rN-2]: * __________________________ * r1 | (nav) | * r2 |------------------------| * r3 | ::buffer start:: | * | | * ... | | * | | * rN-2 | ::buffer end:: | * rN-1 |------------------------| * rN |________(input)_________| * * * So the general steps for drawing are: * * 1. Starting from line L = scrollback, traverse backwards through the * buffer summing the rows required to draw lines, until the sum * exceeds the number of rows available * * 2. L now points to the top-most line to be drawn. L might not be able * to draw in full, so discard the excessive word-wrapped segments and * draw the remainder * * 3. Traverse forward through the buffer, drawing lines until buffer.head * is encountered */ check_coords(coords); unsigned int row, row_count = 0, row_total = coords.rN - coords.r1 + 1; unsigned int col_total = coords.cN - coords.c1 + 1; unsigned int buffer_i = b->scrollback, head_w, text_w; /* Clear the buffer area */ for (row = coords.r1; row <= coords.rN; row++) printf(MOVE(%d, 1) CLEAR_LINE, row); struct buffer_line *line = buffer_line(b, buffer_i); if (line == NULL) return; struct buffer_line *tail = buffer_tail(b); struct buffer_line *head = buffer_head(b); /* Find top line */ for (;;) { split_buffer_cols(line, NULL, &text_w, col_total, b->pad); row_count += buffer_line_rows(line, text_w); if (line == tail) break; if (row_count >= row_total) break; line = buffer_line(b, --buffer_i); } /* Handle impartial top line print */ if (row_count > row_total) { split_buffer_cols(line, &head_w, &text_w, col_total, b->pad); _draw_buffer_line( line, coords, head_w, text_w, row_count - row_total, BUFFER_PADDING ? (b->pad - line->from_len) : 0 ); coords.r1 += buffer_line_rows(line, text_w) - (row_count - row_total); if (line == head) return; line = buffer_line(b, ++buffer_i); } /* Draw all remaining lines */ while (coords.r1 <= coords.rN) { split_buffer_cols(line, &head_w, &text_w, col_total, b->pad); _draw_buffer_line( line, coords, head_w, text_w, 0, BUFFER_PADDING ? (b->pad - line->from_len) : 0 ); coords.r1 += buffer_line_rows(line, text_w); if (line == head) return; line = buffer_line(b, ++buffer_i); } } /* TODO * * | [server-name[:port]] *#chan | * * - Disconnected/parted channels are printed (#chan) * - Servers with non-standard ports are printed: server-name:port * - Channels that won't fit are printed at a minimum: #... * - eg: | ...chan #chan2 chan3 | Right printing * | #chan1 #chan2 #ch... | Left printing * */ static void _draw_nav(struct channel *c) { /* Dynamically draw the nav such that: * * - The current channel is kept framed while navigating * - Channels are coloured based on their current activity * - The nav is kept framed between the first and last channels */ printf(MOVE(1, 1) CLEAR_LINE); static struct channel *frame_prev, *frame_next; struct channel *c_first = channel_get_first(), *c_last = channel_get_last(), *tmp; c->activity = ACTIVITY_DEFAULT; /* By default assume drawing starts towards the next channel */ int colour, nextward = 1; size_t len, total_len = 0; /* Bump the channel frames, if applicable */ if ((total_len = (strlen(c->name) + 2)) >= _term_cols()) return; else if (c == frame_prev && frame_prev != c_first) frame_prev = channel_get_prev(frame_prev); else if (c == frame_next && frame_next != c_last) frame_next = channel_get_next(frame_next); /* Calculate the new frames */ struct channel *tmp_prev = c, *tmp_next = c; for (;;) { if (tmp_prev == c_first || tmp_prev == frame_prev) { /* Pad out nextward */ tmp = channel_get_next(tmp_next); len = strlen(tmp->name); while ((total_len += (len + 2)) < _term_cols() && tmp != c_first) { tmp_next = tmp; tmp = channel_get_next(tmp); len = strlen(tmp->name); } break; } if (tmp_next == c_last || tmp_next == frame_next) { /* Pad out prevward */ tmp = channel_get_prev(tmp_prev); len = strlen(tmp->name); while ((total_len += (len + 2)) < _term_cols() && tmp != c_last) { tmp_prev = tmp; tmp = channel_get_prev(tmp); len = strlen(tmp->name); } break; } tmp = nextward ? channel_get_next(tmp_next) : channel_get_prev(tmp_prev); len = strlen(tmp->name); /* Next channel doesn't fit */ if ((total_len += (len + 2)) >= _term_cols()) break; if (nextward) tmp_next = tmp; else tmp_prev = tmp; nextward = !nextward; } frame_prev = tmp_prev; frame_next = tmp_next; /* Draw coloured channel names, from frame to frame */ for (tmp = frame_prev; ; tmp = channel_get_next(tmp)) { colour = (tmp == c) ? NAV_CURRENT_CHAN : actv_colours[tmp->activity]; if (fputs(_colour(colour, -1), stdout) < 0) break; if (printf(" %s ", tmp->name) < 0) break; if (tmp == frame_next) break; } } static void _draw_input(struct input *in, struct coords coords) { /* Draw the input line, or the current action message */ check_coords(coords); unsigned int cols_t = coords.cN - coords.c1 + 1, cursor = coords.c1; printf(RESET_ATTRIBUTES); printf(MOVE(%d, 1) CLEAR_LINE, coords.rN); printf(CURSOR_SAVE); /* Insufficient columns for meaningful input drawing */ if (cols_t < 3) return; char input[cols_t + COLOUR_SIZE * 2 + 1]; char *input_ptr = input; size_t buff_n = sizeof(input) - 1, text_n = cols_t; if (sizeof(INPUT_PREFIX)) { if (!_draw_fmt(&input_ptr, &buff_n, &text_n, 0, "%s", _colour(INPUT_PREFIX_FG, INPUT_PREFIX_BG))) goto print_input; cursor = coords.c1 + sizeof(INPUT_PREFIX) - 1; if (!_draw_fmt(&input_ptr, &buff_n, &text_n, 1, INPUT_PREFIX)) goto print_input; } if (!_draw_fmt(&input_ptr, &buff_n, &text_n, 0, "%s", _colour(INPUT_FG, INPUT_BG))) goto print_input; if (action_message) { cursor = coords.cN; if (!_draw_fmt(&input_ptr, &buff_n, &text_n, 1, "%s", action_message)) goto print_input; cursor = cols_t - text_n + 1; } else { /* Keep the input head in view, reframing if the cursor would be * drawn outside [A, B] as a function of input window and head * * | <prefix> <text area> | * |............|---------------| * | A B| * | | : cols_t * | | : text_n * * The cursor should track the input head, where the next * character would be entered * * In the <= A case: deletions occurred; the head is less than * or equal to the window * * In the >= B case: insertions occurred; the distance from window * to head is greater than the distance from [A, B] * * Set the window 2/3 of the text area width backwards from the head */ size_t frame = text_n * 2 / 3; char *w1, *w2, *ptr; if (in->window >= in->head || (in->window + text_n) <= in->head) { w1 = in->line->text, w2 = in->line->text + frame; in->window = (w2 >= in->head) ? w1 : in->head - frame; } cursor = (cols_t - text_n) + (in->head - in->window + 1); for (ptr = in->window; text_n; text_n--) { /* Copy characters, x, from the gap buffer, i.e.: * * window head tail * v v v * |.....xxxxxxx|------|xxxxxxx| */ if (ptr == in->head) ptr = in->tail; if (ptr == in->line->text + MAX_INPUT) break; *input_ptr++ = *ptr++; } *input_ptr = '\0'; } print_input: fputs(input, stdout); printf(MOVE(%d, %d), coords.rN, (cursor >= coords.c1 && cursor <= coords.cN) ? cursor : coords.cN); printf(CURSOR_SAVE); } static void _draw_status(struct channel *c) { /* server / private chat: * |-[usermodes]-(latency)---...| * * channel: * |-[usermodes]-[chancount chantype chanmodes]/[priv]-(latency)---...| * */ float sb; int ret; unsigned int col = 0; unsigned int cols = _term_cols(); unsigned int rows = _term_rows(); /* Insufficient columns for meaningful status */ if (cols < 3) return; printf(RESET_ATTRIBUTES); printf(MOVE(2, 1)); printf("%.*s", cols, (char *)(memset(alloca(cols), *HORIZONTAL_SEPARATOR, cols))); printf(MOVE(%d, 1) CLEAR_LINE, rows - 1); /* Print status to temporary buffer */ char status_buff[cols + 1]; memset(status_buff, 0, cols + 1); /* -[usermodes] */ if (c->server && *c->server->usermodes) { ret = snprintf(status_buff + col, cols - col + 1, "%s", HORIZONTAL_SEPARATOR "[+"); if (ret < 0 || (col += ret) >= cols) goto print_status; ret = snprintf(status_buff + col, cols - col + 1, "%s", c->server->usermodes); if (ret < 0 || (col += ret) >= cols) goto print_status; ret = snprintf(status_buff + col, cols - col + 1, "%s", "]"); if (ret < 0 || (col += ret) >= cols) goto print_status; } /* If private chat buffer: * -[priv] */ if (c->buffer.type == BUFFER_PRIVATE) { ret = snprintf(status_buff + col, cols - col + 1, "%s", HORIZONTAL_SEPARATOR "[priv]"); if (ret < 0 || (col += ret) >= cols) goto print_status; } /* If IRC channel buffer: * -[chancount chantype chanmodes] */ if (c->buffer.type == BUFFER_CHANNEL) { ret = snprintf(status_buff + col, cols - col + 1, HORIZONTAL_SEPARATOR "[%d", c->nicklist.count); if (ret < 0 || (col += ret) >= cols) goto print_status; if (c->type_flag) { ret = snprintf(status_buff + col, cols - col + 1, " %c", c->type_flag); if (ret < 0 || (col += ret) >= cols) goto print_status; } if (*c->chanmodes) { ret = snprintf(status_buff + col, cols - col + 1, " +%s", c->chanmodes); if (ret < 0 || (col += ret) >= cols) goto print_status; } ret = snprintf(status_buff + col, cols - col + 1, "%s", "]"); if (ret < 0 || (col += ret) >= cols) goto print_status; } /* -(latency) */ if (c->server && c->server->latency_delta) { ret = snprintf(status_buff + col, cols - col + 1, HORIZONTAL_SEPARATOR "(%llds)", (long long) c->server->latency_delta); if (ret < 0 || (col += ret) >= cols) goto print_status; } /* -(scrollback%) */ if ((sb = buffer_scrollback_status(&c->buffer))) { ret = snprintf(status_buff + col, cols - col + 1, HORIZONTAL_SEPARATOR "(%02d%%)", (int)(sb * 100)); if (ret < 0 || (col += ret) >= cols) goto print_status; } print_status: fputs(status_buff, stdout); /* Trailing separator */ while (col++ < cols) printf(HORIZONTAL_SEPARATOR); } static inline void check_coords(struct coords coords) { /* Check coordinate validity before drawing, ensure at least one row, column */ if (coords.r1 > coords.rN) fatal("row coordinates invalid", 0); if (coords.c1 > coords.cN) fatal("column coordinates invalid", 0); } static inline unsigned int nick_col(char *nick) { unsigned int colour = 0; while (*nick) colour += *nick++; return nick_colours[colour % sizeof(nick_colours) / sizeof(nick_colours[0])]; } static char* _colour(int fg, int bg) { /* Set terminal foreground and background colours to a value [0, 255], * or reset colour if given anything else * * Foreground(F): ESC"[38;5;Fm" * Background(B): ESC"[48;5;Bm" * */ static char col_buff[COLOUR_SIZE + 1] = RESET_ATTRIBUTES; int ret = 0; char *col_buff_ptr = col_buff + sizeof(RESET_ATTRIBUTES) - 1; /* Assume any colour sequence begins by resetting all attributes */ *(col_buff_ptr = col_buff + sizeof(RESET_ATTRIBUTES) - 1) = '\0'; /* Set valid foreground colour */ if (fg >= 0 && fg <= 255 && ((ret = sprintf(col_buff_ptr, ESC"[38;5;%dm", fg)) < 0)) return strcpy(col_buff, RESET_ATTRIBUTES); col_buff_ptr += ret; /* Set valid background colour */ if (bg >= 0 && bg <= 255 && ((ret = sprintf(col_buff_ptr, ESC"[48;5;%dm", bg)) < 0)) return strcpy(col_buff, RESET_ATTRIBUTES); return col_buff; } static int _draw_fmt(char **ptr, size_t *buff_n, size_t *text_n, int txt, const char *fmt, ...) { /* Write formatted text to a buffer for purposes of preparing an object to be drawn * to the terminal. * * Calls to this function should distinguish between formatting and printed text * with the txt flag. * * - ptr : pointer to location in buffer being printed to * - buff_n : remaining bytes available in buff * - text_n : remaining columns available for text * - txt : flag set true if bytes being written are printable text * * returns 0 on error, or if no more prints to this buffer can occur */ int ret; va_list ap; va_start(ap, fmt); ret = vsnprintf(*ptr, *buff_n, fmt, ap); va_end(ap); if (ret < 0) return (**ptr = 0); size_t _ret = (size_t) ret; if (!txt && _ret >= *buff_n) return (**ptr = 0); if (txt) { if (*text_n > _ret) *text_n -= _ret; else { *ptr += *text_n; **ptr = 0; return (*text_n = 0); } } *ptr += _ret; return 1; } void split_buffer_cols( struct buffer_line *line, unsigned int *head_w, unsigned int *text_w, unsigned int cols, unsigned int pad) { unsigned int _head_w = sizeof(" HH:MM "VERTICAL_SEPARATOR" "); if (BUFFER_PADDING) _head_w += pad; else _head_w += line->from_len; /* If header won't fit, split in half */ if (_head_w >= cols) _head_w = cols / 2; //TODO: why? _head_w -= 1; if (head_w) *head_w = _head_w; if (text_w) *text_w = cols - _head_w + 1; }
2.59375
3
2024-11-18T20:57:37.946105+00:00
2022-03-20T17:53:25
abf0e7bb643a3d459bebd0ef2c94a403413f879e
{ "blob_id": "abf0e7bb643a3d459bebd0ef2c94a403413f879e", "branch_name": "refs/heads/master", "committer_date": "2022-03-20T17:53:25", "content_id": "e6ba557db7ee08efe3b999ab1374c3f1a2b154d7", "detected_licenses": [ "MIT" ], "directory_id": "15fbb35cb68bd707f6a1eee9485e2ee37fc52876", "extension": "c", "filename": "vl6180x_chibios.c", "fork_events_count": 23, "gha_created_at": "2016-09-19T19:00:32", "gha_event_created_at": "2023-07-06T21:24:19", "gha_language": "C", "gha_license_id": "MIT", "github_id": 68636610, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 550, "license": "MIT", "license_type": "permissive", "path": "/sensor-firmware/src/vl6180x/vl6180x_chibios.c", "provenance": "stackv2-0064.json.gz:70420", "repo_name": "cvra/robot-software", "revision_date": "2022-03-20T17:53:25", "revision_id": "dcbfa7a99c452145e53142c182ae909079a63962", "snapshot_id": "f922ec80a5d24f6d7904c1586a9d5f5aa7c1b4bf", "src_encoding": "UTF-8", "star_events_count": 42, "url": "https://raw.githubusercontent.com/cvra/robot-software/dcbfa7a99c452145e53142c182ae909079a63962/sensor-firmware/src/vl6180x/vl6180x_chibios.c", "visit_date": "2023-07-20T09:58:30.975456" }
stackv2
#include <ch.h> #include <hal.h> #include "vl6180x.h" #ifdef HAL_USE_I2C void vl6180x_write_register(vl6180x_t* dev, uint16_t reg, uint8_t val) { uint8_t buf[] = {(reg >> 8), reg & 0xff, val}; i2cMasterTransmit(dev->i2c, dev->address, buf, 3, NULL, 0); } uint8_t vl6180x_read_register(vl6180x_t* dev, uint16_t reg) { uint8_t ret; uint8_t buf[] = {(reg >> 8), reg & 0xff}; i2cMasterTransmit(dev->i2c, dev->address, buf, 2, &ret, 1); return ret; } #else #error "VL6180X driver requires I2C. Please enable HAL_USE_I2C." #endif
2.328125
2
2024-11-18T20:57:38.463350+00:00
2018-10-30T05:48:31
386b64a206db3986e332d9ce50c18ce045177537
{ "blob_id": "386b64a206db3986e332d9ce50c18ce045177537", "branch_name": "refs/heads/master", "committer_date": "2018-10-30T05:48:31", "content_id": "2e1da200847f55ecca5b30de3b3da46a0a1f16fb", "detected_licenses": [ "MIT" ], "directory_id": "d7c47cc2dd4f94c45549a26e7367c0e86848039f", "extension": "c", "filename": "keyvals_btree.c", "fork_events_count": 2, "gha_created_at": "2018-04-02T01:54:48", "gha_event_created_at": "2018-10-30T05:48:32", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 127689005, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7152, "license": "MIT", "license_type": "permissive", "path": "/metis/lib/keyvals_btree.c", "provenance": "stackv2-0064.json.gz:70805", "repo_name": "twd2/sv6", "revision_date": "2018-10-30T05:48:31", "revision_id": "29ce0f0a05d76a993a74072b5dd73c173b4af091", "snapshot_id": "78cac936da368c86739a1281343c5ff2487eda80", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/twd2/sv6/29ce0f0a05d76a993a74072b5dd73c173b4af091/metis/lib/keyvals_btree.c", "visit_date": "2020-03-07T20:06:47.872586" }
stackv2
#include "pchandler.h" #include "value_helper.h" #include "bsearch.h" // #include "values.h" #include <string.h> #include <stdlib.h> #include <assert.h> #ifdef JOS_USER // #include <inc/compiler.h> #endif enum { type_leaf = 0, type_internal }; static key_cmp_t JSHARED_ATTR keycmp = NULL; static void pch_set_util(key_cmp_t kcmp) { keycmp = kcmp; } static void pch_init(void *coll) { assert(coll); memset(coll, 0, sizeof(btree_t)); } static btnode_t * create_node(int type) { return calloc(1, sizeof(btnode_t)); } static btnode_t * btree_split_internal(btnode_t * node) { btnode_t *newsib = create_node(type_internal); newsib->nkeys = order; memcpy(newsib->arr, &node->arr[order + 1], sizeof(keyvals_t) * (order + 1)); node->nkeys = order; return newsib; } static int keyvals_cmp(const void *k1, const void *k2) { keyvals_t *p1 = (keyvals_t *) k1; keyvals_t *p2 = (keyvals_t *) k2; return keycmp(p1->key, p2->key); } // left < key <= right. Right is the new sibling static void btree_insert_index(btree_t * bt, void *key, btnode_t * left, btnode_t * right) { if (!left->parent) { btnode_t *newroot = create_node(type_internal); newroot->nkeys = 1; keyvals_t *kv = (keyvals_t *) newroot->arr; kv[0].key = key; kv[0].vals = (void **) left; kv[1].vals = (void **) right; bt->root = newroot; left->parent = newroot; right->parent = newroot; bt->nlevel++; } else { btnode_t *parent = (btnode_t *) left->parent; keyvals_t tmp; tmp.key = key; int ikey = bsearch_lar(&tmp, parent->arr, parent->nkeys, sizeof(keyvals_t), keyvals_cmp); // insert newkey at ikey, values at ikey + 1 keyvals_t *kv = (keyvals_t *) parent->arr; for (int i = parent->nkeys - 1; i >= ikey; i--) kv[i + 1].key = kv[i].key; for (int i = parent->nkeys; i >= ikey + 1; i--) kv[i + 1].vals = kv[i].vals; kv[ikey].key = key; kv[ikey + 1].vals = (void **) right; parent->nkeys++; right->parent = parent; if (parent->nkeys == 2 * order + 1) { void *newkey = kv[order].key; btnode_t *newparent = btree_split_internal(parent); // push up newkey btree_insert_index(bt, newkey, parent, newparent); // fix parent pointers for (int i = 0; i < newparent->nkeys + 1; i++) ((btnode_t *) (newparent->arr[i].vals))->parent = newparent; } } } static btnode_t * get_leaf(btree_t * bt, void *key) { if (!bt->nlevel) { btnode_t *node = create_node(type_leaf); bt->root = node; bt->nlevel = 1; bt->nkeys = 0; return node; } int ipt; btnode_t *node = bt->root; keyvals_t tmp; tmp.key = key; for (int i = 0; i < bt->nlevel - 1; i++) { ipt = bsearch_lar(&tmp, node->arr, node->nkeys, sizeof(keyvals_t), keyvals_cmp); node = (btnode_t *) node->arr[ipt].vals; } return node; } static void insert_key(btree_t * bt, btnode_t * leaf, void *key, int pos, int keylen) { keyvals_t *kvs = (keyvals_t *) leaf->arr; if (pos < leaf->nkeys) memmove(&kvs[pos + 1], &kvs[pos], sizeof(keyvals_t) * (leaf->nkeys - pos)); leaf->nkeys++; bt->nkeys++; if (keylen && mrkeycopy) kvs[pos].key = mrkeycopy(key, keylen); else kvs[pos].key = key; kvs[pos].alloc_len = 0; kvs[pos].len = 0; } static void split_leaf(btree_t * bt, btnode_t * leaf) { keyvals_t *kvs = (keyvals_t *) leaf->arr; btnode_t *right = create_node(type_leaf); memcpy(right->arr, &kvs[order + 1], sizeof(keyvals_t) * (1 + order)); right->nkeys = order + 1; leaf->nkeys = order + 1; btree_insert_index(bt, right->arr[0].key, leaf, right); void *next = leaf->next; leaf->next = right; right->next = next; } // left < splitkey <= right. Right is the new sibling static int pch_insert_kv(void *coll, void *key, void *val, size_t keylen, unsigned hash) { assert(coll); btree_t *btree = (btree_t *) coll; btnode_t *leaf = get_leaf(btree, key); int bfound = 0; keyvals_t tmp; tmp.key = key; int pos = bsearch_eq(&tmp, leaf->arr, leaf->nkeys, sizeof(keyvals_t), keyvals_cmp, &bfound); if (!bfound) { insert_key(btree, leaf, key, pos, keylen); leaf->arr[pos].hash = hash; } values_insert(&leaf->arr[pos], val); if (leaf->nkeys == order * 2 + 2) split_leaf(btree, leaf); return !bfound; } static void pch_insert_kvs(void *coll, const keyvals_t * k) { btree_t *btree = (btree_t *) coll; btnode_t *leaf = get_leaf(btree, k->key); int bfound = 0; int pos = bsearch_eq(k, leaf->arr, leaf->nkeys, sizeof(keyvals_t), keyvals_cmp, &bfound); assert(!bfound); // do not copy key insert_key(btree, leaf, k->key, pos, 0); leaf->arr[pos] = *k; if (leaf->nkeys == order * 2 + 2) split_leaf(btree, leaf); } static uint64_t pch_get_len(void *coll) { assert(coll); return ((btree_t *) coll)->nkeys; } static void btree_delete_level(btnode_t * node, int level) { if (level != 1) { for (int i = 0; i < node->nkeys; i++) { btree_delete_level((btnode_t *) (node->arr[i].vals), level - 1); node->arr[i].vals = NULL; } } free(node); } static void pch_shallow_free(void *coll) { assert(coll); btree_t *btree = (btree_t *) coll; if (btree->nlevel) { btree_delete_level(btree->root, btree->nlevel); btree->nlevel = 0; } } typedef struct { int next; btnode_t *node; } iter_t; static int pch_iter_begin(void *coll, void **iter_) { assert(coll); btree_t *btree = (btree_t *) coll; if (!btree->nlevel) { *iter_ = 0; return 1; } btnode_t *node = btree->root; for (int i = 0; i < btree->nlevel - 1; i++) node = (btnode_t *) (node->arr[0].vals); iter_t *iter = (iter_t *) malloc(sizeof(iter_t)); iter->next = 0; iter->node = node; *iter_ = iter; return 0; } static int pch_iter_next_kvs(void *coll, keyvals_t * kvs, void *iter_, int bclear) { iter_t *iter = (iter_t *) iter_; if (iter->next == iter->node->nkeys) { if (!iter->node->next) return 1; iter->node = iter->node->next; iter->next = 0; } keyvals_t *src = &((keyvals_t *) iter->node->arr)[iter->next]; *kvs = *src; if (bclear) memset(src, 0, sizeof(keyvals_t)); iter->next++; return 0; } static void pch_iter_end(void *iter) { if (iter) free(iter); } static uint64_t pch_copy_kvs(void *coll, keyvals_t * dst) { btree_t *btree = (btree_t *) coll; if (!btree->nlevel) return 0; btnode_t *node = btree->root; for (int i = 0; i < btree->nlevel - 1; i++) node = (btnode_t *) (node->arr[0].vals); uint64_t len = 0; while (node) { memcpy(&dst[len], node->arr, sizeof(keyvals_t) * node->nkeys); len += node->nkeys; node = (btnode_t *) node->next; } assert(len == btree->nkeys); return len; } const pc_handler_t hkvsbtree = { .pch_init = pch_init, .pch_set_util = pch_set_util, .pch_insert_kv = pch_insert_kv, .pch_insert_kvs = pch_insert_kvs, .pch_shallow_free = pch_shallow_free, .pch_get_len = pch_get_len, .pch_iter_begin = pch_iter_begin, .pch_iter_next_kvs = pch_iter_next_kvs, .pch_iter_end = pch_iter_end, .pch_copy_kvs = pch_copy_kvs, };
2.390625
2
2024-11-18T20:57:38.530167+00:00
2023-03-25T18:48:23
212365030a8049088d1f23d79fdad403ca23abf0
{ "blob_id": "212365030a8049088d1f23d79fdad403ca23abf0", "branch_name": "refs/heads/master", "committer_date": "2023-03-25T18:48:23", "content_id": "559ff54e310968a5181ae58239250ae8fccc54cb", "detected_licenses": [ "MIT" ], "directory_id": "a7da48e8ea1eba569076e4eb20affd2a80630f8c", "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": 78802203, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5021, "license": "MIT", "license_type": "permissive", "path": "/ygrep/main.c", "provenance": "stackv2-0064.json.gz:70933", "repo_name": "charlievieth/c-utils", "revision_date": "2023-03-25T18:48:23", "revision_id": "b29f88394542e5b6a02be65add1e68585d3d24e6", "snapshot_id": "2369a2751747fa80e166be0d8d981efe887e8a0e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/charlievieth/c-utils/b29f88394542e5b6a02be65add1e68585d3d24e6/ygrep/main.c", "visit_date": "2023-04-05T06:25:03.772592" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <yaml.h> typedef struct { int len; int cap; char *data; } char_slice; void char_slice_init(char_slice *a) { a->len = 0; a->cap = 0; a->data = NULL; } int char_slice_do_grow(char_slice *a, int n) { int cap = a->cap > 0 ? 2*a->cap + n : n; char *data = realloc(a->data, (size_t)cap); if (!data) { free(a->data); return 0; } a->cap = cap; a->data = data; return 1; } static inline int char_slice_grow(char_slice *a, int n) { if (n <= a->cap - a->len) { return 1; } return char_slice_do_grow(a, n); } int char_slice_write_char(char_slice *a, char c) { if (!char_slice_grow(a, 1)) { return 0; } a->data[a->len++] = c; return 1; } int char_slice_unread_char(char_slice *a) { if (a->len > 0) { a->data[--a->len] = '\0'; return 1; } return 0; } int char_slice_write_string(char_slice *a, const char *s) { const int n = strlen(s); if (!char_slice_grow(a, n+1)) { return 0; } memcpy(a->data + a->len, s, n+1); a->len += n; return 1; } // typedef struct { // int len; // int cap; // char **str; // } string_array; typedef struct { yaml_char_t *value; // The scalar value. size_t length; // The length of the scalar value. yaml_scalar_style_t style; // The scalar style. } token_scalar; typedef struct { int depth; token_scalar **toks; } parse_state; // forward decls... const char * token_type_string(yaml_token_type_t t); void print_token(yaml_token_t *token); int main() { FILE *fp = fopen("testdata/cf-deployment.yml", "r"); if(!fp) { perror("fopen"); return 1; } yaml_parser_t parser; if (yaml_parser_initialize(&parser) == 0) { fprintf(stderr, "error: initialize\n"); goto InitError; } yaml_parser_set_input_file(&parser, fp); int ret; int count = 0; yaml_token_t token; while ((ret = yaml_parser_scan(&parser, &token))) { printf("%d: %s\n", count++, token_type_string(token.type)); print_token(&token); if (token.type == YAML_STREAM_END_TOKEN) { break; } } if (ret == 1) { printf("error (scan): last state: %s\n", token_type_string(token.type)); } yaml_parser_delete(&parser); return 0; InitError: fclose(fp); return 1; } void print_token(yaml_token_t *token) { switch (token->type) { case YAML_STREAM_START_TOKEN: break; case YAML_ALIAS_TOKEN: printf(" alias: %s\n", token->data.alias.value); break; case YAML_ANCHOR_TOKEN: printf(" anchor: %s\n", token->data.anchor.value); break; case YAML_TAG_TOKEN: printf(" handle: %s\n", token->data.tag.handle); printf(" suffix: %s\n", token->data.tag.suffix); break; case YAML_SCALAR_TOKEN: printf(" value: %s\n", token->data.scalar.value); break; case YAML_VERSION_DIRECTIVE_TOKEN: break; case YAML_TAG_DIRECTIVE_TOKEN: printf(" handle: %s\n", token->data.tag_directive.handle); printf(" suffix: %s\n", token->data.tag_directive.prefix); break; // make the compiler happy... case YAML_BLOCK_END_TOKEN: case YAML_BLOCK_ENTRY_TOKEN: case YAML_BLOCK_MAPPING_START_TOKEN: case YAML_BLOCK_SEQUENCE_START_TOKEN: case YAML_DOCUMENT_END_TOKEN: case YAML_DOCUMENT_START_TOKEN: case YAML_FLOW_ENTRY_TOKEN: case YAML_FLOW_MAPPING_END_TOKEN: case YAML_FLOW_MAPPING_START_TOKEN: case YAML_FLOW_SEQUENCE_END_TOKEN: case YAML_FLOW_SEQUENCE_START_TOKEN: case YAML_KEY_TOKEN: case YAML_NO_TOKEN: case YAML_STREAM_END_TOKEN: case YAML_VALUE_TOKEN: return; } } const char * token_type_string(yaml_token_type_t t) { switch (t) { case YAML_NO_TOKEN: return "YAML_NO_TOKEN"; case YAML_STREAM_START_TOKEN: return "YAML_STREAM_START_TOKEN"; case YAML_STREAM_END_TOKEN: return "YAML_STREAM_END_TOKEN"; case YAML_VERSION_DIRECTIVE_TOKEN: return "YAML_VERSION_DIRECTIVE_TOKEN"; case YAML_TAG_DIRECTIVE_TOKEN: return "YAML_TAG_DIRECTIVE_TOKEN"; case YAML_DOCUMENT_START_TOKEN: return "YAML_DOCUMENT_START_TOKEN"; case YAML_DOCUMENT_END_TOKEN: return "YAML_DOCUMENT_END_TOKEN"; case YAML_BLOCK_SEQUENCE_START_TOKEN: return "YAML_BLOCK_SEQUENCE_START_TOKEN"; case YAML_BLOCK_MAPPING_START_TOKEN: return "YAML_BLOCK_MAPPING_START_TOKEN"; case YAML_BLOCK_END_TOKEN: return "YAML_BLOCK_END_TOKEN"; case YAML_FLOW_SEQUENCE_START_TOKEN: return "YAML_FLOW_SEQUENCE_START_TOKEN"; case YAML_FLOW_SEQUENCE_END_TOKEN: return "YAML_FLOW_SEQUENCE_END_TOKEN"; case YAML_FLOW_MAPPING_START_TOKEN: return "YAML_FLOW_MAPPING_START_TOKEN"; case YAML_FLOW_MAPPING_END_TOKEN: return "YAML_FLOW_MAPPING_END_TOKEN"; case YAML_BLOCK_ENTRY_TOKEN: return "YAML_BLOCK_ENTRY_TOKEN"; case YAML_FLOW_ENTRY_TOKEN: return "YAML_FLOW_ENTRY_TOKEN"; case YAML_KEY_TOKEN: return "YAML_KEY_TOKEN"; case YAML_VALUE_TOKEN: return "YAML_VALUE_TOKEN"; case YAML_ALIAS_TOKEN: return "YAML_ALIAS_TOKEN"; case YAML_ANCHOR_TOKEN: return "YAML_ANCHOR_TOKEN"; case YAML_TAG_TOKEN: return "YAML_TAG_TOKEN"; case YAML_SCALAR_TOKEN: return "YAML_SCALAR_TOKEN"; default: return "INVALID_TOKEN"; } }
2.734375
3
2024-11-18T20:57:38.683324+00:00
2023-03-31T07:55:02
a61ff7852c74aff6bcefdc614768722b86233418
{ "blob_id": "a61ff7852c74aff6bcefdc614768722b86233418", "branch_name": "refs/heads/master", "committer_date": "2023-03-31T14:23:11", "content_id": "09d9e76be9c0c7e27d73632a4a65a34566fe5815", "detected_licenses": [ "Apache-2.0" ], "directory_id": "997a173e1a758750ca90e5f15e5f826344916c74", "extension": "h", "filename": "nicestream.h", "fork_events_count": 0, "gha_created_at": "2020-02-10T09:30:49", "gha_event_created_at": "2020-02-10T09:30:50", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 239473744, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 777, "license": "Apache-2.0", "license_type": "permissive", "path": "/include/nicestream.h", "provenance": "stackv2-0064.json.gz:71063", "repo_name": "exg/async", "revision_date": "2023-03-31T07:55:02", "revision_id": "63583e1fd83f872d19195d28948f510892984e1d", "snapshot_id": "9c0cc2ec53b669d2e0332494d8859d2f3544c0dc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/exg/async/63583e1fd83f872d19195d28948f510892984e1d/include/nicestream.h", "visit_date": "2023-04-26T19:23:21.896327" }
stackv2
#ifndef __NICESTREAM__ #define __NICESTREAM__ #include "async.h" #include "bytestream_1.h" #ifdef __cplusplus extern "C" { #endif typedef struct nicestream nicestream_t; /* * Open a stream wrapper that prevents the underlying stream from * monopolizing the scheduler. The returned stream yields whenever the * given burst size has been relayed. */ nicestream_t *make_nice(async_t *async, bytestream_1 stream, size_t max_burst); bytestream_1 nicestream_as_bytestream_1(nicestream_t *nice); ssize_t nicestream_read(nicestream_t *nice, void *buf, size_t count); void nicestream_close(nicestream_t *nice); void nicestream_register_callback(nicestream_t *nice, action_1 action); void nicestream_unregister_callback(nicestream_t *nice); #ifdef __cplusplus } #endif #endif
2.0625
2
2024-11-18T20:57:38.744781+00:00
2017-04-30T12:02:41
2f08f7b171bccfd535e49da82fcbc9208778c248
{ "blob_id": "2f08f7b171bccfd535e49da82fcbc9208778c248", "branch_name": "refs/heads/master", "committer_date": "2017-04-30T12:02:41", "content_id": "1583829f0df7b03fd6b5ba125432972fa677961b", "detected_licenses": [ "MIT" ], "directory_id": "9953f2a34f58ac311100c8de2bd8496dbf396216", "extension": "c", "filename": "object.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 87044488, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4769, "license": "MIT", "license_type": "permissive", "path": "/object.c", "provenance": "stackv2-0064.json.gz:71192", "repo_name": "wenjixiao/orange", "revision_date": "2017-04-30T12:02:41", "revision_id": "af78edc7389dd219d1490d68223b159b8446f29b", "snapshot_id": "3d8571227790544efa0aa04414f9a6dd5d5d6db0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wenjixiao/orange/af78edc7389dd219d1490d68223b159b8446f29b/object.c", "visit_date": "2021-01-18T22:17:44.746238" }
stackv2
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "object.h" #include "gc.h" extern Object *Nil,*True,*False; extern Object *Procedure; Object* new_object(ObjectType type) { Object* obj = (Object*) GC_MALLOC(sizeof(Object)); obj->type = type; return obj; } void pair_print(Object* pair,int isBegin){ if(!isBegin){ printf("("); pair_print(pair,1); }else{ Object* left = CAR(pair); Object* right = CDR(pair); //print left if(left->type != OBJ_PAIR){ obj_print(left); printf(" "); }else{ pair_print(left,0); } //print right if(right == Nil || right->type != OBJ_PAIR){ if(right != Nil){ printf(" . "); obj_print(right); } printf(") "); }else{ pair_print(right,1); } } } void obj_print(Object* obj){ if(obj == NULL) { perror("obj is null!"); exit(1); } if(obj != Nil){ switch(obj->type){ case OBJ_INTEGER: printf("%d",obj->value.i); break; case OBJ_STRING: printf("%s",obj->value.s); break; case OBJ_SYMBOL: printf("%s",obj->value.s); break; case OBJ_PRIMITIVE_PROCEDURE: printf("%s","<#primitive>"); break; case OBJ_PAIR: /* printf("("); obj_print(CAR(obj)); printf(","); obj_print(CDR(obj)); printf(")"); */ if(CAR(obj) == Procedure){ printf("%s","<#procedure>"); }else{ pair_print(obj,0); } break; } }else{ printf("nil"); } } void myprint(Object* obj,char* s){ printf("\n-------%s-------\n",s); obj_print(obj); printf("\n-------%s-------\n",s); } Object* new_integer(int i){ Object* obj = new_object(OBJ_INTEGER); obj->value.i = i; return obj; } Object* new_symbol(char* symname){ Object* obj = new_object(OBJ_SYMBOL); obj->value.s = symname; return obj; } Object* new_primitive_procedure(Object* (*primitive)()){ Object* obj = new_object(OBJ_PRIMITIVE_PROCEDURE); obj->value.primitive_procedure = primitive; return obj; } Object* new_string(char* s){ Object* obj = new_object(OBJ_STRING); obj->value.s = s; return obj; } Object* cons(Object* car,Object* cdr){ Object* pair = new_object(OBJ_PAIR); CAR(pair) = car; CDR(pair) = cdr; return pair; } Object* is_empty(Object* list){ return list == Nil ? True : False; } Object* new_list1(Object* obj){ return cons(obj,Nil); } Object* new_list2(Object* obj1,Object* obj2){ return cons(obj1,new_list1(obj2)); } Object* new_list3(Object* obj1,Object* obj2,Object* obj3){ return cons(obj1,new_list2(obj2,obj3)); } Object* new_list4(Object* obj1,Object* obj2,Object* obj3,Object* obj4){ return cons(obj1,new_list3(obj2,obj3,obj4)); } int length(Object* list){ int count=0; Object* pair = list; while(pair != Nil){ count++; pair = CDR(pair); } return count; } Object* last_pair(Object* list){ Object* p = list; while(CDR(p) != Nil){ p = CDR(p); } return p; } Object* last(Object* list){ Object* pair = last_pair(list); return CAR(pair); } Object* append(Object* list,Object* obj){ if(list == Nil){ return cons(obj,Nil); }else{ Object* lastPair = last_pair(list); CDR(lastPair) = cons(obj,Nil); return list; } } Object* filter(Object* list,Object* (*func)()){ Object *p = list; Object *from_obj,*to_obj; Object *result_list = Nil; while(p != Nil){ from_obj = CAR(p); to_obj = (*func)(from_obj); if(to_obj == True){ result_list = append(result_list,to_obj); } p = CDR(p); } return result_list; } Object* map(Object* list,Object* (*func)()){ Object *p = list; Object *from_obj,*to_obj; Object *result_list = Nil; while(p != Nil){ from_obj = CAR(p); to_obj = (*func)(from_obj); result_list = append(result_list,to_obj); p = CDR(p); } return result_list; } Object* eqv(Object* obj1,Object* obj2){ if(obj1->type == obj2->type){ switch(obj1->type){ case OBJ_SYMBOL: return strcmp(STR(obj1),STR(obj2)) == 0 ? True : False; case OBJ_INTEGER: return INTEGER(obj1) == INTEGER(obj2) ? True : False; case OBJ_STRING: return strcmp(STR(obj1),STR(obj2)) == 0 ? True : False; } }else{ } }
2.859375
3
2024-11-18T20:57:38.810974+00:00
2020-08-24T04:53:02
bec097c58221c25008e05b558e34f390f9a31ff3
{ "blob_id": "bec097c58221c25008e05b558e34f390f9a31ff3", "branch_name": "refs/heads/master", "committer_date": "2020-08-24T04:54:28", "content_id": "18e7eee387aa452256078149a316cce9121a3d99", "detected_licenses": [ "MIT" ], "directory_id": "c7ad4d19731635a8a0eb0d98715fb7f2f8b90a5c", "extension": "c", "filename": "Cmd.C", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 61456866, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13425, "license": "MIT", "license_type": "permissive", "path": "/dev/hh3core/Cmd.C", "provenance": "stackv2-0064.json.gz:71321", "repo_name": "fmatthew5876/hh3-rm2k", "revision_date": "2020-08-24T04:53:02", "revision_id": "100192e569fe4bd4c086396e73773a39a68bfb5c", "snapshot_id": "38e788ad7b4e4053d1f89c024383e4cb9da37a6f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fmatthew5876/hh3-rm2k/100192e569fe4bd4c086396e73773a39a68bfb5c/dev/hh3core/Cmd.C", "visit_date": "2021-01-09T20:07:27.333814" }
stackv2
#include "Cmd.H" #include "Log.H" #include "Code.H" #include "Exception.H" namespace Cmd { lcf::rpg::EventCommand END() { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::END); return cmd; } static lcf::rpg::EventCommand makeControlSwitches(int sub, int arg1, int arg2, ControlSwitches::SwitchOp op) { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::ControlSwitches); cmd.parameters.resize(4, 0); cmd.parameters[0] = sub; cmd.parameters[1] = arg1; cmd.parameters[2] = arg2; cmd.parameters[3] = int(op); return cmd; } lcf::rpg::EventCommand ControlSwitches::Single(int switch_id, SwitchOp op) { return makeControlSwitches(0, switch_id, switch_id, op); } lcf::rpg::EventCommand ControlSwitches::Batch(int first_switch_id, int last_switch_id, SwitchOp op) { return makeControlSwitches(1, first_switch_id, last_switch_id, op); } lcf::rpg::EventCommand ControlSwitches::Variable(int var_id, SwitchOp op) { return makeControlSwitches(2, var_id, 0, op); } static lcf::rpg::EventCommand makeControlVars(int select, int var1, int var2, ControlVars::VarOp op, int arg1, int arg2, int arg3) { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::ControlVars); cmd.parameters.resize(7, 0); cmd.parameters[0] = select; cmd.parameters[1] = var1; cmd.parameters[2] = var2; cmd.parameters[3] = int(op); cmd.parameters[4] = arg1; cmd.parameters[5] = arg2; cmd.parameters[6] = arg3; return cmd; } lcf::rpg::EventCommand ControlVars::Single::Constant(int var_id, VarOp op, int constant) { return makeControlVars(0, var_id, var_id, op, 0, constant, 0); } lcf::rpg::EventCommand ControlVars::Single::Variable(int var_id, VarOp op, int other_var_id) { return makeControlVars(0, var_id, var_id, op, 1, other_var_id, 0); } lcf::rpg::EventCommand ControlVars::Single::VariableID(int var_id, VarOp op, int other_var_id) { return makeControlVars(0, var_id, var_id, op, 2, other_var_id, 0); } lcf::rpg::EventCommand ControlVars::Single::Random(int var_id, VarOp op, int rand_min, int rand_max) { return makeControlVars(0, var_id, var_id, op, 3, rand_min, rand_max); } lcf::rpg::EventCommand ControlVars::Single::Item(int var_id, VarOp op, int item_id, bool has_item) { return makeControlVars(0, var_id, var_id, op, 4, item_id, !has_item); } lcf::rpg::EventCommand ControlVars::Single::Player(int var_id, VarOp op, int actor_id, PlayerAttribute pa) { return makeControlVars(0, var_id, var_id, op, 5, actor_id, int(pa)); } lcf::rpg::EventCommand ControlVars::Single::Event(int var_id, VarOp op, int event_id, EventQuery q) { return makeControlVars(0, var_id, var_id, op, 6, event_id, int(q)); } lcf::rpg::EventCommand ControlVars::Single::Other(int var_id, VarOp op, VarOther vo) { return makeControlVars(0, var_id, var_id, op, 7, int(vo), 0); } lcf::rpg::EventCommand ControlVars::Batch::Constant(int first_var_id, int last_var_id, VarOp op, int constant) { return makeControlVars(1, first_var_id, last_var_id, op, 0, constant, 0); } lcf::rpg::EventCommand ControlVars::Batch::Variable(int first_var_id, int last_var_id, VarOp op, int other_var_id) { return makeControlVars(1, first_var_id, last_var_id, op, 1, other_var_id, 0); } lcf::rpg::EventCommand ControlVars::Batch::VariableID(int first_var_id, int last_var_id, VarOp op, int other_var_id) { return makeControlVars(1, first_var_id, last_var_id, op, 2, other_var_id, 0); } lcf::rpg::EventCommand ControlVars::Batch::Random(int first_var_id, int last_var_id, VarOp op, int rand_min, int rand_max) { return makeControlVars(1, first_var_id, last_var_id, op, 3, rand_min, rand_max); } lcf::rpg::EventCommand ControlVars::Batch::Item(int first_var_id, int last_var_id, VarOp op, int item_id, bool has_item) { return makeControlVars(1, first_var_id, last_var_id, op, 4, item_id, !has_item); } lcf::rpg::EventCommand ControlVars::Batch::Player(int first_var_id, int last_var_id, VarOp op, int actor_id, PlayerAttribute pa) { return makeControlVars(1, first_var_id, last_var_id, op, 5, actor_id, int(pa)); } lcf::rpg::EventCommand ControlVars::Batch::Event(int first_var_id, int last_var_id, VarOp op, int event_id, EventQuery q) { return makeControlVars(1, first_var_id, last_var_id, op, 6, event_id, int(q)); } lcf::rpg::EventCommand ControlVars::Batch::Other(int first_var_id, int last_var_id, VarOp op, VarOther vo) { return makeControlVars(1, first_var_id, last_var_id, op, 7, int(vo), 0); } lcf::rpg::EventCommand ControlVars::Variable::Constant(int var_id, VarOp op, int constant) { return makeControlVars(2, var_id, 0, op, 0, constant, 0); } lcf::rpg::EventCommand ControlVars::Variable::Variable(int var_id, VarOp op, int other_var_id) { return makeControlVars(2, var_id, 0, op, 1, other_var_id, 0); } lcf::rpg::EventCommand ControlVars::Variable::VariableID(int var_id, VarOp op, int other_var_id) { return makeControlVars(2, var_id, 0, op, 2, other_var_id, 0); } lcf::rpg::EventCommand ControlVars::Variable::Random(int var_id, VarOp op, int rand_min, int rand_max) { return makeControlVars(2, var_id, 0, op, 3, rand_min, rand_max); } lcf::rpg::EventCommand ControlVars::Variable::Item(int var_id, VarOp op, int item_id, bool has_item) { return makeControlVars(2, var_id, 0, op, 4, item_id, !has_item); } lcf::rpg::EventCommand ControlVars::Variable::Player(int var_id, VarOp op, int actor_id, PlayerAttribute pa) { return makeControlVars(2, var_id, 0, op, 5, actor_id, int(pa)); } lcf::rpg::EventCommand ControlVars::Variable::Event(int var_id, VarOp op, int event_id, EventQuery q) { return makeControlVars(2, var_id, 0, op, 6, event_id, int(q)); } lcf::rpg::EventCommand ControlVars::Variable::Other(int var_id, VarOp op, VarOther vo) { return makeControlVars(2, var_id, 0, op, 7, int(vo), 0); } static lcf::rpg::EventCommand makeChangeItems(int incdec, int fv1, int item, int fv2, int amt) { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::ChangeItems); cmd.parameters = { incdec, fv1, item, fv2, amt }; return cmd; } lcf::rpg::EventCommand ChangeItems::Increase::Fixed::Constant(int item_id, int amt) { return makeChangeItems(0, 0, item_id, 0, amt); } lcf::rpg::EventCommand ChangeItems::Increase::Fixed::Variable(int item_id, int amt_var_id) { return makeChangeItems(0, 0, item_id, 1, amt_var_id); } lcf::rpg::EventCommand ChangeItems::Increase::Variable::Constant(int var_item_id, int amt) { return makeChangeItems(0, 1, var_item_id, 0, amt); } lcf::rpg::EventCommand ChangeItems::Increase::Variable::Variable(int var_item_id, int amt_var_id) { return makeChangeItems(0, 1, var_item_id, 1, amt_var_id); } lcf::rpg::EventCommand ChangeItems::Decrease::Fixed::Constant(int item_id, int amt) { return makeChangeItems(1, 0, item_id, 0, amt); } lcf::rpg::EventCommand ChangeItems::Decrease::Fixed::Variable(int item_id, int amt_var_id) { return makeChangeItems(1, 0, item_id, 1, amt_var_id); } lcf::rpg::EventCommand ChangeItems::Decrease::Variable::Constant(int var_item_id, int amt) { return makeChangeItems(1, 1, var_item_id, 0, amt); } lcf::rpg::EventCommand ChangeItems::Decrease::Variable::Variable(int var_item_id, int amt_var_id) { return makeChangeItems(1, 1, var_item_id, 1, amt_var_id); } static lcf::rpg::EventCommand makeChangeEquipment(int select, int which, int addrem, int arg1, int arg2) { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::ChangeEquipment); cmd.parameters = { select, which, addrem, arg1, arg2 }; return cmd; } lcf::rpg::EventCommand ChangeEquipment::EntireParty::Change::Fixed(int item_id) { return makeChangeEquipment(0, 0, 0, 0, item_id); } lcf::rpg::EventCommand ChangeEquipment::EntireParty::Change::Variable(int item_var_id) { return makeChangeEquipment(0, 0, 0, 1, item_var_id); } lcf::rpg::EventCommand ChangeEquipment::EntireParty::Remove(RemoveType rt) { return makeChangeEquipment(0, 0, 1, int(rt), 0); } lcf::rpg::EventCommand ChangeEquipment::Fixed::Change::Fixed(int actor_id, int item_id) { return makeChangeEquipment(1, actor_id, 0, 0, item_id); } lcf::rpg::EventCommand ChangeEquipment::Fixed::Change::Variable(int actor_id, int item_var_id) { return makeChangeEquipment(1, actor_id, 0, 1, item_var_id); } lcf::rpg::EventCommand ChangeEquipment::Fixed::Remove(int actor_id, RemoveType rt) { return makeChangeEquipment(1, actor_id, 1, int(rt), 0); } lcf::rpg::EventCommand ChangeEquipment::Variable::Change::Fixed(int var_id, int item_id) { return makeChangeEquipment(2, var_id, 0, 1, item_id); } lcf::rpg::EventCommand ChangeEquipment::Variable::Change::Variable(int var_id, int item_var_id) { return makeChangeEquipment(2, var_id, 0, 1, item_var_id); } lcf::rpg::EventCommand ChangeEquipment::Variable::Remove(int var_id, RemoveType rt) { return makeChangeEquipment(2, var_id, 1, int(rt), 0); } static lcf::rpg::EventCommand makeConditionalBranch(bool has_else) { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::ConditionalBranch); cmd.parameters.resize(6, 0); cmd.parameters[5] = has_else; return cmd; } lcf::rpg::EventCommand ConditionalBranch::Switch(int swid, bool on, bool has_else) { auto cmd = makeConditionalBranch(has_else); cmd.parameters[1] = swid; cmd.parameters[2] = !on; return cmd; } lcf::rpg::EventCommand ConditionalBranch::Variable::Constant(int varid, Compare cmp, int constant, bool has_else) { auto cmd = makeConditionalBranch(has_else); cmd.parameters[0] = 1; cmd.parameters[1] = varid; cmd.parameters[2] = 0; cmd.parameters[3] = constant; cmd.parameters[4] = int(cmp); return cmd; } lcf::rpg::EventCommand ConditionalBranch::Variable::Variable(int varid, Compare cmp, int other_varid, bool has_else) { auto cmd = makeConditionalBranch(has_else); cmd.parameters[0] = 1; cmd.parameters[1] = varid; cmd.parameters[2] = 1; cmd.parameters[3] = other_varid; cmd.parameters[4] = int(cmp); return cmd; } static lcf::rpg::EventCommand makeConditionalBranchActor(int actor_id, int subcmd, int arg, bool has_else) { auto cmd = makeConditionalBranch(has_else); cmd.parameters[0] = 5; cmd.parameters[1] = actor_id; cmd.parameters[2] = subcmd; cmd.parameters[3] = arg; return cmd; } lcf::rpg::EventCommand ConditionalBranch::Actor::IsInParty(int actor_id, bool has_else) { return makeConditionalBranchActor(actor_id, 0, 0, has_else); } lcf::rpg::EventCommand ConditionalBranch::Actor::NameIs(int actor_id, std::string name, bool has_else) { auto cmd = makeConditionalBranchActor(actor_id, 1, 0, has_else); cmd.string = std::move(name); return cmd; } lcf::rpg::EventCommand ConditionalBranch::Actor::LevelIsGE(int actor_id, int level, bool has_else) { return makeConditionalBranchActor(actor_id, 2, level, has_else); } lcf::rpg::EventCommand ConditionalBranch::Actor::HPIsGE(int actor_id, int hp, bool has_else) { return makeConditionalBranchActor(actor_id, 3, hp, has_else); } lcf::rpg::EventCommand ConditionalBranch::Actor::SkillLearned(int actor_id, int skill_id, bool has_else) { return makeConditionalBranchActor(actor_id, 4, skill_id, has_else); } lcf::rpg::EventCommand ConditionalBranch::Actor::ItemEquipped(int actor_id, int item_id, bool has_else) { return makeConditionalBranchActor(actor_id, 5, item_id, has_else); } lcf::rpg::EventCommand ConditionalBranch::Actor::StateInflicted(int actor_id, int state_id, bool has_else) { return makeConditionalBranchActor(actor_id, 6, state_id, has_else); } lcf::rpg::EventCommand PlayBGM(std::string bgm, int fadein_ms, int volume, int tempo, int balance) { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::PlayBGM); cmd.parameters = { fadein_ms, volume, tempo, balance }; cmd.string = std::move(bgm); return cmd; } lcf::rpg::EventCommand Comment(std::string msg) { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::Comment); cmd.string = std::move(msg); return cmd; } lcf::rpg::EventCommand Comment_2(std::string msg) { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::Comment_2); cmd.string = std::move(msg); return cmd; } lcf::rpg::EventCommand ElseBranch() { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::ElseBranch); return cmd; } lcf::rpg::EventCommand EndBranch() { lcf::rpg::EventCommand cmd; cmd.code = static_cast<int>(lcf::rpg::EventCommand::Code::EndBranch); return cmd; } void logCmd(int idx, const lcf::rpg::EventCommand& cmd, LogLevel ll) { logLvlStart(ll); for(int i = 0; i < cmd.indent; ++i) { logLvlRaw(ll, ' '); } logLvlRaw(ll, "Cmd (", idx, ") : code=", Code(cmd.code), " indent=", cmd.indent, " str=\"", cmd.string, "\" params="); char sep = '['; if(cmd.parameters.empty()) { logLvlRaw(ll, sep); } else { for (auto& p: cmd.parameters) { logLvlRaw(ll, sep, p); sep = ' '; } } logLvlEnd(ll, ']'); } } //namespace Cmd
2.109375
2
2024-11-18T20:57:43.670679+00:00
2023-05-03T01:44:35
87117818347dda9030553a31ad420be76a4877c3
{ "blob_id": "87117818347dda9030553a31ad420be76a4877c3", "branch_name": "refs/heads/master", "committer_date": "2023-05-03T01:44:35", "content_id": "ba317f58733af08755f0931ce535142d6d15652a", "detected_licenses": [ "MIT" ], "directory_id": "d5cc073b986be4e44f5bfd310e8465c4d1bc0b52", "extension": "c", "filename": "__PREFIX__Control.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 153774060, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1888, "license": "MIT", "license_type": "permissive", "path": "/starterkit/c/__PREFIX__Control.c", "provenance": "stackv2-0064.json.gz:71578", "repo_name": "NNNIC/psgg-starter-kit", "revision_date": "2023-05-03T01:44:35", "revision_id": "11ef123be669b3243824019064b40626c3d5b8de", "snapshot_id": "1a6f21cbeb8a7c83769c5a8cc4e4e042e5e70224", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/NNNIC/psgg-starter-kit/11ef123be669b3243824019064b40626c3d5b8de/starterkit/c/__PREFIX__Control.c", "visit_date": "2023-05-12T22:39:33.815204" }
stackv2
#include <stdio.h> #include <stdbool.h> //== Declear States == // [SYN-G-GEN OUTPUT START] $/^S_/->#static$ static void S_START(bool bFirst); static void S_END(bool bFirst); // [SYN-G-GEN OUTPUT END] // == manager == static void *m_curfunc = NULL; static void *m_nextfunc= NULL; static void *m_tempfunc = NULL; static bool m_bNoWait = false; static void update() { while(true) { bool bFirst = false; if (m_nextfunc!=NULL) { m_curfunc = m_nextfunc; m_nextfunc = NULL; bFirst = true; } m_bNoWait = false; if (m_curfunc!=NULL) { void (*func)(bool); func = m_curfunc; (*func)(bFirst); } if (m_bNoWait == false) break; } } static void Goto(void *st) { m_nextfunc = st; } static bool CheckState(void *st) { return m_curfunc == st; } static void SetNextState(void *st) { m_tempfunc = st; } static void GoNextState() { m_nextfunc = m_tempfunc; m_tempfunc = NULL; } static bool HasNextState() { return m_tempfunc != NULL; } static void NoWait() { m_bNoWait = true; } // static bool m_bYesNo = false; static void br_YES(void *st) { if (!HasNextState()) { if (m_bYesNo) { SetNextState(st); } } } static void br_NO(void *st) { if (!HasNextState()) { if (!m_bYesNo) { SetNextState(st); } } } // [SYN-G-GEN OUTPUT START] $/^S_/$ static void S_START(bool bFirst) { Goto(S_END); } static void S_END(bool bFirst) {} // [SYN-G-GEN OUTPUT END] // externs extern void __PREFIX__Control_start() { Goto(S_START); } extern void __PREFIX__Control_update() { update(); } extern bool __PREFIX__Control_is_end() { return CheckState(S_END); }
2.484375
2
2024-11-18T20:57:44.279333+00:00
2022-02-20T01:13:52
ff138d9b511c34917ac6f0f4ac2970942fb6673d
{ "blob_id": "ff138d9b511c34917ac6f0f4ac2970942fb6673d", "branch_name": "refs/heads/master", "committer_date": "2022-02-21T19:38:33", "content_id": "40d1c24bc96ee228c6e2ed821ce097b6b99582ed", "detected_licenses": [ "MIT" ], "directory_id": "ae8d0783918ca0476c4ea617fc014c7436538c5a", "extension": "c", "filename": "datetime.c", "fork_events_count": 5, "gha_created_at": "2017-10-03T19:47:08", "gha_event_created_at": "2022-02-21T19:38:34", "gha_language": "C", "gha_license_id": "MIT", "github_id": 105695732, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8314, "license": "MIT", "license_type": "permissive", "path": "/examples/KPRCA_00062/src/datetime.c", "provenance": "stackv2-0064.json.gz:71834", "repo_name": "GrammaTech/cgc-cbs", "revision_date": "2022-02-20T01:13:52", "revision_id": "797bd722ea544ab8205446dde13dcfdc059c0989", "snapshot_id": "75c93cd2d33f794b33097a45f7b6417fb27acc25", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/GrammaTech/cgc-cbs/797bd722ea544ab8205446dde13dcfdc059c0989/examples/KPRCA_00062/src/datetime.c", "visit_date": "2022-03-18T07:07:47.271029" }
stackv2
/* * Copyright (c) 2015 Kaprica Security, Inc. * * 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 <string.h> #include <stdio.h> #include "datetime.h" #define JAN "January" #define FEB "Februrary" #define MAR "March" #define APR "April" #define MAY "May" #define JUN "June" #define JUL "July" #define AUG "August" #define SEP "Septempber" #define OCT "October" #define NOV "November" #define DEC "December" #define BAD_MONTH "Undefined Month" bool is_valid_date(date_t *date) { if (!date || date->year < 2015 || date->year > 2025 || date->month < 1 || date->month > 12 || date->day < 1) return false; switch (date->month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (date->day > 31) return false; break; case 4: case 6: case 9: case 11: if (date->day > 30) return false; break; case 2: if (date->year % 400 != 0 && date->year % 4 == 0) { if (date->day > 29) return false; else if (date->day > 28) return false; } break; default: return false; } return true; } bool is_valid_time(time_t *time) { return (time && time->hour >= 0 && time->hour <= 23 && time->minute >= 0 && time->minute <= 59); } bool set_date(date_t *date, char month, char day, short year) { if (!date) return false; date_t temp; temp.year = year; temp.month = month; temp.day = day; if(!is_valid_date(&temp)) return false; *date = temp; return true; } bool set_time(time_t *time, char hour, char minute) { if (!time || hour < 0 || hour > 23 || minute < 0 || minute > 59) return false; time->hour = hour; time->minute = minute; return true; } bool set_datetime(datetime_t *dt, date_t date, time_t time) { if (!dt || !is_valid_date(&date) || !is_valid_time(&time)) return false; dt->date = date; dt->time = time; return true; } bool set_duration(duration_t *d, datetime_t dt1, datetime_t dt2) { if (!d) return false; if (compare_date(&dt1, &dt2) >= 0) return false; if (!set_datetime(&d->start, dt1.date, dt1.time)) return false; if (!set_datetime(&d->end, dt2.date, dt2.time)) return false; return true; } int compare_date(void *_date1, void *_date2) { date_t *date1 = (date_t *)_date1; date_t *date2 = (date_t *)_date2; if (!date1 || !date2) return -1; if (date1->year < date2->year) return -1; if (date1->year > date2->year) return 1; if (date1->month < date2->month) return -1; if (date1->month > date2->month) return 1; if (date1->day < date2->day) return -1; if (date1->day > date2->day) return 1; return 0; } int compare_time(void *_time1, void *_time2) { time_t *time1 = (time_t *)_time1; time_t *time2 = (time_t *)_time2; if (!time1 || !time2) return -1; if (time1->hour < time2->hour) return -1; if (time1->hour > time2->hour) return 1; if (time1->minute < time2->minute) return -1; if (time1->minute > time2->minute) return 1; return 0; } int compare_datetime(void *_dt1, void *_dt2) { int comp_val = 0; datetime_t *dt1 = (datetime_t *)_dt1; datetime_t *dt2 = (datetime_t *)_dt2; comp_val = compare_date(&dt1->date, &dt2->date); if (comp_val != 0) return comp_val; return compare_time(&dt1->time, &dt2->time); } bool durations_overlap(duration_t d1, duration_t d2) { int comp1, comp2; comp1 = compare_datetime(&d1.start, &d2.end); comp2 = compare_datetime(&d1.end, &d2.start); if (comp1 == -1 && comp2 == 1) return true; comp1 = compare_datetime(&d2.start, &d1.end); comp2 = compare_datetime(&d2.end, &d1.start); if (comp1 == -1 && comp2 == 1) return true; return false; } bool date_within(duration_t d, date_t date) { int comp1, comp2; comp1 = compare_date(&d.start.date, &date); comp2 = compare_date(&d.end.date, &date); if (comp1 <= 0 && comp2 >= 0) return true; return false; } bool datetime_within(duration_t d, datetime_t dt) { int comp1, comp2; comp1 = compare_datetime(&d.start, &dt); comp2 = compare_datetime(&d.end, &dt); if (comp1 == -1 && comp2 == 1) return true; return false; } bool strtodate(char *datestr, date_t *date) { if (!datestr || !date || strlen(datestr) < 8) return false; date_t temp; memset(&temp, 0, sizeof(date_t)); char *year, *month, *day; if ((month = strsep(&datestr, "-")) == NULL) return false; if ((day = strsep(&datestr, "-")) == NULL) return false; if ((year = strsep(&datestr, "-")) == NULL) return false; temp.year = strtol(year, NULL, 10); temp.month = strtol(month, NULL, 10); temp.day = strtol(day, NULL, 10); if (is_valid_date(&temp)) { *date = temp; return true; } else { return false; } } bool strtotime(char *timestr, time_t *time) { if (!timestr || !time || strlen(timestr) < 4) return false; time_t temp; char *hour, *minute; if ((hour = strsep(&timestr, ":")) == NULL) return false; if ((minute = strsep(&timestr, "-")) == NULL) return false; temp.hour = strtol(hour, NULL, 10); temp.minute = strtol(minute, NULL, 10); if (temp.hour == 0) { int i; for (i = 0; i < strlen(hour); i++) { if (hour[i] != '0') return false; } } if (temp.minute == 0) { int i; for (i = 0; i < strlen(minute); i++) { if (minute[i] != '0') return false; } } if (is_valid_time(&temp)) { *time = temp; return true; } else { return false; } } void print_date(date_t *date) { printf("%d-%d-%d", date->month, date->day, date->year); } void get_date_str(char *date_str, date_t *date) { sprintf(date_str, "%d-%d-%d", date->month, date->day, date->year); } char *get_month(date_t *date) { if (!date) return BAD_MONTH; switch(date->month) { case 1: return JAN; case 2: return FEB; case 3: return MAR; case 4: return APR; case 5: return MAY; case 6: return JUN; case 7: return JUL; case 8: return AUG; case 9: return SEP; case 10: return OCT; case 11: return NOV; case 12: return DEC; default: return BAD_MONTH; } } void print_time(time_t *time) { char *zero = "0"; char *emptystr = ""; char *min_pad; if(time->minute < 10) min_pad = zero; else min_pad = emptystr; printf("%d:%s%d", time->hour, min_pad, time->minute); } void get_time_str(char *time_str, time_t *time) { char *zero = "0"; char *emptystr = ""; char *min_pad; if(time->minute < 10) min_pad = zero; else min_pad = emptystr; sprintf(time_str, "%d:%s%d", time->hour, min_pad, time->minute); }
2.328125
2
2024-11-18T20:57:44.345268+00:00
2021-08-30T09:16:27
c5365c53225730d5132003410bb5164f367da815
{ "blob_id": "c5365c53225730d5132003410bb5164f367da815", "branch_name": "refs/heads/main", "committer_date": "2021-08-30T09:16:27", "content_id": "dbcbdeef481642e190aced9cc953c4f8c20d2890", "detected_licenses": [ "MIT" ], "directory_id": "82dbccdbaae8a985c887e1ec808fe8b90eec8e33", "extension": "c", "filename": "reverse.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 365662845, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1413, "license": "MIT", "license_type": "permissive", "path": "/Linked-List/reverse.c", "provenance": "stackv2-0064.json.gz:71962", "repo_name": "daniel05155/Data-Structure-and-Algorithm", "revision_date": "2021-08-30T09:16:27", "revision_id": "05212abbf8134785d02ac91f8c4341a4c7a4c66b", "snapshot_id": "e151412d2ff549629ac2893f2ba2fe14c20b9469", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/daniel05155/Data-Structure-and-Algorithm/05212abbf8134785d02ac91f8c4341a4c7a4c66b/Linked-List/reverse.c", "visit_date": "2023-07-14T10:16:54.400954" }
stackv2
#include <stdio.h> #include <stdlib.h> // 反轉鏈結串列 struct node { int data; struct node *link; }; typedef struct node *nodeptr; nodeptr create(int a[],int length); //建立Linked list void printlist(nodeptr linklist); // 列印鏈結串列 nodeptr invert(nodeptr first); int main() { int arr[] = {12,43,56,34,98,76,43,24}; int length = sizeof(arr)/sizeof(arr[0]); nodeptr first = create(arr,length); printf("反轉前:\n"); printlist(first); printf("\n"); nodeptr InvList = invert(first); printf("反轉後:\n"); printlist(InvList); return 0; } nodeptr create(int a[],int length) //建立Linked list { nodeptr head,tail,p; head = tail = (nodeptr)malloc(sizeof(struct node)); for(int i=0;i<length;i++) { tail->link =(nodeptr)malloc(sizeof(struct node)); tail = tail->link; tail->data = a[i]; } p=head; head = head->link; free(p); return head; } void printlist(nodeptr linklist) // 列印鏈結串列 { nodeptr q = linklist; while(q!=NULL) { printf("%d,",q->data); q=q->link; } printf("\n"); } nodeptr invert(nodeptr first) { nodeptr middle,trail=NULL; while(first!=NULL) { middle = first; first = first->link; middle->link = trail; trail = middle; } first = trail; return first; }
3.578125
4
2024-11-18T20:57:44.514975+00:00
2017-04-19T17:12:49
f21867ec56538d9100562a2c6073d1e7a0936ffb
{ "blob_id": "f21867ec56538d9100562a2c6073d1e7a0936ffb", "branch_name": "refs/heads/master", "committer_date": "2017-04-19T17:12:49", "content_id": "7c9f4435f30da1aa6c9e4aa74ee400f9f58194b2", "detected_licenses": [ "MIT" ], "directory_id": "a761aa7edbc0eec7576f007e026b4778964c5ee9", "extension": "c", "filename": "read-file.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 88770880, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5019, "license": "MIT", "license_type": "permissive", "path": "/read-file.c", "provenance": "stackv2-0064.json.gz:72219", "repo_name": "dpezely/Lisp-manipulation-of-C-structs", "revision_date": "2017-04-19T17:12:49", "revision_id": "23fb03c8f3affeca679b0f08cc48b90e7ac8aeb7", "snapshot_id": "866277fceeb3c24d7736b185cfcec02251ec3c5b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/dpezely/Lisp-manipulation-of-C-structs/23fb03c8f3affeca679b0f08cc48b90e7ac8aeb7/read-file.c", "visit_date": "2021-01-19T22:13:27.726938" }
stackv2
/* read-file.c - send UDP datagram to remote application */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <signal.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> static char *APP_NAME = "OTHER APP"; static char *APP_STATS_FILENAME = "payload.txt"; static char *STRUCTURED_FILENAME = "data.struct"; static unsigned char MAGIC_NUMBER = (unsigned char)'C'; static unsigned char PROTOCOL_REVISION = (unsigned char)241; static unsigned char DEFAULT_FLAGS = (unsigned char)0x00; static unsigned char DEFAULT_STATE = (unsigned char)0x23; #define APP_NAME_LENGTH 16 //#define STATUS_LENGTH 40 #define STATUS_LENGTH 400 typedef struct _message { unsigned char magic_number; unsigned char revision; unsigned char flags; unsigned char state; char app_name[APP_NAME_LENGTH]; // null terminated or clipped unsigned short agent_id; // zero or number of instance on node unsigned short other; // UNUSED; for proper byte alignment // all time values are in seconds and in network byte order uint32_t node_time; // sender's "now" uint32_t app_time; // e.g., start of App char status[STATUS_LENGTH]; // stats from App } message_t; static int MAX_MESSAGE_SIZE = sizeof(message_t); int parse_args(int argc, char **argv) { if (argc > 1) { int remaining = argc - 1; char **arg = &(argv[1]); char *next; while (remaining > 0) { if (remaining > 1) next = arg[1]; else next = (char*)NULL; if (strcmp(*arg,"--app-name")==0 || strcmp(*arg,"-a")==0) if (next) { APP_NAME=next; ++arg; --remaining; } else usage(*arg); else if (strcmp(*arg,"--stats-file")==0 || strcmp(*arg,"-s")==0) if (next) { APP_STATS_FILENAME=next; ++arg; --remaining; } else usage(*arg); else if (strcmp(*arg,"--file")==0 || strcmp(*arg,"-f")==0) if (next) { STRUCTURED_FILENAME=next; ++arg; --remaining; } else usage(*arg); else usage(*arg); ++arg; --remaining; } } } int usage(const char *arg) { if (arg != (char*)NULL) fprintf(stderr,"\nIncorrect use of %s\n\n", arg); fprintf(stderr,"Flags: \n" "-a --app-name '%s'\n" "-s --stats-file '%s'\n" "-f --file '%s'\n", APP_NAME, APP_STATS_FILENAME, STRUCTURED_FILENAME); exit(1); } int show_state(void) { printf("App name: %s\n", APP_NAME); printf("App stats file: %s\n", APP_STATS_FILENAME); printf("Structured file to read: %s\n", STRUCTURED_FILENAME); printf("sizeof(char) is %d bytes\n", sizeof(char)); printf("sizeof(short) is %d bytes\n", sizeof(short)); printf("sizeof(timeval.tv_sec) is %d bytes\n", sizeof(time_t)); printf("sizeof(uint32_t) is %d bytes\n", sizeof(uint32_t)); message_t example; printf("offet of .app_name is byte %lu\n", (unsigned long)&example.app_name - (unsigned long)&example); printf("offet of .agent_id is byte %lu\n", (unsigned long)&example.agent_id - (unsigned long)&example); printf("offet of .node_time is byte %lu\n", (unsigned long)&example.node_time - (unsigned long)&example); printf("offet of .app_time is byte %lu\n", (unsigned long)&example.app_time - (unsigned long)&example); printf("offet of .status is byte %lu\n", (unsigned long)&example.status - (unsigned long)&example); } int main(int argc, char *argv[]) { parse_args(argc, argv); show_state(); // load struct from file: message_t message; bzero(&message, MAX_MESSAGE_SIZE); int fd = open(STRUCTURED_FILENAME, O_RDONLY); if (fd < 0) { perror("unable to load structured data file"); } else { ssize_t loaded = read(fd, &message, MAX_MESSAGE_SIZE); close(fd); printf("loaded %ld bytes\n", (long)loaded); } printf("RAW BUFFER = "); int i; for (i=0; i!=sizeof(message); ++i) printf(" %.2d", ((unsigned char*)&message)[i]); printf("\n\n"); printf("RAW BUFFER=0x"); for (i=0; i!=sizeof(message); ++i) printf(" %.2X", ((unsigned char*)&message)[i]); printf("\n\n"); printf("RAW BUFFER = \"%s...\"\n\n", (const char*)&message); printf("magic number = %d 0x%X '%c'\n", message.magic_number, message.magic_number, message.magic_number); printf("revision = %d 0x%X '%c'\n", message.revision, message.revision, message.revision); printf("flags = %d 0x%X '%c'\n", message.flags, message.flags, message.flags); printf("state = %d 0x%X '%c'\n", message.state, message.state, message.state); printf("app name = \"%s\"\n", message.app_name); printf("agent id = %d 0x%X (net:%x)\n", ntohs(message.agent_id), ntohs(message.agent_id), message.agent_id); time_t node_time = ntohl(message.node_time); printf("node time: %ld==0x%lX (net:%lx) %s\n", node_time, node_time, message.node_time, ctime(&node_time)); time_t app_time = ntohl(message.app_time); printf("app time: %ld==0x%lX (net:%lx) %s\n", app_time, app_time, message.app_time, ctime(&app_time)); printf("status = \"%s\"\n", message.status); }
2.515625
3
2024-11-18T20:57:45.023421+00:00
2021-10-17T01:31:27
325d7a5bc92144b6f59c60ece42f84770cc74579
{ "blob_id": "325d7a5bc92144b6f59c60ece42f84770cc74579", "branch_name": "refs/heads/master", "committer_date": "2021-10-17T01:31:27", "content_id": "7110fa5309ca5f70c4b050e8d2475fe8909fec75", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "32e48bb5c7b9714e25bc9312f185a85e02338cc5", "extension": "c", "filename": "memcmp.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 397209343, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 309, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/usr/libs/libc/string/memcmp.c", "provenance": "stackv2-0064.json.gz:72609", "repo_name": "thebigcx/micro", "revision_date": "2021-10-17T01:31:27", "revision_id": "6400dfe82b1dcf42d2ef976ac5f7eb1f9a4a5c7c", "snapshot_id": "3e31cc30822c89bed342797ca407079bdf52a3c4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/thebigcx/micro/6400dfe82b1dcf42d2ef976ac5f7eb1f9a4a5c7c/usr/libs/libc/string/memcmp.c", "visit_date": "2023-08-25T18:25:17.336079" }
stackv2
#include <string.h> int memcmp(const void* s1, const void* s2, size_t n) { unsigned char* cs1 = (unsigned char*)s1; unsigned char* cs2 = (unsigned char*)s2; for (size_t i = 0; i < n; i++) { if (cs1[i] < cs2[i]) return -1; if (cs1[i] > cs2[i]) return 1; } return 0; }
2.625
3
2024-11-18T20:57:47.392283+00:00
2022-03-12T03:16:16
876df2c5ab67ba23023010082736ce8947027662
{ "blob_id": "876df2c5ab67ba23023010082736ce8947027662", "branch_name": "refs/heads/master", "committer_date": "2022-03-12T03:16:16", "content_id": "3b9ecd1fff6df8159ea65b5f15733260305f88a9", "detected_licenses": [ "MIT" ], "directory_id": "e912c5622fb8d5867cf7bf760d53871e79534310", "extension": "h", "filename": "race_switch.h", "fork_events_count": 14, "gha_created_at": "2019-10-26T14:28:35", "gha_event_created_at": "2022-12-27T16:14:18", "gha_language": "C", "gha_license_id": "MIT", "github_id": 217720818, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 924, "license": "MIT", "license_type": "permissive", "path": "/projects/centre_console/inc/race_switch.h", "provenance": "stackv2-0064.json.gz:73381", "repo_name": "uw-midsun/firmware_xiv", "revision_date": "2022-03-12T03:16:16", "revision_id": "57f9ca57252d1d17bac4681a319272b160df23f1", "snapshot_id": "e96852380fe7aa8f5433b668f3fbbdffdef8de9b", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/uw-midsun/firmware_xiv/57f9ca57252d1d17bac4681a319272b160df23f1/projects/centre_console/inc/race_switch.h", "visit_date": "2023-01-14T18:04:20.938144" }
stackv2
#pragma once // This module implements a 2-state FSM to switch between race mode and normal // mode. In normal mode the infotainment system and fan control run, however, // in race mode these are disabled to conserve power. Disabling and enabling // the features is managed using the 5V regulator. // Requires GPIO, soft timers, event queue, and interrupts to be initialized. #include <stdint.h> #include "fsm.h" #include "status.h" #include "voltage_regulator.h" typedef enum { RACE_STATE_OFF = 0, RACE_STATE_ON, NUM_RACE_STATES } RaceState; typedef struct RaceSwitchFsmStorage { Fsm race_switch_fsm; RaceState current_state; VoltageRegulatorStorage voltage_storage; } RaceSwitchFsmStorage; StatusCode race_switch_fsm_init(RaceSwitchFsmStorage *storage); bool race_switch_fsm_process_event(RaceSwitchFsmStorage *storage, Event *e); RaceState race_switch_fsm_get_current_state(RaceSwitchFsmStorage *storage);
2.171875
2
2024-11-18T20:57:47.457433+00:00
2021-05-06T21:27:14
a2af0ad0f74391c125690040d9f61059bc4a3633
{ "blob_id": "a2af0ad0f74391c125690040d9f61059bc4a3633", "branch_name": "refs/heads/main", "committer_date": "2021-05-06T21:27:14", "content_id": "bf93572ee8f02d1ced9f597e27c82d9b8dd27d1f", "detected_licenses": [ "MIT" ], "directory_id": "d8cad73652b03ed55825177bfc038ea8efd4ae08", "extension": "c", "filename": "VetorCaractere.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 333721346, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 414, "license": "MIT", "license_type": "permissive", "path": "/Exercícios/VetorCaractere.c", "provenance": "stackv2-0064.json.gz:73511", "repo_name": "dudalealf/Atividades-em-C", "revision_date": "2021-05-06T21:27:14", "revision_id": "d40e85f919282804e048facb5f8e4912cd31958f", "snapshot_id": "304d4cbb7d04ed8b9efcb1ae00f12efed74cc859", "src_encoding": "WINDOWS-1252", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dudalealf/Atividades-em-C/d40e85f919282804e048facb5f8e4912cd31958f/Exercícios/VetorCaractere.c", "visit_date": "2023-04-22T12:23:42.184566" }
stackv2
#include <iostream> #include <stdio.h> /*• Declare um vetor de caracteres e inicialize com a string "algoritmos". Então conte quantos caracteres tem esta string e imprima. */ int main(int argc, char** argv) { char str[]= "algoritmos"; int i; for(i=0;str[i];++i){ printf("Caractere: %c\n",str[i]); } printf("Quantidade de caracteres: %d\n", i); printf("Tamanho da string: %d",sizeof(str)); return 0; }
3.65625
4
2024-11-18T20:57:47.626286+00:00
2013-10-10T07:20:26
656341f6e9e2c391c8aec6764f1fc436ef3d45fd
{ "blob_id": "656341f6e9e2c391c8aec6764f1fc436ef3d45fd", "branch_name": "refs/heads/master", "committer_date": "2013-10-10T07:20:26", "content_id": "2f6d3477642299c667452b1af68fec288b7a6e78", "detected_licenses": [ "MIT" ], "directory_id": "b86843a72bc3938d26e8036c67145cd07059bf19", "extension": "c", "filename": "cConfig.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": 7278, "license": "MIT", "license_type": "permissive", "path": "/cConfig.c", "provenance": "stackv2-0064.json.gz:73768", "repo_name": "niels07/cConfig", "revision_date": "2013-10-10T07:20:26", "revision_id": "eb433329c1f63237c01a0f57aa2285605e51aa92", "snapshot_id": "63dedef9e13e0b1e5c78e9d1b4e03054e0169b54", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/niels07/cConfig/eb433329c1f63237c01a0f57aa2285605e51aa92/cConfig.c", "visit_date": "2021-01-22T04:36:46.436151" }
stackv2
/* * cConfig.c * * Copyright (c) 2012 "cConfig" Niels Vanden Eynde * * 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 <stdarg.h> #include "hash.h" #include "lib.h" #include "cConfig.h" #define TABLE_SIZE 150 #define DQUOTE '"' #define PAREN_OPEN '(' #define PAREN_CLOSE ')' #define END_LINE(c) (c == '\n' || c == '\0') static Hash_table *config_table = NULL; static char delim = '='; static char comment = '#'; void cConfig_error(const char *format, ...) { char buf[255]; va_list vl; va_start(vl, format); vsprintf(buf, format, vl); fprintf(stderr, "cConfig error: %s\n", buf); va_end (vl); } void cConfig_init(void) { if (!config_table) config_table = new_hash_table(TABLE_SIZE); } cConfig_opt * new_config_opt(const char *name, const char *value) { cConfig_opt *opt; opt = xmalloc(sizeof(cConfig_opt)); opt->name = dupstr(name); opt->value = value == NULL ? NULL : dupstr(value); opt->is_array = 0; opt->size = 1; return opt; } cConfig_opt * cConfig_add_opt(const char *name, const char *value) { cConfig_opt *opt; opt = new_config_opt(name, value); insert_hash_node(name, (void *)opt, config_table); return opt; } cConfig_opt * cConfig_add_opt_array(const char *name, char **values, const size_t size) { cConfig_opt *opt; opt = new_config_opt(name, NULL); opt->values = values; opt->is_array = 1; opt->size = size; insert_hash_node(name, (void *)opt, config_table); return opt; } cConfig_opt * cConfig_get_opt(const char *name) { cConfig_opt *opt; Hash_node *node; node = find_hash_node(name, config_table); if (node) opt = node->data; else opt = NULL; return opt; } char * cConfig_get_value(const char *name) { char *value; cConfig_opt *opt; opt = cConfig_get_opt(name); if (opt) value = opt->value; else value = NULL; return value; } void cConfig_set_delim(char d) { delim = d; } unsigned int cConfig_find_opt_value(char *name, char *value) { size_t i; cConfig_opt *opt; opt = cConfig_get_opt(name); if (opt == NULL) return 0; if (!opt->is_array) return 0; for (i = 0; i < opt->size; ++i) { if (streq(opt->values[i], value)) return 1; } return 0; } void cConfig_print_opt(char *name) { char **values; size_t i; cConfig_opt *opt; opt = cConfig_get_opt(name); if (opt == NULL) puts("NULL ==> NULL"); if (!opt->is_array) { fprintf(stdout, "NAME ==> %s\n", opt->name); fprintf(stdout, "VALUE ==> %s\n", opt->value); return; } values = opt->values; fprintf(stdout, "NAME ==> %s\n", opt->name); for (i = 0; i < opt->size; ++i) fprintf(stdout, "VALUE [%d] ==> %s\n", i, opt->values[i]); } static unsigned int parse_line(char *string) { char value[255], name[255], c; unsigned int have_name, have_quote, have_paren; char **values; size_t i = 0, len; have_name = have_quote = have_paren = 0; while ((c = *string++) != '\0') { if (c == DQUOTE) { if (!have_name) { cConfig_error("unexpected '%c'", DQUOTE); return 0; } if (have_quote && !END_LINE(*string)) { cConfig_error("unexpected '%c' after '%c'", *string, DQUOTE); return 0; } have_quote = !have_quote; } else if (c == ' ') { /* Ignore spaces outside of quotes. */ if (have_quote) value[i++] = c; } else if (c == delim) { if (have_name) { cConfig_error("unexpected '%c'", delim); return 0; } have_name = 1; name[i] = '\0'; i = 0; } else if (c == '\n') break; else if (c == PAREN_OPEN) { if (!have_name) { cConfig_error("unexpected '%c'", PAREN_OPEN); return 0; } have_paren = 1; } else if (c == PAREN_CLOSE) { if (have_paren && !END_LINE(*string)) { cConfig_error("unexpected '%c' after '%c'", *string, PAREN_CLOSE); return 0; } } else { if (have_name) value[i++] = c; else name[i++] = c; } } value[i] = '\0'; if (!have_name) return 1; if (have_paren) { explode(value, ",", &values, &len); cConfig_add_opt_array(name, values, len); } else cConfig_add_opt(name, value); return 1; } unsigned int cConfig_load(const char *filename) { FILE *f; char line[255]; if ((f = fopen(filename, "r")) == NULL) return 0; while (fgets(line, 255, f) != NULL) { /* Ignore lines that start with a comment character. */ if (*line == comment) continue; if (!parse_line(line)) { fclose(f); return 0; } } fclose(f); return 1; } void cConfig_free_opt(cConfig_opt *opt) { size_t i; if (opt->is_array) { for (i = 0; i < opt->size; ++i) xfree(opt->values[i]); xfree(opt->values); } else xfree(opt->value); xfree(opt->name); xfree(opt); } void cConfig_free(void) { size_t i; Hash_node *node, *temp; cConfig_opt *opt; for (i = 0; i < config_table->size; ++i) { node = config_table->nodes[i]; while (node) { opt = (cConfig_opt *)node->data; cConfig_free_opt(opt); temp = node; node = node->next; xfree(temp->key); xfree(temp); } config_table->nodes[i] = NULL; } xfree(config_table->nodes); xfree(config_table); }
2.359375
2
2024-11-18T20:57:48.634861+00:00
2023-05-24T19:48:55
158f57ab3e02a0e727e3087cb2a0b381e16b7a3d
{ "blob_id": "158f57ab3e02a0e727e3087cb2a0b381e16b7a3d", "branch_name": "refs/heads/master", "committer_date": "2023-05-24T19:48:55", "content_id": "5479735291c58d92e5b92a2b300c87ed7f335a40", "detected_licenses": [ "MIT" ], "directory_id": "0541cc80602b7ddaa62197e8eecdc0235a4df8bf", "extension": "h", "filename": "drm_format_set.h", "fork_events_count": 5, "gha_created_at": "2016-11-18T20:24:50", "gha_event_created_at": "2022-07-24T20:03:52", "gha_language": "C", "gha_license_id": "MIT", "github_id": 74163801, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3265, "license": "MIT", "license_type": "permissive", "path": "/server/node/proxy/native/src/drm_format_set.h", "provenance": "stackv2-0064.json.gz:74025", "repo_name": "udevbe/westfield", "revision_date": "2023-05-24T19:48:55", "revision_id": "cf9ebfd101c203febd984393cd0f2a54a0fd2bf1", "snapshot_id": "73536f3145e05caa39149b17a35128eac324d6a2", "src_encoding": "UTF-8", "star_events_count": 97, "url": "https://raw.githubusercontent.com/udevbe/westfield/cf9ebfd101c203febd984393cd0f2a54a0fd2bf1/server/node/proxy/native/src/drm_format_set.h", "visit_date": "2023-06-07T17:36:35.450012" }
stackv2
#ifndef RENDER_DRM_FORMAT_SET_H #define RENDER_DRM_FORMAT_SET_H #include <stdbool.h> #include <stddef.h> #include <stdint.h> /** A single DRM format, with a set of modifiers attached. */ struct drm_format { // The actual DRM format, from `drm_fourcc.h` uint32_t format; // The number of modifiers size_t len; // The capacity of the array; do not use. size_t capacity; // The actual modifiers uint64_t modifiers[]; }; /** * A set of DRM formats and modifiers. * * This is used to describe the supported format + modifier combinations. For * instance, backends will report the set they can display, and renderers will * report the set they can render to. For a more general overview of formats * and modifiers, see: * https://lore.kernel.org/dri-devel/[email protected]/ * * For compatibility with legacy drivers which don't support explicit * modifiers, the special modifier DRM_FORMAT_MOD_INVALID is used to indicate * that implicit modifiers are supported. Legacy drivers can also support the * DRM_FORMAT_MOD_LINEAR modifier, which forces the buffer to have a linear * layout. * * Users must not assume that implicit modifiers are supported unless INVALID * is listed in the modifier list. */ struct drm_format_set { // The number of formats size_t len; // The capacity of the array; private to wlroots size_t capacity; // A pointer to an array of `struct drm_format *` of length `len`. struct drm_format **formats; }; /** * Free all of the DRM formats in the set, making the set empty. Does not * free the set itself. */ void drm_format_set_finish(struct drm_format_set *set); /** * Return a pointer to a member of this struct drm_format_set of format * `format`, or NULL if none exists. */ const struct drm_format *drm_format_set_get( const struct drm_format_set *set, uint32_t format); bool drm_format_set_has(const struct drm_format_set *set, uint32_t format, uint64_t modifier); bool drm_format_set_add(struct drm_format_set *set, uint32_t format, uint64_t modifier); /** * Intersect two DRM format sets `a` and `b`, storing in the destination set * `dst` the format + modifier pairs which are in both source sets. * * Returns false on failure or when the intersection is empty. */ bool drm_format_set_intersect(struct drm_format_set *dst, const struct drm_format_set *a, const struct drm_format_set *b); #endif struct drm_format *drm_format_create(uint32_t format); bool drm_format_has(const struct drm_format *fmt, uint64_t modifier); bool drm_format_add(struct drm_format **fmt_ptr, uint64_t modifier); struct drm_format *drm_format_dup(const struct drm_format *format); /** * Intersect modifiers for two DRM formats. * * Both arguments must have the same format field. If the formats aren't * compatible, NULL is returned. If either format doesn't support any modifier, * a format that doesn't support any modifier is returned. */ struct drm_format *drm_format_intersect( const struct drm_format *a, const struct drm_format *b); bool drm_format_set_copy(struct drm_format_set *dst, const struct drm_format_set *src);
2.5
2
2024-11-18T20:57:48.809277+00:00
2016-09-09T04:31:49
74f94f7dacd8ba0dc81ee6d279a9562f02d35296
{ "blob_id": "74f94f7dacd8ba0dc81ee6d279a9562f02d35296", "branch_name": "refs/heads/master", "committer_date": "2016-09-09T04:31:49", "content_id": "baf95ef91904efffc8905ed10960773d7a10771f", "detected_licenses": [ "MIT" ], "directory_id": "95cb3e87fc75a11579dedac362408d402f86b3dd", "extension": "c", "filename": "pong.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 66134719, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13640, "license": "MIT", "license_type": "permissive", "path": "/pong.c", "provenance": "stackv2-0064.json.gz:74154", "repo_name": "me4502/cab202-pong", "revision_date": "2016-09-09T04:31:49", "revision_id": "6f2fd82c02f164abc6e4a146b2a239e8c74ba98f", "snapshot_id": "9ea62baf06e9330be22b28676e6783863d47e06f", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/me4502/cab202-pong/6f2fd82c02f164abc6e4a146b2a239e8c74ba98f/pong.c", "visit_date": "2022-03-15T14:56:03.720263" }
stackv2
#include <stdlib.h> #include <math.h> #include <time.h> #include "cab202_graphics.h" #include "cab202_timers.h" #include "cab202_sprites.h" #include "pong.h" int main() { setup_screen(); setup(); while (running) { clear_screen(); process(); show_screen(); timer_pause(DELAY); } cleanup(); cleanup_screen(); return 0; } void setup() { srand((unsigned int) time(NULL)); paddle_size = MIN(7, (screen_height() - 2 - 1) / 2); left_paddle_offset = screen_height()/2 - paddle_size/2; right_paddle_offset = screen_height()/2 - paddle_size/2; } void cleanup() { if (cooldown_timer) { destroy_timer(*cooldown_timer); } if (ball_sprite) { sprite_destroy(*ball_sprite); } } void process() { int pressed_char = get_char(); // Draw the gameover screen if (gameover) { for (int i = 0; i < sizeof(game_over_screen_text) / sizeof(game_over_screen_text[0]); i++) { const char * text = game_over_screen_text[i]; int x = screen_width()/2 - string_length((char *) text) / 2; draw_formatted(x, i, text); } if (pressed_char == 'y') { reset_game(); } else if (pressed_char == 'n') { running = false; } return; } // Draw help screen if (display_help_screen) { for (int i = 0; i < sizeof(help_screen_text) / sizeof(help_screen_text[0]); i++) { const char * help_text = help_screen_text[i]; int x = screen_width()/2 - string_length((char *) help_text) / 2; draw_formatted(x, i, help_text); } if (pressed_char > 0) { display_help_screen = false; } return; } // Draw the border draw_line(0, 0, screen_width()-1, 0, '*'); draw_line(0, 0, 0, screen_height()-1, '*'); draw_line(0, screen_height()-1, screen_width()-1, screen_height()-1, '*'); draw_line(screen_width()-1, 0, screen_width()-1, screen_height()-1, '*'); // Draw the info area. draw_line(0, 2, screen_width()-1, 2, '*'); // Get the third mark, excluding the border int third = screen_width()/3 - 6; draw_formatted(2, 1, "Lives: %d", lives); draw_formatted(2 + third, 1, "* Score: %d", score); draw_formatted(2 + third*2, 1, "* Level: %d", level + 1); int modified_time = game_time / FPS; int seconds = modified_time % 60; int minutes = (modified_time - seconds) / 60; draw_formatted(2 + third*3, 1, "* Time: %02d:%02d", minutes, seconds); // Draw left paddle. for (int i = 0; i < paddle_size; i++) { draw_char(3, left_paddle_offset + i, '|'); } // Draw right paddle. if (level != 0) { for (int i = 0; i < paddle_size; i++) { draw_char(screen_width() - 4, right_paddle_offset + i, '|'); } } // Draw the main game screen switch (level) { case 0: break; case 1: break; case 2: if (anomoly_visible) { sprite_draw(*anomoly); } break; case 3: for (int x = 0; x < rail_width-1; x++) { if (top_rail[x] == '=') { draw_char(rail_xoffset + x, screen_height() / 3, top_rail[x]); } if (bottom_rail[x] == '=') { draw_char(rail_xoffset + x, screen_height() - (screen_height() / 3), bottom_rail[x]); } } break; default: start_level(0); break; } // Draw the main ball sprite after the level has been drawn. if (ball_sprite) { sprite_draw(*ball_sprite); } if (cooldown_timer) { char *text = "Starting in... %d"; int x = screen_width()/2 - string_length(text) / 2; draw_formatted(x, screen_height()/2, text, cooldown_number); if (timer_expired(*cooldown_timer)) { cooldown_number --; if (cooldown_number < 0) { destroy_timer(*cooldown_timer); cooldown_timer = NULL; if (!ball_sprite) { ball_sprite = malloc(sizeof(sprite_id)); *ball_sprite = sprite_create(screen_width()/2, screen_height()/2, 1, 1, "*"); } else { sprite_move_to(*ball_sprite, screen_width()/2, screen_height()/2); } double degrees = ((rand() % 91) - 90 - 45); double radians = (degrees * PI / 180.0); double dx = sin(radians) * ball_starting_velocity; double dy = cos(radians) * ball_starting_velocity; sprite_turn_to(*ball_sprite, dx, dy); } else { timer_reset(*cooldown_timer); } } return; } int sx = ball_sprite ? (int) round(sprite_x(*ball_sprite)) : 0; int sy = ball_sprite ? (int) round(sprite_y(*ball_sprite)) : 0; if (!ball_sprite || sx < 0 || sx > screen_width()) { if (ball_sprite && sy < screen_width() / 2) { lives -= 1; if (lives < 0) { game_over(); } } spawn_ball(); return; } game_time ++; // Bounce when the ball hits the top or bottom. if (sy < 3 || sy > screen_height()-2) { double dx = sprite_dx(*ball_sprite); double dy = -sprite_dy(*ball_sprite); sprite_back(*ball_sprite); sprite_turn_to(*ball_sprite, dx, dy); } // Bounce when the ball hits the left paddle if (sx == 3 && sy >= left_paddle_offset && sy < left_paddle_offset + paddle_size) { double dy = sprite_dy(*ball_sprite); double dx = sprite_dx(*ball_sprite); if ((sy == left_paddle_offset && dy > 0) || (sy == left_paddle_offset + paddle_size - 1 && dy < 0)) { dy = -dy; } else { dx = -dx; } sprite_back(*ball_sprite); sprite_turn_to(*ball_sprite, dx, dy); score ++; } if (level != 0) { // Bounce when the ball hits the right paddle if (sx == screen_width() - 4 && sy >= right_paddle_offset && sy < right_paddle_offset + paddle_size) { double dy = sprite_dy(*ball_sprite); double dx = sprite_dx(*ball_sprite); if ((sy == right_paddle_offset && dy > 0) || (sy == right_paddle_offset + paddle_size - 1 && dy < 0)) { dy = -dy; } else { dx = -dx; } sprite_back(*ball_sprite); sprite_turn_to(*ball_sprite, dx, dy); } right_paddle_offset = sy - paddle_size/2; if (right_paddle_offset < 3) { right_paddle_offset = 3; } else if (right_paddle_offset > screen_height() - paddle_size - 1) { right_paddle_offset = screen_height() - paddle_size - 1; } } // Update the main game screen switch (level) { case 0: if (sx >= screen_width() - 2) { double dx = -sprite_dx(*ball_sprite); double dy = sprite_dy(*ball_sprite); sprite_back(*ball_sprite); sprite_turn_to(*ball_sprite, dx, dy); } break; case 1: break; case 2: if (!anomoly_visible && timer_expired(*anomoly_timer)) { anomoly_visible = true; } if (anomoly_visible) { int x_diff = (int)round(sprite_x(*anomoly)) + anomoly_x_offset - sx - 1; int y_diff = (int)round(sprite_y(*anomoly)) + anomoly_y_offset - sy; double dist_squared = pow(x_diff, 2) + pow(y_diff, 2); if (dist_squared < pow(1, -10)) { dist_squared = pow(1, -10); } double dist = sqrt(dist_squared); if (dist > 2 && dist < 8) { double dx = sprite_dx(*ball_sprite); double dy = sprite_dy(*ball_sprite); double magnitude = (1 / dist_squared) * 0.7; dx += (magnitude * x_diff / dist); dy += (magnitude * y_diff / dist); double normal_dist = sqrt(pow(dx, 2) + pow(dy, 2)); if (normal_dist > 1) { dx /= normal_dist; dy /= normal_dist; } sprite_turn_to(*ball_sprite, dx, dy); } } break; case 3: if (sy == screen_height() / 3 || sy == (screen_height() - screen_height() / 3)) { if (sx >= rail_xoffset && sx < rail_xoffset + rail_width - 1) { bool hit = false; bool is_top = sy == screen_height() / 3; if (is_top) { if (top_rail[sx - rail_xoffset] == '=') { top_rail[sx - rail_xoffset] = ' '; if (sx - rail_xoffset > 0) top_rail[sx - rail_xoffset - 1] = ' '; if (sx - rail_xoffset < rail_width) top_rail[sx - rail_xoffset + 1] = ' '; hit = true; } } else { if (bottom_rail[sx - rail_xoffset] == '=') { bottom_rail[sx - rail_xoffset] = ' '; if (sx - rail_xoffset > 0) bottom_rail[sx - rail_xoffset - 1] = ' '; if (sx - rail_xoffset < rail_width) bottom_rail[sx - rail_xoffset + 1] = ' '; hit = true; } } if (hit) { double dx = sprite_dx(*ball_sprite); double dy = sprite_dy(*ball_sprite); if (sx == rail_xoffset || sx == rail_xoffset + rail_width - 2 //|| (is_top && (top_rail[sx - rail_xoffset - (int)(dx)] == ' ')) //|| (!is_top && (bottom_rail[sx - rail_xoffset - (int)(dx)] == ' ')) ) { dx = -dx; } else { dy = -dy; } sprite_back(*ball_sprite); sprite_turn_to(*ball_sprite, dx, dy); } } } break; default: start_level(0); break; } // Normalize the ball velocity. double dx = sprite_dx(*ball_sprite); double dy = sprite_dy(*ball_sprite); double dist = sqrt(pow(dx, 2) + pow(dy, 2)); if (dist > 1) { dx /= dist; dy /= dist; sprite_turn_to(*ball_sprite, dx, dy); } sprite_step(*ball_sprite); if (pressed_char == 'l') { int new_level = level + 1; if (new_level >= LEVEL_COUNT) { new_level = 0; } start_level(new_level); } else if (pressed_char == 'h') { display_help_screen = true; } else if (pressed_char == 'w') { left_paddle_offset --; if (left_paddle_offset < 3) left_paddle_offset = 3; } else if (pressed_char == 's') { left_paddle_offset ++; if (left_paddle_offset > screen_height() - paddle_size - 1) left_paddle_offset = screen_height() - paddle_size - 1; } } void spawn_ball() { cooldown_timer = malloc(sizeof(timer_id)); *cooldown_timer = create_timer(300); cooldown_number = 3; if (level == 2) { if (!anomoly_timer) { anomoly_timer = malloc(sizeof(timer_id)); *anomoly_timer = create_timer(5000); } else { timer_reset(*anomoly_timer); } anomoly_visible = false; } } void start_level(int new_level) { level = new_level; spawn_ball(); switch (new_level) { case 0: break; case 1: break; case 2: if (!anomoly) { anomoly = malloc(sizeof(sprite_id)); *anomoly = sprite_create(screen_width() / 2 - anomoly_x_offset, screen_height() / 2 - anomoly_y_offset, 5, 5, anomoly_image); } if (!anomoly_timer) { anomoly_timer = malloc(sizeof(timer_id)); *anomoly_timer = create_timer(5000); } else { timer_reset(*anomoly_timer); } anomoly_visible = false; break; case 3: rail_xoffset = screen_width() / 4; rail_width = screen_width() / 2; top_rail = malloc(rail_width * sizeof(*top_rail)); bottom_rail = malloc(rail_width * sizeof(*bottom_rail)); for (int i = 0; i < rail_width; i++) { top_rail[i] = '='; bottom_rail[i] = '='; } break; default: start_level(0); break; } } void reset_game() { lives = 3; score = 0; game_time = 0; gameover = false; spawn_ball(); } void game_over() { gameover = true; } int string_length(char * str) { int length = 0; // Iterate until it's null terminated. while (str[length] != '\0') { length++; } return length; }
2.703125
3
2024-11-18T20:57:48.872432+00:00
2021-01-22T22:20:06
c4f86d4edfd3ea3df0480f7f88d388f96ec3cdb9
{ "blob_id": "c4f86d4edfd3ea3df0480f7f88d388f96ec3cdb9", "branch_name": "refs/heads/master", "committer_date": "2021-01-22T22:20:06", "content_id": "f8a3e51de9fff6b9592b74f5a7e37de1a0bdb2b7", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c3ac780e5fa6ecde494af5fd46488a9af847d17e", "extension": "h", "filename": "helper_funcs.h", "fork_events_count": 8, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 323450134, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3041, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/include/includes/helper_funcs.h", "provenance": "stackv2-0064.json.gz:74284", "repo_name": "pnnl/HiParTI", "revision_date": "2021-01-22T22:20:06", "revision_id": "591148482d50bdee39d305c9f9082e6192d59cda", "snapshot_id": "45354a9167e2699c62cd54882199898e34a69ae4", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/pnnl/HiParTI/591148482d50bdee39d305c9f9082e6192d59cda/include/includes/helper_funcs.h", "visit_date": "2023-04-04T08:23:06.576372" }
stackv2
/* This file is part of ParTI!. ParTI! is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ParTI! is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with ParTI!. If not, see <http://www.gnu.org/licenses/>. */ #ifndef HIPARTI_HELPER_FUNCS_H #define HIPARTI_HELPER_FUNCS_H #include <stdlib.h> #define max(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; }) int ptiGetLastError(const char **module, const char **file, unsigned *line, const char **reason); void ptiClearLastError(void); void pti_Panic(const char *file, unsigned line, const char *expr); /** * The assert function that always execute even when `NDEBUG` is set * * Quick & dirty error checking. Useful when writing small programs. */ #define ptiAssert(expr) ((expr) ? (void) 0 : pti_Panic(__FILE__, __LINE__, #expr)) /* Helper function for pure C module */ int ptiCudaSetDevice(int device); int ptiCudaGetLastError(void); /* Timer functions, using either CPU or GPU timer */ int ptiNewTimer(ptiTimer *timer, int use_cuda); int ptiStartTimer(ptiTimer timer); int ptiStopTimer(ptiTimer timer); double ptiElapsedTime(const ptiTimer timer); double ptiPrintElapsedTime(const ptiTimer timer, const char *name); double ptiPrintAverageElapsedTime(const ptiTimer timer, const int niters, const char *name); int ptiFreeTimer(ptiTimer timer); double ptiPrintGFLOPS(const double elapsed_time, const ptiNnzIndex flops, const char *name); /* Base functions */ char * ptiBytesString(uint64_t const bytes); ptiValue ptiRandomValue(void); /** * OMP Lock functions */ ptiMutexPool * ptiMutexAlloc(); ptiMutexPool * SptMutexAllocCustom( ptiIndex const num_locks, ptiIndex const pad_size); void ptiMutexFree(ptiMutexPool * pool); static inline ptiIndex ptiMutexTranslateId( ptiIndex const id, ptiIndex const num_locks, ptiIndex const pad_size) { return (id % num_locks) * pad_size; } static inline void ptiMutexSetLock( ptiMutexPool * const pool, ptiIndex const id) { #ifdef HIPARTI_USE_OPENMP ptiIndex const lock_id = ptiMutexTranslateId(id, pool->nlocks, pool->padsize); omp_set_lock(pool->locks + lock_id); #else fprintf(stderr, "OpenMP support is not enabled.\n"); abort(); #endif } static inline void ptiMutexUnsetLock( ptiMutexPool * const pool, ptiIndex const id) { #ifdef HIPARTI_USE_OPENMP ptiIndex const lock_id = ptiMutexTranslateId(id, pool->nlocks, pool->padsize); omp_unset_lock(pool->locks + lock_id); #else fprintf(stderr, "OpenMP support is not enabled.\n"); abort(); #endif } #endif
2.265625
2
2024-11-18T20:57:51.819062+00:00
2015-04-24T14:08:42
ff21cc73b2ecc154ef96916f8a5d056ee983e364
{ "blob_id": "ff21cc73b2ecc154ef96916f8a5d056ee983e364", "branch_name": "refs/heads/webupload", "committer_date": "2015-04-24T14:08:42", "content_id": "59d620e59454ef5c3f45bd76abf96a28e2627c6a", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "582c4802cef0aea802dc556ab5c14f75f8533df6", "extension": "c", "filename": "queue.c", "fork_events_count": 8, "gha_created_at": "2015-03-31T10:44:45", "gha_event_created_at": "2020-03-08T01:59:36", "gha_language": "C", "gha_license_id": null, "github_id": 33180072, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2039, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/source/user/totd-1.5/queue.c", "provenance": "stackv2-0064.json.gz:75699", "repo_name": "noblepepper/ralink_sdk", "revision_date": "2015-04-24T14:08:42", "revision_id": "a9e7ea3aa439d5f7852171e0988f9a45a65a1346", "snapshot_id": "7c85a52c33e212597cc7f950674bce9d84136528", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/noblepepper/ralink_sdk/a9e7ea3aa439d5f7852171e0988f9a45a65a1346/source/user/totd-1.5/queue.c", "visit_date": "2021-01-15T10:17:04.813034" }
stackv2
/**************************************************************************** * Copyright (C) 1998 WIDE Project. All rights reserved. * Copyright (C) 1999,2000,2001,2002 University of Tromso. All rights reserved. * Copyright (C) 2002 Invenia Innovation AS. All rights reserved. * * Author: Feike W. Dillema, [email protected]. * based on newbie code by Yusuke DOI, Keio Univ. Murai Lab. ****************************************************************************/ /* * <$Id: queue.c,v 1.1 2007-09-06 07:00:05 winfred Exp $> */ #include "totd.h" Q_Set *queue_create (void) { char *fn = "queue_create()"; Q_Set *qs_tmp; qs_tmp = malloc (sizeof (Q_Set)); if (!qs_tmp) syslog (LOG_ERR, "%s: Cannot allocate memory", fn); else if (!(qs_tmp->head = qs_tmp->tail = malloc (sizeof (G_Queue)))) { syslog (LOG_ERR, "%s: Cannot allocate memory", fn); free (qs_tmp); } else { qs_tmp->head->next = NULL; qs_tmp->head->p = NULL; /* SUCCESS */ return qs_tmp; } /* FAILURE */ return (NULL); } int enqueue (Q_Set *qs, void *p) { char *fn = "enqueue()"; G_Queue *gq_tmp; gq_tmp = malloc (sizeof (G_Queue)); if (!gq_tmp) syslog (LOG_ERR, "%s: Cannot allocate memory", fn); else { gq_tmp->next = NULL; gq_tmp->p = NULL; qs->tail->p = p; qs->tail->next = gq_tmp; qs->tail = gq_tmp; /* SUCCESS */ return 0; } /* FAILURE */ return (-1); } void *dequeue (Q_Set *qs) { void *p; G_Queue *gq_tmp; if (!qs->head->next) return NULL; do { p = qs->head->p; gq_tmp = qs->head; qs->head = qs->head->next; free (gq_tmp); } while (!p && qs->head != qs->tail); return p; } void *queue_peek (Q_Set *qs) { if (!qs->head->next) return NULL; return qs->head->p; } void *queue_disable (G_Queue *gq) { void *p; p = gq->p; gq->p = NULL; return p; } void queue_destroy (Q_Set *qs, void (*freefnc) (void *)) { void *p; if (!qs) return; while ((p = dequeue (qs))) (*freefnc) (p); if (qs->head) { /* watchdog */ free (qs->head); } free (qs); }
2.265625
2
2024-11-18T20:57:53.223048+00:00
2023-07-27T14:49:11
b807d2927248348bd58a4697e8b3f43e411d17a2
{ "blob_id": "b807d2927248348bd58a4697e8b3f43e411d17a2", "branch_name": "refs/heads/master", "committer_date": "2023-07-27T14:49:11", "content_id": "fdd9918c8e22b52dcb8afd813bfa0974a1e5fb5f", "detected_licenses": [ "MIT" ], "directory_id": "13e2a9bf3ebb4d2c6cdcc5b3cadaa9d87d94933e", "extension": "c", "filename": "newsroom.c", "fork_events_count": 40, "gha_created_at": "2013-01-06T22:58:13", "gha_event_created_at": "2023-07-27T14:49:13", "gha_language": "C", "gha_license_id": "MIT", "github_id": 7473802, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13542, "license": "MIT", "license_type": "permissive", "path": "/src/game/scenes/newsroom.c", "provenance": "stackv2-0064.json.gz:76214", "repo_name": "omf2097/openomf", "revision_date": "2023-07-27T14:49:11", "revision_id": "4287067184d9f16d02035f6cf0abcafb0f9755be", "snapshot_id": "5421fa6702efa16c33b4154bfacd36a1a9127aae", "src_encoding": "UTF-8", "star_events_count": 299, "url": "https://raw.githubusercontent.com/omf2097/openomf/4287067184d9f16d02035f6cf0abcafb0f9755be/src/game/scenes/newsroom.c", "visit_date": "2023-08-26T00:39:11.531162" }
stackv2
#include "game/scenes/newsroom.h" #include "audio/music.h" #include "game/gui/dialog.h" #include "game/gui/menu_background.h" #include "game/gui/text_render.h" #include "game/utils/settings.h" #include "resources/ids.h" #include "resources/languages.h" #include "resources/pilots.h" #include "utils/allocator.h" #include "utils/log.h" #include "utils/miscmath.h" #include "utils/random.h" #include "utils/str.h" #include "video/surface.h" #include "video/video.h" // newsroom text starts at 87 in english.dat // there are 24*2 texts in total #define NEWSROOM_TEXT 87 typedef struct newsroom_local_t { int news_id; int screen; surface news_bg; str news_str; str pilot1, pilot2; str har1, har2; int sex1, sex2; int won; bool champion; dialog continue_dialog; } newsroom_local; const char *object_pronoun(int sex) { if(sex == PILOT_SEX_MALE) { return "Him"; } return "Her"; } const char *subject_pronoun(int sex) { if(sex == PILOT_SEX_MALE) { return "He"; } return "She"; } void newsroom_fixup_str(newsroom_local *local) { /* * Substitution table 1= Player1 - Crystal 2= Player2 - Steffan 3= HAR1 - jaguar 4= HAR2 - shadow 5= Arena - power plant 6= His/Her P1 - Her 7= Him/Her P1 - Her 8= He/She P1 - She 10= Him/Her P2 - Him 11= He/She P2 - He */ unsigned int translation_id; if(local->champion && local->screen >= 2) { translation_id = 79; } else { translation_id = NEWSROOM_TEXT + local->news_id + min2(local->screen, 1); } str tmp; str_from_c(&tmp, lang_get(translation_id)); str_replace(&tmp, "~11", subject_pronoun(local->sex2), -1); str_replace(&tmp, "~10", object_pronoun(local->sex2), -1); str_replace(&tmp, "~9", "WTF", -1); str_replace(&tmp, "~8", subject_pronoun(local->sex1), -1); str_replace(&tmp, "~7", object_pronoun(local->sex1), -1); str_replace(&tmp, "~6", "The", -1); str_replace(&tmp, "~5", "Stadium", -1); str_replace(&tmp, "~4", str_c(&local->har2), -1); str_replace(&tmp, "~3", str_c(&local->har1), -1); str_replace(&tmp, "~2", str_c(&local->pilot2), -1); str_replace(&tmp, "~1", str_c(&local->pilot1), -1); str_free(&local->news_str); str_from(&local->news_str, &tmp); str_free(&tmp); } void newsroom_set_names(newsroom_local *local, const char *pilot1, const char *pilot2, const char *har1, const char *har2, int sex1, int sex2) { str_from_c(&local->pilot1, pilot1); str_from_c(&local->pilot2, pilot2); str_from_c(&local->har1, har1); str_from_c(&local->har2, har2); local->sex1 = sex1; local->sex2 = sex2; // Remove the whitespace at the end of pilots name str_rstrip(&local->pilot1); str_rstrip(&local->pilot2); } // newsroom callbacks void newsroom_free(scene *scene) { newsroom_local *local = scene_get_userdata(scene); surface_free(&local->news_bg); str_free(&local->news_str); str_free(&local->pilot1); str_free(&local->pilot2); str_free(&local->har1); str_free(&local->har2); dialog_free(&local->continue_dialog); omf_free(local); scene_set_userdata(scene, local); } void newsroom_static_tick(scene *scene, int paused) { newsroom_local *local = scene_get_userdata(scene); dialog_tick(&local->continue_dialog); } void newsroom_overlay_render(scene *scene) { newsroom_local *local = scene_get_userdata(scene); // Render screencapture har_screencaps *caps = &(game_state_get_player(scene->gs, (local->won ? 0 : 1))->screencaps); if(local->screen == 0) { if(caps->ok[SCREENCAP_POSE]) video_render_sprite_size(&caps->cap[SCREENCAP_POSE], 165, 15, SCREENCAP_W, SCREENCAP_H); } else { if(caps->ok[SCREENCAP_BLOW]) video_render_sprite_size(&caps->cap[SCREENCAP_BLOW], 165, 15, SCREENCAP_W, SCREENCAP_H); } // Render text if(str_size(&local->news_str) > 0) { video_render_sprite(&local->news_bg, 20, 140, BLEND_ALPHA, 0); font_render_wrapped(&font_small, str_c(&local->news_str), 30, 150, 250, COLOR_YELLOW); } // Dialog if(dialog_is_visible(&local->continue_dialog)) { dialog_render(&local->continue_dialog); } } void newsroom_continue_dialog_clicked(dialog *dlg, dialog_result result) { scene *sc = dlg->userdata; if(result == DIALOG_RESULT_NO) { game_state_set_next(sc->gs, SCENE_SCOREBOARD); } else if(result == DIALOG_RESULT_YES_OK) { // Resetting p2->sp_wins here allows the game to progress, // otherwise you get stuck with the same opponent game_player *p1 = game_state_get_player(sc->gs, 0); game_player *p2 = game_state_get_player(sc->gs, 1); p2->sp_wins = 0; // score is reset by the scoreboard scene chr_score_reset_wins(game_player_get_score(p1)); game_state_set_next(sc->gs, SCENE_SCOREBOARD); sc->gs->next_next_id = SCENE_VS; } } void newsroom_input_tick(scene *scene) { newsroom_local *local = scene_get_userdata(scene); game_player *player1 = game_state_get_player(scene->gs, 0); ctrl_event *p1 = NULL, *i; controller_poll(player1->ctrl, &p1); i = p1; if(i) { do { if(i->type == EVENT_TYPE_ACTION) { if(dialog_is_visible(&local->continue_dialog)) { dialog_event(&local->continue_dialog, i->event_data.action); } else if(i->event_data.action == ACT_ESC || i->event_data.action == ACT_KICK || i->event_data.action == ACT_PUNCH) { local->screen++; newsroom_fixup_str(local); if((local->screen >= 2 && !local->champion) || local->screen >= 3) { if(local->won || player1->chr) { // pick a new player game_player *p1 = game_state_get_player(scene->gs, 0); game_player *p2 = game_state_get_player(scene->gs, 1); if(p1->chr) { // clear the opponent as a signal to display plug on the VS p2->pilot = NULL; // also zero out the p2 wins so the game doesn't think // we keep losing p2->sp_wins = 0; } else { DEBUG("wins are %d", p1->sp_wins); if(p1->sp_wins == (4094 ^ (2 << p1->pilot->pilot_id))) { // won the game game_state_set_next(scene->gs, SCENE_END); } else { if(p1->sp_wins == (2046 ^ (2 << p1->pilot->pilot_id))) { // everyone but kriessack p2->pilot->pilot_id = 10; p2->pilot->har_id = HAR_NOVA; } else { // pick an opponent we have not yet beaten while(1) { int i = rand_int(10); if((2 << i) & p1->sp_wins || i == p1->pilot->pilot_id) { continue; } p2->pilot->pilot_id = i; p2->pilot->har_id = rand_int(10); break; } } pilot p; pilot_get_info(&p, p2->pilot->pilot_id); sd_pilot_set_player_color(p2->pilot, TERTIARY, p.colors[0]); sd_pilot_set_player_color(p2->pilot, SECONDARY, p.colors[1]); sd_pilot_set_player_color(p2->pilot, PRIMARY, p.colors[2]); // make a new AI controller controller *ctrl = omf_calloc(1, sizeof(controller)); controller_init(ctrl); sd_pilot *pilot = game_player_get_pilot(p2); ai_controller_create(ctrl, settings_get()->gameplay.difficulty, pilot, p2->pilot->pilot_id); game_player_set_ctrl(p2, ctrl); } } if(p1->chr && local->champion) { game_state_set_next(scene->gs, p1->chr->cutscene); } else { game_state_set_next(scene->gs, SCENE_VS); } } else { dialog_show(&local->continue_dialog, 1); } } } } } while((i = i->next)); } controller_free_chain(p1); } int pilot_sex(int pilot_id) { switch(pilot_id) { case 0: // Crystal case 7: // Angel case 8: // Cossette return PILOT_SEX_FEMALE; default: // everyone else is male return PILOT_SEX_MALE; } } void newsroom_startup(scene *scene, int id, int *m_load, int *m_repeat) { switch(id) { case 5: case 6: *m_load = 1; return; } } int newsroom_create(scene *scene) { newsroom_local *local = omf_calloc(1, sizeof(newsroom_local)); local->news_id = rand_int(24) * 2; local->screen = 0; local->champion = false; menu_background_create(&local->news_bg, 280, 50); str_create(&local->news_str); str_create(&local->pilot1); str_create(&local->pilot2); str_create(&local->har1); str_create(&local->har2); game_player *p1 = game_state_get_player(scene->gs, 0); game_player *p2 = game_state_get_player(scene->gs, 1); int health = 0; if(p2->sp_wins > 0) { // AI won, player lost local->won = 0; health = game_player_get_score(p2)->health; } else { local->won = 1; if(p1->chr && p1->chr->pilot.rank == 1) { local->champion = true; } health = game_player_get_score(p1)->health; } DEBUG("health is %d", health); // there's 3 random messages for // each situation for winner/loser // depending on the winner's health // > 75%, >50% >25% and >0% if(health > 75 && local->won == 1) { // player won with > 75% local->news_id = rand_int(3) * 2; } else if(health > 50 && local->won == 1) { // player won with > 50% local->news_id = 6 + rand_int(3) * 2; } else if(health > 25 && local->won == 1) { // player won with > 25% local->news_id = 12 + rand_int(3) * 2; } else if(local->won == 1) { // player won with > 0% local->news_id = 18 + rand_int(3) * 2; } else if(health > 75 && local->won == 0) { // opponent won with > 75% local->news_id = 24 + rand_int(3) * 2; } else if(health > 50 && local->won == 0) { // opponent won with > 50% local->news_id = 30 + rand_int(3) * 2; } else if(health > 25 && local->won == 0) { // opponent won with > 25% local->news_id = 36 + rand_int(3) * 2; } else { // opponent won with > 0% local->news_id = 42 + rand_int(3) * 2; } // XXX TODO get the real sex of pilot // XXX TODO strip spaces from the end of the pilots name // XXX TODO set winner/loser names properly if(p1->chr) { // TODO pilot genders newsroom_set_names(local, p1->pilot->name, p2->pilot->name, har_get_name(p1->pilot->har_id), har_get_name(p2->pilot->har_id), pilot_sex(p1->pilot->pilot_id), pilot_sex(p2->pilot->pilot_id)); } else { newsroom_set_names(local, lang_get(20 + p1->pilot->pilot_id), lang_get(20 + p2->pilot->pilot_id), har_get_name(p1->pilot->har_id), har_get_name(p2->pilot->har_id), pilot_sex(p1->pilot->pilot_id), pilot_sex(p2->pilot->pilot_id)); } newsroom_fixup_str(local); // Continue Dialog dialog_create(&local->continue_dialog, DIALOG_STYLE_YES_NO, "DO YOU WISH TO CONTINUE?", 72, 60); local->continue_dialog.userdata = scene; local->continue_dialog.clicked = newsroom_continue_dialog_clicked; // Set callbacks scene_set_userdata(scene, local); scene_set_input_poll_cb(scene, newsroom_input_tick); scene_set_render_overlay_cb(scene, newsroom_overlay_render); scene_set_free_cb(scene, newsroom_free); scene_set_static_tick_cb(scene, newsroom_static_tick); scene_set_startup_cb(scene, newsroom_startup); // Start correct music music_play(PSM_MENU); // Don't render background on its own layer // Fix for some additive blending tricks. video_render_bg_separately(false); return 0; }
2.09375
2
2024-11-18T20:58:01.473857+00:00
2021-09-12T05:21:02
962c78dd15134e5355bcfdef6dac5b105103bc7b
{ "blob_id": "962c78dd15134e5355bcfdef6dac5b105103bc7b", "branch_name": "refs/heads/master", "committer_date": "2021-09-12T05:21:02", "content_id": "4b5b13cad10974923cdfce5ee4d0505d5f50eea0", "detected_licenses": [ "MIT" ], "directory_id": "045f9ad2722216f8e8f6db61786a101d2a745473", "extension": "c", "filename": "sys_file.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 263054251, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3867, "license": "MIT", "license_type": "permissive", "path": "/sys_file.c", "provenance": "stackv2-0064.json.gz:76602", "repo_name": "ty60/quaros", "revision_date": "2021-09-12T05:21:02", "revision_id": "7baa4ed87556265d6967cd9837b2ef2830c69cb2", "snapshot_id": "5359cc7e2aa0ea8346906be00d37e6dd4ad8e455", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ty60/quaros/7baa4ed87556265d6967cd9837b2ef2830c69cb2/sys_file.c", "visit_date": "2023-07-25T02:33:55.940312" }
stackv2
#include "syscall.h" #include "types.h" #include "memory.h" #include "proc.h" #include "fs.h" #include "string.h" #include "io.h" #include "util.h" #include "sys_file.h" extern struct file console_file; int sys_open(struct int_regs *int_frame) { uint32_t user_esp = int_frame->esp; char *path = NULL; if (read_syscall_arg((void *)user_esp, 0, (uint32_t *)&path) < 0) { return -1; } int flags; if (read_syscall_arg((void *)user_esp, 1, (uint32_t *)&flags) < 0) { return -1; } int fd = 0; for (fd = 0; fd < MAX_OPEN_FILES; fd++) { if (!(curr_task->open_files[fd])) { // found empty slot break; } } struct file *fp = NULL; if (strcmp("console", path) == 0) { curr_task->open_files[fd] = &console_file; } else if (strcmp("/", path) == 0 && !(fp = get_file(path))) { // get_file("/") returned NULL. // i.e., First time to list root directory. // Allocate it. if (!(fp = alloc_file(path))) { return -1; } fp->type = FT_DIR; if ((fp->size = list_rootdir(fp->data)) < 0) { return -1; } } else if (flags == O_RDONLY) { // Read regular file if (!(fp = get_file(path))) { return -1; } } else if (flags == O_WRONLY || flags == O_RDWR) { // Write regular file if ((fp = get_file(path))) { // Delete data if file already exists memset(fp->data, 0, sizeof(MAX_FILE_SIZE)); } else if (!(fp = alloc_file(path))) { return -1; } fp->type = FT_REGULAR; } else { return -1; } if (fp) { curr_task->open_files[fd] = fp; fp->pos = 0; } return fd; } int sys_read(struct int_regs *int_frame) { uint32_t user_esp = int_frame->esp; int fd = 0; char *buf = NULL; size_t count = 0; if (read_syscall_arg((void *)user_esp, 0, (uint32_t *)&fd) < 0) { return -1; } if (read_syscall_arg((void *)user_esp, 1, (uint32_t *)&buf) < 0) { return -1; } if (read_syscall_arg((void *)user_esp, 2, &count) < 0) { return -1; } if (!curr_task->open_files[fd]) { return -1; } if (curr_task->open_files[fd]->type == FT_DEV) { return read_console(buf, count); } else if (curr_task->open_files[fd]->type == FT_REGULAR) { return read_file(curr_task->open_files[fd], buf, count); } else if (curr_task->open_files[fd]->type == FT_DIR) { return read_file(curr_task->open_files[fd], buf, count); } return -1; } int sys_write(struct int_regs *int_frame) { uint32_t user_esp = int_frame->esp; int fd; char *buf; size_t count; if (read_syscall_arg((void *)user_esp, 0, (uint32_t *)&fd) < 0) { return -1; } if (read_syscall_arg((void *)user_esp, 1, (uint32_t *)&buf) < 0) { return -1; } if (read_syscall_arg((void *)user_esp, 2, &count) < 0) { return -1; } if (!curr_task->open_files[fd]) { return -1; } if (curr_task->open_files[fd]->type == FT_DEV) { return printn(buf, count); } else if (curr_task->open_files[fd]->type == FT_REGULAR) { write_file(curr_task->open_files[fd], buf, count); } return -1; } int sys_close(struct int_regs *int_frame) { // TODO: Think carefully about the implementation. // I think there should be more things done in close // but too lazy to consider about it. uint32_t user_esp = int_frame->esp; int fd; if (read_syscall_arg((void *)user_esp, 0, (uint32_t *)&fd) < 0) { return -1; } struct file *fp = curr_task->open_files[fd]; if (!fp) return -1; if (!fp->in_use) return -1; curr_task->open_files[fd] = NULL; return 0; }
2.5
2
2024-11-18T20:58:01.988492+00:00
2015-10-17T14:03:47
950f2bf2a3b9d7c8174c2cea24cd0a47448cf931
{ "blob_id": "950f2bf2a3b9d7c8174c2cea24cd0a47448cf931", "branch_name": "refs/heads/master", "committer_date": "2015-10-17T14:03:47", "content_id": "a0284142181636607852ea3a91e6420a2f48739a", "detected_licenses": [ "MIT" ], "directory_id": "e207c098396b97f5a3d38639400df7616acf0f88", "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": 44431462, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 814, "license": "MIT", "license_type": "permissive", "path": "/tp4/linked_list_create/main.c", "provenance": "stackv2-0064.json.gz:77114", "repo_name": "gabrielvv/seminaire_C", "revision_date": "2015-10-17T14:03:47", "revision_id": "ae101b2c481f79653c370cdab76dfb6bdce98fb2", "snapshot_id": "89768c74d1f8bfbeb9eae82efc3afdedc0614e5a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gabrielvv/seminaire_C/ae101b2c481f79653c370cdab76dfb6bdce98fb2/tp4/linked_list_create/main.c", "visit_date": "2021-01-10T11:09:07.300368" }
stackv2
#include <stdio.h> #include "linked_list.h" int main(int argc, char** argv) { t_maillon* list = new_maillon(4); list->next = new_maillon(19); list->next->next = new_maillon(2); list->next->next->next = new_maillon(7); int found; printf("Taille liste : %u \n", linked_list_size(list)); printf("Valeur position 2 : %d \n", linked_list_get_by_position(list, 2, &found)); printf("Position valeur 19: %d \n", linked_list_get_by_value(list, 19)); linked_list_display(list); linked_list_display(list); printf("Valeur position 2 : %d \n", linked_list_get_by_position(list, 2, &found)); printf("Valeur position 3 : %d \n", linked_list_get_by_position(list, 3, &found)); printf("Position valeur 7: %d \n", linked_list_get_by_value(list, 7)); linked_list_free(&list); return 0; }
2.828125
3
2024-11-18T20:58:02.090476+00:00
2020-03-25T05:50:33
d967546c4880f6c5d5b25161367d76c1d66b699c
{ "blob_id": "d967546c4880f6c5d5b25161367d76c1d66b699c", "branch_name": "refs/heads/master", "committer_date": "2020-03-25T05:50:33", "content_id": "868d5f1c56956f18138a60d3d530b2d92c0d902a", "detected_licenses": [ "MIT" ], "directory_id": "85c84a8a0b71414a9c04ff097b39c085ff562eb3", "extension": "c", "filename": "fifo.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 237762678, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1221, "license": "MIT", "license_type": "permissive", "path": "/day09/harib06d/fifo.c", "provenance": "stackv2-0064.json.gz:77244", "repo_name": "itiB/hariboteOS_30days", "revision_date": "2020-03-25T05:50:33", "revision_id": "f04fccc0f394f3f1687c547e65658af429898f48", "snapshot_id": "e79108b4e901bc8207855a8c3a52e50098fbaf55", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/itiB/hariboteOS_30days/f04fccc0f394f3f1687c547e65658af429898f48/day09/harib06d/fifo.c", "visit_date": "2022-04-18T09:39:48.087346" }
stackv2
#include "bootpack.h" // 初期化関数 void fifo8_init(struct FIFO8 *fifo, int size, unsigned char *buf) { fifo -> size = size; fifo -> buf = buf; fifo -> free = size; fifo -> flags = 0; fifo -> p = 0; fifo -> q = 0; return; } // FIFOに8bit(1byte)記録する int fifo8_put(struct FIFO8 *fifo, unsigned char data) { if (fifo -> free == 0) { // 空きがなくてあふれた状態 -> return -1 fifo -> flags |= FLAGS_OVERRUN; return -1; } fifo -> buf[fifo -> p] = data; fifo -> p++; // サイズを超えたら0に戻ってループする if (fifo -> p == fifo -> size) { fifo -> p = 0; } fifo -> free--; return 0; } // fifo から1byteもらってくる int fifo8_get(struct FIFO8 *fifo) { int data; if (fifo -> free == fifo -> size) { // バッファが空の時にはとりあえず-1 return -1; } data = fifo -> buf[fifo -> q]; fifo -> q++; if (fifo -> q == fifo -> size) { fifo -> q = 0; } fifo -> free++; return data; }; int fifo8_status(struct FIFO8 *fifo) { return fifo -> size - fifo -> free; };
2.921875
3
2024-11-18T21:09:16.066946+00:00
2022-04-24T17:49:12
4bbfe010912b2c7f67a737c1f6f8237a43a7f9cb
{ "blob_id": "4bbfe010912b2c7f67a737c1f6f8237a43a7f9cb", "branch_name": "refs/heads/master", "committer_date": "2022-04-24T17:49:12", "content_id": "cd8a897eadab24c4d53b17a54da8ed0aa87fa455", "detected_licenses": [ "MIT" ], "directory_id": "ccbc18f1ae7327778b978aa6e9cf02322db3bc0d", "extension": "c", "filename": "Dijkstra.c", "fork_events_count": 7, "gha_created_at": "2016-07-09T12:57:11", "gha_event_created_at": "2022-04-24T17:49:13", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 62949540, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3229, "license": "MIT", "license_type": "permissive", "path": "/src/dijkstra/c/simple/Dijkstra.c", "provenance": "stackv2-0065.json.gz:35", "repo_name": "ClaasM/Algorithms", "revision_date": "2022-04-24T17:49:12", "revision_id": "78a7bcf0212e38995043c5d4b084c2f8ea331c49", "snapshot_id": "fc504fc2d8a98fc006e014097a4abdca07977fc3", "src_encoding": "UTF-8", "star_events_count": 17, "url": "https://raw.githubusercontent.com/ClaasM/Algorithms/78a7bcf0212e38995043c5d4b084c2f8ea331c49/src/dijkstra/c/simple/Dijkstra.c", "visit_date": "2022-05-13T09:04:07.854310" }
stackv2
package dijkstra.c.simple; import java.util.Arrays; /** * Used to perform the dijkstra Algorithm using adjacency matrices. * For a faster implementation, see @see ../fast/Dijkstra.java (using adjacency Lists) */ public class Dijkstra { /** * Implementation of dijkstra using adjacency matrix. * This returns an array containing the length of the shortest path from the start node to each other node. * It is only guaranteed to return correct results if there are no negative edges in the graph. Positive cycles are fine. * This has a runtime of O(|V|^2) (|V| = number of Nodes), for a faster implementation see @see ../fast/Dijkstra.java (using adjacency lists) * * @param graph an adjacency-matrix-representation of the graph where (x,y) is the weight of the edge or 0 if there is no edge. * @param start the node to start from. * @return an array containing the shortest distances from the given start node to each other node */ public static int[] dijkstra(int[][] graph, int start) { //This contains the distances from the start node to all other nodes int[] distances = new int[graph.length]; //Initializing with a distance of "Infinity" Arrays.fill(distances, Integer.MAX_VALUE); //The distance from the start node to itself is of course 0 distances[start] = 0; //This contains whether a node was already visited boolean[] visited = new boolean[graph.length]; //While there are nodes left to visit... while (true) { // ... find the node with the currently shortest distance from the start node... int shortestDistance = Integer.MAX_VALUE; int shortestIndex = -1; for (int i = 0; i < graph.length; i++) { //... by going through all nodes that haven't been visited yet if (distances[i] < shortestDistance && !visited[i]) { shortestDistance = distances[i]; shortestIndex = i; } } System.out.println("Visiting node " + shortestDistance + " with current distance " + shortestDistance); if (shortestIndex == -1) { // There was no node not yet visited --> We are done return distances; } //...then, for all neighboring nodes.... for (int i = 0; i < graph[shortestIndex].length; i++) { //...if the path over this edge is shorter... if (graph[shortestIndex][i] != 0 && distances[i] > distances[shortestIndex] + graph[shortestIndex][i]) { //...Save this path as new shortest path. distances[i] = distances[shortestIndex] + graph[shortestIndex][i]; System.out.println("Updating distance of node " + i + " to " + distances[i]); } } // Lastly, note that we are finished with this node. visited[shortestIndex] = true; System.out.println("Visited nodes: " + Arrays.toString(visited)); System.out.println("Currently lowest distances: " + Arrays.toString(distances)); } } }
3.65625
4
2024-11-18T21:09:16.293787+00:00
2023-09-01T09:21:17
079b4a057f2fb612e18abe8e44d36b18733ad359
{ "blob_id": "079b4a057f2fb612e18abe8e44d36b18733ad359", "branch_name": "refs/heads/master", "committer_date": "2023-09-01T09:45:00", "content_id": "d4f2af34724ed6bc685d7fa0ff37349b050938b3", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "011e552512f45ca313615e428924d001a427e8e6", "extension": "h", "filename": "rb.h", "fork_events_count": 39, "gha_created_at": "2018-03-19T08:14:43", "gha_event_created_at": "2023-09-14T13:34:22", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 125823596, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1539, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/lib/rb.h", "provenance": "stackv2-0065.json.gz:293", "repo_name": "phoenix-rtos/phoenix-rtos-kernel", "revision_date": "2023-09-01T09:21:17", "revision_id": "e15898bac82e168f7e6aaea60d413790a282f389", "snapshot_id": "3d4c1d0e7703ea5ce50c2642d35fbb79c1f2afd6", "src_encoding": "UTF-8", "star_events_count": 115, "url": "https://raw.githubusercontent.com/phoenix-rtos/phoenix-rtos-kernel/e15898bac82e168f7e6aaea60d413790a282f389/lib/rb.h", "visit_date": "2023-09-01T15:04:26.226958" }
stackv2
/* * Phoenix-RTOS * * Operating system kernel * * Standard routines - red-black tree * * Copyright 2017 Phoenix Systems * Author: Jakub Sejdak * * This file is part of Phoenix-RTOS. * * %LICENSE% */ #ifndef _LIB_RB_H_ #define _LIB_RB_H_ //#include "../hal/hal.h" #define lib_treeof(type, node_field, node) ({ \ long _off = (long) &(((type *) 0)->node_field); \ rbnode_t *tmpnode = (node); \ (type *) ((tmpnode == NULL) ? NULL : ((void *) tmpnode - _off)); \ }) typedef enum _rbcolor_t { RB_RED, RB_BLACK } rbcolor_t; typedef struct _rbnode_t { struct _rbnode_t *parent; struct _rbnode_t *left; struct _rbnode_t *right; rbcolor_t color; } rbnode_t; typedef int (*rbcomp_t)(rbnode_t *n1, rbnode_t *n2); typedef void (*rbaugment_t)(rbnode_t *node); typedef void (*rbdump_t)(rbnode_t *node); typedef struct _rbtree_t { rbnode_t *root; rbcomp_t compare; rbaugment_t augment; } rbtree_t; extern void lib_rbInit(rbtree_t *tree, rbcomp_t compare, rbaugment_t augment); extern int lib_rbInsert(rbtree_t *tree, rbnode_t *node); extern void lib_rbRemove(rbtree_t *tree, rbnode_t *node); extern rbnode_t *lib_rbMinimum(rbnode_t *node); extern rbnode_t *lib_rbMaximum(rbnode_t *node); extern rbnode_t *lib_rbPrev(rbnode_t *node); extern rbnode_t *lib_rbNext(rbnode_t *node); extern rbnode_t *lib_rbFind(rbtree_t *tree, rbnode_t *node); extern rbnode_t *lib_rbFindEx(rbnode_t *root, rbnode_t *node, rbcomp_t compare); extern void lib_rbDump(rbnode_t *node, rbdump_t dump); #endif
2.234375
2
2024-11-18T21:09:16.606789+00:00
2023-08-17T16:08:06
fd6d6cc0f145b91d645f5829956a999ea914703c
{ "blob_id": "fd6d6cc0f145b91d645f5829956a999ea914703c", "branch_name": "refs/heads/main", "committer_date": "2023-08-17T16:08:06", "content_id": "6581631f1c1c2ac27eae839a37e734a899db2d42", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "eecd5e4c50d8b78a769bcc2675250576bed34066", "extension": "c", "filename": "vecnest.c", "fork_events_count": 169, "gha_created_at": "2013-03-10T20:55:21", "gha_event_created_at": "2023-03-29T11:02:58", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 8691401, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 37805, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/vec/vec/impls/nest/vecnest.c", "provenance": "stackv2-0065.json.gz:677", "repo_name": "petsc/petsc", "revision_date": "2023-08-17T16:08:06", "revision_id": "9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9", "snapshot_id": "3b1a04fea71858e0292f9fd4d04ea11618c50969", "src_encoding": "UTF-8", "star_events_count": 341, "url": "https://raw.githubusercontent.com/petsc/petsc/9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9/src/vec/vec/impls/nest/vecnest.c", "visit_date": "2023-08-17T20:51:16.507070" }
stackv2
#include <../src/vec/vec/impls/nest/vecnestimpl.h> /*I "petscvec.h" I*/ /* check all blocks are filled */ static PetscErrorCode VecAssemblyBegin_Nest(Vec v) { Vec_Nest *vs = (Vec_Nest *)v->data; PetscInt i; PetscFunctionBegin; for (i = 0; i < vs->nb; i++) { PetscCheck(vs->v[i], PetscObjectComm((PetscObject)v), PETSC_ERR_SUP, "Nest vector cannot contain NULL blocks"); PetscCall(VecAssemblyBegin(vs->v[i])); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecAssemblyEnd_Nest(Vec v) { Vec_Nest *vs = (Vec_Nest *)v->data; PetscInt i; PetscFunctionBegin; for (i = 0; i < vs->nb; i++) PetscCall(VecAssemblyEnd(vs->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecDestroy_Nest(Vec v) { Vec_Nest *vs = (Vec_Nest *)v->data; PetscInt i; PetscFunctionBegin; if (vs->v) { for (i = 0; i < vs->nb; i++) PetscCall(VecDestroy(&vs->v[i])); PetscCall(PetscFree(vs->v)); } for (i = 0; i < vs->nb; i++) PetscCall(ISDestroy(&vs->is[i])); PetscCall(PetscFree(vs->is)); PetscCall(PetscObjectComposeFunction((PetscObject)v, "VecNestGetSubVec_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)v, "VecNestGetSubVecs_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)v, "VecNestSetSubVec_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)v, "VecNestSetSubVecs_C", NULL)); PetscCall(PetscObjectComposeFunction((PetscObject)v, "VecNestGetSize_C", NULL)); PetscCall(PetscFree(vs)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecCopy_Nest(Vec x, Vec y) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; PetscInt i; PetscFunctionBegin; VecNestCheckCompatible2(x, 1, y, 2); for (i = 0; i < bx->nb; i++) PetscCall(VecCopy(bx->v[i], by->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecDuplicate_Nest(Vec x, Vec *y) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec Y; Vec *sub; PetscInt i; PetscFunctionBegin; PetscCall(PetscMalloc1(bx->nb, &sub)); for (i = 0; i < bx->nb; i++) PetscCall(VecDuplicate(bx->v[i], &sub[i])); PetscCall(VecCreateNest(PetscObjectComm((PetscObject)x), bx->nb, bx->is, sub, &Y)); for (i = 0; i < bx->nb; i++) PetscCall(VecDestroy(&sub[i])); PetscCall(PetscFree(sub)); *y = Y; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecDot_Nest(Vec x, Vec y, PetscScalar *val) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; PetscInt i, nr; PetscScalar x_dot_y, _val; PetscFunctionBegin; VecNestCheckCompatible2(x, 1, y, 2); nr = bx->nb; _val = 0.0; for (i = 0; i < nr; i++) { PetscCall(VecDot(bx->v[i], by->v[i], &x_dot_y)); _val = _val + x_dot_y; } *val = _val; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecTDot_Nest(Vec x, Vec y, PetscScalar *val) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; PetscInt i, nr; PetscScalar x_dot_y, _val; PetscFunctionBegin; VecNestCheckCompatible2(x, 1, y, 2); nr = bx->nb; _val = 0.0; for (i = 0; i < nr; i++) { PetscCall(VecTDot(bx->v[i], by->v[i], &x_dot_y)); _val = _val + x_dot_y; } *val = _val; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecDotNorm2_Nest(Vec x, Vec y, PetscScalar *dp, PetscScalar *nm) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; PetscInt i, nr; PetscScalar x_dot_y, _dp, _nm; PetscReal norm2_y; PetscFunctionBegin; VecNestCheckCompatible2(x, 1, y, 2); nr = bx->nb; _dp = 0.0; _nm = 0.0; for (i = 0; i < nr; i++) { PetscCall(VecDotNorm2(bx->v[i], by->v[i], &x_dot_y, &norm2_y)); _dp += x_dot_y; _nm += norm2_y; } *dp = _dp; *nm = _nm; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecAXPY_Nest(Vec y, PetscScalar alpha, Vec x) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; PetscInt i, nr; PetscFunctionBegin; VecNestCheckCompatible2(y, 1, x, 3); nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecAXPY(by->v[i], alpha, bx->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecAYPX_Nest(Vec y, PetscScalar alpha, Vec x) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; PetscInt i, nr; PetscFunctionBegin; VecNestCheckCompatible2(y, 1, x, 3); nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecAYPX(by->v[i], alpha, bx->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecAXPBY_Nest(Vec y, PetscScalar alpha, PetscScalar beta, Vec x) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; PetscInt i, nr; PetscFunctionBegin; VecNestCheckCompatible2(y, 1, x, 4); nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecAXPBY(by->v[i], alpha, beta, bx->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecAXPBYPCZ_Nest(Vec z, PetscScalar alpha, PetscScalar beta, PetscScalar gamma, Vec x, Vec y) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; Vec_Nest *bz = (Vec_Nest *)z->data; PetscInt i, nr; PetscFunctionBegin; VecNestCheckCompatible3(z, 1, x, 5, y, 6); nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecAXPBYPCZ(bz->v[i], alpha, beta, gamma, bx->v[i], by->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecScale_Nest(Vec x, PetscScalar alpha) { Vec_Nest *bx = (Vec_Nest *)x->data; PetscInt i, nr; PetscFunctionBegin; nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecScale(bx->v[i], alpha)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecPointwiseMult_Nest(Vec w, Vec x, Vec y) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; Vec_Nest *bw = (Vec_Nest *)w->data; PetscInt i, nr; PetscFunctionBegin; VecNestCheckCompatible3(w, 1, x, 2, y, 3); nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecPointwiseMult(bw->v[i], bx->v[i], by->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecPointwiseDivide_Nest(Vec w, Vec x, Vec y) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; Vec_Nest *bw = (Vec_Nest *)w->data; PetscInt i, nr; PetscFunctionBegin; VecNestCheckCompatible3(w, 1, x, 2, y, 3); nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecPointwiseDivide(bw->v[i], bx->v[i], by->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecReciprocal_Nest(Vec x) { Vec_Nest *bx = (Vec_Nest *)x->data; PetscInt i, nr; PetscFunctionBegin; nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecReciprocal(bx->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecNorm_Nest(Vec xin, NormType type, PetscReal *z) { Vec_Nest *bx = (Vec_Nest *)xin->data; PetscInt i, nr; PetscReal z_i; PetscReal _z; PetscFunctionBegin; nr = bx->nb; _z = 0.0; if (type == NORM_2) { PetscScalar dot; PetscCall(VecDot(xin, xin, &dot)); _z = PetscAbsScalar(PetscSqrtScalar(dot)); } else if (type == NORM_1) { for (i = 0; i < nr; i++) { PetscCall(VecNorm(bx->v[i], type, &z_i)); _z = _z + z_i; } } else if (type == NORM_INFINITY) { for (i = 0; i < nr; i++) { PetscCall(VecNorm(bx->v[i], type, &z_i)); if (z_i > _z) _z = z_i; } } *z = _z; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecMAXPY_Nest(Vec y, PetscInt nv, const PetscScalar alpha[], Vec *x) { PetscFunctionBegin; /* TODO: implement proper MAXPY. For now, do axpy on each vector */ for (PetscInt v = 0; v < nv; v++) PetscCall(VecAXPY(y, alpha[v], x[v])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecMDot_Nest(Vec x, PetscInt nv, const Vec y[], PetscScalar *val) { PetscFunctionBegin; /* TODO: implement proper MDOT. For now, do dot on each vector */ for (PetscInt j = 0; j < nv; j++) PetscCall(VecDot(x, y[j], &val[j])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecMTDot_Nest(Vec x, PetscInt nv, const Vec y[], PetscScalar *val) { PetscFunctionBegin; /* TODO: implement proper MTDOT. For now, do tdot on each vector */ for (PetscInt j = 0; j < nv; j++) PetscCall(VecTDot(x, y[j], &val[j])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecSet_Nest(Vec x, PetscScalar alpha) { Vec_Nest *bx = (Vec_Nest *)x->data; PetscInt i, nr; PetscFunctionBegin; nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecSet(bx->v[i], alpha)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecConjugate_Nest(Vec x) { Vec_Nest *bx = (Vec_Nest *)x->data; PetscInt j, nr; PetscFunctionBegin; nr = bx->nb; for (j = 0; j < nr; j++) PetscCall(VecConjugate(bx->v[j])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecSwap_Nest(Vec x, Vec y) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; PetscInt i, nr; PetscFunctionBegin; VecNestCheckCompatible2(x, 1, y, 2); nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecSwap(bx->v[i], by->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecWAXPY_Nest(Vec w, PetscScalar alpha, Vec x, Vec y) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; Vec_Nest *bw = (Vec_Nest *)w->data; PetscInt i, nr; PetscFunctionBegin; VecNestCheckCompatible3(w, 1, x, 3, y, 4); nr = bx->nb; for (i = 0; i < nr; i++) PetscCall(VecWAXPY(bw->v[i], alpha, bx->v[i], by->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecMin_Nest(Vec x, PetscInt *p, PetscReal *v) { PetscInt i, lp = -1, lw = -1; PetscReal lv; Vec_Nest *bx = (Vec_Nest *)x->data; PetscFunctionBegin; *v = PETSC_MAX_REAL; for (i = 0; i < bx->nb; i++) { PetscInt tp; PetscCall(VecMin(bx->v[i], &tp, &lv)); if (lv < *v) { *v = lv; lw = i; lp = tp; } } if (p && lw > -1) { PetscInt st, en; const PetscInt *idxs; *p = -1; PetscCall(VecGetOwnershipRange(bx->v[lw], &st, &en)); if (lp >= st && lp < en) { PetscCall(ISGetIndices(bx->is[lw], &idxs)); *p = idxs[lp - st]; PetscCall(ISRestoreIndices(bx->is[lw], &idxs)); } PetscCall(MPIU_Allreduce(MPI_IN_PLACE, p, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)x))); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecMax_Nest(Vec x, PetscInt *p, PetscReal *v) { PetscInt i, lp = -1, lw = -1; PetscReal lv; Vec_Nest *bx = (Vec_Nest *)x->data; PetscFunctionBegin; *v = PETSC_MIN_REAL; for (i = 0; i < bx->nb; i++) { PetscInt tp; PetscCall(VecMax(bx->v[i], &tp, &lv)); if (lv > *v) { *v = lv; lw = i; lp = tp; } } if (p && lw > -1) { PetscInt st, en; const PetscInt *idxs; *p = -1; PetscCall(VecGetOwnershipRange(bx->v[lw], &st, &en)); if (lp >= st && lp < en) { PetscCall(ISGetIndices(bx->is[lw], &idxs)); *p = idxs[lp - st]; PetscCall(ISRestoreIndices(bx->is[lw], &idxs)); } PetscCall(MPIU_Allreduce(MPI_IN_PLACE, p, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)x))); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecView_Nest(Vec x, PetscViewer viewer) { Vec_Nest *bx = (Vec_Nest *)x->data; PetscBool isascii; PetscInt i; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii)); if (isascii) { PetscCall(PetscViewerASCIIPushTab(viewer)); PetscCall(PetscViewerASCIIPrintf(viewer, "VecNest, rows=%" PetscInt_FMT ", structure: \n", bx->nb)); for (i = 0; i < bx->nb; i++) { VecType type; char name[256] = "", prefix[256] = ""; PetscInt NR; PetscCall(VecGetSize(bx->v[i], &NR)); PetscCall(VecGetType(bx->v[i], &type)); if (((PetscObject)bx->v[i])->name) PetscCall(PetscSNPrintf(name, sizeof(name), "name=\"%s\", ", ((PetscObject)bx->v[i])->name)); if (((PetscObject)bx->v[i])->prefix) PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "prefix=\"%s\", ", ((PetscObject)bx->v[i])->prefix)); PetscCall(PetscViewerASCIIPrintf(viewer, "(%" PetscInt_FMT ") : %s%stype=%s, rows=%" PetscInt_FMT " \n", i, name, prefix, type, NR)); PetscCall(PetscViewerASCIIPushTab(viewer)); /* push1 */ PetscCall(VecView(bx->v[i], viewer)); PetscCall(PetscViewerASCIIPopTab(viewer)); /* pop1 */ } PetscCall(PetscViewerASCIIPopTab(viewer)); /* pop0 */ } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecSize_Nest_Recursive(Vec x, PetscBool globalsize, PetscInt *L) { Vec_Nest *bx; PetscInt size, i, nr; PetscBool isnest; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)x, VECNEST, &isnest)); if (!isnest) { /* Not nest */ if (globalsize) PetscCall(VecGetSize(x, &size)); else PetscCall(VecGetLocalSize(x, &size)); *L = *L + size; PetscFunctionReturn(PETSC_SUCCESS); } /* Otherwise we have a nest */ bx = (Vec_Nest *)x->data; nr = bx->nb; /* now descend recursively */ for (i = 0; i < nr; i++) PetscCall(VecSize_Nest_Recursive(bx->v[i], globalsize, L)); PetscFunctionReturn(PETSC_SUCCESS); } /* Returns the sum of the global size of all the constituent vectors in the nest */ static PetscErrorCode VecGetSize_Nest(Vec x, PetscInt *N) { PetscFunctionBegin; *N = x->map->N; PetscFunctionReturn(PETSC_SUCCESS); } /* Returns the sum of the local size of all the constituent vectors in the nest */ static PetscErrorCode VecGetLocalSize_Nest(Vec x, PetscInt *n) { PetscFunctionBegin; *n = x->map->n; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecMaxPointwiseDivide_Nest(Vec x, Vec y, PetscReal *max) { Vec_Nest *bx = (Vec_Nest *)x->data; Vec_Nest *by = (Vec_Nest *)y->data; PetscInt i, nr; PetscReal local_max, m; PetscFunctionBegin; VecNestCheckCompatible2(x, 1, y, 2); nr = bx->nb; m = 0.0; for (i = 0; i < nr; i++) { PetscCall(VecMaxPointwiseDivide(bx->v[i], by->v[i], &local_max)); if (local_max > m) m = local_max; } *max = m; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecGetSubVector_Nest(Vec X, IS is, Vec *x) { Vec_Nest *bx = (Vec_Nest *)X->data; PetscInt i; PetscFunctionBegin; *x = NULL; for (i = 0; i < bx->nb; i++) { PetscBool issame = PETSC_FALSE; PetscCall(ISEqual(is, bx->is[i], &issame)); if (issame) { *x = bx->v[i]; PetscCall(PetscObjectReference((PetscObject)(*x))); break; } } PetscCheck(*x, PetscObjectComm((PetscObject)is), PETSC_ERR_ARG_OUTOFRANGE, "Index set not found in nested Vec"); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecRestoreSubVector_Nest(Vec X, IS is, Vec *x) { PetscFunctionBegin; PetscCall(PetscObjectStateIncrease((PetscObject)X)); PetscCall(VecDestroy(x)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecGetArray_Nest(Vec X, PetscScalar **x) { Vec_Nest *bx = (Vec_Nest *)X->data; PetscInt i, m, rstart, rend; PetscFunctionBegin; PetscCall(VecGetOwnershipRange(X, &rstart, &rend)); PetscCall(VecGetLocalSize(X, &m)); PetscCall(PetscMalloc1(m, x)); for (i = 0; i < bx->nb; i++) { Vec subvec = bx->v[i]; IS isy = bx->is[i]; PetscInt j, sm; const PetscInt *ixy; const PetscScalar *y; PetscCall(VecGetLocalSize(subvec, &sm)); PetscCall(VecGetArrayRead(subvec, &y)); PetscCall(ISGetIndices(isy, &ixy)); for (j = 0; j < sm; j++) { PetscInt ix = ixy[j]; PetscCheck(ix >= rstart && rend > ix, PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for getting array from nonlocal subvec"); (*x)[ix - rstart] = y[j]; } PetscCall(ISRestoreIndices(isy, &ixy)); PetscCall(VecRestoreArrayRead(subvec, &y)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecRestoreArray_Nest(Vec X, PetscScalar **x) { Vec_Nest *bx = (Vec_Nest *)X->data; PetscInt i, m, rstart, rend; PetscFunctionBegin; PetscCall(VecGetOwnershipRange(X, &rstart, &rend)); PetscCall(VecGetLocalSize(X, &m)); for (i = 0; i < bx->nb; i++) { Vec subvec = bx->v[i]; IS isy = bx->is[i]; PetscInt j, sm; const PetscInt *ixy; PetscScalar *y; PetscCall(VecGetLocalSize(subvec, &sm)); PetscCall(VecGetArray(subvec, &y)); PetscCall(ISGetIndices(isy, &ixy)); for (j = 0; j < sm; j++) { PetscInt ix = ixy[j]; PetscCheck(ix >= rstart && rend > ix, PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for getting array from nonlocal subvec"); y[j] = (*x)[ix - rstart]; } PetscCall(ISRestoreIndices(isy, &ixy)); PetscCall(VecRestoreArray(subvec, &y)); } PetscCall(PetscFree(*x)); PetscCall(PetscObjectStateIncrease((PetscObject)X)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecRestoreArrayRead_Nest(Vec X, const PetscScalar **x) { PetscFunctionBegin; PetscCall(PetscFree(*x)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecConcatenate_Nest(PetscInt nx, const Vec X[], Vec *Y, IS *x_is[]) { PetscFunctionBegin; PetscCheck(nx <= 0, PetscObjectComm((PetscObject)(*X)), PETSC_ERR_SUP, "VecConcatenate() is not supported for VecNest"); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecCreateLocalVector_Nest(Vec v, Vec *w) { Vec *ww; IS *wis; Vec_Nest *bv = (Vec_Nest *)v->data; PetscInt i; PetscFunctionBegin; PetscCall(PetscMalloc2(bv->nb, &ww, bv->nb, &wis)); for (i = 0; i < bv->nb; i++) PetscCall(VecCreateLocalVector(bv->v[i], &ww[i])); for (i = 0; i < bv->nb; i++) { PetscInt off; PetscCall(VecGetOwnershipRange(v, &off, NULL)); PetscCall(ISOnComm(bv->is[i], PetscObjectComm((PetscObject)ww[i]), PETSC_COPY_VALUES, &wis[i])); PetscCall(ISShift(wis[i], -off, wis[i])); } PetscCall(VecCreateNest(PETSC_COMM_SELF, bv->nb, wis, ww, w)); for (i = 0; i < bv->nb; i++) { PetscCall(VecDestroy(&ww[i])); PetscCall(ISDestroy(&wis[i])); } PetscCall(PetscFree2(ww, wis)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecGetLocalVector_Nest(Vec v, Vec w) { Vec_Nest *bv = (Vec_Nest *)v->data; Vec_Nest *bw = (Vec_Nest *)w->data; PetscInt i; PetscFunctionBegin; PetscCheckSameType(v, 1, w, 2); PetscCheck(bv->nb = bw->nb, PetscObjectComm((PetscObject)w), PETSC_ERR_ARG_WRONG, "Invalid local vector"); for (i = 0; i < bv->nb; i++) PetscCall(VecGetLocalVector(bv->v[i], bw->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecRestoreLocalVector_Nest(Vec v, Vec w) { Vec_Nest *bv = (Vec_Nest *)v->data; Vec_Nest *bw = (Vec_Nest *)w->data; PetscInt i; PetscFunctionBegin; PetscCheckSameType(v, 1, w, 2); PetscCheck(bv->nb = bw->nb, PetscObjectComm((PetscObject)w), PETSC_ERR_ARG_WRONG, "Invalid local vector"); for (i = 0; i < bv->nb; i++) PetscCall(VecRestoreLocalVector(bv->v[i], bw->v[i])); PetscCall(PetscObjectStateIncrease((PetscObject)v)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecGetLocalVectorRead_Nest(Vec v, Vec w) { Vec_Nest *bv = (Vec_Nest *)v->data; Vec_Nest *bw = (Vec_Nest *)w->data; PetscInt i; PetscFunctionBegin; PetscCheckSameType(v, 1, w, 2); PetscCheck(bv->nb = bw->nb, PetscObjectComm((PetscObject)w), PETSC_ERR_ARG_WRONG, "Invalid local vector"); for (i = 0; i < bv->nb; i++) PetscCall(VecGetLocalVectorRead(bv->v[i], bw->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecRestoreLocalVectorRead_Nest(Vec v, Vec w) { Vec_Nest *bv = (Vec_Nest *)v->data; Vec_Nest *bw = (Vec_Nest *)w->data; PetscInt i; PetscFunctionBegin; PetscCheckSameType(v, 1, w, 2); PetscCheck(bv->nb = bw->nb, PetscObjectComm((PetscObject)w), PETSC_ERR_ARG_WRONG, "Invalid local vector"); for (i = 0; i < bv->nb; i++) PetscCall(VecRestoreLocalVectorRead(bv->v[i], bw->v[i])); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecSetRandom_Nest(Vec v, PetscRandom r) { Vec_Nest *bv = (Vec_Nest *)v->data; PetscFunctionBegin; for (PetscInt i = 0; i < bv->nb; i++) PetscCall(VecSetRandom(bv->v[i], r)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecErrorWeightedNorms_Nest(Vec U, Vec Y, Vec E, NormType wnormtype, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol, PetscReal ignore_max, PetscReal *norm, PetscInt *norm_loc, PetscReal *norma, PetscInt *norma_loc, PetscReal *normr, PetscInt *normr_loc) { Vec_Nest *bu = (Vec_Nest *)U->data; Vec_Nest *by = (Vec_Nest *)Y->data; Vec_Nest *be = E ? (Vec_Nest *)E->data : NULL; Vec_Nest *ba = vatol ? (Vec_Nest *)vatol->data : NULL; Vec_Nest *br = vrtol ? (Vec_Nest *)vrtol->data : NULL; PetscFunctionBegin; VecNestCheckCompatible2(U, 1, Y, 2); if (E) VecNestCheckCompatible2(U, 1, E, 3); if (vatol) VecNestCheckCompatible2(U, 1, vatol, 6); if (vrtol) VecNestCheckCompatible2(U, 1, vrtol, 8); *norm = 0.0; *norma = 0.0; *normr = 0.0; *norm_loc = 0; *norma_loc = 0; *normr_loc = 0; for (PetscInt i = 0; i < bu->nb; i++) { PetscReal n, na, nr; PetscInt n_loc, na_loc, nr_loc; PetscCall(VecErrorWeightedNorms(bu->v[i], by->v[i], be ? be->v[i] : NULL, wnormtype, atol, ba ? ba->v[i] : NULL, rtol, br ? br->v[i] : NULL, ignore_max, &n, &n_loc, &na, &na_loc, &nr, &nr_loc)); if (wnormtype == NORM_INFINITY) { *norm = PetscMax(*norm, n); *norma = PetscMax(*norma, na); *normr = PetscMax(*normr, nr); } else { *norm += PetscSqr(n); *norma += PetscSqr(na); *normr += PetscSqr(nr); } *norm_loc += n_loc; *norma_loc += na_loc; *normr_loc += nr_loc; } if (wnormtype == NORM_2) { *norm = PetscSqrtReal(*norm); *norma = PetscSqrtReal(*norma); *normr = PetscSqrtReal(*normr); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecNestSetOps_Private(struct _VecOps *ops) { PetscFunctionBegin; ops->duplicate = VecDuplicate_Nest; ops->duplicatevecs = VecDuplicateVecs_Default; ops->destroyvecs = VecDestroyVecs_Default; ops->dot = VecDot_Nest; ops->mdot = VecMDot_Nest; ops->norm = VecNorm_Nest; ops->tdot = VecTDot_Nest; ops->mtdot = VecMTDot_Nest; ops->scale = VecScale_Nest; ops->copy = VecCopy_Nest; ops->set = VecSet_Nest; ops->swap = VecSwap_Nest; ops->axpy = VecAXPY_Nest; ops->axpby = VecAXPBY_Nest; ops->maxpy = VecMAXPY_Nest; ops->aypx = VecAYPX_Nest; ops->waxpy = VecWAXPY_Nest; ops->axpbypcz = NULL; ops->pointwisemult = VecPointwiseMult_Nest; ops->pointwisedivide = VecPointwiseDivide_Nest; ops->setvalues = NULL; ops->assemblybegin = VecAssemblyBegin_Nest; ops->assemblyend = VecAssemblyEnd_Nest; ops->getarray = VecGetArray_Nest; ops->getsize = VecGetSize_Nest; ops->getlocalsize = VecGetLocalSize_Nest; ops->restorearray = VecRestoreArray_Nest; ops->restorearrayread = VecRestoreArrayRead_Nest; ops->max = VecMax_Nest; ops->min = VecMin_Nest; ops->setrandom = NULL; ops->setoption = NULL; ops->setvaluesblocked = NULL; ops->destroy = VecDestroy_Nest; ops->view = VecView_Nest; ops->placearray = NULL; ops->replacearray = NULL; ops->dot_local = VecDot_Nest; ops->tdot_local = VecTDot_Nest; ops->norm_local = VecNorm_Nest; ops->mdot_local = VecMDot_Nest; ops->mtdot_local = VecMTDot_Nest; ops->load = NULL; ops->reciprocal = VecReciprocal_Nest; ops->conjugate = VecConjugate_Nest; ops->setlocaltoglobalmapping = NULL; ops->setvalueslocal = NULL; ops->resetarray = NULL; ops->setfromoptions = NULL; ops->maxpointwisedivide = VecMaxPointwiseDivide_Nest; ops->load = NULL; ops->pointwisemax = NULL; ops->pointwisemaxabs = NULL; ops->pointwisemin = NULL; ops->getvalues = NULL; ops->sqrt = NULL; ops->abs = NULL; ops->exp = NULL; ops->shift = NULL; ops->create = NULL; ops->stridegather = NULL; ops->stridescatter = NULL; ops->dotnorm2 = VecDotNorm2_Nest; ops->getsubvector = VecGetSubVector_Nest; ops->restoresubvector = VecRestoreSubVector_Nest; ops->axpbypcz = VecAXPBYPCZ_Nest; ops->concatenate = VecConcatenate_Nest; ops->createlocalvector = VecCreateLocalVector_Nest; ops->getlocalvector = VecGetLocalVector_Nest; ops->getlocalvectorread = VecGetLocalVectorRead_Nest; ops->restorelocalvector = VecRestoreLocalVector_Nest; ops->restorelocalvectorread = VecRestoreLocalVectorRead_Nest; ops->setrandom = VecSetRandom_Nest; ops->errorwnorm = VecErrorWeightedNorms_Nest; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecNestGetSubVecs_Private(Vec x, PetscInt m, const PetscInt idxm[], Vec vec[]) { Vec_Nest *b = (Vec_Nest *)x->data; PetscInt i; PetscInt row; PetscFunctionBegin; if (!m) PetscFunctionReturn(PETSC_SUCCESS); for (i = 0; i < m; i++) { row = idxm[i]; PetscCheck(row < b->nb, PetscObjectComm((PetscObject)x), PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, row, b->nb - 1); vec[i] = b->v[row]; } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecNestGetSubVec_Nest(Vec X, PetscInt idxm, Vec *sx) { PetscFunctionBegin; PetscCall(PetscObjectStateIncrease((PetscObject)X)); PetscCall(VecNestGetSubVecs_Private(X, 1, &idxm, sx)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ VecNestGetSubVec - Returns a single, sub-vector from a nest vector. Not Collective Input Parameters: + X - nest vector - idxm - index of the vector within the nest Output Parameter: . sx - vector at index `idxm` within the nest Level: developer .seealso: `VECNEST`, [](ch_vectors), `Vec`, `VecType`, `VecNestGetSize()`, `VecNestGetSubVecs()` @*/ PetscErrorCode VecNestGetSubVec(Vec X, PetscInt idxm, Vec *sx) { PetscFunctionBegin; PetscUseMethod(X, "VecNestGetSubVec_C", (Vec, PetscInt, Vec *), (X, idxm, sx)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecNestGetSubVecs_Nest(Vec X, PetscInt *N, Vec **sx) { Vec_Nest *b = (Vec_Nest *)X->data; PetscFunctionBegin; PetscCall(PetscObjectStateIncrease((PetscObject)X)); if (N) *N = b->nb; if (sx) *sx = b->v; PetscFunctionReturn(PETSC_SUCCESS); } /*@C VecNestGetSubVecs - Returns the entire array of vectors defining a nest vector. Not Collective Input Parameter: . X - nest vector Output Parameters: + N - number of nested vecs - sx - array of vectors Level: developer Note: The user should not free the array `sx`. Fortran Notes: The caller must allocate the array to hold the subvectors. .seealso: `VECNEST`, [](ch_vectors), `Vec`, `VecType`, `VecNestGetSize()`, `VecNestGetSubVec()` @*/ PetscErrorCode VecNestGetSubVecs(Vec X, PetscInt *N, Vec **sx) { PetscFunctionBegin; PetscUseMethod(X, "VecNestGetSubVecs_C", (Vec, PetscInt *, Vec **), (X, N, sx)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecNestSetSubVec_Private(Vec X, PetscInt idxm, Vec x) { Vec_Nest *bx = (Vec_Nest *)X->data; PetscInt i, offset = 0, n = 0, bs; IS is; PetscBool issame = PETSC_FALSE; PetscInt N = 0; PetscFunctionBegin; /* check if idxm < bx->nb */ PetscCheck(idxm < bx->nb, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Out of range index value %" PetscInt_FMT " maximum %" PetscInt_FMT, idxm, bx->nb); PetscCall(VecDestroy(&bx->v[idxm])); /* destroy the existing vector */ PetscCall(VecDuplicate(x, &bx->v[idxm])); /* duplicate the layout of given vector */ PetscCall(VecCopy(x, bx->v[idxm])); /* copy the contents of the given vector */ /* check if we need to update the IS for the block */ offset = X->map->rstart; for (i = 0; i < idxm; i++) { n = 0; PetscCall(VecGetLocalSize(bx->v[i], &n)); offset += n; } /* get the local size and block size */ PetscCall(VecGetLocalSize(x, &n)); PetscCall(VecGetBlockSize(x, &bs)); /* create the new IS */ PetscCall(ISCreateStride(PetscObjectComm((PetscObject)x), n, offset, 1, &is)); PetscCall(ISSetBlockSize(is, bs)); /* check if they are equal */ PetscCall(ISEqual(is, bx->is[idxm], &issame)); if (!issame) { /* The IS of given vector has a different layout compared to the existing block vector. Destroy the existing reference and update the IS. */ PetscCall(ISDestroy(&bx->is[idxm])); PetscCall(ISDuplicate(is, &bx->is[idxm])); PetscCall(ISCopy(is, bx->is[idxm])); offset += n; /* Since the current IS[idxm] changed, we need to update all the subsequent IS */ for (i = idxm + 1; i < bx->nb; i++) { /* get the local size and block size */ PetscCall(VecGetLocalSize(bx->v[i], &n)); PetscCall(VecGetBlockSize(bx->v[i], &bs)); /* destroy the old and create the new IS */ PetscCall(ISDestroy(&bx->is[i])); PetscCall(ISCreateStride(((PetscObject)bx->v[i])->comm, n, offset, 1, &bx->is[i])); PetscCall(ISSetBlockSize(bx->is[i], bs)); offset += n; } n = 0; PetscCall(VecSize_Nest_Recursive(X, PETSC_TRUE, &N)); PetscCall(VecSize_Nest_Recursive(X, PETSC_FALSE, &n)); PetscCall(PetscLayoutSetSize(X->map, N)); PetscCall(PetscLayoutSetLocalSize(X->map, n)); } PetscCall(ISDestroy(&is)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecNestSetSubVec_Nest(Vec X, PetscInt idxm, Vec sx) { PetscFunctionBegin; PetscCall(PetscObjectStateIncrease((PetscObject)X)); PetscCall(VecNestSetSubVec_Private(X, idxm, sx)); PetscFunctionReturn(PETSC_SUCCESS); } /*@ VecNestSetSubVec - Set a single component vector in a nest vector at specified index. Not Collective Input Parameters: + X - nest vector . idxm - index of the vector within the nest vector - sx - vector at index `idxm` within the nest vector Level: developer Note: The new vector `sx` does not have to be of same size as X[idxm]. Arbitrary vector layouts are allowed. .seealso: `VECNEST`, [](ch_vectors), `Vec`, `VecType`, `VecNestSetSubVecs()`, `VecNestGetSubVec()` @*/ PetscErrorCode VecNestSetSubVec(Vec X, PetscInt idxm, Vec sx) { PetscFunctionBegin; PetscUseMethod(X, "VecNestSetSubVec_C", (Vec, PetscInt, Vec), (X, idxm, sx)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecNestSetSubVecs_Nest(Vec X, PetscInt N, PetscInt *idxm, Vec *sx) { PetscInt i; PetscFunctionBegin; PetscCall(PetscObjectStateIncrease((PetscObject)X)); for (i = 0; i < N; i++) PetscCall(VecNestSetSubVec_Private(X, idxm[i], sx[i])); PetscFunctionReturn(PETSC_SUCCESS); } /*@C VecNestSetSubVecs - Sets the component vectors at the specified indices in a nest vector. Not Collective Input Parameters: + X - nest vector . N - number of component vecs in `sx` . idxm - indices of component vectors that are to be replaced - sx - array of vectors Level: developer Note: The components in the vector array `sx` do not have to be of the same size as corresponding components in `X`. The user can also free the array `sx` after the call. .seealso: `VECNEST`, [](ch_vectors), `Vec`, `VecType`, `VecNestGetSize()`, `VecNestGetSubVec()` @*/ PetscErrorCode VecNestSetSubVecs(Vec X, PetscInt N, PetscInt *idxm, Vec *sx) { PetscFunctionBegin; PetscUseMethod(X, "VecNestSetSubVecs_C", (Vec, PetscInt, PetscInt *, Vec *), (X, N, idxm, sx)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecNestGetSize_Nest(Vec X, PetscInt *N) { Vec_Nest *b = (Vec_Nest *)X->data; PetscFunctionBegin; *N = b->nb; PetscFunctionReturn(PETSC_SUCCESS); } /*@ VecNestGetSize - Returns the size of the nest vector. Not Collective Input Parameter: . X - nest vector Output Parameter: . N - number of nested vecs Level: developer .seealso: `VECNEST`, [](ch_vectors), `Vec`, `VecType`, `VecNestGetSubVec()`, `VecNestGetSubVecs()` @*/ PetscErrorCode VecNestGetSize(Vec X, PetscInt *N) { PetscFunctionBegin; PetscValidHeaderSpecific(X, VEC_CLASSID, 1); PetscAssertPointer(N, 2); PetscUseMethod(X, "VecNestGetSize_C", (Vec, PetscInt *), (X, N)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecSetUp_Nest_Private(Vec V, PetscInt nb, Vec x[]) { Vec_Nest *ctx = (Vec_Nest *)V->data; PetscInt i; PetscFunctionBegin; if (ctx->setup_called) PetscFunctionReturn(PETSC_SUCCESS); ctx->nb = nb; PetscCheck(ctx->nb >= 0, PetscObjectComm((PetscObject)V), PETSC_ERR_ARG_WRONG, "Cannot create VECNEST with < 0 blocks."); /* Create space */ PetscCall(PetscMalloc1(ctx->nb, &ctx->v)); for (i = 0; i < ctx->nb; i++) { ctx->v[i] = x[i]; PetscCall(PetscObjectReference((PetscObject)x[i])); /* Do not allocate memory for internal sub blocks */ } PetscCall(PetscMalloc1(ctx->nb, &ctx->is)); ctx->setup_called = PETSC_TRUE; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode VecSetUp_NestIS_Private(Vec V, PetscInt nb, IS is[]) { Vec_Nest *ctx = (Vec_Nest *)V->data; PetscInt i, offset, m, n, M, N; PetscFunctionBegin; (void)nb; if (is) { /* Do some consistency checks and reference the is */ offset = V->map->rstart; for (i = 0; i < ctx->nb; i++) { PetscCall(ISGetSize(is[i], &M)); PetscCall(VecGetSize(ctx->v[i], &N)); PetscCheck(M == N, PetscObjectComm((PetscObject)V), PETSC_ERR_ARG_INCOMP, "In slot %" PetscInt_FMT ", IS of size %" PetscInt_FMT " is not compatible with Vec of size %" PetscInt_FMT, i, M, N); PetscCall(ISGetLocalSize(is[i], &m)); PetscCall(VecGetLocalSize(ctx->v[i], &n)); PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "In slot %" PetscInt_FMT ", IS of local size %" PetscInt_FMT " is not compatible with Vec of local size %" PetscInt_FMT, i, m, n); PetscCall(PetscObjectReference((PetscObject)is[i])); ctx->is[i] = is[i]; offset += n; } } else { /* Create a contiguous ISStride for each entry */ offset = V->map->rstart; for (i = 0; i < ctx->nb; i++) { PetscInt bs; PetscCall(VecGetLocalSize(ctx->v[i], &n)); PetscCall(VecGetBlockSize(ctx->v[i], &bs)); PetscCall(ISCreateStride(((PetscObject)ctx->v[i])->comm, n, offset, 1, &ctx->is[i])); PetscCall(ISSetBlockSize(ctx->is[i], bs)); offset += n; } } PetscFunctionReturn(PETSC_SUCCESS); } /*MC VECNEST - VECNEST = "nest" - Vector type consisting of nested subvectors, each stored separately. Level: intermediate Notes: This vector type reduces the number of copies for certain solvers applied to multi-physics problems. It is usually used with `MATNEST` and `DMCOMPOSITE` via `DMSetVecType()`. .seealso: [](ch_vectors), `Vec`, `VecType`, `VecCreate()`, `VecType`, `VecCreateNest()`, `MatCreateNest()` M*/ /*@C VecCreateNest - Creates a new vector containing several nested subvectors, each stored separately Collective Input Parameters: + comm - Communicator for the new `Vec` . nb - number of nested blocks . is - array of `nb` index sets describing each nested block, or `NULL` to pack subvectors contiguously - x - array of `nb` sub-vectors Output Parameter: . Y - new vector Level: advanced .seealso: `VECNEST`, [](ch_vectors), `Vec`, `VecType`, `VecCreate()`, `MatCreateNest()`, `DMSetVecType()` @*/ PetscErrorCode VecCreateNest(MPI_Comm comm, PetscInt nb, IS is[], Vec x[], Vec *Y) { Vec V; Vec_Nest *s; PetscInt n, N; PetscFunctionBegin; PetscCall(VecCreate(comm, &V)); PetscCall(PetscObjectChangeTypeName((PetscObject)V, VECNEST)); /* allocate and set pointer for implementation data */ PetscCall(PetscNew(&s)); V->data = (void *)s; s->setup_called = PETSC_FALSE; s->nb = -1; s->v = NULL; PetscCall(VecSetUp_Nest_Private(V, nb, x)); n = N = 0; PetscCall(VecSize_Nest_Recursive(V, PETSC_TRUE, &N)); PetscCall(VecSize_Nest_Recursive(V, PETSC_FALSE, &n)); PetscCall(PetscLayoutSetSize(V->map, N)); PetscCall(PetscLayoutSetLocalSize(V->map, n)); PetscCall(PetscLayoutSetBlockSize(V->map, 1)); PetscCall(PetscLayoutSetUp(V->map)); PetscCall(VecSetUp_NestIS_Private(V, nb, is)); PetscCall(VecNestSetOps_Private(V->ops)); V->petscnative = PETSC_FALSE; /* expose block api's */ PetscCall(PetscObjectComposeFunction((PetscObject)V, "VecNestGetSubVec_C", VecNestGetSubVec_Nest)); PetscCall(PetscObjectComposeFunction((PetscObject)V, "VecNestGetSubVecs_C", VecNestGetSubVecs_Nest)); PetscCall(PetscObjectComposeFunction((PetscObject)V, "VecNestSetSubVec_C", VecNestSetSubVec_Nest)); PetscCall(PetscObjectComposeFunction((PetscObject)V, "VecNestSetSubVecs_C", VecNestSetSubVecs_Nest)); PetscCall(PetscObjectComposeFunction((PetscObject)V, "VecNestGetSize_C", VecNestGetSize_Nest)); *Y = V; PetscFunctionReturn(PETSC_SUCCESS); }
2.421875
2
2024-11-18T21:09:16.745539+00:00
2017-12-12T13:35:23
545c7b296300d1244ac74423c8d57678e197bf3f
{ "blob_id": "545c7b296300d1244ac74423c8d57678e197bf3f", "branch_name": "refs/heads/master", "committer_date": "2017-12-12T13:35:23", "content_id": "4eb13e22d7f4a9da415f72c41dd3b8ebf1ba95ae", "detected_licenses": [ "Unlicense", "BSD-2-Clause" ], "directory_id": "b9db971eebe2f3d52129004b96cee08971bdd909", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2017-12-12T13:35:18", "gha_event_created_at": "2017-12-12T13:35:18", "gha_language": null, "gha_license_id": null, "github_id": 113994493, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3354, "license": "Unlicense,BSD-2-Clause", "license_type": "permissive", "path": "/examples/console/main.c", "provenance": "stackv2-0065.json.gz:934", "repo_name": "fossabot/platform", "revision_date": "2017-12-12T13:35:23", "revision_id": "44e16f06d2f06c9a2680070988518a3be101aa83", "snapshot_id": "89d225a22b1c6a0812ff0c472feb1c284efc89dd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fossabot/platform/44e16f06d2f06c9a2680070988518a3be101aa83/examples/console/main.c", "visit_date": "2021-05-06T08:43:01.517772" }
stackv2
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org> */ #include <PL/platform_console.h> #include <PL/platform_graphics.h> #include <PL/platform_filesystem.h> #include <PL/platform_display.h> /* Example of console API, minus error handling :) */ #define TITLE "Console" #define WIDTH 1024 #define HEIGHT 768 void Shutdown(void) { plShutdown(); exit(0); } #if 0 void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { if(action != GLFW_PRESS) { return; } switch(key) { default: break; case GLFW_KEY_ESCAPE: { Shutdown(); } case GLFW_KEY_TAB: { plShowConsole(!plIsConsoleVisible()); break; } case GLFW_KEY_1: { plSetupConsole(1); break; } case GLFW_KEY_2: { plSetupConsole(2); break; } case GLFW_KEY_3: { plSetupConsole(3); break; } case GLFW_KEY_4: { plSetupConsole(4); break; } } } #endif int main(int argc, char **argv) { plInitialize(argc, argv); PLWindow *window = plCreateWindow(TITLE, 0, 0, WIDTH, HEIGHT); if(!window) { printf("%s\n", plGetError()); return -1; } plSetupConsole(1); plShowConsole(true); plSetConsoleColour(1, PLColour(128, 128, 0, 128)); plSetConsoleColour(2, PLColour(0, 128, 0, 128)); plSetConsoleColour(3, PLColour(0, 0, 128, 128)); plSetConsoleColour(4, PLColour(0, 0, 0, 128)); plSetDefaultGraphicsState(); plSetClearColour(PLColour(0, 0, 0, 255)); PLCamera *camera = plCreateCamera(); if(camera == NULL) { exit(EXIT_FAILURE); } camera->mode = PL_CAMERA_MODE_ORTHOGRAPHIC; camera->viewport.w = window->width; camera->viewport.h = window->height; #if 1 while(plIsRunning()) { plClearBuffers(PL_BUFFER_COLOUR | PL_BUFFER_DEPTH | PL_BUFFER_STENCIL); plSetupCamera(camera); // todo, input?? plDrawConsole(); plSwapBuffers(window); } Shutdown(); #endif return EXIT_SUCCESS; }
2.125
2
2024-11-18T21:09:16.840811+00:00
2014-10-27T16:21:41
3d64c3cb2a9d232b6228f7e32a365615cca75ed8
{ "blob_id": "3d64c3cb2a9d232b6228f7e32a365615cca75ed8", "branch_name": "refs/heads/master", "committer_date": "2014-10-27T16:21:41", "content_id": "f8f1b7354ed49fa050e817e4443ba417ba56031f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "b27e6f98905a4e9d213010320175111841b6c23e", "extension": "c", "filename": "multiple_qsort.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": 702, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/funnel/temp/multiple_qsort.c", "provenance": "stackv2-0065.json.gz:1062", "repo_name": "bigbes/smth", "revision_date": "2014-10-27T16:21:41", "revision_id": "527f11b739c02d85dfc61a7538bdc534115e74ef", "snapshot_id": "c9f62f497b0be7b99f60345d01312f00b43a987c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bigbes/smth/527f11b739c02d85dfc61a7538bdc534115e74ef/funnel/temp/multiple_qsort.c", "visit_date": "2020-05-30T22:16:34.544523" }
stackv2
#include <assert.h> #include <stdlib.h> #include <stdint.h> #include <math.h> /* Comparing function for qsort */ int compare_int64(const void *p1, const void *p2) { return (*(const int64_t *)p1 > *(const int64_t *)p2); } int main(int argc, char *argv[], char *arge[]) { size_t size = 67108864; // size_t size = (size_t )atoll(getenv("SORT_SIZE")); int64_t *a = calloc(size, sizeof(int64_t)); assert(a); for (int i = 0; i < size; ++i) { int64_t temp = (int64_t )rand(); if (temp < 0) temp *= -1; a[i] = temp + 1; } int i = 0; #pragma omp parallel for private(i), num_threads(4) for (i = 0; i < 1024; ++i) qsort(a + i*size/1024, size/1024, sizeof(int64_t), compare_int64); return 0; }
2.46875
2
2024-11-18T21:09:16.913393+00:00
2023-05-14T06:13:40
d1cb05a21d65e9bd0a5dc1f28bc935c2fc7196f8
{ "blob_id": "d1cb05a21d65e9bd0a5dc1f28bc935c2fc7196f8", "branch_name": "refs/heads/master", "committer_date": "2023-05-14T06:13:40", "content_id": "119ce78dca2083af8ae3f4f8b62d89d9d0048947", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "9264a389f2bd761284f155accdbd190aeaf7eea4", "extension": "h", "filename": "simd_utils_avx512_int32.h", "fork_events_count": 13, "gha_created_at": "2019-10-10T13:26:33", "gha_event_created_at": "2023-09-11T15:50:35", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 214189880, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 41201, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/simd_utils_avx512_int32.h", "provenance": "stackv2-0065.json.gz:1190", "repo_name": "JishinMaster/simd_utils", "revision_date": "2023-05-14T06:13:40", "revision_id": "9f8bc0f1749bcf7b7a7a67830b3d082ea225fc56", "snapshot_id": "8c5896c8eecead341fd3c591b92b66eb9d41b00a", "src_encoding": "UTF-8", "star_events_count": 66, "url": "https://raw.githubusercontent.com/JishinMaster/simd_utils/9f8bc0f1749bcf7b7a7a67830b3d082ea225fc56/simd_utils_avx512_int32.h", "visit_date": "2023-05-27T02:06:20.609996" }
stackv2
/* * Project : SIMD_Utils * Version : 0.2.5 * Author : JishinMaster * Licence : BSD-2 */ #pragma once #include <stdint.h> #include "immintrin.h" static inline void add512s(int32_t *src1, int32_t *src2, int32_t *dst, int len) { int stop_len = len / AVX512_LEN_INT32; stop_len *= AVX512_LEN_INT32; if (areAligned3((uintptr_t) (src1), (uintptr_t) (src2), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { _mm512_store_si512((__m512i *) (dst + i), _mm512_add_epi32(_mm512_load_si512((__m512i *) (src1 + i)), _mm512_load_si512((__m512i *) (src2 + i)))); } } else { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { _mm512_storeu_si512((__m512i *) (dst + i), _mm512_add_epi32(_mm512_loadu_si512((__m512i *) (src1 + i)), _mm512_loadu_si512((__m512i *) (src2 + i)))); } } for (int i = stop_len; i < len; i++) { dst[i] = src1[i] + src2[i]; } } // Works only for Integers stored on 32bits smaller than 16bits static inline void mul512s(int32_t *src1, int32_t *src2, int32_t *dst, int len) { int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (areAligned3((uintptr_t) (src1), (uintptr_t) (src2), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src1_tmp = _mm512_load_si512((__m512i *) (src1 + i)); v16si src2_tmp = _mm512_load_si512((__m512i *) (src2 + i)); v16si src1_tmp2 = _mm512_load_si512((__m512i *) (src1 + i + AVX512_LEN_INT32)); v16si src2_tmp2 = _mm512_load_si512((__m512i *) (src2 + i + AVX512_LEN_INT32)); v16si tmp = _mm512_mullo_epi32(src1_tmp, src2_tmp); v16si tmp2 = _mm512_mullo_epi32(src1_tmp2, src2_tmp2); _mm512_store_si512((__m512i *) (dst + i), tmp); _mm512_store_si512((__m512i *) (dst + i + AVX512_LEN_INT32), tmp2); } } else { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src1_tmp = _mm512_loadu_si512((__m512i *) (src1 + i)); v16si src2_tmp = _mm512_loadu_si512((__m512i *) (src2 + i)); v16si src1_tmp2 = _mm512_loadu_si512((__m512i *) (src1 + i + AVX512_LEN_INT32)); v16si src2_tmp2 = _mm512_loadu_si512((__m512i *) (src2 + i + AVX512_LEN_INT32)); v16si tmp = _mm512_mullo_epi32(src1_tmp, src2_tmp); v16si tmp2 = _mm512_mullo_epi32(src1_tmp2, src2_tmp2); _mm512_storeu_si512((__m512i *) (dst + i), tmp); _mm512_storeu_si512((__m512i *) (dst + i + AVX512_LEN_INT32), tmp2); } } for (int i = stop_len; i < len; i++) { dst[i] = src1[i] * src2[i]; } } static inline void sub512s(int32_t *src1, int32_t *src2, int32_t *dst, int len) { int stop_len = len / AVX512_LEN_INT32; stop_len *= AVX512_LEN_INT32; if (areAligned3((uintptr_t) (src1), (uintptr_t) (src2), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { _mm512_store_si512((__m512i *) (dst + i), _mm512_sub_epi32(_mm512_load_si512((__m512i *) (src1 + i)), _mm512_load_si512((__m512i *) (src2 + i)))); } } else { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { _mm512_storeu_si512((__m512i *) (dst + i), _mm512_sub_epi32(_mm512_loadu_si512((__m512i *) (src1 + i)), _mm512_loadu_si512((__m512i *) (src2 + i)))); } } for (int i = stop_len; i < len; i++) { dst[i] = src1[i] - src2[i]; } } static inline void addc512s(int32_t *src, int32_t value, int32_t *dst, int len) { int stop_len = len / AVX512_LEN_INT32; stop_len *= AVX512_LEN_INT32; const v16si tmp = _mm512_set1_epi32(value); if (areAligned2((uintptr_t) (src), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { _mm512_store_si512((__m512i *) (dst + i), _mm512_add_epi32(tmp, _mm512_load_si512((__m512i *) (src + i)))); } } else { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { _mm512_storeu_si512((__m512i *) (dst + i), _mm512_add_epi32(tmp, _mm512_loadu_si512((__m512i *) (src + i)))); } } for (int i = stop_len; i < len; i++) { dst[i] = src[i] + value; } } static inline void vectorSlope512s(int *dst, int len, int offset, int slope) { v16si coef = _mm512_set_epi32(15 * slope, 14 * slope, 13 * slope, 12 * slope, 11 * slope, 10 * slope, 9 * slope, 8 * slope, 7 * slope, 6 * slope, 5 * slope, 4 * slope, 3 * slope, 2 * slope, slope, 0); v16si slope32_vec = _mm512_set1_epi32(32 * slope); v16si curVal = _mm512_add_epi32(_mm512_set1_epi32(offset), coef); v16si curVal2 = _mm512_add_epi32(_mm512_set1_epi32(offset), coef); curVal2 = _mm512_add_epi32(curVal2, _mm512_set1_epi32(16 * slope)); int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (isAligned((uintptr_t) (dst), AVX512_LEN_BYTES)) { _mm512_store_si512((__m512i *) (dst + 0), curVal); _mm512_store_si512((__m512i *) (dst + AVX512_LEN_INT32), curVal2); } else { _mm512_storeu_si512((__m512i *) (dst + 0), curVal); _mm512_storeu_si512((__m512i *) (dst + AVX512_LEN_INT32), curVal2); } if (isAligned((uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 2 * AVX512_LEN_INT32; i < stop_len; i += 2 * AVX512_LEN_INT32) { curVal = _mm512_add_epi32(curVal, slope32_vec); _mm512_store_si512((__m512i *) (dst + i), curVal); curVal2 = _mm512_add_epi32(curVal2, slope32_vec); _mm512_store_si512((__m512i *) (dst + i + AVX512_LEN_INT32), curVal2); } } else { for (int i = 2 * AVX512_LEN_INT32; i < stop_len; i += 2 * AVX512_LEN_INT32) { curVal = _mm512_add_epi32(curVal, slope32_vec); _mm512_storeu_si512((__m512i *) (dst + i), curVal); curVal2 = _mm512_add_epi32(curVal2, slope32_vec); _mm512_storeu_si512((__m512i *) (dst + i + AVX512_LEN_INT32), curVal2); } } for (int i = stop_len; i < len; i++) { dst[i] = offset + slope * i; } } // Experimental static inline void copy512s(int32_t *src, int32_t *dst, int len) { int stop_len = len / AVX512_LEN_INT32; stop_len *= AVX512_LEN_INT32; if (areAligned2((uintptr_t) (src), (uintptr_t) (dst), AVX512_LEN_BYTES)) { #ifdef OMP #pragma omp parallel for schedule(auto) #endif for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { _mm512_store_si512((__m512i *) (dst + i), _mm512_load_si512((__m512i *) (src + i))); } } else { #ifdef OMP #pragma omp parallel for schedule(auto) #endif for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { _mm512_storeu_si512((__m512i *) (dst + i), _mm512_loadu_si512((__m512i *) (src + i))); } } for (int i = stop_len; i < len; i++) { dst[i] = src[i]; } } static inline void copy512s_2(int32_t *src, int32_t *dst, int len) { int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (areAligned2((uintptr_t) (src), (uintptr_t) (dst), AVX512_LEN_BYTES)) { #ifdef OMP #pragma omp parallel for schedule(auto) #endif for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { __m512i tmp1 = _mm512_load_si512((__m512i *) (src + i)); __m512i tmp2 = _mm512_load_si512((__m512i *) (src + i + AVX512_LEN_INT32)); _mm512_store_si512((__m512i *) (dst + i), tmp1); _mm512_store_si512((__m512i *) (dst + i + AVX512_LEN_INT32), tmp2); } } else { #ifdef OMP #pragma omp parallel for schedule(auto) #endif for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { __m512i tmp1 = _mm512_loadu_si512((__m512i *) (src + i)); __m512i tmp2 = _mm512_loadu_si512((__m512i *) (src + i + AVX512_LEN_INT32)); _mm512_storeu_si512((__m512i *) (dst + i), tmp1); _mm512_storeu_si512((__m512i *) (dst + i + AVX512_LEN_INT32), tmp2); } } #ifdef OMP #pragma omp parallel for schedule(auto) #endif for (int i = stop_len; i < len; i++) { dst[i] = src[i]; } } static inline void fast_copy512s(int32_t *src, int32_t *dst, int len) { int stop_len = len / AVX512_LEN_INT32; stop_len *= AVX512_LEN_INT32; #ifdef OMP #pragma omp parallel for schedule(auto) #endif for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { _mm512_stream_si512((__m512i *) (dst + i), _mm512_stream_load_si512((__m512i *) (src + i))); } _mm_mfence(); for (int i = stop_len; i < len; i++) { dst[i] = src[i]; } } static inline void fast_copy512s_2(int32_t *src, int32_t *dst, int len) { int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); #ifdef OMP #pragma omp parallel for schedule(auto) #endif for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { __m512i tmp1 = _mm512_stream_load_si512((__m512i *) (src + i)); __m512i tmp2 = _mm512_stream_load_si512((__m512i *) (src + i + AVX512_LEN_INT32)); _mm512_stream_si512((__m512i *) (dst + i), tmp1); _mm512_stream_si512((__m512i *) (dst + i + AVX512_LEN_INT32), tmp2); } _mm_mfence(); for (int i = stop_len; i < len; i++) { dst[i] = src[i]; } } static inline void fast_copy512s_4(int32_t *src, int32_t *dst, int len) { int stop_len = len / (4 * AVX512_LEN_INT32); stop_len *= (4 * AVX512_LEN_INT32); #ifdef OMP #pragma omp parallel for schedule(auto) #endif for (int i = 0; i < stop_len; i += 4 * AVX512_LEN_INT32) { __m512i tmp1 = _mm512_stream_load_si512((__m512i *) (src + i)); __m512i tmp2 = _mm512_stream_load_si512((__m512i *) (src + i + AVX512_LEN_INT32)); __m512i tmp3 = _mm512_stream_load_si512((__m512i *) (src + i + 2 * AVX512_LEN_INT32)); __m512i tmp4 = _mm512_stream_load_si512((__m512i *) (src + i + 3 * AVX512_LEN_INT32)); _mm512_stream_si512((__m512i *) (dst + i), tmp1); _mm512_stream_si512((__m512i *) (dst + i + AVX512_LEN_INT32), tmp2); _mm512_stream_si512((__m512i *) (dst + i + 2 * AVX512_LEN_INT32), tmp3); _mm512_stream_si512((__m512i *) (dst + i + 3 * AVX512_LEN_INT32), tmp4); } _mm_mfence(); for (int i = stop_len; i < len; i++) { dst[i] = src[i]; } } static inline __m512i _mm512_absdiff_epi16(__m512i a, __m512i b) { __m512i cmp, difab, difba; __mmask32 cmp_mask = _mm512_cmpgt_epi16_mask(a, b); difab = _mm512_sub_epi16(a, b); difba = _mm512_sub_epi16(b, a); #if 1 // should be faster return _mm512_mask_blend_epi16(cmp_mask, difba, difab); #else __m512i zero = _mm512_setzero_epi32(); cmp = _mm512_mask_set1_epi16(zero, cmp_mask, 0xFFFF); difab = _mm512_and_si512(cmp, difab); difba = _mm512_andnot_si512(cmp, difba); return _mm512_or_si512(difab, difba); #endif } static inline __m512i _mm512_absdiff_epi32(__m512i a, __m512i b) { __m512i cmp, difab, difba; __mmask16 cmp_mask = _mm512_cmpgt_epi32_mask(a, b); difab = _mm512_sub_epi32(a, b); difba = _mm512_sub_epi32(b, a); #if 1 // should be faster return _mm512_mask_blend_epi32(cmp_mask, difba, difab); #else __m512i zero = _mm512_setzero_epi32(); cmp = _mm512_mask_set1_epi32(zero, cmp_mask, 0xFFFFFFFF); difab = _mm512_and_si512(cmp, difab); difba = _mm512_andnot_si512(cmp, difba); return _mm512_or_si512(difab, difba); #endif } static inline __m512i _mm512_absdiff_epi8(__m512i a, __m512i b) { __m512i cmp, difab, difba; __mmask64 cmp_mask = _mm512_cmpgt_epi8_mask(a, b); difab = _mm512_sub_epi8(a, b); difba = _mm512_sub_epi8(b, a); #if 1 // should be faster return _mm512_mask_blend_epi32(cmp_mask, difba, difab); #else __m512i zero = _mm512_setzero_epi32(); cmp = _mm512_mask_set1_epi8(zero, cmp_mask, 0xFF); difab = _mm512_and_si512(cmp, difab); difba = _mm512_andnot_si512(cmp, difba); return _mm512_or_si512(difab, difba); #endif } static inline void absdiff16s_512s(int16_t *src1, int16_t *src2, int16_t *dst, int len) { int stop_len = len / AVX512_LEN_INT16; stop_len *= AVX512_LEN_INT16; if (areAligned3((uintptr_t) (src1), (uintptr_t) (src2), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += AVX512_LEN_INT16) { __m512i a = _mm512_load_si512((__m512i *) (src1 + i)); __m512i b = _mm512_load_si512((__m512i *) (src2 + i)); _mm512_store_si512((__m512i *) (dst + i), _mm512_absdiff_epi16(a, b)); } } else { for (int i = 0; i < stop_len; i += AVX512_LEN_INT16) { __m512i a = _mm512_loadu_si512((__m512i *) (src1 + i)); __m512i b = _mm512_loadu_si512((__m512i *) (src2 + i)); _mm512_storeu_si512((__m512i *) (dst + i), _mm512_absdiff_epi16(a, b)); } } for (int i = stop_len; i < len; i++) { dst[i] = abs(src1[i] - src2[i]); } } static inline void powerspect16s_512s_interleaved(complex16s_t *src, int32_t *dst, int len) { int stop_len = len / AVX512_LEN_INT32; stop_len *= AVX512_LEN_INT32; int j = 0; if (areAligned2((uintptr_t) (src), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { __m512i reim = _mm512_load_si512((__m512i *) ((const int16_t *) src + j)); _mm512_store_si512((__m512i *) (dst + i), _mm512_madd_epi16(reim, reim)); j += AVX512_LEN_INT16; } } else { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { __m512i reim = _mm512_loadu_si512((__m512i *) ((const int16_t *) src + j)); _mm512_storeu_si512((__m512i *) (dst + i), _mm512_madd_epi16(reim, reim)); j += AVX512_LEN_INT16; } } for (int i = stop_len; i < len; i++) { dst[i] = (int32_t) src[i].re * (int32_t) src[i].re + (int32_t) src[i].im * (int32_t) src[i].im; } } static inline void sum16s32s512(int16_t *src, int len, int32_t *dst, int scale_factor) { int stop_len = len / (4 * AVX512_LEN_INT16); stop_len *= (4 * AVX512_LEN_INT16); __attribute__((aligned(AVX512_LEN_BYTES))) int32_t accumulate[AVX512_LEN_INT32] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; int32_t tmp_acc = 0; int16_t scale = 1 << scale_factor; v16si one = _mm512_set1_epi16(1); v16si vec_acc1 = _mm512_setzero_si512(); // initialize the vector accumulator v16si vec_acc2 = _mm512_setzero_si512(); // initialize the vector accumulator if (isAligned((uintptr_t) (src), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += 4 * AVX512_LEN_INT16) { v16si vec_src_tmp = _mm512_load_si512((__m512i *) ((const int16_t *) src + i)); v16si vec_src_tmp2 = _mm512_load_si512((__m512i *) ((const int16_t *) src + i + AVX512_LEN_INT16)); v16si vec_src_tmp3 = _mm512_load_si512((__m512i *) ((const int16_t *) src + i + 2 * AVX512_LEN_INT16)); v16si vec_src_tmp4 = _mm512_load_si512((__m512i *) ((const int16_t *) src + i + 3 * AVX512_LEN_INT16)); vec_src_tmp = _mm512_madd_epi16(vec_src_tmp, one); vec_src_tmp2 = _mm512_madd_epi16(vec_src_tmp2, one); vec_src_tmp3 = _mm512_madd_epi16(vec_src_tmp3, one); vec_src_tmp4 = _mm512_madd_epi16(vec_src_tmp4, one); vec_src_tmp = _mm512_add_epi32(vec_src_tmp, vec_src_tmp2); vec_src_tmp3 = _mm512_add_epi32(vec_src_tmp3, vec_src_tmp4); vec_acc1 = _mm512_add_epi32(vec_src_tmp, vec_acc1); vec_acc2 = _mm512_add_epi32(vec_src_tmp3, vec_acc2); } } else { for (int i = 0; i < stop_len; i += 4 * AVX512_LEN_INT16) { v16si vec_src_tmp = _mm512_loadu_si512((__m512i *) ((const int16_t *) src + i)); v16si vec_src_tmp2 = _mm512_loadu_si512((__m512i *) ((const int16_t *) src + i + AVX512_LEN_INT16)); v16si vec_src_tmp3 = _mm512_loadu_si512((__m512i *) ((const int16_t *) src + i + 2 * AVX512_LEN_INT16)); v16si vec_src_tmp4 = _mm512_loadu_si512((__m512i *) ((const int16_t *) src + i + 3 * AVX512_LEN_INT16)); vec_src_tmp = _mm512_madd_epi16(vec_src_tmp, one); vec_src_tmp2 = _mm512_madd_epi16(vec_src_tmp2, one); vec_src_tmp3 = _mm512_madd_epi16(vec_src_tmp3, one); vec_src_tmp4 = _mm512_madd_epi16(vec_src_tmp4, one); vec_src_tmp = _mm512_add_epi32(vec_src_tmp, vec_src_tmp2); vec_src_tmp3 = _mm512_add_epi32(vec_src_tmp3, vec_src_tmp4); vec_acc1 = _mm512_add_epi32(vec_src_tmp, vec_acc1); vec_acc2 = _mm512_add_epi32(vec_src_tmp3, vec_acc2); } } vec_acc1 = _mm512_add_epi32(vec_acc1, vec_acc2); _mm512_store_si512((v16si *) accumulate, vec_acc1); for (int i = stop_len; i < len; i++) { tmp_acc += (int32_t) src[i]; } tmp_acc = tmp_acc + accumulate[0] + accumulate[1] + accumulate[2] + accumulate[3] + accumulate[4] + accumulate[5] + accumulate[6] + accumulate[7] + accumulate[8] + accumulate[9] + accumulate[10] + accumulate[11] + accumulate[12] + accumulate[13] + accumulate[14] + accumulate[15]; tmp_acc /= scale; *dst = tmp_acc; } static inline void flip512s(int32_t *src, int32_t *dst, int len) { int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); v16si flip_idx = _mm512_set_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); int mini = ((len - 1) < (2 * AVX512_LEN_INT32)) ? (len - 1) : (2 * AVX512_LEN_INT32); for (int i = 0; i < mini; i++) { dst[len - i - 1] = src[i]; } if (areAligned2((uintptr_t) (src), (uintptr_t) (dst + len - AVX512_LEN_INT32), AVX512_LEN_BYTES)) { for (int i = 2 * AVX512_LEN_INT32; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_load_si512((__m512i *) (src + i)); // load a,b,c,d,e,f,g,h v16si src_tmp2 = _mm512_load_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si src_tmp_flip = _mm512_permutex2var_epi32(src_tmp, flip_idx, src_tmp); v16si src_tmp_flip2 = _mm512_permutex2var_epi32(src_tmp2, flip_idx, src_tmp2); _mm512_store_si512((__m512i *) (dst + len - i - AVX512_LEN_INT32), src_tmp_flip); _mm512_store_si512((__m512i *) (dst + len - i - 2 * AVX512_LEN_INT32), src_tmp_flip2); } } else { for (int i = 2 * AVX512_LEN_INT32; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_loadu_si512((__m512i *) (src + i)); // load a,b,c,d,e,f,g,h v16si src_tmp2 = _mm512_loadu_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si src_tmp_flip = _mm512_permutex2var_epi32(src_tmp, flip_idx, src_tmp); v16si src_tmp_flip2 = _mm512_permutex2var_epi32(src_tmp2, flip_idx, src_tmp2); _mm512_storeu_si512((__m512i *) (dst + len - i - AVX512_LEN_INT32), src_tmp_flip); _mm512_storeu_si512((__m512i *) (dst + len - i - 2 * AVX512_LEN_INT32), src_tmp_flip2); } } for (int i = stop_len; i < len; i++) { dst[len - i - 1] = src[i]; } } static inline void maxevery512s(int32_t *src1, int32_t *src2, int32_t *dst, int len) { int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (areAligned3((uintptr_t) (src1), (uintptr_t) (src2), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src1_tmp = _mm512_load_si512((__m512i *) ((const int32_t *) src1 + i)); v16si src2_tmp = _mm512_load_si512((__m512i *) ((const int32_t *) src2 + i)); v16si src1_tmp2 = _mm512_load_si512((__m512i *) ((const int32_t *) src1 + i + AVX512_LEN_INT32)); v16si src2_tmp2 = _mm512_load_si512((__m512i *) ((const int32_t *) src2 + i + AVX512_LEN_INT32)); v16si max1 = _mm512_max_epi32(src1_tmp, src2_tmp); v16si max2 = _mm512_max_epi32(src1_tmp2, src2_tmp2); _mm512_store_si512((__m512i *) (dst + i), max1); _mm512_store_si512((__m512i *) (dst + i + AVX512_LEN_INT32), max2); } } else { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src1_tmp = _mm512_loadu_si512((__m512i *) (src1 + i)); v16si src2_tmp = _mm512_loadu_si512((__m512i *) (src2 + i)); v16si src1_tmp2 = _mm512_loadu_si512((__m512i *) (src1 + i + AVX512_LEN_INT32)); v16si src2_tmp2 = _mm512_loadu_si512((__m512i *) (src2 + i + AVX512_LEN_INT32)); v16si max1 = _mm512_max_epi32(src1_tmp, src2_tmp); v16si max2 = _mm512_max_epi32(src1_tmp2, src2_tmp2); _mm512_storeu_si512((__m512i *) (dst + i), max1); _mm512_storeu_si512((__m512i *) (dst + i + AVX512_LEN_INT32), max2); } } for (int i = stop_len; i < len; i++) { dst[i] = src1[i] > src2[i] ? src1[i] : src2[i]; } } static inline void minevery512s(int32_t *src1, int32_t *src2, int32_t *dst, int len) { int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (areAligned3((uintptr_t) (src1), (uintptr_t) (src2), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src1_tmp = _mm512_load_si512((__m512i *) ((const int32_t *) src1 + i)); v16si src2_tmp = _mm512_load_si512((__m512i *) ((const int32_t *) src2 + i)); v16si src1_tmp2 = _mm512_load_si512((__m512i *) ((const int32_t *) src1 + i + AVX512_LEN_INT32)); v16si src2_tmp2 = _mm512_load_si512((__m512i *) ((const int32_t *) src2 + i + AVX512_LEN_INT32)); v16si min1 = _mm512_min_epi32(src1_tmp, src2_tmp); v16si min2 = _mm512_min_epi32(src1_tmp2, src2_tmp2); _mm512_store_si512((__m512i *) (dst + i), min1); _mm512_store_si512((__m512i *) (dst + i + AVX512_LEN_INT32), min2); } } else { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src1_tmp = _mm512_loadu_si512((__m512i *) (src1 + i)); v16si src2_tmp = _mm512_loadu_si512((__m512i *) (src2 + i)); v16si src1_tmp2 = _mm512_loadu_si512((__m512i *) (src1 + i + AVX512_LEN_INT32)); v16si src2_tmp2 = _mm512_loadu_si512((__m512i *) (src2 + i + AVX512_LEN_INT32)); v16si min1 = _mm512_min_epi32(src1_tmp, src2_tmp); v16si min2 = _mm512_min_epi32(src1_tmp2, src2_tmp2); _mm512_storeu_si512((__m512i *) (dst + i), min1); _mm512_storeu_si512((__m512i *) (dst + i + AVX512_LEN_INT32), min2); } } for (int i = stop_len; i < len; i++) { dst[i] = src1[i] < src2[i] ? src1[i] : src2[i]; } } static inline void minmax512s(int32_t *src, int len, int32_t *min_value, int32_t *max_value) { int stop_len = (len - AVX512_LEN_INT32) / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); stop_len = (stop_len < 0) ? 0 : stop_len; v16si max_v, min_v, max_v2, min_v2; v16si src_tmp, src_tmp2; int32_t min_tmp = src[0]; int32_t max_tmp = src[0]; __attribute__((aligned(SSE_LEN_BYTES))) int32_t max_f[SSE_LEN_INT32]; __attribute__((aligned(SSE_LEN_BYTES))) int32_t min_f[SSE_LEN_INT32]; if (len >= AVX512_LEN_INT32) { if (isAligned((uintptr_t) (src), AVX512_LEN_BYTES)) { src_tmp = _mm512_load_si512((__m512i *) (src + 0)); max_v = src_tmp; min_v = src_tmp; max_v2 = src_tmp; min_v2 = src_tmp; for (int i = AVX512_LEN_INT32; i < stop_len; i += 2 * AVX512_LEN_INT32) { src_tmp = _mm512_load_si512((__m512i *) (src + i)); src_tmp2 = _mm512_load_si512((__m512i *) (src + i + AVX512_LEN_INT32)); max_v = _mm512_max_epi32(max_v, src_tmp); min_v = _mm512_min_epi32(min_v, src_tmp); max_v2 = _mm512_max_epi32(max_v2, src_tmp2); min_v2 = _mm512_min_epi32(min_v2, src_tmp2); } } else { src_tmp = _mm512_loadu_si512((__m512i *) (src + 0)); max_v = src_tmp; min_v = src_tmp; max_v2 = src_tmp; min_v2 = src_tmp; for (int i = AVX512_LEN_INT32; i < stop_len; i += 2 * AVX512_LEN_INT32) { src_tmp = _mm512_loadu_si512((__m512i *) (src + i)); src_tmp2 = _mm512_loadu_si512((__m512i *) (src + i + AVX512_LEN_INT32)); max_v = _mm512_max_epi32(max_v, src_tmp); min_v = _mm512_min_epi32(min_v, src_tmp); max_v2 = _mm512_max_epi32(max_v2, src_tmp2); min_v2 = _mm512_min_epi32(min_v2, src_tmp2); } } max_v = _mm512_max_epi32(max_v, max_v2); min_v = _mm512_min_epi32(min_v, min_v2); v8si max1 = _mm512_castsi512_si256(max_v); v8si min1 = _mm512_castsi512_si256(min_v); v8si max2 = _mm512_extracti32x8_epi32(max_v, 1); v8si min2 = _mm512_extracti32x8_epi32(min_v, 1); max2 = _mm256_max_epi32(max1, max2); min2 = _mm256_min_epi32(min1, min2); v4si max3 = _mm256_castsi256_si128(max2); v4si min3 = _mm256_castsi256_si128(min2); v4si max4 = _mm256_extracti32x4_epi32(max2, 1); v4si min4 = _mm256_extracti32x4_epi32(min2, 1); max4 = _mm_max_epi32(max3, max4); min4 = _mm_min_epi32(min3, min4); _mm_store_si128((__m128i *) (max_f), max4); _mm_store_si128((__m128i *) (min_f), min4); max_tmp = max_f[0]; max_tmp = max_tmp > max_f[1] ? max_tmp : max_f[1]; max_tmp = max_tmp > max_f[2] ? max_tmp : max_f[2]; max_tmp = max_tmp > max_f[3] ? max_tmp : max_f[3]; min_tmp = min_f[0]; min_tmp = min_tmp < min_f[1] ? min_tmp : min_f[1]; min_tmp = min_tmp < min_f[2] ? min_tmp : min_f[2]; min_tmp = min_tmp < min_f[3] ? min_tmp : min_f[3]; } for (int i = stop_len; i < len; i++) { max_tmp = max_tmp > src[i] ? max_tmp : src[i]; min_tmp = min_tmp < src[i] ? min_tmp : src[i]; } *max_value = max_tmp; *min_value = min_tmp; } static inline void threshold512_gt_s(int32_t *src, int32_t *dst, int len, int32_t value) { const v16si tmp = _mm512_set1_epi32(value); int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (areAligned2((uintptr_t) (src), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_load_si512((__m512i *) (src + i)); v16si src_tmp2 = _mm512_load_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si dst_tmp = _mm512_min_epi32(src_tmp, tmp); v16si dst_tmp2 = _mm512_min_epi32(src_tmp2, tmp); _mm512_store_si512((__m512i *) (dst + i), dst_tmp); _mm512_store_si512((__m512i *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } else { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_loadu_si512((__m512i *) (src + i)); v16si src_tmp2 = _mm512_loadu_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si dst_tmp = _mm512_min_epi32(src_tmp, tmp); v16si dst_tmp2 = _mm512_min_epi32(src_tmp2, tmp); _mm512_storeu_si512((__m512i *) (dst + i), dst_tmp); _mm512_storeu_si512((__m512i *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } for (int i = stop_len; i < len; i++) { dst[i] = src[i] < value ? src[i] : value; } } static inline void threshold512_gtabs_s(int32_t *src, int32_t *dst, int len, int32_t value) { const v16si pval = _mm512_set1_epi32(value); const v16si mval = _mm512_set1_epi32(-value); int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (areAligned2((uintptr_t) (src), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_load_si512((__m512i *) (src + i)); v16si src_tmp2 = _mm512_load_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si src_abs = _mm512_abs_epi32(src_tmp); v16si src_abs2 = _mm512_abs_epi32(src_tmp2); __mmask16 eqmask = _mm512_cmp_epi32_mask(src_abs, src_tmp, _MM_CMPINT_EQ); // if A = abs(A), then A is >= 0 (mask 0xFFFFFFFF) __mmask16 eqmask2 = _mm512_cmp_epi32_mask(src_abs2, src_tmp2, _MM_CMPINT_EQ); v16si max = _mm512_min_epi32(src_tmp, pval); v16si max2 = _mm512_min_epi32(src_tmp2, pval); v16si min = _mm512_max_epi32(src_tmp, mval); v16si min2 = _mm512_max_epi32(src_tmp2, mval); v16si dst_tmp = _mm512_mask_blend_epi32(eqmask, min, max); v16si dst_tmp2 = _mm512_mask_blend_epi32(eqmask2, min2, max2); _mm512_store_si512((__m512i *) (dst + i), dst_tmp); _mm512_store_si512((__m512i *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } else { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_loadu_si512((__m512i *) (src + i)); v16si src_tmp2 = _mm512_loadu_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si src_abs = _mm512_abs_epi32(src_tmp); v16si src_abs2 = _mm512_abs_epi32(src_tmp2); __mmask16 eqmask = _mm512_cmp_epi32_mask(src_abs, src_tmp, _MM_CMPINT_EQ); // if A = abs(A), then A is >= 0 (mask 0xFFFFFFFF) __mmask16 eqmask2 = _mm512_cmp_epi32_mask(src_abs2, src_tmp2, _MM_CMPINT_EQ); v16si max = _mm512_min_epi32(src_tmp, pval); v16si max2 = _mm512_min_epi32(src_tmp2, pval); v16si min = _mm512_max_epi32(src_tmp, mval); v16si min2 = _mm512_max_epi32(src_tmp2, mval); v16si dst_tmp = _mm512_mask_blend_epi32(eqmask, min, max); v16si dst_tmp2 = _mm512_mask_blend_epi32(eqmask2, min2, max2); _mm512_storeu_si512((__m512i *) (dst + i), dst_tmp); _mm512_storeu_si512((__m512i *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } for (int i = stop_len; i < len; i++) { if (src[i] >= 0) { dst[i] = src[i] > value ? value : src[i]; } else { dst[i] = src[i] < (-value) ? (-value) : src[i]; } } } static inline void threshold512_lt_s(int32_t *src, int32_t *dst, int len, int32_t value) { const v16si tmp = _mm512_set1_epi32(value); int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (areAligned2((uintptr_t) (src), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_load_si512((__m512i *) (src + i)); v16si src_tmp2 = _mm512_load_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si dst_tmp = _mm512_max_epi32(src_tmp, tmp); v16si dst_tmp2 = _mm512_max_epi32(src_tmp2, tmp); _mm512_store_si512((__m512i *) (dst + i), dst_tmp); _mm512_store_si512((__m512i *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } else { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_loadu_si512((__m512i *) (src + i)); v16si src_tmp2 = _mm512_loadu_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si dst_tmp = _mm512_max_epi32(src_tmp, tmp); v16si dst_tmp2 = _mm512_max_epi32(src_tmp2, tmp); _mm512_storeu_si512((__m512i *) (dst + i), dst_tmp); _mm512_storeu_si512((__m512i *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } for (int i = stop_len; i < len; i++) { dst[i] = src[i] > value ? src[i] : value; } } static inline void threshold512_ltabs_s(int32_t *src, int32_t *dst, int len, int32_t value) { const v16si pval = _mm512_set1_epi32(value); const v16si mval = _mm512_set1_epi32(-value); int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (areAligned2((uintptr_t) (src), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_load_si512((__m512i *) (src + i)); v16si src_tmp2 = _mm512_load_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si src_abs = _mm512_abs_epi32(src_tmp); v16si src_abs2 = _mm512_abs_epi32(src_tmp2); __mmask16 eqmask = _mm512_cmp_epi32_mask(src_abs, src_tmp, _MM_CMPINT_EQ); // if A = abs(A), then A is >= 0 (mask 0xFFFFFFFF) __mmask16 eqmask2 = _mm512_cmp_epi32_mask(src_abs2, src_tmp2, _MM_CMPINT_EQ); v16si max = _mm512_max_epi32(src_tmp, pval); v16si max2 = _mm512_max_epi32(src_tmp2, pval); v16si min = _mm512_min_epi32(src_tmp, mval); v16si min2 = _mm512_min_epi32(src_tmp2, mval); v16si dst_tmp = _mm512_mask_blend_epi32(eqmask, min, max); v16si dst_tmp2 = _mm512_mask_blend_epi32(eqmask2, min2, max2); _mm512_store_si512((__m512i *) (dst + i), dst_tmp); _mm512_store_si512((__m512i *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } else { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_loadu_si512((__m512i *) (src + i)); v16si src_tmp2 = _mm512_loadu_si512((__m512i *) (src + i + AVX512_LEN_INT32)); v16si src_abs = _mm512_abs_epi32(src_tmp); v16si src_abs2 = _mm512_abs_epi32(src_tmp2); __mmask16 eqmask = _mm512_cmp_epi32_mask(src_abs, src_tmp, _MM_CMPINT_EQ); // if A = abs(A), then A is >= 0 (mask 0xFFFFFFFF) __mmask16 eqmask2 = _mm512_cmp_epi32_mask(src_abs2, src_tmp2, _MM_CMPINT_EQ); v16si max = _mm512_max_epi32(src_tmp, pval); v16si max2 = _mm512_max_epi32(src_tmp2, pval); v16si min = _mm512_min_epi32(src_tmp, mval); v16si min2 = _mm512_min_epi32(src_tmp2, mval); v16si dst_tmp = _mm512_mask_blend_epi32(eqmask, min, max); v16si dst_tmp2 = _mm512_mask_blend_epi32(eqmask2, min2, max2); _mm512_storeu_si512((__m512i *) (dst + i), dst_tmp); _mm512_storeu_si512((__m512i *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } for (int i = stop_len; i < len; i++) { if (src[i] >= 0) { dst[i] = src[i] < value ? value : src[i]; } else { dst[i] = src[i] > (-value) ? (-value) : src[i]; } } } static inline void threshold512_ltval_gtval_s(int32_t *src, int32_t *dst, int len, int32_t ltlevel, int32_t ltvalue, int32_t gtlevel, int32_t gtvalue) { const v16si ltlevel_v = _mm512_set1_epi32(ltlevel); const v16si ltvalue_v = _mm512_set1_epi32(ltvalue); const v16si gtlevel_v = _mm512_set1_epi32(gtlevel); const v16si gtvalue_v = _mm512_set1_epi32(gtvalue); int stop_len = len / (2 * AVX512_LEN_INT32); stop_len *= (2 * AVX512_LEN_INT32); if (areAligned2((uintptr_t) (src), (uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_load_si512((v16si *) (src + i)); v16si src_tmp2 = _mm512_load_si512((v16si *) (src + i + AVX512_LEN_INT32)); __mmask16 lt_mask = _mm512_cmp_epi32_mask(src_tmp, ltlevel_v, _MM_CMPINT_LT); __mmask16 gt_mask = _mm512_cmp_epi32_mask(src_tmp, gtlevel_v, _MM_CMPINT_NLE); v16si dst_tmp = _mm512_mask_blend_epi32(lt_mask, src_tmp, ltvalue_v); dst_tmp = _mm512_mask_blend_epi32(gt_mask, dst_tmp, gtvalue_v); _mm512_store_si512((v16si *) (dst + i), dst_tmp); __mmask16 lt_mask2 = _mm512_cmp_epi32_mask(src_tmp2, ltlevel_v, _MM_CMPINT_LT); __mmask16 gt_mask2 = _mm512_cmp_epi32_mask(src_tmp2, gtlevel_v, _MM_CMPINT_NLE); v16si dst_tmp2 = _mm512_mask_blend_epi32(lt_mask2, src_tmp2, ltvalue_v); dst_tmp2 = _mm512_mask_blend_epi32(gt_mask2, dst_tmp2, gtvalue_v); _mm512_store_si512((v16si *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } else { for (int i = 0; i < stop_len; i += 2 * AVX512_LEN_INT32) { v16si src_tmp = _mm512_loadu_si512((v16si *) (src + i)); v16si src_tmp2 = _mm512_loadu_si512((v16si *) (src + i + AVX512_LEN_INT32)); __mmask16 lt_mask = _mm512_cmp_epi32_mask(src_tmp, ltlevel_v, _MM_CMPINT_LT); __mmask16 gt_mask = _mm512_cmp_epi32_mask(src_tmp, gtlevel_v, _MM_CMPINT_NLE); v16si dst_tmp = _mm512_mask_blend_epi32(lt_mask, src_tmp, ltvalue_v); dst_tmp = _mm512_mask_blend_epi32(gt_mask, dst_tmp, gtvalue_v); _mm512_storeu_si512((v16si *) (dst + i), dst_tmp); __mmask16 lt_mask2 = _mm512_cmp_epi32_mask(src_tmp2, ltlevel_v, _MM_CMPINT_LT); __mmask16 gt_mask2 = _mm512_cmp_epi32_mask(src_tmp2, gtlevel_v, _MM_CMPINT_NLE); v16si dst_tmp2 = _mm512_mask_blend_epi32(lt_mask2, src_tmp2, ltvalue_v); dst_tmp2 = _mm512_mask_blend_epi32(gt_mask2, dst_tmp2, gtvalue_v); _mm512_storeu_si512((v16si *) (dst + i + AVX512_LEN_INT32), dst_tmp2); } } for (int i = stop_len; i < len; i++) { dst[i] = src[i] < ltlevel ? ltvalue : src[i]; dst[i] = src[i] > gtlevel ? gtvalue : dst[i]; } } // is it useful to unroll? static inline void gatheri_512s(int32_t *src, int32_t *dst, int stride, int offset, int len) { int stop_len = len / (AVX512_LEN_INT32); stop_len *= (AVX512_LEN_INT32); v16si vindex = _mm512_setr_epi32(offset, stride + offset, 2 * stride + offset, 3 * stride + offset, 4 * stride + offset, 5 * stride + offset, 6 * stride + offset, 7 * stride + offset, 8 * stride + offset, 9 * stride + offset, 10 * stride + offset, 11 * stride + offset, 12 * stride + offset, 13 * stride + offset, 14 * stride + offset, 15 * stride + offset); if (isAligned((uintptr_t) (dst), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { v16si tmp = _mm512_i32gather_epi32(vindex, (const int *) (src + i * AVX512_LEN_INT32), 1); _mm512_store_si512((v16si *) (dst + i * AVX512_LEN_INT32), tmp); } } else { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { v16si tmp = _mm512_i32gather_epi32(vindex, (const int *) (src + i * AVX512_LEN_INT32), 1); _mm512_storeu_si512((v16si *) (dst + i * AVX512_LEN_INT32), tmp); } } for (int i = stop_len; i < len; i++) { dst[i] = src[i * stride + offset]; } } // is it useful to unroll? static inline void scatteri_512s(int32_t *src, int32_t *dst, int stride, int offset, int len) { int stop_len = len / (AVX512_LEN_INT32); stop_len *= (AVX512_LEN_INT32); v16si vindex = _mm512_setr_epi32(offset, stride + offset, 2 * stride + offset, 3 * stride + offset, 4 * stride + offset, 5 * stride + offset, 6 * stride + offset, 7 * stride + offset, 8 * stride + offset, 9 * stride + offset, 10 * stride + offset, 11 * stride + offset, 12 * stride + offset, 13 * stride + offset, 14 * stride + offset, 15 * stride + offset); if (isAligned((uintptr_t) (src), AVX512_LEN_BYTES)) { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { v16si tmp = _mm512_load_si512((const int *) (src + i * AVX512_LEN_INT32)); _mm512_i32scatter_epi32((int *) (dst + i * AVX512_LEN_INT32), vindex, tmp, 1); } } else { for (int i = 0; i < stop_len; i += AVX512_LEN_INT32) { v16si tmp = _mm512_loadu_si512((const int *) (src + i * AVX512_LEN_INT32)); _mm512_i32scatter_epi32((int *) (dst + i * AVX512_LEN_INT32), vindex, tmp, 1); } } for (int i = stop_len; i < len; i++) { dst[i] = src[i * stride + offset]; } }
2.5
2
2024-11-18T21:09:17.079801+00:00
2017-04-04T14:49:50
5049ae7a8e76b6bdcd1cf6c7b97b0393d2271c24
{ "blob_id": "5049ae7a8e76b6bdcd1cf6c7b97b0393d2271c24", "branch_name": "refs/heads/master", "committer_date": "2017-04-04T14:49:50", "content_id": "93fa17e56ac2ea3ad3e21fd06abeb9a72d472ee2", "detected_licenses": [ "Unlicense" ], "directory_id": "9c67774e6de2d46701573df5b86a838c5bde0a90", "extension": "c", "filename": "matrix.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": 3415, "license": "Unlicense", "license_type": "permissive", "path": "/src/F38x/matrix.c", "provenance": "stackv2-0065.json.gz:1449", "repo_name": "fuqboyz/ELEC291P2", "revision_date": "2017-04-04T14:49:50", "revision_id": "06e570e2205cbd0a87f7864da14cae3bd6c60243", "snapshot_id": "a6f4de4c7fcc7ce45a996340f8d80dfaab1488e1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fuqboyz/ELEC291P2/06e570e2205cbd0a87f7864da14cae3bd6c60243/src/F38x/matrix.c", "visit_date": "2021-04-06T08:40:34.340627" }
stackv2
// functions containing stuff for LED matrix // Matrix pins #define LED_CS P1_4 #define LED_DATA P1_3 #define LED_CLK P1_2 // libraries #include <stdio.h> #include <c8051f38x.h> #include "robot_header.h" // LED MATRIX IMAGE IN MEMORY (COMPRESSED) unsigned char MX_TURN[8] = {0x10, 0x30, 0x70, 0xFC, 0x76, 0x32, 0x12, 0x02}; unsigned char MX_STOP[2] = {0x37, 0xF8}; unsigned char MX_UTURN[8] = {0x1C, 0x36, 0x22, 0x22, 0x22, 0xFA, 0x72, 0x22}; // reverses the bytes unsigned char reverse(unsigned char b) { b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; b = (b & 0xCC) >> 2 | (b & 0x33) << 2; b = (b & 0xAA) >> 1 | (b & 0x55) << 1; return b; } // mirror the bits unsigned char mirror(unsigned char b, unsigned char upper) { if (upper) return ((reverse(b) & 0x0F) | (b & 0xF0)); else return ((reverse(b) & 0xF0)>>4 | (b & 0x0F)<<4); } // display direction void mxDirection(unsigned char flipped) { // right if (flipped) mxDisplay(MX_TURN, 1); // left else mxDisplay(MX_TURN, 0); } // display stop void mxStop(void) { mxDisplay(MX_STOP, 2); } // display uturn void mxUTurn(void) { mxDisplay(MX_UTURN, 0); } // display some image to the screen // options: 0 - 8 byte full image // 1 - flipped 8 byte full image // 2 - 2 byte image void mxDisplay(unsigned char *grid, unsigned char options) { unsigned char i; // (2 byte images) if (options == 2) { mxWrite(1, mirror(grid[0], 1)); mxWrite(2, mirror(grid[0], 0)); mxWrite(3, mirror(grid[1], 1)); mxWrite(4, mirror(grid[1], 0)); mxWrite(5, mirror(grid[1], 0)); mxWrite(6, mirror(grid[1], 1)); mxWrite(7, mirror(grid[0], 0)); mxWrite(8, mirror(grid[0], 1)); return; } // (8 bytes) for (i = 0; i < 8; i++) { // flipped horizontally <- -> if (options == 1) mxWrite(i+1, reverse(grid[i])); // normal else mxWrite(i+1, grid[i]); } } // write a byte to the MAX7219 void mxWrite(unsigned char address, unsigned char value) { if ((address < 1) || (address > 8)) return; mxSPI(address); mxSPI(value); mxPulse(); } // send one byte void mxSPI(unsigned char value) { unsigned char j, temp; for (j = 0; j < 8; j++) { temp = value & 0x80; LED_DATA = (temp == 0x80) ? HIGH : LOW; // toggle clock LED_CLK = HIGH; Timer3us(20); LED_CLK = LOW; // shift one bit over value = value << 1; } } // send one byte in reverse void mxSPIR(unsigned char value) { unsigned char j, temp; for (j = 0; j < 8; j++) { temp = value & 0x01; LED_DATA = (temp == 0x01) ? HIGH : LOW; // toggle clock LED_CLK = HIGH; Timer3us(20); LED_CLK = LOW; // shift one bit over value = value >> 1; } } // pulse at LED select void mxPulse(void) { LED_CS = HIGH; waitms(1); LED_CS = LOW; } // clear all memory in MAX7219 void mxClear(void) { unsigned char j; for (j = 1; j <= 8; j++) { mxSPI(j); mxSPI(0x00); mxPulse(); } } // set intensity of the LED matrix screen void mxIntensity(unsigned char intensity) { if (intensity > 0x0F) return; mxSPI(0x0A); mxSPI(intensity); mxPulse(); } // initialize matrix void mxInit(void) { // set pin out as open drain P1MDOUT &= 0b_1111_0001; LED_CS = LOW; // set decode mode (no-decode) mxSPI(0x09); mxSPI(0x00); mxPulse(); // set intensity mxSPI(0x0A); mxSPI(0x01); mxPulse(); // set scan limit mxSPI(0x0b); mxSPI(0x07); mxPulse(); // clear memory mxClear(); // set for normal operation mxSPI(0x0C); mxSPI(0x01); mxPulse(); }
2.921875
3
2024-11-18T21:09:17.353721+00:00
2017-05-24T16:18:49
3b367c95536a8e7239d646978721ffe1d69b024c
{ "blob_id": "3b367c95536a8e7239d646978721ffe1d69b024c", "branch_name": "refs/heads/master", "committer_date": "2017-05-24T16:18:49", "content_id": "49709f5017242b7cc760e09e90db0a55e2a2c052", "detected_licenses": [ "MIT" ], "directory_id": "d762099b49fc8a6e4bad96e067f5328d22051794", "extension": "h", "filename": "Vertex.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 26534620, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 416, "license": "MIT", "license_type": "permissive", "path": "/GeneticEvolution2/Vertex.h", "provenance": "stackv2-0065.json.gz:1577", "repo_name": "christiancosgrove/GeneticEvolution", "revision_date": "2017-05-24T16:18:49", "revision_id": "a3669a952b31f32cc2451236c252d23a5cb0b0c8", "snapshot_id": "10fe7d1adcab3d14cde757f0fa1a4a2041909053", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/christiancosgrove/GeneticEvolution/a3669a952b31f32cc2451236c252d23a5cb0b0c8/GeneticEvolution2/Vertex.h", "visit_date": "2021-06-22T02:27:34.663531" }
stackv2
// // Vertex.h // GeneticEvolution // // Created by Christian Cosgrove on 11/21/14. // Copyright (c) 2014 Christian. All rights reserved. // #pragma once #include "glm/glm.hpp" struct Vertex { glm::vec3 position; glm::vec3 color; Vertex(glm::vec3 pos, glm::vec3 col) : position(pos), color(col) {} Vertex(float x, float y, float z, float r, float g, float b) : position(x,y,z), color(r,g,b) {} };
2.28125
2
2024-11-18T21:09:17.548378+00:00
2013-02-18T01:19:24
238da9f977abd5c4580553be1c0b23d4d5af3ea3
{ "blob_id": "238da9f977abd5c4580553be1c0b23d4d5af3ea3", "branch_name": "refs/heads/master", "committer_date": "2013-02-18T01:19:24", "content_id": "bcc54e99aedf68337cf9f7426c9e939519ef8468", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0ff4f88bed6c524eddc45cdef217a9ece457376d", "extension": "c", "filename": "str.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 8415805, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8865, "license": "Apache-2.0", "license_type": "permissive", "path": "/libchimp/str.c", "provenance": "stackv2-0065.json.gz:1833", "repo_name": "ged/chimp", "revision_date": "2013-02-18T01:19:24", "revision_id": "07a4bba413bd4af53a3b8f97d5f9b01c9b8b951a", "snapshot_id": "7f1ddeb134ebcd01ac75d9daac2a16c994e9b3b3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ged/chimp/07a4bba413bd4af53a3b8f97d5f9b01c9b8b951a/libchimp/str.c", "visit_date": "2023-03-31T07:26:56.936503" }
stackv2
/***************************************************************************** * * * Copyright 2012 Thomas Lee * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *****************************************************************************/ #include "chimp/object.h" #include "chimp/str.h" ChimpRef * chimp_str_new (const char *data, size_t size) { char *copy; copy = CHIMP_MALLOC(char, size + 1); if (copy == NULL) return NULL; memcpy (copy, data, size); copy[size] = '\0'; return chimp_str_new_take (copy, size); } ChimpRef * chimp_str_new_take (char *data, size_t size) { ChimpRef *ref = chimp_gc_new_object (NULL); if (ref == NULL) { return NULL; } CHIMP_ANY(ref)->klass = chimp_str_class; CHIMP_STR(ref)->data = data; CHIMP_STR(ref)->size = size; return ref; } ChimpRef * chimp_str_new_format (const char *fmt, ...) { va_list args; ChimpRef *result; va_start (args, fmt); result = chimp_str_new_formatv (fmt, args); va_end (args); return result; } ChimpRef * chimp_str_new_formatv (const char *fmt, va_list args) { size_t size; va_list args_p; va_copy (args_p, args); size = vsnprintf (NULL, 0, fmt, args); if (size >= 0) { char *buf = CHIMP_MALLOC(char, size + 1); if (buf == NULL) { va_end (args_p); return NULL; } va_end (args); va_copy (args, args_p); va_end (args_p); vsnprintf (buf, size + 1, fmt, args); return chimp_str_new_take (buf, size); } else { va_end (args_p); return NULL; } } ChimpRef * chimp_str_new_concat (const char *a, ...) { va_list args; const char *arg; size_t size = 0; char *ptr, *temp; size_t len; va_start (args, a); size = strlen (a); while ((arg = va_arg(args, const char *)) != NULL) { size += strlen (arg); } va_end (args); temp = ptr = CHIMP_MALLOC(char, size + 1); if (temp == NULL) return NULL; va_start (args, a); len = strlen (a); memcpy (temp, a, len); temp += len; while ((arg = va_arg(args, const char *)) != NULL) { len = strlen (arg); memcpy (temp, arg, len); temp += len; } va_end (args); *temp = '\0'; return chimp_str_new_take (ptr, size); } chimp_bool_t chimp_str_append (ChimpRef *self, ChimpRef *append_me) { ChimpRef *append_str = chimp_object_str (append_me); /* TODO error checking */ char *data = CHIMP_REALLOC (char, CHIMP_STR(self)->data, CHIMP_STR_SIZE(self) + CHIMP_STR_SIZE(append_str) + 1); if (data == NULL) { return CHIMP_FALSE; } CHIMP_STR(self)->data = data; memcpy (CHIMP_STR_DATA(self) + CHIMP_STR_SIZE(self), CHIMP_STR_DATA(append_str), CHIMP_STR_SIZE(append_str)); CHIMP_STR(self)->size += CHIMP_STR_SIZE(append_str); CHIMP_STR(self)->data[CHIMP_STR(self)->size] = '\0'; return CHIMP_TRUE; } chimp_bool_t chimp_str_append_str (ChimpRef *self, const char *s) { /* XXX inefficient */ return chimp_str_append (self, chimp_str_new (s, strlen(s))); } chimp_bool_t chimp_str_append_strn (ChimpRef *self, const char *s, size_t n) { /* XXX inefficient */ return chimp_str_append (self, chimp_str_new (s, n)); } chimp_bool_t chimp_str_append_char (ChimpRef *self, char c) { /* XXX inefficient */ return chimp_str_append (self, chimp_str_new (&c, 1)); } const char * chimp_str_data (ChimpRef *str) { return CHIMP_STR_DATA(str); } static ChimpRef * _chimp_str_size (ChimpRef *self, ChimpRef *args) { return chimp_int_new (CHIMP_STR_SIZE(self)); } static ChimpRef * _chimp_str_index (ChimpRef *self, ChimpRef *args) { const char *needle; const char *res; if (!chimp_method_parse_args (args, "s", &needle)) { return NULL; } res = strstr (CHIMP_STR_DATA(self), needle); if (res == NULL) { return chimp_int_new (-1); } else { return chimp_int_new ((size_t)(res - CHIMP_STR_DATA(self))); } } static ChimpRef * _chimp_str_trim (ChimpRef *self, ChimpRef *args) { size_t i, j; for (i = 0; i < CHIMP_STR_SIZE(self); i++) { if (!isspace (CHIMP_STR(self)->data[i])) { break; } } if (CHIMP_STR_SIZE(self) > 0) { for (j = CHIMP_STR_SIZE(self)-1; j > i; j--) { if (!isspace (CHIMP_STR(self)->data[j])) { break; } } } else { j = 0; } return chimp_str_new (CHIMP_STR_DATA(self) + i, j + 1 - i); } static ChimpRef * _chimp_str_substr (ChimpRef *self, ChimpRef *args) { int64_t i, j; ChimpRef *jobj = NULL; if (!chimp_method_parse_args (args, "I|o", &i, &jobj)) { return NULL; } if (i < 0) { i += CHIMP_STR_SIZE(self); } if (jobj == NULL) { j = CHIMP_STR_SIZE(self); } else { j = CHIMP_INT(jobj)->value; if (j < 0) { j += CHIMP_STR_SIZE(self); } } return chimp_str_new (CHIMP_STR_DATA(self) + i, j - i); } static ChimpRef * _chimp_str_split (ChimpRef *self, ChimpRef *args) { const char *begin; const char *end; const char *sep; size_t seplen; ChimpRef *arr; const size_t len = CHIMP_STR_SIZE(self); size_t n = 0; if (!chimp_method_parse_args (args, "s", &sep)) { return NULL; } /* XXX could pull this directly from the str object */ seplen = strlen (sep); arr = chimp_array_new (); if (arr == NULL) { return NULL; } begin = CHIMP_STR_DATA(self); while (n < len) { ChimpRef *ref; end = strstr (begin + n, sep); if (end == NULL) { end = CHIMP_STR_DATA(self) + CHIMP_STR_SIZE(self); } ref = chimp_str_new (begin + n, (size_t)(end - begin - n)); if (ref == NULL) { return NULL; } if (!chimp_array_push (arr, ref)) { return NULL; } n += CHIMP_STR_SIZE(ref) + seplen; } return arr; } static ChimpRef * _chimp_str_upper (ChimpRef *self, ChimpRef *args) { size_t i; char *data; size_t len = CHIMP_STR_SIZE(self); ChimpRef *str = chimp_str_new (CHIMP_STR_DATA(self), len); data = CHIMP_STR_DATA(str); for (i = 0; i < len; i++) { if (data[i] >= 'a' && data[i] <= 'z') { data[i] -= (char) 0x20; } } return str; } static ChimpRef * _chimp_str_lower (ChimpRef *self, ChimpRef *args) { size_t i; char *data; size_t len = CHIMP_STR_SIZE(self); ChimpRef *str = chimp_str_new (CHIMP_STR_DATA(self), len); data = CHIMP_STR_DATA(str); for (i = 0; i < len; i++) { if (data[i] >= 'A' && data[i] <= 'Z') { data[i] += (char) 0x20; } } return str; } int chimp_str_class_init_2 (void) { if (!chimp_class_add_native_method (chimp_str_class, "size", _chimp_str_size)) { return CHIMP_FALSE; } if (!chimp_class_add_native_method (chimp_str_class, "trim", _chimp_str_trim)) { return CHIMP_FALSE; } if (!chimp_class_add_native_method (chimp_str_class, "index", _chimp_str_index)) { return CHIMP_FALSE; } if (!chimp_class_add_native_method (chimp_str_class, "substr", _chimp_str_substr)) { return CHIMP_FALSE; } if (!chimp_class_add_native_method (chimp_str_class, "split", _chimp_str_split)) { return CHIMP_FALSE; } if (!chimp_class_add_native_method (chimp_str_class, "upper", _chimp_str_upper)) { return CHIMP_FALSE; } if (!chimp_class_add_native_method (chimp_str_class, "lower", _chimp_str_lower)) { return CHIMP_FALSE; } return CHIMP_TRUE; }
2.203125
2
2024-11-18T21:09:18.482531+00:00
2013-12-20T21:27:09
4b835e034a986767a12bfb7cd44bf3c47d187a09
{ "blob_id": "4b835e034a986767a12bfb7cd44bf3c47d187a09", "branch_name": "refs/heads/master", "committer_date": "2013-12-20T21:27:09", "content_id": "f6d265d97e1a60c96100f26cdfabe2206df0af84", "detected_licenses": [ "MIT" ], "directory_id": "043da47d8825018be200680174227adef5456959", "extension": "h", "filename": "matrix44f.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 15337082, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3036, "license": "MIT", "license_type": "permissive", "path": "/lamb/math/matrix44f.h", "provenance": "stackv2-0065.json.gz:2091", "repo_name": "Volcore/es3-ssao", "revision_date": "2013-12-20T21:27:09", "revision_id": "d027cb7790b424c30e69288a452545005fdc2b8a", "snapshot_id": "3a3f9e1542ee9299fc3c0eb0baf72e75a830f9e9", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/Volcore/es3-ssao/d027cb7790b424c30e69288a452545005fdc2b8a/lamb/math/matrix44f.h", "visit_date": "2021-01-06T20:37:48.547024" }
stackv2
/******************************************************************************* Copyright (c) 2010, Limbic Software, Inc. All rights reserved. ******************************************************************************/ #ifndef LAMB_MATH_MATRIX44F_H_ #define LAMB_MATH_MATRIX44F_H_ #include "lamb/codingguides.h" struct Vector3f; struct Vector4f; struct Matrix33f; struct Matrix44f { // Human Readable Matrix // m00 m01 m02 m03 // m10 m11 m12 m13 // m20 m21 m22 m23 // m30 m31 m32 m33 // is stored in memory as // m00 m10 m20 m30 m01 m11 m21 m31 ... // so in the order // 0 4 8 12 // 1 5 9 13 // 2 6 10 14 // 3 7 11 15 union { struct { float m00, m10, m20, m30; float m01, m11, m21, m31; float m02, m12, m22, m32; float m03, m13, m23, m33; }; float m[16]; }; explicit Matrix44f(); explicit Matrix44f(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33); explicit Matrix44f(const float a[16]); // The only non-explicit constructor is the copy constructor Matrix44f(const Matrix44f &a); ~Matrix44f(); void Transpose(); void TransposeFrom(const Matrix44f &a); void TransposeInto(Matrix44f *a) const; static Matrix44f Translation(const float x, const float y, const float z); static Matrix44f Translation(const Vector3f& v); void Translate(const float x, const float y, const float z); void Translate(const Vector3f& v); void glTranslate(const float x, const float y, const float z); void glTranslate(const Vector3f& v); static Matrix44f Scaling(const float x, const float y, const float z); static Matrix44f Scaling(const Vector3f& s); void Scale(const float x, const float y, const float z); void Scale(const Vector3f& s); void glScale(const float x, const float y, const float z); void glScale(const Vector3f& s); static Matrix44f Rotation(const float angle, const Vector3f& axis); void Rotate(const float angle, const Vector3f& axis); void glRotate(const float angle, const Vector3f& axis); void InvertFrom(const Matrix44f& a); void InvertInto(Matrix44f *a) const; void Print(const char *const name = 0) const; static Matrix44f Identity(); static Matrix44f Zero(); // x' = M(x) Vector4f Transform(const Vector4f& vector) const; // x' = M^T(x) Vector4f TransformTransposed(const Vector4f& vector) const; // x_3' = M_33(x_3) Vector3f TransformUpper33(const Vector3f& vector) const; // x_3' = M_33^T(x_3) Vector3f TransformTransposedUpper33(const Vector3f& vector) const; // M = A * B, M(x) = A(B(x)) void Multiply(const Matrix44f& a, const Matrix44f& b); bool EpsilonEqual(const Matrix44f& a, const float epsilon); void glOrthof(float l, float r, float b, float t, float n, float f); void Upper3x3(Matrix33f *m) const; }; #endif // LAMB_MATH_MATRIX44F_H_
2.203125
2
2024-11-18T21:09:18.622359+00:00
2020-02-17T09:35:14
5910188904db139a86b3661192b5e2b18692b0ec
{ "blob_id": "5910188904db139a86b3661192b5e2b18692b0ec", "branch_name": "refs/heads/master", "committer_date": "2020-02-17T09:35:14", "content_id": "d776affc756e236d10781aea6be56146036408c8", "detected_licenses": [ "MIT" ], "directory_id": "b6cd08e111ef200fe739c9bae4383088ff1fe2bb", "extension": "h", "filename": "PID.h", "fork_events_count": 0, "gha_created_at": "2019-11-07T11:04:48", "gha_event_created_at": "2020-02-15T03:15:28", "gha_language": "C", "gha_license_id": "MIT", "github_id": 220216897, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 776, "license": "MIT", "license_type": "permissive", "path": "/最终比赛源码/App/PID.h", "provenance": "stackv2-0065.json.gz:2219", "repo_name": "yirrk/BJTUwh-dlqx-Intelligent-Car", "revision_date": "2020-02-17T09:35:14", "revision_id": "e37ec4e181cc63ddd2472fa34395ddab1312245f", "snapshot_id": "93fe2b5875970d7680297c2dfffb7013af271b3c", "src_encoding": "GB18030", "star_events_count": 2, "url": "https://raw.githubusercontent.com/yirrk/BJTUwh-dlqx-Intelligent-Car/e37ec4e181cc63ddd2472fa34395ddab1312245f/最终比赛源码/App/PID.h", "visit_date": "2020-09-05T21:23:22.001104" }
stackv2
#ifndef __PID_H__ #define __PID_H__ struct PID { float kp; //比例系数 float ki; //积分系数 float kd; //微分系数 float kc; //积分门限 double targetPoint; //目标点 double lastError; //Error[-1] double prevError; //Error[-2] }; void PID_Init(struct PID *this, double targetPoint); double PID_OutputLimit(struct PID *this, double output, float Max, float Min); void PID_SetParameter(struct PID *this, float kp, float ki, float kd, float kc); void PID_SetTargetValue(struct PID *this, double targetPoint); double PID_GetTargetValue(struct PID *this); double PID_IncCalculate(struct PID *this, double samplePoint); #endif
2.140625
2
2024-11-18T21:09:19.458716+00:00
2021-10-10T04:51:52
726e991e3af9ced7779fec965384a370d90a666e
{ "blob_id": "726e991e3af9ced7779fec965384a370d90a666e", "branch_name": "refs/heads/main", "committer_date": "2021-10-10T04:51:52", "content_id": "0b8e2a4bb69636785cd96ea74cb00abc6d99dc65", "detected_licenses": [ "MIT" ], "directory_id": "cadaa9654fa3a29c38ccdbc522e9dd900a70cbe7", "extension": "c", "filename": "logging_util.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 398684312, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 378, "license": "MIT", "license_type": "permissive", "path": "/src/util/logging_util.c", "provenance": "stackv2-0065.json.gz:2475", "repo_name": "EthanDP/ceam-carving", "revision_date": "2021-10-10T04:51:52", "revision_id": "619a6528bab46a643eb85a7db2385ce097b22182", "snapshot_id": "a201a4d65c303a66323e4f1960e55ac612e24b82", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/EthanDP/ceam-carving/619a6528bab46a643eb85a7db2385ce097b22182/src/util/logging_util.c", "visit_date": "2023-08-29T07:14:17.390223" }
stackv2
#include <stdio.h> int logging_mode = 0; int set_logging_mode(int value) { /* * Sets logging mode to verbose (1) or quiet (0) */ logging_mode = value; } void log_message(char *message) { if (logging_mode == 0) { return; } printf("%s", message); } void log_error(char *error) { printf("ERROR: %s\n", error); }
2.734375
3
2024-11-18T21:09:19.573630+00:00
2023-05-31T14:21:53
29b584d36fb4af4f39a00985b547bd06d9eaeef4
{ "blob_id": "29b584d36fb4af4f39a00985b547bd06d9eaeef4", "branch_name": "refs/heads/main", "committer_date": "2023-05-31T14:21:53", "content_id": "6457788babcd650177f694c1bb186a6549a5f8a5", "detected_licenses": [ "MIT" ], "directory_id": "089a5095283e7cd2d23553f17fcc4a2faa1ef98e", "extension": "c", "filename": "0707-design-linked-list.c", "fork_events_count": 0, "gha_created_at": "2023-05-31T13:03:39", "gha_event_created_at": "2023-05-31T13:03:40", "gha_language": null, "gha_license_id": null, "github_id": 647755381, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3067, "license": "MIT", "license_type": "permissive", "path": "/c/0707-design-linked-list.c", "provenance": "stackv2-0065.json.gz:2603", "repo_name": "tonngw/leetcode", "revision_date": "2023-05-31T14:21:53", "revision_id": "2842da53c2da06a39f45d12f3182cb52d1d69f35", "snapshot_id": "e5bb6913eeb764041b221ef975ea703d58da8c4f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tonngw/leetcode/2842da53c2da06a39f45d12f3182cb52d1d69f35/c/0707-design-linked-list.c", "visit_date": "2023-06-05T07:07:45.172410" }
stackv2
typedef struct Node { struct Node* next; struct Node* prev; int val; } Node; typedef struct { Node* head; Node* tail; int length; } MyLinkedList; Node* createNode(int val) { Node* new_node = (Node*)malloc(sizeof(Node) ); new_node->next = NULL; new_node->prev = NULL; new_node->val = val; return new_node; } MyLinkedList* myLinkedListCreate() { MyLinkedList* list = (MyLinkedList*)malloc(sizeof(MyLinkedList) ); list->head = createNode(-1); list->tail = list->head; list->length = 0; return list; } Node* traverseList(MyLinkedList* obj, int index) { if (index < 0 || index >= obj->length) return NULL; Node* trev = obj->head; while (index >= 0) { trev = trev->next; index -= 1; } return trev; } int myLinkedListGet(MyLinkedList* obj, int index) { Node *node = traverseList(obj, index); if (node != NULL) return node->val; return -1; } void myLinkedListAddAtHead(MyLinkedList* obj, int val) { Node* new_node = createNode(val); new_node->next = obj->head->next; new_node->prev = obj->head; obj->head->next = new_node; if (new_node->next != NULL) new_node->next->prev = new_node; else obj->tail = new_node; obj->length += 1; return; } void myLinkedListAddAtTail(MyLinkedList* obj, int val) { Node* new_node = createNode(val); obj->tail->next = new_node; new_node->prev = obj->tail; obj->tail = obj->tail->next; obj->length += 1; return; } void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) { if (index == 0) { myLinkedListAddAtHead(obj, val); return; } else if (index == obj->length) { myLinkedListAddAtTail(obj, val); return; } Node* prev_node = traverseList(obj, index - 1); if (prev_node == NULL) return; Node* new_node = createNode(val); new_node->next = prev_node->next; new_node->prev = prev_node; prev_node->next = new_node; if (new_node->next != NULL) new_node->next->prev = new_node; obj->length += 1; return; } void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) { Node *node = traverseList(obj, index); if (node == NULL) return; Node *temp = node; node->prev->next = node->next; if (node->next != NULL) node->next->prev = node->prev; else obj->tail = node->prev; obj->length -= 1; free(temp); return; } void myLinkedListFree(MyLinkedList* obj) { Node *prev = NULL, *cur = obj->head; while (cur != NULL) { prev = cur; cur = cur->next; free(prev); } free(obj); } /** * Your MyLinkedList struct will be instantiated and called as such: * MyLinkedList* obj = myLinkedListCreate(); * int param_1 = myLinkedListGet(obj, index); * myLinkedListAddAtHead(obj, val); * myLinkedListAddAtTail(obj, val); * myLinkedListAddAtIndex(obj, index, val); * myLinkedListDeleteAtIndex(obj, index); * myLinkedListFree(obj); */
3.265625
3
2024-11-18T21:09:19.851010+00:00
2023-08-29T06:33:10
e3a9ee302a799fa563cd68dfad9d25290b07f33e
{ "blob_id": "e3a9ee302a799fa563cd68dfad9d25290b07f33e", "branch_name": "refs/heads/master", "committer_date": "2023-08-29T06:33:10", "content_id": "f1de41a5713ebacea0797cb66a2ff18ff9e179e7", "detected_licenses": [ "Apache-2.0" ], "directory_id": "676acab8ff535019faff7da3afb8eecc3fa127f5", "extension": "c", "filename": "ppm.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": 2984, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/hal/rc/ppm.c", "provenance": "stackv2-0065.json.gz:2731", "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/src/hal/rc/ppm.c", "visit_date": "2023-09-01T11:37:46.194145" }
stackv2
/****************************************************************************** * Copyright 2022 The Firmament Authors. 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. *****************************************************************************/ #include <string.h> #include "hal/rc/ppm.h" /* 16-bit timer */ #define GET_GAP(x, y) (x > y ? (x - y) : (0xFFFF - y + x)) /** * @brief update ppm decoder status * * @param decoder ppm decoder * @param ic_val input capture value */ void ppm_update(ppm_decoder_t* decoder, uint32_t ic_val) { static uint16_t temp_val[MAX_PPM_CHANNEL]; uint16_t gap; gap = GET_GAP(ic_val, decoder->last_ic); if (gap > decoder->freq_hz / 1000 * 0.9f && gap < decoder->freq_hz / 1000 * 2.1f) { /* valid ppm signal should between 1ms to 2ms */ if (decoder->chan_id < MAX_PPM_CHANNEL) { temp_val[decoder->chan_id] = gap; decoder->chan_id++; } } else { /* sync signal */ if (decoder->chan_id >= 1 && decoder->chan_id <= MAX_PPM_CHANNEL) { /* get total channel count */ decoder->total_chan = decoder->chan_id; } /* if user is reading ppm data while we got a new frame, just drop this frame */ if (decoder->total_chan && decoder->chan_id == decoder->total_chan && !decoder->ppm_reading) { /* reveived all channel data */ for (uint8_t i = 0; i < decoder->total_chan; i++) { decoder->ppm_val[i] = decoder->scale_us * temp_val[i]; if (decoder->ppm_val[i] < 1000) { decoder->ppm_val[i] = 1000; } else if (decoder->ppm_val[i] > 2000) { decoder->ppm_val[i] = 2000; } } decoder->ppm_recvd = 1; } decoder->chan_id = 0; } /* update last capture value */ decoder->last_ic = ic_val; } /** * @brief initialize ppm decoder * * @param decoder ppm decoder * @param freq_hz decoder timer frequency in Hz * @return rt_err_t RT_EOK for success */ rt_err_t ppm_decoder_init(ppm_decoder_t* decoder, uint32_t freq_hz) { decoder->chan_id = 0; decoder->total_chan = 0; decoder->last_ic = 0; decoder->ppm_recvd = 0; decoder->ppm_reading = 0; decoder->freq_hz = freq_hz; decoder->scale_us = 1000000.0f / freq_hz; memset(decoder->ppm_val, 0, sizeof(decoder->ppm_val)); return RT_EOK; }
2.203125
2
2024-11-18T21:09:20.156268+00:00
2022-03-10T21:08:40
cedc613799901b58a4acadce3478fa8c5da63d74
{ "blob_id": "cedc613799901b58a4acadce3478fa8c5da63d74", "branch_name": "refs/heads/main", "committer_date": "2022-03-10T21:08:40", "content_id": "81968004085ad06c1c27def608d233f71a780536", "detected_licenses": [ "MIT" ], "directory_id": "d3e4ff2671841b86dd7744efc770e723a233b1da", "extension": "c", "filename": "mmio.c", "fork_events_count": 11, "gha_created_at": "2016-03-13T11:56:10", "gha_event_created_at": "2021-09-12T16:08:13", "gha_language": "C", "gha_license_id": "MIT", "github_id": 53782623, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1592, "license": "MIT", "license_type": "permissive", "path": "/operatingSystems/ics2015/nemu/src/device/io/mmio.c", "provenance": "stackv2-0065.json.gz:3119", "repo_name": "sabertazimi/hust-lab", "revision_date": "2022-03-10T21:08:40", "revision_id": "1f821fb9f50fa670bd1887d0d99c0bf6ca3c7a31", "snapshot_id": "4a88ce0067c497439c36b9d3b4dd0cfe0682e95e", "src_encoding": "UTF-8", "star_events_count": 37, "url": "https://raw.githubusercontent.com/sabertazimi/hust-lab/1f821fb9f50fa670bd1887d0d99c0bf6ca3c7a31/operatingSystems/ics2015/nemu/src/device/io/mmio.c", "visit_date": "2022-06-11T23:55:02.656231" }
stackv2
#include "common.h" #include "device/mmio.h" #include "misc.h" #define MMIO_SPACE_MAX (256 * 1024) #define NR_MAP 8 static uint8_t mmio_space_pool[MMIO_SPACE_MAX]; static uint32_t mmio_space_free_index = 0; typedef struct { hwaddr_t low; hwaddr_t high; uint8_t *mmio_space; mmio_callback_t callback; } MMIO_t; static MMIO_t maps[NR_MAP]; static int nr_map = 0; /* device interface */ void* add_mmio_map(hwaddr_t addr, size_t len, mmio_callback_t callback) { assert(nr_map < NR_MAP); assert(mmio_space_free_index + len <= MMIO_SPACE_MAX); uint8_t *space_base = &mmio_space_pool[mmio_space_free_index]; maps[nr_map].low = addr; maps[nr_map].high = addr + len - 1; maps[nr_map].mmio_space = space_base; maps[nr_map].callback = callback; nr_map ++; mmio_space_free_index += len; return space_base; } /* bus interface */ int is_mmio(hwaddr_t addr) { int i; for(i = 0; i < nr_map; i ++) { if(addr >= maps[i].low && addr <= maps[i].high) { return i; } } return -1; } uint32_t mmio_read(hwaddr_t addr, size_t len, int map_NO) { assert(len == 1 || len == 2 || len == 4); MMIO_t *map = &maps[map_NO]; uint32_t data = *(uint32_t *)(map->mmio_space + (addr - map->low)) & (~0u >> ((4 - len) << 3)); map->callback(addr, len, false); return data; } void mmio_write(hwaddr_t addr, size_t len, uint32_t data, int map_NO) { assert(len == 1 || len == 2 || len == 4); MMIO_t *map = &maps[map_NO]; uint32_t mask = (~0u >> ((4 - len) << 3)); memcpy_with_mask(map->mmio_space + (addr - map->low), &data, len, (void *)&mask); maps[map_NO].callback(addr, len, true); }
2.625
3
2024-11-18T21:09:20.284056+00:00
2023-05-24T20:22:32
62a2fbf4fe6c1641594d94c59917c74981a35fa6
{ "blob_id": "62a2fbf4fe6c1641594d94c59917c74981a35fa6", "branch_name": "refs/heads/main", "committer_date": "2023-05-24T20:22:32", "content_id": "99c64fa5f88ffd2244d2837d1996f9576902f341", "detected_licenses": [ "MIT" ], "directory_id": "cc56c569de3931944b38ed23671e38e79c15a248", "extension": "c", "filename": "logging.c", "fork_events_count": 19, "gha_created_at": "2013-10-19T18:02:30", "gha_event_created_at": "2023-05-24T20:20:07", "gha_language": "Shell", "gha_license_id": "NOASSERTION", "github_id": 13705957, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2704, "license": "MIT", "license_type": "permissive", "path": "/src/logging.c", "provenance": "stackv2-0065.json.gz:3247", "repo_name": "nerves-project/erlinit", "revision_date": "2023-05-24T20:22:32", "revision_id": "77101dba98d44e88bf95b8801e203916424ca304", "snapshot_id": "7d82f855b8d6680f66fb9be9bd669f4c6aa3bd28", "src_encoding": "UTF-8", "star_events_count": 76, "url": "https://raw.githubusercontent.com/nerves-project/erlinit/77101dba98d44e88bf95b8801e203916424ca304/src/logging.c", "visit_date": "2023-06-11T04:04:33.660403" }
stackv2
/* The MIT License (MIT) Copyright (c) 2013-16 Frank Hunleth 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 "erlinit.h" #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/reboot.h> static int format_message(char **strp, const char *fmt, va_list ap) { char *msg; if (vasprintf(&msg, fmt, ap) < 0) { return -1; } int rc = asprintf(strp, PROGRAM_NAME ": %s\n", msg); free(msg); return rc; } static void log_write(const char *str, size_t len) { size_t ignore; int log_fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC); if (log_fd >= 0) { ignore = write(log_fd, str, len); close(log_fd); } else { ignore = write(STDERR_FILENO, str, len); } (void) ignore; } static void log_format(const char *fmt, va_list ap) { char *line; int len = format_message(&line, fmt, ap); if (len >= 0) { log_write(line, len); free(line); } } void debug(const char *fmt, ...) { if (options.verbose) { va_list ap; va_start(ap, fmt); log_format(fmt, ap); va_end(ap); } } void warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); log_format(fmt, ap); va_end(ap); } void fatal(const char *fmt, ...) { log_write("\n\nFATAL ERROR:\n", 18); va_list ap; va_start(ap, fmt); log_format(fmt, ap); va_end(ap); log_write("\n\nCANNOT CONTINUE.\n", 22); // Sleep so that the message can be printed sleep(1); // Halt/reboot/poweroff reboot(options.fatal_reboot_cmd); // Kernel panic if reboot() returns. exit(1); }
2.546875
3
2024-11-18T21:09:20.454922+00:00
2018-07-08T16:35:01
db160948a4687246bf1b6c88de98fdfef9702623
{ "blob_id": "db160948a4687246bf1b6c88de98fdfef9702623", "branch_name": "refs/heads/master", "committer_date": "2018-07-08T16:35:01", "content_id": "3fc0821451cc620a76fb395ad97c813e26fc4c86", "detected_licenses": [ "MIT" ], "directory_id": "a6f9fbd87e8f6c18588d496aec2c28c1d4129933", "extension": "c", "filename": "program.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 132126402, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 975, "license": "MIT", "license_type": "permissive", "path": "/flags/program.c", "provenance": "stackv2-0065.json.gz:3503", "repo_name": "sszost/learning-c", "revision_date": "2018-07-08T16:35:01", "revision_id": "9ad52642d225485cffa87ae6388051cdee26b931", "snapshot_id": "d81877d204b56cbf8a1b70fc7b3fe080ea26f472", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sszost/learning-c/9ad52642d225485cffa87ae6388051cdee26b931/flags/program.c", "visit_date": "2020-03-15T11:42:58.454053" }
stackv2
#include <stdio.h> #define SUNNY 01 // 001 #define RAINING 02 // 010 #define WINDY 04 // 100 struct flags { unsigned is_sunny: 1; unsigned is_raining: 1; unsigned is_windy: 1; }; typedef struct flags flags_t; void forecast_flags( flags_t f ) { // test if any of the fs are set // test if none of the f are set if( ( f.is_sunny | f.is_raining ) != 0 && ( f.is_windy ) == 0 ) { printf( "%s\n", "take umbrella" ); } else { printf( "%s\n", "dont take umbrella" ); } } void forecast( char f ) { // test if any of the fs are set // test if none of the f are set if( ( f & ( SUNNY | RAINING ) ) != 0 && ( f & WINDY ) == 0 ) { printf( "%s\n", "take umbrella" ); } else { printf( "%s\n", "dont take umbrella" ); } } int main( int argc, char *argv[] ) { // set flags forecast( RAINING | WINDY ); // 110 forecast( RAINING | SUNNY ); // 011 forecast_flags( ( flags_t ) { 0, 1, 1 } ); forecast_flags( ( flags_t ) { 1, 1, 0 } ); return 0; }
2.78125
3
2024-11-18T21:09:21.256750+00:00
2019-08-06T14:24:54
3c20a57d2218c3cd5a3adf46eeb4943f60db8db6
{ "blob_id": "3c20a57d2218c3cd5a3adf46eeb4943f60db8db6", "branch_name": "refs/heads/master", "committer_date": "2019-08-06T14:24:54", "content_id": "a720c9e92df7fa093087bb0bd13d7d14d39fda77", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "021a3ccdcb91d84629f1de7343981b572840b169", "extension": "c", "filename": "ex22.c", "fork_events_count": 8, "gha_created_at": "2016-02-22T11:40:41", "gha_event_created_at": "2023-04-11T09:20:08", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 52269402, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2463, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/sys/examples/tests/ex22.c", "provenance": "stackv2-0065.json.gz:3632", "repo_name": "firedrakeproject/petsc", "revision_date": "2019-08-06T14:24:54", "revision_id": "7afe75c1a0a66862f32d7a0f5c0c5ae5079c4c77", "snapshot_id": "dcf7b32e83bdc88d37099904960d7a4c3c4a89e4", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/firedrakeproject/petsc/7afe75c1a0a66862f32d7a0f5c0c5ae5079c4c77/src/sys/examples/tests/ex22.c", "visit_date": "2023-08-31T22:16:45.175956" }
stackv2
static char help[] = "Tests the PetscByteSwap()\n"; #include <petscsys.h> int main(int argc,char **argv) { PetscErrorCode ierr; PetscInt oint[2],sint[2]; PetscBool obool[2],sbool[2]; PetscScalar oscalar[2],sscalar[2]; double odouble[2],sdouble[2]; float ofloat[2],sfloat[2]; short oshort[2],sshort[2]; ierr = PetscInitialize(&argc,&argv,(char*)0,help);if (ierr) return ierr; sint[0] = oint[0] = 5; sint[1] = oint[1] = 19; sbool[0] = obool[0] = PETSC_FALSE; sbool[1] = obool[1] = PETSC_TRUE; sscalar[0] = oscalar[0] = 3.14159265; sscalar[1] = oscalar[1] = 1.3806504e-23; sdouble[0] = odouble[0] = 3.14159265; sdouble[1] = odouble[1] = 1.3806504e-23; sfloat[0] = ofloat[0] = 3.14159265; sfloat[1] = ofloat[1] = 1.3806504e-23; sshort[0] = oshort[0] = 5; sshort[1] = oshort[1] = 19; ierr = PetscByteSwap(sint,PETSC_INT,2);CHKERRQ(ierr); ierr = PetscByteSwap(sbool,PETSC_BOOL,2);CHKERRQ(ierr); ierr = PetscByteSwap(sscalar,PETSC_SCALAR,2);CHKERRQ(ierr); ierr = PetscByteSwap(sdouble,PETSC_DOUBLE,2);CHKERRQ(ierr); ierr = PetscByteSwap(sfloat,PETSC_FLOAT,2);CHKERRQ(ierr); ierr = PetscByteSwap(sshort,PETSC_SHORT,2);CHKERRQ(ierr); ierr = PetscByteSwap(sint,PETSC_INT,2);CHKERRQ(ierr); ierr = PetscByteSwap(sbool,PETSC_BOOL,2);CHKERRQ(ierr); ierr = PetscByteSwap(sscalar,PETSC_SCALAR,2);CHKERRQ(ierr); ierr = PetscByteSwap(sdouble,PETSC_DOUBLE,2);CHKERRQ(ierr); ierr = PetscByteSwap(sfloat,PETSC_FLOAT,2);CHKERRQ(ierr); ierr = PetscByteSwap(sshort,PETSC_SHORT,2);CHKERRQ(ierr); if ((sint[0] !=oint[0])|| (sint[1] != oint[1])) PetscPrintf(PETSC_COMM_SELF,"Byteswap mismatch for PETSC_INT\n"); if ((sbool[0] !=obool[0])|| (sbool[1] != obool[1])) PetscPrintf(PETSC_COMM_SELF,"Byteswap mismatch for PETSC_BOOL\n"); if ((sscalar[0] !=oscalar[0])|| (sscalar[1] != oscalar[1])) PetscPrintf(PETSC_COMM_SELF,"Byteswap mismatch for PETSC_SCALAR\n"); if ((sdouble[0] !=odouble[0])|| (sdouble[1] != odouble[1])) PetscPrintf(PETSC_COMM_SELF,"Byteswap mismatch for PETSC_DOUBLE\n"); if ((sfloat[0] !=ofloat[0])|| (sfloat[1] != ofloat[1])) PetscPrintf(PETSC_COMM_SELF,"Byteswap mismatch for PETSC_FLOAT\n"); if ((sshort[0] !=oshort[0])|| (sshort[1] != oshort[1])) PetscPrintf(PETSC_COMM_SELF,"Byteswap mismatch for PETSC_SHORT\n"); ierr = PetscFinalize(); return ierr; } /*TEST test: TEST*/
2.453125
2
2024-11-18T21:09:22.781966+00:00
2019-08-06T07:35:08
ebc409fb2629747dc4f915ceb6f52ae47089128a
{ "blob_id": "ebc409fb2629747dc4f915ceb6f52ae47089128a", "branch_name": "refs/heads/master", "committer_date": "2019-08-06T07:35:08", "content_id": "9eed9f2f8a00da687c1973526e78f5ae6f08e2f7", "detected_licenses": [ "MIT" ], "directory_id": "9d8178f3401860259e8e27220cb2e9e035a0af44", "extension": "c", "filename": "main.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 176683257, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9174, "license": "MIT", "license_type": "permissive", "path": "/Board_STM32Cube_Code/STM32F103C8/Src/main.c", "provenance": "stackv2-0065.json.gz:4018", "repo_name": "Xcping2013/RTT_BSP_APP", "revision_date": "2019-08-06T07:35:08", "revision_id": "f9fc1af0360da0f35cd5ef317cef5a330a10a8e1", "snapshot_id": "bdbeec94b9b616810792a93fc1524af77d33ef3c", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Xcping2013/RTT_BSP_APP/f9fc1af0360da0f35cd5ef317cef5a330a10a8e1/Board_STM32Cube_Code/STM32F103C8/Src/main.c", "visit_date": "2020-04-30T07:24:08.961318" }
stackv2
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "i2c.h" #include "iwdg.h" #include "spi.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include <stdlib.h> #include <stddef.h> #include <string.h> #include "TM1638.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ uint8_t USART_RX_BUF[USART_REC_LEN]; uint16_t USART_RX_STA=0; uint16_t display_num[10]={C7_0,C7_1,C7_2,C7_3,C7_4,C7_5,C7_6,C7_7,C7_8,C7_9}; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ uint32_t tickLedstart; /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); // MX_I2C1_Init(); // MX_IWDG_Init(); MX_USART1_UART_Init(); // MX_SPI1_Init(); // MX_I2C2_Init(); /* USER CODE BEGIN 2 */ __HAL_UART_ENABLE_IT(&huart1, UART_IT_RXNE); TM1638_init(); tickLedstart=HAL_GetTick(); TM1638_writeData(display_num[9], SEG_BIT1); TM1638_writeData(display_num[1], SEG_BIT2); TM1638_writeData(display_num[0], SEG_BIT3); TM1638_writeData(display_num[2], SEG_BIT4); printf("mcu init ok\r\n"); printf("if you see this string , the cable RX is OK\r\n"); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ CommandCheckAndExe(); if(abs((int)(HAL_GetTick()-tickLedstart))>800) { HAL_GPIO_TogglePin(SYS_LED_GPIO_Port,SYS_LED_Pin); tickLedstart=HAL_GetTick(); if(cable_rx_ok==1) printf("if you see this string 线材通讯OK 调试板的LED需要亮\r\n"); // printf("if you see this string , the cable RX is OK...线材接收OK...上位机发送字符串来验证Tx是否OK\r\n"); //printf("\r\n"); } } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI|RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.LSIState = RCC_LSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ void CommandCheckAndExe(void) { uint8_t len; if(USART_RX_STA&0x8000) //接收到\r\n { len=USART_RX_STA&0x3fff; //得到此次接收到的数据长度 USART_RX_BUF[len]='\0'; //在末尾加入结束符. printf((char*)USART_RX_BUF); printf("\n"); if(USART_RX_BUF[0]=='\0') printf("\n"); else if(ProcessCommand((char*)USART_RX_BUF)) ; else printf("<NA>\n"); printf(">>"); USART_RX_STA=0; } } uint8_t cable_rx_ok=0; uint8_t ProcessCommand(char *Commands) { //MakeLowercase(Commands); // if (CommmandLine_help(Commands)==1) return 1; // // else if(strcmp("reset", Commands)==0) { ResetCPU(TRUE); return 1; } ////board iO test // else if(strcmp("io test", Commands)==0) { Board_debugFlag=1;ProID=PROJECT_NONE; printf("OK\n"); return 1; } ////Project switch // else if(strcmp("type[basic]", Commands)==0) { AT24CXX_WriteOneByte(ADDR_PROJECT_ID,BASIC_APP); printf("OK\n"); return 1; } // else if(strcmp("type[button online]", Commands)==0) { AT24CXX_WriteOneByte(ADDR_PROJECT_ID,BUTTON_ONLINE); printf("OK\n"); return 1; } // else if(strcmp("type[button offline]",Commands)==0) { AT24CXX_WriteOneByte(ADDR_PROJECT_ID,BUTTON_OFFLINE); printf("OK\n"); return 1; } // else if(strcmp("type[button ver3]", Commands)==0) { AT24CXX_WriteOneByte(ADDR_PROJECT_ID,BUTTON_VER3); printf("OK\n"); return 1; } // else if(strcmp("type[road]", Commands)==0) { AT24CXX_WriteOneByte(ADDR_PROJECT_ID,BUTTON_ROAD); printf("OK\n"); return 1; } // else if(strcmp("type[lidopen]", Commands)==0) { AT24CXX_WriteOneByte(ADDR_PROJECT_ID,LIDOPEN); printf("OK\n"); return 1; } // else if(strcmp("type[jabil lcr]", Commands)==0) { AT24CXX_WriteOneByte(ADDR_PROJECT_ID,JABIL_LCR); printf("OK\n"); return 1; } if(strcmp("display 6666 via uart", Commands)==0) { TM1638_writeData(C7_6, SEG_BIT1); TM1638_writeData(C7_6, SEG_BIT2); TM1638_writeData(C7_6, SEG_BIT3); TM1638_writeData(C7_6, SEG_BIT4); return 1; } if(strcmp("display 0000 via uart", Commands)==0) { TM1638_writeData(C7_0, SEG_BIT1); TM1638_writeData(C7_0, SEG_BIT2); TM1638_writeData(C7_0, SEG_BIT3); TM1638_writeData(C7_0, SEG_BIT4); return 1; } if(strlen(Commands)==4 ) { TM1638_writeData(display_num[Commands[0]-'0'], SEG_BIT4); TM1638_writeData(display_num[Commands[1]-'0'], SEG_BIT3); TM1638_writeData(display_num[Commands[2]-'0'], SEG_BIT2); TM1638_writeData(display_num[Commands[3]-'0'], SEG_BIT1); return 1; } else if(strcmp("help", Commands)==0) { printf("display 6666 via uart\r\n"); printf("display 0000 via uart\r\n"); return 1; } else if(strcmp("cable debug", Commands)==0) { cable_rx_ok=1; //printf("if you see this string 线材通讯OK\r\n"); return 1; } else { printf("if you see this string 线材通讯OK 调试板的LED需要亮\r\n"); return 1; //return 0; } } /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
2.203125
2
2024-11-18T21:09:24.714581+00:00
2020-05-23T02:32:38
13c34207d0b4317e05b6ba075b7a432f6ddf5997
{ "blob_id": "13c34207d0b4317e05b6ba075b7a432f6ddf5997", "branch_name": "refs/heads/master", "committer_date": "2020-05-23T02:32:38", "content_id": "6654918b93c09594a297b0f32493dcacd3b5aee6", "detected_licenses": [ "MIT" ], "directory_id": "3cf9c3a914dcab63f68c0209082c07a26521e3ec", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2020-05-20T11:16:20", "gha_event_created_at": "2020-05-21T22:24:00", "gha_language": "C", "gha_license_id": "MIT", "github_id": 265541221, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3292, "license": "MIT", "license_type": "permissive", "path": "/tests/machsuite-backprop/main.c", "provenance": "stackv2-0065.json.gz:4793", "repo_name": "sa2257/llvm-runtime-pass", "revision_date": "2020-05-23T02:32:38", "revision_id": "6f2c92141465e7df56f9720ab7753826663d799f", "snapshot_id": "69dcd7b684ac1eda9deec4d03fc5401b610a15e0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sa2257/llvm-runtime-pass/6f2c92141465e7df56f9720ab7753826663d799f/tests/machsuite-backprop/main.c", "visit_date": "2022-11-06T11:57:13.029474" }
stackv2
#include <fcntl.h> #include <assert.h> #include <string.h> #include "backprop.h" #include <unistd.h> #include <sys/stat.h> char *readfile(int fd) { char *p; struct stat s; off_t len; ssize_t bytes_read, status; assert(fd>1 && "Invalid file descriptor"); assert(0==fstat(fd, &s) && "Couldn't determine file size"); len = s.st_size; assert(len>0 && "File is empty"); p = (char *)malloc(len+1); bytes_read = 0; while( bytes_read<len ) { status = read(fd, &p[bytes_read], len-bytes_read); assert(status>=0 && "read() failed"); bytes_read+=status; } p[len] = (char)0; // Add NULL terminator close(fd); return p; } char *find_section_start(char *s, int n) { int i=0; assert(n>=0 && "Invalid section number"); if(n==0) return s; // Find the nth "%%\n" substring (if *s==0, there wasn't one) while(i<n && (*s)!=(char)0) { // This comparison will short-circuit before overrunning the string, so no length check. if( s[0]=='%' && s[1]=='%' && s[2]=='\n' ) { i++; } s++; } if(*s!=(char)0) return s+2; // Skip the section header itself, return pointer to the content return s; // Hit the end, return an empty string } int parse_double_array(char *s, TYPE *arr, int n) { char *line, *endptr; int i=0; TYPE v; assert(s!=NULL && "Invalid input string"); line = strtok(s,"\n"); while( line!=NULL && i<n ) { endptr = line; v = (TYPE)(strtod(line, &endptr)); if( (*endptr)!=(char)0 ) { fprintf(stderr, "Invalid input: line %d of section\n", i); } arr[i] = v; i++; line[strlen(line)] = '\n'; /* Undo the strtok replacement.*/ line = strtok(NULL,"\n"); } if(line!=NULL) { /* stopped because we read all the things */ line[strlen(line)] = '\n'; /* Undo the strtok replacement.*/ } return 0; } void run_benchmark() { struct bench_args_t args; char const *in_file; in_file = "input.data"; int in_fd; in_fd = open( in_file, O_RDONLY ); assert( in_fd>0 && "Couldn't open input data file"); char *p, *s; p = readfile(in_fd); s = find_section_start(p,1); parse_double_array(s, args.weights1, input_dimension * nodes_per_layer); s = find_section_start(p,2); parse_double_array(s, args.weights2, nodes_per_layer * nodes_per_layer); s = find_section_start(p,3); parse_double_array(s, args.weights3, nodes_per_layer * possible_outputs); s = find_section_start(p,4); parse_double_array(s, args.biases1, nodes_per_layer); s = find_section_start(p,5); parse_double_array(s, args.biases2, nodes_per_layer); s = find_section_start(p,6); parse_double_array(s, args.biases3, possible_outputs); s = find_section_start(p,7); parse_double_array(s, args.training_data, training_sets * input_dimension); s = find_section_start(p,8); parse_double_array(s, args.training_targets, training_sets * possible_outputs); free(p); backprop( args.weights1, args.weights2, args.weights3, args.biases1, args.biases2, args.biases3, args.training_data, args.training_targets ); printf("One example output is %f \n", args.biases3[possible_outputs-1]); } int main () { run_benchmark(); return 1; }
2.78125
3
2024-11-18T21:09:25.582825+00:00
2019-12-19T03:59:22
7d49d3e76d949674c82ef5ade712dd779b3c6258
{ "blob_id": "7d49d3e76d949674c82ef5ade712dd779b3c6258", "branch_name": "refs/heads/master", "committer_date": "2019-12-19T03:59:22", "content_id": "9f90b37d4162f71b9ed57993e51ffcd52d7bbf8a", "detected_licenses": [ "BSD-2-Clause", "NCSA" ], "directory_id": "83964e7fb41ee62e3084eef5d3deef07eecdd93e", "extension": "c", "filename": "variables.c", "fork_events_count": 1, "gha_created_at": "2019-12-02T15:17:36", "gha_event_created_at": "2019-12-02T15:17:37", "gha_language": null, "gha_license_id": "BSD-2-Clause", "github_id": 225405289, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1035, "license": "BSD-2-Clause,NCSA", "license_type": "permissive", "path": "/clang/test/PCH/variables.c", "provenance": "stackv2-0065.json.gz:4922", "repo_name": "pbb59/ScaffCC", "revision_date": "2019-12-19T03:59:22", "revision_id": "7d28d310063d147930ec4705aa5ebdf94ea8e924", "snapshot_id": "e0bee9e5b16a6f145224ad6b0b6eb32adb026f95", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pbb59/ScaffCC/7d28d310063d147930ec4705aa5ebdf94ea8e924/clang/test/PCH/variables.c", "visit_date": "2020-09-23T04:43:54.059923" }
stackv2
// Test this without pch. // RUN: %clang_cc1 -include %s -fsyntax-only -verify %s // Test with pch. // RUN: %clang_cc1 -emit-pch -o %t %s // RUN: %clang_cc1 -include-pch %t -fsyntax-only -verify %s #ifndef HEADER #define HEADER extern float y; extern int *ip, x; float z; // expected-note{{previous}} int z2 = 17; // expected-note{{previous}} #define MAKE_HAPPY(X) X##Happy int MAKE_HAPPY(Very); // expected-note{{previous definition is here}} #define A_MACRO_IN_THE_PCH 492 #define FUNCLIKE_MACRO(X, Y) X ## Y #define PASTE2(x,y) x##y #define PASTE1(x,y) PASTE2(x,y) #define UNIQUE(x) PASTE1(x,__COUNTER__) int UNIQUE(a); // a0 int UNIQUE(a); // a1 #else int *ip2 = &x; float *fp = &ip; // expected-warning{{incompatible pointer types}} double z; // expected-error{{redefinition}} int z2 = 18; // expected-error{{redefinition}} double VeryHappy; // expected-error{{redefinition}} int Q = A_MACRO_IN_THE_PCH; int R = FUNCLIKE_MACRO(A_MACRO_, IN_THE_PCH); int UNIQUE(a); // a2 int *Arr[] = { &a0, &a1, &a2 }; #endif
2.125
2
2024-11-18T21:09:25.730757+00:00
2017-09-05T15:38:22
35273729a6a8f351f6b13c70e31f208481aba131
{ "blob_id": "35273729a6a8f351f6b13c70e31f208481aba131", "branch_name": "refs/heads/master", "committer_date": "2017-09-05T15:38:22", "content_id": "ceb5cfe8e9721f3d0c3cb9f28238a8e915b9f017", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "14088b589c1a818eb044c7d2326a4cf5cf881ef8", "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": 11275, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/tools/sphinx.opensource.26may10/SphinxTrain-1.0/src/programs/lda_train/main.c", "provenance": "stackv2-0065.json.gz:5178", "repo_name": "johndpope/Speech-Detection-Demo", "revision_date": "2017-09-05T15:38:22", "revision_id": "b66d364f633198efc99b615a10ed3549c73fb58c", "snapshot_id": "f1f3f9595a0c621097b99d767898e653f7aa0730", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/johndpope/Speech-Detection-Demo/b66d364f633198efc99b615a10ed3549c73fb58c/tools/sphinx.opensource.26may10/SphinxTrain-1.0/src/programs/lda_train/main.c", "visit_date": "2021-01-23T07:16:14.721864" }
stackv2
/* -*- c-basic-offset:4; indent-tabs-mode: nil -*- */ #include "parse_cmd_ln.h" #include <s3/cmd_ln.h> #include <s3/ckd_alloc.h> #include <s3/feat.h> #include <s3/s3io.h> #include <s3/matrix.h> #include <s3/clapack_lite.h> #include <s3/vector.h> #include <s3/corpus.h> #include <s3/model_def_io.h> #include <s3/err.h> #include <s3/s3.h> #include <string.h> #define MATRIX_FILE_VERSION "0.1" static int lda_save(const char *outfile, float32 ***lda, int32 nlda, int32 featlen) { FILE *outfh; uint32 val, chksum = 0; s3clr_fattr(); s3add_fattr("version", MATRIX_FILE_VERSION, TRUE); s3add_fattr("chksum0", "yes", TRUE); if ((outfh = s3open(outfile, "wb", NULL)) == NULL) { E_FATAL_SYSTEM("Failed to open %s for writing", outfile); } s3write_3d((void ***)lda, sizeof(float32), nlda, featlen, featlen, outfh, &chksum); s3write(&chksum, sizeof(chksum), 1, outfh, &val); s3close(outfh); return 0; } static void calc_scatter(float32 ***out_sw, float32 ***out_sb, uint32 *out_featlen) { uint32 tick_cnt; uint16 *seg; vector_t *mfcc; vector_t **feat; uint32 *class_n_frame; uint32 n_class, n_frame, i; model_def_t *mdef; uint32 ceplen, featlen; float32 *globalmean, **mean, ***scatter, **sw, **sb, **op; const char *outfn; /* Set up corpus and mdef. */ if (model_def_read(&mdef, cmd_ln_access("-moddeffn")) != S3_SUCCESS) { E_FATAL_SYSTEM("Unable to open model def file"); } corpus_set_ctl_filename(cmd_ln_access("-ctlfn")); corpus_set_seg_dir(cmd_ln_access("-segdir")); corpus_set_seg_ext(cmd_ln_access("-segext")); corpus_set_mfcc_dir(cmd_ln_access("-cepdir")); corpus_set_mfcc_ext(cmd_ln_access("-cepext")); if (corpus_init() != S3_SUCCESS) { E_FATAL("Corpus initialization failed\n"); } ceplen = cmd_ln_int32("-ceplen"); feat_set(cmd_ln_access("-feat")); feat_set_in_veclen(ceplen); if (feat_n_stream() > 1) { E_FATAL("Multi-stream features are not supported\n"); } featlen = feat_blksize(); /* Use all non-filler senones as classes. */ n_class = mdef->n_tied_state; /* Per-class frame count */ class_n_frame = ckd_calloc(n_class, sizeof(uint32)); /* Per-class mean */ mean = (float32 **)ckd_calloc_2d(n_class, featlen, sizeof(float32)); /* Global mean */ globalmean = ckd_calloc(featlen, sizeof(float32)); /* Per-class covariance (I think) */ scatter = (float32 ***)ckd_calloc_3d(n_class, featlen, featlen, sizeof(float32)); /* Within-class covariance */ sw = (float32 **)ckd_calloc_2d(featlen, featlen, sizeof(float32)); /* Between-class covariance */ sb = (float32 **)ckd_calloc_2d(featlen, featlen, sizeof(float32)); /* Temporary accumulator for outer-product */ op = (float32 **)ckd_calloc_2d(featlen, featlen, sizeof(float32)); /* Accumulate for means */ E_INFO("Accumulating for means...\n"); tick_cnt = 0; n_frame = 0; while (corpus_next_utt()) { uint32 utt_n_frame, tmp_n_frame; if ((++tick_cnt % 500) == 0) { printf("[%u] ", tick_cnt); fflush(stdout); } if (corpus_get_seg(&seg, &utt_n_frame) != S3_SUCCESS) { E_FATAL("Unable to read Viterbi state segmentation for %s\n", corpus_utt_brief_name()); } corpus_get_generic_featurevec(&mfcc, &tmp_n_frame, ceplen); if (tmp_n_frame != utt_n_frame) { E_ERROR("State segmentation/control file mismatch in #frames: %u != %u\n", utt_n_frame, tmp_n_frame); ckd_free(mfcc[0]); ckd_free(mfcc); mfcc = NULL; ckd_free(seg); seg = NULL; continue; } feat = feat_compute(mfcc, &utt_n_frame); for (i = 0; i < utt_n_frame; ++i) { uint32 class = seg[i] & 0x7fff; /* We do not care if it's the first state */ vector_add(mean[class], feat[i][0], featlen); vector_add(globalmean, feat[i][0], featlen); ++class_n_frame[class]; } n_frame += utt_n_frame; ckd_free(seg); feat_free(feat); ckd_free(mfcc[0]); ckd_free(mfcc); } printf("\n"); /* Normalize for class and global means */ for (i = 0; i < n_class; ++i) { if (class_n_frame[i] != 0) { vector_scale(mean[i], 1.0/class_n_frame[i], featlen); } else { E_WARN("Empty class %d\n", i); } } if (n_frame != 0) vector_scale(globalmean, 1.0/n_frame, featlen); /* Accumulate for covariances */ corpus_reset(); E_INFO("Accumulating for covariances...\n"); tick_cnt = 0; while (corpus_next_utt()) { if ((++tick_cnt % 500) == 0) { printf("[%u] ", tick_cnt); fflush(stdout); } corpus_get_seg(&seg, &n_frame); corpus_get_generic_featurevec(&mfcc, &n_frame, ceplen); feat = feat_compute(mfcc, &n_frame); for (i = 0; i < n_frame; ++i) { uint32 class = seg[i] & 0x7fff; vector_sub(feat[i][0], mean[class], featlen); outerproduct(op, feat[i][0], feat[i][0], featlen); matrixadd(scatter[class], op, featlen, featlen); } ckd_free(seg); feat_free(feat); ckd_free(mfcc[0]); ckd_free(mfcc); } printf("\n"); if ((outfn = cmd_ln_access("-outcovfn"))) { lda_save(outfn, scatter, n_class, featlen); } if ((outfn = cmd_ln_access("-outcountfn"))) { FILE *fh; if ((fh = fopen(outfn, "w")) == NULL) { E_FATAL_SYSTEM("Failed to open output count file %s"); } for (i = 0; i < n_class; ++i) { fprintf(fh, "%d\n", class_n_frame[i]); } fclose(fh); } for (i = 0; i < n_class; ++i) { /* We are "supposed" to normalize scatter_i here: * (class_n_frame[i]/n_frame) * (1/class_n_frame[i]) = 1/n_frame * scalarmultiply(scatter[i], 1.0/n_frame, featlen, featlen); * however it seems to work slightly better to scale up the * individual classes in Sb instead as noted below. */ matrixadd(sw, scatter[i], featlen, featlen); } for (i = 0; i < n_class; ++i) { vector_sub(mean[i], globalmean, featlen); outerproduct(op, mean[i], mean[i], featlen); /* This is slightly different than the "classic" LDA formula, * in that we weight the between-class variances according to * their counts. It seems to work better. */ scalarmultiply(op, class_n_frame[i], featlen, featlen); matrixadd(sb, op, featlen, featlen); } ckd_free_3d((void ***)scatter); ckd_free_2d((void **)mean); ckd_free_2d((void **)op); ckd_free(globalmean); if (out_sw) *out_sw = sw; if (out_sb) *out_sb = sb; if (out_featlen) *out_featlen = featlen; } static int eigen_sort(const void *a, const void *b) { float32 *const *aa = a; float32 *const *bb = b; /* Sort descending. */ if ((*aa)[0] < (*bb)[0]) return 1; else if ((*aa)[0] > (*bb)[0]) return -1; else return 0; } static void lda_compute_inv(float32 **sw, float32 **sb, float32 **out_u, float32 ***out_v, uint32 featlen) { float32 **swinv, **ba, *ur, *ui, **vr, **vi, **eigen, *tmp; uint32 i, j; printf("Sw:\n"); for (i = 0; i < featlen; ++i) { for (j = 0; j < featlen; ++j) { printf("%f ", sw[i][j]); } printf("\n"); } printf("\n"); printf("Sb:\n"); for (i = 0; i < featlen; ++i) { for (j = 0; j < featlen; ++j) { printf("%f ", sb[i][j]); } printf("\n"); } printf("\n"); /* Solve the eigenproblem B^{-1}Av = uv (this isn't the most * efficient way to do this but the matrix is pretty small so it * doesn't matter) */ /* Note that the eigenvectors we get from this are quite different * from the ones we get from solving the generalized eigenproblem * directly with SGGEV (QR-factorization). This does not seem to * affect accuracy. SphinxBase will have the generalized routine * in it and we may wish to switch at that point. */ swinv = (float32 **)ckd_calloc_2d(featlen, featlen, sizeof(float32)); if (invert(swinv, sw, featlen) < 0) { E_FATAL("Singular Sw matrix!! Argh!\n"); } ba = (float32 **)ckd_calloc_2d(featlen, featlen, sizeof(float32)); vr = (float32 **)ckd_calloc_2d(featlen, featlen, sizeof(float32)); vi = (float32 **)ckd_calloc_2d(featlen, featlen, sizeof(float32)); ur = ckd_calloc(featlen, sizeof(float32)); ui = ckd_calloc(featlen, sizeof(float32)); matrixmultiply(ba, swinv, sb, featlen, featlen, featlen); eigenvectors(ba, ur, ui, vr, vi, featlen); /* Discard the imaginary parts (they will be zero because B^{-1}A * is symmetric). */ ckd_free_2d((void **)vi); ckd_free(ui); /* Construct the LDA transformation. LAPACK is supposed to return * the eigenvalues in sorted order but that doesn't actually * always happen, so we will sort them to be sure here. */ /* Concatenate eigenvalues/eigenvectors. */ eigen = (float32 **)ckd_calloc_2d(featlen, featlen+1, sizeof(float32)); for (i = 0; i < featlen; ++i) { eigen[i][0] = ur[i]; memcpy(&eigen[i][1], vr[i], featlen * sizeof(float32)); } /* Save the old base pointer so we can free it. */ tmp = eigen[0]; qsort(eigen, featlen, sizeof(float32 *), eigen_sort); /* Copy the eigenvalues/vectors back to ur, vr */ for (i = 0; i < featlen; ++i) { ur[i] = eigen[i][0]; memcpy(vr[i], &eigen[i][1], featlen * sizeof(float32)); } for (i = 0; i < featlen; ++i) { printf("Eigenvalue %d: %f\n", i, eigen[i][0]); } printf("\n"); for (i = 0; i < featlen; ++i) { printf("Eigenvector %d: \n", i); for (j = 0; j < featlen; ++j) { printf("%f ", eigen[i][j+1]); } printf("\n"); } ckd_free(tmp); ckd_free(eigen); if (out_u) *out_u = ur; else ckd_free(ur); if (out_v) *out_v = vr; else ckd_free_2d((void **)vr); } int main(int argc, char *argv[]) { float32 **sw, **sb, **lda; uint32 featlen; /* Get arguments. */ parse_cmd_ln(argc, argv); /* Check required arguments (imagine that) */ if (cmd_ln_access("-ctlfn") == NULL || cmd_ln_access("-cepdir") == NULL || cmd_ln_access("-segdir") == NULL || cmd_ln_access("-moddeffn") == NULL || cmd_ln_access("-feat") == NULL) { E_FATAL("Some required arguments missing (-ctlfn, -cepdir, -segdir, -moddeffn, -feat)\n"); } /* Calculate scatter matrices */ calc_scatter(&sw, &sb, &featlen); /* Do eigen decomposition to find LDA matrix. */ lda_compute_inv(sw, sb, NULL, &lda, featlen); /* Write out the matrix. */ if (cmd_ln_access("-outfn") != NULL) { lda_save(cmd_ln_access("-outfn"), &lda, 1, featlen); } ckd_free_2d((void **)sw); ckd_free_2d((void **)sb); ckd_free_2d((void **)lda); return 0; }
2.140625
2
2024-11-18T21:09:25.964227+00:00
2020-11-30T03:52:58
a299cb26fe8ea4d1d8e40a9817b7792ab3a9843f
{ "blob_id": "a299cb26fe8ea4d1d8e40a9817b7792ab3a9843f", "branch_name": "refs/heads/main", "committer_date": "2020-11-30T03:52:58", "content_id": "f3b2f2a441d83aa7e340e306ea176ec5192f3426", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c438005959127098709e83471884ff37369ce5a4", "extension": "c", "filename": "platinum.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 305242379, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 773, "license": "Apache-2.0", "license_type": "permissive", "path": "/第3章_数据和C/程序清单3.1 示例程序/3.1 示例程序/platinum.c", "provenance": "stackv2-0065.json.gz:5309", "repo_name": "LangfordGuo/C_Primer_Plus", "revision_date": "2020-11-30T03:52:58", "revision_id": "b70b08eee3845bb71bf3eca5dcc38f9bf6133b93", "snapshot_id": "89a99338211c2712ebb4eda666e31cd37fb1625a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LangfordGuo/C_Primer_Plus/b70b08eee3845bb71bf3eca5dcc38f9bf6133b93/第3章_数据和C/程序清单3.1 示例程序/3.1 示例程序/platinum.c", "visit_date": "2023-01-19T02:01:08.310046" }
stackv2
// // main.c // 3.1 示例程序 // // Created by 郭龙飞 on 2020/11/4. // /* platinum.c -- your weight in platinum */ #include <stdio.h> int main(void) { float weight; // 体重 float value; //白金价值 printf("Are you worth your weight in platinum?\n"); printf("Let's check it out.\n"); printf("please enter your weight in pounds: "); /*获取用户输入*/ scanf("%f",&weight); /*假设白金的价格是每盎司$1700*/ /*14.5833用于把英镑常衡盎司转换为金衡盎司*/ value = 1700.0 * weight *14.5833; printf("Your weight in platinum is worth $%.2f.\n",value); printf("You are easily worth that! if Platinum prices drop,\n"); printf("eat more maintain your value.\n"); return 0; }
3.375
3
2024-11-18T21:09:26.254587+00:00
2021-03-13T14:30:41
ed92fa3b224628f4c2fa7bd136ba5de4c1865403
{ "blob_id": "ed92fa3b224628f4c2fa7bd136ba5de4c1865403", "branch_name": "refs/heads/main", "committer_date": "2021-03-13T14:30:41", "content_id": "dd1e5cb26248c818f4b1252beaba459d6c9b7a32", "detected_licenses": [ "MIT" ], "directory_id": "673487fc58f63c24b4f1fa1836d443c89e286a1c", "extension": "c", "filename": "input.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 341270522, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1958, "license": "MIT", "license_type": "permissive", "path": "/input.c", "provenance": "stackv2-0065.json.gz:5693", "repo_name": "b4ba/Postoffice_Queue_Simulation", "revision_date": "2021-03-13T14:30:41", "revision_id": "9f1dfaa6b97049ddeb508e692865f7ed442062e7", "snapshot_id": "84eaacbc3c34fb7beeb1eefe7fa2e2af7570a6d5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/b4ba/Postoffice_Queue_Simulation/9f1dfaa6b97049ddeb508e692865f7ed442062e7/input.c", "visit_date": "2023-03-25T01:27:42.652314" }
stackv2
#include "input.h" /* Function to read the parameters from the input file and store them in variables */ INPUT * readFile(char *fileName, INPUT *I, FILE *outputFile) { char c[100]; FILE *fp = NULL; if ((fp = fopen(fileName, "r")) == NULL) { fprintf(stderr, "Unable to open file and read parameters: %d: %s\n", errno, strerror(errno)); exit(-1); } while( !feof(fp) ) { fgets(c, 100, fp); if( c[0] != '#' && strlen(c) > 1 ) { sscanf(c, "maxQueueLength %d", &(I->maxQueueLength)); sscanf(c, "numServicePoints %d", &(I->numServicePoints)); sscanf(c, "closingTime %d", &(I->closingTime)); sscanf(c, "averageNewCustomersPerInterval %d", &(I->averageNewCustomerPerInterval)); } } if(I->maxQueueLength == 0) { fprintf(stderr, "Parameter maxQueueLength wasn't identified\n"); } if(I->numServicePoints == 0) { fprintf(stderr, "Parameter numServicePoints wasn't identified\n"); } if(I->closingTime == 0) { fprintf(stderr, "Parameter closingTime wasn't identified\n"); } if(I->averageNewCustomerPerInterval == 0) { fprintf(stderr, "Parameter averageNewCustomersPerInterval wasn't identified\n"); } fprintf(outputFile, "----Parameters read from %s----\n", fileName); fprintf(outputFile, "Max queue length: %d\n", I->maxQueueLength); fprintf(outputFile, "Number of service points: %d\n", I->numServicePoints); fprintf(outputFile, "Closing time: %d\n", I->closingTime); fprintf(outputFile, "Average new customers per interval: %d\n", I->averageNewCustomerPerInterval); fclose(fp); return I; }
2.859375
3
2024-11-18T21:09:26.474539+00:00
2021-03-30T22:38:12
a4e3a36d1f8c5bd23b797f0a4d647430ffdcc768
{ "blob_id": "a4e3a36d1f8c5bd23b797f0a4d647430ffdcc768", "branch_name": "refs/heads/main", "committer_date": "2021-03-30T22:38:12", "content_id": "9e36f5c8c8762f9d89ce712f901b62bac407dcc1", "detected_licenses": [ "MIT" ], "directory_id": "b8584c95fb8845398cd5e6e81c1d141897f3a75b", "extension": "c", "filename": "stack.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 353159252, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3414, "license": "MIT", "license_type": "permissive", "path": "/Assignment_02/stack.c", "provenance": "stackv2-0065.json.gz:5821", "repo_name": "Exiled1/CS261", "revision_date": "2021-03-30T22:38:12", "revision_id": "6cd718e5527e4ca6a35938f74b7f2f26ecbe7693", "snapshot_id": "df12d95fbf8941c41c2d2b5c17747c4ab5adc0ac", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Exiled1/CS261/6cd718e5527e4ca6a35938f74b7f2f26ecbe7693/Assignment_02/stack.c", "visit_date": "2023-03-27T05:47:02.024966" }
stackv2
/* * This file is where you should implement your stack. It already contains * skeletons of the functions you need to implement (along with documentation * for each function). Feel free to implement any additional functions you * might need. Also, don't forget to include your name and @oregonstate.edu * email address below. * * Name: * Email: */ #include <stdlib.h> #include "stack.h" #include "list.h" typedef struct stack Stack; typedef struct list List; /* * This is the structure that will be used to represent a stack. This * structure specifically contains a single field representing a linked list * that should be used as the underlying data storage for the stack. * * You should not modify this structure. */ struct stack { List *list; }; /* * This function should allocate and initialize a new, empty stack and return * a pointer to it. */ Stack *stack_create() { Stack *stack = (Stack *) malloc(sizeof(Stack)); // Make a new stack button. stack->list = list_create(); return stack; } /* * This function should free the memory associated with a stack. While this * function should up all memory used in the stack itself, it should not free * any memory allocated to the pointer values stored in the stack. This is the * responsibility of the caller. * * Params: * stack - the stack to be destroyed. May not be NULL. */ void stack_free(Stack *stack) { list_free(stack->list); free(stack); return; } /* * This function should indicate whether a given stack is currently empty. * Specifically, it should return 1 if the specified stack is empty (i.e. * contains no elements) and 0 otherwise. * * Params: * stack - the stack whose emptiness is being questioned. May not be NULL. */ int stack_isempty(Stack *stack) { // Basically this is an if statement that checks if the list inside the stack is null or the stack inside the list is null, if it is, then set flag to 0, 1 otherwise. int flag; if(list_is_empty(stack->list) == 1){ flag = 1; }else{ flag = 0; } return flag; } /* * This function should push a new value onto a given stack. The value to be * pushed is specified as a void pointer. This function must have O(1) * average runtime complexity. * * Params: * stack - the stack onto which a value is to be pushed. May not be NULL. * val - the value to be pushed. Note that this parameter has type void*, * which means that a pointer of any type can be passed. */ void stack_push(Stack *stack, void *val) { list_insert(stack->list, val); return; } /* * This function should return the value stored at the top of a given stack * *without* removing that value. This function must have O(1) average runtime * complexity. * * Params: * stack - the stack from which to query the top value. May not be NULL. * Return: * Head value. */ void *stack_top(Stack *stack) { return list_get_top_val(stack->list); } /* * This function should pop a value from a given stack and return the popped * value. This function must have O(1) average runtime complexity. * * Params: * stack - the stack from which a value is to be popped. May not be NULL. * * Return: * This function should return the value that was popped. */ void* stack_pop(Stack *stack) { void* returnVal = list_remove_head(stack->list); return returnVal; }
3.390625
3
2024-11-18T21:09:26.818048+00:00
2022-07-26T19:29:48
89f7f4378506d9e85a6c38b1cc93b612338d2c9d
{ "blob_id": "89f7f4378506d9e85a6c38b1cc93b612338d2c9d", "branch_name": "refs/heads/master", "committer_date": "2022-07-26T19:29:48", "content_id": "7d490387558d7d95c3e52c6c25ddf575a6eb1009", "detected_licenses": [ "Unlicense" ], "directory_id": "05557c0fc6d922cddb2d827defe85c8a0dd5f34e", "extension": "c", "filename": "eval.c", "fork_events_count": 5, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 10880534, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12435, "license": "Unlicense", "license_type": "permissive", "path": "/eval.c", "provenance": "stackv2-0065.json.gz:6206", "repo_name": "wernsey/miscsrc", "revision_date": "2022-07-26T19:29:48", "revision_id": "a6c82d20f3a85620c22f597813a669ae2c52e22e", "snapshot_id": "ef76437afacdf26d3025306e2da70f258965e63b", "src_encoding": "UTF-8", "star_events_count": 31, "url": "https://raw.githubusercontent.com/wernsey/miscsrc/a6c82d20f3a85620c22f597813a669ae2c52e22e/eval.c", "visit_date": "2022-08-14T00:53:39.591336" }
stackv2
/* * Mathematical expression evaluator. * * See eval.h for more info * * This is free and unencumbered software released into the public domain. * http://unlicense.org/ */ /* * You can use the following awk script to obtain the syntax of the parser in * [my own] EBNF form: * * awk '/\*#/{a=index($0,"#")+2;print(substr($0,a))}' eval.c * * The following awk script will print a list of all the functions and constants * defined in the script from the comments. * * awk '/\*\$/{a=index($0,"$")+2;b=index($0,"* /");print(substr($0,a,b-a))}' eval.c * * NOTE: there's a space in the 'index($0,"* /")' above for the sake of this comment */ #include <stdlib.h> #include <math.h> /* remember to compile with -lm */ #include <string.h> #include <ctype.h> #include <setjmp.h> #include <assert.h> #include "eval.h" /* Special tokens used by the lexer function lex() * they've been chosen as non-printable characters * so that printable characters can be used for other * purposes */ #define TOK_END 0 /* end of text */ #define TOK_INI 1 /* Initial state */ #define TOK_ID 2 /* identifier */ #define TOK_NUM 3 /* number */ /* Types of errors */ #define ERR_MEMORY 1 #define ERR_LEXER 2 #define ERR_LONGID 3 #define ERR_VALUE 4 #define ERR_BRACKET 5 #define ERR_FUNC 6 #define ERR_ARGS 7 #define ERR_CONST 8 /* Other definitions */ #define MAX_ID_LEN 11 /* Max length of an identifier */ #define OPERATORS "+-*/%(),^" /* Valid operators */ #define EVAL_PI 3.141592654 #define EVAL_E 2.718281828 /* Internal structure for the parser/evaluator */ struct eval { jmp_buf j; /* For error handling */ const char *p; /* Position in the text being parsed */ double *st; /* Stack */ int st_size; /* Stack size */ int sp; /* Stack pointer */ /* The current and next tokens identified by the lexer */ struct { int type; /* Type of the token */ double n_val; /* Numeric value of the previous lexed token */ char s_val[MAX_ID_LEN]; /* String (identifier) value of the previous lexed token */ } token[2]; int cur_tok; /* Current token, either 0 or 1 (see the comments of lex()) */ }; /* Prototypes */ static double pop(struct eval *ev); static void push(struct eval *ev, double d); static int lex(struct eval *ev); /* Prototypes for the recursive descent parser */ static void expr(struct eval *ev); static void add_expr(struct eval *ev); static void mul_expr(struct eval *ev); static void pow_expr(struct eval *ev); static void uni_expr(struct eval *ev); static void bra_expr(struct eval *ev); static void id_expr(struct eval *ev); static void num_expr(struct eval *ev); /* * Evaluates a mathemeatical expression */ double eval(const char *exp, int *ep) { struct eval ev; double ans = 0.0; assert(ep != NULL); /* Allocate a stack */ ev.st_size = 10; ev.st = calloc(ev.st_size, sizeof *ev.st); if(!ev.st) { *ep = ERR_MEMORY; return 0.0; } ev.sp = 0; /* Manage errors */ *ep = setjmp(ev.j); if(*ep != 0) { free(ev.st); return 0.0; } /* Initialize the lexer */ ev.token[0].type = TOK_INI; ev.token[0].s_val[0] = '\0'; ev.token[1].type = TOK_INI; ev.token[1].s_val[0] = '\0'; ev.cur_tok = 0; /* Initialize the parser */ ev.p = exp; /* lex once to initialize the lexer */ if(lex(&ev) != TOK_END) { expr(&ev); ans = pop(&ev); } free(ev.st); return ans; } /* * Pushes a value onto the stack, increases the stack size if necessary */ static void push(struct eval *ev, double d) { if(ev->sp == ev->st_size) { /* Resize the stack by 1.5 */ double *old = ev->st; int new_size = ev->st_size + (ev->st_size >> 1); ev->st = realloc(ev->st, new_size); if(!ev->st) { ev->st = old; longjmp(ev->j, ERR_MEMORY); } ev->st_size = new_size; } ev->st[ev->sp++] = d; } /* * Pops a value from the top of the stack */ static double pop(struct eval *ev) { assert(ev->sp > 0); return ev->st[--ev->sp]; } /* stricmp() is common, but not standard, so I provide my own */ static int istrcmp(const char *p, const char *q) { for(; tolower(p[0]) == tolower(q[0]) && p[0]; p++, q++); return tolower(p[0]) - tolower(q[0]); } /* * Returns a string describing a specific error code */ const char *eval_error(int err) { switch(err) { case 0: return "no error"; case ERR_MEMORY: return "out of memory"; case ERR_LEXER: return "unknown token"; case ERR_LONGID: return "identifier too long"; case ERR_VALUE: return "value expected"; case ERR_BRACKET: return "missing ')'"; case ERR_FUNC: return "unknown function"; case ERR_ARGS: return "wrong number of arguments"; case ERR_CONST: return "unknown constant"; } return "unknown error"; } /* * Lexical analyzer function * * In order to implement LL(1), struct eval has an array of two token structures, * and its cur_tok member is used to point to the _current_ token, while the other * element contains the _next_ token. This implements a 2 element ring buffer where * the lexer always writes to the _next_ token so that the recursive descent parser can * _peek_ at the next token. */ static int lex(struct eval *ev) { int next_tok; start: /* Cycle the tokens */ next_tok = ev->cur_tok; ev->cur_tok = ev->cur_tok?0:1; while(isspace(ev->p[0])) ev->p++; if(!ev->p[0]) { /* End of the expression */ ev->token[next_tok].type = TOK_END; goto end; } else if(isdigit(ev->p[0]) || ev->p[0] == '.') { /* Number */ char *endp; ev->token[next_tok].type = TOK_NUM; ev->token[next_tok].n_val = strtod(ev->p, &endp); ev->p = endp; goto end; } else if(isalpha(ev->p[0])) { /* Identifier */ int i; for(i = 0; isalnum(ev->p[0]) && i < MAX_ID_LEN - 1; i++, ev->p++) ev->token[next_tok].s_val[i] = ev->p[0]; if(isalpha(ev->p[0])) longjmp(ev->j, ERR_LONGID); ev->token[next_tok].s_val[i] = '\0'; ev->token[next_tok].type = TOK_ID; goto end; } else if(strchr(OPERATORS, ev->p[0])) { /* Operator */ ev->token[next_tok].type = ev->p[0]; ev->p++; goto end; } else /* Unknown token */ longjmp(ev->j, ERR_LEXER); end: /* If this was the first call, cycle the tokens again */ if(ev->token[ev->cur_tok].type == TOK_INI) goto start; return ev->token[ev->cur_tok].type; } #define THIS(e) (e->token[e->cur_tok].type) #define PEEK(e) (e->token[e->cur_tok?0:1].type) #define GOBBLE(e) lex(e) #define ERROR(c) longjmp(ev->j, (c)) /*# expr ::= add_expr */ static void expr(struct eval *ev) { add_expr(ev); } /*# add_expr ::= mul_expr [('+'|'-') mul_expr]* */ static void add_expr(struct eval *ev) { int t; mul_expr(ev); while((t =THIS(ev)) == '+' || t == '-') { double a,b; GOBBLE(ev); mul_expr(ev); b = pop(ev); a = pop(ev); if(t == '+') push(ev, a + b); else push(ev, a - b); } } /*# mul_expr ::= pow_expr [('*'|'/'|'%') pow_expr]* */ static void mul_expr(struct eval *ev) { int t; pow_expr(ev); while((t = THIS(ev)) == '*' || t == '/' || t == '%') { double a,b; GOBBLE(ev); pow_expr(ev); b = pop(ev); a = pop(ev); if(t == '*') push(ev, a * b); else if(t == '/') push(ev, a / b); else push(ev, fmod(a, b)); } } /*# pow_expr ::= uni_expr ['^' pow_expr] */ static void pow_expr(struct eval *ev) { /* Note that exponentiation is right associative: 2^3^4 is 2^(3^4), not (2^3)^4 */ uni_expr(ev); if(THIS(ev) == '^') { double a,b; GOBBLE(ev); pow_expr(ev); b = pop(ev); a = pop(ev); push(ev, pow(a,b)); } } /*# uni_expr ::= ['+'|'-'] bra_expr */ static void uni_expr(struct eval *ev) { int t = '+'; if(THIS(ev) == '-' || THIS(ev) == '+') { t = THIS(ev); GOBBLE(ev); } bra_expr(ev); if(t == '-') { double a = pop(ev); push(ev, -a); } } /*# bra_expr ::= '(' add_expr ')' *# | id_expr */ static void bra_expr(struct eval *ev) { if(THIS(ev) == '(') { GOBBLE(ev); add_expr(ev); if(THIS(ev) != ')') ERROR(ERR_BRACKET); GOBBLE(ev); } else id_expr(ev); } /*# id_expr ::= ID '(' add_expr [',' add_expr]* ')' *# | ID *# | num_expr */ static void id_expr(struct eval *ev) { if(THIS(ev) == TOK_ID) { char id[MAX_ID_LEN]; strcpy(id, ev->token[ev->cur_tok].s_val); GOBBLE(ev); if(THIS(ev) == '(') { int nargs = 0; GOBBLE(ev); while(THIS(ev) != ')') { add_expr(ev); nargs++; if(THIS(ev) == ')') break; if(THIS(ev) != ',') ERROR(ERR_BRACKET); GOBBLE(ev); } GOBBLE(ev); /*$ abs(x) - absolute value of x */ if(!istrcmp(id, "abs")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, fabs(pop(ev))); } /*$ ceil(x) - smallest integer greater than x */ else if(!istrcmp(id, "ceil")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, ceil(pop(ev))); } /*$ floor(x) - largest integer smaller than x */ else if(!istrcmp(id, "floor")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, floor(pop(ev))); } /*$ sin(x) - sine of x, in radians */ else if(!istrcmp(id, "sin")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, sin(pop(ev))); } /*$ asin(x) - arcsine of x, in radians */ else if(!istrcmp(id, "asin")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, asin(pop(ev))); } /*$ cos(x) - cosine of x, in radians */ else if(!istrcmp(id, "cos")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, cos(pop(ev))); } /*$ acos(x) - arccosine of x, in radians */ else if(!istrcmp(id, "acos")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, acos(pop(ev))); } /*$ tan(x) - tangent of x, in radians */ else if(!istrcmp(id, "tan")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, tan(pop(ev))); } /*$ atan(x) - arctangent of x, in radians */ else if(!istrcmp(id, "atan")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, atan(pop(ev))); } /*$ atan(y,x) - arctangent of y/x, in radians. */ else if(!istrcmp(id, "atan2")) { double a, b; if(nargs != 2) ERROR(ERR_ARGS); b = pop(ev); a = pop(ev); push(ev, atan2(a,b)); } /*$ sinh(x) - hyperbolic sine of x, in radians */ else if(!istrcmp(id, "sinh")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, sinh(pop(ev))); } /*$ cosh(x) - hyperbolic cosine of x, in radians */ else if(!istrcmp(id, "cosh")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, cosh(pop(ev))); } /*$ tanh(x) - hyperbolic tangent of x, in radians */ else if(!istrcmp(id, "tanh")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, tanh(pop(ev))); } /*$ log(x) - natural logarithm of x */ else if(!istrcmp(id, "log")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, log(pop(ev))); } /*$ log10(x) - logarithm of x, base-10 */ else if(!istrcmp(id, "log10")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, log10(pop(ev))); } /*$ exp(x) - computes e^x */ else if(!istrcmp(id, "exp")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, exp(pop(ev))); } /*$ sqrt(x) - square root of x */ else if(!istrcmp(id, "sqrt")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, sqrt(pop(ev))); } /*$ rad(x) - converts x from degrees to radians */ else if(!istrcmp(id, "rad")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, pop(ev)*EVAL_PI/180); } /*$ deg(x) - converts x from radians to degrees */ else if(!istrcmp(id, "deg")) { if(nargs != 1) ERROR(ERR_ARGS); push(ev, pop(ev)*180/EVAL_PI); } /*$ pow(x,y) - computes x^y */ else if(!istrcmp(id, "pow")) { double a, b; if(nargs != 2) ERROR(ERR_ARGS); b = pop(ev); a = pop(ev); push(ev, pow(a,b)); } /*$ hypot(x,y) - computes sqrt(x*x + y*y) */ else if(!istrcmp(id, "hypot")) { double a, b; if(nargs != 2) ERROR(ERR_ARGS); b = pop(ev); a = pop(ev); push(ev, sqrt(a*a + b*b)); } else ERROR(ERR_FUNC); } else { /*$ pi - 3.141592654 */ if(!istrcmp(id, "pi")) push(ev, EVAL_PI); /*$ e - base of natural logarithms, 2.718281828 */ else if(!istrcmp(id, "e")) push(ev, EVAL_E); else ERROR(ERR_CONST); } } else num_expr(ev); } /*# num_expr ::= NUMBER */ static void num_expr(struct eval *ev) { if(THIS(ev) != TOK_NUM) ERROR(ERR_VALUE); push(ev, ev->token[ev->cur_tok].n_val); GOBBLE(ev); }
2.6875
3
2024-11-18T21:09:27.317020+00:00
2018-06-20T04:41:26
43316a1104e6d3d489eb6868a3bc217df66ebcc1
{ "blob_id": "43316a1104e6d3d489eb6868a3bc217df66ebcc1", "branch_name": "refs/heads/master", "committer_date": "2018-06-20T04:41:26", "content_id": "db8fe142fcac642cdca84f5071ed0e111c1271fe", "detected_licenses": [ "MIT" ], "directory_id": "a03f87c7f99d4f2f330df782de80958a5c19815a", "extension": "h", "filename": "friends_memory.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 137973576, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2486, "license": "MIT", "license_type": "permissive", "path": "/lib/friends_memory.h", "provenance": "stackv2-0065.json.gz:6334", "repo_name": "lugia-kun/friends", "revision_date": "2018-06-20T04:41:26", "revision_id": "22303e51f469ee48ae8411799eaec7cf68ddb9bc", "snapshot_id": "2fa461d7adc78df56b178aef30d37d650870c6a0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lugia-kun/friends/22303e51f469ee48ae8411799eaec7cf68ddb9bc/lib/friends_memory.h", "visit_date": "2020-03-21T01:59:39.100414" }
stackv2
#ifndef FRIENDS_MEMORY_H #define FRIENDS_MEMORY_H #include "friends_defs.h" /** * @brief 新しいメモリ管理領域を作るのです。 * @param e NULL でなければ、そこにエラーの情報を書き込むのです。 * @return 新しく作ったメモリ管理領域を返すのです。 */ friendsMemory *friendsNewMemory(friendsError *e); /** * @brief メモリ管理領域を削除するのです。 * @param pool 削除するメモリ管理領域をよこすのです。 * * 登録されているすべてのメモリ領域を解放するのです。 */ void friendsDeleteMemory(friendsMemory *pool); /** * @brief メモリ管理領域にポインタを登録するのです。 * @param pool 登録先のメモリ管理領域をよこすのです。 * @param ptr 登録するポインタをよこすのです。 * @param ptrdel 登録したポインタを削除するときに使う関数をよこすのです。 * @param e NULL でなければ、そこにエラーの情報を書き込むのです。 * @return 成功した場合は ptr を、失敗した場合は NULL を返すのです。 */ void * friendsMemoryAddPointer(friendsMemory *pool, void *ptr, friendsPointerDeleter *ptrdel, friendsError *e); /** * @brief 指定したポインタが管理領域に登録されているかを調べるのです。 * @param pool 調べるメモリ管理領域をよこすのです。 * @param ptr 調べるポインタをよこすのです。 * @return 登録されていれば friendsTrue を、そうでなければ * friendsFalse を返すのです。 */ friendsBool friendsMemoryHasPointer(friendsMemory *pool, void *ptr); /** * @brief 指定したポインタを管理領域の登録から解除するのです。 * @param pool メモリ管理領域をよこすのです。 * @param ptr 登録を解除するポインタをよこすのです。 * @return ptr か、登録されていない場合は NULL を返すのです。 */ void *friendsMemoryUnregister(friendsMemory *pool, void *ptr); /** * @brief 管理領域に登録されている指定したポインタを解放するのです。 * @param pool メモリ管理領域をよこすのです。 * @param ptr 解放するポインタをよこすのです。 * @return 解放した場合は NULL を、登録されていない場合は ptr を返すのです。 */ void *friendsMemoryDeletePointer(friendsMemory *pool, void *ptr); #endif
2.578125
3
2024-11-18T21:09:27.514272+00:00
2018-09-16T17:31:31
fccff303c04b90336b0c092ffb86dec0933c24f2
{ "blob_id": "fccff303c04b90336b0c092ffb86dec0933c24f2", "branch_name": "refs/heads/master", "committer_date": "2018-09-16T17:31:31", "content_id": "5e7e0afa799a895790525d5cc10ac85759952f12", "detected_licenses": [ "MIT" ], "directory_id": "9bb3569bda64843a4a968e2bccd0701003545f26", "extension": "c", "filename": "bitmap.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 141850880, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2660, "license": "MIT", "license_type": "permissive", "path": "/bitmap/bitmap.c", "provenance": "stackv2-0065.json.gz:6462", "repo_name": "marcolgl/simple-fs", "revision_date": "2018-09-16T17:31:31", "revision_id": "8be39c8d83a0757be8fd704f3a167829b04a1831", "snapshot_id": "eac3ae3d2f2e6fe745947053697751df1debbab8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/marcolgl/simple-fs/8be39c8d83a0757be8fd704f3a167829b04a1831/bitmap/bitmap.c", "visit_date": "2020-03-23T17:15:17.986438" }
stackv2
#include "bitmap.h" #include <stdio.h> // converts a block index to an index in the array, // and a char that indicates the offset of the bit inside the array BitMapEntryKey BitMap_blockToIndex(int num){ int entry_num = num/8; char bit_num = (char)(num%8); BitMapEntryKey res; res.entry_num = entry_num; res.bit_num = bit_num; return res; } // converts a bit to a linear index int BitMap_indexToBlock(int entry, uint8_t bit_num){ return entry*8+bit_num; } // sets the bit at index pos in bmap to status int BitMap_set(BitMap* bmap, int pos, int status){ if (pos >= bmap->num_bits || (status!=0 && status != 1)) return -1; BitMapEntryKey bmek = BitMap_blockToIndex(pos); char mask =(char) 1 << bmek.bit_num; if (status == 1) bmap->entries[bmek.entry_num] |= mask; else bmap->entries[bmek.entry_num] &= ~mask; return 1; } // returns the index of the first bit having status "status" // in the bitmap bmap, and starts looking from position start int BitMap_get(BitMap* bmap, int start, int status){ BitMapEntryKey bmek = BitMap_blockToIndex(start); char map; char mask = 1 << bmek.bit_num; char check = status << bmek.bit_num; //printf("starting bit_num = %d, starting entry_num = %d\n",bmek.bit_num, bmek.entry_num); while (BitMap_indexToBlock(bmek.entry_num, bmek.bit_num) < bmap->num_bits){ //printf("index = %d\n",BitMap_indexToBlock(bmek.entry_num, bmek.bit_num)); map = bmap->entries[bmek.entry_num]; if ( !(map & mask ^ check) & mask != 0 ) return BitMap_indexToBlock(bmek.entry_num, bmek.bit_num); // printf("control = %d, bit_num = %d, entry_num = %d, map = %d\n",mask & map , bmek.bit_num, bmek.entry_num, map); if (bmek.bit_num < 7 ){ bmek.bit_num++; mask = mask << 1; check = check << 1; } else{ bmek.bit_num = 0; mask = 1; check = status; bmek.entry_num++; } } return -1; } void BitMap_print(BitMap* bmap){ int i; int prev_block_used = 0; int block_used; printf("\nBitmap representation:\n"); for (i=0; i < bmap->num_bits; ){ block_used = BitMap_get(bmap, prev_block_used ,1); if (block_used == -1){ printf("0"); i++; } else{ while(prev_block_used < block_used){ printf("0"); prev_block_used++; i++; } printf("1"); prev_block_used++; i++; } } printf("\nEnd of Bitmap\n"); }
3.28125
3
2024-11-18T21:09:28.268584+00:00
2016-02-11T17:26:09
7767ecd29ae41bd4c1a2deb252f898e450437e43
{ "blob_id": "7767ecd29ae41bd4c1a2deb252f898e450437e43", "branch_name": "refs/heads/master", "committer_date": "2016-02-11T17:26:09", "content_id": "9e49c595743534693bbf0b3aab3006d84f900b27", "detected_licenses": [ "MIT" ], "directory_id": "34edab51b4e6966c1b6666152926d505dfbd11a5", "extension": "c", "filename": "xv.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 51531688, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10764, "license": "MIT", "license_type": "permissive", "path": "/src/output/drivers/xv/xv.c", "provenance": "stackv2-0065.json.gz:6718", "repo_name": "xaradevil/tcvp", "revision_date": "2016-02-11T17:26:09", "revision_id": "9d17022cb6470d546e11c65aafa41b940c888d5f", "snapshot_id": "8e5ce807f077fa4c0add31126de68ce7640e40d8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xaradevil/tcvp/9d17022cb6470d546e11c65aafa41b940c888d5f/src/output/drivers/xv/xv.c", "visit_date": "2021-01-10T01:52:50.414533" }
stackv2
/** Copyright (C) 2003-2006 Michael Ahlberg, Måns Rullgård 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 <stdlib.h> #include <string.h> #include <unistd.h> #include <stdint.h> #include <sys/time.h> #include <sys/shm.h> #include <sys/ipc.h> #include <X11/Xlib.h> #include <X11/keysym.h> #include <X11/extensions/XShm.h> #include <X11/extensions/Xvlib.h> #include <pthread.h> #include <tcvp_types.h> #include <xv_tc2.h> #define FRAMES 64 typedef struct xv_window { Display *dpy; Window win; GC gc; XvPortID port; int width, height; int dx, dy, dw, dh; XShmSegmentInfo *shm; XvImage **images; window_manager_t *wm; int last_frame; pthread_mutex_t flock; tcvp_module_t *mod; } xv_window_t; static int do_show(xv_window_t *xvw, int frame) { pthread_mutex_lock(&xvw->flock); XvShmPutImage(xvw->dpy, xvw->port, xvw->win, xvw->gc, xvw->images[frame], 0, 0, xvw->width, xvw->height, xvw->dx, xvw->dy, xvw->dw, xvw->dh, False); XSync(xvw->dpy, False); xvw->last_frame = frame; pthread_mutex_unlock(&xvw->flock); return 0; } static int xv_show(video_driver_t *vd, int frame) { return do_show(vd->private, frame); } static int xv_get(video_driver_t *vd, int frame, u_char **data, int *strides) { xv_window_t *xvw = vd->private; XvImage *xi = xvw->images[frame]; int i; pthread_mutex_lock(&xvw->flock); if(frame == xvw->last_frame){ if(xvw->last_frame == vd->frames - 1) xvw->last_frame = 0; else xvw->last_frame++; } pthread_mutex_unlock(&xvw->flock); for(i = 0; i < xi->num_planes; i++){ data[i] = (u_char*)xi->data + xi->offsets[i]; strides[i] = xi->pitches[i]; } return xi->num_planes; } extern int xve_show(tcvp_module_t *m, tcvp_event_t *te) { xv_window_t *xvw = m->private; if(xvw->last_frame > -1) do_show(xvw, xvw->last_frame); return 0; } extern int xve_move(tcvp_module_t *m, tcvp_event_t *te) { xv_window_t *xvw = m->private; tcvp_wm_move_event_t *me = (tcvp_wm_move_event_t *) te; xvw->dx = me->x; xvw->dy = me->y; xvw->dw = me->w; xvw->dh = me->h; if(xvw->last_frame > -1) do_show(xvw, xvw->last_frame); return 0; } static int xv_close(video_driver_t *vd) { xv_window_t *xvw = vd->private; int i; xvw->mod->private = NULL; tcfree(xvw->mod); for(i = 0; i < vd->frames; i++){ XShmDetach(xvw->dpy, &xvw->shm[i]); shmdt(xvw->shm[i].shmaddr); XFree(xvw->images[i]); } xvw->wm->close(xvw->wm); XCloseDisplay(xvw->dpy); pthread_mutex_destroy(&xvw->flock); free(xvw->images); free(xvw->shm); free(xvw); free(vd); return 0; } static struct { char *name; uint32_t tag; } formats[] = { { "i420", 0x30323449 }, { "yv12", 0x32315659 }, { "yuy2", 0x32595559 }, { "yvyu", 0x55595659 }, { "uyvy", 0x59565955 }, { "rgb555", 0x35315652 }, { "rgb565", 0x36315652 } }; #define NUMFORMATS (sizeof(formats) / sizeof(formats[0])) static uint32_t xv_get_format(const char *fmt) { unsigned int i; for(i = 0; i < NUMFORMATS; i++){ if(!strcmp(fmt, formats[i].name)){ return formats[i].tag; } } return 0; } static int xv_valid_attr(XvAttribute *attr, int n, char *name, int set, int value) { int i; for(i = 0; i < n; i++){ if(!strcmp(attr[i].name, name)) break; } if(i == n) return -1; if(!set) return attr[i].flags & XvGettable? 0: -1; if(!(attr[i].flags & XvSettable)) return -1; if(value < attr[i].min_value || value > attr[i].max_value) return -1; return 0; } extern video_driver_t * xv_open(video_stream_t *vs, tcconf_section_t *cs) { video_driver_t *vd; xv_window_t *xvw; Display *dpy; unsigned int ver, rev, rb, evb, erb; XvAdaptorInfo *xai; XvAttribute *xvattr; u_int na; int nattr; Window win; int i; int frames = tcvp_driver_video_xv_conf_frames?: FRAMES; int color_key; Atom atm; window_manager_t *wm; char *display = NULL; float dasp = 0; char *fmt; uint32_t fmtid = 0; int port = 0; fmt = strstr(vs->codec, "raw-"); if(!fmt) return NULL; fmt += 4; fmtid = xv_get_format(fmt); if(!fmtid && tcvp_driver_video_xv_conf_format){ fmt = tcvp_driver_video_xv_conf_format; tc2_print("XV", TC2_PRINT_WARNING, "using default format '%s'\n", fmt); fmtid = xv_get_format(fmt); } if(!fmtid){ tc2_print("XV", TC2_PRINT_ERROR, "unknown format '%s'\n", fmt); return NULL; } if(cs){ tcconf_getvalue(cs, "video/device", "%s", &display); tcconf_getvalue(cs, "video/aspect", "%f", &dasp); } XInitThreads(); if((dpy = XOpenDisplay(display)) == NULL){ tc2_print("XV", TC2_PRINT_ERROR, "can't open display %s\n", display? display: "NULL"); return NULL; } if(XvQueryExtension(dpy, &ver, &rev, &rb, &evb, &erb) != Success){ tc2_print("XV", TC2_PRINT_ERROR, "XVideo extension not present\n"); return NULL; } tc2_print("XV", TC2_PRINT_DEBUG, "XVideo version %u.%u\n", ver, rev); if(XvQueryAdaptors(dpy, DefaultRootWindow(dpy), &na, &xai) != Success){ tc2_print("XV", TC2_PRINT_ERROR, "XvQueryAdaptors failed\n"); return NULL; } tc2_print("XV", TC2_PRINT_DEBUG, "%i adaptors\n", na); for(i = 0; i < na && !port; i++){ int j; tc2_print("XV", TC2_PRINT_DEBUG, "Adaptor #%i: \"%s\", %i ports, base %i\n", i, xai[i].name, xai[i].num_ports, xai[i].base_id); for(j = 0; j < xai[i].num_ports && !port; j++){ XvImageFormatValues *xif; int nf, k; xif = XvListImageFormats(dpy, xai[i].base_id + j, &nf); for(k = 0; k < nf; k++){ if(xif[k].id == fmtid){ port = xai[i].base_id + j; break; } } XFree(xif); } } XvFreeAdaptorInfo(xai); if(!port){ tc2_print("XV", TC2_PRINT_ERROR, "no suitable port for format %s\n", fmt); return NULL; } tc2_print("XV", TC2_PRINT_DEBUG, "using port %i\n", port); xvw = calloc(1, sizeof(*xvw)); xvw->port = port; xvw->width = vs->width; xvw->height = vs->height; xvw->dw = vs->width; xvw->dh = vs->height; xvw->shm = malloc(frames * sizeof(*xvw->shm)); xvw->images = malloc(frames * sizeof(*xvw->images)); xvw->last_frame = -1; pthread_mutex_init(&xvw->flock, NULL); if(dasp > 0 || (vs->aspect.num && vs->aspect.den)){ float asp = (float) vs->width / vs->height; if(dasp <= 0) dasp = (float) vs->aspect.num / vs->aspect.den; if(dasp > asp) xvw->dw = (float) vs->height * dasp; else xvw->dh = (float) vs->width / dasp; } xvattr = XvQueryPortAttributes(dpy, port, &nattr); for(i = 0; i < driver_video_xv_conf_attribute_count; i++){ char *name = driver_video_xv_conf_attribute[i].name; int value = driver_video_xv_conf_attribute[i].value; if(!xv_valid_attr(xvattr, nattr, name, 1, value)){ if((atm = XInternAtom(dpy, name, True)) != None){ XvSetPortAttribute(dpy, xvw->port, atm, value); } } else { tc2_print("XV", TC2_PRINT_WARNING, "can't set attribute %s to %i\n", name, value); } } if((atm = XInternAtom(dpy, "XV_COLORKEY", True)) != None){ if(tcconf_getvalue(cs, "video/color_key", "%i", &color_key) > 0){ if(!xv_valid_attr(xvattr, nattr, "XV_COLORKEY", 1, color_key)) XvSetPortAttribute(dpy, xvw->port, atm, color_key); else tc2_print("XV", TC2_PRINT_WARNING, "can't set color key\n"); } else { if(!xv_valid_attr(xvattr, nattr, "XV_COLORKEY", 0, 0)){ XvGetPortAttribute(dpy, xvw->port, atm, &color_key); tcconf_clearvalue(cs, "video/color_key"); tcconf_setvalue(cs, "video/color_key", "%i", color_key); } } } XFree(xvattr); xvw->dpy = dpy; xvw->mod = driver_video_xv_new(cs); xvw->mod->private = xvw; xvw->mod->init(xvw->mod); if(!(wm = wm_x11_open(xvw->dw, xvw->dh, cs, 0))){ tcfree(xvw->mod); free(xvw); return NULL; } wm_x11_getwindow(wm, &dpy, &win); xvw->win = win; xvw->gc = DefaultGC(xvw->dpy, DefaultScreen(xvw->dpy)); xvw->wm = wm; for(i = 0; i < frames; i++){ XvImage *xvi; XShmSegmentInfo *shm = &xvw->shm[i]; xvi = XvShmCreateImage(xvw->dpy, xvw->port, fmtid, NULL, vs->width, vs->height, shm); shm->shmid = shmget(IPC_PRIVATE, xvi->data_size, IPC_CREAT | 0777); shm->shmaddr = shmat(shm->shmid, 0, 0); shm->readOnly = False; xvi->data = shm->shmaddr; XShmAttach(xvw->dpy, shm); shmctl(shm->shmid, IPC_RMID, NULL); /* delete now in case we crash */ xvw->images[i] = xvi; } XSync(xvw->dpy, False); vd = calloc(1, sizeof(*vd)); vd->frames = frames; vd->pixel_format = fmt; vd->get_frame = xv_get; vd->show_frame = xv_show; vd->close = xv_close; vd->private = xvw; if(display) free(display); return vd; }
2.0625
2
2024-11-18T21:09:29.722709+00:00
2019-01-26T21:44:49
960380497b4e337f5aecb62c4601a1eceea25d5d
{ "blob_id": "960380497b4e337f5aecb62c4601a1eceea25d5d", "branch_name": "refs/heads/master", "committer_date": "2019-01-26T21:44:49", "content_id": "b66115aae951fc3288d233d932174752ec6bddd4", "detected_licenses": [ "MIT" ], "directory_id": "ab83049141b3a1f35166e11c7e74e7db8be0950d", "extension": "c", "filename": "setSpriteObjectPosition.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": 235, "license": "MIT", "license_type": "permissive", "path": "/player/src/sprite/setSpriteObjectPosition.c", "provenance": "stackv2-0065.json.gz:7488", "repo_name": "blurymind/Tiled2GBA", "revision_date": "2019-01-26T21:44:49", "revision_id": "7f9a4f0c22803eec15e35bdd7fb36f9a9ed5f6b9", "snapshot_id": "773aa25cfa712c2ea37e848eb2d25bb9f2a31541", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/blurymind/Tiled2GBA/7f9a4f0c22803eec15e35bdd7fb36f9a9ed5f6b9/player/src/sprite/setSpriteObjectPosition.c", "visit_date": "2021-01-26T02:28:17.502297" }
stackv2
#include "sprite.h" #include "tonc.h" void setSpriteObjectPosition(OBJ_ATTR* spriteObject, ObjectPoint position) { BFN_SET(spriteObject->attr0, position.y - 8, ATTR0_Y); BFN_SET(spriteObject->attr1, position.x - 8, ATTR1_X); }
2.015625
2
2024-11-18T21:09:29.993380+00:00
2019-03-23T01:35:07
3cb7e0591b0c0d3eac7df34e53a3e24202420edf
{ "blob_id": "3cb7e0591b0c0d3eac7df34e53a3e24202420edf", "branch_name": "refs/heads/master", "committer_date": "2019-03-23T01:35:07", "content_id": "58c44b617aa73ae428d3feecb493f0dece494754", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "df33f1348277ef3bacda73a99c3fcfa8269e73e4", "extension": "c", "filename": "zlib_token.c", "fork_events_count": 2, "gha_created_at": "2017-05-22T04:19:02", "gha_event_created_at": "2018-08-14T20:02:24", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 92010746, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4560, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/servlets/network/http/render/zlib_token.c", "provenance": "stackv2-0065.json.gz:7746", "repo_name": "38/plumber", "revision_date": "2019-03-23T01:35:07", "revision_id": "30fead11cddd6352025dcac0c16065172744c0f9", "snapshot_id": "ab0153ed1b34fffd45c7db20f4e5535158ada0bc", "src_encoding": "UTF-8", "star_events_count": 40, "url": "https://raw.githubusercontent.com/38/plumber/30fead11cddd6352025dcac0c16065172744c0f9/servlets/network/http/render/zlib_token.c", "visit_date": "2021-01-21T18:05:51.981562" }
stackv2
/** * Copyright (C) 2018, Hao Hou **/ #if HAS_ZLIB #include <stdint.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <zlib.h> #include <pservlet.h> #include <pstd.h> #include <pstd/mempool.h> #include <pstd/types/trans.h> #include <zlib_token.h> typedef struct { uint32_t data_source_eos:1; /*!< Indicates we see end-of-stream marker from the data source */ z_stream* zlib_stream; /*!< The zlib stream we are dealing with */ char* input_buf; /*!< The input buffer */ int last_zlib_ret; /*!< The last zlib return value */ } _processor_t; static uint32_t _page_size = 0; static pstd_trans_inst_t* _init(void* data) { z_stream* zs = (z_stream*)data; _processor_t* ret = (_processor_t*)pstd_mempool_alloc(sizeof(_processor_t)); if(NULL == ret) ERROR_LOG_GOTO(ERR, "Cannot allocate memory for the processor"); memset(ret, 0, sizeof(*ret)); ret->zlib_stream = zs; if(NULL == (ret->input_buf = (char*)pstd_mempool_page_alloc())) ERROR_LOG_GOTO(ERR, "Cannot allocate memory for the input buffer"); ret->last_zlib_ret = Z_STREAM_END; ret->zlib_stream->avail_in = 0; return (pstd_trans_inst_t*)ret; ERR: if(NULL != ret) { if(NULL != ret->input_buf) pstd_mempool_page_dealloc(ret->input_buf); pstd_mempool_free(ret); } if(NULL != zs) { deflateEnd(zs); pstd_mempool_free(zs); } return NULL; } static size_t _feed(pstd_trans_inst_t* __restrict stream_proc, const void* __restrict in, size_t size) { _processor_t* proc = (_processor_t*)stream_proc; if(NULL == in) { proc->data_source_eos = 1; return 0; } if(proc->zlib_stream->avail_in > 0 && proc->last_zlib_ret != Z_OK) return 0; size_t ret = size; if(ret > _page_size) ret = _page_size; memcpy(proc->input_buf, in, ret); proc->zlib_stream->next_in = (uint8_t*)proc->input_buf; proc->zlib_stream->avail_in = (uint32_t)ret; proc->last_zlib_ret = Z_OK; return ret; } static size_t _fetch(pstd_trans_inst_t* __restrict stream_proc, void* __restrict out, size_t size) { _processor_t* proc = (_processor_t*)stream_proc; if(proc->last_zlib_ret == Z_STREAM_END) return 0; proc->zlib_stream->next_out = (uint8_t*)out; proc->zlib_stream->avail_out = (uint32_t)size; proc->last_zlib_ret = deflate(proc->zlib_stream, proc->data_source_eos ? Z_FINISH : Z_NO_FLUSH); if(proc->last_zlib_ret == Z_STREAM_ERROR) ERROR_RETURN_LOG(size_t, "Zlib returns an error: %s", proc->zlib_stream->msg); return (size_t)(size - proc->zlib_stream->avail_out); } static int _cleanup(pstd_trans_inst_t* stream_proc) { int ret = 0; _processor_t* proc = (_processor_t*)stream_proc; if(NULL != proc->input_buf && ERROR_CODE(int) == pstd_mempool_page_dealloc(proc->input_buf)) ret = ERROR_CODE(int); if(ERROR_CODE(int) == pstd_mempool_free(proc)) ret = ERROR_CODE(int); if(NULL != proc->zlib_stream) { if(Z_OK != deflateEnd(proc->zlib_stream)) ret = ERROR_CODE(int); if(ERROR_CODE(int) == pstd_mempool_free(proc->zlib_stream)) ret = ERROR_CODE(int); } return ret; } scope_token_t zlib_token_encode(scope_token_t data_token, zlib_token_format_t format, int level) { if(_page_size == 0) _page_size = (uint32_t)getpagesize(); if(ERROR_CODE(scope_token_t) == data_token || 0 == data_token || level < 0 || level > 9) ERROR_RETURN_LOG(scope_token_t, "Invalid arguments"); z_stream* zs = NULL; if(NULL == (zs = (z_stream*)pstd_mempool_alloc(sizeof(z_stream)))) ERROR_LOG_ERRNO_GOTO(ERR, "Cannot allocate memory for the z_stream"); zs->zalloc = Z_NULL; zs->zfree = Z_NULL; zs->opaque = Z_NULL; switch(format) { case ZLIB_TOKEN_FORMAT_DEFLATE: if(Z_OK != deflateInit(zs, level)) ERROR_LOG_GOTO(ERR, "Cannot initialize the zlib for deflate algoritm"); break; case ZLIB_TOKEN_FORMAT_GZIP: if(Z_OK != deflateInit2(zs, level, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY)) ERROR_LOG_GOTO(ERR, "Cannot itnialize the zlib for gzip"); break; default: ERROR_LOG_GOTO(ERR, "Invalid format option"); } pstd_trans_desc_t desc = { .data = zs, .init_func = _init, .feed_func = _feed, .fetch_func = _fetch, .cleanup_func = _cleanup }; pstd_trans_t* trans = pstd_trans_new(data_token, desc); if(NULL == trans) ERROR_RETURN_LOG(scope_token_t, "Cannot create stream processor object"); scope_token_t result = pstd_trans_commit(trans); if(ERROR_CODE(scope_token_t) == result) { pstd_trans_free(trans); return ERROR_CODE(scope_token_t); } return result; ERR: pstd_mempool_free(zs); return ERROR_CODE(scope_token_t); } #endif
2.5625
3
2024-11-18T21:09:30.673800+00:00
2014-10-11T15:35:31
63f9578436c434002ccfeb26949c053e542a39fe
{ "blob_id": "63f9578436c434002ccfeb26949c053e542a39fe", "branch_name": "refs/heads/master", "committer_date": "2014-10-11T15:35:31", "content_id": "b95f4810f2c4e8d5f6b386f70fcede6de56ec7da", "detected_licenses": [ "MIT" ], "directory_id": "fada3491749cc3f2274ed5439f2232097dd0d1fc", "extension": "c", "filename": "drv_uart.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 23516329, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10664, "license": "MIT", "license_type": "permissive", "path": "/src/drv_uart.c", "provenance": "stackv2-0065.json.gz:8260", "repo_name": "oroca/SkyRover_CM", "revision_date": "2014-10-11T15:35:31", "revision_id": "334d5d098ca00c446dc5589d5e991ce82d832133", "snapshot_id": "bbd1ebb75ada00a8974094377279941e720bd170", "src_encoding": "WINDOWS-1252", "star_events_count": 0, "url": "https://raw.githubusercontent.com/oroca/SkyRover_CM/334d5d098ca00c446dc5589d5e991ce82d832133/src/drv_uart.c", "visit_date": "2020-09-24T11:34:33.537649" }
stackv2
#include "board.h" /* DMA UART routines idea lifted from AutoQuad Copyright © 2011 Bill Nesbitt */ static uartPort_t uartPort1; static uartPort_t uartPort2; // USART1 - Telemetry (RX/TX by DMA) uartPort_t *serialUSART1(uint32_t baudRate, portMode_t mode) { uartPort_t *s; static volatile uint8_t rx1Buffer[UART1_RX_BUFFER_SIZE]; static volatile uint8_t tx1Buffer[UART1_TX_BUFFER_SIZE]; gpio_config_t gpio; NVIC_InitTypeDef NVIC_InitStructure; s = &uartPort1; s->port.vTable = uartVTable; s->port.baudRate = baudRate; s->port.rxBuffer = rx1Buffer; s->port.txBuffer = tx1Buffer; s->port.rxBufferSize = UART1_RX_BUFFER_SIZE; s->port.txBufferSize = UART1_TX_BUFFER_SIZE; s->rxDMAChannel = DMA1_Channel5; s->txDMAChannel = DMA1_Channel4; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); // USART1_TX PA9 // USART1_RX PA10 gpio.speed = Speed_2MHz; gpio.pin = Pin_9; gpio.mode = Mode_AF_PP; if (mode & MODE_TX) gpioInit(GPIOA, &gpio); gpio.pin = Pin_10; gpio.mode = Mode_IPU; if (mode & MODE_RX) gpioInit(GPIOA, &gpio); // DMA TX Interrupt NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel4_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); return s; } // USART2 - GPS or Spektrum or ?? (RX + TX by IRQ) uartPort_t *serialUSART2(uint32_t baudRate, portMode_t mode) { uartPort_t *s; static volatile uint8_t rx2Buffer[UART2_RX_BUFFER_SIZE]; static volatile uint8_t tx2Buffer[UART2_TX_BUFFER_SIZE]; gpio_config_t gpio; NVIC_InitTypeDef NVIC_InitStructure; s = &uartPort2; s->port.vTable = uartVTable; s->port.baudRate = baudRate; s->port.rxBufferSize = UART2_RX_BUFFER_SIZE; s->port.txBufferSize = UART2_TX_BUFFER_SIZE; s->port.rxBuffer = rx2Buffer; s->port.txBuffer = tx2Buffer; s->USARTx = USART2; RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); // USART2_TX PA2 // USART2_RX PA3 gpio.speed = Speed_2MHz; gpio.pin = Pin_2; gpio.mode = Mode_AF_PP; if (mode & MODE_TX) gpioInit(GPIOA, &gpio); gpio.pin = Pin_3; gpio.mode = Mode_IPU; if (mode & MODE_RX) gpioInit(GPIOA, &gpio); // RX/TX Interrupt NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); return s; } serialPort_t *uartOpen(USART_TypeDef *USARTx, serialReceiveCallbackPtr callback, uint32_t baudRate, portMode_t mode) { DMA_InitTypeDef DMA_InitStructure; USART_InitTypeDef USART_InitStructure; uartPort_t *s = NULL; if (USARTx == USART1) s = serialUSART1(baudRate, mode); if (USARTx == USART2) s = serialUSART2(baudRate, mode); s->USARTx = USARTx; // common serial initialisation code should move to serialPort::init() s->port.rxBufferHead = s->port.rxBufferTail = 0; s->port.txBufferHead = s->port.txBufferTail = 0; // callback for IRQ-based RX ONLY s->port.callback = callback; s->port.mode = mode; s->port.baudRate = baudRate; USART_InitStructure.USART_BaudRate = baudRate; USART_InitStructure.USART_WordLength = USART_WordLength_8b; if (mode & MODE_SBUS) { USART_InitStructure.USART_StopBits = USART_StopBits_2; USART_InitStructure.USART_Parity = USART_Parity_Even; } else { USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; } USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = 0; if (mode & MODE_RX) USART_InitStructure.USART_Mode |= USART_Mode_Rx; if (mode & MODE_TX) USART_InitStructure.USART_Mode |= USART_Mode_Tx; USART_Init(USARTx, &USART_InitStructure); USART_Cmd(USARTx, ENABLE); DMA_StructInit(&DMA_InitStructure); DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&USARTx->DR; DMA_InitStructure.DMA_Priority = DMA_Priority_Medium; DMA_InitStructure.DMA_M2M = DMA_M2M_Disable; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; // Receive DMA or IRQ if (mode & MODE_RX) { if (s->rxDMAChannel) { DMA_InitStructure.DMA_BufferSize = s->port.rxBufferSize; DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC; DMA_InitStructure.DMA_Mode = DMA_Mode_Circular; DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)s->port.rxBuffer; DMA_DeInit(s->rxDMAChannel); DMA_Init(s->rxDMAChannel, &DMA_InitStructure); DMA_Cmd(s->rxDMAChannel, ENABLE); USART_DMACmd(USARTx, USART_DMAReq_Rx, ENABLE); s->rxDMAPos = DMA_GetCurrDataCounter(s->rxDMAChannel); } else { USART_ITConfig(USARTx, USART_IT_RXNE, ENABLE); } } // Transmit DMA or IRQ if (mode & MODE_TX) { if (s->txDMAChannel) { DMA_InitStructure.DMA_BufferSize = s->port.txBufferSize; DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST; DMA_InitStructure.DMA_Mode = DMA_Mode_Normal; DMA_DeInit(s->txDMAChannel); DMA_Init(s->txDMAChannel, &DMA_InitStructure); DMA_ITConfig(s->txDMAChannel, DMA_IT_TC, ENABLE); DMA_SetCurrDataCounter(s->txDMAChannel, 0); s->txDMAChannel->CNDTR = 0; USART_DMACmd(USARTx, USART_DMAReq_Tx, ENABLE); } else { USART_ITConfig(USARTx, USART_IT_TXE, ENABLE); } } return (serialPort_t *)s; } void uartSetBaudRate(serialPort_t *instance, uint32_t baudRate) { USART_InitTypeDef USART_InitStructure; uartPort_t *s = (uartPort_t *)instance; USART_InitStructure.USART_BaudRate = baudRate; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = 0; if (s->port.mode & MODE_RX) USART_InitStructure.USART_Mode |= USART_Mode_Rx; if (s->port.mode & MODE_TX) USART_InitStructure.USART_Mode |= USART_Mode_Tx; USART_Init(s->USARTx, &USART_InitStructure); s->port.baudRate = baudRate; } static void uartStartTxDMA(uartPort_t *s) { s->txDMAChannel->CMAR = (uint32_t)&s->port.txBuffer[s->port.txBufferTail]; if (s->port.txBufferHead > s->port.txBufferTail) { s->txDMAChannel->CNDTR = s->port.txBufferHead - s->port.txBufferTail; s->port.txBufferTail = s->port.txBufferHead; } else { s->txDMAChannel->CNDTR = s->port.txBufferSize - s->port.txBufferTail; s->port.txBufferTail = 0; } s->txDMAEmpty = false; DMA_Cmd(s->txDMAChannel, ENABLE); } uint8_t uartTotalBytesWaiting(serialPort_t *instance) { uartPort_t *s = (uartPort_t*)instance; // FIXME always returns 1 or 0, not the amount of bytes waiting if (s->rxDMAChannel) return s->rxDMAChannel->CNDTR != s->rxDMAPos; else return s->port.rxBufferTail != s->port.rxBufferHead; } // BUGBUG TODO TODO FIXME - What is the bug? bool isUartTransmitBufferEmpty(serialPort_t *instance) { uartPort_t *s = (uartPort_t *)instance; if (s->txDMAChannel) return s->txDMAEmpty; else return s->port.txBufferTail == s->port.txBufferHead; } uint8_t uartRead(serialPort_t *instance) { uint8_t ch; uartPort_t *s = (uartPort_t *)instance; if (s->rxDMAChannel) { ch = s->port.rxBuffer[s->port.rxBufferSize - s->rxDMAPos]; if (--s->rxDMAPos == 0) s->rxDMAPos = s->port.rxBufferSize; } else { ch = s->port.rxBuffer[s->port.rxBufferTail]; s->port.rxBufferTail = (s->port.rxBufferTail + 1) % s->port.rxBufferSize; } return ch; } void uartWrite(serialPort_t *instance, uint8_t ch) { uartPort_t *s = (uartPort_t *)instance; s->port.txBuffer[s->port.txBufferHead] = ch; s->port.txBufferHead = (s->port.txBufferHead + 1) % s->port.txBufferSize; if (s->txDMAChannel) { if (!(s->txDMAChannel->CCR & 1)) uartStartTxDMA(s); } else { USART_ITConfig(s->USARTx, USART_IT_TXE, ENABLE); } } const struct serialPortVTable uartVTable[] = { { uartWrite, uartTotalBytesWaiting, uartRead, uartSetBaudRate, isUartTransmitBufferEmpty } }; // Handlers // USART1 Tx DMA Handler void DMA1_Channel4_IRQHandler(void) { uartPort_t *s = &uartPort1; DMA_ClearITPendingBit(DMA1_IT_TC4); DMA_Cmd(s->txDMAChannel, DISABLE); if (s->port.txBufferHead != s->port.txBufferTail) uartStartTxDMA(s); else s->txDMAEmpty = true; } // USART1 Tx IRQ Handler void USART1_IRQHandler(void) { uartPort_t *s = &uartPort1; uint16_t SR = s->USARTx->SR; if (SR & USART_FLAG_TXE) { if (s->port.txBufferTail != s->port.txBufferHead) { s->USARTx->DR = s->port.txBuffer[s->port.txBufferTail]; s->port.txBufferTail = (s->port.txBufferTail + 1) % s->port.txBufferSize; } else { USART_ITConfig(s->USARTx, USART_IT_TXE, DISABLE); } } } // USART2 Rx/Tx IRQ Handler void USART2_IRQHandler(void) { uartPort_t *s = &uartPort2; uint16_t SR = s->USARTx->SR; if (SR & USART_FLAG_RXNE) { // If we registered a callback, pass crap there if (s->port.callback) { s->port.callback(s->USARTx->DR); } else { s->port.rxBuffer[s->port.rxBufferHead] = s->USARTx->DR; s->port.rxBufferHead = (s->port.rxBufferHead + 1) % s->port.rxBufferSize; } } if (SR & USART_FLAG_TXE) { if (s->port.txBufferTail != s->port.txBufferHead) { s->USARTx->DR = s->port.txBuffer[s->port.txBufferTail]; s->port.txBufferTail = (s->port.txBufferTail + 1) % s->port.txBufferSize; } else { USART_ITConfig(s->USARTx, USART_IT_TXE, DISABLE); } } }
2.140625
2
2024-11-18T21:09:30.765752+00:00
2019-12-06T00:05:17
56df9620f08bae3535e838dc202fe281a7689a56
{ "blob_id": "56df9620f08bae3535e838dc202fe281a7689a56", "branch_name": "refs/heads/master", "committer_date": "2019-12-06T00:05:17", "content_id": "621337327b824a11b1ad2e440485285c5185e48b", "detected_licenses": [ "MIT" ], "directory_id": "3a91fc3584707a2db8777bcc7639c39baac06855", "extension": "c", "filename": "tests.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 210479492, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 41929, "license": "MIT", "license_type": "permissive", "path": "/tests.c", "provenance": "stackv2-0065.json.gz:8388", "repo_name": "avolang/avocc", "revision_date": "2019-12-06T00:05:17", "revision_id": "b258b3d1ae7e34f76bec7830563e2302a45322c9", "snapshot_id": "2cfc687804e52863b24931b605304e08315d23b0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/avolang/avocc/b258b3d1ae7e34f76bec7830563e2302a45322c9/tests.c", "visit_date": "2020-07-31T04:04:45.846531" }
stackv2
#include "tests.h" #include "avocc.h" #include <stdio.h> #include <string.h> void test_source_init_free() { avoc_source src0; avoc_source_init(&src0, NULL, NULL, 0L); assert_okb(src0.buf_data == NULL); assert_eql(src0.buf_len, 0L); assert_eql(src0.buf_pos, 0L); assert_eq(src0.cur_cp, 0); assert_eq(src0.nxt_cp, 0); assert_eql(src0.cur_cp_pos, 0L); assert_eql(src0.nxt_cp_pos, 0L); assert_eql(src0.col, 1L); assert_eql(src0.row, 1L); assert_okb(src0.name == NULL); avoc_source src1; load_string(&src1, "avocado"); assert_ok(src1.buf_data != NULL); assert_okb(src1.buf_len == 7L); assert_okb(src1.buf_data != NULL && strncmp("avocado", (char *)src1.buf_data, src1.buf_len) == 0); assert_eql(src1.buf_pos, 0L); assert_eq(src1.cur_cp, 0); assert_eq(src1.nxt_cp, 0); assert_eql(src1.cur_cp_pos, 0L); assert_eql(src1.nxt_cp_pos, 0L); assert_eql(src1.col, 1L); assert_eql(src1.row, 1L); avoc_source_free(&src1); assert_okb(src0.buf_data == NULL); assert_okb(src0.name == NULL); avoc_source src2; avoc_source_init(&src2, "filename", NULL, 0L); assert_okb(src2.name != NULL); assert_eqs(src2.name, "filename"); avoc_source_free(&src2); } void test_source_move_fwd_ascii() { avoc_source src; load_string(&src, "ABC"); assert_eql(src.buf_pos, 0L); assert_eq(src.cur_cp, 0); assert_eq(src.nxt_cp, 0); assert_eql(src.cur_cp_pos, 0L); assert_eql(src.nxt_cp_pos, 0L); avoc_source_fwd(&src); assert_eql(src.buf_pos, 2L); assert_eq(src.cur_cp, 'A'); assert_eq(src.nxt_cp, 'B'); assert_eql(src.cur_cp_pos, 0L); assert_eql(src.nxt_cp_pos, 1L); avoc_source_fwd(&src); assert_eql(src.buf_pos, 3L); assert_eq(src.cur_cp, 'B'); assert_eq(src.nxt_cp, 'C'); assert_eql(src.cur_cp_pos, 1L); assert_eql(src.nxt_cp_pos, 2L); avoc_source_fwd(&src); assert_eql(src.buf_pos, 3L); assert_eq(src.cur_cp, 'C'); assert_eq(src.nxt_cp, UTF8_END); assert_eql(src.cur_cp_pos, 2L); assert_eql(src.nxt_cp_pos, 3L); avoc_source_fwd(&src); assert_eql(src.buf_pos, 3L); assert_eq(src.cur_cp, UTF8_END); assert_eq(src.nxt_cp, UTF8_END); assert_eql(src.cur_cp_pos, 3L); assert_eql(src.nxt_cp_pos, 3L); avoc_source_fwd(&src); assert_eql(src.buf_pos, 3L); assert_eq(src.cur_cp, UTF8_END); assert_eq(src.nxt_cp, UTF8_END); assert_eql(src.cur_cp_pos, 3L); assert_eql(src.nxt_cp_pos, 3L); avoc_source_free(&src); } void test_source_move_fwd_utf8() { avoc_source src; // One continuation (UTF-8) load_string(&src, "\xC2\xA1"); // U+00A1 avoc_source_fwd(&src); assert_eql(src.buf_pos, 2L); assert_eq(src.cur_cp, 0x00A1); assert_eq(src.nxt_cp, UTF8_END); assert_eql(src.cur_cp_pos, 0L); assert_eql(src.nxt_cp_pos, 2L); avoc_source_free(&src); // Two continuations (UTF-8) load_string(&src, "\xE0\xA0\x80"); // U+0800 avoc_source_fwd(&src); assert_eql(src.buf_pos, 3L); assert_eq(src.cur_cp, 0x0800); assert_eq(src.nxt_cp, UTF8_END); assert_eql(src.cur_cp_pos, 0L); assert_eql(src.nxt_cp_pos, 3L); avoc_source_free(&src); load_string(&src, "\xEE\x80\x80"); // U+E000 (reserved) avoc_source_fwd(&src); assert_eql(src.buf_pos, 3L); assert_eq(src.cur_cp, 0xE000); assert_eq(src.nxt_cp, UTF8_END); assert_eql(src.cur_cp_pos, 0L); assert_eql(src.nxt_cp_pos, 3L); avoc_source_free(&src); // Three continuations (UTF-8) load_string(&src, "\xF0\x90\x80\x81"); // U+10001 avoc_source_fwd(&src); assert_eql(src.buf_pos, 4L); assert_eq(src.cur_cp, 0x10001); assert_eq(src.nxt_cp, UTF8_END); assert_eql(src.cur_cp_pos, 0L); assert_eql(src.nxt_cp_pos, 4L); avoc_source_free(&src); load_string(&src, "\xF0\x9F\x98\x8A"); // U+1F60A (smiling face) avoc_source_fwd(&src); assert_eql(src.buf_pos, 4L); assert_eq(src.cur_cp, 0x1F60A); assert_eq(src.nxt_cp, UTF8_END); assert_eql(src.cur_cp_pos, 0L); assert_eql(src.nxt_cp_pos, 4L); avoc_source_free(&src); // U+1F60A U+1F951 (smiling face, avocado) load_string(&src, "\xF0\x9F\x98\x8A\xF0\x9F\xA5\x91"); avoc_source_fwd(&src); assert_eql(src.buf_pos, 8L); assert_eq(src.cur_cp, 0x1F60A); assert_eq(src.nxt_cp, 0x1F951); assert_eql(src.cur_cp_pos, 0L); assert_eql(src.nxt_cp_pos, 4L); avoc_source_free(&src); // 'A' U+1F951 'V' 'O' load_string(&src, "A\xF0\x9F\xA5\x91VO"); avoc_source_fwd(&src); assert_eql(src.buf_pos, 5L); assert_eq(src.cur_cp, 'A'); assert_eq(src.nxt_cp, 0x1F951); assert_eql(src.cur_cp_pos, 0L); assert_eql(src.nxt_cp_pos, 1L); avoc_source_fwd(&src); assert_eql(src.buf_pos, 6L); assert_eq(src.cur_cp, 0x1F951); assert_eq(src.nxt_cp, 'V'); assert_eql(src.cur_cp_pos, 1L); assert_eql(src.nxt_cp_pos, 5L); avoc_source_fwd(&src); assert_eql(src.buf_pos, 7L); assert_eq(src.cur_cp, 'V'); assert_eq(src.nxt_cp, 'O'); assert_eql(src.cur_cp_pos, 5L); assert_eql(src.nxt_cp_pos, 6L); avoc_source_fwd(&src); assert_eql(src.buf_pos, 7L); assert_eq(src.cur_cp, 'O'); assert_eq(src.nxt_cp, UTF8_END); assert_eql(src.cur_cp_pos, 6L); assert_eql(src.nxt_cp_pos, 7L); avoc_source_free(&src); } void test_source_move_fwd_newl() { avoc_source src; load_string(&src, "A\nB"); assert_eql(src.row, 1L); assert_eql(src.col, 1L); avoc_source_fwd(&src); assert_eql(src.row, 1L); assert_eql(src.col, 2L); avoc_source_fwd(&src); assert_eql(src.row, 2L); assert_eql(src.col, 1L); avoc_source_free(&src); } void test_token_init() { avoc_token token; avoc_token_init(&token); assert_eq(token.type, 0); assert_eql(token.offset, 0L); assert_eql(token.length, 0L); assert_eql(token.auxlen, 0L); } void test_token_next_singlechar() { avoc_source src; avoc_status status; avoc_token token; load_string(&src, ""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_EOF); avoc_source_free(&src); load_string(&src, "\n"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_EOL); avoc_source_free(&src); load_string(&src, ":"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_COLON); assert_eql(token.offset, 0L); assert_eql(token.length, 1L); avoc_source_free(&src); load_string(&src, "<[("); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_CALL_S); assert_eql(token.offset, 0L); assert_eql(token.length, 1L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIST_S); assert_eql(token.offset, 1L); assert_eql(token.length, 1L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_CALL_S); assert_eql(token.offset, 2L); assert_eql(token.length, 1L); avoc_source_free(&src); load_string(&src, ")]>"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_CALL_E); assert_eql(token.offset, 0L); assert_eql(token.length, 1L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIST_E); assert_eql(token.offset, 1L); assert_eql(token.length, 1L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_CALL_E); assert_eql(token.offset, 2L); assert_eql(token.length, 1L); avoc_source_free(&src); } void test_token_next_comments() { avoc_source src; avoc_status status; avoc_token token; load_string(&src, "; this is a line comment\n"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_COMMENT); assert_eql(token.offset, 0L); assert_eql(token.length, 25L); avoc_source_free(&src); load_string(&src, ";; this is a \n block comment ;;\n"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_COMMENT); assert_eql(token.offset, 0L); assert_eql(token.length, 31L); avoc_source_free(&src); load_string(&src, ";; a ;; ;; b ;; ;c\n"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_COMMENT); assert_eql(token.offset, 0L); assert_eql(token.length, 7L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_COMMENT); assert_eql(token.offset, 8L); assert_eql(token.length, 7L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_COMMENT); assert_eql(token.offset, 16L); assert_eql(token.length, 3L); avoc_source_free(&src); } void test_token_next_str_lit() { avoc_source src; avoc_status status; avoc_token token; load_string(&src, "\"string\""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 0L); assert_eql(token.length, 8L); assert_eql(token.auxlen, 6L); avoc_source_free(&src); load_string(&src, "\"a\\\"b\""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 0L); assert_eql(token.length, 6L); assert_eql(token.auxlen, 3L); avoc_source_free(&src); load_string(&src, "\"a\" \"b\""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 0L); assert_eql(token.length, 3L); assert_eql(token.auxlen, 1L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 4L); assert_eql(token.length, 3L); assert_eql(token.auxlen, 1L); avoc_source_free(&src); load_string(&src, "\"\\n\""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); assert_eql(token.auxlen, 1L); avoc_source_free(&src); load_string(&src, "\"\\\\\""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); assert_eql(token.auxlen, 1L); avoc_source_free(&src); load_string(&src, "\"\\xFF\""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 0L); assert_eql(token.length, 6L); assert_eql(token.auxlen, 1L); avoc_source_free(&src); load_string(&src, "\"\\u00A1\""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 0L); assert_eql(token.length, 8L); assert_eql(token.auxlen, 2L); avoc_source_free(&src); } void test_token_next_num_lit() { avoc_source src; avoc_status status; avoc_token token; load_string(&src, "1234"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, "1u32"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, "0x12"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, "0b01"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, "0o66"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, "0.12"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, ".123"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, "-.12"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, "-.12f32"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 7L); avoc_source_free(&src); load_string(&src, "1 -2 .3 4i64"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 1L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 2L); assert_eql(token.length, 2L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 5L); assert_eql(token.length, 2L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 8L); assert_eql(token.length, 4L); avoc_source_free(&src); } void test_token_next_nilbol_lit() { avoc_source src; avoc_status status; avoc_token token; load_string(&src, "false true"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_BOL); assert_eql(token.offset, 0L); assert_eql(token.length, 5L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_BOL); assert_eql(token.offset, 6L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, "falses trues"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); avoc_source_free(&src); load_string(&src, "nil nil"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_NIL); assert_eql(token.offset, 0L); assert_eql(token.length, 3L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_NIL); assert_eql(token.offset, 4L); assert_eql(token.length, 3L); avoc_source_free(&src); load_string(&src, "nils nils"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); assert_eql(token.offset, 5L); assert_eql(token.length, 4L); avoc_source_free(&src); } void test_token_next_id() { avoc_source src; avoc_status status; avoc_token token; load_string(&src, "var"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); assert_eql(token.offset, 0L); assert_eql(token.length, 3L); avoc_source_free(&src); load_string(&src, "\xF0\x9F\xA5\x91"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); avoc_source_free(&src); load_string(&src, "\xF0\x9F\xA5\x91 A"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); assert_eql(token.offset, 0L); assert_eql(token.length, 4L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); assert_eql(token.offset, 5L); assert_eql(token.length, 1L); avoc_source_free(&src); } void test_token_edge_cases() { avoc_source src; avoc_status status; avoc_token token; load_string(&src, "-.nonum"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); assert_eql(token.offset, 0L); assert_eql(token.length, 7L); avoc_source_free(&src); load_string(&src, "-nonum"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); assert_eql(token.offset, 0L); assert_eql(token.length, 6L); avoc_source_free(&src); load_string(&src, ".nonum"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_ID); assert_eql(token.offset, 0L); assert_eql(token.length, 6L); avoc_source_free(&src); // this is not an error: a token number is detected, // however this should fail on parsing load_string(&src, "0xNUMBER?"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 0L); assert_eql(token.length, 9L); avoc_source_free(&src); load_string(&src, ";; \xF0\x9F\xA5\x91 ;;"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_COMMENT); assert_eql(token.offset, 0L); assert_eql(token.length, 10L); avoc_source_free(&src); load_string(&src, ";; \xF0\x9F\xA5\x91 ;; 1 ; something \n 2"); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_COMMENT); assert_eql(token.offset, 0L); assert_eql(token.length, 10L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 11L); assert_eql(token.length, 1L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_COMMENT); assert_eql(token.offset, 13L); assert_eql(token.length, 13L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_NUM); assert_eql(token.offset, 27L); assert_eql(token.length, 1L); avoc_source_free(&src); load_string(&src, "\"\xF0\x9F\xA5\x91\""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 0L); assert_eql(token.length, 6L); avoc_source_free(&src); load_string(&src, "\"\xF0\x9F\xA5\x91 avocado\" \"a\""); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 0L); assert_eql(token.length, 14L); status = avoc_next_token(&src, &token); assert_okb(status == OK); assert_eq(token.type, TOKEN_LIT_STR); assert_eql(token.offset, 15L); assert_eql(token.length, 3L); avoc_source_free(&src); } void test_lists() { avoc_item item1, item2, item3, item4; avoc_list list1, list2; avoc_item_init(&item1); assert_eq(item1.type, 0); assert_eql(item1.as_u64, 0UL); assert_ok(item1.next_sibling == NULL); assert_ok(item1.prev_sibling == NULL); avoc_list_init(&list1); assert_ok(list1.head == NULL); assert_ok(list1.tail == NULL); assert_eql(list1.item_count, 0L); avoc_list_push(&list1, &item1); assert_eql(list1.item_count, 1L); assert_okb(list1.head == &item1); assert_okb(list1.tail == &item1); assert_okb(list1.head->next_sibling == NULL); assert_okb(list1.tail->next_sibling == NULL); avoc_item_init(&item2); avoc_list_push(&list1, &item2); assert_eql(list1.item_count, 2L); assert_okb(list1.head == &item1); assert_okb(list1.tail == &item2); assert_okb(list1.head->next_sibling == &item2); assert_okb(list1.tail->prev_sibling == &item1); assert_okb(list1.tail->next_sibling == NULL); avoc_item_init(&item3); avoc_item_init(&item4); avoc_list_init(&list2); avoc_list_push(&list2, &item3); avoc_list_push(&list2, &item4); avoc_list_merge(&list1, &list2); assert_okb(list1.tail == &item4); assert_okb(list1.tail->prev_sibling == &item3); assert_okb(item2.next_sibling == &item3); assert_okb(item3.prev_sibling == &item2); } void test_parse_bol_lit() { avoc_source src; avoc_token token; avoc_item item; avoc_status status; avoc_item_init(&item); load_string(&src, "true false"); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_BOL); assert_eq(item.as_bol, 1); avoc_item_free(&item); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_BOL); assert_eq(item.as_bol, 0); avoc_source_free(&src); avoc_item_free(&item); } void test_parse_int_lit() { avoc_source src; avoc_token token; avoc_item item; avoc_status status; load_string(&src, "0 1i32 2i64 3u32 4u64"); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, 0); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, 1); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I64); assert_eql(item.as_i64, 2L); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_U32); assert_eq(item.as_u32, 3); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_U64); assert_eql(item.as_u64, 4UL); avoc_source_free(&src); load_string(&src, "0b11 0o77 0xFF 0b0i32 0o77i64 0xFFu32"); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, 3); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, 077); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, 0xFF); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, 0); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I64); assert_eql(item.as_i64, 077L); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_U32); assert_eq(item.as_u32, 0xFF); avoc_source_free(&src); load_string(&src, "-1 -2i32 -0x1 -0x1i64"); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, -1); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, -2); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, -0x1); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I64); assert_eql(item.as_i64, -0x1L); avoc_source_free(&src); } void test_parse_flt_lit() { avoc_source src; avoc_token token; avoc_item item; avoc_status status; load_string(&src, "0.1 .2 3.4f32 .5f64"); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_F32); assert_eqf(item.as_f32, 0.1f); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_F32); assert_eqf(item.as_f32, 0.2f); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_F32); assert_eqf(item.as_f32, 3.4f); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_F64); assert_eqf(item.as_f64, 0.5f); avoc_source_free(&src); load_string(&src, "-0.1 -.2 -3.4f32 -.5f64"); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_F32); assert_eqf(item.as_f32, -0.1f); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_F32); assert_eqf(item.as_f32, -0.2f); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_F32); assert_eqf(item.as_f32, -3.4f); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_F64); assert_eqf(item.as_f64, -0.5f); avoc_source_free(&src); } void test_parse_str_lit() { avoc_source src; avoc_token token; avoc_item item; avoc_status status; load_string(&src, "'str1' \"str2\" `str3`"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_STR); assert_eqs(item.as_str, "str1"); avoc_item_free(&item); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_STR); assert_eqs(item.as_str, "str2"); avoc_item_free(&item); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_STR); assert_eqs(item.as_str, "str3"); avoc_source_free(&src); avoc_item_free(&item); load_string(&src, "'c\\\\c'"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_STR); assert_eqs(item.as_str, "c\\c"); avoc_item_free(&item); avoc_source_free(&src); load_string(&src, "'c\\x0Ac'"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_STR); assert_eqs(item.as_str, "c\nc"); avoc_item_free(&item); avoc_source_free(&src); load_string(&src, "'x \\u00A1 x'"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_STR); assert_eqs(item.as_str, "x \xC2\xA1 x"); avoc_item_free(&item); avoc_source_free(&src); load_string(&src, "'x \\U0001F60A x'"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_STR); assert_eqs(item.as_str, "x \xF0\x9F\x98\x8A x"); avoc_item_free(&item); avoc_source_free(&src); } void test_parse_lst_lit() { avoc_source src; avoc_token token; avoc_item item; avoc_list *list; avoc_status status; load_string(&src, "[first second 3]"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_LST); assert_okb(item.as_list != NULL); list = item.as_list; assert_eq(list->head->type, ITEM_SYM); assert_eqs(list->head->as_str, "first"); assert_okb(list->head->next_sibling != NULL); assert_eq(list->head->next_sibling->type, ITEM_SYM); assert_eqs(list->head->next_sibling->as_str, "second"); assert_eq(list->tail->type, ITEM_LIT_I32); assert_eq(list->tail->as_i32, 3); avoc_item_free(&item); avoc_source_free(&src); load_string(&src, "[first [second]]"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_lit(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_LST); assert_okb(item.as_list != NULL); list = item.as_list; assert_eq(list->head->type, ITEM_SYM); assert_eqs(list->head->as_str, "first"); assert_okb(list->tail->type == ITEM_LIT_LST); avoc_item *nested_head = list->tail->as_list->head; assert_eq(nested_head->type, ITEM_SYM); assert_eqs(nested_head->as_str, "second"); avoc_item_free(&item); avoc_source_free(&src); } void test_parse_sym_no_type() { avoc_source src; avoc_token token; avoc_item item; avoc_status status; load_string(&src, "sym1 SYM2 $sym3 \xF0\x9F\xA5\x91"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_sym(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_str, "sym1"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_sym(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_str, "SYM2"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_sym(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_str, "$sym3"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_sym(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_str, "\xF0\x9F\xA5\x91"); avoc_item_free(&item); avoc_source_free(&src); } void test_parse_sym_with_ord_type() { avoc_source src; avoc_token token; avoc_item item; avoc_status status; load_string( &src, "sym1:type1 SYM2:TYPE2 $sym3:$type3 \xF0\x9F\xA5\x91:\xF0\x9F\xA5\x91"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_sym(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_str, "sym1"); assert_eqs(item.sym_ordinary_type, "type1"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_sym(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_str, "SYM2"); assert_eqs(item.sym_ordinary_type, "TYPE2"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_sym(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_str, "$sym3"); assert_eqs(item.sym_ordinary_type, "$type3"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_sym(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_str, "\xF0\x9F\xA5\x91"); assert_eqs(item.sym_ordinary_type, "\xF0\x9F\xA5\x91"); avoc_item_free(&item); avoc_source_free(&src); } void test_parse_comment() { avoc_source src; avoc_token token; avoc_item item; avoc_status status; load_string(&src, ";; this is a comment ;; ;; another comment ;;"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_comment(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_COMMENT); assert_eqs(item.as_str, ";; this is a comment ;;"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_comment(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_COMMENT); assert_eqs(item.as_str, ";; another comment ;;"); avoc_source_free(&src); } void test_parse_item_no_lists() { avoc_source src; avoc_token token; avoc_item item; avoc_status status; load_string(&src, "a '1' 2 3.0 ;; 4 ;; %5:%6 7i64"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_item(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_sym, "a"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_item(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_STR); assert_eqs(item.as_str, "1"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_item(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I32); assert_eq(item.as_i32, 2); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_item(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_F32); assert_eqf(item.as_f32, 3.0f); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_item(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_COMMENT); assert_eqs(item.as_str, ";; 4 ;;"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_item(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_sym, "%5"); assert_eqs(item.sym_ordinary_type, "%6"); avoc_item_free(&item); avoc_item_init(&item); status = avoc_parse_item(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_LIT_I64); assert_eql(item.as_i64, 7L); avoc_item_free(&item); avoc_source_free(&src); } void test_parse_calls() { avoc_source src; avoc_token token; avoc_list list; avoc_status status; load_string(&src, "()"); avoc_list_init(&list); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_list(&src, &token, &list, TOKEN_CALL_E); assert_okb(status == OK); assert_okb(list.head == NULL); assert_okb(list.tail == NULL); avoc_list_free(&list); avoc_source_free(&src); load_string(&src, "(first second)"); avoc_list_init(&list); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_list(&src, &token, &list, TOKEN_CALL_E); assert_okb(status == OK); assert_okb(list.head != NULL); assert_eq(list.head->type, ITEM_SYM); assert_eqs(list.head->as_sym, "first"); assert_okb(list.tail != NULL); assert_eq(list.tail->type, ITEM_SYM); assert_eqs(list.tail->as_sym, "second"); avoc_list_free(&list); avoc_source_free(&src); load_string(&src, "(first \n second)"); avoc_list_init(&list); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_list(&src, &token, &list, TOKEN_CALL_E); assert_okb(status == OK); assert_okb(list.head != NULL); assert_eq(list.head->type, ITEM_SYM); assert_eqs(list.head->as_sym, "first"); assert_okb(list.tail != NULL); assert_eq(list.tail->type, ITEM_SYM); assert_eqs(list.tail->as_sym, "second"); avoc_list_free(&list); avoc_source_free(&src); load_string(&src, "(\n first \n second \n)"); avoc_list_init(&list); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_list(&src, &token, &list, TOKEN_CALL_E); assert_okb(status == OK); assert_okb(list.head != NULL); assert_eq(list.head->type, ITEM_SYM); assert_eqs(list.head->as_sym, "first"); assert_okb(list.tail != NULL); assert_eq(list.tail->type, ITEM_SYM); assert_eqs(list.tail->as_sym, "second"); avoc_list_free(&list); avoc_source_free(&src); load_string(&src, "(first second:third)"); avoc_list_init(&list); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_list(&src, &token, &list, TOKEN_CALL_E); assert_okb(status == OK); assert_okb(list.head != NULL); assert_eq(list.head->type, ITEM_SYM); assert_eqs(list.head->as_sym, "first"); assert_okb(list.tail != NULL); assert_eq(list.tail->type, ITEM_SYM); assert_eqs(list.tail->as_sym, "second"); assert_okb(list.tail->sym_ordinary_type != NULL); assert_eqs(list.tail->sym_ordinary_type, "third"); avoc_list_free(&list); avoc_source_free(&src); load_string(&src, "(num 123)"); avoc_list_init(&list); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_list(&src, &token, &list, TOKEN_CALL_E); assert_okb(status == OK); assert_okb(list.head != NULL); assert_eq(list.head->type, ITEM_SYM); assert_eqs(list.head->as_sym, "num"); assert_okb(list.tail != NULL); assert_eq(list.tail->type, ITEM_LIT_I32); assert_eq(list.tail->as_i32, 123); avoc_list_free(&list); avoc_source_free(&src); load_string(&src, "(str 'string')"); avoc_list_init(&list); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_list(&src, &token, &list, TOKEN_CALL_E); assert_okb(status == OK); assert_okb(list.head != NULL); assert_eq(list.head->type, ITEM_SYM); assert_eqs(list.head->as_sym, "str"); assert_okb(list.tail != NULL); assert_eq(list.tail->type, ITEM_LIT_STR); assert_eqs(list.tail->as_str, "string"); avoc_list_free(&list); avoc_source_free(&src); load_string(&src, "(parent (child))"); avoc_list_init(&list); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_list(&src, &token, &list, TOKEN_CALL_E); assert_okb(status == OK); assert_okb(list.head != NULL); assert_eq(list.head->type, ITEM_SYM); assert_eqs(list.head->as_sym, "parent"); assert_okb(list.tail != NULL); assert_okb(list.tail->type == ITEM_CALL); assert_okb(list.tail->as_list->head->type == ITEM_SYM); assert_eqs(list.tail->as_list->head->as_sym, "child"); avoc_list_free(&list); avoc_source_free(&src); } void test_parse_sym_with_composed_type() { avoc_source src; avoc_token token; avoc_item item; avoc_status status; avoc_list *type; load_string(&src, "sym:(composed type)"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_item(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_sym, "sym"); assert_okb(item.sym_composed_type != NULL); type = item.sym_composed_type; assert_okb(type->head != NULL); assert_eq(type->head->type, ITEM_SYM); assert_eqs(type->head->as_sym, "composed"); assert_okb(type->tail != NULL); assert_eq(type->tail->type, ITEM_SYM); assert_eqs(type->tail->as_sym, "type"); avoc_item_free(&item); avoc_source_free(&src); load_string(&src, "sym:(composed (type))"); avoc_item_init(&item); status = avoc_next_token(&src, &token); assert_okb(status == OK); status = avoc_parse_item(&src, &token, &item); assert_okb(status == OK); assert_eq(item.type, ITEM_SYM); assert_eqs(item.as_sym, "sym"); assert_okb(item.sym_composed_type != NULL); type = item.sym_composed_type; assert_okb(type->head != NULL); assert_eq(type->head->type, ITEM_SYM); assert_eqs(type->head->as_sym, "composed"); assert_okb(type->tail != NULL); assert_eq(type->tail->type, ITEM_CALL); assert_okb(type->tail->as_list->head->type == ITEM_SYM); assert_eqs(type->tail->as_list->head->as_sym, "type"); avoc_item_free(&item); avoc_source_free(&src); } void test_parse_source() { avoc_source src; avoc_list list; avoc_status status; load_string(&src, ""); avoc_list_init(&list); status = avoc_parse_source(&src, &list); assert_okb(status == OK); assert_okb(list.head == NULL); assert_okb(list.tail == NULL); avoc_list_free(&list); avoc_source_free(&src); load_string(&src, "(1) (2)"); avoc_list_init(&list); status = avoc_parse_source(&src, &list); assert_okb(status == OK); assert_okb(list.head->type == ITEM_CALL); assert_okb(list.head->as_list->head->type == ITEM_LIT_I32); assert_eq(list.head->as_list->head->as_i32, 1); avoc_list_free(&list); avoc_source_free(&src); load_string(&src, "(1) \n (2)"); avoc_list_init(&list); status = avoc_parse_source(&src, &list); assert_okb(status == OK); assert_okb(list.head->type == ITEM_CALL); assert_okb(list.head->as_list->head->type == ITEM_LIT_I32); assert_eq(list.head->as_list->head->as_i32, 1); avoc_list_free(&list); avoc_source_free(&src); } int main() { trun("test_source_init_free", test_source_init_free); trun("test_source_move_fwd_ascii", test_source_move_fwd_ascii); trun("test_source_move_fwd_utf8", test_source_move_fwd_utf8); trun("test_source_move_fwd_newl", test_source_move_fwd_newl); trun("test_token_init", test_token_init); trun("test_token_next_singlechar", test_token_next_singlechar); trun("test_token_next_comments", test_token_next_comments); trun("test_token_next_str_lit", test_token_next_str_lit); trun("test_token_next_num_lit", test_token_next_num_lit); trun("test_token_next_nilbol_lit", test_token_next_nilbol_lit); trun("test_token_next_id", test_token_next_id); trun("test_token_edge_cases", test_token_edge_cases); trun("test_lists", test_lists); trun("test_parse_bol_lit", test_parse_bol_lit); trun("test_parse_int_lit", test_parse_int_lit); trun("test_parse_flt_lit", test_parse_flt_lit); trun("test_parse_str_lit", test_parse_str_lit); trun("test_parse_lst_lit", test_parse_lst_lit); trun("test_parse_sym_no_type", test_parse_sym_no_type); trun("test_parse_sym_with_ord_type", test_parse_sym_with_ord_type); trun("test_parse_item_no_lists", test_parse_item_no_lists); trun("test_parse_lists", test_parse_calls); trun("test_parse_sym_with_composed_type", test_parse_sym_with_composed_type); trun("test_parse_source", test_parse_source); tresults(); return 0; }
2.5
2
2024-11-18T21:09:31.092178+00:00
2023-09-01T13:55:35
b844963299f610e07abb6282d69d675a27aca53e
{ "blob_id": "b844963299f610e07abb6282d69d675a27aca53e", "branch_name": "refs/heads/master", "committer_date": "2023-09-01T13:55:35", "content_id": "f67cf17820994f791d37eea79b11c21a07533c14", "detected_licenses": [ "NIST-Software" ], "directory_id": "198a497422f10ce47985a32136e4bf547a47b1e4", "extension": "c", "filename": "main.c", "fork_events_count": 174, "gha_created_at": "2016-08-31T15:46:51", "gha_event_created_at": "2023-09-14T19:20:44", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 67051618, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1427, "license": "NIST-Software", "license_type": "permissive", "path": "/Source/runbatch/main.c", "provenance": "stackv2-0065.json.gz:8645", "repo_name": "firemodels/smv", "revision_date": "2023-09-01T13:55:35", "revision_id": "b6efa48fb709ab19854cd091c3f692cd2d67a6a1", "snapshot_id": "2e1c7ca5251a5071e6e89ef2df78704443735a5e", "src_encoding": "UTF-8", "star_events_count": 46, "url": "https://raw.githubusercontent.com/firemodels/smv/b6efa48fb709ab19854cd091c3f692cd2d67a6a1/Source/runbatch/main.c", "visit_date": "2023-09-01T16:17:28.238850" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> void usage(void); int batchfile_exists(char *filename); /* ------------------ main ------------------------ */ int main(int argc, char **argv){ int i; char *arg; if(argc==1){ usage(); return 1; } for(i=1;i<argc;i++){ arg=argv[i]; if(arg[0]=='-'){ if(strlen(arg)>1){ switch(arg[1]){ case 'h': usage(); return 1; break; default: printf("Unknown option: %s\n",arg); usage(); return 1; } } } else{ break; } } if(batchfile_exists(arg)==1){ system(arg); } else{ if(arg!=NULL&&strlen(arg)>0){ fprintf(stderr,"ERROR: the batch file, %s, does not exist.\n",arg); } else{ fprintf(stderr,"ERROR: batch file does not exist.\n"); } } } /* ------------------ usage ------------------------ */ void usage(void){ printf("\n"); printf("runbatch batchfile\n"); printf(" Runs a batch file as an executable\n\n"); } /* ------------------ batchfile_exists ------------------------ */ int batchfile_exists(char *filename){ char batchfilename[1024]; if(filename==NULL)return 0; strcpy(batchfilename,filename); if(strstr(filename,".bat")==NULL)strcat(batchfilename,".bat"); if(_access(batchfilename,0)==-1){ return 0; } else{ return 1; } }
2.8125
3
2024-11-18T21:09:31.233028+00:00
2018-02-19T09:28:52
da53beeaa09ea2687b0a8844f3a287a5d1e21a61
{ "blob_id": "da53beeaa09ea2687b0a8844f3a287a5d1e21a61", "branch_name": "refs/heads/master", "committer_date": "2018-02-19T09:28:52", "content_id": "6ed47e1cf175a285daa6d4527903c11213cda70f", "detected_licenses": [ "MIT" ], "directory_id": "aec0c01cb1e098dd0a021c8c46f5b598dee3f7b0", "extension": "c", "filename": "myproc.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 122038957, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4308, "license": "MIT", "license_type": "permissive", "path": "/Project2_AUnixShell/myproc.c", "provenance": "stackv2-0065.json.gz:8903", "repo_name": "Receiling/ecnu_oslab", "revision_date": "2018-02-19T09:28:52", "revision_id": "490a6fa6b6c63062774f871526e3c27b2937186d", "snapshot_id": "e7719e3f95ee646268d49638da16c1b1abe03189", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Receiling/ecnu_oslab/490a6fa6b6c63062774f871526e3c27b2937186d/Project2_AUnixShell/myproc.c", "visit_date": "2021-04-28T09:25:09.629480" }
stackv2
#include "mysh.h" //shell main process void myproc(FILE* instream, int model) { char Redir[2] = ">"; char Backgd[2] = "&"; char Pipe[2] = "|"; char error_message[30] = "An error has occurred\n"; int BackProc_cnt = 0; pid_t BackProc[MAXNBGPROC]; int status; char* buffer = (char*)malloc(sizeof(char) * (MAXSIZE + 5)); if(buffer == NULL) { write(STDERR_FILENO, error_message, strlen(error_message)); exit(0); } char** parament = (char**)malloc(sizeof(char*) * (MAXPARAM + 2)); if(parament == NULL) { write(STDERR_FILENO, error_message, strlen(error_message)); exit(0); } while(TRUE) { if(model == 0) { write(STDOUT_FILENO, "mysh> ", 6); } //memset(buffer, 0, sizeof(buffer)); char* res_fgets = fgets(buffer, MAXSIZE, instream); if(res_fgets == NULL) { write(STDERR_FILENO, error_message, strlen(error_message)); exit(0); } //write(STDOUT_FILENO, buffer, strlen(buffer)); if(model) { write(STDOUT_FILENO, buffer, strlen(buffer)); } if(strlen(buffer) > 512) { write(STDERR_FILENO, error_message, strlen(error_message)); continue; } if(strcmp(buffer, "\n") == 0) continue; //command pre_processing int param_cnt = 0; int tag = 1; char* pstart = buffer; while(*pstart != '\n') { if(*pstart == '&') { *pstart = 0; parament[param_cnt++] = Backgd; tag = 1; } else if(*pstart == '>') { *pstart = 0; parament[param_cnt++] = Redir; tag = 1; } else if(*pstart == '|') { *pstart = 0; parament[param_cnt++] = Pipe; tag = 1; } else if(*pstart == '\t' || *pstart == ' ') { *pstart = 0; tag = 1; } else if(tag == 1) { parament[param_cnt++] = pstart; if(param_cnt >= MAXPARAM) break; tag = 0; } pstart++; } *pstart = 0; if(param_cnt >= MAXPARAM) { write(STDERR_FILENO, error_message, strlen(error_message)); continue; } parament[param_cnt] = NULL; if(param_cnt == 0) continue; //parse commond line if(strcmp(parament[0], "wait") == 0) { if(param_cnt > 1) { write(STDERR_FILENO, error_message, strlen(error_message)); exit(0); } for(; BackProc_cnt > 0; BackProc_cnt--) { waitpid(BackProc[BackProc_cnt - 1], &status, 0); } continue; } //Builtin_command if(builtin_command(parament, param_cnt)) continue; //others command, backgrgound, redirection, pipe, common command command_info info = parse_command(parament, param_cnt); if(info.isValid == FALSE || (info.isPipe == TRUE && info.pipe_cmd_cnt <= 1)) { write(STDERR_FILENO, error_message, strlen(error_message)); continue; } if(info.isPipe) { mypipe(info.pipe_cmd_cnt, info.pipe_cmd, info.outfile); continue; } pid_t chdpid; if((chdpid = fork()) < 0) { write(STDERR_FILENO, error_message, strlen(error_message)); continue; } if(chdpid > 0) { if(info.isBackgd == FALSE) { waitpid(chdpid, &status, 0); } else { BackProc[BackProc_cnt++] = chdpid; continue; } } else { //这是一个最大的问题,因为进程fork的原因导致文件偏移量发生了改变,导致文件除了第一行以外都要重复读入一次 //因此如果在父进程如果open了一些文件,子进程不用时要注意将这些文件关闭,防止对父进程的文件读入造成干扰 fclose(instream); if(info.isRedir) { if(info.outfile == NULL) { write(STDERR_FILENO, error_message, strlen(error_message)); exit(0); } else { int out_fd = open(info.outfile, O_WRONLY|O_CREAT|O_TRUNC, 0666); if(out_fd == -1) { write(STDERR_FILENO, error_message, strlen(error_message)); exit(0); } close(fileno(stdout)); dup2(out_fd, fileno(stdout)); close(out_fd); } } if(execvp(parament[0], parament) == -1) { write(STDERR_FILENO, error_message, strlen(error_message)); exit(0); } break; } } free(buffer); free(parament); }
2.15625
2
2024-11-18T21:09:31.653297+00:00
2022-04-15T07:49:21
ca665ff03125f17ac7e69fce2f7e67404105ccf3
{ "blob_id": "ca665ff03125f17ac7e69fce2f7e67404105ccf3", "branch_name": "refs/heads/master", "committer_date": "2022-04-15T07:49:21", "content_id": "afa441ee63ac7ad62467cb48acca08f0907c1f06", "detected_licenses": [ "MIT" ], "directory_id": "3224e35e1ec1d387bf50990a2e59157f6f84f98c", "extension": "c", "filename": "mq4.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 224388060, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3524, "license": "MIT", "license_type": "permissive", "path": "/stm32_code/Bsp/Src/mq4.c", "provenance": "stackv2-0065.json.gz:9289", "repo_name": "YanxingLiu/wireless-sensor", "revision_date": "2022-04-15T07:49:21", "revision_id": "a00b812489a8588d3ddfa4eaea9b45ab1cdb7a94", "snapshot_id": "3819003e5c4206dec5107b9cf6a808ee530b715b", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/YanxingLiu/wireless-sensor/a00b812489a8588d3ddfa4eaea9b45ab1cdb7a94/stm32_code/Bsp/Src/mq4.c", "visit_date": "2022-05-01T07:43:21.185522" }
stackv2
#include "mq4.h" #include "stm32f10x.h" #include "stm32f10x_adc.h" void MQ4_ADC_init(void) { GPIO_InitTypeDef GPIO_InitStructure; ADC_InitTypeDef ADC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO|RCC_APB2Periph_ADC2,ENABLE); RCC_ADCCLKConfig(RCC_PCLK2_Div6);//12M 最大14M 设置ADC时钟(ADCCLK) ADC_DeInit(ADC2); GPIO_InitStructure.GPIO_Pin=GPIO_Pin_1;//ADC GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AIN; //模拟输入 GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; GPIO_Init(GPIOA,&GPIO_InitStructure); ADC_InitStructure.ADC_Mode = ADC_Mode_Independent; ADC_InitStructure.ADC_ScanConvMode = DISABLE; ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfChannel = 1; ADC_Init(ADC2, &ADC_InitStructure); //设置指定ADC的规则组通道,设置它们的转化顺序和采样时间 // ADC_RegularChannelConfig(ADC1,ADC_Channel_1,1,ADC_SampleTime_239Cycles5); //内部温度传感器是在ADC1通道16的。 ADC_RegularChannelConfig(ADC2,ADC_Channel_1,1,ADC_SampleTime_239Cycles5); // ADC_TempSensorVrefintCmd(ENABLE);//打开内部温度传感器使能 ADC_Cmd(ADC2,ENABLE); ADC_ResetCalibration(ADC2);//重置指定的ADC的校准寄存器 while(ADC_GetResetCalibrationStatus(ADC2));//获取ADC重置校准寄存器的状态 ADC_StartCalibration(ADC2);//开始指定ADC的校准状态 while(ADC_GetCalibrationStatus(ADC2));//获取指定ADC的校准程序 ADC_SoftwareStartConvCmd(ADC2, ENABLE);//使能或者失能指定的ADC的软件转换启动功能 } u16 test_adc_value; u16 GetMQ4Value(void) { uint16_t ADCVal; float Voltage; uint16_t ppm; ADC_SoftwareStartConvCmd(ADC2, ENABLE); while(!ADC_GetFlagStatus(ADC2, ADC_FLAG_EOC )); ADCVal = ADC_GetConversionValue(ADC2); test_adc_value = ADCVal; Voltage = ADCVal * 3.3 / 4096; //无天然气的环境下,实测AOUT端的电压为0.5V,当检测到天然气时,电压每升高0.1V,实际被测气体浓度增加200ppm ppm = (Voltage - 0.5) / 0.1 * 200; return ppm; //return ADCVal; } int Read_MQ4_DOUT_Data(void) { int status; status = GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_3); return status; } void adc_init(void) { GPIO_InitTypeDef GPIO_InitStructure; ADC_InitTypeDef ADC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE); RCC_ADCCLKConfig(RCC_PCLK2_Div6); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN; GPIO_Init(GPIOA,&GPIO_InitStructure); ADC_DeInit(ADC1); ADC_InitStructure.ADC_Mode = ADC_Mode_Independent; ADC_InitStructure.ADC_ScanConvMode = DISABLE; ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfChannel = 1; ADC_Init(ADC1,&ADC_InitStructure); ADC_Cmd(ADC1,ENABLE); ADC_ResetCalibration(ADC1); while(ADC_GetResetCalibrationStatus(ADC1)); ADC_StartCalibration(ADC1); while(ADC_GetCalibrationStatus(ADC1)); ADC_SoftwareStartConvCmd(ADC1,ENABLE); } u16 get_adc(void) { ADC_RegularChannelConfig(ADC1,1,1,ADC_SampleTime_239Cycles5); ADC_SoftwareStartConvCmd(ADC1,ENABLE); while(!ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC)); return ADC_GetConversionValue(ADC1); }
2.234375
2
2024-11-18T21:09:33.185393+00:00
2023-06-01T17:48:37
23aa854120a2f853b042e2760be5a18e539c3f9a
{ "blob_id": "23aa854120a2f853b042e2760be5a18e539c3f9a", "branch_name": "refs/heads/master", "committer_date": "2023-06-01T17:48:37", "content_id": "6350275a56c56269a11d5c827ccc475e49eb80b7", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0a97b814e4e90c6abb25c1fdc00eb5bc7015cabf", "extension": "c", "filename": "lexer.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 16000103, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11532, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/lexer.c", "provenance": "stackv2-0065.json.gz:9545", "repo_name": "BlurryRoots/Lq", "revision_date": "2023-06-01T17:48:37", "revision_id": "9a2d16a8e6969553aa77de72ff6ef1c4fdb52ea9", "snapshot_id": "86c3ab91af563f76ee36bdad87eb6e06240bb85d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BlurryRoots/Lq/9a2d16a8e6969553aa77de72ff6ef1c4fdb52ea9/src/lexer.c", "visit_date": "2023-06-10T13:52:36.052125" }
stackv2
#include <lexer.h> #include <wchar.h> #define LEXER_ERROR_BUFFER_LENGTH 64 /**/ #define is_blank( c ) \ (c == L' ') #define is_tab( c ) \ (c == L'\t') #define is_newline( c ) \ (c == L'\n') #define is_whitespace( c ) \ (is_blank( c ) || is_tab( c ) || is_newline( c )) /**/ #define is_number( c ) \ (c >= L'0' && c <= L'9') #define is_decimal_point( c ) \ (c == L'.') #define is_symbol( c ) \ (c >= L'!' && c <= L'~') \ || (c >= L'¡' && c <= L'ÿ') /**/ #define is_list_begin( c ) \ (c == L'(') #define is_list_end( c ) \ (c == L')') /**/ #define is_string_operator( c ) \ (c == L'"') /**/ #define is_quotation_operator( c ) \ (c == L'\'') /**/ #define is_comment( c ) \ (c == L';') const char* IDLE_STRING = "IDLE"; const char* READ_SYMBOL_STRING = "READ_SYMBOL"; const char* READ_STRING_STRING = "READ_STRING"; const char* READ_COMMENT_STRING = "READ_COMMENT"; const char* READ_NUMBER_STRING = "READ_NUMBER"; const char* LEXER_SUCCESS_STRING = "LEXER_SUCCESS"; const char* LEXER_ERROR_STRING = "LEXER_ERROR"; const char* UNKNOWN_STRING = "UNKNOWN"; const char* lexer_state_to_string( lexer_state someState ) { switch( someState ) { case IDLE: return IDLE_STRING; break; case READ_SYMBOL: return READ_SYMBOL_STRING; break; case READ_STRING: return READ_STRING_STRING; break; case READ_COMMENT: return READ_COMMENT_STRING; break; case READ_NUMBER: return READ_NUMBER_STRING; break; case LEXER_SUCCESS: return LEXER_SUCCESS_STRING; break; case LEXER_ERROR: return LEXER_ERROR_STRING; break; default: return UNKNOWN_STRING; break; } } lexer_t lexer_create() { lexer_t lexer; lexer.tokenlist.tokens = NULL; token_list_init( & lexer.tokenlist ); lexer.state = IDLE; lexer.errorMessage = string_new(); return lexer; } int lexer_reset( lexer_t* someLexer ) { if( ! someLexer ) { return 0; } string_free( someLexer->errorMessage ); someLexer->errorMessage = NULL; token_list_free( & someLexer->tokenlist ); *someLexer = lexer_create(); return 1; } int lexer_scan( lexer_t* someLexer, const string_t* someScript ) { size_t iterator, line, column; string_t* buffer; token_type typeBuffer; wchar_t c; if( ! someLexer ) { return 0; } if( someScript->length == 0 ) { someLexer->state = LEXER_SUCCESS; } iterator = 0; line = column = 0; buffer = string_new(); while( 1 ) { c = someScript->data[iterator]; ++column; if( someLexer->state == IDLE ) { if( is_whitespace( c ) ) { if( is_newline( c ) ) { column = 0; ++line; } goto LABEL_continue; } if( is_comment( c ) ) { someLexer->state = READ_COMMENT; goto LABEL_continue; } if( is_number( c ) ) { someLexer->state = READ_NUMBER; string_append( buffer, c ); goto LABEL_continue; } if( is_list_begin( c ) || is_list_end( c ) ) { someLexer->state = IDLE; string_append( buffer, c ); typeBuffer = (is_list_begin( c ) ? LIST_BEGIN : LIST_END); goto LABEL_append_token; } if( is_quotation_operator( c ) ) { someLexer->state = IDLE; string_append( buffer, c ); typeBuffer = QUOTE; goto LABEL_append_token; } if( is_symbol( c ) ) { someLexer->state = READ_SYMBOL; string_append( buffer, c ); } goto LABEL_continue; } if( someLexer->state == READ_COMMENT ) { if( is_newline( c ) ) { someLexer->state = IDLE; } goto LABEL_continue; } if( someLexer->state == READ_STRING ) { if( is_string_operator( c ) ) { someLexer->state = IDLE; typeBuffer = STRING; goto LABEL_append_token; } string_append( buffer, c ); goto LABEL_continue; } if( someLexer->state == READ_SYMBOL ) { static int finalize = 0; if( is_comment( c ) ) { someLexer->state = READ_COMMENT; finalize = 1; } else if( is_string_operator( c ) ) { someLexer->state = READ_STRING; finalize = 1; } else if( is_whitespace( c ) ) { someLexer->state = IDLE; finalize = 1; } else if( is_list_begin( c ) || is_list_end( c ) ) { token_list_append( & someLexer->tokenlist, buffer, SYMBOL, line, column ); string_free( buffer ); buffer = string_new(); someLexer->state = IDLE; string_append( buffer, c ); typeBuffer = (is_list_begin( c ) ? LIST_BEGIN : LIST_END); goto LABEL_append_token; } else if( is_quotation_operator( c ) ) { token_list_append( & someLexer->tokenlist, buffer, NUMBER, line, column ); string_free( buffer ); buffer = string_new(); someLexer->state = IDLE; string_append( buffer, c ); typeBuffer = QUOTE; goto LABEL_append_token; } if( finalize ) { finalize = 0; typeBuffer = SYMBOL; goto LABEL_append_token; } string_append( buffer, c ); goto LABEL_continue; } if( someLexer->state == READ_NUMBER ) { static int finalize = 0; static int hadDecimalPoint = 0; if( is_whitespace( c ) ) { someLexer->state = IDLE; finalize = 1; } else if( is_comment( c ) ) { someLexer->state = READ_COMMENT; finalize = 1; } else if( is_string_operator( c ) ) { someLexer->state = READ_STRING; finalize = 1; } else if( is_list_begin( c ) || is_list_end( c ) ) { finalize = 0; hadDecimalPoint = 0; token_list_append( & someLexer->tokenlist, buffer, NUMBER, line, column ); string_free( buffer ); buffer = string_new(); someLexer->state = IDLE; string_append( buffer, c ); typeBuffer = (is_list_begin( c ) ? LIST_BEGIN : LIST_END); goto LABEL_append_token; } else if( is_quotation_operator( c ) ) { finalize = 0; hadDecimalPoint = 0; token_list_append( & someLexer->tokenlist, buffer, NUMBER, line, column ); string_free( buffer ); buffer = string_new(); someLexer->state = IDLE; string_append( buffer, c ); typeBuffer = QUOTE; goto LABEL_append_token; } else if( is_decimal_point( c ) ) { if( hadDecimalPoint ) { someLexer->state = LEXER_ERROR; string_copy_cstr( someLexer->errorMessage, L"Error: while reading number -> second decimal point!" ); } else { hadDecimalPoint = 1; string_append( buffer, c ); } goto LABEL_continue; } else if( is_number( c ) ) { string_append( buffer, c ); goto LABEL_continue; } else if( is_symbol( c ) ) { someLexer->state = LEXER_ERROR; string_copy_cstr( someLexer->errorMessage, L"Error: while reading number -> found symbol!" ); goto LABEL_continue; } if( finalize ) { finalize = 0; hadDecimalPoint = 0; someLexer->state = IDLE; typeBuffer = NUMBER; goto LABEL_append_token; } goto LABEL_continue; } LABEL_append_token: token_list_append( & someLexer->tokenlist, buffer, typeBuffer, line, column ); string_free( buffer ); buffer = string_new(); LABEL_continue: if( someLexer->state == LEXER_ERROR ) { break; } if( c == '\0' || iterator >= someScript->length ) { if( someLexer->state == READ_STRING ) { string_copy_cstr( someLexer->errorMessage, L"Error: while reading string -> unexpected end of file!" ); someLexer->state = LEXER_ERROR; break; } if( buffer->length > 0 ) { if( someLexer->state == READ_SYMBOL ) { typeBuffer = SYMBOL; goto LABEL_append_token; } else if( someLexer->state == READ_NUMBER ) { typeBuffer = NUMBER; goto LABEL_append_token; } } someLexer->state = LEXER_SUCCESS; break; } else { ++iterator; } } string_free( buffer ); return someLexer->state == LEXER_SUCCESS; } void lexer_free( lexer_t* someLexer ) { if( ! someLexer ) { return; } string_free( someLexer->errorMessage ); token_list_free( & someLexer->tokenlist ); } /**/
2.40625
2
2024-11-18T21:09:33.311822+00:00
2018-07-26T03:35:32
32ee97f193661ea0b3998bad2aa23da9dee890a0
{ "blob_id": "32ee97f193661ea0b3998bad2aa23da9dee890a0", "branch_name": "refs/heads/master", "committer_date": "2018-07-26T03:35:32", "content_id": "befc76b4956679e17a1643be5f3363f2bd7eba82", "detected_licenses": [ "MIT" ], "directory_id": "076d746eef1db0837a86cf314fb041fd35572801", "extension": "c", "filename": "sdd_ast.c", "fork_events_count": 4, "gha_created_at": "2016-05-13T10:54:21", "gha_event_created_at": "2016-05-27T03:01:07", "gha_language": "Python", "gha_license_id": null, "github_id": 58731158, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13096, "license": "MIT", "license_type": "permissive", "path": "/SDDKit/sdd_ast.c", "provenance": "stackv2-0065.json.gz:9674", "repo_name": "charleslyh/SDDKit", "revision_date": "2018-07-26T03:35:32", "revision_id": "3b973084d72f209dbc65cdd114ba54fb61fc3570", "snapshot_id": "776d1d6dba9835553f1a2fd530eaae1434164c11", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/charleslyh/SDDKit/3b973084d72f209dbc65cdd114ba54fb61fc3570/SDDKit/sdd_ast.c", "visit_date": "2020-12-24T19:28:15.203405" }
stackv2
// sdd_ast.c // // Copyright (c) 2016 CharlesLee // // 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 "sdd_ast.h" #include "sdd_parser.h" #include "sdd_array.h" #include <stdio.h> #include <string.h> #include <stdlib.h> void sdd_ast_construct(sdd_ast* ast, sdd_markdown markdown, sdd_parser_callback* callback) { ast->procedures = sdd_array_new(); ast->state_names = sdd_array_new(); ast->entries = sdd_array_new(); ast->exits = sdd_array_new(); ast->defaults = sdd_array_new(); ast->states = sdd_array_new(); ast->clusters = sdd_array_new(); ast->buckets = sdd_array_new(); ast->ids = sdd_array_new(); ast->id_groups = sdd_array_new(); ast->stubs = sdd_array_new(); ast->post_acts = sdd_array_new(); ast->signals = sdd_array_new(); ast->markdown = markdown; ast->callback = callback; } void sdd_dump_state_by_names(void* context, void* element) { sdd_state* state = (sdd_state*)element; printf("[%s]", state->name); } void sdd_dump_string(void* context, void* element) { printf("%s ", (const char*)element); } void sdd_dump_array_count(void* context, void* array) { printf("%d ", sdd_array_count((sdd_array*)array)); } void sdd_dump_signal(void* context, void *element) { sdd_signal *sig = (sdd_signal *)element; char str[256]; sdd_describe_signal(sig, str); printf("%s\n", str); } void sdd_dump_elements(const char* name, sdd_bool isGroup, sdd_array* elements, sdd_array_element_handler handler) { printf(""); printf(isGroup ? "[*]" : " "); printf("[%d]%s\t", sdd_array_count(elements), name); sdd_array_foreach(elements, handler, 0); printf("\n"); } void sdd_dump_ast(sdd_ast* ast, const char* tag) { printf ("_______ %s _______\n", tag); sdd_dump_elements("states", sdd_no, ast->states, sdd_dump_state_by_names); sdd_dump_elements("buckets", sdd_yes, ast->buckets, sdd_dump_array_count); sdd_dump_elements("clusters", sdd_yes, ast->clusters, sdd_dump_array_count); sdd_dump_elements("state_names",sdd_no, ast->state_names,sdd_dump_string); sdd_dump_elements("entries", sdd_no, ast->entries, sdd_dump_string); sdd_dump_elements("exits", sdd_no, ast->exits, sdd_dump_string); sdd_dump_elements("signals", sdd_no, ast->signals, sdd_dump_signal); // sdd_dump_elements("defaults", sdd_no, ast->defaults, sdd_dump_string); sdd_dump_elements("stubs", sdd_no, ast->stubs, sdd_dump_string); sdd_dump_elements("procedures", sdd_no, ast->procedures, sdd_dump_string); sdd_dump_elements("id_groups", sdd_yes, ast->id_groups, sdd_dump_array_count); sdd_dump_elements("post_acts", sdd_no, ast->post_acts, sdd_dump_string); sdd_dump_elements("ids", sdd_no, ast->ids, sdd_dump_string); printf ("________________________\n"); } void sdd_ast_destruct(sdd_ast* ast) { sdd_array_delete(ast->signals); sdd_array_delete(ast->post_acts); sdd_array_delete(ast->ids); sdd_array_delete(ast->id_groups); sdd_array_delete(ast->procedures); sdd_array_delete(ast->state_names); sdd_array_delete(ast->entries); sdd_array_delete(ast->exits); sdd_array_delete(ast->defaults); sdd_array_delete(ast->stubs); sdd_array_delete(ast->clusters); sdd_array_delete(ast->buckets); sdd_array_delete(ast->states); } void sdd_ast_push_id(sdd_ast* ast, const char* identifier) { sdd_array_push(ast->ids, (void*)strdup(identifier)); (*ast->markdown)("ids", identifier); } void sdd_ast_make_id_group(sdd_ast* ast, int gen_new) { sdd_array* group; if (gen_new) { group = sdd_array_new(); sdd_array_push(ast->id_groups, group); } else { group = sdd_array_at(ast->id_groups, 0, sdd_no); } const char* id = sdd_array_pop(ast->ids); sdd_array_push(group, (void*)id); (*ast->markdown)("id_groups", id); } void sdd_ast_make_stub(sdd_ast* ast) { const char* stub = sdd_array_pop(ast->ids); sdd_array_push(ast->stubs, (void*)stub); ast->markdown("stub", stub); } void sdd_ast_make_pseudo_stub(sdd_ast *ast, const char *pseudo) { sdd_array_push(ast->stubs, (void*)strdup(pseudo)); ast->markdown("stub", pseudo); } void sdd_ast_make_state_name(sdd_ast* ast) { const char* identifier = sdd_array_pop(ast->ids); sdd_array_push(ast->state_names, (void*)identifier); (*ast->markdown)("state_name", identifier); } void sdd_ast_array_delete(sdd_array* array) { while(sdd_array_count(array)>0) { free((void*)sdd_array_pop(array)); } free(array); } char* sdd_ast_array_string_new(sdd_array* array) { char buffer[256]; buffer[0] = 0; while(sdd_array_count(array) > 0) { const char* elem = sdd_array_pop_front(array); strcat(buffer, elem); if (sdd_array_count(array) > 0) { // Not the very last one strcat(buffer, " "); } } return strdup(buffer); } void sdd_ast_make_procedure(sdd_ast* ast, int empty) { if (empty != 0) { sdd_array_push(ast->procedures, strdup("")); return; } sdd_array* id_group = sdd_array_pop(ast->id_groups); const char* procedure = sdd_ast_array_string_new(id_group); sdd_array_push(ast->procedures, (void*)procedure); sdd_ast_array_delete(id_group); (*ast->markdown)("procedure", procedure); } void sdd_ast_make_entry(sdd_ast* ast, int empty) { const char* procs = empty == 0 ? sdd_array_pop(ast->procedures) : strdup(""); sdd_array_push(ast->entries, (void*)procs); (*ast->markdown)("entry", procs); } void sdd_ast_make_exit(sdd_ast* ast, int empty) { char* procs = empty == 0 ? sdd_array_pop(ast->procedures) : strdup(""); sdd_array_push(ast->exits, (void*)procs); (*ast->markdown)("exit", empty ? "<null>" : procs); } void sdd_ast_make_default(sdd_ast* ast, int empty) { char* stub = empty == 0 ? sdd_array_pop(ast->stubs) : strdup(""); sdd_array_push(ast->defaults, (void*)stub); (*ast->markdown)("default", empty ? "<null>" : stub); } void sdd_ast_make_cluster(sdd_ast* ast, int gen_new) { if (gen_new) { sdd_array_push(ast->clusters, sdd_array_new()); } sdd_array* clusters = (sdd_array*)sdd_array_at(ast->clusters, 0, sdd_no); sdd_state* state = (sdd_state*)sdd_array_pop(ast->states); sdd_array_push(clusters, state); } void sdd_ast_make_bucket(sdd_ast* ast, int gen_new) { sdd_array* bucket; if (gen_new) { bucket = sdd_array_new(); sdd_array_push(ast->buckets, bucket); // 由于states是FIFO的(例如[S1, S2]),必须将通过“前插”操作,才能保证bucket中状态的顺序 // 依旧是[S1, S2]。否则,如果使用push,则会变成[S2, S1]。另外,不能使用pop_front从ast->states中获取状态对象。因为栈中很可能还有很多早前被推入的状态。只有最后两个才是属于该bucket的 sdd_array_push_front(bucket, sdd_array_pop(ast->states)); sdd_array_push_front(bucket, sdd_array_pop(ast->states)); } else { // peek,不应该pop出来 bucket = sdd_array_at(ast->buckets, 0, sdd_no); sdd_array_push(bucket, sdd_array_pop(ast->states)); } } sdd_state* sdd_ast_extract_state(sdd_ast* ast) { const char* name = sdd_array_pop(ast->state_names); const char* en = sdd_array_pop(ast->entries); const char* ex = sdd_array_pop(ast->exits); const char* def = sdd_array_pop(ast->defaults); sdd_state* s = malloc(sizeof(sdd_state)); sdd_state_construct(s, name, en, ex, def); free((void*)name); free((void*)en); free((void*)ex); free((void*)def); return s; } void sdd_md_make_state_desc(sdd_state* state, char* desc) { sprintf(desc, "[%s", state->name); if (strlen(state->entries) != 0) { strcat(desc, " e:"); strcat(desc, state->entries); } if (strlen(state->exits) != 0) { strcat(desc, " x:"); strcat(desc, state->exits); } if (strlen(state->default_stub) != 0) { strcat(desc, " d:["); strcat(desc, state->default_stub); strcat(desc, "]"); } strcat(desc, "]"); } void sdd_ast_make_state(sdd_ast* ast, int mode) { sdd_parser_callback* callback = ast->callback; sdd_state* state = sdd_ast_extract_state(ast); char text[1024]; sdd_md_make_state_desc(state, text); (*ast->markdown)("state", text); callback->stateHandler(callback->context, state); sprintf(text, "[%-8s ", state->name); if (mode == 1) { sdd_array* cluster = sdd_array_pop(ast->clusters); callback->clusterHandler(callback->context, state, cluster); while(sdd_array_count(cluster) > 0) { sdd_state* cluster_state = sdd_array_pop_front(cluster); strcat(text, "["); strcat(text, cluster_state->name); strcat(text, "]"); sdd_state_destruct(cluster_state); free((void*)cluster_state); } strcat(text, "]"); (*ast->markdown)("cluster", text); sdd_array_delete(cluster); } else if (mode == 2) { sdd_array* bucket = sdd_array_pop(ast->buckets); while(sdd_array_count(bucket) > 0) { sdd_state* bucket_state = sdd_array_pop_front(bucket); strcat(text, "["); strcat(text, bucket_state->name); if (sdd_array_count(bucket)!=0) strcat(text, "]|"); else strcat(text, "]"); sdd_state_destruct(bucket_state); free((void*)bucket_state); } strcat(text, "]"); (*ast->markdown)("bucket", text); sdd_array_delete(bucket); } sdd_array_push(ast->states, (void*)state); } void sdd_ast_begin_condition(sdd_ast* ast) { ast->postfix_exprs[0] = 0; } void sdd_ast_make_expr(sdd_ast* ast, sdd_expr_type type) { switch(type) { case SDD_EXPR_VAL: if (ast->postfix_exprs[0] != 0) { // strlen会导致大量计算,而我们只需要判断是否0长度即可 strcat(ast->postfix_exprs, " "); // 只有第一个元素不需要在前面加上用于分隔的空格符 } strcat(ast->postfix_exprs, sdd_array_at(ast->ids, 0, sdd_no)); free(sdd_array_pop(ast->ids)); break; case SDD_EXPR_NOT: strcat(ast->postfix_exprs, " !"); break; case SDD_EXPR_AND: strcat(ast->postfix_exprs, " &"); break; case SDD_EXPR_OR: strcat(ast->postfix_exprs, " |"); break; case SDD_EXPR_XOR: strcat(ast->postfix_exprs, " ^"); break; } } void sdd_ast_end_condition(sdd_ast* ast) { (*ast->markdown)("condition", ast->postfix_exprs); } void sdd_ast_make_postactions(sdd_ast* ast, int empty) { if (empty) { sdd_array_push(ast->post_acts, strdup("")); return; } sdd_array* id_group = sdd_array_pop(ast->id_groups); const char* actions = sdd_ast_array_string_new(id_group); sdd_array_push(ast->post_acts, (void*)actions); sdd_ast_array_delete(id_group); (*ast->markdown)("post_acts", actions); } void sdd_ast_make_transition(sdd_ast* ast) { sdd_signal *sig = sdd_array_pop(ast->signals); const char* to = sdd_array_pop(ast->stubs); const char* from = sdd_array_pop(ast->stubs); const char* post_acts = sdd_array_pop(ast->post_acts); char sig_desc[512]; sdd_describe_signal(sig, sig_desc); char desc[512]; if (ast->postfix_exprs[0] == 0) { sprintf(desc, "[%s] -> [%s]: %s", from, to, sig_desc); } else { sprintf(desc, "[%s] -> [%s]: %s (%s)", from, to, sig_desc, ast->postfix_exprs); } if (post_acts[0] != 0) { strcat(desc, "/"); strcat(desc, post_acts); } (*ast->markdown)("trans", desc); sdd_transition* transition = sdd_transition_new(from, to, sig, ast->postfix_exprs, post_acts); (*ast->callback->transitionHandler)(ast->callback->context, transition); sdd_transition_delete(transition); free((void*)to); free((void*)from); free((void*)post_acts); sdd_signal_delete(sig); } void sdd_ast_make_signal(sdd_ast *ast, sdd_signal_type type) { const char *name = sdd_array_pop(ast->ids); sdd_signal *sig = sdd_signal_new(type, name); free((void *)name); sdd_array_push(ast->signals, sig); } void sdd_ast_make_top_state(sdd_ast *ast) { sdd_state* topstate = (sdd_state*)sdd_array_pop(ast->states); ast->callback->topstateHandler(ast->callback->context, topstate); sdd_state_destruct(topstate); free((void*)topstate); } void sdd_ast_make_dsl(sdd_ast* ast, int mode) { ast->callback->completionHandler(ast->callback->context); } void yyerror(char *msg) { printf("SDD error: %s \n", msg); }
2.25
2
2024-11-18T21:09:34.256831+00:00
2020-03-03T19:33:34
85bf64586355a9a0e6fc4cf3a74e325ba2f3e560
{ "blob_id": "85bf64586355a9a0e6fc4cf3a74e325ba2f3e560", "branch_name": "refs/heads/master", "committer_date": "2020-03-03T19:33:34", "content_id": "4c850f63b69a9316421a874c58d99b3182922aa5", "detected_licenses": [ "Unlicense" ], "directory_id": "0d98ad615a7ee36eb65f311197f0251c52e1761a", "extension": "c", "filename": "linkedList.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 224980639, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1898, "license": "Unlicense", "license_type": "permissive", "path": "/linkedList.c", "provenance": "stackv2-0065.json.gz:10316", "repo_name": "efe-cevher/OS-HW4", "revision_date": "2020-03-03T19:33:34", "revision_id": "1e16874332fa299ada853d6f2e584f3326d07cef", "snapshot_id": "b01650b0b6d95f29f2fc2a2dd19592a6c9713642", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/efe-cevher/OS-HW4/1e16874332fa299ada853d6f2e584f3326d07cef/linkedList.c", "visit_date": "2022-04-15T03:00:08.492173" }
stackv2
#include<stdio.h> #include<stdlib.h> #include"linkedList.h" void append(Node** head_ref, Song new_data) { /* 1. allocate node */ Node* new_node = (Node*) malloc(sizeof(Node)); Node *last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next; /* 6. Change the next of last node */ last->next = new_node; return; } void deleteNode(Node **head_ref, int position) { // If linked list is empty if (*head_ref == NULL) return; // Store head node Node* temp = *head_ref; // If head needs to be removed if (position == 0) { *head_ref = temp->next; // Change head free(temp); // free old head return; } // Find previous node of the node to be deleted for (int i=0; temp!=NULL && i<position-1; i++) temp = temp->next; // If position is more than number of ndoes if (temp == NULL || temp->next == NULL) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node *next = temp->next->next; // Unlink the node from linked list free(temp->next); // Free memory temp->next = next; // Unlink the deleted node from list } void printList(Node* n) { while (n != NULL) { printf(" %s, %s, %d \n", n->data.name, n->data.genre, n->data.year); n = n->next; } }
3.796875
4
2024-11-18T21:09:34.332624+00:00
2017-12-21T02:39:22
50d65d1c3c893f6cb48e463cfa8ec9ae5cde901b
{ "blob_id": "50d65d1c3c893f6cb48e463cfa8ec9ae5cde901b", "branch_name": "refs/heads/master", "committer_date": "2017-12-21T02:39:22", "content_id": "6990e53b7a9d10d5df7fb2bc61c21ce0595c8320", "detected_licenses": [ "MIT" ], "directory_id": "455e8a95cffe9da26eca6d4d1c03847b3175aba7", "extension": "c", "filename": "5b.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": 416, "license": "MIT", "license_type": "permissive", "path": "/5b.c", "provenance": "stackv2-0065.json.gz:10444", "repo_name": "debajyotiguha11/Data-Structure-with-C", "revision_date": "2017-12-21T02:39:22", "revision_id": "77b96536b5c1823e65ecf3cfef496e54f5ce4cf5", "snapshot_id": "e6e8f92653ddfc17ee2ef2427bb92837d9ee13a5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/debajyotiguha11/Data-Structure-with-C/77b96536b5c1823e65ecf3cfef496e54f5ce4cf5/5b.c", "visit_date": "2021-08-31T10:23:47.384925" }
stackv2
#include<stdio.h> void tower(int,char,char,char); void main() { int n; printf("Enter no of disks: "); scanf("%d",&n); printf("Sequence involved are\n"); tower(n,'A','C','B'); } void tower(int n, char from, char top, char aux) { if(n==1) { printf("Move Disk 1 from %c to %c\n",from,top); return; } tower(n-1,from,aux,top); printf("Move Disk %d from %c to %c\n",n,from,top); tower(n-1,aux,top,from); }
3.375
3
2024-11-18T21:09:34.493928+00:00
2019-11-16T22:07:55
fbdf12aa0c38f947a4c8c092d3c78dcc1d727f98
{ "blob_id": "fbdf12aa0c38f947a4c8c092d3c78dcc1d727f98", "branch_name": "refs/heads/master", "committer_date": "2019-11-16T22:15:13", "content_id": "897d3c1aed2df773e6ce756fd7c13e258fa8a343", "detected_licenses": [ "MIT" ], "directory_id": "218a7b74dd777cc502309cb2d99bd2dafa886db6", "extension": "h", "filename": "mem_pool.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 174831994, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1527, "license": "MIT", "license_type": "permissive", "path": "/array-ds/mem_pool/mem_pool.h", "provenance": "stackv2-0065.json.gz:10572", "repo_name": "vladcc/array-ds", "revision_date": "2019-11-16T22:07:55", "revision_id": "e606017c9708163070c64939f5ac7e77f308b13a", "snapshot_id": "9721759c6b508e114278ecf4d1d831a9db8af42d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vladcc/array-ds/e606017c9708163070c64939f5ac7e77f308b13a/array-ds/mem_pool/mem_pool.h", "visit_date": "2020-04-28T00:52:29.482154" }
stackv2
/* mem_pool.h -- memory pool v1.11 A c_vector of memory blocks. Allocates a contiguous piece of memory, gives you pointers to a preset number of bytes at a time. When it reaches the end of the current memory block, allocates another. Allocated memory is only freed at once upon reset, or on destroy. Author: Vladimir Dinev [email protected] 2019-08-18 */ #ifndef MEM_POOL_H #define MEM_POOL_H #include "../c_vector/c_vector.h" // Do not use directly typedef struct mem_pool { c_vector the_pool; int elem_count; int elem_size; int node_cap; } mem_pool; void * mpl_make(mem_pool * mpl, int elem_size, int node_cap); /* Returns: mpl on success, NULL otherwise. Description: Creates a memory pool of node_cap number of elem_size elements. On failure *mpl is zeroed out. Complexity: O(1) */ void mpl_destroy(mem_pool * mpl); /* Returns: Nothing. Description: Frees all memory associated with mpl, zeroes *mpl out. Complexity: O(1) */ void * mpl_get(mem_pool * mpl); /* Returns: A pointer to the next available location in mpl. Description: Retrieves a location in memory elem_size number of bytes large. Complexity: O(1) */ void * mpl_reset(mem_pool * mpl); /* Returns: mpl on success, NULL otherwise. Description: Destroys and recreates mpl with only one memory block. As all memory belonging to mpl before this call is freed, all pointers received from mpl before this call are now invalid. Complexity: O(n) where n is the number of memory blocks. */ #endif
2.90625
3
2024-11-18T21:09:34.766020+00:00
2020-09-08T02:52:56
1f49f437b3b958c2204e897587ca92f97cce523e
{ "blob_id": "1f49f437b3b958c2204e897587ca92f97cce523e", "branch_name": "refs/heads/master", "committer_date": "2020-09-08T02:52:56", "content_id": "3fd559460293681ea2deb13bf3401b15b7b1b08c", "detected_licenses": [ "MIT" ], "directory_id": "efb25a20ecddb3a0a8795bc616069fc1a94e5375", "extension": "h", "filename": "ELF.h", "fork_events_count": 0, "gha_created_at": "2020-08-21T06:55:08", "gha_event_created_at": "2020-08-24T02:16:20", "gha_language": "C", "gha_license_id": "MIT", "github_id": 289200355, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14999, "license": "MIT", "license_type": "permissive", "path": "/sdk_k64f/middleware/mcu-boot/tools/tools/elftosb/common/ELF.h", "provenance": "stackv2-0065.json.gz:10828", "repo_name": "Sir-Branch/k64f-starter-template", "revision_date": "2020-09-08T02:52:56", "revision_id": "f8959fd185f090363d180d69f84c2727e37cbeeb", "snapshot_id": "f6119d67a4d661affca4ca8b5b72a971d0a65754", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Sir-Branch/k64f-starter-template/f8959fd185f090363d180d69f84c2727e37cbeeb/sdk_k64f/middleware/mcu-boot/tools/tools/elftosb/common/ELF.h", "visit_date": "2022-12-18T22:24:58.356426" }
stackv2
/* * Copyright (c) 2008-2015 Freescale Semiconductor, Inc. * Copyright 2016-2018 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #if !defined(_ELF_h_) #define _ELF_h_ //! \name ELF types //! Types used in ELF file structures. //@{ typedef uint32_t Elf32_Addr; typedef uint16_t Elf32_Half; typedef /*off_t*/ uint32_t Elf32_Off; typedef int32_t Elf32_Sword; typedef uint32_t Elf32_Word; typedef uint64_t Elf64_Addr; typedef uint16_t Elf64_Half; typedef /*off_t*/ uint64_t Elf64_Off; typedef int32_t Elf64_Sword; typedef uint32_t Elf64_Word; typedef uint64_t Elf64_XWord; //@} // All ELF structures are byte aligned. Any alignment padding is explicit. #pragma pack(1) //! \name File header //@{ /*! * Constants for the various fields of Elf32_Ehdr.e_ident. */ enum { EI_MAG0 = 0, EI_MAG1, EI_MAG2, EI_MAG3, EI_CLASS, EI_DATA, EI_VERSION, EI_PAD, EI_NIDENT = 16, // Magic number. ELFMAG0 = 0x7f, ELFMAG1 = 'E', ELFMAG2 = 'L', ELFMAG3 = 'F', // EI_CLASS ELFCLASSNONE = 0, ELFCLASS32 = 1, ELFCLASS64 = 2, // EI_DATA ELFDATANONE = 0, ELFDATA2LSB = 1, ELFDATA2MSB = 2 }; /*! * \brief ELF file header. */ struct Elf32_Ehdr { unsigned char e_ident[EI_NIDENT]; //!< Magic number identifying the file format. Elf32_Half e_type; //!< Identifies the object file format. Elf32_Half e_machine; //!< Specified the architecture for the object file. Elf32_Word e_version; //!< Object file version. Elf32_Addr e_entry; //!< Virtual address of the entry point, or 0. Elf32_Off e_phoff; //!< Program header table offset in bytes, or 0 if no program header table. Elf32_Off e_shoff; //!< Section header table offset in bytes, or 0 if no section header table. Elf32_Word e_flags; //!< Processor-specific flags associated with the file. Elf32_Half e_ehsize; //!< The ELF header's size in bytes. Elf32_Half e_phentsize; //!< Size in bytes of one entry in the program header table. Elf32_Half e_phnum; //!< Number of entries in the program header table. Elf32_Half e_shentsize; //!< Size in bytes of an entry in the section header table. Elf32_Half e_shnum; //!< Number of entries in the section header table. Elf32_Half e_shstrndx; //!< Section header table index of the section name string table. }; struct Elf64_Ehdr { unsigned char e_ident[EI_NIDENT]; //!< Magic number identifying the file format. Elf64_Half e_type; //!< Identifies the object file format. Elf64_Half e_machine; //!< Specified the architecture for the object file. Elf64_Word e_version; //!< Object file version. Elf64_Addr e_entry; //!< Virtual address of the entry point, or 0. Elf64_Off e_phoff; //!< Program header table offset in bytes, or 0 if no program header table. Elf64_Off e_shoff; //!< Section header table offset in bytes, or 0 if no section header table. Elf64_Word e_flags; //!< Processor-specific flags associated with the file. Elf64_Half e_ehsize; //!< The ELF header's size in bytes. Elf64_Half e_phentsize; //!< Size in bytes of one entry in the program header table. Elf64_Half e_phnum; //!< Number of entries in the program header table. Elf64_Half e_shentsize; //!< Size in bytes of an entry in the section header table. Elf64_Half e_shnum; //!< Number of entries in the section header table. Elf64_Half e_shstrndx; //!< Section header table index of the section name string table. }; /*! * Constants for #Elf32_Ehdr.e_type. */ enum { ET_NONE, //!< No file type. ET_REL, //!< Relocatable file. ET_EXEC, //!< Executable file. ET_DYN, //!< Shared object file. ET_CORE, //!< Core file. ET_LOPROC, //!< Low bound of processor-specific file types. ET_HIPROC //!< High bound of processor-specific file types. }; /*! * ARM-specific #Elf32_Ehdr.e_flags */ enum { EF_ARM_HASENTRY = 0x02, //!< #Elf32_Ehdr.e_entry contains a program-loader entry point. EF_ARM_SYMSARESORTED = 0x04, //!< Each subsection of the symbol table is sorted by symbol value. EF_ARM_DYNSYMSUSESEGIDX = 0x08, //!< Symbols in dynamic symbol tables that are defined in sections included in //!program segment n have #Elf32_Sym.st_shndx = n + 1. EF_ARM_MAPSYMSFIRST = 0x10, //!< Mapping symbols precede other local symbols in the symbol table. EF_ARM_EABIMASK = 0xff000000, //!< This masks an 8-bit version number, the version of the ARM EABI to which this ELF //!file conforms. The current EABI version is #ARM_EABI_VERSION. ARM_EABI_VERSION = 0x02000000 //!< Current ARM EABI version. }; //@} //! \name Sections //@{ /*! * \brief ELF section header. * * An object file's section header table lets one locate all the file's * sections. The section header table is an array of #Elf32_Shdr structures. * A section header table index is a subscript into this array. The ELF * header's #Elf32_Ehdr::e_shoff member gives the byte offset from the beginning of * the file to the section header table; #Elf32_Ehdr::e_shnum tells how many entries * the section header table contains; #Elf32_Ehdr::e_shentsize gives the size in bytes * of each entry. * * Some section header table indexes are reserved. An object file will not * have sections for these special indexes: * - #SHN_UNDEF * - #SHN_LORESERVE * - #SHN_LOPROC * - #SHN_HIPROC * - #SHN_ABS * - #SHN_COMMON * - #SHN_HIRESERVE */ struct Elf32_Shdr { Elf32_Word sh_name; //!< The section's name. Index into the section header string table section. Elf32_Word sh_type; //!< Section type, describing the contents and semantics. Elf32_Word sh_flags; //!< Section flags describing various attributes. Elf32_Addr sh_addr; //!< The address at which the section will appear in the memory image, or 0. Elf32_Off sh_offset; //!< Offset from beginning of the file to the first byte in the section. Elf32_Word sh_size; //!< The section's size in bytes. Elf32_Word sh_link; //!< Section header table link index. Interpretation depends on section type. Elf32_Word sh_info; //!< Extra information about the section. Depends on section type. Elf32_Word sh_addralign; //!< Address alignment constraint. Values are 0 and positive powers of 2. Elf32_Word sh_entsize; //!< Size in bytes of section entries, or 0 if the section does not have fixed-size entries. }; struct Elf64_Shdr { Elf64_Word sh_name; //!< The section's name. Index into the section header string table section. Elf64_Word sh_type; //!< Section type, describing the contents and semantics. Elf64_XWord sh_flags; //!< Section flags describing various attributes. Elf64_Addr sh_addr; //!< The address at which the section will appear in the memory image, or 0. Elf64_Off sh_offset; //!< Offset from beginning of the file to the first byte in the section. Elf64_XWord sh_size; //!< The section's size in bytes. Elf64_Word sh_link; //!< Section header table link index. Interpretation depends on section type. Elf64_Word sh_info; //!< Extra information about the section. Depends on section type. Elf64_XWord sh_addralign; //!< Address alignment constraint. Values are 0 and positive powers of 2. Elf64_XWord sh_entsize; //!< Size in bytes of section entries, or 0 if the section does not have fixed-size entries. }; /*! * Special section indexes. */ enum { SHN_UNDEF = 0, SHN_LORESERVE = 0xff00, SHN_LOPROC = 0xff00, SHN_HIPROC = 0xff1f, SHN_ABS = 0xfff1, //!< The symbol has an absolute value that will not change because of relocation. SHN_COMMON = 0xfff2, //!< The symbol labels a common block that has not yet been allocated. SHN_HIRESERVE = 0xffff }; /*! * Section type constants. */ enum { SHT_NULL = 0, SHT_PROGBITS = 1, SHT_SYMTAB = 2, SHT_STRTAB = 3, SHT_RELA = 4, SHT_HASH = 5, SHT_DYNAMIC = 6, SHT_NOTE = 7, SHT_NOBITS = 8, SHT_REL = 9, SHT_SHLIB = 10, SHT_DYNSYM = 11, SHT_INITARRAY = 14, SHT_FINIARRAY = 15, SHT_PREINITARRAY = 16 }; /*! * Section flag constants. */ enum { SHF_WRITE = 0x1, //!< Section is writable. SHF_ALLOC = 0x2, //!< Allocate section. SHF_EXECINSTR = 0x4 //!< Section contains executable instructions. }; /*! * ARM-specific section flag constants */ enum { SHF_ENTRYSECT = 0x10000000, //!< The section contains an entry point. SHF_COMDEF = 0x80000000 //!< The section may be multiply defined in the input to a link step. }; #define BSS_SECTION_NAME ".bss" #define DATA_SECTION_NAME ".data" #define TEXT_SECTION_NAME ".text" #define SHSTRTAB_SECTION_NAME ".shstrtab" #define STRTAB_SECTION_NAME ".strtab" #define SYMTAB_SECTION_NAME ".symtab" //@} //! \name Segments //@{ /*! * \brief ELF program header. * * An executable or shared object file's program header table is an array of * structures, each describing a segment or other information the system needs * to prepare the program for execution. An object file segment contains one * or more sections. Program headers are meaningful only for executable and * shared object files. A file specifies its own program header size with the * ELF header's #Elf32_Ehdr::e_phentsize and #Elf32_Ehdr::e_phnum members. */ struct Elf32_Phdr { Elf32_Word p_type; //!< What type of segment this header describes. Elf32_Off p_offset; //!< Offset in bytes from start of file to the first byte of the segment. Elf32_Addr p_vaddr; //!< Virtual address at which the segment will reside in memory. Elf32_Addr p_paddr; //!< Physical address, for systems where this is relevant. Elf32_Word p_filesz; //!< Number of bytes of file data the segment consumes. May be zero. Elf32_Word p_memsz; //!< Size in bytes of the segment in memory. May be zero. Elf32_Word p_flags; //!< Flags relevant to the segment. Elf32_Word p_align; //!< Alignment constraint for segment addresses. Possible values are 0 and positive powers of 2. }; struct Elf64_Phdr { Elf64_Word p_type; //!< What type of segment this header describes. Elf64_Word p_flags; //!< Flags relevant to the segment. Elf64_Off p_offset; //!< Offset in bytes from start of file to the first byte of the segment. Elf64_Addr p_vaddr; //!< Virtual address at which the segment will reside in memory. Elf64_Addr p_paddr; //!< Physical address, for systems where this is relevant. Elf64_XWord p_filesz; //!< Number of bytes of file data the segment consumes. May be zero. Elf64_XWord p_memsz; //!< Size in bytes of the segment in memory. May be zero. Elf64_XWord p_align; //!< Alignment constraint for segment addresses. Possible values are 0 and positive powers of 2. }; /*! * Segment type constants. */ enum { PT_NULL = 0, PT_LOAD = 1, PT_DYNAMIC = 2, PT_INTERP = 3, PT_NOTE = 4, PT_SHLIB = 5, PT_PHDR = 6 }; /*! * Program header flag constants. */ enum { PF_X = 0x1, //!< Segment is executable. PF_W = 0x2, //!< Segment is writable. PF_R = 0x4 //!< Segment is readable. }; //@} //! \name Symbol table //@{ enum { STN_UNDEF = 0 //!< Undefined symbol index. }; /*! * \brief ELF symbol table entry. * * An object file's symbol table holds information needed to locate and * relocate a program's symbolic definitions and references. A symbol * table index is a subscript into this array. Index 0 both designates * the first entry in the table and serves as the undefined symbol index. */ struct Elf32_Sym { Elf32_Word st_name; //!< Index into file's string table. Elf32_Addr st_value; //!< Value associated with the symbol. Depends on context. Elf32_Word st_size; //!< Size associated with symbol. 0 if the symbol has no size or an unknown size. unsigned char st_info; //!< Specified the symbol's type and binding attributes. unsigned char st_other; //!< Currently 0 (reserved). Elf32_Half st_shndx; //!< Section header table index for this symbol. }; struct Elf64_Sym { Elf64_Word st_name; //!< Index into file's string table. unsigned char st_info; //!< Specified the symbol's type and binding attributes. unsigned char st_other; //!< Currently 0 (reserved). Elf64_Half st_shndx; //!< Section header table index for this symbol. Elf64_Addr st_value; //!< Value associated with the symbol. Depends on context. Elf64_XWord st_size; //!< Size associated with symbol. 0 if the symbol has no size or an unknown size. }; //! \name st_info macros //! Macros for manipulating the st_info field of Elf32_Sym struct. //@{ #define ELF32_ST_BIND(i) ((i) >> 4) //!< Get binding attributes. #define ELF32_ST_TYPE(i) ((i)&0x0f) //!< Get symbol type. #define ELF32_ST_INFO(b, t) \ (((b) << 4) + ((t)&0x0f)) //!< Construct st_info value from binding attributes and symbol type. //@} #define ELF64_ST_BIND(i) ((i)>>4) #define ELF64_ST_TYPE(i) ((i)&0xf) #define ELF64_ST_INFO(b,t) (((b)<<4)+((t)&0xf)) /*! * \brief Symbol binding attributes. * * These constants are mask values. */ enum { STB_LOCAL = 0, //!< Local symbol not visible outside the object file. STB_GLOBAL = 1, //!< Symbol is visible to all object files being linked together. STB_WEAK = 2, //!< Like global symbols, but with lower precedence. // Processor-specific semantics. STB_LOPROC = 13, STB_HIPROC = 15 }; /*! * \brief Symbol types. */ enum { STT_NOTYPE = 0, //!< The symbol's type is not specified. STT_OBJECT = 1, //!< The symbol is associated with a data object, such as a variable or array. STT_FUNC = 2, //!< The symbol is associated with a function or other executable code. STT_SECTION = 3, //!< The synmbol is associated with a section. Primarily used for relocation. STT_FILE = 4, //!< A file symbol has STB_LOCAL binding, its section index is SHN_ABS, and it precedes the other //!STB_LOCAL symbols for the file, if it is present. STT_LOPROC = 13, //!< Low bound of processor-specific symbol types. STT_HIPROC = 15 //!< High bound of processor-specific symbol types. }; /*! * GHS-specific constants */ enum { STO_THUMB = 1 //!< This flag is set on #Elf32_Sym.st_other if the symbol is Thumb mode code. }; #define ARM_SEQUENCE_MAPSYM "$a" #define DATA_SEQUENCE_MAPSYM "$d" #define THUMB_SEQUENCE_MAPSYM "$t" #define THUMB_BL_TAGSYM "$b" #define FN_PTR_CONST_TAGSYM "$f" #define INDIRECT_FN_CALL_TAGSYM "$p" #define MAPPING_SYMBOL_COUNT_TAGSYM "$m" //@} #pragma pack() #endif // _ELF_h_
2.34375
2
2024-11-18T21:09:34.833980+00:00
2023-08-27T19:14:02
bfd5a653dc85877c1ee373f608cae287322391cb
{ "blob_id": "bfd5a653dc85877c1ee373f608cae287322391cb", "branch_name": "refs/heads/master", "committer_date": "2023-08-27T19:14:02", "content_id": "9c04d52037de5045a1e4f269bdd4dd03b0832c01", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "7c857119fe1505b1d80d6e62969661c06dc1a2f4", "extension": "h", "filename": "ServiceProcessorManagementInterfaceTable.h", "fork_events_count": 770, "gha_created_at": "2019-09-02T08:22:14", "gha_event_created_at": "2023-09-03T12:41:33", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 205810121, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3373, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/MdePkg/Include/IndustryStandard/ServiceProcessorManagementInterfaceTable.h", "provenance": "stackv2-0065.json.gz:10956", "repo_name": "CloverHackyColor/CloverBootloader", "revision_date": "2023-08-27T19:14:02", "revision_id": "2711170df4f60b2ae5aa20add3e00f35cf57b7e5", "snapshot_id": "7042ca7dd6b513d22be591a295e49071ae1482ee", "src_encoding": "UTF-8", "star_events_count": 4734, "url": "https://raw.githubusercontent.com/CloverHackyColor/CloverBootloader/2711170df4f60b2ae5aa20add3e00f35cf57b7e5/MdePkg/Include/IndustryStandard/ServiceProcessorManagementInterfaceTable.h", "visit_date": "2023-08-30T22:14:34.590134" }
stackv2
/** @file Service Processor Management Interface (SPMI) ACPI table definition from Intelligent Platform Management Interface Specification Second Generation. Copyright (c) 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent @par Revision Reference: - Intelligent Platform Management Interface Specification Second Generation v2.0 Revision 1.1, Dated October 2013. https://www.intel.com/content/dam/www/public/us/en/documents/specification-updates/ipmi-intelligent-platform-mgt-interface-spec-2nd-gen-v2-0-spec-update.pdf **/ #ifndef _SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_TABLE_H_ #define _SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_TABLE_H_ #include <IndustryStandard/Acpi.h> #pragma pack(1) /// /// Definition for the device identification information used by the Service /// Processor Management Interface Description Table /// typedef union { /// /// For PCI IPMI device /// struct { UINT8 SegmentGroup; UINT8 Bus; UINT8 Device; UINT8 Function; } Pci; /// /// For non-PCI IPMI device, the ACPI _UID value of the device /// UINT32 Uid; } EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_TABLE_DEVICE_ID; /// /// Definition for Service Processor Management Interface Description Table /// typedef struct { EFI_ACPI_DESCRIPTION_HEADER Header; /// /// Indicates the type of IPMI interface. /// UINT8 InterfaceType; /// /// This field must always be 01h to be compatible with any software that /// implements previous versions of this spec. /// UINT8 Reserved1; /// /// Identifies the IPMI specification revision, in BCD format. /// UINT16 SpecificationRevision; /// /// Interrupt type(s) used by the interface. /// UINT8 InterruptType; /// /// The bit assignment of the SCI interrupt within the GPEx_STS register of a /// GPE described if the FADT that the interface triggers. /// UINT8 Gpe; /// /// Reserved, must be 00h. /// UINT8 Reserved2; /// /// PCI Device Flag. /// UINT8 PciDeviceFlag; /// /// The I/O APIC or I/O SAPIC Global System Interrupt used by the interface. /// UINT32 GlobalSystemInterrupt; /// /// The base address of the interface register set described using the /// Generic Address Structure (GAS, See [ACPI 2.0] for the definition). /// EFI_ACPI_2_0_GENERIC_ADDRESS_STRUCTURE BaseAddress; /// /// Device identification information. /// EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_TABLE_DEVICE_ID DeviceId; /// /// This field must always be null (0x00) to be compatible with any software /// that implements previous versions of this spec. /// UINT8 Reserved3; } EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_TABLE; #pragma pack() #endif
2.15625
2
2024-11-18T21:09:34.918966+00:00
2021-05-13T15:45:50
43a99ff1e687bd3f87cb116c28cd8e50c13da57d
{ "blob_id": "43a99ff1e687bd3f87cb116c28cd8e50c13da57d", "branch_name": "refs/heads/main", "committer_date": "2021-05-13T15:45:50", "content_id": "54846b967b7eb013363107c04cae75e83ee58d21", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e52a03615c9237b53432ceb30584abbbdd5e4d45", "extension": "c", "filename": "security.c", "fork_events_count": 1, "gha_created_at": "2021-05-08T15:23:25", "gha_event_created_at": "2021-05-13T15:45:50", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 365547387, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13941, "license": "Apache-2.0", "license_type": "permissive", "path": "/stsdk/src/main/jni/security/security.c", "provenance": "stackv2-0065.json.gz:11085", "repo_name": "secure-tunnel/st-android", "revision_date": "2021-05-13T15:45:50", "revision_id": "5fc83672b05f914a520b23132111da3f9511d93a", "snapshot_id": "1ebbb58f6df2542cd2732889947a3d110486e621", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/secure-tunnel/st-android/5fc83672b05f914a520b23132111da3f9511d93a/stsdk/src/main/jni/security/security.c", "visit_date": "2023-04-28T14:29:01.844490" }
stackv2
// // Created by rytong on 2021/4/27. // #include "security.h" #include <android/log.h> #include <string.h> #include <stdlib.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <stdio.h> #define LOG_TAG "LOG_C" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) jbyteArray Java_com_st_security_SM3_hash(JNIEnv *env, jclass cls, jbyteArray data, jint datalen) { unsigned char * dataChars = (unsigned char *) (*env)->GetByteArrayElements(env, data, 0); EVP_MD_CTX *md_ctx; const EVP_MD *md; unsigned char hash[64]; unsigned int hash_len = 0; md = EVP_sm3(); md_ctx = EVP_MD_CTX_new(); EVP_DigestInit_ex(md_ctx, md, NULL); EVP_DigestUpdate(md_ctx, dataChars, datalen); EVP_DigestFinal_ex(md_ctx, hash, &hash_len); EVP_MD_CTX_free(md_ctx); (*env)->ReleaseByteArrayElements(env, data, (jbyte*)dataChars, 0); jbyteArray resultArray = (*env)->NewByteArray(env, hash_len); (*env)->SetByteArrayRegion(env, resultArray, 0, hash_len, hash); if(md_ctx) { EVP_MD_CTX_free(md_ctx); } return resultArray; } jbyteArray Java_com_st_security_SM4_encrypt(JNIEnv *env, jclass cls, jbyteArray data, jint datalen, jbyteArray key, jint keylen, jbyteArray iv, jint ivlen) { /* 预处理参数类型 */ unsigned char * keyChars = (unsigned char *) (*env)->GetByteArrayElements(env, key, 0); unsigned char * ivChars = (unsigned char *) (*env)->GetByteArrayElements(env, iv, 0); unsigned char * dataChars = (unsigned char *) (*env)->GetByteArrayElements(env, data, 0); EVP_CIPHER *evp_cipher = EVP_sm4_cbc(); int cipher_key_length = EVP_CIPHER_key_length(evp_cipher); int cipher_iv_length = EVP_CIPHER_iv_length(evp_cipher); int i, cipher_length, final_length; unsigned char *ciphertext; if(cipher_key_length != keylen) { goto END; } if(cipher_iv_length != ivlen) { goto END; } EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); if(ctx == NULL) { goto END; } EVP_EncryptInit_ex(ctx, evp_cipher, NULL, keyChars, ivChars); cipher_length = datalen + EVP_MAX_BLOCK_LENGTH; ciphertext = (unsigned char*)malloc(cipher_length); EVP_EncryptUpdate(ctx, ciphertext, &cipher_length, dataChars, datalen); EVP_EncryptFinal_ex(ctx, ciphertext + cipher_length, &final_length); jbyteArray resultArray = (*env)->NewByteArray(env, cipher_length + final_length); (*env)->SetByteArrayRegion(env, resultArray, 0, cipher_length + final_length, ciphertext); free(ciphertext); EVP_CIPHER_CTX_free(ctx); END: /* 释放资源 */ (*env)->ReleaseByteArrayElements(env, data, (jbyte *) dataChars, 0); (*env)->ReleaseByteArrayElements(env, key, (jbyte *) keyChars, 0); (*env)->ReleaseByteArrayElements(env, iv, (jbyte *) ivChars, 0); return resultArray; } jbyteArray Java_com_st_security_SM4_decrypt(JNIEnv *env, jclass cls, jbyteArray data, jint datalen, jbyteArray key, jint keylen, jbyteArray iv, jint ivlen) { /* 预处理参数类型 */ unsigned char * keyChars = (unsigned char *) (*env)->GetByteArrayElements(env, key, 0); unsigned char * ivChars = (unsigned char *) (*env)->GetByteArrayElements(env, iv, 0); unsigned char * dataChars = (unsigned char *) (*env)->GetByteArrayElements(env, data, 0); EVP_CIPHER *evp_cipher = EVP_sm4_cbc(); int cipher_key_length = EVP_CIPHER_key_length(evp_cipher); int cipher_iv_length = EVP_CIPHER_iv_length(evp_cipher); int i, cipher_length, final_length; unsigned char *ciphertext; if(cipher_key_length != keylen) { goto END; } if(cipher_iv_length != ivlen) { goto END; } EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); if(ctx == NULL) { goto END; } EVP_DecryptInit_ex(ctx, evp_cipher, NULL, keyChars, ivChars); cipher_length = datalen + EVP_MAX_BLOCK_LENGTH; ciphertext = (unsigned char*)malloc(cipher_length); EVP_DecryptUpdate(ctx, ciphertext, &cipher_length, dataChars, datalen); EVP_DecryptFinal_ex(ctx, ciphertext + cipher_length, &final_length); jbyteArray resultArray = (*env)->NewByteArray(env, cipher_length + final_length); (*env)->SetByteArrayRegion(env, resultArray, 0, cipher_length + final_length, ciphertext); free(ciphertext); EVP_CIPHER_CTX_free(ctx); END: /* 释放资源 */ (*env)->ReleaseByteArrayElements(env, data, (jbyte *) dataChars, 0); (*env)->ReleaseByteArrayElements(env, key, (jbyte *) keyChars, 0); (*env)->ReleaseByteArrayElements(env, iv, (jbyte *) ivChars, 0); return resultArray; } int create_evp_pkey(unsigned char *key, int keyLen, int is_public, EVP_PKEY **out_pkey) { BIO *keybio = NULL; EC_KEY *ecKey = NULL; keybio = BIO_new_mem_buf(key, keyLen); if(keybio == NULL) { LOGI("BIO_new_mem_buf failed.\n"); return 0; } if(is_public){ ecKey = PEM_read_bio_EC_PUBKEY(keybio, &ecKey, NULL, NULL); if(ecKey == NULL) { LOGI("PEM_read_bio_EC_PUBKEY failed\n"); BIO_free(keybio); return 0; } }else{ ecKey = PEM_read_bio_ECPrivateKey(keybio, &ecKey, NULL, NULL); if(ecKey == NULL) { LOGI("PEM_read_bio_ECPrivateKey failed\n"); BIO_free(keybio); return 0; } } int ret = EVP_PKEY_set1_EC_KEY(*out_pkey, ecKey); if(ret != 1){ LOGI("EVP_PKEY_set1_EC_KEY failed. ", ret); EC_KEY_free(ecKey); BIO_free(keybio); return 0; } if(*out_pkey == NULL) { LOGI("Failed to Get Key\n"); EC_KEY_free(ecKey); BIO_free(keybio); return 0; } EC_KEY_free(ecKey); BIO_free(keybio); return 1; } jbyteArray Java_com_st_security_SM2_encrypt(JNIEnv *env, jclass cls, jbyteArray data, jint datalen, jbyteArray publickey, jint publickeylen) { EVP_PKEY_CTX *ectx = NULL; EVP_PKEY *pkey = EVP_PKEY_new(); unsigned char *ciphertext = NULL; size_t ciphertext_len; jbyteArray resultArray = NULL; unsigned char * dataChars = (unsigned char *) (*env)->GetByteArrayElements(env, data, 0); unsigned char * pubKeyChars = (unsigned char *) (*env)->GetByteArrayElements(env, publickey, 0); if(create_evp_pkey(pubKeyChars, publickeylen, 1, &pkey) == 0) { LOGI("create_evp_pkey failed\n"); goto clean_up; } /* compute SM2 encryption */ if((EVP_PKEY_set_alias_type(pkey, EVP_PKEY_SM2)) != 1) { LOGI("EVP_PKEY_set_alias_type failed.\n"); goto clean_up; } if(!(ectx = EVP_PKEY_CTX_new(pkey, NULL))){ LOGI("EVP_PKEY_CTX_new failed.\n"); goto clean_up; } if((EVP_PKEY_encrypt_init(ectx)) != 1) { LOGI("EVP_PKEY_encrypt_init failed.\n"); goto clean_up; } if((EVP_PKEY_encrypt(ectx, NULL, &ciphertext_len, dataChars, datalen)) != 1){ LOGI("EVP_PKEY_encrypt failed.\n"); goto clean_up; } if(!(ciphertext = (unsigned char*)malloc(ciphertext_len))){ LOGI("malloc failed.\n"); goto clean_up; } if((EVP_PKEY_encrypt(ectx, ciphertext, &ciphertext_len, dataChars, datalen)) != 1){ LOGI("EVP_PKEY_encrypt failed.\n"); goto clean_up; } resultArray = (*env)->NewByteArray(env, ciphertext_len); (*env)->SetByteArrayRegion(env, resultArray, 0, ciphertext_len, ciphertext); clean_up: if(pkey){ EVP_PKEY_free(pkey); } if(ectx){ EVP_PKEY_CTX_free(ectx); } if(ciphertext){ free(ciphertext); } (*env)->ReleaseByteArrayElements(env, data, (jbyte *) dataChars, 0); (*env)->ReleaseByteArrayElements(env, publickey, (jbyte *) pubKeyChars, 0); return resultArray; } jbyteArray Java_com_st_security_SM2_decrypt(JNIEnv *env, jclass cls, jbyteArray data, jint datalen, jbyteArray privatekey, jint privatekeylen) { EVP_PKEY_CTX *ectx = NULL; EVP_PKEY *pkey = EVP_PKEY_new(); unsigned char *plaintext = NULL; size_t plaintext_len; jbyteArray resultArray = NULL; unsigned char * dataChars = (unsigned char *) (*env)->GetByteArrayElements(env, data, 0); unsigned char * privKeyChars = (unsigned char *) (*env)->GetByteArrayElements(env, privatekey, 0); if(create_evp_pkey(privKeyChars, privatekeylen, 0, &pkey) == 0) { LOGI("create_evp_pkey failed.\n"); goto clean_up; } if((EVP_PKEY_set_alias_type(pkey, EVP_PKEY_SM2)) != 1) { LOGI("EVP_PKEY_set_alias_type failed.\n"); goto clean_up; } if(!(ectx = EVP_PKEY_CTX_new(pkey, NULL))) { LOGI("EVP_PKEY_CTX_new failed.\n"); goto clean_up; } /* compute SM2 decryption */ if((EVP_PKEY_decrypt_init(ectx)) != 1){ LOGI("EVP_PKEY_decrypt_init failed.\n"); goto clean_up; } if((EVP_PKEY_decrypt(ectx, NULL, &plaintext_len, dataChars, datalen)) != 1){ LOGI("EVP_PKEY_decrypt failed.\n"); goto clean_up; } if(!(plaintext = (unsigned char*)malloc(plaintext_len))){ LOGI("malloc failed.\n"); goto clean_up; } if((EVP_PKEY_decrypt(ectx, plaintext, &plaintext_len, dataChars, datalen)) != 1){ LOGI("EVP_PKEY_decrypt failed.\n"); goto clean_up; } resultArray = (*env)->NewByteArray(env, plaintext_len); (*env)->SetByteArrayRegion(env, resultArray, 0, plaintext_len, plaintext); clean_up: if(pkey){ EVP_PKEY_free(pkey); } if(ectx){ EVP_PKEY_CTX_free(ectx); } if(plaintext){ free(plaintext); } (*env)->ReleaseByteArrayElements(env, data, (jbyte *) dataChars, 0); (*env)->ReleaseByteArrayElements(env, privatekey, (jbyte *) privKeyChars, 0); return resultArray; } jbyteArray Java_com_st_security_SM2_sign(JNIEnv *env, jclass cls, jbyteArray data, jint datalen, jbyteArray privatekey, jint privatekeylen) { EVP_PKEY *evpPkey = EVP_PKEY_new(); EVP_MD_CTX *evpMdCtx = NULL; int len_sig = 0; jbyteArray resultArray = NULL; unsigned char szSign[256] = {0}; unsigned char * dataChars = (unsigned char *) (*env)->GetByteArrayElements(env, data, 0); unsigned char * privKeyChars = (unsigned char *) (*env)->GetByteArrayElements(env, privatekey, 0); if(create_evp_pkey(privKeyChars, privatekeylen, 0, &evpPkey) == 0){ LOGI("create_evp_pkey failed\n"); goto END; } if((EVP_PKEY_set_alias_type(evpPkey, EVP_PKEY_SM2)) != 1) { LOGI("EVP_PKEY_set_alias_type failed.\n"); goto END; } /* do signature */ evpMdCtx = EVP_MD_CTX_new(); if(evpMdCtx == NULL) { LOGI("EVP_MD_CTX_new failed"); goto END; } EVP_MD_CTX_init(evpMdCtx); if(EVP_SignInit_ex(evpMdCtx, EVP_sm3(), NULL) != 1) { LOGI("EVP_SignInit_ex failed"); goto END; } if(EVP_SignUpdate(evpMdCtx, dataChars, datalen) != 1) { LOGI("EVP_SignUpdate failed"); goto END; } if(EVP_SignFinal(evpMdCtx, szSign, &len_sig, evpPkey) != 1){ LOGI("EVP_SignFinal failed"); goto END; } resultArray = (*env)->NewByteArray(env, len_sig); (*env)->SetByteArrayRegion(env, resultArray, 0, len_sig, szSign); END: /* 释放资源 */ if(evpMdCtx != NULL){ EVP_MD_CTX_free(evpMdCtx); } if(evpPkey != NULL){ EVP_PKEY_free(evpPkey); } (*env)->ReleaseByteArrayElements(env, data, (jbyte *) dataChars, 0); (*env)->ReleaseByteArrayElements(env, privatekey, (jbyte *) privKeyChars, 0); return resultArray; } jint Java_com_st_security_SM2_verify(JNIEnv *env, jclass cls, jbyteArray data, jint datalen, jbyteArray signdata, jint signdatalen, jbyteArray publickey, jint publickeylen) { int ret_val = 0; EVP_PKEY *evpPkey = EVP_PKEY_new(); EVP_MD_CTX *evpMdCtx = NULL; unsigned char *dataChars = (unsigned char *) (*env)->GetByteArrayElements(env, data, 0); unsigned char *pubKeyChars = (unsigned char *) (*env)->GetByteArrayElements(env, publickey, 0); unsigned char *signdataChars = (unsigned char*)(*env)->GetByteArrayElements(env, signdata, 0); if(create_evp_pkey(pubKeyChars, publickeylen, 1, &evpPkey) == 0){ LOGI("create_evp_pkey failed"); ret_val = -1; goto END; } if((EVP_PKEY_set_alias_type(evpPkey, EVP_PKEY_SM2)) != 1) { LOGI("EVP_PKEY_set_alias_type failed.\n"); goto END; } /* do signature */ evpMdCtx = EVP_MD_CTX_new(); if(evpMdCtx == NULL) { LOGI("EVP_MD_CTX_new failed"); ret_val = -2; goto END; } EVP_MD_CTX_init(evpMdCtx); if(EVP_VerifyInit_ex(evpMdCtx, EVP_sm3(), NULL) != 1) { LOGI("EVP_SignInit_ex failed"); ret_val = -3; goto END; } if(EVP_VerifyUpdate(evpMdCtx, dataChars, datalen) != 1) { LOGI("EVP_SignUpdate failed"); ret_val = -4; goto END; } if(EVP_VerifyFinal(evpMdCtx, signdataChars, signdatalen, evpPkey) != 1){ LOGI("EVP_SignFinal failed"); ret_val = -5; goto END; } ret_val = 0; END: /* 释放资源 */ if(evpMdCtx != NULL){ EVP_MD_CTX_free(evpMdCtx); } if(evpPkey != NULL){ EVP_PKEY_free(evpPkey); } (*env)->ReleaseByteArrayElements(env, data, (jbyte *) dataChars, 0); (*env)->ReleaseByteArrayElements(env, publickey, (jbyte *) pubKeyChars, 0); (*env)->ReleaseByteArrayElements(env, signdata, (jbyte*)signdataChars, 0); return (jint)ret_val; }
2.203125
2
2024-11-18T21:09:35.273839+00:00
2014-04-04T18:21:15
ce1f993c5f3e19d3fcf5e083564c9d607d811d90
{ "blob_id": "ce1f993c5f3e19d3fcf5e083564c9d607d811d90", "branch_name": "refs/heads/master", "committer_date": "2014-04-04T18:21:15", "content_id": "a7ae15c1f73958a8eacc5ead8cb3ba27ee634488", "detected_licenses": [ "MIT" ], "directory_id": "7e2c9ea8a31c3c955af74f0daf952ba6d7697651", "extension": "c", "filename": "dexe_stack.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 18448094, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2138, "license": "MIT", "license_type": "permissive", "path": "/src/dexe_stack.c", "provenance": "stackv2-0065.json.gz:11471", "repo_name": "pdemian/DEXEv3", "revision_date": "2014-04-04T18:21:15", "revision_id": "e6cbc625e26e33a8b9faa538eeaea008b3f9a476", "snapshot_id": "19ea54ee7a15bbf4f27055567751f780283a18c4", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/pdemian/DEXEv3/e6cbc625e26e33a8b9faa538eeaea008b3f9a476/src/dexe_stack.c", "visit_date": "2021-01-10T19:37:04.240562" }
stackv2
/* Copyright (C) 2014 Patrick Demian 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 "dexe_utils.h" #include "dexe_stack.h" int stack_init(stack* st) { st->stack_elements = (long*)malloc(DEFAULT_STACK_SIZE * sizeof(long)); if(st->stack_elements == NULL) return 1; st->length = DEFAULT_STACK_SIZE; st->stack_pointer = 0; return 0; } void stack_free(stack* st) { if(st != NULL) { free(st->stack_elements); st = NULL; } } void stack_empty(stack* st) { st->stack_pointer = 0; } int stack_push(stack* st, long value) { if(st->stack_pointer >= st->length) { //allocate more memory st->length += INCREASE_STACK_SIZE_BY; long* ptr = (long*)realloc(st->stack_elements, st->length * sizeof(long)); if(ptr == NULL) return 1; st->stack_elements = ptr; } st->stack_elements[st->stack_pointer++] = value; return 0; } //Removed pushing Executable* and Opcode* and testing for range //This now must be done via the calling method. long stack_peek(stack* st) { return st->stack_elements[st->stack_pointer-1]; } long stack_pop(stack* st) { return st->stack_elements[--st->stack_pointer]; }
2.625
3
2024-11-18T21:09:35.333755+00:00
2019-05-13T13:40:29
b270ddb984aac0c8388d9b1e7707465d40ba6716
{ "blob_id": "b270ddb984aac0c8388d9b1e7707465d40ba6716", "branch_name": "refs/heads/master", "committer_date": "2019-05-13T13:40:29", "content_id": "a09d48adb9e720a7e6dca88a60b18e7465caa682", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "2818e84c898daa580ce32b99a1d2bd295b2481de", "extension": "c", "filename": "proj_main.c", "fork_events_count": 1, "gha_created_at": "2020-06-02T07:54:18", "gha_event_created_at": "2020-06-02T07:54:19", "gha_language": null, "gha_license_id": null, "github_id": 268736789, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1221, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/examples/drivers/demo_pwm/code/application/proj_main.c", "provenance": "stackv2-0065.json.gz:11599", "repo_name": "silan-wireless/FR801x-SDK", "revision_date": "2019-05-13T13:40:29", "revision_id": "073b08fe21bb8423d7037641fcdd72421e96a596", "snapshot_id": "6017bc2b04d4349a746c60165bc1e13eaed38725", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/silan-wireless/FR801x-SDK/073b08fe21bb8423d7037641fcdd72421e96a596/examples/drivers/demo_pwm/code/application/proj_main.c", "visit_date": "2022-01-26T05:44:35.196994" }
stackv2
/** * Copyright (c) 2019, Tsingtao Freqchip * * All rights reserved. * * */ /* * INCLUDE FILES **************************************************************************************** */ #include <stdio.h> #include <string.h> #include "gap_api.h" #include "driver_gpio.h" #include "driver_iomux.h" #include "driver_pwm.h" /* one count means: 83ns high_count:1~0xffffffff low_count:1~0xffffffff high_count + low_count <=0xffffffff */ pwm_config_t demo_pwm_cfg; void user_proj_main_before_ble_ini(void) { printf("user proj_main_before_ble_ini\r\n"); uint8_t addr[] = {0x1f, 0x09, 0x07, 0x09, 0x17, 0x20}; gap_address_set(addr); } void user_proj_main(void) { //Configure PC2 as PWM gpio_set_port_mux(GPIO_PORT_C,GPIO_BIT_2,PORTC2_FUNC_PWM2); demo_pwm_cfg.gpio_pin = GPIO_BIT_2; demo_pwm_cfg.gpio_port = GPIO_PORT_C; demo_pwm_cfg.high_count = 10000000; //Set the high count as 830 milliseconds demo_pwm_cfg.low_count = 10000000; //Set the low count as 830 milliseconds pwm_timer_init(&demo_pwm_cfg); pwm_timer_config(&demo_pwm_cfg); pwm_timer_start(&demo_pwm_cfg); //pwm_timer_stop(&demo_pwm_cfg); }
2.25
2
2024-11-18T21:09:35.638515+00:00
2021-09-14T04:49:56
1e44879fed96890845b3867bf5ef44a7fbcb6c1f
{ "blob_id": "1e44879fed96890845b3867bf5ef44a7fbcb6c1f", "branch_name": "refs/heads/master", "committer_date": "2021-09-14T04:49:56", "content_id": "152d5d9d61cdfcefb3fee57ef2e7476a4b59e711", "detected_licenses": [ "MIT" ], "directory_id": "10bacc7cc5a7a1cbd82f41bfc4e201360517e9b0", "extension": "c", "filename": "decode_max.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": 2934, "license": "MIT", "license_type": "permissive", "path": "/decode_max.c", "provenance": "stackv2-0065.json.gz:11857", "repo_name": "alsophian/qdv", "revision_date": "2021-09-14T04:49:56", "revision_id": "a603f76006a2228346f37fde386b6881ba6acf7f", "snapshot_id": "4b000a1124d00aff4b9cf2ff892971614c00c401", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alsophian/qdv/a603f76006a2228346f37fde386b6881ba6acf7f/decode_max.c", "visit_date": "2023-07-19T07:01:09.115576" }
stackv2
/*============================================================================== decode_max.c -- Used for code size measurement of max size of decoder. Copyright (c) 2020, Laurence Lundblade. All rights reserved. SPDX-License-Identifier: BSD-3-Clause See BSD-3-Clause license in README.md =============================================================================*/ #include "qcbor/qcbor_decode.h" #include "qcbor/qcbor_spiffy_decode.h" /* These two symbols hopefully appear at the start and allow use of nm(1) to list symbols in order so the sizes of the functions can be computed relative to the previous symbol */ int first_symbol_1() { return 7; } static const uint8_t first_symbol_2[] = {0x55, 0x66}; /* This calls enough decode functions so that everything in the decode library will be linked so the object code size of the full decoder can be measured. */ int main(int argc, const char * argv[]) { (void)argc; // Suppress unused warning (void)argv; // Suppress unused warning static const uint8_t min[] = {0x81, 0xf5}; QCBORTagListOut TL; UsefulBuf_MAKE_STACK_UB(Pool, 100); // Decode it and see that is right QCBORDecodeContext DC; QCBORItem Item; // So first_symbol_x isn't dead-stripped Item.uDataType = first_symbol_1(); Item.val.string.ptr = first_symbol_2; QCBORDecode_SetCallerConfiguredTagList(&DC, NULL); QCBORDecode_SetMemPool(&DC, Pool, true); QCBORDecode_Init(&DC, UsefulBuf_FROM_BYTE_ARRAY_LITERAL(min), QCBOR_DECODE_MODE_NORMAL); QCBORDecode_GetNextWithTags(&DC, &Item, &TL); if(Item.uDataType != QCBOR_TYPE_MAP) { return -2; } QCBORDecode_GetNext(&DC, &Item); if(Item.uDataType != QCBOR_TYPE_TRUE) { return -3; } // This won't actually run correctly, but does link correctly int64_t nInt; uint64_t uInt; double dDoub; QCBORDecode_GetInt64(&DC, &nInt); QCBORDecode_GetInt64ConvertAll(&DC, 0xff, &nInt); QCBORDecode_GetUInt64ConvertAll(&DC, 0xff, &uInt); QCBORDecode_GetDoubleConvertAll(&DC, 0xff, &dDoub); UsefulBufC UB; QCBORDecode_GetByteStringInMapN(&DC, 9, &UB); bool b; QCBORDecode_GetBool(&DC, &b); QCBORDecode_GetEpochDate(&DC, 0, &nInt); QCBORDecode_GetBignumInMapN(&DC, 0, 0, &UB, &b); QCBORDecode_GetDecimalFraction(&DC, 0, &nInt, &nInt); UsefulBuf B = {NULL, 0}; QCBORDecode_GetBigFloatBig(&DC, 0, B, &UB, &b, &nInt); QCBORDecode_IsTagged(&DC, &Item, 5); QCBORDecode_EnterMapFromMapSZ(&DC, "map"); QCBORDecode_ExitMap(&DC); QCBORDecode_EnterArrayFromMapSZ(&DC, "map"); QCBORDecode_ExitArray(&DC); QCBORDecode_EnterBstrWrapped(&DC, 0, &UB); QCBORDecode_ExitBstrWrapped(&DC); QCBORDecode_GetItemInMapN(&DC, 0, 0, &Item); QCBORDecode_GetItemsInMap(&DC, &Item); if(QCBORDecode_Finish(&DC)) { return -4; } return 0; }
2.328125
2
2024-11-18T21:09:35.853553+00:00
2022-06-16T13:42:25
8da63c5af7c3ee0769f9880b9e0b3e90a907ef77
{ "blob_id": "8da63c5af7c3ee0769f9880b9e0b3e90a907ef77", "branch_name": "refs/heads/master", "committer_date": "2022-06-16T13:42:25", "content_id": "62eb64fd156860627d3e33591e230119bfd295e0", "detected_licenses": [ "MIT" ], "directory_id": "a6c41a3afec655e173d520edbb8cd2fed827e052", "extension": "h", "filename": "char_io.h", "fork_events_count": 19, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 174347105, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 700, "license": "MIT", "license_type": "permissive", "path": "/008Cbase/char_io.h", "provenance": "stackv2-0065.json.gz:12115", "repo_name": "marcotessarotto/exOpSys", "revision_date": "2022-06-16T13:42:25", "revision_id": "2841ed468c20bc76f0bb7d7af814626cd211a164", "snapshot_id": "abf58b02a75cfac10a541e4a34646a6fcddce6fb", "src_encoding": "UTF-8", "star_events_count": 18, "url": "https://raw.githubusercontent.com/marcotessarotto/exOpSys/2841ed468c20bc76f0bb7d7af814626cd211a164/008Cbase/char_io.h", "visit_date": "2022-06-18T05:25:08.913279" }
stackv2
#ifndef CHAR_IO_H_ #define CHAR_IO_H_ // stream ("flusso") di caratteri: sequenza di caratteri // TEXT stream: sequenza di caratteri divisa in linee; // ogni linea si compone di zero o più caratteri seguita dal carattere "new line" (\n) /* * c = getchar() legge il prossimo carattere dall'input (stdin, di solito è la tastiera) * * putchar(c) stampa (aggiunge) un carattere nell'output (di solito è lo schermo) * * getchar e putchar sono essere inframmezzate tra loro e con le altre funzioni; * * posso alternare tranquillamente putchar e printf. * */ void copy_input_to_output(); void count_lines_in_input(); void word_count(); void count_to_array(); #endif /* CHAR_IO_H_ */
2.3125
2
2024-11-18T21:09:36.066441+00:00
2019-06-28T20:13:58
f6c16b36c7cb9e75419b12281cb960f825d96519
{ "blob_id": "f6c16b36c7cb9e75419b12281cb960f825d96519", "branch_name": "refs/heads/master", "committer_date": "2019-06-28T20:13:58", "content_id": "56c6e2627b6588a6c8ff291859fd3632ad02d125", "detected_licenses": [ "MIT" ], "directory_id": "47af4690b6e26285d37e388dcce594378fc1e21c", "extension": "c", "filename": "gsanity.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 188196804, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 363, "license": "MIT", "license_type": "permissive", "path": "/gsanity.c", "provenance": "stackv2-0065.json.gz:12372", "repo_name": "sHDiV4RHs/OSMiniProject2", "revision_date": "2019-06-28T20:13:58", "revision_id": "f49cd9fcd15ed7a7be376eaec29dd7c8ff38fbac", "snapshot_id": "9797e5bdd52e95606e0d93944cfc8ded9b7d510d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sHDiV4RHs/OSMiniProject2/f49cd9fcd15ed7a7be376eaec29dd7c8ff38fbac/gsanity.c", "visit_date": "2020-05-26T10:02:20.931328" }
stackv2
#include "types.h" #include "stat.h" #include "user.h" int main(void) { printf(1, "Father pid is %d\n", getpid()); sleep(10); int pid = fork(); for(int i = 0; i < 50; i++) { printf(1, "process %d is printing for the %d time\n", getpid(), i); } // wait for child if(pid > 0) { while(wait() > 0); } exit(); }
2.5625
3
2024-11-18T21:09:36.321568+00:00
2017-11-29T02:08:36
85b4fac0af269ed5c735c2830e53cdc18c2fe2de
{ "blob_id": "85b4fac0af269ed5c735c2830e53cdc18c2fe2de", "branch_name": "refs/heads/master", "committer_date": "2017-11-29T02:08:36", "content_id": "304ef647807dacf6c1e6eb444e17c3b39a40091f", "detected_licenses": [ "MIT" ], "directory_id": "d9adf88fb5e7f6b6e5a1e3263259e69306220e4b", "extension": "c", "filename": "http_tcp.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": 1748, "license": "MIT", "license_type": "permissive", "path": "/webserver/http_tcp.c", "provenance": "stackv2-0065.json.gz:12629", "repo_name": "huanghl365/StudyNote_201308", "revision_date": "2017-11-29T02:08:36", "revision_id": "ee4e4515a2acd9a27e7f208aaacc2daf8b4cfa16", "snapshot_id": "e576bbd3d856455e6d357ef13a3753c29b1db3f1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/huanghl365/StudyNote_201308/ee4e4515a2acd9a27e7f208aaacc2daf8b4cfa16/webserver/http_tcp.c", "visit_date": "2021-12-24T00:49:00.248977" }
stackv2
#include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include "client_fun.h" int main(int argc,char *argv[]) { int sockfd = 0; //定义套接字 int err_log = 0; //绑定监听的返回值 int connfd = 0; //accept返回链接好的套接字描述符 unsigned short port = 8000; //端口8000 struct sockaddr_in my_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); //创建套接字 if (sockfd < 0) { perror("socket"); exit(-1); } //对结构体进行赋值(函数组,端口,IP) bzero (&my_addr,sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(port); my_addr.sin_addr.s_addr = htonl(INADDR_ANY); err_log = bind(sockfd, (struct sockaddr*)&my_addr, sizeof(my_addr)); //绑定 if(err_log != 0) { perror("bind"); close(sockfd); exit(-1); } err_log = listen (sockfd, 10); //监听 if(err_log != 0) { perror("listen"); close(sockfd); exit(-1); } while(1) { char cli_ip[INET_ADDRSTRLEN] = ""; struct sockaddr_in client_addr; //客户端结构体 socklen_t cliaddr_len = sizeof(client_addr); //传输使用IP connfd = accept(sockfd, (struct sockaddr*)&client_addr, &cliaddr_len); //取出已连接的套接字 if(connfd < 0) { perror("accept"); continue; } inet_ntop (AF_INET, &client_addr.sin_addr, cli_ip,INET_ADDRSTRLEN); printf("\e[32mclient ip = %s\e[0m ,\e[33mport = %d\e[0m\n",cli_ip, ntohs(client_addr.sin_port));//多彩显示 pthread_t tid; pthread_create(&tid, NULL, (void *)client_fun, (void *)connfd);//调用线程函数 pthread_detach(tid); } close(sockfd); return 0; }
2.78125
3
2024-11-18T21:09:38.015539+00:00
2021-05-05T21:10:19
70e0f3b9a9c91be5edb4fc58f1e71da5fbfeb78d
{ "blob_id": "70e0f3b9a9c91be5edb4fc58f1e71da5fbfeb78d", "branch_name": "refs/heads/master", "committer_date": "2021-05-05T21:10:19", "content_id": "75b5ba1d78437713c30cbdbd417bee80cc36b53b", "detected_licenses": [ "ISC" ], "directory_id": "aeaecf0810848f85f4a01b6bfdbec1b583b79ce9", "extension": "c", "filename": "delaunay.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 276252828, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15769, "license": "ISC", "license_type": "permissive", "path": "/src/delaunay.c", "provenance": "stackv2-0065.json.gz:13529", "repo_name": "raintherrien/delaunator-c", "revision_date": "2021-05-05T21:10:19", "revision_id": "ae0de0c3ff8edc8f88b303b3b4edb26884f708ef", "snapshot_id": "29f33c69c43707733954acb524093e0daebbcd6f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/raintherrien/delaunator-c/ae0de0c3ff8edc8f88b303b3b4edb26884f708ef/src/delaunay.c", "visit_date": "2023-04-18T09:56:00.383295" }
stackv2
/* * Fast 2D Delaunay triangulation in C. Yet another port of Delaunator. * https://github.com/mapbox/delaunator * * Copyright (c) 2017, Mapbox * Copyright (c) 2021, Rain Therrien * Distributed under the ISC license. * See accompanying LICENSE */ #include "delaunay/delaunay.h" #include "delaunay/helper.h" #include <assert.h> #include <errno.h> #include <float.h> #include <math.h> #include <stdlib.h> #include <stdint.h> #include <string.h> /* Internal aliases for some type clarity */ typedef uint32_t vid; typedef uint32_t tid; /* * Creates a new triangle from three verts and links to neighbors */ static tid addtri(vid *triverts, uint32_t *ntrivert, tid *halfedge, vid v0, vid v1, vid v2, tid t0, tid t1, tid t2); /* * Returns whether the three points are counter-clockwise in order. */ static int ccw(float, float, float, float, float, float); /* * Returns the circumradius between three points, or FLT_MAX if points * are colinear. */ static float circr(float, float, float, float, float, float); /* * Returns a pseudo-angle between two points which monotonically * increases with real angle but doesn't need expensive trigonometry. */ static uint32_t hashk(float, float, float, float, uint32_t mask); /* * Returns whether the point p is within the circumcircle formed by the * three vertices. */ static int incircc(float ax, float ay, float bx, float by, float cx, float cy, float px, float py); /* * Recursively flips neighboring triangles until they (locally) satisfy * the Delaunay condition. * * Stack is a pre-allocated fixed sized stack used to avoid actual * recursion, the size of which must be at least npt. */ static tid legalize(tid *halfedge, vid *hullprev, tid *hulltris, vid *triverts, uint32_t *hullstrt, float *pt, uint32_t npt, tid t, tid *stack); /* * Links two triangles with half edges */ static void link(tid *halfedge, tid, tid); /* * Seed stores the vertices of a triangle close to the center of points * in the first three elements of s, and returns zero on success. * * If all points are colinear errno is set to EINVAL, which is returned, * and s is undefined. */ static int seed(float *pt, uint32_t npt, vid *s); /* * Structure and comparator of a (index, distance) tuple used to order * points by distance from domain seed. */ struct pointdist { vid i; float d; }; static int pointdistcmp(const void *xa, const void *xb); int triangulate(uint32_t *delaunay, float *pt, uint32_t npt) { if (npt < 3) { errno = ERANGE; return errno; } if (npt > DELAUNAY_MAXNPT) { errno = ERANGE; return errno; } /* Define pointers into buffer; see delaunay.h for layout */ tid *halfedge = DELAUNAY_HALFEDGE(delaunay, npt); vid *hullhash = DELAUNAY_HULLHASH(delaunay, npt); vid *hullnext = DELAUNAY_HULLNEXT(delaunay, npt); vid *hullprev = DELAUNAY_HULLPREV(delaunay, npt); tid *hulltris = DELAUNAY_HULLTRIS(delaunay, npt); vid *triverts = DELAUNAY_TRIVERTS(delaunay, npt); uint32_t *ntrivert = DELAUNAY_NTRIVERT(delaunay, npt); uint32_t *hullsize = DELAUNAY_HULLSIZE(delaunay, npt); uint32_t *hullstrt = DELAUNAY_HULLSTRT(delaunay, npt); /* * Array of point indices to sort by distance from seed and a fixed * size stack for legalize. * * Static asserts here that: if the buffer allocation is safe from * overflow, then we're definitely safe with these temp allocations. */ _Static_assert(sizeof(struct pointdist) <= 16, ""); _Static_assert(sizeof(tid) <= 16, ""); struct pointdist *pds = malloc(npt * sizeof *pds); /* Fixed sized stack for legalize */ tid *stack = malloc(npt * sizeof *stack); if (pds == NULL || stack == NULL) { goto free_buffers; } #define ADDTRI(...) addtri(triverts, ntrivert, halfedge, __VA_ARGS__); #define LEGALIZE(T) legalize(halfedge, hullprev, hulltris, triverts, \ hullstrt, pt, npt, T, stack); /* Assign initial values to UINT32_MAX, which means no vert/tri */ _Static_assert((uint32_t)-1 == (uint32_t)~0, "Assumes two's complement"); memset(delaunay, 0xFF, DELAUNAY_SZ(npt) * sizeof *delaunay); /* Find seed */ vid s[3] = { 0 }; if (seed(pt, npt, s) != 0) { goto free_buffers; } float c[2]; circumcenter(pt[s[0]*2], pt[s[0]*2+1], pt[s[1]*2], pt[s[1]*2+1], pt[s[2]*2], pt[s[2]*2+1], c); for (uint32_t i = 0; i < npt; ++ i) { pds[i] = (struct pointdist) { .i = i, .d = hypotf(pt[i*2]-c[0], pt[i*2+1]-c[1]) }; } /* Sort indices by distance from "center" of pts */ qsort(pds, npt, sizeof *pds, pointdistcmp); /* Create the initial hull around seed triangle */ uint32_t hashsz = llroundf(ceilf(sqrtf(npt))); *hullstrt = s[0]; *hullsize = 3; hullnext[s[0]] = hullprev[s[2]] = s[1]; hullnext[s[1]] = hullprev[s[0]] = s[2]; hullnext[s[2]] = hullprev[s[1]] = s[0]; hulltris[s[0]] = 0; hulltris[s[1]] = 1; hulltris[s[2]] = 2; hullhash[hashk(c[0],c[1], pt[s[0]*2],pt[s[0]*2+1], hashsz)] = s[0]; hullhash[hashk(c[0],c[1], pt[s[1]*2],pt[s[1]*2+1], hashsz)] = s[1]; hullhash[hashk(c[0],c[1], pt[s[2]*2],pt[s[2]*2+1], hashsz)] = s[2]; *ntrivert = 0; assert(*ntrivert + 3 < npt * 6); ADDTRI(s[0], s[1], s[2], UINT32_MAX, UINT32_MAX, UINT32_MAX); float p[2] = { FLT_MAX }; for (uint32_t idx = 0; idx < npt; ++ idx) { vid i = pds[idx].i; float *v = pt + i*2; /* Skip near-duplicate points */ if (fabsf(v[0]-p[0]) <= FLT_EPSILON && fabsf(v[1]-p[1]) <= FLT_EPSILON) { continue; } p[0] = v[0]; p[1] = v[1]; /* Skip seed triangle points */ if (i == s[0] || i == s[1] || i == s[2]) { continue; } /* Find a visible edge on the convex hull using edge hash */ vid start = 0; uint32_t key = hashk(c[0],c[1], v[0],v[1], hashsz); for (uint32_t j = 0; j < hashsz; ++ j) { start = hullhash[(key + j) % hashsz]; if (start != UINT32_MAX && start != hullnext[start]) { break; } } start = hullprev[start]; vid e = start; vid q = hullnext[e]; while (ccw(v[0],v[1], pt[e*2],pt[e*2+1], pt[q*2],pt[q*2+1])) { e = q; if (e == start) { e = UINT32_MAX; break; } q = hullnext[e]; } /* Likely a near-duplicate point; skip it */ if (e == UINT32_MAX) continue; /* Add the first triangle from the point */ assert(*ntrivert + 3 < npt * 6); tid t = ADDTRI(e, i, hullnext[e], UINT32_MAX, UINT32_MAX, hulltris[e]); /* Flip triangles until they satisfy the Delaunay condition */ hulltris[i] = LEGALIZE(t + 2); hulltris[e] = t; /* Keep track of boundary (hull) triangles */ ++ hullsize; /* Walk through the hull adding more triangles and flipping */ vid n = hullnext[e]; q = hullnext[n]; while (!ccw(v[0],v[1], pt[n*2],pt[n*2+1], pt[q*2],pt[q*2+1])) { assert(*ntrivert + 3 < npt * 6); t = ADDTRI(n, i, q, hulltris[i], UINT32_MAX, hulltris[n]); hulltris[i] = LEGALIZE(t + 2); hullnext[n] = n; /* mark as removed */ -- hullsize; n = q; q = hullnext[n]; } /* Walk backwards adding more tris and flipping */ if (e == start) { q = hullprev[e]; while (!ccw(v[0],v[1], pt[q*2],pt[q*2+1], pt[e*2],pt[e*2+1])) { assert(*ntrivert + 3 < npt * 6); t = ADDTRI(q, i, e, UINT32_MAX, hulltris[e], hulltris[q]); LEGALIZE(t + 2); hulltris[q] = t; hullnext[e] = e; /* mark as removed */ -- hullsize; e = q; q = hullprev[e]; } } /* Update the hull indices */ *hullstrt = hullprev[i] = e; hullnext[e] = hullprev[n] = i; hullnext[i] = n; /* Save the two new edges in the hash table */ hullhash[hashk(c[0],c[1], v[0],v[1], hashsz)] = i; hullhash[hashk(c[0],c[1], pt[e*2],pt[e*2+1], hashsz)] = e; } /* XXX Shrink halfedges to only valid triangles */ /* this.triangles = this._triangles.subarray(0, this.trianglesLen); this.halfedge = this._halfedges.subarray(0, this.trianglesLen); */ free(stack); free(pds); return 0; free_buffers: free(stack); free(pds); return errno; #undef LEGALIZE #undef ADDTRI } static int seed(float *pt, uint32_t npt, vid *s) { /* Calculate pt bounding box */ float maxx = FLT_MIN; float maxy = FLT_MIN; float minx = FLT_MAX; float miny = FLT_MAX; for (vid i = 0; i < npt; ++ i) { float x = pt[i*2]; float y = pt[i*2+1]; if (x > maxx) maxx = x; if (x < minx) minx = x; if (y > maxy) maxy = y; if (y < miny) miny = y; } /* Pick a seed close to the center */ float ctrx = (minx + maxx) / 2.0f; float ctry = (miny + maxy) / 2.0f; vid s0 = UINT32_MAX; vid s1 = UINT32_MAX; vid s2 = UINT32_MAX; float mind = FLT_MAX; for (vid i = 0; i < npt; ++ i) { float d = hypotf(pt[i*2]-ctrx, pt[i*2+1]-ctry); if (d < mind) { s0 = i; mind = d; } } /* Pick the Vertex closest to seed */ mind = FLT_MAX; for (vid i = 0; i < npt; ++ i) { if (s0 == i) continue; float d = hypotf(pt[s0*2] - pt[ i*2], pt[s0*2+1] - pt[ i*2+1]); if (d < mind) { s1 = i; mind = d; } } /* Pick the third vertex which forms the smallest circumcircle */ float minr = FLT_MAX; for (vid i = 0; i < npt; ++ i) { if (s0 == i || s1 == i) continue; float r = circr(pt[s0*2], pt[s0*2+1], pt[s1*2], pt[s1*2+1], pt[ i*2], pt[ i*2+1]); if (r < minr) { s2 = i; minr = r; } } /* * Note: original JS implementation handles colinear domains. I just * don't want the extra case. */ if (minr == FLT_MAX) { errno = EINVAL; return errno; } /* Swap the order of our seed triangle until it is ccw */ if (!ccw(pt[s0*2], pt[s0*2+1], pt[s1*2], pt[s1*2+1], pt[s2*2], pt[s2*2+1])) { vid t = s1; s1 = s2; s2 = t; } s[0] = s0; s[1] = s1; s[2] = s2; return 0; } static inline tid addtri(vid *triverts, uint32_t *ntrivert, tid *halfedge, vid v0, vid v1, vid v2, tid t0, tid t1, tid t2) { uint32_t t = *ntrivert; triverts[t+0] = v0; triverts[t+1] = v1; triverts[t+2] = v2; *ntrivert += 3; link(halfedge, t+0, t0); link(halfedge, t+1, t1); link(halfedge, t+2, t2); return t; } static inline int ccw(float ax, float ay, float bx, float by, float cx, float cy) { return (by - ay) * (cx - bx) - (bx - ax) * (cy - by) >= 0; } static inline float circr(float ax, float ay, float bx, float by, float cx, float cy) { float dx = bx - ax; float dy = by - ay; float ex = cx - ax; float ey = cy - ay; float bl = dx * dx + dy * dy; float cl = ex * ex + ey * ey; float d = dx * ey - dy * ex; float x = (ey * bl - dy * cl) * 0.5f / d; float y = (dx * cl - ex * bl) * 0.5f / d; if (bl != 0.0f && cl != 0.0f && d != 0.0f) { return x * x + y * y; } else { return FLT_MAX; } } static inline uint32_t hashk(float cx, float cy, float vx, float vy, uint32_t mask) { float d0 = vx - cx; float d1 = vy - cy; /* * Pseudo angle monotonically increases with real angle, but doesn't * need expensive trigonometry */ float p = d0 / (fabsf(d0) + fabsf(d1)); float angle = (d1 > 0 ? 3 - p : 1 + p) / 4.0f; /* [0..1] */ return llroundf(floorf(angle * (float)mask)) % mask; } static inline int incircc(float ax, float ay, float bx, float by, float cx, float cy, float px, float py) { float dx = ax - px; float dy = ay - py; float ex = bx - px; float ey = by - py; float fx = cx - px; float fy = cy - py; float ap = dx * dx + dy * dy; float bp = ex * ex + ey * ey; float cp = fx * fx + fy * fy; return ( dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) ) < 0; } static tid legalize(tid *halfedge, vid *hullprev, tid *hulltris, vid *triverts, uint32_t *hullstrt, float *pt, uint32_t npt, tid a, tid *stack) { uint32_t stacksz = 0; tid ar = 0; /* Recursion eliminated with a fixed-size stack. */ for (;;) { (void) npt; assert(stacksz < npt); tid b = halfedge[a]; /* * If the pair of triangles doesn't satisfy the Delaunay * condition (p1 is inside the circumcircle of [p0, pl, pr]), * flip them, then do the same check/flip recursively for the * new pair of triangles. * * pl pl * /||\ / \ * al/ || \bl al/ \a * / || \ / \ * / a||b \ flip /___ar___\ * p0\ || /p1 => p0\---bl---/p1 * \ || / \ / * ar\ || /br b\ /br * \||/ \ / * pr pr * */ tid a0 = a - a % 3; ar = a0 + (a + 2) % 3; /* Convex hull edge */ if (b == UINT32_MAX) { if (stacksz == 0) break; a = stack[-- stacksz]; continue; } tid b0 = b - b % 3; tid al = a0 + (a + 1) % 3; tid bl = b0 + (b + 2) % 3; vid p0 = triverts[ar]; vid pr = triverts[a]; vid pl = triverts[al]; vid p1 = triverts[bl]; int flip = incircc(pt[p0*2], pt[p0*2+1], pt[pr*2], pt[pr*2+1], pt[pl*2], pt[pl*2+1], pt[p1*2], pt[p1*2+1]); if (flip) { triverts[a] = p1; triverts[b] = p0; tid hbl = halfedge[bl]; /* * Edge swapped on the other side of the hull (rare); fix * the halfedge reference */ if (hbl == UINT32_MAX) { vid e = *hullstrt; do { if (hulltris[e] == bl) { hulltris[e] = a; break; } e = hullprev[e]; } while (e != *hullstrt); } link(halfedge, a, hbl); link(halfedge, b, halfedge[ar]); link(halfedge, ar, bl); tid br = b0 + (b + 1) % 3; stack[stacksz ++] = br; } else { if (stacksz == 0) break; a = stack[-- stacksz]; } } return ar; } static inline void link(tid *halfedge, tid a, tid b) { halfedge[a] = b; if (b != UINT32_MAX) halfedge[b] = a; } static inline int pointdistcmp(const void *xa, const void *xb) { const struct pointdist *a = xa; const struct pointdist *b = xb; if (a->d < b->d) return -1; if (a->d > b->d) return 1; return 0; }
2.40625
2
2024-11-18T21:09:38.279390+00:00
2023-03-08T20:42:48
454f5690174c5e1df880f8efc42ad4aa95d7d130
{ "blob_id": "454f5690174c5e1df880f8efc42ad4aa95d7d130", "branch_name": "refs/heads/master", "committer_date": "2023-03-08T20:42:48", "content_id": "8ef8478308fe4c9384f6353d6d1fb241f586eb62", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "0ab78d9b913d22b626508ab993367555cc099fcb", "extension": "c", "filename": "tommytree.c", "fork_events_count": 43, "gha_created_at": "2014-03-18T22:38:20", "gha_event_created_at": "2023-01-31T20:21:38", "gha_language": "C++", "gha_license_id": "BSD-2-Clause", "github_id": 17884512, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6822, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/tommyds/tommytree.c", "provenance": "stackv2-0065.json.gz:13787", "repo_name": "amadvance/tommyds", "revision_date": "2023-03-08T20:42:48", "revision_id": "97ff74356f6d5ae899b9cb672deb803da01270ca", "snapshot_id": "b6da1248ca72fa8a708bd4b5a9e852ef693b1613", "src_encoding": "UTF-8", "star_events_count": 214, "url": "https://raw.githubusercontent.com/amadvance/tommyds/97ff74356f6d5ae899b9cb672deb803da01270ca/tommyds/tommytree.c", "visit_date": "2023-03-21T14:16:20.853027" }
stackv2
/* * Copyright (c) 2015, Andrea Mazzoleni. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "tommytree.h" #include <assert.h> /* for assert */ /******************************************************************************/ /* tree */ void tommy_tree_init(tommy_tree* tree, tommy_compare_func* cmp) { tree->root = 0; tree->count = 0; tree->cmp = cmp; } static tommy_ssize_t tommy_tree_delta(tommy_tree_node* root) { tommy_ssize_t left_height = root->prev ? root->prev->index : 0; tommy_ssize_t right_height = root->next ? root->next->index : 0; return left_height - right_height; } /* AVL tree operations */ static tommy_tree_node* tommy_tree_balance(tommy_tree_node*); static tommy_tree_node* tommy_tree_rotate_left(tommy_tree_node* root) { tommy_tree_node* next = root->next; root->next = next->prev; next->prev = tommy_tree_balance(root); return tommy_tree_balance(next); } static tommy_tree_node* tommy_tree_rotate_right(tommy_tree_node* root) { tommy_tree_node* prev = root->prev; root->prev = prev->next; prev->next = tommy_tree_balance(root); return tommy_tree_balance(prev); } static tommy_tree_node* tommy_tree_move_right(tommy_tree_node* root, tommy_tree_node* node) { if (!root) return node; root->next = tommy_tree_move_right(root->next, node); return tommy_tree_balance(root); } static tommy_tree_node* tommy_tree_balance(tommy_tree_node* root) { tommy_ssize_t delta = tommy_tree_delta(root); if (delta < -1) { if (tommy_tree_delta(root->next) > 0) root->next = tommy_tree_rotate_right(root->next); return tommy_tree_rotate_left(root); } if (delta > 1) { if (tommy_tree_delta(root->prev) < 0) root->prev = tommy_tree_rotate_left(root->prev); return tommy_tree_rotate_right(root); } /* recompute key */ root->index = 0; if (root->prev && root->prev->index > root->index) root->index = root->prev->index; if (root->next && root->next->index > root->index) root->index = root->next->index; /* count itself */ root->index += 1; return root; } static tommy_tree_node* tommy_tree_insert_node(tommy_compare_func* cmp, tommy_tree_node* root, tommy_tree_node** let) { int c; if (!root) return *let; c = cmp((*let)->data, root->data); if (c < 0) { root->prev = tommy_tree_insert_node(cmp, root->prev, let); return tommy_tree_balance(root); } if (c > 0) { root->next = tommy_tree_insert_node(cmp, root->next, let); return tommy_tree_balance(root); } /* already present, set the return pointer */ *let = root; return root; } void* tommy_tree_insert(tommy_tree* tree, tommy_tree_node* node, void* data) { tommy_tree_node* insert = node; insert->data = data; insert->prev = 0; insert->next = 0; insert->index = 0; tree->root = tommy_tree_insert_node(tree->cmp, tree->root, &insert); if (insert == node) ++tree->count; return insert->data; } static tommy_tree_node* tommy_tree_remove_node(tommy_compare_func* cmp, tommy_tree_node* root, void* data, tommy_tree_node** let) { int c; if (!root) return 0; c = cmp(data, root->data); if (c < 0) { root->prev = tommy_tree_remove_node(cmp, root->prev, data, let); return tommy_tree_balance(root); } if (c > 0) { root->next = tommy_tree_remove_node(cmp, root->next, data, let); return tommy_tree_balance(root); } /* found */ *let = root; return tommy_tree_move_right(root->prev, root->next); } void* tommy_tree_remove(tommy_tree* tree, void* data) { tommy_tree_node* node = 0; tree->root = tommy_tree_remove_node(tree->cmp, tree->root, data, &node); if (!node) return 0; --tree->count; return node->data; } static tommy_tree_node* tommy_tree_search_node(tommy_compare_func* cmp, tommy_tree_node* root, void* data) { int c; if (!root) return 0; c = cmp(data, root->data); if (c < 0) return tommy_tree_search_node(cmp, root->prev, data); if (c > 0) return tommy_tree_search_node(cmp, root->next, data); return root; } void* tommy_tree_search(tommy_tree* tree, void* data) { tommy_tree_node* node = tommy_tree_search_node(tree->cmp, tree->root, data); if (!node) return 0; return node->data; } void* tommy_tree_search_compare(tommy_tree* tree, tommy_compare_func* cmp, void* cmp_arg) { tommy_tree_node* node = tommy_tree_search_node(cmp, tree->root, cmp_arg); if (!node) return 0; return node->data; } void* tommy_tree_remove_existing(tommy_tree* tree, tommy_tree_node* node) { void* data = tommy_tree_remove(tree, node->data); assert(data != 0); return data; } static void tommy_tree_foreach_node(tommy_tree_node* root, tommy_foreach_func* func) { tommy_tree_node* next; if (!root) return; tommy_tree_foreach_node(root->prev, func); /* make a copy in case func is free() */ next = root->next; func(root->data); tommy_tree_foreach_node(next, func); } void tommy_tree_foreach(tommy_tree* tree, tommy_foreach_func* func) { tommy_tree_foreach_node(tree->root, func); } static void tommy_tree_foreach_arg_node(tommy_tree_node* root, tommy_foreach_arg_func* func, void* arg) { tommy_tree_node* next; if (!root) return; tommy_tree_foreach_arg_node(root->prev, func, arg); /* make a copy in case func is free() */ next = root->next; func(arg, root->data); tommy_tree_foreach_arg_node(next, func, arg); } void tommy_tree_foreach_arg(tommy_tree* tree, tommy_foreach_arg_func* func, void* arg) { tommy_tree_foreach_arg_node(tree->root, func, arg); } tommy_size_t tommy_tree_memory_usage(tommy_tree* tree) { return tommy_tree_count(tree) * sizeof(tommy_tree_node); }
2.5
2